blob: 9bbabd9203bf05522f1c15faa6f44ebb79b7f345 [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///
Simon Pilgrim0b9f3912018-02-08 14:10:01 +0000135/// If C is a scalar/vector of known powers of 2, then this function returns
136/// a new scalar/vector obtained from logBase2 of C.
Rafael Espindola65281bf2013-05-31 14:27:15 +0000137/// Return a null pointer otherwise.
Simon Pilgrim0b9f3912018-02-08 14:10:01 +0000138static Constant *getLogBase2(Type *Ty, Constant *C) {
Rafael Espindola65281bf2013-05-31 14:27:15 +0000139 const APInt *IVal;
Simon Pilgrim0b9f3912018-02-08 14:10:01 +0000140 if (const auto *CI = dyn_cast<ConstantInt>(C))
Simon Pilgrim4039dbe2018-02-08 14:24:26 +0000141 if (match(CI, m_APInt(IVal)) && IVal->isPowerOf2())
Simon Pilgrim0b9f3912018-02-08 14:10:01 +0000142 return ConstantInt::get(Ty, IVal->logBase2());
Rafael Espindola65281bf2013-05-31 14:27:15 +0000143
Simon Pilgrim0b9f3912018-02-08 14:10:01 +0000144 if (!Ty->isVectorTy())
145 return nullptr;
146
147 SmallVector<Constant *, 4> Elts;
148 for (unsigned I = 0, E = Ty->getVectorNumElements(); I != E; ++I) {
149 Constant *Elt = C->getAggregateElement(I);
150 if (!Elt)
151 return nullptr;
152 if (isa<UndefValue>(Elt)) {
153 Elts.push_back(UndefValue::get(Ty->getScalarType()));
154 continue;
155 }
Rafael Espindola65281bf2013-05-31 14:27:15 +0000156 if (!match(Elt, m_APInt(IVal)) || !IVal->isPowerOf2())
Craig Topperf40110f2014-04-25 05:29:35 +0000157 return nullptr;
Simon Pilgrim0b9f3912018-02-08 14:10:01 +0000158 Elts.push_back(ConstantInt::get(Ty->getScalarType(), IVal->logBase2()));
Rafael Espindola65281bf2013-05-31 14:27:15 +0000159 }
160
161 return ConstantVector::get(Elts);
162}
163
David Majnemer54c2ca22014-12-26 09:10:14 +0000164/// \brief Return true if we can prove that:
165/// (mul LHS, RHS) === (mul nsw LHS, RHS)
Craig Topper2b1fc322017-05-22 06:25:31 +0000166bool InstCombiner::willNotOverflowSignedMul(const Value *LHS,
167 const Value *RHS,
168 const Instruction &CxtI) const {
David Majnemer54c2ca22014-12-26 09:10:14 +0000169 // Multiplying n * m significant bits yields a result of n + m significant
170 // bits. If the total number of significant bits does not exceed the
171 // result bit width (minus 1), there is no overflow.
172 // This means if we have enough leading sign bits in the operands
173 // we can guarantee that the result does not overflow.
174 // Ref: "Hacker's Delight" by Henry Warren
175 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
176
177 // Note that underestimating the number of sign bits gives a more
178 // conservative answer.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000179 unsigned SignBits =
180 ComputeNumSignBits(LHS, 0, &CxtI) + ComputeNumSignBits(RHS, 0, &CxtI);
David Majnemer54c2ca22014-12-26 09:10:14 +0000181
182 // First handle the easy case: if we have enough sign bits there's
183 // definitely no overflow.
184 if (SignBits > BitWidth + 1)
185 return true;
186
187 // There are two ambiguous cases where there can be no overflow:
188 // SignBits == BitWidth + 1 and
189 // SignBits == BitWidth
190 // The second case is difficult to check, therefore we only handle the
191 // first case.
192 if (SignBits == BitWidth + 1) {
193 // It overflows only when both arguments are negative and the true
194 // product is exactly the minimum negative number.
195 // E.g. mul i16 with 17 sign bits: 0xff00 * 0xff80 = 0x8000
196 // For simplicity we just check if at least one side is not negative.
Craig Topper1a36b7d2017-05-15 06:39:41 +0000197 KnownBits LHSKnown = computeKnownBits(LHS, /*Depth=*/0, &CxtI);
198 KnownBits RHSKnown = computeKnownBits(RHS, /*Depth=*/0, &CxtI);
199 if (LHSKnown.isNonNegative() || RHSKnown.isNonNegative())
David Majnemer54c2ca22014-12-26 09:10:14 +0000200 return true;
201 }
202 return false;
203}
204
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000205Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +0000206 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000207 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
208
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000209 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +0000210 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000211
Craig Toppera4205622017-06-09 03:21:29 +0000212 if (Value *V = SimplifyMulInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +0000213 return replaceInstUsesWith(I, V);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000214
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000215 if (Value *V = SimplifyUsingDistributiveLaws(I))
Sanjay Patel4b198802016-02-01 22:23:39 +0000216 return replaceInstUsesWith(I, V);
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000217
David Majnemer027bc802014-11-22 04:52:38 +0000218 // X * -1 == 0 - X
219 if (match(Op1, m_AllOnes())) {
220 BinaryOperator *BO = BinaryOperator::CreateNeg(Op0, I.getName());
221 if (I.hasNoSignedWrap())
222 BO->setHasNoSignedWrap();
223 return BO;
224 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000225
Rafael Espindola65281bf2013-05-31 14:27:15 +0000226 // Also allow combining multiply instructions on vectors.
227 {
228 Value *NewOp;
229 Constant *C1, *C2;
230 const APInt *IVal;
231 if (match(&I, m_Mul(m_Shl(m_Value(NewOp), m_Constant(C2)),
232 m_Constant(C1))) &&
David Majnemerfd4a6d22014-11-22 04:52:52 +0000233 match(C1, m_APInt(IVal))) {
234 // ((X << C2)*C1) == (X * (C1 << C2))
235 Constant *Shl = ConstantExpr::getShl(C1, C2);
236 BinaryOperator *Mul = cast<BinaryOperator>(I.getOperand(0));
237 BinaryOperator *BO = BinaryOperator::CreateMul(NewOp, Shl);
238 if (I.hasNoUnsignedWrap() && Mul->hasNoUnsignedWrap())
239 BO->setHasNoUnsignedWrap();
240 if (I.hasNoSignedWrap() && Mul->hasNoSignedWrap() &&
241 Shl->isNotMinSignedValue())
242 BO->setHasNoSignedWrap();
243 return BO;
244 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000245
Rafael Espindola65281bf2013-05-31 14:27:15 +0000246 if (match(&I, m_Mul(m_Value(NewOp), m_Constant(C1)))) {
Simon Pilgrim0b9f3912018-02-08 14:10:01 +0000247 // Replace X*(2^C) with X << C, where C is either a scalar or a vector.
248 if (Constant *NewCst = getLogBase2(NewOp->getType(), C1)) {
David Majnemer45951a62015-04-18 04:41:30 +0000249 unsigned Width = NewCst->getType()->getPrimitiveSizeInBits();
Rafael Espindola65281bf2013-05-31 14:27:15 +0000250 BinaryOperator *Shl = BinaryOperator::CreateShl(NewOp, NewCst);
Tilmann Scheller2bc5cb62014-10-07 10:19:34 +0000251
Tilmann Scheller2bc5cb62014-10-07 10:19:34 +0000252 if (I.hasNoUnsignedWrap())
253 Shl->setHasNoUnsignedWrap();
David Majnemer45951a62015-04-18 04:41:30 +0000254 if (I.hasNoSignedWrap()) {
Craig Topper5fe01972017-06-27 19:57:53 +0000255 const APInt *V;
256 if (match(NewCst, m_APInt(V)) && *V != Width - 1)
David Majnemer45951a62015-04-18 04:41:30 +0000257 Shl->setHasNoSignedWrap();
258 }
Tilmann Scheller2bc5cb62014-10-07 10:19:34 +0000259
Rafael Espindola65281bf2013-05-31 14:27:15 +0000260 return Shl;
261 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000262 }
Rafael Espindola65281bf2013-05-31 14:27:15 +0000263 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000264
Rafael Espindola65281bf2013-05-31 14:27:15 +0000265 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Stuart Hastings23804832011-06-01 16:42:47 +0000266 // (Y - X) * (-(2**n)) -> (X - Y) * (2**n), for positive nonzero n
267 // (Y + const) * (-(2**n)) -> (-constY) * (2**n), for positive nonzero n
268 // The "* (2**n)" thus becomes a potential shifting opportunity.
Stuart Hastings82843742011-05-30 20:00:33 +0000269 {
270 const APInt & Val = CI->getValue();
271 const APInt &PosVal = Val.abs();
272 if (Val.isNegative() && PosVal.isPowerOf2()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000273 Value *X = nullptr, *Y = nullptr;
Stuart Hastings23804832011-06-01 16:42:47 +0000274 if (Op0->hasOneUse()) {
275 ConstantInt *C1;
Craig Topperf40110f2014-04-25 05:29:35 +0000276 Value *Sub = nullptr;
Stuart Hastings23804832011-06-01 16:42:47 +0000277 if (match(Op0, m_Sub(m_Value(Y), m_Value(X))))
Craig Topperbb4069e2017-07-07 23:16:26 +0000278 Sub = Builder.CreateSub(X, Y, "suba");
Stuart Hastings23804832011-06-01 16:42:47 +0000279 else if (match(Op0, m_Add(m_Value(Y), m_ConstantInt(C1))))
Craig Topperbb4069e2017-07-07 23:16:26 +0000280 Sub = Builder.CreateSub(Builder.CreateNeg(C1), Y, "subc");
Stuart Hastings23804832011-06-01 16:42:47 +0000281 if (Sub)
282 return
283 BinaryOperator::CreateMul(Sub,
284 ConstantInt::get(Y->getType(), PosVal));
Stuart Hastings82843742011-05-30 20:00:33 +0000285 }
286 }
287 }
Chris Lattner6b657ae2011-02-10 05:36:31 +0000288 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000289
Chris Lattner6b657ae2011-02-10 05:36:31 +0000290 // Simplify mul instructions with a constant RHS.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000291 if (isa<Constant>(Op1)) {
Sanjay Pateldb0938f2017-01-10 23:49:07 +0000292 if (Instruction *FoldedMul = foldOpWithConstantIntoOperand(I))
293 return FoldedMul;
Benjamin Kramer72196f32014-01-19 15:24:22 +0000294
295 // Canonicalize (X+C1)*CI -> X*CI+C1*CI.
296 {
297 Value *X;
298 Constant *C1;
299 if (match(Op0, m_OneUse(m_Add(m_Value(X), m_Constant(C1))))) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000300 Value *Mul = Builder.CreateMul(C1, Op1);
David Majnemer6cf6c052014-06-19 07:14:33 +0000301 // Only go forward with the transform if C1*CI simplifies to a tidier
302 // constant.
303 if (!match(Mul, m_Mul(m_Value(), m_Value())))
Craig Topperbb4069e2017-07-07 23:16:26 +0000304 return BinaryOperator::CreateAdd(Builder.CreateMul(X, Op1), Mul);
Benjamin Kramer72196f32014-01-19 15:24:22 +0000305 }
306 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000307 }
308
David Majnemer8279a7502014-11-22 07:25:19 +0000309 if (Value *Op0v = dyn_castNegVal(Op0)) { // -X * -Y = X*Y
310 if (Value *Op1v = dyn_castNegVal(Op1)) {
311 BinaryOperator *BO = BinaryOperator::CreateMul(Op0v, Op1v);
312 if (I.hasNoSignedWrap() &&
313 match(Op0, m_NSWSub(m_Value(), m_Value())) &&
314 match(Op1, m_NSWSub(m_Value(), m_Value())))
315 BO->setHasNoSignedWrap();
316 return BO;
317 }
318 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000319
320 // (X / Y) * Y = X - (X % Y)
321 // (X / Y) * -Y = (X % Y) - X
322 {
Sanjay Patela0a56822017-03-14 17:27:27 +0000323 Value *Y = Op1;
324 BinaryOperator *Div = dyn_cast<BinaryOperator>(Op0);
325 if (!Div || (Div->getOpcode() != Instruction::UDiv &&
326 Div->getOpcode() != Instruction::SDiv)) {
327 Y = Op0;
328 Div = dyn_cast<BinaryOperator>(Op1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000329 }
Sanjay Patela0a56822017-03-14 17:27:27 +0000330 Value *Neg = dyn_castNegVal(Y);
331 if (Div && Div->hasOneUse() &&
332 (Div->getOperand(1) == Y || Div->getOperand(1) == Neg) &&
333 (Div->getOpcode() == Instruction::UDiv ||
334 Div->getOpcode() == Instruction::SDiv)) {
335 Value *X = Div->getOperand(0), *DivOp1 = Div->getOperand(1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000336
Chris Lattner35315d02011-02-06 21:44:57 +0000337 // If the division is exact, X % Y is zero, so we end up with X or -X.
Sanjay Patela0a56822017-03-14 17:27:27 +0000338 if (Div->isExact()) {
339 if (DivOp1 == Y)
340 return replaceInstUsesWith(I, X);
341 return BinaryOperator::CreateNeg(X);
342 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000343
Sanjay Patela0a56822017-03-14 17:27:27 +0000344 auto RemOpc = Div->getOpcode() == Instruction::UDiv ? Instruction::URem
345 : Instruction::SRem;
Craig Topperbb4069e2017-07-07 23:16:26 +0000346 Value *Rem = Builder.CreateBinOp(RemOpc, X, DivOp1);
Sanjay Patela0a56822017-03-14 17:27:27 +0000347 if (DivOp1 == Y)
348 return BinaryOperator::CreateSub(X, Rem);
349 return BinaryOperator::CreateSub(Rem, X);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000350 }
351 }
352
353 /// i1 mul -> i1 and.
Craig Topperfde47232017-07-09 07:04:03 +0000354 if (I.getType()->isIntOrIntVectorTy(1))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000355 return BinaryOperator::CreateAnd(Op0, Op1);
356
357 // X*(1 << Y) --> X << Y
358 // (1 << Y)*X --> X << Y
359 {
360 Value *Y;
David Majnemer546f8102014-11-22 08:57:02 +0000361 BinaryOperator *BO = nullptr;
362 bool ShlNSW = false;
363 if (match(Op0, m_Shl(m_One(), m_Value(Y)))) {
364 BO = BinaryOperator::CreateShl(Op1, Y);
David Majnemer087dc8b2015-01-04 07:36:02 +0000365 ShlNSW = cast<ShlOperator>(Op0)->hasNoSignedWrap();
David Majnemer8e6f6a92014-11-24 16:41:13 +0000366 } else if (match(Op1, m_Shl(m_One(), m_Value(Y)))) {
David Majnemer546f8102014-11-22 08:57:02 +0000367 BO = BinaryOperator::CreateShl(Op0, Y);
David Majnemer087dc8b2015-01-04 07:36:02 +0000368 ShlNSW = cast<ShlOperator>(Op1)->hasNoSignedWrap();
David Majnemer546f8102014-11-22 08:57:02 +0000369 }
370 if (BO) {
371 if (I.hasNoUnsignedWrap())
372 BO->setHasNoUnsignedWrap();
373 if (I.hasNoSignedWrap() && ShlNSW)
374 BO->setHasNoSignedWrap();
375 return BO;
376 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000377 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000378
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000379 // If one of the operands of the multiply is a cast from a boolean value, then
380 // we know the bool is either zero or one, so this is a 'masking' multiply.
381 // X * Y (where Y is 0 or 1) -> X & (0-Y)
Duncan Sands19d0b472010-02-16 11:11:14 +0000382 if (!I.getType()->isVectorTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000383 // -2 is "-1 << 1" so it is all bits set except the low one.
384 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000385
Craig Topperf40110f2014-04-25 05:29:35 +0000386 Value *BoolCast = nullptr, *OtherOp = nullptr;
Richard Trieu7a083812016-02-18 22:09:30 +0000387 if (MaskedValueIsZero(Op0, Negative2, 0, &I)) {
388 BoolCast = Op0;
389 OtherOp = Op1;
390 } else if (MaskedValueIsZero(Op1, Negative2, 0, &I)) {
391 BoolCast = Op1;
392 OtherOp = Op0;
393 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000394
395 if (BoolCast) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000396 Value *V = Builder.CreateSub(Constant::getNullValue(I.getType()),
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000397 BoolCast);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000398 return BinaryOperator::CreateAnd(V, OtherOp);
399 }
400 }
401
David Majnemera1cfd7c2016-12-30 00:28:58 +0000402 // Check for (mul (sext x), y), see if we can merge this into an
403 // integer mul followed by a sext.
404 if (SExtInst *Op0Conv = dyn_cast<SExtInst>(Op0)) {
405 // (mul (sext x), cst) --> (sext (mul x, cst'))
406 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
407 if (Op0Conv->hasOneUse()) {
408 Constant *CI =
409 ConstantExpr::getTrunc(Op1C, Op0Conv->getOperand(0)->getType());
410 if (ConstantExpr::getSExt(CI, I.getType()) == Op1C &&
Craig Topper2b1fc322017-05-22 06:25:31 +0000411 willNotOverflowSignedMul(Op0Conv->getOperand(0), CI, I)) {
David Majnemera1cfd7c2016-12-30 00:28:58 +0000412 // Insert the new, smaller mul.
413 Value *NewMul =
Craig Topperbb4069e2017-07-07 23:16:26 +0000414 Builder.CreateNSWMul(Op0Conv->getOperand(0), CI, "mulconv");
David Majnemera1cfd7c2016-12-30 00:28:58 +0000415 return new SExtInst(NewMul, I.getType());
416 }
417 }
418 }
419
420 // (mul (sext x), (sext y)) --> (sext (mul int x, y))
421 if (SExtInst *Op1Conv = dyn_cast<SExtInst>(Op1)) {
422 // Only do this if x/y have the same type, if at last one of them has a
423 // single use (so we don't increase the number of sexts), and if the
424 // integer mul will not overflow.
425 if (Op0Conv->getOperand(0)->getType() ==
426 Op1Conv->getOperand(0)->getType() &&
427 (Op0Conv->hasOneUse() || Op1Conv->hasOneUse()) &&
Craig Topper2b1fc322017-05-22 06:25:31 +0000428 willNotOverflowSignedMul(Op0Conv->getOperand(0),
David Majnemera1cfd7c2016-12-30 00:28:58 +0000429 Op1Conv->getOperand(0), I)) {
430 // Insert the new integer mul.
Craig Topperbb4069e2017-07-07 23:16:26 +0000431 Value *NewMul = Builder.CreateNSWMul(
David Majnemera1cfd7c2016-12-30 00:28:58 +0000432 Op0Conv->getOperand(0), Op1Conv->getOperand(0), "mulconv");
433 return new SExtInst(NewMul, I.getType());
434 }
435 }
436 }
437
438 // Check for (mul (zext x), y), see if we can merge this into an
439 // integer mul followed by a zext.
440 if (auto *Op0Conv = dyn_cast<ZExtInst>(Op0)) {
441 // (mul (zext x), cst) --> (zext (mul x, cst'))
442 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
443 if (Op0Conv->hasOneUse()) {
444 Constant *CI =
445 ConstantExpr::getTrunc(Op1C, Op0Conv->getOperand(0)->getType());
446 if (ConstantExpr::getZExt(CI, I.getType()) == Op1C &&
Craig Topperbb973722017-05-15 02:44:08 +0000447 willNotOverflowUnsignedMul(Op0Conv->getOperand(0), CI, I)) {
David Majnemera1cfd7c2016-12-30 00:28:58 +0000448 // Insert the new, smaller mul.
449 Value *NewMul =
Craig Topperbb4069e2017-07-07 23:16:26 +0000450 Builder.CreateNUWMul(Op0Conv->getOperand(0), CI, "mulconv");
David Majnemera1cfd7c2016-12-30 00:28:58 +0000451 return new ZExtInst(NewMul, I.getType());
452 }
453 }
454 }
455
456 // (mul (zext x), (zext y)) --> (zext (mul int x, y))
457 if (auto *Op1Conv = dyn_cast<ZExtInst>(Op1)) {
458 // Only do this if x/y have the same type, if at last one of them has a
459 // single use (so we don't increase the number of zexts), and if the
460 // integer mul will not overflow.
461 if (Op0Conv->getOperand(0)->getType() ==
462 Op1Conv->getOperand(0)->getType() &&
463 (Op0Conv->hasOneUse() || Op1Conv->hasOneUse()) &&
Craig Topperbb973722017-05-15 02:44:08 +0000464 willNotOverflowUnsignedMul(Op0Conv->getOperand(0),
465 Op1Conv->getOperand(0), I)) {
David Majnemera1cfd7c2016-12-30 00:28:58 +0000466 // Insert the new integer mul.
Craig Topperbb4069e2017-07-07 23:16:26 +0000467 Value *NewMul = Builder.CreateNUWMul(
David Majnemera1cfd7c2016-12-30 00:28:58 +0000468 Op0Conv->getOperand(0), Op1Conv->getOperand(0), "mulconv");
469 return new ZExtInst(NewMul, I.getType());
470 }
471 }
472 }
473
Craig Topper2b1fc322017-05-22 06:25:31 +0000474 if (!I.hasNoSignedWrap() && willNotOverflowSignedMul(Op0, Op1, I)) {
David Majnemer54c2ca22014-12-26 09:10:14 +0000475 Changed = true;
476 I.setHasNoSignedWrap(true);
477 }
478
Craig Topperbb973722017-05-15 02:44:08 +0000479 if (!I.hasNoUnsignedWrap() && willNotOverflowUnsignedMul(Op0, Op1, I)) {
David Majnemerb1296ec2014-12-26 09:50:35 +0000480 Changed = true;
481 I.setHasNoUnsignedWrap(true);
482 }
483
Craig Topperf40110f2014-04-25 05:29:35 +0000484 return Changed ? &I : nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000485}
486
Sanjay Patel17045f72014-10-14 00:33:23 +0000487/// Detect pattern log2(Y * 0.5) with corresponding fast math flags.
Pedro Artigas993acd02012-11-30 22:07:05 +0000488static void detectLog2OfHalf(Value *&Op, Value *&Y, IntrinsicInst *&Log2) {
Sanjay Patel17045f72014-10-14 00:33:23 +0000489 if (!Op->hasOneUse())
490 return;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000491
Sanjay Patel17045f72014-10-14 00:33:23 +0000492 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op);
493 if (!II)
494 return;
Sanjay Patel629c4112017-11-06 16:27:15 +0000495 if (II->getIntrinsicID() != Intrinsic::log2 || !II->isFast())
Sanjay Patel17045f72014-10-14 00:33:23 +0000496 return;
497 Log2 = II;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000498
Sanjay Patel17045f72014-10-14 00:33:23 +0000499 Value *OpLog2Of = II->getArgOperand(0);
500 if (!OpLog2Of->hasOneUse())
501 return;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000502
Sanjay Patel17045f72014-10-14 00:33:23 +0000503 Instruction *I = dyn_cast<Instruction>(OpLog2Of);
504 if (!I)
505 return;
Sanjay Patel629c4112017-11-06 16:27:15 +0000506
507 if (I->getOpcode() != Instruction::FMul || !I->isFast())
Sanjay Patel17045f72014-10-14 00:33:23 +0000508 return;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000509
Sanjay Patel17045f72014-10-14 00:33:23 +0000510 if (match(I->getOperand(0), m_SpecificFP(0.5)))
511 Y = I->getOperand(1);
512 else if (match(I->getOperand(1), m_SpecificFP(0.5)))
513 Y = I->getOperand(0);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000514}
Pedro Artigas993acd02012-11-30 22:07:05 +0000515
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000516static bool isFiniteNonZeroFp(Constant *C) {
517 if (C->getType()->isVectorTy()) {
518 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
519 ++I) {
Michael Kupersteinbcb26d62015-03-05 08:38:57 +0000520 ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(C->getAggregateElement(I));
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000521 if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
522 return false;
523 }
524 return true;
525 }
526
527 return isa<ConstantFP>(C) &&
528 cast<ConstantFP>(C)->getValueAPF().isFiniteNonZero();
529}
530
531static bool isNormalFp(Constant *C) {
532 if (C->getType()->isVectorTy()) {
533 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
534 ++I) {
Michael Kupersteinbcb26d62015-03-05 08:38:57 +0000535 ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(C->getAggregateElement(I));
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000536 if (!CFP || !CFP->getValueAPF().isNormal())
537 return false;
538 }
539 return true;
540 }
541
542 return isa<ConstantFP>(C) && cast<ConstantFP>(C)->getValueAPF().isNormal();
543}
544
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000545/// Helper function of InstCombiner::visitFMul(BinaryOperator(). It returns
546/// true iff the given value is FMul or FDiv with one and only one operand
547/// being a normal constant (i.e. not Zero/NaN/Infinity).
548static bool isFMulOrFDivWithConstant(Value *V) {
549 Instruction *I = dyn_cast<Instruction>(V);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000550 if (!I || (I->getOpcode() != Instruction::FMul &&
Shuxin Yang80138662013-01-07 22:41:28 +0000551 I->getOpcode() != Instruction::FDiv))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000552 return false;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000553
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000554 Constant *C0 = dyn_cast<Constant>(I->getOperand(0));
555 Constant *C1 = dyn_cast<Constant>(I->getOperand(1));
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000556
557 if (C0 && C1)
558 return false;
559
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000560 return (C0 && isFiniteNonZeroFp(C0)) || (C1 && isFiniteNonZeroFp(C1));
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000561}
562
563/// foldFMulConst() is a helper routine of InstCombiner::visitFMul().
564/// The input \p FMulOrDiv is a FMul/FDiv with one and only one operand
565/// being a constant (i.e. isFMulOrFDivWithConstant(FMulOrDiv) == true).
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000566/// This function is to simplify "FMulOrDiv * C" and returns the
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000567/// resulting expression. Note that this function could return NULL in
568/// case the constants cannot be folded into a normal floating-point.
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000569Value *InstCombiner::foldFMulConst(Instruction *FMulOrDiv, Constant *C,
Shuxin Yang80138662013-01-07 22:41:28 +0000570 Instruction *InsertBefore) {
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000571 assert(isFMulOrFDivWithConstant(FMulOrDiv) && "V is invalid");
572
573 Value *Opnd0 = FMulOrDiv->getOperand(0);
574 Value *Opnd1 = FMulOrDiv->getOperand(1);
575
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000576 Constant *C0 = dyn_cast<Constant>(Opnd0);
577 Constant *C1 = dyn_cast<Constant>(Opnd1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000578
Craig Topperf40110f2014-04-25 05:29:35 +0000579 BinaryOperator *R = nullptr;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000580
581 // (X * C0) * C => X * (C0*C)
582 if (FMulOrDiv->getOpcode() == Instruction::FMul) {
583 Constant *F = ConstantExpr::getFMul(C1 ? C1 : C0, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000584 if (isNormalFp(F))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000585 R = BinaryOperator::CreateFMul(C1 ? Opnd0 : Opnd1, F);
586 } else {
587 if (C0) {
588 // (C0 / X) * C => (C0 * C) / X
Shuxin Yang3a7ca6e2013-09-19 21:13:46 +0000589 if (FMulOrDiv->hasOneUse()) {
590 // It would otherwise introduce another div.
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000591 Constant *F = ConstantExpr::getFMul(C0, C);
Shuxin Yang3a7ca6e2013-09-19 21:13:46 +0000592 if (isNormalFp(F))
593 R = BinaryOperator::CreateFDiv(F, Opnd1);
594 }
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000595 } else {
596 // (X / C1) * C => X * (C/C1) if C/C1 is not a denormal
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000597 Constant *F = ConstantExpr::getFDiv(C, C1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000598 if (isNormalFp(F)) {
599 R = BinaryOperator::CreateFMul(Opnd0, F);
600 } else {
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000601 // (X / C1) * C => X / (C1/C)
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000602 Constant *F = ConstantExpr::getFDiv(C1, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000603 if (isNormalFp(F))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000604 R = BinaryOperator::CreateFDiv(Opnd0, F);
605 }
606 }
607 }
608
609 if (R) {
Sanjay Patel629c4112017-11-06 16:27:15 +0000610 R->setFast(true);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000611 InsertNewInstWith(R, *InsertBefore);
612 }
613
614 return R;
615}
616
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000617Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +0000618 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000619 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
620
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000621 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +0000622 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000623
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000624 if (isa<Constant>(Op0))
625 std::swap(Op0, Op1);
626
Craig Toppera4205622017-06-09 03:21:29 +0000627 if (Value *V = SimplifyFMulInst(Op0, Op1, I.getFastMathFlags(),
628 SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +0000629 return replaceInstUsesWith(I, V);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000630
Sanjay Patel629c4112017-11-06 16:27:15 +0000631 bool AllowReassociate = I.isFast();
Shuxin Yange8227452013-01-15 21:09:32 +0000632
Michael Ilsemand5787be2012-12-12 00:28:32 +0000633 // Simplify mul instructions with a constant RHS.
634 if (isa<Constant>(Op1)) {
Sanjay Pateldb0938f2017-01-10 23:49:07 +0000635 if (Instruction *FoldedMul = foldOpWithConstantIntoOperand(I))
636 return FoldedMul;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000637
Owen Andersonf74cfe02014-01-16 20:36:42 +0000638 // (fmul X, -1.0) --> (fsub -0.0, X)
Benjamin Kramerfea9ac92014-01-18 16:43:14 +0000639 if (match(Op1, m_SpecificFP(-1.0))) {
640 Constant *NegZero = ConstantFP::getNegativeZero(Op1->getType());
641 Instruction *RI = BinaryOperator::CreateFSub(NegZero, Op0);
Owen Andersonf74cfe02014-01-16 20:36:42 +0000642 RI->copyFastMathFlags(&I);
643 return RI;
644 }
645
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000646 Constant *C = cast<Constant>(Op1);
647 if (AllowReassociate && isFiniteNonZeroFp(C)) {
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000648 // Let MDC denote an expression in one of these forms:
649 // X * C, C/X, X/C, where C is a constant.
650 //
651 // Try to simplify "MDC * Constant"
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000652 if (isFMulOrFDivWithConstant(Op0))
653 if (Value *V = foldFMulConst(cast<Instruction>(Op0), C, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +0000654 return replaceInstUsesWith(I, V);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000655
Quentin Colombete684a6d2013-02-28 21:12:40 +0000656 // (MDC +/- C1) * C => (MDC * C) +/- (C1 * C)
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000657 Instruction *FAddSub = dyn_cast<Instruction>(Op0);
658 if (FAddSub &&
659 (FAddSub->getOpcode() == Instruction::FAdd ||
660 FAddSub->getOpcode() == Instruction::FSub)) {
661 Value *Opnd0 = FAddSub->getOperand(0);
662 Value *Opnd1 = FAddSub->getOperand(1);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000663 Constant *C0 = dyn_cast<Constant>(Opnd0);
664 Constant *C1 = dyn_cast<Constant>(Opnd1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000665 bool Swap = false;
666 if (C0) {
Shuxin Yang80138662013-01-07 22:41:28 +0000667 std::swap(C0, C1);
668 std::swap(Opnd0, Opnd1);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000669 Swap = true;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000670 }
671
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000672 if (C1 && isFiniteNonZeroFp(C1) && isFMulOrFDivWithConstant(Opnd0)) {
Quentin Colombete684a6d2013-02-28 21:12:40 +0000673 Value *M1 = ConstantExpr::getFMul(C1, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000674 Value *M0 = isNormalFp(cast<Constant>(M1)) ?
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000675 foldFMulConst(cast<Instruction>(Opnd0), C, &I) :
Craig Topperf40110f2014-04-25 05:29:35 +0000676 nullptr;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000677 if (M0 && M1) {
678 if (Swap && FAddSub->getOpcode() == Instruction::FSub)
679 std::swap(M0, M1);
680
Benjamin Kramer67485762013-09-30 15:39:59 +0000681 Instruction *RI = (FAddSub->getOpcode() == Instruction::FAdd)
682 ? BinaryOperator::CreateFAdd(M0, M1)
683 : BinaryOperator::CreateFSub(M0, M1);
Shuxin Yange8227452013-01-15 21:09:32 +0000684 RI->copyFastMathFlags(&I);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000685 return RI;
686 }
687 }
688 }
689 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000690 }
691
Matt Arsenault56c079f2016-01-30 05:02:00 +0000692 if (Op0 == Op1) {
693 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
694 // sqrt(X) * sqrt(X) -> X
695 if (AllowReassociate && II->getIntrinsicID() == Intrinsic::sqrt)
Sanjay Patel4b198802016-02-01 22:23:39 +0000696 return replaceInstUsesWith(I, II->getOperand(0));
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000697
Matt Arsenault56c079f2016-01-30 05:02:00 +0000698 // fabs(X) * fabs(X) -> X * X
699 if (II->getIntrinsicID() == Intrinsic::fabs) {
700 Instruction *FMulVal = BinaryOperator::CreateFMul(II->getOperand(0),
701 II->getOperand(0),
702 I.getName());
703 FMulVal->copyFastMathFlags(&I);
704 return FMulVal;
705 }
706 }
707 }
708
Pedro Artigasd8795042012-11-30 19:09:41 +0000709 // Under unsafe algebra do:
710 // X * log2(0.5*Y) = X*log2(Y) - X
Sanjay Patelb41d4612014-10-02 15:20:45 +0000711 if (AllowReassociate) {
Craig Topperf40110f2014-04-25 05:29:35 +0000712 Value *OpX = nullptr;
713 Value *OpY = nullptr;
Pedro Artigasd8795042012-11-30 19:09:41 +0000714 IntrinsicInst *Log2;
Pedro Artigas993acd02012-11-30 22:07:05 +0000715 detectLog2OfHalf(Op0, OpY, Log2);
716 if (OpY) {
717 OpX = Op1;
718 } else {
719 detectLog2OfHalf(Op1, OpY, Log2);
720 if (OpY) {
721 OpX = Op0;
Pedro Artigasd8795042012-11-30 19:09:41 +0000722 }
723 }
724 // if pattern detected emit alternate sequence
725 if (OpX && OpY) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000726 BuilderTy::FastMathFlagGuard Guard(Builder);
727 Builder.setFastMathFlags(Log2->getFastMathFlags());
Pedro Artigasd8795042012-11-30 19:09:41 +0000728 Log2->setArgOperand(0, OpY);
Craig Topperbb4069e2017-07-07 23:16:26 +0000729 Value *FMulVal = Builder.CreateFMul(OpX, Log2);
730 Value *FSub = Builder.CreateFSub(FMulVal, OpX);
Benjamin Kramer67485762013-09-30 15:39:59 +0000731 FSub->takeName(&I);
Sanjay Patel4b198802016-02-01 22:23:39 +0000732 return replaceInstUsesWith(I, FSub);
Pedro Artigasd8795042012-11-30 19:09:41 +0000733 }
734 }
735
Dmitry Venikova58d8de2018-01-02 05:58:11 +0000736 // sqrt(a) * sqrt(b) -> sqrt(a * b)
737 if (AllowReassociate &&
738 Op0->hasOneUse() && Op1->hasOneUse()) {
739 Value *Opnd0 = nullptr;
740 Value *Opnd1 = nullptr;
741 if (match(Op0, m_Intrinsic<Intrinsic::sqrt>(m_Value(Opnd0))) &&
742 match(Op1, m_Intrinsic<Intrinsic::sqrt>(m_Value(Opnd1)))) {
743 BuilderTy::FastMathFlagGuard Guard(Builder);
744 Builder.setFastMathFlags(I.getFastMathFlags());
745 Value *FMulVal = Builder.CreateFMul(Opnd0, Opnd1);
746 Value *Sqrt = Intrinsic::getDeclaration(I.getModule(),
747 Intrinsic::sqrt, I.getType());
748 Value *SqrtCall = Builder.CreateCall(Sqrt, FMulVal);
749 return replaceInstUsesWith(I, SqrtCall);
750 }
751 }
752
Shuxin Yange8227452013-01-15 21:09:32 +0000753 // Handle symmetric situation in a 2-iteration loop
754 Value *Opnd0 = Op0;
755 Value *Opnd1 = Op1;
756 for (int i = 0; i < 2; i++) {
757 bool IgnoreZeroSign = I.hasNoSignedZeros();
758 if (BinaryOperator::isFNeg(Opnd0, IgnoreZeroSign)) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000759 BuilderTy::FastMathFlagGuard Guard(Builder);
760 Builder.setFastMathFlags(I.getFastMathFlags());
Benjamin Kramer67485762013-09-30 15:39:59 +0000761
Shuxin Yange8227452013-01-15 21:09:32 +0000762 Value *N0 = dyn_castFNegVal(Opnd0, IgnoreZeroSign);
763 Value *N1 = dyn_castFNegVal(Opnd1, IgnoreZeroSign);
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000764
Shuxin Yange8227452013-01-15 21:09:32 +0000765 // -X * -Y => X*Y
Owen Andersone8537fc2014-01-16 20:59:41 +0000766 if (N1) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000767 Value *FMul = Builder.CreateFMul(N0, N1);
Owen Andersone8537fc2014-01-16 20:59:41 +0000768 FMul->takeName(&I);
Sanjay Patel4b198802016-02-01 22:23:39 +0000769 return replaceInstUsesWith(I, FMul);
Owen Andersone8537fc2014-01-16 20:59:41 +0000770 }
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000771
Shuxin Yange8227452013-01-15 21:09:32 +0000772 if (Opnd0->hasOneUse()) {
773 // -X * Y => -(X*Y) (Promote negation as high as possible)
Craig Topperbb4069e2017-07-07 23:16:26 +0000774 Value *T = Builder.CreateFMul(N0, Opnd1);
775 Value *Neg = Builder.CreateFNeg(T);
Benjamin Kramer67485762013-09-30 15:39:59 +0000776 Neg->takeName(&I);
Sanjay Patel4b198802016-02-01 22:23:39 +0000777 return replaceInstUsesWith(I, Neg);
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000778 }
779 }
Shuxin Yange8227452013-01-15 21:09:32 +0000780
Quentin Colombetaa103b32017-09-20 17:32:16 +0000781 // Handle specials cases for FMul with selects feeding the operation
782 if (Value *V = SimplifySelectsFeedingBinaryOp(I, Op0, Op1))
783 return replaceInstUsesWith(I, V);
784
Shuxin Yange8227452013-01-15 21:09:32 +0000785 // (X*Y) * X => (X*X) * Y where Y != X
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000786 // The purpose is two-fold:
Shuxin Yange8227452013-01-15 21:09:32 +0000787 // 1) to form a power expression (of X).
788 // 2) potentially shorten the critical path: After transformation, the
789 // latency of the instruction Y is amortized by the expression of X*X,
790 // and therefore Y is in a "less critical" position compared to what it
791 // was before the transformation.
Shuxin Yange8227452013-01-15 21:09:32 +0000792 if (AllowReassociate) {
793 Value *Opnd0_0, *Opnd0_1;
794 if (Opnd0->hasOneUse() &&
795 match(Opnd0, m_FMul(m_Value(Opnd0_0), m_Value(Opnd0_1)))) {
Craig Topperf40110f2014-04-25 05:29:35 +0000796 Value *Y = nullptr;
Shuxin Yange8227452013-01-15 21:09:32 +0000797 if (Opnd0_0 == Opnd1 && Opnd0_1 != Opnd1)
798 Y = Opnd0_1;
799 else if (Opnd0_1 == Opnd1 && Opnd0_0 != Opnd1)
800 Y = Opnd0_0;
801
802 if (Y) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000803 BuilderTy::FastMathFlagGuard Guard(Builder);
804 Builder.setFastMathFlags(I.getFastMathFlags());
805 Value *T = Builder.CreateFMul(Opnd1, Opnd1);
806 Value *R = Builder.CreateFMul(T, Y);
Benjamin Kramer67485762013-09-30 15:39:59 +0000807 R->takeName(&I);
Sanjay Patel4b198802016-02-01 22:23:39 +0000808 return replaceInstUsesWith(I, R);
Shuxin Yange8227452013-01-15 21:09:32 +0000809 }
810 }
811 }
812
813 if (!isa<Constant>(Op1))
814 std::swap(Opnd0, Opnd1);
815 else
816 break;
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000817 }
818
Craig Topperf40110f2014-04-25 05:29:35 +0000819 return Changed ? &I : nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000820}
821
Sanjay Patelae2e3a42017-10-06 23:20:16 +0000822/// Fold a divide or remainder with a select instruction divisor when one of the
823/// select operands is zero. In that case, we can use the other select operand
824/// because div/rem by zero is undefined.
825bool InstCombiner::simplifyDivRemOfSelectWithZeroOp(BinaryOperator &I) {
826 SelectInst *SI = dyn_cast<SelectInst>(I.getOperand(1));
827 if (!SI)
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000828 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000829
Sanjay Patelae2e3a42017-10-06 23:20:16 +0000830 int NonNullOperand;
831 if (match(SI->getTrueValue(), m_Zero()))
832 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
833 NonNullOperand = 2;
834 else if (match(SI->getFalseValue(), m_Zero()))
835 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
836 NonNullOperand = 1;
837 else
838 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000839
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000840 // Change the div/rem to use 'Y' instead of the select.
841 I.setOperand(1, SI->getOperand(NonNullOperand));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000842
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000843 // Okay, we know we replace the operand of the div/rem with 'Y' with no
844 // problem. However, the select, or the condition of the select may have
845 // multiple uses. Based on our knowledge that the operand must be non-zero,
846 // propagate the known value for the select into other uses of it, and
847 // propagate a known value of the condition into its other users.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000848
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000849 // If the select and condition only have a single use, don't bother with this,
850 // early exit.
Sanjay Patelae2e3a42017-10-06 23:20:16 +0000851 Value *SelectCond = SI->getCondition();
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000852 if (SI->use_empty() && SelectCond->hasOneUse())
853 return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000854
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000855 // Scan the current block backward, looking for other uses of SI.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000856 BasicBlock::iterator BBI = I.getIterator(), BBFront = I.getParent()->begin();
Sanjay Patel72d339a2017-10-06 23:43:06 +0000857 Type *CondTy = SelectCond->getType();
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000858 while (BBI != BBFront) {
859 --BBI;
860 // If we found a call to a function, we can't assume it will return, so
861 // information from below it cannot be propagated above it.
862 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
863 break;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000864
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000865 // Replace uses of the select or its condition with the known values.
866 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
867 I != E; ++I) {
868 if (*I == SI) {
869 *I = SI->getOperand(NonNullOperand);
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000870 Worklist.Add(&*BBI);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000871 } else if (*I == SelectCond) {
Sanjay Patel72d339a2017-10-06 23:43:06 +0000872 *I = NonNullOperand == 1 ? ConstantInt::getTrue(CondTy)
873 : ConstantInt::getFalse(CondTy);
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000874 Worklist.Add(&*BBI);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000875 }
876 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000877
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000878 // If we past the instruction, quit looking for it.
879 if (&*BBI == SI)
Craig Topperf40110f2014-04-25 05:29:35 +0000880 SI = nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000881 if (&*BBI == SelectCond)
Craig Topperf40110f2014-04-25 05:29:35 +0000882 SelectCond = nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000883
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000884 // If we ran out of things to eliminate, break out of the loop.
Craig Topperf40110f2014-04-25 05:29:35 +0000885 if (!SelectCond && !SI)
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000886 break;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000887
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000888 }
889 return true;
890}
891
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000892/// This function implements the transforms common to both integer division
893/// instructions (udiv and sdiv). It is called by the visitors to those integer
894/// division instructions.
895/// @brief Common integer divide transforms
896Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
897 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Sanjay Patel9530f182018-01-21 16:14:51 +0000898 bool IsSigned = I.getOpcode() == Instruction::SDiv;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000899
Chris Lattner7c99f192011-05-22 18:18:41 +0000900 // The RHS is known non-zero.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000901 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I)) {
Chris Lattner7c99f192011-05-22 18:18:41 +0000902 I.setOperand(1, V);
903 return &I;
904 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000905
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000906 // Handle cases involving: [su]div X, (select Cond, Y, Z)
907 // This does not apply for fdiv.
Sanjay Patelae2e3a42017-10-06 23:20:16 +0000908 if (simplifyDivRemOfSelectWithZeroOp(I))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000909 return &I;
910
David Majnemer27adb122014-10-12 08:34:24 +0000911 if (Instruction *LHS = dyn_cast<Instruction>(Op0)) {
912 const APInt *C2;
913 if (match(Op1, m_APInt(C2))) {
David Majnemerf9a095d2014-08-16 08:55:06 +0000914 Value *X;
David Majnemer27adb122014-10-12 08:34:24 +0000915 const APInt *C1;
David Majnemerf9a095d2014-08-16 08:55:06 +0000916
David Majnemer27adb122014-10-12 08:34:24 +0000917 // (X / C1) / C2 -> X / (C1*C2)
918 if ((IsSigned && match(LHS, m_SDiv(m_Value(X), m_APInt(C1)))) ||
919 (!IsSigned && match(LHS, m_UDiv(m_Value(X), m_APInt(C1))))) {
920 APInt Product(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
921 if (!MultiplyOverflows(*C1, *C2, Product, IsSigned))
922 return BinaryOperator::Create(I.getOpcode(), X,
923 ConstantInt::get(I.getType(), Product));
924 }
David Majnemerf9a095d2014-08-16 08:55:06 +0000925
David Majnemer27adb122014-10-12 08:34:24 +0000926 if ((IsSigned && match(LHS, m_NSWMul(m_Value(X), m_APInt(C1)))) ||
927 (!IsSigned && match(LHS, m_NUWMul(m_Value(X), m_APInt(C1))))) {
928 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
929
930 // (X * C1) / C2 -> X / (C2 / C1) if C2 is a multiple of C1.
931 if (IsMultiple(*C2, *C1, Quotient, IsSigned)) {
932 BinaryOperator *BO = BinaryOperator::Create(
933 I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
934 BO->setIsExact(I.isExact());
935 return BO;
David Majnemerf9a095d2014-08-16 08:55:06 +0000936 }
937
David Majnemer27adb122014-10-12 08:34:24 +0000938 // (X * C1) / C2 -> X * (C1 / C2) if C1 is a multiple of C2.
939 if (IsMultiple(*C1, *C2, Quotient, IsSigned)) {
940 BinaryOperator *BO = BinaryOperator::Create(
941 Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
942 BO->setHasNoUnsignedWrap(
943 !IsSigned &&
944 cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
945 BO->setHasNoSignedWrap(
946 cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
947 return BO;
David Majnemerf9a095d2014-08-16 08:55:06 +0000948 }
949 }
David Majnemerf9a095d2014-08-16 08:55:06 +0000950
David Majnemer27adb122014-10-12 08:34:24 +0000951 if ((IsSigned && match(LHS, m_NSWShl(m_Value(X), m_APInt(C1))) &&
952 *C1 != C1->getBitWidth() - 1) ||
953 (!IsSigned && match(LHS, m_NUWShl(m_Value(X), m_APInt(C1))))) {
954 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
955 APInt C1Shifted = APInt::getOneBitSet(
956 C1->getBitWidth(), static_cast<unsigned>(C1->getLimitedValue()));
957
958 // (X << C1) / C2 -> X / (C2 >> C1) if C2 is a multiple of C1.
959 if (IsMultiple(*C2, C1Shifted, Quotient, IsSigned)) {
960 BinaryOperator *BO = BinaryOperator::Create(
961 I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
962 BO->setIsExact(I.isExact());
963 return BO;
964 }
965
966 // (X << C1) / C2 -> X * (C2 >> C1) if C1 is a multiple of C2.
967 if (IsMultiple(C1Shifted, *C2, Quotient, IsSigned)) {
968 BinaryOperator *BO = BinaryOperator::Create(
969 Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
970 BO->setHasNoUnsignedWrap(
971 !IsSigned &&
972 cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
973 BO->setHasNoSignedWrap(
974 cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
975 return BO;
976 }
977 }
978
Craig Topper73ba1c82017-06-07 07:40:37 +0000979 if (!C2->isNullValue()) // avoid X udiv 0
Sanjay Pateldb0938f2017-01-10 23:49:07 +0000980 if (Instruction *FoldedDiv = foldOpWithConstantIntoOperand(I))
981 return FoldedDiv;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000982 }
983 }
984
Craig Topper218a3592017-04-17 03:41:47 +0000985 if (match(Op0, m_One())) {
Craig Topperfde47232017-07-09 07:04:03 +0000986 assert(!I.getType()->isIntOrIntVectorTy(1) && "i1 divide not removed?");
Craig Topper218a3592017-04-17 03:41:47 +0000987 if (I.getOpcode() == Instruction::SDiv) {
988 // If Op1 is 0 then it's undefined behaviour, if Op1 is 1 then the
989 // result is one, if Op1 is -1 then the result is minus one, otherwise
990 // it's zero.
Craig Topperbb4069e2017-07-07 23:16:26 +0000991 Value *Inc = Builder.CreateAdd(Op1, Op0);
992 Value *Cmp = Builder.CreateICmpULT(Inc, ConstantInt::get(I.getType(), 3));
Craig Topper218a3592017-04-17 03:41:47 +0000993 return SelectInst::Create(Cmp, Op1, ConstantInt::get(I.getType(), 0));
994 } else {
995 // If Op1 is 0 then it's undefined behaviour. If Op1 is 1 then the
996 // result is one, otherwise it's zero.
Craig Topperbb4069e2017-07-07 23:16:26 +0000997 return new ZExtInst(Builder.CreateICmpEQ(Op1, Op0), I.getType());
Nick Lewyckyf0cf8fa2014-05-14 03:03:05 +0000998 }
999 }
1000
Benjamin Kramer57b3df52011-04-30 18:16:00 +00001001 // See if we can fold away this div instruction.
1002 if (SimplifyDemandedInstructionBits(I))
1003 return &I;
1004
Duncan Sands771e82a2011-01-28 16:51:11 +00001005 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
Sanjay Patel9530f182018-01-21 16:14:51 +00001006 Value *X, *Z;
1007 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) // (X - Z) / Y; Y = Op1
1008 if ((IsSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
1009 (!IsSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
Duncan Sands771e82a2011-01-28 16:51:11 +00001010 return BinaryOperator::Create(I.getOpcode(), X, Op1);
Sanjay Patel9530f182018-01-21 16:14:51 +00001011
1012 // (X << Y) / X -> 1 << Y
1013 Value *Y;
1014 if (IsSigned && match(Op0, m_NSWShl(m_Specific(Op1), m_Value(Y))))
1015 return BinaryOperator::CreateNSWShl(ConstantInt::get(I.getType(), 1), Y);
1016 if (!IsSigned && match(Op0, m_NUWShl(m_Specific(Op1), m_Value(Y))))
1017 return BinaryOperator::CreateNUWShl(ConstantInt::get(I.getType(), 1), Y);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001018
Craig Topperf40110f2014-04-25 05:29:35 +00001019 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001020}
1021
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00001022static const unsigned MaxDepth = 6;
1023
David Majnemer37f8f442013-07-04 21:17:49 +00001024namespace {
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00001025
1026using FoldUDivOperandCb = Instruction *(*)(Value *Op0, Value *Op1,
1027 const BinaryOperator &I,
1028 InstCombiner &IC);
David Majnemer37f8f442013-07-04 21:17:49 +00001029
1030/// \brief Used to maintain state for visitUDivOperand().
1031struct UDivFoldAction {
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00001032 /// Informs visitUDiv() how to fold this operand. This can be zero if this
1033 /// action joins two actions together.
1034 FoldUDivOperandCb FoldAction;
David Majnemer37f8f442013-07-04 21:17:49 +00001035
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00001036 /// Which operand to fold.
1037 Value *OperandToFold;
1038
David Majnemer37f8f442013-07-04 21:17:49 +00001039 union {
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00001040 /// The instruction returned when FoldAction is invoked.
1041 Instruction *FoldResult;
David Majnemer37f8f442013-07-04 21:17:49 +00001042
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00001043 /// Stores the LHS action index if this action joins two actions together.
1044 size_t SelectLHSIdx;
David Majnemer37f8f442013-07-04 21:17:49 +00001045 };
1046
1047 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand)
Craig Topperf40110f2014-04-25 05:29:35 +00001048 : FoldAction(FA), OperandToFold(InputOperand), FoldResult(nullptr) {}
David Majnemer37f8f442013-07-04 21:17:49 +00001049 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand, size_t SLHS)
1050 : FoldAction(FA), OperandToFold(InputOperand), SelectLHSIdx(SLHS) {}
1051};
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00001052
1053} // end anonymous namespace
David Majnemer37f8f442013-07-04 21:17:49 +00001054
1055// X udiv 2^C -> X >> C
1056static Instruction *foldUDivPow2Cst(Value *Op0, Value *Op1,
1057 const BinaryOperator &I, InstCombiner &IC) {
Simon Pilgrim94cc89d2018-02-08 14:46:10 +00001058 Constant *C1 = getLogBase2(Op0->getType(), cast<Constant>(Op1));
1059 if (!C1)
1060 llvm_unreachable("Failed to constant fold udiv -> logbase2");
1061 BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, C1);
Suyog Sarda65f5ae92014-10-07 12:04:07 +00001062 if (I.isExact())
1063 LShr->setIsExact();
David Majnemer37f8f442013-07-04 21:17:49 +00001064 return LShr;
1065}
1066
1067// X udiv C, where C >= signbit
1068static Instruction *foldUDivNegCst(Value *Op0, Value *Op1,
1069 const BinaryOperator &I, InstCombiner &IC) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001070 Value *ICI = IC.Builder.CreateICmpULT(Op0, cast<ConstantInt>(Op1));
David Majnemer37f8f442013-07-04 21:17:49 +00001071
1072 return SelectInst::Create(ICI, Constant::getNullValue(I.getType()),
1073 ConstantInt::get(I.getType(), 1));
1074}
1075
1076// X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Andrea Di Biagioa82d52d2016-09-26 12:07:23 +00001077// X udiv (zext (C1 << N)), where C1 is "1<<C2" --> X >> (N+C2)
David Majnemer37f8f442013-07-04 21:17:49 +00001078static Instruction *foldUDivShl(Value *Op0, Value *Op1, const BinaryOperator &I,
1079 InstCombiner &IC) {
Andrea Di Biagioa82d52d2016-09-26 12:07:23 +00001080 Value *ShiftLeft;
1081 if (!match(Op1, m_ZExt(m_Value(ShiftLeft))))
1082 ShiftLeft = Op1;
David Majnemer37f8f442013-07-04 21:17:49 +00001083
Simon Pilgrim2a90acd2018-02-08 15:19:38 +00001084 Constant *CI;
Andrea Di Biagioa82d52d2016-09-26 12:07:23 +00001085 Value *N;
Simon Pilgrim2a90acd2018-02-08 15:19:38 +00001086 if (!match(ShiftLeft, m_Shl(m_Constant(CI), m_Value(N))))
Andrea Di Biagioa82d52d2016-09-26 12:07:23 +00001087 llvm_unreachable("match should never fail here!");
Simon Pilgrim2a90acd2018-02-08 15:19:38 +00001088 Constant *Log2Base = getLogBase2(N->getType(), CI);
1089 if (!Log2Base)
1090 llvm_unreachable("getLogBase2 should never fail here!");
1091 N = IC.Builder.CreateAdd(N, Log2Base);
Andrea Di Biagioa82d52d2016-09-26 12:07:23 +00001092 if (Op1 != ShiftLeft)
Craig Topperbb4069e2017-07-07 23:16:26 +00001093 N = IC.Builder.CreateZExt(N, Op1->getType());
David Majnemer37f8f442013-07-04 21:17:49 +00001094 BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, N);
Suyog Sarda65f5ae92014-10-07 12:04:07 +00001095 if (I.isExact())
1096 LShr->setIsExact();
David Majnemer37f8f442013-07-04 21:17:49 +00001097 return LShr;
1098}
1099
1100// \brief Recursively visits the possible right hand operands of a udiv
1101// instruction, seeing through select instructions, to determine if we can
1102// replace the udiv with something simpler. If we find that an operand is not
1103// able to simplify the udiv, we abort the entire transformation.
1104static size_t visitUDivOperand(Value *Op0, Value *Op1, const BinaryOperator &I,
1105 SmallVectorImpl<UDivFoldAction> &Actions,
1106 unsigned Depth = 0) {
1107 // Check to see if this is an unsigned division with an exact power of 2,
1108 // if so, convert to a right shift.
1109 if (match(Op1, m_Power2())) {
1110 Actions.push_back(UDivFoldAction(foldUDivPow2Cst, Op1));
1111 return Actions.size();
1112 }
1113
1114 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1))
1115 // X udiv C, where C >= signbit
1116 if (C->getValue().isNegative()) {
1117 Actions.push_back(UDivFoldAction(foldUDivNegCst, C));
1118 return Actions.size();
1119 }
1120
1121 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
1122 if (match(Op1, m_Shl(m_Power2(), m_Value())) ||
1123 match(Op1, m_ZExt(m_Shl(m_Power2(), m_Value())))) {
1124 Actions.push_back(UDivFoldAction(foldUDivShl, Op1));
1125 return Actions.size();
1126 }
1127
1128 // The remaining tests are all recursive, so bail out if we hit the limit.
1129 if (Depth++ == MaxDepth)
1130 return 0;
1131
1132 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
David Majnemer492e6122014-08-30 09:19:05 +00001133 if (size_t LHSIdx =
1134 visitUDivOperand(Op0, SI->getOperand(1), I, Actions, Depth))
1135 if (visitUDivOperand(Op0, SI->getOperand(2), I, Actions, Depth)) {
1136 Actions.push_back(UDivFoldAction(nullptr, Op1, LHSIdx - 1));
David Majnemer37f8f442013-07-04 21:17:49 +00001137 return Actions.size();
1138 }
1139
1140 return 0;
1141}
1142
Sanjay Patelbb789382017-08-24 22:54:01 +00001143/// If we have zero-extended operands of an unsigned div or rem, we may be able
1144/// to narrow the operation (sink the zext below the math).
1145static Instruction *narrowUDivURem(BinaryOperator &I,
1146 InstCombiner::BuilderTy &Builder) {
1147 Instruction::BinaryOps Opcode = I.getOpcode();
1148 Value *N = I.getOperand(0);
1149 Value *D = I.getOperand(1);
1150 Type *Ty = I.getType();
1151 Value *X, *Y;
1152 if (match(N, m_ZExt(m_Value(X))) && match(D, m_ZExt(m_Value(Y))) &&
1153 X->getType() == Y->getType() && (N->hasOneUse() || D->hasOneUse())) {
1154 // udiv (zext X), (zext Y) --> zext (udiv X, Y)
1155 // urem (zext X), (zext Y) --> zext (urem X, Y)
1156 Value *NarrowOp = Builder.CreateBinOp(Opcode, X, Y);
1157 return new ZExtInst(NarrowOp, Ty);
1158 }
1159
1160 Constant *C;
1161 if ((match(N, m_OneUse(m_ZExt(m_Value(X)))) && match(D, m_Constant(C))) ||
1162 (match(D, m_OneUse(m_ZExt(m_Value(X)))) && match(N, m_Constant(C)))) {
1163 // If the constant is the same in the smaller type, use the narrow version.
1164 Constant *TruncC = ConstantExpr::getTrunc(C, X->getType());
1165 if (ConstantExpr::getZExt(TruncC, Ty) != C)
1166 return nullptr;
1167
1168 // udiv (zext X), C --> zext (udiv X, C')
1169 // urem (zext X), C --> zext (urem X, C')
1170 // udiv C, (zext X) --> zext (udiv C', X)
1171 // urem C, (zext X) --> zext (urem C', X)
1172 Value *NarrowOp = isa<Constant>(D) ? Builder.CreateBinOp(Opcode, X, TruncC)
1173 : Builder.CreateBinOp(Opcode, TruncC, X);
1174 return new ZExtInst(NarrowOp, Ty);
1175 }
1176
1177 return nullptr;
1178}
1179
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001180Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
1181 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1182
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001183 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001184 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001185
Craig Toppera4205622017-06-09 03:21:29 +00001186 if (Value *V = SimplifyUDivInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001187 return replaceInstUsesWith(I, V);
Duncan Sands771e82a2011-01-28 16:51:11 +00001188
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001189 // Handle the integer div common cases
1190 if (Instruction *Common = commonIDivTransforms(I))
1191 return Common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001192
Benjamin Kramerd4a64712012-08-30 15:07:40 +00001193 // (x lshr C1) udiv C2 --> x udiv (C2 << C1)
David Majnemera2521382014-10-13 21:48:30 +00001194 {
Benjamin Kramer9c0a8072012-08-28 13:08:13 +00001195 Value *X;
David Majnemera2521382014-10-13 21:48:30 +00001196 const APInt *C1, *C2;
1197 if (match(Op0, m_LShr(m_Value(X), m_APInt(C1))) &&
1198 match(Op1, m_APInt(C2))) {
1199 bool Overflow;
1200 APInt C2ShlC1 = C2->ushl_ov(*C1, Overflow);
David Majnemera3aeb152014-11-22 18:16:54 +00001201 if (!Overflow) {
1202 bool IsExact = I.isExact() && match(Op0, m_Exact(m_Value()));
1203 BinaryOperator *BO = BinaryOperator::CreateUDiv(
David Majnemera2521382014-10-13 21:48:30 +00001204 X, ConstantInt::get(X->getType(), C2ShlC1));
David Majnemera3aeb152014-11-22 18:16:54 +00001205 if (IsExact)
1206 BO->setIsExact();
1207 return BO;
1208 }
David Majnemera2521382014-10-13 21:48:30 +00001209 }
Nadav Rotem11935b22012-08-28 10:01:43 +00001210 }
1211
Sanjay Patelbb789382017-08-24 22:54:01 +00001212 if (Instruction *NarrowDiv = narrowUDivURem(I, Builder))
1213 return NarrowDiv;
Benjamin Kramer9aa91b12011-04-30 18:16:07 +00001214
David Majnemer37f8f442013-07-04 21:17:49 +00001215 // (LHS udiv (select (select (...)))) -> (LHS >> (select (select (...))))
1216 SmallVector<UDivFoldAction, 6> UDivActions;
1217 if (visitUDivOperand(Op0, Op1, I, UDivActions))
1218 for (unsigned i = 0, e = UDivActions.size(); i != e; ++i) {
1219 FoldUDivOperandCb Action = UDivActions[i].FoldAction;
1220 Value *ActionOp1 = UDivActions[i].OperandToFold;
1221 Instruction *Inst;
1222 if (Action)
1223 Inst = Action(Op0, ActionOp1, I, *this);
1224 else {
1225 // This action joins two actions together. The RHS of this action is
1226 // simply the last action we processed, we saved the LHS action index in
1227 // the joining action.
1228 size_t SelectRHSIdx = i - 1;
1229 Value *SelectRHS = UDivActions[SelectRHSIdx].FoldResult;
1230 size_t SelectLHSIdx = UDivActions[i].SelectLHSIdx;
1231 Value *SelectLHS = UDivActions[SelectLHSIdx].FoldResult;
1232 Inst = SelectInst::Create(cast<SelectInst>(ActionOp1)->getCondition(),
1233 SelectLHS, SelectRHS);
1234 }
1235
1236 // If this is the last action to process, return it to the InstCombiner.
1237 // Otherwise, we insert it before the UDiv and record it so that we may
1238 // use it as part of a joining action (i.e., a SelectInst).
1239 if (e - i != 1) {
1240 Inst->insertBefore(&I);
1241 UDivActions[i].FoldResult = Inst;
1242 } else
1243 return Inst;
1244 }
1245
Craig Topperf40110f2014-04-25 05:29:35 +00001246 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001247}
1248
1249Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
1250 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1251
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001252 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001253 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001254
Craig Toppera4205622017-06-09 03:21:29 +00001255 if (Value *V = SimplifySDivInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001256 return replaceInstUsesWith(I, V);
Duncan Sands771e82a2011-01-28 16:51:11 +00001257
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001258 // Handle the integer div common cases
1259 if (Instruction *Common = commonIDivTransforms(I))
1260 return Common;
1261
Sanjay Patelc6ada532016-06-27 17:25:57 +00001262 const APInt *Op1C;
Sanjay Patelbedd1f92016-06-27 18:38:40 +00001263 if (match(Op1, m_APInt(Op1C))) {
1264 // sdiv X, -1 == -X
1265 if (Op1C->isAllOnesValue())
1266 return BinaryOperator::CreateNeg(Op0);
1267
1268 // sdiv exact X, C --> ashr exact X, log2(C)
1269 if (I.isExact() && Op1C->isNonNegative() && Op1C->isPowerOf2()) {
1270 Value *ShAmt = ConstantInt::get(Op1->getType(), Op1C->exactLogBase2());
1271 return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
1272 }
Sanjay Patel59ed2ff2016-06-27 22:27:11 +00001273
1274 // If the dividend is sign-extended and the constant divisor is small enough
1275 // to fit in the source type, shrink the division to the narrower type:
1276 // (sext X) sdiv C --> sext (X sdiv C)
1277 Value *Op0Src;
1278 if (match(Op0, m_OneUse(m_SExt(m_Value(Op0Src)))) &&
1279 Op0Src->getType()->getScalarSizeInBits() >= Op1C->getMinSignedBits()) {
1280
1281 // In the general case, we need to make sure that the dividend is not the
1282 // minimum signed value because dividing that by -1 is UB. But here, we
1283 // know that the -1 divisor case is already handled above.
1284
1285 Constant *NarrowDivisor =
1286 ConstantExpr::getTrunc(cast<Constant>(Op1), Op0Src->getType());
Craig Topperbb4069e2017-07-07 23:16:26 +00001287 Value *NarrowOp = Builder.CreateSDiv(Op0Src, NarrowDivisor);
Sanjay Patel59ed2ff2016-06-27 22:27:11 +00001288 return new SExtInst(NarrowOp, Op0->getType());
1289 }
Benjamin Kramer72196f32014-01-19 15:24:22 +00001290 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001291
Benjamin Kramer72196f32014-01-19 15:24:22 +00001292 if (Constant *RHS = dyn_cast<Constant>(Op1)) {
David Majnemerf28e2a42014-07-02 06:42:13 +00001293 // X/INT_MIN -> X == INT_MIN
1294 if (RHS->isMinSignedValue())
Craig Topperbb4069e2017-07-07 23:16:26 +00001295 return new ZExtInst(Builder.CreateICmpEQ(Op0, Op1), I.getType());
David Majnemerf28e2a42014-07-02 06:42:13 +00001296
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001297 // -X/C --> X/-C provided the negation doesn't overflow.
David Majnemerfa4699e2014-11-22 20:00:34 +00001298 Value *X;
1299 if (match(Op0, m_NSWSub(m_Zero(), m_Value(X)))) {
1300 auto *BO = BinaryOperator::CreateSDiv(X, ConstantExpr::getNeg(RHS));
1301 BO->setIsExact(I.isExact());
1302 return BO;
1303 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001304 }
1305
1306 // If the sign bits of both operands are zero (i.e. we can prove they are
1307 // unsigned inputs), turn this into a udiv.
Craig Topperbcfd2d12017-04-20 16:56:25 +00001308 APInt Mask(APInt::getSignMask(I.getType()->getScalarSizeInBits()));
Craig Topperf2484682017-04-17 01:51:19 +00001309 if (MaskedValueIsZero(Op0, Mask, 0, &I)) {
1310 if (MaskedValueIsZero(Op1, Mask, 0, &I)) {
1311 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
1312 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1313 BO->setIsExact(I.isExact());
1314 return BO;
1315 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001316
Craig Topperd4039f72017-05-25 21:51:12 +00001317 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/ true, 0, &I)) {
Craig Topperf2484682017-04-17 01:51:19 +00001318 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
1319 // Safe because the only negative value (1 << Y) can take on is
1320 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
1321 // the sign bit set.
1322 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1323 BO->setIsExact(I.isExact());
1324 return BO;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001325 }
1326 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001327
Craig Topperf40110f2014-04-25 05:29:35 +00001328 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001329}
1330
Shuxin Yang320f52a2013-01-14 22:48:41 +00001331/// CvtFDivConstToReciprocal tries to convert X/C into X*1/C if C not a special
1332/// FP value and:
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001333/// 1) 1/C is exact, or
Shuxin Yang320f52a2013-01-14 22:48:41 +00001334/// 2) reciprocal is allowed.
Sylvestre Ledru149e2812013-05-14 23:36:24 +00001335/// If the conversion was successful, the simplified expression "X * 1/C" is
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00001336/// returned; otherwise, nullptr is returned.
Suyog Sardaea205512014-10-07 11:56:06 +00001337static Instruction *CvtFDivConstToReciprocal(Value *Dividend, Constant *Divisor,
Shuxin Yang320f52a2013-01-14 22:48:41 +00001338 bool AllowReciprocal) {
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001339 if (!isa<ConstantFP>(Divisor)) // TODO: handle vectors.
Craig Topperf40110f2014-04-25 05:29:35 +00001340 return nullptr;
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001341
1342 const APFloat &FpVal = cast<ConstantFP>(Divisor)->getValueAPF();
Shuxin Yang320f52a2013-01-14 22:48:41 +00001343 APFloat Reciprocal(FpVal.getSemantics());
1344 bool Cvt = FpVal.getExactInverse(&Reciprocal);
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001345
Michael Gottesman3cb77ab2013-06-19 21:23:18 +00001346 if (!Cvt && AllowReciprocal && FpVal.isFiniteNonZero()) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001347 Reciprocal = APFloat(FpVal.getSemantics(), 1.0f);
1348 (void)Reciprocal.divide(FpVal, APFloat::rmNearestTiesToEven);
1349 Cvt = !Reciprocal.isDenormal();
1350 }
1351
1352 if (!Cvt)
Craig Topperf40110f2014-04-25 05:29:35 +00001353 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001354
1355 ConstantFP *R;
1356 R = ConstantFP::get(Dividend->getType()->getContext(), Reciprocal);
1357 return BinaryOperator::CreateFMul(Dividend, R);
1358}
1359
Frits van Bommel2a559512011-01-29 17:50:27 +00001360Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
1361 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1362
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001363 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001364 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001365
Craig Toppera4205622017-06-09 03:21:29 +00001366 if (Value *V = SimplifyFDivInst(Op0, Op1, I.getFastMathFlags(),
1367 SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001368 return replaceInstUsesWith(I, V);
Frits van Bommel2a559512011-01-29 17:50:27 +00001369
Stephen Lina9b57f62013-07-20 07:13:13 +00001370 if (isa<Constant>(Op0))
1371 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1372 if (Instruction *R = FoldOpIntoSelect(I, SI))
1373 return R;
1374
Sanjay Patel629c4112017-11-06 16:27:15 +00001375 bool AllowReassociate = I.isFast();
Shuxin Yang320f52a2013-01-14 22:48:41 +00001376 bool AllowReciprocal = I.hasAllowReciprocal();
Benjamin Kramer8564e0d2011-03-30 15:42:35 +00001377
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001378 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Stephen Lina9b57f62013-07-20 07:13:13 +00001379 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1380 if (Instruction *R = FoldOpIntoSelect(I, SI))
1381 return R;
1382
Shuxin Yang320f52a2013-01-14 22:48:41 +00001383 if (AllowReassociate) {
Craig Topperf40110f2014-04-25 05:29:35 +00001384 Constant *C1 = nullptr;
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001385 Constant *C2 = Op1C;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001386 Value *X;
Craig Topperf40110f2014-04-25 05:29:35 +00001387 Instruction *Res = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001388
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001389 if (match(Op0, m_FMul(m_Value(X), m_Constant(C1)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001390 // (X*C1)/C2 => X * (C1/C2)
1391 //
1392 Constant *C = ConstantExpr::getFDiv(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001393 if (isNormalFp(C))
Shuxin Yang320f52a2013-01-14 22:48:41 +00001394 Res = BinaryOperator::CreateFMul(X, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001395 } else if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001396 // (X/C1)/C2 => X /(C2*C1) [=> X * 1/(C2*C1) if reciprocal is allowed]
Shuxin Yang320f52a2013-01-14 22:48:41 +00001397 Constant *C = ConstantExpr::getFMul(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001398 if (isNormalFp(C)) {
1399 Res = CvtFDivConstToReciprocal(X, C, AllowReciprocal);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001400 if (!Res)
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001401 Res = BinaryOperator::CreateFDiv(X, C);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001402 }
1403 }
1404
1405 if (Res) {
1406 Res->setFastMathFlags(I.getFastMathFlags());
1407 return Res;
1408 }
1409 }
1410
1411 // X / C => X * 1/C
Owen Anderson4557a152014-01-16 21:07:52 +00001412 if (Instruction *T = CvtFDivConstToReciprocal(Op0, Op1C, AllowReciprocal)) {
1413 T->copyFastMathFlags(&I);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001414 return T;
Owen Anderson4557a152014-01-16 21:07:52 +00001415 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001416
Craig Topperf40110f2014-04-25 05:29:35 +00001417 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001418 }
1419
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001420 if (AllowReassociate && isa<Constant>(Op0)) {
1421 Constant *C1 = cast<Constant>(Op0), *C2;
Craig Topperf40110f2014-04-25 05:29:35 +00001422 Constant *Fold = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001423 Value *X;
1424 bool CreateDiv = true;
1425
1426 // C1 / (X*C2) => (C1/C2) / X
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001427 if (match(Op1, m_FMul(m_Value(X), m_Constant(C2))))
Shuxin Yang320f52a2013-01-14 22:48:41 +00001428 Fold = ConstantExpr::getFDiv(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001429 else if (match(Op1, m_FDiv(m_Value(X), m_Constant(C2)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001430 // C1 / (X/C2) => (C1*C2) / X
1431 Fold = ConstantExpr::getFMul(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001432 } else if (match(Op1, m_FDiv(m_Constant(C2), m_Value(X)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001433 // C1 / (C2/X) => (C1/C2) * X
1434 Fold = ConstantExpr::getFDiv(C1, C2);
1435 CreateDiv = false;
1436 }
1437
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001438 if (Fold && isNormalFp(Fold)) {
1439 Instruction *R = CreateDiv ? BinaryOperator::CreateFDiv(Fold, X)
1440 : BinaryOperator::CreateFMul(X, Fold);
1441 R->setFastMathFlags(I.getFastMathFlags());
1442 return R;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001443 }
Craig Topperf40110f2014-04-25 05:29:35 +00001444 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001445 }
1446
1447 if (AllowReassociate) {
1448 Value *X, *Y;
Craig Topperf40110f2014-04-25 05:29:35 +00001449 Value *NewInst = nullptr;
1450 Instruction *SimpR = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001451
1452 if (Op0->hasOneUse() && match(Op0, m_FDiv(m_Value(X), m_Value(Y)))) {
1453 // (X/Y) / Z => X / (Y*Z)
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001454 if (!isa<Constant>(Y) || !isa<Constant>(Op1)) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001455 NewInst = Builder.CreateFMul(Y, Op1);
Owen Anderson1664dc82014-01-20 07:44:53 +00001456 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1457 FastMathFlags Flags = I.getFastMathFlags();
1458 Flags &= cast<Instruction>(Op0)->getFastMathFlags();
1459 RI->setFastMathFlags(Flags);
1460 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001461 SimpR = BinaryOperator::CreateFDiv(X, NewInst);
1462 }
1463 } else if (Op1->hasOneUse() && match(Op1, m_FDiv(m_Value(X), m_Value(Y)))) {
1464 // Z / (X/Y) => Z*Y / X
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001465 if (!isa<Constant>(Y) || !isa<Constant>(Op0)) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001466 NewInst = Builder.CreateFMul(Op0, Y);
Owen Anderson1664dc82014-01-20 07:44:53 +00001467 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1468 FastMathFlags Flags = I.getFastMathFlags();
1469 Flags &= cast<Instruction>(Op1)->getFastMathFlags();
1470 RI->setFastMathFlags(Flags);
1471 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001472 SimpR = BinaryOperator::CreateFDiv(NewInst, X);
1473 }
1474 }
1475
1476 if (NewInst) {
1477 if (Instruction *T = dyn_cast<Instruction>(NewInst))
1478 T->setDebugLoc(I.getDebugLoc());
1479 SimpR->setFastMathFlags(I.getFastMathFlags());
1480 return SimpR;
Benjamin Kramer8564e0d2011-03-30 15:42:35 +00001481 }
1482 }
1483
Dmitry Venikove5fbf592018-01-11 06:33:00 +00001484 if (AllowReassociate &&
1485 Op0->hasOneUse() && Op1->hasOneUse()) {
1486 Value *A;
1487 // sin(a) / cos(a) -> tan(a)
1488 if (match(Op0, m_Intrinsic<Intrinsic::sin>(m_Value(A))) &&
1489 match(Op1, m_Intrinsic<Intrinsic::cos>(m_Specific(A)))) {
1490 if (hasUnaryFloatFn(&TLI, I.getType(), LibFunc_tan,
1491 LibFunc_tanf, LibFunc_tanl)) {
1492 IRBuilder<> B(&I);
1493 IRBuilder<>::FastMathFlagGuard Guard(B);
1494 B.setFastMathFlags(I.getFastMathFlags());
Benjamin Kramer738e6e72018-01-11 15:33:21 +00001495 Value *Tan = emitUnaryFloatFnCall(
1496 A, TLI.getName(LibFunc_tan), B,
1497 CallSite(Op0).getCalledFunction()->getAttributes());
Dmitry Venikove5fbf592018-01-11 06:33:00 +00001498 return replaceInstUsesWith(I, Tan);
1499 }
1500 }
1501
1502 // cos(a) / sin(a) -> 1/tan(a)
1503 if (match(Op0, m_Intrinsic<Intrinsic::cos>(m_Value(A))) &&
1504 match(Op1, m_Intrinsic<Intrinsic::sin>(m_Specific(A)))) {
1505 if (hasUnaryFloatFn(&TLI, I.getType(), LibFunc_tan,
1506 LibFunc_tanf, LibFunc_tanl)) {
1507 IRBuilder<> B(&I);
1508 IRBuilder<>::FastMathFlagGuard Guard(B);
1509 B.setFastMathFlags(I.getFastMathFlags());
Benjamin Kramer44993ed2018-01-11 15:19:02 +00001510 Value *Tan = emitUnaryFloatFnCall(
1511 A, TLI.getName(LibFunc_tan), B,
1512 CallSite(Op0).getCalledFunction()->getAttributes());
Dmitry Venikove5fbf592018-01-11 06:33:00 +00001513 Value *One = ConstantFP::get(Tan->getType(), 1.0);
1514 Value *Div = B.CreateFDiv(One, Tan);
1515 return replaceInstUsesWith(I, Div);
1516 }
1517 }
1518 }
1519
Matt Arsenaultfdb78f82017-01-10 23:08:54 +00001520 Value *LHS;
1521 Value *RHS;
1522
1523 // -x / -y -> x / y
1524 if (match(Op0, m_FNeg(m_Value(LHS))) && match(Op1, m_FNeg(m_Value(RHS)))) {
1525 I.setOperand(0, LHS);
1526 I.setOperand(1, RHS);
1527 return &I;
1528 }
1529
Craig Topperf40110f2014-04-25 05:29:35 +00001530 return nullptr;
Frits van Bommel2a559512011-01-29 17:50:27 +00001531}
1532
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001533/// This function implements the transforms common to both integer remainder
1534/// instructions (urem and srem). It is called by the visitors to those integer
1535/// remainder instructions.
1536/// @brief Common integer remainder transforms
1537Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
1538 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1539
Chris Lattner7c99f192011-05-22 18:18:41 +00001540 // The RHS is known non-zero.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001541 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I)) {
Chris Lattner7c99f192011-05-22 18:18:41 +00001542 I.setOperand(1, V);
1543 return &I;
1544 }
1545
Duncan Sandsa3e36992011-05-02 16:27:02 +00001546 // Handle cases involving: rem X, (select Cond, Y, Z)
Sanjay Patelae2e3a42017-10-06 23:20:16 +00001547 if (simplifyDivRemOfSelectWithZeroOp(I))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001548 return &I;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001549
Benjamin Kramer72196f32014-01-19 15:24:22 +00001550 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001551 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1552 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1553 if (Instruction *R = FoldOpIntoSelect(I, SI))
1554 return R;
Craig Topperfb71b7d2017-04-14 19:20:12 +00001555 } else if (auto *PN = dyn_cast<PHINode>(Op0I)) {
Sanjoy Dasb7e861a2016-06-05 21:17:04 +00001556 const APInt *Op1Int;
1557 if (match(Op1, m_APInt(Op1Int)) && !Op1Int->isMinValue() &&
1558 (I.getOpcode() == Instruction::URem ||
1559 !Op1Int->isMinSignedValue())) {
Craig Topperfb71b7d2017-04-14 19:20:12 +00001560 // foldOpIntoPhi will speculate instructions to the end of the PHI's
Sanjoy Dasb7e861a2016-06-05 21:17:04 +00001561 // predecessor blocks, so do this only if we know the srem or urem
1562 // will not fault.
Craig Topperfb71b7d2017-04-14 19:20:12 +00001563 if (Instruction *NV = foldOpIntoPhi(I, PN))
Sanjoy Dasb7e861a2016-06-05 21:17:04 +00001564 return NV;
1565 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001566 }
1567
1568 // See if we can fold away this rem instruction.
1569 if (SimplifyDemandedInstructionBits(I))
1570 return &I;
1571 }
1572 }
1573
Craig Topperf40110f2014-04-25 05:29:35 +00001574 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001575}
1576
1577Instruction *InstCombiner::visitURem(BinaryOperator &I) {
1578 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1579
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001580 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001581 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001582
Craig Toppera4205622017-06-09 03:21:29 +00001583 if (Value *V = SimplifyURemInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001584 return replaceInstUsesWith(I, V);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001585
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001586 if (Instruction *common = commonIRemTransforms(I))
1587 return common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001588
Sanjay Patelbb789382017-08-24 22:54:01 +00001589 if (Instruction *NarrowRem = narrowUDivURem(I, Builder))
1590 return NarrowRem;
David Majnemer6c30f492013-05-12 00:07:05 +00001591
David Majnemer470b0772013-05-11 09:01:28 +00001592 // X urem Y -> X and Y-1, where Y is a power of 2,
Craig Topperd4039f72017-05-25 21:51:12 +00001593 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/ true, 0, &I)) {
Chris Lattner6b657ae2011-02-10 05:36:31 +00001594 Constant *N1 = Constant::getAllOnesValue(I.getType());
Craig Topperbb4069e2017-07-07 23:16:26 +00001595 Value *Add = Builder.CreateAdd(Op1, N1);
Chris Lattner6b657ae2011-02-10 05:36:31 +00001596 return BinaryOperator::CreateAnd(Op0, Add);
1597 }
1598
Nick Lewycky7459be62013-07-13 01:16:47 +00001599 // 1 urem X -> zext(X != 1)
1600 if (match(Op0, m_One())) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001601 Value *Cmp = Builder.CreateICmpNE(Op1, Op0);
1602 Value *Ext = Builder.CreateZExt(Cmp, I.getType());
Sanjay Patel4b198802016-02-01 22:23:39 +00001603 return replaceInstUsesWith(I, Ext);
Nick Lewycky7459be62013-07-13 01:16:47 +00001604 }
1605
Sanjay Patel30ef70b2016-09-22 22:36:26 +00001606 // X urem C -> X < C ? X : X - C, where C >= signbit.
1607 const APInt *DivisorC;
1608 if (match(Op1, m_APInt(DivisorC)) && DivisorC->isNegative()) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001609 Value *Cmp = Builder.CreateICmpULT(Op0, Op1);
1610 Value *Sub = Builder.CreateSub(Op0, Op1);
Sanjay Patel30ef70b2016-09-22 22:36:26 +00001611 return SelectInst::Create(Cmp, Op0, Sub);
1612 }
1613
Craig Topperf40110f2014-04-25 05:29:35 +00001614 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001615}
1616
1617Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
1618 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1619
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001620 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001621 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001622
Craig Toppera4205622017-06-09 03:21:29 +00001623 if (Value *V = SimplifySRemInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001624 return replaceInstUsesWith(I, V);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001625
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001626 // Handle the integer rem common cases
1627 if (Instruction *Common = commonIRemTransforms(I))
1628 return Common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001629
David Majnemerdb077302014-10-13 22:37:51 +00001630 {
1631 const APInt *Y;
1632 // X % -Y -> X % Y
1633 if (match(Op1, m_APInt(Y)) && Y->isNegative() && !Y->isMinSignedValue()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001634 Worklist.AddValue(I.getOperand(1));
David Majnemerdb077302014-10-13 22:37:51 +00001635 I.setOperand(1, ConstantInt::get(I.getType(), -*Y));
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001636 return &I;
1637 }
David Majnemerdb077302014-10-13 22:37:51 +00001638 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001639
1640 // If the sign bits of both operands are zero (i.e. we can prove they are
1641 // unsigned inputs), turn this into a urem.
Craig Topperbcfd2d12017-04-20 16:56:25 +00001642 APInt Mask(APInt::getSignMask(I.getType()->getScalarSizeInBits()));
Craig Topper1a18a7c2017-04-17 01:51:24 +00001643 if (MaskedValueIsZero(Op1, Mask, 0, &I) &&
1644 MaskedValueIsZero(Op0, Mask, 0, &I)) {
1645 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
1646 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001647 }
1648
1649 // If it's a constant vector, flip any negative values positive.
Chris Lattner0256be92012-01-27 03:08:05 +00001650 if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
1651 Constant *C = cast<Constant>(Op1);
1652 unsigned VWidth = C->getType()->getVectorNumElements();
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001653
1654 bool hasNegative = false;
Chris Lattner0256be92012-01-27 03:08:05 +00001655 bool hasMissing = false;
1656 for (unsigned i = 0; i != VWidth; ++i) {
1657 Constant *Elt = C->getAggregateElement(i);
Craig Topperf40110f2014-04-25 05:29:35 +00001658 if (!Elt) {
Chris Lattner0256be92012-01-27 03:08:05 +00001659 hasMissing = true;
1660 break;
1661 }
1662
1663 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
Chris Lattnerb1a15122011-07-15 06:08:15 +00001664 if (RHS->isNegative())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001665 hasNegative = true;
Chris Lattner0256be92012-01-27 03:08:05 +00001666 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001667
Chris Lattner0256be92012-01-27 03:08:05 +00001668 if (hasNegative && !hasMissing) {
Chris Lattner47a86bd2012-01-25 06:02:56 +00001669 SmallVector<Constant *, 16> Elts(VWidth);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001670 for (unsigned i = 0; i != VWidth; ++i) {
Chris Lattner8213c8a2012-02-06 21:56:39 +00001671 Elts[i] = C->getAggregateElement(i); // Handle undef, etc.
Chris Lattner0256be92012-01-27 03:08:05 +00001672 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
Chris Lattnerb1a15122011-07-15 06:08:15 +00001673 if (RHS->isNegative())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001674 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001675 }
1676 }
1677
1678 Constant *NewRHSV = ConstantVector::get(Elts);
Chris Lattner0256be92012-01-27 03:08:05 +00001679 if (NewRHSV != C) { // Don't loop on -MININT
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001680 Worklist.AddValue(I.getOperand(1));
1681 I.setOperand(1, NewRHSV);
1682 return &I;
1683 }
1684 }
1685 }
1686
Craig Topperf40110f2014-04-25 05:29:35 +00001687 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001688}
1689
1690Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Duncan Sandsa3e36992011-05-02 16:27:02 +00001691 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001692
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001693 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001694 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001695
Craig Toppera4205622017-06-09 03:21:29 +00001696 if (Value *V = SimplifyFRemInst(Op0, Op1, I.getFastMathFlags(),
1697 SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001698 return replaceInstUsesWith(I, V);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001699
Craig Topperf40110f2014-04-25 05:29:35 +00001700 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001701}