blob: 6c34b1bf56631f587407aba26e3ec29b0f846eee [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"
Chris Lattnerdc054bf2010-01-05 06:09:35 +000018#include "llvm/Support/PatternMatch.h"
19using namespace llvm;
20using namespace PatternMatch;
21
Chris Lattner7c99f192011-05-22 18:18:41 +000022
23/// simplifyValueKnownNonZero - The specific integer value is used in a context
24/// where it is known to be non-zero. If this allows us to simplify the
25/// computation, do so and return the new operand, otherwise return null.
26static Value *simplifyValueKnownNonZero(Value *V, InstCombiner &IC) {
27 // If V has multiple uses, then we would have to do more analysis to determine
28 // if this is safe. For example, the use could be in dynamically unreached
29 // code.
30 if (!V->hasOneUse()) return 0;
Jim Grosbachbdbd7342013-04-05 21:20:12 +000031
Chris Lattner388cb8a2011-05-23 00:32:19 +000032 bool MadeChange = false;
33
Chris Lattner7c99f192011-05-22 18:18:41 +000034 // ((1 << A) >>u B) --> (1 << (A-B))
35 // Because V cannot be zero, we know that B is less than A.
Chris Lattner321c58f2011-05-23 00:09:55 +000036 Value *A = 0, *B = 0, *PowerOf2 = 0;
37 if (match(V, m_LShr(m_OneUse(m_Shl(m_Value(PowerOf2), m_Value(A))),
Chris Lattner7c99f192011-05-22 18:18:41 +000038 m_Value(B))) &&
39 // The "1" can be any value known to be a power of 2.
Rafael Espindola319f74c2012-12-13 03:37:24 +000040 isKnownToBeAPowerOfTwo(PowerOf2)) {
Benjamin Kramer547b6c52011-09-27 20:39:19 +000041 A = IC.Builder->CreateSub(A, B);
Chris Lattner321c58f2011-05-23 00:09:55 +000042 return IC.Builder->CreateShl(PowerOf2, A);
Chris Lattner7c99f192011-05-22 18:18:41 +000043 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000044
Chris Lattner388cb8a2011-05-23 00:32:19 +000045 // (PowerOfTwo >>u B) --> isExact since shifting out the result would make it
46 // inexact. Similarly for <<.
47 if (BinaryOperator *I = dyn_cast<BinaryOperator>(V))
Rafael Espindola319f74c2012-12-13 03:37:24 +000048 if (I->isLogicalShift() && isKnownToBeAPowerOfTwo(I->getOperand(0))) {
Chris Lattner388cb8a2011-05-23 00:32:19 +000049 // We know that this is an exact/nuw shift and that the input is a
50 // non-zero context as well.
51 if (Value *V2 = simplifyValueKnownNonZero(I->getOperand(0), IC)) {
52 I->setOperand(0, V2);
53 MadeChange = true;
54 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000055
Chris Lattner388cb8a2011-05-23 00:32:19 +000056 if (I->getOpcode() == Instruction::LShr && !I->isExact()) {
57 I->setIsExact();
58 MadeChange = true;
59 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000060
Chris Lattner388cb8a2011-05-23 00:32:19 +000061 if (I->getOpcode() == Instruction::Shl && !I->hasNoUnsignedWrap()) {
62 I->setHasNoUnsignedWrap();
63 MadeChange = true;
64 }
65 }
66
Chris Lattner162dfc32011-05-22 18:26:48 +000067 // TODO: Lots more we could do here:
Chris Lattner162dfc32011-05-22 18:26:48 +000068 // If V is a phi node, we can call this on each of its operands.
69 // "select cond, X, 0" can simplify to "X".
Jim Grosbachbdbd7342013-04-05 21:20:12 +000070
Chris Lattner388cb8a2011-05-23 00:32:19 +000071 return MadeChange ? V : 0;
Chris Lattner7c99f192011-05-22 18:18:41 +000072}
73
74
Chris Lattnerdc054bf2010-01-05 06:09:35 +000075/// MultiplyOverflows - True if the multiply can not be expressed in an int
76/// this size.
77static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
78 uint32_t W = C1->getBitWidth();
79 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
80 if (sign) {
Jay Foad583abbc2010-12-07 08:25:19 +000081 LHSExt = LHSExt.sext(W * 2);
82 RHSExt = RHSExt.sext(W * 2);
Chris Lattnerdc054bf2010-01-05 06:09:35 +000083 } else {
Jay Foad583abbc2010-12-07 08:25:19 +000084 LHSExt = LHSExt.zext(W * 2);
85 RHSExt = RHSExt.zext(W * 2);
Chris Lattnerdc054bf2010-01-05 06:09:35 +000086 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000087
Chris Lattnerdc054bf2010-01-05 06:09:35 +000088 APInt MulExt = LHSExt * RHSExt;
Jim Grosbachbdbd7342013-04-05 21:20:12 +000089
Chris Lattnerdc054bf2010-01-05 06:09:35 +000090 if (!sign)
91 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
Jim Grosbachbdbd7342013-04-05 21:20:12 +000092
Chris Lattnerdc054bf2010-01-05 06:09:35 +000093 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
94 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
95 return MulExt.slt(Min) || MulExt.sgt(Max);
96}
97
Rafael Espindola65281bf2013-05-31 14:27:15 +000098/// \brief A helper routine of InstCombiner::visitMul().
99///
100/// If C is a vector of known powers of 2, then this function returns
101/// a new vector obtained from C replacing each element with its logBase2.
102/// Return a null pointer otherwise.
103static Constant *getLogBase2Vector(ConstantDataVector *CV) {
104 const APInt *IVal;
105 SmallVector<Constant *, 4> Elts;
106
107 for (unsigned I = 0, E = CV->getNumElements(); I != E; ++I) {
108 Constant *Elt = CV->getElementAsConstant(I);
109 if (!match(Elt, m_APInt(IVal)) || !IVal->isPowerOf2())
110 return 0;
111 Elts.push_back(ConstantInt::get(Elt->getType(), IVal->logBase2()));
112 }
113
114 return ConstantVector::get(Elts);
115}
116
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000117Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +0000118 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000119 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
120
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000121 if (Value *V = SimplifyMulInst(Op0, Op1, TD))
122 return ReplaceInstUsesWith(I, V);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000123
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000124 if (Value *V = SimplifyUsingDistributiveLaws(I))
125 return ReplaceInstUsesWith(I, V);
126
Chris Lattner6b657ae2011-02-10 05:36:31 +0000127 if (match(Op1, m_AllOnes())) // X * -1 == 0 - X
128 return BinaryOperator::CreateNeg(Op0, I.getName());
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000129
Rafael Espindola65281bf2013-05-31 14:27:15 +0000130 // Also allow combining multiply instructions on vectors.
131 {
132 Value *NewOp;
133 Constant *C1, *C2;
134 const APInt *IVal;
135 if (match(&I, m_Mul(m_Shl(m_Value(NewOp), m_Constant(C2)),
136 m_Constant(C1))) &&
137 match(C1, m_APInt(IVal)))
138 // ((X << C1)*C2) == (X * (C2 << C1))
139 return BinaryOperator::CreateMul(NewOp, ConstantExpr::getShl(C1, C2));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000140
Rafael Espindola65281bf2013-05-31 14:27:15 +0000141 if (match(&I, m_Mul(m_Value(NewOp), m_Constant(C1)))) {
142 Constant *NewCst = 0;
143 if (match(C1, m_APInt(IVal)) && IVal->isPowerOf2())
144 // Replace X*(2^C) with X << C, where C is either a scalar or a splat.
145 NewCst = ConstantInt::get(NewOp->getType(), IVal->logBase2());
146 else if (ConstantDataVector *CV = dyn_cast<ConstantDataVector>(C1))
147 // Replace X*(2^C) with X << C, where C is a vector of known
148 // constant powers of 2.
149 NewCst = getLogBase2Vector(CV);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000150
Rafael Espindola65281bf2013-05-31 14:27:15 +0000151 if (NewCst) {
152 BinaryOperator *Shl = BinaryOperator::CreateShl(NewOp, NewCst);
153 if (I.hasNoSignedWrap()) Shl->setHasNoSignedWrap();
154 if (I.hasNoUnsignedWrap()) Shl->setHasNoUnsignedWrap();
155 return Shl;
156 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000157 }
Rafael Espindola65281bf2013-05-31 14:27:15 +0000158 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000159
Rafael Espindola65281bf2013-05-31 14:27:15 +0000160 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6b657ae2011-02-10 05:36:31 +0000161 // Canonicalize (X+C1)*CI -> X*CI+C1*CI.
162 { Value *X; ConstantInt *C1;
163 if (Op0->hasOneUse() &&
164 match(Op0, m_Add(m_Value(X), m_ConstantInt(C1)))) {
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000165 Value *Add = Builder->CreateMul(X, CI);
Chris Lattner6b657ae2011-02-10 05:36:31 +0000166 return BinaryOperator::CreateAdd(Add, Builder->CreateMul(C1, CI));
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000167 }
Chris Lattner6b657ae2011-02-10 05:36:31 +0000168 }
Stuart Hastings82843742011-05-30 20:00:33 +0000169
Stuart Hastings23804832011-06-01 16:42:47 +0000170 // (Y - X) * (-(2**n)) -> (X - Y) * (2**n), for positive nonzero n
171 // (Y + const) * (-(2**n)) -> (-constY) * (2**n), for positive nonzero n
172 // The "* (2**n)" thus becomes a potential shifting opportunity.
Stuart Hastings82843742011-05-30 20:00:33 +0000173 {
174 const APInt & Val = CI->getValue();
175 const APInt &PosVal = Val.abs();
176 if (Val.isNegative() && PosVal.isPowerOf2()) {
Stuart Hastings23804832011-06-01 16:42:47 +0000177 Value *X = 0, *Y = 0;
178 if (Op0->hasOneUse()) {
179 ConstantInt *C1;
180 Value *Sub = 0;
181 if (match(Op0, m_Sub(m_Value(Y), m_Value(X))))
182 Sub = Builder->CreateSub(X, Y, "suba");
183 else if (match(Op0, m_Add(m_Value(Y), m_ConstantInt(C1))))
184 Sub = Builder->CreateSub(Builder->CreateNeg(C1), Y, "subc");
185 if (Sub)
186 return
187 BinaryOperator::CreateMul(Sub,
188 ConstantInt::get(Y->getType(), PosVal));
Stuart Hastings82843742011-05-30 20:00:33 +0000189 }
190 }
191 }
Chris Lattner6b657ae2011-02-10 05:36:31 +0000192 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000193
Chris Lattner6b657ae2011-02-10 05:36:31 +0000194 // Simplify mul instructions with a constant RHS.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000195 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000196 // Try to fold constant mul into select arguments.
197 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
198 if (Instruction *R = FoldOpIntoSelect(I, SI))
199 return R;
200
201 if (isa<PHINode>(Op0))
202 if (Instruction *NV = FoldOpIntoPhi(I))
203 return NV;
204 }
205
206 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
207 if (Value *Op1v = dyn_castNegVal(Op1))
208 return BinaryOperator::CreateMul(Op0v, Op1v);
209
210 // (X / Y) * Y = X - (X % Y)
211 // (X / Y) * -Y = (X % Y) - X
212 {
213 Value *Op1C = Op1;
214 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
215 if (!BO ||
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000216 (BO->getOpcode() != Instruction::UDiv &&
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000217 BO->getOpcode() != Instruction::SDiv)) {
218 Op1C = Op0;
219 BO = dyn_cast<BinaryOperator>(Op1);
220 }
221 Value *Neg = dyn_castNegVal(Op1C);
222 if (BO && BO->hasOneUse() &&
223 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
224 (BO->getOpcode() == Instruction::UDiv ||
225 BO->getOpcode() == Instruction::SDiv)) {
226 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
227
Chris Lattner35315d02011-02-06 21:44:57 +0000228 // If the division is exact, X % Y is zero, so we end up with X or -X.
229 if (PossiblyExactOperator *SDiv = dyn_cast<PossiblyExactOperator>(BO))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000230 if (SDiv->isExact()) {
231 if (Op1BO == Op1C)
232 return ReplaceInstUsesWith(I, Op0BO);
233 return BinaryOperator::CreateNeg(Op0BO);
234 }
235
236 Value *Rem;
237 if (BO->getOpcode() == Instruction::UDiv)
238 Rem = Builder->CreateURem(Op0BO, Op1BO);
239 else
240 Rem = Builder->CreateSRem(Op0BO, Op1BO);
241 Rem->takeName(BO);
242
243 if (Op1BO == Op1C)
244 return BinaryOperator::CreateSub(Op0BO, Rem);
245 return BinaryOperator::CreateSub(Rem, Op0BO);
246 }
247 }
248
249 /// i1 mul -> i1 and.
Duncan Sands9dff9be2010-02-15 16:12:20 +0000250 if (I.getType()->isIntegerTy(1))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000251 return BinaryOperator::CreateAnd(Op0, Op1);
252
253 // X*(1 << Y) --> X << Y
254 // (1 << Y)*X --> X << Y
255 {
256 Value *Y;
257 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
258 return BinaryOperator::CreateShl(Op1, Y);
259 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
260 return BinaryOperator::CreateShl(Op0, Y);
261 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000262
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000263 // If one of the operands of the multiply is a cast from a boolean value, then
264 // we know the bool is either zero or one, so this is a 'masking' multiply.
265 // X * Y (where Y is 0 or 1) -> X & (0-Y)
Duncan Sands19d0b472010-02-16 11:11:14 +0000266 if (!I.getType()->isVectorTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000267 // -2 is "-1 << 1" so it is all bits set except the low one.
268 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000269
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000270 Value *BoolCast = 0, *OtherOp = 0;
271 if (MaskedValueIsZero(Op0, Negative2))
272 BoolCast = Op0, OtherOp = Op1;
273 else if (MaskedValueIsZero(Op1, Negative2))
274 BoolCast = Op1, OtherOp = Op0;
275
276 if (BoolCast) {
277 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000278 BoolCast);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000279 return BinaryOperator::CreateAnd(V, OtherOp);
280 }
281 }
282
283 return Changed ? &I : 0;
284}
285
Pedro Artigas993acd02012-11-30 22:07:05 +0000286//
287// Detect pattern:
288//
289// log2(Y*0.5)
290//
291// And check for corresponding fast math flags
292//
293
294static void detectLog2OfHalf(Value *&Op, Value *&Y, IntrinsicInst *&Log2) {
Pedro Artigas00b83c92012-11-30 22:47:15 +0000295
296 if (!Op->hasOneUse())
297 return;
298
299 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op);
300 if (!II)
301 return;
302 if (II->getIntrinsicID() != Intrinsic::log2 || !II->hasUnsafeAlgebra())
303 return;
304 Log2 = II;
305
306 Value *OpLog2Of = II->getArgOperand(0);
307 if (!OpLog2Of->hasOneUse())
308 return;
309
310 Instruction *I = dyn_cast<Instruction>(OpLog2Of);
311 if (!I)
312 return;
313 if (I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
314 return;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000315
Pedro Artigas00b83c92012-11-30 22:47:15 +0000316 ConstantFP *CFP = dyn_cast<ConstantFP>(I->getOperand(0));
317 if (CFP && CFP->isExactlyValue(0.5)) {
318 Y = I->getOperand(1);
319 return;
320 }
321 CFP = dyn_cast<ConstantFP>(I->getOperand(1));
322 if (CFP && CFP->isExactlyValue(0.5))
323 Y = I->getOperand(0);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000324}
Pedro Artigas993acd02012-11-30 22:07:05 +0000325
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000326/// Helper function of InstCombiner::visitFMul(BinaryOperator(). It returns
327/// true iff the given value is FMul or FDiv with one and only one operand
328/// being a normal constant (i.e. not Zero/NaN/Infinity).
329static bool isFMulOrFDivWithConstant(Value *V) {
330 Instruction *I = dyn_cast<Instruction>(V);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000331 if (!I || (I->getOpcode() != Instruction::FMul &&
Shuxin Yang80138662013-01-07 22:41:28 +0000332 I->getOpcode() != Instruction::FDiv))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000333 return false;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000334
335 ConstantFP *C0 = dyn_cast<ConstantFP>(I->getOperand(0));
336 ConstantFP *C1 = dyn_cast<ConstantFP>(I->getOperand(1));
337
338 if (C0 && C1)
339 return false;
340
Michael Gottesman3cb77ab2013-06-19 21:23:18 +0000341 return (C0 && C0->getValueAPF().isFiniteNonZero()) ||
342 (C1 && C1->getValueAPF().isFiniteNonZero());
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000343}
344
345static bool isNormalFp(const ConstantFP *C) {
346 const APFloat &Flt = C->getValueAPF();
Michael Gottesmanc2af8d62013-06-26 23:17:31 +0000347 return Flt.isNormal();
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000348}
349
350/// foldFMulConst() is a helper routine of InstCombiner::visitFMul().
351/// The input \p FMulOrDiv is a FMul/FDiv with one and only one operand
352/// being a constant (i.e. isFMulOrFDivWithConstant(FMulOrDiv) == true).
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000353/// This function is to simplify "FMulOrDiv * C" and returns the
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000354/// resulting expression. Note that this function could return NULL in
355/// case the constants cannot be folded into a normal floating-point.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000356///
Shuxin Yang80138662013-01-07 22:41:28 +0000357Value *InstCombiner::foldFMulConst(Instruction *FMulOrDiv, ConstantFP *C,
358 Instruction *InsertBefore) {
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000359 assert(isFMulOrFDivWithConstant(FMulOrDiv) && "V is invalid");
360
361 Value *Opnd0 = FMulOrDiv->getOperand(0);
362 Value *Opnd1 = FMulOrDiv->getOperand(1);
363
364 ConstantFP *C0 = dyn_cast<ConstantFP>(Opnd0);
365 ConstantFP *C1 = dyn_cast<ConstantFP>(Opnd1);
366
367 BinaryOperator *R = 0;
368
369 // (X * C0) * C => X * (C0*C)
370 if (FMulOrDiv->getOpcode() == Instruction::FMul) {
371 Constant *F = ConstantExpr::getFMul(C1 ? C1 : C0, C);
372 if (isNormalFp(cast<ConstantFP>(F)))
373 R = BinaryOperator::CreateFMul(C1 ? Opnd0 : Opnd1, F);
374 } else {
375 if (C0) {
376 // (C0 / X) * C => (C0 * C) / X
Shuxin Yang3a7ca6e2013-09-19 21:13:46 +0000377 if (FMulOrDiv->hasOneUse()) {
378 // It would otherwise introduce another div.
379 ConstantFP *F = cast<ConstantFP>(ConstantExpr::getFMul(C0, C));
380 if (isNormalFp(F))
381 R = BinaryOperator::CreateFDiv(F, Opnd1);
382 }
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000383 } else {
384 // (X / C1) * C => X * (C/C1) if C/C1 is not a denormal
385 ConstantFP *F = cast<ConstantFP>(ConstantExpr::getFDiv(C, C1));
386 if (isNormalFp(F)) {
387 R = BinaryOperator::CreateFMul(Opnd0, F);
388 } else {
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000389 // (X / C1) * C => X / (C1/C)
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000390 Constant *F = ConstantExpr::getFDiv(C1, C);
391 if (isNormalFp(cast<ConstantFP>(F)))
392 R = BinaryOperator::CreateFDiv(Opnd0, F);
393 }
394 }
395 }
396
397 if (R) {
398 R->setHasUnsafeAlgebra(true);
399 InsertNewInstWith(R, *InsertBefore);
400 }
401
402 return R;
403}
404
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000405Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +0000406 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000407 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
408
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000409 if (isa<Constant>(Op0))
410 std::swap(Op0, Op1);
411
Michael Ilsemand5787be2012-12-12 00:28:32 +0000412 if (Value *V = SimplifyFMulInst(Op0, Op1, I.getFastMathFlags(), TD))
413 return ReplaceInstUsesWith(I, V);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000414
Shuxin Yange8227452013-01-15 21:09:32 +0000415 bool AllowReassociate = I.hasUnsafeAlgebra();
416
Michael Ilsemand5787be2012-12-12 00:28:32 +0000417 // Simplify mul instructions with a constant RHS.
418 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000419 // Try to fold constant mul into select arguments.
420 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
421 if (Instruction *R = FoldOpIntoSelect(I, SI))
422 return R;
423
424 if (isa<PHINode>(Op0))
425 if (Instruction *NV = FoldOpIntoPhi(I))
426 return NV;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000427
428 ConstantFP *C = dyn_cast<ConstantFP>(Op1);
Owen Andersonf74cfe02014-01-16 20:36:42 +0000429
430 // (fmul X, -1.0) --> (fsub -0.0, X)
431 if (C && C->isExactlyValue(-1.0)) {
432 Instruction *RI = BinaryOperator::CreateFSub(
433 ConstantFP::getNegativeZero(C->getType()),
434 Op0);
435 RI->copyFastMathFlags(&I);
436 return RI;
437 }
438
Michael Gottesman3cb77ab2013-06-19 21:23:18 +0000439 if (C && AllowReassociate && C->getValueAPF().isFiniteNonZero()) {
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000440 // Let MDC denote an expression in one of these forms:
441 // X * C, C/X, X/C, where C is a constant.
442 //
443 // Try to simplify "MDC * Constant"
444 if (isFMulOrFDivWithConstant(Op0)) {
445 Value *V = foldFMulConst(cast<Instruction>(Op0), C, &I);
446 if (V)
447 return ReplaceInstUsesWith(I, V);
448 }
449
Quentin Colombete684a6d2013-02-28 21:12:40 +0000450 // (MDC +/- C1) * C => (MDC * C) +/- (C1 * C)
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000451 Instruction *FAddSub = dyn_cast<Instruction>(Op0);
452 if (FAddSub &&
453 (FAddSub->getOpcode() == Instruction::FAdd ||
454 FAddSub->getOpcode() == Instruction::FSub)) {
455 Value *Opnd0 = FAddSub->getOperand(0);
456 Value *Opnd1 = FAddSub->getOperand(1);
457 ConstantFP *C0 = dyn_cast<ConstantFP>(Opnd0);
458 ConstantFP *C1 = dyn_cast<ConstantFP>(Opnd1);
459 bool Swap = false;
460 if (C0) {
Shuxin Yang80138662013-01-07 22:41:28 +0000461 std::swap(C0, C1);
462 std::swap(Opnd0, Opnd1);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000463 Swap = true;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000464 }
465
Michael Gottesman3cb77ab2013-06-19 21:23:18 +0000466 if (C1 && C1->getValueAPF().isFiniteNonZero() &&
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000467 isFMulOrFDivWithConstant(Opnd0)) {
Quentin Colombete684a6d2013-02-28 21:12:40 +0000468 Value *M1 = ConstantExpr::getFMul(C1, C);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000469 Value *M0 = isNormalFp(cast<ConstantFP>(M1)) ?
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000470 foldFMulConst(cast<Instruction>(Opnd0), C, &I) :
471 0;
472 if (M0 && M1) {
473 if (Swap && FAddSub->getOpcode() == Instruction::FSub)
474 std::swap(M0, M1);
475
Benjamin Kramer67485762013-09-30 15:39:59 +0000476 Instruction *RI = (FAddSub->getOpcode() == Instruction::FAdd)
477 ? BinaryOperator::CreateFAdd(M0, M1)
478 : BinaryOperator::CreateFSub(M0, M1);
Shuxin Yange8227452013-01-15 21:09:32 +0000479 RI->copyFastMathFlags(&I);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000480 return RI;
481 }
482 }
483 }
484 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000485 }
486
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000487
Pedro Artigasd8795042012-11-30 19:09:41 +0000488 // Under unsafe algebra do:
489 // X * log2(0.5*Y) = X*log2(Y) - X
490 if (I.hasUnsafeAlgebra()) {
491 Value *OpX = NULL;
492 Value *OpY = NULL;
493 IntrinsicInst *Log2;
Pedro Artigas993acd02012-11-30 22:07:05 +0000494 detectLog2OfHalf(Op0, OpY, Log2);
495 if (OpY) {
496 OpX = Op1;
497 } else {
498 detectLog2OfHalf(Op1, OpY, Log2);
499 if (OpY) {
500 OpX = Op0;
Pedro Artigasd8795042012-11-30 19:09:41 +0000501 }
502 }
503 // if pattern detected emit alternate sequence
504 if (OpX && OpY) {
Benjamin Kramer67485762013-09-30 15:39:59 +0000505 BuilderTy::FastMathFlagGuard Guard(*Builder);
506 Builder->SetFastMathFlags(Log2->getFastMathFlags());
Pedro Artigasd8795042012-11-30 19:09:41 +0000507 Log2->setArgOperand(0, OpY);
508 Value *FMulVal = Builder->CreateFMul(OpX, Log2);
Benjamin Kramer67485762013-09-30 15:39:59 +0000509 Value *FSub = Builder->CreateFSub(FMulVal, OpX);
510 FSub->takeName(&I);
511 return ReplaceInstUsesWith(I, FSub);
Pedro Artigasd8795042012-11-30 19:09:41 +0000512 }
513 }
514
Shuxin Yange8227452013-01-15 21:09:32 +0000515 // Handle symmetric situation in a 2-iteration loop
516 Value *Opnd0 = Op0;
517 Value *Opnd1 = Op1;
518 for (int i = 0; i < 2; i++) {
519 bool IgnoreZeroSign = I.hasNoSignedZeros();
520 if (BinaryOperator::isFNeg(Opnd0, IgnoreZeroSign)) {
Benjamin Kramer67485762013-09-30 15:39:59 +0000521 BuilderTy::FastMathFlagGuard Guard(*Builder);
522 Builder->SetFastMathFlags(I.getFastMathFlags());
523
Shuxin Yange8227452013-01-15 21:09:32 +0000524 Value *N0 = dyn_castFNegVal(Opnd0, IgnoreZeroSign);
525 Value *N1 = dyn_castFNegVal(Opnd1, IgnoreZeroSign);
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000526
Shuxin Yange8227452013-01-15 21:09:32 +0000527 // -X * -Y => X*Y
528 if (N1)
529 return BinaryOperator::CreateFMul(N0, N1);
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000530
Shuxin Yange8227452013-01-15 21:09:32 +0000531 if (Opnd0->hasOneUse()) {
532 // -X * Y => -(X*Y) (Promote negation as high as possible)
533 Value *T = Builder->CreateFMul(N0, Opnd1);
Benjamin Kramer67485762013-09-30 15:39:59 +0000534 Value *Neg = Builder->CreateFNeg(T);
535 Neg->takeName(&I);
536 return ReplaceInstUsesWith(I, Neg);
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000537 }
538 }
Shuxin Yange8227452013-01-15 21:09:32 +0000539
540 // (X*Y) * X => (X*X) * Y where Y != X
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000541 // The purpose is two-fold:
Shuxin Yange8227452013-01-15 21:09:32 +0000542 // 1) to form a power expression (of X).
543 // 2) potentially shorten the critical path: After transformation, the
544 // latency of the instruction Y is amortized by the expression of X*X,
545 // and therefore Y is in a "less critical" position compared to what it
546 // was before the transformation.
547 //
548 if (AllowReassociate) {
549 Value *Opnd0_0, *Opnd0_1;
550 if (Opnd0->hasOneUse() &&
551 match(Opnd0, m_FMul(m_Value(Opnd0_0), m_Value(Opnd0_1)))) {
552 Value *Y = 0;
553 if (Opnd0_0 == Opnd1 && Opnd0_1 != Opnd1)
554 Y = Opnd0_1;
555 else if (Opnd0_1 == Opnd1 && Opnd0_0 != Opnd1)
556 Y = Opnd0_0;
557
558 if (Y) {
Benjamin Kramer67485762013-09-30 15:39:59 +0000559 BuilderTy::FastMathFlagGuard Guard(*Builder);
560 Builder->SetFastMathFlags(I.getFastMathFlags());
561 Value *T = Builder->CreateFMul(Opnd1, Opnd1);
Shuxin Yange8227452013-01-15 21:09:32 +0000562
Benjamin Kramer67485762013-09-30 15:39:59 +0000563 Value *R = Builder->CreateFMul(T, Y);
564 R->takeName(&I);
565 return ReplaceInstUsesWith(I, R);
Shuxin Yange8227452013-01-15 21:09:32 +0000566 }
567 }
568 }
569
Stephen Lin03f9fbb2013-07-17 20:06:03 +0000570 // B * (uitofp i1 C) -> select C, B, 0
571 if (I.hasNoNaNs() && I.hasNoInfs() && I.hasNoSignedZeros()) {
572 Value *LHS = Op0, *RHS = Op1;
573 Value *B, *C;
Stephen Lin4ef13872013-07-26 17:55:00 +0000574 if (!match(RHS, m_UIToFP(m_Value(C))))
Stephen Lin03f9fbb2013-07-17 20:06:03 +0000575 std::swap(LHS, RHS);
576
Stephen Lin4ef13872013-07-26 17:55:00 +0000577 if (match(RHS, m_UIToFP(m_Value(C))) && C->getType()->isIntegerTy(1)) {
Stephen Lin03f9fbb2013-07-17 20:06:03 +0000578 B = LHS;
579 Value *Zero = ConstantFP::getNegativeZero(B->getType());
580 return SelectInst::Create(C, B, Zero);
581 }
582 }
583
584 // A * (1 - uitofp i1 C) -> select C, 0, A
585 if (I.hasNoNaNs() && I.hasNoInfs() && I.hasNoSignedZeros()) {
586 Value *LHS = Op0, *RHS = Op1;
587 Value *A, *C;
Stephen Lin4ef13872013-07-26 17:55:00 +0000588 if (!match(RHS, m_FSub(m_FPOne(), m_UIToFP(m_Value(C)))))
Stephen Lin03f9fbb2013-07-17 20:06:03 +0000589 std::swap(LHS, RHS);
590
Stephen Lin4ef13872013-07-26 17:55:00 +0000591 if (match(RHS, m_FSub(m_FPOne(), m_UIToFP(m_Value(C)))) &&
Stephen Lin03f9fbb2013-07-17 20:06:03 +0000592 C->getType()->isIntegerTy(1)) {
593 A = LHS;
594 Value *Zero = ConstantFP::getNegativeZero(A->getType());
595 return SelectInst::Create(C, Zero, A);
596 }
597 }
598
Shuxin Yange8227452013-01-15 21:09:32 +0000599 if (!isa<Constant>(Op1))
600 std::swap(Opnd0, Opnd1);
601 else
602 break;
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000603 }
604
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000605 return Changed ? &I : 0;
606}
607
608/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
609/// instruction.
610bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
611 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000612
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000613 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
614 int NonNullOperand = -1;
615 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
616 if (ST->isNullValue())
617 NonNullOperand = 2;
618 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
619 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
620 if (ST->isNullValue())
621 NonNullOperand = 1;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000622
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000623 if (NonNullOperand == -1)
624 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000625
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000626 Value *SelectCond = SI->getOperand(0);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000627
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000628 // Change the div/rem to use 'Y' instead of the select.
629 I.setOperand(1, SI->getOperand(NonNullOperand));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000630
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000631 // Okay, we know we replace the operand of the div/rem with 'Y' with no
632 // problem. However, the select, or the condition of the select may have
633 // multiple uses. Based on our knowledge that the operand must be non-zero,
634 // propagate the known value for the select into other uses of it, and
635 // propagate a known value of the condition into its other users.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000636
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000637 // If the select and condition only have a single use, don't bother with this,
638 // early exit.
639 if (SI->use_empty() && SelectCond->hasOneUse())
640 return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000641
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000642 // Scan the current block backward, looking for other uses of SI.
643 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000644
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000645 while (BBI != BBFront) {
646 --BBI;
647 // If we found a call to a function, we can't assume it will return, so
648 // information from below it cannot be propagated above it.
649 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
650 break;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000651
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000652 // Replace uses of the select or its condition with the known values.
653 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
654 I != E; ++I) {
655 if (*I == SI) {
656 *I = SI->getOperand(NonNullOperand);
657 Worklist.Add(BBI);
658 } else if (*I == SelectCond) {
Jakub Staszak96ff4d62013-06-06 23:34:59 +0000659 *I = Builder->getInt1(NonNullOperand == 1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000660 Worklist.Add(BBI);
661 }
662 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000663
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000664 // If we past the instruction, quit looking for it.
665 if (&*BBI == SI)
666 SI = 0;
667 if (&*BBI == SelectCond)
668 SelectCond = 0;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000669
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000670 // If we ran out of things to eliminate, break out of the loop.
671 if (SelectCond == 0 && SI == 0)
672 break;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000673
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000674 }
675 return true;
676}
677
678
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000679/// This function implements the transforms common to both integer division
680/// instructions (udiv and sdiv). It is called by the visitors to those integer
681/// division instructions.
682/// @brief Common integer divide transforms
683Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
684 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
685
Chris Lattner7c99f192011-05-22 18:18:41 +0000686 // The RHS is known non-zero.
687 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) {
688 I.setOperand(1, V);
689 return &I;
690 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000691
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000692 // Handle cases involving: [su]div X, (select Cond, Y, Z)
693 // This does not apply for fdiv.
694 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
695 return &I;
696
697 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000698 // (X / C1) / C2 -> X / (C1*C2)
699 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
700 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
701 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
702 if (MultiplyOverflows(RHS, LHSRHS,
703 I.getOpcode()==Instruction::SDiv))
704 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner6b657ae2011-02-10 05:36:31 +0000705 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
706 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000707 }
708
709 if (!RHS->isZero()) { // avoid X udiv 0
710 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
711 if (Instruction *R = FoldOpIntoSelect(I, SI))
712 return R;
713 if (isa<PHINode>(Op0))
714 if (Instruction *NV = FoldOpIntoPhi(I))
715 return NV;
716 }
717 }
718
Benjamin Kramer57b3df52011-04-30 18:16:00 +0000719 // See if we can fold away this div instruction.
720 if (SimplifyDemandedInstructionBits(I))
721 return &I;
722
Duncan Sands771e82a2011-01-28 16:51:11 +0000723 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
724 Value *X = 0, *Z = 0;
725 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) { // (X - Z) / Y; Y = Op1
726 bool isSigned = I.getOpcode() == Instruction::SDiv;
727 if ((isSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
728 (!isSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
729 return BinaryOperator::Create(I.getOpcode(), X, Op1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000730 }
731
732 return 0;
733}
734
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000735/// dyn_castZExtVal - Checks if V is a zext or constant that can
736/// be truncated to Ty without losing bits.
Chris Lattner229907c2011-07-18 04:54:35 +0000737static Value *dyn_castZExtVal(Value *V, Type *Ty) {
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000738 if (ZExtInst *Z = dyn_cast<ZExtInst>(V)) {
739 if (Z->getSrcTy() == Ty)
740 return Z->getOperand(0);
741 } else if (ConstantInt *C = dyn_cast<ConstantInt>(V)) {
742 if (C->getValue().getActiveBits() <= cast<IntegerType>(Ty)->getBitWidth())
743 return ConstantExpr::getTrunc(C, Ty);
744 }
745 return 0;
746}
747
David Majnemer37f8f442013-07-04 21:17:49 +0000748namespace {
749const unsigned MaxDepth = 6;
750typedef Instruction *(*FoldUDivOperandCb)(Value *Op0, Value *Op1,
751 const BinaryOperator &I,
752 InstCombiner &IC);
753
754/// \brief Used to maintain state for visitUDivOperand().
755struct UDivFoldAction {
756 FoldUDivOperandCb FoldAction; ///< Informs visitUDiv() how to fold this
757 ///< operand. This can be zero if this action
758 ///< joins two actions together.
759
760 Value *OperandToFold; ///< Which operand to fold.
761 union {
762 Instruction *FoldResult; ///< The instruction returned when FoldAction is
763 ///< invoked.
764
765 size_t SelectLHSIdx; ///< Stores the LHS action index if this action
766 ///< joins two actions together.
767 };
768
769 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand)
770 : FoldAction(FA), OperandToFold(InputOperand), FoldResult(0) {}
771 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand, size_t SLHS)
772 : FoldAction(FA), OperandToFold(InputOperand), SelectLHSIdx(SLHS) {}
773};
774}
775
776// X udiv 2^C -> X >> C
777static Instruction *foldUDivPow2Cst(Value *Op0, Value *Op1,
778 const BinaryOperator &I, InstCombiner &IC) {
779 const APInt &C = cast<Constant>(Op1)->getUniqueInteger();
780 BinaryOperator *LShr = BinaryOperator::CreateLShr(
781 Op0, ConstantInt::get(Op0->getType(), C.logBase2()));
782 if (I.isExact()) LShr->setIsExact();
783 return LShr;
784}
785
786// X udiv C, where C >= signbit
787static Instruction *foldUDivNegCst(Value *Op0, Value *Op1,
788 const BinaryOperator &I, InstCombiner &IC) {
789 Value *ICI = IC.Builder->CreateICmpULT(Op0, cast<ConstantInt>(Op1));
790
791 return SelectInst::Create(ICI, Constant::getNullValue(I.getType()),
792 ConstantInt::get(I.getType(), 1));
793}
794
795// X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
796static Instruction *foldUDivShl(Value *Op0, Value *Op1, const BinaryOperator &I,
797 InstCombiner &IC) {
798 Instruction *ShiftLeft = cast<Instruction>(Op1);
799 if (isa<ZExtInst>(ShiftLeft))
800 ShiftLeft = cast<Instruction>(ShiftLeft->getOperand(0));
801
802 const APInt &CI =
803 cast<Constant>(ShiftLeft->getOperand(0))->getUniqueInteger();
804 Value *N = ShiftLeft->getOperand(1);
805 if (CI != 1)
806 N = IC.Builder->CreateAdd(N, ConstantInt::get(N->getType(), CI.logBase2()));
807 if (ZExtInst *Z = dyn_cast<ZExtInst>(Op1))
808 N = IC.Builder->CreateZExt(N, Z->getDestTy());
809 BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, N);
810 if (I.isExact()) LShr->setIsExact();
811 return LShr;
812}
813
814// \brief Recursively visits the possible right hand operands of a udiv
815// instruction, seeing through select instructions, to determine if we can
816// replace the udiv with something simpler. If we find that an operand is not
817// able to simplify the udiv, we abort the entire transformation.
818static size_t visitUDivOperand(Value *Op0, Value *Op1, const BinaryOperator &I,
819 SmallVectorImpl<UDivFoldAction> &Actions,
820 unsigned Depth = 0) {
821 // Check to see if this is an unsigned division with an exact power of 2,
822 // if so, convert to a right shift.
823 if (match(Op1, m_Power2())) {
824 Actions.push_back(UDivFoldAction(foldUDivPow2Cst, Op1));
825 return Actions.size();
826 }
827
828 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1))
829 // X udiv C, where C >= signbit
830 if (C->getValue().isNegative()) {
831 Actions.push_back(UDivFoldAction(foldUDivNegCst, C));
832 return Actions.size();
833 }
834
835 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
836 if (match(Op1, m_Shl(m_Power2(), m_Value())) ||
837 match(Op1, m_ZExt(m_Shl(m_Power2(), m_Value())))) {
838 Actions.push_back(UDivFoldAction(foldUDivShl, Op1));
839 return Actions.size();
840 }
841
842 // The remaining tests are all recursive, so bail out if we hit the limit.
843 if (Depth++ == MaxDepth)
844 return 0;
845
846 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
847 if (size_t LHSIdx = visitUDivOperand(Op0, SI->getOperand(1), I, Actions))
848 if (visitUDivOperand(Op0, SI->getOperand(2), I, Actions)) {
849 Actions.push_back(UDivFoldAction((FoldUDivOperandCb)0, Op1, LHSIdx-1));
850 return Actions.size();
851 }
852
853 return 0;
854}
855
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000856Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
857 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
858
Duncan Sands771e82a2011-01-28 16:51:11 +0000859 if (Value *V = SimplifyUDivInst(Op0, Op1, TD))
860 return ReplaceInstUsesWith(I, V);
861
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000862 // Handle the integer div common cases
863 if (Instruction *Common = commonIDivTransforms(I))
864 return Common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000865
Benjamin Kramerd4a64712012-08-30 15:07:40 +0000866 // (x lshr C1) udiv C2 --> x udiv (C2 << C1)
Nadav Rotemd4577872012-08-28 12:23:22 +0000867 if (ConstantInt *C2 = dyn_cast<ConstantInt>(Op1)) {
Benjamin Kramer9c0a8072012-08-28 13:08:13 +0000868 Value *X;
869 ConstantInt *C1;
870 if (match(Op0, m_LShr(m_Value(X), m_ConstantInt(C1)))) {
Benjamin Kramer1e1a1de2012-08-28 13:59:23 +0000871 APInt NC = C2->getValue().shl(C1->getLimitedValue(C1->getBitWidth()-1));
Benjamin Kramer9c0a8072012-08-28 13:08:13 +0000872 return BinaryOperator::CreateUDiv(X, Builder->getInt(NC));
Nadav Rotem11935b22012-08-28 10:01:43 +0000873 }
874 }
875
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000876 // (zext A) udiv (zext B) --> zext (A udiv B)
877 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
878 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
879 return new ZExtInst(Builder->CreateUDiv(ZOp0->getOperand(0), ZOp1, "div",
880 I.isExact()),
881 I.getType());
882
David Majnemer37f8f442013-07-04 21:17:49 +0000883 // (LHS udiv (select (select (...)))) -> (LHS >> (select (select (...))))
884 SmallVector<UDivFoldAction, 6> UDivActions;
885 if (visitUDivOperand(Op0, Op1, I, UDivActions))
886 for (unsigned i = 0, e = UDivActions.size(); i != e; ++i) {
887 FoldUDivOperandCb Action = UDivActions[i].FoldAction;
888 Value *ActionOp1 = UDivActions[i].OperandToFold;
889 Instruction *Inst;
890 if (Action)
891 Inst = Action(Op0, ActionOp1, I, *this);
892 else {
893 // This action joins two actions together. The RHS of this action is
894 // simply the last action we processed, we saved the LHS action index in
895 // the joining action.
896 size_t SelectRHSIdx = i - 1;
897 Value *SelectRHS = UDivActions[SelectRHSIdx].FoldResult;
898 size_t SelectLHSIdx = UDivActions[i].SelectLHSIdx;
899 Value *SelectLHS = UDivActions[SelectLHSIdx].FoldResult;
900 Inst = SelectInst::Create(cast<SelectInst>(ActionOp1)->getCondition(),
901 SelectLHS, SelectRHS);
902 }
903
904 // If this is the last action to process, return it to the InstCombiner.
905 // Otherwise, we insert it before the UDiv and record it so that we may
906 // use it as part of a joining action (i.e., a SelectInst).
907 if (e - i != 1) {
908 Inst->insertBefore(&I);
909 UDivActions[i].FoldResult = Inst;
910 } else
911 return Inst;
912 }
913
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000914 return 0;
915}
916
917Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
918 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
919
Duncan Sands771e82a2011-01-28 16:51:11 +0000920 if (Value *V = SimplifySDivInst(Op0, Op1, TD))
921 return ReplaceInstUsesWith(I, V);
922
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000923 // Handle the integer div common cases
924 if (Instruction *Common = commonIDivTransforms(I))
925 return Common;
926
927 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
928 // sdiv X, -1 == -X
929 if (RHS->isAllOnesValue())
930 return BinaryOperator::CreateNeg(Op0);
931
Chris Lattner6b657ae2011-02-10 05:36:31 +0000932 // sdiv X, C --> ashr exact X, log2(C)
933 if (I.isExact() && RHS->getValue().isNonNegative() &&
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000934 RHS->getValue().isPowerOf2()) {
935 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
936 RHS->getValue().exactLogBase2());
Chris Lattner6b657ae2011-02-10 05:36:31 +0000937 return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000938 }
939
940 // -X/C --> X/-C provided the negation doesn't overflow.
941 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
Chris Lattner6b657ae2011-02-10 05:36:31 +0000942 if (match(Sub->getOperand(0), m_Zero()) && Sub->hasNoSignedWrap())
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000943 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
944 ConstantExpr::getNeg(RHS));
945 }
946
947 // If the sign bits of both operands are zero (i.e. we can prove they are
948 // unsigned inputs), turn this into a udiv.
Duncan Sands9dff9be2010-02-15 16:12:20 +0000949 if (I.getType()->isIntegerTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000950 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
951 if (MaskedValueIsZero(Op0, Mask)) {
952 if (MaskedValueIsZero(Op1, Mask)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000953 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000954 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
955 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000956
Chris Lattner6b657ae2011-02-10 05:36:31 +0000957 if (match(Op1, m_Shl(m_Power2(), m_Value()))) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000958 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
959 // Safe because the only negative value (1 << Y) can take on is
960 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
961 // the sign bit set.
962 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
963 }
964 }
965 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000966
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000967 return 0;
968}
969
Shuxin Yang320f52a2013-01-14 22:48:41 +0000970/// CvtFDivConstToReciprocal tries to convert X/C into X*1/C if C not a special
971/// FP value and:
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000972/// 1) 1/C is exact, or
Shuxin Yang320f52a2013-01-14 22:48:41 +0000973/// 2) reciprocal is allowed.
Sylvestre Ledru149e2812013-05-14 23:36:24 +0000974/// If the conversion was successful, the simplified expression "X * 1/C" is
Shuxin Yang320f52a2013-01-14 22:48:41 +0000975/// returned; otherwise, NULL is returned.
976///
977static Instruction *CvtFDivConstToReciprocal(Value *Dividend,
978 ConstantFP *Divisor,
979 bool AllowReciprocal) {
980 const APFloat &FpVal = Divisor->getValueAPF();
981 APFloat Reciprocal(FpVal.getSemantics());
982 bool Cvt = FpVal.getExactInverse(&Reciprocal);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000983
Michael Gottesman3cb77ab2013-06-19 21:23:18 +0000984 if (!Cvt && AllowReciprocal && FpVal.isFiniteNonZero()) {
Shuxin Yang320f52a2013-01-14 22:48:41 +0000985 Reciprocal = APFloat(FpVal.getSemantics(), 1.0f);
986 (void)Reciprocal.divide(FpVal, APFloat::rmNearestTiesToEven);
987 Cvt = !Reciprocal.isDenormal();
988 }
989
990 if (!Cvt)
991 return 0;
992
993 ConstantFP *R;
994 R = ConstantFP::get(Dividend->getType()->getContext(), Reciprocal);
995 return BinaryOperator::CreateFMul(Dividend, R);
996}
997
Frits van Bommel2a559512011-01-29 17:50:27 +0000998Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
999 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1000
1001 if (Value *V = SimplifyFDivInst(Op0, Op1, TD))
1002 return ReplaceInstUsesWith(I, V);
1003
Stephen Lina9b57f62013-07-20 07:13:13 +00001004 if (isa<Constant>(Op0))
1005 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1006 if (Instruction *R = FoldOpIntoSelect(I, SI))
1007 return R;
1008
Shuxin Yang320f52a2013-01-14 22:48:41 +00001009 bool AllowReassociate = I.hasUnsafeAlgebra();
1010 bool AllowReciprocal = I.hasAllowReciprocal();
Benjamin Kramer8564e0d2011-03-30 15:42:35 +00001011
Shuxin Yang320f52a2013-01-14 22:48:41 +00001012 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
Stephen Lina9b57f62013-07-20 07:13:13 +00001013 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1014 if (Instruction *R = FoldOpIntoSelect(I, SI))
1015 return R;
1016
Shuxin Yang320f52a2013-01-14 22:48:41 +00001017 if (AllowReassociate) {
1018 ConstantFP *C1 = 0;
1019 ConstantFP *C2 = Op1C;
1020 Value *X;
1021 Instruction *Res = 0;
1022
1023 if (match(Op0, m_FMul(m_Value(X), m_ConstantFP(C1)))) {
1024 // (X*C1)/C2 => X * (C1/C2)
1025 //
1026 Constant *C = ConstantExpr::getFDiv(C1, C2);
1027 const APFloat &F = cast<ConstantFP>(C)->getValueAPF();
Michael Gottesmanc2af8d62013-06-26 23:17:31 +00001028 if (F.isNormal())
Shuxin Yang320f52a2013-01-14 22:48:41 +00001029 Res = BinaryOperator::CreateFMul(X, C);
1030 } else if (match(Op0, m_FDiv(m_Value(X), m_ConstantFP(C1)))) {
1031 // (X/C1)/C2 => X /(C2*C1) [=> X * 1/(C2*C1) if reciprocal is allowed]
1032 //
1033 Constant *C = ConstantExpr::getFMul(C1, C2);
1034 const APFloat &F = cast<ConstantFP>(C)->getValueAPF();
Michael Gottesmanc2af8d62013-06-26 23:17:31 +00001035 if (F.isNormal()) {
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001036 Res = CvtFDivConstToReciprocal(X, cast<ConstantFP>(C),
Shuxin Yang320f52a2013-01-14 22:48:41 +00001037 AllowReciprocal);
1038 if (!Res)
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001039 Res = BinaryOperator::CreateFDiv(X, C);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001040 }
1041 }
1042
1043 if (Res) {
1044 Res->setFastMathFlags(I.getFastMathFlags());
1045 return Res;
1046 }
1047 }
1048
1049 // X / C => X * 1/C
1050 if (Instruction *T = CvtFDivConstToReciprocal(Op0, Op1C, AllowReciprocal))
1051 return T;
1052
1053 return 0;
1054 }
1055
1056 if (AllowReassociate && isa<ConstantFP>(Op0)) {
1057 ConstantFP *C1 = cast<ConstantFP>(Op0), *C2;
1058 Constant *Fold = 0;
1059 Value *X;
1060 bool CreateDiv = true;
1061
1062 // C1 / (X*C2) => (C1/C2) / X
1063 if (match(Op1, m_FMul(m_Value(X), m_ConstantFP(C2))))
1064 Fold = ConstantExpr::getFDiv(C1, C2);
1065 else if (match(Op1, m_FDiv(m_Value(X), m_ConstantFP(C2)))) {
1066 // C1 / (X/C2) => (C1*C2) / X
1067 Fold = ConstantExpr::getFMul(C1, C2);
1068 } else if (match(Op1, m_FDiv(m_ConstantFP(C2), m_Value(X)))) {
1069 // C1 / (C2/X) => (C1/C2) * X
1070 Fold = ConstantExpr::getFDiv(C1, C2);
1071 CreateDiv = false;
1072 }
1073
1074 if (Fold) {
1075 const APFloat &FoldC = cast<ConstantFP>(Fold)->getValueAPF();
Michael Gottesmanc2af8d62013-06-26 23:17:31 +00001076 if (FoldC.isNormal()) {
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001077 Instruction *R = CreateDiv ?
Shuxin Yang320f52a2013-01-14 22:48:41 +00001078 BinaryOperator::CreateFDiv(Fold, X) :
1079 BinaryOperator::CreateFMul(X, Fold);
1080 R->setFastMathFlags(I.getFastMathFlags());
1081 return R;
1082 }
1083 }
1084 return 0;
1085 }
1086
1087 if (AllowReassociate) {
1088 Value *X, *Y;
1089 Value *NewInst = 0;
1090 Instruction *SimpR = 0;
1091
1092 if (Op0->hasOneUse() && match(Op0, m_FDiv(m_Value(X), m_Value(Y)))) {
1093 // (X/Y) / Z => X / (Y*Z)
1094 //
1095 if (!isa<ConstantFP>(Y) || !isa<ConstantFP>(Op1)) {
1096 NewInst = Builder->CreateFMul(Y, Op1);
1097 SimpR = BinaryOperator::CreateFDiv(X, NewInst);
1098 }
1099 } else if (Op1->hasOneUse() && match(Op1, m_FDiv(m_Value(X), m_Value(Y)))) {
1100 // Z / (X/Y) => Z*Y / X
1101 //
1102 if (!isa<ConstantFP>(Y) || !isa<ConstantFP>(Op0)) {
1103 NewInst = Builder->CreateFMul(Op0, Y);
1104 SimpR = BinaryOperator::CreateFDiv(NewInst, X);
1105 }
1106 }
1107
1108 if (NewInst) {
1109 if (Instruction *T = dyn_cast<Instruction>(NewInst))
1110 T->setDebugLoc(I.getDebugLoc());
1111 SimpR->setFastMathFlags(I.getFastMathFlags());
1112 return SimpR;
Benjamin Kramer8564e0d2011-03-30 15:42:35 +00001113 }
1114 }
1115
Frits van Bommel2a559512011-01-29 17:50:27 +00001116 return 0;
1117}
1118
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001119/// This function implements the transforms common to both integer remainder
1120/// instructions (urem and srem). It is called by the visitors to those integer
1121/// remainder instructions.
1122/// @brief Common integer remainder transforms
1123Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
1124 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1125
Chris Lattner7c99f192011-05-22 18:18:41 +00001126 // The RHS is known non-zero.
1127 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) {
1128 I.setOperand(1, V);
1129 return &I;
1130 }
1131
Duncan Sandsa3e36992011-05-02 16:27:02 +00001132 // Handle cases involving: rem X, (select Cond, Y, Z)
1133 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1134 return &I;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001135
Duncan Sands6b699f82011-05-02 18:41:29 +00001136 if (isa<ConstantInt>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001137 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1138 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1139 if (Instruction *R = FoldOpIntoSelect(I, SI))
1140 return R;
1141 } else if (isa<PHINode>(Op0I)) {
1142 if (Instruction *NV = FoldOpIntoPhi(I))
1143 return NV;
1144 }
1145
1146 // See if we can fold away this rem instruction.
1147 if (SimplifyDemandedInstructionBits(I))
1148 return &I;
1149 }
1150 }
1151
1152 return 0;
1153}
1154
1155Instruction *InstCombiner::visitURem(BinaryOperator &I) {
1156 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1157
Duncan Sandsa3e36992011-05-02 16:27:02 +00001158 if (Value *V = SimplifyURemInst(Op0, Op1, TD))
1159 return ReplaceInstUsesWith(I, V);
1160
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001161 if (Instruction *common = commonIRemTransforms(I))
1162 return common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001163
David Majnemer6c30f492013-05-12 00:07:05 +00001164 // (zext A) urem (zext B) --> zext (A urem B)
1165 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
1166 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
1167 return new ZExtInst(Builder->CreateURem(ZOp0->getOperand(0), ZOp1),
1168 I.getType());
1169
David Majnemer470b0772013-05-11 09:01:28 +00001170 // X urem Y -> X and Y-1, where Y is a power of 2,
1171 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/true)) {
Chris Lattner6b657ae2011-02-10 05:36:31 +00001172 Constant *N1 = Constant::getAllOnesValue(I.getType());
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001173 Value *Add = Builder->CreateAdd(Op1, N1);
Chris Lattner6b657ae2011-02-10 05:36:31 +00001174 return BinaryOperator::CreateAnd(Op0, Add);
1175 }
1176
Nick Lewycky7459be62013-07-13 01:16:47 +00001177 // 1 urem X -> zext(X != 1)
1178 if (match(Op0, m_One())) {
1179 Value *Cmp = Builder->CreateICmpNE(Op1, Op0);
1180 Value *Ext = Builder->CreateZExt(Cmp, I.getType());
1181 return ReplaceInstUsesWith(I, Ext);
1182 }
1183
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001184 return 0;
1185}
1186
1187Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
1188 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1189
Duncan Sandsa3e36992011-05-02 16:27:02 +00001190 if (Value *V = SimplifySRemInst(Op0, Op1, TD))
1191 return ReplaceInstUsesWith(I, V);
1192
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001193 // Handle the integer rem common cases
1194 if (Instruction *Common = commonIRemTransforms(I))
1195 return Common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001196
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001197 if (Value *RHSNeg = dyn_castNegVal(Op1))
1198 if (!isa<Constant>(RHSNeg) ||
1199 (isa<ConstantInt>(RHSNeg) &&
1200 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
1201 // X % -Y -> X % Y
1202 Worklist.AddValue(I.getOperand(1));
1203 I.setOperand(1, RHSNeg);
1204 return &I;
1205 }
1206
1207 // If the sign bits of both operands are zero (i.e. we can prove they are
1208 // unsigned inputs), turn this into a urem.
Duncan Sands9dff9be2010-02-15 16:12:20 +00001209 if (I.getType()->isIntegerTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001210 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
1211 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001212 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001213 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
1214 }
1215 }
1216
1217 // If it's a constant vector, flip any negative values positive.
Chris Lattner0256be92012-01-27 03:08:05 +00001218 if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
1219 Constant *C = cast<Constant>(Op1);
1220 unsigned VWidth = C->getType()->getVectorNumElements();
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001221
1222 bool hasNegative = false;
Chris Lattner0256be92012-01-27 03:08:05 +00001223 bool hasMissing = false;
1224 for (unsigned i = 0; i != VWidth; ++i) {
1225 Constant *Elt = C->getAggregateElement(i);
1226 if (Elt == 0) {
1227 hasMissing = true;
1228 break;
1229 }
1230
1231 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
Chris Lattnerb1a15122011-07-15 06:08:15 +00001232 if (RHS->isNegative())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001233 hasNegative = true;
Chris Lattner0256be92012-01-27 03:08:05 +00001234 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001235
Chris Lattner0256be92012-01-27 03:08:05 +00001236 if (hasNegative && !hasMissing) {
Chris Lattner47a86bd2012-01-25 06:02:56 +00001237 SmallVector<Constant *, 16> Elts(VWidth);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001238 for (unsigned i = 0; i != VWidth; ++i) {
Chris Lattner8213c8a2012-02-06 21:56:39 +00001239 Elts[i] = C->getAggregateElement(i); // Handle undef, etc.
Chris Lattner0256be92012-01-27 03:08:05 +00001240 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
Chris Lattnerb1a15122011-07-15 06:08:15 +00001241 if (RHS->isNegative())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001242 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001243 }
1244 }
1245
1246 Constant *NewRHSV = ConstantVector::get(Elts);
Chris Lattner0256be92012-01-27 03:08:05 +00001247 if (NewRHSV != C) { // Don't loop on -MININT
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001248 Worklist.AddValue(I.getOperand(1));
1249 I.setOperand(1, NewRHSV);
1250 return &I;
1251 }
1252 }
1253 }
1254
1255 return 0;
1256}
1257
1258Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Duncan Sandsa3e36992011-05-02 16:27:02 +00001259 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001260
Duncan Sandsa3e36992011-05-02 16:27:02 +00001261 if (Value *V = SimplifyFRemInst(Op0, Op1, TD))
1262 return ReplaceInstUsesWith(I, V);
1263
1264 // Handle cases involving: rem X, (select Cond, Y, Z)
1265 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1266 return &I;
1267
1268 return 0;
1269}