blob: 6e7e11a15aea3f477b3c491c2a0ec32f0eb0d580 [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"
Dmitry Venikove5fbf592018-01-11 06:33:00 +000036#include "llvm/Transforms/Utils/BuildLibCalls.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000037#include <cassert>
38#include <cstddef>
39#include <cstdint>
40#include <utility>
41
Chris Lattnerdc054bf2010-01-05 06:09:35 +000042using namespace llvm;
43using namespace PatternMatch;
44
Chandler Carruth964daaa2014-04-22 02:55:47 +000045#define DEBUG_TYPE "instcombine"
46
Sanjay Patel6eccf482015-09-09 15:24:36 +000047/// The specific integer value is used in a context where it is known to be
48/// non-zero. If this allows us to simplify the computation, do so and return
49/// the new operand, otherwise return null.
Hal Finkel60db0582014-09-07 18:57:58 +000050static Value *simplifyValueKnownNonZero(Value *V, InstCombiner &IC,
Mehdi Aminia28d91d2015-03-10 02:37:25 +000051 Instruction &CxtI) {
Chris Lattner7c99f192011-05-22 18:18:41 +000052 // If V has multiple uses, then we would have to do more analysis to determine
53 // if this is safe. For example, the use could be in dynamically unreached
54 // code.
Craig Topperf40110f2014-04-25 05:29:35 +000055 if (!V->hasOneUse()) return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +000056
Chris Lattner388cb8a2011-05-23 00:32:19 +000057 bool MadeChange = false;
58
Chris Lattner7c99f192011-05-22 18:18:41 +000059 // ((1 << A) >>u B) --> (1 << (A-B))
60 // Because V cannot be zero, we know that B is less than A.
David Majnemerdad21032014-10-14 20:28:40 +000061 Value *A = nullptr, *B = nullptr, *One = nullptr;
62 if (match(V, m_LShr(m_OneUse(m_Shl(m_Value(One), m_Value(A))), m_Value(B))) &&
63 match(One, m_One())) {
Craig Topperbb4069e2017-07-07 23:16:26 +000064 A = IC.Builder.CreateSub(A, B);
65 return IC.Builder.CreateShl(One, A);
Chris Lattner7c99f192011-05-22 18:18:41 +000066 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000067
Chris Lattner388cb8a2011-05-23 00:32:19 +000068 // (PowerOfTwo >>u B) --> isExact since shifting out the result would make it
69 // inexact. Similarly for <<.
Sanjay Patela8ef4a52016-05-22 17:08:52 +000070 BinaryOperator *I = dyn_cast<BinaryOperator>(V);
71 if (I && I->isLogicalShift() &&
Craig Topperd4039f72017-05-25 21:51:12 +000072 IC.isKnownToBeAPowerOfTwo(I->getOperand(0), false, 0, &CxtI)) {
Sanjay Patela8ef4a52016-05-22 17:08:52 +000073 // We know that this is an exact/nuw shift and that the input is a
74 // non-zero context as well.
75 if (Value *V2 = simplifyValueKnownNonZero(I->getOperand(0), IC, CxtI)) {
76 I->setOperand(0, V2);
77 MadeChange = true;
Chris Lattner388cb8a2011-05-23 00:32:19 +000078 }
79
Sanjay Patela8ef4a52016-05-22 17:08:52 +000080 if (I->getOpcode() == Instruction::LShr && !I->isExact()) {
81 I->setIsExact();
82 MadeChange = true;
83 }
84
85 if (I->getOpcode() == Instruction::Shl && !I->hasNoUnsignedWrap()) {
86 I->setHasNoUnsignedWrap();
87 MadeChange = true;
88 }
89 }
90
Chris Lattner162dfc32011-05-22 18:26:48 +000091 // TODO: Lots more we could do here:
Chris Lattner162dfc32011-05-22 18:26:48 +000092 // If V is a phi node, we can call this on each of its operands.
93 // "select cond, X, 0" can simplify to "X".
Jim Grosbachbdbd7342013-04-05 21:20:12 +000094
Craig Topperf40110f2014-04-25 05:29:35 +000095 return MadeChange ? V : nullptr;
Chris Lattner7c99f192011-05-22 18:18:41 +000096}
97
Sanjay Patel6eccf482015-09-09 15:24:36 +000098/// True if the multiply can not be expressed in an int this size.
David Majnemer27adb122014-10-12 08:34:24 +000099static bool MultiplyOverflows(const APInt &C1, const APInt &C2, APInt &Product,
100 bool IsSigned) {
101 bool Overflow;
102 if (IsSigned)
103 Product = C1.smul_ov(C2, Overflow);
104 else
105 Product = C1.umul_ov(C2, Overflow);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000106
David Majnemer27adb122014-10-12 08:34:24 +0000107 return Overflow;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000108}
109
David Majnemerf9a095d2014-08-16 08:55:06 +0000110/// \brief True if C2 is a multiple of C1. Quotient contains C2/C1.
111static bool IsMultiple(const APInt &C1, const APInt &C2, APInt &Quotient,
112 bool IsSigned) {
113 assert(C1.getBitWidth() == C2.getBitWidth() &&
114 "Inconsistent width of constants!");
115
David Majnemer135ca402015-09-06 06:49:59 +0000116 // Bail if we will divide by zero.
117 if (C2.isMinValue())
118 return false;
119
120 // Bail if we would divide INT_MIN by -1.
121 if (IsSigned && C1.isMinSignedValue() && C2.isAllOnesValue())
122 return false;
123
David Majnemerf9a095d2014-08-16 08:55:06 +0000124 APInt Remainder(C1.getBitWidth(), /*Val=*/0ULL, IsSigned);
125 if (IsSigned)
126 APInt::sdivrem(C1, C2, Quotient, Remainder);
127 else
128 APInt::udivrem(C1, C2, Quotient, Remainder);
129
130 return Remainder.isMinValue();
131}
132
Rafael Espindola65281bf2013-05-31 14:27:15 +0000133/// \brief A helper routine of InstCombiner::visitMul().
134///
135/// If C is a vector of known powers of 2, then this function returns
136/// a new vector obtained from C replacing each element with its logBase2.
137/// Return a null pointer otherwise.
138static Constant *getLogBase2Vector(ConstantDataVector *CV) {
139 const APInt *IVal;
140 SmallVector<Constant *, 4> Elts;
141
142 for (unsigned I = 0, E = CV->getNumElements(); I != E; ++I) {
143 Constant *Elt = CV->getElementAsConstant(I);
144 if (!match(Elt, m_APInt(IVal)) || !IVal->isPowerOf2())
Craig Topperf40110f2014-04-25 05:29:35 +0000145 return nullptr;
Rafael Espindola65281bf2013-05-31 14:27:15 +0000146 Elts.push_back(ConstantInt::get(Elt->getType(), IVal->logBase2()));
147 }
148
149 return ConstantVector::get(Elts);
150}
151
David Majnemer54c2ca22014-12-26 09:10:14 +0000152/// \brief Return true if we can prove that:
153/// (mul LHS, RHS) === (mul nsw LHS, RHS)
Craig Topper2b1fc322017-05-22 06:25:31 +0000154bool InstCombiner::willNotOverflowSignedMul(const Value *LHS,
155 const Value *RHS,
156 const Instruction &CxtI) const {
David Majnemer54c2ca22014-12-26 09:10:14 +0000157 // Multiplying n * m significant bits yields a result of n + m significant
158 // bits. If the total number of significant bits does not exceed the
159 // result bit width (minus 1), there is no overflow.
160 // This means if we have enough leading sign bits in the operands
161 // we can guarantee that the result does not overflow.
162 // Ref: "Hacker's Delight" by Henry Warren
163 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
164
165 // Note that underestimating the number of sign bits gives a more
166 // conservative answer.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000167 unsigned SignBits =
168 ComputeNumSignBits(LHS, 0, &CxtI) + ComputeNumSignBits(RHS, 0, &CxtI);
David Majnemer54c2ca22014-12-26 09:10:14 +0000169
170 // First handle the easy case: if we have enough sign bits there's
171 // definitely no overflow.
172 if (SignBits > BitWidth + 1)
173 return true;
174
175 // There are two ambiguous cases where there can be no overflow:
176 // SignBits == BitWidth + 1 and
177 // SignBits == BitWidth
178 // The second case is difficult to check, therefore we only handle the
179 // first case.
180 if (SignBits == BitWidth + 1) {
181 // It overflows only when both arguments are negative and the true
182 // product is exactly the minimum negative number.
183 // E.g. mul i16 with 17 sign bits: 0xff00 * 0xff80 = 0x8000
184 // For simplicity we just check if at least one side is not negative.
Craig Topper1a36b7d2017-05-15 06:39:41 +0000185 KnownBits LHSKnown = computeKnownBits(LHS, /*Depth=*/0, &CxtI);
186 KnownBits RHSKnown = computeKnownBits(RHS, /*Depth=*/0, &CxtI);
187 if (LHSKnown.isNonNegative() || RHSKnown.isNonNegative())
David Majnemer54c2ca22014-12-26 09:10:14 +0000188 return true;
189 }
190 return false;
191}
192
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000193Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +0000194 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000195 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
196
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000197 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +0000198 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000199
Craig Toppera4205622017-06-09 03:21:29 +0000200 if (Value *V = SimplifyMulInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +0000201 return replaceInstUsesWith(I, V);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000202
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000203 if (Value *V = SimplifyUsingDistributiveLaws(I))
Sanjay Patel4b198802016-02-01 22:23:39 +0000204 return replaceInstUsesWith(I, V);
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000205
David Majnemer027bc802014-11-22 04:52:38 +0000206 // X * -1 == 0 - X
207 if (match(Op1, m_AllOnes())) {
208 BinaryOperator *BO = BinaryOperator::CreateNeg(Op0, I.getName());
209 if (I.hasNoSignedWrap())
210 BO->setHasNoSignedWrap();
211 return BO;
212 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000213
Rafael Espindola65281bf2013-05-31 14:27:15 +0000214 // Also allow combining multiply instructions on vectors.
215 {
216 Value *NewOp;
217 Constant *C1, *C2;
218 const APInt *IVal;
219 if (match(&I, m_Mul(m_Shl(m_Value(NewOp), m_Constant(C2)),
220 m_Constant(C1))) &&
David Majnemerfd4a6d22014-11-22 04:52:52 +0000221 match(C1, m_APInt(IVal))) {
222 // ((X << C2)*C1) == (X * (C1 << C2))
223 Constant *Shl = ConstantExpr::getShl(C1, C2);
224 BinaryOperator *Mul = cast<BinaryOperator>(I.getOperand(0));
225 BinaryOperator *BO = BinaryOperator::CreateMul(NewOp, Shl);
226 if (I.hasNoUnsignedWrap() && Mul->hasNoUnsignedWrap())
227 BO->setHasNoUnsignedWrap();
228 if (I.hasNoSignedWrap() && Mul->hasNoSignedWrap() &&
229 Shl->isNotMinSignedValue())
230 BO->setHasNoSignedWrap();
231 return BO;
232 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000233
Rafael Espindola65281bf2013-05-31 14:27:15 +0000234 if (match(&I, m_Mul(m_Value(NewOp), m_Constant(C1)))) {
Craig Topperf40110f2014-04-25 05:29:35 +0000235 Constant *NewCst = nullptr;
Rafael Espindola65281bf2013-05-31 14:27:15 +0000236 if (match(C1, m_APInt(IVal)) && IVal->isPowerOf2())
237 // Replace X*(2^C) with X << C, where C is either a scalar or a splat.
238 NewCst = ConstantInt::get(NewOp->getType(), IVal->logBase2());
239 else if (ConstantDataVector *CV = dyn_cast<ConstantDataVector>(C1))
240 // Replace X*(2^C) with X << C, where C is a vector of known
241 // constant powers of 2.
242 NewCst = getLogBase2Vector(CV);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000243
Rafael Espindola65281bf2013-05-31 14:27:15 +0000244 if (NewCst) {
David Majnemer45951a62015-04-18 04:41:30 +0000245 unsigned Width = NewCst->getType()->getPrimitiveSizeInBits();
Rafael Espindola65281bf2013-05-31 14:27:15 +0000246 BinaryOperator *Shl = BinaryOperator::CreateShl(NewOp, NewCst);
Tilmann Scheller2bc5cb62014-10-07 10:19:34 +0000247
Tilmann Scheller2bc5cb62014-10-07 10:19:34 +0000248 if (I.hasNoUnsignedWrap())
249 Shl->setHasNoUnsignedWrap();
David Majnemer45951a62015-04-18 04:41:30 +0000250 if (I.hasNoSignedWrap()) {
Craig Topper5fe01972017-06-27 19:57:53 +0000251 const APInt *V;
252 if (match(NewCst, m_APInt(V)) && *V != Width - 1)
David Majnemer45951a62015-04-18 04:41:30 +0000253 Shl->setHasNoSignedWrap();
254 }
Tilmann Scheller2bc5cb62014-10-07 10:19:34 +0000255
Rafael Espindola65281bf2013-05-31 14:27:15 +0000256 return Shl;
257 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000258 }
Rafael Espindola65281bf2013-05-31 14:27:15 +0000259 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000260
Rafael Espindola65281bf2013-05-31 14:27:15 +0000261 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Stuart Hastings23804832011-06-01 16:42:47 +0000262 // (Y - X) * (-(2**n)) -> (X - Y) * (2**n), for positive nonzero n
263 // (Y + const) * (-(2**n)) -> (-constY) * (2**n), for positive nonzero n
264 // The "* (2**n)" thus becomes a potential shifting opportunity.
Stuart Hastings82843742011-05-30 20:00:33 +0000265 {
266 const APInt & Val = CI->getValue();
267 const APInt &PosVal = Val.abs();
268 if (Val.isNegative() && PosVal.isPowerOf2()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000269 Value *X = nullptr, *Y = nullptr;
Stuart Hastings23804832011-06-01 16:42:47 +0000270 if (Op0->hasOneUse()) {
271 ConstantInt *C1;
Craig Topperf40110f2014-04-25 05:29:35 +0000272 Value *Sub = nullptr;
Stuart Hastings23804832011-06-01 16:42:47 +0000273 if (match(Op0, m_Sub(m_Value(Y), m_Value(X))))
Craig Topperbb4069e2017-07-07 23:16:26 +0000274 Sub = Builder.CreateSub(X, Y, "suba");
Stuart Hastings23804832011-06-01 16:42:47 +0000275 else if (match(Op0, m_Add(m_Value(Y), m_ConstantInt(C1))))
Craig Topperbb4069e2017-07-07 23:16:26 +0000276 Sub = Builder.CreateSub(Builder.CreateNeg(C1), Y, "subc");
Stuart Hastings23804832011-06-01 16:42:47 +0000277 if (Sub)
278 return
279 BinaryOperator::CreateMul(Sub,
280 ConstantInt::get(Y->getType(), PosVal));
Stuart Hastings82843742011-05-30 20:00:33 +0000281 }
282 }
283 }
Chris Lattner6b657ae2011-02-10 05:36:31 +0000284 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000285
Chris Lattner6b657ae2011-02-10 05:36:31 +0000286 // Simplify mul instructions with a constant RHS.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000287 if (isa<Constant>(Op1)) {
Sanjay Pateldb0938f2017-01-10 23:49:07 +0000288 if (Instruction *FoldedMul = foldOpWithConstantIntoOperand(I))
289 return FoldedMul;
Benjamin Kramer72196f32014-01-19 15:24:22 +0000290
291 // Canonicalize (X+C1)*CI -> X*CI+C1*CI.
292 {
293 Value *X;
294 Constant *C1;
295 if (match(Op0, m_OneUse(m_Add(m_Value(X), m_Constant(C1))))) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000296 Value *Mul = Builder.CreateMul(C1, Op1);
David Majnemer6cf6c052014-06-19 07:14:33 +0000297 // Only go forward with the transform if C1*CI simplifies to a tidier
298 // constant.
299 if (!match(Mul, m_Mul(m_Value(), m_Value())))
Craig Topperbb4069e2017-07-07 23:16:26 +0000300 return BinaryOperator::CreateAdd(Builder.CreateMul(X, Op1), Mul);
Benjamin Kramer72196f32014-01-19 15:24:22 +0000301 }
302 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000303 }
304
David Majnemer8279a7502014-11-22 07:25:19 +0000305 if (Value *Op0v = dyn_castNegVal(Op0)) { // -X * -Y = X*Y
306 if (Value *Op1v = dyn_castNegVal(Op1)) {
307 BinaryOperator *BO = BinaryOperator::CreateMul(Op0v, Op1v);
308 if (I.hasNoSignedWrap() &&
309 match(Op0, m_NSWSub(m_Value(), m_Value())) &&
310 match(Op1, m_NSWSub(m_Value(), m_Value())))
311 BO->setHasNoSignedWrap();
312 return BO;
313 }
314 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000315
316 // (X / Y) * Y = X - (X % Y)
317 // (X / Y) * -Y = (X % Y) - X
318 {
Sanjay Patela0a56822017-03-14 17:27:27 +0000319 Value *Y = Op1;
320 BinaryOperator *Div = dyn_cast<BinaryOperator>(Op0);
321 if (!Div || (Div->getOpcode() != Instruction::UDiv &&
322 Div->getOpcode() != Instruction::SDiv)) {
323 Y = Op0;
324 Div = dyn_cast<BinaryOperator>(Op1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000325 }
Sanjay Patela0a56822017-03-14 17:27:27 +0000326 Value *Neg = dyn_castNegVal(Y);
327 if (Div && Div->hasOneUse() &&
328 (Div->getOperand(1) == Y || Div->getOperand(1) == Neg) &&
329 (Div->getOpcode() == Instruction::UDiv ||
330 Div->getOpcode() == Instruction::SDiv)) {
331 Value *X = Div->getOperand(0), *DivOp1 = Div->getOperand(1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000332
Chris Lattner35315d02011-02-06 21:44:57 +0000333 // If the division is exact, X % Y is zero, so we end up with X or -X.
Sanjay Patela0a56822017-03-14 17:27:27 +0000334 if (Div->isExact()) {
335 if (DivOp1 == Y)
336 return replaceInstUsesWith(I, X);
337 return BinaryOperator::CreateNeg(X);
338 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000339
Sanjay Patela0a56822017-03-14 17:27:27 +0000340 auto RemOpc = Div->getOpcode() == Instruction::UDiv ? Instruction::URem
341 : Instruction::SRem;
Craig Topperbb4069e2017-07-07 23:16:26 +0000342 Value *Rem = Builder.CreateBinOp(RemOpc, X, DivOp1);
Sanjay Patela0a56822017-03-14 17:27:27 +0000343 if (DivOp1 == Y)
344 return BinaryOperator::CreateSub(X, Rem);
345 return BinaryOperator::CreateSub(Rem, X);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000346 }
347 }
348
349 /// i1 mul -> i1 and.
Craig Topperfde47232017-07-09 07:04:03 +0000350 if (I.getType()->isIntOrIntVectorTy(1))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000351 return BinaryOperator::CreateAnd(Op0, Op1);
352
353 // X*(1 << Y) --> X << Y
354 // (1 << Y)*X --> X << Y
355 {
356 Value *Y;
David Majnemer546f8102014-11-22 08:57:02 +0000357 BinaryOperator *BO = nullptr;
358 bool ShlNSW = false;
359 if (match(Op0, m_Shl(m_One(), m_Value(Y)))) {
360 BO = BinaryOperator::CreateShl(Op1, Y);
David Majnemer087dc8b2015-01-04 07:36:02 +0000361 ShlNSW = cast<ShlOperator>(Op0)->hasNoSignedWrap();
David Majnemer8e6f6a92014-11-24 16:41:13 +0000362 } else if (match(Op1, m_Shl(m_One(), m_Value(Y)))) {
David Majnemer546f8102014-11-22 08:57:02 +0000363 BO = BinaryOperator::CreateShl(Op0, Y);
David Majnemer087dc8b2015-01-04 07:36:02 +0000364 ShlNSW = cast<ShlOperator>(Op1)->hasNoSignedWrap();
David Majnemer546f8102014-11-22 08:57:02 +0000365 }
366 if (BO) {
367 if (I.hasNoUnsignedWrap())
368 BO->setHasNoUnsignedWrap();
369 if (I.hasNoSignedWrap() && ShlNSW)
370 BO->setHasNoSignedWrap();
371 return BO;
372 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000373 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000374
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000375 // If one of the operands of the multiply is a cast from a boolean value, then
376 // we know the bool is either zero or one, so this is a 'masking' multiply.
377 // X * Y (where Y is 0 or 1) -> X & (0-Y)
Duncan Sands19d0b472010-02-16 11:11:14 +0000378 if (!I.getType()->isVectorTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000379 // -2 is "-1 << 1" so it is all bits set except the low one.
380 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000381
Craig Topperf40110f2014-04-25 05:29:35 +0000382 Value *BoolCast = nullptr, *OtherOp = nullptr;
Richard Trieu7a083812016-02-18 22:09:30 +0000383 if (MaskedValueIsZero(Op0, Negative2, 0, &I)) {
384 BoolCast = Op0;
385 OtherOp = Op1;
386 } else if (MaskedValueIsZero(Op1, Negative2, 0, &I)) {
387 BoolCast = Op1;
388 OtherOp = Op0;
389 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000390
391 if (BoolCast) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000392 Value *V = Builder.CreateSub(Constant::getNullValue(I.getType()),
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000393 BoolCast);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000394 return BinaryOperator::CreateAnd(V, OtherOp);
395 }
396 }
397
David Majnemera1cfd7c2016-12-30 00:28:58 +0000398 // Check for (mul (sext x), y), see if we can merge this into an
399 // integer mul followed by a sext.
400 if (SExtInst *Op0Conv = dyn_cast<SExtInst>(Op0)) {
401 // (mul (sext x), cst) --> (sext (mul x, cst'))
402 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
403 if (Op0Conv->hasOneUse()) {
404 Constant *CI =
405 ConstantExpr::getTrunc(Op1C, Op0Conv->getOperand(0)->getType());
406 if (ConstantExpr::getSExt(CI, I.getType()) == Op1C &&
Craig Topper2b1fc322017-05-22 06:25:31 +0000407 willNotOverflowSignedMul(Op0Conv->getOperand(0), CI, I)) {
David Majnemera1cfd7c2016-12-30 00:28:58 +0000408 // Insert the new, smaller mul.
409 Value *NewMul =
Craig Topperbb4069e2017-07-07 23:16:26 +0000410 Builder.CreateNSWMul(Op0Conv->getOperand(0), CI, "mulconv");
David Majnemera1cfd7c2016-12-30 00:28:58 +0000411 return new SExtInst(NewMul, I.getType());
412 }
413 }
414 }
415
416 // (mul (sext x), (sext y)) --> (sext (mul int x, y))
417 if (SExtInst *Op1Conv = dyn_cast<SExtInst>(Op1)) {
418 // Only do this if x/y have the same type, if at last one of them has a
419 // single use (so we don't increase the number of sexts), and if the
420 // integer mul will not overflow.
421 if (Op0Conv->getOperand(0)->getType() ==
422 Op1Conv->getOperand(0)->getType() &&
423 (Op0Conv->hasOneUse() || Op1Conv->hasOneUse()) &&
Craig Topper2b1fc322017-05-22 06:25:31 +0000424 willNotOverflowSignedMul(Op0Conv->getOperand(0),
David Majnemera1cfd7c2016-12-30 00:28:58 +0000425 Op1Conv->getOperand(0), I)) {
426 // Insert the new integer mul.
Craig Topperbb4069e2017-07-07 23:16:26 +0000427 Value *NewMul = Builder.CreateNSWMul(
David Majnemera1cfd7c2016-12-30 00:28:58 +0000428 Op0Conv->getOperand(0), Op1Conv->getOperand(0), "mulconv");
429 return new SExtInst(NewMul, I.getType());
430 }
431 }
432 }
433
434 // Check for (mul (zext x), y), see if we can merge this into an
435 // integer mul followed by a zext.
436 if (auto *Op0Conv = dyn_cast<ZExtInst>(Op0)) {
437 // (mul (zext x), cst) --> (zext (mul x, cst'))
438 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
439 if (Op0Conv->hasOneUse()) {
440 Constant *CI =
441 ConstantExpr::getTrunc(Op1C, Op0Conv->getOperand(0)->getType());
442 if (ConstantExpr::getZExt(CI, I.getType()) == Op1C &&
Craig Topperbb973722017-05-15 02:44:08 +0000443 willNotOverflowUnsignedMul(Op0Conv->getOperand(0), CI, I)) {
David Majnemera1cfd7c2016-12-30 00:28:58 +0000444 // Insert the new, smaller mul.
445 Value *NewMul =
Craig Topperbb4069e2017-07-07 23:16:26 +0000446 Builder.CreateNUWMul(Op0Conv->getOperand(0), CI, "mulconv");
David Majnemera1cfd7c2016-12-30 00:28:58 +0000447 return new ZExtInst(NewMul, I.getType());
448 }
449 }
450 }
451
452 // (mul (zext x), (zext y)) --> (zext (mul int x, y))
453 if (auto *Op1Conv = dyn_cast<ZExtInst>(Op1)) {
454 // Only do this if x/y have the same type, if at last one of them has a
455 // single use (so we don't increase the number of zexts), and if the
456 // integer mul will not overflow.
457 if (Op0Conv->getOperand(0)->getType() ==
458 Op1Conv->getOperand(0)->getType() &&
459 (Op0Conv->hasOneUse() || Op1Conv->hasOneUse()) &&
Craig Topperbb973722017-05-15 02:44:08 +0000460 willNotOverflowUnsignedMul(Op0Conv->getOperand(0),
461 Op1Conv->getOperand(0), I)) {
David Majnemera1cfd7c2016-12-30 00:28:58 +0000462 // Insert the new integer mul.
Craig Topperbb4069e2017-07-07 23:16:26 +0000463 Value *NewMul = Builder.CreateNUWMul(
David Majnemera1cfd7c2016-12-30 00:28:58 +0000464 Op0Conv->getOperand(0), Op1Conv->getOperand(0), "mulconv");
465 return new ZExtInst(NewMul, I.getType());
466 }
467 }
468 }
469
Craig Topper2b1fc322017-05-22 06:25:31 +0000470 if (!I.hasNoSignedWrap() && willNotOverflowSignedMul(Op0, Op1, I)) {
David Majnemer54c2ca22014-12-26 09:10:14 +0000471 Changed = true;
472 I.setHasNoSignedWrap(true);
473 }
474
Craig Topperbb973722017-05-15 02:44:08 +0000475 if (!I.hasNoUnsignedWrap() && willNotOverflowUnsignedMul(Op0, Op1, I)) {
David Majnemerb1296ec2014-12-26 09:50:35 +0000476 Changed = true;
477 I.setHasNoUnsignedWrap(true);
478 }
479
Craig Topperf40110f2014-04-25 05:29:35 +0000480 return Changed ? &I : nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000481}
482
Sanjay Patel17045f72014-10-14 00:33:23 +0000483/// Detect pattern log2(Y * 0.5) with corresponding fast math flags.
Pedro Artigas993acd02012-11-30 22:07:05 +0000484static void detectLog2OfHalf(Value *&Op, Value *&Y, IntrinsicInst *&Log2) {
Sanjay Patel17045f72014-10-14 00:33:23 +0000485 if (!Op->hasOneUse())
486 return;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000487
Sanjay Patel17045f72014-10-14 00:33:23 +0000488 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op);
489 if (!II)
490 return;
Sanjay Patel629c4112017-11-06 16:27:15 +0000491 if (II->getIntrinsicID() != Intrinsic::log2 || !II->isFast())
Sanjay Patel17045f72014-10-14 00:33:23 +0000492 return;
493 Log2 = II;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000494
Sanjay Patel17045f72014-10-14 00:33:23 +0000495 Value *OpLog2Of = II->getArgOperand(0);
496 if (!OpLog2Of->hasOneUse())
497 return;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000498
Sanjay Patel17045f72014-10-14 00:33:23 +0000499 Instruction *I = dyn_cast<Instruction>(OpLog2Of);
500 if (!I)
501 return;
Sanjay Patel629c4112017-11-06 16:27:15 +0000502
503 if (I->getOpcode() != Instruction::FMul || !I->isFast())
Sanjay Patel17045f72014-10-14 00:33:23 +0000504 return;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000505
Sanjay Patel17045f72014-10-14 00:33:23 +0000506 if (match(I->getOperand(0), m_SpecificFP(0.5)))
507 Y = I->getOperand(1);
508 else if (match(I->getOperand(1), m_SpecificFP(0.5)))
509 Y = I->getOperand(0);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000510}
Pedro Artigas993acd02012-11-30 22:07:05 +0000511
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000512static bool isFiniteNonZeroFp(Constant *C) {
513 if (C->getType()->isVectorTy()) {
514 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
515 ++I) {
Michael Kupersteinbcb26d62015-03-05 08:38:57 +0000516 ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(C->getAggregateElement(I));
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000517 if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
518 return false;
519 }
520 return true;
521 }
522
523 return isa<ConstantFP>(C) &&
524 cast<ConstantFP>(C)->getValueAPF().isFiniteNonZero();
525}
526
527static bool isNormalFp(Constant *C) {
528 if (C->getType()->isVectorTy()) {
529 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
530 ++I) {
Michael Kupersteinbcb26d62015-03-05 08:38:57 +0000531 ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(C->getAggregateElement(I));
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000532 if (!CFP || !CFP->getValueAPF().isNormal())
533 return false;
534 }
535 return true;
536 }
537
538 return isa<ConstantFP>(C) && cast<ConstantFP>(C)->getValueAPF().isNormal();
539}
540
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000541/// Helper function of InstCombiner::visitFMul(BinaryOperator(). It returns
542/// true iff the given value is FMul or FDiv with one and only one operand
543/// being a normal constant (i.e. not Zero/NaN/Infinity).
544static bool isFMulOrFDivWithConstant(Value *V) {
545 Instruction *I = dyn_cast<Instruction>(V);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000546 if (!I || (I->getOpcode() != Instruction::FMul &&
Shuxin Yang80138662013-01-07 22:41:28 +0000547 I->getOpcode() != Instruction::FDiv))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000548 return false;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000549
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000550 Constant *C0 = dyn_cast<Constant>(I->getOperand(0));
551 Constant *C1 = dyn_cast<Constant>(I->getOperand(1));
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000552
553 if (C0 && C1)
554 return false;
555
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000556 return (C0 && isFiniteNonZeroFp(C0)) || (C1 && isFiniteNonZeroFp(C1));
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000557}
558
559/// foldFMulConst() is a helper routine of InstCombiner::visitFMul().
560/// The input \p FMulOrDiv is a FMul/FDiv with one and only one operand
561/// being a constant (i.e. isFMulOrFDivWithConstant(FMulOrDiv) == true).
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000562/// This function is to simplify "FMulOrDiv * C" and returns the
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000563/// resulting expression. Note that this function could return NULL in
564/// case the constants cannot be folded into a normal floating-point.
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000565Value *InstCombiner::foldFMulConst(Instruction *FMulOrDiv, Constant *C,
Shuxin Yang80138662013-01-07 22:41:28 +0000566 Instruction *InsertBefore) {
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000567 assert(isFMulOrFDivWithConstant(FMulOrDiv) && "V is invalid");
568
569 Value *Opnd0 = FMulOrDiv->getOperand(0);
570 Value *Opnd1 = FMulOrDiv->getOperand(1);
571
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000572 Constant *C0 = dyn_cast<Constant>(Opnd0);
573 Constant *C1 = dyn_cast<Constant>(Opnd1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000574
Craig Topperf40110f2014-04-25 05:29:35 +0000575 BinaryOperator *R = nullptr;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000576
577 // (X * C0) * C => X * (C0*C)
578 if (FMulOrDiv->getOpcode() == Instruction::FMul) {
579 Constant *F = ConstantExpr::getFMul(C1 ? C1 : C0, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000580 if (isNormalFp(F))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000581 R = BinaryOperator::CreateFMul(C1 ? Opnd0 : Opnd1, F);
582 } else {
583 if (C0) {
584 // (C0 / X) * C => (C0 * C) / X
Shuxin Yang3a7ca6e2013-09-19 21:13:46 +0000585 if (FMulOrDiv->hasOneUse()) {
586 // It would otherwise introduce another div.
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000587 Constant *F = ConstantExpr::getFMul(C0, C);
Shuxin Yang3a7ca6e2013-09-19 21:13:46 +0000588 if (isNormalFp(F))
589 R = BinaryOperator::CreateFDiv(F, Opnd1);
590 }
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000591 } else {
592 // (X / C1) * C => X * (C/C1) if C/C1 is not a denormal
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000593 Constant *F = ConstantExpr::getFDiv(C, C1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000594 if (isNormalFp(F)) {
595 R = BinaryOperator::CreateFMul(Opnd0, F);
596 } else {
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000597 // (X / C1) * C => X / (C1/C)
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000598 Constant *F = ConstantExpr::getFDiv(C1, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000599 if (isNormalFp(F))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000600 R = BinaryOperator::CreateFDiv(Opnd0, F);
601 }
602 }
603 }
604
605 if (R) {
Sanjay Patel629c4112017-11-06 16:27:15 +0000606 R->setFast(true);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000607 InsertNewInstWith(R, *InsertBefore);
608 }
609
610 return R;
611}
612
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000613Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +0000614 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000615 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
616
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000617 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +0000618 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000619
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000620 if (isa<Constant>(Op0))
621 std::swap(Op0, Op1);
622
Craig Toppera4205622017-06-09 03:21:29 +0000623 if (Value *V = SimplifyFMulInst(Op0, Op1, I.getFastMathFlags(),
624 SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +0000625 return replaceInstUsesWith(I, V);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000626
Sanjay Patel629c4112017-11-06 16:27:15 +0000627 bool AllowReassociate = I.isFast();
Shuxin Yange8227452013-01-15 21:09:32 +0000628
Michael Ilsemand5787be2012-12-12 00:28:32 +0000629 // Simplify mul instructions with a constant RHS.
630 if (isa<Constant>(Op1)) {
Sanjay Pateldb0938f2017-01-10 23:49:07 +0000631 if (Instruction *FoldedMul = foldOpWithConstantIntoOperand(I))
632 return FoldedMul;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000633
Owen Andersonf74cfe02014-01-16 20:36:42 +0000634 // (fmul X, -1.0) --> (fsub -0.0, X)
Benjamin Kramerfea9ac92014-01-18 16:43:14 +0000635 if (match(Op1, m_SpecificFP(-1.0))) {
636 Constant *NegZero = ConstantFP::getNegativeZero(Op1->getType());
637 Instruction *RI = BinaryOperator::CreateFSub(NegZero, Op0);
Owen Andersonf74cfe02014-01-16 20:36:42 +0000638 RI->copyFastMathFlags(&I);
639 return RI;
640 }
641
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000642 Constant *C = cast<Constant>(Op1);
643 if (AllowReassociate && isFiniteNonZeroFp(C)) {
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000644 // Let MDC denote an expression in one of these forms:
645 // X * C, C/X, X/C, where C is a constant.
646 //
647 // Try to simplify "MDC * Constant"
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000648 if (isFMulOrFDivWithConstant(Op0))
649 if (Value *V = foldFMulConst(cast<Instruction>(Op0), C, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +0000650 return replaceInstUsesWith(I, V);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000651
Quentin Colombete684a6d2013-02-28 21:12:40 +0000652 // (MDC +/- C1) * C => (MDC * C) +/- (C1 * C)
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000653 Instruction *FAddSub = dyn_cast<Instruction>(Op0);
654 if (FAddSub &&
655 (FAddSub->getOpcode() == Instruction::FAdd ||
656 FAddSub->getOpcode() == Instruction::FSub)) {
657 Value *Opnd0 = FAddSub->getOperand(0);
658 Value *Opnd1 = FAddSub->getOperand(1);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000659 Constant *C0 = dyn_cast<Constant>(Opnd0);
660 Constant *C1 = dyn_cast<Constant>(Opnd1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000661 bool Swap = false;
662 if (C0) {
Shuxin Yang80138662013-01-07 22:41:28 +0000663 std::swap(C0, C1);
664 std::swap(Opnd0, Opnd1);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000665 Swap = true;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000666 }
667
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000668 if (C1 && isFiniteNonZeroFp(C1) && isFMulOrFDivWithConstant(Opnd0)) {
Quentin Colombete684a6d2013-02-28 21:12:40 +0000669 Value *M1 = ConstantExpr::getFMul(C1, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000670 Value *M0 = isNormalFp(cast<Constant>(M1)) ?
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000671 foldFMulConst(cast<Instruction>(Opnd0), C, &I) :
Craig Topperf40110f2014-04-25 05:29:35 +0000672 nullptr;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000673 if (M0 && M1) {
674 if (Swap && FAddSub->getOpcode() == Instruction::FSub)
675 std::swap(M0, M1);
676
Benjamin Kramer67485762013-09-30 15:39:59 +0000677 Instruction *RI = (FAddSub->getOpcode() == Instruction::FAdd)
678 ? BinaryOperator::CreateFAdd(M0, M1)
679 : BinaryOperator::CreateFSub(M0, M1);
Shuxin Yange8227452013-01-15 21:09:32 +0000680 RI->copyFastMathFlags(&I);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000681 return RI;
682 }
683 }
684 }
685 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000686 }
687
Matt Arsenault56c079f2016-01-30 05:02:00 +0000688 if (Op0 == Op1) {
689 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
690 // sqrt(X) * sqrt(X) -> X
691 if (AllowReassociate && II->getIntrinsicID() == Intrinsic::sqrt)
Sanjay Patel4b198802016-02-01 22:23:39 +0000692 return replaceInstUsesWith(I, II->getOperand(0));
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000693
Matt Arsenault56c079f2016-01-30 05:02:00 +0000694 // fabs(X) * fabs(X) -> X * X
695 if (II->getIntrinsicID() == Intrinsic::fabs) {
696 Instruction *FMulVal = BinaryOperator::CreateFMul(II->getOperand(0),
697 II->getOperand(0),
698 I.getName());
699 FMulVal->copyFastMathFlags(&I);
700 return FMulVal;
701 }
702 }
703 }
704
Pedro Artigasd8795042012-11-30 19:09:41 +0000705 // Under unsafe algebra do:
706 // X * log2(0.5*Y) = X*log2(Y) - X
Sanjay Patelb41d4612014-10-02 15:20:45 +0000707 if (AllowReassociate) {
Craig Topperf40110f2014-04-25 05:29:35 +0000708 Value *OpX = nullptr;
709 Value *OpY = nullptr;
Pedro Artigasd8795042012-11-30 19:09:41 +0000710 IntrinsicInst *Log2;
Pedro Artigas993acd02012-11-30 22:07:05 +0000711 detectLog2OfHalf(Op0, OpY, Log2);
712 if (OpY) {
713 OpX = Op1;
714 } else {
715 detectLog2OfHalf(Op1, OpY, Log2);
716 if (OpY) {
717 OpX = Op0;
Pedro Artigasd8795042012-11-30 19:09:41 +0000718 }
719 }
720 // if pattern detected emit alternate sequence
721 if (OpX && OpY) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000722 BuilderTy::FastMathFlagGuard Guard(Builder);
723 Builder.setFastMathFlags(Log2->getFastMathFlags());
Pedro Artigasd8795042012-11-30 19:09:41 +0000724 Log2->setArgOperand(0, OpY);
Craig Topperbb4069e2017-07-07 23:16:26 +0000725 Value *FMulVal = Builder.CreateFMul(OpX, Log2);
726 Value *FSub = Builder.CreateFSub(FMulVal, OpX);
Benjamin Kramer67485762013-09-30 15:39:59 +0000727 FSub->takeName(&I);
Sanjay Patel4b198802016-02-01 22:23:39 +0000728 return replaceInstUsesWith(I, FSub);
Pedro Artigasd8795042012-11-30 19:09:41 +0000729 }
730 }
731
Dmitry Venikova58d8de2018-01-02 05:58:11 +0000732 // sqrt(a) * sqrt(b) -> sqrt(a * b)
733 if (AllowReassociate &&
734 Op0->hasOneUse() && Op1->hasOneUse()) {
735 Value *Opnd0 = nullptr;
736 Value *Opnd1 = nullptr;
737 if (match(Op0, m_Intrinsic<Intrinsic::sqrt>(m_Value(Opnd0))) &&
738 match(Op1, m_Intrinsic<Intrinsic::sqrt>(m_Value(Opnd1)))) {
739 BuilderTy::FastMathFlagGuard Guard(Builder);
740 Builder.setFastMathFlags(I.getFastMathFlags());
741 Value *FMulVal = Builder.CreateFMul(Opnd0, Opnd1);
742 Value *Sqrt = Intrinsic::getDeclaration(I.getModule(),
743 Intrinsic::sqrt, I.getType());
744 Value *SqrtCall = Builder.CreateCall(Sqrt, FMulVal);
745 return replaceInstUsesWith(I, SqrtCall);
746 }
747 }
748
Shuxin Yange8227452013-01-15 21:09:32 +0000749 // Handle symmetric situation in a 2-iteration loop
750 Value *Opnd0 = Op0;
751 Value *Opnd1 = Op1;
752 for (int i = 0; i < 2; i++) {
753 bool IgnoreZeroSign = I.hasNoSignedZeros();
754 if (BinaryOperator::isFNeg(Opnd0, IgnoreZeroSign)) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000755 BuilderTy::FastMathFlagGuard Guard(Builder);
756 Builder.setFastMathFlags(I.getFastMathFlags());
Benjamin Kramer67485762013-09-30 15:39:59 +0000757
Shuxin Yange8227452013-01-15 21:09:32 +0000758 Value *N0 = dyn_castFNegVal(Opnd0, IgnoreZeroSign);
759 Value *N1 = dyn_castFNegVal(Opnd1, IgnoreZeroSign);
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000760
Shuxin Yange8227452013-01-15 21:09:32 +0000761 // -X * -Y => X*Y
Owen Andersone8537fc2014-01-16 20:59:41 +0000762 if (N1) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000763 Value *FMul = Builder.CreateFMul(N0, N1);
Owen Andersone8537fc2014-01-16 20:59:41 +0000764 FMul->takeName(&I);
Sanjay Patel4b198802016-02-01 22:23:39 +0000765 return replaceInstUsesWith(I, FMul);
Owen Andersone8537fc2014-01-16 20:59:41 +0000766 }
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000767
Shuxin Yange8227452013-01-15 21:09:32 +0000768 if (Opnd0->hasOneUse()) {
769 // -X * Y => -(X*Y) (Promote negation as high as possible)
Craig Topperbb4069e2017-07-07 23:16:26 +0000770 Value *T = Builder.CreateFMul(N0, Opnd1);
771 Value *Neg = Builder.CreateFNeg(T);
Benjamin Kramer67485762013-09-30 15:39:59 +0000772 Neg->takeName(&I);
Sanjay Patel4b198802016-02-01 22:23:39 +0000773 return replaceInstUsesWith(I, Neg);
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000774 }
775 }
Shuxin Yange8227452013-01-15 21:09:32 +0000776
Quentin Colombetaa103b32017-09-20 17:32:16 +0000777 // Handle specials cases for FMul with selects feeding the operation
778 if (Value *V = SimplifySelectsFeedingBinaryOp(I, Op0, Op1))
779 return replaceInstUsesWith(I, V);
780
Shuxin Yange8227452013-01-15 21:09:32 +0000781 // (X*Y) * X => (X*X) * Y where Y != X
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000782 // The purpose is two-fold:
Shuxin Yange8227452013-01-15 21:09:32 +0000783 // 1) to form a power expression (of X).
784 // 2) potentially shorten the critical path: After transformation, the
785 // latency of the instruction Y is amortized by the expression of X*X,
786 // and therefore Y is in a "less critical" position compared to what it
787 // was before the transformation.
Shuxin Yange8227452013-01-15 21:09:32 +0000788 if (AllowReassociate) {
789 Value *Opnd0_0, *Opnd0_1;
790 if (Opnd0->hasOneUse() &&
791 match(Opnd0, m_FMul(m_Value(Opnd0_0), m_Value(Opnd0_1)))) {
Craig Topperf40110f2014-04-25 05:29:35 +0000792 Value *Y = nullptr;
Shuxin Yange8227452013-01-15 21:09:32 +0000793 if (Opnd0_0 == Opnd1 && Opnd0_1 != Opnd1)
794 Y = Opnd0_1;
795 else if (Opnd0_1 == Opnd1 && Opnd0_0 != Opnd1)
796 Y = Opnd0_0;
797
798 if (Y) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000799 BuilderTy::FastMathFlagGuard Guard(Builder);
800 Builder.setFastMathFlags(I.getFastMathFlags());
801 Value *T = Builder.CreateFMul(Opnd1, Opnd1);
802 Value *R = Builder.CreateFMul(T, Y);
Benjamin Kramer67485762013-09-30 15:39:59 +0000803 R->takeName(&I);
Sanjay Patel4b198802016-02-01 22:23:39 +0000804 return replaceInstUsesWith(I, R);
Shuxin Yange8227452013-01-15 21:09:32 +0000805 }
806 }
807 }
808
809 if (!isa<Constant>(Op1))
810 std::swap(Opnd0, Opnd1);
811 else
812 break;
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000813 }
814
Craig Topperf40110f2014-04-25 05:29:35 +0000815 return Changed ? &I : nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000816}
817
Sanjay Patelae2e3a42017-10-06 23:20:16 +0000818/// Fold a divide or remainder with a select instruction divisor when one of the
819/// select operands is zero. In that case, we can use the other select operand
820/// because div/rem by zero is undefined.
821bool InstCombiner::simplifyDivRemOfSelectWithZeroOp(BinaryOperator &I) {
822 SelectInst *SI = dyn_cast<SelectInst>(I.getOperand(1));
823 if (!SI)
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000824 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000825
Sanjay Patelae2e3a42017-10-06 23:20:16 +0000826 int NonNullOperand;
827 if (match(SI->getTrueValue(), m_Zero()))
828 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
829 NonNullOperand = 2;
830 else if (match(SI->getFalseValue(), m_Zero()))
831 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
832 NonNullOperand = 1;
833 else
834 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000835
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000836 // Change the div/rem to use 'Y' instead of the select.
837 I.setOperand(1, SI->getOperand(NonNullOperand));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000838
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000839 // Okay, we know we replace the operand of the div/rem with 'Y' with no
840 // problem. However, the select, or the condition of the select may have
841 // multiple uses. Based on our knowledge that the operand must be non-zero,
842 // propagate the known value for the select into other uses of it, and
843 // propagate a known value of the condition into its other users.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000844
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000845 // If the select and condition only have a single use, don't bother with this,
846 // early exit.
Sanjay Patelae2e3a42017-10-06 23:20:16 +0000847 Value *SelectCond = SI->getCondition();
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000848 if (SI->use_empty() && SelectCond->hasOneUse())
849 return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000850
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000851 // Scan the current block backward, looking for other uses of SI.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000852 BasicBlock::iterator BBI = I.getIterator(), BBFront = I.getParent()->begin();
Sanjay Patel72d339a2017-10-06 23:43:06 +0000853 Type *CondTy = SelectCond->getType();
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000854 while (BBI != BBFront) {
855 --BBI;
856 // If we found a call to a function, we can't assume it will return, so
857 // information from below it cannot be propagated above it.
858 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
859 break;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000860
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000861 // Replace uses of the select or its condition with the known values.
862 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
863 I != E; ++I) {
864 if (*I == SI) {
865 *I = SI->getOperand(NonNullOperand);
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000866 Worklist.Add(&*BBI);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000867 } else if (*I == SelectCond) {
Sanjay Patel72d339a2017-10-06 23:43:06 +0000868 *I = NonNullOperand == 1 ? ConstantInt::getTrue(CondTy)
869 : ConstantInt::getFalse(CondTy);
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000870 Worklist.Add(&*BBI);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000871 }
872 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000873
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000874 // If we past the instruction, quit looking for it.
875 if (&*BBI == SI)
Craig Topperf40110f2014-04-25 05:29:35 +0000876 SI = nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000877 if (&*BBI == SelectCond)
Craig Topperf40110f2014-04-25 05:29:35 +0000878 SelectCond = nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000879
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000880 // If we ran out of things to eliminate, break out of the loop.
Craig Topperf40110f2014-04-25 05:29:35 +0000881 if (!SelectCond && !SI)
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000882 break;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000883
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000884 }
885 return true;
886}
887
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000888/// This function implements the transforms common to both integer division
889/// instructions (udiv and sdiv). It is called by the visitors to those integer
890/// division instructions.
891/// @brief Common integer divide transforms
892Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
893 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Sanjay Patel9530f182018-01-21 16:14:51 +0000894 bool IsSigned = I.getOpcode() == Instruction::SDiv;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000895
Chris Lattner7c99f192011-05-22 18:18:41 +0000896 // The RHS is known non-zero.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000897 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I)) {
Chris Lattner7c99f192011-05-22 18:18:41 +0000898 I.setOperand(1, V);
899 return &I;
900 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000901
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000902 // Handle cases involving: [su]div X, (select Cond, Y, Z)
903 // This does not apply for fdiv.
Sanjay Patelae2e3a42017-10-06 23:20:16 +0000904 if (simplifyDivRemOfSelectWithZeroOp(I))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000905 return &I;
906
David Majnemer27adb122014-10-12 08:34:24 +0000907 if (Instruction *LHS = dyn_cast<Instruction>(Op0)) {
908 const APInt *C2;
909 if (match(Op1, m_APInt(C2))) {
David Majnemerf9a095d2014-08-16 08:55:06 +0000910 Value *X;
David Majnemer27adb122014-10-12 08:34:24 +0000911 const APInt *C1;
David Majnemerf9a095d2014-08-16 08:55:06 +0000912
David Majnemer27adb122014-10-12 08:34:24 +0000913 // (X / C1) / C2 -> X / (C1*C2)
914 if ((IsSigned && match(LHS, m_SDiv(m_Value(X), m_APInt(C1)))) ||
915 (!IsSigned && match(LHS, m_UDiv(m_Value(X), m_APInt(C1))))) {
916 APInt Product(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
917 if (!MultiplyOverflows(*C1, *C2, Product, IsSigned))
918 return BinaryOperator::Create(I.getOpcode(), X,
919 ConstantInt::get(I.getType(), Product));
920 }
David Majnemerf9a095d2014-08-16 08:55:06 +0000921
David Majnemer27adb122014-10-12 08:34:24 +0000922 if ((IsSigned && match(LHS, m_NSWMul(m_Value(X), m_APInt(C1)))) ||
923 (!IsSigned && match(LHS, m_NUWMul(m_Value(X), m_APInt(C1))))) {
924 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
925
926 // (X * C1) / C2 -> X / (C2 / C1) if C2 is a multiple of C1.
927 if (IsMultiple(*C2, *C1, Quotient, IsSigned)) {
928 BinaryOperator *BO = BinaryOperator::Create(
929 I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
930 BO->setIsExact(I.isExact());
931 return BO;
David Majnemerf9a095d2014-08-16 08:55:06 +0000932 }
933
David Majnemer27adb122014-10-12 08:34:24 +0000934 // (X * C1) / C2 -> X * (C1 / C2) if C1 is a multiple of C2.
935 if (IsMultiple(*C1, *C2, Quotient, IsSigned)) {
936 BinaryOperator *BO = BinaryOperator::Create(
937 Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
938 BO->setHasNoUnsignedWrap(
939 !IsSigned &&
940 cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
941 BO->setHasNoSignedWrap(
942 cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
943 return BO;
David Majnemerf9a095d2014-08-16 08:55:06 +0000944 }
945 }
David Majnemerf9a095d2014-08-16 08:55:06 +0000946
David Majnemer27adb122014-10-12 08:34:24 +0000947 if ((IsSigned && match(LHS, m_NSWShl(m_Value(X), m_APInt(C1))) &&
948 *C1 != C1->getBitWidth() - 1) ||
949 (!IsSigned && match(LHS, m_NUWShl(m_Value(X), m_APInt(C1))))) {
950 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
951 APInt C1Shifted = APInt::getOneBitSet(
952 C1->getBitWidth(), static_cast<unsigned>(C1->getLimitedValue()));
953
954 // (X << C1) / C2 -> X / (C2 >> C1) if C2 is a multiple of C1.
955 if (IsMultiple(*C2, C1Shifted, Quotient, IsSigned)) {
956 BinaryOperator *BO = BinaryOperator::Create(
957 I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
958 BO->setIsExact(I.isExact());
959 return BO;
960 }
961
962 // (X << C1) / C2 -> X * (C2 >> C1) if C1 is a multiple of C2.
963 if (IsMultiple(C1Shifted, *C2, Quotient, IsSigned)) {
964 BinaryOperator *BO = BinaryOperator::Create(
965 Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
966 BO->setHasNoUnsignedWrap(
967 !IsSigned &&
968 cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
969 BO->setHasNoSignedWrap(
970 cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
971 return BO;
972 }
973 }
974
Craig Topper73ba1c82017-06-07 07:40:37 +0000975 if (!C2->isNullValue()) // avoid X udiv 0
Sanjay Pateldb0938f2017-01-10 23:49:07 +0000976 if (Instruction *FoldedDiv = foldOpWithConstantIntoOperand(I))
977 return FoldedDiv;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000978 }
979 }
980
Craig Topper218a3592017-04-17 03:41:47 +0000981 if (match(Op0, m_One())) {
Craig Topperfde47232017-07-09 07:04:03 +0000982 assert(!I.getType()->isIntOrIntVectorTy(1) && "i1 divide not removed?");
Craig Topper218a3592017-04-17 03:41:47 +0000983 if (I.getOpcode() == Instruction::SDiv) {
984 // If Op1 is 0 then it's undefined behaviour, if Op1 is 1 then the
985 // result is one, if Op1 is -1 then the result is minus one, otherwise
986 // it's zero.
Craig Topperbb4069e2017-07-07 23:16:26 +0000987 Value *Inc = Builder.CreateAdd(Op1, Op0);
988 Value *Cmp = Builder.CreateICmpULT(Inc, ConstantInt::get(I.getType(), 3));
Craig Topper218a3592017-04-17 03:41:47 +0000989 return SelectInst::Create(Cmp, Op1, ConstantInt::get(I.getType(), 0));
990 } else {
991 // If Op1 is 0 then it's undefined behaviour. If Op1 is 1 then the
992 // result is one, otherwise it's zero.
Craig Topperbb4069e2017-07-07 23:16:26 +0000993 return new ZExtInst(Builder.CreateICmpEQ(Op1, Op0), I.getType());
Nick Lewyckyf0cf8fa2014-05-14 03:03:05 +0000994 }
995 }
996
Benjamin Kramer57b3df52011-04-30 18:16:00 +0000997 // See if we can fold away this div instruction.
998 if (SimplifyDemandedInstructionBits(I))
999 return &I;
1000
Duncan Sands771e82a2011-01-28 16:51:11 +00001001 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
Sanjay Patel9530f182018-01-21 16:14:51 +00001002 Value *X, *Z;
1003 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) // (X - Z) / Y; Y = Op1
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)))))
Duncan Sands771e82a2011-01-28 16:51:11 +00001006 return BinaryOperator::Create(I.getOpcode(), X, Op1);
Sanjay Patel9530f182018-01-21 16:14:51 +00001007
1008 // (X << Y) / X -> 1 << Y
1009 Value *Y;
1010 if (IsSigned && match(Op0, m_NSWShl(m_Specific(Op1), m_Value(Y))))
1011 return BinaryOperator::CreateNSWShl(ConstantInt::get(I.getType(), 1), Y);
1012 if (!IsSigned && match(Op0, m_NUWShl(m_Specific(Op1), m_Value(Y))))
1013 return BinaryOperator::CreateNUWShl(ConstantInt::get(I.getType(), 1), Y);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001014
Craig Topperf40110f2014-04-25 05:29:35 +00001015 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001016}
1017
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00001018static const unsigned MaxDepth = 6;
1019
David Majnemer37f8f442013-07-04 21:17:49 +00001020namespace {
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00001021
1022using FoldUDivOperandCb = Instruction *(*)(Value *Op0, Value *Op1,
1023 const BinaryOperator &I,
1024 InstCombiner &IC);
David Majnemer37f8f442013-07-04 21:17:49 +00001025
1026/// \brief Used to maintain state for visitUDivOperand().
1027struct UDivFoldAction {
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00001028 /// Informs visitUDiv() how to fold this operand. This can be zero if this
1029 /// action joins two actions together.
1030 FoldUDivOperandCb FoldAction;
David Majnemer37f8f442013-07-04 21:17:49 +00001031
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00001032 /// Which operand to fold.
1033 Value *OperandToFold;
1034
David Majnemer37f8f442013-07-04 21:17:49 +00001035 union {
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00001036 /// The instruction returned when FoldAction is invoked.
1037 Instruction *FoldResult;
David Majnemer37f8f442013-07-04 21:17:49 +00001038
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00001039 /// Stores the LHS action index if this action joins two actions together.
1040 size_t SelectLHSIdx;
David Majnemer37f8f442013-07-04 21:17:49 +00001041 };
1042
1043 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand)
Craig Topperf40110f2014-04-25 05:29:35 +00001044 : FoldAction(FA), OperandToFold(InputOperand), FoldResult(nullptr) {}
David Majnemer37f8f442013-07-04 21:17:49 +00001045 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand, size_t SLHS)
1046 : FoldAction(FA), OperandToFold(InputOperand), SelectLHSIdx(SLHS) {}
1047};
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00001048
1049} // end anonymous namespace
David Majnemer37f8f442013-07-04 21:17:49 +00001050
1051// X udiv 2^C -> X >> C
1052static Instruction *foldUDivPow2Cst(Value *Op0, Value *Op1,
1053 const BinaryOperator &I, InstCombiner &IC) {
1054 const APInt &C = cast<Constant>(Op1)->getUniqueInteger();
1055 BinaryOperator *LShr = BinaryOperator::CreateLShr(
1056 Op0, ConstantInt::get(Op0->getType(), C.logBase2()));
Suyog Sarda65f5ae92014-10-07 12:04:07 +00001057 if (I.isExact())
1058 LShr->setIsExact();
David Majnemer37f8f442013-07-04 21:17:49 +00001059 return LShr;
1060}
1061
1062// X udiv C, where C >= signbit
1063static Instruction *foldUDivNegCst(Value *Op0, Value *Op1,
1064 const BinaryOperator &I, InstCombiner &IC) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001065 Value *ICI = IC.Builder.CreateICmpULT(Op0, cast<ConstantInt>(Op1));
David Majnemer37f8f442013-07-04 21:17:49 +00001066
1067 return SelectInst::Create(ICI, Constant::getNullValue(I.getType()),
1068 ConstantInt::get(I.getType(), 1));
1069}
1070
1071// X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Andrea Di Biagioa82d52d2016-09-26 12:07:23 +00001072// X udiv (zext (C1 << N)), where C1 is "1<<C2" --> X >> (N+C2)
David Majnemer37f8f442013-07-04 21:17:49 +00001073static Instruction *foldUDivShl(Value *Op0, Value *Op1, const BinaryOperator &I,
1074 InstCombiner &IC) {
Andrea Di Biagioa82d52d2016-09-26 12:07:23 +00001075 Value *ShiftLeft;
1076 if (!match(Op1, m_ZExt(m_Value(ShiftLeft))))
1077 ShiftLeft = Op1;
David Majnemer37f8f442013-07-04 21:17:49 +00001078
Andrea Di Biagioa82d52d2016-09-26 12:07:23 +00001079 const APInt *CI;
1080 Value *N;
1081 if (!match(ShiftLeft, m_Shl(m_APInt(CI), m_Value(N))))
1082 llvm_unreachable("match should never fail here!");
1083 if (*CI != 1)
Craig Topperbb4069e2017-07-07 23:16:26 +00001084 N = IC.Builder.CreateAdd(N, ConstantInt::get(N->getType(), CI->logBase2()));
Andrea Di Biagioa82d52d2016-09-26 12:07:23 +00001085 if (Op1 != ShiftLeft)
Craig Topperbb4069e2017-07-07 23:16:26 +00001086 N = IC.Builder.CreateZExt(N, Op1->getType());
David Majnemer37f8f442013-07-04 21:17:49 +00001087 BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, N);
Suyog Sarda65f5ae92014-10-07 12:04:07 +00001088 if (I.isExact())
1089 LShr->setIsExact();
David Majnemer37f8f442013-07-04 21:17:49 +00001090 return LShr;
1091}
1092
1093// \brief Recursively visits the possible right hand operands of a udiv
1094// instruction, seeing through select instructions, to determine if we can
1095// replace the udiv with something simpler. If we find that an operand is not
1096// able to simplify the udiv, we abort the entire transformation.
1097static size_t visitUDivOperand(Value *Op0, Value *Op1, const BinaryOperator &I,
1098 SmallVectorImpl<UDivFoldAction> &Actions,
1099 unsigned Depth = 0) {
1100 // Check to see if this is an unsigned division with an exact power of 2,
1101 // if so, convert to a right shift.
1102 if (match(Op1, m_Power2())) {
1103 Actions.push_back(UDivFoldAction(foldUDivPow2Cst, Op1));
1104 return Actions.size();
1105 }
1106
1107 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1))
1108 // X udiv C, where C >= signbit
1109 if (C->getValue().isNegative()) {
1110 Actions.push_back(UDivFoldAction(foldUDivNegCst, C));
1111 return Actions.size();
1112 }
1113
1114 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
1115 if (match(Op1, m_Shl(m_Power2(), m_Value())) ||
1116 match(Op1, m_ZExt(m_Shl(m_Power2(), m_Value())))) {
1117 Actions.push_back(UDivFoldAction(foldUDivShl, Op1));
1118 return Actions.size();
1119 }
1120
1121 // The remaining tests are all recursive, so bail out if we hit the limit.
1122 if (Depth++ == MaxDepth)
1123 return 0;
1124
1125 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
David Majnemer492e6122014-08-30 09:19:05 +00001126 if (size_t LHSIdx =
1127 visitUDivOperand(Op0, SI->getOperand(1), I, Actions, Depth))
1128 if (visitUDivOperand(Op0, SI->getOperand(2), I, Actions, Depth)) {
1129 Actions.push_back(UDivFoldAction(nullptr, Op1, LHSIdx - 1));
David Majnemer37f8f442013-07-04 21:17:49 +00001130 return Actions.size();
1131 }
1132
1133 return 0;
1134}
1135
Sanjay Patelbb789382017-08-24 22:54:01 +00001136/// If we have zero-extended operands of an unsigned div or rem, we may be able
1137/// to narrow the operation (sink the zext below the math).
1138static Instruction *narrowUDivURem(BinaryOperator &I,
1139 InstCombiner::BuilderTy &Builder) {
1140 Instruction::BinaryOps Opcode = I.getOpcode();
1141 Value *N = I.getOperand(0);
1142 Value *D = I.getOperand(1);
1143 Type *Ty = I.getType();
1144 Value *X, *Y;
1145 if (match(N, m_ZExt(m_Value(X))) && match(D, m_ZExt(m_Value(Y))) &&
1146 X->getType() == Y->getType() && (N->hasOneUse() || D->hasOneUse())) {
1147 // udiv (zext X), (zext Y) --> zext (udiv X, Y)
1148 // urem (zext X), (zext Y) --> zext (urem X, Y)
1149 Value *NarrowOp = Builder.CreateBinOp(Opcode, X, Y);
1150 return new ZExtInst(NarrowOp, Ty);
1151 }
1152
1153 Constant *C;
1154 if ((match(N, m_OneUse(m_ZExt(m_Value(X)))) && match(D, m_Constant(C))) ||
1155 (match(D, m_OneUse(m_ZExt(m_Value(X)))) && match(N, m_Constant(C)))) {
1156 // If the constant is the same in the smaller type, use the narrow version.
1157 Constant *TruncC = ConstantExpr::getTrunc(C, X->getType());
1158 if (ConstantExpr::getZExt(TruncC, Ty) != C)
1159 return nullptr;
1160
1161 // udiv (zext X), C --> zext (udiv X, C')
1162 // urem (zext X), C --> zext (urem X, C')
1163 // udiv C, (zext X) --> zext (udiv C', X)
1164 // urem C, (zext X) --> zext (urem C', X)
1165 Value *NarrowOp = isa<Constant>(D) ? Builder.CreateBinOp(Opcode, X, TruncC)
1166 : Builder.CreateBinOp(Opcode, TruncC, X);
1167 return new ZExtInst(NarrowOp, Ty);
1168 }
1169
1170 return nullptr;
1171}
1172
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001173Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
1174 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1175
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001176 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001177 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001178
Craig Toppera4205622017-06-09 03:21:29 +00001179 if (Value *V = SimplifyUDivInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001180 return replaceInstUsesWith(I, V);
Duncan Sands771e82a2011-01-28 16:51:11 +00001181
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001182 // Handle the integer div common cases
1183 if (Instruction *Common = commonIDivTransforms(I))
1184 return Common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001185
Benjamin Kramerd4a64712012-08-30 15:07:40 +00001186 // (x lshr C1) udiv C2 --> x udiv (C2 << C1)
David Majnemera2521382014-10-13 21:48:30 +00001187 {
Benjamin Kramer9c0a8072012-08-28 13:08:13 +00001188 Value *X;
David Majnemera2521382014-10-13 21:48:30 +00001189 const APInt *C1, *C2;
1190 if (match(Op0, m_LShr(m_Value(X), m_APInt(C1))) &&
1191 match(Op1, m_APInt(C2))) {
1192 bool Overflow;
1193 APInt C2ShlC1 = C2->ushl_ov(*C1, Overflow);
David Majnemera3aeb152014-11-22 18:16:54 +00001194 if (!Overflow) {
1195 bool IsExact = I.isExact() && match(Op0, m_Exact(m_Value()));
1196 BinaryOperator *BO = BinaryOperator::CreateUDiv(
David Majnemera2521382014-10-13 21:48:30 +00001197 X, ConstantInt::get(X->getType(), C2ShlC1));
David Majnemera3aeb152014-11-22 18:16:54 +00001198 if (IsExact)
1199 BO->setIsExact();
1200 return BO;
1201 }
David Majnemera2521382014-10-13 21:48:30 +00001202 }
Nadav Rotem11935b22012-08-28 10:01:43 +00001203 }
1204
Sanjay Patelbb789382017-08-24 22:54:01 +00001205 if (Instruction *NarrowDiv = narrowUDivURem(I, Builder))
1206 return NarrowDiv;
Benjamin Kramer9aa91b12011-04-30 18:16:07 +00001207
David Majnemer37f8f442013-07-04 21:17:49 +00001208 // (LHS udiv (select (select (...)))) -> (LHS >> (select (select (...))))
1209 SmallVector<UDivFoldAction, 6> UDivActions;
1210 if (visitUDivOperand(Op0, Op1, I, UDivActions))
1211 for (unsigned i = 0, e = UDivActions.size(); i != e; ++i) {
1212 FoldUDivOperandCb Action = UDivActions[i].FoldAction;
1213 Value *ActionOp1 = UDivActions[i].OperandToFold;
1214 Instruction *Inst;
1215 if (Action)
1216 Inst = Action(Op0, ActionOp1, I, *this);
1217 else {
1218 // This action joins two actions together. The RHS of this action is
1219 // simply the last action we processed, we saved the LHS action index in
1220 // the joining action.
1221 size_t SelectRHSIdx = i - 1;
1222 Value *SelectRHS = UDivActions[SelectRHSIdx].FoldResult;
1223 size_t SelectLHSIdx = UDivActions[i].SelectLHSIdx;
1224 Value *SelectLHS = UDivActions[SelectLHSIdx].FoldResult;
1225 Inst = SelectInst::Create(cast<SelectInst>(ActionOp1)->getCondition(),
1226 SelectLHS, SelectRHS);
1227 }
1228
1229 // If this is the last action to process, return it to the InstCombiner.
1230 // Otherwise, we insert it before the UDiv and record it so that we may
1231 // use it as part of a joining action (i.e., a SelectInst).
1232 if (e - i != 1) {
1233 Inst->insertBefore(&I);
1234 UDivActions[i].FoldResult = Inst;
1235 } else
1236 return Inst;
1237 }
1238
Craig Topperf40110f2014-04-25 05:29:35 +00001239 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001240}
1241
1242Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
1243 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1244
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001245 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001246 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001247
Craig Toppera4205622017-06-09 03:21:29 +00001248 if (Value *V = SimplifySDivInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001249 return replaceInstUsesWith(I, V);
Duncan Sands771e82a2011-01-28 16:51:11 +00001250
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001251 // Handle the integer div common cases
1252 if (Instruction *Common = commonIDivTransforms(I))
1253 return Common;
1254
Sanjay Patelc6ada532016-06-27 17:25:57 +00001255 const APInt *Op1C;
Sanjay Patelbedd1f92016-06-27 18:38:40 +00001256 if (match(Op1, m_APInt(Op1C))) {
1257 // sdiv X, -1 == -X
1258 if (Op1C->isAllOnesValue())
1259 return BinaryOperator::CreateNeg(Op0);
1260
1261 // sdiv exact X, C --> ashr exact X, log2(C)
1262 if (I.isExact() && Op1C->isNonNegative() && Op1C->isPowerOf2()) {
1263 Value *ShAmt = ConstantInt::get(Op1->getType(), Op1C->exactLogBase2());
1264 return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
1265 }
Sanjay Patel59ed2ff2016-06-27 22:27:11 +00001266
1267 // If the dividend is sign-extended and the constant divisor is small enough
1268 // to fit in the source type, shrink the division to the narrower type:
1269 // (sext X) sdiv C --> sext (X sdiv C)
1270 Value *Op0Src;
1271 if (match(Op0, m_OneUse(m_SExt(m_Value(Op0Src)))) &&
1272 Op0Src->getType()->getScalarSizeInBits() >= Op1C->getMinSignedBits()) {
1273
1274 // In the general case, we need to make sure that the dividend is not the
1275 // minimum signed value because dividing that by -1 is UB. But here, we
1276 // know that the -1 divisor case is already handled above.
1277
1278 Constant *NarrowDivisor =
1279 ConstantExpr::getTrunc(cast<Constant>(Op1), Op0Src->getType());
Craig Topperbb4069e2017-07-07 23:16:26 +00001280 Value *NarrowOp = Builder.CreateSDiv(Op0Src, NarrowDivisor);
Sanjay Patel59ed2ff2016-06-27 22:27:11 +00001281 return new SExtInst(NarrowOp, Op0->getType());
1282 }
Benjamin Kramer72196f32014-01-19 15:24:22 +00001283 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001284
Benjamin Kramer72196f32014-01-19 15:24:22 +00001285 if (Constant *RHS = dyn_cast<Constant>(Op1)) {
David Majnemerf28e2a42014-07-02 06:42:13 +00001286 // X/INT_MIN -> X == INT_MIN
1287 if (RHS->isMinSignedValue())
Craig Topperbb4069e2017-07-07 23:16:26 +00001288 return new ZExtInst(Builder.CreateICmpEQ(Op0, Op1), I.getType());
David Majnemerf28e2a42014-07-02 06:42:13 +00001289
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001290 // -X/C --> X/-C provided the negation doesn't overflow.
David Majnemerfa4699e2014-11-22 20:00:34 +00001291 Value *X;
1292 if (match(Op0, m_NSWSub(m_Zero(), m_Value(X)))) {
1293 auto *BO = BinaryOperator::CreateSDiv(X, ConstantExpr::getNeg(RHS));
1294 BO->setIsExact(I.isExact());
1295 return BO;
1296 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001297 }
1298
1299 // If the sign bits of both operands are zero (i.e. we can prove they are
1300 // unsigned inputs), turn this into a udiv.
Craig Topperbcfd2d12017-04-20 16:56:25 +00001301 APInt Mask(APInt::getSignMask(I.getType()->getScalarSizeInBits()));
Craig Topperf2484682017-04-17 01:51:19 +00001302 if (MaskedValueIsZero(Op0, Mask, 0, &I)) {
1303 if (MaskedValueIsZero(Op1, Mask, 0, &I)) {
1304 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
1305 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1306 BO->setIsExact(I.isExact());
1307 return BO;
1308 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001309
Craig Topperd4039f72017-05-25 21:51:12 +00001310 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/ true, 0, &I)) {
Craig Topperf2484682017-04-17 01:51:19 +00001311 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
1312 // Safe because the only negative value (1 << Y) can take on is
1313 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
1314 // the sign bit set.
1315 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1316 BO->setIsExact(I.isExact());
1317 return BO;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001318 }
1319 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001320
Craig Topperf40110f2014-04-25 05:29:35 +00001321 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001322}
1323
Shuxin Yang320f52a2013-01-14 22:48:41 +00001324/// CvtFDivConstToReciprocal tries to convert X/C into X*1/C if C not a special
1325/// FP value and:
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001326/// 1) 1/C is exact, or
Shuxin Yang320f52a2013-01-14 22:48:41 +00001327/// 2) reciprocal is allowed.
Sylvestre Ledru149e2812013-05-14 23:36:24 +00001328/// If the conversion was successful, the simplified expression "X * 1/C" is
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00001329/// returned; otherwise, nullptr is returned.
Suyog Sardaea205512014-10-07 11:56:06 +00001330static Instruction *CvtFDivConstToReciprocal(Value *Dividend, Constant *Divisor,
Shuxin Yang320f52a2013-01-14 22:48:41 +00001331 bool AllowReciprocal) {
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001332 if (!isa<ConstantFP>(Divisor)) // TODO: handle vectors.
Craig Topperf40110f2014-04-25 05:29:35 +00001333 return nullptr;
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001334
1335 const APFloat &FpVal = cast<ConstantFP>(Divisor)->getValueAPF();
Shuxin Yang320f52a2013-01-14 22:48:41 +00001336 APFloat Reciprocal(FpVal.getSemantics());
1337 bool Cvt = FpVal.getExactInverse(&Reciprocal);
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001338
Michael Gottesman3cb77ab2013-06-19 21:23:18 +00001339 if (!Cvt && AllowReciprocal && FpVal.isFiniteNonZero()) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001340 Reciprocal = APFloat(FpVal.getSemantics(), 1.0f);
1341 (void)Reciprocal.divide(FpVal, APFloat::rmNearestTiesToEven);
1342 Cvt = !Reciprocal.isDenormal();
1343 }
1344
1345 if (!Cvt)
Craig Topperf40110f2014-04-25 05:29:35 +00001346 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001347
1348 ConstantFP *R;
1349 R = ConstantFP::get(Dividend->getType()->getContext(), Reciprocal);
1350 return BinaryOperator::CreateFMul(Dividend, R);
1351}
1352
Frits van Bommel2a559512011-01-29 17:50:27 +00001353Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
1354 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1355
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001356 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001357 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001358
Craig Toppera4205622017-06-09 03:21:29 +00001359 if (Value *V = SimplifyFDivInst(Op0, Op1, I.getFastMathFlags(),
1360 SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001361 return replaceInstUsesWith(I, V);
Frits van Bommel2a559512011-01-29 17:50:27 +00001362
Stephen Lina9b57f62013-07-20 07:13:13 +00001363 if (isa<Constant>(Op0))
1364 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1365 if (Instruction *R = FoldOpIntoSelect(I, SI))
1366 return R;
1367
Sanjay Patel629c4112017-11-06 16:27:15 +00001368 bool AllowReassociate = I.isFast();
Shuxin Yang320f52a2013-01-14 22:48:41 +00001369 bool AllowReciprocal = I.hasAllowReciprocal();
Benjamin Kramer8564e0d2011-03-30 15:42:35 +00001370
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001371 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Stephen Lina9b57f62013-07-20 07:13:13 +00001372 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1373 if (Instruction *R = FoldOpIntoSelect(I, SI))
1374 return R;
1375
Shuxin Yang320f52a2013-01-14 22:48:41 +00001376 if (AllowReassociate) {
Craig Topperf40110f2014-04-25 05:29:35 +00001377 Constant *C1 = nullptr;
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001378 Constant *C2 = Op1C;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001379 Value *X;
Craig Topperf40110f2014-04-25 05:29:35 +00001380 Instruction *Res = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001381
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001382 if (match(Op0, m_FMul(m_Value(X), m_Constant(C1)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001383 // (X*C1)/C2 => X * (C1/C2)
1384 //
1385 Constant *C = ConstantExpr::getFDiv(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001386 if (isNormalFp(C))
Shuxin Yang320f52a2013-01-14 22:48:41 +00001387 Res = BinaryOperator::CreateFMul(X, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001388 } else if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001389 // (X/C1)/C2 => X /(C2*C1) [=> X * 1/(C2*C1) if reciprocal is allowed]
Shuxin Yang320f52a2013-01-14 22:48:41 +00001390 Constant *C = ConstantExpr::getFMul(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001391 if (isNormalFp(C)) {
1392 Res = CvtFDivConstToReciprocal(X, C, AllowReciprocal);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001393 if (!Res)
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001394 Res = BinaryOperator::CreateFDiv(X, C);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001395 }
1396 }
1397
1398 if (Res) {
1399 Res->setFastMathFlags(I.getFastMathFlags());
1400 return Res;
1401 }
1402 }
1403
1404 // X / C => X * 1/C
Owen Anderson4557a152014-01-16 21:07:52 +00001405 if (Instruction *T = CvtFDivConstToReciprocal(Op0, Op1C, AllowReciprocal)) {
1406 T->copyFastMathFlags(&I);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001407 return T;
Owen Anderson4557a152014-01-16 21:07:52 +00001408 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001409
Craig Topperf40110f2014-04-25 05:29:35 +00001410 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001411 }
1412
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001413 if (AllowReassociate && isa<Constant>(Op0)) {
1414 Constant *C1 = cast<Constant>(Op0), *C2;
Craig Topperf40110f2014-04-25 05:29:35 +00001415 Constant *Fold = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001416 Value *X;
1417 bool CreateDiv = true;
1418
1419 // C1 / (X*C2) => (C1/C2) / X
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001420 if (match(Op1, m_FMul(m_Value(X), m_Constant(C2))))
Shuxin Yang320f52a2013-01-14 22:48:41 +00001421 Fold = ConstantExpr::getFDiv(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001422 else if (match(Op1, m_FDiv(m_Value(X), m_Constant(C2)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001423 // C1 / (X/C2) => (C1*C2) / X
1424 Fold = ConstantExpr::getFMul(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001425 } else if (match(Op1, m_FDiv(m_Constant(C2), m_Value(X)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001426 // C1 / (C2/X) => (C1/C2) * X
1427 Fold = ConstantExpr::getFDiv(C1, C2);
1428 CreateDiv = false;
1429 }
1430
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001431 if (Fold && isNormalFp(Fold)) {
1432 Instruction *R = CreateDiv ? BinaryOperator::CreateFDiv(Fold, X)
1433 : BinaryOperator::CreateFMul(X, Fold);
1434 R->setFastMathFlags(I.getFastMathFlags());
1435 return R;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001436 }
Craig Topperf40110f2014-04-25 05:29:35 +00001437 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001438 }
1439
1440 if (AllowReassociate) {
1441 Value *X, *Y;
Craig Topperf40110f2014-04-25 05:29:35 +00001442 Value *NewInst = nullptr;
1443 Instruction *SimpR = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001444
1445 if (Op0->hasOneUse() && match(Op0, m_FDiv(m_Value(X), m_Value(Y)))) {
1446 // (X/Y) / Z => X / (Y*Z)
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001447 if (!isa<Constant>(Y) || !isa<Constant>(Op1)) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001448 NewInst = Builder.CreateFMul(Y, Op1);
Owen Anderson1664dc82014-01-20 07:44:53 +00001449 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1450 FastMathFlags Flags = I.getFastMathFlags();
1451 Flags &= cast<Instruction>(Op0)->getFastMathFlags();
1452 RI->setFastMathFlags(Flags);
1453 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001454 SimpR = BinaryOperator::CreateFDiv(X, NewInst);
1455 }
1456 } else if (Op1->hasOneUse() && match(Op1, m_FDiv(m_Value(X), m_Value(Y)))) {
1457 // Z / (X/Y) => Z*Y / X
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001458 if (!isa<Constant>(Y) || !isa<Constant>(Op0)) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001459 NewInst = Builder.CreateFMul(Op0, Y);
Owen Anderson1664dc82014-01-20 07:44:53 +00001460 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1461 FastMathFlags Flags = I.getFastMathFlags();
1462 Flags &= cast<Instruction>(Op1)->getFastMathFlags();
1463 RI->setFastMathFlags(Flags);
1464 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001465 SimpR = BinaryOperator::CreateFDiv(NewInst, X);
1466 }
1467 }
1468
1469 if (NewInst) {
1470 if (Instruction *T = dyn_cast<Instruction>(NewInst))
1471 T->setDebugLoc(I.getDebugLoc());
1472 SimpR->setFastMathFlags(I.getFastMathFlags());
1473 return SimpR;
Benjamin Kramer8564e0d2011-03-30 15:42:35 +00001474 }
1475 }
1476
Dmitry Venikove5fbf592018-01-11 06:33:00 +00001477 if (AllowReassociate &&
1478 Op0->hasOneUse() && Op1->hasOneUse()) {
1479 Value *A;
1480 // sin(a) / cos(a) -> tan(a)
1481 if (match(Op0, m_Intrinsic<Intrinsic::sin>(m_Value(A))) &&
1482 match(Op1, m_Intrinsic<Intrinsic::cos>(m_Specific(A)))) {
1483 if (hasUnaryFloatFn(&TLI, I.getType(), LibFunc_tan,
1484 LibFunc_tanf, LibFunc_tanl)) {
1485 IRBuilder<> B(&I);
1486 IRBuilder<>::FastMathFlagGuard Guard(B);
1487 B.setFastMathFlags(I.getFastMathFlags());
Benjamin Kramer738e6e72018-01-11 15:33:21 +00001488 Value *Tan = emitUnaryFloatFnCall(
1489 A, TLI.getName(LibFunc_tan), B,
1490 CallSite(Op0).getCalledFunction()->getAttributes());
Dmitry Venikove5fbf592018-01-11 06:33:00 +00001491 return replaceInstUsesWith(I, Tan);
1492 }
1493 }
1494
1495 // cos(a) / sin(a) -> 1/tan(a)
1496 if (match(Op0, m_Intrinsic<Intrinsic::cos>(m_Value(A))) &&
1497 match(Op1, m_Intrinsic<Intrinsic::sin>(m_Specific(A)))) {
1498 if (hasUnaryFloatFn(&TLI, I.getType(), LibFunc_tan,
1499 LibFunc_tanf, LibFunc_tanl)) {
1500 IRBuilder<> B(&I);
1501 IRBuilder<>::FastMathFlagGuard Guard(B);
1502 B.setFastMathFlags(I.getFastMathFlags());
Benjamin Kramer44993ed2018-01-11 15:19:02 +00001503 Value *Tan = emitUnaryFloatFnCall(
1504 A, TLI.getName(LibFunc_tan), B,
1505 CallSite(Op0).getCalledFunction()->getAttributes());
Dmitry Venikove5fbf592018-01-11 06:33:00 +00001506 Value *One = ConstantFP::get(Tan->getType(), 1.0);
1507 Value *Div = B.CreateFDiv(One, Tan);
1508 return replaceInstUsesWith(I, Div);
1509 }
1510 }
1511 }
1512
Matt Arsenaultfdb78f82017-01-10 23:08:54 +00001513 Value *LHS;
1514 Value *RHS;
1515
1516 // -x / -y -> x / y
1517 if (match(Op0, m_FNeg(m_Value(LHS))) && match(Op1, m_FNeg(m_Value(RHS)))) {
1518 I.setOperand(0, LHS);
1519 I.setOperand(1, RHS);
1520 return &I;
1521 }
1522
Craig Topperf40110f2014-04-25 05:29:35 +00001523 return nullptr;
Frits van Bommel2a559512011-01-29 17:50:27 +00001524}
1525
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001526/// This function implements the transforms common to both integer remainder
1527/// instructions (urem and srem). It is called by the visitors to those integer
1528/// remainder instructions.
1529/// @brief Common integer remainder transforms
1530Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
1531 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1532
Chris Lattner7c99f192011-05-22 18:18:41 +00001533 // The RHS is known non-zero.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001534 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I)) {
Chris Lattner7c99f192011-05-22 18:18:41 +00001535 I.setOperand(1, V);
1536 return &I;
1537 }
1538
Duncan Sandsa3e36992011-05-02 16:27:02 +00001539 // Handle cases involving: rem X, (select Cond, Y, Z)
Sanjay Patelae2e3a42017-10-06 23:20:16 +00001540 if (simplifyDivRemOfSelectWithZeroOp(I))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001541 return &I;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001542
Benjamin Kramer72196f32014-01-19 15:24:22 +00001543 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001544 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1545 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1546 if (Instruction *R = FoldOpIntoSelect(I, SI))
1547 return R;
Craig Topperfb71b7d2017-04-14 19:20:12 +00001548 } else if (auto *PN = dyn_cast<PHINode>(Op0I)) {
Sanjoy Dasb7e861a2016-06-05 21:17:04 +00001549 const APInt *Op1Int;
1550 if (match(Op1, m_APInt(Op1Int)) && !Op1Int->isMinValue() &&
1551 (I.getOpcode() == Instruction::URem ||
1552 !Op1Int->isMinSignedValue())) {
Craig Topperfb71b7d2017-04-14 19:20:12 +00001553 // foldOpIntoPhi will speculate instructions to the end of the PHI's
Sanjoy Dasb7e861a2016-06-05 21:17:04 +00001554 // predecessor blocks, so do this only if we know the srem or urem
1555 // will not fault.
Craig Topperfb71b7d2017-04-14 19:20:12 +00001556 if (Instruction *NV = foldOpIntoPhi(I, PN))
Sanjoy Dasb7e861a2016-06-05 21:17:04 +00001557 return NV;
1558 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001559 }
1560
1561 // See if we can fold away this rem instruction.
1562 if (SimplifyDemandedInstructionBits(I))
1563 return &I;
1564 }
1565 }
1566
Craig Topperf40110f2014-04-25 05:29:35 +00001567 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001568}
1569
1570Instruction *InstCombiner::visitURem(BinaryOperator &I) {
1571 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1572
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001573 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001574 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001575
Craig Toppera4205622017-06-09 03:21:29 +00001576 if (Value *V = SimplifyURemInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001577 return replaceInstUsesWith(I, V);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001578
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001579 if (Instruction *common = commonIRemTransforms(I))
1580 return common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001581
Sanjay Patelbb789382017-08-24 22:54:01 +00001582 if (Instruction *NarrowRem = narrowUDivURem(I, Builder))
1583 return NarrowRem;
David Majnemer6c30f492013-05-12 00:07:05 +00001584
David Majnemer470b0772013-05-11 09:01:28 +00001585 // X urem Y -> X and Y-1, where Y is a power of 2,
Craig Topperd4039f72017-05-25 21:51:12 +00001586 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/ true, 0, &I)) {
Chris Lattner6b657ae2011-02-10 05:36:31 +00001587 Constant *N1 = Constant::getAllOnesValue(I.getType());
Craig Topperbb4069e2017-07-07 23:16:26 +00001588 Value *Add = Builder.CreateAdd(Op1, N1);
Chris Lattner6b657ae2011-02-10 05:36:31 +00001589 return BinaryOperator::CreateAnd(Op0, Add);
1590 }
1591
Nick Lewycky7459be62013-07-13 01:16:47 +00001592 // 1 urem X -> zext(X != 1)
1593 if (match(Op0, m_One())) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001594 Value *Cmp = Builder.CreateICmpNE(Op1, Op0);
1595 Value *Ext = Builder.CreateZExt(Cmp, I.getType());
Sanjay Patel4b198802016-02-01 22:23:39 +00001596 return replaceInstUsesWith(I, Ext);
Nick Lewycky7459be62013-07-13 01:16:47 +00001597 }
1598
Sanjay Patel30ef70b2016-09-22 22:36:26 +00001599 // X urem C -> X < C ? X : X - C, where C >= signbit.
1600 const APInt *DivisorC;
1601 if (match(Op1, m_APInt(DivisorC)) && DivisorC->isNegative()) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001602 Value *Cmp = Builder.CreateICmpULT(Op0, Op1);
1603 Value *Sub = Builder.CreateSub(Op0, Op1);
Sanjay Patel30ef70b2016-09-22 22:36:26 +00001604 return SelectInst::Create(Cmp, Op0, Sub);
1605 }
1606
Craig Topperf40110f2014-04-25 05:29:35 +00001607 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001608}
1609
1610Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
1611 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1612
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001613 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001614 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001615
Craig Toppera4205622017-06-09 03:21:29 +00001616 if (Value *V = SimplifySRemInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001617 return replaceInstUsesWith(I, V);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001618
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001619 // Handle the integer rem common cases
1620 if (Instruction *Common = commonIRemTransforms(I))
1621 return Common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001622
David Majnemerdb077302014-10-13 22:37:51 +00001623 {
1624 const APInt *Y;
1625 // X % -Y -> X % Y
1626 if (match(Op1, m_APInt(Y)) && Y->isNegative() && !Y->isMinSignedValue()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001627 Worklist.AddValue(I.getOperand(1));
David Majnemerdb077302014-10-13 22:37:51 +00001628 I.setOperand(1, ConstantInt::get(I.getType(), -*Y));
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001629 return &I;
1630 }
David Majnemerdb077302014-10-13 22:37:51 +00001631 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001632
1633 // If the sign bits of both operands are zero (i.e. we can prove they are
1634 // unsigned inputs), turn this into a urem.
Craig Topperbcfd2d12017-04-20 16:56:25 +00001635 APInt Mask(APInt::getSignMask(I.getType()->getScalarSizeInBits()));
Craig Topper1a18a7c2017-04-17 01:51:24 +00001636 if (MaskedValueIsZero(Op1, Mask, 0, &I) &&
1637 MaskedValueIsZero(Op0, Mask, 0, &I)) {
1638 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
1639 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001640 }
1641
1642 // If it's a constant vector, flip any negative values positive.
Chris Lattner0256be92012-01-27 03:08:05 +00001643 if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
1644 Constant *C = cast<Constant>(Op1);
1645 unsigned VWidth = C->getType()->getVectorNumElements();
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001646
1647 bool hasNegative = false;
Chris Lattner0256be92012-01-27 03:08:05 +00001648 bool hasMissing = false;
1649 for (unsigned i = 0; i != VWidth; ++i) {
1650 Constant *Elt = C->getAggregateElement(i);
Craig Topperf40110f2014-04-25 05:29:35 +00001651 if (!Elt) {
Chris Lattner0256be92012-01-27 03:08:05 +00001652 hasMissing = true;
1653 break;
1654 }
1655
1656 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
Chris Lattnerb1a15122011-07-15 06:08:15 +00001657 if (RHS->isNegative())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001658 hasNegative = true;
Chris Lattner0256be92012-01-27 03:08:05 +00001659 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001660
Chris Lattner0256be92012-01-27 03:08:05 +00001661 if (hasNegative && !hasMissing) {
Chris Lattner47a86bd2012-01-25 06:02:56 +00001662 SmallVector<Constant *, 16> Elts(VWidth);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001663 for (unsigned i = 0; i != VWidth; ++i) {
Chris Lattner8213c8a2012-02-06 21:56:39 +00001664 Elts[i] = C->getAggregateElement(i); // Handle undef, etc.
Chris Lattner0256be92012-01-27 03:08:05 +00001665 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
Chris Lattnerb1a15122011-07-15 06:08:15 +00001666 if (RHS->isNegative())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001667 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001668 }
1669 }
1670
1671 Constant *NewRHSV = ConstantVector::get(Elts);
Chris Lattner0256be92012-01-27 03:08:05 +00001672 if (NewRHSV != C) { // Don't loop on -MININT
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001673 Worklist.AddValue(I.getOperand(1));
1674 I.setOperand(1, NewRHSV);
1675 return &I;
1676 }
1677 }
1678 }
1679
Craig Topperf40110f2014-04-25 05:29:35 +00001680 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001681}
1682
1683Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Duncan Sandsa3e36992011-05-02 16:27:02 +00001684 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001685
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001686 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001687 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001688
Craig Toppera4205622017-06-09 03:21:29 +00001689 if (Value *V = SimplifyFRemInst(Op0, Op1, I.getFastMathFlags(),
1690 SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001691 return replaceInstUsesWith(I, V);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001692
Craig Topperf40110f2014-04-25 05:29:35 +00001693 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001694}