blob: cccde0cc81c61d52f2ca27c8260f176c0c90168e [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
Sanjay Patel604cb9e2018-02-14 16:50:55 +0000273 // -X * C --> X * -C
274 Value *X, *Y;
275 Constant *Op1C;
276 if (match(Op0, m_Neg(m_Value(X))) && match(Op1, m_Constant(Op1C)))
277 return BinaryOperator::CreateMul(X, ConstantExpr::getNeg(Op1C));
278
279 // -X * -Y --> X * Y
280 if (match(Op0, m_Neg(m_Value(X))) && match(Op1, m_Neg(m_Value(Y)))) {
281 auto *NewMul = BinaryOperator::CreateMul(X, Y);
282 if (I.hasNoSignedWrap() &&
283 cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap() &&
284 cast<OverflowingBinaryOperator>(Op1)->hasNoSignedWrap())
285 NewMul->setHasNoSignedWrap();
286 return NewMul;
David Majnemer8279a7502014-11-22 07:25:19 +0000287 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000288
289 // (X / Y) * Y = X - (X % Y)
290 // (X / Y) * -Y = (X % Y) - X
291 {
Sanjay Patela0a56822017-03-14 17:27:27 +0000292 Value *Y = Op1;
293 BinaryOperator *Div = dyn_cast<BinaryOperator>(Op0);
294 if (!Div || (Div->getOpcode() != Instruction::UDiv &&
295 Div->getOpcode() != Instruction::SDiv)) {
296 Y = Op0;
297 Div = dyn_cast<BinaryOperator>(Op1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000298 }
Sanjay Patela0a56822017-03-14 17:27:27 +0000299 Value *Neg = dyn_castNegVal(Y);
300 if (Div && Div->hasOneUse() &&
301 (Div->getOperand(1) == Y || Div->getOperand(1) == Neg) &&
302 (Div->getOpcode() == Instruction::UDiv ||
303 Div->getOpcode() == Instruction::SDiv)) {
304 Value *X = Div->getOperand(0), *DivOp1 = Div->getOperand(1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000305
Chris Lattner35315d02011-02-06 21:44:57 +0000306 // If the division is exact, X % Y is zero, so we end up with X or -X.
Sanjay Patela0a56822017-03-14 17:27:27 +0000307 if (Div->isExact()) {
308 if (DivOp1 == Y)
309 return replaceInstUsesWith(I, X);
310 return BinaryOperator::CreateNeg(X);
311 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000312
Sanjay Patela0a56822017-03-14 17:27:27 +0000313 auto RemOpc = Div->getOpcode() == Instruction::UDiv ? Instruction::URem
314 : Instruction::SRem;
Craig Topperbb4069e2017-07-07 23:16:26 +0000315 Value *Rem = Builder.CreateBinOp(RemOpc, X, DivOp1);
Sanjay Patela0a56822017-03-14 17:27:27 +0000316 if (DivOp1 == Y)
317 return BinaryOperator::CreateSub(X, Rem);
318 return BinaryOperator::CreateSub(Rem, X);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000319 }
320 }
321
322 /// i1 mul -> i1 and.
Craig Topperfde47232017-07-09 07:04:03 +0000323 if (I.getType()->isIntOrIntVectorTy(1))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000324 return BinaryOperator::CreateAnd(Op0, Op1);
325
326 // X*(1 << Y) --> X << Y
327 // (1 << Y)*X --> X << Y
328 {
329 Value *Y;
David Majnemer546f8102014-11-22 08:57:02 +0000330 BinaryOperator *BO = nullptr;
331 bool ShlNSW = false;
332 if (match(Op0, m_Shl(m_One(), m_Value(Y)))) {
333 BO = BinaryOperator::CreateShl(Op1, Y);
David Majnemer087dc8b2015-01-04 07:36:02 +0000334 ShlNSW = cast<ShlOperator>(Op0)->hasNoSignedWrap();
David Majnemer8e6f6a92014-11-24 16:41:13 +0000335 } else if (match(Op1, m_Shl(m_One(), m_Value(Y)))) {
David Majnemer546f8102014-11-22 08:57:02 +0000336 BO = BinaryOperator::CreateShl(Op0, Y);
David Majnemer087dc8b2015-01-04 07:36:02 +0000337 ShlNSW = cast<ShlOperator>(Op1)->hasNoSignedWrap();
David Majnemer546f8102014-11-22 08:57:02 +0000338 }
339 if (BO) {
340 if (I.hasNoUnsignedWrap())
341 BO->setHasNoUnsignedWrap();
342 if (I.hasNoSignedWrap() && ShlNSW)
343 BO->setHasNoSignedWrap();
344 return BO;
345 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000346 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000347
Sanjay Patelcb8ac002018-02-13 20:41:22 +0000348 // (bool X) * Y --> X ? Y : 0
Sanjay Patel7558d862018-02-13 22:24:37 +0000349 // Y * (bool X) --> X ? Y : 0
Sanjay Patelcb8ac002018-02-13 20:41:22 +0000350 if (match(Op0, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
351 return SelectInst::Create(X, Op1, ConstantInt::get(I.getType(), 0));
Sanjay Patelcb8ac002018-02-13 20:41:22 +0000352 if (match(Op1, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
353 return SelectInst::Create(X, Op0, ConstantInt::get(I.getType(), 0));
354
Sanjay Patel7558d862018-02-13 22:24:37 +0000355 // (lshr X, 31) * Y --> (ashr X, 31) & Y
356 // Y * (lshr X, 31) --> (ashr X, 31) & Y
357 // TODO: We are not checking one-use because the elimination of the multiply
358 // is better for analysis?
359 // TODO: Should we canonicalize to '(X < 0) ? Y : 0' instead? That would be
360 // more similar to what we're doing above.
361 const APInt *C;
362 if (match(Op0, m_LShr(m_Value(X), m_APInt(C))) && *C == C->getBitWidth() - 1)
363 return BinaryOperator::CreateAnd(Builder.CreateAShr(X, *C), Op1);
364 if (match(Op1, m_LShr(m_Value(X), m_APInt(C))) && *C == C->getBitWidth() - 1)
365 return BinaryOperator::CreateAnd(Builder.CreateAShr(X, *C), Op0);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000366
David Majnemera1cfd7c2016-12-30 00:28:58 +0000367 // Check for (mul (sext x), y), see if we can merge this into an
368 // integer mul followed by a sext.
369 if (SExtInst *Op0Conv = dyn_cast<SExtInst>(Op0)) {
370 // (mul (sext x), cst) --> (sext (mul x, cst'))
371 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
372 if (Op0Conv->hasOneUse()) {
373 Constant *CI =
374 ConstantExpr::getTrunc(Op1C, Op0Conv->getOperand(0)->getType());
375 if (ConstantExpr::getSExt(CI, I.getType()) == Op1C &&
Craig Topper2b1fc322017-05-22 06:25:31 +0000376 willNotOverflowSignedMul(Op0Conv->getOperand(0), CI, I)) {
David Majnemera1cfd7c2016-12-30 00:28:58 +0000377 // Insert the new, smaller mul.
378 Value *NewMul =
Craig Topperbb4069e2017-07-07 23:16:26 +0000379 Builder.CreateNSWMul(Op0Conv->getOperand(0), CI, "mulconv");
David Majnemera1cfd7c2016-12-30 00:28:58 +0000380 return new SExtInst(NewMul, I.getType());
381 }
382 }
383 }
384
385 // (mul (sext x), (sext y)) --> (sext (mul int x, y))
386 if (SExtInst *Op1Conv = dyn_cast<SExtInst>(Op1)) {
387 // Only do this if x/y have the same type, if at last one of them has a
388 // single use (so we don't increase the number of sexts), and if the
389 // integer mul will not overflow.
390 if (Op0Conv->getOperand(0)->getType() ==
391 Op1Conv->getOperand(0)->getType() &&
392 (Op0Conv->hasOneUse() || Op1Conv->hasOneUse()) &&
Craig Topper2b1fc322017-05-22 06:25:31 +0000393 willNotOverflowSignedMul(Op0Conv->getOperand(0),
David Majnemera1cfd7c2016-12-30 00:28:58 +0000394 Op1Conv->getOperand(0), I)) {
395 // Insert the new integer mul.
Craig Topperbb4069e2017-07-07 23:16:26 +0000396 Value *NewMul = Builder.CreateNSWMul(
David Majnemera1cfd7c2016-12-30 00:28:58 +0000397 Op0Conv->getOperand(0), Op1Conv->getOperand(0), "mulconv");
398 return new SExtInst(NewMul, I.getType());
399 }
400 }
401 }
402
403 // Check for (mul (zext x), y), see if we can merge this into an
404 // integer mul followed by a zext.
405 if (auto *Op0Conv = dyn_cast<ZExtInst>(Op0)) {
406 // (mul (zext x), cst) --> (zext (mul x, cst'))
407 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
408 if (Op0Conv->hasOneUse()) {
409 Constant *CI =
410 ConstantExpr::getTrunc(Op1C, Op0Conv->getOperand(0)->getType());
411 if (ConstantExpr::getZExt(CI, I.getType()) == Op1C &&
Craig Topperbb973722017-05-15 02:44:08 +0000412 willNotOverflowUnsignedMul(Op0Conv->getOperand(0), CI, I)) {
David Majnemera1cfd7c2016-12-30 00:28:58 +0000413 // Insert the new, smaller mul.
414 Value *NewMul =
Craig Topperbb4069e2017-07-07 23:16:26 +0000415 Builder.CreateNUWMul(Op0Conv->getOperand(0), CI, "mulconv");
David Majnemera1cfd7c2016-12-30 00:28:58 +0000416 return new ZExtInst(NewMul, I.getType());
417 }
418 }
419 }
420
421 // (mul (zext x), (zext y)) --> (zext (mul int x, y))
422 if (auto *Op1Conv = dyn_cast<ZExtInst>(Op1)) {
423 // Only do this if x/y have the same type, if at last one of them has a
424 // single use (so we don't increase the number of zexts), and if the
425 // integer mul will not overflow.
426 if (Op0Conv->getOperand(0)->getType() ==
427 Op1Conv->getOperand(0)->getType() &&
428 (Op0Conv->hasOneUse() || Op1Conv->hasOneUse()) &&
Craig Topperbb973722017-05-15 02:44:08 +0000429 willNotOverflowUnsignedMul(Op0Conv->getOperand(0),
430 Op1Conv->getOperand(0), I)) {
David Majnemera1cfd7c2016-12-30 00:28:58 +0000431 // Insert the new integer mul.
Craig Topperbb4069e2017-07-07 23:16:26 +0000432 Value *NewMul = Builder.CreateNUWMul(
David Majnemera1cfd7c2016-12-30 00:28:58 +0000433 Op0Conv->getOperand(0), Op1Conv->getOperand(0), "mulconv");
434 return new ZExtInst(NewMul, I.getType());
435 }
436 }
437 }
438
Craig Topper2b1fc322017-05-22 06:25:31 +0000439 if (!I.hasNoSignedWrap() && willNotOverflowSignedMul(Op0, Op1, I)) {
David Majnemer54c2ca22014-12-26 09:10:14 +0000440 Changed = true;
441 I.setHasNoSignedWrap(true);
442 }
443
Craig Topperbb973722017-05-15 02:44:08 +0000444 if (!I.hasNoUnsignedWrap() && willNotOverflowUnsignedMul(Op0, Op1, I)) {
David Majnemerb1296ec2014-12-26 09:50:35 +0000445 Changed = true;
446 I.setHasNoUnsignedWrap(true);
447 }
448
Craig Topperf40110f2014-04-25 05:29:35 +0000449 return Changed ? &I : nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000450}
451
Sanjay Patel17045f72014-10-14 00:33:23 +0000452/// Detect pattern log2(Y * 0.5) with corresponding fast math flags.
Pedro Artigas993acd02012-11-30 22:07:05 +0000453static void detectLog2OfHalf(Value *&Op, Value *&Y, IntrinsicInst *&Log2) {
Sanjay Patel17045f72014-10-14 00:33:23 +0000454 if (!Op->hasOneUse())
455 return;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000456
Sanjay Patel17045f72014-10-14 00:33:23 +0000457 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op);
458 if (!II)
459 return;
Sanjay Patel629c4112017-11-06 16:27:15 +0000460 if (II->getIntrinsicID() != Intrinsic::log2 || !II->isFast())
Sanjay Patel17045f72014-10-14 00:33:23 +0000461 return;
462 Log2 = II;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000463
Sanjay Patel17045f72014-10-14 00:33:23 +0000464 Value *OpLog2Of = II->getArgOperand(0);
465 if (!OpLog2Of->hasOneUse())
466 return;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000467
Sanjay Patel17045f72014-10-14 00:33:23 +0000468 Instruction *I = dyn_cast<Instruction>(OpLog2Of);
469 if (!I)
470 return;
Sanjay Patel629c4112017-11-06 16:27:15 +0000471
472 if (I->getOpcode() != Instruction::FMul || !I->isFast())
Sanjay Patel17045f72014-10-14 00:33:23 +0000473 return;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000474
Sanjay Patel17045f72014-10-14 00:33:23 +0000475 if (match(I->getOperand(0), m_SpecificFP(0.5)))
476 Y = I->getOperand(1);
477 else if (match(I->getOperand(1), m_SpecificFP(0.5)))
478 Y = I->getOperand(0);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000479}
Pedro Artigas993acd02012-11-30 22:07:05 +0000480
Sanjay Patel5df4d882018-02-14 17:16:33 +0000481/// Helper function of InstCombiner::visitFMul(). Return true iff the given
482/// value is FMul or FDiv with one and only one operand being a finite-non-zero
483/// constant (i.e. not Zero/NaN/Infinity).
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000484static bool isFMulOrFDivWithConstant(Value *V) {
Sanjay Patel5df4d882018-02-14 17:16:33 +0000485 Constant *C;
486 return (match(V, m_FMul(m_Value(), m_Constant(C))) ||
487 match(V, m_FDiv(m_Value(), m_Constant(C))) ||
Sanjay Patel08868e4942018-02-16 22:32:54 +0000488 match(V, m_FDiv(m_Constant(C), m_Value()))) && C->isFiniteNonZeroFP();
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000489}
490
491/// foldFMulConst() is a helper routine of InstCombiner::visitFMul().
492/// The input \p FMulOrDiv is a FMul/FDiv with one and only one operand
493/// being a constant (i.e. isFMulOrFDivWithConstant(FMulOrDiv) == true).
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000494/// This function is to simplify "FMulOrDiv * C" and returns the
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000495/// resulting expression. Note that this function could return NULL in
496/// case the constants cannot be folded into a normal floating-point.
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000497Value *InstCombiner::foldFMulConst(Instruction *FMulOrDiv, Constant *C,
Shuxin Yang80138662013-01-07 22:41:28 +0000498 Instruction *InsertBefore) {
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000499 assert(isFMulOrFDivWithConstant(FMulOrDiv) && "V is invalid");
500
501 Value *Opnd0 = FMulOrDiv->getOperand(0);
502 Value *Opnd1 = FMulOrDiv->getOperand(1);
503
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000504 Constant *C0 = dyn_cast<Constant>(Opnd0);
505 Constant *C1 = dyn_cast<Constant>(Opnd1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000506
Craig Topperf40110f2014-04-25 05:29:35 +0000507 BinaryOperator *R = nullptr;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000508
509 // (X * C0) * C => X * (C0*C)
510 if (FMulOrDiv->getOpcode() == Instruction::FMul) {
511 Constant *F = ConstantExpr::getFMul(C1 ? C1 : C0, C);
Sanjay Patel08868e4942018-02-16 22:32:54 +0000512 if (F->isNormalFP())
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000513 R = BinaryOperator::CreateFMul(C1 ? Opnd0 : Opnd1, F);
514 } else {
515 if (C0) {
516 // (C0 / X) * C => (C0 * C) / X
Shuxin Yang3a7ca6e2013-09-19 21:13:46 +0000517 if (FMulOrDiv->hasOneUse()) {
518 // It would otherwise introduce another div.
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000519 Constant *F = ConstantExpr::getFMul(C0, C);
Sanjay Patel08868e4942018-02-16 22:32:54 +0000520 if (F->isNormalFP())
Shuxin Yang3a7ca6e2013-09-19 21:13:46 +0000521 R = BinaryOperator::CreateFDiv(F, Opnd1);
522 }
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000523 } else {
524 // (X / C1) * C => X * (C/C1) if C/C1 is not a denormal
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000525 Constant *F = ConstantExpr::getFDiv(C, C1);
Sanjay Patel08868e4942018-02-16 22:32:54 +0000526 if (F->isNormalFP()) {
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000527 R = BinaryOperator::CreateFMul(Opnd0, F);
528 } else {
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000529 // (X / C1) * C => X / (C1/C)
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000530 Constant *F = ConstantExpr::getFDiv(C1, C);
Sanjay Patel08868e4942018-02-16 22:32:54 +0000531 if (F->isNormalFP())
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000532 R = BinaryOperator::CreateFDiv(Opnd0, F);
533 }
534 }
535 }
536
537 if (R) {
Sanjay Patel629c4112017-11-06 16:27:15 +0000538 R->setFast(true);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000539 InsertNewInstWith(R, *InsertBefore);
540 }
541
542 return R;
543}
544
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000545Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +0000546 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000547 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
548
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000549 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +0000550 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000551
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000552 if (isa<Constant>(Op0))
553 std::swap(Op0, Op1);
554
Craig Toppera4205622017-06-09 03:21:29 +0000555 if (Value *V = SimplifyFMulInst(Op0, Op1, I.getFastMathFlags(),
556 SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +0000557 return replaceInstUsesWith(I, V);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000558
Sanjay Patel629c4112017-11-06 16:27:15 +0000559 bool AllowReassociate = I.isFast();
Shuxin Yange8227452013-01-15 21:09:32 +0000560
Michael Ilsemand5787be2012-12-12 00:28:32 +0000561 // Simplify mul instructions with a constant RHS.
Sanjay Patel58dab852018-02-14 16:56:44 +0000562 if (auto *C = dyn_cast<Constant>(Op1)) {
Sanjay Pateldb0938f2017-01-10 23:49:07 +0000563 if (Instruction *FoldedMul = foldOpWithConstantIntoOperand(I))
564 return FoldedMul;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000565
Owen Andersonf74cfe02014-01-16 20:36:42 +0000566 // (fmul X, -1.0) --> (fsub -0.0, X)
Sanjay Patel58dab852018-02-14 16:56:44 +0000567 if (match(C, m_SpecificFP(-1.0))) {
Benjamin Kramerfea9ac92014-01-18 16:43:14 +0000568 Constant *NegZero = ConstantFP::getNegativeZero(Op1->getType());
569 Instruction *RI = BinaryOperator::CreateFSub(NegZero, Op0);
Owen Andersonf74cfe02014-01-16 20:36:42 +0000570 RI->copyFastMathFlags(&I);
571 return RI;
572 }
573
Sanjay Patel08868e4942018-02-16 22:32:54 +0000574 if (AllowReassociate && C->isFiniteNonZeroFP()) {
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000575 // Let MDC denote an expression in one of these forms:
576 // X * C, C/X, X/C, where C is a constant.
577 //
578 // Try to simplify "MDC * Constant"
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000579 if (isFMulOrFDivWithConstant(Op0))
580 if (Value *V = foldFMulConst(cast<Instruction>(Op0), C, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +0000581 return replaceInstUsesWith(I, V);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000582
Quentin Colombete684a6d2013-02-28 21:12:40 +0000583 // (MDC +/- C1) * C => (MDC * C) +/- (C1 * C)
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000584 Instruction *FAddSub = dyn_cast<Instruction>(Op0);
585 if (FAddSub &&
586 (FAddSub->getOpcode() == Instruction::FAdd ||
587 FAddSub->getOpcode() == Instruction::FSub)) {
588 Value *Opnd0 = FAddSub->getOperand(0);
589 Value *Opnd1 = FAddSub->getOperand(1);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000590 Constant *C0 = dyn_cast<Constant>(Opnd0);
591 Constant *C1 = dyn_cast<Constant>(Opnd1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000592 bool Swap = false;
593 if (C0) {
Shuxin Yang80138662013-01-07 22:41:28 +0000594 std::swap(C0, C1);
595 std::swap(Opnd0, Opnd1);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000596 Swap = true;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000597 }
598
Sanjay Patel08868e4942018-02-16 22:32:54 +0000599 if (C1 && C1->isFiniteNonZeroFP() && isFMulOrFDivWithConstant(Opnd0)) {
Quentin Colombete684a6d2013-02-28 21:12:40 +0000600 Value *M1 = ConstantExpr::getFMul(C1, C);
Sanjay Patel08868e4942018-02-16 22:32:54 +0000601 Value *M0 = cast<Constant>(M1)->isNormalFP() ?
602 foldFMulConst(cast<Instruction>(Opnd0), C, &I) :
603 nullptr;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000604 if (M0 && M1) {
605 if (Swap && FAddSub->getOpcode() == Instruction::FSub)
606 std::swap(M0, M1);
607
Benjamin Kramer67485762013-09-30 15:39:59 +0000608 Instruction *RI = (FAddSub->getOpcode() == Instruction::FAdd)
609 ? BinaryOperator::CreateFAdd(M0, M1)
610 : BinaryOperator::CreateFSub(M0, M1);
Shuxin Yange8227452013-01-15 21:09:32 +0000611 RI->copyFastMathFlags(&I);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000612 return RI;
613 }
614 }
615 }
616 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000617 }
618
Matt Arsenault56c079f2016-01-30 05:02:00 +0000619 if (Op0 == Op1) {
620 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
621 // sqrt(X) * sqrt(X) -> X
622 if (AllowReassociate && II->getIntrinsicID() == Intrinsic::sqrt)
Sanjay Patel4b198802016-02-01 22:23:39 +0000623 return replaceInstUsesWith(I, II->getOperand(0));
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000624
Matt Arsenault56c079f2016-01-30 05:02:00 +0000625 // fabs(X) * fabs(X) -> X * X
626 if (II->getIntrinsicID() == Intrinsic::fabs) {
627 Instruction *FMulVal = BinaryOperator::CreateFMul(II->getOperand(0),
628 II->getOperand(0),
629 I.getName());
630 FMulVal->copyFastMathFlags(&I);
631 return FMulVal;
632 }
633 }
634 }
635
Pedro Artigasd8795042012-11-30 19:09:41 +0000636 // Under unsafe algebra do:
637 // X * log2(0.5*Y) = X*log2(Y) - X
Sanjay Patelb41d4612014-10-02 15:20:45 +0000638 if (AllowReassociate) {
Craig Topperf40110f2014-04-25 05:29:35 +0000639 Value *OpX = nullptr;
640 Value *OpY = nullptr;
Pedro Artigasd8795042012-11-30 19:09:41 +0000641 IntrinsicInst *Log2;
Pedro Artigas993acd02012-11-30 22:07:05 +0000642 detectLog2OfHalf(Op0, OpY, Log2);
643 if (OpY) {
644 OpX = Op1;
645 } else {
646 detectLog2OfHalf(Op1, OpY, Log2);
647 if (OpY) {
648 OpX = Op0;
Pedro Artigasd8795042012-11-30 19:09:41 +0000649 }
650 }
651 // if pattern detected emit alternate sequence
652 if (OpX && OpY) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000653 BuilderTy::FastMathFlagGuard Guard(Builder);
654 Builder.setFastMathFlags(Log2->getFastMathFlags());
Pedro Artigasd8795042012-11-30 19:09:41 +0000655 Log2->setArgOperand(0, OpY);
Craig Topperbb4069e2017-07-07 23:16:26 +0000656 Value *FMulVal = Builder.CreateFMul(OpX, Log2);
657 Value *FSub = Builder.CreateFSub(FMulVal, OpX);
Benjamin Kramer67485762013-09-30 15:39:59 +0000658 FSub->takeName(&I);
Sanjay Patel4b198802016-02-01 22:23:39 +0000659 return replaceInstUsesWith(I, FSub);
Pedro Artigasd8795042012-11-30 19:09:41 +0000660 }
661 }
662
Dmitry Venikova58d8de2018-01-02 05:58:11 +0000663 // sqrt(a) * sqrt(b) -> sqrt(a * b)
Sanjay Patel1998cc62018-02-12 18:38:35 +0000664 if (AllowReassociate && Op0->hasOneUse() && Op1->hasOneUse()) {
Dmitry Venikova58d8de2018-01-02 05:58:11 +0000665 Value *Opnd0 = nullptr;
666 Value *Opnd1 = nullptr;
667 if (match(Op0, m_Intrinsic<Intrinsic::sqrt>(m_Value(Opnd0))) &&
668 match(Op1, m_Intrinsic<Intrinsic::sqrt>(m_Value(Opnd1)))) {
669 BuilderTy::FastMathFlagGuard Guard(Builder);
670 Builder.setFastMathFlags(I.getFastMathFlags());
671 Value *FMulVal = Builder.CreateFMul(Opnd0, Opnd1);
672 Value *Sqrt = Intrinsic::getDeclaration(I.getModule(),
673 Intrinsic::sqrt, I.getType());
674 Value *SqrtCall = Builder.CreateCall(Sqrt, FMulVal);
675 return replaceInstUsesWith(I, SqrtCall);
676 }
677 }
678
Shuxin Yange8227452013-01-15 21:09:32 +0000679 // Handle symmetric situation in a 2-iteration loop
680 Value *Opnd0 = Op0;
681 Value *Opnd1 = Op1;
682 for (int i = 0; i < 2; i++) {
683 bool IgnoreZeroSign = I.hasNoSignedZeros();
684 if (BinaryOperator::isFNeg(Opnd0, IgnoreZeroSign)) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000685 BuilderTy::FastMathFlagGuard Guard(Builder);
686 Builder.setFastMathFlags(I.getFastMathFlags());
Benjamin Kramer67485762013-09-30 15:39:59 +0000687
Shuxin Yange8227452013-01-15 21:09:32 +0000688 Value *N0 = dyn_castFNegVal(Opnd0, IgnoreZeroSign);
689 Value *N1 = dyn_castFNegVal(Opnd1, IgnoreZeroSign);
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000690
Shuxin Yange8227452013-01-15 21:09:32 +0000691 // -X * -Y => X*Y
Owen Andersone8537fc2014-01-16 20:59:41 +0000692 if (N1) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000693 Value *FMul = Builder.CreateFMul(N0, N1);
Owen Andersone8537fc2014-01-16 20:59:41 +0000694 FMul->takeName(&I);
Sanjay Patel4b198802016-02-01 22:23:39 +0000695 return replaceInstUsesWith(I, FMul);
Owen Andersone8537fc2014-01-16 20:59:41 +0000696 }
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000697
Shuxin Yange8227452013-01-15 21:09:32 +0000698 if (Opnd0->hasOneUse()) {
699 // -X * Y => -(X*Y) (Promote negation as high as possible)
Craig Topperbb4069e2017-07-07 23:16:26 +0000700 Value *T = Builder.CreateFMul(N0, Opnd1);
701 Value *Neg = Builder.CreateFNeg(T);
Benjamin Kramer67485762013-09-30 15:39:59 +0000702 Neg->takeName(&I);
Sanjay Patel4b198802016-02-01 22:23:39 +0000703 return replaceInstUsesWith(I, Neg);
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000704 }
705 }
Shuxin Yange8227452013-01-15 21:09:32 +0000706
Quentin Colombetaa103b32017-09-20 17:32:16 +0000707 // Handle specials cases for FMul with selects feeding the operation
708 if (Value *V = SimplifySelectsFeedingBinaryOp(I, Op0, Op1))
709 return replaceInstUsesWith(I, V);
710
Shuxin Yange8227452013-01-15 21:09:32 +0000711 // (X*Y) * X => (X*X) * Y where Y != X
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000712 // The purpose is two-fold:
Shuxin Yange8227452013-01-15 21:09:32 +0000713 // 1) to form a power expression (of X).
714 // 2) potentially shorten the critical path: After transformation, the
715 // latency of the instruction Y is amortized by the expression of X*X,
716 // and therefore Y is in a "less critical" position compared to what it
717 // was before the transformation.
Shuxin Yange8227452013-01-15 21:09:32 +0000718 if (AllowReassociate) {
719 Value *Opnd0_0, *Opnd0_1;
720 if (Opnd0->hasOneUse() &&
721 match(Opnd0, m_FMul(m_Value(Opnd0_0), m_Value(Opnd0_1)))) {
Craig Topperf40110f2014-04-25 05:29:35 +0000722 Value *Y = nullptr;
Shuxin Yange8227452013-01-15 21:09:32 +0000723 if (Opnd0_0 == Opnd1 && Opnd0_1 != Opnd1)
724 Y = Opnd0_1;
725 else if (Opnd0_1 == Opnd1 && Opnd0_0 != Opnd1)
726 Y = Opnd0_0;
727
728 if (Y) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000729 BuilderTy::FastMathFlagGuard Guard(Builder);
730 Builder.setFastMathFlags(I.getFastMathFlags());
731 Value *T = Builder.CreateFMul(Opnd1, Opnd1);
732 Value *R = Builder.CreateFMul(T, Y);
Benjamin Kramer67485762013-09-30 15:39:59 +0000733 R->takeName(&I);
Sanjay Patel4b198802016-02-01 22:23:39 +0000734 return replaceInstUsesWith(I, R);
Shuxin Yange8227452013-01-15 21:09:32 +0000735 }
736 }
737 }
738
739 if (!isa<Constant>(Op1))
740 std::swap(Opnd0, Opnd1);
741 else
742 break;
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000743 }
744
Craig Topperf40110f2014-04-25 05:29:35 +0000745 return Changed ? &I : nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000746}
747
Sanjay Patelae2e3a42017-10-06 23:20:16 +0000748/// Fold a divide or remainder with a select instruction divisor when one of the
749/// select operands is zero. In that case, we can use the other select operand
750/// because div/rem by zero is undefined.
751bool InstCombiner::simplifyDivRemOfSelectWithZeroOp(BinaryOperator &I) {
752 SelectInst *SI = dyn_cast<SelectInst>(I.getOperand(1));
753 if (!SI)
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000754 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000755
Sanjay Patelae2e3a42017-10-06 23:20:16 +0000756 int NonNullOperand;
757 if (match(SI->getTrueValue(), m_Zero()))
758 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
759 NonNullOperand = 2;
760 else if (match(SI->getFalseValue(), m_Zero()))
761 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
762 NonNullOperand = 1;
763 else
764 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000765
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000766 // Change the div/rem to use 'Y' instead of the select.
767 I.setOperand(1, SI->getOperand(NonNullOperand));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000768
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000769 // Okay, we know we replace the operand of the div/rem with 'Y' with no
770 // problem. However, the select, or the condition of the select may have
771 // multiple uses. Based on our knowledge that the operand must be non-zero,
772 // propagate the known value for the select into other uses of it, and
773 // propagate a known value of the condition into its other users.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000774
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000775 // If the select and condition only have a single use, don't bother with this,
776 // early exit.
Sanjay Patelae2e3a42017-10-06 23:20:16 +0000777 Value *SelectCond = SI->getCondition();
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000778 if (SI->use_empty() && SelectCond->hasOneUse())
779 return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000780
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000781 // Scan the current block backward, looking for other uses of SI.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000782 BasicBlock::iterator BBI = I.getIterator(), BBFront = I.getParent()->begin();
Sanjay Patel72d339a2017-10-06 23:43:06 +0000783 Type *CondTy = SelectCond->getType();
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000784 while (BBI != BBFront) {
785 --BBI;
786 // If we found a call to a function, we can't assume it will return, so
787 // information from below it cannot be propagated above it.
788 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
789 break;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000790
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000791 // Replace uses of the select or its condition with the known values.
792 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
793 I != E; ++I) {
794 if (*I == SI) {
795 *I = SI->getOperand(NonNullOperand);
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000796 Worklist.Add(&*BBI);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000797 } else if (*I == SelectCond) {
Sanjay Patel72d339a2017-10-06 23:43:06 +0000798 *I = NonNullOperand == 1 ? ConstantInt::getTrue(CondTy)
799 : ConstantInt::getFalse(CondTy);
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000800 Worklist.Add(&*BBI);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000801 }
802 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000803
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000804 // If we past the instruction, quit looking for it.
805 if (&*BBI == SI)
Craig Topperf40110f2014-04-25 05:29:35 +0000806 SI = nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000807 if (&*BBI == SelectCond)
Craig Topperf40110f2014-04-25 05:29:35 +0000808 SelectCond = nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000809
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000810 // If we ran out of things to eliminate, break out of the loop.
Craig Topperf40110f2014-04-25 05:29:35 +0000811 if (!SelectCond && !SI)
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000812 break;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000813
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000814 }
815 return true;
816}
817
Sanjay Patel1998cc62018-02-12 18:38:35 +0000818/// True if the multiply can not be expressed in an int this size.
819static bool multiplyOverflows(const APInt &C1, const APInt &C2, APInt &Product,
820 bool IsSigned) {
821 bool Overflow;
822 Product = IsSigned ? C1.smul_ov(C2, Overflow) : C1.umul_ov(C2, Overflow);
823 return Overflow;
824}
825
826/// True if C2 is a multiple of C1. Quotient contains C2/C1.
827static bool isMultiple(const APInt &C1, const APInt &C2, APInt &Quotient,
828 bool IsSigned) {
829 assert(C1.getBitWidth() == C2.getBitWidth() && "Constant widths not equal");
830
831 // Bail if we will divide by zero.
832 if (C2.isNullValue())
833 return false;
834
835 // Bail if we would divide INT_MIN by -1.
836 if (IsSigned && C1.isMinSignedValue() && C2.isAllOnesValue())
837 return false;
838
839 APInt Remainder(C1.getBitWidth(), /*Val=*/0ULL, IsSigned);
840 if (IsSigned)
841 APInt::sdivrem(C1, C2, Quotient, Remainder);
842 else
843 APInt::udivrem(C1, C2, Quotient, Remainder);
844
845 return Remainder.isMinValue();
846}
847
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000848/// This function implements the transforms common to both integer division
849/// instructions (udiv and sdiv). It is called by the visitors to those integer
850/// division instructions.
851/// @brief Common integer divide transforms
852Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
853 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Sanjay Patel9530f182018-01-21 16:14:51 +0000854 bool IsSigned = I.getOpcode() == Instruction::SDiv;
Sanjay Patel39059d22018-02-12 14:14:56 +0000855 Type *Ty = I.getType();
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000856
Chris Lattner7c99f192011-05-22 18:18:41 +0000857 // The RHS is known non-zero.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000858 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I)) {
Chris Lattner7c99f192011-05-22 18:18:41 +0000859 I.setOperand(1, V);
860 return &I;
861 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000862
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000863 // Handle cases involving: [su]div X, (select Cond, Y, Z)
864 // This does not apply for fdiv.
Sanjay Patelae2e3a42017-10-06 23:20:16 +0000865 if (simplifyDivRemOfSelectWithZeroOp(I))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000866 return &I;
867
Sanjay Patel1998cc62018-02-12 18:38:35 +0000868 const APInt *C2;
869 if (match(Op1, m_APInt(C2))) {
870 Value *X;
871 const APInt *C1;
David Majnemerf9a095d2014-08-16 08:55:06 +0000872
Sanjay Patel1998cc62018-02-12 18:38:35 +0000873 // (X / C1) / C2 -> X / (C1*C2)
874 if ((IsSigned && match(Op0, m_SDiv(m_Value(X), m_APInt(C1)))) ||
875 (!IsSigned && match(Op0, m_UDiv(m_Value(X), m_APInt(C1))))) {
876 APInt Product(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
877 if (!multiplyOverflows(*C1, *C2, Product, IsSigned))
878 return BinaryOperator::Create(I.getOpcode(), X,
879 ConstantInt::get(Ty, Product));
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000880 }
Sanjay Patel1998cc62018-02-12 18:38:35 +0000881
882 if ((IsSigned && match(Op0, m_NSWMul(m_Value(X), m_APInt(C1)))) ||
883 (!IsSigned && match(Op0, m_NUWMul(m_Value(X), m_APInt(C1))))) {
884 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
885
886 // (X * C1) / C2 -> X / (C2 / C1) if C2 is a multiple of C1.
887 if (isMultiple(*C2, *C1, Quotient, IsSigned)) {
888 auto *NewDiv = BinaryOperator::Create(I.getOpcode(), X,
889 ConstantInt::get(Ty, Quotient));
890 NewDiv->setIsExact(I.isExact());
891 return NewDiv;
892 }
893
894 // (X * C1) / C2 -> X * (C1 / C2) if C1 is a multiple of C2.
895 if (isMultiple(*C1, *C2, Quotient, IsSigned)) {
896 auto *Mul = BinaryOperator::Create(Instruction::Mul, X,
897 ConstantInt::get(Ty, Quotient));
898 auto *OBO = cast<OverflowingBinaryOperator>(Op0);
899 Mul->setHasNoUnsignedWrap(!IsSigned && OBO->hasNoUnsignedWrap());
900 Mul->setHasNoSignedWrap(OBO->hasNoSignedWrap());
901 return Mul;
902 }
903 }
904
905 if ((IsSigned && match(Op0, m_NSWShl(m_Value(X), m_APInt(C1))) &&
906 *C1 != C1->getBitWidth() - 1) ||
907 (!IsSigned && match(Op0, m_NUWShl(m_Value(X), m_APInt(C1))))) {
908 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
909 APInt C1Shifted = APInt::getOneBitSet(
910 C1->getBitWidth(), static_cast<unsigned>(C1->getLimitedValue()));
911
912 // (X << C1) / C2 -> X / (C2 >> C1) if C2 is a multiple of C1.
913 if (isMultiple(*C2, C1Shifted, Quotient, IsSigned)) {
914 auto *BO = BinaryOperator::Create(I.getOpcode(), X,
915 ConstantInt::get(Ty, Quotient));
916 BO->setIsExact(I.isExact());
917 return BO;
918 }
919
920 // (X << C1) / C2 -> X * (C2 >> C1) if C1 is a multiple of C2.
921 if (isMultiple(C1Shifted, *C2, Quotient, IsSigned)) {
922 auto *Mul = BinaryOperator::Create(Instruction::Mul, X,
923 ConstantInt::get(Ty, Quotient));
924 auto *OBO = cast<OverflowingBinaryOperator>(Op0);
925 Mul->setHasNoUnsignedWrap(!IsSigned && OBO->hasNoUnsignedWrap());
926 Mul->setHasNoSignedWrap(OBO->hasNoSignedWrap());
927 return Mul;
928 }
929 }
930
931 if (!C2->isNullValue()) // avoid X udiv 0
932 if (Instruction *FoldedDiv = foldOpWithConstantIntoOperand(I))
933 return FoldedDiv;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000934 }
935
Craig Topper218a3592017-04-17 03:41:47 +0000936 if (match(Op0, m_One())) {
Sanjay Patel39059d22018-02-12 14:14:56 +0000937 assert(!Ty->isIntOrIntVectorTy(1) && "i1 divide not removed?");
938 if (IsSigned) {
Craig Topper218a3592017-04-17 03:41:47 +0000939 // If Op1 is 0 then it's undefined behaviour, if Op1 is 1 then the
940 // result is one, if Op1 is -1 then the result is minus one, otherwise
941 // it's zero.
Craig Topperbb4069e2017-07-07 23:16:26 +0000942 Value *Inc = Builder.CreateAdd(Op1, Op0);
Sanjay Patel39059d22018-02-12 14:14:56 +0000943 Value *Cmp = Builder.CreateICmpULT(Inc, ConstantInt::get(Ty, 3));
944 return SelectInst::Create(Cmp, Op1, ConstantInt::get(Ty, 0));
Craig Topper218a3592017-04-17 03:41:47 +0000945 } else {
946 // If Op1 is 0 then it's undefined behaviour. If Op1 is 1 then the
947 // result is one, otherwise it's zero.
Sanjay Patel39059d22018-02-12 14:14:56 +0000948 return new ZExtInst(Builder.CreateICmpEQ(Op1, Op0), Ty);
Nick Lewyckyf0cf8fa2014-05-14 03:03:05 +0000949 }
950 }
951
Benjamin Kramer57b3df52011-04-30 18:16:00 +0000952 // See if we can fold away this div instruction.
953 if (SimplifyDemandedInstructionBits(I))
954 return &I;
955
Duncan Sands771e82a2011-01-28 16:51:11 +0000956 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
Sanjay Patel9530f182018-01-21 16:14:51 +0000957 Value *X, *Z;
958 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) // (X - Z) / Y; Y = Op1
959 if ((IsSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
960 (!IsSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
Duncan Sands771e82a2011-01-28 16:51:11 +0000961 return BinaryOperator::Create(I.getOpcode(), X, Op1);
Sanjay Patel9530f182018-01-21 16:14:51 +0000962
963 // (X << Y) / X -> 1 << Y
964 Value *Y;
965 if (IsSigned && match(Op0, m_NSWShl(m_Specific(Op1), m_Value(Y))))
Sanjay Patel39059d22018-02-12 14:14:56 +0000966 return BinaryOperator::CreateNSWShl(ConstantInt::get(Ty, 1), Y);
Sanjay Patel9530f182018-01-21 16:14:51 +0000967 if (!IsSigned && match(Op0, m_NUWShl(m_Specific(Op1), m_Value(Y))))
Sanjay Patel39059d22018-02-12 14:14:56 +0000968 return BinaryOperator::CreateNUWShl(ConstantInt::get(Ty, 1), Y);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000969
Sanjay Patel510d6472018-02-11 17:20:32 +0000970 // X / (X * Y) -> 1 / Y if the multiplication does not overflow.
971 if (match(Op1, m_c_Mul(m_Specific(Op0), m_Value(Y)))) {
972 bool HasNSW = cast<OverflowingBinaryOperator>(Op1)->hasNoSignedWrap();
973 bool HasNUW = cast<OverflowingBinaryOperator>(Op1)->hasNoUnsignedWrap();
974 if ((IsSigned && HasNSW) || (!IsSigned && HasNUW)) {
Sanjay Patel39059d22018-02-12 14:14:56 +0000975 I.setOperand(0, ConstantInt::get(Ty, 1));
Sanjay Patel510d6472018-02-11 17:20:32 +0000976 I.setOperand(1, Y);
977 return &I;
978 }
979 }
980
Craig Topperf40110f2014-04-25 05:29:35 +0000981 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000982}
983
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000984static const unsigned MaxDepth = 6;
985
David Majnemer37f8f442013-07-04 21:17:49 +0000986namespace {
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000987
988using FoldUDivOperandCb = Instruction *(*)(Value *Op0, Value *Op1,
989 const BinaryOperator &I,
990 InstCombiner &IC);
David Majnemer37f8f442013-07-04 21:17:49 +0000991
992/// \brief Used to maintain state for visitUDivOperand().
993struct UDivFoldAction {
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000994 /// Informs visitUDiv() how to fold this operand. This can be zero if this
995 /// action joins two actions together.
996 FoldUDivOperandCb FoldAction;
David Majnemer37f8f442013-07-04 21:17:49 +0000997
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000998 /// Which operand to fold.
999 Value *OperandToFold;
1000
David Majnemer37f8f442013-07-04 21:17:49 +00001001 union {
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00001002 /// The instruction returned when FoldAction is invoked.
1003 Instruction *FoldResult;
David Majnemer37f8f442013-07-04 21:17:49 +00001004
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00001005 /// Stores the LHS action index if this action joins two actions together.
1006 size_t SelectLHSIdx;
David Majnemer37f8f442013-07-04 21:17:49 +00001007 };
1008
1009 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand)
Craig Topperf40110f2014-04-25 05:29:35 +00001010 : FoldAction(FA), OperandToFold(InputOperand), FoldResult(nullptr) {}
David Majnemer37f8f442013-07-04 21:17:49 +00001011 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand, size_t SLHS)
1012 : FoldAction(FA), OperandToFold(InputOperand), SelectLHSIdx(SLHS) {}
1013};
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00001014
1015} // end anonymous namespace
David Majnemer37f8f442013-07-04 21:17:49 +00001016
1017// X udiv 2^C -> X >> C
1018static Instruction *foldUDivPow2Cst(Value *Op0, Value *Op1,
1019 const BinaryOperator &I, InstCombiner &IC) {
Simon Pilgrim94cc89d2018-02-08 14:46:10 +00001020 Constant *C1 = getLogBase2(Op0->getType(), cast<Constant>(Op1));
1021 if (!C1)
1022 llvm_unreachable("Failed to constant fold udiv -> logbase2");
1023 BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, C1);
Suyog Sarda65f5ae92014-10-07 12:04:07 +00001024 if (I.isExact())
1025 LShr->setIsExact();
David Majnemer37f8f442013-07-04 21:17:49 +00001026 return LShr;
1027}
1028
1029// X udiv C, where C >= signbit
1030static Instruction *foldUDivNegCst(Value *Op0, Value *Op1,
1031 const BinaryOperator &I, InstCombiner &IC) {
Simon Pilgrim9620f4b2018-02-09 10:43:59 +00001032 Value *ICI = IC.Builder.CreateICmpULT(Op0, cast<Constant>(Op1));
David Majnemer37f8f442013-07-04 21:17:49 +00001033 return SelectInst::Create(ICI, Constant::getNullValue(I.getType()),
1034 ConstantInt::get(I.getType(), 1));
1035}
1036
1037// X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Andrea Di Biagioa82d52d2016-09-26 12:07:23 +00001038// X udiv (zext (C1 << N)), where C1 is "1<<C2" --> X >> (N+C2)
David Majnemer37f8f442013-07-04 21:17:49 +00001039static Instruction *foldUDivShl(Value *Op0, Value *Op1, const BinaryOperator &I,
1040 InstCombiner &IC) {
Andrea Di Biagioa82d52d2016-09-26 12:07:23 +00001041 Value *ShiftLeft;
1042 if (!match(Op1, m_ZExt(m_Value(ShiftLeft))))
1043 ShiftLeft = Op1;
David Majnemer37f8f442013-07-04 21:17:49 +00001044
Simon Pilgrim2a90acd2018-02-08 15:19:38 +00001045 Constant *CI;
Andrea Di Biagioa82d52d2016-09-26 12:07:23 +00001046 Value *N;
Simon Pilgrim2a90acd2018-02-08 15:19:38 +00001047 if (!match(ShiftLeft, m_Shl(m_Constant(CI), m_Value(N))))
Andrea Di Biagioa82d52d2016-09-26 12:07:23 +00001048 llvm_unreachable("match should never fail here!");
Simon Pilgrim2a90acd2018-02-08 15:19:38 +00001049 Constant *Log2Base = getLogBase2(N->getType(), CI);
1050 if (!Log2Base)
1051 llvm_unreachable("getLogBase2 should never fail here!");
1052 N = IC.Builder.CreateAdd(N, Log2Base);
Andrea Di Biagioa82d52d2016-09-26 12:07:23 +00001053 if (Op1 != ShiftLeft)
Craig Topperbb4069e2017-07-07 23:16:26 +00001054 N = IC.Builder.CreateZExt(N, Op1->getType());
David Majnemer37f8f442013-07-04 21:17:49 +00001055 BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, N);
Suyog Sarda65f5ae92014-10-07 12:04:07 +00001056 if (I.isExact())
1057 LShr->setIsExact();
David Majnemer37f8f442013-07-04 21:17:49 +00001058 return LShr;
1059}
1060
1061// \brief Recursively visits the possible right hand operands of a udiv
1062// instruction, seeing through select instructions, to determine if we can
1063// replace the udiv with something simpler. If we find that an operand is not
1064// able to simplify the udiv, we abort the entire transformation.
1065static size_t visitUDivOperand(Value *Op0, Value *Op1, const BinaryOperator &I,
1066 SmallVectorImpl<UDivFoldAction> &Actions,
1067 unsigned Depth = 0) {
1068 // Check to see if this is an unsigned division with an exact power of 2,
1069 // if so, convert to a right shift.
1070 if (match(Op1, m_Power2())) {
1071 Actions.push_back(UDivFoldAction(foldUDivPow2Cst, Op1));
1072 return Actions.size();
1073 }
1074
Simon Pilgrim9620f4b2018-02-09 10:43:59 +00001075 // X udiv C, where C >= signbit
1076 if (match(Op1, m_Negative())) {
1077 Actions.push_back(UDivFoldAction(foldUDivNegCst, Op1));
1078 return Actions.size();
1079 }
David Majnemer37f8f442013-07-04 21:17:49 +00001080
1081 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
1082 if (match(Op1, m_Shl(m_Power2(), m_Value())) ||
1083 match(Op1, m_ZExt(m_Shl(m_Power2(), m_Value())))) {
1084 Actions.push_back(UDivFoldAction(foldUDivShl, Op1));
1085 return Actions.size();
1086 }
1087
1088 // The remaining tests are all recursive, so bail out if we hit the limit.
1089 if (Depth++ == MaxDepth)
1090 return 0;
1091
1092 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
David Majnemer492e6122014-08-30 09:19:05 +00001093 if (size_t LHSIdx =
1094 visitUDivOperand(Op0, SI->getOperand(1), I, Actions, Depth))
1095 if (visitUDivOperand(Op0, SI->getOperand(2), I, Actions, Depth)) {
1096 Actions.push_back(UDivFoldAction(nullptr, Op1, LHSIdx - 1));
David Majnemer37f8f442013-07-04 21:17:49 +00001097 return Actions.size();
1098 }
1099
1100 return 0;
1101}
1102
Sanjay Patelbb789382017-08-24 22:54:01 +00001103/// If we have zero-extended operands of an unsigned div or rem, we may be able
1104/// to narrow the operation (sink the zext below the math).
1105static Instruction *narrowUDivURem(BinaryOperator &I,
1106 InstCombiner::BuilderTy &Builder) {
1107 Instruction::BinaryOps Opcode = I.getOpcode();
1108 Value *N = I.getOperand(0);
1109 Value *D = I.getOperand(1);
1110 Type *Ty = I.getType();
1111 Value *X, *Y;
1112 if (match(N, m_ZExt(m_Value(X))) && match(D, m_ZExt(m_Value(Y))) &&
1113 X->getType() == Y->getType() && (N->hasOneUse() || D->hasOneUse())) {
1114 // udiv (zext X), (zext Y) --> zext (udiv X, Y)
1115 // urem (zext X), (zext Y) --> zext (urem X, Y)
1116 Value *NarrowOp = Builder.CreateBinOp(Opcode, X, Y);
1117 return new ZExtInst(NarrowOp, Ty);
1118 }
1119
1120 Constant *C;
1121 if ((match(N, m_OneUse(m_ZExt(m_Value(X)))) && match(D, m_Constant(C))) ||
1122 (match(D, m_OneUse(m_ZExt(m_Value(X)))) && match(N, m_Constant(C)))) {
1123 // If the constant is the same in the smaller type, use the narrow version.
1124 Constant *TruncC = ConstantExpr::getTrunc(C, X->getType());
1125 if (ConstantExpr::getZExt(TruncC, Ty) != C)
1126 return nullptr;
1127
1128 // udiv (zext X), C --> zext (udiv X, C')
1129 // urem (zext X), C --> zext (urem X, C')
1130 // udiv C, (zext X) --> zext (udiv C', X)
1131 // urem C, (zext X) --> zext (urem C', X)
1132 Value *NarrowOp = isa<Constant>(D) ? Builder.CreateBinOp(Opcode, X, TruncC)
1133 : Builder.CreateBinOp(Opcode, TruncC, X);
1134 return new ZExtInst(NarrowOp, Ty);
1135 }
1136
1137 return nullptr;
1138}
1139
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001140Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
1141 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1142
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001143 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001144 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001145
Craig Toppera4205622017-06-09 03:21:29 +00001146 if (Value *V = SimplifyUDivInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001147 return replaceInstUsesWith(I, V);
Duncan Sands771e82a2011-01-28 16:51:11 +00001148
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001149 // Handle the integer div common cases
1150 if (Instruction *Common = commonIDivTransforms(I))
1151 return Common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001152
Benjamin Kramerd4a64712012-08-30 15:07:40 +00001153 // (x lshr C1) udiv C2 --> x udiv (C2 << C1)
David Majnemera2521382014-10-13 21:48:30 +00001154 {
Benjamin Kramer9c0a8072012-08-28 13:08:13 +00001155 Value *X;
David Majnemera2521382014-10-13 21:48:30 +00001156 const APInt *C1, *C2;
1157 if (match(Op0, m_LShr(m_Value(X), m_APInt(C1))) &&
1158 match(Op1, m_APInt(C2))) {
1159 bool Overflow;
1160 APInt C2ShlC1 = C2->ushl_ov(*C1, Overflow);
David Majnemera3aeb152014-11-22 18:16:54 +00001161 if (!Overflow) {
1162 bool IsExact = I.isExact() && match(Op0, m_Exact(m_Value()));
1163 BinaryOperator *BO = BinaryOperator::CreateUDiv(
David Majnemera2521382014-10-13 21:48:30 +00001164 X, ConstantInt::get(X->getType(), C2ShlC1));
David Majnemera3aeb152014-11-22 18:16:54 +00001165 if (IsExact)
1166 BO->setIsExact();
1167 return BO;
1168 }
David Majnemera2521382014-10-13 21:48:30 +00001169 }
Nadav Rotem11935b22012-08-28 10:01:43 +00001170 }
1171
Sanjay Patelbb789382017-08-24 22:54:01 +00001172 if (Instruction *NarrowDiv = narrowUDivURem(I, Builder))
1173 return NarrowDiv;
Benjamin Kramer9aa91b12011-04-30 18:16:07 +00001174
David Majnemer37f8f442013-07-04 21:17:49 +00001175 // (LHS udiv (select (select (...)))) -> (LHS >> (select (select (...))))
1176 SmallVector<UDivFoldAction, 6> UDivActions;
1177 if (visitUDivOperand(Op0, Op1, I, UDivActions))
1178 for (unsigned i = 0, e = UDivActions.size(); i != e; ++i) {
1179 FoldUDivOperandCb Action = UDivActions[i].FoldAction;
1180 Value *ActionOp1 = UDivActions[i].OperandToFold;
1181 Instruction *Inst;
1182 if (Action)
1183 Inst = Action(Op0, ActionOp1, I, *this);
1184 else {
1185 // This action joins two actions together. The RHS of this action is
1186 // simply the last action we processed, we saved the LHS action index in
1187 // the joining action.
1188 size_t SelectRHSIdx = i - 1;
1189 Value *SelectRHS = UDivActions[SelectRHSIdx].FoldResult;
1190 size_t SelectLHSIdx = UDivActions[i].SelectLHSIdx;
1191 Value *SelectLHS = UDivActions[SelectLHSIdx].FoldResult;
1192 Inst = SelectInst::Create(cast<SelectInst>(ActionOp1)->getCondition(),
1193 SelectLHS, SelectRHS);
1194 }
1195
1196 // If this is the last action to process, return it to the InstCombiner.
1197 // Otherwise, we insert it before the UDiv and record it so that we may
1198 // use it as part of a joining action (i.e., a SelectInst).
1199 if (e - i != 1) {
1200 Inst->insertBefore(&I);
1201 UDivActions[i].FoldResult = Inst;
1202 } else
1203 return Inst;
1204 }
1205
Craig Topperf40110f2014-04-25 05:29:35 +00001206 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001207}
1208
1209Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
1210 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1211
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001212 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001213 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001214
Craig Toppera4205622017-06-09 03:21:29 +00001215 if (Value *V = SimplifySDivInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001216 return replaceInstUsesWith(I, V);
Duncan Sands771e82a2011-01-28 16:51:11 +00001217
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001218 // Handle the integer div common cases
1219 if (Instruction *Common = commonIDivTransforms(I))
1220 return Common;
1221
Sanjay Patelc6ada532016-06-27 17:25:57 +00001222 const APInt *Op1C;
Sanjay Patelbedd1f92016-06-27 18:38:40 +00001223 if (match(Op1, m_APInt(Op1C))) {
1224 // sdiv X, -1 == -X
1225 if (Op1C->isAllOnesValue())
1226 return BinaryOperator::CreateNeg(Op0);
1227
1228 // sdiv exact X, C --> ashr exact X, log2(C)
1229 if (I.isExact() && Op1C->isNonNegative() && Op1C->isPowerOf2()) {
1230 Value *ShAmt = ConstantInt::get(Op1->getType(), Op1C->exactLogBase2());
1231 return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
1232 }
Sanjay Patel59ed2ff2016-06-27 22:27:11 +00001233
1234 // If the dividend is sign-extended and the constant divisor is small enough
1235 // to fit in the source type, shrink the division to the narrower type:
1236 // (sext X) sdiv C --> sext (X sdiv C)
1237 Value *Op0Src;
1238 if (match(Op0, m_OneUse(m_SExt(m_Value(Op0Src)))) &&
1239 Op0Src->getType()->getScalarSizeInBits() >= Op1C->getMinSignedBits()) {
1240
1241 // In the general case, we need to make sure that the dividend is not the
1242 // minimum signed value because dividing that by -1 is UB. But here, we
1243 // know that the -1 divisor case is already handled above.
1244
1245 Constant *NarrowDivisor =
1246 ConstantExpr::getTrunc(cast<Constant>(Op1), Op0Src->getType());
Craig Topperbb4069e2017-07-07 23:16:26 +00001247 Value *NarrowOp = Builder.CreateSDiv(Op0Src, NarrowDivisor);
Sanjay Patel59ed2ff2016-06-27 22:27:11 +00001248 return new SExtInst(NarrowOp, Op0->getType());
1249 }
Benjamin Kramer72196f32014-01-19 15:24:22 +00001250 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001251
Benjamin Kramer72196f32014-01-19 15:24:22 +00001252 if (Constant *RHS = dyn_cast<Constant>(Op1)) {
David Majnemerf28e2a42014-07-02 06:42:13 +00001253 // X/INT_MIN -> X == INT_MIN
1254 if (RHS->isMinSignedValue())
Craig Topperbb4069e2017-07-07 23:16:26 +00001255 return new ZExtInst(Builder.CreateICmpEQ(Op0, Op1), I.getType());
David Majnemerf28e2a42014-07-02 06:42:13 +00001256
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001257 // -X/C --> X/-C provided the negation doesn't overflow.
David Majnemerfa4699e2014-11-22 20:00:34 +00001258 Value *X;
1259 if (match(Op0, m_NSWSub(m_Zero(), m_Value(X)))) {
1260 auto *BO = BinaryOperator::CreateSDiv(X, ConstantExpr::getNeg(RHS));
1261 BO->setIsExact(I.isExact());
1262 return BO;
1263 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001264 }
1265
1266 // If the sign bits of both operands are zero (i.e. we can prove they are
1267 // unsigned inputs), turn this into a udiv.
Craig Topperbcfd2d12017-04-20 16:56:25 +00001268 APInt Mask(APInt::getSignMask(I.getType()->getScalarSizeInBits()));
Craig Topperf2484682017-04-17 01:51:19 +00001269 if (MaskedValueIsZero(Op0, Mask, 0, &I)) {
1270 if (MaskedValueIsZero(Op1, Mask, 0, &I)) {
1271 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
1272 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1273 BO->setIsExact(I.isExact());
1274 return BO;
1275 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001276
Craig Topperd4039f72017-05-25 21:51:12 +00001277 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/ true, 0, &I)) {
Craig Topperf2484682017-04-17 01:51:19 +00001278 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
1279 // Safe because the only negative value (1 << Y) can take on is
1280 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
1281 // the sign bit set.
1282 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1283 BO->setIsExact(I.isExact());
1284 return BO;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001285 }
1286 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001287
Craig Topperf40110f2014-04-25 05:29:35 +00001288 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001289}
1290
Sanjay Patelb39bcc02018-02-14 23:04:17 +00001291/// Try to convert X/C into X * (1/C).
1292static Instruction *foldFDivConstantDivisor(BinaryOperator &FDiv) {
Sanjay Patel6a0f6672018-02-15 13:55:52 +00001293 // TODO: Handle non-splat vector constants.
1294 const APFloat *C;
1295 if (!match(FDiv.getOperand(1), m_APFloat(C)))
Craig Topperf40110f2014-04-25 05:29:35 +00001296 return nullptr;
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001297
Sanjay Patelb39bcc02018-02-14 23:04:17 +00001298 // This returns false if the inverse would be a denormal.
Sanjay Patel6a0f6672018-02-15 13:55:52 +00001299 APFloat Reciprocal(C->getSemantics());
1300 bool HasRecip = C->getExactInverse(&Reciprocal);
Sanjay Patelb39bcc02018-02-14 23:04:17 +00001301 // If the inverse is not exact, we may still be able to convert if we are
1302 // not operating with strict math.
Sanjay Patel6a0f6672018-02-15 13:55:52 +00001303 if (!HasRecip && FDiv.hasAllowReciprocal() && C->isFiniteNonZero()) {
1304 Reciprocal = APFloat(C->getSemantics(), 1.0f);
1305 Reciprocal.divide(*C, APFloat::rmNearestTiesToEven);
Sanjay Patelb39bcc02018-02-14 23:04:17 +00001306 // Disallow denormal constants because we don't know what would happen
1307 // on all targets.
1308 // TODO: Function attributes can tell us that denorms are flushed?
1309 HasRecip = !Reciprocal.isDenormal();
Shuxin Yang320f52a2013-01-14 22:48:41 +00001310 }
1311
Sanjay Patelb39bcc02018-02-14 23:04:17 +00001312 if (!HasRecip)
Craig Topperf40110f2014-04-25 05:29:35 +00001313 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001314
Sanjay Patel6a0f6672018-02-15 13:55:52 +00001315 auto *RecipCFP = ConstantFP::get(FDiv.getType(), Reciprocal);
Sanjay Patelb39bcc02018-02-14 23:04:17 +00001316 return BinaryOperator::CreateFMul(FDiv.getOperand(0), RecipCFP);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001317}
1318
Frits van Bommel2a559512011-01-29 17:50:27 +00001319Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
1320 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1321
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001322 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001323 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001324
Craig Toppera4205622017-06-09 03:21:29 +00001325 if (Value *V = SimplifyFDivInst(Op0, Op1, I.getFastMathFlags(),
1326 SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001327 return replaceInstUsesWith(I, V);
Frits van Bommel2a559512011-01-29 17:50:27 +00001328
Sanjay Patelb39bcc02018-02-14 23:04:17 +00001329 if (Instruction *FMul = foldFDivConstantDivisor(I)) {
1330 FMul->copyFastMathFlags(&I);
1331 return FMul;
1332 }
1333
Stephen Lina9b57f62013-07-20 07:13:13 +00001334 if (isa<Constant>(Op0))
1335 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1336 if (Instruction *R = FoldOpIntoSelect(I, SI))
1337 return R;
1338
Sanjay Patel629c4112017-11-06 16:27:15 +00001339 bool AllowReassociate = I.isFast();
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001340 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Stephen Lina9b57f62013-07-20 07:13:13 +00001341 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1342 if (Instruction *R = FoldOpIntoSelect(I, SI))
1343 return R;
1344
Shuxin Yang320f52a2013-01-14 22:48:41 +00001345 if (AllowReassociate) {
Craig Topperf40110f2014-04-25 05:29:35 +00001346 Constant *C1 = nullptr;
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001347 Constant *C2 = Op1C;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001348 Value *X;
Craig Topperf40110f2014-04-25 05:29:35 +00001349 Instruction *Res = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001350
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001351 if (match(Op0, m_FMul(m_Value(X), m_Constant(C1)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001352 // (X*C1)/C2 => X * (C1/C2)
Shuxin Yang320f52a2013-01-14 22:48:41 +00001353 Constant *C = ConstantExpr::getFDiv(C1, C2);
Sanjay Patel08868e4942018-02-16 22:32:54 +00001354 if (C->isNormalFP())
Shuxin Yang320f52a2013-01-14 22:48:41 +00001355 Res = BinaryOperator::CreateFMul(X, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001356 } else if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) {
Sanjay Patelb39bcc02018-02-14 23:04:17 +00001357 // (X/C1)/C2 => X /(C2*C1)
Shuxin Yang320f52a2013-01-14 22:48:41 +00001358 Constant *C = ConstantExpr::getFMul(C1, C2);
Sanjay Patel08868e4942018-02-16 22:32:54 +00001359 if (C->isNormalFP())
Sanjay Patelb39bcc02018-02-14 23:04:17 +00001360 Res = BinaryOperator::CreateFDiv(X, C);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001361 }
1362
1363 if (Res) {
1364 Res->setFastMathFlags(I.getFastMathFlags());
1365 return Res;
1366 }
1367 }
Craig Topperf40110f2014-04-25 05:29:35 +00001368 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001369 }
1370
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001371 if (AllowReassociate && isa<Constant>(Op0)) {
1372 Constant *C1 = cast<Constant>(Op0), *C2;
Craig Topperf40110f2014-04-25 05:29:35 +00001373 Constant *Fold = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001374 Value *X;
1375 bool CreateDiv = true;
1376
1377 // C1 / (X*C2) => (C1/C2) / X
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001378 if (match(Op1, m_FMul(m_Value(X), m_Constant(C2))))
Shuxin Yang320f52a2013-01-14 22:48:41 +00001379 Fold = ConstantExpr::getFDiv(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001380 else if (match(Op1, m_FDiv(m_Value(X), m_Constant(C2)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001381 // C1 / (X/C2) => (C1*C2) / X
1382 Fold = ConstantExpr::getFMul(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001383 } else if (match(Op1, m_FDiv(m_Constant(C2), m_Value(X)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001384 // C1 / (C2/X) => (C1/C2) * X
1385 Fold = ConstantExpr::getFDiv(C1, C2);
1386 CreateDiv = false;
1387 }
1388
Sanjay Patel08868e4942018-02-16 22:32:54 +00001389 if (Fold && Fold->isNormalFP()) {
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001390 Instruction *R = CreateDiv ? BinaryOperator::CreateFDiv(Fold, X)
1391 : BinaryOperator::CreateFMul(X, Fold);
1392 R->setFastMathFlags(I.getFastMathFlags());
1393 return R;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001394 }
Craig Topperf40110f2014-04-25 05:29:35 +00001395 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001396 }
1397
1398 if (AllowReassociate) {
1399 Value *X, *Y;
Sanjay Patel91bb7752018-02-16 17:52:32 +00001400 if (match(Op0, m_OneUse(m_FDiv(m_Value(X), m_Value(Y)))) &&
1401 (!isa<Constant>(Y) || !isa<Constant>(Op1))) {
1402 // (X / Y) / Z => X / (Y * Z)
1403 Value *YZ = Builder.CreateFMul(Y, Op1);
1404 if (auto *YZInst = dyn_cast<Instruction>(YZ)) {
1405 FastMathFlags FMFIntersect = I.getFastMathFlags();
1406 FMFIntersect &= cast<Instruction>(Op0)->getFastMathFlags();
1407 YZInst->setFastMathFlags(FMFIntersect);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001408 }
Sanjay Patel91bb7752018-02-16 17:52:32 +00001409 Instruction *NewDiv = BinaryOperator::CreateFDiv(X, YZ);
1410 NewDiv->setFastMathFlags(I.getFastMathFlags());
1411 return NewDiv;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001412 }
Sanjay Patel91bb7752018-02-16 17:52:32 +00001413 if (match(Op1, m_OneUse(m_FDiv(m_Value(X), m_Value(Y)))) &&
1414 (!isa<Constant>(Y) || !isa<Constant>(Op0))) {
1415 // Z / (X / Y) => (Y * Z) / X
1416 Value *YZ = Builder.CreateFMul(Y, Op0);
1417 if (auto *YZInst = dyn_cast<Instruction>(YZ)) {
1418 FastMathFlags FMFIntersect = I.getFastMathFlags();
1419 FMFIntersect &= cast<Instruction>(Op1)->getFastMathFlags();
1420 YZInst->setFastMathFlags(FMFIntersect);
1421 }
1422 Instruction *NewDiv = BinaryOperator::CreateFDiv(YZ, X);
1423 NewDiv->setFastMathFlags(I.getFastMathFlags());
1424 return NewDiv;
Benjamin Kramer8564e0d2011-03-30 15:42:35 +00001425 }
1426 }
1427
Sanjay Patel339b4d32018-02-15 15:07:12 +00001428 if (I.hasAllowReassoc() && Op0->hasOneUse() && Op1->hasOneUse()) {
Sanjay Patel65da14d2018-02-16 16:13:20 +00001429 // sin(X) / cos(X) -> tan(X)
1430 // cos(X) / sin(X) -> 1/tan(X) (cotangent)
1431 Value *X;
1432 bool IsTan = match(Op0, m_Intrinsic<Intrinsic::sin>(m_Value(X))) &&
1433 match(Op1, m_Intrinsic<Intrinsic::cos>(m_Specific(X)));
1434 bool IsCot =
1435 !IsTan && match(Op0, m_Intrinsic<Intrinsic::cos>(m_Value(X))) &&
1436 match(Op1, m_Intrinsic<Intrinsic::sin>(m_Specific(X)));
Dmitry Venikove5fbf592018-01-11 06:33:00 +00001437
Sanjay Patel65da14d2018-02-16 16:13:20 +00001438 if ((IsTan || IsCot) && hasUnaryFloatFn(&TLI, I.getType(), LibFunc_tan,
1439 LibFunc_tanf, LibFunc_tanl)) {
1440 IRBuilder<> B(&I);
1441 IRBuilder<>::FastMathFlagGuard FMFGuard(B);
1442 B.setFastMathFlags(I.getFastMathFlags());
1443 AttributeList Attrs = CallSite(Op0).getCalledFunction()->getAttributes();
1444 Value *Res = emitUnaryFloatFnCall(X, TLI.getName(LibFunc_tan), B, Attrs);
1445 if (IsCot)
1446 Res = B.CreateFDiv(ConstantFP::get(I.getType(), 1.0), Res);
1447 return replaceInstUsesWith(I, Res);
Dmitry Venikove5fbf592018-01-11 06:33:00 +00001448 }
1449 }
1450
Sanjay Patel1998cc62018-02-12 18:38:35 +00001451 // -X / -Y -> X / Y
1452 Value *X, *Y;
1453 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y)))) {
1454 I.setOperand(0, X);
1455 I.setOperand(1, Y);
Matt Arsenaultfdb78f82017-01-10 23:08:54 +00001456 return &I;
1457 }
1458
Sanjay Patel4a4f35f2018-02-12 19:39:21 +00001459 // X / (X * Y) --> 1.0 / Y
1460 // Reassociate to (X / X -> 1.0) is legal when NaNs are not allowed.
1461 // We can ignore the possibility that X is infinity because INF/INF is NaN.
1462 if (I.hasNoNaNs() && I.hasAllowReassoc() &&
1463 match(Op1, m_c_FMul(m_Specific(Op0), m_Value(Y)))) {
1464 I.setOperand(0, ConstantFP::get(I.getType(), 1.0));
1465 I.setOperand(1, Y);
1466 return &I;
1467 }
1468
Craig Topperf40110f2014-04-25 05:29:35 +00001469 return nullptr;
Frits van Bommel2a559512011-01-29 17:50:27 +00001470}
1471
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001472/// This function implements the transforms common to both integer remainder
1473/// instructions (urem and srem). It is called by the visitors to those integer
1474/// remainder instructions.
1475/// @brief Common integer remainder transforms
1476Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
1477 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1478
Chris Lattner7c99f192011-05-22 18:18:41 +00001479 // The RHS is known non-zero.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001480 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I)) {
Chris Lattner7c99f192011-05-22 18:18:41 +00001481 I.setOperand(1, V);
1482 return &I;
1483 }
1484
Duncan Sandsa3e36992011-05-02 16:27:02 +00001485 // Handle cases involving: rem X, (select Cond, Y, Z)
Sanjay Patelae2e3a42017-10-06 23:20:16 +00001486 if (simplifyDivRemOfSelectWithZeroOp(I))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001487 return &I;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001488
Benjamin Kramer72196f32014-01-19 15:24:22 +00001489 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001490 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1491 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1492 if (Instruction *R = FoldOpIntoSelect(I, SI))
1493 return R;
Craig Topperfb71b7d2017-04-14 19:20:12 +00001494 } else if (auto *PN = dyn_cast<PHINode>(Op0I)) {
Sanjoy Dasb7e861a2016-06-05 21:17:04 +00001495 const APInt *Op1Int;
1496 if (match(Op1, m_APInt(Op1Int)) && !Op1Int->isMinValue() &&
1497 (I.getOpcode() == Instruction::URem ||
1498 !Op1Int->isMinSignedValue())) {
Craig Topperfb71b7d2017-04-14 19:20:12 +00001499 // foldOpIntoPhi will speculate instructions to the end of the PHI's
Sanjoy Dasb7e861a2016-06-05 21:17:04 +00001500 // predecessor blocks, so do this only if we know the srem or urem
1501 // will not fault.
Craig Topperfb71b7d2017-04-14 19:20:12 +00001502 if (Instruction *NV = foldOpIntoPhi(I, PN))
Sanjoy Dasb7e861a2016-06-05 21:17:04 +00001503 return NV;
1504 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001505 }
1506
1507 // See if we can fold away this rem instruction.
1508 if (SimplifyDemandedInstructionBits(I))
1509 return &I;
1510 }
1511 }
1512
Craig Topperf40110f2014-04-25 05:29:35 +00001513 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001514}
1515
1516Instruction *InstCombiner::visitURem(BinaryOperator &I) {
1517 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1518
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001519 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001520 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001521
Craig Toppera4205622017-06-09 03:21:29 +00001522 if (Value *V = SimplifyURemInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001523 return replaceInstUsesWith(I, V);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001524
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001525 if (Instruction *common = commonIRemTransforms(I))
1526 return common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001527
Sanjay Patelbb789382017-08-24 22:54:01 +00001528 if (Instruction *NarrowRem = narrowUDivURem(I, Builder))
1529 return NarrowRem;
David Majnemer6c30f492013-05-12 00:07:05 +00001530
David Majnemer470b0772013-05-11 09:01:28 +00001531 // X urem Y -> X and Y-1, where Y is a power of 2,
Craig Topperd4039f72017-05-25 21:51:12 +00001532 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/ true, 0, &I)) {
Chris Lattner6b657ae2011-02-10 05:36:31 +00001533 Constant *N1 = Constant::getAllOnesValue(I.getType());
Craig Topperbb4069e2017-07-07 23:16:26 +00001534 Value *Add = Builder.CreateAdd(Op1, N1);
Chris Lattner6b657ae2011-02-10 05:36:31 +00001535 return BinaryOperator::CreateAnd(Op0, Add);
1536 }
1537
Nick Lewycky7459be62013-07-13 01:16:47 +00001538 // 1 urem X -> zext(X != 1)
1539 if (match(Op0, m_One())) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001540 Value *Cmp = Builder.CreateICmpNE(Op1, Op0);
1541 Value *Ext = Builder.CreateZExt(Cmp, I.getType());
Sanjay Patel4b198802016-02-01 22:23:39 +00001542 return replaceInstUsesWith(I, Ext);
Nick Lewycky7459be62013-07-13 01:16:47 +00001543 }
1544
Sanjay Patel30ef70b2016-09-22 22:36:26 +00001545 // X urem C -> X < C ? X : X - C, where C >= signbit.
Simon Pilgrim1889f262018-02-08 18:36:01 +00001546 if (match(Op1, m_Negative())) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001547 Value *Cmp = Builder.CreateICmpULT(Op0, Op1);
1548 Value *Sub = Builder.CreateSub(Op0, Op1);
Sanjay Patel30ef70b2016-09-22 22:36:26 +00001549 return SelectInst::Create(Cmp, Op0, Sub);
1550 }
1551
Craig Topperf40110f2014-04-25 05:29:35 +00001552 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001553}
1554
1555Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
1556 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1557
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001558 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001559 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001560
Craig Toppera4205622017-06-09 03:21:29 +00001561 if (Value *V = SimplifySRemInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001562 return replaceInstUsesWith(I, V);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001563
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001564 // Handle the integer rem common cases
1565 if (Instruction *Common = commonIRemTransforms(I))
1566 return Common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001567
David Majnemerdb077302014-10-13 22:37:51 +00001568 {
1569 const APInt *Y;
1570 // X % -Y -> X % Y
Simon Pilgrima54e8e42018-02-08 19:00:45 +00001571 if (match(Op1, m_Negative(Y)) && !Y->isMinSignedValue()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001572 Worklist.AddValue(I.getOperand(1));
David Majnemerdb077302014-10-13 22:37:51 +00001573 I.setOperand(1, ConstantInt::get(I.getType(), -*Y));
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001574 return &I;
1575 }
David Majnemerdb077302014-10-13 22:37:51 +00001576 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001577
1578 // If the sign bits of both operands are zero (i.e. we can prove they are
1579 // unsigned inputs), turn this into a urem.
Craig Topperbcfd2d12017-04-20 16:56:25 +00001580 APInt Mask(APInt::getSignMask(I.getType()->getScalarSizeInBits()));
Craig Topper1a18a7c2017-04-17 01:51:24 +00001581 if (MaskedValueIsZero(Op1, Mask, 0, &I) &&
1582 MaskedValueIsZero(Op0, Mask, 0, &I)) {
1583 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
1584 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001585 }
1586
1587 // If it's a constant vector, flip any negative values positive.
Chris Lattner0256be92012-01-27 03:08:05 +00001588 if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
1589 Constant *C = cast<Constant>(Op1);
1590 unsigned VWidth = C->getType()->getVectorNumElements();
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001591
1592 bool hasNegative = false;
Chris Lattner0256be92012-01-27 03:08:05 +00001593 bool hasMissing = false;
1594 for (unsigned i = 0; i != VWidth; ++i) {
1595 Constant *Elt = C->getAggregateElement(i);
Craig Topperf40110f2014-04-25 05:29:35 +00001596 if (!Elt) {
Chris Lattner0256be92012-01-27 03:08:05 +00001597 hasMissing = true;
1598 break;
1599 }
1600
1601 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
Chris Lattnerb1a15122011-07-15 06:08:15 +00001602 if (RHS->isNegative())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001603 hasNegative = true;
Chris Lattner0256be92012-01-27 03:08:05 +00001604 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001605
Chris Lattner0256be92012-01-27 03:08:05 +00001606 if (hasNegative && !hasMissing) {
Chris Lattner47a86bd2012-01-25 06:02:56 +00001607 SmallVector<Constant *, 16> Elts(VWidth);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001608 for (unsigned i = 0; i != VWidth; ++i) {
Chris Lattner8213c8a2012-02-06 21:56:39 +00001609 Elts[i] = C->getAggregateElement(i); // Handle undef, etc.
Chris Lattner0256be92012-01-27 03:08:05 +00001610 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
Chris Lattnerb1a15122011-07-15 06:08:15 +00001611 if (RHS->isNegative())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001612 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001613 }
1614 }
1615
1616 Constant *NewRHSV = ConstantVector::get(Elts);
Chris Lattner0256be92012-01-27 03:08:05 +00001617 if (NewRHSV != C) { // Don't loop on -MININT
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001618 Worklist.AddValue(I.getOperand(1));
1619 I.setOperand(1, NewRHSV);
1620 return &I;
1621 }
1622 }
1623 }
1624
Craig Topperf40110f2014-04-25 05:29:35 +00001625 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001626}
1627
1628Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Duncan Sandsa3e36992011-05-02 16:27:02 +00001629 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001630
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001631 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001632 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001633
Craig Toppera4205622017-06-09 03:21:29 +00001634 if (Value *V = SimplifyFRemInst(Op0, Op1, I.getFastMathFlags(),
1635 SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001636 return replaceInstUsesWith(I, V);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001637
Craig Topperf40110f2014-04-25 05:29:35 +00001638 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001639}