LLVM 19.0.0git
InstCombineMulDivRem.cpp
Go to the documentation of this file.
1//===- InstCombineMulDivRem.cpp -------------------------------------------===//
2//
3// 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
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the visit functions for mul, fmul, sdiv, udiv, fdiv,
10// srem, urem, frem.
11//
12//===----------------------------------------------------------------------===//
13
14#include "InstCombineInternal.h"
15#include "llvm/ADT/APInt.h"
19#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"
26#include "llvm/IR/Intrinsics.h"
27#include "llvm/IR/Operator.h"
29#include "llvm/IR/Type.h"
30#include "llvm/IR/Value.h"
35#include <cassert>
36
37#define DEBUG_TYPE "instcombine"
39
40using namespace llvm;
41using namespace PatternMatch;
42
43/// The specific integer value is used in a context where it is known to be
44/// non-zero. If this allows us to simplify the computation, do so and return
45/// the new operand, otherwise return null.
47 Instruction &CxtI) {
48 // If V has multiple uses, then we would have to do more analysis to determine
49 // if this is safe. For example, the use could be in dynamically unreached
50 // code.
51 if (!V->hasOneUse()) return nullptr;
52
53 bool MadeChange = false;
54
55 // ((1 << A) >>u B) --> (1 << (A-B))
56 // Because V cannot be zero, we know that B is less than A.
57 Value *A = nullptr, *B = nullptr, *One = nullptr;
58 if (match(V, m_LShr(m_OneUse(m_Shl(m_Value(One), m_Value(A))), m_Value(B))) &&
59 match(One, m_One())) {
60 A = IC.Builder.CreateSub(A, B);
61 return IC.Builder.CreateShl(One, A);
62 }
63
64 // (PowerOfTwo >>u B) --> isExact since shifting out the result would make it
65 // inexact. Similarly for <<.
66 BinaryOperator *I = dyn_cast<BinaryOperator>(V);
67 if (I && I->isLogicalShift() &&
68 IC.isKnownToBeAPowerOfTwo(I->getOperand(0), false, 0, &CxtI)) {
69 // We know that this is an exact/nuw shift and that the input is a
70 // non-zero context as well.
71 if (Value *V2 = simplifyValueKnownNonZero(I->getOperand(0), IC, CxtI)) {
72 IC.replaceOperand(*I, 0, V2);
73 MadeChange = true;
74 }
75
76 if (I->getOpcode() == Instruction::LShr && !I->isExact()) {
77 I->setIsExact();
78 MadeChange = true;
79 }
80
81 if (I->getOpcode() == Instruction::Shl && !I->hasNoUnsignedWrap()) {
82 I->setHasNoUnsignedWrap();
83 MadeChange = true;
84 }
85 }
86
87 // TODO: Lots more we could do here:
88 // If V is a phi node, we can call this on each of its operands.
89 // "select cond, X, 0" can simplify to "X".
90
91 return MadeChange ? V : nullptr;
92}
93
94// TODO: This is a specific form of a much more general pattern.
95// We could detect a select with any binop identity constant, or we
96// could use SimplifyBinOp to see if either arm of the select reduces.
97// But that needs to be done carefully and/or while removing potential
98// reverse canonicalizations as in InstCombiner::foldSelectIntoOp().
100 InstCombiner::BuilderTy &Builder) {
101 Value *Cond, *OtherOp;
102
103 // mul (select Cond, 1, -1), OtherOp --> select Cond, OtherOp, -OtherOp
104 // mul OtherOp, (select Cond, 1, -1) --> select Cond, OtherOp, -OtherOp
106 m_Value(OtherOp)))) {
107 bool HasAnyNoWrap = I.hasNoSignedWrap() || I.hasNoUnsignedWrap();
108 Value *Neg = Builder.CreateNeg(OtherOp, "", HasAnyNoWrap);
109 return Builder.CreateSelect(Cond, OtherOp, Neg);
110 }
111 // mul (select Cond, -1, 1), OtherOp --> select Cond, -OtherOp, OtherOp
112 // mul OtherOp, (select Cond, -1, 1) --> select Cond, -OtherOp, OtherOp
114 m_Value(OtherOp)))) {
115 bool HasAnyNoWrap = I.hasNoSignedWrap() || I.hasNoUnsignedWrap();
116 Value *Neg = Builder.CreateNeg(OtherOp, "", HasAnyNoWrap);
117 return Builder.CreateSelect(Cond, Neg, OtherOp);
118 }
119
120 // fmul (select Cond, 1.0, -1.0), OtherOp --> select Cond, OtherOp, -OtherOp
121 // fmul OtherOp, (select Cond, 1.0, -1.0) --> select Cond, OtherOp, -OtherOp
123 m_SpecificFP(-1.0))),
124 m_Value(OtherOp)))) {
125 IRBuilder<>::FastMathFlagGuard FMFGuard(Builder);
126 Builder.setFastMathFlags(I.getFastMathFlags());
127 return Builder.CreateSelect(Cond, OtherOp, Builder.CreateFNeg(OtherOp));
128 }
129
130 // fmul (select Cond, -1.0, 1.0), OtherOp --> select Cond, -OtherOp, OtherOp
131 // fmul OtherOp, (select Cond, -1.0, 1.0) --> select Cond, -OtherOp, OtherOp
133 m_SpecificFP(1.0))),
134 m_Value(OtherOp)))) {
135 IRBuilder<>::FastMathFlagGuard FMFGuard(Builder);
136 Builder.setFastMathFlags(I.getFastMathFlags());
137 return Builder.CreateSelect(Cond, Builder.CreateFNeg(OtherOp), OtherOp);
138 }
139
140 return nullptr;
141}
142
143/// Reduce integer multiplication patterns that contain a (+/-1 << Z) factor.
144/// Callers are expected to call this twice to handle commuted patterns.
145static Value *foldMulShl1(BinaryOperator &Mul, bool CommuteOperands,
146 InstCombiner::BuilderTy &Builder) {
147 Value *X = Mul.getOperand(0), *Y = Mul.getOperand(1);
148 if (CommuteOperands)
149 std::swap(X, Y);
150
151 const bool HasNSW = Mul.hasNoSignedWrap();
152 const bool HasNUW = Mul.hasNoUnsignedWrap();
153
154 // X * (1 << Z) --> X << Z
155 Value *Z;
156 if (match(Y, m_Shl(m_One(), m_Value(Z)))) {
157 bool PropagateNSW = HasNSW && cast<ShlOperator>(Y)->hasNoSignedWrap();
158 return Builder.CreateShl(X, Z, Mul.getName(), HasNUW, PropagateNSW);
159 }
160
161 // Similar to above, but an increment of the shifted value becomes an add:
162 // X * ((1 << Z) + 1) --> (X * (1 << Z)) + X --> (X << Z) + X
163 // This increases uses of X, so it may require a freeze, but that is still
164 // expected to be an improvement because it removes the multiply.
165 BinaryOperator *Shift;
166 if (match(Y, m_OneUse(m_Add(m_BinOp(Shift), m_One()))) &&
167 match(Shift, m_OneUse(m_Shl(m_One(), m_Value(Z))))) {
168 bool PropagateNSW = HasNSW && Shift->hasNoSignedWrap();
169 Value *FrX = Builder.CreateFreeze(X, X->getName() + ".fr");
170 Value *Shl = Builder.CreateShl(FrX, Z, "mulshl", HasNUW, PropagateNSW);
171 return Builder.CreateAdd(Shl, FrX, Mul.getName(), HasNUW, PropagateNSW);
172 }
173
174 // Similar to above, but a decrement of the shifted value is disguised as
175 // 'not' and becomes a sub:
176 // X * (~(-1 << Z)) --> X * ((1 << Z) - 1) --> (X << Z) - X
177 // This increases uses of X, so it may require a freeze, but that is still
178 // expected to be an improvement because it removes the multiply.
180 Value *FrX = Builder.CreateFreeze(X, X->getName() + ".fr");
181 Value *Shl = Builder.CreateShl(FrX, Z, "mulshl");
182 return Builder.CreateSub(Shl, FrX, Mul.getName());
183 }
184
185 return nullptr;
186}
187
188static Value *takeLog2(IRBuilderBase &Builder, Value *Op, unsigned Depth,
189 bool AssumeNonZero, bool DoFold);
190
192 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
193 if (Value *V =
194 simplifyMulInst(Op0, Op1, I.hasNoSignedWrap(), I.hasNoUnsignedWrap(),
196 return replaceInstUsesWith(I, V);
197
199 return &I;
200
202 return X;
203
205 return Phi;
206
208 return replaceInstUsesWith(I, V);
209
210 Type *Ty = I.getType();
211 const unsigned BitWidth = Ty->getScalarSizeInBits();
212 const bool HasNSW = I.hasNoSignedWrap();
213 const bool HasNUW = I.hasNoUnsignedWrap();
214
215 // X * -1 --> 0 - X
216 if (match(Op1, m_AllOnes())) {
217 return HasNSW ? BinaryOperator::CreateNSWNeg(Op0)
219 }
220
221 // Also allow combining multiply instructions on vectors.
222 {
223 Value *NewOp;
224 Constant *C1, *C2;
225 const APInt *IVal;
226 if (match(&I, m_Mul(m_Shl(m_Value(NewOp), m_Constant(C2)),
227 m_Constant(C1))) &&
228 match(C1, m_APInt(IVal))) {
229 // ((X << C2)*C1) == (X * (C1 << C2))
230 Constant *Shl = ConstantExpr::getShl(C1, C2);
231 BinaryOperator *Mul = cast<BinaryOperator>(I.getOperand(0));
232 BinaryOperator *BO = BinaryOperator::CreateMul(NewOp, Shl);
233 if (HasNUW && Mul->hasNoUnsignedWrap())
235 if (HasNSW && Mul->hasNoSignedWrap() && Shl->isNotMinSignedValue())
236 BO->setHasNoSignedWrap();
237 return BO;
238 }
239
240 if (match(&I, m_Mul(m_Value(NewOp), m_Constant(C1)))) {
241 // Replace X*(2^C) with X << C, where C is either a scalar or a vector.
242 if (Constant *NewCst = ConstantExpr::getExactLogBase2(C1)) {
243 BinaryOperator *Shl = BinaryOperator::CreateShl(NewOp, NewCst);
244
245 if (HasNUW)
247 if (HasNSW) {
248 const APInt *V;
249 if (match(NewCst, m_APInt(V)) && *V != V->getBitWidth() - 1)
250 Shl->setHasNoSignedWrap();
251 }
252
253 return Shl;
254 }
255 }
256 }
257
258 if (Op0->hasOneUse() && match(Op1, m_NegatedPower2())) {
259 // Interpret X * (-1<<C) as (-X) * (1<<C) and try to sink the negation.
260 // The "* (1<<C)" thus becomes a potential shifting opportunity.
261 if (Value *NegOp0 =
262 Negator::Negate(/*IsNegation*/ true, HasNSW, Op0, *this)) {
263 auto *Op1C = cast<Constant>(Op1);
264 return replaceInstUsesWith(
265 I, Builder.CreateMul(NegOp0, ConstantExpr::getNeg(Op1C), "",
266 /* HasNUW */ false,
267 HasNSW && Op1C->isNotMinSignedValue()));
268 }
269
270 // Try to convert multiply of extended operand to narrow negate and shift
271 // for better analysis.
272 // This is valid if the shift amount (trailing zeros in the multiplier
273 // constant) clears more high bits than the bitwidth difference between
274 // source and destination types:
275 // ({z/s}ext X) * (-1<<C) --> (zext (-X)) << C
276 const APInt *NegPow2C;
277 Value *X;
278 if (match(Op0, m_ZExtOrSExt(m_Value(X))) &&
279 match(Op1, m_APIntAllowPoison(NegPow2C))) {
280 unsigned SrcWidth = X->getType()->getScalarSizeInBits();
281 unsigned ShiftAmt = NegPow2C->countr_zero();
282 if (ShiftAmt >= BitWidth - SrcWidth) {
283 Value *N = Builder.CreateNeg(X, X->getName() + ".neg");
284 Value *Z = Builder.CreateZExt(N, Ty, N->getName() + ".z");
285 return BinaryOperator::CreateShl(Z, ConstantInt::get(Ty, ShiftAmt));
286 }
287 }
288 }
289
290 if (Instruction *FoldedMul = foldBinOpIntoSelectOrPhi(I))
291 return FoldedMul;
292
293 if (Value *FoldedMul = foldMulSelectToNegate(I, Builder))
294 return replaceInstUsesWith(I, FoldedMul);
295
296 // Simplify mul instructions with a constant RHS.
297 Constant *MulC;
298 if (match(Op1, m_ImmConstant(MulC))) {
299 // Canonicalize (X+C1)*MulC -> X*MulC+C1*MulC.
300 // Canonicalize (X|C1)*MulC -> X*MulC+C1*MulC.
301 Value *X;
302 Constant *C1;
303 if (match(Op0, m_OneUse(m_AddLike(m_Value(X), m_ImmConstant(C1))))) {
304 // C1*MulC simplifies to a tidier constant.
305 Value *NewC = Builder.CreateMul(C1, MulC);
306 auto *BOp0 = cast<BinaryOperator>(Op0);
307 bool Op0NUW =
308 (BOp0->getOpcode() == Instruction::Or || BOp0->hasNoUnsignedWrap());
309 Value *NewMul = Builder.CreateMul(X, MulC);
310 auto *BO = BinaryOperator::CreateAdd(NewMul, NewC);
311 if (HasNUW && Op0NUW) {
312 // If NewMulBO is constant we also can set BO to nuw.
313 if (auto *NewMulBO = dyn_cast<BinaryOperator>(NewMul))
314 NewMulBO->setHasNoUnsignedWrap();
315 BO->setHasNoUnsignedWrap();
316 }
317 return BO;
318 }
319 }
320
321 // abs(X) * abs(X) -> X * X
322 Value *X;
323 if (Op0 == Op1 && match(Op0, m_Intrinsic<Intrinsic::abs>(m_Value(X))))
324 return BinaryOperator::CreateMul(X, X);
325
326 {
327 Value *Y;
328 // abs(X) * abs(Y) -> abs(X * Y)
329 if (I.hasNoSignedWrap() &&
330 match(Op0,
331 m_OneUse(m_Intrinsic<Intrinsic::abs>(m_Value(X), m_One()))) &&
332 match(Op1, m_OneUse(m_Intrinsic<Intrinsic::abs>(m_Value(Y), m_One()))))
333 return replaceInstUsesWith(
334 I, Builder.CreateBinaryIntrinsic(Intrinsic::abs,
336 Builder.getTrue()));
337 }
338
339 // -X * C --> X * -C
340 Value *Y;
341 Constant *Op1C;
342 if (match(Op0, m_Neg(m_Value(X))) && match(Op1, m_Constant(Op1C)))
343 return BinaryOperator::CreateMul(X, ConstantExpr::getNeg(Op1C));
344
345 // -X * -Y --> X * Y
346 if (match(Op0, m_Neg(m_Value(X))) && match(Op1, m_Neg(m_Value(Y)))) {
347 auto *NewMul = BinaryOperator::CreateMul(X, Y);
348 if (HasNSW && cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap() &&
349 cast<OverflowingBinaryOperator>(Op1)->hasNoSignedWrap())
350 NewMul->setHasNoSignedWrap();
351 return NewMul;
352 }
353
354 // -X * Y --> -(X * Y)
355 // X * -Y --> -(X * Y)
358
359 // (-X * Y) * -X --> (X * Y) * X
360 // (-X << Y) * -X --> (X << Y) * X
361 if (match(Op1, m_Neg(m_Value(X)))) {
362 if (Value *NegOp0 = Negator::Negate(false, /*IsNSW*/ false, Op0, *this))
363 return BinaryOperator::CreateMul(NegOp0, X);
364 }
365
366 // (X / Y) * Y = X - (X % Y)
367 // (X / Y) * -Y = (X % Y) - X
368 {
369 Value *Y = Op1;
370 BinaryOperator *Div = dyn_cast<BinaryOperator>(Op0);
371 if (!Div || (Div->getOpcode() != Instruction::UDiv &&
372 Div->getOpcode() != Instruction::SDiv)) {
373 Y = Op0;
374 Div = dyn_cast<BinaryOperator>(Op1);
375 }
376 Value *Neg = dyn_castNegVal(Y);
377 if (Div && Div->hasOneUse() &&
378 (Div->getOperand(1) == Y || Div->getOperand(1) == Neg) &&
379 (Div->getOpcode() == Instruction::UDiv ||
380 Div->getOpcode() == Instruction::SDiv)) {
381 Value *X = Div->getOperand(0), *DivOp1 = Div->getOperand(1);
382
383 // If the division is exact, X % Y is zero, so we end up with X or -X.
384 if (Div->isExact()) {
385 if (DivOp1 == Y)
386 return replaceInstUsesWith(I, X);
388 }
389
390 auto RemOpc = Div->getOpcode() == Instruction::UDiv ? Instruction::URem
391 : Instruction::SRem;
392 // X must be frozen because we are increasing its number of uses.
393 Value *XFreeze = Builder.CreateFreeze(X, X->getName() + ".fr");
394 Value *Rem = Builder.CreateBinOp(RemOpc, XFreeze, DivOp1);
395 if (DivOp1 == Y)
396 return BinaryOperator::CreateSub(XFreeze, Rem);
397 return BinaryOperator::CreateSub(Rem, XFreeze);
398 }
399 }
400
401 // Fold the following two scenarios:
402 // 1) i1 mul -> i1 and.
403 // 2) X * Y --> X & Y, iff X, Y can be only {0,1}.
404 // Note: We could use known bits to generalize this and related patterns with
405 // shifts/truncs
406 if (Ty->isIntOrIntVectorTy(1) ||
407 (match(Op0, m_And(m_Value(), m_One())) &&
408 match(Op1, m_And(m_Value(), m_One()))))
409 return BinaryOperator::CreateAnd(Op0, Op1);
410
411 if (Value *R = foldMulShl1(I, /* CommuteOperands */ false, Builder))
412 return replaceInstUsesWith(I, R);
413 if (Value *R = foldMulShl1(I, /* CommuteOperands */ true, Builder))
414 return replaceInstUsesWith(I, R);
415
416 // (zext bool X) * (zext bool Y) --> zext (and X, Y)
417 // (sext bool X) * (sext bool Y) --> zext (and X, Y)
418 // Note: -1 * -1 == 1 * 1 == 1 (if the extends match, the result is the same)
419 if (((match(Op0, m_ZExt(m_Value(X))) && match(Op1, m_ZExt(m_Value(Y)))) ||
420 (match(Op0, m_SExt(m_Value(X))) && match(Op1, m_SExt(m_Value(Y))))) &&
421 X->getType()->isIntOrIntVectorTy(1) && X->getType() == Y->getType() &&
422 (Op0->hasOneUse() || Op1->hasOneUse() || X == Y)) {
423 Value *And = Builder.CreateAnd(X, Y, "mulbool");
424 return CastInst::Create(Instruction::ZExt, And, Ty);
425 }
426 // (sext bool X) * (zext bool Y) --> sext (and X, Y)
427 // (zext bool X) * (sext bool Y) --> sext (and X, Y)
428 // Note: -1 * 1 == 1 * -1 == -1
429 if (((match(Op0, m_SExt(m_Value(X))) && match(Op1, m_ZExt(m_Value(Y)))) ||
430 (match(Op0, m_ZExt(m_Value(X))) && match(Op1, m_SExt(m_Value(Y))))) &&
431 X->getType()->isIntOrIntVectorTy(1) && X->getType() == Y->getType() &&
432 (Op0->hasOneUse() || Op1->hasOneUse())) {
433 Value *And = Builder.CreateAnd(X, Y, "mulbool");
434 return CastInst::Create(Instruction::SExt, And, Ty);
435 }
436
437 // (zext bool X) * Y --> X ? Y : 0
438 // Y * (zext bool X) --> X ? Y : 0
439 if (match(Op0, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
441 if (match(Op1, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
443
444 // mul (sext X), Y -> select X, -Y, 0
445 // mul Y, (sext X) -> select X, -Y, 0
446 if (match(&I, m_c_Mul(m_OneUse(m_SExt(m_Value(X))), m_Value(Y))) &&
447 X->getType()->isIntOrIntVectorTy(1))
448 return SelectInst::Create(X, Builder.CreateNeg(Y, "", I.hasNoSignedWrap()),
450
451 Constant *ImmC;
452 if (match(Op1, m_ImmConstant(ImmC))) {
453 // (sext bool X) * C --> X ? -C : 0
454 if (match(Op0, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
455 Constant *NegC = ConstantExpr::getNeg(ImmC);
457 }
458
459 // (ashr i32 X, 31) * C --> (X < 0) ? -C : 0
460 const APInt *C;
461 if (match(Op0, m_OneUse(m_AShr(m_Value(X), m_APInt(C)))) &&
462 *C == C->getBitWidth() - 1) {
463 Constant *NegC = ConstantExpr::getNeg(ImmC);
464 Value *IsNeg = Builder.CreateIsNeg(X, "isneg");
465 return SelectInst::Create(IsNeg, NegC, ConstantInt::getNullValue(Ty));
466 }
467 }
468
469 // (lshr X, 31) * Y --> (X < 0) ? Y : 0
470 // TODO: We are not checking one-use because the elimination of the multiply
471 // is better for analysis?
472 const APInt *C;
473 if (match(&I, m_c_BinOp(m_LShr(m_Value(X), m_APInt(C)), m_Value(Y))) &&
474 *C == C->getBitWidth() - 1) {
475 Value *IsNeg = Builder.CreateIsNeg(X, "isneg");
477 }
478
479 // (and X, 1) * Y --> (trunc X) ? Y : 0
480 if (match(&I, m_c_BinOp(m_OneUse(m_And(m_Value(X), m_One())), m_Value(Y)))) {
483 }
484
485 // ((ashr X, 31) | 1) * X --> abs(X)
486 // X * ((ashr X, 31) | 1) --> abs(X)
489 m_One()),
490 m_Deferred(X)))) {
492 Intrinsic::abs, X, ConstantInt::getBool(I.getContext(), HasNSW));
493 Abs->takeName(&I);
494 return replaceInstUsesWith(I, Abs);
495 }
496
497 if (Instruction *Ext = narrowMathIfNoOverflow(I))
498 return Ext;
499
501 return Res;
502
503 // (mul Op0 Op1):
504 // if Log2(Op0) folds away ->
505 // (shl Op1, Log2(Op0))
506 // if Log2(Op1) folds away ->
507 // (shl Op0, Log2(Op1))
508 if (takeLog2(Builder, Op0, /*Depth*/ 0, /*AssumeNonZero*/ false,
509 /*DoFold*/ false)) {
510 Value *Res = takeLog2(Builder, Op0, /*Depth*/ 0, /*AssumeNonZero*/ false,
511 /*DoFold*/ true);
512 BinaryOperator *Shl = BinaryOperator::CreateShl(Op1, Res);
513 // We can only propegate nuw flag.
514 Shl->setHasNoUnsignedWrap(HasNUW);
515 return Shl;
516 }
517 if (takeLog2(Builder, Op1, /*Depth*/ 0, /*AssumeNonZero*/ false,
518 /*DoFold*/ false)) {
519 Value *Res = takeLog2(Builder, Op1, /*Depth*/ 0, /*AssumeNonZero*/ false,
520 /*DoFold*/ true);
521 BinaryOperator *Shl = BinaryOperator::CreateShl(Op0, Res);
522 // We can only propegate nuw flag.
523 Shl->setHasNoUnsignedWrap(HasNUW);
524 return Shl;
525 }
526
527 bool Changed = false;
528 if (!HasNSW && willNotOverflowSignedMul(Op0, Op1, I)) {
529 Changed = true;
530 I.setHasNoSignedWrap(true);
531 }
532
533 if (!HasNUW && willNotOverflowUnsignedMul(Op0, Op1, I)) {
534 Changed = true;
535 I.setHasNoUnsignedWrap(true);
536 }
537
538 return Changed ? &I : nullptr;
539}
540
541Instruction *InstCombinerImpl::foldFPSignBitOps(BinaryOperator &I) {
542 BinaryOperator::BinaryOps Opcode = I.getOpcode();
543 assert((Opcode == Instruction::FMul || Opcode == Instruction::FDiv) &&
544 "Expected fmul or fdiv");
545
546 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
547 Value *X, *Y;
548
549 // -X * -Y --> X * Y
550 // -X / -Y --> X / Y
551 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
552 return BinaryOperator::CreateWithCopiedFlags(Opcode, X, Y, &I);
553
554 // fabs(X) * fabs(X) -> X * X
555 // fabs(X) / fabs(X) -> X / X
556 if (Op0 == Op1 && match(Op0, m_FAbs(m_Value(X))))
557 return BinaryOperator::CreateWithCopiedFlags(Opcode, X, X, &I);
558
559 // fabs(X) * fabs(Y) --> fabs(X * Y)
560 // fabs(X) / fabs(Y) --> fabs(X / Y)
561 if (match(Op0, m_FAbs(m_Value(X))) && match(Op1, m_FAbs(m_Value(Y))) &&
562 (Op0->hasOneUse() || Op1->hasOneUse())) {
564 Builder.setFastMathFlags(I.getFastMathFlags());
565 Value *XY = Builder.CreateBinOp(Opcode, X, Y);
566 Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, XY);
567 Fabs->takeName(&I);
568 return replaceInstUsesWith(I, Fabs);
569 }
570
571 return nullptr;
572}
573
575 auto createPowiExpr = [](BinaryOperator &I, InstCombinerImpl &IC, Value *X,
576 Value *Y, Value *Z) {
577 InstCombiner::BuilderTy &Builder = IC.Builder;
578 Value *YZ = Builder.CreateAdd(Y, Z);
579 auto *NewPow = Builder.CreateIntrinsic(
580 Intrinsic::powi, {X->getType(), YZ->getType()}, {X, YZ}, &I);
581 return IC.replaceInstUsesWith(I, NewPow);
582 };
583
584 Value *X, *Y, *Z;
585
586 // powi(X, Y) * X --> powi(X, Y+1)
587 // X * powi(X, Y) --> powi(X, Y+1)
588 if (match(&I, m_c_FMul(m_OneUse(m_AllowReassoc(m_Intrinsic<Intrinsic::powi>(
589 m_Value(X), m_Value(Y)))),
590 m_Deferred(X)))) {
591 Constant *One = ConstantInt::get(Y->getType(), 1);
592 if (willNotOverflowSignedAdd(Y, One, I))
593 return createPowiExpr(I, *this, X, Y, One);
594 }
595
596 // powi(x, y) * powi(x, z) -> powi(x, y + z)
597 Value *Op0 = I.getOperand(0);
598 Value *Op1 = I.getOperand(1);
599 if (I.isOnlyUserOfAnyOperand() &&
601 m_Intrinsic<Intrinsic::powi>(m_Value(X), m_Value(Y)))) &&
602 match(Op1, m_AllowReassoc(m_Intrinsic<Intrinsic::powi>(m_Specific(X),
603 m_Value(Z)))) &&
604 Y->getType() == Z->getType())
605 return createPowiExpr(I, *this, X, Y, Z);
606
607 // powi(X, Y) / X --> powi(X, Y-1)
608 // This is legal when (Y - 1) can't wraparound, in which case reassoc and nnan
609 // are required.
610 // TODO: Multi-use may be also better off creating Powi(x,y-1)
611 if (I.hasAllowReassoc() && I.hasNoNaNs() &&
612 match(Op0, m_OneUse(m_AllowReassoc(m_Intrinsic<Intrinsic::powi>(
613 m_Specific(Op1), m_Value(Y))))) &&
614 willNotOverflowSignedSub(Y, ConstantInt::get(Y->getType(), 1), I)) {
615 Constant *NegOne = ConstantInt::getAllOnesValue(Y->getType());
616 return createPowiExpr(I, *this, Op1, Y, NegOne);
617 }
618
619 return nullptr;
620}
621
623 Value *Op0 = I.getOperand(0);
624 Value *Op1 = I.getOperand(1);
625 Value *X, *Y;
626 Constant *C;
627 BinaryOperator *Op0BinOp;
628
629 // Reassociate constant RHS with another constant to form constant
630 // expression.
631 if (match(Op1, m_Constant(C)) && C->isFiniteNonZeroFP() &&
632 match(Op0, m_AllowReassoc(m_BinOp(Op0BinOp)))) {
633 // Everything in this scope folds I with Op0, intersecting their FMF.
634 FastMathFlags FMF = I.getFastMathFlags() & Op0BinOp->getFastMathFlags();
637 Constant *C1;
638 if (match(Op0, m_OneUse(m_FDiv(m_Constant(C1), m_Value(X))))) {
639 // (C1 / X) * C --> (C * C1) / X
640 Constant *CC1 =
641 ConstantFoldBinaryOpOperands(Instruction::FMul, C, C1, DL);
642 if (CC1 && CC1->isNormalFP())
643 return BinaryOperator::CreateFDivFMF(CC1, X, FMF);
644 }
645 if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) {
646 // FIXME: This seems like it should also be checking for arcp
647 // (X / C1) * C --> X * (C / C1)
648 Constant *CDivC1 =
649 ConstantFoldBinaryOpOperands(Instruction::FDiv, C, C1, DL);
650 if (CDivC1 && CDivC1->isNormalFP())
651 return BinaryOperator::CreateFMulFMF(X, CDivC1, FMF);
652
653 // If the constant was a denormal, try reassociating differently.
654 // (X / C1) * C --> X / (C1 / C)
655 Constant *C1DivC =
656 ConstantFoldBinaryOpOperands(Instruction::FDiv, C1, C, DL);
657 if (C1DivC && Op0->hasOneUse() && C1DivC->isNormalFP())
658 return BinaryOperator::CreateFDivFMF(X, C1DivC, FMF);
659 }
660
661 // We do not need to match 'fadd C, X' and 'fsub X, C' because they are
662 // canonicalized to 'fadd X, C'. Distributing the multiply may allow
663 // further folds and (X * C) + C2 is 'fma'.
664 if (match(Op0, m_OneUse(m_FAdd(m_Value(X), m_Constant(C1))))) {
665 // (X + C1) * C --> (X * C) + (C * C1)
666 if (Constant *CC1 =
667 ConstantFoldBinaryOpOperands(Instruction::FMul, C, C1, DL)) {
668 Value *XC = Builder.CreateFMul(X, C);
669 return BinaryOperator::CreateFAddFMF(XC, CC1, FMF);
670 }
671 }
672 if (match(Op0, m_OneUse(m_FSub(m_Constant(C1), m_Value(X))))) {
673 // (C1 - X) * C --> (C * C1) - (X * C)
674 if (Constant *CC1 =
675 ConstantFoldBinaryOpOperands(Instruction::FMul, C, C1, DL)) {
676 Value *XC = Builder.CreateFMul(X, C);
677 return BinaryOperator::CreateFSubFMF(CC1, XC, FMF);
678 }
679 }
680 }
681
682 Value *Z;
683 if (match(&I,
685 m_Value(Z)))) {
686 BinaryOperator *DivOp = cast<BinaryOperator>(((Z == Op0) ? Op1 : Op0));
687 FastMathFlags FMF = I.getFastMathFlags() & DivOp->getFastMathFlags();
688 if (FMF.allowReassoc()) {
689 // Sink division: (X / Y) * Z --> (X * Z) / Y
692 auto *NewFMul = Builder.CreateFMul(X, Z);
693 return BinaryOperator::CreateFDivFMF(NewFMul, Y, FMF);
694 }
695 }
696
697 // sqrt(X) * sqrt(Y) -> sqrt(X * Y)
698 // nnan disallows the possibility of returning a number if both operands are
699 // negative (in that case, we should return NaN).
700 if (I.hasNoNaNs() && match(Op0, m_OneUse(m_Sqrt(m_Value(X)))) &&
701 match(Op1, m_OneUse(m_Sqrt(m_Value(Y))))) {
702 Value *XY = Builder.CreateFMulFMF(X, Y, &I);
703 Value *Sqrt = Builder.CreateUnaryIntrinsic(Intrinsic::sqrt, XY, &I);
704 return replaceInstUsesWith(I, Sqrt);
705 }
706
707 // The following transforms are done irrespective of the number of uses
708 // for the expression "1.0/sqrt(X)".
709 // 1) 1.0/sqrt(X) * X -> X/sqrt(X)
710 // 2) X * 1.0/sqrt(X) -> X/sqrt(X)
711 // We always expect the backend to reduce X/sqrt(X) to sqrt(X), if it
712 // has the necessary (reassoc) fast-math-flags.
713 if (I.hasNoSignedZeros() &&
714 match(Op0, (m_FDiv(m_SpecificFP(1.0), m_Value(Y)))) &&
715 match(Y, m_Sqrt(m_Value(X))) && Op1 == X)
717 if (I.hasNoSignedZeros() &&
718 match(Op1, (m_FDiv(m_SpecificFP(1.0), m_Value(Y)))) &&
719 match(Y, m_Sqrt(m_Value(X))) && Op0 == X)
721
722 // Like the similar transform in instsimplify, this requires 'nsz' because
723 // sqrt(-0.0) = -0.0, and -0.0 * -0.0 does not simplify to -0.0.
724 if (I.hasNoNaNs() && I.hasNoSignedZeros() && Op0 == Op1 && Op0->hasNUses(2)) {
725 // Peek through fdiv to find squaring of square root:
726 // (X / sqrt(Y)) * (X / sqrt(Y)) --> (X * X) / Y
727 if (match(Op0, m_FDiv(m_Value(X), m_Sqrt(m_Value(Y))))) {
728 Value *XX = Builder.CreateFMulFMF(X, X, &I);
729 return BinaryOperator::CreateFDivFMF(XX, Y, &I);
730 }
731 // (sqrt(Y) / X) * (sqrt(Y) / X) --> Y / (X * X)
732 if (match(Op0, m_FDiv(m_Sqrt(m_Value(Y)), m_Value(X)))) {
733 Value *XX = Builder.CreateFMulFMF(X, X, &I);
734 return BinaryOperator::CreateFDivFMF(Y, XX, &I);
735 }
736 }
737
738 // pow(X, Y) * X --> pow(X, Y+1)
739 // X * pow(X, Y) --> pow(X, Y+1)
740 if (match(&I, m_c_FMul(m_OneUse(m_Intrinsic<Intrinsic::pow>(m_Value(X),
741 m_Value(Y))),
742 m_Deferred(X)))) {
743 Value *Y1 = Builder.CreateFAddFMF(Y, ConstantFP::get(I.getType(), 1.0), &I);
744 Value *Pow = Builder.CreateBinaryIntrinsic(Intrinsic::pow, X, Y1, &I);
745 return replaceInstUsesWith(I, Pow);
746 }
747
748 if (Instruction *FoldedPowi = foldPowiReassoc(I))
749 return FoldedPowi;
750
751 if (I.isOnlyUserOfAnyOperand()) {
752 // pow(X, Y) * pow(X, Z) -> pow(X, Y + Z)
753 if (match(Op0, m_Intrinsic<Intrinsic::pow>(m_Value(X), m_Value(Y))) &&
754 match(Op1, m_Intrinsic<Intrinsic::pow>(m_Specific(X), m_Value(Z)))) {
755 auto *YZ = Builder.CreateFAddFMF(Y, Z, &I);
756 auto *NewPow = Builder.CreateBinaryIntrinsic(Intrinsic::pow, X, YZ, &I);
757 return replaceInstUsesWith(I, NewPow);
758 }
759 // pow(X, Y) * pow(Z, Y) -> pow(X * Z, Y)
760 if (match(Op0, m_Intrinsic<Intrinsic::pow>(m_Value(X), m_Value(Y))) &&
761 match(Op1, m_Intrinsic<Intrinsic::pow>(m_Value(Z), m_Specific(Y)))) {
762 auto *XZ = Builder.CreateFMulFMF(X, Z, &I);
763 auto *NewPow = Builder.CreateBinaryIntrinsic(Intrinsic::pow, XZ, Y, &I);
764 return replaceInstUsesWith(I, NewPow);
765 }
766
767 // exp(X) * exp(Y) -> exp(X + Y)
768 if (match(Op0, m_Intrinsic<Intrinsic::exp>(m_Value(X))) &&
769 match(Op1, m_Intrinsic<Intrinsic::exp>(m_Value(Y)))) {
770 Value *XY = Builder.CreateFAddFMF(X, Y, &I);
771 Value *Exp = Builder.CreateUnaryIntrinsic(Intrinsic::exp, XY, &I);
772 return replaceInstUsesWith(I, Exp);
773 }
774
775 // exp2(X) * exp2(Y) -> exp2(X + Y)
776 if (match(Op0, m_Intrinsic<Intrinsic::exp2>(m_Value(X))) &&
777 match(Op1, m_Intrinsic<Intrinsic::exp2>(m_Value(Y)))) {
778 Value *XY = Builder.CreateFAddFMF(X, Y, &I);
779 Value *Exp2 = Builder.CreateUnaryIntrinsic(Intrinsic::exp2, XY, &I);
780 return replaceInstUsesWith(I, Exp2);
781 }
782 }
783
784 // (X*Y) * X => (X*X) * Y where Y != X
785 // The purpose is two-fold:
786 // 1) to form a power expression (of X).
787 // 2) potentially shorten the critical path: After transformation, the
788 // latency of the instruction Y is amortized by the expression of X*X,
789 // and therefore Y is in a "less critical" position compared to what it
790 // was before the transformation.
791 if (match(Op0, m_OneUse(m_c_FMul(m_Specific(Op1), m_Value(Y)))) && Op1 != Y) {
792 Value *XX = Builder.CreateFMulFMF(Op1, Op1, &I);
793 return BinaryOperator::CreateFMulFMF(XX, Y, &I);
794 }
795 if (match(Op1, m_OneUse(m_c_FMul(m_Specific(Op0), m_Value(Y)))) && Op0 != Y) {
796 Value *XX = Builder.CreateFMulFMF(Op0, Op0, &I);
797 return BinaryOperator::CreateFMulFMF(XX, Y, &I);
798 }
799
800 return nullptr;
801}
802
804 if (Value *V = simplifyFMulInst(I.getOperand(0), I.getOperand(1),
805 I.getFastMathFlags(),
807 return replaceInstUsesWith(I, V);
808
810 return &I;
811
813 return X;
814
816 return Phi;
817
818 if (Instruction *FoldedMul = foldBinOpIntoSelectOrPhi(I))
819 return FoldedMul;
820
821 if (Value *FoldedMul = foldMulSelectToNegate(I, Builder))
822 return replaceInstUsesWith(I, FoldedMul);
823
824 if (Instruction *R = foldFPSignBitOps(I))
825 return R;
826
827 if (Instruction *R = foldFBinOpOfIntCasts(I))
828 return R;
829
830 // X * -1.0 --> -X
831 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
832 if (match(Op1, m_SpecificFP(-1.0)))
833 return UnaryOperator::CreateFNegFMF(Op0, &I);
834
835 // With no-nans/no-infs:
836 // X * 0.0 --> copysign(0.0, X)
837 // X * -0.0 --> copysign(0.0, -X)
838 const APFloat *FPC;
839 if (match(Op1, m_APFloatAllowPoison(FPC)) && FPC->isZero() &&
840 ((I.hasNoInfs() &&
841 isKnownNeverNaN(Op0, /*Depth=*/0, SQ.getWithInstruction(&I))) ||
842 isKnownNeverNaN(&I, /*Depth=*/0, SQ.getWithInstruction(&I)))) {
843 if (FPC->isNegative())
844 Op0 = Builder.CreateFNegFMF(Op0, &I);
846 cast<Constant>(Op1),
847 ConstantFP::get(Op1->getType()->getScalarType(), *FPC));
848 CallInst *CopySign = Builder.CreateIntrinsic(Intrinsic::copysign,
849 {I.getType()}, {Op1, Op0}, &I);
850 return replaceInstUsesWith(I, CopySign);
851 }
852
853 // -X * C --> X * -C
854 Value *X, *Y;
855 Constant *C;
856 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_Constant(C)))
857 if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL))
858 return BinaryOperator::CreateFMulFMF(X, NegC, &I);
859
860 // (select A, B, C) * (select A, D, E) --> select A, (B*D), (C*E)
861 if (Value *V = SimplifySelectsFeedingBinaryOp(I, Op0, Op1))
862 return replaceInstUsesWith(I, V);
863
864 if (I.hasAllowReassoc())
865 if (Instruction *FoldedMul = foldFMulReassoc(I))
866 return FoldedMul;
867
868 // log2(X * 0.5) * Y = log2(X) * Y - Y
869 if (I.isFast()) {
870 IntrinsicInst *Log2 = nullptr;
871 if (match(Op0, m_OneUse(m_Intrinsic<Intrinsic::log2>(
872 m_OneUse(m_FMul(m_Value(X), m_SpecificFP(0.5))))))) {
873 Log2 = cast<IntrinsicInst>(Op0);
874 Y = Op1;
875 }
876 if (match(Op1, m_OneUse(m_Intrinsic<Intrinsic::log2>(
877 m_OneUse(m_FMul(m_Value(X), m_SpecificFP(0.5))))))) {
878 Log2 = cast<IntrinsicInst>(Op1);
879 Y = Op0;
880 }
881 if (Log2) {
882 Value *Log2 = Builder.CreateUnaryIntrinsic(Intrinsic::log2, X, &I);
883 Value *LogXTimesY = Builder.CreateFMulFMF(Log2, Y, &I);
884 return BinaryOperator::CreateFSubFMF(LogXTimesY, Y, &I);
885 }
886 }
887
888 // Simplify FMUL recurrences starting with 0.0 to 0.0 if nnan and nsz are set.
889 // Given a phi node with entry value as 0 and it used in fmul operation,
890 // we can replace fmul with 0 safely and eleminate loop operation.
891 PHINode *PN = nullptr;
892 Value *Start = nullptr, *Step = nullptr;
893 if (matchSimpleRecurrence(&I, PN, Start, Step) && I.hasNoNaNs() &&
894 I.hasNoSignedZeros() && match(Start, m_Zero()))
895 return replaceInstUsesWith(I, Start);
896
897 // minimum(X, Y) * maximum(X, Y) => X * Y.
898 if (match(&I,
899 m_c_FMul(m_Intrinsic<Intrinsic::maximum>(m_Value(X), m_Value(Y)),
900 m_c_Intrinsic<Intrinsic::minimum>(m_Deferred(X),
901 m_Deferred(Y))))) {
903 // We cannot preserve ninf if nnan flag is not set.
904 // If X is NaN and Y is Inf then in original program we had NaN * NaN,
905 // while in optimized version NaN * Inf and this is a poison with ninf flag.
906 if (!Result->hasNoNaNs())
907 Result->setHasNoInfs(false);
908 return Result;
909 }
910
911 return nullptr;
912}
913
914/// Fold a divide or remainder with a select instruction divisor when one of the
915/// select operands is zero. In that case, we can use the other select operand
916/// because div/rem by zero is undefined.
918 SelectInst *SI = dyn_cast<SelectInst>(I.getOperand(1));
919 if (!SI)
920 return false;
921
922 int NonNullOperand;
923 if (match(SI->getTrueValue(), m_Zero()))
924 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
925 NonNullOperand = 2;
926 else if (match(SI->getFalseValue(), m_Zero()))
927 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
928 NonNullOperand = 1;
929 else
930 return false;
931
932 // Change the div/rem to use 'Y' instead of the select.
933 replaceOperand(I, 1, SI->getOperand(NonNullOperand));
934
935 // Okay, we know we replace the operand of the div/rem with 'Y' with no
936 // problem. However, the select, or the condition of the select may have
937 // multiple uses. Based on our knowledge that the operand must be non-zero,
938 // propagate the known value for the select into other uses of it, and
939 // propagate a known value of the condition into its other users.
940
941 // If the select and condition only have a single use, don't bother with this,
942 // early exit.
943 Value *SelectCond = SI->getCondition();
944 if (SI->use_empty() && SelectCond->hasOneUse())
945 return true;
946
947 // Scan the current block backward, looking for other uses of SI.
948 BasicBlock::iterator BBI = I.getIterator(), BBFront = I.getParent()->begin();
949 Type *CondTy = SelectCond->getType();
950 while (BBI != BBFront) {
951 --BBI;
952 // If we found an instruction that we can't assume will return, so
953 // information from below it cannot be propagated above it.
955 break;
956
957 // Replace uses of the select or its condition with the known values.
958 for (Use &Op : BBI->operands()) {
959 if (Op == SI) {
960 replaceUse(Op, SI->getOperand(NonNullOperand));
961 Worklist.push(&*BBI);
962 } else if (Op == SelectCond) {
963 replaceUse(Op, NonNullOperand == 1 ? ConstantInt::getTrue(CondTy)
964 : ConstantInt::getFalse(CondTy));
965 Worklist.push(&*BBI);
966 }
967 }
968
969 // If we past the instruction, quit looking for it.
970 if (&*BBI == SI)
971 SI = nullptr;
972 if (&*BBI == SelectCond)
973 SelectCond = nullptr;
974
975 // If we ran out of things to eliminate, break out of the loop.
976 if (!SelectCond && !SI)
977 break;
978
979 }
980 return true;
981}
982
983/// True if the multiply can not be expressed in an int this size.
984static bool multiplyOverflows(const APInt &C1, const APInt &C2, APInt &Product,
985 bool IsSigned) {
986 bool Overflow;
987 Product = IsSigned ? C1.smul_ov(C2, Overflow) : C1.umul_ov(C2, Overflow);
988 return Overflow;
989}
990
991/// True if C1 is a multiple of C2. Quotient contains C1/C2.
992static bool isMultiple(const APInt &C1, const APInt &C2, APInt &Quotient,
993 bool IsSigned) {
994 assert(C1.getBitWidth() == C2.getBitWidth() && "Constant widths not equal");
995
996 // Bail if we will divide by zero.
997 if (C2.isZero())
998 return false;
999
1000 // Bail if we would divide INT_MIN by -1.
1001 if (IsSigned && C1.isMinSignedValue() && C2.isAllOnes())
1002 return false;
1003
1004 APInt Remainder(C1.getBitWidth(), /*val=*/0ULL, IsSigned);
1005 if (IsSigned)
1006 APInt::sdivrem(C1, C2, Quotient, Remainder);
1007 else
1008 APInt::udivrem(C1, C2, Quotient, Remainder);
1009
1010 return Remainder.isMinValue();
1011}
1012
1014 assert((I.getOpcode() == Instruction::SDiv ||
1015 I.getOpcode() == Instruction::UDiv) &&
1016 "Expected integer divide");
1017
1018 bool IsSigned = I.getOpcode() == Instruction::SDiv;
1019 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1020 Type *Ty = I.getType();
1021
1022 Value *X, *Y, *Z;
1023
1024 // With appropriate no-wrap constraints, remove a common factor in the
1025 // dividend and divisor that is disguised as a left-shifted value.
1026 if (match(Op1, m_Shl(m_Value(X), m_Value(Z))) &&
1027 match(Op0, m_c_Mul(m_Specific(X), m_Value(Y)))) {
1028 // Both operands must have the matching no-wrap for this kind of division.
1029 auto *Mul = cast<OverflowingBinaryOperator>(Op0);
1030 auto *Shl = cast<OverflowingBinaryOperator>(Op1);
1031 bool HasNUW = Mul->hasNoUnsignedWrap() && Shl->hasNoUnsignedWrap();
1032 bool HasNSW = Mul->hasNoSignedWrap() && Shl->hasNoSignedWrap();
1033
1034 // (X * Y) u/ (X << Z) --> Y u>> Z
1035 if (!IsSigned && HasNUW)
1036 return Builder.CreateLShr(Y, Z, "", I.isExact());
1037
1038 // (X * Y) s/ (X << Z) --> Y s/ (1 << Z)
1039 if (IsSigned && HasNSW && (Op0->hasOneUse() || Op1->hasOneUse())) {
1040 Value *Shl = Builder.CreateShl(ConstantInt::get(Ty, 1), Z);
1041 return Builder.CreateSDiv(Y, Shl, "", I.isExact());
1042 }
1043 }
1044
1045 // With appropriate no-wrap constraints, remove a common factor in the
1046 // dividend and divisor that is disguised as a left-shift amount.
1047 if (match(Op0, m_Shl(m_Value(X), m_Value(Z))) &&
1048 match(Op1, m_Shl(m_Value(Y), m_Specific(Z)))) {
1049 auto *Shl0 = cast<OverflowingBinaryOperator>(Op0);
1050 auto *Shl1 = cast<OverflowingBinaryOperator>(Op1);
1051
1052 // For unsigned div, we need 'nuw' on both shifts or
1053 // 'nsw' on both shifts + 'nuw' on the dividend.
1054 // (X << Z) / (Y << Z) --> X / Y
1055 if (!IsSigned &&
1056 ((Shl0->hasNoUnsignedWrap() && Shl1->hasNoUnsignedWrap()) ||
1057 (Shl0->hasNoUnsignedWrap() && Shl0->hasNoSignedWrap() &&
1058 Shl1->hasNoSignedWrap())))
1059 return Builder.CreateUDiv(X, Y, "", I.isExact());
1060
1061 // For signed div, we need 'nsw' on both shifts + 'nuw' on the divisor.
1062 // (X << Z) / (Y << Z) --> X / Y
1063 if (IsSigned && Shl0->hasNoSignedWrap() && Shl1->hasNoSignedWrap() &&
1064 Shl1->hasNoUnsignedWrap())
1065 return Builder.CreateSDiv(X, Y, "", I.isExact());
1066 }
1067
1068 // If X << Y and X << Z does not overflow, then:
1069 // (X << Y) / (X << Z) -> (1 << Y) / (1 << Z) -> 1 << Y >> Z
1070 if (match(Op0, m_Shl(m_Value(X), m_Value(Y))) &&
1071 match(Op1, m_Shl(m_Specific(X), m_Value(Z)))) {
1072 auto *Shl0 = cast<OverflowingBinaryOperator>(Op0);
1073 auto *Shl1 = cast<OverflowingBinaryOperator>(Op1);
1074
1075 if (IsSigned ? (Shl0->hasNoSignedWrap() && Shl1->hasNoSignedWrap())
1076 : (Shl0->hasNoUnsignedWrap() && Shl1->hasNoUnsignedWrap())) {
1077 Constant *One = ConstantInt::get(X->getType(), 1);
1078 // Only preserve the nsw flag if dividend has nsw
1079 // or divisor has nsw and operator is sdiv.
1080 Value *Dividend = Builder.CreateShl(
1081 One, Y, "shl.dividend",
1082 /*HasNUW*/ true,
1083 /*HasNSW*/
1084 IsSigned ? (Shl0->hasNoUnsignedWrap() || Shl1->hasNoUnsignedWrap())
1085 : Shl0->hasNoSignedWrap());
1086 return Builder.CreateLShr(Dividend, Z, "", I.isExact());
1087 }
1088 }
1089
1090 return nullptr;
1091}
1092
1093/// This function implements the transforms common to both integer division
1094/// instructions (udiv and sdiv). It is called by the visitors to those integer
1095/// division instructions.
1096/// Common integer divide transforms
1099 return Phi;
1100
1101 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1102 bool IsSigned = I.getOpcode() == Instruction::SDiv;
1103 Type *Ty = I.getType();
1104
1105 // The RHS is known non-zero.
1106 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I))
1107 return replaceOperand(I, 1, V);
1108
1109 // Handle cases involving: [su]div X, (select Cond, Y, Z)
1110 // This does not apply for fdiv.
1112 return &I;
1113
1114 // If the divisor is a select-of-constants, try to constant fold all div ops:
1115 // C / (select Cond, TrueC, FalseC) --> select Cond, (C / TrueC), (C / FalseC)
1116 // TODO: Adapt simplifyDivRemOfSelectWithZeroOp to allow this and other folds.
1117 if (match(Op0, m_ImmConstant()) &&
1119 if (Instruction *R = FoldOpIntoSelect(I, cast<SelectInst>(Op1),
1120 /*FoldWithMultiUse*/ true))
1121 return R;
1122 }
1123
1124 const APInt *C2;
1125 if (match(Op1, m_APInt(C2))) {
1126 Value *X;
1127 const APInt *C1;
1128
1129 // (X / C1) / C2 -> X / (C1*C2)
1130 if ((IsSigned && match(Op0, m_SDiv(m_Value(X), m_APInt(C1)))) ||
1131 (!IsSigned && match(Op0, m_UDiv(m_Value(X), m_APInt(C1))))) {
1132 APInt Product(C1->getBitWidth(), /*val=*/0ULL, IsSigned);
1133 if (!multiplyOverflows(*C1, *C2, Product, IsSigned))
1134 return BinaryOperator::Create(I.getOpcode(), X,
1135 ConstantInt::get(Ty, Product));
1136 }
1137
1138 APInt Quotient(C2->getBitWidth(), /*val=*/0ULL, IsSigned);
1139 if ((IsSigned && match(Op0, m_NSWMul(m_Value(X), m_APInt(C1)))) ||
1140 (!IsSigned && match(Op0, m_NUWMul(m_Value(X), m_APInt(C1))))) {
1141
1142 // (X * C1) / C2 -> X / (C2 / C1) if C2 is a multiple of C1.
1143 if (isMultiple(*C2, *C1, Quotient, IsSigned)) {
1144 auto *NewDiv = BinaryOperator::Create(I.getOpcode(), X,
1145 ConstantInt::get(Ty, Quotient));
1146 NewDiv->setIsExact(I.isExact());
1147 return NewDiv;
1148 }
1149
1150 // (X * C1) / C2 -> X * (C1 / C2) if C1 is a multiple of C2.
1151 if (isMultiple(*C1, *C2, Quotient, IsSigned)) {
1152 auto *Mul = BinaryOperator::Create(Instruction::Mul, X,
1153 ConstantInt::get(Ty, Quotient));
1154 auto *OBO = cast<OverflowingBinaryOperator>(Op0);
1155 Mul->setHasNoUnsignedWrap(!IsSigned && OBO->hasNoUnsignedWrap());
1156 Mul->setHasNoSignedWrap(OBO->hasNoSignedWrap());
1157 return Mul;
1158 }
1159 }
1160
1161 if ((IsSigned && match(Op0, m_NSWShl(m_Value(X), m_APInt(C1))) &&
1162 C1->ult(C1->getBitWidth() - 1)) ||
1163 (!IsSigned && match(Op0, m_NUWShl(m_Value(X), m_APInt(C1))) &&
1164 C1->ult(C1->getBitWidth()))) {
1165 APInt C1Shifted = APInt::getOneBitSet(
1166 C1->getBitWidth(), static_cast<unsigned>(C1->getZExtValue()));
1167
1168 // (X << C1) / C2 -> X / (C2 >> C1) if C2 is a multiple of 1 << C1.
1169 if (isMultiple(*C2, C1Shifted, Quotient, IsSigned)) {
1170 auto *BO = BinaryOperator::Create(I.getOpcode(), X,
1171 ConstantInt::get(Ty, Quotient));
1172 BO->setIsExact(I.isExact());
1173 return BO;
1174 }
1175
1176 // (X << C1) / C2 -> X * ((1 << C1) / C2) if 1 << C1 is a multiple of C2.
1177 if (isMultiple(C1Shifted, *C2, Quotient, IsSigned)) {
1178 auto *Mul = BinaryOperator::Create(Instruction::Mul, X,
1179 ConstantInt::get(Ty, Quotient));
1180 auto *OBO = cast<OverflowingBinaryOperator>(Op0);
1181 Mul->setHasNoUnsignedWrap(!IsSigned && OBO->hasNoUnsignedWrap());
1182 Mul->setHasNoSignedWrap(OBO->hasNoSignedWrap());
1183 return Mul;
1184 }
1185 }
1186
1187 // Distribute div over add to eliminate a matching div/mul pair:
1188 // ((X * C2) + C1) / C2 --> X + C1/C2
1189 // We need a multiple of the divisor for a signed add constant, but
1190 // unsigned is fine with any constant pair.
1191 if (IsSigned &&
1193 m_APInt(C1))) &&
1194 isMultiple(*C1, *C2, Quotient, IsSigned)) {
1195 return BinaryOperator::CreateNSWAdd(X, ConstantInt::get(Ty, Quotient));
1196 }
1197 if (!IsSigned &&
1199 m_APInt(C1)))) {
1200 return BinaryOperator::CreateNUWAdd(X,
1201 ConstantInt::get(Ty, C1->udiv(*C2)));
1202 }
1203
1204 if (!C2->isZero()) // avoid X udiv 0
1205 if (Instruction *FoldedDiv = foldBinOpIntoSelectOrPhi(I))
1206 return FoldedDiv;
1207 }
1208
1209 if (match(Op0, m_One())) {
1210 assert(!Ty->isIntOrIntVectorTy(1) && "i1 divide not removed?");
1211 if (IsSigned) {
1212 // 1 / 0 --> undef ; 1 / 1 --> 1 ; 1 / -1 --> -1 ; 1 / anything else --> 0
1213 // (Op1 + 1) u< 3 ? Op1 : 0
1214 // Op1 must be frozen because we are increasing its number of uses.
1215 Value *F1 = Builder.CreateFreeze(Op1, Op1->getName() + ".fr");
1216 Value *Inc = Builder.CreateAdd(F1, Op0);
1217 Value *Cmp = Builder.CreateICmpULT(Inc, ConstantInt::get(Ty, 3));
1218 return SelectInst::Create(Cmp, F1, ConstantInt::get(Ty, 0));
1219 } else {
1220 // If Op1 is 0 then it's undefined behaviour. If Op1 is 1 then the
1221 // result is one, otherwise it's zero.
1222 return new ZExtInst(Builder.CreateICmpEQ(Op1, Op0), Ty);
1223 }
1224 }
1225
1226 // See if we can fold away this div instruction.
1228 return &I;
1229
1230 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
1231 Value *X, *Z;
1232 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) // (X - Z) / Y; Y = Op1
1233 if ((IsSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
1234 (!IsSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
1235 return BinaryOperator::Create(I.getOpcode(), X, Op1);
1236
1237 // (X << Y) / X -> 1 << Y
1238 Value *Y;
1239 if (IsSigned && match(Op0, m_NSWShl(m_Specific(Op1), m_Value(Y))))
1240 return BinaryOperator::CreateNSWShl(ConstantInt::get(Ty, 1), Y);
1241 if (!IsSigned && match(Op0, m_NUWShl(m_Specific(Op1), m_Value(Y))))
1242 return BinaryOperator::CreateNUWShl(ConstantInt::get(Ty, 1), Y);
1243
1244 // X / (X * Y) -> 1 / Y if the multiplication does not overflow.
1245 if (match(Op1, m_c_Mul(m_Specific(Op0), m_Value(Y)))) {
1246 bool HasNSW = cast<OverflowingBinaryOperator>(Op1)->hasNoSignedWrap();
1247 bool HasNUW = cast<OverflowingBinaryOperator>(Op1)->hasNoUnsignedWrap();
1248 if ((IsSigned && HasNSW) || (!IsSigned && HasNUW)) {
1249 replaceOperand(I, 0, ConstantInt::get(Ty, 1));
1250 replaceOperand(I, 1, Y);
1251 return &I;
1252 }
1253 }
1254
1255 // (X << Z) / (X * Y) -> (1 << Z) / Y
1256 // TODO: Handle sdiv.
1257 if (!IsSigned && Op1->hasOneUse() &&
1258 match(Op0, m_NUWShl(m_Value(X), m_Value(Z))) &&
1259 match(Op1, m_c_Mul(m_Specific(X), m_Value(Y))))
1260 if (cast<OverflowingBinaryOperator>(Op1)->hasNoUnsignedWrap()) {
1261 Instruction *NewDiv = BinaryOperator::CreateUDiv(
1262 Builder.CreateShl(ConstantInt::get(Ty, 1), Z, "", /*NUW*/ true), Y);
1263 NewDiv->setIsExact(I.isExact());
1264 return NewDiv;
1265 }
1266
1267 if (Value *R = foldIDivShl(I, Builder))
1268 return replaceInstUsesWith(I, R);
1269
1270 // With the appropriate no-wrap constraint, remove a multiply by the divisor
1271 // after peeking through another divide:
1272 // ((Op1 * X) / Y) / Op1 --> X / Y
1273 if (match(Op0, m_BinOp(I.getOpcode(), m_c_Mul(m_Specific(Op1), m_Value(X)),
1274 m_Value(Y)))) {
1275 auto *InnerDiv = cast<PossiblyExactOperator>(Op0);
1276 auto *Mul = cast<OverflowingBinaryOperator>(InnerDiv->getOperand(0));
1277 Instruction *NewDiv = nullptr;
1278 if (!IsSigned && Mul->hasNoUnsignedWrap())
1279 NewDiv = BinaryOperator::CreateUDiv(X, Y);
1280 else if (IsSigned && Mul->hasNoSignedWrap())
1281 NewDiv = BinaryOperator::CreateSDiv(X, Y);
1282
1283 // Exact propagates only if both of the original divides are exact.
1284 if (NewDiv) {
1285 NewDiv->setIsExact(I.isExact() && InnerDiv->isExact());
1286 return NewDiv;
1287 }
1288 }
1289
1290 // (X * Y) / (X * Z) --> Y / Z (and commuted variants)
1291 if (match(Op0, m_Mul(m_Value(X), m_Value(Y)))) {
1292 auto OB0HasNSW = cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap();
1293 auto OB0HasNUW = cast<OverflowingBinaryOperator>(Op0)->hasNoUnsignedWrap();
1294
1295 auto CreateDivOrNull = [&](Value *A, Value *B) -> Instruction * {
1296 auto OB1HasNSW = cast<OverflowingBinaryOperator>(Op1)->hasNoSignedWrap();
1297 auto OB1HasNUW =
1298 cast<OverflowingBinaryOperator>(Op1)->hasNoUnsignedWrap();
1299 const APInt *C1, *C2;
1300 if (IsSigned && OB0HasNSW) {
1301 if (OB1HasNSW && match(B, m_APInt(C1)) && !C1->isAllOnes())
1302 return BinaryOperator::CreateSDiv(A, B);
1303 }
1304 if (!IsSigned && OB0HasNUW) {
1305 if (OB1HasNUW)
1306 return BinaryOperator::CreateUDiv(A, B);
1307 if (match(A, m_APInt(C1)) && match(B, m_APInt(C2)) && C2->ule(*C1))
1308 return BinaryOperator::CreateUDiv(A, B);
1309 }
1310 return nullptr;
1311 };
1312
1313 if (match(Op1, m_c_Mul(m_Specific(X), m_Value(Z)))) {
1314 if (auto *Val = CreateDivOrNull(Y, Z))
1315 return Val;
1316 }
1317 if (match(Op1, m_c_Mul(m_Specific(Y), m_Value(Z)))) {
1318 if (auto *Val = CreateDivOrNull(X, Z))
1319 return Val;
1320 }
1321 }
1322 return nullptr;
1323}
1324
1325static const unsigned MaxDepth = 6;
1326
1327// Take the exact integer log2 of the value. If DoFold is true, create the
1328// actual instructions, otherwise return a non-null dummy value. Return nullptr
1329// on failure.
1330static Value *takeLog2(IRBuilderBase &Builder, Value *Op, unsigned Depth,
1331 bool AssumeNonZero, bool DoFold) {
1332 auto IfFold = [DoFold](function_ref<Value *()> Fn) {
1333 if (!DoFold)
1334 return reinterpret_cast<Value *>(-1);
1335 return Fn();
1336 };
1337
1338 // FIXME: assert that Op1 isn't/doesn't contain undef.
1339
1340 // log2(2^C) -> C
1341 if (match(Op, m_Power2()))
1342 return IfFold([&]() {
1343 Constant *C = ConstantExpr::getExactLogBase2(cast<Constant>(Op));
1344 if (!C)
1345 llvm_unreachable("Failed to constant fold udiv -> logbase2");
1346 return C;
1347 });
1348
1349 // The remaining tests are all recursive, so bail out if we hit the limit.
1350 if (Depth++ == MaxDepth)
1351 return nullptr;
1352
1353 // log2(zext X) -> zext log2(X)
1354 // FIXME: Require one use?
1355 Value *X, *Y;
1356 if (match(Op, m_ZExt(m_Value(X))))
1357 if (Value *LogX = takeLog2(Builder, X, Depth, AssumeNonZero, DoFold))
1358 return IfFold([&]() { return Builder.CreateZExt(LogX, Op->getType()); });
1359
1360 // log2(X << Y) -> log2(X) + Y
1361 // FIXME: Require one use unless X is 1?
1362 if (match(Op, m_Shl(m_Value(X), m_Value(Y)))) {
1363 auto *BO = cast<OverflowingBinaryOperator>(Op);
1364 // nuw will be set if the `shl` is trivially non-zero.
1365 if (AssumeNonZero || BO->hasNoUnsignedWrap() || BO->hasNoSignedWrap())
1366 if (Value *LogX = takeLog2(Builder, X, Depth, AssumeNonZero, DoFold))
1367 return IfFold([&]() { return Builder.CreateAdd(LogX, Y); });
1368 }
1369
1370 // log2(Cond ? X : Y) -> Cond ? log2(X) : log2(Y)
1371 // FIXME: Require one use?
1372 if (SelectInst *SI = dyn_cast<SelectInst>(Op))
1373 if (Value *LogX = takeLog2(Builder, SI->getOperand(1), Depth,
1374 AssumeNonZero, DoFold))
1375 if (Value *LogY = takeLog2(Builder, SI->getOperand(2), Depth,
1376 AssumeNonZero, DoFold))
1377 return IfFold([&]() {
1378 return Builder.CreateSelect(SI->getOperand(0), LogX, LogY);
1379 });
1380
1381 // log2(umin(X, Y)) -> umin(log2(X), log2(Y))
1382 // log2(umax(X, Y)) -> umax(log2(X), log2(Y))
1383 auto *MinMax = dyn_cast<MinMaxIntrinsic>(Op);
1384 if (MinMax && MinMax->hasOneUse() && !MinMax->isSigned()) {
1385 // Use AssumeNonZero as false here. Otherwise we can hit case where
1386 // log2(umax(X, Y)) != umax(log2(X), log2(Y)) (because overflow).
1387 if (Value *LogX = takeLog2(Builder, MinMax->getLHS(), Depth,
1388 /*AssumeNonZero*/ false, DoFold))
1389 if (Value *LogY = takeLog2(Builder, MinMax->getRHS(), Depth,
1390 /*AssumeNonZero*/ false, DoFold))
1391 return IfFold([&]() {
1392 return Builder.CreateBinaryIntrinsic(MinMax->getIntrinsicID(), LogX,
1393 LogY);
1394 });
1395 }
1396
1397 return nullptr;
1398}
1399
1400/// If we have zero-extended operands of an unsigned div or rem, we may be able
1401/// to narrow the operation (sink the zext below the math).
1403 InstCombinerImpl &IC) {
1404 Instruction::BinaryOps Opcode = I.getOpcode();
1405 Value *N = I.getOperand(0);
1406 Value *D = I.getOperand(1);
1407 Type *Ty = I.getType();
1408 Value *X, *Y;
1409 if (match(N, m_ZExt(m_Value(X))) && match(D, m_ZExt(m_Value(Y))) &&
1410 X->getType() == Y->getType() && (N->hasOneUse() || D->hasOneUse())) {
1411 // udiv (zext X), (zext Y) --> zext (udiv X, Y)
1412 // urem (zext X), (zext Y) --> zext (urem X, Y)
1413 Value *NarrowOp = IC.Builder.CreateBinOp(Opcode, X, Y);
1414 return new ZExtInst(NarrowOp, Ty);
1415 }
1416
1417 Constant *C;
1418 if (isa<Instruction>(N) && match(N, m_OneUse(m_ZExt(m_Value(X)))) &&
1419 match(D, m_Constant(C))) {
1420 // If the constant is the same in the smaller type, use the narrow version.
1421 Constant *TruncC = IC.getLosslessUnsignedTrunc(C, X->getType());
1422 if (!TruncC)
1423 return nullptr;
1424
1425 // udiv (zext X), C --> zext (udiv X, C')
1426 // urem (zext X), C --> zext (urem X, C')
1427 return new ZExtInst(IC.Builder.CreateBinOp(Opcode, X, TruncC), Ty);
1428 }
1429 if (isa<Instruction>(D) && match(D, m_OneUse(m_ZExt(m_Value(X)))) &&
1430 match(N, m_Constant(C))) {
1431 // If the constant is the same in the smaller type, use the narrow version.
1432 Constant *TruncC = IC.getLosslessUnsignedTrunc(C, X->getType());
1433 if (!TruncC)
1434 return nullptr;
1435
1436 // udiv C, (zext X) --> zext (udiv C', X)
1437 // urem C, (zext X) --> zext (urem C', X)
1438 return new ZExtInst(IC.Builder.CreateBinOp(Opcode, TruncC, X), Ty);
1439 }
1440
1441 return nullptr;
1442}
1443
1445 if (Value *V = simplifyUDivInst(I.getOperand(0), I.getOperand(1), I.isExact(),
1447 return replaceInstUsesWith(I, V);
1448
1450 return X;
1451
1452 // Handle the integer div common cases
1453 if (Instruction *Common = commonIDivTransforms(I))
1454 return Common;
1455
1456 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1457 Value *X;
1458 const APInt *C1, *C2;
1459 if (match(Op0, m_LShr(m_Value(X), m_APInt(C1))) && match(Op1, m_APInt(C2))) {
1460 // (X lshr C1) udiv C2 --> X udiv (C2 << C1)
1461 bool Overflow;
1462 APInt C2ShlC1 = C2->ushl_ov(*C1, Overflow);
1463 if (!Overflow) {
1464 bool IsExact = I.isExact() && match(Op0, m_Exact(m_Value()));
1465 BinaryOperator *BO = BinaryOperator::CreateUDiv(
1466 X, ConstantInt::get(X->getType(), C2ShlC1));
1467 if (IsExact)
1468 BO->setIsExact();
1469 return BO;
1470 }
1471 }
1472
1473 // Op0 / C where C is large (negative) --> zext (Op0 >= C)
1474 // TODO: Could use isKnownNegative() to handle non-constant values.
1475 Type *Ty = I.getType();
1476 if (match(Op1, m_Negative())) {
1477 Value *Cmp = Builder.CreateICmpUGE(Op0, Op1);
1478 return CastInst::CreateZExtOrBitCast(Cmp, Ty);
1479 }
1480 // Op0 / (sext i1 X) --> zext (Op0 == -1) (if X is 0, the div is undefined)
1481 if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
1483 return CastInst::CreateZExtOrBitCast(Cmp, Ty);
1484 }
1485
1486 if (Instruction *NarrowDiv = narrowUDivURem(I, *this))
1487 return NarrowDiv;
1488
1489 Value *A, *B;
1490
1491 // Look through a right-shift to find the common factor:
1492 // ((Op1 *nuw A) >> B) / Op1 --> A >> B
1493 if (match(Op0, m_LShr(m_NUWMul(m_Specific(Op1), m_Value(A)), m_Value(B))) ||
1494 match(Op0, m_LShr(m_NUWMul(m_Value(A), m_Specific(Op1)), m_Value(B)))) {
1495 Instruction *Lshr = BinaryOperator::CreateLShr(A, B);
1496 if (I.isExact() && cast<PossiblyExactOperator>(Op0)->isExact())
1497 Lshr->setIsExact();
1498 return Lshr;
1499 }
1500
1501 // Op1 udiv Op2 -> Op1 lshr log2(Op2), if log2() folds away.
1502 if (takeLog2(Builder, Op1, /*Depth*/ 0, /*AssumeNonZero*/ true,
1503 /*DoFold*/ false)) {
1504 Value *Res = takeLog2(Builder, Op1, /*Depth*/ 0,
1505 /*AssumeNonZero*/ true, /*DoFold*/ true);
1506 return replaceInstUsesWith(
1507 I, Builder.CreateLShr(Op0, Res, I.getName(), I.isExact()));
1508 }
1509
1510 return nullptr;
1511}
1512
1514 if (Value *V = simplifySDivInst(I.getOperand(0), I.getOperand(1), I.isExact(),
1516 return replaceInstUsesWith(I, V);
1517
1519 return X;
1520
1521 // Handle the integer div common cases
1522 if (Instruction *Common = commonIDivTransforms(I))
1523 return Common;
1524
1525 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1526 Type *Ty = I.getType();
1527 Value *X;
1528 // sdiv Op0, -1 --> -Op0
1529 // sdiv Op0, (sext i1 X) --> -Op0 (because if X is 0, the op is undefined)
1530 if (match(Op1, m_AllOnes()) ||
1531 (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)))
1532 return BinaryOperator::CreateNSWNeg(Op0);
1533
1534 // X / INT_MIN --> X == INT_MIN
1535 if (match(Op1, m_SignMask()))
1536 return new ZExtInst(Builder.CreateICmpEQ(Op0, Op1), Ty);
1537
1538 if (I.isExact()) {
1539 // sdiv exact X, 1<<C --> ashr exact X, C iff 1<<C is non-negative
1540 if (match(Op1, m_Power2()) && match(Op1, m_NonNegative())) {
1541 Constant *C = ConstantExpr::getExactLogBase2(cast<Constant>(Op1));
1542 return BinaryOperator::CreateExactAShr(Op0, C);
1543 }
1544
1545 // sdiv exact X, (1<<ShAmt) --> ashr exact X, ShAmt (if shl is non-negative)
1546 Value *ShAmt;
1547 if (match(Op1, m_NSWShl(m_One(), m_Value(ShAmt))))
1548 return BinaryOperator::CreateExactAShr(Op0, ShAmt);
1549
1550 // sdiv exact X, -1<<C --> -(ashr exact X, C)
1551 if (match(Op1, m_NegatedPower2())) {
1552 Constant *NegPow2C = ConstantExpr::getNeg(cast<Constant>(Op1));
1554 Value *Ashr = Builder.CreateAShr(Op0, C, I.getName() + ".neg", true);
1555 return BinaryOperator::CreateNSWNeg(Ashr);
1556 }
1557 }
1558
1559 const APInt *Op1C;
1560 if (match(Op1, m_APInt(Op1C))) {
1561 // If the dividend is sign-extended and the constant divisor is small enough
1562 // to fit in the source type, shrink the division to the narrower type:
1563 // (sext X) sdiv C --> sext (X sdiv C)
1564 Value *Op0Src;
1565 if (match(Op0, m_OneUse(m_SExt(m_Value(Op0Src)))) &&
1566 Op0Src->getType()->getScalarSizeInBits() >=
1567 Op1C->getSignificantBits()) {
1568
1569 // In the general case, we need to make sure that the dividend is not the
1570 // minimum signed value because dividing that by -1 is UB. But here, we
1571 // know that the -1 divisor case is already handled above.
1572
1573 Constant *NarrowDivisor =
1574 ConstantExpr::getTrunc(cast<Constant>(Op1), Op0Src->getType());
1575 Value *NarrowOp = Builder.CreateSDiv(Op0Src, NarrowDivisor);
1576 return new SExtInst(NarrowOp, Ty);
1577 }
1578
1579 // -X / C --> X / -C (if the negation doesn't overflow).
1580 // TODO: This could be enhanced to handle arbitrary vector constants by
1581 // checking if all elements are not the min-signed-val.
1582 if (!Op1C->isMinSignedValue() && match(Op0, m_NSWNeg(m_Value(X)))) {
1583 Constant *NegC = ConstantInt::get(Ty, -(*Op1C));
1584 Instruction *BO = BinaryOperator::CreateSDiv(X, NegC);
1585 BO->setIsExact(I.isExact());
1586 return BO;
1587 }
1588 }
1589
1590 // -X / Y --> -(X / Y)
1591 Value *Y;
1594 Builder.CreateSDiv(X, Y, I.getName(), I.isExact()));
1595
1596 // abs(X) / X --> X > -1 ? 1 : -1
1597 // X / abs(X) --> X > -1 ? 1 : -1
1598 if (match(&I, m_c_BinOp(
1599 m_OneUse(m_Intrinsic<Intrinsic::abs>(m_Value(X), m_One())),
1600 m_Deferred(X)))) {
1602 return SelectInst::Create(Cond, ConstantInt::get(Ty, 1),
1604 }
1605
1606 KnownBits KnownDividend = computeKnownBits(Op0, 0, &I);
1607 if (!I.isExact() &&
1608 (match(Op1, m_Power2(Op1C)) || match(Op1, m_NegatedPower2(Op1C))) &&
1609 KnownDividend.countMinTrailingZeros() >= Op1C->countr_zero()) {
1610 I.setIsExact();
1611 return &I;
1612 }
1613
1614 if (KnownDividend.isNonNegative()) {
1615 // If both operands are unsigned, turn this into a udiv.
1617 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1618 BO->setIsExact(I.isExact());
1619 return BO;
1620 }
1621
1622 if (match(Op1, m_NegatedPower2())) {
1623 // X sdiv (-(1 << C)) -> -(X sdiv (1 << C)) ->
1624 // -> -(X udiv (1 << C)) -> -(X u>> C)
1626 ConstantExpr::getNeg(cast<Constant>(Op1)));
1627 Value *Shr = Builder.CreateLShr(Op0, CNegLog2, I.getName(), I.isExact());
1628 return BinaryOperator::CreateNeg(Shr);
1629 }
1630
1631 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/ true, 0, &I)) {
1632 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
1633 // Safe because the only negative value (1 << Y) can take on is
1634 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
1635 // the sign bit set.
1636 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1637 BO->setIsExact(I.isExact());
1638 return BO;
1639 }
1640 }
1641
1642 // -X / X --> X == INT_MIN ? 1 : -1
1643 if (isKnownNegation(Op0, Op1)) {
1645 Value *Cond = Builder.CreateICmpEQ(Op0, ConstantInt::get(Ty, MinVal));
1646 return SelectInst::Create(Cond, ConstantInt::get(Ty, 1),
1648 }
1649 return nullptr;
1650}
1651
1652/// Remove negation and try to convert division into multiplication.
1653Instruction *InstCombinerImpl::foldFDivConstantDivisor(BinaryOperator &I) {
1654 Constant *C;
1655 if (!match(I.getOperand(1), m_Constant(C)))
1656 return nullptr;
1657
1658 // -X / C --> X / -C
1659 Value *X;
1660 const DataLayout &DL = I.getModule()->getDataLayout();
1661 if (match(I.getOperand(0), m_FNeg(m_Value(X))))
1662 if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL))
1663 return BinaryOperator::CreateFDivFMF(X, NegC, &I);
1664
1665 // nnan X / +0.0 -> copysign(inf, X)
1666 // nnan nsz X / -0.0 -> copysign(inf, X)
1667 if (I.hasNoNaNs() &&
1668 (match(I.getOperand(1), m_PosZeroFP()) ||
1669 (I.hasNoSignedZeros() && match(I.getOperand(1), m_AnyZeroFP())))) {
1670 IRBuilder<> B(&I);
1671 CallInst *CopySign = B.CreateIntrinsic(
1672 Intrinsic::copysign, {C->getType()},
1673 {ConstantFP::getInfinity(I.getType()), I.getOperand(0)}, &I);
1674 CopySign->takeName(&I);
1675 return replaceInstUsesWith(I, CopySign);
1676 }
1677
1678 // If the constant divisor has an exact inverse, this is always safe. If not,
1679 // then we can still create a reciprocal if fast-math-flags allow it and the
1680 // constant is a regular number (not zero, infinite, or denormal).
1681 if (!(C->hasExactInverseFP() || (I.hasAllowReciprocal() && C->isNormalFP())))
1682 return nullptr;
1683
1684 // Disallow denormal constants because we don't know what would happen
1685 // on all targets.
1686 // TODO: Use Intrinsic::canonicalize or let function attributes tell us that
1687 // denorms are flushed?
1688 auto *RecipC = ConstantFoldBinaryOpOperands(
1689 Instruction::FDiv, ConstantFP::get(I.getType(), 1.0), C, DL);
1690 if (!RecipC || !RecipC->isNormalFP())
1691 return nullptr;
1692
1693 // X / C --> X * (1 / C)
1694 return BinaryOperator::CreateFMulFMF(I.getOperand(0), RecipC, &I);
1695}
1696
1697/// Remove negation and try to reassociate constant math.
1699 Constant *C;
1700 if (!match(I.getOperand(0), m_Constant(C)))
1701 return nullptr;
1702
1703 // C / -X --> -C / X
1704 Value *X;
1705 const DataLayout &DL = I.getModule()->getDataLayout();
1706 if (match(I.getOperand(1), m_FNeg(m_Value(X))))
1707 if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL))
1708 return BinaryOperator::CreateFDivFMF(NegC, X, &I);
1709
1710 if (!I.hasAllowReassoc() || !I.hasAllowReciprocal())
1711 return nullptr;
1712
1713 // Try to reassociate C / X expressions where X includes another constant.
1714 Constant *C2, *NewC = nullptr;
1715 if (match(I.getOperand(1), m_FMul(m_Value(X), m_Constant(C2)))) {
1716 // C / (X * C2) --> (C / C2) / X
1717 NewC = ConstantFoldBinaryOpOperands(Instruction::FDiv, C, C2, DL);
1718 } else if (match(I.getOperand(1), m_FDiv(m_Value(X), m_Constant(C2)))) {
1719 // C / (X / C2) --> (C * C2) / X
1720 NewC = ConstantFoldBinaryOpOperands(Instruction::FMul, C, C2, DL);
1721 }
1722 // Disallow denormal constants because we don't know what would happen
1723 // on all targets.
1724 // TODO: Use Intrinsic::canonicalize or let function attributes tell us that
1725 // denorms are flushed?
1726 if (!NewC || !NewC->isNormalFP())
1727 return nullptr;
1728
1729 return BinaryOperator::CreateFDivFMF(NewC, X, &I);
1730}
1731
1732/// Negate the exponent of pow/exp to fold division-by-pow() into multiply.
1734 InstCombiner::BuilderTy &Builder) {
1735 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1736 auto *II = dyn_cast<IntrinsicInst>(Op1);
1737 if (!II || !II->hasOneUse() || !I.hasAllowReassoc() ||
1738 !I.hasAllowReciprocal())
1739 return nullptr;
1740
1741 // Z / pow(X, Y) --> Z * pow(X, -Y)
1742 // Z / exp{2}(Y) --> Z * exp{2}(-Y)
1743 // In the general case, this creates an extra instruction, but fmul allows
1744 // for better canonicalization and optimization than fdiv.
1745 Intrinsic::ID IID = II->getIntrinsicID();
1747 switch (IID) {
1748 case Intrinsic::pow:
1749 Args.push_back(II->getArgOperand(0));
1750 Args.push_back(Builder.CreateFNegFMF(II->getArgOperand(1), &I));
1751 break;
1752 case Intrinsic::powi: {
1753 // Require 'ninf' assuming that makes powi(X, -INT_MIN) acceptable.
1754 // That is, X ** (huge negative number) is 0.0, ~1.0, or INF and so
1755 // dividing by that is INF, ~1.0, or 0.0. Code that uses powi allows
1756 // non-standard results, so this corner case should be acceptable if the
1757 // code rules out INF values.
1758 if (!I.hasNoInfs())
1759 return nullptr;
1760 Args.push_back(II->getArgOperand(0));
1761 Args.push_back(Builder.CreateNeg(II->getArgOperand(1)));
1762 Type *Tys[] = {I.getType(), II->getArgOperand(1)->getType()};
1763 Value *Pow = Builder.CreateIntrinsic(IID, Tys, Args, &I);
1764 return BinaryOperator::CreateFMulFMF(Op0, Pow, &I);
1765 }
1766 case Intrinsic::exp:
1767 case Intrinsic::exp2:
1768 Args.push_back(Builder.CreateFNegFMF(II->getArgOperand(0), &I));
1769 break;
1770 default:
1771 return nullptr;
1772 }
1773 Value *Pow = Builder.CreateIntrinsic(IID, I.getType(), Args, &I);
1774 return BinaryOperator::CreateFMulFMF(Op0, Pow, &I);
1775}
1776
1777/// Convert div to mul if we have an sqrt divisor iff sqrt's operand is a fdiv
1778/// instruction.
1780 InstCombiner::BuilderTy &Builder) {
1781 // X / sqrt(Y / Z) --> X * sqrt(Z / Y)
1782 if (!I.hasAllowReassoc() || !I.hasAllowReciprocal())
1783 return nullptr;
1784 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1785 auto *II = dyn_cast<IntrinsicInst>(Op1);
1786 if (!II || II->getIntrinsicID() != Intrinsic::sqrt || !II->hasOneUse() ||
1787 !II->hasAllowReassoc() || !II->hasAllowReciprocal())
1788 return nullptr;
1789
1790 Value *Y, *Z;
1791 auto *DivOp = dyn_cast<Instruction>(II->getOperand(0));
1792 if (!DivOp)
1793 return nullptr;
1794 if (!match(DivOp, m_FDiv(m_Value(Y), m_Value(Z))))
1795 return nullptr;
1796 if (!DivOp->hasAllowReassoc() || !I.hasAllowReciprocal() ||
1797 !DivOp->hasOneUse())
1798 return nullptr;
1799 Value *SwapDiv = Builder.CreateFDivFMF(Z, Y, DivOp);
1800 Value *NewSqrt =
1801 Builder.CreateUnaryIntrinsic(II->getIntrinsicID(), SwapDiv, II);
1802 return BinaryOperator::CreateFMulFMF(Op0, NewSqrt, &I);
1803}
1804
1806 Module *M = I.getModule();
1807
1808 if (Value *V = simplifyFDivInst(I.getOperand(0), I.getOperand(1),
1809 I.getFastMathFlags(),
1811 return replaceInstUsesWith(I, V);
1812
1814 return X;
1815
1817 return Phi;
1818
1819 if (Instruction *R = foldFDivConstantDivisor(I))
1820 return R;
1821
1823 return R;
1824
1825 if (Instruction *R = foldFPSignBitOps(I))
1826 return R;
1827
1828 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1829 if (isa<Constant>(Op0))
1830 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1831 if (Instruction *R = FoldOpIntoSelect(I, SI))
1832 return R;
1833
1834 if (isa<Constant>(Op1))
1835 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1836 if (Instruction *R = FoldOpIntoSelect(I, SI))
1837 return R;
1838
1839 if (I.hasAllowReassoc() && I.hasAllowReciprocal()) {
1840 Value *X, *Y;
1841 if (match(Op0, m_OneUse(m_FDiv(m_Value(X), m_Value(Y)))) &&
1842 (!isa<Constant>(Y) || !isa<Constant>(Op1))) {
1843 // (X / Y) / Z => X / (Y * Z)
1844 Value *YZ = Builder.CreateFMulFMF(Y, Op1, &I);
1845 return BinaryOperator::CreateFDivFMF(X, YZ, &I);
1846 }
1847 if (match(Op1, m_OneUse(m_FDiv(m_Value(X), m_Value(Y)))) &&
1848 (!isa<Constant>(Y) || !isa<Constant>(Op0))) {
1849 // Z / (X / Y) => (Y * Z) / X
1850 Value *YZ = Builder.CreateFMulFMF(Y, Op0, &I);
1851 return BinaryOperator::CreateFDivFMF(YZ, X, &I);
1852 }
1853 // Z / (1.0 / Y) => (Y * Z)
1854 //
1855 // This is a special case of Z / (X / Y) => (Y * Z) / X, with X = 1.0. The
1856 // m_OneUse check is avoided because even in the case of the multiple uses
1857 // for 1.0/Y, the number of instructions remain the same and a division is
1858 // replaced by a multiplication.
1859 if (match(Op1, m_FDiv(m_SpecificFP(1.0), m_Value(Y))))
1860 return BinaryOperator::CreateFMulFMF(Y, Op0, &I);
1861 }
1862
1863 if (I.hasAllowReassoc() && Op0->hasOneUse() && Op1->hasOneUse()) {
1864 // sin(X) / cos(X) -> tan(X)
1865 // cos(X) / sin(X) -> 1/tan(X) (cotangent)
1866 Value *X;
1867 bool IsTan = match(Op0, m_Intrinsic<Intrinsic::sin>(m_Value(X))) &&
1868 match(Op1, m_Intrinsic<Intrinsic::cos>(m_Specific(X)));
1869 bool IsCot =
1870 !IsTan && match(Op0, m_Intrinsic<Intrinsic::cos>(m_Value(X))) &&
1871 match(Op1, m_Intrinsic<Intrinsic::sin>(m_Specific(X)));
1872
1873 if ((IsTan || IsCot) && hasFloatFn(M, &TLI, I.getType(), LibFunc_tan,
1874 LibFunc_tanf, LibFunc_tanl)) {
1875 IRBuilder<> B(&I);
1877 B.setFastMathFlags(I.getFastMathFlags());
1878 AttributeList Attrs =
1879 cast<CallBase>(Op0)->getCalledFunction()->getAttributes();
1880 Value *Res = emitUnaryFloatFnCall(X, &TLI, LibFunc_tan, LibFunc_tanf,
1881 LibFunc_tanl, B, Attrs);
1882 if (IsCot)
1883 Res = B.CreateFDiv(ConstantFP::get(I.getType(), 1.0), Res);
1884 return replaceInstUsesWith(I, Res);
1885 }
1886 }
1887
1888 // X / (X * Y) --> 1.0 / Y
1889 // Reassociate to (X / X -> 1.0) is legal when NaNs are not allowed.
1890 // We can ignore the possibility that X is infinity because INF/INF is NaN.
1891 Value *X, *Y;
1892 if (I.hasNoNaNs() && I.hasAllowReassoc() &&
1893 match(Op1, m_c_FMul(m_Specific(Op0), m_Value(Y)))) {
1894 replaceOperand(I, 0, ConstantFP::get(I.getType(), 1.0));
1895 replaceOperand(I, 1, Y);
1896 return &I;
1897 }
1898
1899 // X / fabs(X) -> copysign(1.0, X)
1900 // fabs(X) / X -> copysign(1.0, X)
1901 if (I.hasNoNaNs() && I.hasNoInfs() &&
1902 (match(&I, m_FDiv(m_Value(X), m_FAbs(m_Deferred(X)))) ||
1903 match(&I, m_FDiv(m_FAbs(m_Value(X)), m_Deferred(X))))) {
1905 Intrinsic::copysign, ConstantFP::get(I.getType(), 1.0), X, &I);
1906 return replaceInstUsesWith(I, V);
1907 }
1908
1910 return Mul;
1911
1913 return Mul;
1914
1915 // pow(X, Y) / X --> pow(X, Y-1)
1916 if (I.hasAllowReassoc() &&
1917 match(Op0, m_OneUse(m_Intrinsic<Intrinsic::pow>(m_Specific(Op1),
1918 m_Value(Y))))) {
1919 Value *Y1 =
1920 Builder.CreateFAddFMF(Y, ConstantFP::get(I.getType(), -1.0), &I);
1921 Value *Pow = Builder.CreateBinaryIntrinsic(Intrinsic::pow, Op1, Y1, &I);
1922 return replaceInstUsesWith(I, Pow);
1923 }
1924
1925 if (Instruction *FoldedPowi = foldPowiReassoc(I))
1926 return FoldedPowi;
1927
1928 return nullptr;
1929}
1930
1931// Variety of transform for:
1932// (urem/srem (mul X, Y), (mul X, Z))
1933// (urem/srem (shl X, Y), (shl X, Z))
1934// (urem/srem (shl Y, X), (shl Z, X))
1935// NB: The shift cases are really just extensions of the mul case. We treat
1936// shift as Val * (1 << Amt).
1938 InstCombinerImpl &IC) {
1939 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1), *X = nullptr;
1940 APInt Y, Z;
1941 bool ShiftByX = false;
1942
1943 // If V is not nullptr, it will be matched using m_Specific.
1944 auto MatchShiftOrMulXC = [](Value *Op, Value *&V, APInt &C) -> bool {
1945 const APInt *Tmp = nullptr;
1946 if ((!V && match(Op, m_Mul(m_Value(V), m_APInt(Tmp)))) ||
1947 (V && match(Op, m_Mul(m_Specific(V), m_APInt(Tmp)))))
1948 C = *Tmp;
1949 else if ((!V && match(Op, m_Shl(m_Value(V), m_APInt(Tmp)))) ||
1950 (V && match(Op, m_Shl(m_Specific(V), m_APInt(Tmp)))))
1951 C = APInt(Tmp->getBitWidth(), 1) << *Tmp;
1952 if (Tmp != nullptr)
1953 return true;
1954
1955 // Reset `V` so we don't start with specific value on next match attempt.
1956 V = nullptr;
1957 return false;
1958 };
1959
1960 auto MatchShiftCX = [](Value *Op, APInt &C, Value *&V) -> bool {
1961 const APInt *Tmp = nullptr;
1962 if ((!V && match(Op, m_Shl(m_APInt(Tmp), m_Value(V)))) ||
1963 (V && match(Op, m_Shl(m_APInt(Tmp), m_Specific(V))))) {
1964 C = *Tmp;
1965 return true;
1966 }
1967
1968 // Reset `V` so we don't start with specific value on next match attempt.
1969 V = nullptr;
1970 return false;
1971 };
1972
1973 if (MatchShiftOrMulXC(Op0, X, Y) && MatchShiftOrMulXC(Op1, X, Z)) {
1974 // pass
1975 } else if (MatchShiftCX(Op0, Y, X) && MatchShiftCX(Op1, Z, X)) {
1976 ShiftByX = true;
1977 } else {
1978 return nullptr;
1979 }
1980
1981 bool IsSRem = I.getOpcode() == Instruction::SRem;
1982
1983 OverflowingBinaryOperator *BO0 = cast<OverflowingBinaryOperator>(Op0);
1984 // TODO: We may be able to deduce more about nsw/nuw of BO0/BO1 based on Y >=
1985 // Z or Z >= Y.
1986 bool BO0HasNSW = BO0->hasNoSignedWrap();
1987 bool BO0HasNUW = BO0->hasNoUnsignedWrap();
1988 bool BO0NoWrap = IsSRem ? BO0HasNSW : BO0HasNUW;
1989
1990 APInt RemYZ = IsSRem ? Y.srem(Z) : Y.urem(Z);
1991 // (rem (mul nuw/nsw X, Y), (mul X, Z))
1992 // if (rem Y, Z) == 0
1993 // -> 0
1994 if (RemYZ.isZero() && BO0NoWrap)
1995 return IC.replaceInstUsesWith(I, ConstantInt::getNullValue(I.getType()));
1996
1997 // Helper function to emit either (RemSimplificationC << X) or
1998 // (RemSimplificationC * X) depending on whether we matched Op0/Op1 as
1999 // (shl V, X) or (mul V, X) respectively.
2000 auto CreateMulOrShift =
2001 [&](const APInt &RemSimplificationC) -> BinaryOperator * {
2002 Value *RemSimplification =
2003 ConstantInt::get(I.getType(), RemSimplificationC);
2004 return ShiftByX ? BinaryOperator::CreateShl(RemSimplification, X)
2005 : BinaryOperator::CreateMul(X, RemSimplification);
2006 };
2007
2008 OverflowingBinaryOperator *BO1 = cast<OverflowingBinaryOperator>(Op1);
2009 bool BO1HasNSW = BO1->hasNoSignedWrap();
2010 bool BO1HasNUW = BO1->hasNoUnsignedWrap();
2011 bool BO1NoWrap = IsSRem ? BO1HasNSW : BO1HasNUW;
2012 // (rem (mul X, Y), (mul nuw/nsw X, Z))
2013 // if (rem Y, Z) == Y
2014 // -> (mul nuw/nsw X, Y)
2015 if (RemYZ == Y && BO1NoWrap) {
2016 BinaryOperator *BO = CreateMulOrShift(Y);
2017 // Copy any overflow flags from Op0.
2018 BO->setHasNoSignedWrap(IsSRem || BO0HasNSW);
2019 BO->setHasNoUnsignedWrap(!IsSRem || BO0HasNUW);
2020 return BO;
2021 }
2022
2023 // (rem (mul nuw/nsw X, Y), (mul {nsw} X, Z))
2024 // if Y >= Z
2025 // -> (mul {nuw} nsw X, (rem Y, Z))
2026 if (Y.uge(Z) && (IsSRem ? (BO0HasNSW && BO1HasNSW) : BO0HasNUW)) {
2027 BinaryOperator *BO = CreateMulOrShift(RemYZ);
2028 BO->setHasNoSignedWrap();
2029 BO->setHasNoUnsignedWrap(BO0HasNUW);
2030 return BO;
2031 }
2032
2033 return nullptr;
2034}
2035
2036/// This function implements the transforms common to both integer remainder
2037/// instructions (urem and srem). It is called by the visitors to those integer
2038/// remainder instructions.
2039/// Common integer remainder transforms
2042 return Phi;
2043
2044 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2045
2046 // The RHS is known non-zero.
2047 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I))
2048 return replaceOperand(I, 1, V);
2049
2050 // Handle cases involving: rem X, (select Cond, Y, Z)
2052 return &I;
2053
2054 // If the divisor is a select-of-constants, try to constant fold all rem ops:
2055 // C % (select Cond, TrueC, FalseC) --> select Cond, (C % TrueC), (C % FalseC)
2056 // TODO: Adapt simplifyDivRemOfSelectWithZeroOp to allow this and other folds.
2057 if (match(Op0, m_ImmConstant()) &&
2059 if (Instruction *R = FoldOpIntoSelect(I, cast<SelectInst>(Op1),
2060 /*FoldWithMultiUse*/ true))
2061 return R;
2062 }
2063
2064 if (isa<Constant>(Op1)) {
2065 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2066 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2067 if (Instruction *R = FoldOpIntoSelect(I, SI))
2068 return R;
2069 } else if (auto *PN = dyn_cast<PHINode>(Op0I)) {
2070 const APInt *Op1Int;
2071 if (match(Op1, m_APInt(Op1Int)) && !Op1Int->isMinValue() &&
2072 (I.getOpcode() == Instruction::URem ||
2073 !Op1Int->isMinSignedValue())) {
2074 // foldOpIntoPhi will speculate instructions to the end of the PHI's
2075 // predecessor blocks, so do this only if we know the srem or urem
2076 // will not fault.
2077 if (Instruction *NV = foldOpIntoPhi(I, PN))
2078 return NV;
2079 }
2080 }
2081
2082 // See if we can fold away this rem instruction.
2084 return &I;
2085 }
2086 }
2087
2088 if (Instruction *R = simplifyIRemMulShl(I, *this))
2089 return R;
2090
2091 return nullptr;
2092}
2093
2095 if (Value *V = simplifyURemInst(I.getOperand(0), I.getOperand(1),
2097 return replaceInstUsesWith(I, V);
2098
2100 return X;
2101
2102 if (Instruction *common = commonIRemTransforms(I))
2103 return common;
2104
2105 if (Instruction *NarrowRem = narrowUDivURem(I, *this))
2106 return NarrowRem;
2107
2108 // X urem Y -> X and Y-1, where Y is a power of 2,
2109 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2110 Type *Ty = I.getType();
2111 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/ true, 0, &I)) {
2112 // This may increase instruction count, we don't enforce that Y is a
2113 // constant.
2115 Value *Add = Builder.CreateAdd(Op1, N1);
2116 return BinaryOperator::CreateAnd(Op0, Add);
2117 }
2118
2119 // 1 urem X -> zext(X != 1)
2120 if (match(Op0, m_One())) {
2121 Value *Cmp = Builder.CreateICmpNE(Op1, ConstantInt::get(Ty, 1));
2122 return CastInst::CreateZExtOrBitCast(Cmp, Ty);
2123 }
2124
2125 // Op0 urem C -> Op0 < C ? Op0 : Op0 - C, where C >= signbit.
2126 // Op0 must be frozen because we are increasing its number of uses.
2127 if (match(Op1, m_Negative())) {
2128 Value *F0 = Builder.CreateFreeze(Op0, Op0->getName() + ".fr");
2129 Value *Cmp = Builder.CreateICmpULT(F0, Op1);
2130 Value *Sub = Builder.CreateSub(F0, Op1);
2131 return SelectInst::Create(Cmp, F0, Sub);
2132 }
2133
2134 // If the divisor is a sext of a boolean, then the divisor must be max
2135 // unsigned value (-1). Therefore, the remainder is Op0 unless Op0 is also
2136 // max unsigned value. In that case, the remainder is 0:
2137 // urem Op0, (sext i1 X) --> (Op0 == -1) ? 0 : Op0
2138 Value *X;
2139 if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
2140 Value *FrozenOp0 = Builder.CreateFreeze(Op0, Op0->getName() + ".frozen");
2141 Value *Cmp =
2143 return SelectInst::Create(Cmp, ConstantInt::getNullValue(Ty), FrozenOp0);
2144 }
2145
2146 // For "(X + 1) % Op1" and if (X u< Op1) => (X + 1) == Op1 ? 0 : X + 1 .
2147 if (match(Op0, m_Add(m_Value(X), m_One()))) {
2148 Value *Val =
2150 if (Val && match(Val, m_One())) {
2151 Value *FrozenOp0 = Builder.CreateFreeze(Op0, Op0->getName() + ".frozen");
2152 Value *Cmp = Builder.CreateICmpEQ(FrozenOp0, Op1);
2153 return SelectInst::Create(Cmp, ConstantInt::getNullValue(Ty), FrozenOp0);
2154 }
2155 }
2156
2157 return nullptr;
2158}
2159
2161 if (Value *V = simplifySRemInst(I.getOperand(0), I.getOperand(1),
2163 return replaceInstUsesWith(I, V);
2164
2166 return X;
2167
2168 // Handle the integer rem common cases
2169 if (Instruction *Common = commonIRemTransforms(I))
2170 return Common;
2171
2172 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2173 {
2174 const APInt *Y;
2175 // X % -Y -> X % Y
2176 if (match(Op1, m_Negative(Y)) && !Y->isMinSignedValue())
2177 return replaceOperand(I, 1, ConstantInt::get(I.getType(), -*Y));
2178 }
2179
2180 // -X srem Y --> -(X srem Y)
2181 Value *X, *Y;
2184
2185 // If the sign bits of both operands are zero (i.e. we can prove they are
2186 // unsigned inputs), turn this into a urem.
2187 APInt Mask(APInt::getSignMask(I.getType()->getScalarSizeInBits()));
2188 if (MaskedValueIsZero(Op1, Mask, 0, &I) &&
2189 MaskedValueIsZero(Op0, Mask, 0, &I)) {
2190 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2191 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
2192 }
2193
2194 // If it's a constant vector, flip any negative values positive.
2195 if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
2196 Constant *C = cast<Constant>(Op1);
2197 unsigned VWidth = cast<FixedVectorType>(C->getType())->getNumElements();
2198
2199 bool hasNegative = false;
2200 bool hasMissing = false;
2201 for (unsigned i = 0; i != VWidth; ++i) {
2202 Constant *Elt = C->getAggregateElement(i);
2203 if (!Elt) {
2204 hasMissing = true;
2205 break;
2206 }
2207
2208 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
2209 if (RHS->isNegative())
2210 hasNegative = true;
2211 }
2212
2213 if (hasNegative && !hasMissing) {
2214 SmallVector<Constant *, 16> Elts(VWidth);
2215 for (unsigned i = 0; i != VWidth; ++i) {
2216 Elts[i] = C->getAggregateElement(i); // Handle undef, etc.
2217 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
2218 if (RHS->isNegative())
2219 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
2220 }
2221 }
2222
2223 Constant *NewRHSV = ConstantVector::get(Elts);
2224 if (NewRHSV != C) // Don't loop on -MININT
2225 return replaceOperand(I, 1, NewRHSV);
2226 }
2227 }
2228
2229 return nullptr;
2230}
2231
2233 if (Value *V = simplifyFRemInst(I.getOperand(0), I.getOperand(1),
2234 I.getFastMathFlags(),
2236 return replaceInstUsesWith(I, V);
2237
2239 return X;
2240
2242 return Phi;
2243
2244 return nullptr;
2245}
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
This file implements a class to represent arbitrary precision integral constant values and operations...
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
This file provides internal interfaces used to implement the InstCombine.
static Instruction * simplifyIRemMulShl(BinaryOperator &I, InstCombinerImpl &IC)
static Instruction * narrowUDivURem(BinaryOperator &I, InstCombinerImpl &IC)
If we have zero-extended operands of an unsigned div or rem, we may be able to narrow the operation (...
static Value * simplifyValueKnownNonZero(Value *V, InstCombinerImpl &IC, Instruction &CxtI)
The specific integer value is used in a context where it is known to be non-zero.
static const unsigned MaxDepth
static Value * foldMulSelectToNegate(BinaryOperator &I, InstCombiner::BuilderTy &Builder)
static Instruction * foldFDivPowDivisor(BinaryOperator &I, InstCombiner::BuilderTy &Builder)
Negate the exponent of pow/exp to fold division-by-pow() into multiply.
static bool multiplyOverflows(const APInt &C1, const APInt &C2, APInt &Product, bool IsSigned)
True if the multiply can not be expressed in an int this size.
static Value * foldMulShl1(BinaryOperator &Mul, bool CommuteOperands, InstCombiner::BuilderTy &Builder)
Reduce integer multiplication patterns that contain a (+/-1 << Z) factor.
static Value * takeLog2(IRBuilderBase &Builder, Value *Op, unsigned Depth, bool AssumeNonZero, bool DoFold)
static bool isMultiple(const APInt &C1, const APInt &C2, APInt &Quotient, bool IsSigned)
True if C1 is a multiple of C2. Quotient contains C1/C2.
static Instruction * foldFDivSqrtDivisor(BinaryOperator &I, InstCombiner::BuilderTy &Builder)
Convert div to mul if we have an sqrt divisor iff sqrt's operand is a fdiv instruction.
static Instruction * foldFDivConstantDividend(BinaryOperator &I)
Remove negation and try to reassociate constant math.
static Value * foldIDivShl(BinaryOperator &I, InstCombiner::BuilderTy &Builder)
This file provides the interface for the instcombine pass implementation.
static bool hasNoSignedWrap(BinaryOperator &I)
static bool hasNoUnsignedWrap(BinaryOperator &I)
#define I(x, y, z)
Definition: MD5.cpp:58
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
const SmallVectorImpl< MachineOperand > & Cond
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the SmallVector class.
Value * RHS
BinaryOperator * Mul
bool isNegative() const
Definition: APFloat.h:1295
bool isZero() const
Definition: APFloat.h:1291
Class for arbitrary precision integers.
Definition: APInt.h:76
APInt umul_ov(const APInt &RHS, bool &Overflow) const
Definition: APInt.cpp:1941
APInt udiv(const APInt &RHS) const
Unsigned division operation.
Definition: APInt.cpp:1543
static void udivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, APInt &Remainder)
Dual division/remainder interface.
Definition: APInt.cpp:1728
static APInt getSignMask(unsigned BitWidth)
Get the SignMask for a specific bit width.
Definition: APInt.h:207
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition: APInt.h:401
uint64_t getZExtValue() const
Get zero extended value.
Definition: APInt.h:1491
static void sdivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, APInt &Remainder)
Definition: APInt.cpp:1860
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition: APInt.h:349
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition: APInt.h:358
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition: APInt.h:1439
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition: APInt.h:1089
bool isMinValue() const
Determine if this is the smallest unsigned value.
Definition: APInt.h:395
unsigned countr_zero() const
Count the number of trailing zero bits.
Definition: APInt.h:1589
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition: APInt.h:197
APInt ushl_ov(const APInt &Amt, bool &Overflow) const
Definition: APInt.cpp:1975
unsigned getSignificantBits() const
Get the minimum bit size for this signed APInt.
Definition: APInt.h:1482
APInt smul_ov(const APInt &RHS, bool &Overflow) const
Definition: APInt.cpp:1930
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition: APInt.h:1128
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition: APInt.h:217
InstListType::iterator iterator
Instruction iterators...
Definition: BasicBlock.h:165
static BinaryOperator * CreateFAddFMF(Value *V1, Value *V2, FastMathFlags FMF, const Twine &Name="")
Definition: InstrTypes.h:324
static BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name, BasicBlock::iterator InsertBefore)
Construct a binary instruction, given the opcode and the two operands.
static BinaryOperator * CreateNSWNeg(Value *Op, const Twine &Name, BasicBlock::iterator InsertBefore)
BinaryOps getOpcode() const
Definition: InstrTypes.h:513
static BinaryOperator * CreateNeg(Value *Op, const Twine &Name, BasicBlock::iterator InsertBefore)
Helper functions to construct and inspect unary operations (NEG and NOT) via binary operators SUB and...
static BinaryOperator * CreateFMulFMF(Value *V1, Value *V2, FastMathFlags FMF, const Twine &Name="")
Definition: InstrTypes.h:332
static BinaryOperator * CreateFDivFMF(Value *V1, Value *V2, FastMathFlags FMF, const Twine &Name="")
Definition: InstrTypes.h:336
static BinaryOperator * CreateFSubFMF(Value *V1, Value *V2, FastMathFlags FMF, const Twine &Name="")
Definition: InstrTypes.h:328
static BinaryOperator * CreateWithCopiedFlags(BinaryOps Opc, Value *V1, Value *V2, Value *CopyO, const Twine &Name, BasicBlock::iterator InsertBefore)
Definition: InstrTypes.h:299
This class represents a function call, abstracting a target machine's calling convention.
static CastInst * CreateZExtOrBitCast(Value *S, Type *Ty, const Twine &Name, BasicBlock::iterator InsertBefore)
Create a ZExt or BitCast cast instruction.
static CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name, BasicBlock::iterator InsertBefore)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
static Type * makeCmpResultType(Type *opnd_type)
Create a result type for fcmp/icmp.
Definition: InstrTypes.h:1362
@ ICMP_ULT
unsigned less than
Definition: InstrTypes.h:1018
static Constant * getShl(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
Definition: Constants.cpp:2560
static Constant * getNeg(Constant *C, bool HasNSW=false)
Definition: Constants.cpp:2523
static Constant * getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:2098
static Constant * getExactLogBase2(Constant *C)
If C is a scalar/fixed width vector of known powers of 2, then this function returns a new scalar/fix...
Definition: Constants.cpp:2567
static Constant * getInfinity(Type *Ty, bool Negative=false)
Definition: Constants.cpp:1083
This is the shared class of boolean and integer constants.
Definition: Constants.h:80
static ConstantInt * getTrue(LLVMContext &Context)
Definition: Constants.cpp:849
static ConstantInt * getFalse(LLVMContext &Context)
Definition: Constants.cpp:856
static ConstantInt * getBool(LLVMContext &Context, bool V)
Definition: Constants.cpp:863
static Constant * get(ArrayRef< Constant * > V)
Definition: Constants.cpp:1398
This is an important base class in LLVM.
Definition: Constant.h:41
static Constant * replaceUndefsWith(Constant *C, Constant *Replacement)
Try to replace undefined constant C or undefined elements in C with Replacement.
Definition: Constants.cpp:767
static Constant * getAllOnesValue(Type *Ty)
Definition: Constants.cpp:417
bool isNormalFP() const
Return true if this is a normal (as opposed to denormal, infinity, nan, or zero) floating-point scala...
Definition: Constants.cpp:235
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Definition: Constants.cpp:370
bool isNotMinSignedValue() const
Return true if the value is not the smallest signed value, or, for vectors, does not contain smallest...
Definition: Constants.cpp:186
This class represents an Operation in the Expression.
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:110
Convenience struct for specifying and reasoning about fast-math flags.
Definition: FMF.h:20
bool allowReassoc() const
Flag queries.
Definition: FMF.h:65
Common base class shared among various IRBuilders.
Definition: IRBuilder.h:94
Value * CreateFAddFMF(Value *L, Value *R, Instruction *FMFSource, const Twine &Name="")
Copy fast-math-flags from an instruction rather than using the builder's default FMF.
Definition: IRBuilder.h:1547
CallInst * CreateUnaryIntrinsic(Intrinsic::ID ID, Value *V, Instruction *FMFSource=nullptr, const Twine &Name="")
Create a call to intrinsic ID with 1 operand which is mangled on its type.
Definition: IRBuilder.cpp:913
Value * CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:2257
Value * CreateSRem(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1410
Value * CreateBinaryIntrinsic(Intrinsic::ID ID, Value *LHS, Value *RHS, Instruction *FMFSource=nullptr, const Twine &Name="")
Create a call to intrinsic ID with 2 operands which is mangled on the first type.
Definition: IRBuilder.cpp:921
Value * CreateFMulFMF(Value *L, Value *R, Instruction *FMFSource, const Twine &Name="")
Copy fast-math-flags from an instruction rather than using the builder's default FMF.
Definition: IRBuilder.h:1601
Value * CreateFDivFMF(Value *L, Value *R, Instruction *FMFSource, const Twine &Name="")
Copy fast-math-flags from an instruction rather than using the builder's default FMF.
Definition: IRBuilder.h:1628
ConstantInt * getTrue()
Get the constant value for i1 true.
Definition: IRBuilder.h:466
CallInst * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type * > Types, ArrayRef< Value * > Args, Instruction *FMFSource=nullptr, const Twine &Name="")
Create a call to intrinsic ID with Args, mangled using Types.
Definition: IRBuilder.cpp:932
Value * CreateFNegFMF(Value *V, Instruction *FMFSource, const Twine &Name="")
Copy fast-math-flags from an instruction rather than using the builder's default FMF.
Definition: IRBuilder.h:1740
Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
Definition: IRBuilder.cpp:1110
Value * CreateFreeze(Value *V, const Twine &Name="")
Definition: IRBuilder.h:2535
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition: IRBuilder.h:1437
Value * CreateIsNotNeg(Value *Arg, const Twine &Name="")
Return a boolean value testing if Arg > -1.
Definition: IRBuilder.h:2559
void setFastMathFlags(FastMathFlags NewFMF)
Set the fast-math flags to be used with generated fp-math operators.
Definition: IRBuilder.h:311
Value * CreateNSWMul(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1370
Value * CreateUDiv(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition: IRBuilder.h:1378
Value * CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:2245
Value * CreateNeg(Value *V, const Twine &Name="", bool HasNSW=false)
Definition: IRBuilder.h:1721
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:2241
Value * CreateIsNeg(Value *Arg, const Twine &Name="")
Return a boolean value testing if Arg < 0.
Definition: IRBuilder.h:2554
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1344
Value * CreateShl(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1416
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="", bool IsNonNeg=false)
Definition: IRBuilder.h:2021
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1475
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1327
Value * CreateSDiv(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition: IRBuilder.h:1391
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="", bool IsNUW=false, bool IsNSW=false)
Definition: IRBuilder.h:2007
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:1666
Value * CreateICmpUGE(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:2253
Value * CreateAShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition: IRBuilder.h:1456
Value * CreateFMul(Value *L, Value *R, const Twine &Name="", MDNode *FPMD=nullptr)
Definition: IRBuilder.h:1587
Value * CreateFNeg(Value *V, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:1730
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1361
Instruction * visitMul(BinaryOperator &I)
Instruction * FoldOpIntoSelect(Instruction &Op, SelectInst *SI, bool FoldWithMultiUse=false)
Given an instruction with a select as one operand and a constant as the other operand,...
Instruction * foldBinOpOfSelectAndCastOfSelectCondition(BinaryOperator &I)
Tries to simplify binops of select and cast of the select condition.
Instruction * foldBinOpIntoSelectOrPhi(BinaryOperator &I)
This is a convenience wrapper function for the above two functions.
Instruction * visitUDiv(BinaryOperator &I)
bool SimplifyAssociativeOrCommutative(BinaryOperator &I)
Performs a few simplifications for operators which are associative or commutative.
Value * foldUsingDistributiveLaws(BinaryOperator &I)
Tries to simplify binary operations which some other binary operation distributes over.
Instruction * visitURem(BinaryOperator &I)
Instruction * foldOpIntoPhi(Instruction &I, PHINode *PN)
Given a binary operator, cast instruction, or select which has a PHI node as operand #0,...
Instruction * visitSRem(BinaryOperator &I)
Instruction * visitFDiv(BinaryOperator &I)
bool simplifyDivRemOfSelectWithZeroOp(BinaryOperator &I)
Fold a divide or remainder with a select instruction divisor when one of the select operands is zero.
Constant * getLosslessUnsignedTrunc(Constant *C, Type *TruncTy)
Instruction * commonIDivTransforms(BinaryOperator &I)
This function implements the transforms common to both integer division instructions (udiv and sdiv).
Instruction * foldBinopWithPhiOperands(BinaryOperator &BO)
For a binary operator with 2 phi operands, try to hoist the binary operation before the phi.
Instruction * visitFRem(BinaryOperator &I)
bool SimplifyDemandedInstructionBits(Instruction &Inst)
Tries to simplify operands to an integer instruction based on its demanded bits.
Instruction * visitFMul(BinaryOperator &I)
Instruction * foldFMulReassoc(BinaryOperator &I)
Instruction * foldVectorBinop(BinaryOperator &Inst)
Canonicalize the position of binops relative to shufflevector.
Value * SimplifySelectsFeedingBinaryOp(BinaryOperator &I, Value *LHS, Value *RHS)
Instruction * foldPowiReassoc(BinaryOperator &I)
Instruction * visitSDiv(BinaryOperator &I)
Instruction * commonIRemTransforms(BinaryOperator &I)
This function implements the transforms common to both integer remainder instructions (urem and srem)...
SimplifyQuery SQ
Definition: InstCombiner.h:76
TargetLibraryInfo & TLI
Definition: InstCombiner.h:73
bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero=false, unsigned Depth=0, const Instruction *CxtI=nullptr)
Definition: InstCombiner.h:440
Instruction * replaceInstUsesWith(Instruction &I, Value *V)
A combiner-aware RAUW-like routine.
Definition: InstCombiner.h:385
void replaceUse(Use &U, Value *NewValue)
Replace use and add the previously used value to the worklist.
Definition: InstCombiner.h:417
InstructionWorklist & Worklist
A worklist of the instructions that need to be simplified.
Definition: InstCombiner.h:64
const DataLayout & DL
Definition: InstCombiner.h:75
Instruction * replaceOperand(Instruction &I, unsigned OpNum, Value *V)
Replace operand of instruction and add old operand to the worklist.
Definition: InstCombiner.h:409
void computeKnownBits(const Value *V, KnownBits &Known, unsigned Depth, const Instruction *CxtI) const
Definition: InstCombiner.h:430
BuilderTy & Builder
Definition: InstCombiner.h:60
bool MaskedValueIsZero(const Value *V, const APInt &Mask, unsigned Depth=0, const Instruction *CxtI=nullptr) const
Definition: InstCombiner.h:446
void push(Instruction *I)
Push the instruction onto the worklist stack.
void setHasNoUnsignedWrap(bool b=true)
Set or clear the nuw flag on this instruction, which must be an operator which supports this flag.
bool hasNoUnsignedWrap() const LLVM_READONLY
Determine whether the no unsigned wrap flag is set.
bool hasNoSignedWrap() const LLVM_READONLY
Determine whether the no signed wrap flag is set.
void setHasNoSignedWrap(bool b=true)
Set or clear the nsw flag on this instruction, which must be an operator which supports this flag.
bool isExact() const LLVM_READONLY
Determine whether the exact flag is set.
FastMathFlags getFastMathFlags() const LLVM_READONLY
Convenience function for getting all the fast-math flags, which must be an operator which supports th...
void setIsExact(bool b=true)
Set or clear the exact flag on this instruction, which must be an operator which supports this flag.
A wrapper class for inspecting calls to intrinsic functions.
Definition: IntrinsicInst.h:47
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
static Value * Negate(bool LHSIsZero, bool IsNSW, Value *Root, InstCombinerImpl &IC)
Attempt to negate Root.
Utility class for integer operators which may exhibit overflow - Add, Sub, Mul, and Shl.
Definition: Operator.h:76
bool hasNoSignedWrap() const
Test whether this operation is known to never undergo signed overflow, aka the nsw property.
Definition: Operator.h:109
bool hasNoUnsignedWrap() const
Test whether this operation is known to never undergo unsigned overflow, aka the nuw property.
Definition: Operator.h:103
This class represents a sign extension of integer types.
This class represents the LLVM 'select' instruction.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr, BasicBlock::iterator InsertBefore, Instruction *MDFrom=nullptr)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition: Type.h:234
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
static UnaryOperator * CreateFNegFMF(Value *Op, Instruction *FMFSource, const Twine &Name, BasicBlock::iterator InsertBefore)
Definition: InstrTypes.h:191
A Use represents the edge between a Value definition and its users.
Definition: Use.h:43
Value * getOperand(unsigned i) const
Definition: User.h:169
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition: Value.h:434
bool hasNUses(unsigned N) const
Return true if this Value has exactly N uses.
Definition: Value.cpp:149
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
void takeName(Value *V)
Transfer the name from V to this value.
Definition: Value.cpp:383
This class represents zero extension of integer types.
An efficient, type-erasing, non-owning reference to a callable.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
cst_pred_ty< is_all_ones > m_AllOnes()
Match an integer or vector with all bits set.
Definition: PatternMatch.h:477
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
cst_pred_ty< is_negative > m_Negative()
Match an integer or vector of negative values.
Definition: PatternMatch.h:499
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
class_match< BinaryOperator > m_BinOp()
Match an arbitrary binary operation and ignore it.
Definition: PatternMatch.h:100
BinaryOp_match< LHS, RHS, Instruction::FMul, true > m_c_FMul(const LHS &L, const RHS &R)
Matches FMul with LHS and RHS in either order.
cst_pred_ty< is_sign_mask > m_SignMask()
Match an integer or vector with only the sign bit(s) set.
Definition: PatternMatch.h:613
BinaryOp_match< LHS, RHS, Instruction::AShr > m_AShr(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::FSub > m_FSub(const LHS &L, const RHS &R)
cst_pred_ty< is_power2 > m_Power2()
Match an integer or vector power-of-2.
Definition: PatternMatch.h:568
BinaryOp_match< LHS, RHS, Instruction::URem > m_URem(const LHS &L, const RHS &R)
class_match< Constant > m_Constant()
Match an arbitrary Constant and ignore it.
Definition: PatternMatch.h:160
AllowReassoc_match< T > m_AllowReassoc(const T &SubPattern)
Definition: PatternMatch.h:83
specific_intval< false > m_SpecificInt(const APInt &V)
Match a specific integer value or vector with all elements equal to the value.
Definition: PatternMatch.h:918
BinaryOp_match< LHS, RHS, Instruction::FMul > m_FMul(const LHS &L, const RHS &R)
bool match(Val *V, const Pattern &P)
Definition: PatternMatch.h:49
cstfp_pred_ty< is_any_zero_fp > m_AnyZeroFP()
Match a floating-point negative zero or positive zero.
Definition: PatternMatch.h:713
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
Definition: PatternMatch.h:821
specific_intval< true > m_SpecificIntAllowPoison(const APInt &V)
Definition: PatternMatch.h:926
OverflowingBinaryOp_match< cst_pred_ty< is_zero_int >, ValTy, Instruction::Sub, OverflowingBinaryOperator::NoSignedWrap > m_NSWNeg(const ValTy &V)
Matches a 'Neg' as 'sub nsw 0, V'.
cst_pred_ty< is_nonnegative > m_NonNegative()
Match an integer or vector of non-negative values.
Definition: PatternMatch.h:509
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
Definition: PatternMatch.h:541
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
specific_fpval m_SpecificFP(double V)
Match a specific floating point value or vector with all elements equal to the value.
Definition: PatternMatch.h:864
m_Intrinsic_Ty< Opnd0 >::Ty m_Sqrt(const Opnd0 &Op0)
BinaryOp_match< LHS, RHS, Instruction::FAdd > m_FAdd(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Mul > m_Mul(const LHS &L, const RHS &R)
deferredval_ty< Value > m_Deferred(Value *const &V)
Like m_Specific(), but works if the specific value to match is determined as part of the same match()...
Definition: PatternMatch.h:839
apint_match m_APIntAllowPoison(const APInt *&Res)
Match APInt while allowing poison in splat vector constants.
Definition: PatternMatch.h:300
OneUse_match< T > m_OneUse(const T &SubPattern)
Definition: PatternMatch.h:67
BinaryOp_match< cst_pred_ty< is_zero_int >, ValTy, Instruction::Sub > m_Neg(const ValTy &V)
Matches a 'Neg' as 'sub 0, V'.
match_combine_and< class_match< Constant >, match_unless< constantexpr_match > > m_ImmConstant()
Match an arbitrary immediate Constant and ignore it.
Definition: PatternMatch.h:800
OverflowingBinaryOp_match< LHS, RHS, Instruction::Shl, OverflowingBinaryOperator::NoSignedWrap > m_NSWShl(const LHS &L, const RHS &R)
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Shl, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWShl(const LHS &L, const RHS &R)
OverflowingBinaryOp_match< LHS, RHS, Instruction::Mul, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWMul(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::UDiv > m_UDiv(const LHS &L, const RHS &R)
cst_pred_ty< is_negated_power2 > m_NegatedPower2()
Match a integer or vector negated power-of-2.
Definition: PatternMatch.h:576
apfloat_match m_APFloatAllowPoison(const APFloat *&Res)
Match APFloat while allowing poison in splat vector constants.
Definition: PatternMatch.h:317
match_combine_or< BinaryOp_match< LHS, RHS, Instruction::Add >, DisjointOr_match< LHS, RHS > > m_AddLike(const LHS &L, const RHS &R)
Match either "add" or "or disjoint".
BinaryOp_match< LHS, RHS, Instruction::SDiv > m_SDiv(const LHS &L, const RHS &R)
apint_match m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
Definition: PatternMatch.h:294
match_combine_or< OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoSignedWrap >, DisjointOr_match< LHS, RHS > > m_NSWAddLike(const LHS &L, const RHS &R)
Match either "add nsw" or "or disjoint".
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
Definition: PatternMatch.h:92
AnyBinaryOp_match< LHS, RHS, true > m_c_BinOp(const LHS &L, const RHS &R)
Matches a BinaryOperator with LHS and RHS in either order.
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
match_combine_or< CastInst_match< OpTy, ZExtInst >, CastInst_match< OpTy, SExtInst > > m_ZExtOrSExt(const OpTy &Op)
Exact_match< T > m_Exact(const T &SubPattern)
FNeg_match< OpTy > m_FNeg(const OpTy &X)
Match 'fneg X' as 'fsub -0.0, X'.
cstfp_pred_ty< is_pos_zero_fp > m_PosZeroFP()
Match a floating-point positive zero.
Definition: PatternMatch.h:722
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::FDiv > m_FDiv(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::SRem > m_SRem(const LHS &L, const RHS &R)
BinaryOp_match< cst_pred_ty< is_all_ones >, ValTy, Instruction::Xor, true > m_Not(const ValTy &V)
Matches a 'Not' as 'xor V, -1' or 'xor -1, V'.
BinaryOp_match< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
CastInst_match< OpTy, SExtInst > m_SExt(const OpTy &Op)
Matches SExt.
is_zero m_Zero()
Match any null constant or a vector with all elements equal to 0.
Definition: PatternMatch.h:561
match_combine_or< OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap >, DisjointOr_match< LHS, RHS > > m_NUWAddLike(const LHS &L, const RHS &R)
Match either "add nuw" or "or disjoint".
m_Intrinsic_Ty< Opnd0 >::Ty m_FAbs(const Opnd0 &Op0)
BinaryOp_match< LHS, RHS, Instruction::Mul, true > m_c_Mul(const LHS &L, const RHS &R)
Matches a Mul with LHS and RHS in either order.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Mul, OverflowingBinaryOperator::NoSignedWrap > m_NSWMul(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
Value * emitUnaryFloatFnCall(Value *Op, const TargetLibraryInfo *TLI, StringRef Name, IRBuilderBase &B, const AttributeList &Attrs)
Emit a call to the unary function named 'Name' (e.g.
Value * simplifyFMulInst(Value *LHS, Value *RHS, FastMathFlags FMF, const SimplifyQuery &Q, fp::ExceptionBehavior ExBehavior=fp::ebIgnore, RoundingMode Rounding=RoundingMode::NearestTiesToEven)
Given operands for an FMul, fold the result or return null.
bool isKnownNegation(const Value *X, const Value *Y, bool NeedNSW=false)
Return true if the two given values are negation.
Value * simplifySDivInst(Value *LHS, Value *RHS, bool IsExact, const SimplifyQuery &Q)
Given operands for an SDiv, fold the result or return null.
Value * simplifyMulInst(Value *LHS, Value *RHS, bool IsNSW, bool IsNUW, const SimplifyQuery &Q)
Given operands for a Mul, fold the result or return null.
bool hasFloatFn(const Module *M, const TargetLibraryInfo *TLI, Type *Ty, LibFunc DoubleFn, LibFunc FloatFn, LibFunc LongDoubleFn)
Check whether the overloaded floating point function corresponding to Ty is available.
bool matchSimpleRecurrence(const PHINode *P, BinaryOperator *&BO, Value *&Start, Value *&Step)
Attempt to match a simple first order recurrence cycle of the form: iv = phi Ty [Start,...
Constant * ConstantFoldUnaryOpOperand(unsigned Opcode, Constant *Op, const DataLayout &DL)
Attempt to constant fold a unary operation with the specified operand.
Value * simplifyFRemInst(Value *LHS, Value *RHS, FastMathFlags FMF, const SimplifyQuery &Q, fp::ExceptionBehavior ExBehavior=fp::ebIgnore, RoundingMode Rounding=RoundingMode::NearestTiesToEven)
Given operands for an FRem, fold the result or return null.
Constant * ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS, Constant *RHS, const DataLayout &DL)
Attempt to constant fold a binary operation with the specified operands.
Value * simplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for an ICmpInst, fold the result or return null.
Value * simplifyFDivInst(Value *LHS, Value *RHS, FastMathFlags FMF, const SimplifyQuery &Q, fp::ExceptionBehavior ExBehavior=fp::ebIgnore, RoundingMode Rounding=RoundingMode::NearestTiesToEven)
Given operands for an FDiv, fold the result or return null.
@ Mul
Product of integers.
@ And
Bitwise or logical AND of integers.
@ Add
Sum of integers.
Value * simplifyUDivInst(Value *LHS, Value *RHS, bool IsExact, const SimplifyQuery &Q)
Given operands for a UDiv, fold the result or return null.
DWARFExpression::Operation Op
constexpr unsigned BitWidth
Definition: BitmaskEnum.h:191
bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I)
Return true if this function can prove that the instruction I will always transfer execution to one o...
Value * simplifySRemInst(Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for an SRem, fold the result or return null.
unsigned Log2(Align A)
Returns the log2 of the alignment.
Definition: Alignment.h:208
bool isKnownNeverNaN(const Value *V, unsigned Depth, const SimplifyQuery &SQ)
Return true if the floating-point scalar value is not a NaN or if the floating-point vector value has...
bool isKnownNonNegative(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the give value is known to be non-negative.
Value * simplifyURemInst(Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for a URem, fold the result or return null.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:860
#define N
bool isNonNegative() const
Returns true if this value is known to be non-negative.
Definition: KnownBits.h:104
unsigned countMinTrailingZeros() const
Returns the minimum number of trailing zero bits.
Definition: KnownBits.h:238
SimplifyQuery getWithInstruction(const Instruction *I) const
Definition: SimplifyQuery.h:96