blob: bbd4b2edc1b5b9e58b6b8c3aa6477af65e07f24d [file] [log] [blame]
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001//===- InstCombineMulDivRem.cpp -------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the visit functions for mul, fmul, sdiv, udiv, fdiv,
11// srem, urem, frem.
12//
13//===----------------------------------------------------------------------===//
14
15#include "InstCombine.h"
Duncan Sandsd0eb6d32010-12-21 14:00:22 +000016#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000017#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000018#include "llvm/IR/PatternMatch.h"
Chris Lattnerdc054bf2010-01-05 06:09:35 +000019using namespace llvm;
20using namespace PatternMatch;
21
Chandler Carruth964daaa2014-04-22 02:55:47 +000022#define DEBUG_TYPE "instcombine"
23
Chris Lattner7c99f192011-05-22 18:18:41 +000024
25/// simplifyValueKnownNonZero - The specific integer value is used in a context
26/// where it is known to be non-zero. If this allows us to simplify the
27/// computation, do so and return the new operand, otherwise return null.
28static Value *simplifyValueKnownNonZero(Value *V, InstCombiner &IC) {
29 // If V has multiple uses, then we would have to do more analysis to determine
30 // if this is safe. For example, the use could be in dynamically unreached
31 // code.
32 if (!V->hasOneUse()) return 0;
Jim Grosbachbdbd7342013-04-05 21:20:12 +000033
Chris Lattner388cb8a2011-05-23 00:32:19 +000034 bool MadeChange = false;
35
Chris Lattner7c99f192011-05-22 18:18:41 +000036 // ((1 << A) >>u B) --> (1 << (A-B))
37 // Because V cannot be zero, we know that B is less than A.
Chris Lattner321c58f2011-05-23 00:09:55 +000038 Value *A = 0, *B = 0, *PowerOf2 = 0;
39 if (match(V, m_LShr(m_OneUse(m_Shl(m_Value(PowerOf2), m_Value(A))),
Chris Lattner7c99f192011-05-22 18:18:41 +000040 m_Value(B))) &&
41 // The "1" can be any value known to be a power of 2.
Rafael Espindola319f74c2012-12-13 03:37:24 +000042 isKnownToBeAPowerOfTwo(PowerOf2)) {
Benjamin Kramer547b6c52011-09-27 20:39:19 +000043 A = IC.Builder->CreateSub(A, B);
Chris Lattner321c58f2011-05-23 00:09:55 +000044 return IC.Builder->CreateShl(PowerOf2, A);
Chris Lattner7c99f192011-05-22 18:18:41 +000045 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000046
Chris Lattner388cb8a2011-05-23 00:32:19 +000047 // (PowerOfTwo >>u B) --> isExact since shifting out the result would make it
48 // inexact. Similarly for <<.
49 if (BinaryOperator *I = dyn_cast<BinaryOperator>(V))
Rafael Espindola319f74c2012-12-13 03:37:24 +000050 if (I->isLogicalShift() && isKnownToBeAPowerOfTwo(I->getOperand(0))) {
Chris Lattner388cb8a2011-05-23 00:32:19 +000051 // We know that this is an exact/nuw shift and that the input is a
52 // non-zero context as well.
53 if (Value *V2 = simplifyValueKnownNonZero(I->getOperand(0), IC)) {
54 I->setOperand(0, V2);
55 MadeChange = true;
56 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000057
Chris Lattner388cb8a2011-05-23 00:32:19 +000058 if (I->getOpcode() == Instruction::LShr && !I->isExact()) {
59 I->setIsExact();
60 MadeChange = true;
61 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000062
Chris Lattner388cb8a2011-05-23 00:32:19 +000063 if (I->getOpcode() == Instruction::Shl && !I->hasNoUnsignedWrap()) {
64 I->setHasNoUnsignedWrap();
65 MadeChange = true;
66 }
67 }
68
Chris Lattner162dfc32011-05-22 18:26:48 +000069 // TODO: Lots more we could do here:
Chris Lattner162dfc32011-05-22 18:26:48 +000070 // If V is a phi node, we can call this on each of its operands.
71 // "select cond, X, 0" can simplify to "X".
Jim Grosbachbdbd7342013-04-05 21:20:12 +000072
Chris Lattner388cb8a2011-05-23 00:32:19 +000073 return MadeChange ? V : 0;
Chris Lattner7c99f192011-05-22 18:18:41 +000074}
75
76
Chris Lattnerdc054bf2010-01-05 06:09:35 +000077/// MultiplyOverflows - True if the multiply can not be expressed in an int
78/// this size.
79static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
80 uint32_t W = C1->getBitWidth();
81 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
82 if (sign) {
Jay Foad583abbc2010-12-07 08:25:19 +000083 LHSExt = LHSExt.sext(W * 2);
84 RHSExt = RHSExt.sext(W * 2);
Chris Lattnerdc054bf2010-01-05 06:09:35 +000085 } else {
Jay Foad583abbc2010-12-07 08:25:19 +000086 LHSExt = LHSExt.zext(W * 2);
87 RHSExt = RHSExt.zext(W * 2);
Chris Lattnerdc054bf2010-01-05 06:09:35 +000088 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000089
Chris Lattnerdc054bf2010-01-05 06:09:35 +000090 APInt MulExt = LHSExt * RHSExt;
Jim Grosbachbdbd7342013-04-05 21:20:12 +000091
Chris Lattnerdc054bf2010-01-05 06:09:35 +000092 if (!sign)
93 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
Jim Grosbachbdbd7342013-04-05 21:20:12 +000094
Chris Lattnerdc054bf2010-01-05 06:09:35 +000095 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
96 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
97 return MulExt.slt(Min) || MulExt.sgt(Max);
98}
99
Rafael Espindola65281bf2013-05-31 14:27:15 +0000100/// \brief A helper routine of InstCombiner::visitMul().
101///
102/// If C is a vector of known powers of 2, then this function returns
103/// a new vector obtained from C replacing each element with its logBase2.
104/// Return a null pointer otherwise.
105static Constant *getLogBase2Vector(ConstantDataVector *CV) {
106 const APInt *IVal;
107 SmallVector<Constant *, 4> Elts;
108
109 for (unsigned I = 0, E = CV->getNumElements(); I != E; ++I) {
110 Constant *Elt = CV->getElementAsConstant(I);
111 if (!match(Elt, m_APInt(IVal)) || !IVal->isPowerOf2())
112 return 0;
113 Elts.push_back(ConstantInt::get(Elt->getType(), IVal->logBase2()));
114 }
115
116 return ConstantVector::get(Elts);
117}
118
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000119Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +0000120 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000121 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
122
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000123 if (Value *V = SimplifyMulInst(Op0, Op1, DL))
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000124 return ReplaceInstUsesWith(I, V);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000125
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000126 if (Value *V = SimplifyUsingDistributiveLaws(I))
127 return ReplaceInstUsesWith(I, V);
128
Chris Lattner6b657ae2011-02-10 05:36:31 +0000129 if (match(Op1, m_AllOnes())) // X * -1 == 0 - X
130 return BinaryOperator::CreateNeg(Op0, I.getName());
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000131
Rafael Espindola65281bf2013-05-31 14:27:15 +0000132 // Also allow combining multiply instructions on vectors.
133 {
134 Value *NewOp;
135 Constant *C1, *C2;
136 const APInt *IVal;
137 if (match(&I, m_Mul(m_Shl(m_Value(NewOp), m_Constant(C2)),
138 m_Constant(C1))) &&
139 match(C1, m_APInt(IVal)))
140 // ((X << C1)*C2) == (X * (C2 << C1))
141 return BinaryOperator::CreateMul(NewOp, ConstantExpr::getShl(C1, C2));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000142
Rafael Espindola65281bf2013-05-31 14:27:15 +0000143 if (match(&I, m_Mul(m_Value(NewOp), m_Constant(C1)))) {
144 Constant *NewCst = 0;
145 if (match(C1, m_APInt(IVal)) && IVal->isPowerOf2())
146 // Replace X*(2^C) with X << C, where C is either a scalar or a splat.
147 NewCst = ConstantInt::get(NewOp->getType(), IVal->logBase2());
148 else if (ConstantDataVector *CV = dyn_cast<ConstantDataVector>(C1))
149 // Replace X*(2^C) with X << C, where C is a vector of known
150 // constant powers of 2.
151 NewCst = getLogBase2Vector(CV);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000152
Rafael Espindola65281bf2013-05-31 14:27:15 +0000153 if (NewCst) {
154 BinaryOperator *Shl = BinaryOperator::CreateShl(NewOp, NewCst);
155 if (I.hasNoSignedWrap()) Shl->setHasNoSignedWrap();
156 if (I.hasNoUnsignedWrap()) Shl->setHasNoUnsignedWrap();
157 return Shl;
158 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000159 }
Rafael Espindola65281bf2013-05-31 14:27:15 +0000160 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000161
Rafael Espindola65281bf2013-05-31 14:27:15 +0000162 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Stuart Hastings23804832011-06-01 16:42:47 +0000163 // (Y - X) * (-(2**n)) -> (X - Y) * (2**n), for positive nonzero n
164 // (Y + const) * (-(2**n)) -> (-constY) * (2**n), for positive nonzero n
165 // The "* (2**n)" thus becomes a potential shifting opportunity.
Stuart Hastings82843742011-05-30 20:00:33 +0000166 {
167 const APInt & Val = CI->getValue();
168 const APInt &PosVal = Val.abs();
169 if (Val.isNegative() && PosVal.isPowerOf2()) {
Stuart Hastings23804832011-06-01 16:42:47 +0000170 Value *X = 0, *Y = 0;
171 if (Op0->hasOneUse()) {
172 ConstantInt *C1;
173 Value *Sub = 0;
174 if (match(Op0, m_Sub(m_Value(Y), m_Value(X))))
175 Sub = Builder->CreateSub(X, Y, "suba");
176 else if (match(Op0, m_Add(m_Value(Y), m_ConstantInt(C1))))
177 Sub = Builder->CreateSub(Builder->CreateNeg(C1), Y, "subc");
178 if (Sub)
179 return
180 BinaryOperator::CreateMul(Sub,
181 ConstantInt::get(Y->getType(), PosVal));
Stuart Hastings82843742011-05-30 20:00:33 +0000182 }
183 }
184 }
Chris Lattner6b657ae2011-02-10 05:36:31 +0000185 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000186
Chris Lattner6b657ae2011-02-10 05:36:31 +0000187 // Simplify mul instructions with a constant RHS.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000188 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000189 // Try to fold constant mul into select arguments.
190 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
191 if (Instruction *R = FoldOpIntoSelect(I, SI))
192 return R;
193
194 if (isa<PHINode>(Op0))
195 if (Instruction *NV = FoldOpIntoPhi(I))
196 return NV;
Benjamin Kramer72196f32014-01-19 15:24:22 +0000197
198 // Canonicalize (X+C1)*CI -> X*CI+C1*CI.
199 {
200 Value *X;
201 Constant *C1;
202 if (match(Op0, m_OneUse(m_Add(m_Value(X), m_Constant(C1))))) {
203 Value *Add = Builder->CreateMul(X, Op1);
204 return BinaryOperator::CreateAdd(Add, Builder->CreateMul(C1, Op1));
205 }
206 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000207 }
208
209 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
210 if (Value *Op1v = dyn_castNegVal(Op1))
211 return BinaryOperator::CreateMul(Op0v, Op1v);
212
213 // (X / Y) * Y = X - (X % Y)
214 // (X / Y) * -Y = (X % Y) - X
215 {
216 Value *Op1C = Op1;
217 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
218 if (!BO ||
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000219 (BO->getOpcode() != Instruction::UDiv &&
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000220 BO->getOpcode() != Instruction::SDiv)) {
221 Op1C = Op0;
222 BO = dyn_cast<BinaryOperator>(Op1);
223 }
224 Value *Neg = dyn_castNegVal(Op1C);
225 if (BO && BO->hasOneUse() &&
226 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
227 (BO->getOpcode() == Instruction::UDiv ||
228 BO->getOpcode() == Instruction::SDiv)) {
229 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
230
Chris Lattner35315d02011-02-06 21:44:57 +0000231 // If the division is exact, X % Y is zero, so we end up with X or -X.
232 if (PossiblyExactOperator *SDiv = dyn_cast<PossiblyExactOperator>(BO))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000233 if (SDiv->isExact()) {
234 if (Op1BO == Op1C)
235 return ReplaceInstUsesWith(I, Op0BO);
236 return BinaryOperator::CreateNeg(Op0BO);
237 }
238
239 Value *Rem;
240 if (BO->getOpcode() == Instruction::UDiv)
241 Rem = Builder->CreateURem(Op0BO, Op1BO);
242 else
243 Rem = Builder->CreateSRem(Op0BO, Op1BO);
244 Rem->takeName(BO);
245
246 if (Op1BO == Op1C)
247 return BinaryOperator::CreateSub(Op0BO, Rem);
248 return BinaryOperator::CreateSub(Rem, Op0BO);
249 }
250 }
251
252 /// i1 mul -> i1 and.
Benjamin Kramer72196f32014-01-19 15:24:22 +0000253 if (I.getType()->getScalarType()->isIntegerTy(1))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000254 return BinaryOperator::CreateAnd(Op0, Op1);
255
256 // X*(1 << Y) --> X << Y
257 // (1 << Y)*X --> X << Y
258 {
259 Value *Y;
260 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
261 return BinaryOperator::CreateShl(Op1, Y);
262 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
263 return BinaryOperator::CreateShl(Op0, Y);
264 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000265
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000266 // If one of the operands of the multiply is a cast from a boolean value, then
267 // we know the bool is either zero or one, so this is a 'masking' multiply.
268 // X * Y (where Y is 0 or 1) -> X & (0-Y)
Duncan Sands19d0b472010-02-16 11:11:14 +0000269 if (!I.getType()->isVectorTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000270 // -2 is "-1 << 1" so it is all bits set except the low one.
271 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000272
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000273 Value *BoolCast = 0, *OtherOp = 0;
274 if (MaskedValueIsZero(Op0, Negative2))
275 BoolCast = Op0, OtherOp = Op1;
276 else if (MaskedValueIsZero(Op1, Negative2))
277 BoolCast = Op1, OtherOp = Op0;
278
279 if (BoolCast) {
280 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000281 BoolCast);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000282 return BinaryOperator::CreateAnd(V, OtherOp);
283 }
284 }
285
286 return Changed ? &I : 0;
287}
288
Pedro Artigas993acd02012-11-30 22:07:05 +0000289//
290// Detect pattern:
291//
292// log2(Y*0.5)
293//
294// And check for corresponding fast math flags
295//
296
297static void detectLog2OfHalf(Value *&Op, Value *&Y, IntrinsicInst *&Log2) {
Pedro Artigas00b83c92012-11-30 22:47:15 +0000298
299 if (!Op->hasOneUse())
300 return;
301
302 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op);
303 if (!II)
304 return;
305 if (II->getIntrinsicID() != Intrinsic::log2 || !II->hasUnsafeAlgebra())
306 return;
307 Log2 = II;
308
309 Value *OpLog2Of = II->getArgOperand(0);
310 if (!OpLog2Of->hasOneUse())
311 return;
312
313 Instruction *I = dyn_cast<Instruction>(OpLog2Of);
314 if (!I)
315 return;
316 if (I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
317 return;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000318
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000319 if (match(I->getOperand(0), m_SpecificFP(0.5)))
Pedro Artigas00b83c92012-11-30 22:47:15 +0000320 Y = I->getOperand(1);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000321 else if (match(I->getOperand(1), m_SpecificFP(0.5)))
Pedro Artigas00b83c92012-11-30 22:47:15 +0000322 Y = I->getOperand(0);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000323}
Pedro Artigas993acd02012-11-30 22:07:05 +0000324
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000325static bool isFiniteNonZeroFp(Constant *C) {
326 if (C->getType()->isVectorTy()) {
327 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
328 ++I) {
329 ConstantFP *CFP = dyn_cast<ConstantFP>(C->getAggregateElement(I));
330 if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
331 return false;
332 }
333 return true;
334 }
335
336 return isa<ConstantFP>(C) &&
337 cast<ConstantFP>(C)->getValueAPF().isFiniteNonZero();
338}
339
340static bool isNormalFp(Constant *C) {
341 if (C->getType()->isVectorTy()) {
342 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
343 ++I) {
344 ConstantFP *CFP = dyn_cast<ConstantFP>(C->getAggregateElement(I));
345 if (!CFP || !CFP->getValueAPF().isNormal())
346 return false;
347 }
348 return true;
349 }
350
351 return isa<ConstantFP>(C) && cast<ConstantFP>(C)->getValueAPF().isNormal();
352}
353
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000354/// Helper function of InstCombiner::visitFMul(BinaryOperator(). It returns
355/// true iff the given value is FMul or FDiv with one and only one operand
356/// being a normal constant (i.e. not Zero/NaN/Infinity).
357static bool isFMulOrFDivWithConstant(Value *V) {
358 Instruction *I = dyn_cast<Instruction>(V);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000359 if (!I || (I->getOpcode() != Instruction::FMul &&
Shuxin Yang80138662013-01-07 22:41:28 +0000360 I->getOpcode() != Instruction::FDiv))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000361 return false;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000362
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000363 Constant *C0 = dyn_cast<Constant>(I->getOperand(0));
364 Constant *C1 = dyn_cast<Constant>(I->getOperand(1));
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000365
366 if (C0 && C1)
367 return false;
368
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000369 return (C0 && isFiniteNonZeroFp(C0)) || (C1 && isFiniteNonZeroFp(C1));
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000370}
371
372/// foldFMulConst() is a helper routine of InstCombiner::visitFMul().
373/// The input \p FMulOrDiv is a FMul/FDiv with one and only one operand
374/// being a constant (i.e. isFMulOrFDivWithConstant(FMulOrDiv) == true).
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000375/// This function is to simplify "FMulOrDiv * C" and returns the
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000376/// resulting expression. Note that this function could return NULL in
377/// case the constants cannot be folded into a normal floating-point.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000378///
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000379Value *InstCombiner::foldFMulConst(Instruction *FMulOrDiv, Constant *C,
Shuxin Yang80138662013-01-07 22:41:28 +0000380 Instruction *InsertBefore) {
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000381 assert(isFMulOrFDivWithConstant(FMulOrDiv) && "V is invalid");
382
383 Value *Opnd0 = FMulOrDiv->getOperand(0);
384 Value *Opnd1 = FMulOrDiv->getOperand(1);
385
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000386 Constant *C0 = dyn_cast<Constant>(Opnd0);
387 Constant *C1 = dyn_cast<Constant>(Opnd1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000388
389 BinaryOperator *R = 0;
390
391 // (X * C0) * C => X * (C0*C)
392 if (FMulOrDiv->getOpcode() == Instruction::FMul) {
393 Constant *F = ConstantExpr::getFMul(C1 ? C1 : C0, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000394 if (isNormalFp(F))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000395 R = BinaryOperator::CreateFMul(C1 ? Opnd0 : Opnd1, F);
396 } else {
397 if (C0) {
398 // (C0 / X) * C => (C0 * C) / X
Shuxin Yang3a7ca6e2013-09-19 21:13:46 +0000399 if (FMulOrDiv->hasOneUse()) {
400 // It would otherwise introduce another div.
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000401 Constant *F = ConstantExpr::getFMul(C0, C);
Shuxin Yang3a7ca6e2013-09-19 21:13:46 +0000402 if (isNormalFp(F))
403 R = BinaryOperator::CreateFDiv(F, Opnd1);
404 }
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000405 } else {
406 // (X / C1) * C => X * (C/C1) if C/C1 is not a denormal
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000407 Constant *F = ConstantExpr::getFDiv(C, C1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000408 if (isNormalFp(F)) {
409 R = BinaryOperator::CreateFMul(Opnd0, F);
410 } else {
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000411 // (X / C1) * C => X / (C1/C)
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000412 Constant *F = ConstantExpr::getFDiv(C1, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000413 if (isNormalFp(F))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000414 R = BinaryOperator::CreateFDiv(Opnd0, F);
415 }
416 }
417 }
418
419 if (R) {
420 R->setHasUnsafeAlgebra(true);
421 InsertNewInstWith(R, *InsertBefore);
422 }
423
424 return R;
425}
426
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000427Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +0000428 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000429 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
430
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000431 if (isa<Constant>(Op0))
432 std::swap(Op0, Op1);
433
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000434 if (Value *V = SimplifyFMulInst(Op0, Op1, I.getFastMathFlags(), DL))
Michael Ilsemand5787be2012-12-12 00:28:32 +0000435 return ReplaceInstUsesWith(I, V);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000436
Shuxin Yange8227452013-01-15 21:09:32 +0000437 bool AllowReassociate = I.hasUnsafeAlgebra();
438
Michael Ilsemand5787be2012-12-12 00:28:32 +0000439 // Simplify mul instructions with a constant RHS.
440 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000441 // Try to fold constant mul into select arguments.
442 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
443 if (Instruction *R = FoldOpIntoSelect(I, SI))
444 return R;
445
446 if (isa<PHINode>(Op0))
447 if (Instruction *NV = FoldOpIntoPhi(I))
448 return NV;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000449
Owen Andersonf74cfe02014-01-16 20:36:42 +0000450 // (fmul X, -1.0) --> (fsub -0.0, X)
Benjamin Kramerfea9ac92014-01-18 16:43:14 +0000451 if (match(Op1, m_SpecificFP(-1.0))) {
452 Constant *NegZero = ConstantFP::getNegativeZero(Op1->getType());
453 Instruction *RI = BinaryOperator::CreateFSub(NegZero, Op0);
Owen Andersonf74cfe02014-01-16 20:36:42 +0000454 RI->copyFastMathFlags(&I);
455 return RI;
456 }
457
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000458 Constant *C = cast<Constant>(Op1);
459 if (AllowReassociate && isFiniteNonZeroFp(C)) {
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000460 // Let MDC denote an expression in one of these forms:
461 // X * C, C/X, X/C, where C is a constant.
462 //
463 // Try to simplify "MDC * Constant"
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000464 if (isFMulOrFDivWithConstant(Op0))
465 if (Value *V = foldFMulConst(cast<Instruction>(Op0), C, &I))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000466 return ReplaceInstUsesWith(I, V);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000467
Quentin Colombete684a6d2013-02-28 21:12:40 +0000468 // (MDC +/- C1) * C => (MDC * C) +/- (C1 * C)
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000469 Instruction *FAddSub = dyn_cast<Instruction>(Op0);
470 if (FAddSub &&
471 (FAddSub->getOpcode() == Instruction::FAdd ||
472 FAddSub->getOpcode() == Instruction::FSub)) {
473 Value *Opnd0 = FAddSub->getOperand(0);
474 Value *Opnd1 = FAddSub->getOperand(1);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000475 Constant *C0 = dyn_cast<Constant>(Opnd0);
476 Constant *C1 = dyn_cast<Constant>(Opnd1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000477 bool Swap = false;
478 if (C0) {
Shuxin Yang80138662013-01-07 22:41:28 +0000479 std::swap(C0, C1);
480 std::swap(Opnd0, Opnd1);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000481 Swap = true;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000482 }
483
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000484 if (C1 && isFiniteNonZeroFp(C1) && isFMulOrFDivWithConstant(Opnd0)) {
Quentin Colombete684a6d2013-02-28 21:12:40 +0000485 Value *M1 = ConstantExpr::getFMul(C1, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000486 Value *M0 = isNormalFp(cast<Constant>(M1)) ?
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000487 foldFMulConst(cast<Instruction>(Opnd0), C, &I) :
488 0;
489 if (M0 && M1) {
490 if (Swap && FAddSub->getOpcode() == Instruction::FSub)
491 std::swap(M0, M1);
492
Benjamin Kramer67485762013-09-30 15:39:59 +0000493 Instruction *RI = (FAddSub->getOpcode() == Instruction::FAdd)
494 ? BinaryOperator::CreateFAdd(M0, M1)
495 : BinaryOperator::CreateFSub(M0, M1);
Shuxin Yange8227452013-01-15 21:09:32 +0000496 RI->copyFastMathFlags(&I);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000497 return RI;
498 }
499 }
500 }
501 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000502 }
503
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000504
Pedro Artigasd8795042012-11-30 19:09:41 +0000505 // Under unsafe algebra do:
506 // X * log2(0.5*Y) = X*log2(Y) - X
507 if (I.hasUnsafeAlgebra()) {
508 Value *OpX = NULL;
509 Value *OpY = NULL;
510 IntrinsicInst *Log2;
Pedro Artigas993acd02012-11-30 22:07:05 +0000511 detectLog2OfHalf(Op0, OpY, Log2);
512 if (OpY) {
513 OpX = Op1;
514 } else {
515 detectLog2OfHalf(Op1, OpY, Log2);
516 if (OpY) {
517 OpX = Op0;
Pedro Artigasd8795042012-11-30 19:09:41 +0000518 }
519 }
520 // if pattern detected emit alternate sequence
521 if (OpX && OpY) {
Benjamin Kramer67485762013-09-30 15:39:59 +0000522 BuilderTy::FastMathFlagGuard Guard(*Builder);
523 Builder->SetFastMathFlags(Log2->getFastMathFlags());
Pedro Artigasd8795042012-11-30 19:09:41 +0000524 Log2->setArgOperand(0, OpY);
525 Value *FMulVal = Builder->CreateFMul(OpX, Log2);
Benjamin Kramer67485762013-09-30 15:39:59 +0000526 Value *FSub = Builder->CreateFSub(FMulVal, OpX);
527 FSub->takeName(&I);
528 return ReplaceInstUsesWith(I, FSub);
Pedro Artigasd8795042012-11-30 19:09:41 +0000529 }
530 }
531
Shuxin Yange8227452013-01-15 21:09:32 +0000532 // Handle symmetric situation in a 2-iteration loop
533 Value *Opnd0 = Op0;
534 Value *Opnd1 = Op1;
535 for (int i = 0; i < 2; i++) {
536 bool IgnoreZeroSign = I.hasNoSignedZeros();
537 if (BinaryOperator::isFNeg(Opnd0, IgnoreZeroSign)) {
Benjamin Kramer67485762013-09-30 15:39:59 +0000538 BuilderTy::FastMathFlagGuard Guard(*Builder);
539 Builder->SetFastMathFlags(I.getFastMathFlags());
540
Shuxin Yange8227452013-01-15 21:09:32 +0000541 Value *N0 = dyn_castFNegVal(Opnd0, IgnoreZeroSign);
542 Value *N1 = dyn_castFNegVal(Opnd1, IgnoreZeroSign);
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000543
Shuxin Yange8227452013-01-15 21:09:32 +0000544 // -X * -Y => X*Y
Owen Andersone8537fc2014-01-16 20:59:41 +0000545 if (N1) {
546 Value *FMul = Builder->CreateFMul(N0, N1);
547 FMul->takeName(&I);
548 return ReplaceInstUsesWith(I, FMul);
549 }
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000550
Shuxin Yange8227452013-01-15 21:09:32 +0000551 if (Opnd0->hasOneUse()) {
552 // -X * Y => -(X*Y) (Promote negation as high as possible)
553 Value *T = Builder->CreateFMul(N0, Opnd1);
Benjamin Kramer67485762013-09-30 15:39:59 +0000554 Value *Neg = Builder->CreateFNeg(T);
555 Neg->takeName(&I);
556 return ReplaceInstUsesWith(I, Neg);
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000557 }
558 }
Shuxin Yange8227452013-01-15 21:09:32 +0000559
560 // (X*Y) * X => (X*X) * Y where Y != X
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000561 // The purpose is two-fold:
Shuxin Yange8227452013-01-15 21:09:32 +0000562 // 1) to form a power expression (of X).
563 // 2) potentially shorten the critical path: After transformation, the
564 // latency of the instruction Y is amortized by the expression of X*X,
565 // and therefore Y is in a "less critical" position compared to what it
566 // was before the transformation.
567 //
568 if (AllowReassociate) {
569 Value *Opnd0_0, *Opnd0_1;
570 if (Opnd0->hasOneUse() &&
571 match(Opnd0, m_FMul(m_Value(Opnd0_0), m_Value(Opnd0_1)))) {
572 Value *Y = 0;
573 if (Opnd0_0 == Opnd1 && Opnd0_1 != Opnd1)
574 Y = Opnd0_1;
575 else if (Opnd0_1 == Opnd1 && Opnd0_0 != Opnd1)
576 Y = Opnd0_0;
577
578 if (Y) {
Benjamin Kramer67485762013-09-30 15:39:59 +0000579 BuilderTy::FastMathFlagGuard Guard(*Builder);
580 Builder->SetFastMathFlags(I.getFastMathFlags());
581 Value *T = Builder->CreateFMul(Opnd1, Opnd1);
Shuxin Yange8227452013-01-15 21:09:32 +0000582
Benjamin Kramer67485762013-09-30 15:39:59 +0000583 Value *R = Builder->CreateFMul(T, Y);
584 R->takeName(&I);
585 return ReplaceInstUsesWith(I, R);
Shuxin Yange8227452013-01-15 21:09:32 +0000586 }
587 }
588 }
589
Stephen Lin03f9fbb2013-07-17 20:06:03 +0000590 // B * (uitofp i1 C) -> select C, B, 0
591 if (I.hasNoNaNs() && I.hasNoInfs() && I.hasNoSignedZeros()) {
592 Value *LHS = Op0, *RHS = Op1;
593 Value *B, *C;
Stephen Lin4ef13872013-07-26 17:55:00 +0000594 if (!match(RHS, m_UIToFP(m_Value(C))))
Stephen Lin03f9fbb2013-07-17 20:06:03 +0000595 std::swap(LHS, RHS);
596
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000597 if (match(RHS, m_UIToFP(m_Value(C))) &&
598 C->getType()->getScalarType()->isIntegerTy(1)) {
Stephen Lin03f9fbb2013-07-17 20:06:03 +0000599 B = LHS;
600 Value *Zero = ConstantFP::getNegativeZero(B->getType());
601 return SelectInst::Create(C, B, Zero);
602 }
603 }
604
605 // A * (1 - uitofp i1 C) -> select C, 0, A
606 if (I.hasNoNaNs() && I.hasNoInfs() && I.hasNoSignedZeros()) {
607 Value *LHS = Op0, *RHS = Op1;
608 Value *A, *C;
Stephen Lin4ef13872013-07-26 17:55:00 +0000609 if (!match(RHS, m_FSub(m_FPOne(), m_UIToFP(m_Value(C)))))
Stephen Lin03f9fbb2013-07-17 20:06:03 +0000610 std::swap(LHS, RHS);
611
Stephen Lin4ef13872013-07-26 17:55:00 +0000612 if (match(RHS, m_FSub(m_FPOne(), m_UIToFP(m_Value(C)))) &&
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000613 C->getType()->getScalarType()->isIntegerTy(1)) {
Stephen Lin03f9fbb2013-07-17 20:06:03 +0000614 A = LHS;
615 Value *Zero = ConstantFP::getNegativeZero(A->getType());
616 return SelectInst::Create(C, Zero, A);
617 }
618 }
619
Shuxin Yange8227452013-01-15 21:09:32 +0000620 if (!isa<Constant>(Op1))
621 std::swap(Opnd0, Opnd1);
622 else
623 break;
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000624 }
625
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000626 return Changed ? &I : 0;
627}
628
629/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
630/// instruction.
631bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
632 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000633
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000634 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
635 int NonNullOperand = -1;
636 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
637 if (ST->isNullValue())
638 NonNullOperand = 2;
639 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
640 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
641 if (ST->isNullValue())
642 NonNullOperand = 1;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000643
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000644 if (NonNullOperand == -1)
645 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000646
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000647 Value *SelectCond = SI->getOperand(0);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000648
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000649 // Change the div/rem to use 'Y' instead of the select.
650 I.setOperand(1, SI->getOperand(NonNullOperand));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000651
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000652 // Okay, we know we replace the operand of the div/rem with 'Y' with no
653 // problem. However, the select, or the condition of the select may have
654 // multiple uses. Based on our knowledge that the operand must be non-zero,
655 // propagate the known value for the select into other uses of it, and
656 // propagate a known value of the condition into its other users.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000657
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000658 // If the select and condition only have a single use, don't bother with this,
659 // early exit.
660 if (SI->use_empty() && SelectCond->hasOneUse())
661 return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000662
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000663 // Scan the current block backward, looking for other uses of SI.
664 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000665
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000666 while (BBI != BBFront) {
667 --BBI;
668 // If we found a call to a function, we can't assume it will return, so
669 // information from below it cannot be propagated above it.
670 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
671 break;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000672
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000673 // Replace uses of the select or its condition with the known values.
674 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
675 I != E; ++I) {
676 if (*I == SI) {
677 *I = SI->getOperand(NonNullOperand);
678 Worklist.Add(BBI);
679 } else if (*I == SelectCond) {
Jakub Staszak96ff4d62013-06-06 23:34:59 +0000680 *I = Builder->getInt1(NonNullOperand == 1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000681 Worklist.Add(BBI);
682 }
683 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000684
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000685 // If we past the instruction, quit looking for it.
686 if (&*BBI == SI)
687 SI = 0;
688 if (&*BBI == SelectCond)
689 SelectCond = 0;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000690
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000691 // If we ran out of things to eliminate, break out of the loop.
692 if (SelectCond == 0 && SI == 0)
693 break;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000694
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000695 }
696 return true;
697}
698
699
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000700/// This function implements the transforms common to both integer division
701/// instructions (udiv and sdiv). It is called by the visitors to those integer
702/// division instructions.
703/// @brief Common integer divide transforms
704Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
705 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
706
Chris Lattner7c99f192011-05-22 18:18:41 +0000707 // The RHS is known non-zero.
708 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) {
709 I.setOperand(1, V);
710 return &I;
711 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000712
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000713 // Handle cases involving: [su]div X, (select Cond, Y, Z)
714 // This does not apply for fdiv.
715 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
716 return &I;
717
718 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000719 // (X / C1) / C2 -> X / (C1*C2)
720 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
721 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
722 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
723 if (MultiplyOverflows(RHS, LHSRHS,
724 I.getOpcode()==Instruction::SDiv))
725 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner6b657ae2011-02-10 05:36:31 +0000726 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
727 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000728 }
729
730 if (!RHS->isZero()) { // avoid X udiv 0
731 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
732 if (Instruction *R = FoldOpIntoSelect(I, SI))
733 return R;
734 if (isa<PHINode>(Op0))
735 if (Instruction *NV = FoldOpIntoPhi(I))
736 return NV;
737 }
738 }
739
Benjamin Kramer57b3df52011-04-30 18:16:00 +0000740 // See if we can fold away this div instruction.
741 if (SimplifyDemandedInstructionBits(I))
742 return &I;
743
Duncan Sands771e82a2011-01-28 16:51:11 +0000744 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
745 Value *X = 0, *Z = 0;
746 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) { // (X - Z) / Y; Y = Op1
747 bool isSigned = I.getOpcode() == Instruction::SDiv;
748 if ((isSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
749 (!isSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
750 return BinaryOperator::Create(I.getOpcode(), X, Op1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000751 }
752
753 return 0;
754}
755
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000756/// dyn_castZExtVal - Checks if V is a zext or constant that can
757/// be truncated to Ty without losing bits.
Chris Lattner229907c2011-07-18 04:54:35 +0000758static Value *dyn_castZExtVal(Value *V, Type *Ty) {
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000759 if (ZExtInst *Z = dyn_cast<ZExtInst>(V)) {
760 if (Z->getSrcTy() == Ty)
761 return Z->getOperand(0);
762 } else if (ConstantInt *C = dyn_cast<ConstantInt>(V)) {
763 if (C->getValue().getActiveBits() <= cast<IntegerType>(Ty)->getBitWidth())
764 return ConstantExpr::getTrunc(C, Ty);
765 }
766 return 0;
767}
768
David Majnemer37f8f442013-07-04 21:17:49 +0000769namespace {
770const unsigned MaxDepth = 6;
771typedef Instruction *(*FoldUDivOperandCb)(Value *Op0, Value *Op1,
772 const BinaryOperator &I,
773 InstCombiner &IC);
774
775/// \brief Used to maintain state for visitUDivOperand().
776struct UDivFoldAction {
777 FoldUDivOperandCb FoldAction; ///< Informs visitUDiv() how to fold this
778 ///< operand. This can be zero if this action
779 ///< joins two actions together.
780
781 Value *OperandToFold; ///< Which operand to fold.
782 union {
783 Instruction *FoldResult; ///< The instruction returned when FoldAction is
784 ///< invoked.
785
786 size_t SelectLHSIdx; ///< Stores the LHS action index if this action
787 ///< joins two actions together.
788 };
789
790 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand)
791 : FoldAction(FA), OperandToFold(InputOperand), FoldResult(0) {}
792 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand, size_t SLHS)
793 : FoldAction(FA), OperandToFold(InputOperand), SelectLHSIdx(SLHS) {}
794};
795}
796
797// X udiv 2^C -> X >> C
798static Instruction *foldUDivPow2Cst(Value *Op0, Value *Op1,
799 const BinaryOperator &I, InstCombiner &IC) {
800 const APInt &C = cast<Constant>(Op1)->getUniqueInteger();
801 BinaryOperator *LShr = BinaryOperator::CreateLShr(
802 Op0, ConstantInt::get(Op0->getType(), C.logBase2()));
803 if (I.isExact()) LShr->setIsExact();
804 return LShr;
805}
806
807// X udiv C, where C >= signbit
808static Instruction *foldUDivNegCst(Value *Op0, Value *Op1,
809 const BinaryOperator &I, InstCombiner &IC) {
810 Value *ICI = IC.Builder->CreateICmpULT(Op0, cast<ConstantInt>(Op1));
811
812 return SelectInst::Create(ICI, Constant::getNullValue(I.getType()),
813 ConstantInt::get(I.getType(), 1));
814}
815
816// X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
817static Instruction *foldUDivShl(Value *Op0, Value *Op1, const BinaryOperator &I,
818 InstCombiner &IC) {
819 Instruction *ShiftLeft = cast<Instruction>(Op1);
820 if (isa<ZExtInst>(ShiftLeft))
821 ShiftLeft = cast<Instruction>(ShiftLeft->getOperand(0));
822
823 const APInt &CI =
824 cast<Constant>(ShiftLeft->getOperand(0))->getUniqueInteger();
825 Value *N = ShiftLeft->getOperand(1);
826 if (CI != 1)
827 N = IC.Builder->CreateAdd(N, ConstantInt::get(N->getType(), CI.logBase2()));
828 if (ZExtInst *Z = dyn_cast<ZExtInst>(Op1))
829 N = IC.Builder->CreateZExt(N, Z->getDestTy());
830 BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, N);
831 if (I.isExact()) LShr->setIsExact();
832 return LShr;
833}
834
835// \brief Recursively visits the possible right hand operands of a udiv
836// instruction, seeing through select instructions, to determine if we can
837// replace the udiv with something simpler. If we find that an operand is not
838// able to simplify the udiv, we abort the entire transformation.
839static size_t visitUDivOperand(Value *Op0, Value *Op1, const BinaryOperator &I,
840 SmallVectorImpl<UDivFoldAction> &Actions,
841 unsigned Depth = 0) {
842 // Check to see if this is an unsigned division with an exact power of 2,
843 // if so, convert to a right shift.
844 if (match(Op1, m_Power2())) {
845 Actions.push_back(UDivFoldAction(foldUDivPow2Cst, Op1));
846 return Actions.size();
847 }
848
849 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1))
850 // X udiv C, where C >= signbit
851 if (C->getValue().isNegative()) {
852 Actions.push_back(UDivFoldAction(foldUDivNegCst, C));
853 return Actions.size();
854 }
855
856 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
857 if (match(Op1, m_Shl(m_Power2(), m_Value())) ||
858 match(Op1, m_ZExt(m_Shl(m_Power2(), m_Value())))) {
859 Actions.push_back(UDivFoldAction(foldUDivShl, Op1));
860 return Actions.size();
861 }
862
863 // The remaining tests are all recursive, so bail out if we hit the limit.
864 if (Depth++ == MaxDepth)
865 return 0;
866
867 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
868 if (size_t LHSIdx = visitUDivOperand(Op0, SI->getOperand(1), I, Actions))
869 if (visitUDivOperand(Op0, SI->getOperand(2), I, Actions)) {
870 Actions.push_back(UDivFoldAction((FoldUDivOperandCb)0, Op1, LHSIdx-1));
871 return Actions.size();
872 }
873
874 return 0;
875}
876
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000877Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
878 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
879
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000880 if (Value *V = SimplifyUDivInst(Op0, Op1, DL))
Duncan Sands771e82a2011-01-28 16:51:11 +0000881 return ReplaceInstUsesWith(I, V);
882
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000883 // Handle the integer div common cases
884 if (Instruction *Common = commonIDivTransforms(I))
885 return Common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000886
Benjamin Kramerd4a64712012-08-30 15:07:40 +0000887 // (x lshr C1) udiv C2 --> x udiv (C2 << C1)
Benjamin Kramer72196f32014-01-19 15:24:22 +0000888 if (Constant *C2 = dyn_cast<Constant>(Op1)) {
Benjamin Kramer9c0a8072012-08-28 13:08:13 +0000889 Value *X;
Benjamin Kramer72196f32014-01-19 15:24:22 +0000890 Constant *C1;
891 if (match(Op0, m_LShr(m_Value(X), m_Constant(C1))))
892 return BinaryOperator::CreateUDiv(X, ConstantExpr::getShl(C2, C1));
Nadav Rotem11935b22012-08-28 10:01:43 +0000893 }
894
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000895 // (zext A) udiv (zext B) --> zext (A udiv B)
896 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
897 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
898 return new ZExtInst(Builder->CreateUDiv(ZOp0->getOperand(0), ZOp1, "div",
899 I.isExact()),
900 I.getType());
901
David Majnemer37f8f442013-07-04 21:17:49 +0000902 // (LHS udiv (select (select (...)))) -> (LHS >> (select (select (...))))
903 SmallVector<UDivFoldAction, 6> UDivActions;
904 if (visitUDivOperand(Op0, Op1, I, UDivActions))
905 for (unsigned i = 0, e = UDivActions.size(); i != e; ++i) {
906 FoldUDivOperandCb Action = UDivActions[i].FoldAction;
907 Value *ActionOp1 = UDivActions[i].OperandToFold;
908 Instruction *Inst;
909 if (Action)
910 Inst = Action(Op0, ActionOp1, I, *this);
911 else {
912 // This action joins two actions together. The RHS of this action is
913 // simply the last action we processed, we saved the LHS action index in
914 // the joining action.
915 size_t SelectRHSIdx = i - 1;
916 Value *SelectRHS = UDivActions[SelectRHSIdx].FoldResult;
917 size_t SelectLHSIdx = UDivActions[i].SelectLHSIdx;
918 Value *SelectLHS = UDivActions[SelectLHSIdx].FoldResult;
919 Inst = SelectInst::Create(cast<SelectInst>(ActionOp1)->getCondition(),
920 SelectLHS, SelectRHS);
921 }
922
923 // If this is the last action to process, return it to the InstCombiner.
924 // Otherwise, we insert it before the UDiv and record it so that we may
925 // use it as part of a joining action (i.e., a SelectInst).
926 if (e - i != 1) {
927 Inst->insertBefore(&I);
928 UDivActions[i].FoldResult = Inst;
929 } else
930 return Inst;
931 }
932
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000933 return 0;
934}
935
936Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
937 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
938
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000939 if (Value *V = SimplifySDivInst(Op0, Op1, DL))
Duncan Sands771e82a2011-01-28 16:51:11 +0000940 return ReplaceInstUsesWith(I, V);
941
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000942 // Handle the integer div common cases
943 if (Instruction *Common = commonIDivTransforms(I))
944 return Common;
945
Benjamin Kramer72196f32014-01-19 15:24:22 +0000946 // sdiv X, -1 == -X
947 if (match(Op1, m_AllOnes()))
948 return BinaryOperator::CreateNeg(Op0);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000949
Benjamin Kramer72196f32014-01-19 15:24:22 +0000950 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6b657ae2011-02-10 05:36:31 +0000951 // sdiv X, C --> ashr exact X, log2(C)
952 if (I.isExact() && RHS->getValue().isNonNegative() &&
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000953 RHS->getValue().isPowerOf2()) {
954 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
955 RHS->getValue().exactLogBase2());
Chris Lattner6b657ae2011-02-10 05:36:31 +0000956 return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000957 }
Benjamin Kramer72196f32014-01-19 15:24:22 +0000958 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000959
Benjamin Kramer72196f32014-01-19 15:24:22 +0000960 if (Constant *RHS = dyn_cast<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000961 // -X/C --> X/-C provided the negation doesn't overflow.
962 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
Chris Lattner6b657ae2011-02-10 05:36:31 +0000963 if (match(Sub->getOperand(0), m_Zero()) && Sub->hasNoSignedWrap())
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000964 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
965 ConstantExpr::getNeg(RHS));
966 }
967
968 // If the sign bits of both operands are zero (i.e. we can prove they are
969 // unsigned inputs), turn this into a udiv.
Duncan Sands9dff9be2010-02-15 16:12:20 +0000970 if (I.getType()->isIntegerTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000971 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
972 if (MaskedValueIsZero(Op0, Mask)) {
973 if (MaskedValueIsZero(Op1, Mask)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000974 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000975 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
976 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000977
Chris Lattner6b657ae2011-02-10 05:36:31 +0000978 if (match(Op1, m_Shl(m_Power2(), m_Value()))) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000979 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
980 // Safe because the only negative value (1 << Y) can take on is
981 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
982 // the sign bit set.
983 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
984 }
985 }
986 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000987
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000988 return 0;
989}
990
Shuxin Yang320f52a2013-01-14 22:48:41 +0000991/// CvtFDivConstToReciprocal tries to convert X/C into X*1/C if C not a special
992/// FP value and:
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000993/// 1) 1/C is exact, or
Shuxin Yang320f52a2013-01-14 22:48:41 +0000994/// 2) reciprocal is allowed.
Sylvestre Ledru149e2812013-05-14 23:36:24 +0000995/// If the conversion was successful, the simplified expression "X * 1/C" is
Shuxin Yang320f52a2013-01-14 22:48:41 +0000996/// returned; otherwise, NULL is returned.
997///
998static Instruction *CvtFDivConstToReciprocal(Value *Dividend,
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000999 Constant *Divisor,
Shuxin Yang320f52a2013-01-14 22:48:41 +00001000 bool AllowReciprocal) {
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001001 if (!isa<ConstantFP>(Divisor)) // TODO: handle vectors.
1002 return 0;
1003
1004 const APFloat &FpVal = cast<ConstantFP>(Divisor)->getValueAPF();
Shuxin Yang320f52a2013-01-14 22:48:41 +00001005 APFloat Reciprocal(FpVal.getSemantics());
1006 bool Cvt = FpVal.getExactInverse(&Reciprocal);
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001007
Michael Gottesman3cb77ab2013-06-19 21:23:18 +00001008 if (!Cvt && AllowReciprocal && FpVal.isFiniteNonZero()) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001009 Reciprocal = APFloat(FpVal.getSemantics(), 1.0f);
1010 (void)Reciprocal.divide(FpVal, APFloat::rmNearestTiesToEven);
1011 Cvt = !Reciprocal.isDenormal();
1012 }
1013
1014 if (!Cvt)
1015 return 0;
1016
1017 ConstantFP *R;
1018 R = ConstantFP::get(Dividend->getType()->getContext(), Reciprocal);
1019 return BinaryOperator::CreateFMul(Dividend, R);
1020}
1021
Frits van Bommel2a559512011-01-29 17:50:27 +00001022Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
1023 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1024
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001025 if (Value *V = SimplifyFDivInst(Op0, Op1, DL))
Frits van Bommel2a559512011-01-29 17:50:27 +00001026 return ReplaceInstUsesWith(I, V);
1027
Stephen Lina9b57f62013-07-20 07:13:13 +00001028 if (isa<Constant>(Op0))
1029 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1030 if (Instruction *R = FoldOpIntoSelect(I, SI))
1031 return R;
1032
Shuxin Yang320f52a2013-01-14 22:48:41 +00001033 bool AllowReassociate = I.hasUnsafeAlgebra();
1034 bool AllowReciprocal = I.hasAllowReciprocal();
Benjamin Kramer8564e0d2011-03-30 15:42:35 +00001035
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001036 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Stephen Lina9b57f62013-07-20 07:13:13 +00001037 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1038 if (Instruction *R = FoldOpIntoSelect(I, SI))
1039 return R;
1040
Shuxin Yang320f52a2013-01-14 22:48:41 +00001041 if (AllowReassociate) {
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001042 Constant *C1 = 0;
1043 Constant *C2 = Op1C;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001044 Value *X;
1045 Instruction *Res = 0;
1046
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001047 if (match(Op0, m_FMul(m_Value(X), m_Constant(C1)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001048 // (X*C1)/C2 => X * (C1/C2)
1049 //
1050 Constant *C = ConstantExpr::getFDiv(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001051 if (isNormalFp(C))
Shuxin Yang320f52a2013-01-14 22:48:41 +00001052 Res = BinaryOperator::CreateFMul(X, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001053 } else if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001054 // (X/C1)/C2 => X /(C2*C1) [=> X * 1/(C2*C1) if reciprocal is allowed]
1055 //
1056 Constant *C = ConstantExpr::getFMul(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001057 if (isNormalFp(C)) {
1058 Res = CvtFDivConstToReciprocal(X, C, AllowReciprocal);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001059 if (!Res)
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001060 Res = BinaryOperator::CreateFDiv(X, C);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001061 }
1062 }
1063
1064 if (Res) {
1065 Res->setFastMathFlags(I.getFastMathFlags());
1066 return Res;
1067 }
1068 }
1069
1070 // X / C => X * 1/C
Owen Anderson4557a152014-01-16 21:07:52 +00001071 if (Instruction *T = CvtFDivConstToReciprocal(Op0, Op1C, AllowReciprocal)) {
1072 T->copyFastMathFlags(&I);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001073 return T;
Owen Anderson4557a152014-01-16 21:07:52 +00001074 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001075
1076 return 0;
1077 }
1078
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001079 if (AllowReassociate && isa<Constant>(Op0)) {
1080 Constant *C1 = cast<Constant>(Op0), *C2;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001081 Constant *Fold = 0;
1082 Value *X;
1083 bool CreateDiv = true;
1084
1085 // C1 / (X*C2) => (C1/C2) / X
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001086 if (match(Op1, m_FMul(m_Value(X), m_Constant(C2))))
Shuxin Yang320f52a2013-01-14 22:48:41 +00001087 Fold = ConstantExpr::getFDiv(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001088 else if (match(Op1, m_FDiv(m_Value(X), m_Constant(C2)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001089 // C1 / (X/C2) => (C1*C2) / X
1090 Fold = ConstantExpr::getFMul(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001091 } else if (match(Op1, m_FDiv(m_Constant(C2), m_Value(X)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001092 // C1 / (C2/X) => (C1/C2) * X
1093 Fold = ConstantExpr::getFDiv(C1, C2);
1094 CreateDiv = false;
1095 }
1096
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001097 if (Fold && isNormalFp(Fold)) {
1098 Instruction *R = CreateDiv ? BinaryOperator::CreateFDiv(Fold, X)
1099 : BinaryOperator::CreateFMul(X, Fold);
1100 R->setFastMathFlags(I.getFastMathFlags());
1101 return R;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001102 }
1103 return 0;
1104 }
1105
1106 if (AllowReassociate) {
1107 Value *X, *Y;
1108 Value *NewInst = 0;
1109 Instruction *SimpR = 0;
1110
1111 if (Op0->hasOneUse() && match(Op0, m_FDiv(m_Value(X), m_Value(Y)))) {
1112 // (X/Y) / Z => X / (Y*Z)
1113 //
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001114 if (!isa<Constant>(Y) || !isa<Constant>(Op1)) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001115 NewInst = Builder->CreateFMul(Y, Op1);
Owen Anderson1664dc82014-01-20 07:44:53 +00001116 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1117 FastMathFlags Flags = I.getFastMathFlags();
1118 Flags &= cast<Instruction>(Op0)->getFastMathFlags();
1119 RI->setFastMathFlags(Flags);
1120 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001121 SimpR = BinaryOperator::CreateFDiv(X, NewInst);
1122 }
1123 } else if (Op1->hasOneUse() && match(Op1, m_FDiv(m_Value(X), m_Value(Y)))) {
1124 // Z / (X/Y) => Z*Y / X
1125 //
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001126 if (!isa<Constant>(Y) || !isa<Constant>(Op0)) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001127 NewInst = Builder->CreateFMul(Op0, Y);
Owen Anderson1664dc82014-01-20 07:44:53 +00001128 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1129 FastMathFlags Flags = I.getFastMathFlags();
1130 Flags &= cast<Instruction>(Op1)->getFastMathFlags();
1131 RI->setFastMathFlags(Flags);
1132 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001133 SimpR = BinaryOperator::CreateFDiv(NewInst, X);
1134 }
1135 }
1136
1137 if (NewInst) {
1138 if (Instruction *T = dyn_cast<Instruction>(NewInst))
1139 T->setDebugLoc(I.getDebugLoc());
1140 SimpR->setFastMathFlags(I.getFastMathFlags());
1141 return SimpR;
Benjamin Kramer8564e0d2011-03-30 15:42:35 +00001142 }
1143 }
1144
Frits van Bommel2a559512011-01-29 17:50:27 +00001145 return 0;
1146}
1147
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001148/// This function implements the transforms common to both integer remainder
1149/// instructions (urem and srem). It is called by the visitors to those integer
1150/// remainder instructions.
1151/// @brief Common integer remainder transforms
1152Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
1153 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1154
Chris Lattner7c99f192011-05-22 18:18:41 +00001155 // The RHS is known non-zero.
1156 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) {
1157 I.setOperand(1, V);
1158 return &I;
1159 }
1160
Duncan Sandsa3e36992011-05-02 16:27:02 +00001161 // Handle cases involving: rem X, (select Cond, Y, Z)
1162 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1163 return &I;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001164
Benjamin Kramer72196f32014-01-19 15:24:22 +00001165 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001166 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1167 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1168 if (Instruction *R = FoldOpIntoSelect(I, SI))
1169 return R;
1170 } else if (isa<PHINode>(Op0I)) {
1171 if (Instruction *NV = FoldOpIntoPhi(I))
1172 return NV;
1173 }
1174
1175 // See if we can fold away this rem instruction.
1176 if (SimplifyDemandedInstructionBits(I))
1177 return &I;
1178 }
1179 }
1180
1181 return 0;
1182}
1183
1184Instruction *InstCombiner::visitURem(BinaryOperator &I) {
1185 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1186
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001187 if (Value *V = SimplifyURemInst(Op0, Op1, DL))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001188 return ReplaceInstUsesWith(I, V);
1189
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001190 if (Instruction *common = commonIRemTransforms(I))
1191 return common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001192
David Majnemer6c30f492013-05-12 00:07:05 +00001193 // (zext A) urem (zext B) --> zext (A urem B)
1194 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
1195 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
1196 return new ZExtInst(Builder->CreateURem(ZOp0->getOperand(0), ZOp1),
1197 I.getType());
1198
David Majnemer470b0772013-05-11 09:01:28 +00001199 // X urem Y -> X and Y-1, where Y is a power of 2,
1200 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/true)) {
Chris Lattner6b657ae2011-02-10 05:36:31 +00001201 Constant *N1 = Constant::getAllOnesValue(I.getType());
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001202 Value *Add = Builder->CreateAdd(Op1, N1);
Chris Lattner6b657ae2011-02-10 05:36:31 +00001203 return BinaryOperator::CreateAnd(Op0, Add);
1204 }
1205
Nick Lewycky7459be62013-07-13 01:16:47 +00001206 // 1 urem X -> zext(X != 1)
1207 if (match(Op0, m_One())) {
1208 Value *Cmp = Builder->CreateICmpNE(Op1, Op0);
1209 Value *Ext = Builder->CreateZExt(Cmp, I.getType());
1210 return ReplaceInstUsesWith(I, Ext);
1211 }
1212
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001213 return 0;
1214}
1215
1216Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
1217 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1218
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001219 if (Value *V = SimplifySRemInst(Op0, Op1, DL))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001220 return ReplaceInstUsesWith(I, V);
1221
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001222 // Handle the integer rem common cases
1223 if (Instruction *Common = commonIRemTransforms(I))
1224 return Common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001225
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001226 if (Value *RHSNeg = dyn_castNegVal(Op1))
1227 if (!isa<Constant>(RHSNeg) ||
1228 (isa<ConstantInt>(RHSNeg) &&
1229 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
1230 // X % -Y -> X % Y
1231 Worklist.AddValue(I.getOperand(1));
1232 I.setOperand(1, RHSNeg);
1233 return &I;
1234 }
1235
1236 // If the sign bits of both operands are zero (i.e. we can prove they are
1237 // unsigned inputs), turn this into a urem.
Duncan Sands9dff9be2010-02-15 16:12:20 +00001238 if (I.getType()->isIntegerTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001239 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
1240 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001241 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001242 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
1243 }
1244 }
1245
1246 // If it's a constant vector, flip any negative values positive.
Chris Lattner0256be92012-01-27 03:08:05 +00001247 if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
1248 Constant *C = cast<Constant>(Op1);
1249 unsigned VWidth = C->getType()->getVectorNumElements();
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001250
1251 bool hasNegative = false;
Chris Lattner0256be92012-01-27 03:08:05 +00001252 bool hasMissing = false;
1253 for (unsigned i = 0; i != VWidth; ++i) {
1254 Constant *Elt = C->getAggregateElement(i);
1255 if (Elt == 0) {
1256 hasMissing = true;
1257 break;
1258 }
1259
1260 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
Chris Lattnerb1a15122011-07-15 06:08:15 +00001261 if (RHS->isNegative())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001262 hasNegative = true;
Chris Lattner0256be92012-01-27 03:08:05 +00001263 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001264
Chris Lattner0256be92012-01-27 03:08:05 +00001265 if (hasNegative && !hasMissing) {
Chris Lattner47a86bd2012-01-25 06:02:56 +00001266 SmallVector<Constant *, 16> Elts(VWidth);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001267 for (unsigned i = 0; i != VWidth; ++i) {
Chris Lattner8213c8a2012-02-06 21:56:39 +00001268 Elts[i] = C->getAggregateElement(i); // Handle undef, etc.
Chris Lattner0256be92012-01-27 03:08:05 +00001269 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
Chris Lattnerb1a15122011-07-15 06:08:15 +00001270 if (RHS->isNegative())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001271 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001272 }
1273 }
1274
1275 Constant *NewRHSV = ConstantVector::get(Elts);
Chris Lattner0256be92012-01-27 03:08:05 +00001276 if (NewRHSV != C) { // Don't loop on -MININT
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001277 Worklist.AddValue(I.getOperand(1));
1278 I.setOperand(1, NewRHSV);
1279 return &I;
1280 }
1281 }
1282 }
1283
1284 return 0;
1285}
1286
1287Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Duncan Sandsa3e36992011-05-02 16:27:02 +00001288 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001289
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001290 if (Value *V = SimplifyFRemInst(Op0, Op1, DL))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001291 return ReplaceInstUsesWith(I, V);
1292
1293 // Handle cases involving: rem X, (select Cond, Y, Z)
1294 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1295 return &I;
1296
1297 return 0;
1298}