blob: 27f2a6dbc4e30377a22a6a8bafa399ed284fa7f3 [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
Rafael Espindola65281bf2013-05-31 14:27:15 +000098/// \brief A helper routine of InstCombiner::visitMul().
99///
Simon Pilgrim0b9f3912018-02-08 14:10:01 +0000100/// If C is a scalar/vector of known powers of 2, then this function returns
101/// a new scalar/vector obtained from logBase2 of C.
Rafael Espindola65281bf2013-05-31 14:27:15 +0000102/// Return a null pointer otherwise.
Simon Pilgrim0b9f3912018-02-08 14:10:01 +0000103static Constant *getLogBase2(Type *Ty, Constant *C) {
Rafael Espindola65281bf2013-05-31 14:27:15 +0000104 const APInt *IVal;
Simon Pilgrimbe0dd722018-02-13 13:16:26 +0000105 if (match(C, m_APInt(IVal)) && IVal->isPowerOf2())
106 return ConstantInt::get(Ty, IVal->logBase2());
Rafael Espindola65281bf2013-05-31 14:27:15 +0000107
Simon Pilgrim0b9f3912018-02-08 14:10:01 +0000108 if (!Ty->isVectorTy())
109 return nullptr;
110
111 SmallVector<Constant *, 4> Elts;
112 for (unsigned I = 0, E = Ty->getVectorNumElements(); I != E; ++I) {
113 Constant *Elt = C->getAggregateElement(I);
114 if (!Elt)
115 return nullptr;
116 if (isa<UndefValue>(Elt)) {
117 Elts.push_back(UndefValue::get(Ty->getScalarType()));
118 continue;
119 }
Rafael Espindola65281bf2013-05-31 14:27:15 +0000120 if (!match(Elt, m_APInt(IVal)) || !IVal->isPowerOf2())
Craig Topperf40110f2014-04-25 05:29:35 +0000121 return nullptr;
Simon Pilgrim0b9f3912018-02-08 14:10:01 +0000122 Elts.push_back(ConstantInt::get(Ty->getScalarType(), IVal->logBase2()));
Rafael Espindola65281bf2013-05-31 14:27:15 +0000123 }
124
125 return ConstantVector::get(Elts);
126}
127
David Majnemer54c2ca22014-12-26 09:10:14 +0000128/// \brief Return true if we can prove that:
129/// (mul LHS, RHS) === (mul nsw LHS, RHS)
Craig Topper2b1fc322017-05-22 06:25:31 +0000130bool InstCombiner::willNotOverflowSignedMul(const Value *LHS,
131 const Value *RHS,
132 const Instruction &CxtI) const {
David Majnemer54c2ca22014-12-26 09:10:14 +0000133 // Multiplying n * m significant bits yields a result of n + m significant
134 // bits. If the total number of significant bits does not exceed the
135 // result bit width (minus 1), there is no overflow.
136 // This means if we have enough leading sign bits in the operands
137 // we can guarantee that the result does not overflow.
138 // Ref: "Hacker's Delight" by Henry Warren
139 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
140
141 // Note that underestimating the number of sign bits gives a more
142 // conservative answer.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000143 unsigned SignBits =
144 ComputeNumSignBits(LHS, 0, &CxtI) + ComputeNumSignBits(RHS, 0, &CxtI);
David Majnemer54c2ca22014-12-26 09:10:14 +0000145
146 // First handle the easy case: if we have enough sign bits there's
147 // definitely no overflow.
148 if (SignBits > BitWidth + 1)
149 return true;
150
151 // There are two ambiguous cases where there can be no overflow:
152 // SignBits == BitWidth + 1 and
153 // SignBits == BitWidth
154 // The second case is difficult to check, therefore we only handle the
155 // first case.
156 if (SignBits == BitWidth + 1) {
157 // It overflows only when both arguments are negative and the true
158 // product is exactly the minimum negative number.
159 // E.g. mul i16 with 17 sign bits: 0xff00 * 0xff80 = 0x8000
160 // For simplicity we just check if at least one side is not negative.
Craig Topper1a36b7d2017-05-15 06:39:41 +0000161 KnownBits LHSKnown = computeKnownBits(LHS, /*Depth=*/0, &CxtI);
162 KnownBits RHSKnown = computeKnownBits(RHS, /*Depth=*/0, &CxtI);
163 if (LHSKnown.isNonNegative() || RHSKnown.isNonNegative())
David Majnemer54c2ca22014-12-26 09:10:14 +0000164 return true;
165 }
166 return false;
167}
168
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000169Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +0000170 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000171 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
172
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000173 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +0000174 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000175
Craig Toppera4205622017-06-09 03:21:29 +0000176 if (Value *V = SimplifyMulInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +0000177 return replaceInstUsesWith(I, V);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000178
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000179 if (Value *V = SimplifyUsingDistributiveLaws(I))
Sanjay Patel4b198802016-02-01 22:23:39 +0000180 return replaceInstUsesWith(I, V);
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000181
David Majnemer027bc802014-11-22 04:52:38 +0000182 // X * -1 == 0 - X
183 if (match(Op1, m_AllOnes())) {
184 BinaryOperator *BO = BinaryOperator::CreateNeg(Op0, I.getName());
185 if (I.hasNoSignedWrap())
186 BO->setHasNoSignedWrap();
187 return BO;
188 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000189
Rafael Espindola65281bf2013-05-31 14:27:15 +0000190 // Also allow combining multiply instructions on vectors.
191 {
192 Value *NewOp;
193 Constant *C1, *C2;
194 const APInt *IVal;
195 if (match(&I, m_Mul(m_Shl(m_Value(NewOp), m_Constant(C2)),
196 m_Constant(C1))) &&
David Majnemerfd4a6d22014-11-22 04:52:52 +0000197 match(C1, m_APInt(IVal))) {
198 // ((X << C2)*C1) == (X * (C1 << C2))
199 Constant *Shl = ConstantExpr::getShl(C1, C2);
200 BinaryOperator *Mul = cast<BinaryOperator>(I.getOperand(0));
201 BinaryOperator *BO = BinaryOperator::CreateMul(NewOp, Shl);
202 if (I.hasNoUnsignedWrap() && Mul->hasNoUnsignedWrap())
203 BO->setHasNoUnsignedWrap();
204 if (I.hasNoSignedWrap() && Mul->hasNoSignedWrap() &&
205 Shl->isNotMinSignedValue())
206 BO->setHasNoSignedWrap();
207 return BO;
208 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000209
Rafael Espindola65281bf2013-05-31 14:27:15 +0000210 if (match(&I, m_Mul(m_Value(NewOp), m_Constant(C1)))) {
Simon Pilgrim0b9f3912018-02-08 14:10:01 +0000211 // Replace X*(2^C) with X << C, where C is either a scalar or a vector.
212 if (Constant *NewCst = getLogBase2(NewOp->getType(), C1)) {
David Majnemer45951a62015-04-18 04:41:30 +0000213 unsigned Width = NewCst->getType()->getPrimitiveSizeInBits();
Rafael Espindola65281bf2013-05-31 14:27:15 +0000214 BinaryOperator *Shl = BinaryOperator::CreateShl(NewOp, NewCst);
Tilmann Scheller2bc5cb62014-10-07 10:19:34 +0000215
Tilmann Scheller2bc5cb62014-10-07 10:19:34 +0000216 if (I.hasNoUnsignedWrap())
217 Shl->setHasNoUnsignedWrap();
David Majnemer45951a62015-04-18 04:41:30 +0000218 if (I.hasNoSignedWrap()) {
Craig Topper5fe01972017-06-27 19:57:53 +0000219 const APInt *V;
220 if (match(NewCst, m_APInt(V)) && *V != Width - 1)
David Majnemer45951a62015-04-18 04:41:30 +0000221 Shl->setHasNoSignedWrap();
222 }
Tilmann Scheller2bc5cb62014-10-07 10:19:34 +0000223
Rafael Espindola65281bf2013-05-31 14:27:15 +0000224 return Shl;
225 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000226 }
Rafael Espindola65281bf2013-05-31 14:27:15 +0000227 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000228
Rafael Espindola65281bf2013-05-31 14:27:15 +0000229 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Stuart Hastings23804832011-06-01 16:42:47 +0000230 // (Y - X) * (-(2**n)) -> (X - Y) * (2**n), for positive nonzero n
231 // (Y + const) * (-(2**n)) -> (-constY) * (2**n), for positive nonzero n
232 // The "* (2**n)" thus becomes a potential shifting opportunity.
Stuart Hastings82843742011-05-30 20:00:33 +0000233 {
234 const APInt & Val = CI->getValue();
235 const APInt &PosVal = Val.abs();
236 if (Val.isNegative() && PosVal.isPowerOf2()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000237 Value *X = nullptr, *Y = nullptr;
Stuart Hastings23804832011-06-01 16:42:47 +0000238 if (Op0->hasOneUse()) {
239 ConstantInt *C1;
Craig Topperf40110f2014-04-25 05:29:35 +0000240 Value *Sub = nullptr;
Stuart Hastings23804832011-06-01 16:42:47 +0000241 if (match(Op0, m_Sub(m_Value(Y), m_Value(X))))
Craig Topperbb4069e2017-07-07 23:16:26 +0000242 Sub = Builder.CreateSub(X, Y, "suba");
Stuart Hastings23804832011-06-01 16:42:47 +0000243 else if (match(Op0, m_Add(m_Value(Y), m_ConstantInt(C1))))
Craig Topperbb4069e2017-07-07 23:16:26 +0000244 Sub = Builder.CreateSub(Builder.CreateNeg(C1), Y, "subc");
Stuart Hastings23804832011-06-01 16:42:47 +0000245 if (Sub)
246 return
247 BinaryOperator::CreateMul(Sub,
248 ConstantInt::get(Y->getType(), PosVal));
Stuart Hastings82843742011-05-30 20:00:33 +0000249 }
250 }
251 }
Chris Lattner6b657ae2011-02-10 05:36:31 +0000252 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000253
Chris Lattner6b657ae2011-02-10 05:36:31 +0000254 // Simplify mul instructions with a constant RHS.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000255 if (isa<Constant>(Op1)) {
Sanjay Pateldb0938f2017-01-10 23:49:07 +0000256 if (Instruction *FoldedMul = foldOpWithConstantIntoOperand(I))
257 return FoldedMul;
Benjamin Kramer72196f32014-01-19 15:24:22 +0000258
259 // Canonicalize (X+C1)*CI -> X*CI+C1*CI.
260 {
261 Value *X;
262 Constant *C1;
263 if (match(Op0, m_OneUse(m_Add(m_Value(X), m_Constant(C1))))) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000264 Value *Mul = Builder.CreateMul(C1, Op1);
David Majnemer6cf6c052014-06-19 07:14:33 +0000265 // Only go forward with the transform if C1*CI simplifies to a tidier
266 // constant.
267 if (!match(Mul, m_Mul(m_Value(), m_Value())))
Craig Topperbb4069e2017-07-07 23:16:26 +0000268 return BinaryOperator::CreateAdd(Builder.CreateMul(X, Op1), Mul);
Benjamin Kramer72196f32014-01-19 15:24:22 +0000269 }
270 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000271 }
272
David Majnemer8279a7502014-11-22 07:25:19 +0000273 if (Value *Op0v = dyn_castNegVal(Op0)) { // -X * -Y = X*Y
274 if (Value *Op1v = dyn_castNegVal(Op1)) {
275 BinaryOperator *BO = BinaryOperator::CreateMul(Op0v, Op1v);
276 if (I.hasNoSignedWrap() &&
277 match(Op0, m_NSWSub(m_Value(), m_Value())) &&
278 match(Op1, m_NSWSub(m_Value(), m_Value())))
279 BO->setHasNoSignedWrap();
280 return BO;
281 }
282 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000283
284 // (X / Y) * Y = X - (X % Y)
285 // (X / Y) * -Y = (X % Y) - X
286 {
Sanjay Patela0a56822017-03-14 17:27:27 +0000287 Value *Y = Op1;
288 BinaryOperator *Div = dyn_cast<BinaryOperator>(Op0);
289 if (!Div || (Div->getOpcode() != Instruction::UDiv &&
290 Div->getOpcode() != Instruction::SDiv)) {
291 Y = Op0;
292 Div = dyn_cast<BinaryOperator>(Op1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000293 }
Sanjay Patela0a56822017-03-14 17:27:27 +0000294 Value *Neg = dyn_castNegVal(Y);
295 if (Div && Div->hasOneUse() &&
296 (Div->getOperand(1) == Y || Div->getOperand(1) == Neg) &&
297 (Div->getOpcode() == Instruction::UDiv ||
298 Div->getOpcode() == Instruction::SDiv)) {
299 Value *X = Div->getOperand(0), *DivOp1 = Div->getOperand(1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000300
Chris Lattner35315d02011-02-06 21:44:57 +0000301 // If the division is exact, X % Y is zero, so we end up with X or -X.
Sanjay Patela0a56822017-03-14 17:27:27 +0000302 if (Div->isExact()) {
303 if (DivOp1 == Y)
304 return replaceInstUsesWith(I, X);
305 return BinaryOperator::CreateNeg(X);
306 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000307
Sanjay Patela0a56822017-03-14 17:27:27 +0000308 auto RemOpc = Div->getOpcode() == Instruction::UDiv ? Instruction::URem
309 : Instruction::SRem;
Craig Topperbb4069e2017-07-07 23:16:26 +0000310 Value *Rem = Builder.CreateBinOp(RemOpc, X, DivOp1);
Sanjay Patela0a56822017-03-14 17:27:27 +0000311 if (DivOp1 == Y)
312 return BinaryOperator::CreateSub(X, Rem);
313 return BinaryOperator::CreateSub(Rem, X);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000314 }
315 }
316
317 /// i1 mul -> i1 and.
Craig Topperfde47232017-07-09 07:04:03 +0000318 if (I.getType()->isIntOrIntVectorTy(1))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000319 return BinaryOperator::CreateAnd(Op0, Op1);
320
321 // X*(1 << Y) --> X << Y
322 // (1 << Y)*X --> X << Y
323 {
324 Value *Y;
David Majnemer546f8102014-11-22 08:57:02 +0000325 BinaryOperator *BO = nullptr;
326 bool ShlNSW = false;
327 if (match(Op0, m_Shl(m_One(), m_Value(Y)))) {
328 BO = BinaryOperator::CreateShl(Op1, Y);
David Majnemer087dc8b2015-01-04 07:36:02 +0000329 ShlNSW = cast<ShlOperator>(Op0)->hasNoSignedWrap();
David Majnemer8e6f6a92014-11-24 16:41:13 +0000330 } else if (match(Op1, m_Shl(m_One(), m_Value(Y)))) {
David Majnemer546f8102014-11-22 08:57:02 +0000331 BO = BinaryOperator::CreateShl(Op0, Y);
David Majnemer087dc8b2015-01-04 07:36:02 +0000332 ShlNSW = cast<ShlOperator>(Op1)->hasNoSignedWrap();
David Majnemer546f8102014-11-22 08:57:02 +0000333 }
334 if (BO) {
335 if (I.hasNoUnsignedWrap())
336 BO->setHasNoUnsignedWrap();
337 if (I.hasNoSignedWrap() && ShlNSW)
338 BO->setHasNoSignedWrap();
339 return BO;
340 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000341 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000342
Sanjay Patelcb8ac002018-02-13 20:41:22 +0000343 Value *X;
344 // (bool X) * Y --> X ? Y : 0
345 if (match(Op0, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
346 return SelectInst::Create(X, Op1, ConstantInt::get(I.getType(), 0));
347
348 // Y * (bool X) --> X ? Y : 0
349 if (match(Op1, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
350 return SelectInst::Create(X, Op0, ConstantInt::get(I.getType(), 0));
351
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000352 // If one of the operands of the multiply is a cast from a boolean value, then
353 // we know the bool is either zero or one, so this is a 'masking' multiply.
354 // X * Y (where Y is 0 or 1) -> X & (0-Y)
Duncan Sands19d0b472010-02-16 11:11:14 +0000355 if (!I.getType()->isVectorTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000356 // -2 is "-1 << 1" so it is all bits set except the low one.
357 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000358
Craig Topperf40110f2014-04-25 05:29:35 +0000359 Value *BoolCast = nullptr, *OtherOp = nullptr;
Richard Trieu7a083812016-02-18 22:09:30 +0000360 if (MaskedValueIsZero(Op0, Negative2, 0, &I)) {
361 BoolCast = Op0;
362 OtherOp = Op1;
363 } else if (MaskedValueIsZero(Op1, Negative2, 0, &I)) {
364 BoolCast = Op1;
365 OtherOp = Op0;
366 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000367
368 if (BoolCast) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000369 Value *V = Builder.CreateSub(Constant::getNullValue(I.getType()),
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000370 BoolCast);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000371 return BinaryOperator::CreateAnd(V, OtherOp);
372 }
373 }
374
David Majnemera1cfd7c2016-12-30 00:28:58 +0000375 // Check for (mul (sext x), y), see if we can merge this into an
376 // integer mul followed by a sext.
377 if (SExtInst *Op0Conv = dyn_cast<SExtInst>(Op0)) {
378 // (mul (sext x), cst) --> (sext (mul x, cst'))
379 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
380 if (Op0Conv->hasOneUse()) {
381 Constant *CI =
382 ConstantExpr::getTrunc(Op1C, Op0Conv->getOperand(0)->getType());
383 if (ConstantExpr::getSExt(CI, I.getType()) == Op1C &&
Craig Topper2b1fc322017-05-22 06:25:31 +0000384 willNotOverflowSignedMul(Op0Conv->getOperand(0), CI, I)) {
David Majnemera1cfd7c2016-12-30 00:28:58 +0000385 // Insert the new, smaller mul.
386 Value *NewMul =
Craig Topperbb4069e2017-07-07 23:16:26 +0000387 Builder.CreateNSWMul(Op0Conv->getOperand(0), CI, "mulconv");
David Majnemera1cfd7c2016-12-30 00:28:58 +0000388 return new SExtInst(NewMul, I.getType());
389 }
390 }
391 }
392
393 // (mul (sext x), (sext y)) --> (sext (mul int x, y))
394 if (SExtInst *Op1Conv = dyn_cast<SExtInst>(Op1)) {
395 // Only do this if x/y have the same type, if at last one of them has a
396 // single use (so we don't increase the number of sexts), and if the
397 // integer mul will not overflow.
398 if (Op0Conv->getOperand(0)->getType() ==
399 Op1Conv->getOperand(0)->getType() &&
400 (Op0Conv->hasOneUse() || Op1Conv->hasOneUse()) &&
Craig Topper2b1fc322017-05-22 06:25:31 +0000401 willNotOverflowSignedMul(Op0Conv->getOperand(0),
David Majnemera1cfd7c2016-12-30 00:28:58 +0000402 Op1Conv->getOperand(0), I)) {
403 // Insert the new integer mul.
Craig Topperbb4069e2017-07-07 23:16:26 +0000404 Value *NewMul = Builder.CreateNSWMul(
David Majnemera1cfd7c2016-12-30 00:28:58 +0000405 Op0Conv->getOperand(0), Op1Conv->getOperand(0), "mulconv");
406 return new SExtInst(NewMul, I.getType());
407 }
408 }
409 }
410
411 // Check for (mul (zext x), y), see if we can merge this into an
412 // integer mul followed by a zext.
413 if (auto *Op0Conv = dyn_cast<ZExtInst>(Op0)) {
414 // (mul (zext x), cst) --> (zext (mul x, cst'))
415 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
416 if (Op0Conv->hasOneUse()) {
417 Constant *CI =
418 ConstantExpr::getTrunc(Op1C, Op0Conv->getOperand(0)->getType());
419 if (ConstantExpr::getZExt(CI, I.getType()) == Op1C &&
Craig Topperbb973722017-05-15 02:44:08 +0000420 willNotOverflowUnsignedMul(Op0Conv->getOperand(0), CI, I)) {
David Majnemera1cfd7c2016-12-30 00:28:58 +0000421 // Insert the new, smaller mul.
422 Value *NewMul =
Craig Topperbb4069e2017-07-07 23:16:26 +0000423 Builder.CreateNUWMul(Op0Conv->getOperand(0), CI, "mulconv");
David Majnemera1cfd7c2016-12-30 00:28:58 +0000424 return new ZExtInst(NewMul, I.getType());
425 }
426 }
427 }
428
429 // (mul (zext x), (zext y)) --> (zext (mul int x, y))
430 if (auto *Op1Conv = dyn_cast<ZExtInst>(Op1)) {
431 // Only do this if x/y have the same type, if at last one of them has a
432 // single use (so we don't increase the number of zexts), and if the
433 // integer mul will not overflow.
434 if (Op0Conv->getOperand(0)->getType() ==
435 Op1Conv->getOperand(0)->getType() &&
436 (Op0Conv->hasOneUse() || Op1Conv->hasOneUse()) &&
Craig Topperbb973722017-05-15 02:44:08 +0000437 willNotOverflowUnsignedMul(Op0Conv->getOperand(0),
438 Op1Conv->getOperand(0), I)) {
David Majnemera1cfd7c2016-12-30 00:28:58 +0000439 // Insert the new integer mul.
Craig Topperbb4069e2017-07-07 23:16:26 +0000440 Value *NewMul = Builder.CreateNUWMul(
David Majnemera1cfd7c2016-12-30 00:28:58 +0000441 Op0Conv->getOperand(0), Op1Conv->getOperand(0), "mulconv");
442 return new ZExtInst(NewMul, I.getType());
443 }
444 }
445 }
446
Craig Topper2b1fc322017-05-22 06:25:31 +0000447 if (!I.hasNoSignedWrap() && willNotOverflowSignedMul(Op0, Op1, I)) {
David Majnemer54c2ca22014-12-26 09:10:14 +0000448 Changed = true;
449 I.setHasNoSignedWrap(true);
450 }
451
Craig Topperbb973722017-05-15 02:44:08 +0000452 if (!I.hasNoUnsignedWrap() && willNotOverflowUnsignedMul(Op0, Op1, I)) {
David Majnemerb1296ec2014-12-26 09:50:35 +0000453 Changed = true;
454 I.setHasNoUnsignedWrap(true);
455 }
456
Craig Topperf40110f2014-04-25 05:29:35 +0000457 return Changed ? &I : nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000458}
459
Sanjay Patel17045f72014-10-14 00:33:23 +0000460/// Detect pattern log2(Y * 0.5) with corresponding fast math flags.
Pedro Artigas993acd02012-11-30 22:07:05 +0000461static void detectLog2OfHalf(Value *&Op, Value *&Y, IntrinsicInst *&Log2) {
Sanjay Patel17045f72014-10-14 00:33:23 +0000462 if (!Op->hasOneUse())
463 return;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000464
Sanjay Patel17045f72014-10-14 00:33:23 +0000465 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op);
466 if (!II)
467 return;
Sanjay Patel629c4112017-11-06 16:27:15 +0000468 if (II->getIntrinsicID() != Intrinsic::log2 || !II->isFast())
Sanjay Patel17045f72014-10-14 00:33:23 +0000469 return;
470 Log2 = II;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000471
Sanjay Patel17045f72014-10-14 00:33:23 +0000472 Value *OpLog2Of = II->getArgOperand(0);
473 if (!OpLog2Of->hasOneUse())
474 return;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000475
Sanjay Patel17045f72014-10-14 00:33:23 +0000476 Instruction *I = dyn_cast<Instruction>(OpLog2Of);
477 if (!I)
478 return;
Sanjay Patel629c4112017-11-06 16:27:15 +0000479
480 if (I->getOpcode() != Instruction::FMul || !I->isFast())
Sanjay Patel17045f72014-10-14 00:33:23 +0000481 return;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000482
Sanjay Patel17045f72014-10-14 00:33:23 +0000483 if (match(I->getOperand(0), m_SpecificFP(0.5)))
484 Y = I->getOperand(1);
485 else if (match(I->getOperand(1), m_SpecificFP(0.5)))
486 Y = I->getOperand(0);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000487}
Pedro Artigas993acd02012-11-30 22:07:05 +0000488
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000489static bool isFiniteNonZeroFp(Constant *C) {
490 if (C->getType()->isVectorTy()) {
491 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
492 ++I) {
Michael Kupersteinbcb26d62015-03-05 08:38:57 +0000493 ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(C->getAggregateElement(I));
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000494 if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
495 return false;
496 }
497 return true;
498 }
499
500 return isa<ConstantFP>(C) &&
501 cast<ConstantFP>(C)->getValueAPF().isFiniteNonZero();
502}
503
504static bool isNormalFp(Constant *C) {
505 if (C->getType()->isVectorTy()) {
506 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
507 ++I) {
Michael Kupersteinbcb26d62015-03-05 08:38:57 +0000508 ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(C->getAggregateElement(I));
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000509 if (!CFP || !CFP->getValueAPF().isNormal())
510 return false;
511 }
512 return true;
513 }
514
515 return isa<ConstantFP>(C) && cast<ConstantFP>(C)->getValueAPF().isNormal();
516}
517
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000518/// Helper function of InstCombiner::visitFMul(BinaryOperator(). It returns
519/// true iff the given value is FMul or FDiv with one and only one operand
520/// being a normal constant (i.e. not Zero/NaN/Infinity).
521static bool isFMulOrFDivWithConstant(Value *V) {
522 Instruction *I = dyn_cast<Instruction>(V);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000523 if (!I || (I->getOpcode() != Instruction::FMul &&
Shuxin Yang80138662013-01-07 22:41:28 +0000524 I->getOpcode() != Instruction::FDiv))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000525 return false;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000526
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000527 Constant *C0 = dyn_cast<Constant>(I->getOperand(0));
528 Constant *C1 = dyn_cast<Constant>(I->getOperand(1));
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000529
530 if (C0 && C1)
531 return false;
532
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000533 return (C0 && isFiniteNonZeroFp(C0)) || (C1 && isFiniteNonZeroFp(C1));
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000534}
535
536/// foldFMulConst() is a helper routine of InstCombiner::visitFMul().
537/// The input \p FMulOrDiv is a FMul/FDiv with one and only one operand
538/// being a constant (i.e. isFMulOrFDivWithConstant(FMulOrDiv) == true).
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000539/// This function is to simplify "FMulOrDiv * C" and returns the
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000540/// resulting expression. Note that this function could return NULL in
541/// case the constants cannot be folded into a normal floating-point.
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000542Value *InstCombiner::foldFMulConst(Instruction *FMulOrDiv, Constant *C,
Shuxin Yang80138662013-01-07 22:41:28 +0000543 Instruction *InsertBefore) {
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000544 assert(isFMulOrFDivWithConstant(FMulOrDiv) && "V is invalid");
545
546 Value *Opnd0 = FMulOrDiv->getOperand(0);
547 Value *Opnd1 = FMulOrDiv->getOperand(1);
548
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000549 Constant *C0 = dyn_cast<Constant>(Opnd0);
550 Constant *C1 = dyn_cast<Constant>(Opnd1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000551
Craig Topperf40110f2014-04-25 05:29:35 +0000552 BinaryOperator *R = nullptr;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000553
554 // (X * C0) * C => X * (C0*C)
555 if (FMulOrDiv->getOpcode() == Instruction::FMul) {
556 Constant *F = ConstantExpr::getFMul(C1 ? C1 : C0, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000557 if (isNormalFp(F))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000558 R = BinaryOperator::CreateFMul(C1 ? Opnd0 : Opnd1, F);
559 } else {
560 if (C0) {
561 // (C0 / X) * C => (C0 * C) / X
Shuxin Yang3a7ca6e2013-09-19 21:13:46 +0000562 if (FMulOrDiv->hasOneUse()) {
563 // It would otherwise introduce another div.
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000564 Constant *F = ConstantExpr::getFMul(C0, C);
Shuxin Yang3a7ca6e2013-09-19 21:13:46 +0000565 if (isNormalFp(F))
566 R = BinaryOperator::CreateFDiv(F, Opnd1);
567 }
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000568 } else {
569 // (X / C1) * C => X * (C/C1) if C/C1 is not a denormal
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000570 Constant *F = ConstantExpr::getFDiv(C, C1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000571 if (isNormalFp(F)) {
572 R = BinaryOperator::CreateFMul(Opnd0, F);
573 } else {
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000574 // (X / C1) * C => X / (C1/C)
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000575 Constant *F = ConstantExpr::getFDiv(C1, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000576 if (isNormalFp(F))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000577 R = BinaryOperator::CreateFDiv(Opnd0, F);
578 }
579 }
580 }
581
582 if (R) {
Sanjay Patel629c4112017-11-06 16:27:15 +0000583 R->setFast(true);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000584 InsertNewInstWith(R, *InsertBefore);
585 }
586
587 return R;
588}
589
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000590Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +0000591 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000592 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
593
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000594 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +0000595 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000596
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000597 if (isa<Constant>(Op0))
598 std::swap(Op0, Op1);
599
Craig Toppera4205622017-06-09 03:21:29 +0000600 if (Value *V = SimplifyFMulInst(Op0, Op1, I.getFastMathFlags(),
601 SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +0000602 return replaceInstUsesWith(I, V);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000603
Sanjay Patel629c4112017-11-06 16:27:15 +0000604 bool AllowReassociate = I.isFast();
Shuxin Yange8227452013-01-15 21:09:32 +0000605
Michael Ilsemand5787be2012-12-12 00:28:32 +0000606 // Simplify mul instructions with a constant RHS.
607 if (isa<Constant>(Op1)) {
Sanjay Pateldb0938f2017-01-10 23:49:07 +0000608 if (Instruction *FoldedMul = foldOpWithConstantIntoOperand(I))
609 return FoldedMul;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000610
Owen Andersonf74cfe02014-01-16 20:36:42 +0000611 // (fmul X, -1.0) --> (fsub -0.0, X)
Benjamin Kramerfea9ac92014-01-18 16:43:14 +0000612 if (match(Op1, m_SpecificFP(-1.0))) {
613 Constant *NegZero = ConstantFP::getNegativeZero(Op1->getType());
614 Instruction *RI = BinaryOperator::CreateFSub(NegZero, Op0);
Owen Andersonf74cfe02014-01-16 20:36:42 +0000615 RI->copyFastMathFlags(&I);
616 return RI;
617 }
618
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000619 Constant *C = cast<Constant>(Op1);
620 if (AllowReassociate && isFiniteNonZeroFp(C)) {
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000621 // Let MDC denote an expression in one of these forms:
622 // X * C, C/X, X/C, where C is a constant.
623 //
624 // Try to simplify "MDC * Constant"
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000625 if (isFMulOrFDivWithConstant(Op0))
626 if (Value *V = foldFMulConst(cast<Instruction>(Op0), C, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +0000627 return replaceInstUsesWith(I, V);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000628
Quentin Colombete684a6d2013-02-28 21:12:40 +0000629 // (MDC +/- C1) * C => (MDC * C) +/- (C1 * C)
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000630 Instruction *FAddSub = dyn_cast<Instruction>(Op0);
631 if (FAddSub &&
632 (FAddSub->getOpcode() == Instruction::FAdd ||
633 FAddSub->getOpcode() == Instruction::FSub)) {
634 Value *Opnd0 = FAddSub->getOperand(0);
635 Value *Opnd1 = FAddSub->getOperand(1);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000636 Constant *C0 = dyn_cast<Constant>(Opnd0);
637 Constant *C1 = dyn_cast<Constant>(Opnd1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000638 bool Swap = false;
639 if (C0) {
Shuxin Yang80138662013-01-07 22:41:28 +0000640 std::swap(C0, C1);
641 std::swap(Opnd0, Opnd1);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000642 Swap = true;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000643 }
644
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000645 if (C1 && isFiniteNonZeroFp(C1) && isFMulOrFDivWithConstant(Opnd0)) {
Quentin Colombete684a6d2013-02-28 21:12:40 +0000646 Value *M1 = ConstantExpr::getFMul(C1, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000647 Value *M0 = isNormalFp(cast<Constant>(M1)) ?
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000648 foldFMulConst(cast<Instruction>(Opnd0), C, &I) :
Craig Topperf40110f2014-04-25 05:29:35 +0000649 nullptr;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000650 if (M0 && M1) {
651 if (Swap && FAddSub->getOpcode() == Instruction::FSub)
652 std::swap(M0, M1);
653
Benjamin Kramer67485762013-09-30 15:39:59 +0000654 Instruction *RI = (FAddSub->getOpcode() == Instruction::FAdd)
655 ? BinaryOperator::CreateFAdd(M0, M1)
656 : BinaryOperator::CreateFSub(M0, M1);
Shuxin Yange8227452013-01-15 21:09:32 +0000657 RI->copyFastMathFlags(&I);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000658 return RI;
659 }
660 }
661 }
662 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000663 }
664
Matt Arsenault56c079f2016-01-30 05:02:00 +0000665 if (Op0 == Op1) {
666 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
667 // sqrt(X) * sqrt(X) -> X
668 if (AllowReassociate && II->getIntrinsicID() == Intrinsic::sqrt)
Sanjay Patel4b198802016-02-01 22:23:39 +0000669 return replaceInstUsesWith(I, II->getOperand(0));
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000670
Matt Arsenault56c079f2016-01-30 05:02:00 +0000671 // fabs(X) * fabs(X) -> X * X
672 if (II->getIntrinsicID() == Intrinsic::fabs) {
673 Instruction *FMulVal = BinaryOperator::CreateFMul(II->getOperand(0),
674 II->getOperand(0),
675 I.getName());
676 FMulVal->copyFastMathFlags(&I);
677 return FMulVal;
678 }
679 }
680 }
681
Pedro Artigasd8795042012-11-30 19:09:41 +0000682 // Under unsafe algebra do:
683 // X * log2(0.5*Y) = X*log2(Y) - X
Sanjay Patelb41d4612014-10-02 15:20:45 +0000684 if (AllowReassociate) {
Craig Topperf40110f2014-04-25 05:29:35 +0000685 Value *OpX = nullptr;
686 Value *OpY = nullptr;
Pedro Artigasd8795042012-11-30 19:09:41 +0000687 IntrinsicInst *Log2;
Pedro Artigas993acd02012-11-30 22:07:05 +0000688 detectLog2OfHalf(Op0, OpY, Log2);
689 if (OpY) {
690 OpX = Op1;
691 } else {
692 detectLog2OfHalf(Op1, OpY, Log2);
693 if (OpY) {
694 OpX = Op0;
Pedro Artigasd8795042012-11-30 19:09:41 +0000695 }
696 }
697 // if pattern detected emit alternate sequence
698 if (OpX && OpY) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000699 BuilderTy::FastMathFlagGuard Guard(Builder);
700 Builder.setFastMathFlags(Log2->getFastMathFlags());
Pedro Artigasd8795042012-11-30 19:09:41 +0000701 Log2->setArgOperand(0, OpY);
Craig Topperbb4069e2017-07-07 23:16:26 +0000702 Value *FMulVal = Builder.CreateFMul(OpX, Log2);
703 Value *FSub = Builder.CreateFSub(FMulVal, OpX);
Benjamin Kramer67485762013-09-30 15:39:59 +0000704 FSub->takeName(&I);
Sanjay Patel4b198802016-02-01 22:23:39 +0000705 return replaceInstUsesWith(I, FSub);
Pedro Artigasd8795042012-11-30 19:09:41 +0000706 }
707 }
708
Dmitry Venikova58d8de2018-01-02 05:58:11 +0000709 // sqrt(a) * sqrt(b) -> sqrt(a * b)
Sanjay Patel1998cc62018-02-12 18:38:35 +0000710 if (AllowReassociate && Op0->hasOneUse() && Op1->hasOneUse()) {
Dmitry Venikova58d8de2018-01-02 05:58:11 +0000711 Value *Opnd0 = nullptr;
712 Value *Opnd1 = nullptr;
713 if (match(Op0, m_Intrinsic<Intrinsic::sqrt>(m_Value(Opnd0))) &&
714 match(Op1, m_Intrinsic<Intrinsic::sqrt>(m_Value(Opnd1)))) {
715 BuilderTy::FastMathFlagGuard Guard(Builder);
716 Builder.setFastMathFlags(I.getFastMathFlags());
717 Value *FMulVal = Builder.CreateFMul(Opnd0, Opnd1);
718 Value *Sqrt = Intrinsic::getDeclaration(I.getModule(),
719 Intrinsic::sqrt, I.getType());
720 Value *SqrtCall = Builder.CreateCall(Sqrt, FMulVal);
721 return replaceInstUsesWith(I, SqrtCall);
722 }
723 }
724
Shuxin Yange8227452013-01-15 21:09:32 +0000725 // Handle symmetric situation in a 2-iteration loop
726 Value *Opnd0 = Op0;
727 Value *Opnd1 = Op1;
728 for (int i = 0; i < 2; i++) {
729 bool IgnoreZeroSign = I.hasNoSignedZeros();
730 if (BinaryOperator::isFNeg(Opnd0, IgnoreZeroSign)) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000731 BuilderTy::FastMathFlagGuard Guard(Builder);
732 Builder.setFastMathFlags(I.getFastMathFlags());
Benjamin Kramer67485762013-09-30 15:39:59 +0000733
Shuxin Yange8227452013-01-15 21:09:32 +0000734 Value *N0 = dyn_castFNegVal(Opnd0, IgnoreZeroSign);
735 Value *N1 = dyn_castFNegVal(Opnd1, IgnoreZeroSign);
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000736
Shuxin Yange8227452013-01-15 21:09:32 +0000737 // -X * -Y => X*Y
Owen Andersone8537fc2014-01-16 20:59:41 +0000738 if (N1) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000739 Value *FMul = Builder.CreateFMul(N0, N1);
Owen Andersone8537fc2014-01-16 20:59:41 +0000740 FMul->takeName(&I);
Sanjay Patel4b198802016-02-01 22:23:39 +0000741 return replaceInstUsesWith(I, FMul);
Owen Andersone8537fc2014-01-16 20:59:41 +0000742 }
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000743
Shuxin Yange8227452013-01-15 21:09:32 +0000744 if (Opnd0->hasOneUse()) {
745 // -X * Y => -(X*Y) (Promote negation as high as possible)
Craig Topperbb4069e2017-07-07 23:16:26 +0000746 Value *T = Builder.CreateFMul(N0, Opnd1);
747 Value *Neg = Builder.CreateFNeg(T);
Benjamin Kramer67485762013-09-30 15:39:59 +0000748 Neg->takeName(&I);
Sanjay Patel4b198802016-02-01 22:23:39 +0000749 return replaceInstUsesWith(I, Neg);
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000750 }
751 }
Shuxin Yange8227452013-01-15 21:09:32 +0000752
Quentin Colombetaa103b32017-09-20 17:32:16 +0000753 // Handle specials cases for FMul with selects feeding the operation
754 if (Value *V = SimplifySelectsFeedingBinaryOp(I, Op0, Op1))
755 return replaceInstUsesWith(I, V);
756
Shuxin Yange8227452013-01-15 21:09:32 +0000757 // (X*Y) * X => (X*X) * Y where Y != X
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000758 // The purpose is two-fold:
Shuxin Yange8227452013-01-15 21:09:32 +0000759 // 1) to form a power expression (of X).
760 // 2) potentially shorten the critical path: After transformation, the
761 // latency of the instruction Y is amortized by the expression of X*X,
762 // and therefore Y is in a "less critical" position compared to what it
763 // was before the transformation.
Shuxin Yange8227452013-01-15 21:09:32 +0000764 if (AllowReassociate) {
765 Value *Opnd0_0, *Opnd0_1;
766 if (Opnd0->hasOneUse() &&
767 match(Opnd0, m_FMul(m_Value(Opnd0_0), m_Value(Opnd0_1)))) {
Craig Topperf40110f2014-04-25 05:29:35 +0000768 Value *Y = nullptr;
Shuxin Yange8227452013-01-15 21:09:32 +0000769 if (Opnd0_0 == Opnd1 && Opnd0_1 != Opnd1)
770 Y = Opnd0_1;
771 else if (Opnd0_1 == Opnd1 && Opnd0_0 != Opnd1)
772 Y = Opnd0_0;
773
774 if (Y) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000775 BuilderTy::FastMathFlagGuard Guard(Builder);
776 Builder.setFastMathFlags(I.getFastMathFlags());
777 Value *T = Builder.CreateFMul(Opnd1, Opnd1);
778 Value *R = Builder.CreateFMul(T, Y);
Benjamin Kramer67485762013-09-30 15:39:59 +0000779 R->takeName(&I);
Sanjay Patel4b198802016-02-01 22:23:39 +0000780 return replaceInstUsesWith(I, R);
Shuxin Yange8227452013-01-15 21:09:32 +0000781 }
782 }
783 }
784
785 if (!isa<Constant>(Op1))
786 std::swap(Opnd0, Opnd1);
787 else
788 break;
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000789 }
790
Craig Topperf40110f2014-04-25 05:29:35 +0000791 return Changed ? &I : nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000792}
793
Sanjay Patelae2e3a42017-10-06 23:20:16 +0000794/// Fold a divide or remainder with a select instruction divisor when one of the
795/// select operands is zero. In that case, we can use the other select operand
796/// because div/rem by zero is undefined.
797bool InstCombiner::simplifyDivRemOfSelectWithZeroOp(BinaryOperator &I) {
798 SelectInst *SI = dyn_cast<SelectInst>(I.getOperand(1));
799 if (!SI)
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000800 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000801
Sanjay Patelae2e3a42017-10-06 23:20:16 +0000802 int NonNullOperand;
803 if (match(SI->getTrueValue(), m_Zero()))
804 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
805 NonNullOperand = 2;
806 else if (match(SI->getFalseValue(), m_Zero()))
807 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
808 NonNullOperand = 1;
809 else
810 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000811
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000812 // Change the div/rem to use 'Y' instead of the select.
813 I.setOperand(1, SI->getOperand(NonNullOperand));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000814
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000815 // Okay, we know we replace the operand of the div/rem with 'Y' with no
816 // problem. However, the select, or the condition of the select may have
817 // multiple uses. Based on our knowledge that the operand must be non-zero,
818 // propagate the known value for the select into other uses of it, and
819 // propagate a known value of the condition into its other users.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000820
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000821 // If the select and condition only have a single use, don't bother with this,
822 // early exit.
Sanjay Patelae2e3a42017-10-06 23:20:16 +0000823 Value *SelectCond = SI->getCondition();
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000824 if (SI->use_empty() && SelectCond->hasOneUse())
825 return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000826
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000827 // Scan the current block backward, looking for other uses of SI.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000828 BasicBlock::iterator BBI = I.getIterator(), BBFront = I.getParent()->begin();
Sanjay Patel72d339a2017-10-06 23:43:06 +0000829 Type *CondTy = SelectCond->getType();
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000830 while (BBI != BBFront) {
831 --BBI;
832 // If we found a call to a function, we can't assume it will return, so
833 // information from below it cannot be propagated above it.
834 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
835 break;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000836
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000837 // Replace uses of the select or its condition with the known values.
838 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
839 I != E; ++I) {
840 if (*I == SI) {
841 *I = SI->getOperand(NonNullOperand);
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000842 Worklist.Add(&*BBI);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000843 } else if (*I == SelectCond) {
Sanjay Patel72d339a2017-10-06 23:43:06 +0000844 *I = NonNullOperand == 1 ? ConstantInt::getTrue(CondTy)
845 : ConstantInt::getFalse(CondTy);
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000846 Worklist.Add(&*BBI);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000847 }
848 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000849
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000850 // If we past the instruction, quit looking for it.
851 if (&*BBI == SI)
Craig Topperf40110f2014-04-25 05:29:35 +0000852 SI = nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000853 if (&*BBI == SelectCond)
Craig Topperf40110f2014-04-25 05:29:35 +0000854 SelectCond = nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000855
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000856 // If we ran out of things to eliminate, break out of the loop.
Craig Topperf40110f2014-04-25 05:29:35 +0000857 if (!SelectCond && !SI)
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000858 break;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000859
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000860 }
861 return true;
862}
863
Sanjay Patel1998cc62018-02-12 18:38:35 +0000864/// True if the multiply can not be expressed in an int this size.
865static bool multiplyOverflows(const APInt &C1, const APInt &C2, APInt &Product,
866 bool IsSigned) {
867 bool Overflow;
868 Product = IsSigned ? C1.smul_ov(C2, Overflow) : C1.umul_ov(C2, Overflow);
869 return Overflow;
870}
871
872/// True if C2 is a multiple of C1. Quotient contains C2/C1.
873static bool isMultiple(const APInt &C1, const APInt &C2, APInt &Quotient,
874 bool IsSigned) {
875 assert(C1.getBitWidth() == C2.getBitWidth() && "Constant widths not equal");
876
877 // Bail if we will divide by zero.
878 if (C2.isNullValue())
879 return false;
880
881 // Bail if we would divide INT_MIN by -1.
882 if (IsSigned && C1.isMinSignedValue() && C2.isAllOnesValue())
883 return false;
884
885 APInt Remainder(C1.getBitWidth(), /*Val=*/0ULL, IsSigned);
886 if (IsSigned)
887 APInt::sdivrem(C1, C2, Quotient, Remainder);
888 else
889 APInt::udivrem(C1, C2, Quotient, Remainder);
890
891 return Remainder.isMinValue();
892}
893
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000894/// This function implements the transforms common to both integer division
895/// instructions (udiv and sdiv). It is called by the visitors to those integer
896/// division instructions.
897/// @brief Common integer divide transforms
898Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
899 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Sanjay Patel9530f182018-01-21 16:14:51 +0000900 bool IsSigned = I.getOpcode() == Instruction::SDiv;
Sanjay Patel39059d22018-02-12 14:14:56 +0000901 Type *Ty = I.getType();
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000902
Chris Lattner7c99f192011-05-22 18:18:41 +0000903 // The RHS is known non-zero.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000904 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I)) {
Chris Lattner7c99f192011-05-22 18:18:41 +0000905 I.setOperand(1, V);
906 return &I;
907 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000908
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000909 // Handle cases involving: [su]div X, (select Cond, Y, Z)
910 // This does not apply for fdiv.
Sanjay Patelae2e3a42017-10-06 23:20:16 +0000911 if (simplifyDivRemOfSelectWithZeroOp(I))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000912 return &I;
913
Sanjay Patel1998cc62018-02-12 18:38:35 +0000914 const APInt *C2;
915 if (match(Op1, m_APInt(C2))) {
916 Value *X;
917 const APInt *C1;
David Majnemerf9a095d2014-08-16 08:55:06 +0000918
Sanjay Patel1998cc62018-02-12 18:38:35 +0000919 // (X / C1) / C2 -> X / (C1*C2)
920 if ((IsSigned && match(Op0, m_SDiv(m_Value(X), m_APInt(C1)))) ||
921 (!IsSigned && match(Op0, m_UDiv(m_Value(X), m_APInt(C1))))) {
922 APInt Product(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
923 if (!multiplyOverflows(*C1, *C2, Product, IsSigned))
924 return BinaryOperator::Create(I.getOpcode(), X,
925 ConstantInt::get(Ty, Product));
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000926 }
Sanjay Patel1998cc62018-02-12 18:38:35 +0000927
928 if ((IsSigned && match(Op0, m_NSWMul(m_Value(X), m_APInt(C1)))) ||
929 (!IsSigned && match(Op0, m_NUWMul(m_Value(X), m_APInt(C1))))) {
930 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
931
932 // (X * C1) / C2 -> X / (C2 / C1) if C2 is a multiple of C1.
933 if (isMultiple(*C2, *C1, Quotient, IsSigned)) {
934 auto *NewDiv = BinaryOperator::Create(I.getOpcode(), X,
935 ConstantInt::get(Ty, Quotient));
936 NewDiv->setIsExact(I.isExact());
937 return NewDiv;
938 }
939
940 // (X * C1) / C2 -> X * (C1 / C2) if C1 is a multiple of C2.
941 if (isMultiple(*C1, *C2, Quotient, IsSigned)) {
942 auto *Mul = BinaryOperator::Create(Instruction::Mul, X,
943 ConstantInt::get(Ty, Quotient));
944 auto *OBO = cast<OverflowingBinaryOperator>(Op0);
945 Mul->setHasNoUnsignedWrap(!IsSigned && OBO->hasNoUnsignedWrap());
946 Mul->setHasNoSignedWrap(OBO->hasNoSignedWrap());
947 return Mul;
948 }
949 }
950
951 if ((IsSigned && match(Op0, m_NSWShl(m_Value(X), m_APInt(C1))) &&
952 *C1 != C1->getBitWidth() - 1) ||
953 (!IsSigned && match(Op0, 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 auto *BO = BinaryOperator::Create(I.getOpcode(), X,
961 ConstantInt::get(Ty, 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 auto *Mul = BinaryOperator::Create(Instruction::Mul, X,
969 ConstantInt::get(Ty, Quotient));
970 auto *OBO = cast<OverflowingBinaryOperator>(Op0);
971 Mul->setHasNoUnsignedWrap(!IsSigned && OBO->hasNoUnsignedWrap());
972 Mul->setHasNoSignedWrap(OBO->hasNoSignedWrap());
973 return Mul;
974 }
975 }
976
977 if (!C2->isNullValue()) // avoid X udiv 0
978 if (Instruction *FoldedDiv = foldOpWithConstantIntoOperand(I))
979 return FoldedDiv;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000980 }
981
Craig Topper218a3592017-04-17 03:41:47 +0000982 if (match(Op0, m_One())) {
Sanjay Patel39059d22018-02-12 14:14:56 +0000983 assert(!Ty->isIntOrIntVectorTy(1) && "i1 divide not removed?");
984 if (IsSigned) {
Craig Topper218a3592017-04-17 03:41:47 +0000985 // If Op1 is 0 then it's undefined behaviour, if Op1 is 1 then the
986 // result is one, if Op1 is -1 then the result is minus one, otherwise
987 // it's zero.
Craig Topperbb4069e2017-07-07 23:16:26 +0000988 Value *Inc = Builder.CreateAdd(Op1, Op0);
Sanjay Patel39059d22018-02-12 14:14:56 +0000989 Value *Cmp = Builder.CreateICmpULT(Inc, ConstantInt::get(Ty, 3));
990 return SelectInst::Create(Cmp, Op1, ConstantInt::get(Ty, 0));
Craig Topper218a3592017-04-17 03:41:47 +0000991 } else {
992 // If Op1 is 0 then it's undefined behaviour. If Op1 is 1 then the
993 // result is one, otherwise it's zero.
Sanjay Patel39059d22018-02-12 14:14:56 +0000994 return new ZExtInst(Builder.CreateICmpEQ(Op1, Op0), Ty);
Nick Lewyckyf0cf8fa2014-05-14 03:03:05 +0000995 }
996 }
997
Benjamin Kramer57b3df52011-04-30 18:16:00 +0000998 // See if we can fold away this div instruction.
999 if (SimplifyDemandedInstructionBits(I))
1000 return &I;
1001
Duncan Sands771e82a2011-01-28 16:51:11 +00001002 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
Sanjay Patel9530f182018-01-21 16:14:51 +00001003 Value *X, *Z;
1004 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) // (X - Z) / Y; Y = Op1
1005 if ((IsSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
1006 (!IsSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
Duncan Sands771e82a2011-01-28 16:51:11 +00001007 return BinaryOperator::Create(I.getOpcode(), X, Op1);
Sanjay Patel9530f182018-01-21 16:14:51 +00001008
1009 // (X << Y) / X -> 1 << Y
1010 Value *Y;
1011 if (IsSigned && match(Op0, m_NSWShl(m_Specific(Op1), m_Value(Y))))
Sanjay Patel39059d22018-02-12 14:14:56 +00001012 return BinaryOperator::CreateNSWShl(ConstantInt::get(Ty, 1), Y);
Sanjay Patel9530f182018-01-21 16:14:51 +00001013 if (!IsSigned && match(Op0, m_NUWShl(m_Specific(Op1), m_Value(Y))))
Sanjay Patel39059d22018-02-12 14:14:56 +00001014 return BinaryOperator::CreateNUWShl(ConstantInt::get(Ty, 1), Y);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001015
Sanjay Patel510d6472018-02-11 17:20:32 +00001016 // X / (X * Y) -> 1 / Y if the multiplication does not overflow.
1017 if (match(Op1, m_c_Mul(m_Specific(Op0), m_Value(Y)))) {
1018 bool HasNSW = cast<OverflowingBinaryOperator>(Op1)->hasNoSignedWrap();
1019 bool HasNUW = cast<OverflowingBinaryOperator>(Op1)->hasNoUnsignedWrap();
1020 if ((IsSigned && HasNSW) || (!IsSigned && HasNUW)) {
Sanjay Patel39059d22018-02-12 14:14:56 +00001021 I.setOperand(0, ConstantInt::get(Ty, 1));
Sanjay Patel510d6472018-02-11 17:20:32 +00001022 I.setOperand(1, Y);
1023 return &I;
1024 }
1025 }
1026
Craig Topperf40110f2014-04-25 05:29:35 +00001027 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001028}
1029
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00001030static const unsigned MaxDepth = 6;
1031
David Majnemer37f8f442013-07-04 21:17:49 +00001032namespace {
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00001033
1034using FoldUDivOperandCb = Instruction *(*)(Value *Op0, Value *Op1,
1035 const BinaryOperator &I,
1036 InstCombiner &IC);
David Majnemer37f8f442013-07-04 21:17:49 +00001037
1038/// \brief Used to maintain state for visitUDivOperand().
1039struct UDivFoldAction {
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00001040 /// Informs visitUDiv() how to fold this operand. This can be zero if this
1041 /// action joins two actions together.
1042 FoldUDivOperandCb FoldAction;
David Majnemer37f8f442013-07-04 21:17:49 +00001043
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00001044 /// Which operand to fold.
1045 Value *OperandToFold;
1046
David Majnemer37f8f442013-07-04 21:17:49 +00001047 union {
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00001048 /// The instruction returned when FoldAction is invoked.
1049 Instruction *FoldResult;
David Majnemer37f8f442013-07-04 21:17:49 +00001050
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00001051 /// Stores the LHS action index if this action joins two actions together.
1052 size_t SelectLHSIdx;
David Majnemer37f8f442013-07-04 21:17:49 +00001053 };
1054
1055 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand)
Craig Topperf40110f2014-04-25 05:29:35 +00001056 : FoldAction(FA), OperandToFold(InputOperand), FoldResult(nullptr) {}
David Majnemer37f8f442013-07-04 21:17:49 +00001057 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand, size_t SLHS)
1058 : FoldAction(FA), OperandToFold(InputOperand), SelectLHSIdx(SLHS) {}
1059};
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00001060
1061} // end anonymous namespace
David Majnemer37f8f442013-07-04 21:17:49 +00001062
1063// X udiv 2^C -> X >> C
1064static Instruction *foldUDivPow2Cst(Value *Op0, Value *Op1,
1065 const BinaryOperator &I, InstCombiner &IC) {
Simon Pilgrim94cc89d2018-02-08 14:46:10 +00001066 Constant *C1 = getLogBase2(Op0->getType(), cast<Constant>(Op1));
1067 if (!C1)
1068 llvm_unreachable("Failed to constant fold udiv -> logbase2");
1069 BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, C1);
Suyog Sarda65f5ae92014-10-07 12:04:07 +00001070 if (I.isExact())
1071 LShr->setIsExact();
David Majnemer37f8f442013-07-04 21:17:49 +00001072 return LShr;
1073}
1074
1075// X udiv C, where C >= signbit
1076static Instruction *foldUDivNegCst(Value *Op0, Value *Op1,
1077 const BinaryOperator &I, InstCombiner &IC) {
Simon Pilgrim9620f4b2018-02-09 10:43:59 +00001078 Value *ICI = IC.Builder.CreateICmpULT(Op0, cast<Constant>(Op1));
David Majnemer37f8f442013-07-04 21:17:49 +00001079 return SelectInst::Create(ICI, Constant::getNullValue(I.getType()),
1080 ConstantInt::get(I.getType(), 1));
1081}
1082
1083// X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Andrea Di Biagioa82d52d2016-09-26 12:07:23 +00001084// X udiv (zext (C1 << N)), where C1 is "1<<C2" --> X >> (N+C2)
David Majnemer37f8f442013-07-04 21:17:49 +00001085static Instruction *foldUDivShl(Value *Op0, Value *Op1, const BinaryOperator &I,
1086 InstCombiner &IC) {
Andrea Di Biagioa82d52d2016-09-26 12:07:23 +00001087 Value *ShiftLeft;
1088 if (!match(Op1, m_ZExt(m_Value(ShiftLeft))))
1089 ShiftLeft = Op1;
David Majnemer37f8f442013-07-04 21:17:49 +00001090
Simon Pilgrim2a90acd2018-02-08 15:19:38 +00001091 Constant *CI;
Andrea Di Biagioa82d52d2016-09-26 12:07:23 +00001092 Value *N;
Simon Pilgrim2a90acd2018-02-08 15:19:38 +00001093 if (!match(ShiftLeft, m_Shl(m_Constant(CI), m_Value(N))))
Andrea Di Biagioa82d52d2016-09-26 12:07:23 +00001094 llvm_unreachable("match should never fail here!");
Simon Pilgrim2a90acd2018-02-08 15:19:38 +00001095 Constant *Log2Base = getLogBase2(N->getType(), CI);
1096 if (!Log2Base)
1097 llvm_unreachable("getLogBase2 should never fail here!");
1098 N = IC.Builder.CreateAdd(N, Log2Base);
Andrea Di Biagioa82d52d2016-09-26 12:07:23 +00001099 if (Op1 != ShiftLeft)
Craig Topperbb4069e2017-07-07 23:16:26 +00001100 N = IC.Builder.CreateZExt(N, Op1->getType());
David Majnemer37f8f442013-07-04 21:17:49 +00001101 BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, N);
Suyog Sarda65f5ae92014-10-07 12:04:07 +00001102 if (I.isExact())
1103 LShr->setIsExact();
David Majnemer37f8f442013-07-04 21:17:49 +00001104 return LShr;
1105}
1106
1107// \brief Recursively visits the possible right hand operands of a udiv
1108// instruction, seeing through select instructions, to determine if we can
1109// replace the udiv with something simpler. If we find that an operand is not
1110// able to simplify the udiv, we abort the entire transformation.
1111static size_t visitUDivOperand(Value *Op0, Value *Op1, const BinaryOperator &I,
1112 SmallVectorImpl<UDivFoldAction> &Actions,
1113 unsigned Depth = 0) {
1114 // Check to see if this is an unsigned division with an exact power of 2,
1115 // if so, convert to a right shift.
1116 if (match(Op1, m_Power2())) {
1117 Actions.push_back(UDivFoldAction(foldUDivPow2Cst, Op1));
1118 return Actions.size();
1119 }
1120
Simon Pilgrim9620f4b2018-02-09 10:43:59 +00001121 // X udiv C, where C >= signbit
1122 if (match(Op1, m_Negative())) {
1123 Actions.push_back(UDivFoldAction(foldUDivNegCst, Op1));
1124 return Actions.size();
1125 }
David Majnemer37f8f442013-07-04 21:17:49 +00001126
1127 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
1128 if (match(Op1, m_Shl(m_Power2(), m_Value())) ||
1129 match(Op1, m_ZExt(m_Shl(m_Power2(), m_Value())))) {
1130 Actions.push_back(UDivFoldAction(foldUDivShl, Op1));
1131 return Actions.size();
1132 }
1133
1134 // The remaining tests are all recursive, so bail out if we hit the limit.
1135 if (Depth++ == MaxDepth)
1136 return 0;
1137
1138 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
David Majnemer492e6122014-08-30 09:19:05 +00001139 if (size_t LHSIdx =
1140 visitUDivOperand(Op0, SI->getOperand(1), I, Actions, Depth))
1141 if (visitUDivOperand(Op0, SI->getOperand(2), I, Actions, Depth)) {
1142 Actions.push_back(UDivFoldAction(nullptr, Op1, LHSIdx - 1));
David Majnemer37f8f442013-07-04 21:17:49 +00001143 return Actions.size();
1144 }
1145
1146 return 0;
1147}
1148
Sanjay Patelbb789382017-08-24 22:54:01 +00001149/// If we have zero-extended operands of an unsigned div or rem, we may be able
1150/// to narrow the operation (sink the zext below the math).
1151static Instruction *narrowUDivURem(BinaryOperator &I,
1152 InstCombiner::BuilderTy &Builder) {
1153 Instruction::BinaryOps Opcode = I.getOpcode();
1154 Value *N = I.getOperand(0);
1155 Value *D = I.getOperand(1);
1156 Type *Ty = I.getType();
1157 Value *X, *Y;
1158 if (match(N, m_ZExt(m_Value(X))) && match(D, m_ZExt(m_Value(Y))) &&
1159 X->getType() == Y->getType() && (N->hasOneUse() || D->hasOneUse())) {
1160 // udiv (zext X), (zext Y) --> zext (udiv X, Y)
1161 // urem (zext X), (zext Y) --> zext (urem X, Y)
1162 Value *NarrowOp = Builder.CreateBinOp(Opcode, X, Y);
1163 return new ZExtInst(NarrowOp, Ty);
1164 }
1165
1166 Constant *C;
1167 if ((match(N, m_OneUse(m_ZExt(m_Value(X)))) && match(D, m_Constant(C))) ||
1168 (match(D, m_OneUse(m_ZExt(m_Value(X)))) && match(N, m_Constant(C)))) {
1169 // If the constant is the same in the smaller type, use the narrow version.
1170 Constant *TruncC = ConstantExpr::getTrunc(C, X->getType());
1171 if (ConstantExpr::getZExt(TruncC, Ty) != C)
1172 return nullptr;
1173
1174 // udiv (zext X), C --> zext (udiv X, C')
1175 // urem (zext X), C --> zext (urem X, C')
1176 // udiv C, (zext X) --> zext (udiv C', X)
1177 // urem C, (zext X) --> zext (urem C', X)
1178 Value *NarrowOp = isa<Constant>(D) ? Builder.CreateBinOp(Opcode, X, TruncC)
1179 : Builder.CreateBinOp(Opcode, TruncC, X);
1180 return new ZExtInst(NarrowOp, Ty);
1181 }
1182
1183 return nullptr;
1184}
1185
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001186Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
1187 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1188
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001189 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001190 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001191
Craig Toppera4205622017-06-09 03:21:29 +00001192 if (Value *V = SimplifyUDivInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001193 return replaceInstUsesWith(I, V);
Duncan Sands771e82a2011-01-28 16:51:11 +00001194
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001195 // Handle the integer div common cases
1196 if (Instruction *Common = commonIDivTransforms(I))
1197 return Common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001198
Benjamin Kramerd4a64712012-08-30 15:07:40 +00001199 // (x lshr C1) udiv C2 --> x udiv (C2 << C1)
David Majnemera2521382014-10-13 21:48:30 +00001200 {
Benjamin Kramer9c0a8072012-08-28 13:08:13 +00001201 Value *X;
David Majnemera2521382014-10-13 21:48:30 +00001202 const APInt *C1, *C2;
1203 if (match(Op0, m_LShr(m_Value(X), m_APInt(C1))) &&
1204 match(Op1, m_APInt(C2))) {
1205 bool Overflow;
1206 APInt C2ShlC1 = C2->ushl_ov(*C1, Overflow);
David Majnemera3aeb152014-11-22 18:16:54 +00001207 if (!Overflow) {
1208 bool IsExact = I.isExact() && match(Op0, m_Exact(m_Value()));
1209 BinaryOperator *BO = BinaryOperator::CreateUDiv(
David Majnemera2521382014-10-13 21:48:30 +00001210 X, ConstantInt::get(X->getType(), C2ShlC1));
David Majnemera3aeb152014-11-22 18:16:54 +00001211 if (IsExact)
1212 BO->setIsExact();
1213 return BO;
1214 }
David Majnemera2521382014-10-13 21:48:30 +00001215 }
Nadav Rotem11935b22012-08-28 10:01:43 +00001216 }
1217
Sanjay Patelbb789382017-08-24 22:54:01 +00001218 if (Instruction *NarrowDiv = narrowUDivURem(I, Builder))
1219 return NarrowDiv;
Benjamin Kramer9aa91b12011-04-30 18:16:07 +00001220
David Majnemer37f8f442013-07-04 21:17:49 +00001221 // (LHS udiv (select (select (...)))) -> (LHS >> (select (select (...))))
1222 SmallVector<UDivFoldAction, 6> UDivActions;
1223 if (visitUDivOperand(Op0, Op1, I, UDivActions))
1224 for (unsigned i = 0, e = UDivActions.size(); i != e; ++i) {
1225 FoldUDivOperandCb Action = UDivActions[i].FoldAction;
1226 Value *ActionOp1 = UDivActions[i].OperandToFold;
1227 Instruction *Inst;
1228 if (Action)
1229 Inst = Action(Op0, ActionOp1, I, *this);
1230 else {
1231 // This action joins two actions together. The RHS of this action is
1232 // simply the last action we processed, we saved the LHS action index in
1233 // the joining action.
1234 size_t SelectRHSIdx = i - 1;
1235 Value *SelectRHS = UDivActions[SelectRHSIdx].FoldResult;
1236 size_t SelectLHSIdx = UDivActions[i].SelectLHSIdx;
1237 Value *SelectLHS = UDivActions[SelectLHSIdx].FoldResult;
1238 Inst = SelectInst::Create(cast<SelectInst>(ActionOp1)->getCondition(),
1239 SelectLHS, SelectRHS);
1240 }
1241
1242 // If this is the last action to process, return it to the InstCombiner.
1243 // Otherwise, we insert it before the UDiv and record it so that we may
1244 // use it as part of a joining action (i.e., a SelectInst).
1245 if (e - i != 1) {
1246 Inst->insertBefore(&I);
1247 UDivActions[i].FoldResult = Inst;
1248 } else
1249 return Inst;
1250 }
1251
Craig Topperf40110f2014-04-25 05:29:35 +00001252 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001253}
1254
1255Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
1256 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1257
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001258 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001259 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001260
Craig Toppera4205622017-06-09 03:21:29 +00001261 if (Value *V = SimplifySDivInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001262 return replaceInstUsesWith(I, V);
Duncan Sands771e82a2011-01-28 16:51:11 +00001263
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001264 // Handle the integer div common cases
1265 if (Instruction *Common = commonIDivTransforms(I))
1266 return Common;
1267
Sanjay Patelc6ada532016-06-27 17:25:57 +00001268 const APInt *Op1C;
Sanjay Patelbedd1f92016-06-27 18:38:40 +00001269 if (match(Op1, m_APInt(Op1C))) {
1270 // sdiv X, -1 == -X
1271 if (Op1C->isAllOnesValue())
1272 return BinaryOperator::CreateNeg(Op0);
1273
1274 // sdiv exact X, C --> ashr exact X, log2(C)
1275 if (I.isExact() && Op1C->isNonNegative() && Op1C->isPowerOf2()) {
1276 Value *ShAmt = ConstantInt::get(Op1->getType(), Op1C->exactLogBase2());
1277 return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
1278 }
Sanjay Patel59ed2ff2016-06-27 22:27:11 +00001279
1280 // If the dividend is sign-extended and the constant divisor is small enough
1281 // to fit in the source type, shrink the division to the narrower type:
1282 // (sext X) sdiv C --> sext (X sdiv C)
1283 Value *Op0Src;
1284 if (match(Op0, m_OneUse(m_SExt(m_Value(Op0Src)))) &&
1285 Op0Src->getType()->getScalarSizeInBits() >= Op1C->getMinSignedBits()) {
1286
1287 // In the general case, we need to make sure that the dividend is not the
1288 // minimum signed value because dividing that by -1 is UB. But here, we
1289 // know that the -1 divisor case is already handled above.
1290
1291 Constant *NarrowDivisor =
1292 ConstantExpr::getTrunc(cast<Constant>(Op1), Op0Src->getType());
Craig Topperbb4069e2017-07-07 23:16:26 +00001293 Value *NarrowOp = Builder.CreateSDiv(Op0Src, NarrowDivisor);
Sanjay Patel59ed2ff2016-06-27 22:27:11 +00001294 return new SExtInst(NarrowOp, Op0->getType());
1295 }
Benjamin Kramer72196f32014-01-19 15:24:22 +00001296 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001297
Benjamin Kramer72196f32014-01-19 15:24:22 +00001298 if (Constant *RHS = dyn_cast<Constant>(Op1)) {
David Majnemerf28e2a42014-07-02 06:42:13 +00001299 // X/INT_MIN -> X == INT_MIN
1300 if (RHS->isMinSignedValue())
Craig Topperbb4069e2017-07-07 23:16:26 +00001301 return new ZExtInst(Builder.CreateICmpEQ(Op0, Op1), I.getType());
David Majnemerf28e2a42014-07-02 06:42:13 +00001302
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001303 // -X/C --> X/-C provided the negation doesn't overflow.
David Majnemerfa4699e2014-11-22 20:00:34 +00001304 Value *X;
1305 if (match(Op0, m_NSWSub(m_Zero(), m_Value(X)))) {
1306 auto *BO = BinaryOperator::CreateSDiv(X, ConstantExpr::getNeg(RHS));
1307 BO->setIsExact(I.isExact());
1308 return BO;
1309 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001310 }
1311
1312 // If the sign bits of both operands are zero (i.e. we can prove they are
1313 // unsigned inputs), turn this into a udiv.
Craig Topperbcfd2d12017-04-20 16:56:25 +00001314 APInt Mask(APInt::getSignMask(I.getType()->getScalarSizeInBits()));
Craig Topperf2484682017-04-17 01:51:19 +00001315 if (MaskedValueIsZero(Op0, Mask, 0, &I)) {
1316 if (MaskedValueIsZero(Op1, Mask, 0, &I)) {
1317 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
1318 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1319 BO->setIsExact(I.isExact());
1320 return BO;
1321 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001322
Craig Topperd4039f72017-05-25 21:51:12 +00001323 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/ true, 0, &I)) {
Craig Topperf2484682017-04-17 01:51:19 +00001324 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
1325 // Safe because the only negative value (1 << Y) can take on is
1326 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
1327 // the sign bit set.
1328 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1329 BO->setIsExact(I.isExact());
1330 return BO;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001331 }
1332 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001333
Craig Topperf40110f2014-04-25 05:29:35 +00001334 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001335}
1336
Shuxin Yang320f52a2013-01-14 22:48:41 +00001337/// CvtFDivConstToReciprocal tries to convert X/C into X*1/C if C not a special
1338/// FP value and:
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001339/// 1) 1/C is exact, or
Shuxin Yang320f52a2013-01-14 22:48:41 +00001340/// 2) reciprocal is allowed.
Sylvestre Ledru149e2812013-05-14 23:36:24 +00001341/// If the conversion was successful, the simplified expression "X * 1/C" is
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00001342/// returned; otherwise, nullptr is returned.
Suyog Sardaea205512014-10-07 11:56:06 +00001343static Instruction *CvtFDivConstToReciprocal(Value *Dividend, Constant *Divisor,
Shuxin Yang320f52a2013-01-14 22:48:41 +00001344 bool AllowReciprocal) {
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001345 if (!isa<ConstantFP>(Divisor)) // TODO: handle vectors.
Craig Topperf40110f2014-04-25 05:29:35 +00001346 return nullptr;
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001347
1348 const APFloat &FpVal = cast<ConstantFP>(Divisor)->getValueAPF();
Shuxin Yang320f52a2013-01-14 22:48:41 +00001349 APFloat Reciprocal(FpVal.getSemantics());
1350 bool Cvt = FpVal.getExactInverse(&Reciprocal);
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001351
Michael Gottesman3cb77ab2013-06-19 21:23:18 +00001352 if (!Cvt && AllowReciprocal && FpVal.isFiniteNonZero()) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001353 Reciprocal = APFloat(FpVal.getSemantics(), 1.0f);
1354 (void)Reciprocal.divide(FpVal, APFloat::rmNearestTiesToEven);
1355 Cvt = !Reciprocal.isDenormal();
1356 }
1357
1358 if (!Cvt)
Craig Topperf40110f2014-04-25 05:29:35 +00001359 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001360
1361 ConstantFP *R;
1362 R = ConstantFP::get(Dividend->getType()->getContext(), Reciprocal);
1363 return BinaryOperator::CreateFMul(Dividend, R);
1364}
1365
Frits van Bommel2a559512011-01-29 17:50:27 +00001366Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
1367 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1368
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001369 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001370 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001371
Craig Toppera4205622017-06-09 03:21:29 +00001372 if (Value *V = SimplifyFDivInst(Op0, Op1, I.getFastMathFlags(),
1373 SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001374 return replaceInstUsesWith(I, V);
Frits van Bommel2a559512011-01-29 17:50:27 +00001375
Stephen Lina9b57f62013-07-20 07:13:13 +00001376 if (isa<Constant>(Op0))
1377 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1378 if (Instruction *R = FoldOpIntoSelect(I, SI))
1379 return R;
1380
Sanjay Patel629c4112017-11-06 16:27:15 +00001381 bool AllowReassociate = I.isFast();
Shuxin Yang320f52a2013-01-14 22:48:41 +00001382 bool AllowReciprocal = I.hasAllowReciprocal();
Benjamin Kramer8564e0d2011-03-30 15:42:35 +00001383
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001384 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Stephen Lina9b57f62013-07-20 07:13:13 +00001385 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1386 if (Instruction *R = FoldOpIntoSelect(I, SI))
1387 return R;
1388
Shuxin Yang320f52a2013-01-14 22:48:41 +00001389 if (AllowReassociate) {
Craig Topperf40110f2014-04-25 05:29:35 +00001390 Constant *C1 = nullptr;
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001391 Constant *C2 = Op1C;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001392 Value *X;
Craig Topperf40110f2014-04-25 05:29:35 +00001393 Instruction *Res = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001394
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001395 if (match(Op0, m_FMul(m_Value(X), m_Constant(C1)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001396 // (X*C1)/C2 => X * (C1/C2)
1397 //
1398 Constant *C = ConstantExpr::getFDiv(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001399 if (isNormalFp(C))
Shuxin Yang320f52a2013-01-14 22:48:41 +00001400 Res = BinaryOperator::CreateFMul(X, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001401 } else if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001402 // (X/C1)/C2 => X /(C2*C1) [=> X * 1/(C2*C1) if reciprocal is allowed]
Shuxin Yang320f52a2013-01-14 22:48:41 +00001403 Constant *C = ConstantExpr::getFMul(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001404 if (isNormalFp(C)) {
1405 Res = CvtFDivConstToReciprocal(X, C, AllowReciprocal);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001406 if (!Res)
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001407 Res = BinaryOperator::CreateFDiv(X, C);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001408 }
1409 }
1410
1411 if (Res) {
1412 Res->setFastMathFlags(I.getFastMathFlags());
1413 return Res;
1414 }
1415 }
1416
1417 // X / C => X * 1/C
Owen Anderson4557a152014-01-16 21:07:52 +00001418 if (Instruction *T = CvtFDivConstToReciprocal(Op0, Op1C, AllowReciprocal)) {
1419 T->copyFastMathFlags(&I);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001420 return T;
Owen Anderson4557a152014-01-16 21:07:52 +00001421 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001422
Craig Topperf40110f2014-04-25 05:29:35 +00001423 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001424 }
1425
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001426 if (AllowReassociate && isa<Constant>(Op0)) {
1427 Constant *C1 = cast<Constant>(Op0), *C2;
Craig Topperf40110f2014-04-25 05:29:35 +00001428 Constant *Fold = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001429 Value *X;
1430 bool CreateDiv = true;
1431
1432 // C1 / (X*C2) => (C1/C2) / X
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001433 if (match(Op1, m_FMul(m_Value(X), m_Constant(C2))))
Shuxin Yang320f52a2013-01-14 22:48:41 +00001434 Fold = ConstantExpr::getFDiv(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001435 else if (match(Op1, m_FDiv(m_Value(X), m_Constant(C2)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001436 // C1 / (X/C2) => (C1*C2) / X
1437 Fold = ConstantExpr::getFMul(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001438 } else if (match(Op1, m_FDiv(m_Constant(C2), m_Value(X)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001439 // C1 / (C2/X) => (C1/C2) * X
1440 Fold = ConstantExpr::getFDiv(C1, C2);
1441 CreateDiv = false;
1442 }
1443
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001444 if (Fold && isNormalFp(Fold)) {
1445 Instruction *R = CreateDiv ? BinaryOperator::CreateFDiv(Fold, X)
1446 : BinaryOperator::CreateFMul(X, Fold);
1447 R->setFastMathFlags(I.getFastMathFlags());
1448 return R;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001449 }
Craig Topperf40110f2014-04-25 05:29:35 +00001450 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001451 }
1452
1453 if (AllowReassociate) {
1454 Value *X, *Y;
Craig Topperf40110f2014-04-25 05:29:35 +00001455 Value *NewInst = nullptr;
1456 Instruction *SimpR = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001457
1458 if (Op0->hasOneUse() && match(Op0, m_FDiv(m_Value(X), m_Value(Y)))) {
1459 // (X/Y) / Z => X / (Y*Z)
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001460 if (!isa<Constant>(Y) || !isa<Constant>(Op1)) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001461 NewInst = Builder.CreateFMul(Y, Op1);
Owen Anderson1664dc82014-01-20 07:44:53 +00001462 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1463 FastMathFlags Flags = I.getFastMathFlags();
1464 Flags &= cast<Instruction>(Op0)->getFastMathFlags();
1465 RI->setFastMathFlags(Flags);
1466 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001467 SimpR = BinaryOperator::CreateFDiv(X, NewInst);
1468 }
1469 } else if (Op1->hasOneUse() && match(Op1, m_FDiv(m_Value(X), m_Value(Y)))) {
1470 // Z / (X/Y) => Z*Y / X
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001471 if (!isa<Constant>(Y) || !isa<Constant>(Op0)) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001472 NewInst = Builder.CreateFMul(Op0, Y);
Owen Anderson1664dc82014-01-20 07:44:53 +00001473 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1474 FastMathFlags Flags = I.getFastMathFlags();
1475 Flags &= cast<Instruction>(Op1)->getFastMathFlags();
1476 RI->setFastMathFlags(Flags);
1477 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001478 SimpR = BinaryOperator::CreateFDiv(NewInst, X);
1479 }
1480 }
1481
1482 if (NewInst) {
1483 if (Instruction *T = dyn_cast<Instruction>(NewInst))
1484 T->setDebugLoc(I.getDebugLoc());
1485 SimpR->setFastMathFlags(I.getFastMathFlags());
1486 return SimpR;
Benjamin Kramer8564e0d2011-03-30 15:42:35 +00001487 }
1488 }
1489
Dmitry Venikove5fbf592018-01-11 06:33:00 +00001490 if (AllowReassociate &&
1491 Op0->hasOneUse() && Op1->hasOneUse()) {
1492 Value *A;
1493 // sin(a) / cos(a) -> tan(a)
1494 if (match(Op0, m_Intrinsic<Intrinsic::sin>(m_Value(A))) &&
1495 match(Op1, m_Intrinsic<Intrinsic::cos>(m_Specific(A)))) {
1496 if (hasUnaryFloatFn(&TLI, I.getType(), LibFunc_tan,
1497 LibFunc_tanf, LibFunc_tanl)) {
1498 IRBuilder<> B(&I);
1499 IRBuilder<>::FastMathFlagGuard Guard(B);
1500 B.setFastMathFlags(I.getFastMathFlags());
Benjamin Kramer738e6e72018-01-11 15:33:21 +00001501 Value *Tan = emitUnaryFloatFnCall(
1502 A, TLI.getName(LibFunc_tan), B,
1503 CallSite(Op0).getCalledFunction()->getAttributes());
Dmitry Venikove5fbf592018-01-11 06:33:00 +00001504 return replaceInstUsesWith(I, Tan);
1505 }
1506 }
1507
1508 // cos(a) / sin(a) -> 1/tan(a)
1509 if (match(Op0, m_Intrinsic<Intrinsic::cos>(m_Value(A))) &&
1510 match(Op1, m_Intrinsic<Intrinsic::sin>(m_Specific(A)))) {
1511 if (hasUnaryFloatFn(&TLI, I.getType(), LibFunc_tan,
1512 LibFunc_tanf, LibFunc_tanl)) {
1513 IRBuilder<> B(&I);
1514 IRBuilder<>::FastMathFlagGuard Guard(B);
1515 B.setFastMathFlags(I.getFastMathFlags());
Benjamin Kramer44993ed2018-01-11 15:19:02 +00001516 Value *Tan = emitUnaryFloatFnCall(
1517 A, TLI.getName(LibFunc_tan), B,
1518 CallSite(Op0).getCalledFunction()->getAttributes());
Dmitry Venikove5fbf592018-01-11 06:33:00 +00001519 Value *One = ConstantFP::get(Tan->getType(), 1.0);
1520 Value *Div = B.CreateFDiv(One, Tan);
1521 return replaceInstUsesWith(I, Div);
1522 }
1523 }
1524 }
1525
Sanjay Patel1998cc62018-02-12 18:38:35 +00001526 // -X / -Y -> X / Y
1527 Value *X, *Y;
1528 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y)))) {
1529 I.setOperand(0, X);
1530 I.setOperand(1, Y);
Matt Arsenaultfdb78f82017-01-10 23:08:54 +00001531 return &I;
1532 }
1533
Sanjay Patel4a4f35f2018-02-12 19:39:21 +00001534 // X / (X * Y) --> 1.0 / Y
1535 // Reassociate to (X / X -> 1.0) is legal when NaNs are not allowed.
1536 // We can ignore the possibility that X is infinity because INF/INF is NaN.
1537 if (I.hasNoNaNs() && I.hasAllowReassoc() &&
1538 match(Op1, m_c_FMul(m_Specific(Op0), m_Value(Y)))) {
1539 I.setOperand(0, ConstantFP::get(I.getType(), 1.0));
1540 I.setOperand(1, Y);
1541 return &I;
1542 }
1543
Craig Topperf40110f2014-04-25 05:29:35 +00001544 return nullptr;
Frits van Bommel2a559512011-01-29 17:50:27 +00001545}
1546
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001547/// This function implements the transforms common to both integer remainder
1548/// instructions (urem and srem). It is called by the visitors to those integer
1549/// remainder instructions.
1550/// @brief Common integer remainder transforms
1551Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
1552 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1553
Chris Lattner7c99f192011-05-22 18:18:41 +00001554 // The RHS is known non-zero.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001555 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I)) {
Chris Lattner7c99f192011-05-22 18:18:41 +00001556 I.setOperand(1, V);
1557 return &I;
1558 }
1559
Duncan Sandsa3e36992011-05-02 16:27:02 +00001560 // Handle cases involving: rem X, (select Cond, Y, Z)
Sanjay Patelae2e3a42017-10-06 23:20:16 +00001561 if (simplifyDivRemOfSelectWithZeroOp(I))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001562 return &I;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001563
Benjamin Kramer72196f32014-01-19 15:24:22 +00001564 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001565 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1566 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1567 if (Instruction *R = FoldOpIntoSelect(I, SI))
1568 return R;
Craig Topperfb71b7d2017-04-14 19:20:12 +00001569 } else if (auto *PN = dyn_cast<PHINode>(Op0I)) {
Sanjoy Dasb7e861a2016-06-05 21:17:04 +00001570 const APInt *Op1Int;
1571 if (match(Op1, m_APInt(Op1Int)) && !Op1Int->isMinValue() &&
1572 (I.getOpcode() == Instruction::URem ||
1573 !Op1Int->isMinSignedValue())) {
Craig Topperfb71b7d2017-04-14 19:20:12 +00001574 // foldOpIntoPhi will speculate instructions to the end of the PHI's
Sanjoy Dasb7e861a2016-06-05 21:17:04 +00001575 // predecessor blocks, so do this only if we know the srem or urem
1576 // will not fault.
Craig Topperfb71b7d2017-04-14 19:20:12 +00001577 if (Instruction *NV = foldOpIntoPhi(I, PN))
Sanjoy Dasb7e861a2016-06-05 21:17:04 +00001578 return NV;
1579 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001580 }
1581
1582 // See if we can fold away this rem instruction.
1583 if (SimplifyDemandedInstructionBits(I))
1584 return &I;
1585 }
1586 }
1587
Craig Topperf40110f2014-04-25 05:29:35 +00001588 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001589}
1590
1591Instruction *InstCombiner::visitURem(BinaryOperator &I) {
1592 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1593
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001594 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001595 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001596
Craig Toppera4205622017-06-09 03:21:29 +00001597 if (Value *V = SimplifyURemInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001598 return replaceInstUsesWith(I, V);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001599
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001600 if (Instruction *common = commonIRemTransforms(I))
1601 return common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001602
Sanjay Patelbb789382017-08-24 22:54:01 +00001603 if (Instruction *NarrowRem = narrowUDivURem(I, Builder))
1604 return NarrowRem;
David Majnemer6c30f492013-05-12 00:07:05 +00001605
David Majnemer470b0772013-05-11 09:01:28 +00001606 // X urem Y -> X and Y-1, where Y is a power of 2,
Craig Topperd4039f72017-05-25 21:51:12 +00001607 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/ true, 0, &I)) {
Chris Lattner6b657ae2011-02-10 05:36:31 +00001608 Constant *N1 = Constant::getAllOnesValue(I.getType());
Craig Topperbb4069e2017-07-07 23:16:26 +00001609 Value *Add = Builder.CreateAdd(Op1, N1);
Chris Lattner6b657ae2011-02-10 05:36:31 +00001610 return BinaryOperator::CreateAnd(Op0, Add);
1611 }
1612
Nick Lewycky7459be62013-07-13 01:16:47 +00001613 // 1 urem X -> zext(X != 1)
1614 if (match(Op0, m_One())) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001615 Value *Cmp = Builder.CreateICmpNE(Op1, Op0);
1616 Value *Ext = Builder.CreateZExt(Cmp, I.getType());
Sanjay Patel4b198802016-02-01 22:23:39 +00001617 return replaceInstUsesWith(I, Ext);
Nick Lewycky7459be62013-07-13 01:16:47 +00001618 }
1619
Sanjay Patel30ef70b2016-09-22 22:36:26 +00001620 // X urem C -> X < C ? X : X - C, where C >= signbit.
Simon Pilgrim1889f262018-02-08 18:36:01 +00001621 if (match(Op1, m_Negative())) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001622 Value *Cmp = Builder.CreateICmpULT(Op0, Op1);
1623 Value *Sub = Builder.CreateSub(Op0, Op1);
Sanjay Patel30ef70b2016-09-22 22:36:26 +00001624 return SelectInst::Create(Cmp, Op0, Sub);
1625 }
1626
Craig Topperf40110f2014-04-25 05:29:35 +00001627 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001628}
1629
1630Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
1631 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1632
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001633 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001634 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001635
Craig Toppera4205622017-06-09 03:21:29 +00001636 if (Value *V = SimplifySRemInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001637 return replaceInstUsesWith(I, V);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001638
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001639 // Handle the integer rem common cases
1640 if (Instruction *Common = commonIRemTransforms(I))
1641 return Common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001642
David Majnemerdb077302014-10-13 22:37:51 +00001643 {
1644 const APInt *Y;
1645 // X % -Y -> X % Y
Simon Pilgrima54e8e42018-02-08 19:00:45 +00001646 if (match(Op1, m_Negative(Y)) && !Y->isMinSignedValue()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001647 Worklist.AddValue(I.getOperand(1));
David Majnemerdb077302014-10-13 22:37:51 +00001648 I.setOperand(1, ConstantInt::get(I.getType(), -*Y));
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001649 return &I;
1650 }
David Majnemerdb077302014-10-13 22:37:51 +00001651 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001652
1653 // If the sign bits of both operands are zero (i.e. we can prove they are
1654 // unsigned inputs), turn this into a urem.
Craig Topperbcfd2d12017-04-20 16:56:25 +00001655 APInt Mask(APInt::getSignMask(I.getType()->getScalarSizeInBits()));
Craig Topper1a18a7c2017-04-17 01:51:24 +00001656 if (MaskedValueIsZero(Op1, Mask, 0, &I) &&
1657 MaskedValueIsZero(Op0, Mask, 0, &I)) {
1658 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
1659 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001660 }
1661
1662 // If it's a constant vector, flip any negative values positive.
Chris Lattner0256be92012-01-27 03:08:05 +00001663 if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
1664 Constant *C = cast<Constant>(Op1);
1665 unsigned VWidth = C->getType()->getVectorNumElements();
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001666
1667 bool hasNegative = false;
Chris Lattner0256be92012-01-27 03:08:05 +00001668 bool hasMissing = false;
1669 for (unsigned i = 0; i != VWidth; ++i) {
1670 Constant *Elt = C->getAggregateElement(i);
Craig Topperf40110f2014-04-25 05:29:35 +00001671 if (!Elt) {
Chris Lattner0256be92012-01-27 03:08:05 +00001672 hasMissing = true;
1673 break;
1674 }
1675
1676 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
Chris Lattnerb1a15122011-07-15 06:08:15 +00001677 if (RHS->isNegative())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001678 hasNegative = true;
Chris Lattner0256be92012-01-27 03:08:05 +00001679 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001680
Chris Lattner0256be92012-01-27 03:08:05 +00001681 if (hasNegative && !hasMissing) {
Chris Lattner47a86bd2012-01-25 06:02:56 +00001682 SmallVector<Constant *, 16> Elts(VWidth);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001683 for (unsigned i = 0; i != VWidth; ++i) {
Chris Lattner8213c8a2012-02-06 21:56:39 +00001684 Elts[i] = C->getAggregateElement(i); // Handle undef, etc.
Chris Lattner0256be92012-01-27 03:08:05 +00001685 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
Chris Lattnerb1a15122011-07-15 06:08:15 +00001686 if (RHS->isNegative())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001687 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001688 }
1689 }
1690
1691 Constant *NewRHSV = ConstantVector::get(Elts);
Chris Lattner0256be92012-01-27 03:08:05 +00001692 if (NewRHSV != C) { // Don't loop on -MININT
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001693 Worklist.AddValue(I.getOperand(1));
1694 I.setOperand(1, NewRHSV);
1695 return &I;
1696 }
1697 }
1698 }
1699
Craig Topperf40110f2014-04-25 05:29:35 +00001700 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001701}
1702
1703Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Duncan Sandsa3e36992011-05-02 16:27:02 +00001704 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001705
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001706 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001707 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001708
Craig Toppera4205622017-06-09 03:21:29 +00001709 if (Value *V = SimplifyFRemInst(Op0, Op1, I.getFastMathFlags(),
1710 SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001711 return replaceInstUsesWith(I, V);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001712
Craig Topperf40110f2014-04-25 05:29:35 +00001713 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001714}