blob: 38604830b8852b2ab0a1698c106143067ff098f6 [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
Chandler Carrutha9174582015-01-22 05:25:13 +000015#include "InstCombineInternal.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000016#include "llvm/ADT/APFloat.h"
17#include "llvm/ADT/APInt.h"
18#include "llvm/ADT/SmallVector.h"
Duncan Sandsd0eb6d32010-12-21 14:00:22 +000019#include "llvm/Analysis/InstructionSimplify.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000020#include "llvm/IR/BasicBlock.h"
21#include "llvm/IR/Constant.h"
22#include "llvm/IR/Constants.h"
23#include "llvm/IR/InstrTypes.h"
24#include "llvm/IR/Instruction.h"
25#include "llvm/IR/Instructions.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000027#include "llvm/IR/Intrinsics.h"
28#include "llvm/IR/Operator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000029#include "llvm/IR/PatternMatch.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000030#include "llvm/IR/Type.h"
31#include "llvm/IR/Value.h"
32#include "llvm/Support/Casting.h"
33#include "llvm/Support/ErrorHandling.h"
34#include "llvm/Support/KnownBits.h"
35#include "llvm/Transforms/InstCombine/InstCombineWorklist.h"
36#include <cassert>
37#include <cstddef>
38#include <cstdint>
39#include <utility>
40
Chris Lattnerdc054bf2010-01-05 06:09:35 +000041using namespace llvm;
42using namespace PatternMatch;
43
Chandler Carruth964daaa2014-04-22 02:55:47 +000044#define DEBUG_TYPE "instcombine"
45
Sanjay Patel6eccf482015-09-09 15:24:36 +000046/// The specific integer value is used in a context where it is known to be
47/// non-zero. If this allows us to simplify the computation, do so and return
48/// the new operand, otherwise return null.
Hal Finkel60db0582014-09-07 18:57:58 +000049static Value *simplifyValueKnownNonZero(Value *V, InstCombiner &IC,
Mehdi Aminia28d91d2015-03-10 02:37:25 +000050 Instruction &CxtI) {
Chris Lattner7c99f192011-05-22 18:18:41 +000051 // If V has multiple uses, then we would have to do more analysis to determine
52 // if this is safe. For example, the use could be in dynamically unreached
53 // code.
Craig Topperf40110f2014-04-25 05:29:35 +000054 if (!V->hasOneUse()) return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +000055
Chris Lattner388cb8a2011-05-23 00:32:19 +000056 bool MadeChange = false;
57
Chris Lattner7c99f192011-05-22 18:18:41 +000058 // ((1 << A) >>u B) --> (1 << (A-B))
59 // Because V cannot be zero, we know that B is less than A.
David Majnemerdad21032014-10-14 20:28:40 +000060 Value *A = nullptr, *B = nullptr, *One = nullptr;
61 if (match(V, m_LShr(m_OneUse(m_Shl(m_Value(One), m_Value(A))), m_Value(B))) &&
62 match(One, m_One())) {
Craig Topperbb4069e2017-07-07 23:16:26 +000063 A = IC.Builder.CreateSub(A, B);
64 return IC.Builder.CreateShl(One, A);
Chris Lattner7c99f192011-05-22 18:18:41 +000065 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000066
Chris Lattner388cb8a2011-05-23 00:32:19 +000067 // (PowerOfTwo >>u B) --> isExact since shifting out the result would make it
68 // inexact. Similarly for <<.
Sanjay Patela8ef4a52016-05-22 17:08:52 +000069 BinaryOperator *I = dyn_cast<BinaryOperator>(V);
70 if (I && I->isLogicalShift() &&
Craig Topperd4039f72017-05-25 21:51:12 +000071 IC.isKnownToBeAPowerOfTwo(I->getOperand(0), false, 0, &CxtI)) {
Sanjay Patela8ef4a52016-05-22 17:08:52 +000072 // We know that this is an exact/nuw shift and that the input is a
73 // non-zero context as well.
74 if (Value *V2 = simplifyValueKnownNonZero(I->getOperand(0), IC, CxtI)) {
75 I->setOperand(0, V2);
76 MadeChange = true;
Chris Lattner388cb8a2011-05-23 00:32:19 +000077 }
78
Sanjay Patela8ef4a52016-05-22 17:08:52 +000079 if (I->getOpcode() == Instruction::LShr && !I->isExact()) {
80 I->setIsExact();
81 MadeChange = true;
82 }
83
84 if (I->getOpcode() == Instruction::Shl && !I->hasNoUnsignedWrap()) {
85 I->setHasNoUnsignedWrap();
86 MadeChange = true;
87 }
88 }
89
Chris Lattner162dfc32011-05-22 18:26:48 +000090 // TODO: Lots more we could do here:
Chris Lattner162dfc32011-05-22 18:26:48 +000091 // If V is a phi node, we can call this on each of its operands.
92 // "select cond, X, 0" can simplify to "X".
Jim Grosbachbdbd7342013-04-05 21:20:12 +000093
Craig Topperf40110f2014-04-25 05:29:35 +000094 return MadeChange ? V : nullptr;
Chris Lattner7c99f192011-05-22 18:18:41 +000095}
96
Sanjay Patel6eccf482015-09-09 15:24:36 +000097/// True if the multiply can not be expressed in an int this size.
David Majnemer27adb122014-10-12 08:34:24 +000098static bool MultiplyOverflows(const APInt &C1, const APInt &C2, APInt &Product,
99 bool IsSigned) {
100 bool Overflow;
101 if (IsSigned)
102 Product = C1.smul_ov(C2, Overflow);
103 else
104 Product = C1.umul_ov(C2, Overflow);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000105
David Majnemer27adb122014-10-12 08:34:24 +0000106 return Overflow;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000107}
108
David Majnemerf9a095d2014-08-16 08:55:06 +0000109/// \brief True if C2 is a multiple of C1. Quotient contains C2/C1.
110static bool IsMultiple(const APInt &C1, const APInt &C2, APInt &Quotient,
111 bool IsSigned) {
112 assert(C1.getBitWidth() == C2.getBitWidth() &&
113 "Inconsistent width of constants!");
114
David Majnemer135ca402015-09-06 06:49:59 +0000115 // Bail if we will divide by zero.
116 if (C2.isMinValue())
117 return false;
118
119 // Bail if we would divide INT_MIN by -1.
120 if (IsSigned && C1.isMinSignedValue() && C2.isAllOnesValue())
121 return false;
122
David Majnemerf9a095d2014-08-16 08:55:06 +0000123 APInt Remainder(C1.getBitWidth(), /*Val=*/0ULL, IsSigned);
124 if (IsSigned)
125 APInt::sdivrem(C1, C2, Quotient, Remainder);
126 else
127 APInt::udivrem(C1, C2, Quotient, Remainder);
128
129 return Remainder.isMinValue();
130}
131
Rafael Espindola65281bf2013-05-31 14:27:15 +0000132/// \brief A helper routine of InstCombiner::visitMul().
133///
134/// If C is a vector of known powers of 2, then this function returns
135/// a new vector obtained from C replacing each element with its logBase2.
136/// Return a null pointer otherwise.
137static Constant *getLogBase2Vector(ConstantDataVector *CV) {
138 const APInt *IVal;
139 SmallVector<Constant *, 4> Elts;
140
141 for (unsigned I = 0, E = CV->getNumElements(); I != E; ++I) {
142 Constant *Elt = CV->getElementAsConstant(I);
143 if (!match(Elt, m_APInt(IVal)) || !IVal->isPowerOf2())
Craig Topperf40110f2014-04-25 05:29:35 +0000144 return nullptr;
Rafael Espindola65281bf2013-05-31 14:27:15 +0000145 Elts.push_back(ConstantInt::get(Elt->getType(), IVal->logBase2()));
146 }
147
148 return ConstantVector::get(Elts);
149}
150
David Majnemer54c2ca22014-12-26 09:10:14 +0000151/// \brief Return true if we can prove that:
152/// (mul LHS, RHS) === (mul nsw LHS, RHS)
Craig Topper2b1fc322017-05-22 06:25:31 +0000153bool InstCombiner::willNotOverflowSignedMul(const Value *LHS,
154 const Value *RHS,
155 const Instruction &CxtI) const {
David Majnemer54c2ca22014-12-26 09:10:14 +0000156 // Multiplying n * m significant bits yields a result of n + m significant
157 // bits. If the total number of significant bits does not exceed the
158 // result bit width (minus 1), there is no overflow.
159 // This means if we have enough leading sign bits in the operands
160 // we can guarantee that the result does not overflow.
161 // Ref: "Hacker's Delight" by Henry Warren
162 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
163
164 // Note that underestimating the number of sign bits gives a more
165 // conservative answer.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000166 unsigned SignBits =
167 ComputeNumSignBits(LHS, 0, &CxtI) + ComputeNumSignBits(RHS, 0, &CxtI);
David Majnemer54c2ca22014-12-26 09:10:14 +0000168
169 // First handle the easy case: if we have enough sign bits there's
170 // definitely no overflow.
171 if (SignBits > BitWidth + 1)
172 return true;
173
174 // There are two ambiguous cases where there can be no overflow:
175 // SignBits == BitWidth + 1 and
176 // SignBits == BitWidth
177 // The second case is difficult to check, therefore we only handle the
178 // first case.
179 if (SignBits == BitWidth + 1) {
180 // It overflows only when both arguments are negative and the true
181 // product is exactly the minimum negative number.
182 // E.g. mul i16 with 17 sign bits: 0xff00 * 0xff80 = 0x8000
183 // For simplicity we just check if at least one side is not negative.
Craig Topper1a36b7d2017-05-15 06:39:41 +0000184 KnownBits LHSKnown = computeKnownBits(LHS, /*Depth=*/0, &CxtI);
185 KnownBits RHSKnown = computeKnownBits(RHS, /*Depth=*/0, &CxtI);
186 if (LHSKnown.isNonNegative() || RHSKnown.isNonNegative())
David Majnemer54c2ca22014-12-26 09:10:14 +0000187 return true;
188 }
189 return false;
190}
191
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000192Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +0000193 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000194 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
195
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000196 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +0000197 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000198
Craig Toppera4205622017-06-09 03:21:29 +0000199 if (Value *V = SimplifyMulInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +0000200 return replaceInstUsesWith(I, V);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000201
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000202 if (Value *V = SimplifyUsingDistributiveLaws(I))
Sanjay Patel4b198802016-02-01 22:23:39 +0000203 return replaceInstUsesWith(I, V);
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000204
David Majnemer027bc802014-11-22 04:52:38 +0000205 // X * -1 == 0 - X
206 if (match(Op1, m_AllOnes())) {
207 BinaryOperator *BO = BinaryOperator::CreateNeg(Op0, I.getName());
208 if (I.hasNoSignedWrap())
209 BO->setHasNoSignedWrap();
210 return BO;
211 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000212
Rafael Espindola65281bf2013-05-31 14:27:15 +0000213 // Also allow combining multiply instructions on vectors.
214 {
215 Value *NewOp;
216 Constant *C1, *C2;
217 const APInt *IVal;
218 if (match(&I, m_Mul(m_Shl(m_Value(NewOp), m_Constant(C2)),
219 m_Constant(C1))) &&
David Majnemerfd4a6d22014-11-22 04:52:52 +0000220 match(C1, m_APInt(IVal))) {
221 // ((X << C2)*C1) == (X * (C1 << C2))
222 Constant *Shl = ConstantExpr::getShl(C1, C2);
223 BinaryOperator *Mul = cast<BinaryOperator>(I.getOperand(0));
224 BinaryOperator *BO = BinaryOperator::CreateMul(NewOp, Shl);
225 if (I.hasNoUnsignedWrap() && Mul->hasNoUnsignedWrap())
226 BO->setHasNoUnsignedWrap();
227 if (I.hasNoSignedWrap() && Mul->hasNoSignedWrap() &&
228 Shl->isNotMinSignedValue())
229 BO->setHasNoSignedWrap();
230 return BO;
231 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000232
Rafael Espindola65281bf2013-05-31 14:27:15 +0000233 if (match(&I, m_Mul(m_Value(NewOp), m_Constant(C1)))) {
Craig Topperf40110f2014-04-25 05:29:35 +0000234 Constant *NewCst = nullptr;
Rafael Espindola65281bf2013-05-31 14:27:15 +0000235 if (match(C1, m_APInt(IVal)) && IVal->isPowerOf2())
236 // Replace X*(2^C) with X << C, where C is either a scalar or a splat.
237 NewCst = ConstantInt::get(NewOp->getType(), IVal->logBase2());
238 else if (ConstantDataVector *CV = dyn_cast<ConstantDataVector>(C1))
239 // Replace X*(2^C) with X << C, where C is a vector of known
240 // constant powers of 2.
241 NewCst = getLogBase2Vector(CV);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000242
Rafael Espindola65281bf2013-05-31 14:27:15 +0000243 if (NewCst) {
David Majnemer45951a62015-04-18 04:41:30 +0000244 unsigned Width = NewCst->getType()->getPrimitiveSizeInBits();
Rafael Espindola65281bf2013-05-31 14:27:15 +0000245 BinaryOperator *Shl = BinaryOperator::CreateShl(NewOp, NewCst);
Tilmann Scheller2bc5cb62014-10-07 10:19:34 +0000246
Tilmann Scheller2bc5cb62014-10-07 10:19:34 +0000247 if (I.hasNoUnsignedWrap())
248 Shl->setHasNoUnsignedWrap();
David Majnemer45951a62015-04-18 04:41:30 +0000249 if (I.hasNoSignedWrap()) {
Craig Topper5fe01972017-06-27 19:57:53 +0000250 const APInt *V;
251 if (match(NewCst, m_APInt(V)) && *V != Width - 1)
David Majnemer45951a62015-04-18 04:41:30 +0000252 Shl->setHasNoSignedWrap();
253 }
Tilmann Scheller2bc5cb62014-10-07 10:19:34 +0000254
Rafael Espindola65281bf2013-05-31 14:27:15 +0000255 return Shl;
256 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000257 }
Rafael Espindola65281bf2013-05-31 14:27:15 +0000258 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000259
Rafael Espindola65281bf2013-05-31 14:27:15 +0000260 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Stuart Hastings23804832011-06-01 16:42:47 +0000261 // (Y - X) * (-(2**n)) -> (X - Y) * (2**n), for positive nonzero n
262 // (Y + const) * (-(2**n)) -> (-constY) * (2**n), for positive nonzero n
263 // The "* (2**n)" thus becomes a potential shifting opportunity.
Stuart Hastings82843742011-05-30 20:00:33 +0000264 {
265 const APInt & Val = CI->getValue();
266 const APInt &PosVal = Val.abs();
267 if (Val.isNegative() && PosVal.isPowerOf2()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000268 Value *X = nullptr, *Y = nullptr;
Stuart Hastings23804832011-06-01 16:42:47 +0000269 if (Op0->hasOneUse()) {
270 ConstantInt *C1;
Craig Topperf40110f2014-04-25 05:29:35 +0000271 Value *Sub = nullptr;
Stuart Hastings23804832011-06-01 16:42:47 +0000272 if (match(Op0, m_Sub(m_Value(Y), m_Value(X))))
Craig Topperbb4069e2017-07-07 23:16:26 +0000273 Sub = Builder.CreateSub(X, Y, "suba");
Stuart Hastings23804832011-06-01 16:42:47 +0000274 else if (match(Op0, m_Add(m_Value(Y), m_ConstantInt(C1))))
Craig Topperbb4069e2017-07-07 23:16:26 +0000275 Sub = Builder.CreateSub(Builder.CreateNeg(C1), Y, "subc");
Stuart Hastings23804832011-06-01 16:42:47 +0000276 if (Sub)
277 return
278 BinaryOperator::CreateMul(Sub,
279 ConstantInt::get(Y->getType(), PosVal));
Stuart Hastings82843742011-05-30 20:00:33 +0000280 }
281 }
282 }
Chris Lattner6b657ae2011-02-10 05:36:31 +0000283 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000284
Chris Lattner6b657ae2011-02-10 05:36:31 +0000285 // Simplify mul instructions with a constant RHS.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000286 if (isa<Constant>(Op1)) {
Sanjay Pateldb0938f2017-01-10 23:49:07 +0000287 if (Instruction *FoldedMul = foldOpWithConstantIntoOperand(I))
288 return FoldedMul;
Benjamin Kramer72196f32014-01-19 15:24:22 +0000289
290 // Canonicalize (X+C1)*CI -> X*CI+C1*CI.
291 {
292 Value *X;
293 Constant *C1;
294 if (match(Op0, m_OneUse(m_Add(m_Value(X), m_Constant(C1))))) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000295 Value *Mul = Builder.CreateMul(C1, Op1);
David Majnemer6cf6c052014-06-19 07:14:33 +0000296 // Only go forward with the transform if C1*CI simplifies to a tidier
297 // constant.
298 if (!match(Mul, m_Mul(m_Value(), m_Value())))
Craig Topperbb4069e2017-07-07 23:16:26 +0000299 return BinaryOperator::CreateAdd(Builder.CreateMul(X, Op1), Mul);
Benjamin Kramer72196f32014-01-19 15:24:22 +0000300 }
301 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000302 }
303
David Majnemer8279a7502014-11-22 07:25:19 +0000304 if (Value *Op0v = dyn_castNegVal(Op0)) { // -X * -Y = X*Y
305 if (Value *Op1v = dyn_castNegVal(Op1)) {
306 BinaryOperator *BO = BinaryOperator::CreateMul(Op0v, Op1v);
307 if (I.hasNoSignedWrap() &&
308 match(Op0, m_NSWSub(m_Value(), m_Value())) &&
309 match(Op1, m_NSWSub(m_Value(), m_Value())))
310 BO->setHasNoSignedWrap();
311 return BO;
312 }
313 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000314
315 // (X / Y) * Y = X - (X % Y)
316 // (X / Y) * -Y = (X % Y) - X
317 {
Sanjay Patela0a56822017-03-14 17:27:27 +0000318 Value *Y = Op1;
319 BinaryOperator *Div = dyn_cast<BinaryOperator>(Op0);
320 if (!Div || (Div->getOpcode() != Instruction::UDiv &&
321 Div->getOpcode() != Instruction::SDiv)) {
322 Y = Op0;
323 Div = dyn_cast<BinaryOperator>(Op1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000324 }
Sanjay Patela0a56822017-03-14 17:27:27 +0000325 Value *Neg = dyn_castNegVal(Y);
326 if (Div && Div->hasOneUse() &&
327 (Div->getOperand(1) == Y || Div->getOperand(1) == Neg) &&
328 (Div->getOpcode() == Instruction::UDiv ||
329 Div->getOpcode() == Instruction::SDiv)) {
330 Value *X = Div->getOperand(0), *DivOp1 = Div->getOperand(1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000331
Chris Lattner35315d02011-02-06 21:44:57 +0000332 // If the division is exact, X % Y is zero, so we end up with X or -X.
Sanjay Patela0a56822017-03-14 17:27:27 +0000333 if (Div->isExact()) {
334 if (DivOp1 == Y)
335 return replaceInstUsesWith(I, X);
336 return BinaryOperator::CreateNeg(X);
337 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000338
Sanjay Patela0a56822017-03-14 17:27:27 +0000339 auto RemOpc = Div->getOpcode() == Instruction::UDiv ? Instruction::URem
340 : Instruction::SRem;
Craig Topperbb4069e2017-07-07 23:16:26 +0000341 Value *Rem = Builder.CreateBinOp(RemOpc, X, DivOp1);
Sanjay Patela0a56822017-03-14 17:27:27 +0000342 if (DivOp1 == Y)
343 return BinaryOperator::CreateSub(X, Rem);
344 return BinaryOperator::CreateSub(Rem, X);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000345 }
346 }
347
348 /// i1 mul -> i1 and.
Craig Topperfde47232017-07-09 07:04:03 +0000349 if (I.getType()->isIntOrIntVectorTy(1))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000350 return BinaryOperator::CreateAnd(Op0, Op1);
351
352 // X*(1 << Y) --> X << Y
353 // (1 << Y)*X --> X << Y
354 {
355 Value *Y;
David Majnemer546f8102014-11-22 08:57:02 +0000356 BinaryOperator *BO = nullptr;
357 bool ShlNSW = false;
358 if (match(Op0, m_Shl(m_One(), m_Value(Y)))) {
359 BO = BinaryOperator::CreateShl(Op1, Y);
David Majnemer087dc8b2015-01-04 07:36:02 +0000360 ShlNSW = cast<ShlOperator>(Op0)->hasNoSignedWrap();
David Majnemer8e6f6a92014-11-24 16:41:13 +0000361 } else if (match(Op1, m_Shl(m_One(), m_Value(Y)))) {
David Majnemer546f8102014-11-22 08:57:02 +0000362 BO = BinaryOperator::CreateShl(Op0, Y);
David Majnemer087dc8b2015-01-04 07:36:02 +0000363 ShlNSW = cast<ShlOperator>(Op1)->hasNoSignedWrap();
David Majnemer546f8102014-11-22 08:57:02 +0000364 }
365 if (BO) {
366 if (I.hasNoUnsignedWrap())
367 BO->setHasNoUnsignedWrap();
368 if (I.hasNoSignedWrap() && ShlNSW)
369 BO->setHasNoSignedWrap();
370 return BO;
371 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000372 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000373
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000374 // If one of the operands of the multiply is a cast from a boolean value, then
375 // we know the bool is either zero or one, so this is a 'masking' multiply.
376 // X * Y (where Y is 0 or 1) -> X & (0-Y)
Duncan Sands19d0b472010-02-16 11:11:14 +0000377 if (!I.getType()->isVectorTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000378 // -2 is "-1 << 1" so it is all bits set except the low one.
379 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000380
Craig Topperf40110f2014-04-25 05:29:35 +0000381 Value *BoolCast = nullptr, *OtherOp = nullptr;
Richard Trieu7a083812016-02-18 22:09:30 +0000382 if (MaskedValueIsZero(Op0, Negative2, 0, &I)) {
383 BoolCast = Op0;
384 OtherOp = Op1;
385 } else if (MaskedValueIsZero(Op1, Negative2, 0, &I)) {
386 BoolCast = Op1;
387 OtherOp = Op0;
388 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000389
390 if (BoolCast) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000391 Value *V = Builder.CreateSub(Constant::getNullValue(I.getType()),
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000392 BoolCast);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000393 return BinaryOperator::CreateAnd(V, OtherOp);
394 }
395 }
396
David Majnemera1cfd7c2016-12-30 00:28:58 +0000397 // Check for (mul (sext x), y), see if we can merge this into an
398 // integer mul followed by a sext.
399 if (SExtInst *Op0Conv = dyn_cast<SExtInst>(Op0)) {
400 // (mul (sext x), cst) --> (sext (mul x, cst'))
401 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
402 if (Op0Conv->hasOneUse()) {
403 Constant *CI =
404 ConstantExpr::getTrunc(Op1C, Op0Conv->getOperand(0)->getType());
405 if (ConstantExpr::getSExt(CI, I.getType()) == Op1C &&
Craig Topper2b1fc322017-05-22 06:25:31 +0000406 willNotOverflowSignedMul(Op0Conv->getOperand(0), CI, I)) {
David Majnemera1cfd7c2016-12-30 00:28:58 +0000407 // Insert the new, smaller mul.
408 Value *NewMul =
Craig Topperbb4069e2017-07-07 23:16:26 +0000409 Builder.CreateNSWMul(Op0Conv->getOperand(0), CI, "mulconv");
David Majnemera1cfd7c2016-12-30 00:28:58 +0000410 return new SExtInst(NewMul, I.getType());
411 }
412 }
413 }
414
415 // (mul (sext x), (sext y)) --> (sext (mul int x, y))
416 if (SExtInst *Op1Conv = dyn_cast<SExtInst>(Op1)) {
417 // Only do this if x/y have the same type, if at last one of them has a
418 // single use (so we don't increase the number of sexts), and if the
419 // integer mul will not overflow.
420 if (Op0Conv->getOperand(0)->getType() ==
421 Op1Conv->getOperand(0)->getType() &&
422 (Op0Conv->hasOneUse() || Op1Conv->hasOneUse()) &&
Craig Topper2b1fc322017-05-22 06:25:31 +0000423 willNotOverflowSignedMul(Op0Conv->getOperand(0),
David Majnemera1cfd7c2016-12-30 00:28:58 +0000424 Op1Conv->getOperand(0), I)) {
425 // Insert the new integer mul.
Craig Topperbb4069e2017-07-07 23:16:26 +0000426 Value *NewMul = Builder.CreateNSWMul(
David Majnemera1cfd7c2016-12-30 00:28:58 +0000427 Op0Conv->getOperand(0), Op1Conv->getOperand(0), "mulconv");
428 return new SExtInst(NewMul, I.getType());
429 }
430 }
431 }
432
433 // Check for (mul (zext x), y), see if we can merge this into an
434 // integer mul followed by a zext.
435 if (auto *Op0Conv = dyn_cast<ZExtInst>(Op0)) {
436 // (mul (zext x), cst) --> (zext (mul x, cst'))
437 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
438 if (Op0Conv->hasOneUse()) {
439 Constant *CI =
440 ConstantExpr::getTrunc(Op1C, Op0Conv->getOperand(0)->getType());
441 if (ConstantExpr::getZExt(CI, I.getType()) == Op1C &&
Craig Topperbb973722017-05-15 02:44:08 +0000442 willNotOverflowUnsignedMul(Op0Conv->getOperand(0), CI, I)) {
David Majnemera1cfd7c2016-12-30 00:28:58 +0000443 // Insert the new, smaller mul.
444 Value *NewMul =
Craig Topperbb4069e2017-07-07 23:16:26 +0000445 Builder.CreateNUWMul(Op0Conv->getOperand(0), CI, "mulconv");
David Majnemera1cfd7c2016-12-30 00:28:58 +0000446 return new ZExtInst(NewMul, I.getType());
447 }
448 }
449 }
450
451 // (mul (zext x), (zext y)) --> (zext (mul int x, y))
452 if (auto *Op1Conv = dyn_cast<ZExtInst>(Op1)) {
453 // Only do this if x/y have the same type, if at last one of them has a
454 // single use (so we don't increase the number of zexts), and if the
455 // integer mul will not overflow.
456 if (Op0Conv->getOperand(0)->getType() ==
457 Op1Conv->getOperand(0)->getType() &&
458 (Op0Conv->hasOneUse() || Op1Conv->hasOneUse()) &&
Craig Topperbb973722017-05-15 02:44:08 +0000459 willNotOverflowUnsignedMul(Op0Conv->getOperand(0),
460 Op1Conv->getOperand(0), I)) {
David Majnemera1cfd7c2016-12-30 00:28:58 +0000461 // Insert the new integer mul.
Craig Topperbb4069e2017-07-07 23:16:26 +0000462 Value *NewMul = Builder.CreateNUWMul(
David Majnemera1cfd7c2016-12-30 00:28:58 +0000463 Op0Conv->getOperand(0), Op1Conv->getOperand(0), "mulconv");
464 return new ZExtInst(NewMul, I.getType());
465 }
466 }
467 }
468
Craig Topper2b1fc322017-05-22 06:25:31 +0000469 if (!I.hasNoSignedWrap() && willNotOverflowSignedMul(Op0, Op1, I)) {
David Majnemer54c2ca22014-12-26 09:10:14 +0000470 Changed = true;
471 I.setHasNoSignedWrap(true);
472 }
473
Craig Topperbb973722017-05-15 02:44:08 +0000474 if (!I.hasNoUnsignedWrap() && willNotOverflowUnsignedMul(Op0, Op1, I)) {
David Majnemerb1296ec2014-12-26 09:50:35 +0000475 Changed = true;
476 I.setHasNoUnsignedWrap(true);
477 }
478
Craig Topperf40110f2014-04-25 05:29:35 +0000479 return Changed ? &I : nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000480}
481
Sanjay Patel17045f72014-10-14 00:33:23 +0000482/// Detect pattern log2(Y * 0.5) with corresponding fast math flags.
Pedro Artigas993acd02012-11-30 22:07:05 +0000483static void detectLog2OfHalf(Value *&Op, Value *&Y, IntrinsicInst *&Log2) {
Sanjay Patel17045f72014-10-14 00:33:23 +0000484 if (!Op->hasOneUse())
485 return;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000486
Sanjay Patel17045f72014-10-14 00:33:23 +0000487 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op);
488 if (!II)
489 return;
Sanjay Patel629c4112017-11-06 16:27:15 +0000490 if (II->getIntrinsicID() != Intrinsic::log2 || !II->isFast())
Sanjay Patel17045f72014-10-14 00:33:23 +0000491 return;
492 Log2 = II;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000493
Sanjay Patel17045f72014-10-14 00:33:23 +0000494 Value *OpLog2Of = II->getArgOperand(0);
495 if (!OpLog2Of->hasOneUse())
496 return;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000497
Sanjay Patel17045f72014-10-14 00:33:23 +0000498 Instruction *I = dyn_cast<Instruction>(OpLog2Of);
499 if (!I)
500 return;
Sanjay Patel629c4112017-11-06 16:27:15 +0000501
502 if (I->getOpcode() != Instruction::FMul || !I->isFast())
Sanjay Patel17045f72014-10-14 00:33:23 +0000503 return;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000504
Sanjay Patel17045f72014-10-14 00:33:23 +0000505 if (match(I->getOperand(0), m_SpecificFP(0.5)))
506 Y = I->getOperand(1);
507 else if (match(I->getOperand(1), m_SpecificFP(0.5)))
508 Y = I->getOperand(0);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000509}
Pedro Artigas993acd02012-11-30 22:07:05 +0000510
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000511static bool isFiniteNonZeroFp(Constant *C) {
512 if (C->getType()->isVectorTy()) {
513 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
514 ++I) {
Michael Kupersteinbcb26d62015-03-05 08:38:57 +0000515 ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(C->getAggregateElement(I));
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000516 if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
517 return false;
518 }
519 return true;
520 }
521
522 return isa<ConstantFP>(C) &&
523 cast<ConstantFP>(C)->getValueAPF().isFiniteNonZero();
524}
525
526static bool isNormalFp(Constant *C) {
527 if (C->getType()->isVectorTy()) {
528 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
529 ++I) {
Michael Kupersteinbcb26d62015-03-05 08:38:57 +0000530 ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(C->getAggregateElement(I));
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000531 if (!CFP || !CFP->getValueAPF().isNormal())
532 return false;
533 }
534 return true;
535 }
536
537 return isa<ConstantFP>(C) && cast<ConstantFP>(C)->getValueAPF().isNormal();
538}
539
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000540/// Helper function of InstCombiner::visitFMul(BinaryOperator(). It returns
541/// true iff the given value is FMul or FDiv with one and only one operand
542/// being a normal constant (i.e. not Zero/NaN/Infinity).
543static bool isFMulOrFDivWithConstant(Value *V) {
544 Instruction *I = dyn_cast<Instruction>(V);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000545 if (!I || (I->getOpcode() != Instruction::FMul &&
Shuxin Yang80138662013-01-07 22:41:28 +0000546 I->getOpcode() != Instruction::FDiv))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000547 return false;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000548
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000549 Constant *C0 = dyn_cast<Constant>(I->getOperand(0));
550 Constant *C1 = dyn_cast<Constant>(I->getOperand(1));
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000551
552 if (C0 && C1)
553 return false;
554
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000555 return (C0 && isFiniteNonZeroFp(C0)) || (C1 && isFiniteNonZeroFp(C1));
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000556}
557
558/// foldFMulConst() is a helper routine of InstCombiner::visitFMul().
559/// The input \p FMulOrDiv is a FMul/FDiv with one and only one operand
560/// being a constant (i.e. isFMulOrFDivWithConstant(FMulOrDiv) == true).
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000561/// This function is to simplify "FMulOrDiv * C" and returns the
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000562/// resulting expression. Note that this function could return NULL in
563/// case the constants cannot be folded into a normal floating-point.
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000564Value *InstCombiner::foldFMulConst(Instruction *FMulOrDiv, Constant *C,
Shuxin Yang80138662013-01-07 22:41:28 +0000565 Instruction *InsertBefore) {
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000566 assert(isFMulOrFDivWithConstant(FMulOrDiv) && "V is invalid");
567
568 Value *Opnd0 = FMulOrDiv->getOperand(0);
569 Value *Opnd1 = FMulOrDiv->getOperand(1);
570
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000571 Constant *C0 = dyn_cast<Constant>(Opnd0);
572 Constant *C1 = dyn_cast<Constant>(Opnd1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000573
Craig Topperf40110f2014-04-25 05:29:35 +0000574 BinaryOperator *R = nullptr;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000575
576 // (X * C0) * C => X * (C0*C)
577 if (FMulOrDiv->getOpcode() == Instruction::FMul) {
578 Constant *F = ConstantExpr::getFMul(C1 ? C1 : C0, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000579 if (isNormalFp(F))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000580 R = BinaryOperator::CreateFMul(C1 ? Opnd0 : Opnd1, F);
581 } else {
582 if (C0) {
583 // (C0 / X) * C => (C0 * C) / X
Shuxin Yang3a7ca6e2013-09-19 21:13:46 +0000584 if (FMulOrDiv->hasOneUse()) {
585 // It would otherwise introduce another div.
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000586 Constant *F = ConstantExpr::getFMul(C0, C);
Shuxin Yang3a7ca6e2013-09-19 21:13:46 +0000587 if (isNormalFp(F))
588 R = BinaryOperator::CreateFDiv(F, Opnd1);
589 }
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000590 } else {
591 // (X / C1) * C => X * (C/C1) if C/C1 is not a denormal
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000592 Constant *F = ConstantExpr::getFDiv(C, C1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000593 if (isNormalFp(F)) {
594 R = BinaryOperator::CreateFMul(Opnd0, F);
595 } else {
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000596 // (X / C1) * C => X / (C1/C)
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000597 Constant *F = ConstantExpr::getFDiv(C1, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000598 if (isNormalFp(F))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000599 R = BinaryOperator::CreateFDiv(Opnd0, F);
600 }
601 }
602 }
603
604 if (R) {
Sanjay Patel629c4112017-11-06 16:27:15 +0000605 R->setFast(true);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000606 InsertNewInstWith(R, *InsertBefore);
607 }
608
609 return R;
610}
611
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000612Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +0000613 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000614 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
615
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000616 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +0000617 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000618
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000619 if (isa<Constant>(Op0))
620 std::swap(Op0, Op1);
621
Craig Toppera4205622017-06-09 03:21:29 +0000622 if (Value *V = SimplifyFMulInst(Op0, Op1, I.getFastMathFlags(),
623 SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +0000624 return replaceInstUsesWith(I, V);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000625
Sanjay Patel629c4112017-11-06 16:27:15 +0000626 bool AllowReassociate = I.isFast();
Shuxin Yange8227452013-01-15 21:09:32 +0000627
Michael Ilsemand5787be2012-12-12 00:28:32 +0000628 // Simplify mul instructions with a constant RHS.
629 if (isa<Constant>(Op1)) {
Sanjay Pateldb0938f2017-01-10 23:49:07 +0000630 if (Instruction *FoldedMul = foldOpWithConstantIntoOperand(I))
631 return FoldedMul;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000632
Owen Andersonf74cfe02014-01-16 20:36:42 +0000633 // (fmul X, -1.0) --> (fsub -0.0, X)
Benjamin Kramerfea9ac92014-01-18 16:43:14 +0000634 if (match(Op1, m_SpecificFP(-1.0))) {
635 Constant *NegZero = ConstantFP::getNegativeZero(Op1->getType());
636 Instruction *RI = BinaryOperator::CreateFSub(NegZero, Op0);
Owen Andersonf74cfe02014-01-16 20:36:42 +0000637 RI->copyFastMathFlags(&I);
638 return RI;
639 }
640
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000641 Constant *C = cast<Constant>(Op1);
642 if (AllowReassociate && isFiniteNonZeroFp(C)) {
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000643 // Let MDC denote an expression in one of these forms:
644 // X * C, C/X, X/C, where C is a constant.
645 //
646 // Try to simplify "MDC * Constant"
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000647 if (isFMulOrFDivWithConstant(Op0))
648 if (Value *V = foldFMulConst(cast<Instruction>(Op0), C, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +0000649 return replaceInstUsesWith(I, V);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000650
Quentin Colombete684a6d2013-02-28 21:12:40 +0000651 // (MDC +/- C1) * C => (MDC * C) +/- (C1 * C)
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000652 Instruction *FAddSub = dyn_cast<Instruction>(Op0);
653 if (FAddSub &&
654 (FAddSub->getOpcode() == Instruction::FAdd ||
655 FAddSub->getOpcode() == Instruction::FSub)) {
656 Value *Opnd0 = FAddSub->getOperand(0);
657 Value *Opnd1 = FAddSub->getOperand(1);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000658 Constant *C0 = dyn_cast<Constant>(Opnd0);
659 Constant *C1 = dyn_cast<Constant>(Opnd1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000660 bool Swap = false;
661 if (C0) {
Shuxin Yang80138662013-01-07 22:41:28 +0000662 std::swap(C0, C1);
663 std::swap(Opnd0, Opnd1);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000664 Swap = true;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000665 }
666
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000667 if (C1 && isFiniteNonZeroFp(C1) && isFMulOrFDivWithConstant(Opnd0)) {
Quentin Colombete684a6d2013-02-28 21:12:40 +0000668 Value *M1 = ConstantExpr::getFMul(C1, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000669 Value *M0 = isNormalFp(cast<Constant>(M1)) ?
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000670 foldFMulConst(cast<Instruction>(Opnd0), C, &I) :
Craig Topperf40110f2014-04-25 05:29:35 +0000671 nullptr;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000672 if (M0 && M1) {
673 if (Swap && FAddSub->getOpcode() == Instruction::FSub)
674 std::swap(M0, M1);
675
Benjamin Kramer67485762013-09-30 15:39:59 +0000676 Instruction *RI = (FAddSub->getOpcode() == Instruction::FAdd)
677 ? BinaryOperator::CreateFAdd(M0, M1)
678 : BinaryOperator::CreateFSub(M0, M1);
Shuxin Yange8227452013-01-15 21:09:32 +0000679 RI->copyFastMathFlags(&I);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000680 return RI;
681 }
682 }
683 }
684 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000685 }
686
Matt Arsenault56c079f2016-01-30 05:02:00 +0000687 if (Op0 == Op1) {
688 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
689 // sqrt(X) * sqrt(X) -> X
690 if (AllowReassociate && II->getIntrinsicID() == Intrinsic::sqrt)
Sanjay Patel4b198802016-02-01 22:23:39 +0000691 return replaceInstUsesWith(I, II->getOperand(0));
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000692
Matt Arsenault56c079f2016-01-30 05:02:00 +0000693 // fabs(X) * fabs(X) -> X * X
694 if (II->getIntrinsicID() == Intrinsic::fabs) {
695 Instruction *FMulVal = BinaryOperator::CreateFMul(II->getOperand(0),
696 II->getOperand(0),
697 I.getName());
698 FMulVal->copyFastMathFlags(&I);
699 return FMulVal;
700 }
701 }
702 }
703
Pedro Artigasd8795042012-11-30 19:09:41 +0000704 // Under unsafe algebra do:
705 // X * log2(0.5*Y) = X*log2(Y) - X
Sanjay Patelb41d4612014-10-02 15:20:45 +0000706 if (AllowReassociate) {
Craig Topperf40110f2014-04-25 05:29:35 +0000707 Value *OpX = nullptr;
708 Value *OpY = nullptr;
Pedro Artigasd8795042012-11-30 19:09:41 +0000709 IntrinsicInst *Log2;
Pedro Artigas993acd02012-11-30 22:07:05 +0000710 detectLog2OfHalf(Op0, OpY, Log2);
711 if (OpY) {
712 OpX = Op1;
713 } else {
714 detectLog2OfHalf(Op1, OpY, Log2);
715 if (OpY) {
716 OpX = Op0;
Pedro Artigasd8795042012-11-30 19:09:41 +0000717 }
718 }
719 // if pattern detected emit alternate sequence
720 if (OpX && OpY) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000721 BuilderTy::FastMathFlagGuard Guard(Builder);
722 Builder.setFastMathFlags(Log2->getFastMathFlags());
Pedro Artigasd8795042012-11-30 19:09:41 +0000723 Log2->setArgOperand(0, OpY);
Craig Topperbb4069e2017-07-07 23:16:26 +0000724 Value *FMulVal = Builder.CreateFMul(OpX, Log2);
725 Value *FSub = Builder.CreateFSub(FMulVal, OpX);
Benjamin Kramer67485762013-09-30 15:39:59 +0000726 FSub->takeName(&I);
Sanjay Patel4b198802016-02-01 22:23:39 +0000727 return replaceInstUsesWith(I, FSub);
Pedro Artigasd8795042012-11-30 19:09:41 +0000728 }
729 }
730
Dmitry Venikova58d8de2018-01-02 05:58:11 +0000731 // sqrt(a) * sqrt(b) -> sqrt(a * b)
732 if (AllowReassociate &&
733 Op0->hasOneUse() && Op1->hasOneUse()) {
734 Value *Opnd0 = nullptr;
735 Value *Opnd1 = nullptr;
736 if (match(Op0, m_Intrinsic<Intrinsic::sqrt>(m_Value(Opnd0))) &&
737 match(Op1, m_Intrinsic<Intrinsic::sqrt>(m_Value(Opnd1)))) {
738 BuilderTy::FastMathFlagGuard Guard(Builder);
739 Builder.setFastMathFlags(I.getFastMathFlags());
740 Value *FMulVal = Builder.CreateFMul(Opnd0, Opnd1);
741 Value *Sqrt = Intrinsic::getDeclaration(I.getModule(),
742 Intrinsic::sqrt, I.getType());
743 Value *SqrtCall = Builder.CreateCall(Sqrt, FMulVal);
744 return replaceInstUsesWith(I, SqrtCall);
745 }
746 }
747
Shuxin Yange8227452013-01-15 21:09:32 +0000748 // Handle symmetric situation in a 2-iteration loop
749 Value *Opnd0 = Op0;
750 Value *Opnd1 = Op1;
751 for (int i = 0; i < 2; i++) {
752 bool IgnoreZeroSign = I.hasNoSignedZeros();
753 if (BinaryOperator::isFNeg(Opnd0, IgnoreZeroSign)) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000754 BuilderTy::FastMathFlagGuard Guard(Builder);
755 Builder.setFastMathFlags(I.getFastMathFlags());
Benjamin Kramer67485762013-09-30 15:39:59 +0000756
Shuxin Yange8227452013-01-15 21:09:32 +0000757 Value *N0 = dyn_castFNegVal(Opnd0, IgnoreZeroSign);
758 Value *N1 = dyn_castFNegVal(Opnd1, IgnoreZeroSign);
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000759
Shuxin Yange8227452013-01-15 21:09:32 +0000760 // -X * -Y => X*Y
Owen Andersone8537fc2014-01-16 20:59:41 +0000761 if (N1) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000762 Value *FMul = Builder.CreateFMul(N0, N1);
Owen Andersone8537fc2014-01-16 20:59:41 +0000763 FMul->takeName(&I);
Sanjay Patel4b198802016-02-01 22:23:39 +0000764 return replaceInstUsesWith(I, FMul);
Owen Andersone8537fc2014-01-16 20:59:41 +0000765 }
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000766
Shuxin Yange8227452013-01-15 21:09:32 +0000767 if (Opnd0->hasOneUse()) {
768 // -X * Y => -(X*Y) (Promote negation as high as possible)
Craig Topperbb4069e2017-07-07 23:16:26 +0000769 Value *T = Builder.CreateFMul(N0, Opnd1);
770 Value *Neg = Builder.CreateFNeg(T);
Benjamin Kramer67485762013-09-30 15:39:59 +0000771 Neg->takeName(&I);
Sanjay Patel4b198802016-02-01 22:23:39 +0000772 return replaceInstUsesWith(I, Neg);
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000773 }
774 }
Shuxin Yange8227452013-01-15 21:09:32 +0000775
Quentin Colombetaa103b32017-09-20 17:32:16 +0000776 // Handle specials cases for FMul with selects feeding the operation
777 if (Value *V = SimplifySelectsFeedingBinaryOp(I, Op0, Op1))
778 return replaceInstUsesWith(I, V);
779
Shuxin Yange8227452013-01-15 21:09:32 +0000780 // (X*Y) * X => (X*X) * Y where Y != X
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000781 // The purpose is two-fold:
Shuxin Yange8227452013-01-15 21:09:32 +0000782 // 1) to form a power expression (of X).
783 // 2) potentially shorten the critical path: After transformation, the
784 // latency of the instruction Y is amortized by the expression of X*X,
785 // and therefore Y is in a "less critical" position compared to what it
786 // was before the transformation.
Shuxin Yange8227452013-01-15 21:09:32 +0000787 if (AllowReassociate) {
788 Value *Opnd0_0, *Opnd0_1;
789 if (Opnd0->hasOneUse() &&
790 match(Opnd0, m_FMul(m_Value(Opnd0_0), m_Value(Opnd0_1)))) {
Craig Topperf40110f2014-04-25 05:29:35 +0000791 Value *Y = nullptr;
Shuxin Yange8227452013-01-15 21:09:32 +0000792 if (Opnd0_0 == Opnd1 && Opnd0_1 != Opnd1)
793 Y = Opnd0_1;
794 else if (Opnd0_1 == Opnd1 && Opnd0_0 != Opnd1)
795 Y = Opnd0_0;
796
797 if (Y) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000798 BuilderTy::FastMathFlagGuard Guard(Builder);
799 Builder.setFastMathFlags(I.getFastMathFlags());
800 Value *T = Builder.CreateFMul(Opnd1, Opnd1);
801 Value *R = Builder.CreateFMul(T, Y);
Benjamin Kramer67485762013-09-30 15:39:59 +0000802 R->takeName(&I);
Sanjay Patel4b198802016-02-01 22:23:39 +0000803 return replaceInstUsesWith(I, R);
Shuxin Yange8227452013-01-15 21:09:32 +0000804 }
805 }
806 }
807
808 if (!isa<Constant>(Op1))
809 std::swap(Opnd0, Opnd1);
810 else
811 break;
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000812 }
813
Craig Topperf40110f2014-04-25 05:29:35 +0000814 return Changed ? &I : nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000815}
816
Sanjay Patelae2e3a42017-10-06 23:20:16 +0000817/// Fold a divide or remainder with a select instruction divisor when one of the
818/// select operands is zero. In that case, we can use the other select operand
819/// because div/rem by zero is undefined.
820bool InstCombiner::simplifyDivRemOfSelectWithZeroOp(BinaryOperator &I) {
821 SelectInst *SI = dyn_cast<SelectInst>(I.getOperand(1));
822 if (!SI)
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000823 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000824
Sanjay Patelae2e3a42017-10-06 23:20:16 +0000825 int NonNullOperand;
826 if (match(SI->getTrueValue(), m_Zero()))
827 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
828 NonNullOperand = 2;
829 else if (match(SI->getFalseValue(), m_Zero()))
830 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
831 NonNullOperand = 1;
832 else
833 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000834
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000835 // Change the div/rem to use 'Y' instead of the select.
836 I.setOperand(1, SI->getOperand(NonNullOperand));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000837
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000838 // Okay, we know we replace the operand of the div/rem with 'Y' with no
839 // problem. However, the select, or the condition of the select may have
840 // multiple uses. Based on our knowledge that the operand must be non-zero,
841 // propagate the known value for the select into other uses of it, and
842 // propagate a known value of the condition into its other users.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000843
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000844 // If the select and condition only have a single use, don't bother with this,
845 // early exit.
Sanjay Patelae2e3a42017-10-06 23:20:16 +0000846 Value *SelectCond = SI->getCondition();
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000847 if (SI->use_empty() && SelectCond->hasOneUse())
848 return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000849
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000850 // Scan the current block backward, looking for other uses of SI.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000851 BasicBlock::iterator BBI = I.getIterator(), BBFront = I.getParent()->begin();
Sanjay Patel72d339a2017-10-06 23:43:06 +0000852 Type *CondTy = SelectCond->getType();
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000853 while (BBI != BBFront) {
854 --BBI;
855 // If we found a call to a function, we can't assume it will return, so
856 // information from below it cannot be propagated above it.
857 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
858 break;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000859
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000860 // Replace uses of the select or its condition with the known values.
861 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
862 I != E; ++I) {
863 if (*I == SI) {
864 *I = SI->getOperand(NonNullOperand);
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000865 Worklist.Add(&*BBI);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000866 } else if (*I == SelectCond) {
Sanjay Patel72d339a2017-10-06 23:43:06 +0000867 *I = NonNullOperand == 1 ? ConstantInt::getTrue(CondTy)
868 : ConstantInt::getFalse(CondTy);
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000869 Worklist.Add(&*BBI);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000870 }
871 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000872
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000873 // If we past the instruction, quit looking for it.
874 if (&*BBI == SI)
Craig Topperf40110f2014-04-25 05:29:35 +0000875 SI = nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000876 if (&*BBI == SelectCond)
Craig Topperf40110f2014-04-25 05:29:35 +0000877 SelectCond = nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000878
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000879 // If we ran out of things to eliminate, break out of the loop.
Craig Topperf40110f2014-04-25 05:29:35 +0000880 if (!SelectCond && !SI)
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000881 break;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000882
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000883 }
884 return true;
885}
886
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000887/// This function implements the transforms common to both integer division
888/// instructions (udiv and sdiv). It is called by the visitors to those integer
889/// division instructions.
890/// @brief Common integer divide transforms
891Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
892 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
893
Chris Lattner7c99f192011-05-22 18:18:41 +0000894 // The RHS is known non-zero.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000895 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I)) {
Chris Lattner7c99f192011-05-22 18:18:41 +0000896 I.setOperand(1, V);
897 return &I;
898 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000899
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000900 // Handle cases involving: [su]div X, (select Cond, Y, Z)
901 // This does not apply for fdiv.
Sanjay Patelae2e3a42017-10-06 23:20:16 +0000902 if (simplifyDivRemOfSelectWithZeroOp(I))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000903 return &I;
904
David Majnemer27adb122014-10-12 08:34:24 +0000905 if (Instruction *LHS = dyn_cast<Instruction>(Op0)) {
906 const APInt *C2;
907 if (match(Op1, m_APInt(C2))) {
David Majnemerf9a095d2014-08-16 08:55:06 +0000908 Value *X;
David Majnemer27adb122014-10-12 08:34:24 +0000909 const APInt *C1;
910 bool IsSigned = I.getOpcode() == Instruction::SDiv;
David Majnemerf9a095d2014-08-16 08:55:06 +0000911
David Majnemer27adb122014-10-12 08:34:24 +0000912 // (X / C1) / C2 -> X / (C1*C2)
913 if ((IsSigned && match(LHS, m_SDiv(m_Value(X), m_APInt(C1)))) ||
914 (!IsSigned && match(LHS, m_UDiv(m_Value(X), m_APInt(C1))))) {
915 APInt Product(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
916 if (!MultiplyOverflows(*C1, *C2, Product, IsSigned))
917 return BinaryOperator::Create(I.getOpcode(), X,
918 ConstantInt::get(I.getType(), Product));
919 }
David Majnemerf9a095d2014-08-16 08:55:06 +0000920
David Majnemer27adb122014-10-12 08:34:24 +0000921 if ((IsSigned && match(LHS, m_NSWMul(m_Value(X), m_APInt(C1)))) ||
922 (!IsSigned && match(LHS, m_NUWMul(m_Value(X), m_APInt(C1))))) {
923 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
924
925 // (X * C1) / C2 -> X / (C2 / C1) if C2 is a multiple of C1.
926 if (IsMultiple(*C2, *C1, Quotient, IsSigned)) {
927 BinaryOperator *BO = BinaryOperator::Create(
928 I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
929 BO->setIsExact(I.isExact());
930 return BO;
David Majnemerf9a095d2014-08-16 08:55:06 +0000931 }
932
David Majnemer27adb122014-10-12 08:34:24 +0000933 // (X * C1) / C2 -> X * (C1 / C2) if C1 is a multiple of C2.
934 if (IsMultiple(*C1, *C2, Quotient, IsSigned)) {
935 BinaryOperator *BO = BinaryOperator::Create(
936 Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
937 BO->setHasNoUnsignedWrap(
938 !IsSigned &&
939 cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
940 BO->setHasNoSignedWrap(
941 cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
942 return BO;
David Majnemerf9a095d2014-08-16 08:55:06 +0000943 }
944 }
David Majnemerf9a095d2014-08-16 08:55:06 +0000945
David Majnemer27adb122014-10-12 08:34:24 +0000946 if ((IsSigned && match(LHS, m_NSWShl(m_Value(X), m_APInt(C1))) &&
947 *C1 != C1->getBitWidth() - 1) ||
948 (!IsSigned && match(LHS, m_NUWShl(m_Value(X), m_APInt(C1))))) {
949 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
950 APInt C1Shifted = APInt::getOneBitSet(
951 C1->getBitWidth(), static_cast<unsigned>(C1->getLimitedValue()));
952
953 // (X << C1) / C2 -> X / (C2 >> C1) if C2 is a multiple of C1.
954 if (IsMultiple(*C2, C1Shifted, Quotient, IsSigned)) {
955 BinaryOperator *BO = BinaryOperator::Create(
956 I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
957 BO->setIsExact(I.isExact());
958 return BO;
959 }
960
961 // (X << C1) / C2 -> X * (C2 >> C1) if C1 is a multiple of C2.
962 if (IsMultiple(C1Shifted, *C2, Quotient, IsSigned)) {
963 BinaryOperator *BO = BinaryOperator::Create(
964 Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
965 BO->setHasNoUnsignedWrap(
966 !IsSigned &&
967 cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
968 BO->setHasNoSignedWrap(
969 cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
970 return BO;
971 }
972 }
973
Craig Topper73ba1c82017-06-07 07:40:37 +0000974 if (!C2->isNullValue()) // avoid X udiv 0
Sanjay Pateldb0938f2017-01-10 23:49:07 +0000975 if (Instruction *FoldedDiv = foldOpWithConstantIntoOperand(I))
976 return FoldedDiv;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000977 }
978 }
979
Craig Topper218a3592017-04-17 03:41:47 +0000980 if (match(Op0, m_One())) {
Craig Topperfde47232017-07-09 07:04:03 +0000981 assert(!I.getType()->isIntOrIntVectorTy(1) && "i1 divide not removed?");
Craig Topper218a3592017-04-17 03:41:47 +0000982 if (I.getOpcode() == Instruction::SDiv) {
983 // If Op1 is 0 then it's undefined behaviour, if Op1 is 1 then the
984 // result is one, if Op1 is -1 then the result is minus one, otherwise
985 // it's zero.
Craig Topperbb4069e2017-07-07 23:16:26 +0000986 Value *Inc = Builder.CreateAdd(Op1, Op0);
987 Value *Cmp = Builder.CreateICmpULT(Inc, ConstantInt::get(I.getType(), 3));
Craig Topper218a3592017-04-17 03:41:47 +0000988 return SelectInst::Create(Cmp, Op1, ConstantInt::get(I.getType(), 0));
989 } else {
990 // If Op1 is 0 then it's undefined behaviour. If Op1 is 1 then the
991 // result is one, otherwise it's zero.
Craig Topperbb4069e2017-07-07 23:16:26 +0000992 return new ZExtInst(Builder.CreateICmpEQ(Op1, Op0), I.getType());
Nick Lewyckyf0cf8fa2014-05-14 03:03:05 +0000993 }
994 }
995
Benjamin Kramer57b3df52011-04-30 18:16:00 +0000996 // See if we can fold away this div instruction.
997 if (SimplifyDemandedInstructionBits(I))
998 return &I;
999
Duncan Sands771e82a2011-01-28 16:51:11 +00001000 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
Craig Topperf40110f2014-04-25 05:29:35 +00001001 Value *X = nullptr, *Z = nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001002 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) { // (X - Z) / Y; Y = Op1
1003 bool isSigned = I.getOpcode() == Instruction::SDiv;
1004 if ((isSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
1005 (!isSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
1006 return BinaryOperator::Create(I.getOpcode(), X, Op1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001007 }
1008
Craig Topperf40110f2014-04-25 05:29:35 +00001009 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001010}
1011
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00001012static const unsigned MaxDepth = 6;
1013
David Majnemer37f8f442013-07-04 21:17:49 +00001014namespace {
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00001015
1016using FoldUDivOperandCb = Instruction *(*)(Value *Op0, Value *Op1,
1017 const BinaryOperator &I,
1018 InstCombiner &IC);
David Majnemer37f8f442013-07-04 21:17:49 +00001019
1020/// \brief Used to maintain state for visitUDivOperand().
1021struct UDivFoldAction {
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00001022 /// Informs visitUDiv() how to fold this operand. This can be zero if this
1023 /// action joins two actions together.
1024 FoldUDivOperandCb FoldAction;
David Majnemer37f8f442013-07-04 21:17:49 +00001025
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00001026 /// Which operand to fold.
1027 Value *OperandToFold;
1028
David Majnemer37f8f442013-07-04 21:17:49 +00001029 union {
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00001030 /// The instruction returned when FoldAction is invoked.
1031 Instruction *FoldResult;
David Majnemer37f8f442013-07-04 21:17:49 +00001032
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00001033 /// Stores the LHS action index if this action joins two actions together.
1034 size_t SelectLHSIdx;
David Majnemer37f8f442013-07-04 21:17:49 +00001035 };
1036
1037 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand)
Craig Topperf40110f2014-04-25 05:29:35 +00001038 : FoldAction(FA), OperandToFold(InputOperand), FoldResult(nullptr) {}
David Majnemer37f8f442013-07-04 21:17:49 +00001039 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand, size_t SLHS)
1040 : FoldAction(FA), OperandToFold(InputOperand), SelectLHSIdx(SLHS) {}
1041};
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00001042
1043} // end anonymous namespace
David Majnemer37f8f442013-07-04 21:17:49 +00001044
1045// X udiv 2^C -> X >> C
1046static Instruction *foldUDivPow2Cst(Value *Op0, Value *Op1,
1047 const BinaryOperator &I, InstCombiner &IC) {
1048 const APInt &C = cast<Constant>(Op1)->getUniqueInteger();
1049 BinaryOperator *LShr = BinaryOperator::CreateLShr(
1050 Op0, ConstantInt::get(Op0->getType(), C.logBase2()));
Suyog Sarda65f5ae92014-10-07 12:04:07 +00001051 if (I.isExact())
1052 LShr->setIsExact();
David Majnemer37f8f442013-07-04 21:17:49 +00001053 return LShr;
1054}
1055
1056// X udiv C, where C >= signbit
1057static Instruction *foldUDivNegCst(Value *Op0, Value *Op1,
1058 const BinaryOperator &I, InstCombiner &IC) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001059 Value *ICI = IC.Builder.CreateICmpULT(Op0, cast<ConstantInt>(Op1));
David Majnemer37f8f442013-07-04 21:17:49 +00001060
1061 return SelectInst::Create(ICI, Constant::getNullValue(I.getType()),
1062 ConstantInt::get(I.getType(), 1));
1063}
1064
1065// X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Andrea Di Biagioa82d52d2016-09-26 12:07:23 +00001066// X udiv (zext (C1 << N)), where C1 is "1<<C2" --> X >> (N+C2)
David Majnemer37f8f442013-07-04 21:17:49 +00001067static Instruction *foldUDivShl(Value *Op0, Value *Op1, const BinaryOperator &I,
1068 InstCombiner &IC) {
Andrea Di Biagioa82d52d2016-09-26 12:07:23 +00001069 Value *ShiftLeft;
1070 if (!match(Op1, m_ZExt(m_Value(ShiftLeft))))
1071 ShiftLeft = Op1;
David Majnemer37f8f442013-07-04 21:17:49 +00001072
Andrea Di Biagioa82d52d2016-09-26 12:07:23 +00001073 const APInt *CI;
1074 Value *N;
1075 if (!match(ShiftLeft, m_Shl(m_APInt(CI), m_Value(N))))
1076 llvm_unreachable("match should never fail here!");
1077 if (*CI != 1)
Craig Topperbb4069e2017-07-07 23:16:26 +00001078 N = IC.Builder.CreateAdd(N, ConstantInt::get(N->getType(), CI->logBase2()));
Andrea Di Biagioa82d52d2016-09-26 12:07:23 +00001079 if (Op1 != ShiftLeft)
Craig Topperbb4069e2017-07-07 23:16:26 +00001080 N = IC.Builder.CreateZExt(N, Op1->getType());
David Majnemer37f8f442013-07-04 21:17:49 +00001081 BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, N);
Suyog Sarda65f5ae92014-10-07 12:04:07 +00001082 if (I.isExact())
1083 LShr->setIsExact();
David Majnemer37f8f442013-07-04 21:17:49 +00001084 return LShr;
1085}
1086
1087// \brief Recursively visits the possible right hand operands of a udiv
1088// instruction, seeing through select instructions, to determine if we can
1089// replace the udiv with something simpler. If we find that an operand is not
1090// able to simplify the udiv, we abort the entire transformation.
1091static size_t visitUDivOperand(Value *Op0, Value *Op1, const BinaryOperator &I,
1092 SmallVectorImpl<UDivFoldAction> &Actions,
1093 unsigned Depth = 0) {
1094 // Check to see if this is an unsigned division with an exact power of 2,
1095 // if so, convert to a right shift.
1096 if (match(Op1, m_Power2())) {
1097 Actions.push_back(UDivFoldAction(foldUDivPow2Cst, Op1));
1098 return Actions.size();
1099 }
1100
1101 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1))
1102 // X udiv C, where C >= signbit
1103 if (C->getValue().isNegative()) {
1104 Actions.push_back(UDivFoldAction(foldUDivNegCst, C));
1105 return Actions.size();
1106 }
1107
1108 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
1109 if (match(Op1, m_Shl(m_Power2(), m_Value())) ||
1110 match(Op1, m_ZExt(m_Shl(m_Power2(), m_Value())))) {
1111 Actions.push_back(UDivFoldAction(foldUDivShl, Op1));
1112 return Actions.size();
1113 }
1114
1115 // The remaining tests are all recursive, so bail out if we hit the limit.
1116 if (Depth++ == MaxDepth)
1117 return 0;
1118
1119 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
David Majnemer492e6122014-08-30 09:19:05 +00001120 if (size_t LHSIdx =
1121 visitUDivOperand(Op0, SI->getOperand(1), I, Actions, Depth))
1122 if (visitUDivOperand(Op0, SI->getOperand(2), I, Actions, Depth)) {
1123 Actions.push_back(UDivFoldAction(nullptr, Op1, LHSIdx - 1));
David Majnemer37f8f442013-07-04 21:17:49 +00001124 return Actions.size();
1125 }
1126
1127 return 0;
1128}
1129
Sanjay Patelbb789382017-08-24 22:54:01 +00001130/// If we have zero-extended operands of an unsigned div or rem, we may be able
1131/// to narrow the operation (sink the zext below the math).
1132static Instruction *narrowUDivURem(BinaryOperator &I,
1133 InstCombiner::BuilderTy &Builder) {
1134 Instruction::BinaryOps Opcode = I.getOpcode();
1135 Value *N = I.getOperand(0);
1136 Value *D = I.getOperand(1);
1137 Type *Ty = I.getType();
1138 Value *X, *Y;
1139 if (match(N, m_ZExt(m_Value(X))) && match(D, m_ZExt(m_Value(Y))) &&
1140 X->getType() == Y->getType() && (N->hasOneUse() || D->hasOneUse())) {
1141 // udiv (zext X), (zext Y) --> zext (udiv X, Y)
1142 // urem (zext X), (zext Y) --> zext (urem X, Y)
1143 Value *NarrowOp = Builder.CreateBinOp(Opcode, X, Y);
1144 return new ZExtInst(NarrowOp, Ty);
1145 }
1146
1147 Constant *C;
1148 if ((match(N, m_OneUse(m_ZExt(m_Value(X)))) && match(D, m_Constant(C))) ||
1149 (match(D, m_OneUse(m_ZExt(m_Value(X)))) && match(N, m_Constant(C)))) {
1150 // If the constant is the same in the smaller type, use the narrow version.
1151 Constant *TruncC = ConstantExpr::getTrunc(C, X->getType());
1152 if (ConstantExpr::getZExt(TruncC, Ty) != C)
1153 return nullptr;
1154
1155 // udiv (zext X), C --> zext (udiv X, C')
1156 // urem (zext X), C --> zext (urem X, C')
1157 // udiv C, (zext X) --> zext (udiv C', X)
1158 // urem C, (zext X) --> zext (urem C', X)
1159 Value *NarrowOp = isa<Constant>(D) ? Builder.CreateBinOp(Opcode, X, TruncC)
1160 : Builder.CreateBinOp(Opcode, TruncC, X);
1161 return new ZExtInst(NarrowOp, Ty);
1162 }
1163
1164 return nullptr;
1165}
1166
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001167Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
1168 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1169
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001170 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001171 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001172
Craig Toppera4205622017-06-09 03:21:29 +00001173 if (Value *V = SimplifyUDivInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001174 return replaceInstUsesWith(I, V);
Duncan Sands771e82a2011-01-28 16:51:11 +00001175
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001176 // Handle the integer div common cases
1177 if (Instruction *Common = commonIDivTransforms(I))
1178 return Common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001179
Benjamin Kramerd4a64712012-08-30 15:07:40 +00001180 // (x lshr C1) udiv C2 --> x udiv (C2 << C1)
David Majnemera2521382014-10-13 21:48:30 +00001181 {
Benjamin Kramer9c0a8072012-08-28 13:08:13 +00001182 Value *X;
David Majnemera2521382014-10-13 21:48:30 +00001183 const APInt *C1, *C2;
1184 if (match(Op0, m_LShr(m_Value(X), m_APInt(C1))) &&
1185 match(Op1, m_APInt(C2))) {
1186 bool Overflow;
1187 APInt C2ShlC1 = C2->ushl_ov(*C1, Overflow);
David Majnemera3aeb152014-11-22 18:16:54 +00001188 if (!Overflow) {
1189 bool IsExact = I.isExact() && match(Op0, m_Exact(m_Value()));
1190 BinaryOperator *BO = BinaryOperator::CreateUDiv(
David Majnemera2521382014-10-13 21:48:30 +00001191 X, ConstantInt::get(X->getType(), C2ShlC1));
David Majnemera3aeb152014-11-22 18:16:54 +00001192 if (IsExact)
1193 BO->setIsExact();
1194 return BO;
1195 }
David Majnemera2521382014-10-13 21:48:30 +00001196 }
Nadav Rotem11935b22012-08-28 10:01:43 +00001197 }
1198
Sanjay Patelbb789382017-08-24 22:54:01 +00001199 if (Instruction *NarrowDiv = narrowUDivURem(I, Builder))
1200 return NarrowDiv;
Benjamin Kramer9aa91b12011-04-30 18:16:07 +00001201
David Majnemer37f8f442013-07-04 21:17:49 +00001202 // (LHS udiv (select (select (...)))) -> (LHS >> (select (select (...))))
1203 SmallVector<UDivFoldAction, 6> UDivActions;
1204 if (visitUDivOperand(Op0, Op1, I, UDivActions))
1205 for (unsigned i = 0, e = UDivActions.size(); i != e; ++i) {
1206 FoldUDivOperandCb Action = UDivActions[i].FoldAction;
1207 Value *ActionOp1 = UDivActions[i].OperandToFold;
1208 Instruction *Inst;
1209 if (Action)
1210 Inst = Action(Op0, ActionOp1, I, *this);
1211 else {
1212 // This action joins two actions together. The RHS of this action is
1213 // simply the last action we processed, we saved the LHS action index in
1214 // the joining action.
1215 size_t SelectRHSIdx = i - 1;
1216 Value *SelectRHS = UDivActions[SelectRHSIdx].FoldResult;
1217 size_t SelectLHSIdx = UDivActions[i].SelectLHSIdx;
1218 Value *SelectLHS = UDivActions[SelectLHSIdx].FoldResult;
1219 Inst = SelectInst::Create(cast<SelectInst>(ActionOp1)->getCondition(),
1220 SelectLHS, SelectRHS);
1221 }
1222
1223 // If this is the last action to process, return it to the InstCombiner.
1224 // Otherwise, we insert it before the UDiv and record it so that we may
1225 // use it as part of a joining action (i.e., a SelectInst).
1226 if (e - i != 1) {
1227 Inst->insertBefore(&I);
1228 UDivActions[i].FoldResult = Inst;
1229 } else
1230 return Inst;
1231 }
1232
Craig Topperf40110f2014-04-25 05:29:35 +00001233 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001234}
1235
1236Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
1237 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1238
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001239 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001240 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001241
Craig Toppera4205622017-06-09 03:21:29 +00001242 if (Value *V = SimplifySDivInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001243 return replaceInstUsesWith(I, V);
Duncan Sands771e82a2011-01-28 16:51:11 +00001244
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001245 // Handle the integer div common cases
1246 if (Instruction *Common = commonIDivTransforms(I))
1247 return Common;
1248
Sanjay Patelc6ada532016-06-27 17:25:57 +00001249 const APInt *Op1C;
Sanjay Patelbedd1f92016-06-27 18:38:40 +00001250 if (match(Op1, m_APInt(Op1C))) {
1251 // sdiv X, -1 == -X
1252 if (Op1C->isAllOnesValue())
1253 return BinaryOperator::CreateNeg(Op0);
1254
1255 // sdiv exact X, C --> ashr exact X, log2(C)
1256 if (I.isExact() && Op1C->isNonNegative() && Op1C->isPowerOf2()) {
1257 Value *ShAmt = ConstantInt::get(Op1->getType(), Op1C->exactLogBase2());
1258 return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
1259 }
Sanjay Patel59ed2ff2016-06-27 22:27:11 +00001260
1261 // If the dividend is sign-extended and the constant divisor is small enough
1262 // to fit in the source type, shrink the division to the narrower type:
1263 // (sext X) sdiv C --> sext (X sdiv C)
1264 Value *Op0Src;
1265 if (match(Op0, m_OneUse(m_SExt(m_Value(Op0Src)))) &&
1266 Op0Src->getType()->getScalarSizeInBits() >= Op1C->getMinSignedBits()) {
1267
1268 // In the general case, we need to make sure that the dividend is not the
1269 // minimum signed value because dividing that by -1 is UB. But here, we
1270 // know that the -1 divisor case is already handled above.
1271
1272 Constant *NarrowDivisor =
1273 ConstantExpr::getTrunc(cast<Constant>(Op1), Op0Src->getType());
Craig Topperbb4069e2017-07-07 23:16:26 +00001274 Value *NarrowOp = Builder.CreateSDiv(Op0Src, NarrowDivisor);
Sanjay Patel59ed2ff2016-06-27 22:27:11 +00001275 return new SExtInst(NarrowOp, Op0->getType());
1276 }
Benjamin Kramer72196f32014-01-19 15:24:22 +00001277 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001278
Benjamin Kramer72196f32014-01-19 15:24:22 +00001279 if (Constant *RHS = dyn_cast<Constant>(Op1)) {
David Majnemerf28e2a42014-07-02 06:42:13 +00001280 // X/INT_MIN -> X == INT_MIN
1281 if (RHS->isMinSignedValue())
Craig Topperbb4069e2017-07-07 23:16:26 +00001282 return new ZExtInst(Builder.CreateICmpEQ(Op0, Op1), I.getType());
David Majnemerf28e2a42014-07-02 06:42:13 +00001283
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001284 // -X/C --> X/-C provided the negation doesn't overflow.
David Majnemerfa4699e2014-11-22 20:00:34 +00001285 Value *X;
1286 if (match(Op0, m_NSWSub(m_Zero(), m_Value(X)))) {
1287 auto *BO = BinaryOperator::CreateSDiv(X, ConstantExpr::getNeg(RHS));
1288 BO->setIsExact(I.isExact());
1289 return BO;
1290 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001291 }
1292
1293 // If the sign bits of both operands are zero (i.e. we can prove they are
1294 // unsigned inputs), turn this into a udiv.
Craig Topperbcfd2d12017-04-20 16:56:25 +00001295 APInt Mask(APInt::getSignMask(I.getType()->getScalarSizeInBits()));
Craig Topperf2484682017-04-17 01:51:19 +00001296 if (MaskedValueIsZero(Op0, Mask, 0, &I)) {
1297 if (MaskedValueIsZero(Op1, Mask, 0, &I)) {
1298 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
1299 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1300 BO->setIsExact(I.isExact());
1301 return BO;
1302 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001303
Craig Topperd4039f72017-05-25 21:51:12 +00001304 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/ true, 0, &I)) {
Craig Topperf2484682017-04-17 01:51:19 +00001305 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
1306 // Safe because the only negative value (1 << Y) can take on is
1307 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
1308 // the sign bit set.
1309 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1310 BO->setIsExact(I.isExact());
1311 return BO;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001312 }
1313 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001314
Craig Topperf40110f2014-04-25 05:29:35 +00001315 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001316}
1317
Shuxin Yang320f52a2013-01-14 22:48:41 +00001318/// CvtFDivConstToReciprocal tries to convert X/C into X*1/C if C not a special
1319/// FP value and:
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001320/// 1) 1/C is exact, or
Shuxin Yang320f52a2013-01-14 22:48:41 +00001321/// 2) reciprocal is allowed.
Sylvestre Ledru149e2812013-05-14 23:36:24 +00001322/// If the conversion was successful, the simplified expression "X * 1/C" is
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00001323/// returned; otherwise, nullptr is returned.
Suyog Sardaea205512014-10-07 11:56:06 +00001324static Instruction *CvtFDivConstToReciprocal(Value *Dividend, Constant *Divisor,
Shuxin Yang320f52a2013-01-14 22:48:41 +00001325 bool AllowReciprocal) {
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001326 if (!isa<ConstantFP>(Divisor)) // TODO: handle vectors.
Craig Topperf40110f2014-04-25 05:29:35 +00001327 return nullptr;
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001328
1329 const APFloat &FpVal = cast<ConstantFP>(Divisor)->getValueAPF();
Shuxin Yang320f52a2013-01-14 22:48:41 +00001330 APFloat Reciprocal(FpVal.getSemantics());
1331 bool Cvt = FpVal.getExactInverse(&Reciprocal);
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001332
Michael Gottesman3cb77ab2013-06-19 21:23:18 +00001333 if (!Cvt && AllowReciprocal && FpVal.isFiniteNonZero()) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001334 Reciprocal = APFloat(FpVal.getSemantics(), 1.0f);
1335 (void)Reciprocal.divide(FpVal, APFloat::rmNearestTiesToEven);
1336 Cvt = !Reciprocal.isDenormal();
1337 }
1338
1339 if (!Cvt)
Craig Topperf40110f2014-04-25 05:29:35 +00001340 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001341
1342 ConstantFP *R;
1343 R = ConstantFP::get(Dividend->getType()->getContext(), Reciprocal);
1344 return BinaryOperator::CreateFMul(Dividend, R);
1345}
1346
Frits van Bommel2a559512011-01-29 17:50:27 +00001347Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
1348 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1349
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001350 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001351 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001352
Craig Toppera4205622017-06-09 03:21:29 +00001353 if (Value *V = SimplifyFDivInst(Op0, Op1, I.getFastMathFlags(),
1354 SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001355 return replaceInstUsesWith(I, V);
Frits van Bommel2a559512011-01-29 17:50:27 +00001356
Stephen Lina9b57f62013-07-20 07:13:13 +00001357 if (isa<Constant>(Op0))
1358 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1359 if (Instruction *R = FoldOpIntoSelect(I, SI))
1360 return R;
1361
Sanjay Patel629c4112017-11-06 16:27:15 +00001362 bool AllowReassociate = I.isFast();
Shuxin Yang320f52a2013-01-14 22:48:41 +00001363 bool AllowReciprocal = I.hasAllowReciprocal();
Benjamin Kramer8564e0d2011-03-30 15:42:35 +00001364
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001365 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Stephen Lina9b57f62013-07-20 07:13:13 +00001366 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1367 if (Instruction *R = FoldOpIntoSelect(I, SI))
1368 return R;
1369
Shuxin Yang320f52a2013-01-14 22:48:41 +00001370 if (AllowReassociate) {
Craig Topperf40110f2014-04-25 05:29:35 +00001371 Constant *C1 = nullptr;
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001372 Constant *C2 = Op1C;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001373 Value *X;
Craig Topperf40110f2014-04-25 05:29:35 +00001374 Instruction *Res = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001375
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001376 if (match(Op0, m_FMul(m_Value(X), m_Constant(C1)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001377 // (X*C1)/C2 => X * (C1/C2)
1378 //
1379 Constant *C = ConstantExpr::getFDiv(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001380 if (isNormalFp(C))
Shuxin Yang320f52a2013-01-14 22:48:41 +00001381 Res = BinaryOperator::CreateFMul(X, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001382 } else if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001383 // (X/C1)/C2 => X /(C2*C1) [=> X * 1/(C2*C1) if reciprocal is allowed]
Shuxin Yang320f52a2013-01-14 22:48:41 +00001384 Constant *C = ConstantExpr::getFMul(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001385 if (isNormalFp(C)) {
1386 Res = CvtFDivConstToReciprocal(X, C, AllowReciprocal);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001387 if (!Res)
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001388 Res = BinaryOperator::CreateFDiv(X, C);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001389 }
1390 }
1391
1392 if (Res) {
1393 Res->setFastMathFlags(I.getFastMathFlags());
1394 return Res;
1395 }
1396 }
1397
1398 // X / C => X * 1/C
Owen Anderson4557a152014-01-16 21:07:52 +00001399 if (Instruction *T = CvtFDivConstToReciprocal(Op0, Op1C, AllowReciprocal)) {
1400 T->copyFastMathFlags(&I);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001401 return T;
Owen Anderson4557a152014-01-16 21:07:52 +00001402 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001403
Craig Topperf40110f2014-04-25 05:29:35 +00001404 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001405 }
1406
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001407 if (AllowReassociate && isa<Constant>(Op0)) {
1408 Constant *C1 = cast<Constant>(Op0), *C2;
Craig Topperf40110f2014-04-25 05:29:35 +00001409 Constant *Fold = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001410 Value *X;
1411 bool CreateDiv = true;
1412
1413 // C1 / (X*C2) => (C1/C2) / X
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001414 if (match(Op1, m_FMul(m_Value(X), m_Constant(C2))))
Shuxin Yang320f52a2013-01-14 22:48:41 +00001415 Fold = ConstantExpr::getFDiv(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001416 else if (match(Op1, m_FDiv(m_Value(X), m_Constant(C2)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001417 // C1 / (X/C2) => (C1*C2) / X
1418 Fold = ConstantExpr::getFMul(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001419 } else if (match(Op1, m_FDiv(m_Constant(C2), m_Value(X)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001420 // C1 / (C2/X) => (C1/C2) * X
1421 Fold = ConstantExpr::getFDiv(C1, C2);
1422 CreateDiv = false;
1423 }
1424
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001425 if (Fold && isNormalFp(Fold)) {
1426 Instruction *R = CreateDiv ? BinaryOperator::CreateFDiv(Fold, X)
1427 : BinaryOperator::CreateFMul(X, Fold);
1428 R->setFastMathFlags(I.getFastMathFlags());
1429 return R;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001430 }
Craig Topperf40110f2014-04-25 05:29:35 +00001431 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001432 }
1433
1434 if (AllowReassociate) {
1435 Value *X, *Y;
Craig Topperf40110f2014-04-25 05:29:35 +00001436 Value *NewInst = nullptr;
1437 Instruction *SimpR = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001438
1439 if (Op0->hasOneUse() && match(Op0, m_FDiv(m_Value(X), m_Value(Y)))) {
1440 // (X/Y) / Z => X / (Y*Z)
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001441 if (!isa<Constant>(Y) || !isa<Constant>(Op1)) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001442 NewInst = Builder.CreateFMul(Y, Op1);
Owen Anderson1664dc82014-01-20 07:44:53 +00001443 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1444 FastMathFlags Flags = I.getFastMathFlags();
1445 Flags &= cast<Instruction>(Op0)->getFastMathFlags();
1446 RI->setFastMathFlags(Flags);
1447 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001448 SimpR = BinaryOperator::CreateFDiv(X, NewInst);
1449 }
1450 } else if (Op1->hasOneUse() && match(Op1, m_FDiv(m_Value(X), m_Value(Y)))) {
1451 // Z / (X/Y) => Z*Y / X
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001452 if (!isa<Constant>(Y) || !isa<Constant>(Op0)) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001453 NewInst = Builder.CreateFMul(Op0, Y);
Owen Anderson1664dc82014-01-20 07:44:53 +00001454 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1455 FastMathFlags Flags = I.getFastMathFlags();
1456 Flags &= cast<Instruction>(Op1)->getFastMathFlags();
1457 RI->setFastMathFlags(Flags);
1458 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001459 SimpR = BinaryOperator::CreateFDiv(NewInst, X);
1460 }
1461 }
1462
1463 if (NewInst) {
1464 if (Instruction *T = dyn_cast<Instruction>(NewInst))
1465 T->setDebugLoc(I.getDebugLoc());
1466 SimpR->setFastMathFlags(I.getFastMathFlags());
1467 return SimpR;
Benjamin Kramer8564e0d2011-03-30 15:42:35 +00001468 }
1469 }
1470
Matt Arsenaultfdb78f82017-01-10 23:08:54 +00001471 Value *LHS;
1472 Value *RHS;
1473
1474 // -x / -y -> x / y
1475 if (match(Op0, m_FNeg(m_Value(LHS))) && match(Op1, m_FNeg(m_Value(RHS)))) {
1476 I.setOperand(0, LHS);
1477 I.setOperand(1, RHS);
1478 return &I;
1479 }
1480
Craig Topperf40110f2014-04-25 05:29:35 +00001481 return nullptr;
Frits van Bommel2a559512011-01-29 17:50:27 +00001482}
1483
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001484/// This function implements the transforms common to both integer remainder
1485/// instructions (urem and srem). It is called by the visitors to those integer
1486/// remainder instructions.
1487/// @brief Common integer remainder transforms
1488Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
1489 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1490
Chris Lattner7c99f192011-05-22 18:18:41 +00001491 // The RHS is known non-zero.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001492 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I)) {
Chris Lattner7c99f192011-05-22 18:18:41 +00001493 I.setOperand(1, V);
1494 return &I;
1495 }
1496
Duncan Sandsa3e36992011-05-02 16:27:02 +00001497 // Handle cases involving: rem X, (select Cond, Y, Z)
Sanjay Patelae2e3a42017-10-06 23:20:16 +00001498 if (simplifyDivRemOfSelectWithZeroOp(I))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001499 return &I;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001500
Benjamin Kramer72196f32014-01-19 15:24:22 +00001501 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001502 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1503 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1504 if (Instruction *R = FoldOpIntoSelect(I, SI))
1505 return R;
Craig Topperfb71b7d2017-04-14 19:20:12 +00001506 } else if (auto *PN = dyn_cast<PHINode>(Op0I)) {
Sanjoy Dasb7e861a2016-06-05 21:17:04 +00001507 const APInt *Op1Int;
1508 if (match(Op1, m_APInt(Op1Int)) && !Op1Int->isMinValue() &&
1509 (I.getOpcode() == Instruction::URem ||
1510 !Op1Int->isMinSignedValue())) {
Craig Topperfb71b7d2017-04-14 19:20:12 +00001511 // foldOpIntoPhi will speculate instructions to the end of the PHI's
Sanjoy Dasb7e861a2016-06-05 21:17:04 +00001512 // predecessor blocks, so do this only if we know the srem or urem
1513 // will not fault.
Craig Topperfb71b7d2017-04-14 19:20:12 +00001514 if (Instruction *NV = foldOpIntoPhi(I, PN))
Sanjoy Dasb7e861a2016-06-05 21:17:04 +00001515 return NV;
1516 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001517 }
1518
1519 // See if we can fold away this rem instruction.
1520 if (SimplifyDemandedInstructionBits(I))
1521 return &I;
1522 }
1523 }
1524
Craig Topperf40110f2014-04-25 05:29:35 +00001525 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001526}
1527
1528Instruction *InstCombiner::visitURem(BinaryOperator &I) {
1529 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1530
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001531 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001532 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001533
Craig Toppera4205622017-06-09 03:21:29 +00001534 if (Value *V = SimplifyURemInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001535 return replaceInstUsesWith(I, V);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001536
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001537 if (Instruction *common = commonIRemTransforms(I))
1538 return common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001539
Sanjay Patelbb789382017-08-24 22:54:01 +00001540 if (Instruction *NarrowRem = narrowUDivURem(I, Builder))
1541 return NarrowRem;
David Majnemer6c30f492013-05-12 00:07:05 +00001542
David Majnemer470b0772013-05-11 09:01:28 +00001543 // X urem Y -> X and Y-1, where Y is a power of 2,
Craig Topperd4039f72017-05-25 21:51:12 +00001544 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/ true, 0, &I)) {
Chris Lattner6b657ae2011-02-10 05:36:31 +00001545 Constant *N1 = Constant::getAllOnesValue(I.getType());
Craig Topperbb4069e2017-07-07 23:16:26 +00001546 Value *Add = Builder.CreateAdd(Op1, N1);
Chris Lattner6b657ae2011-02-10 05:36:31 +00001547 return BinaryOperator::CreateAnd(Op0, Add);
1548 }
1549
Nick Lewycky7459be62013-07-13 01:16:47 +00001550 // 1 urem X -> zext(X != 1)
1551 if (match(Op0, m_One())) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001552 Value *Cmp = Builder.CreateICmpNE(Op1, Op0);
1553 Value *Ext = Builder.CreateZExt(Cmp, I.getType());
Sanjay Patel4b198802016-02-01 22:23:39 +00001554 return replaceInstUsesWith(I, Ext);
Nick Lewycky7459be62013-07-13 01:16:47 +00001555 }
1556
Sanjay Patel30ef70b2016-09-22 22:36:26 +00001557 // X urem C -> X < C ? X : X - C, where C >= signbit.
1558 const APInt *DivisorC;
1559 if (match(Op1, m_APInt(DivisorC)) && DivisorC->isNegative()) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001560 Value *Cmp = Builder.CreateICmpULT(Op0, Op1);
1561 Value *Sub = Builder.CreateSub(Op0, Op1);
Sanjay Patel30ef70b2016-09-22 22:36:26 +00001562 return SelectInst::Create(Cmp, Op0, Sub);
1563 }
1564
Craig Topperf40110f2014-04-25 05:29:35 +00001565 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001566}
1567
1568Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
1569 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1570
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001571 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001572 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001573
Craig Toppera4205622017-06-09 03:21:29 +00001574 if (Value *V = SimplifySRemInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001575 return replaceInstUsesWith(I, V);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001576
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001577 // Handle the integer rem common cases
1578 if (Instruction *Common = commonIRemTransforms(I))
1579 return Common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001580
David Majnemerdb077302014-10-13 22:37:51 +00001581 {
1582 const APInt *Y;
1583 // X % -Y -> X % Y
1584 if (match(Op1, m_APInt(Y)) && Y->isNegative() && !Y->isMinSignedValue()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001585 Worklist.AddValue(I.getOperand(1));
David Majnemerdb077302014-10-13 22:37:51 +00001586 I.setOperand(1, ConstantInt::get(I.getType(), -*Y));
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001587 return &I;
1588 }
David Majnemerdb077302014-10-13 22:37:51 +00001589 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001590
1591 // If the sign bits of both operands are zero (i.e. we can prove they are
1592 // unsigned inputs), turn this into a urem.
Craig Topperbcfd2d12017-04-20 16:56:25 +00001593 APInt Mask(APInt::getSignMask(I.getType()->getScalarSizeInBits()));
Craig Topper1a18a7c2017-04-17 01:51:24 +00001594 if (MaskedValueIsZero(Op1, Mask, 0, &I) &&
1595 MaskedValueIsZero(Op0, Mask, 0, &I)) {
1596 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
1597 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001598 }
1599
1600 // If it's a constant vector, flip any negative values positive.
Chris Lattner0256be92012-01-27 03:08:05 +00001601 if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
1602 Constant *C = cast<Constant>(Op1);
1603 unsigned VWidth = C->getType()->getVectorNumElements();
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001604
1605 bool hasNegative = false;
Chris Lattner0256be92012-01-27 03:08:05 +00001606 bool hasMissing = false;
1607 for (unsigned i = 0; i != VWidth; ++i) {
1608 Constant *Elt = C->getAggregateElement(i);
Craig Topperf40110f2014-04-25 05:29:35 +00001609 if (!Elt) {
Chris Lattner0256be92012-01-27 03:08:05 +00001610 hasMissing = true;
1611 break;
1612 }
1613
1614 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
Chris Lattnerb1a15122011-07-15 06:08:15 +00001615 if (RHS->isNegative())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001616 hasNegative = true;
Chris Lattner0256be92012-01-27 03:08:05 +00001617 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001618
Chris Lattner0256be92012-01-27 03:08:05 +00001619 if (hasNegative && !hasMissing) {
Chris Lattner47a86bd2012-01-25 06:02:56 +00001620 SmallVector<Constant *, 16> Elts(VWidth);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001621 for (unsigned i = 0; i != VWidth; ++i) {
Chris Lattner8213c8a2012-02-06 21:56:39 +00001622 Elts[i] = C->getAggregateElement(i); // Handle undef, etc.
Chris Lattner0256be92012-01-27 03:08:05 +00001623 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
Chris Lattnerb1a15122011-07-15 06:08:15 +00001624 if (RHS->isNegative())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001625 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001626 }
1627 }
1628
1629 Constant *NewRHSV = ConstantVector::get(Elts);
Chris Lattner0256be92012-01-27 03:08:05 +00001630 if (NewRHSV != C) { // Don't loop on -MININT
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001631 Worklist.AddValue(I.getOperand(1));
1632 I.setOperand(1, NewRHSV);
1633 return &I;
1634 }
1635 }
1636 }
1637
Craig Topperf40110f2014-04-25 05:29:35 +00001638 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001639}
1640
1641Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Duncan Sandsa3e36992011-05-02 16:27:02 +00001642 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001643
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001644 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001645 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001646
Craig Toppera4205622017-06-09 03:21:29 +00001647 if (Value *V = SimplifyFRemInst(Op0, Op1, I.getFastMathFlags(),
1648 SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001649 return replaceInstUsesWith(I, V);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001650
Craig Topperf40110f2014-04-25 05:29:35 +00001651 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001652}