blob: 0ac0ca27acf60e548474d6663c4c895b9335fa61 [file] [log] [blame]
Chris Lattnerd12c27c2010-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 Sands82fdab32010-12-21 14:00:22 +000016#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000017#include "llvm/IR/IntrinsicInst.h"
Chris Lattnerd12c27c2010-01-05 06:09:35 +000018#include "llvm/Support/PatternMatch.h"
19using namespace llvm;
20using namespace PatternMatch;
21
Chris Lattner1add46d2011-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 Grosbach03fceff2013-04-05 21:20:12 +000031
Chris Lattner613f1a32011-05-23 00:32:19 +000032 bool MadeChange = false;
33
Chris Lattner1add46d2011-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 Lattner6083bb92011-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 Lattner1add46d2011-05-22 18:18:41 +000038 m_Value(B))) &&
39 // The "1" can be any value known to be a power of 2.
Rafael Espindoladbaa2372012-12-13 03:37:24 +000040 isKnownToBeAPowerOfTwo(PowerOf2)) {
Benjamin Kramera9390a42011-09-27 20:39:19 +000041 A = IC.Builder->CreateSub(A, B);
Chris Lattner6083bb92011-05-23 00:09:55 +000042 return IC.Builder->CreateShl(PowerOf2, A);
Chris Lattner1add46d2011-05-22 18:18:41 +000043 }
Jim Grosbach03fceff2013-04-05 21:20:12 +000044
Chris Lattner613f1a32011-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 Espindoladbaa2372012-12-13 03:37:24 +000048 if (I->isLogicalShift() && isKnownToBeAPowerOfTwo(I->getOperand(0))) {
Chris Lattner613f1a32011-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 Grosbach03fceff2013-04-05 21:20:12 +000055
Chris Lattner613f1a32011-05-23 00:32:19 +000056 if (I->getOpcode() == Instruction::LShr && !I->isExact()) {
57 I->setIsExact();
58 MadeChange = true;
59 }
Jim Grosbach03fceff2013-04-05 21:20:12 +000060
Chris Lattner613f1a32011-05-23 00:32:19 +000061 if (I->getOpcode() == Instruction::Shl && !I->hasNoUnsignedWrap()) {
62 I->setHasNoUnsignedWrap();
63 MadeChange = true;
64 }
65 }
66
Chris Lattner6c9b8d32011-05-22 18:26:48 +000067 // TODO: Lots more we could do here:
Chris Lattner6c9b8d32011-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 Grosbach03fceff2013-04-05 21:20:12 +000070
Chris Lattner613f1a32011-05-23 00:32:19 +000071 return MadeChange ? V : 0;
Chris Lattner1add46d2011-05-22 18:18:41 +000072}
73
74
Chris Lattnerd12c27c2010-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 Foad40f8f622010-12-07 08:25:19 +000081 LHSExt = LHSExt.sext(W * 2);
82 RHSExt = RHSExt.sext(W * 2);
Chris Lattnerd12c27c2010-01-05 06:09:35 +000083 } else {
Jay Foad40f8f622010-12-07 08:25:19 +000084 LHSExt = LHSExt.zext(W * 2);
85 RHSExt = RHSExt.zext(W * 2);
Chris Lattnerd12c27c2010-01-05 06:09:35 +000086 }
Jim Grosbach03fceff2013-04-05 21:20:12 +000087
Chris Lattnerd12c27c2010-01-05 06:09:35 +000088 APInt MulExt = LHSExt * RHSExt;
Jim Grosbach03fceff2013-04-05 21:20:12 +000089
Chris Lattnerd12c27c2010-01-05 06:09:35 +000090 if (!sign)
91 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
Jim Grosbach03fceff2013-04-05 21:20:12 +000092
Chris Lattnerd12c27c2010-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
98Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Duncan Sands096aa792010-11-13 15:10:37 +000099 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000100 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
101
Duncan Sands82fdab32010-12-21 14:00:22 +0000102 if (Value *V = SimplifyMulInst(Op0, Op1, TD))
103 return ReplaceInstUsesWith(I, V);
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000104
Duncan Sands37bf92b2010-12-22 13:36:08 +0000105 if (Value *V = SimplifyUsingDistributiveLaws(I))
106 return ReplaceInstUsesWith(I, V);
107
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000108 if (match(Op1, m_AllOnes())) // X * -1 == 0 - X
109 return BinaryOperator::CreateNeg(Op0, I.getName());
Jim Grosbach03fceff2013-04-05 21:20:12 +0000110
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000111 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Jim Grosbach03fceff2013-04-05 21:20:12 +0000112
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000113 // ((X << C1)*C2) == (X * (C2 << C1))
114 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
115 if (SI->getOpcode() == Instruction::Shl)
116 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
117 return BinaryOperator::CreateMul(SI->getOperand(0),
118 ConstantExpr::getShl(CI, ShOp));
Jim Grosbach03fceff2013-04-05 21:20:12 +0000119
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000120 const APInt &Val = CI->getValue();
121 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
122 Constant *NewCst = ConstantInt::get(Op0->getType(), Val.logBase2());
123 BinaryOperator *Shl = BinaryOperator::CreateShl(Op0, NewCst);
124 if (I.hasNoSignedWrap()) Shl->setHasNoSignedWrap();
125 if (I.hasNoUnsignedWrap()) Shl->setHasNoUnsignedWrap();
126 return Shl;
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000127 }
Jim Grosbach03fceff2013-04-05 21:20:12 +0000128
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000129 // Canonicalize (X+C1)*CI -> X*CI+C1*CI.
130 { Value *X; ConstantInt *C1;
131 if (Op0->hasOneUse() &&
132 match(Op0, m_Add(m_Value(X), m_ConstantInt(C1)))) {
Benjamin Kramera9390a42011-09-27 20:39:19 +0000133 Value *Add = Builder->CreateMul(X, CI);
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000134 return BinaryOperator::CreateAdd(Add, Builder->CreateMul(C1, CI));
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000135 }
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000136 }
Stuart Hastingsacbf1072011-05-30 20:00:33 +0000137
Stuart Hastingsf1002822011-06-01 16:42:47 +0000138 // (Y - X) * (-(2**n)) -> (X - Y) * (2**n), for positive nonzero n
139 // (Y + const) * (-(2**n)) -> (-constY) * (2**n), for positive nonzero n
140 // The "* (2**n)" thus becomes a potential shifting opportunity.
Stuart Hastingsacbf1072011-05-30 20:00:33 +0000141 {
142 const APInt & Val = CI->getValue();
143 const APInt &PosVal = Val.abs();
144 if (Val.isNegative() && PosVal.isPowerOf2()) {
Stuart Hastingsf1002822011-06-01 16:42:47 +0000145 Value *X = 0, *Y = 0;
146 if (Op0->hasOneUse()) {
147 ConstantInt *C1;
148 Value *Sub = 0;
149 if (match(Op0, m_Sub(m_Value(Y), m_Value(X))))
150 Sub = Builder->CreateSub(X, Y, "suba");
151 else if (match(Op0, m_Add(m_Value(Y), m_ConstantInt(C1))))
152 Sub = Builder->CreateSub(Builder->CreateNeg(C1), Y, "subc");
153 if (Sub)
154 return
155 BinaryOperator::CreateMul(Sub,
156 ConstantInt::get(Y->getType(), PosVal));
Stuart Hastingsacbf1072011-05-30 20:00:33 +0000157 }
158 }
159 }
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000160 }
Jim Grosbach03fceff2013-04-05 21:20:12 +0000161
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000162 // Simplify mul instructions with a constant RHS.
Jim Grosbach03fceff2013-04-05 21:20:12 +0000163 if (isa<Constant>(Op1)) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000164 // Try to fold constant mul into select arguments.
165 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
166 if (Instruction *R = FoldOpIntoSelect(I, SI))
167 return R;
168
169 if (isa<PHINode>(Op0))
170 if (Instruction *NV = FoldOpIntoPhi(I))
171 return NV;
172 }
173
174 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
175 if (Value *Op1v = dyn_castNegVal(Op1))
176 return BinaryOperator::CreateMul(Op0v, Op1v);
177
178 // (X / Y) * Y = X - (X % Y)
179 // (X / Y) * -Y = (X % Y) - X
180 {
181 Value *Op1C = Op1;
182 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
183 if (!BO ||
Jim Grosbach03fceff2013-04-05 21:20:12 +0000184 (BO->getOpcode() != Instruction::UDiv &&
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000185 BO->getOpcode() != Instruction::SDiv)) {
186 Op1C = Op0;
187 BO = dyn_cast<BinaryOperator>(Op1);
188 }
189 Value *Neg = dyn_castNegVal(Op1C);
190 if (BO && BO->hasOneUse() &&
191 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
192 (BO->getOpcode() == Instruction::UDiv ||
193 BO->getOpcode() == Instruction::SDiv)) {
194 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
195
Chris Lattner35bda892011-02-06 21:44:57 +0000196 // If the division is exact, X % Y is zero, so we end up with X or -X.
197 if (PossiblyExactOperator *SDiv = dyn_cast<PossiblyExactOperator>(BO))
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000198 if (SDiv->isExact()) {
199 if (Op1BO == Op1C)
200 return ReplaceInstUsesWith(I, Op0BO);
201 return BinaryOperator::CreateNeg(Op0BO);
202 }
203
204 Value *Rem;
205 if (BO->getOpcode() == Instruction::UDiv)
206 Rem = Builder->CreateURem(Op0BO, Op1BO);
207 else
208 Rem = Builder->CreateSRem(Op0BO, Op1BO);
209 Rem->takeName(BO);
210
211 if (Op1BO == Op1C)
212 return BinaryOperator::CreateSub(Op0BO, Rem);
213 return BinaryOperator::CreateSub(Rem, Op0BO);
214 }
215 }
216
217 /// i1 mul -> i1 and.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000218 if (I.getType()->isIntegerTy(1))
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000219 return BinaryOperator::CreateAnd(Op0, Op1);
220
221 // X*(1 << Y) --> X << Y
222 // (1 << Y)*X --> X << Y
223 {
224 Value *Y;
225 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
226 return BinaryOperator::CreateShl(Op1, Y);
227 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
228 return BinaryOperator::CreateShl(Op0, Y);
229 }
Jim Grosbach03fceff2013-04-05 21:20:12 +0000230
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000231 // If one of the operands of the multiply is a cast from a boolean value, then
232 // we know the bool is either zero or one, so this is a 'masking' multiply.
233 // X * Y (where Y is 0 or 1) -> X & (0-Y)
Duncan Sands1df98592010-02-16 11:11:14 +0000234 if (!I.getType()->isVectorTy()) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000235 // -2 is "-1 << 1" so it is all bits set except the low one.
236 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
Jim Grosbach03fceff2013-04-05 21:20:12 +0000237
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000238 Value *BoolCast = 0, *OtherOp = 0;
239 if (MaskedValueIsZero(Op0, Negative2))
240 BoolCast = Op0, OtherOp = Op1;
241 else if (MaskedValueIsZero(Op1, Negative2))
242 BoolCast = Op1, OtherOp = Op0;
243
244 if (BoolCast) {
245 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
Benjamin Kramera9390a42011-09-27 20:39:19 +0000246 BoolCast);
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000247 return BinaryOperator::CreateAnd(V, OtherOp);
248 }
249 }
250
251 return Changed ? &I : 0;
252}
253
Pedro Artigasc2a08d22012-11-30 22:07:05 +0000254//
255// Detect pattern:
256//
257// log2(Y*0.5)
258//
259// And check for corresponding fast math flags
260//
261
262static void detectLog2OfHalf(Value *&Op, Value *&Y, IntrinsicInst *&Log2) {
Pedro Artigasef2ef3e2012-11-30 22:47:15 +0000263
264 if (!Op->hasOneUse())
265 return;
266
267 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op);
268 if (!II)
269 return;
270 if (II->getIntrinsicID() != Intrinsic::log2 || !II->hasUnsafeAlgebra())
271 return;
272 Log2 = II;
273
274 Value *OpLog2Of = II->getArgOperand(0);
275 if (!OpLog2Of->hasOneUse())
276 return;
277
278 Instruction *I = dyn_cast<Instruction>(OpLog2Of);
279 if (!I)
280 return;
281 if (I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
282 return;
Jim Grosbach03fceff2013-04-05 21:20:12 +0000283
Pedro Artigasef2ef3e2012-11-30 22:47:15 +0000284 ConstantFP *CFP = dyn_cast<ConstantFP>(I->getOperand(0));
285 if (CFP && CFP->isExactlyValue(0.5)) {
286 Y = I->getOperand(1);
287 return;
288 }
289 CFP = dyn_cast<ConstantFP>(I->getOperand(1));
290 if (CFP && CFP->isExactlyValue(0.5))
291 Y = I->getOperand(0);
Jim Grosbach03fceff2013-04-05 21:20:12 +0000292}
Pedro Artigasc2a08d22012-11-30 22:07:05 +0000293
Shuxin Yangd3ae2862013-01-07 21:39:23 +0000294/// Helper function of InstCombiner::visitFMul(BinaryOperator(). It returns
295/// true iff the given value is FMul or FDiv with one and only one operand
296/// being a normal constant (i.e. not Zero/NaN/Infinity).
297static bool isFMulOrFDivWithConstant(Value *V) {
298 Instruction *I = dyn_cast<Instruction>(V);
Jim Grosbach03fceff2013-04-05 21:20:12 +0000299 if (!I || (I->getOpcode() != Instruction::FMul &&
Shuxin Yangf2797312013-01-07 22:41:28 +0000300 I->getOpcode() != Instruction::FDiv))
Shuxin Yangd3ae2862013-01-07 21:39:23 +0000301 return false;
Shuxin Yangd3ae2862013-01-07 21:39:23 +0000302
303 ConstantFP *C0 = dyn_cast<ConstantFP>(I->getOperand(0));
304 ConstantFP *C1 = dyn_cast<ConstantFP>(I->getOperand(1));
305
306 if (C0 && C1)
307 return false;
308
309 return (C0 && C0->getValueAPF().isNormal()) ||
310 (C1 && C1->getValueAPF().isNormal());
311}
312
313static bool isNormalFp(const ConstantFP *C) {
314 const APFloat &Flt = C->getValueAPF();
315 return Flt.isNormal() && !Flt.isDenormal();
316}
317
318/// foldFMulConst() is a helper routine of InstCombiner::visitFMul().
319/// The input \p FMulOrDiv is a FMul/FDiv with one and only one operand
320/// being a constant (i.e. isFMulOrFDivWithConstant(FMulOrDiv) == true).
Jim Grosbach03fceff2013-04-05 21:20:12 +0000321/// This function is to simplify "FMulOrDiv * C" and returns the
Shuxin Yangd3ae2862013-01-07 21:39:23 +0000322/// resulting expression. Note that this function could return NULL in
323/// case the constants cannot be folded into a normal floating-point.
Jim Grosbach03fceff2013-04-05 21:20:12 +0000324///
Shuxin Yangf2797312013-01-07 22:41:28 +0000325Value *InstCombiner::foldFMulConst(Instruction *FMulOrDiv, ConstantFP *C,
326 Instruction *InsertBefore) {
Shuxin Yangd3ae2862013-01-07 21:39:23 +0000327 assert(isFMulOrFDivWithConstant(FMulOrDiv) && "V is invalid");
328
329 Value *Opnd0 = FMulOrDiv->getOperand(0);
330 Value *Opnd1 = FMulOrDiv->getOperand(1);
331
332 ConstantFP *C0 = dyn_cast<ConstantFP>(Opnd0);
333 ConstantFP *C1 = dyn_cast<ConstantFP>(Opnd1);
334
335 BinaryOperator *R = 0;
336
337 // (X * C0) * C => X * (C0*C)
338 if (FMulOrDiv->getOpcode() == Instruction::FMul) {
339 Constant *F = ConstantExpr::getFMul(C1 ? C1 : C0, C);
340 if (isNormalFp(cast<ConstantFP>(F)))
341 R = BinaryOperator::CreateFMul(C1 ? Opnd0 : Opnd1, F);
342 } else {
343 if (C0) {
344 // (C0 / X) * C => (C0 * C) / X
345 ConstantFP *F = cast<ConstantFP>(ConstantExpr::getFMul(C0, C));
346 if (isNormalFp(F))
347 R = BinaryOperator::CreateFDiv(F, Opnd1);
348 } else {
349 // (X / C1) * C => X * (C/C1) if C/C1 is not a denormal
350 ConstantFP *F = cast<ConstantFP>(ConstantExpr::getFDiv(C, C1));
351 if (isNormalFp(F)) {
352 R = BinaryOperator::CreateFMul(Opnd0, F);
353 } else {
Jim Grosbach03fceff2013-04-05 21:20:12 +0000354 // (X / C1) * C => X / (C1/C)
Shuxin Yangd3ae2862013-01-07 21:39:23 +0000355 Constant *F = ConstantExpr::getFDiv(C1, C);
356 if (isNormalFp(cast<ConstantFP>(F)))
357 R = BinaryOperator::CreateFDiv(Opnd0, F);
358 }
359 }
360 }
361
362 if (R) {
363 R->setHasUnsafeAlgebra(true);
364 InsertNewInstWith(R, *InsertBefore);
365 }
366
367 return R;
368}
369
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000370Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
Duncan Sands096aa792010-11-13 15:10:37 +0000371 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000372 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
373
Shuxin Yangd3ae2862013-01-07 21:39:23 +0000374 if (isa<Constant>(Op0))
375 std::swap(Op0, Op1);
376
Michael Ilsemanc244f382012-12-12 00:28:32 +0000377 if (Value *V = SimplifyFMulInst(Op0, Op1, I.getFastMathFlags(), TD))
378 return ReplaceInstUsesWith(I, V);
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000379
Shuxin Yanga1444212013-01-15 21:09:32 +0000380 bool AllowReassociate = I.hasUnsafeAlgebra();
381
Michael Ilsemanc244f382012-12-12 00:28:32 +0000382 // Simplify mul instructions with a constant RHS.
383 if (isa<Constant>(Op1)) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000384 // Try to fold constant mul into select arguments.
385 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
386 if (Instruction *R = FoldOpIntoSelect(I, SI))
387 return R;
388
389 if (isa<PHINode>(Op0))
390 if (Instruction *NV = FoldOpIntoPhi(I))
391 return NV;
Shuxin Yangd3ae2862013-01-07 21:39:23 +0000392
393 ConstantFP *C = dyn_cast<ConstantFP>(Op1);
Shuxin Yanga1444212013-01-15 21:09:32 +0000394 if (C && AllowReassociate && C->getValueAPF().isNormal()) {
Shuxin Yangd3ae2862013-01-07 21:39:23 +0000395 // Let MDC denote an expression in one of these forms:
396 // X * C, C/X, X/C, where C is a constant.
397 //
398 // Try to simplify "MDC * Constant"
399 if (isFMulOrFDivWithConstant(Op0)) {
400 Value *V = foldFMulConst(cast<Instruction>(Op0), C, &I);
401 if (V)
402 return ReplaceInstUsesWith(I, V);
403 }
404
Quentin Colombetc5a4c252013-02-28 21:12:40 +0000405 // (MDC +/- C1) * C => (MDC * C) +/- (C1 * C)
Shuxin Yangd3ae2862013-01-07 21:39:23 +0000406 Instruction *FAddSub = dyn_cast<Instruction>(Op0);
407 if (FAddSub &&
408 (FAddSub->getOpcode() == Instruction::FAdd ||
409 FAddSub->getOpcode() == Instruction::FSub)) {
410 Value *Opnd0 = FAddSub->getOperand(0);
411 Value *Opnd1 = FAddSub->getOperand(1);
412 ConstantFP *C0 = dyn_cast<ConstantFP>(Opnd0);
413 ConstantFP *C1 = dyn_cast<ConstantFP>(Opnd1);
414 bool Swap = false;
415 if (C0) {
Shuxin Yangf2797312013-01-07 22:41:28 +0000416 std::swap(C0, C1);
417 std::swap(Opnd0, Opnd1);
Jim Grosbach03fceff2013-04-05 21:20:12 +0000418 Swap = true;
Shuxin Yangd3ae2862013-01-07 21:39:23 +0000419 }
420
421 if (C1 && C1->getValueAPF().isNormal() &&
422 isFMulOrFDivWithConstant(Opnd0)) {
Quentin Colombetc5a4c252013-02-28 21:12:40 +0000423 Value *M1 = ConstantExpr::getFMul(C1, C);
Jim Grosbach03fceff2013-04-05 21:20:12 +0000424 Value *M0 = isNormalFp(cast<ConstantFP>(M1)) ?
Shuxin Yangd3ae2862013-01-07 21:39:23 +0000425 foldFMulConst(cast<Instruction>(Opnd0), C, &I) :
426 0;
427 if (M0 && M1) {
428 if (Swap && FAddSub->getOpcode() == Instruction::FSub)
429 std::swap(M0, M1);
430
431 Value *R = (FAddSub->getOpcode() == Instruction::FAdd) ?
432 BinaryOperator::CreateFAdd(M0, M1) :
433 BinaryOperator::CreateFSub(M0, M1);
434 Instruction *RI = cast<Instruction>(R);
Shuxin Yanga1444212013-01-15 21:09:32 +0000435 RI->copyFastMathFlags(&I);
Shuxin Yangd3ae2862013-01-07 21:39:23 +0000436 return RI;
437 }
438 }
439 }
440 }
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000441 }
442
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000443
Pedro Artigas84030dc2012-11-30 19:09:41 +0000444 // Under unsafe algebra do:
445 // X * log2(0.5*Y) = X*log2(Y) - X
446 if (I.hasUnsafeAlgebra()) {
447 Value *OpX = NULL;
448 Value *OpY = NULL;
449 IntrinsicInst *Log2;
Pedro Artigasc2a08d22012-11-30 22:07:05 +0000450 detectLog2OfHalf(Op0, OpY, Log2);
451 if (OpY) {
452 OpX = Op1;
453 } else {
454 detectLog2OfHalf(Op1, OpY, Log2);
455 if (OpY) {
456 OpX = Op0;
Pedro Artigas84030dc2012-11-30 19:09:41 +0000457 }
458 }
459 // if pattern detected emit alternate sequence
460 if (OpX && OpY) {
461 Log2->setArgOperand(0, OpY);
462 Value *FMulVal = Builder->CreateFMul(OpX, Log2);
Pedro Artigasc2a08d22012-11-30 22:07:05 +0000463 Instruction *FMul = cast<Instruction>(FMulVal);
Pedro Artigas84030dc2012-11-30 19:09:41 +0000464 FMul->copyFastMathFlags(Log2);
465 Instruction *FSub = BinaryOperator::CreateFSub(FMulVal, OpX);
466 FSub->copyFastMathFlags(Log2);
467 return FSub;
468 }
469 }
470
Shuxin Yanga1444212013-01-15 21:09:32 +0000471 // Handle symmetric situation in a 2-iteration loop
472 Value *Opnd0 = Op0;
473 Value *Opnd1 = Op1;
474 for (int i = 0; i < 2; i++) {
475 bool IgnoreZeroSign = I.hasNoSignedZeros();
476 if (BinaryOperator::isFNeg(Opnd0, IgnoreZeroSign)) {
477 Value *N0 = dyn_castFNegVal(Opnd0, IgnoreZeroSign);
478 Value *N1 = dyn_castFNegVal(Opnd1, IgnoreZeroSign);
Shuxin Yanga5ed0312012-12-14 18:46:06 +0000479
Shuxin Yanga1444212013-01-15 21:09:32 +0000480 // -X * -Y => X*Y
481 if (N1)
482 return BinaryOperator::CreateFMul(N0, N1);
Shuxin Yanga5ed0312012-12-14 18:46:06 +0000483
Shuxin Yanga1444212013-01-15 21:09:32 +0000484 if (Opnd0->hasOneUse()) {
485 // -X * Y => -(X*Y) (Promote negation as high as possible)
486 Value *T = Builder->CreateFMul(N0, Opnd1);
487 cast<Instruction>(T)->setDebugLoc(I.getDebugLoc());
488 Instruction *Neg = BinaryOperator::CreateFNeg(T);
489 if (I.getFastMathFlags().any()) {
490 cast<Instruction>(T)->copyFastMathFlags(&I);
491 Neg->copyFastMathFlags(&I);
492 }
493 return Neg;
Shuxin Yanga5ed0312012-12-14 18:46:06 +0000494 }
495 }
Shuxin Yanga1444212013-01-15 21:09:32 +0000496
497 // (X*Y) * X => (X*X) * Y where Y != X
Jim Grosbach03fceff2013-04-05 21:20:12 +0000498 // The purpose is two-fold:
Shuxin Yanga1444212013-01-15 21:09:32 +0000499 // 1) to form a power expression (of X).
500 // 2) potentially shorten the critical path: After transformation, the
501 // latency of the instruction Y is amortized by the expression of X*X,
502 // and therefore Y is in a "less critical" position compared to what it
503 // was before the transformation.
504 //
505 if (AllowReassociate) {
506 Value *Opnd0_0, *Opnd0_1;
507 if (Opnd0->hasOneUse() &&
508 match(Opnd0, m_FMul(m_Value(Opnd0_0), m_Value(Opnd0_1)))) {
509 Value *Y = 0;
510 if (Opnd0_0 == Opnd1 && Opnd0_1 != Opnd1)
511 Y = Opnd0_1;
512 else if (Opnd0_1 == Opnd1 && Opnd0_0 != Opnd1)
513 Y = Opnd0_0;
514
515 if (Y) {
516 Instruction *T = cast<Instruction>(Builder->CreateFMul(Opnd1, Opnd1));
517 T->copyFastMathFlags(&I);
518 T->setDebugLoc(I.getDebugLoc());
519
520 Instruction *R = BinaryOperator::CreateFMul(T, Y);
521 R->copyFastMathFlags(&I);
522 return R;
523 }
524 }
525 }
526
Jean-Luc Dupratc5cf6e52013-05-06 16:55:50 +0000527 // B * (uitofp i1 C) -> select C, B, 0
528 if(I.hasNoNaNs() && I.hasNoInfs() && I.hasNoSignedZeros()) {
529 Value *LHS=Op0, *RHS=Op1;
530 Value *B, *C;
531 if (!match(RHS, m_UIToFp(m_Value(C))))
532 std::swap(LHS, RHS);
533
534 if (match(RHS, m_UIToFp(m_Value(C)))) {
535 B=LHS;
536 Value *Zero = ConstantFP::getNegativeZero(B->getType());
537 return SelectInst::Create(C, B, Zero);
538 }
539 }
540
541 // A * (1 - uitofp i1 C) -> select C, 0, A
542 if(I.hasNoNaNs() && I.hasNoInfs() && I.hasNoSignedZeros()) {
543 Value *LHS=Op0, *RHS=Op1;
544 Value *A, *C;
545 if (!match(RHS, m_FSub(m_FPOne(), m_UIToFp(m_Value(C)))))
546 std::swap(LHS, RHS);
547
548 if (match(RHS, m_FSub(m_FPOne(), m_UIToFp(m_Value(C))))) {
549 A=LHS;
550 Value *Zero = ConstantFP::getNegativeZero(A->getType());
551 return SelectInst::Create(C, Zero, A);
552 }
553 }
554
Shuxin Yanga1444212013-01-15 21:09:32 +0000555 if (!isa<Constant>(Op1))
556 std::swap(Opnd0, Opnd1);
557 else
558 break;
Shuxin Yanga5ed0312012-12-14 18:46:06 +0000559 }
560
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000561 return Changed ? &I : 0;
562}
563
564/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
565/// instruction.
566bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
567 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
Jim Grosbach03fceff2013-04-05 21:20:12 +0000568
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000569 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
570 int NonNullOperand = -1;
571 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
572 if (ST->isNullValue())
573 NonNullOperand = 2;
574 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
575 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
576 if (ST->isNullValue())
577 NonNullOperand = 1;
Jim Grosbach03fceff2013-04-05 21:20:12 +0000578
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000579 if (NonNullOperand == -1)
580 return false;
Jim Grosbach03fceff2013-04-05 21:20:12 +0000581
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000582 Value *SelectCond = SI->getOperand(0);
Jim Grosbach03fceff2013-04-05 21:20:12 +0000583
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000584 // Change the div/rem to use 'Y' instead of the select.
585 I.setOperand(1, SI->getOperand(NonNullOperand));
Jim Grosbach03fceff2013-04-05 21:20:12 +0000586
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000587 // Okay, we know we replace the operand of the div/rem with 'Y' with no
588 // problem. However, the select, or the condition of the select may have
589 // multiple uses. Based on our knowledge that the operand must be non-zero,
590 // propagate the known value for the select into other uses of it, and
591 // propagate a known value of the condition into its other users.
Jim Grosbach03fceff2013-04-05 21:20:12 +0000592
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000593 // If the select and condition only have a single use, don't bother with this,
594 // early exit.
595 if (SI->use_empty() && SelectCond->hasOneUse())
596 return true;
Jim Grosbach03fceff2013-04-05 21:20:12 +0000597
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000598 // Scan the current block backward, looking for other uses of SI.
599 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
Jim Grosbach03fceff2013-04-05 21:20:12 +0000600
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000601 while (BBI != BBFront) {
602 --BBI;
603 // If we found a call to a function, we can't assume it will return, so
604 // information from below it cannot be propagated above it.
605 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
606 break;
Jim Grosbach03fceff2013-04-05 21:20:12 +0000607
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000608 // Replace uses of the select or its condition with the known values.
609 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
610 I != E; ++I) {
611 if (*I == SI) {
612 *I = SI->getOperand(NonNullOperand);
613 Worklist.Add(BBI);
614 } else if (*I == SelectCond) {
615 *I = NonNullOperand == 1 ? ConstantInt::getTrue(BBI->getContext()) :
616 ConstantInt::getFalse(BBI->getContext());
617 Worklist.Add(BBI);
618 }
619 }
Jim Grosbach03fceff2013-04-05 21:20:12 +0000620
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000621 // If we past the instruction, quit looking for it.
622 if (&*BBI == SI)
623 SI = 0;
624 if (&*BBI == SelectCond)
625 SelectCond = 0;
Jim Grosbach03fceff2013-04-05 21:20:12 +0000626
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000627 // If we ran out of things to eliminate, break out of the loop.
628 if (SelectCond == 0 && SI == 0)
629 break;
Jim Grosbach03fceff2013-04-05 21:20:12 +0000630
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000631 }
632 return true;
633}
634
635
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000636/// This function implements the transforms common to both integer division
637/// instructions (udiv and sdiv). It is called by the visitors to those integer
638/// division instructions.
639/// @brief Common integer divide transforms
640Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
641 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
642
Chris Lattner1add46d2011-05-22 18:18:41 +0000643 // The RHS is known non-zero.
644 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) {
645 I.setOperand(1, V);
646 return &I;
647 }
Jim Grosbach03fceff2013-04-05 21:20:12 +0000648
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000649 // Handle cases involving: [su]div X, (select Cond, Y, Z)
650 // This does not apply for fdiv.
651 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
652 return &I;
653
654 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000655 // (X / C1) / C2 -> X / (C1*C2)
656 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
657 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
658 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
659 if (MultiplyOverflows(RHS, LHSRHS,
660 I.getOpcode()==Instruction::SDiv))
661 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000662 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
663 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000664 }
665
666 if (!RHS->isZero()) { // avoid X udiv 0
667 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
668 if (Instruction *R = FoldOpIntoSelect(I, SI))
669 return R;
670 if (isa<PHINode>(Op0))
671 if (Instruction *NV = FoldOpIntoPhi(I))
672 return NV;
673 }
674 }
675
Benjamin Kramer23b02cd2011-04-30 18:16:00 +0000676 // See if we can fold away this div instruction.
677 if (SimplifyDemandedInstructionBits(I))
678 return &I;
679
Duncan Sands593faa52011-01-28 16:51:11 +0000680 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
681 Value *X = 0, *Z = 0;
682 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) { // (X - Z) / Y; Y = Op1
683 bool isSigned = I.getOpcode() == Instruction::SDiv;
684 if ((isSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
685 (!isSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
686 return BinaryOperator::Create(I.getOpcode(), X, Op1);
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000687 }
688
689 return 0;
690}
691
Benjamin Kramer7d6eb5a2011-04-30 18:16:07 +0000692/// dyn_castZExtVal - Checks if V is a zext or constant that can
693/// be truncated to Ty without losing bits.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000694static Value *dyn_castZExtVal(Value *V, Type *Ty) {
Benjamin Kramer7d6eb5a2011-04-30 18:16:07 +0000695 if (ZExtInst *Z = dyn_cast<ZExtInst>(V)) {
696 if (Z->getSrcTy() == Ty)
697 return Z->getOperand(0);
698 } else if (ConstantInt *C = dyn_cast<ConstantInt>(V)) {
699 if (C->getValue().getActiveBits() <= cast<IntegerType>(Ty)->getBitWidth())
700 return ConstantExpr::getTrunc(C, Ty);
701 }
702 return 0;
703}
704
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000705Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
706 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
707
Duncan Sands593faa52011-01-28 16:51:11 +0000708 if (Value *V = SimplifyUDivInst(Op0, Op1, TD))
709 return ReplaceInstUsesWith(I, V);
710
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000711 // Handle the integer div common cases
712 if (Instruction *Common = commonIDivTransforms(I))
713 return Common;
Jim Grosbach03fceff2013-04-05 21:20:12 +0000714
715 {
Owen Anderson5b396202010-01-17 06:49:03 +0000716 // X udiv 2^C -> X >> C
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000717 // Check to see if this is an unsigned division with an exact power of 2,
718 // if so, convert to a right shift.
Pete Coopera29fc802011-11-07 23:04:49 +0000719 const APInt *C;
720 if (match(Op1, m_Power2(C))) {
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000721 BinaryOperator *LShr =
Jim Grosbach03fceff2013-04-05 21:20:12 +0000722 BinaryOperator::CreateLShr(Op0,
723 ConstantInt::get(Op0->getType(),
Pete Coopera29fc802011-11-07 23:04:49 +0000724 C->logBase2()));
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000725 if (I.isExact()) LShr->setIsExact();
726 return LShr;
727 }
Pete Coopera29fc802011-11-07 23:04:49 +0000728 }
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000729
Pete Coopera29fc802011-11-07 23:04:49 +0000730 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000731 // X udiv C, where C >= signbit
732 if (C->getValue().isNegative()) {
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000733 Value *IC = Builder->CreateICmpULT(Op0, C);
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000734 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
735 ConstantInt::get(I.getType(), 1));
736 }
737 }
738
Benjamin Kramerc81fe9c2012-08-30 15:07:40 +0000739 // (x lshr C1) udiv C2 --> x udiv (C2 << C1)
Nadav Rotema694e2a2012-08-28 12:23:22 +0000740 if (ConstantInt *C2 = dyn_cast<ConstantInt>(Op1)) {
Benjamin Krameraac7c652012-08-28 13:08:13 +0000741 Value *X;
742 ConstantInt *C1;
743 if (match(Op0, m_LShr(m_Value(X), m_ConstantInt(C1)))) {
Benjamin Kramer37dca632012-08-28 13:59:23 +0000744 APInt NC = C2->getValue().shl(C1->getLimitedValue(C1->getBitWidth()-1));
Benjamin Krameraac7c652012-08-28 13:08:13 +0000745 return BinaryOperator::CreateUDiv(X, Builder->getInt(NC));
Nadav Rotem9753f0b2012-08-28 10:01:43 +0000746 }
747 }
748
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000749 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000750 { const APInt *CI; Value *N;
Evan Cheng2a5422b2012-06-21 22:52:49 +0000751 if (match(Op1, m_Shl(m_Power2(CI), m_Value(N))) ||
752 match(Op1, m_ZExt(m_Shl(m_Power2(CI), m_Value(N))))) {
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000753 if (*CI != 1)
Benjamin Kramere5bd3cf2012-09-21 16:26:41 +0000754 N = Builder->CreateAdd(N,
755 ConstantInt::get(N->getType(), CI->logBase2()));
Evan Cheng2a5422b2012-06-21 22:52:49 +0000756 if (ZExtInst *Z = dyn_cast<ZExtInst>(Op1))
757 N = Builder->CreateZExt(N, Z->getDestTy());
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000758 if (I.isExact())
759 return BinaryOperator::CreateExactLShr(Op0, N);
760 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000761 }
762 }
Jim Grosbach03fceff2013-04-05 21:20:12 +0000763
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000764 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
765 // where C1&C2 are powers of two.
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000766 { Value *Cond; const APInt *C1, *C2;
767 if (match(Op1, m_Select(m_Value(Cond), m_Power2(C1), m_Power2(C2)))) {
768 // Construct the "on true" case of the select
769 Value *TSI = Builder->CreateLShr(Op0, C1->logBase2(), Op1->getName()+".t",
770 I.isExact());
Jim Grosbach03fceff2013-04-05 21:20:12 +0000771
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000772 // Construct the "on false" case of the select
773 Value *FSI = Builder->CreateLShr(Op0, C2->logBase2(), Op1->getName()+".f",
774 I.isExact());
Jim Grosbach03fceff2013-04-05 21:20:12 +0000775
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000776 // construct the select instruction and return it.
777 return SelectInst::Create(Cond, TSI, FSI);
778 }
779 }
Benjamin Kramer7d6eb5a2011-04-30 18:16:07 +0000780
781 // (zext A) udiv (zext B) --> zext (A udiv B)
782 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
783 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
784 return new ZExtInst(Builder->CreateUDiv(ZOp0->getOperand(0), ZOp1, "div",
785 I.isExact()),
786 I.getType());
787
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000788 return 0;
789}
790
791Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
792 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
793
Duncan Sands593faa52011-01-28 16:51:11 +0000794 if (Value *V = SimplifySDivInst(Op0, Op1, TD))
795 return ReplaceInstUsesWith(I, V);
796
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000797 // Handle the integer div common cases
798 if (Instruction *Common = commonIDivTransforms(I))
799 return Common;
800
801 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
802 // sdiv X, -1 == -X
803 if (RHS->isAllOnesValue())
804 return BinaryOperator::CreateNeg(Op0);
805
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000806 // sdiv X, C --> ashr exact X, log2(C)
807 if (I.isExact() && RHS->getValue().isNonNegative() &&
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000808 RHS->getValue().isPowerOf2()) {
809 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
810 RHS->getValue().exactLogBase2());
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000811 return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000812 }
813
814 // -X/C --> X/-C provided the negation doesn't overflow.
815 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000816 if (match(Sub->getOperand(0), m_Zero()) && Sub->hasNoSignedWrap())
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000817 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
818 ConstantExpr::getNeg(RHS));
819 }
820
821 // If the sign bits of both operands are zero (i.e. we can prove they are
822 // unsigned inputs), turn this into a udiv.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000823 if (I.getType()->isIntegerTy()) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000824 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
825 if (MaskedValueIsZero(Op0, Mask)) {
826 if (MaskedValueIsZero(Op1, Mask)) {
Sylvestre Ledru94c22712012-09-27 10:14:43 +0000827 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000828 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
829 }
Jim Grosbach03fceff2013-04-05 21:20:12 +0000830
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000831 if (match(Op1, m_Shl(m_Power2(), m_Value()))) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000832 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
833 // Safe because the only negative value (1 << Y) can take on is
834 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
835 // the sign bit set.
836 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
837 }
838 }
839 }
Jim Grosbach03fceff2013-04-05 21:20:12 +0000840
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000841 return 0;
842}
843
Shuxin Yang7d72cf82013-01-14 22:48:41 +0000844/// CvtFDivConstToReciprocal tries to convert X/C into X*1/C if C not a special
845/// FP value and:
Jim Grosbach03fceff2013-04-05 21:20:12 +0000846/// 1) 1/C is exact, or
Shuxin Yang7d72cf82013-01-14 22:48:41 +0000847/// 2) reciprocal is allowed.
848/// If the convertion was successful, the simplified expression "X * 1/C" is
849/// returned; otherwise, NULL is returned.
850///
851static Instruction *CvtFDivConstToReciprocal(Value *Dividend,
852 ConstantFP *Divisor,
853 bool AllowReciprocal) {
854 const APFloat &FpVal = Divisor->getValueAPF();
855 APFloat Reciprocal(FpVal.getSemantics());
856 bool Cvt = FpVal.getExactInverse(&Reciprocal);
Jim Grosbach03fceff2013-04-05 21:20:12 +0000857
Shuxin Yang7d72cf82013-01-14 22:48:41 +0000858 if (!Cvt && AllowReciprocal && FpVal.isNormal()) {
859 Reciprocal = APFloat(FpVal.getSemantics(), 1.0f);
860 (void)Reciprocal.divide(FpVal, APFloat::rmNearestTiesToEven);
861 Cvt = !Reciprocal.isDenormal();
862 }
863
864 if (!Cvt)
865 return 0;
866
867 ConstantFP *R;
868 R = ConstantFP::get(Dividend->getType()->getContext(), Reciprocal);
869 return BinaryOperator::CreateFMul(Dividend, R);
870}
871
Frits van Bommel31726c12011-01-29 17:50:27 +0000872Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
873 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
874
875 if (Value *V = SimplifyFDivInst(Op0, Op1, TD))
876 return ReplaceInstUsesWith(I, V);
877
Shuxin Yang7d72cf82013-01-14 22:48:41 +0000878 bool AllowReassociate = I.hasUnsafeAlgebra();
879 bool AllowReciprocal = I.hasAllowReciprocal();
Benjamin Kramer54673962011-03-30 15:42:35 +0000880
Shuxin Yang7d72cf82013-01-14 22:48:41 +0000881 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
882 if (AllowReassociate) {
883 ConstantFP *C1 = 0;
884 ConstantFP *C2 = Op1C;
885 Value *X;
886 Instruction *Res = 0;
887
888 if (match(Op0, m_FMul(m_Value(X), m_ConstantFP(C1)))) {
889 // (X*C1)/C2 => X * (C1/C2)
890 //
891 Constant *C = ConstantExpr::getFDiv(C1, C2);
892 const APFloat &F = cast<ConstantFP>(C)->getValueAPF();
893 if (F.isNormal() && !F.isDenormal())
894 Res = BinaryOperator::CreateFMul(X, C);
895 } else if (match(Op0, m_FDiv(m_Value(X), m_ConstantFP(C1)))) {
896 // (X/C1)/C2 => X /(C2*C1) [=> X * 1/(C2*C1) if reciprocal is allowed]
897 //
898 Constant *C = ConstantExpr::getFMul(C1, C2);
899 const APFloat &F = cast<ConstantFP>(C)->getValueAPF();
900 if (F.isNormal() && !F.isDenormal()) {
Jim Grosbach03fceff2013-04-05 21:20:12 +0000901 Res = CvtFDivConstToReciprocal(X, cast<ConstantFP>(C),
Shuxin Yang7d72cf82013-01-14 22:48:41 +0000902 AllowReciprocal);
903 if (!Res)
Jim Grosbach03fceff2013-04-05 21:20:12 +0000904 Res = BinaryOperator::CreateFDiv(X, C);
Shuxin Yang7d72cf82013-01-14 22:48:41 +0000905 }
906 }
907
908 if (Res) {
909 Res->setFastMathFlags(I.getFastMathFlags());
910 return Res;
911 }
912 }
913
914 // X / C => X * 1/C
915 if (Instruction *T = CvtFDivConstToReciprocal(Op0, Op1C, AllowReciprocal))
916 return T;
917
918 return 0;
919 }
920
921 if (AllowReassociate && isa<ConstantFP>(Op0)) {
922 ConstantFP *C1 = cast<ConstantFP>(Op0), *C2;
923 Constant *Fold = 0;
924 Value *X;
925 bool CreateDiv = true;
926
927 // C1 / (X*C2) => (C1/C2) / X
928 if (match(Op1, m_FMul(m_Value(X), m_ConstantFP(C2))))
929 Fold = ConstantExpr::getFDiv(C1, C2);
930 else if (match(Op1, m_FDiv(m_Value(X), m_ConstantFP(C2)))) {
931 // C1 / (X/C2) => (C1*C2) / X
932 Fold = ConstantExpr::getFMul(C1, C2);
933 } else if (match(Op1, m_FDiv(m_ConstantFP(C2), m_Value(X)))) {
934 // C1 / (C2/X) => (C1/C2) * X
935 Fold = ConstantExpr::getFDiv(C1, C2);
936 CreateDiv = false;
937 }
938
939 if (Fold) {
940 const APFloat &FoldC = cast<ConstantFP>(Fold)->getValueAPF();
941 if (FoldC.isNormal() && !FoldC.isDenormal()) {
Jim Grosbach03fceff2013-04-05 21:20:12 +0000942 Instruction *R = CreateDiv ?
Shuxin Yang7d72cf82013-01-14 22:48:41 +0000943 BinaryOperator::CreateFDiv(Fold, X) :
944 BinaryOperator::CreateFMul(X, Fold);
945 R->setFastMathFlags(I.getFastMathFlags());
946 return R;
947 }
948 }
949 return 0;
950 }
951
952 if (AllowReassociate) {
953 Value *X, *Y;
954 Value *NewInst = 0;
955 Instruction *SimpR = 0;
956
957 if (Op0->hasOneUse() && match(Op0, m_FDiv(m_Value(X), m_Value(Y)))) {
958 // (X/Y) / Z => X / (Y*Z)
959 //
960 if (!isa<ConstantFP>(Y) || !isa<ConstantFP>(Op1)) {
961 NewInst = Builder->CreateFMul(Y, Op1);
962 SimpR = BinaryOperator::CreateFDiv(X, NewInst);
963 }
964 } else if (Op1->hasOneUse() && match(Op1, m_FDiv(m_Value(X), m_Value(Y)))) {
965 // Z / (X/Y) => Z*Y / X
966 //
967 if (!isa<ConstantFP>(Y) || !isa<ConstantFP>(Op0)) {
968 NewInst = Builder->CreateFMul(Op0, Y);
969 SimpR = BinaryOperator::CreateFDiv(NewInst, X);
970 }
971 }
972
973 if (NewInst) {
974 if (Instruction *T = dyn_cast<Instruction>(NewInst))
975 T->setDebugLoc(I.getDebugLoc());
976 SimpR->setFastMathFlags(I.getFastMathFlags());
977 return SimpR;
Benjamin Kramer54673962011-03-30 15:42:35 +0000978 }
979 }
980
Frits van Bommel31726c12011-01-29 17:50:27 +0000981 return 0;
982}
983
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000984/// This function implements the transforms common to both integer remainder
985/// instructions (urem and srem). It is called by the visitors to those integer
986/// remainder instructions.
987/// @brief Common integer remainder transforms
988Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
989 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
990
Chris Lattner1add46d2011-05-22 18:18:41 +0000991 // The RHS is known non-zero.
992 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) {
993 I.setOperand(1, V);
994 return &I;
995 }
996
Duncan Sandsf24ed772011-05-02 16:27:02 +0000997 // Handle cases involving: rem X, (select Cond, Y, Z)
998 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
999 return &I;
Chris Lattnerd12c27c2010-01-05 06:09:35 +00001000
Duncan Sands00676a62011-05-02 18:41:29 +00001001 if (isa<ConstantInt>(Op1)) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +00001002 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1003 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1004 if (Instruction *R = FoldOpIntoSelect(I, SI))
1005 return R;
1006 } else if (isa<PHINode>(Op0I)) {
1007 if (Instruction *NV = FoldOpIntoPhi(I))
1008 return NV;
1009 }
1010
1011 // See if we can fold away this rem instruction.
1012 if (SimplifyDemandedInstructionBits(I))
1013 return &I;
1014 }
1015 }
1016
1017 return 0;
1018}
1019
1020Instruction *InstCombiner::visitURem(BinaryOperator &I) {
1021 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1022
Duncan Sandsf24ed772011-05-02 16:27:02 +00001023 if (Value *V = SimplifyURemInst(Op0, Op1, TD))
1024 return ReplaceInstUsesWith(I, V);
1025
Chris Lattnerd12c27c2010-01-05 06:09:35 +00001026 if (Instruction *common = commonIRemTransforms(I))
1027 return common;
Jim Grosbach03fceff2013-04-05 21:20:12 +00001028
Chris Lattner7a6aa1a2011-02-10 05:36:31 +00001029 // X urem C^2 -> X and C-1
1030 { const APInt *C;
1031 if (match(Op1, m_Power2(C)))
1032 return BinaryOperator::CreateAnd(Op0,
1033 ConstantInt::get(I.getType(), *C-1));
Chris Lattnerd12c27c2010-01-05 06:09:35 +00001034 }
1035
Jim Grosbach03fceff2013-04-05 21:20:12 +00001036 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
Chris Lattner7a6aa1a2011-02-10 05:36:31 +00001037 if (match(Op1, m_Shl(m_Power2(), m_Value()))) {
1038 Constant *N1 = Constant::getAllOnesValue(I.getType());
Benjamin Kramera9390a42011-09-27 20:39:19 +00001039 Value *Add = Builder->CreateAdd(Op1, N1);
Chris Lattner7a6aa1a2011-02-10 05:36:31 +00001040 return BinaryOperator::CreateAnd(Op0, Add);
1041 }
1042
1043 // urem X, (select Cond, 2^C1, 2^C2) -->
1044 // select Cond, (and X, C1-1), (and X, C2-1)
1045 // when C1&C2 are powers of two.
1046 { Value *Cond; const APInt *C1, *C2;
1047 if (match(Op1, m_Select(m_Value(Cond), m_Power2(C1), m_Power2(C2)))) {
1048 Value *TrueAnd = Builder->CreateAnd(Op0, *C1-1, Op1->getName()+".t");
1049 Value *FalseAnd = Builder->CreateAnd(Op0, *C2-1, Op1->getName()+".f");
1050 return SelectInst::Create(Cond, TrueAnd, FalseAnd);
Chris Lattnerd12c27c2010-01-05 06:09:35 +00001051 }
1052 }
Benjamin Kramer7d6eb5a2011-04-30 18:16:07 +00001053
1054 // (zext A) urem (zext B) --> zext (A urem B)
1055 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
1056 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
1057 return new ZExtInst(Builder->CreateURem(ZOp0->getOperand(0), ZOp1),
1058 I.getType());
1059
Chris Lattnerd12c27c2010-01-05 06:09:35 +00001060 return 0;
1061}
1062
1063Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
1064 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1065
Duncan Sandsf24ed772011-05-02 16:27:02 +00001066 if (Value *V = SimplifySRemInst(Op0, Op1, TD))
1067 return ReplaceInstUsesWith(I, V);
1068
Chris Lattnerd12c27c2010-01-05 06:09:35 +00001069 // Handle the integer rem common cases
1070 if (Instruction *Common = commonIRemTransforms(I))
1071 return Common;
Jim Grosbach03fceff2013-04-05 21:20:12 +00001072
Chris Lattnerd12c27c2010-01-05 06:09:35 +00001073 if (Value *RHSNeg = dyn_castNegVal(Op1))
1074 if (!isa<Constant>(RHSNeg) ||
1075 (isa<ConstantInt>(RHSNeg) &&
1076 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
1077 // X % -Y -> X % Y
1078 Worklist.AddValue(I.getOperand(1));
1079 I.setOperand(1, RHSNeg);
1080 return &I;
1081 }
1082
1083 // If the sign bits of both operands are zero (i.e. we can prove they are
1084 // unsigned inputs), turn this into a urem.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001085 if (I.getType()->isIntegerTy()) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +00001086 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
1087 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Sylvestre Ledru94c22712012-09-27 10:14:43 +00001088 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Chris Lattnerd12c27c2010-01-05 06:09:35 +00001089 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
1090 }
1091 }
1092
1093 // If it's a constant vector, flip any negative values positive.
Chris Lattnera78fa8c2012-01-27 03:08:05 +00001094 if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
1095 Constant *C = cast<Constant>(Op1);
1096 unsigned VWidth = C->getType()->getVectorNumElements();
Chris Lattnerd12c27c2010-01-05 06:09:35 +00001097
1098 bool hasNegative = false;
Chris Lattnera78fa8c2012-01-27 03:08:05 +00001099 bool hasMissing = false;
1100 for (unsigned i = 0; i != VWidth; ++i) {
1101 Constant *Elt = C->getAggregateElement(i);
1102 if (Elt == 0) {
1103 hasMissing = true;
1104 break;
1105 }
1106
1107 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
Chris Lattnerc73b24d2011-07-15 06:08:15 +00001108 if (RHS->isNegative())
Chris Lattnerd12c27c2010-01-05 06:09:35 +00001109 hasNegative = true;
Chris Lattnera78fa8c2012-01-27 03:08:05 +00001110 }
Chris Lattnerd12c27c2010-01-05 06:09:35 +00001111
Chris Lattnera78fa8c2012-01-27 03:08:05 +00001112 if (hasNegative && !hasMissing) {
Chris Lattner4ca829e2012-01-25 06:02:56 +00001113 SmallVector<Constant *, 16> Elts(VWidth);
Chris Lattnerd12c27c2010-01-05 06:09:35 +00001114 for (unsigned i = 0; i != VWidth; ++i) {
Chris Lattner7302d802012-02-06 21:56:39 +00001115 Elts[i] = C->getAggregateElement(i); // Handle undef, etc.
Chris Lattnera78fa8c2012-01-27 03:08:05 +00001116 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
Chris Lattnerc73b24d2011-07-15 06:08:15 +00001117 if (RHS->isNegative())
Chris Lattnerd12c27c2010-01-05 06:09:35 +00001118 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Chris Lattnerd12c27c2010-01-05 06:09:35 +00001119 }
1120 }
1121
1122 Constant *NewRHSV = ConstantVector::get(Elts);
Chris Lattnera78fa8c2012-01-27 03:08:05 +00001123 if (NewRHSV != C) { // Don't loop on -MININT
Chris Lattnerd12c27c2010-01-05 06:09:35 +00001124 Worklist.AddValue(I.getOperand(1));
1125 I.setOperand(1, NewRHSV);
1126 return &I;
1127 }
1128 }
1129 }
1130
1131 return 0;
1132}
1133
1134Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Duncan Sandsf24ed772011-05-02 16:27:02 +00001135 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerd12c27c2010-01-05 06:09:35 +00001136
Duncan Sandsf24ed772011-05-02 16:27:02 +00001137 if (Value *V = SimplifyFRemInst(Op0, Op1, TD))
1138 return ReplaceInstUsesWith(I, V);
1139
1140 // Handle cases involving: rem X, (select Cond, Y, Z)
1141 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1142 return &I;
1143
1144 return 0;
1145}