blob: 3cd24035f3db44de257cd8d1f9f3f9cd5da895cc [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 Pilgrim0b9f3912018-02-08 14:10:01 +0000105 if (const auto *CI = dyn_cast<ConstantInt>(C))
Simon Pilgrim4039dbe2018-02-08 14:24:26 +0000106 if (match(CI, m_APInt(IVal)) && IVal->isPowerOf2())
Simon Pilgrim0b9f3912018-02-08 14:10:01 +0000107 return ConstantInt::get(Ty, IVal->logBase2());
Rafael Espindola65281bf2013-05-31 14:27:15 +0000108
Simon Pilgrim0b9f3912018-02-08 14:10:01 +0000109 if (!Ty->isVectorTy())
110 return nullptr;
111
112 SmallVector<Constant *, 4> Elts;
113 for (unsigned I = 0, E = Ty->getVectorNumElements(); I != E; ++I) {
114 Constant *Elt = C->getAggregateElement(I);
115 if (!Elt)
116 return nullptr;
117 if (isa<UndefValue>(Elt)) {
118 Elts.push_back(UndefValue::get(Ty->getScalarType()));
119 continue;
120 }
Rafael Espindola65281bf2013-05-31 14:27:15 +0000121 if (!match(Elt, m_APInt(IVal)) || !IVal->isPowerOf2())
Craig Topperf40110f2014-04-25 05:29:35 +0000122 return nullptr;
Simon Pilgrim0b9f3912018-02-08 14:10:01 +0000123 Elts.push_back(ConstantInt::get(Ty->getScalarType(), IVal->logBase2()));
Rafael Espindola65281bf2013-05-31 14:27:15 +0000124 }
125
126 return ConstantVector::get(Elts);
127}
128
David Majnemer54c2ca22014-12-26 09:10:14 +0000129/// \brief Return true if we can prove that:
130/// (mul LHS, RHS) === (mul nsw LHS, RHS)
Craig Topper2b1fc322017-05-22 06:25:31 +0000131bool InstCombiner::willNotOverflowSignedMul(const Value *LHS,
132 const Value *RHS,
133 const Instruction &CxtI) const {
David Majnemer54c2ca22014-12-26 09:10:14 +0000134 // Multiplying n * m significant bits yields a result of n + m significant
135 // bits. If the total number of significant bits does not exceed the
136 // result bit width (minus 1), there is no overflow.
137 // This means if we have enough leading sign bits in the operands
138 // we can guarantee that the result does not overflow.
139 // Ref: "Hacker's Delight" by Henry Warren
140 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
141
142 // Note that underestimating the number of sign bits gives a more
143 // conservative answer.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000144 unsigned SignBits =
145 ComputeNumSignBits(LHS, 0, &CxtI) + ComputeNumSignBits(RHS, 0, &CxtI);
David Majnemer54c2ca22014-12-26 09:10:14 +0000146
147 // First handle the easy case: if we have enough sign bits there's
148 // definitely no overflow.
149 if (SignBits > BitWidth + 1)
150 return true;
151
152 // There are two ambiguous cases where there can be no overflow:
153 // SignBits == BitWidth + 1 and
154 // SignBits == BitWidth
155 // The second case is difficult to check, therefore we only handle the
156 // first case.
157 if (SignBits == BitWidth + 1) {
158 // It overflows only when both arguments are negative and the true
159 // product is exactly the minimum negative number.
160 // E.g. mul i16 with 17 sign bits: 0xff00 * 0xff80 = 0x8000
161 // For simplicity we just check if at least one side is not negative.
Craig Topper1a36b7d2017-05-15 06:39:41 +0000162 KnownBits LHSKnown = computeKnownBits(LHS, /*Depth=*/0, &CxtI);
163 KnownBits RHSKnown = computeKnownBits(RHS, /*Depth=*/0, &CxtI);
164 if (LHSKnown.isNonNegative() || RHSKnown.isNonNegative())
David Majnemer54c2ca22014-12-26 09:10:14 +0000165 return true;
166 }
167 return false;
168}
169
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000170Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +0000171 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000172 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
173
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000174 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +0000175 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000176
Craig Toppera4205622017-06-09 03:21:29 +0000177 if (Value *V = SimplifyMulInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +0000178 return replaceInstUsesWith(I, V);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000179
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000180 if (Value *V = SimplifyUsingDistributiveLaws(I))
Sanjay Patel4b198802016-02-01 22:23:39 +0000181 return replaceInstUsesWith(I, V);
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000182
David Majnemer027bc802014-11-22 04:52:38 +0000183 // X * -1 == 0 - X
184 if (match(Op1, m_AllOnes())) {
185 BinaryOperator *BO = BinaryOperator::CreateNeg(Op0, I.getName());
186 if (I.hasNoSignedWrap())
187 BO->setHasNoSignedWrap();
188 return BO;
189 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000190
Rafael Espindola65281bf2013-05-31 14:27:15 +0000191 // Also allow combining multiply instructions on vectors.
192 {
193 Value *NewOp;
194 Constant *C1, *C2;
195 const APInt *IVal;
196 if (match(&I, m_Mul(m_Shl(m_Value(NewOp), m_Constant(C2)),
197 m_Constant(C1))) &&
David Majnemerfd4a6d22014-11-22 04:52:52 +0000198 match(C1, m_APInt(IVal))) {
199 // ((X << C2)*C1) == (X * (C1 << C2))
200 Constant *Shl = ConstantExpr::getShl(C1, C2);
201 BinaryOperator *Mul = cast<BinaryOperator>(I.getOperand(0));
202 BinaryOperator *BO = BinaryOperator::CreateMul(NewOp, Shl);
203 if (I.hasNoUnsignedWrap() && Mul->hasNoUnsignedWrap())
204 BO->setHasNoUnsignedWrap();
205 if (I.hasNoSignedWrap() && Mul->hasNoSignedWrap() &&
206 Shl->isNotMinSignedValue())
207 BO->setHasNoSignedWrap();
208 return BO;
209 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000210
Rafael Espindola65281bf2013-05-31 14:27:15 +0000211 if (match(&I, m_Mul(m_Value(NewOp), m_Constant(C1)))) {
Simon Pilgrim0b9f3912018-02-08 14:10:01 +0000212 // Replace X*(2^C) with X << C, where C is either a scalar or a vector.
213 if (Constant *NewCst = getLogBase2(NewOp->getType(), C1)) {
David Majnemer45951a62015-04-18 04:41:30 +0000214 unsigned Width = NewCst->getType()->getPrimitiveSizeInBits();
Rafael Espindola65281bf2013-05-31 14:27:15 +0000215 BinaryOperator *Shl = BinaryOperator::CreateShl(NewOp, NewCst);
Tilmann Scheller2bc5cb62014-10-07 10:19:34 +0000216
Tilmann Scheller2bc5cb62014-10-07 10:19:34 +0000217 if (I.hasNoUnsignedWrap())
218 Shl->setHasNoUnsignedWrap();
David Majnemer45951a62015-04-18 04:41:30 +0000219 if (I.hasNoSignedWrap()) {
Craig Topper5fe01972017-06-27 19:57:53 +0000220 const APInt *V;
221 if (match(NewCst, m_APInt(V)) && *V != Width - 1)
David Majnemer45951a62015-04-18 04:41:30 +0000222 Shl->setHasNoSignedWrap();
223 }
Tilmann Scheller2bc5cb62014-10-07 10:19:34 +0000224
Rafael Espindola65281bf2013-05-31 14:27:15 +0000225 return Shl;
226 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000227 }
Rafael Espindola65281bf2013-05-31 14:27:15 +0000228 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000229
Rafael Espindola65281bf2013-05-31 14:27:15 +0000230 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Stuart Hastings23804832011-06-01 16:42:47 +0000231 // (Y - X) * (-(2**n)) -> (X - Y) * (2**n), for positive nonzero n
232 // (Y + const) * (-(2**n)) -> (-constY) * (2**n), for positive nonzero n
233 // The "* (2**n)" thus becomes a potential shifting opportunity.
Stuart Hastings82843742011-05-30 20:00:33 +0000234 {
235 const APInt & Val = CI->getValue();
236 const APInt &PosVal = Val.abs();
237 if (Val.isNegative() && PosVal.isPowerOf2()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000238 Value *X = nullptr, *Y = nullptr;
Stuart Hastings23804832011-06-01 16:42:47 +0000239 if (Op0->hasOneUse()) {
240 ConstantInt *C1;
Craig Topperf40110f2014-04-25 05:29:35 +0000241 Value *Sub = nullptr;
Stuart Hastings23804832011-06-01 16:42:47 +0000242 if (match(Op0, m_Sub(m_Value(Y), m_Value(X))))
Craig Topperbb4069e2017-07-07 23:16:26 +0000243 Sub = Builder.CreateSub(X, Y, "suba");
Stuart Hastings23804832011-06-01 16:42:47 +0000244 else if (match(Op0, m_Add(m_Value(Y), m_ConstantInt(C1))))
Craig Topperbb4069e2017-07-07 23:16:26 +0000245 Sub = Builder.CreateSub(Builder.CreateNeg(C1), Y, "subc");
Stuart Hastings23804832011-06-01 16:42:47 +0000246 if (Sub)
247 return
248 BinaryOperator::CreateMul(Sub,
249 ConstantInt::get(Y->getType(), PosVal));
Stuart Hastings82843742011-05-30 20:00:33 +0000250 }
251 }
252 }
Chris Lattner6b657ae2011-02-10 05:36:31 +0000253 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000254
Chris Lattner6b657ae2011-02-10 05:36:31 +0000255 // Simplify mul instructions with a constant RHS.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000256 if (isa<Constant>(Op1)) {
Sanjay Pateldb0938f2017-01-10 23:49:07 +0000257 if (Instruction *FoldedMul = foldOpWithConstantIntoOperand(I))
258 return FoldedMul;
Benjamin Kramer72196f32014-01-19 15:24:22 +0000259
260 // Canonicalize (X+C1)*CI -> X*CI+C1*CI.
261 {
262 Value *X;
263 Constant *C1;
264 if (match(Op0, m_OneUse(m_Add(m_Value(X), m_Constant(C1))))) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000265 Value *Mul = Builder.CreateMul(C1, Op1);
David Majnemer6cf6c052014-06-19 07:14:33 +0000266 // Only go forward with the transform if C1*CI simplifies to a tidier
267 // constant.
268 if (!match(Mul, m_Mul(m_Value(), m_Value())))
Craig Topperbb4069e2017-07-07 23:16:26 +0000269 return BinaryOperator::CreateAdd(Builder.CreateMul(X, Op1), Mul);
Benjamin Kramer72196f32014-01-19 15:24:22 +0000270 }
271 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000272 }
273
David Majnemer8279a7502014-11-22 07:25:19 +0000274 if (Value *Op0v = dyn_castNegVal(Op0)) { // -X * -Y = X*Y
275 if (Value *Op1v = dyn_castNegVal(Op1)) {
276 BinaryOperator *BO = BinaryOperator::CreateMul(Op0v, Op1v);
277 if (I.hasNoSignedWrap() &&
278 match(Op0, m_NSWSub(m_Value(), m_Value())) &&
279 match(Op1, m_NSWSub(m_Value(), m_Value())))
280 BO->setHasNoSignedWrap();
281 return BO;
282 }
283 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000284
285 // (X / Y) * Y = X - (X % Y)
286 // (X / Y) * -Y = (X % Y) - X
287 {
Sanjay Patela0a56822017-03-14 17:27:27 +0000288 Value *Y = Op1;
289 BinaryOperator *Div = dyn_cast<BinaryOperator>(Op0);
290 if (!Div || (Div->getOpcode() != Instruction::UDiv &&
291 Div->getOpcode() != Instruction::SDiv)) {
292 Y = Op0;
293 Div = dyn_cast<BinaryOperator>(Op1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000294 }
Sanjay Patela0a56822017-03-14 17:27:27 +0000295 Value *Neg = dyn_castNegVal(Y);
296 if (Div && Div->hasOneUse() &&
297 (Div->getOperand(1) == Y || Div->getOperand(1) == Neg) &&
298 (Div->getOpcode() == Instruction::UDiv ||
299 Div->getOpcode() == Instruction::SDiv)) {
300 Value *X = Div->getOperand(0), *DivOp1 = Div->getOperand(1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000301
Chris Lattner35315d02011-02-06 21:44:57 +0000302 // If the division is exact, X % Y is zero, so we end up with X or -X.
Sanjay Patela0a56822017-03-14 17:27:27 +0000303 if (Div->isExact()) {
304 if (DivOp1 == Y)
305 return replaceInstUsesWith(I, X);
306 return BinaryOperator::CreateNeg(X);
307 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000308
Sanjay Patela0a56822017-03-14 17:27:27 +0000309 auto RemOpc = Div->getOpcode() == Instruction::UDiv ? Instruction::URem
310 : Instruction::SRem;
Craig Topperbb4069e2017-07-07 23:16:26 +0000311 Value *Rem = Builder.CreateBinOp(RemOpc, X, DivOp1);
Sanjay Patela0a56822017-03-14 17:27:27 +0000312 if (DivOp1 == Y)
313 return BinaryOperator::CreateSub(X, Rem);
314 return BinaryOperator::CreateSub(Rem, X);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000315 }
316 }
317
318 /// i1 mul -> i1 and.
Craig Topperfde47232017-07-09 07:04:03 +0000319 if (I.getType()->isIntOrIntVectorTy(1))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000320 return BinaryOperator::CreateAnd(Op0, Op1);
321
322 // X*(1 << Y) --> X << Y
323 // (1 << Y)*X --> X << Y
324 {
325 Value *Y;
David Majnemer546f8102014-11-22 08:57:02 +0000326 BinaryOperator *BO = nullptr;
327 bool ShlNSW = false;
328 if (match(Op0, m_Shl(m_One(), m_Value(Y)))) {
329 BO = BinaryOperator::CreateShl(Op1, Y);
David Majnemer087dc8b2015-01-04 07:36:02 +0000330 ShlNSW = cast<ShlOperator>(Op0)->hasNoSignedWrap();
David Majnemer8e6f6a92014-11-24 16:41:13 +0000331 } else if (match(Op1, m_Shl(m_One(), m_Value(Y)))) {
David Majnemer546f8102014-11-22 08:57:02 +0000332 BO = BinaryOperator::CreateShl(Op0, Y);
David Majnemer087dc8b2015-01-04 07:36:02 +0000333 ShlNSW = cast<ShlOperator>(Op1)->hasNoSignedWrap();
David Majnemer546f8102014-11-22 08:57:02 +0000334 }
335 if (BO) {
336 if (I.hasNoUnsignedWrap())
337 BO->setHasNoUnsignedWrap();
338 if (I.hasNoSignedWrap() && ShlNSW)
339 BO->setHasNoSignedWrap();
340 return BO;
341 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000342 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000343
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000344 // If one of the operands of the multiply is a cast from a boolean value, then
345 // we know the bool is either zero or one, so this is a 'masking' multiply.
346 // X * Y (where Y is 0 or 1) -> X & (0-Y)
Duncan Sands19d0b472010-02-16 11:11:14 +0000347 if (!I.getType()->isVectorTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000348 // -2 is "-1 << 1" so it is all bits set except the low one.
349 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000350
Craig Topperf40110f2014-04-25 05:29:35 +0000351 Value *BoolCast = nullptr, *OtherOp = nullptr;
Richard Trieu7a083812016-02-18 22:09:30 +0000352 if (MaskedValueIsZero(Op0, Negative2, 0, &I)) {
353 BoolCast = Op0;
354 OtherOp = Op1;
355 } else if (MaskedValueIsZero(Op1, Negative2, 0, &I)) {
356 BoolCast = Op1;
357 OtherOp = Op0;
358 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000359
360 if (BoolCast) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000361 Value *V = Builder.CreateSub(Constant::getNullValue(I.getType()),
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000362 BoolCast);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000363 return BinaryOperator::CreateAnd(V, OtherOp);
364 }
365 }
366
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
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000481static bool isFiniteNonZeroFp(Constant *C) {
482 if (C->getType()->isVectorTy()) {
483 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
484 ++I) {
Michael Kupersteinbcb26d62015-03-05 08:38:57 +0000485 ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(C->getAggregateElement(I));
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000486 if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
487 return false;
488 }
489 return true;
490 }
491
492 return isa<ConstantFP>(C) &&
493 cast<ConstantFP>(C)->getValueAPF().isFiniteNonZero();
494}
495
496static bool isNormalFp(Constant *C) {
497 if (C->getType()->isVectorTy()) {
498 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
499 ++I) {
Michael Kupersteinbcb26d62015-03-05 08:38:57 +0000500 ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(C->getAggregateElement(I));
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000501 if (!CFP || !CFP->getValueAPF().isNormal())
502 return false;
503 }
504 return true;
505 }
506
507 return isa<ConstantFP>(C) && cast<ConstantFP>(C)->getValueAPF().isNormal();
508}
509
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000510/// Helper function of InstCombiner::visitFMul(BinaryOperator(). It returns
511/// true iff the given value is FMul or FDiv with one and only one operand
512/// being a normal constant (i.e. not Zero/NaN/Infinity).
513static bool isFMulOrFDivWithConstant(Value *V) {
514 Instruction *I = dyn_cast<Instruction>(V);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000515 if (!I || (I->getOpcode() != Instruction::FMul &&
Shuxin Yang80138662013-01-07 22:41:28 +0000516 I->getOpcode() != Instruction::FDiv))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000517 return false;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000518
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000519 Constant *C0 = dyn_cast<Constant>(I->getOperand(0));
520 Constant *C1 = dyn_cast<Constant>(I->getOperand(1));
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000521
522 if (C0 && C1)
523 return false;
524
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000525 return (C0 && isFiniteNonZeroFp(C0)) || (C1 && isFiniteNonZeroFp(C1));
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000526}
527
528/// foldFMulConst() is a helper routine of InstCombiner::visitFMul().
529/// The input \p FMulOrDiv is a FMul/FDiv with one and only one operand
530/// being a constant (i.e. isFMulOrFDivWithConstant(FMulOrDiv) == true).
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000531/// This function is to simplify "FMulOrDiv * C" and returns the
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000532/// resulting expression. Note that this function could return NULL in
533/// case the constants cannot be folded into a normal floating-point.
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000534Value *InstCombiner::foldFMulConst(Instruction *FMulOrDiv, Constant *C,
Shuxin Yang80138662013-01-07 22:41:28 +0000535 Instruction *InsertBefore) {
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000536 assert(isFMulOrFDivWithConstant(FMulOrDiv) && "V is invalid");
537
538 Value *Opnd0 = FMulOrDiv->getOperand(0);
539 Value *Opnd1 = FMulOrDiv->getOperand(1);
540
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000541 Constant *C0 = dyn_cast<Constant>(Opnd0);
542 Constant *C1 = dyn_cast<Constant>(Opnd1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000543
Craig Topperf40110f2014-04-25 05:29:35 +0000544 BinaryOperator *R = nullptr;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000545
546 // (X * C0) * C => X * (C0*C)
547 if (FMulOrDiv->getOpcode() == Instruction::FMul) {
548 Constant *F = ConstantExpr::getFMul(C1 ? C1 : C0, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000549 if (isNormalFp(F))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000550 R = BinaryOperator::CreateFMul(C1 ? Opnd0 : Opnd1, F);
551 } else {
552 if (C0) {
553 // (C0 / X) * C => (C0 * C) / X
Shuxin Yang3a7ca6e2013-09-19 21:13:46 +0000554 if (FMulOrDiv->hasOneUse()) {
555 // It would otherwise introduce another div.
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000556 Constant *F = ConstantExpr::getFMul(C0, C);
Shuxin Yang3a7ca6e2013-09-19 21:13:46 +0000557 if (isNormalFp(F))
558 R = BinaryOperator::CreateFDiv(F, Opnd1);
559 }
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000560 } else {
561 // (X / C1) * C => X * (C/C1) if C/C1 is not a denormal
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000562 Constant *F = ConstantExpr::getFDiv(C, C1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000563 if (isNormalFp(F)) {
564 R = BinaryOperator::CreateFMul(Opnd0, F);
565 } else {
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000566 // (X / C1) * C => X / (C1/C)
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000567 Constant *F = ConstantExpr::getFDiv(C1, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000568 if (isNormalFp(F))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000569 R = BinaryOperator::CreateFDiv(Opnd0, F);
570 }
571 }
572 }
573
574 if (R) {
Sanjay Patel629c4112017-11-06 16:27:15 +0000575 R->setFast(true);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000576 InsertNewInstWith(R, *InsertBefore);
577 }
578
579 return R;
580}
581
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000582Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +0000583 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000584 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
585
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000586 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +0000587 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000588
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000589 if (isa<Constant>(Op0))
590 std::swap(Op0, Op1);
591
Craig Toppera4205622017-06-09 03:21:29 +0000592 if (Value *V = SimplifyFMulInst(Op0, Op1, I.getFastMathFlags(),
593 SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +0000594 return replaceInstUsesWith(I, V);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000595
Sanjay Patel629c4112017-11-06 16:27:15 +0000596 bool AllowReassociate = I.isFast();
Shuxin Yange8227452013-01-15 21:09:32 +0000597
Michael Ilsemand5787be2012-12-12 00:28:32 +0000598 // Simplify mul instructions with a constant RHS.
599 if (isa<Constant>(Op1)) {
Sanjay Pateldb0938f2017-01-10 23:49:07 +0000600 if (Instruction *FoldedMul = foldOpWithConstantIntoOperand(I))
601 return FoldedMul;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000602
Owen Andersonf74cfe02014-01-16 20:36:42 +0000603 // (fmul X, -1.0) --> (fsub -0.0, X)
Benjamin Kramerfea9ac92014-01-18 16:43:14 +0000604 if (match(Op1, m_SpecificFP(-1.0))) {
605 Constant *NegZero = ConstantFP::getNegativeZero(Op1->getType());
606 Instruction *RI = BinaryOperator::CreateFSub(NegZero, Op0);
Owen Andersonf74cfe02014-01-16 20:36:42 +0000607 RI->copyFastMathFlags(&I);
608 return RI;
609 }
610
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000611 Constant *C = cast<Constant>(Op1);
612 if (AllowReassociate && isFiniteNonZeroFp(C)) {
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000613 // Let MDC denote an expression in one of these forms:
614 // X * C, C/X, X/C, where C is a constant.
615 //
616 // Try to simplify "MDC * Constant"
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000617 if (isFMulOrFDivWithConstant(Op0))
618 if (Value *V = foldFMulConst(cast<Instruction>(Op0), C, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +0000619 return replaceInstUsesWith(I, V);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000620
Quentin Colombete684a6d2013-02-28 21:12:40 +0000621 // (MDC +/- C1) * C => (MDC * C) +/- (C1 * C)
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000622 Instruction *FAddSub = dyn_cast<Instruction>(Op0);
623 if (FAddSub &&
624 (FAddSub->getOpcode() == Instruction::FAdd ||
625 FAddSub->getOpcode() == Instruction::FSub)) {
626 Value *Opnd0 = FAddSub->getOperand(0);
627 Value *Opnd1 = FAddSub->getOperand(1);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000628 Constant *C0 = dyn_cast<Constant>(Opnd0);
629 Constant *C1 = dyn_cast<Constant>(Opnd1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000630 bool Swap = false;
631 if (C0) {
Shuxin Yang80138662013-01-07 22:41:28 +0000632 std::swap(C0, C1);
633 std::swap(Opnd0, Opnd1);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000634 Swap = true;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000635 }
636
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000637 if (C1 && isFiniteNonZeroFp(C1) && isFMulOrFDivWithConstant(Opnd0)) {
Quentin Colombete684a6d2013-02-28 21:12:40 +0000638 Value *M1 = ConstantExpr::getFMul(C1, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000639 Value *M0 = isNormalFp(cast<Constant>(M1)) ?
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000640 foldFMulConst(cast<Instruction>(Opnd0), C, &I) :
Craig Topperf40110f2014-04-25 05:29:35 +0000641 nullptr;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000642 if (M0 && M1) {
643 if (Swap && FAddSub->getOpcode() == Instruction::FSub)
644 std::swap(M0, M1);
645
Benjamin Kramer67485762013-09-30 15:39:59 +0000646 Instruction *RI = (FAddSub->getOpcode() == Instruction::FAdd)
647 ? BinaryOperator::CreateFAdd(M0, M1)
648 : BinaryOperator::CreateFSub(M0, M1);
Shuxin Yange8227452013-01-15 21:09:32 +0000649 RI->copyFastMathFlags(&I);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000650 return RI;
651 }
652 }
653 }
654 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000655 }
656
Matt Arsenault56c079f2016-01-30 05:02:00 +0000657 if (Op0 == Op1) {
658 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
659 // sqrt(X) * sqrt(X) -> X
660 if (AllowReassociate && II->getIntrinsicID() == Intrinsic::sqrt)
Sanjay Patel4b198802016-02-01 22:23:39 +0000661 return replaceInstUsesWith(I, II->getOperand(0));
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000662
Matt Arsenault56c079f2016-01-30 05:02:00 +0000663 // fabs(X) * fabs(X) -> X * X
664 if (II->getIntrinsicID() == Intrinsic::fabs) {
665 Instruction *FMulVal = BinaryOperator::CreateFMul(II->getOperand(0),
666 II->getOperand(0),
667 I.getName());
668 FMulVal->copyFastMathFlags(&I);
669 return FMulVal;
670 }
671 }
672 }
673
Pedro Artigasd8795042012-11-30 19:09:41 +0000674 // Under unsafe algebra do:
675 // X * log2(0.5*Y) = X*log2(Y) - X
Sanjay Patelb41d4612014-10-02 15:20:45 +0000676 if (AllowReassociate) {
Craig Topperf40110f2014-04-25 05:29:35 +0000677 Value *OpX = nullptr;
678 Value *OpY = nullptr;
Pedro Artigasd8795042012-11-30 19:09:41 +0000679 IntrinsicInst *Log2;
Pedro Artigas993acd02012-11-30 22:07:05 +0000680 detectLog2OfHalf(Op0, OpY, Log2);
681 if (OpY) {
682 OpX = Op1;
683 } else {
684 detectLog2OfHalf(Op1, OpY, Log2);
685 if (OpY) {
686 OpX = Op0;
Pedro Artigasd8795042012-11-30 19:09:41 +0000687 }
688 }
689 // if pattern detected emit alternate sequence
690 if (OpX && OpY) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000691 BuilderTy::FastMathFlagGuard Guard(Builder);
692 Builder.setFastMathFlags(Log2->getFastMathFlags());
Pedro Artigasd8795042012-11-30 19:09:41 +0000693 Log2->setArgOperand(0, OpY);
Craig Topperbb4069e2017-07-07 23:16:26 +0000694 Value *FMulVal = Builder.CreateFMul(OpX, Log2);
695 Value *FSub = Builder.CreateFSub(FMulVal, OpX);
Benjamin Kramer67485762013-09-30 15:39:59 +0000696 FSub->takeName(&I);
Sanjay Patel4b198802016-02-01 22:23:39 +0000697 return replaceInstUsesWith(I, FSub);
Pedro Artigasd8795042012-11-30 19:09:41 +0000698 }
699 }
700
Dmitry Venikova58d8de2018-01-02 05:58:11 +0000701 // sqrt(a) * sqrt(b) -> sqrt(a * b)
Sanjay Patel1998cc62018-02-12 18:38:35 +0000702 if (AllowReassociate && Op0->hasOneUse() && Op1->hasOneUse()) {
Dmitry Venikova58d8de2018-01-02 05:58:11 +0000703 Value *Opnd0 = nullptr;
704 Value *Opnd1 = nullptr;
705 if (match(Op0, m_Intrinsic<Intrinsic::sqrt>(m_Value(Opnd0))) &&
706 match(Op1, m_Intrinsic<Intrinsic::sqrt>(m_Value(Opnd1)))) {
707 BuilderTy::FastMathFlagGuard Guard(Builder);
708 Builder.setFastMathFlags(I.getFastMathFlags());
709 Value *FMulVal = Builder.CreateFMul(Opnd0, Opnd1);
710 Value *Sqrt = Intrinsic::getDeclaration(I.getModule(),
711 Intrinsic::sqrt, I.getType());
712 Value *SqrtCall = Builder.CreateCall(Sqrt, FMulVal);
713 return replaceInstUsesWith(I, SqrtCall);
714 }
715 }
716
Shuxin Yange8227452013-01-15 21:09:32 +0000717 // Handle symmetric situation in a 2-iteration loop
718 Value *Opnd0 = Op0;
719 Value *Opnd1 = Op1;
720 for (int i = 0; i < 2; i++) {
721 bool IgnoreZeroSign = I.hasNoSignedZeros();
722 if (BinaryOperator::isFNeg(Opnd0, IgnoreZeroSign)) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000723 BuilderTy::FastMathFlagGuard Guard(Builder);
724 Builder.setFastMathFlags(I.getFastMathFlags());
Benjamin Kramer67485762013-09-30 15:39:59 +0000725
Shuxin Yange8227452013-01-15 21:09:32 +0000726 Value *N0 = dyn_castFNegVal(Opnd0, IgnoreZeroSign);
727 Value *N1 = dyn_castFNegVal(Opnd1, IgnoreZeroSign);
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000728
Shuxin Yange8227452013-01-15 21:09:32 +0000729 // -X * -Y => X*Y
Owen Andersone8537fc2014-01-16 20:59:41 +0000730 if (N1) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000731 Value *FMul = Builder.CreateFMul(N0, N1);
Owen Andersone8537fc2014-01-16 20:59:41 +0000732 FMul->takeName(&I);
Sanjay Patel4b198802016-02-01 22:23:39 +0000733 return replaceInstUsesWith(I, FMul);
Owen Andersone8537fc2014-01-16 20:59:41 +0000734 }
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000735
Shuxin Yange8227452013-01-15 21:09:32 +0000736 if (Opnd0->hasOneUse()) {
737 // -X * Y => -(X*Y) (Promote negation as high as possible)
Craig Topperbb4069e2017-07-07 23:16:26 +0000738 Value *T = Builder.CreateFMul(N0, Opnd1);
739 Value *Neg = Builder.CreateFNeg(T);
Benjamin Kramer67485762013-09-30 15:39:59 +0000740 Neg->takeName(&I);
Sanjay Patel4b198802016-02-01 22:23:39 +0000741 return replaceInstUsesWith(I, Neg);
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000742 }
743 }
Shuxin Yange8227452013-01-15 21:09:32 +0000744
Quentin Colombetaa103b32017-09-20 17:32:16 +0000745 // Handle specials cases for FMul with selects feeding the operation
746 if (Value *V = SimplifySelectsFeedingBinaryOp(I, Op0, Op1))
747 return replaceInstUsesWith(I, V);
748
Shuxin Yange8227452013-01-15 21:09:32 +0000749 // (X*Y) * X => (X*X) * Y where Y != X
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000750 // The purpose is two-fold:
Shuxin Yange8227452013-01-15 21:09:32 +0000751 // 1) to form a power expression (of X).
752 // 2) potentially shorten the critical path: After transformation, the
753 // latency of the instruction Y is amortized by the expression of X*X,
754 // and therefore Y is in a "less critical" position compared to what it
755 // was before the transformation.
Shuxin Yange8227452013-01-15 21:09:32 +0000756 if (AllowReassociate) {
757 Value *Opnd0_0, *Opnd0_1;
758 if (Opnd0->hasOneUse() &&
759 match(Opnd0, m_FMul(m_Value(Opnd0_0), m_Value(Opnd0_1)))) {
Craig Topperf40110f2014-04-25 05:29:35 +0000760 Value *Y = nullptr;
Shuxin Yange8227452013-01-15 21:09:32 +0000761 if (Opnd0_0 == Opnd1 && Opnd0_1 != Opnd1)
762 Y = Opnd0_1;
763 else if (Opnd0_1 == Opnd1 && Opnd0_0 != Opnd1)
764 Y = Opnd0_0;
765
766 if (Y) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000767 BuilderTy::FastMathFlagGuard Guard(Builder);
768 Builder.setFastMathFlags(I.getFastMathFlags());
769 Value *T = Builder.CreateFMul(Opnd1, Opnd1);
770 Value *R = Builder.CreateFMul(T, Y);
Benjamin Kramer67485762013-09-30 15:39:59 +0000771 R->takeName(&I);
Sanjay Patel4b198802016-02-01 22:23:39 +0000772 return replaceInstUsesWith(I, R);
Shuxin Yange8227452013-01-15 21:09:32 +0000773 }
774 }
775 }
776
777 if (!isa<Constant>(Op1))
778 std::swap(Opnd0, Opnd1);
779 else
780 break;
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000781 }
782
Craig Topperf40110f2014-04-25 05:29:35 +0000783 return Changed ? &I : nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000784}
785
Sanjay Patelae2e3a42017-10-06 23:20:16 +0000786/// Fold a divide or remainder with a select instruction divisor when one of the
787/// select operands is zero. In that case, we can use the other select operand
788/// because div/rem by zero is undefined.
789bool InstCombiner::simplifyDivRemOfSelectWithZeroOp(BinaryOperator &I) {
790 SelectInst *SI = dyn_cast<SelectInst>(I.getOperand(1));
791 if (!SI)
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000792 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000793
Sanjay Patelae2e3a42017-10-06 23:20:16 +0000794 int NonNullOperand;
795 if (match(SI->getTrueValue(), m_Zero()))
796 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
797 NonNullOperand = 2;
798 else if (match(SI->getFalseValue(), m_Zero()))
799 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
800 NonNullOperand = 1;
801 else
802 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000803
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000804 // Change the div/rem to use 'Y' instead of the select.
805 I.setOperand(1, SI->getOperand(NonNullOperand));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000806
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000807 // Okay, we know we replace the operand of the div/rem with 'Y' with no
808 // problem. However, the select, or the condition of the select may have
809 // multiple uses. Based on our knowledge that the operand must be non-zero,
810 // propagate the known value for the select into other uses of it, and
811 // propagate a known value of the condition into its other users.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000812
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000813 // If the select and condition only have a single use, don't bother with this,
814 // early exit.
Sanjay Patelae2e3a42017-10-06 23:20:16 +0000815 Value *SelectCond = SI->getCondition();
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000816 if (SI->use_empty() && SelectCond->hasOneUse())
817 return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000818
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000819 // Scan the current block backward, looking for other uses of SI.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000820 BasicBlock::iterator BBI = I.getIterator(), BBFront = I.getParent()->begin();
Sanjay Patel72d339a2017-10-06 23:43:06 +0000821 Type *CondTy = SelectCond->getType();
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000822 while (BBI != BBFront) {
823 --BBI;
824 // If we found a call to a function, we can't assume it will return, so
825 // information from below it cannot be propagated above it.
826 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
827 break;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000828
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000829 // Replace uses of the select or its condition with the known values.
830 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
831 I != E; ++I) {
832 if (*I == SI) {
833 *I = SI->getOperand(NonNullOperand);
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000834 Worklist.Add(&*BBI);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000835 } else if (*I == SelectCond) {
Sanjay Patel72d339a2017-10-06 23:43:06 +0000836 *I = NonNullOperand == 1 ? ConstantInt::getTrue(CondTy)
837 : ConstantInt::getFalse(CondTy);
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000838 Worklist.Add(&*BBI);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000839 }
840 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000841
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000842 // If we past the instruction, quit looking for it.
843 if (&*BBI == SI)
Craig Topperf40110f2014-04-25 05:29:35 +0000844 SI = nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000845 if (&*BBI == SelectCond)
Craig Topperf40110f2014-04-25 05:29:35 +0000846 SelectCond = nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000847
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000848 // If we ran out of things to eliminate, break out of the loop.
Craig Topperf40110f2014-04-25 05:29:35 +0000849 if (!SelectCond && !SI)
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000850 break;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000851
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000852 }
853 return true;
854}
855
Sanjay Patel1998cc62018-02-12 18:38:35 +0000856/// True if the multiply can not be expressed in an int this size.
857static bool multiplyOverflows(const APInt &C1, const APInt &C2, APInt &Product,
858 bool IsSigned) {
859 bool Overflow;
860 Product = IsSigned ? C1.smul_ov(C2, Overflow) : C1.umul_ov(C2, Overflow);
861 return Overflow;
862}
863
864/// True if C2 is a multiple of C1. Quotient contains C2/C1.
865static bool isMultiple(const APInt &C1, const APInt &C2, APInt &Quotient,
866 bool IsSigned) {
867 assert(C1.getBitWidth() == C2.getBitWidth() && "Constant widths not equal");
868
869 // Bail if we will divide by zero.
870 if (C2.isNullValue())
871 return false;
872
873 // Bail if we would divide INT_MIN by -1.
874 if (IsSigned && C1.isMinSignedValue() && C2.isAllOnesValue())
875 return false;
876
877 APInt Remainder(C1.getBitWidth(), /*Val=*/0ULL, IsSigned);
878 if (IsSigned)
879 APInt::sdivrem(C1, C2, Quotient, Remainder);
880 else
881 APInt::udivrem(C1, C2, Quotient, Remainder);
882
883 return Remainder.isMinValue();
884}
885
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000886/// This function implements the transforms common to both integer division
887/// instructions (udiv and sdiv). It is called by the visitors to those integer
888/// division instructions.
889/// @brief Common integer divide transforms
890Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
891 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Sanjay Patel9530f182018-01-21 16:14:51 +0000892 bool IsSigned = I.getOpcode() == Instruction::SDiv;
Sanjay Patel39059d22018-02-12 14:14:56 +0000893 Type *Ty = I.getType();
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000894
Chris Lattner7c99f192011-05-22 18:18:41 +0000895 // The RHS is known non-zero.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000896 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I)) {
Chris Lattner7c99f192011-05-22 18:18:41 +0000897 I.setOperand(1, V);
898 return &I;
899 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000900
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000901 // Handle cases involving: [su]div X, (select Cond, Y, Z)
902 // This does not apply for fdiv.
Sanjay Patelae2e3a42017-10-06 23:20:16 +0000903 if (simplifyDivRemOfSelectWithZeroOp(I))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000904 return &I;
905
Sanjay Patel1998cc62018-02-12 18:38:35 +0000906 const APInt *C2;
907 if (match(Op1, m_APInt(C2))) {
908 Value *X;
909 const APInt *C1;
David Majnemerf9a095d2014-08-16 08:55:06 +0000910
Sanjay Patel1998cc62018-02-12 18:38:35 +0000911 // (X / C1) / C2 -> X / (C1*C2)
912 if ((IsSigned && match(Op0, m_SDiv(m_Value(X), m_APInt(C1)))) ||
913 (!IsSigned && match(Op0, m_UDiv(m_Value(X), m_APInt(C1))))) {
914 APInt Product(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
915 if (!multiplyOverflows(*C1, *C2, Product, IsSigned))
916 return BinaryOperator::Create(I.getOpcode(), X,
917 ConstantInt::get(Ty, Product));
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000918 }
Sanjay Patel1998cc62018-02-12 18:38:35 +0000919
920 if ((IsSigned && match(Op0, m_NSWMul(m_Value(X), m_APInt(C1)))) ||
921 (!IsSigned && match(Op0, m_NUWMul(m_Value(X), m_APInt(C1))))) {
922 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
923
924 // (X * C1) / C2 -> X / (C2 / C1) if C2 is a multiple of C1.
925 if (isMultiple(*C2, *C1, Quotient, IsSigned)) {
926 auto *NewDiv = BinaryOperator::Create(I.getOpcode(), X,
927 ConstantInt::get(Ty, Quotient));
928 NewDiv->setIsExact(I.isExact());
929 return NewDiv;
930 }
931
932 // (X * C1) / C2 -> X * (C1 / C2) if C1 is a multiple of C2.
933 if (isMultiple(*C1, *C2, Quotient, IsSigned)) {
934 auto *Mul = BinaryOperator::Create(Instruction::Mul, X,
935 ConstantInt::get(Ty, Quotient));
936 auto *OBO = cast<OverflowingBinaryOperator>(Op0);
937 Mul->setHasNoUnsignedWrap(!IsSigned && OBO->hasNoUnsignedWrap());
938 Mul->setHasNoSignedWrap(OBO->hasNoSignedWrap());
939 return Mul;
940 }
941 }
942
943 if ((IsSigned && match(Op0, m_NSWShl(m_Value(X), m_APInt(C1))) &&
944 *C1 != C1->getBitWidth() - 1) ||
945 (!IsSigned && match(Op0, m_NUWShl(m_Value(X), m_APInt(C1))))) {
946 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
947 APInt C1Shifted = APInt::getOneBitSet(
948 C1->getBitWidth(), static_cast<unsigned>(C1->getLimitedValue()));
949
950 // (X << C1) / C2 -> X / (C2 >> C1) if C2 is a multiple of C1.
951 if (isMultiple(*C2, C1Shifted, Quotient, IsSigned)) {
952 auto *BO = BinaryOperator::Create(I.getOpcode(), X,
953 ConstantInt::get(Ty, Quotient));
954 BO->setIsExact(I.isExact());
955 return BO;
956 }
957
958 // (X << C1) / C2 -> X * (C2 >> C1) if C1 is a multiple of C2.
959 if (isMultiple(C1Shifted, *C2, Quotient, IsSigned)) {
960 auto *Mul = BinaryOperator::Create(Instruction::Mul, X,
961 ConstantInt::get(Ty, Quotient));
962 auto *OBO = cast<OverflowingBinaryOperator>(Op0);
963 Mul->setHasNoUnsignedWrap(!IsSigned && OBO->hasNoUnsignedWrap());
964 Mul->setHasNoSignedWrap(OBO->hasNoSignedWrap());
965 return Mul;
966 }
967 }
968
969 if (!C2->isNullValue()) // avoid X udiv 0
970 if (Instruction *FoldedDiv = foldOpWithConstantIntoOperand(I))
971 return FoldedDiv;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000972 }
973
Craig Topper218a3592017-04-17 03:41:47 +0000974 if (match(Op0, m_One())) {
Sanjay Patel39059d22018-02-12 14:14:56 +0000975 assert(!Ty->isIntOrIntVectorTy(1) && "i1 divide not removed?");
976 if (IsSigned) {
Craig Topper218a3592017-04-17 03:41:47 +0000977 // If Op1 is 0 then it's undefined behaviour, if Op1 is 1 then the
978 // result is one, if Op1 is -1 then the result is minus one, otherwise
979 // it's zero.
Craig Topperbb4069e2017-07-07 23:16:26 +0000980 Value *Inc = Builder.CreateAdd(Op1, Op0);
Sanjay Patel39059d22018-02-12 14:14:56 +0000981 Value *Cmp = Builder.CreateICmpULT(Inc, ConstantInt::get(Ty, 3));
982 return SelectInst::Create(Cmp, Op1, ConstantInt::get(Ty, 0));
Craig Topper218a3592017-04-17 03:41:47 +0000983 } else {
984 // If Op1 is 0 then it's undefined behaviour. If Op1 is 1 then the
985 // result is one, otherwise it's zero.
Sanjay Patel39059d22018-02-12 14:14:56 +0000986 return new ZExtInst(Builder.CreateICmpEQ(Op1, Op0), Ty);
Nick Lewyckyf0cf8fa2014-05-14 03:03:05 +0000987 }
988 }
989
Benjamin Kramer57b3df52011-04-30 18:16:00 +0000990 // See if we can fold away this div instruction.
991 if (SimplifyDemandedInstructionBits(I))
992 return &I;
993
Duncan Sands771e82a2011-01-28 16:51:11 +0000994 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
Sanjay Patel9530f182018-01-21 16:14:51 +0000995 Value *X, *Z;
996 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) // (X - Z) / Y; Y = Op1
997 if ((IsSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
998 (!IsSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
Duncan Sands771e82a2011-01-28 16:51:11 +0000999 return BinaryOperator::Create(I.getOpcode(), X, Op1);
Sanjay Patel9530f182018-01-21 16:14:51 +00001000
1001 // (X << Y) / X -> 1 << Y
1002 Value *Y;
1003 if (IsSigned && match(Op0, m_NSWShl(m_Specific(Op1), m_Value(Y))))
Sanjay Patel39059d22018-02-12 14:14:56 +00001004 return BinaryOperator::CreateNSWShl(ConstantInt::get(Ty, 1), Y);
Sanjay Patel9530f182018-01-21 16:14:51 +00001005 if (!IsSigned && match(Op0, m_NUWShl(m_Specific(Op1), m_Value(Y))))
Sanjay Patel39059d22018-02-12 14:14:56 +00001006 return BinaryOperator::CreateNUWShl(ConstantInt::get(Ty, 1), Y);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001007
Sanjay Patel510d6472018-02-11 17:20:32 +00001008 // X / (X * Y) -> 1 / Y if the multiplication does not overflow.
1009 if (match(Op1, m_c_Mul(m_Specific(Op0), m_Value(Y)))) {
1010 bool HasNSW = cast<OverflowingBinaryOperator>(Op1)->hasNoSignedWrap();
1011 bool HasNUW = cast<OverflowingBinaryOperator>(Op1)->hasNoUnsignedWrap();
1012 if ((IsSigned && HasNSW) || (!IsSigned && HasNUW)) {
Sanjay Patel39059d22018-02-12 14:14:56 +00001013 I.setOperand(0, ConstantInt::get(Ty, 1));
Sanjay Patel510d6472018-02-11 17:20:32 +00001014 I.setOperand(1, Y);
1015 return &I;
1016 }
1017 }
1018
Craig Topperf40110f2014-04-25 05:29:35 +00001019 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001020}
1021
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00001022static const unsigned MaxDepth = 6;
1023
David Majnemer37f8f442013-07-04 21:17:49 +00001024namespace {
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00001025
1026using FoldUDivOperandCb = Instruction *(*)(Value *Op0, Value *Op1,
1027 const BinaryOperator &I,
1028 InstCombiner &IC);
David Majnemer37f8f442013-07-04 21:17:49 +00001029
1030/// \brief Used to maintain state for visitUDivOperand().
1031struct UDivFoldAction {
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00001032 /// Informs visitUDiv() how to fold this operand. This can be zero if this
1033 /// action joins two actions together.
1034 FoldUDivOperandCb FoldAction;
David Majnemer37f8f442013-07-04 21:17:49 +00001035
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00001036 /// Which operand to fold.
1037 Value *OperandToFold;
1038
David Majnemer37f8f442013-07-04 21:17:49 +00001039 union {
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00001040 /// The instruction returned when FoldAction is invoked.
1041 Instruction *FoldResult;
David Majnemer37f8f442013-07-04 21:17:49 +00001042
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00001043 /// Stores the LHS action index if this action joins two actions together.
1044 size_t SelectLHSIdx;
David Majnemer37f8f442013-07-04 21:17:49 +00001045 };
1046
1047 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand)
Craig Topperf40110f2014-04-25 05:29:35 +00001048 : FoldAction(FA), OperandToFold(InputOperand), FoldResult(nullptr) {}
David Majnemer37f8f442013-07-04 21:17:49 +00001049 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand, size_t SLHS)
1050 : FoldAction(FA), OperandToFold(InputOperand), SelectLHSIdx(SLHS) {}
1051};
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00001052
1053} // end anonymous namespace
David Majnemer37f8f442013-07-04 21:17:49 +00001054
1055// X udiv 2^C -> X >> C
1056static Instruction *foldUDivPow2Cst(Value *Op0, Value *Op1,
1057 const BinaryOperator &I, InstCombiner &IC) {
Simon Pilgrim94cc89d2018-02-08 14:46:10 +00001058 Constant *C1 = getLogBase2(Op0->getType(), cast<Constant>(Op1));
1059 if (!C1)
1060 llvm_unreachable("Failed to constant fold udiv -> logbase2");
1061 BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, C1);
Suyog Sarda65f5ae92014-10-07 12:04:07 +00001062 if (I.isExact())
1063 LShr->setIsExact();
David Majnemer37f8f442013-07-04 21:17:49 +00001064 return LShr;
1065}
1066
1067// X udiv C, where C >= signbit
1068static Instruction *foldUDivNegCst(Value *Op0, Value *Op1,
1069 const BinaryOperator &I, InstCombiner &IC) {
Simon Pilgrim9620f4b2018-02-09 10:43:59 +00001070 Value *ICI = IC.Builder.CreateICmpULT(Op0, cast<Constant>(Op1));
David Majnemer37f8f442013-07-04 21:17:49 +00001071 return SelectInst::Create(ICI, Constant::getNullValue(I.getType()),
1072 ConstantInt::get(I.getType(), 1));
1073}
1074
1075// X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Andrea Di Biagioa82d52d2016-09-26 12:07:23 +00001076// X udiv (zext (C1 << N)), where C1 is "1<<C2" --> X >> (N+C2)
David Majnemer37f8f442013-07-04 21:17:49 +00001077static Instruction *foldUDivShl(Value *Op0, Value *Op1, const BinaryOperator &I,
1078 InstCombiner &IC) {
Andrea Di Biagioa82d52d2016-09-26 12:07:23 +00001079 Value *ShiftLeft;
1080 if (!match(Op1, m_ZExt(m_Value(ShiftLeft))))
1081 ShiftLeft = Op1;
David Majnemer37f8f442013-07-04 21:17:49 +00001082
Simon Pilgrim2a90acd2018-02-08 15:19:38 +00001083 Constant *CI;
Andrea Di Biagioa82d52d2016-09-26 12:07:23 +00001084 Value *N;
Simon Pilgrim2a90acd2018-02-08 15:19:38 +00001085 if (!match(ShiftLeft, m_Shl(m_Constant(CI), m_Value(N))))
Andrea Di Biagioa82d52d2016-09-26 12:07:23 +00001086 llvm_unreachable("match should never fail here!");
Simon Pilgrim2a90acd2018-02-08 15:19:38 +00001087 Constant *Log2Base = getLogBase2(N->getType(), CI);
1088 if (!Log2Base)
1089 llvm_unreachable("getLogBase2 should never fail here!");
1090 N = IC.Builder.CreateAdd(N, Log2Base);
Andrea Di Biagioa82d52d2016-09-26 12:07:23 +00001091 if (Op1 != ShiftLeft)
Craig Topperbb4069e2017-07-07 23:16:26 +00001092 N = IC.Builder.CreateZExt(N, Op1->getType());
David Majnemer37f8f442013-07-04 21:17:49 +00001093 BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, N);
Suyog Sarda65f5ae92014-10-07 12:04:07 +00001094 if (I.isExact())
1095 LShr->setIsExact();
David Majnemer37f8f442013-07-04 21:17:49 +00001096 return LShr;
1097}
1098
1099// \brief Recursively visits the possible right hand operands of a udiv
1100// instruction, seeing through select instructions, to determine if we can
1101// replace the udiv with something simpler. If we find that an operand is not
1102// able to simplify the udiv, we abort the entire transformation.
1103static size_t visitUDivOperand(Value *Op0, Value *Op1, const BinaryOperator &I,
1104 SmallVectorImpl<UDivFoldAction> &Actions,
1105 unsigned Depth = 0) {
1106 // Check to see if this is an unsigned division with an exact power of 2,
1107 // if so, convert to a right shift.
1108 if (match(Op1, m_Power2())) {
1109 Actions.push_back(UDivFoldAction(foldUDivPow2Cst, Op1));
1110 return Actions.size();
1111 }
1112
Simon Pilgrim9620f4b2018-02-09 10:43:59 +00001113 // X udiv C, where C >= signbit
1114 if (match(Op1, m_Negative())) {
1115 Actions.push_back(UDivFoldAction(foldUDivNegCst, Op1));
1116 return Actions.size();
1117 }
David Majnemer37f8f442013-07-04 21:17:49 +00001118
1119 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
1120 if (match(Op1, m_Shl(m_Power2(), m_Value())) ||
1121 match(Op1, m_ZExt(m_Shl(m_Power2(), m_Value())))) {
1122 Actions.push_back(UDivFoldAction(foldUDivShl, Op1));
1123 return Actions.size();
1124 }
1125
1126 // The remaining tests are all recursive, so bail out if we hit the limit.
1127 if (Depth++ == MaxDepth)
1128 return 0;
1129
1130 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
David Majnemer492e6122014-08-30 09:19:05 +00001131 if (size_t LHSIdx =
1132 visitUDivOperand(Op0, SI->getOperand(1), I, Actions, Depth))
1133 if (visitUDivOperand(Op0, SI->getOperand(2), I, Actions, Depth)) {
1134 Actions.push_back(UDivFoldAction(nullptr, Op1, LHSIdx - 1));
David Majnemer37f8f442013-07-04 21:17:49 +00001135 return Actions.size();
1136 }
1137
1138 return 0;
1139}
1140
Sanjay Patelbb789382017-08-24 22:54:01 +00001141/// If we have zero-extended operands of an unsigned div or rem, we may be able
1142/// to narrow the operation (sink the zext below the math).
1143static Instruction *narrowUDivURem(BinaryOperator &I,
1144 InstCombiner::BuilderTy &Builder) {
1145 Instruction::BinaryOps Opcode = I.getOpcode();
1146 Value *N = I.getOperand(0);
1147 Value *D = I.getOperand(1);
1148 Type *Ty = I.getType();
1149 Value *X, *Y;
1150 if (match(N, m_ZExt(m_Value(X))) && match(D, m_ZExt(m_Value(Y))) &&
1151 X->getType() == Y->getType() && (N->hasOneUse() || D->hasOneUse())) {
1152 // udiv (zext X), (zext Y) --> zext (udiv X, Y)
1153 // urem (zext X), (zext Y) --> zext (urem X, Y)
1154 Value *NarrowOp = Builder.CreateBinOp(Opcode, X, Y);
1155 return new ZExtInst(NarrowOp, Ty);
1156 }
1157
1158 Constant *C;
1159 if ((match(N, m_OneUse(m_ZExt(m_Value(X)))) && match(D, m_Constant(C))) ||
1160 (match(D, m_OneUse(m_ZExt(m_Value(X)))) && match(N, m_Constant(C)))) {
1161 // If the constant is the same in the smaller type, use the narrow version.
1162 Constant *TruncC = ConstantExpr::getTrunc(C, X->getType());
1163 if (ConstantExpr::getZExt(TruncC, Ty) != C)
1164 return nullptr;
1165
1166 // udiv (zext X), C --> zext (udiv X, C')
1167 // urem (zext X), C --> zext (urem X, C')
1168 // udiv C, (zext X) --> zext (udiv C', X)
1169 // urem C, (zext X) --> zext (urem C', X)
1170 Value *NarrowOp = isa<Constant>(D) ? Builder.CreateBinOp(Opcode, X, TruncC)
1171 : Builder.CreateBinOp(Opcode, TruncC, X);
1172 return new ZExtInst(NarrowOp, Ty);
1173 }
1174
1175 return nullptr;
1176}
1177
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001178Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
1179 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1180
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001181 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001182 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001183
Craig Toppera4205622017-06-09 03:21:29 +00001184 if (Value *V = SimplifyUDivInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001185 return replaceInstUsesWith(I, V);
Duncan Sands771e82a2011-01-28 16:51:11 +00001186
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001187 // Handle the integer div common cases
1188 if (Instruction *Common = commonIDivTransforms(I))
1189 return Common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001190
Benjamin Kramerd4a64712012-08-30 15:07:40 +00001191 // (x lshr C1) udiv C2 --> x udiv (C2 << C1)
David Majnemera2521382014-10-13 21:48:30 +00001192 {
Benjamin Kramer9c0a8072012-08-28 13:08:13 +00001193 Value *X;
David Majnemera2521382014-10-13 21:48:30 +00001194 const APInt *C1, *C2;
1195 if (match(Op0, m_LShr(m_Value(X), m_APInt(C1))) &&
1196 match(Op1, m_APInt(C2))) {
1197 bool Overflow;
1198 APInt C2ShlC1 = C2->ushl_ov(*C1, Overflow);
David Majnemera3aeb152014-11-22 18:16:54 +00001199 if (!Overflow) {
1200 bool IsExact = I.isExact() && match(Op0, m_Exact(m_Value()));
1201 BinaryOperator *BO = BinaryOperator::CreateUDiv(
David Majnemera2521382014-10-13 21:48:30 +00001202 X, ConstantInt::get(X->getType(), C2ShlC1));
David Majnemera3aeb152014-11-22 18:16:54 +00001203 if (IsExact)
1204 BO->setIsExact();
1205 return BO;
1206 }
David Majnemera2521382014-10-13 21:48:30 +00001207 }
Nadav Rotem11935b22012-08-28 10:01:43 +00001208 }
1209
Sanjay Patelbb789382017-08-24 22:54:01 +00001210 if (Instruction *NarrowDiv = narrowUDivURem(I, Builder))
1211 return NarrowDiv;
Benjamin Kramer9aa91b12011-04-30 18:16:07 +00001212
David Majnemer37f8f442013-07-04 21:17:49 +00001213 // (LHS udiv (select (select (...)))) -> (LHS >> (select (select (...))))
1214 SmallVector<UDivFoldAction, 6> UDivActions;
1215 if (visitUDivOperand(Op0, Op1, I, UDivActions))
1216 for (unsigned i = 0, e = UDivActions.size(); i != e; ++i) {
1217 FoldUDivOperandCb Action = UDivActions[i].FoldAction;
1218 Value *ActionOp1 = UDivActions[i].OperandToFold;
1219 Instruction *Inst;
1220 if (Action)
1221 Inst = Action(Op0, ActionOp1, I, *this);
1222 else {
1223 // This action joins two actions together. The RHS of this action is
1224 // simply the last action we processed, we saved the LHS action index in
1225 // the joining action.
1226 size_t SelectRHSIdx = i - 1;
1227 Value *SelectRHS = UDivActions[SelectRHSIdx].FoldResult;
1228 size_t SelectLHSIdx = UDivActions[i].SelectLHSIdx;
1229 Value *SelectLHS = UDivActions[SelectLHSIdx].FoldResult;
1230 Inst = SelectInst::Create(cast<SelectInst>(ActionOp1)->getCondition(),
1231 SelectLHS, SelectRHS);
1232 }
1233
1234 // If this is the last action to process, return it to the InstCombiner.
1235 // Otherwise, we insert it before the UDiv and record it so that we may
1236 // use it as part of a joining action (i.e., a SelectInst).
1237 if (e - i != 1) {
1238 Inst->insertBefore(&I);
1239 UDivActions[i].FoldResult = Inst;
1240 } else
1241 return Inst;
1242 }
1243
Craig Topperf40110f2014-04-25 05:29:35 +00001244 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001245}
1246
1247Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
1248 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1249
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001250 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001251 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001252
Craig Toppera4205622017-06-09 03:21:29 +00001253 if (Value *V = SimplifySDivInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001254 return replaceInstUsesWith(I, V);
Duncan Sands771e82a2011-01-28 16:51:11 +00001255
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001256 // Handle the integer div common cases
1257 if (Instruction *Common = commonIDivTransforms(I))
1258 return Common;
1259
Sanjay Patelc6ada532016-06-27 17:25:57 +00001260 const APInt *Op1C;
Sanjay Patelbedd1f92016-06-27 18:38:40 +00001261 if (match(Op1, m_APInt(Op1C))) {
1262 // sdiv X, -1 == -X
1263 if (Op1C->isAllOnesValue())
1264 return BinaryOperator::CreateNeg(Op0);
1265
1266 // sdiv exact X, C --> ashr exact X, log2(C)
1267 if (I.isExact() && Op1C->isNonNegative() && Op1C->isPowerOf2()) {
1268 Value *ShAmt = ConstantInt::get(Op1->getType(), Op1C->exactLogBase2());
1269 return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
1270 }
Sanjay Patel59ed2ff2016-06-27 22:27:11 +00001271
1272 // If the dividend is sign-extended and the constant divisor is small enough
1273 // to fit in the source type, shrink the division to the narrower type:
1274 // (sext X) sdiv C --> sext (X sdiv C)
1275 Value *Op0Src;
1276 if (match(Op0, m_OneUse(m_SExt(m_Value(Op0Src)))) &&
1277 Op0Src->getType()->getScalarSizeInBits() >= Op1C->getMinSignedBits()) {
1278
1279 // In the general case, we need to make sure that the dividend is not the
1280 // minimum signed value because dividing that by -1 is UB. But here, we
1281 // know that the -1 divisor case is already handled above.
1282
1283 Constant *NarrowDivisor =
1284 ConstantExpr::getTrunc(cast<Constant>(Op1), Op0Src->getType());
Craig Topperbb4069e2017-07-07 23:16:26 +00001285 Value *NarrowOp = Builder.CreateSDiv(Op0Src, NarrowDivisor);
Sanjay Patel59ed2ff2016-06-27 22:27:11 +00001286 return new SExtInst(NarrowOp, Op0->getType());
1287 }
Benjamin Kramer72196f32014-01-19 15:24:22 +00001288 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001289
Benjamin Kramer72196f32014-01-19 15:24:22 +00001290 if (Constant *RHS = dyn_cast<Constant>(Op1)) {
David Majnemerf28e2a42014-07-02 06:42:13 +00001291 // X/INT_MIN -> X == INT_MIN
1292 if (RHS->isMinSignedValue())
Craig Topperbb4069e2017-07-07 23:16:26 +00001293 return new ZExtInst(Builder.CreateICmpEQ(Op0, Op1), I.getType());
David Majnemerf28e2a42014-07-02 06:42:13 +00001294
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001295 // -X/C --> X/-C provided the negation doesn't overflow.
David Majnemerfa4699e2014-11-22 20:00:34 +00001296 Value *X;
1297 if (match(Op0, m_NSWSub(m_Zero(), m_Value(X)))) {
1298 auto *BO = BinaryOperator::CreateSDiv(X, ConstantExpr::getNeg(RHS));
1299 BO->setIsExact(I.isExact());
1300 return BO;
1301 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001302 }
1303
1304 // If the sign bits of both operands are zero (i.e. we can prove they are
1305 // unsigned inputs), turn this into a udiv.
Craig Topperbcfd2d12017-04-20 16:56:25 +00001306 APInt Mask(APInt::getSignMask(I.getType()->getScalarSizeInBits()));
Craig Topperf2484682017-04-17 01:51:19 +00001307 if (MaskedValueIsZero(Op0, Mask, 0, &I)) {
1308 if (MaskedValueIsZero(Op1, Mask, 0, &I)) {
1309 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
1310 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1311 BO->setIsExact(I.isExact());
1312 return BO;
1313 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001314
Craig Topperd4039f72017-05-25 21:51:12 +00001315 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/ true, 0, &I)) {
Craig Topperf2484682017-04-17 01:51:19 +00001316 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
1317 // Safe because the only negative value (1 << Y) can take on is
1318 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
1319 // the sign bit set.
1320 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1321 BO->setIsExact(I.isExact());
1322 return BO;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001323 }
1324 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001325
Craig Topperf40110f2014-04-25 05:29:35 +00001326 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001327}
1328
Shuxin Yang320f52a2013-01-14 22:48:41 +00001329/// CvtFDivConstToReciprocal tries to convert X/C into X*1/C if C not a special
1330/// FP value and:
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001331/// 1) 1/C is exact, or
Shuxin Yang320f52a2013-01-14 22:48:41 +00001332/// 2) reciprocal is allowed.
Sylvestre Ledru149e2812013-05-14 23:36:24 +00001333/// If the conversion was successful, the simplified expression "X * 1/C" is
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00001334/// returned; otherwise, nullptr is returned.
Suyog Sardaea205512014-10-07 11:56:06 +00001335static Instruction *CvtFDivConstToReciprocal(Value *Dividend, Constant *Divisor,
Shuxin Yang320f52a2013-01-14 22:48:41 +00001336 bool AllowReciprocal) {
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001337 if (!isa<ConstantFP>(Divisor)) // TODO: handle vectors.
Craig Topperf40110f2014-04-25 05:29:35 +00001338 return nullptr;
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001339
1340 const APFloat &FpVal = cast<ConstantFP>(Divisor)->getValueAPF();
Shuxin Yang320f52a2013-01-14 22:48:41 +00001341 APFloat Reciprocal(FpVal.getSemantics());
1342 bool Cvt = FpVal.getExactInverse(&Reciprocal);
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001343
Michael Gottesman3cb77ab2013-06-19 21:23:18 +00001344 if (!Cvt && AllowReciprocal && FpVal.isFiniteNonZero()) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001345 Reciprocal = APFloat(FpVal.getSemantics(), 1.0f);
1346 (void)Reciprocal.divide(FpVal, APFloat::rmNearestTiesToEven);
1347 Cvt = !Reciprocal.isDenormal();
1348 }
1349
1350 if (!Cvt)
Craig Topperf40110f2014-04-25 05:29:35 +00001351 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001352
1353 ConstantFP *R;
1354 R = ConstantFP::get(Dividend->getType()->getContext(), Reciprocal);
1355 return BinaryOperator::CreateFMul(Dividend, R);
1356}
1357
Frits van Bommel2a559512011-01-29 17:50:27 +00001358Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
1359 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1360
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001361 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001362 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001363
Craig Toppera4205622017-06-09 03:21:29 +00001364 if (Value *V = SimplifyFDivInst(Op0, Op1, I.getFastMathFlags(),
1365 SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001366 return replaceInstUsesWith(I, V);
Frits van Bommel2a559512011-01-29 17:50:27 +00001367
Stephen Lina9b57f62013-07-20 07:13:13 +00001368 if (isa<Constant>(Op0))
1369 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1370 if (Instruction *R = FoldOpIntoSelect(I, SI))
1371 return R;
1372
Sanjay Patel629c4112017-11-06 16:27:15 +00001373 bool AllowReassociate = I.isFast();
Shuxin Yang320f52a2013-01-14 22:48:41 +00001374 bool AllowReciprocal = I.hasAllowReciprocal();
Benjamin Kramer8564e0d2011-03-30 15:42:35 +00001375
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001376 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Stephen Lina9b57f62013-07-20 07:13:13 +00001377 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1378 if (Instruction *R = FoldOpIntoSelect(I, SI))
1379 return R;
1380
Shuxin Yang320f52a2013-01-14 22:48:41 +00001381 if (AllowReassociate) {
Craig Topperf40110f2014-04-25 05:29:35 +00001382 Constant *C1 = nullptr;
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001383 Constant *C2 = Op1C;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001384 Value *X;
Craig Topperf40110f2014-04-25 05:29:35 +00001385 Instruction *Res = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001386
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001387 if (match(Op0, m_FMul(m_Value(X), m_Constant(C1)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001388 // (X*C1)/C2 => X * (C1/C2)
1389 //
1390 Constant *C = ConstantExpr::getFDiv(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001391 if (isNormalFp(C))
Shuxin Yang320f52a2013-01-14 22:48:41 +00001392 Res = BinaryOperator::CreateFMul(X, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001393 } else if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001394 // (X/C1)/C2 => X /(C2*C1) [=> X * 1/(C2*C1) if reciprocal is allowed]
Shuxin Yang320f52a2013-01-14 22:48:41 +00001395 Constant *C = ConstantExpr::getFMul(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001396 if (isNormalFp(C)) {
1397 Res = CvtFDivConstToReciprocal(X, C, AllowReciprocal);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001398 if (!Res)
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001399 Res = BinaryOperator::CreateFDiv(X, C);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001400 }
1401 }
1402
1403 if (Res) {
1404 Res->setFastMathFlags(I.getFastMathFlags());
1405 return Res;
1406 }
1407 }
1408
1409 // X / C => X * 1/C
Owen Anderson4557a152014-01-16 21:07:52 +00001410 if (Instruction *T = CvtFDivConstToReciprocal(Op0, Op1C, AllowReciprocal)) {
1411 T->copyFastMathFlags(&I);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001412 return T;
Owen Anderson4557a152014-01-16 21:07:52 +00001413 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001414
Craig Topperf40110f2014-04-25 05:29:35 +00001415 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001416 }
1417
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001418 if (AllowReassociate && isa<Constant>(Op0)) {
1419 Constant *C1 = cast<Constant>(Op0), *C2;
Craig Topperf40110f2014-04-25 05:29:35 +00001420 Constant *Fold = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001421 Value *X;
1422 bool CreateDiv = true;
1423
1424 // C1 / (X*C2) => (C1/C2) / X
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001425 if (match(Op1, m_FMul(m_Value(X), m_Constant(C2))))
Shuxin Yang320f52a2013-01-14 22:48:41 +00001426 Fold = ConstantExpr::getFDiv(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001427 else if (match(Op1, m_FDiv(m_Value(X), m_Constant(C2)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001428 // C1 / (X/C2) => (C1*C2) / X
1429 Fold = ConstantExpr::getFMul(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001430 } else if (match(Op1, m_FDiv(m_Constant(C2), m_Value(X)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001431 // C1 / (C2/X) => (C1/C2) * X
1432 Fold = ConstantExpr::getFDiv(C1, C2);
1433 CreateDiv = false;
1434 }
1435
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001436 if (Fold && isNormalFp(Fold)) {
1437 Instruction *R = CreateDiv ? BinaryOperator::CreateFDiv(Fold, X)
1438 : BinaryOperator::CreateFMul(X, Fold);
1439 R->setFastMathFlags(I.getFastMathFlags());
1440 return R;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001441 }
Craig Topperf40110f2014-04-25 05:29:35 +00001442 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001443 }
1444
1445 if (AllowReassociate) {
1446 Value *X, *Y;
Craig Topperf40110f2014-04-25 05:29:35 +00001447 Value *NewInst = nullptr;
1448 Instruction *SimpR = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001449
1450 if (Op0->hasOneUse() && match(Op0, m_FDiv(m_Value(X), m_Value(Y)))) {
1451 // (X/Y) / Z => X / (Y*Z)
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001452 if (!isa<Constant>(Y) || !isa<Constant>(Op1)) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001453 NewInst = Builder.CreateFMul(Y, Op1);
Owen Anderson1664dc82014-01-20 07:44:53 +00001454 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1455 FastMathFlags Flags = I.getFastMathFlags();
1456 Flags &= cast<Instruction>(Op0)->getFastMathFlags();
1457 RI->setFastMathFlags(Flags);
1458 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001459 SimpR = BinaryOperator::CreateFDiv(X, NewInst);
1460 }
1461 } else if (Op1->hasOneUse() && match(Op1, m_FDiv(m_Value(X), m_Value(Y)))) {
1462 // Z / (X/Y) => Z*Y / X
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001463 if (!isa<Constant>(Y) || !isa<Constant>(Op0)) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001464 NewInst = Builder.CreateFMul(Op0, Y);
Owen Anderson1664dc82014-01-20 07:44:53 +00001465 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1466 FastMathFlags Flags = I.getFastMathFlags();
1467 Flags &= cast<Instruction>(Op1)->getFastMathFlags();
1468 RI->setFastMathFlags(Flags);
1469 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001470 SimpR = BinaryOperator::CreateFDiv(NewInst, X);
1471 }
1472 }
1473
1474 if (NewInst) {
1475 if (Instruction *T = dyn_cast<Instruction>(NewInst))
1476 T->setDebugLoc(I.getDebugLoc());
1477 SimpR->setFastMathFlags(I.getFastMathFlags());
1478 return SimpR;
Benjamin Kramer8564e0d2011-03-30 15:42:35 +00001479 }
1480 }
1481
Dmitry Venikove5fbf592018-01-11 06:33:00 +00001482 if (AllowReassociate &&
1483 Op0->hasOneUse() && Op1->hasOneUse()) {
1484 Value *A;
1485 // sin(a) / cos(a) -> tan(a)
1486 if (match(Op0, m_Intrinsic<Intrinsic::sin>(m_Value(A))) &&
1487 match(Op1, m_Intrinsic<Intrinsic::cos>(m_Specific(A)))) {
1488 if (hasUnaryFloatFn(&TLI, I.getType(), LibFunc_tan,
1489 LibFunc_tanf, LibFunc_tanl)) {
1490 IRBuilder<> B(&I);
1491 IRBuilder<>::FastMathFlagGuard Guard(B);
1492 B.setFastMathFlags(I.getFastMathFlags());
Benjamin Kramer738e6e72018-01-11 15:33:21 +00001493 Value *Tan = emitUnaryFloatFnCall(
1494 A, TLI.getName(LibFunc_tan), B,
1495 CallSite(Op0).getCalledFunction()->getAttributes());
Dmitry Venikove5fbf592018-01-11 06:33:00 +00001496 return replaceInstUsesWith(I, Tan);
1497 }
1498 }
1499
1500 // cos(a) / sin(a) -> 1/tan(a)
1501 if (match(Op0, m_Intrinsic<Intrinsic::cos>(m_Value(A))) &&
1502 match(Op1, m_Intrinsic<Intrinsic::sin>(m_Specific(A)))) {
1503 if (hasUnaryFloatFn(&TLI, I.getType(), LibFunc_tan,
1504 LibFunc_tanf, LibFunc_tanl)) {
1505 IRBuilder<> B(&I);
1506 IRBuilder<>::FastMathFlagGuard Guard(B);
1507 B.setFastMathFlags(I.getFastMathFlags());
Benjamin Kramer44993ed2018-01-11 15:19:02 +00001508 Value *Tan = emitUnaryFloatFnCall(
1509 A, TLI.getName(LibFunc_tan), B,
1510 CallSite(Op0).getCalledFunction()->getAttributes());
Dmitry Venikove5fbf592018-01-11 06:33:00 +00001511 Value *One = ConstantFP::get(Tan->getType(), 1.0);
1512 Value *Div = B.CreateFDiv(One, Tan);
1513 return replaceInstUsesWith(I, Div);
1514 }
1515 }
1516 }
1517
Sanjay Patel1998cc62018-02-12 18:38:35 +00001518 // -X / -Y -> X / Y
1519 Value *X, *Y;
1520 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y)))) {
1521 I.setOperand(0, X);
1522 I.setOperand(1, Y);
Matt Arsenaultfdb78f82017-01-10 23:08:54 +00001523 return &I;
1524 }
1525
Craig Topperf40110f2014-04-25 05:29:35 +00001526 return nullptr;
Frits van Bommel2a559512011-01-29 17:50:27 +00001527}
1528
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001529/// This function implements the transforms common to both integer remainder
1530/// instructions (urem and srem). It is called by the visitors to those integer
1531/// remainder instructions.
1532/// @brief Common integer remainder transforms
1533Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
1534 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1535
Chris Lattner7c99f192011-05-22 18:18:41 +00001536 // The RHS is known non-zero.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001537 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I)) {
Chris Lattner7c99f192011-05-22 18:18:41 +00001538 I.setOperand(1, V);
1539 return &I;
1540 }
1541
Duncan Sandsa3e36992011-05-02 16:27:02 +00001542 // Handle cases involving: rem X, (select Cond, Y, Z)
Sanjay Patelae2e3a42017-10-06 23:20:16 +00001543 if (simplifyDivRemOfSelectWithZeroOp(I))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001544 return &I;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001545
Benjamin Kramer72196f32014-01-19 15:24:22 +00001546 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001547 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1548 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1549 if (Instruction *R = FoldOpIntoSelect(I, SI))
1550 return R;
Craig Topperfb71b7d2017-04-14 19:20:12 +00001551 } else if (auto *PN = dyn_cast<PHINode>(Op0I)) {
Sanjoy Dasb7e861a2016-06-05 21:17:04 +00001552 const APInt *Op1Int;
1553 if (match(Op1, m_APInt(Op1Int)) && !Op1Int->isMinValue() &&
1554 (I.getOpcode() == Instruction::URem ||
1555 !Op1Int->isMinSignedValue())) {
Craig Topperfb71b7d2017-04-14 19:20:12 +00001556 // foldOpIntoPhi will speculate instructions to the end of the PHI's
Sanjoy Dasb7e861a2016-06-05 21:17:04 +00001557 // predecessor blocks, so do this only if we know the srem or urem
1558 // will not fault.
Craig Topperfb71b7d2017-04-14 19:20:12 +00001559 if (Instruction *NV = foldOpIntoPhi(I, PN))
Sanjoy Dasb7e861a2016-06-05 21:17:04 +00001560 return NV;
1561 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001562 }
1563
1564 // See if we can fold away this rem instruction.
1565 if (SimplifyDemandedInstructionBits(I))
1566 return &I;
1567 }
1568 }
1569
Craig Topperf40110f2014-04-25 05:29:35 +00001570 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001571}
1572
1573Instruction *InstCombiner::visitURem(BinaryOperator &I) {
1574 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1575
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001576 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001577 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001578
Craig Toppera4205622017-06-09 03:21:29 +00001579 if (Value *V = SimplifyURemInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001580 return replaceInstUsesWith(I, V);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001581
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001582 if (Instruction *common = commonIRemTransforms(I))
1583 return common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001584
Sanjay Patelbb789382017-08-24 22:54:01 +00001585 if (Instruction *NarrowRem = narrowUDivURem(I, Builder))
1586 return NarrowRem;
David Majnemer6c30f492013-05-12 00:07:05 +00001587
David Majnemer470b0772013-05-11 09:01:28 +00001588 // X urem Y -> X and Y-1, where Y is a power of 2,
Craig Topperd4039f72017-05-25 21:51:12 +00001589 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/ true, 0, &I)) {
Chris Lattner6b657ae2011-02-10 05:36:31 +00001590 Constant *N1 = Constant::getAllOnesValue(I.getType());
Craig Topperbb4069e2017-07-07 23:16:26 +00001591 Value *Add = Builder.CreateAdd(Op1, N1);
Chris Lattner6b657ae2011-02-10 05:36:31 +00001592 return BinaryOperator::CreateAnd(Op0, Add);
1593 }
1594
Nick Lewycky7459be62013-07-13 01:16:47 +00001595 // 1 urem X -> zext(X != 1)
1596 if (match(Op0, m_One())) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001597 Value *Cmp = Builder.CreateICmpNE(Op1, Op0);
1598 Value *Ext = Builder.CreateZExt(Cmp, I.getType());
Sanjay Patel4b198802016-02-01 22:23:39 +00001599 return replaceInstUsesWith(I, Ext);
Nick Lewycky7459be62013-07-13 01:16:47 +00001600 }
1601
Sanjay Patel30ef70b2016-09-22 22:36:26 +00001602 // X urem C -> X < C ? X : X - C, where C >= signbit.
Simon Pilgrim1889f262018-02-08 18:36:01 +00001603 if (match(Op1, m_Negative())) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001604 Value *Cmp = Builder.CreateICmpULT(Op0, Op1);
1605 Value *Sub = Builder.CreateSub(Op0, Op1);
Sanjay Patel30ef70b2016-09-22 22:36:26 +00001606 return SelectInst::Create(Cmp, Op0, Sub);
1607 }
1608
Craig Topperf40110f2014-04-25 05:29:35 +00001609 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001610}
1611
1612Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
1613 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1614
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001615 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001616 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001617
Craig Toppera4205622017-06-09 03:21:29 +00001618 if (Value *V = SimplifySRemInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001619 return replaceInstUsesWith(I, V);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001620
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001621 // Handle the integer rem common cases
1622 if (Instruction *Common = commonIRemTransforms(I))
1623 return Common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001624
David Majnemerdb077302014-10-13 22:37:51 +00001625 {
1626 const APInt *Y;
1627 // X % -Y -> X % Y
Simon Pilgrima54e8e42018-02-08 19:00:45 +00001628 if (match(Op1, m_Negative(Y)) && !Y->isMinSignedValue()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001629 Worklist.AddValue(I.getOperand(1));
David Majnemerdb077302014-10-13 22:37:51 +00001630 I.setOperand(1, ConstantInt::get(I.getType(), -*Y));
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001631 return &I;
1632 }
David Majnemerdb077302014-10-13 22:37:51 +00001633 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001634
1635 // If the sign bits of both operands are zero (i.e. we can prove they are
1636 // unsigned inputs), turn this into a urem.
Craig Topperbcfd2d12017-04-20 16:56:25 +00001637 APInt Mask(APInt::getSignMask(I.getType()->getScalarSizeInBits()));
Craig Topper1a18a7c2017-04-17 01:51:24 +00001638 if (MaskedValueIsZero(Op1, Mask, 0, &I) &&
1639 MaskedValueIsZero(Op0, Mask, 0, &I)) {
1640 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
1641 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001642 }
1643
1644 // If it's a constant vector, flip any negative values positive.
Chris Lattner0256be92012-01-27 03:08:05 +00001645 if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
1646 Constant *C = cast<Constant>(Op1);
1647 unsigned VWidth = C->getType()->getVectorNumElements();
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001648
1649 bool hasNegative = false;
Chris Lattner0256be92012-01-27 03:08:05 +00001650 bool hasMissing = false;
1651 for (unsigned i = 0; i != VWidth; ++i) {
1652 Constant *Elt = C->getAggregateElement(i);
Craig Topperf40110f2014-04-25 05:29:35 +00001653 if (!Elt) {
Chris Lattner0256be92012-01-27 03:08:05 +00001654 hasMissing = true;
1655 break;
1656 }
1657
1658 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
Chris Lattnerb1a15122011-07-15 06:08:15 +00001659 if (RHS->isNegative())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001660 hasNegative = true;
Chris Lattner0256be92012-01-27 03:08:05 +00001661 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001662
Chris Lattner0256be92012-01-27 03:08:05 +00001663 if (hasNegative && !hasMissing) {
Chris Lattner47a86bd2012-01-25 06:02:56 +00001664 SmallVector<Constant *, 16> Elts(VWidth);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001665 for (unsigned i = 0; i != VWidth; ++i) {
Chris Lattner8213c8a2012-02-06 21:56:39 +00001666 Elts[i] = C->getAggregateElement(i); // Handle undef, etc.
Chris Lattner0256be92012-01-27 03:08:05 +00001667 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
Chris Lattnerb1a15122011-07-15 06:08:15 +00001668 if (RHS->isNegative())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001669 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001670 }
1671 }
1672
1673 Constant *NewRHSV = ConstantVector::get(Elts);
Chris Lattner0256be92012-01-27 03:08:05 +00001674 if (NewRHSV != C) { // Don't loop on -MININT
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001675 Worklist.AddValue(I.getOperand(1));
1676 I.setOperand(1, NewRHSV);
1677 return &I;
1678 }
1679 }
1680 }
1681
Craig Topperf40110f2014-04-25 05:29:35 +00001682 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001683}
1684
1685Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Duncan Sandsa3e36992011-05-02 16:27:02 +00001686 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001687
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001688 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001689 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001690
Craig Toppera4205622017-06-09 03:21:29 +00001691 if (Value *V = SimplifyFRemInst(Op0, Op1, I.getFastMathFlags(),
1692 SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001693 return replaceInstUsesWith(I, V);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001694
Craig Topperf40110f2014-04-25 05:29:35 +00001695 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001696}