blob: 195916ead66a7f74e4d003dad8698bc66b828293 [file] [log] [blame]
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001//===- InstCombineMulDivRem.cpp -------------------------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattnerdc054bf2010-01-05 06:09:35 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the visit functions for mul, fmul, sdiv, udiv, fdiv,
10// srem, urem, frem.
11//
12//===----------------------------------------------------------------------===//
13
Chandler Carrutha9174582015-01-22 05:25:13 +000014#include "InstCombineInternal.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000015#include "llvm/ADT/APFloat.h"
16#include "llvm/ADT/APInt.h"
17#include "llvm/ADT/SmallVector.h"
Duncan Sandsd0eb6d32010-12-21 14:00:22 +000018#include "llvm/Analysis/InstructionSimplify.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000019#include "llvm/IR/BasicBlock.h"
20#include "llvm/IR/Constant.h"
21#include "llvm/IR/Constants.h"
22#include "llvm/IR/InstrTypes.h"
23#include "llvm/IR/Instruction.h"
24#include "llvm/IR/Instructions.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000026#include "llvm/IR/Intrinsics.h"
27#include "llvm/IR/Operator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000028#include "llvm/IR/PatternMatch.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000029#include "llvm/IR/Type.h"
30#include "llvm/IR/Value.h"
31#include "llvm/Support/Casting.h"
32#include "llvm/Support/ErrorHandling.h"
33#include "llvm/Support/KnownBits.h"
34#include "llvm/Transforms/InstCombine/InstCombineWorklist.h"
Dmitry Venikove5fbf592018-01-11 06:33:00 +000035#include "llvm/Transforms/Utils/BuildLibCalls.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000036#include <cassert>
37#include <cstddef>
38#include <cstdint>
39#include <utility>
40
Chris Lattnerdc054bf2010-01-05 06:09:35 +000041using namespace llvm;
42using namespace PatternMatch;
43
Chandler Carruth964daaa2014-04-22 02:55:47 +000044#define DEBUG_TYPE "instcombine"
45
Sanjay Patel6eccf482015-09-09 15:24:36 +000046/// The specific integer value is used in a context where it is known to be
47/// non-zero. If this allows us to simplify the computation, do so and return
48/// the new operand, otherwise return null.
Hal Finkel60db0582014-09-07 18:57:58 +000049static Value *simplifyValueKnownNonZero(Value *V, InstCombiner &IC,
Mehdi Aminia28d91d2015-03-10 02:37:25 +000050 Instruction &CxtI) {
Chris Lattner7c99f192011-05-22 18:18:41 +000051 // If V has multiple uses, then we would have to do more analysis to determine
52 // if this is safe. For example, the use could be in dynamically unreached
53 // code.
Craig Topperf40110f2014-04-25 05:29:35 +000054 if (!V->hasOneUse()) return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +000055
Chris Lattner388cb8a2011-05-23 00:32:19 +000056 bool MadeChange = false;
57
Chris Lattner7c99f192011-05-22 18:18:41 +000058 // ((1 << A) >>u B) --> (1 << (A-B))
59 // Because V cannot be zero, we know that B is less than A.
David Majnemerdad21032014-10-14 20:28:40 +000060 Value *A = nullptr, *B = nullptr, *One = nullptr;
61 if (match(V, m_LShr(m_OneUse(m_Shl(m_Value(One), m_Value(A))), m_Value(B))) &&
62 match(One, m_One())) {
Craig Topperbb4069e2017-07-07 23:16:26 +000063 A = IC.Builder.CreateSub(A, B);
64 return IC.Builder.CreateShl(One, A);
Chris Lattner7c99f192011-05-22 18:18:41 +000065 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000066
Chris Lattner388cb8a2011-05-23 00:32:19 +000067 // (PowerOfTwo >>u B) --> isExact since shifting out the result would make it
68 // inexact. Similarly for <<.
Sanjay Patela8ef4a52016-05-22 17:08:52 +000069 BinaryOperator *I = dyn_cast<BinaryOperator>(V);
70 if (I && I->isLogicalShift() &&
Craig Topperd4039f72017-05-25 21:51:12 +000071 IC.isKnownToBeAPowerOfTwo(I->getOperand(0), false, 0, &CxtI)) {
Sanjay Patela8ef4a52016-05-22 17:08:52 +000072 // We know that this is an exact/nuw shift and that the input is a
73 // non-zero context as well.
74 if (Value *V2 = simplifyValueKnownNonZero(I->getOperand(0), IC, CxtI)) {
Nikita Popov4b35c812020-03-30 22:00:16 +020075 IC.replaceOperand(*I, 0, V2);
Sanjay Patela8ef4a52016-05-22 17:08:52 +000076 MadeChange = true;
Chris Lattner388cb8a2011-05-23 00:32:19 +000077 }
78
Sanjay Patela8ef4a52016-05-22 17:08:52 +000079 if (I->getOpcode() == Instruction::LShr && !I->isExact()) {
80 I->setIsExact();
81 MadeChange = true;
82 }
83
84 if (I->getOpcode() == Instruction::Shl && !I->hasNoUnsignedWrap()) {
85 I->setHasNoUnsignedWrap();
86 MadeChange = true;
87 }
88 }
89
Chris Lattner162dfc32011-05-22 18:26:48 +000090 // TODO: Lots more we could do here:
Chris Lattner162dfc32011-05-22 18:26:48 +000091 // If V is a phi node, we can call this on each of its operands.
92 // "select cond, X, 0" can simplify to "X".
Jim Grosbachbdbd7342013-04-05 21:20:12 +000093
Craig Topperf40110f2014-04-25 05:29:35 +000094 return MadeChange ? V : nullptr;
Chris Lattner7c99f192011-05-22 18:18:41 +000095}
96
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000097/// A helper routine of InstCombiner::visitMul().
Rafael Espindola65281bf2013-05-31 14:27:15 +000098///
Simon Pilgrim0b9f3912018-02-08 14:10:01 +000099/// If C is a scalar/vector of known powers of 2, then this function returns
100/// a new scalar/vector obtained from logBase2 of C.
Rafael Espindola65281bf2013-05-31 14:27:15 +0000101/// Return a null pointer otherwise.
Simon Pilgrim0b9f3912018-02-08 14:10:01 +0000102static Constant *getLogBase2(Type *Ty, Constant *C) {
Rafael Espindola65281bf2013-05-31 14:27:15 +0000103 const APInt *IVal;
Simon Pilgrimbe0dd722018-02-13 13:16:26 +0000104 if (match(C, m_APInt(IVal)) && IVal->isPowerOf2())
105 return ConstantInt::get(Ty, IVal->logBase2());
Rafael Espindola65281bf2013-05-31 14:27:15 +0000106
Simon Pilgrim0b9f3912018-02-08 14:10:01 +0000107 if (!Ty->isVectorTy())
108 return nullptr;
109
110 SmallVector<Constant *, 4> Elts;
111 for (unsigned I = 0, E = Ty->getVectorNumElements(); I != E; ++I) {
112 Constant *Elt = C->getAggregateElement(I);
113 if (!Elt)
114 return nullptr;
115 if (isa<UndefValue>(Elt)) {
116 Elts.push_back(UndefValue::get(Ty->getScalarType()));
117 continue;
118 }
Rafael Espindola65281bf2013-05-31 14:27:15 +0000119 if (!match(Elt, m_APInt(IVal)) || !IVal->isPowerOf2())
Craig Topperf40110f2014-04-25 05:29:35 +0000120 return nullptr;
Simon Pilgrim0b9f3912018-02-08 14:10:01 +0000121 Elts.push_back(ConstantInt::get(Ty->getScalarType(), IVal->logBase2()));
Rafael Espindola65281bf2013-05-31 14:27:15 +0000122 }
123
124 return ConstantVector::get(Elts);
125}
126
Sanjay Patelaab8b3a2019-10-06 14:15:48 +0000127// TODO: This is a specific form of a much more general pattern.
128// We could detect a select with any binop identity constant, or we
129// could use SimplifyBinOp to see if either arm of the select reduces.
130// But that needs to be done carefully and/or while removing potential
131// reverse canonicalizations as in InstCombiner::foldSelectIntoOp().
132static Value *foldMulSelectToNegate(BinaryOperator &I,
133 InstCombiner::BuilderTy &Builder) {
134 Value *Cond, *OtherOp;
135
136 // mul (select Cond, 1, -1), OtherOp --> select Cond, OtherOp, -OtherOp
137 // mul OtherOp, (select Cond, 1, -1) --> select Cond, OtherOp, -OtherOp
138 if (match(&I, m_c_Mul(m_OneUse(m_Select(m_Value(Cond), m_One(), m_AllOnes())),
139 m_Value(OtherOp))))
140 return Builder.CreateSelect(Cond, OtherOp, Builder.CreateNeg(OtherOp));
141
142 // mul (select Cond, -1, 1), OtherOp --> select Cond, -OtherOp, OtherOp
143 // mul OtherOp, (select Cond, -1, 1) --> select Cond, -OtherOp, OtherOp
144 if (match(&I, m_c_Mul(m_OneUse(m_Select(m_Value(Cond), m_AllOnes(), m_One())),
145 m_Value(OtherOp))))
146 return Builder.CreateSelect(Cond, Builder.CreateNeg(OtherOp), OtherOp);
147
148 // fmul (select Cond, 1.0, -1.0), OtherOp --> select Cond, OtherOp, -OtherOp
149 // fmul OtherOp, (select Cond, 1.0, -1.0) --> select Cond, OtherOp, -OtherOp
150 if (match(&I, m_c_FMul(m_OneUse(m_Select(m_Value(Cond), m_SpecificFP(1.0),
151 m_SpecificFP(-1.0))),
152 m_Value(OtherOp)))) {
153 IRBuilder<>::FastMathFlagGuard FMFGuard(Builder);
154 Builder.setFastMathFlags(I.getFastMathFlags());
155 return Builder.CreateSelect(Cond, OtherOp, Builder.CreateFNeg(OtherOp));
156 }
157
158 // fmul (select Cond, -1.0, 1.0), OtherOp --> select Cond, -OtherOp, OtherOp
159 // fmul OtherOp, (select Cond, -1.0, 1.0) --> select Cond, -OtherOp, OtherOp
160 if (match(&I, m_c_FMul(m_OneUse(m_Select(m_Value(Cond), m_SpecificFP(-1.0),
161 m_SpecificFP(1.0))),
162 m_Value(OtherOp)))) {
163 IRBuilder<>::FastMathFlagGuard FMFGuard(Builder);
164 Builder.setFastMathFlags(I.getFastMathFlags());
165 return Builder.CreateSelect(Cond, Builder.CreateFNeg(OtherOp), OtherOp);
166 }
167
168 return nullptr;
169}
170
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000171Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Sanjay Patel7b0fc752018-06-21 17:06:36 +0000172 if (Value *V = SimplifyMulInst(I.getOperand(0), I.getOperand(1),
173 SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +0000174 return replaceInstUsesWith(I, V);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000175
Sanjay Patel70043b72018-07-13 01:18:07 +0000176 if (SimplifyAssociativeOrCommutative(I))
177 return &I;
178
Sanjay Patel79dceb22018-10-03 15:20:58 +0000179 if (Instruction *X = foldVectorBinop(I))
Sanjay Patelbbc6d602018-06-02 16:27:44 +0000180 return X;
181
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000182 if (Value *V = SimplifyUsingDistributiveLaws(I))
Sanjay Patel4b198802016-02-01 22:23:39 +0000183 return replaceInstUsesWith(I, V);
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000184
David Majnemer027bc802014-11-22 04:52:38 +0000185 // X * -1 == 0 - X
Sanjay Patel7b0fc752018-06-21 17:06:36 +0000186 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
David Majnemer027bc802014-11-22 04:52:38 +0000187 if (match(Op1, m_AllOnes())) {
188 BinaryOperator *BO = BinaryOperator::CreateNeg(Op0, I.getName());
189 if (I.hasNoSignedWrap())
190 BO->setHasNoSignedWrap();
191 return BO;
192 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000193
Rafael Espindola65281bf2013-05-31 14:27:15 +0000194 // Also allow combining multiply instructions on vectors.
195 {
196 Value *NewOp;
197 Constant *C1, *C2;
198 const APInt *IVal;
199 if (match(&I, m_Mul(m_Shl(m_Value(NewOp), m_Constant(C2)),
200 m_Constant(C1))) &&
David Majnemerfd4a6d22014-11-22 04:52:52 +0000201 match(C1, m_APInt(IVal))) {
202 // ((X << C2)*C1) == (X * (C1 << C2))
203 Constant *Shl = ConstantExpr::getShl(C1, C2);
204 BinaryOperator *Mul = cast<BinaryOperator>(I.getOperand(0));
205 BinaryOperator *BO = BinaryOperator::CreateMul(NewOp, Shl);
206 if (I.hasNoUnsignedWrap() && Mul->hasNoUnsignedWrap())
207 BO->setHasNoUnsignedWrap();
208 if (I.hasNoSignedWrap() && Mul->hasNoSignedWrap() &&
209 Shl->isNotMinSignedValue())
210 BO->setHasNoSignedWrap();
211 return BO;
212 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000213
Rafael Espindola65281bf2013-05-31 14:27:15 +0000214 if (match(&I, m_Mul(m_Value(NewOp), m_Constant(C1)))) {
Simon Pilgrim0b9f3912018-02-08 14:10:01 +0000215 // Replace X*(2^C) with X << C, where C is either a scalar or a vector.
216 if (Constant *NewCst = getLogBase2(NewOp->getType(), C1)) {
Rafael Espindola65281bf2013-05-31 14:27:15 +0000217 BinaryOperator *Shl = BinaryOperator::CreateShl(NewOp, NewCst);
Tilmann Scheller2bc5cb62014-10-07 10:19:34 +0000218
Tilmann Scheller2bc5cb62014-10-07 10:19:34 +0000219 if (I.hasNoUnsignedWrap())
220 Shl->setHasNoUnsignedWrap();
David Majnemer45951a62015-04-18 04:41:30 +0000221 if (I.hasNoSignedWrap()) {
Craig Topper5fe01972017-06-27 19:57:53 +0000222 const APInt *V;
Craig Topper4e63db82018-09-11 17:57:20 +0000223 if (match(NewCst, m_APInt(V)) && *V != V->getBitWidth() - 1)
David Majnemer45951a62015-04-18 04:41:30 +0000224 Shl->setHasNoSignedWrap();
225 }
Tilmann Scheller2bc5cb62014-10-07 10:19:34 +0000226
Rafael Espindola65281bf2013-05-31 14:27:15 +0000227 return Shl;
228 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000229 }
Rafael Espindola65281bf2013-05-31 14:27:15 +0000230 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000231
Rafael Espindola65281bf2013-05-31 14:27:15 +0000232 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Stuart Hastings23804832011-06-01 16:42:47 +0000233 // (Y - X) * (-(2**n)) -> (X - Y) * (2**n), for positive nonzero n
234 // (Y + const) * (-(2**n)) -> (-constY) * (2**n), for positive nonzero n
235 // The "* (2**n)" thus becomes a potential shifting opportunity.
Stuart Hastings82843742011-05-30 20:00:33 +0000236 {
237 const APInt & Val = CI->getValue();
238 const APInt &PosVal = Val.abs();
239 if (Val.isNegative() && PosVal.isPowerOf2()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000240 Value *X = nullptr, *Y = nullptr;
Stuart Hastings23804832011-06-01 16:42:47 +0000241 if (Op0->hasOneUse()) {
242 ConstantInt *C1;
Craig Topperf40110f2014-04-25 05:29:35 +0000243 Value *Sub = nullptr;
Stuart Hastings23804832011-06-01 16:42:47 +0000244 if (match(Op0, m_Sub(m_Value(Y), m_Value(X))))
Craig Topperbb4069e2017-07-07 23:16:26 +0000245 Sub = Builder.CreateSub(X, Y, "suba");
Stuart Hastings23804832011-06-01 16:42:47 +0000246 else if (match(Op0, m_Add(m_Value(Y), m_ConstantInt(C1))))
Craig Topperbb4069e2017-07-07 23:16:26 +0000247 Sub = Builder.CreateSub(Builder.CreateNeg(C1), Y, "subc");
Stuart Hastings23804832011-06-01 16:42:47 +0000248 if (Sub)
249 return
250 BinaryOperator::CreateMul(Sub,
251 ConstantInt::get(Y->getType(), PosVal));
Stuart Hastings82843742011-05-30 20:00:33 +0000252 }
253 }
254 }
Chris Lattner6b657ae2011-02-10 05:36:31 +0000255 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000256
Sanjay Patel8fdd87f2018-02-28 16:36:24 +0000257 if (Instruction *FoldedMul = foldBinOpIntoSelectOrPhi(I))
258 return FoldedMul;
259
Sanjay Patelaab8b3a2019-10-06 14:15:48 +0000260 if (Value *FoldedMul = foldMulSelectToNegate(I, Builder))
261 return replaceInstUsesWith(I, FoldedMul);
Sanjay Patel712b7c22019-09-30 17:02:26 +0000262
Chris Lattner6b657ae2011-02-10 05:36:31 +0000263 // Simplify mul instructions with a constant RHS.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000264 if (isa<Constant>(Op1)) {
Benjamin Kramer72196f32014-01-19 15:24:22 +0000265 // Canonicalize (X+C1)*CI -> X*CI+C1*CI.
Sanjay Patel8fdd87f2018-02-28 16:36:24 +0000266 Value *X;
267 Constant *C1;
268 if (match(Op0, m_OneUse(m_Add(m_Value(X), m_Constant(C1))))) {
269 Value *Mul = Builder.CreateMul(C1, Op1);
270 // Only go forward with the transform if C1*CI simplifies to a tidier
271 // constant.
272 if (!match(Mul, m_Mul(m_Value(), m_Value())))
273 return BinaryOperator::CreateAdd(Builder.CreateMul(X, Op1), Mul);
Benjamin Kramer72196f32014-01-19 15:24:22 +0000274 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000275 }
276
Sanjay Patel604cb9e2018-02-14 16:50:55 +0000277 // -X * C --> X * -C
278 Value *X, *Y;
279 Constant *Op1C;
280 if (match(Op0, m_Neg(m_Value(X))) && match(Op1, m_Constant(Op1C)))
281 return BinaryOperator::CreateMul(X, ConstantExpr::getNeg(Op1C));
282
283 // -X * -Y --> X * Y
284 if (match(Op0, m_Neg(m_Value(X))) && match(Op1, m_Neg(m_Value(Y)))) {
285 auto *NewMul = BinaryOperator::CreateMul(X, Y);
286 if (I.hasNoSignedWrap() &&
287 cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap() &&
288 cast<OverflowingBinaryOperator>(Op1)->hasNoSignedWrap())
289 NewMul->setHasNoSignedWrap();
290 return NewMul;
David Majnemer8279a7502014-11-22 07:25:19 +0000291 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000292
Chen Zheng4952e662019-01-01 01:09:20 +0000293 // -X * Y --> -(X * Y)
294 // X * -Y --> -(X * Y)
295 if (match(&I, m_c_Mul(m_OneUse(m_Neg(m_Value(X))), m_Value(Y))))
296 return BinaryOperator::CreateNeg(Builder.CreateMul(X, Y));
297
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000298 // (X / Y) * Y = X - (X % Y)
299 // (X / Y) * -Y = (X % Y) - X
300 {
Sanjay Patela0a56822017-03-14 17:27:27 +0000301 Value *Y = Op1;
302 BinaryOperator *Div = dyn_cast<BinaryOperator>(Op0);
303 if (!Div || (Div->getOpcode() != Instruction::UDiv &&
304 Div->getOpcode() != Instruction::SDiv)) {
305 Y = Op0;
306 Div = dyn_cast<BinaryOperator>(Op1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000307 }
Sanjay Patela0a56822017-03-14 17:27:27 +0000308 Value *Neg = dyn_castNegVal(Y);
309 if (Div && Div->hasOneUse() &&
310 (Div->getOperand(1) == Y || Div->getOperand(1) == Neg) &&
311 (Div->getOpcode() == Instruction::UDiv ||
312 Div->getOpcode() == Instruction::SDiv)) {
313 Value *X = Div->getOperand(0), *DivOp1 = Div->getOperand(1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000314
Chris Lattner35315d02011-02-06 21:44:57 +0000315 // If the division is exact, X % Y is zero, so we end up with X or -X.
Sanjay Patela0a56822017-03-14 17:27:27 +0000316 if (Div->isExact()) {
317 if (DivOp1 == Y)
318 return replaceInstUsesWith(I, X);
319 return BinaryOperator::CreateNeg(X);
320 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000321
Sanjay Patela0a56822017-03-14 17:27:27 +0000322 auto RemOpc = Div->getOpcode() == Instruction::UDiv ? Instruction::URem
323 : Instruction::SRem;
Craig Topperbb4069e2017-07-07 23:16:26 +0000324 Value *Rem = Builder.CreateBinOp(RemOpc, X, DivOp1);
Sanjay Patela0a56822017-03-14 17:27:27 +0000325 if (DivOp1 == Y)
326 return BinaryOperator::CreateSub(X, Rem);
327 return BinaryOperator::CreateSub(Rem, X);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000328 }
329 }
330
331 /// i1 mul -> i1 and.
Craig Topperfde47232017-07-09 07:04:03 +0000332 if (I.getType()->isIntOrIntVectorTy(1))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000333 return BinaryOperator::CreateAnd(Op0, Op1);
334
335 // X*(1 << Y) --> X << Y
336 // (1 << Y)*X --> X << Y
337 {
338 Value *Y;
David Majnemer546f8102014-11-22 08:57:02 +0000339 BinaryOperator *BO = nullptr;
340 bool ShlNSW = false;
341 if (match(Op0, m_Shl(m_One(), m_Value(Y)))) {
342 BO = BinaryOperator::CreateShl(Op1, Y);
David Majnemer087dc8b2015-01-04 07:36:02 +0000343 ShlNSW = cast<ShlOperator>(Op0)->hasNoSignedWrap();
David Majnemer8e6f6a92014-11-24 16:41:13 +0000344 } else if (match(Op1, m_Shl(m_One(), m_Value(Y)))) {
David Majnemer546f8102014-11-22 08:57:02 +0000345 BO = BinaryOperator::CreateShl(Op0, Y);
David Majnemer087dc8b2015-01-04 07:36:02 +0000346 ShlNSW = cast<ShlOperator>(Op1)->hasNoSignedWrap();
David Majnemer546f8102014-11-22 08:57:02 +0000347 }
348 if (BO) {
349 if (I.hasNoUnsignedWrap())
350 BO->setHasNoUnsignedWrap();
351 if (I.hasNoSignedWrap() && ShlNSW)
352 BO->setHasNoSignedWrap();
353 return BO;
354 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000355 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000356
Sanjay Patelcb8ac002018-02-13 20:41:22 +0000357 // (bool X) * Y --> X ? Y : 0
Sanjay Patel7558d862018-02-13 22:24:37 +0000358 // Y * (bool X) --> X ? Y : 0
Sanjay Patelcb8ac002018-02-13 20:41:22 +0000359 if (match(Op0, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
360 return SelectInst::Create(X, Op1, ConstantInt::get(I.getType(), 0));
Sanjay Patelcb8ac002018-02-13 20:41:22 +0000361 if (match(Op1, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
362 return SelectInst::Create(X, Op0, ConstantInt::get(I.getType(), 0));
363
Sanjay Patel7558d862018-02-13 22:24:37 +0000364 // (lshr X, 31) * Y --> (ashr X, 31) & Y
365 // Y * (lshr X, 31) --> (ashr X, 31) & Y
366 // TODO: We are not checking one-use because the elimination of the multiply
367 // is better for analysis?
368 // TODO: Should we canonicalize to '(X < 0) ? Y : 0' instead? That would be
369 // more similar to what we're doing above.
370 const APInt *C;
371 if (match(Op0, m_LShr(m_Value(X), m_APInt(C))) && *C == C->getBitWidth() - 1)
372 return BinaryOperator::CreateAnd(Builder.CreateAShr(X, *C), Op1);
373 if (match(Op1, m_LShr(m_Value(X), m_APInt(C))) && *C == C->getBitWidth() - 1)
374 return BinaryOperator::CreateAnd(Builder.CreateAShr(X, *C), Op0);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000375
Sanjay Patel90a36342018-09-14 22:23:35 +0000376 if (Instruction *Ext = narrowMathIfNoOverflow(I))
377 return Ext;
David Majnemera1cfd7c2016-12-30 00:28:58 +0000378
Sanjay Patel70043b72018-07-13 01:18:07 +0000379 bool Changed = false;
Craig Topper2b1fc322017-05-22 06:25:31 +0000380 if (!I.hasNoSignedWrap() && willNotOverflowSignedMul(Op0, Op1, I)) {
David Majnemer54c2ca22014-12-26 09:10:14 +0000381 Changed = true;
382 I.setHasNoSignedWrap(true);
383 }
384
Craig Topperbb973722017-05-15 02:44:08 +0000385 if (!I.hasNoUnsignedWrap() && willNotOverflowUnsignedMul(Op0, Op1, I)) {
David Majnemerb1296ec2014-12-26 09:50:35 +0000386 Changed = true;
387 I.setHasNoUnsignedWrap(true);
388 }
389
Craig Topperf40110f2014-04-25 05:29:35 +0000390 return Changed ? &I : nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000391}
392
393Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
Sanjay Patel7b0fc752018-06-21 17:06:36 +0000394 if (Value *V = SimplifyFMulInst(I.getOperand(0), I.getOperand(1),
395 I.getFastMathFlags(),
Craig Toppera4205622017-06-09 03:21:29 +0000396 SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +0000397 return replaceInstUsesWith(I, V);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000398
Sanjay Patel70043b72018-07-13 01:18:07 +0000399 if (SimplifyAssociativeOrCommutative(I))
400 return &I;
401
Sanjay Patel79dceb22018-10-03 15:20:58 +0000402 if (Instruction *X = foldVectorBinop(I))
Sanjay Patelbbc6d602018-06-02 16:27:44 +0000403 return X;
404
Sanjay Patel8fdd87f2018-02-28 16:36:24 +0000405 if (Instruction *FoldedMul = foldBinOpIntoSelectOrPhi(I))
406 return FoldedMul;
407
Sanjay Patelaab8b3a2019-10-06 14:15:48 +0000408 if (Value *FoldedMul = foldMulSelectToNegate(I, Builder))
409 return replaceInstUsesWith(I, FoldedMul);
410
Sanjay Patele29375d2018-03-02 23:06:45 +0000411 // X * -1.0 --> -X
Sanjay Patel7b0fc752018-06-21 17:06:36 +0000412 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Sanjay Patele29375d2018-03-02 23:06:45 +0000413 if (match(Op1, m_SpecificFP(-1.0)))
Simon Mollddd11272020-02-27 09:05:54 -0800414 return UnaryOperator::CreateFNegFMF(Op0, &I);
Sanjay Patel6b9c7a92018-02-23 17:14:28 +0000415
Sanjay Patele29375d2018-03-02 23:06:45 +0000416 // -X * -Y --> X * Y
417 Value *X, *Y;
418 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
419 return BinaryOperator::CreateFMulFMF(X, Y, &I);
Owen Andersonf74cfe02014-01-16 20:36:42 +0000420
Sanjay Patele29375d2018-03-02 23:06:45 +0000421 // -X * C --> X * -C
422 Constant *C;
423 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_Constant(C)))
424 return BinaryOperator::CreateFMulFMF(X, ConstantExpr::getFNeg(C), &I);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000425
Sanjay Patele29375d2018-03-02 23:06:45 +0000426 // fabs(X) * fabs(X) -> X * X
427 if (Op0 == Op1 && match(Op0, m_Intrinsic<Intrinsic::fabs>(m_Value(X))))
428 return BinaryOperator::CreateFMulFMF(X, X, &I);
429
430 // (select A, B, C) * (select A, D, E) --> select A, (B*D), (C*E)
431 if (Value *V = SimplifySelectsFeedingBinaryOp(I, Op0, Op1))
432 return replaceInstUsesWith(I, V);
433
Sanjay Patel81b3b102018-04-03 22:19:19 +0000434 if (I.hasAllowReassoc()) {
435 // Reassociate constant RHS with another constant to form constant
436 // expression.
437 if (match(Op1, m_Constant(C)) && C->isFiniteNonZeroFP()) {
438 Constant *C1;
439 if (match(Op0, m_OneUse(m_FDiv(m_Constant(C1), m_Value(X))))) {
440 // (C1 / X) * C --> (C * C1) / X
441 Constant *CC1 = ConstantExpr::getFMul(C, C1);
442 if (CC1->isNormalFP())
443 return BinaryOperator::CreateFDivFMF(CC1, X, &I);
444 }
445 if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) {
446 // (X / C1) * C --> X * (C / C1)
447 Constant *CDivC1 = ConstantExpr::getFDiv(C, C1);
448 if (CDivC1->isNormalFP())
449 return BinaryOperator::CreateFMulFMF(X, CDivC1, &I);
Sanjay Patel204edec2018-03-13 14:46:32 +0000450
Sanjay Patel81b3b102018-04-03 22:19:19 +0000451 // If the constant was a denormal, try reassociating differently.
452 // (X / C1) * C --> X / (C1 / C)
453 Constant *C1DivC = ConstantExpr::getFDiv(C1, C);
454 if (Op0->hasOneUse() && C1DivC->isNormalFP())
455 return BinaryOperator::CreateFDivFMF(X, C1DivC, &I);
456 }
457
458 // We do not need to match 'fadd C, X' and 'fsub X, C' because they are
459 // canonicalized to 'fadd X, C'. Distributing the multiply may allow
460 // further folds and (X * C) + C2 is 'fma'.
461 if (match(Op0, m_OneUse(m_FAdd(m_Value(X), m_Constant(C1))))) {
462 // (X + C1) * C --> (X * C) + (C * C1)
463 Constant *CC1 = ConstantExpr::getFMul(C, C1);
464 Value *XC = Builder.CreateFMulFMF(X, C, &I);
465 return BinaryOperator::CreateFAddFMF(XC, CC1, &I);
466 }
467 if (match(Op0, m_OneUse(m_FSub(m_Constant(C1), m_Value(X))))) {
468 // (C1 - X) * C --> (C * C1) - (X * C)
469 Constant *CC1 = ConstantExpr::getFMul(C, C1);
470 Value *XC = Builder.CreateFMulFMF(X, C, &I);
471 return BinaryOperator::CreateFSubFMF(CC1, XC, &I);
472 }
Sanjay Patel204edec2018-03-13 14:46:32 +0000473 }
474
Sanjay Patel5e13cd22019-04-15 13:23:38 +0000475 Value *Z;
476 if (match(&I, m_c_FMul(m_OneUse(m_FDiv(m_Value(X), m_Value(Y))),
477 m_Value(Z)))) {
478 // Sink division: (X / Y) * Z --> (X * Z) / Y
479 Value *NewFMul = Builder.CreateFMulFMF(X, Z, &I);
480 return BinaryOperator::CreateFDivFMF(NewFMul, Y, &I);
481 }
482
Sanjay Patel81b3b102018-04-03 22:19:19 +0000483 // sqrt(X) * sqrt(Y) -> sqrt(X * Y)
484 // nnan disallows the possibility of returning a number if both operands are
485 // negative (in that case, we should return NaN).
486 if (I.hasNoNaNs() &&
487 match(Op0, m_OneUse(m_Intrinsic<Intrinsic::sqrt>(m_Value(X)))) &&
488 match(Op1, m_OneUse(m_Intrinsic<Intrinsic::sqrt>(m_Value(Y))))) {
489 Value *XY = Builder.CreateFMulFMF(X, Y, &I);
Neil Henning57f5d0a2018-10-08 10:32:33 +0000490 Value *Sqrt = Builder.CreateUnaryIntrinsic(Intrinsic::sqrt, XY, &I);
Sanjay Patel81b3b102018-04-03 22:19:19 +0000491 return replaceInstUsesWith(I, Sqrt);
Sanjay Patel4fd4fd62018-03-26 15:03:57 +0000492 }
Sanjay Patel81b3b102018-04-03 22:19:19 +0000493
Sanjay Patel773e04c2019-04-08 21:23:50 +0000494 // Like the similar transform in instsimplify, this requires 'nsz' because
495 // sqrt(-0.0) = -0.0, and -0.0 * -0.0 does not simplify to -0.0.
496 if (I.hasNoNaNs() && I.hasNoSignedZeros() && Op0 == Op1 &&
497 Op0->hasNUses(2)) {
498 // Peek through fdiv to find squaring of square root:
499 // (X / sqrt(Y)) * (X / sqrt(Y)) --> (X * X) / Y
500 if (match(Op0, m_FDiv(m_Value(X),
501 m_Intrinsic<Intrinsic::sqrt>(m_Value(Y))))) {
502 Value *XX = Builder.CreateFMulFMF(X, X, &I);
503 return BinaryOperator::CreateFDivFMF(XX, Y, &I);
504 }
505 // (sqrt(Y) / X) * (sqrt(Y) / X) --> Y / (X * X)
506 if (match(Op0, m_FDiv(m_Intrinsic<Intrinsic::sqrt>(m_Value(Y)),
507 m_Value(X)))) {
508 Value *XX = Builder.CreateFMulFMF(X, X, &I);
509 return BinaryOperator::CreateFDivFMF(Y, XX, &I);
510 }
511 }
512
Dmitry Venikov88176582019-01-31 06:28:10 +0000513 // exp(X) * exp(Y) -> exp(X + Y)
514 // Match as long as at least one of exp has only one use.
515 if (match(Op0, m_Intrinsic<Intrinsic::exp>(m_Value(X))) &&
516 match(Op1, m_Intrinsic<Intrinsic::exp>(m_Value(Y))) &&
517 (Op0->hasOneUse() || Op1->hasOneUse())) {
518 Value *XY = Builder.CreateFAddFMF(X, Y, &I);
519 Value *Exp = Builder.CreateUnaryIntrinsic(Intrinsic::exp, XY, &I);
520 return replaceInstUsesWith(I, Exp);
521 }
522
523 // exp2(X) * exp2(Y) -> exp2(X + Y)
524 // Match as long as at least one of exp2 has only one use.
525 if (match(Op0, m_Intrinsic<Intrinsic::exp2>(m_Value(X))) &&
526 match(Op1, m_Intrinsic<Intrinsic::exp2>(m_Value(Y))) &&
527 (Op0->hasOneUse() || Op1->hasOneUse())) {
528 Value *XY = Builder.CreateFAddFMF(X, Y, &I);
529 Value *Exp2 = Builder.CreateUnaryIntrinsic(Intrinsic::exp2, XY, &I);
530 return replaceInstUsesWith(I, Exp2);
531 }
532
Sanjay Patel81b3b102018-04-03 22:19:19 +0000533 // (X*Y) * X => (X*X) * Y where Y != X
534 // The purpose is two-fold:
535 // 1) to form a power expression (of X).
536 // 2) potentially shorten the critical path: After transformation, the
537 // latency of the instruction Y is amortized by the expression of X*X,
538 // and therefore Y is in a "less critical" position compared to what it
539 // was before the transformation.
540 if (match(Op0, m_OneUse(m_c_FMul(m_Specific(Op1), m_Value(Y)))) &&
541 Op1 != Y) {
542 Value *XX = Builder.CreateFMulFMF(Op1, Op1, &I);
543 return BinaryOperator::CreateFMulFMF(XX, Y, &I);
544 }
545 if (match(Op1, m_OneUse(m_c_FMul(m_Specific(Op0), m_Value(Y)))) &&
546 Op0 != Y) {
547 Value *XX = Builder.CreateFMulFMF(Op0, Op0, &I);
548 return BinaryOperator::CreateFMulFMF(XX, Y, &I);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000549 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000550 }
551
Sanjay Patel2fd0acf2018-03-02 20:32:46 +0000552 // log2(X * 0.5) * Y = log2(X) * Y - Y
553 if (I.isFast()) {
554 IntrinsicInst *Log2 = nullptr;
555 if (match(Op0, m_OneUse(m_Intrinsic<Intrinsic::log2>(
556 m_OneUse(m_FMul(m_Value(X), m_SpecificFP(0.5))))))) {
557 Log2 = cast<IntrinsicInst>(Op0);
558 Y = Op1;
Pedro Artigasd8795042012-11-30 19:09:41 +0000559 }
Sanjay Patel2fd0acf2018-03-02 20:32:46 +0000560 if (match(Op1, m_OneUse(m_Intrinsic<Intrinsic::log2>(
561 m_OneUse(m_FMul(m_Value(X), m_SpecificFP(0.5))))))) {
562 Log2 = cast<IntrinsicInst>(Op1);
563 Y = Op0;
564 }
565 if (Log2) {
Nikita Popov893c6302020-02-16 10:15:53 +0100566 Value *Log2 = Builder.CreateUnaryIntrinsic(Intrinsic::log2, X, &I);
Sanjay Patel2fd0acf2018-03-02 20:32:46 +0000567 Value *LogXTimesY = Builder.CreateFMulFMF(Log2, Y, &I);
568 return BinaryOperator::CreateFSubFMF(LogXTimesY, Y, &I);
Pedro Artigasd8795042012-11-30 19:09:41 +0000569 }
570 }
571
Sanjay Patel70043b72018-07-13 01:18:07 +0000572 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000573}
574
Sanjay Patelae2e3a42017-10-06 23:20:16 +0000575/// Fold a divide or remainder with a select instruction divisor when one of the
576/// select operands is zero. In that case, we can use the other select operand
577/// because div/rem by zero is undefined.
578bool InstCombiner::simplifyDivRemOfSelectWithZeroOp(BinaryOperator &I) {
579 SelectInst *SI = dyn_cast<SelectInst>(I.getOperand(1));
580 if (!SI)
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000581 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000582
Sanjay Patelae2e3a42017-10-06 23:20:16 +0000583 int NonNullOperand;
584 if (match(SI->getTrueValue(), m_Zero()))
585 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
586 NonNullOperand = 2;
587 else if (match(SI->getFalseValue(), m_Zero()))
588 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
589 NonNullOperand = 1;
590 else
591 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000592
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000593 // Change the div/rem to use 'Y' instead of the select.
Nikita Popov4b35c812020-03-30 22:00:16 +0200594 replaceOperand(I, 1, SI->getOperand(NonNullOperand));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000595
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000596 // Okay, we know we replace the operand of the div/rem with 'Y' with no
597 // problem. However, the select, or the condition of the select may have
598 // multiple uses. Based on our knowledge that the operand must be non-zero,
599 // propagate the known value for the select into other uses of it, and
600 // propagate a known value of the condition into its other users.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000601
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000602 // If the select and condition only have a single use, don't bother with this,
603 // early exit.
Sanjay Patelae2e3a42017-10-06 23:20:16 +0000604 Value *SelectCond = SI->getCondition();
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000605 if (SI->use_empty() && SelectCond->hasOneUse())
606 return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000607
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000608 // Scan the current block backward, looking for other uses of SI.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000609 BasicBlock::iterator BBI = I.getIterator(), BBFront = I.getParent()->begin();
Sanjay Patel72d339a2017-10-06 23:43:06 +0000610 Type *CondTy = SelectCond->getType();
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000611 while (BBI != BBFront) {
612 --BBI;
Serguei Katkovd894fb42018-06-04 02:52:36 +0000613 // If we found an instruction that we can't assume will return, so
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000614 // information from below it cannot be propagated above it.
Serguei Katkovd894fb42018-06-04 02:52:36 +0000615 if (!isGuaranteedToTransferExecutionToSuccessor(&*BBI))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000616 break;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000617
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000618 // Replace uses of the select or its condition with the known values.
619 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
620 I != E; ++I) {
621 if (*I == SI) {
Nikita Popov4b35c812020-03-30 22:00:16 +0200622 replaceUse(*I, SI->getOperand(NonNullOperand));
Nikita Popove6c9ab42020-01-30 22:32:46 +0100623 Worklist.push(&*BBI);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000624 } else if (*I == SelectCond) {
Nikita Popov4b35c812020-03-30 22:00:16 +0200625 replaceUse(*I, NonNullOperand == 1 ? ConstantInt::getTrue(CondTy)
626 : ConstantInt::getFalse(CondTy));
Nikita Popove6c9ab42020-01-30 22:32:46 +0100627 Worklist.push(&*BBI);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000628 }
629 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000630
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000631 // If we past the instruction, quit looking for it.
632 if (&*BBI == SI)
Craig Topperf40110f2014-04-25 05:29:35 +0000633 SI = nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000634 if (&*BBI == SelectCond)
Craig Topperf40110f2014-04-25 05:29:35 +0000635 SelectCond = nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000636
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000637 // If we ran out of things to eliminate, break out of the loop.
Craig Topperf40110f2014-04-25 05:29:35 +0000638 if (!SelectCond && !SI)
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000639 break;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000640
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000641 }
642 return true;
643}
644
Sanjay Patel1998cc62018-02-12 18:38:35 +0000645/// True if the multiply can not be expressed in an int this size.
646static bool multiplyOverflows(const APInt &C1, const APInt &C2, APInt &Product,
647 bool IsSigned) {
648 bool Overflow;
649 Product = IsSigned ? C1.smul_ov(C2, Overflow) : C1.umul_ov(C2, Overflow);
650 return Overflow;
651}
652
Sanjay Patel9d2099c2018-07-15 17:06:59 +0000653/// True if C1 is a multiple of C2. Quotient contains C1/C2.
Sanjay Patel1998cc62018-02-12 18:38:35 +0000654static bool isMultiple(const APInt &C1, const APInt &C2, APInt &Quotient,
655 bool IsSigned) {
656 assert(C1.getBitWidth() == C2.getBitWidth() && "Constant widths not equal");
657
658 // Bail if we will divide by zero.
659 if (C2.isNullValue())
660 return false;
661
662 // Bail if we would divide INT_MIN by -1.
663 if (IsSigned && C1.isMinSignedValue() && C2.isAllOnesValue())
664 return false;
665
Rui Ueyama49a3ad22019-07-16 04:46:31 +0000666 APInt Remainder(C1.getBitWidth(), /*val=*/0ULL, IsSigned);
Sanjay Patel1998cc62018-02-12 18:38:35 +0000667 if (IsSigned)
668 APInt::sdivrem(C1, C2, Quotient, Remainder);
669 else
670 APInt::udivrem(C1, C2, Quotient, Remainder);
671
672 return Remainder.isMinValue();
673}
674
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000675/// This function implements the transforms common to both integer division
676/// instructions (udiv and sdiv). It is called by the visitors to those integer
677/// division instructions.
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000678/// Common integer divide transforms
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000679Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
680 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Sanjay Patel9530f182018-01-21 16:14:51 +0000681 bool IsSigned = I.getOpcode() == Instruction::SDiv;
Sanjay Patel39059d22018-02-12 14:14:56 +0000682 Type *Ty = I.getType();
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000683
Chris Lattner7c99f192011-05-22 18:18:41 +0000684 // The RHS is known non-zero.
Nikita Popov1e363022020-03-29 17:08:04 +0200685 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I))
686 return replaceOperand(I, 1, V);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000687
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000688 // Handle cases involving: [su]div X, (select Cond, Y, Z)
689 // This does not apply for fdiv.
Sanjay Patelae2e3a42017-10-06 23:20:16 +0000690 if (simplifyDivRemOfSelectWithZeroOp(I))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000691 return &I;
692
Sanjay Patel1998cc62018-02-12 18:38:35 +0000693 const APInt *C2;
694 if (match(Op1, m_APInt(C2))) {
695 Value *X;
696 const APInt *C1;
David Majnemerf9a095d2014-08-16 08:55:06 +0000697
Sanjay Patel1998cc62018-02-12 18:38:35 +0000698 // (X / C1) / C2 -> X / (C1*C2)
699 if ((IsSigned && match(Op0, m_SDiv(m_Value(X), m_APInt(C1)))) ||
700 (!IsSigned && match(Op0, m_UDiv(m_Value(X), m_APInt(C1))))) {
Rui Ueyama49a3ad22019-07-16 04:46:31 +0000701 APInt Product(C1->getBitWidth(), /*val=*/0ULL, IsSigned);
Sanjay Patel1998cc62018-02-12 18:38:35 +0000702 if (!multiplyOverflows(*C1, *C2, Product, IsSigned))
703 return BinaryOperator::Create(I.getOpcode(), X,
704 ConstantInt::get(Ty, Product));
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000705 }
Sanjay Patel1998cc62018-02-12 18:38:35 +0000706
707 if ((IsSigned && match(Op0, m_NSWMul(m_Value(X), m_APInt(C1)))) ||
708 (!IsSigned && match(Op0, m_NUWMul(m_Value(X), m_APInt(C1))))) {
Rui Ueyama49a3ad22019-07-16 04:46:31 +0000709 APInt Quotient(C1->getBitWidth(), /*val=*/0ULL, IsSigned);
Sanjay Patel1998cc62018-02-12 18:38:35 +0000710
711 // (X * C1) / C2 -> X / (C2 / C1) if C2 is a multiple of C1.
712 if (isMultiple(*C2, *C1, Quotient, IsSigned)) {
713 auto *NewDiv = BinaryOperator::Create(I.getOpcode(), X,
714 ConstantInt::get(Ty, Quotient));
715 NewDiv->setIsExact(I.isExact());
716 return NewDiv;
717 }
718
719 // (X * C1) / C2 -> X * (C1 / C2) if C1 is a multiple of C2.
720 if (isMultiple(*C1, *C2, Quotient, IsSigned)) {
721 auto *Mul = BinaryOperator::Create(Instruction::Mul, X,
722 ConstantInt::get(Ty, Quotient));
723 auto *OBO = cast<OverflowingBinaryOperator>(Op0);
724 Mul->setHasNoUnsignedWrap(!IsSigned && OBO->hasNoUnsignedWrap());
725 Mul->setHasNoSignedWrap(OBO->hasNoSignedWrap());
726 return Mul;
727 }
728 }
729
730 if ((IsSigned && match(Op0, m_NSWShl(m_Value(X), m_APInt(C1))) &&
731 *C1 != C1->getBitWidth() - 1) ||
732 (!IsSigned && match(Op0, m_NUWShl(m_Value(X), m_APInt(C1))))) {
Rui Ueyama49a3ad22019-07-16 04:46:31 +0000733 APInt Quotient(C1->getBitWidth(), /*val=*/0ULL, IsSigned);
Sanjay Patel1998cc62018-02-12 18:38:35 +0000734 APInt C1Shifted = APInt::getOneBitSet(
735 C1->getBitWidth(), static_cast<unsigned>(C1->getLimitedValue()));
736
Sanjay Patel9d2099c2018-07-15 17:06:59 +0000737 // (X << C1) / C2 -> X / (C2 >> C1) if C2 is a multiple of 1 << C1.
Sanjay Patel1998cc62018-02-12 18:38:35 +0000738 if (isMultiple(*C2, C1Shifted, Quotient, IsSigned)) {
739 auto *BO = BinaryOperator::Create(I.getOpcode(), X,
740 ConstantInt::get(Ty, Quotient));
741 BO->setIsExact(I.isExact());
742 return BO;
743 }
744
Sanjay Patel9d2099c2018-07-15 17:06:59 +0000745 // (X << C1) / C2 -> X * ((1 << C1) / C2) if 1 << C1 is a multiple of C2.
Sanjay Patel1998cc62018-02-12 18:38:35 +0000746 if (isMultiple(C1Shifted, *C2, Quotient, IsSigned)) {
747 auto *Mul = BinaryOperator::Create(Instruction::Mul, X,
748 ConstantInt::get(Ty, Quotient));
749 auto *OBO = cast<OverflowingBinaryOperator>(Op0);
750 Mul->setHasNoUnsignedWrap(!IsSigned && OBO->hasNoUnsignedWrap());
751 Mul->setHasNoSignedWrap(OBO->hasNoSignedWrap());
752 return Mul;
753 }
754 }
755
756 if (!C2->isNullValue()) // avoid X udiv 0
Sanjay Patel8fdd87f2018-02-28 16:36:24 +0000757 if (Instruction *FoldedDiv = foldBinOpIntoSelectOrPhi(I))
Sanjay Patel1998cc62018-02-12 18:38:35 +0000758 return FoldedDiv;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000759 }
760
Craig Topper218a3592017-04-17 03:41:47 +0000761 if (match(Op0, m_One())) {
Sanjay Patel39059d22018-02-12 14:14:56 +0000762 assert(!Ty->isIntOrIntVectorTy(1) && "i1 divide not removed?");
763 if (IsSigned) {
Craig Topper218a3592017-04-17 03:41:47 +0000764 // If Op1 is 0 then it's undefined behaviour, if Op1 is 1 then the
765 // result is one, if Op1 is -1 then the result is minus one, otherwise
766 // it's zero.
Craig Topperbb4069e2017-07-07 23:16:26 +0000767 Value *Inc = Builder.CreateAdd(Op1, Op0);
Sanjay Patel39059d22018-02-12 14:14:56 +0000768 Value *Cmp = Builder.CreateICmpULT(Inc, ConstantInt::get(Ty, 3));
769 return SelectInst::Create(Cmp, Op1, ConstantInt::get(Ty, 0));
Craig Topper218a3592017-04-17 03:41:47 +0000770 } else {
771 // If Op1 is 0 then it's undefined behaviour. If Op1 is 1 then the
772 // result is one, otherwise it's zero.
Sanjay Patel39059d22018-02-12 14:14:56 +0000773 return new ZExtInst(Builder.CreateICmpEQ(Op1, Op0), Ty);
Nick Lewyckyf0cf8fa2014-05-14 03:03:05 +0000774 }
775 }
776
Benjamin Kramer57b3df52011-04-30 18:16:00 +0000777 // See if we can fold away this div instruction.
778 if (SimplifyDemandedInstructionBits(I))
779 return &I;
780
Duncan Sands771e82a2011-01-28 16:51:11 +0000781 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
Sanjay Patel9530f182018-01-21 16:14:51 +0000782 Value *X, *Z;
783 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) // (X - Z) / Y; Y = Op1
784 if ((IsSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
785 (!IsSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
Duncan Sands771e82a2011-01-28 16:51:11 +0000786 return BinaryOperator::Create(I.getOpcode(), X, Op1);
Sanjay Patel9530f182018-01-21 16:14:51 +0000787
788 // (X << Y) / X -> 1 << Y
789 Value *Y;
790 if (IsSigned && match(Op0, m_NSWShl(m_Specific(Op1), m_Value(Y))))
Sanjay Patel39059d22018-02-12 14:14:56 +0000791 return BinaryOperator::CreateNSWShl(ConstantInt::get(Ty, 1), Y);
Sanjay Patel9530f182018-01-21 16:14:51 +0000792 if (!IsSigned && match(Op0, m_NUWShl(m_Specific(Op1), m_Value(Y))))
Sanjay Patel39059d22018-02-12 14:14:56 +0000793 return BinaryOperator::CreateNUWShl(ConstantInt::get(Ty, 1), Y);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000794
Sanjay Patel510d6472018-02-11 17:20:32 +0000795 // X / (X * Y) -> 1 / Y if the multiplication does not overflow.
796 if (match(Op1, m_c_Mul(m_Specific(Op0), m_Value(Y)))) {
797 bool HasNSW = cast<OverflowingBinaryOperator>(Op1)->hasNoSignedWrap();
798 bool HasNUW = cast<OverflowingBinaryOperator>(Op1)->hasNoUnsignedWrap();
799 if ((IsSigned && HasNSW) || (!IsSigned && HasNUW)) {
Nikita Popov1e363022020-03-29 17:08:04 +0200800 replaceOperand(I, 0, ConstantInt::get(Ty, 1));
801 replaceOperand(I, 1, Y);
Sanjay Patel510d6472018-02-11 17:20:32 +0000802 return &I;
803 }
804 }
805
Craig Topperf40110f2014-04-25 05:29:35 +0000806 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000807}
808
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000809static const unsigned MaxDepth = 6;
810
David Majnemer37f8f442013-07-04 21:17:49 +0000811namespace {
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000812
813using FoldUDivOperandCb = Instruction *(*)(Value *Op0, Value *Op1,
814 const BinaryOperator &I,
815 InstCombiner &IC);
David Majnemer37f8f442013-07-04 21:17:49 +0000816
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000817/// Used to maintain state for visitUDivOperand().
David Majnemer37f8f442013-07-04 21:17:49 +0000818struct UDivFoldAction {
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000819 /// Informs visitUDiv() how to fold this operand. This can be zero if this
820 /// action joins two actions together.
821 FoldUDivOperandCb FoldAction;
David Majnemer37f8f442013-07-04 21:17:49 +0000822
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000823 /// Which operand to fold.
824 Value *OperandToFold;
825
David Majnemer37f8f442013-07-04 21:17:49 +0000826 union {
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000827 /// The instruction returned when FoldAction is invoked.
828 Instruction *FoldResult;
David Majnemer37f8f442013-07-04 21:17:49 +0000829
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000830 /// Stores the LHS action index if this action joins two actions together.
831 size_t SelectLHSIdx;
David Majnemer37f8f442013-07-04 21:17:49 +0000832 };
833
834 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand)
Craig Topperf40110f2014-04-25 05:29:35 +0000835 : FoldAction(FA), OperandToFold(InputOperand), FoldResult(nullptr) {}
David Majnemer37f8f442013-07-04 21:17:49 +0000836 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand, size_t SLHS)
837 : FoldAction(FA), OperandToFold(InputOperand), SelectLHSIdx(SLHS) {}
838};
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000839
840} // end anonymous namespace
David Majnemer37f8f442013-07-04 21:17:49 +0000841
842// X udiv 2^C -> X >> C
843static Instruction *foldUDivPow2Cst(Value *Op0, Value *Op1,
844 const BinaryOperator &I, InstCombiner &IC) {
Simon Pilgrim94cc89d2018-02-08 14:46:10 +0000845 Constant *C1 = getLogBase2(Op0->getType(), cast<Constant>(Op1));
846 if (!C1)
847 llvm_unreachable("Failed to constant fold udiv -> logbase2");
848 BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, C1);
Suyog Sarda65f5ae92014-10-07 12:04:07 +0000849 if (I.isExact())
850 LShr->setIsExact();
David Majnemer37f8f442013-07-04 21:17:49 +0000851 return LShr;
852}
853
David Majnemer37f8f442013-07-04 21:17:49 +0000854// X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Andrea Di Biagioa82d52d2016-09-26 12:07:23 +0000855// X udiv (zext (C1 << N)), where C1 is "1<<C2" --> X >> (N+C2)
David Majnemer37f8f442013-07-04 21:17:49 +0000856static Instruction *foldUDivShl(Value *Op0, Value *Op1, const BinaryOperator &I,
857 InstCombiner &IC) {
Andrea Di Biagioa82d52d2016-09-26 12:07:23 +0000858 Value *ShiftLeft;
859 if (!match(Op1, m_ZExt(m_Value(ShiftLeft))))
860 ShiftLeft = Op1;
David Majnemer37f8f442013-07-04 21:17:49 +0000861
Simon Pilgrim2a90acd2018-02-08 15:19:38 +0000862 Constant *CI;
Andrea Di Biagioa82d52d2016-09-26 12:07:23 +0000863 Value *N;
Simon Pilgrim2a90acd2018-02-08 15:19:38 +0000864 if (!match(ShiftLeft, m_Shl(m_Constant(CI), m_Value(N))))
Andrea Di Biagioa82d52d2016-09-26 12:07:23 +0000865 llvm_unreachable("match should never fail here!");
Simon Pilgrim2a90acd2018-02-08 15:19:38 +0000866 Constant *Log2Base = getLogBase2(N->getType(), CI);
867 if (!Log2Base)
868 llvm_unreachable("getLogBase2 should never fail here!");
869 N = IC.Builder.CreateAdd(N, Log2Base);
Andrea Di Biagioa82d52d2016-09-26 12:07:23 +0000870 if (Op1 != ShiftLeft)
Craig Topperbb4069e2017-07-07 23:16:26 +0000871 N = IC.Builder.CreateZExt(N, Op1->getType());
David Majnemer37f8f442013-07-04 21:17:49 +0000872 BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, N);
Suyog Sarda65f5ae92014-10-07 12:04:07 +0000873 if (I.isExact())
874 LShr->setIsExact();
David Majnemer37f8f442013-07-04 21:17:49 +0000875 return LShr;
876}
877
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000878// Recursively visits the possible right hand operands of a udiv
David Majnemer37f8f442013-07-04 21:17:49 +0000879// instruction, seeing through select instructions, to determine if we can
880// replace the udiv with something simpler. If we find that an operand is not
881// able to simplify the udiv, we abort the entire transformation.
882static size_t visitUDivOperand(Value *Op0, Value *Op1, const BinaryOperator &I,
883 SmallVectorImpl<UDivFoldAction> &Actions,
884 unsigned Depth = 0) {
885 // Check to see if this is an unsigned division with an exact power of 2,
886 // if so, convert to a right shift.
887 if (match(Op1, m_Power2())) {
888 Actions.push_back(UDivFoldAction(foldUDivPow2Cst, Op1));
889 return Actions.size();
890 }
891
David Majnemer37f8f442013-07-04 21:17:49 +0000892 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
893 if (match(Op1, m_Shl(m_Power2(), m_Value())) ||
894 match(Op1, m_ZExt(m_Shl(m_Power2(), m_Value())))) {
895 Actions.push_back(UDivFoldAction(foldUDivShl, Op1));
896 return Actions.size();
897 }
898
899 // The remaining tests are all recursive, so bail out if we hit the limit.
900 if (Depth++ == MaxDepth)
901 return 0;
902
903 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
David Majnemer492e6122014-08-30 09:19:05 +0000904 if (size_t LHSIdx =
905 visitUDivOperand(Op0, SI->getOperand(1), I, Actions, Depth))
906 if (visitUDivOperand(Op0, SI->getOperand(2), I, Actions, Depth)) {
907 Actions.push_back(UDivFoldAction(nullptr, Op1, LHSIdx - 1));
David Majnemer37f8f442013-07-04 21:17:49 +0000908 return Actions.size();
909 }
910
911 return 0;
912}
913
Sanjay Patelbb789382017-08-24 22:54:01 +0000914/// If we have zero-extended operands of an unsigned div or rem, we may be able
915/// to narrow the operation (sink the zext below the math).
916static Instruction *narrowUDivURem(BinaryOperator &I,
917 InstCombiner::BuilderTy &Builder) {
918 Instruction::BinaryOps Opcode = I.getOpcode();
919 Value *N = I.getOperand(0);
920 Value *D = I.getOperand(1);
921 Type *Ty = I.getType();
922 Value *X, *Y;
923 if (match(N, m_ZExt(m_Value(X))) && match(D, m_ZExt(m_Value(Y))) &&
924 X->getType() == Y->getType() && (N->hasOneUse() || D->hasOneUse())) {
925 // udiv (zext X), (zext Y) --> zext (udiv X, Y)
926 // urem (zext X), (zext Y) --> zext (urem X, Y)
927 Value *NarrowOp = Builder.CreateBinOp(Opcode, X, Y);
928 return new ZExtInst(NarrowOp, Ty);
929 }
930
931 Constant *C;
932 if ((match(N, m_OneUse(m_ZExt(m_Value(X)))) && match(D, m_Constant(C))) ||
933 (match(D, m_OneUse(m_ZExt(m_Value(X)))) && match(N, m_Constant(C)))) {
934 // If the constant is the same in the smaller type, use the narrow version.
935 Constant *TruncC = ConstantExpr::getTrunc(C, X->getType());
936 if (ConstantExpr::getZExt(TruncC, Ty) != C)
937 return nullptr;
938
939 // udiv (zext X), C --> zext (udiv X, C')
940 // urem (zext X), C --> zext (urem X, C')
941 // udiv C, (zext X) --> zext (udiv C', X)
942 // urem C, (zext X) --> zext (urem C', X)
943 Value *NarrowOp = isa<Constant>(D) ? Builder.CreateBinOp(Opcode, X, TruncC)
944 : Builder.CreateBinOp(Opcode, TruncC, X);
945 return new ZExtInst(NarrowOp, Ty);
946 }
947
948 return nullptr;
949}
950
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000951Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
Sanjay Patel7b0fc752018-06-21 17:06:36 +0000952 if (Value *V = SimplifyUDivInst(I.getOperand(0), I.getOperand(1),
953 SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +0000954 return replaceInstUsesWith(I, V);
Duncan Sands771e82a2011-01-28 16:51:11 +0000955
Sanjay Patel79dceb22018-10-03 15:20:58 +0000956 if (Instruction *X = foldVectorBinop(I))
Sanjay Patelbbc6d602018-06-02 16:27:44 +0000957 return X;
958
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000959 // Handle the integer div common cases
960 if (Instruction *Common = commonIDivTransforms(I))
961 return Common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000962
Sanjay Patel7b0fc752018-06-21 17:06:36 +0000963 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Sanjay Patel38a86d32018-06-25 22:50:26 +0000964 Value *X;
965 const APInt *C1, *C2;
966 if (match(Op0, m_LShr(m_Value(X), m_APInt(C1))) && match(Op1, m_APInt(C2))) {
967 // (X lshr C1) udiv C2 --> X udiv (C2 << C1)
968 bool Overflow;
969 APInt C2ShlC1 = C2->ushl_ov(*C1, Overflow);
970 if (!Overflow) {
971 bool IsExact = I.isExact() && match(Op0, m_Exact(m_Value()));
972 BinaryOperator *BO = BinaryOperator::CreateUDiv(
973 X, ConstantInt::get(X->getType(), C2ShlC1));
974 if (IsExact)
975 BO->setIsExact();
976 return BO;
David Majnemera2521382014-10-13 21:48:30 +0000977 }
Nadav Rotem11935b22012-08-28 10:01:43 +0000978 }
979
Sanjay Patel38a86d32018-06-25 22:50:26 +0000980 // Op0 / C where C is large (negative) --> zext (Op0 >= C)
981 // TODO: Could use isKnownNegative() to handle non-constant values.
Sanjay Patel7c45deb2018-06-26 12:41:15 +0000982 Type *Ty = I.getType();
Sanjay Patel38a86d32018-06-25 22:50:26 +0000983 if (match(Op1, m_Negative())) {
984 Value *Cmp = Builder.CreateICmpUGE(Op0, Op1);
Sanjay Patel7c45deb2018-06-26 12:41:15 +0000985 return CastInst::CreateZExtOrBitCast(Cmp, Ty);
986 }
987 // Op0 / (sext i1 X) --> zext (Op0 == -1) (if X is 0, the div is undefined)
988 if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
989 Value *Cmp = Builder.CreateICmpEQ(Op0, ConstantInt::getAllOnesValue(Ty));
990 return CastInst::CreateZExtOrBitCast(Cmp, Ty);
Sanjay Patel38a86d32018-06-25 22:50:26 +0000991 }
992
Sanjay Patelbb789382017-08-24 22:54:01 +0000993 if (Instruction *NarrowDiv = narrowUDivURem(I, Builder))
994 return NarrowDiv;
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000995
Sanjay Patel6d6eab62018-07-26 19:22:41 +0000996 // If the udiv operands are non-overflowing multiplies with a common operand,
997 // then eliminate the common factor:
998 // (A * B) / (A * X) --> B / X (and commuted variants)
999 // TODO: The code would be reduced if we had m_c_NUWMul pattern matching.
1000 // TODO: If -reassociation handled this generally, we could remove this.
1001 Value *A, *B;
1002 if (match(Op0, m_NUWMul(m_Value(A), m_Value(B)))) {
1003 if (match(Op1, m_NUWMul(m_Specific(A), m_Value(X))) ||
1004 match(Op1, m_NUWMul(m_Value(X), m_Specific(A))))
1005 return BinaryOperator::CreateUDiv(B, X);
1006 if (match(Op1, m_NUWMul(m_Specific(B), m_Value(X))) ||
1007 match(Op1, m_NUWMul(m_Value(X), m_Specific(B))))
1008 return BinaryOperator::CreateUDiv(A, X);
1009 }
1010
David Majnemer37f8f442013-07-04 21:17:49 +00001011 // (LHS udiv (select (select (...)))) -> (LHS >> (select (select (...))))
1012 SmallVector<UDivFoldAction, 6> UDivActions;
1013 if (visitUDivOperand(Op0, Op1, I, UDivActions))
1014 for (unsigned i = 0, e = UDivActions.size(); i != e; ++i) {
1015 FoldUDivOperandCb Action = UDivActions[i].FoldAction;
1016 Value *ActionOp1 = UDivActions[i].OperandToFold;
1017 Instruction *Inst;
1018 if (Action)
1019 Inst = Action(Op0, ActionOp1, I, *this);
1020 else {
1021 // This action joins two actions together. The RHS of this action is
1022 // simply the last action we processed, we saved the LHS action index in
1023 // the joining action.
1024 size_t SelectRHSIdx = i - 1;
1025 Value *SelectRHS = UDivActions[SelectRHSIdx].FoldResult;
1026 size_t SelectLHSIdx = UDivActions[i].SelectLHSIdx;
1027 Value *SelectLHS = UDivActions[SelectLHSIdx].FoldResult;
1028 Inst = SelectInst::Create(cast<SelectInst>(ActionOp1)->getCondition(),
1029 SelectLHS, SelectRHS);
1030 }
1031
1032 // If this is the last action to process, return it to the InstCombiner.
1033 // Otherwise, we insert it before the UDiv and record it so that we may
1034 // use it as part of a joining action (i.e., a SelectInst).
1035 if (e - i != 1) {
1036 Inst->insertBefore(&I);
1037 UDivActions[i].FoldResult = Inst;
1038 } else
1039 return Inst;
1040 }
1041
Craig Topperf40110f2014-04-25 05:29:35 +00001042 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001043}
1044
1045Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
Sanjay Patel7b0fc752018-06-21 17:06:36 +00001046 if (Value *V = SimplifySDivInst(I.getOperand(0), I.getOperand(1),
1047 SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001048 return replaceInstUsesWith(I, V);
Duncan Sands771e82a2011-01-28 16:51:11 +00001049
Sanjay Patel79dceb22018-10-03 15:20:58 +00001050 if (Instruction *X = foldVectorBinop(I))
Sanjay Patelbbc6d602018-06-02 16:27:44 +00001051 return X;
1052
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001053 // Handle the integer div common cases
1054 if (Instruction *Common = commonIDivTransforms(I))
1055 return Common;
1056
Sanjay Patel7b0fc752018-06-21 17:06:36 +00001057 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Sanjay Patel6a96d902018-06-25 21:39:41 +00001058 Value *X;
1059 // sdiv Op0, -1 --> -Op0
1060 // sdiv Op0, (sext i1 X) --> -Op0 (because if X is 0, the op is undefined)
1061 if (match(Op1, m_AllOnes()) ||
1062 (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)))
1063 return BinaryOperator::CreateNeg(Op0);
1064
Sanjay Patel49d9d172019-04-09 15:13:03 +00001065 // X / INT_MIN --> X == INT_MIN
1066 if (match(Op1, m_SignMask()))
1067 return new ZExtInst(Builder.CreateICmpEQ(Op0, Op1), I.getType());
1068
Sanjay Patelc6ada532016-06-27 17:25:57 +00001069 const APInt *Op1C;
Sanjay Patelbedd1f92016-06-27 18:38:40 +00001070 if (match(Op1, m_APInt(Op1C))) {
Sanjay Patelbedd1f92016-06-27 18:38:40 +00001071 // sdiv exact X, C --> ashr exact X, log2(C)
1072 if (I.isExact() && Op1C->isNonNegative() && Op1C->isPowerOf2()) {
1073 Value *ShAmt = ConstantInt::get(Op1->getType(), Op1C->exactLogBase2());
1074 return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
1075 }
Sanjay Patel59ed2ff2016-06-27 22:27:11 +00001076
1077 // If the dividend is sign-extended and the constant divisor is small enough
1078 // to fit in the source type, shrink the division to the narrower type:
1079 // (sext X) sdiv C --> sext (X sdiv C)
1080 Value *Op0Src;
1081 if (match(Op0, m_OneUse(m_SExt(m_Value(Op0Src)))) &&
1082 Op0Src->getType()->getScalarSizeInBits() >= Op1C->getMinSignedBits()) {
1083
1084 // In the general case, we need to make sure that the dividend is not the
1085 // minimum signed value because dividing that by -1 is UB. But here, we
1086 // know that the -1 divisor case is already handled above.
1087
1088 Constant *NarrowDivisor =
1089 ConstantExpr::getTrunc(cast<Constant>(Op1), Op0Src->getType());
Craig Topperbb4069e2017-07-07 23:16:26 +00001090 Value *NarrowOp = Builder.CreateSDiv(Op0Src, NarrowDivisor);
Sanjay Patel59ed2ff2016-06-27 22:27:11 +00001091 return new SExtInst(NarrowOp, Op0->getType());
1092 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001093
Sanjay Patel49d9d172019-04-09 15:13:03 +00001094 // -X / C --> X / -C (if the negation doesn't overflow).
1095 // TODO: This could be enhanced to handle arbitrary vector constants by
1096 // checking if all elements are not the min-signed-val.
1097 if (!Op1C->isMinSignedValue() &&
1098 match(Op0, m_NSWSub(m_Zero(), m_Value(X)))) {
1099 Constant *NegC = ConstantInt::get(I.getType(), -(*Op1C));
1100 Instruction *BO = BinaryOperator::CreateSDiv(X, NegC);
David Majnemerfa4699e2014-11-22 20:00:34 +00001101 BO->setIsExact(I.isExact());
1102 return BO;
1103 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001104 }
1105
Chen Zheng5e13ff12019-04-10 06:52:09 +00001106 // -X / Y --> -(X / Y)
1107 Value *Y;
1108 if (match(&I, m_SDiv(m_OneUse(m_NSWSub(m_Zero(), m_Value(X))), m_Value(Y))))
1109 return BinaryOperator::CreateNSWNeg(
1110 Builder.CreateSDiv(X, Y, I.getName(), I.isExact()));
1111
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001112 // If the sign bits of both operands are zero (i.e. we can prove they are
1113 // unsigned inputs), turn this into a udiv.
Craig Topperbcfd2d12017-04-20 16:56:25 +00001114 APInt Mask(APInt::getSignMask(I.getType()->getScalarSizeInBits()));
Craig Topperf2484682017-04-17 01:51:19 +00001115 if (MaskedValueIsZero(Op0, Mask, 0, &I)) {
1116 if (MaskedValueIsZero(Op1, Mask, 0, &I)) {
1117 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
1118 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1119 BO->setIsExact(I.isExact());
1120 return BO;
1121 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001122
Craig Topperd4039f72017-05-25 21:51:12 +00001123 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/ true, 0, &I)) {
Craig Topperf2484682017-04-17 01:51:19 +00001124 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
1125 // Safe because the only negative value (1 << Y) can take on is
1126 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
1127 // the sign bit set.
1128 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1129 BO->setIsExact(I.isExact());
1130 return BO;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001131 }
1132 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001133
Craig Topperf40110f2014-04-25 05:29:35 +00001134 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001135}
1136
Sanjay Pateld8dd0152018-02-20 23:51:16 +00001137/// Remove negation and try to convert division into multiplication.
Sanjay Patel90f4c8e2018-02-20 16:08:15 +00001138static Instruction *foldFDivConstantDivisor(BinaryOperator &I) {
1139 Constant *C;
1140 if (!match(I.getOperand(1), m_Constant(C)))
Craig Topperf40110f2014-04-25 05:29:35 +00001141 return nullptr;
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001142
Sanjay Pateld8dd0152018-02-20 23:51:16 +00001143 // -X / C --> X / -C
1144 Value *X;
1145 if (match(I.getOperand(0), m_FNeg(m_Value(X))))
Sanjay Patel5a6f9042018-02-21 22:18:55 +00001146 return BinaryOperator::CreateFDivFMF(X, ConstantExpr::getFNeg(C), &I);
Sanjay Pateld8dd0152018-02-20 23:51:16 +00001147
Sanjay Patel90f4c8e2018-02-20 16:08:15 +00001148 // If the constant divisor has an exact inverse, this is always safe. If not,
1149 // then we can still create a reciprocal if fast-math-flags allow it and the
1150 // constant is a regular number (not zero, infinite, or denormal).
1151 if (!(C->hasExactInverseFP() || (I.hasAllowReciprocal() && C->isNormalFP())))
Craig Topperf40110f2014-04-25 05:29:35 +00001152 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001153
Sanjay Patel90f4c8e2018-02-20 16:08:15 +00001154 // Disallow denormal constants because we don't know what would happen
1155 // on all targets.
1156 // TODO: Use Intrinsic::canonicalize or let function attributes tell us that
1157 // denorms are flushed?
1158 auto *RecipC = ConstantExpr::getFDiv(ConstantFP::get(I.getType(), 1.0), C);
1159 if (!RecipC->isNormalFP())
1160 return nullptr;
1161
Sanjay Pateld8dd0152018-02-20 23:51:16 +00001162 // X / C --> X * (1 / C)
Sanjay Patel5a6f9042018-02-21 22:18:55 +00001163 return BinaryOperator::CreateFMulFMF(I.getOperand(0), RecipC, &I);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001164}
1165
Sanjay Patel6f716a72018-02-21 00:01:45 +00001166/// Remove negation and try to reassociate constant math.
Sanjay Patele4129542018-02-19 21:17:58 +00001167static Instruction *foldFDivConstantDividend(BinaryOperator &I) {
Sanjay Patel6f716a72018-02-21 00:01:45 +00001168 Constant *C;
1169 if (!match(I.getOperand(0), m_Constant(C)))
Sanjay Patele4129542018-02-19 21:17:58 +00001170 return nullptr;
1171
Sanjay Patel6f716a72018-02-21 00:01:45 +00001172 // C / -X --> -C / X
Sanjay Patele4129542018-02-19 21:17:58 +00001173 Value *X;
Sanjay Patel5a6f9042018-02-21 22:18:55 +00001174 if (match(I.getOperand(1), m_FNeg(m_Value(X))))
1175 return BinaryOperator::CreateFDivFMF(ConstantExpr::getFNeg(C), X, &I);
Sanjay Patel6f716a72018-02-21 00:01:45 +00001176
1177 if (!I.hasAllowReassoc() || !I.hasAllowReciprocal())
1178 return nullptr;
1179
1180 // Try to reassociate C / X expressions where X includes another constant.
Sanjay Patele4129542018-02-19 21:17:58 +00001181 Constant *C2, *NewC = nullptr;
1182 if (match(I.getOperand(1), m_FMul(m_Value(X), m_Constant(C2)))) {
Sanjay Patel6f716a72018-02-21 00:01:45 +00001183 // C / (X * C2) --> (C / C2) / X
1184 NewC = ConstantExpr::getFDiv(C, C2);
Sanjay Patele4129542018-02-19 21:17:58 +00001185 } else if (match(I.getOperand(1), m_FDiv(m_Value(X), m_Constant(C2)))) {
Sanjay Patel6f716a72018-02-21 00:01:45 +00001186 // C / (X / C2) --> (C * C2) / X
1187 NewC = ConstantExpr::getFMul(C, C2);
Sanjay Patele4129542018-02-19 21:17:58 +00001188 }
1189 // Disallow denormal constants because we don't know what would happen
1190 // on all targets.
1191 // TODO: Use Intrinsic::canonicalize or let function attributes tell us that
1192 // denorms are flushed?
1193 if (!NewC || !NewC->isNormalFP())
1194 return nullptr;
1195
Sanjay Patel5a6f9042018-02-21 22:18:55 +00001196 return BinaryOperator::CreateFDivFMF(NewC, X, &I);
Sanjay Patele4129542018-02-19 21:17:58 +00001197}
1198
Frits van Bommel2a559512011-01-29 17:50:27 +00001199Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
Sanjay Patel7b0fc752018-06-21 17:06:36 +00001200 if (Value *V = SimplifyFDivInst(I.getOperand(0), I.getOperand(1),
1201 I.getFastMathFlags(),
Craig Toppera4205622017-06-09 03:21:29 +00001202 SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001203 return replaceInstUsesWith(I, V);
Frits van Bommel2a559512011-01-29 17:50:27 +00001204
Sanjay Patel79dceb22018-10-03 15:20:58 +00001205 if (Instruction *X = foldVectorBinop(I))
Sanjay Patelbbc6d602018-06-02 16:27:44 +00001206 return X;
1207
Sanjay Pateld8dd0152018-02-20 23:51:16 +00001208 if (Instruction *R = foldFDivConstantDivisor(I))
1209 return R;
Sanjay Patel28165602018-02-19 23:09:03 +00001210
Sanjay Pateld8dd0152018-02-20 23:51:16 +00001211 if (Instruction *R = foldFDivConstantDividend(I))
1212 return R;
Sanjay Patelb39bcc02018-02-14 23:04:17 +00001213
Sanjay Patel7b0fc752018-06-21 17:06:36 +00001214 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Stephen Lina9b57f62013-07-20 07:13:13 +00001215 if (isa<Constant>(Op0))
1216 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1217 if (Instruction *R = FoldOpIntoSelect(I, SI))
1218 return R;
1219
Sanjay Patel29b98ae2018-02-20 17:14:53 +00001220 if (isa<Constant>(Op1))
Stephen Lina9b57f62013-07-20 07:13:13 +00001221 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1222 if (Instruction *R = FoldOpIntoSelect(I, SI))
1223 return R;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001224
Sanjay Patel31a90462018-02-26 16:02:45 +00001225 if (I.hasAllowReassoc() && I.hasAllowReciprocal()) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001226 Value *X, *Y;
Sanjay Patel91bb7752018-02-16 17:52:32 +00001227 if (match(Op0, m_OneUse(m_FDiv(m_Value(X), m_Value(Y)))) &&
1228 (!isa<Constant>(Y) || !isa<Constant>(Op1))) {
1229 // (X / Y) / Z => X / (Y * Z)
Sanjay Patel31a90462018-02-26 16:02:45 +00001230 Value *YZ = Builder.CreateFMulFMF(Y, Op1, &I);
Sanjay Patel5a6f9042018-02-21 22:18:55 +00001231 return BinaryOperator::CreateFDivFMF(X, YZ, &I);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001232 }
Sanjay Patel91bb7752018-02-16 17:52:32 +00001233 if (match(Op1, m_OneUse(m_FDiv(m_Value(X), m_Value(Y)))) &&
1234 (!isa<Constant>(Y) || !isa<Constant>(Op0))) {
1235 // Z / (X / Y) => (Y * Z) / X
Sanjay Patel31a90462018-02-26 16:02:45 +00001236 Value *YZ = Builder.CreateFMulFMF(Y, Op0, &I);
Sanjay Patel5a6f9042018-02-21 22:18:55 +00001237 return BinaryOperator::CreateFDivFMF(YZ, X, &I);
Benjamin Kramer8564e0d2011-03-30 15:42:35 +00001238 }
@raghesh (Raghesh Aloor)6c04ef42020-01-09 10:52:39 -05001239 // Z / (1.0 / Y) => (Y * Z)
1240 //
1241 // This is a special case of Z / (X / Y) => (Y * Z) / X, with X = 1.0. The
1242 // m_OneUse check is avoided because even in the case of the multiple uses
1243 // for 1.0/Y, the number of instructions remain the same and a division is
1244 // replaced by a multiplication.
1245 if (match(Op1, m_FDiv(m_SpecificFP(1.0), m_Value(Y))))
1246 return BinaryOperator::CreateFMulFMF(Y, Op0, &I);
Benjamin Kramer8564e0d2011-03-30 15:42:35 +00001247 }
1248
Sanjay Patel339b4d32018-02-15 15:07:12 +00001249 if (I.hasAllowReassoc() && Op0->hasOneUse() && Op1->hasOneUse()) {
Sanjay Patel65da14d2018-02-16 16:13:20 +00001250 // sin(X) / cos(X) -> tan(X)
1251 // cos(X) / sin(X) -> 1/tan(X) (cotangent)
1252 Value *X;
1253 bool IsTan = match(Op0, m_Intrinsic<Intrinsic::sin>(m_Value(X))) &&
1254 match(Op1, m_Intrinsic<Intrinsic::cos>(m_Specific(X)));
1255 bool IsCot =
1256 !IsTan && match(Op0, m_Intrinsic<Intrinsic::cos>(m_Value(X))) &&
1257 match(Op1, m_Intrinsic<Intrinsic::sin>(m_Specific(X)));
Dmitry Venikove5fbf592018-01-11 06:33:00 +00001258
Evandro Menezesc6c00cd2019-08-09 16:04:18 +00001259 if ((IsTan || IsCot) &&
1260 hasFloatFn(&TLI, I.getType(), LibFunc_tan, LibFunc_tanf, LibFunc_tanl)) {
Sanjay Patel65da14d2018-02-16 16:13:20 +00001261 IRBuilder<> B(&I);
1262 IRBuilder<>::FastMathFlagGuard FMFGuard(B);
1263 B.setFastMathFlags(I.getFastMathFlags());
Craig Topperc1892ec2019-01-31 17:23:29 +00001264 AttributeList Attrs =
1265 cast<CallBase>(Op0)->getCalledFunction()->getAttributes();
Mikael Holmene3605d02018-10-18 06:27:53 +00001266 Value *Res = emitUnaryFloatFnCall(X, &TLI, LibFunc_tan, LibFunc_tanf,
1267 LibFunc_tanl, B, Attrs);
Sanjay Patel65da14d2018-02-16 16:13:20 +00001268 if (IsCot)
1269 Res = B.CreateFDiv(ConstantFP::get(I.getType(), 1.0), Res);
1270 return replaceInstUsesWith(I, Res);
Dmitry Venikove5fbf592018-01-11 06:33:00 +00001271 }
1272 }
1273
Sanjay Patel1998cc62018-02-12 18:38:35 +00001274 // -X / -Y -> X / Y
1275 Value *X, *Y;
1276 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y)))) {
Nikita Popov1e363022020-03-29 17:08:04 +02001277 replaceOperand(I, 0, X);
1278 replaceOperand(I, 1, Y);
Matt Arsenaultfdb78f82017-01-10 23:08:54 +00001279 return &I;
1280 }
1281
Sanjay Patel4a4f35f2018-02-12 19:39:21 +00001282 // X / (X * Y) --> 1.0 / Y
1283 // Reassociate to (X / X -> 1.0) is legal when NaNs are not allowed.
1284 // We can ignore the possibility that X is infinity because INF/INF is NaN.
1285 if (I.hasNoNaNs() && I.hasAllowReassoc() &&
1286 match(Op1, m_c_FMul(m_Specific(Op0), m_Value(Y)))) {
Nikita Popov1e363022020-03-29 17:08:04 +02001287 replaceOperand(I, 0, ConstantFP::get(I.getType(), 1.0));
1288 replaceOperand(I, 1, Y);
Sanjay Patel4a4f35f2018-02-12 19:39:21 +00001289 return &I;
1290 }
1291
David Bolvansky20d37fa2019-08-12 13:43:35 +00001292 // X / fabs(X) -> copysign(1.0, X)
1293 // fabs(X) / X -> copysign(1.0, X)
1294 if (I.hasNoNaNs() && I.hasNoInfs() &&
1295 (match(&I,
1296 m_FDiv(m_Value(X), m_Intrinsic<Intrinsic::fabs>(m_Deferred(X)))) ||
1297 match(&I, m_FDiv(m_Intrinsic<Intrinsic::fabs>(m_Value(X)),
1298 m_Deferred(X))))) {
1299 Value *V = Builder.CreateBinaryIntrinsic(
1300 Intrinsic::copysign, ConstantFP::get(I.getType(), 1.0), X, &I);
1301 return replaceInstUsesWith(I, V);
1302 }
Craig Topperf40110f2014-04-25 05:29:35 +00001303 return nullptr;
Frits van Bommel2a559512011-01-29 17:50:27 +00001304}
1305
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001306/// This function implements the transforms common to both integer remainder
1307/// instructions (urem and srem). It is called by the visitors to those integer
1308/// remainder instructions.
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +00001309/// Common integer remainder transforms
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001310Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
1311 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1312
Chris Lattner7c99f192011-05-22 18:18:41 +00001313 // The RHS is known non-zero.
Nikita Popov1e363022020-03-29 17:08:04 +02001314 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I))
1315 return replaceOperand(I, 1, V);
Chris Lattner7c99f192011-05-22 18:18:41 +00001316
Duncan Sandsa3e36992011-05-02 16:27:02 +00001317 // Handle cases involving: rem X, (select Cond, Y, Z)
Sanjay Patelae2e3a42017-10-06 23:20:16 +00001318 if (simplifyDivRemOfSelectWithZeroOp(I))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001319 return &I;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001320
Benjamin Kramer72196f32014-01-19 15:24:22 +00001321 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001322 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1323 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1324 if (Instruction *R = FoldOpIntoSelect(I, SI))
1325 return R;
Craig Topperfb71b7d2017-04-14 19:20:12 +00001326 } else if (auto *PN = dyn_cast<PHINode>(Op0I)) {
Sanjoy Dasb7e861a2016-06-05 21:17:04 +00001327 const APInt *Op1Int;
1328 if (match(Op1, m_APInt(Op1Int)) && !Op1Int->isMinValue() &&
1329 (I.getOpcode() == Instruction::URem ||
1330 !Op1Int->isMinSignedValue())) {
Craig Topperfb71b7d2017-04-14 19:20:12 +00001331 // foldOpIntoPhi will speculate instructions to the end of the PHI's
Sanjoy Dasb7e861a2016-06-05 21:17:04 +00001332 // predecessor blocks, so do this only if we know the srem or urem
1333 // will not fault.
Craig Topperfb71b7d2017-04-14 19:20:12 +00001334 if (Instruction *NV = foldOpIntoPhi(I, PN))
Sanjoy Dasb7e861a2016-06-05 21:17:04 +00001335 return NV;
1336 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001337 }
1338
1339 // See if we can fold away this rem instruction.
1340 if (SimplifyDemandedInstructionBits(I))
1341 return &I;
1342 }
1343 }
1344
Craig Topperf40110f2014-04-25 05:29:35 +00001345 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001346}
1347
1348Instruction *InstCombiner::visitURem(BinaryOperator &I) {
Sanjay Patel7b0fc752018-06-21 17:06:36 +00001349 if (Value *V = SimplifyURemInst(I.getOperand(0), I.getOperand(1),
1350 SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001351 return replaceInstUsesWith(I, V);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001352
Sanjay Patel79dceb22018-10-03 15:20:58 +00001353 if (Instruction *X = foldVectorBinop(I))
Sanjay Patelbbc6d602018-06-02 16:27:44 +00001354 return X;
1355
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001356 if (Instruction *common = commonIRemTransforms(I))
1357 return common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001358
Sanjay Patelbb789382017-08-24 22:54:01 +00001359 if (Instruction *NarrowRem = narrowUDivURem(I, Builder))
1360 return NarrowRem;
David Majnemer6c30f492013-05-12 00:07:05 +00001361
David Majnemer470b0772013-05-11 09:01:28 +00001362 // X urem Y -> X and Y-1, where Y is a power of 2,
Sanjay Patel7b0fc752018-06-21 17:06:36 +00001363 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Sanjay Patel3575f0c2018-06-26 16:30:00 +00001364 Type *Ty = I.getType();
Craig Topperd4039f72017-05-25 21:51:12 +00001365 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/ true, 0, &I)) {
Roman Lebedevbe612ea2019-07-30 15:28:22 +00001366 // This may increase instruction count, we don't enforce that Y is a
1367 // constant.
Sanjay Patel3575f0c2018-06-26 16:30:00 +00001368 Constant *N1 = Constant::getAllOnesValue(Ty);
Craig Topperbb4069e2017-07-07 23:16:26 +00001369 Value *Add = Builder.CreateAdd(Op1, N1);
Chris Lattner6b657ae2011-02-10 05:36:31 +00001370 return BinaryOperator::CreateAnd(Op0, Add);
1371 }
1372
Nick Lewycky7459be62013-07-13 01:16:47 +00001373 // 1 urem X -> zext(X != 1)
Sanjay Patelaf4e5992019-12-02 12:10:05 -05001374 if (match(Op0, m_One())) {
1375 Value *Cmp = Builder.CreateICmpNE(Op1, ConstantInt::get(Ty, 1));
1376 return CastInst::CreateZExtOrBitCast(Cmp, Ty);
1377 }
Nick Lewycky7459be62013-07-13 01:16:47 +00001378
Sanjay Patel30ef70b2016-09-22 22:36:26 +00001379 // X urem C -> X < C ? X : X - C, where C >= signbit.
Simon Pilgrim1889f262018-02-08 18:36:01 +00001380 if (match(Op1, m_Negative())) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001381 Value *Cmp = Builder.CreateICmpULT(Op0, Op1);
1382 Value *Sub = Builder.CreateSub(Op0, Op1);
Sanjay Patel30ef70b2016-09-22 22:36:26 +00001383 return SelectInst::Create(Cmp, Op0, Sub);
1384 }
1385
Sanjay Patel3575f0c2018-06-26 16:30:00 +00001386 // If the divisor is a sext of a boolean, then the divisor must be max
1387 // unsigned value (-1). Therefore, the remainder is Op0 unless Op0 is also
1388 // max unsigned value. In that case, the remainder is 0:
1389 // urem Op0, (sext i1 X) --> (Op0 == -1) ? 0 : Op0
1390 Value *X;
1391 if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
1392 Value *Cmp = Builder.CreateICmpEQ(Op0, ConstantInt::getAllOnesValue(Ty));
1393 return SelectInst::Create(Cmp, ConstantInt::getNullValue(Ty), Op0);
1394 }
1395
Craig Topperf40110f2014-04-25 05:29:35 +00001396 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001397}
1398
1399Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
Sanjay Patel7b0fc752018-06-21 17:06:36 +00001400 if (Value *V = SimplifySRemInst(I.getOperand(0), I.getOperand(1),
1401 SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001402 return replaceInstUsesWith(I, V);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001403
Sanjay Patel79dceb22018-10-03 15:20:58 +00001404 if (Instruction *X = foldVectorBinop(I))
Sanjay Patelbbc6d602018-06-02 16:27:44 +00001405 return X;
1406
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001407 // Handle the integer rem common cases
1408 if (Instruction *Common = commonIRemTransforms(I))
1409 return Common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001410
Sanjay Patel7b0fc752018-06-21 17:06:36 +00001411 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
David Majnemerdb077302014-10-13 22:37:51 +00001412 {
1413 const APInt *Y;
1414 // X % -Y -> X % Y
Nikita Popov878cb382020-01-31 22:23:33 +01001415 if (match(Op1, m_Negative(Y)) && !Y->isMinSignedValue())
1416 return replaceOperand(I, 1, ConstantInt::get(I.getType(), -*Y));
David Majnemerdb077302014-10-13 22:37:51 +00001417 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001418
Chen Zheng87dd0e02019-04-13 09:21:22 +00001419 // -X srem Y --> -(X srem Y)
1420 Value *X, *Y;
1421 if (match(&I, m_SRem(m_OneUse(m_NSWSub(m_Zero(), m_Value(X))), m_Value(Y))))
1422 return BinaryOperator::CreateNSWNeg(Builder.CreateSRem(X, Y));
1423
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001424 // If the sign bits of both operands are zero (i.e. we can prove they are
1425 // unsigned inputs), turn this into a urem.
Craig Topperbcfd2d12017-04-20 16:56:25 +00001426 APInt Mask(APInt::getSignMask(I.getType()->getScalarSizeInBits()));
Craig Topper1a18a7c2017-04-17 01:51:24 +00001427 if (MaskedValueIsZero(Op1, Mask, 0, &I) &&
1428 MaskedValueIsZero(Op0, Mask, 0, &I)) {
1429 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
1430 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001431 }
1432
1433 // If it's a constant vector, flip any negative values positive.
Chris Lattner0256be92012-01-27 03:08:05 +00001434 if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
1435 Constant *C = cast<Constant>(Op1);
1436 unsigned VWidth = C->getType()->getVectorNumElements();
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001437
1438 bool hasNegative = false;
Chris Lattner0256be92012-01-27 03:08:05 +00001439 bool hasMissing = false;
1440 for (unsigned i = 0; i != VWidth; ++i) {
1441 Constant *Elt = C->getAggregateElement(i);
Craig Topperf40110f2014-04-25 05:29:35 +00001442 if (!Elt) {
Chris Lattner0256be92012-01-27 03:08:05 +00001443 hasMissing = true;
1444 break;
1445 }
1446
1447 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
Chris Lattnerb1a15122011-07-15 06:08:15 +00001448 if (RHS->isNegative())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001449 hasNegative = true;
Chris Lattner0256be92012-01-27 03:08:05 +00001450 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001451
Chris Lattner0256be92012-01-27 03:08:05 +00001452 if (hasNegative && !hasMissing) {
Chris Lattner47a86bd2012-01-25 06:02:56 +00001453 SmallVector<Constant *, 16> Elts(VWidth);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001454 for (unsigned i = 0; i != VWidth; ++i) {
Chris Lattner8213c8a2012-02-06 21:56:39 +00001455 Elts[i] = C->getAggregateElement(i); // Handle undef, etc.
Chris Lattner0256be92012-01-27 03:08:05 +00001456 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
Chris Lattnerb1a15122011-07-15 06:08:15 +00001457 if (RHS->isNegative())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001458 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001459 }
1460 }
1461
1462 Constant *NewRHSV = ConstantVector::get(Elts);
Nikita Popov878cb382020-01-31 22:23:33 +01001463 if (NewRHSV != C) // Don't loop on -MININT
1464 return replaceOperand(I, 1, NewRHSV);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001465 }
1466 }
1467
Craig Topperf40110f2014-04-25 05:29:35 +00001468 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001469}
1470
1471Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Sanjay Patel7b0fc752018-06-21 17:06:36 +00001472 if (Value *V = SimplifyFRemInst(I.getOperand(0), I.getOperand(1),
1473 I.getFastMathFlags(),
Craig Toppera4205622017-06-09 03:21:29 +00001474 SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001475 return replaceInstUsesWith(I, V);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001476
Sanjay Patel79dceb22018-10-03 15:20:58 +00001477 if (Instruction *X = foldVectorBinop(I))
Sanjay Patelbbc6d602018-06-02 16:27:44 +00001478 return X;
1479
Craig Topperf40110f2014-04-25 05:29:35 +00001480 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001481}