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, "", false, 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, "", false, 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_APIntAllowUndef(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 // nabs(X) * nabs(X) -> X * X
323 if (Op0 == Op1) {
324 Value *X, *Y;
326 if (SPF == SPF_ABS || SPF == SPF_NABS)
327 return BinaryOperator::CreateMul(X, X);
328
329 if (match(Op0, m_Intrinsic<Intrinsic::abs>(m_Value(X))))
330 return BinaryOperator::CreateMul(X, X);
331 }
332
333 {
334 Value *X, *Y;
335 // abs(X) * abs(Y) -> abs(X * Y)
336 if (I.hasNoSignedWrap() &&
337 match(Op0,
338 m_OneUse(m_Intrinsic<Intrinsic::abs>(m_Value(X), m_One()))) &&
339 match(Op1, m_OneUse(m_Intrinsic<Intrinsic::abs>(m_Value(Y), m_One()))))
340 return replaceInstUsesWith(
341 I, Builder.CreateBinaryIntrinsic(Intrinsic::abs,
343 Builder.getTrue()));
344 }
345
346 // -X * C --> X * -C
347 Value *X, *Y;
348 Constant *Op1C;
349 if (match(Op0, m_Neg(m_Value(X))) && match(Op1, m_Constant(Op1C)))
350 return BinaryOperator::CreateMul(X, ConstantExpr::getNeg(Op1C));
351
352 // -X * -Y --> X * Y
353 if (match(Op0, m_Neg(m_Value(X))) && match(Op1, m_Neg(m_Value(Y)))) {
354 auto *NewMul = BinaryOperator::CreateMul(X, Y);
355 if (HasNSW && cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap() &&
356 cast<OverflowingBinaryOperator>(Op1)->hasNoSignedWrap())
357 NewMul->setHasNoSignedWrap();
358 return NewMul;
359 }
360
361 // -X * Y --> -(X * Y)
362 // X * -Y --> -(X * Y)
365
366 // (-X * Y) * -X --> (X * Y) * X
367 // (-X << Y) * -X --> (X << Y) * X
368 if (match(Op1, m_Neg(m_Value(X)))) {
369 if (Value *NegOp0 = Negator::Negate(false, /*IsNSW*/ false, Op0, *this))
370 return BinaryOperator::CreateMul(NegOp0, X);
371 }
372
373 // (X / Y) * Y = X - (X % Y)
374 // (X / Y) * -Y = (X % Y) - X
375 {
376 Value *Y = Op1;
377 BinaryOperator *Div = dyn_cast<BinaryOperator>(Op0);
378 if (!Div || (Div->getOpcode() != Instruction::UDiv &&
379 Div->getOpcode() != Instruction::SDiv)) {
380 Y = Op0;
381 Div = dyn_cast<BinaryOperator>(Op1);
382 }
383 Value *Neg = dyn_castNegVal(Y);
384 if (Div && Div->hasOneUse() &&
385 (Div->getOperand(1) == Y || Div->getOperand(1) == Neg) &&
386 (Div->getOpcode() == Instruction::UDiv ||
387 Div->getOpcode() == Instruction::SDiv)) {
388 Value *X = Div->getOperand(0), *DivOp1 = Div->getOperand(1);
389
390 // If the division is exact, X % Y is zero, so we end up with X or -X.
391 if (Div->isExact()) {
392 if (DivOp1 == Y)
393 return replaceInstUsesWith(I, X);
395 }
396
397 auto RemOpc = Div->getOpcode() == Instruction::UDiv ? Instruction::URem
398 : Instruction::SRem;
399 // X must be frozen because we are increasing its number of uses.
400 Value *XFreeze = Builder.CreateFreeze(X, X->getName() + ".fr");
401 Value *Rem = Builder.CreateBinOp(RemOpc, XFreeze, DivOp1);
402 if (DivOp1 == Y)
403 return BinaryOperator::CreateSub(XFreeze, Rem);
404 return BinaryOperator::CreateSub(Rem, XFreeze);
405 }
406 }
407
408 // Fold the following two scenarios:
409 // 1) i1 mul -> i1 and.
410 // 2) X * Y --> X & Y, iff X, Y can be only {0,1}.
411 // Note: We could use known bits to generalize this and related patterns with
412 // shifts/truncs
413 if (Ty->isIntOrIntVectorTy(1) ||
414 (match(Op0, m_And(m_Value(), m_One())) &&
415 match(Op1, m_And(m_Value(), m_One()))))
416 return BinaryOperator::CreateAnd(Op0, Op1);
417
418 if (Value *R = foldMulShl1(I, /* CommuteOperands */ false, Builder))
419 return replaceInstUsesWith(I, R);
420 if (Value *R = foldMulShl1(I, /* CommuteOperands */ true, Builder))
421 return replaceInstUsesWith(I, R);
422
423 // (zext bool X) * (zext bool Y) --> zext (and X, Y)
424 // (sext bool X) * (sext bool Y) --> zext (and X, Y)
425 // Note: -1 * -1 == 1 * 1 == 1 (if the extends match, the result is the same)
426 if (((match(Op0, m_ZExt(m_Value(X))) && match(Op1, m_ZExt(m_Value(Y)))) ||
427 (match(Op0, m_SExt(m_Value(X))) && match(Op1, m_SExt(m_Value(Y))))) &&
428 X->getType()->isIntOrIntVectorTy(1) && X->getType() == Y->getType() &&
429 (Op0->hasOneUse() || Op1->hasOneUse() || X == Y)) {
430 Value *And = Builder.CreateAnd(X, Y, "mulbool");
431 return CastInst::Create(Instruction::ZExt, And, Ty);
432 }
433 // (sext bool X) * (zext bool Y) --> sext (and X, Y)
434 // (zext bool X) * (sext bool Y) --> sext (and X, Y)
435 // Note: -1 * 1 == 1 * -1 == -1
436 if (((match(Op0, m_SExt(m_Value(X))) && match(Op1, m_ZExt(m_Value(Y)))) ||
437 (match(Op0, m_ZExt(m_Value(X))) && match(Op1, m_SExt(m_Value(Y))))) &&
438 X->getType()->isIntOrIntVectorTy(1) && X->getType() == Y->getType() &&
439 (Op0->hasOneUse() || Op1->hasOneUse())) {
440 Value *And = Builder.CreateAnd(X, Y, "mulbool");
441 return CastInst::Create(Instruction::SExt, And, Ty);
442 }
443
444 // (zext bool X) * Y --> X ? Y : 0
445 // Y * (zext bool X) --> X ? Y : 0
446 if (match(Op0, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
448 if (match(Op1, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
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 Value *Op0 = I.getOperand(0);
576 Value *Op1 = I.getOperand(1);
577 Value *X, *Y;
578 Constant *C;
579
580 // Reassociate constant RHS with another constant to form constant
581 // expression.
582 if (match(Op1, m_Constant(C)) && C->isFiniteNonZeroFP()) {
583 Constant *C1;
584 if (match(Op0, m_OneUse(m_FDiv(m_Constant(C1), m_Value(X))))) {
585 // (C1 / X) * C --> (C * C1) / X
586 Constant *CC1 =
587 ConstantFoldBinaryOpOperands(Instruction::FMul, C, C1, DL);
588 if (CC1 && CC1->isNormalFP())
589 return BinaryOperator::CreateFDivFMF(CC1, X, &I);
590 }
591 if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) {
592 // (X / C1) * C --> X * (C / C1)
593 Constant *CDivC1 =
594 ConstantFoldBinaryOpOperands(Instruction::FDiv, C, C1, DL);
595 if (CDivC1 && CDivC1->isNormalFP())
596 return BinaryOperator::CreateFMulFMF(X, CDivC1, &I);
597
598 // If the constant was a denormal, try reassociating differently.
599 // (X / C1) * C --> X / (C1 / C)
600 Constant *C1DivC =
601 ConstantFoldBinaryOpOperands(Instruction::FDiv, C1, C, DL);
602 if (C1DivC && Op0->hasOneUse() && C1DivC->isNormalFP())
603 return BinaryOperator::CreateFDivFMF(X, C1DivC, &I);
604 }
605
606 // We do not need to match 'fadd C, X' and 'fsub X, C' because they are
607 // canonicalized to 'fadd X, C'. Distributing the multiply may allow
608 // further folds and (X * C) + C2 is 'fma'.
609 if (match(Op0, m_OneUse(m_FAdd(m_Value(X), m_Constant(C1))))) {
610 // (X + C1) * C --> (X * C) + (C * C1)
611 if (Constant *CC1 =
612 ConstantFoldBinaryOpOperands(Instruction::FMul, C, C1, DL)) {
613 Value *XC = Builder.CreateFMulFMF(X, C, &I);
614 return BinaryOperator::CreateFAddFMF(XC, CC1, &I);
615 }
616 }
617 if (match(Op0, m_OneUse(m_FSub(m_Constant(C1), m_Value(X))))) {
618 // (C1 - X) * C --> (C * C1) - (X * C)
619 if (Constant *CC1 =
620 ConstantFoldBinaryOpOperands(Instruction::FMul, C, C1, DL)) {
621 Value *XC = Builder.CreateFMulFMF(X, C, &I);
622 return BinaryOperator::CreateFSubFMF(CC1, XC, &I);
623 }
624 }
625 }
626
627 Value *Z;
628 if (match(&I,
630 // Sink division: (X / Y) * Z --> (X * Z) / Y
631 Value *NewFMul = Builder.CreateFMulFMF(X, Z, &I);
632 return BinaryOperator::CreateFDivFMF(NewFMul, Y, &I);
633 }
634
635 // sqrt(X) * sqrt(Y) -> sqrt(X * Y)
636 // nnan disallows the possibility of returning a number if both operands are
637 // negative (in that case, we should return NaN).
638 if (I.hasNoNaNs() && match(Op0, m_OneUse(m_Sqrt(m_Value(X)))) &&
639 match(Op1, m_OneUse(m_Sqrt(m_Value(Y))))) {
640 Value *XY = Builder.CreateFMulFMF(X, Y, &I);
641 Value *Sqrt = Builder.CreateUnaryIntrinsic(Intrinsic::sqrt, XY, &I);
642 return replaceInstUsesWith(I, Sqrt);
643 }
644
645 // The following transforms are done irrespective of the number of uses
646 // for the expression "1.0/sqrt(X)".
647 // 1) 1.0/sqrt(X) * X -> X/sqrt(X)
648 // 2) X * 1.0/sqrt(X) -> X/sqrt(X)
649 // We always expect the backend to reduce X/sqrt(X) to sqrt(X), if it
650 // has the necessary (reassoc) fast-math-flags.
651 if (I.hasNoSignedZeros() &&
652 match(Op0, (m_FDiv(m_SpecificFP(1.0), m_Value(Y)))) &&
653 match(Y, m_Sqrt(m_Value(X))) && Op1 == X)
655 if (I.hasNoSignedZeros() &&
656 match(Op1, (m_FDiv(m_SpecificFP(1.0), m_Value(Y)))) &&
657 match(Y, m_Sqrt(m_Value(X))) && Op0 == X)
659
660 // Like the similar transform in instsimplify, this requires 'nsz' because
661 // sqrt(-0.0) = -0.0, and -0.0 * -0.0 does not simplify to -0.0.
662 if (I.hasNoNaNs() && I.hasNoSignedZeros() && Op0 == Op1 && Op0->hasNUses(2)) {
663 // Peek through fdiv to find squaring of square root:
664 // (X / sqrt(Y)) * (X / sqrt(Y)) --> (X * X) / Y
665 if (match(Op0, m_FDiv(m_Value(X), m_Sqrt(m_Value(Y))))) {
666 Value *XX = Builder.CreateFMulFMF(X, X, &I);
667 return BinaryOperator::CreateFDivFMF(XX, Y, &I);
668 }
669 // (sqrt(Y) / X) * (sqrt(Y) / X) --> Y / (X * X)
670 if (match(Op0, m_FDiv(m_Sqrt(m_Value(Y)), m_Value(X)))) {
671 Value *XX = Builder.CreateFMulFMF(X, X, &I);
672 return BinaryOperator::CreateFDivFMF(Y, XX, &I);
673 }
674 }
675
676 // pow(X, Y) * X --> pow(X, Y+1)
677 // X * pow(X, Y) --> pow(X, Y+1)
678 if (match(&I, m_c_FMul(m_OneUse(m_Intrinsic<Intrinsic::pow>(m_Value(X),
679 m_Value(Y))),
680 m_Deferred(X)))) {
681 Value *Y1 = Builder.CreateFAddFMF(Y, ConstantFP::get(I.getType(), 1.0), &I);
682 Value *Pow = Builder.CreateBinaryIntrinsic(Intrinsic::pow, X, Y1, &I);
683 return replaceInstUsesWith(I, Pow);
684 }
685
686 if (I.isOnlyUserOfAnyOperand()) {
687 // pow(X, Y) * pow(X, Z) -> pow(X, Y + Z)
688 if (match(Op0, m_Intrinsic<Intrinsic::pow>(m_Value(X), m_Value(Y))) &&
689 match(Op1, m_Intrinsic<Intrinsic::pow>(m_Specific(X), m_Value(Z)))) {
690 auto *YZ = Builder.CreateFAddFMF(Y, Z, &I);
691 auto *NewPow = Builder.CreateBinaryIntrinsic(Intrinsic::pow, X, YZ, &I);
692 return replaceInstUsesWith(I, NewPow);
693 }
694 // pow(X, Y) * pow(Z, Y) -> pow(X * Z, Y)
695 if (match(Op0, m_Intrinsic<Intrinsic::pow>(m_Value(X), m_Value(Y))) &&
696 match(Op1, m_Intrinsic<Intrinsic::pow>(m_Value(Z), m_Specific(Y)))) {
697 auto *XZ = Builder.CreateFMulFMF(X, Z, &I);
698 auto *NewPow = Builder.CreateBinaryIntrinsic(Intrinsic::pow, XZ, Y, &I);
699 return replaceInstUsesWith(I, NewPow);
700 }
701
702 // powi(x, y) * powi(x, z) -> powi(x, y + z)
703 if (match(Op0, m_Intrinsic<Intrinsic::powi>(m_Value(X), m_Value(Y))) &&
704 match(Op1, m_Intrinsic<Intrinsic::powi>(m_Specific(X), m_Value(Z))) &&
705 Y->getType() == Z->getType()) {
706 auto *YZ = Builder.CreateAdd(Y, Z);
707 auto *NewPow = Builder.CreateIntrinsic(
708 Intrinsic::powi, {X->getType(), YZ->getType()}, {X, YZ}, &I);
709 return replaceInstUsesWith(I, NewPow);
710 }
711
712 // exp(X) * exp(Y) -> exp(X + Y)
713 if (match(Op0, m_Intrinsic<Intrinsic::exp>(m_Value(X))) &&
714 match(Op1, m_Intrinsic<Intrinsic::exp>(m_Value(Y)))) {
715 Value *XY = Builder.CreateFAddFMF(X, Y, &I);
716 Value *Exp = Builder.CreateUnaryIntrinsic(Intrinsic::exp, XY, &I);
717 return replaceInstUsesWith(I, Exp);
718 }
719
720 // exp2(X) * exp2(Y) -> exp2(X + Y)
721 if (match(Op0, m_Intrinsic<Intrinsic::exp2>(m_Value(X))) &&
722 match(Op1, m_Intrinsic<Intrinsic::exp2>(m_Value(Y)))) {
723 Value *XY = Builder.CreateFAddFMF(X, Y, &I);
724 Value *Exp2 = Builder.CreateUnaryIntrinsic(Intrinsic::exp2, XY, &I);
725 return replaceInstUsesWith(I, Exp2);
726 }
727 }
728
729 // (X*Y) * X => (X*X) * Y where Y != X
730 // The purpose is two-fold:
731 // 1) to form a power expression (of X).
732 // 2) potentially shorten the critical path: After transformation, the
733 // latency of the instruction Y is amortized by the expression of X*X,
734 // and therefore Y is in a "less critical" position compared to what it
735 // was before the transformation.
736 if (match(Op0, m_OneUse(m_c_FMul(m_Specific(Op1), m_Value(Y)))) && Op1 != Y) {
737 Value *XX = Builder.CreateFMulFMF(Op1, Op1, &I);
738 return BinaryOperator::CreateFMulFMF(XX, Y, &I);
739 }
740 if (match(Op1, m_OneUse(m_c_FMul(m_Specific(Op0), m_Value(Y)))) && Op0 != Y) {
741 Value *XX = Builder.CreateFMulFMF(Op0, Op0, &I);
742 return BinaryOperator::CreateFMulFMF(XX, Y, &I);
743 }
744
745 return nullptr;
746}
747
749 if (Value *V = simplifyFMulInst(I.getOperand(0), I.getOperand(1),
750 I.getFastMathFlags(),
752 return replaceInstUsesWith(I, V);
753
755 return &I;
756
758 return X;
759
761 return Phi;
762
763 if (Instruction *FoldedMul = foldBinOpIntoSelectOrPhi(I))
764 return FoldedMul;
765
766 if (Value *FoldedMul = foldMulSelectToNegate(I, Builder))
767 return replaceInstUsesWith(I, FoldedMul);
768
769 if (Instruction *R = foldFPSignBitOps(I))
770 return R;
771
772 // X * -1.0 --> -X
773 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
774 if (match(Op1, m_SpecificFP(-1.0)))
775 return UnaryOperator::CreateFNegFMF(Op0, &I);
776
777 // With no-nans: X * 0.0 --> copysign(0.0, X)
778 if (I.hasNoNaNs() && match(Op1, m_PosZeroFP())) {
779 CallInst *CopySign = Builder.CreateIntrinsic(Intrinsic::copysign,
780 {I.getType()}, {Op1, Op0}, &I);
781 return replaceInstUsesWith(I, CopySign);
782 }
783
784 // -X * C --> X * -C
785 Value *X, *Y;
786 Constant *C;
787 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_Constant(C)))
788 if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL))
789 return BinaryOperator::CreateFMulFMF(X, NegC, &I);
790
791 // (select A, B, C) * (select A, D, E) --> select A, (B*D), (C*E)
792 if (Value *V = SimplifySelectsFeedingBinaryOp(I, Op0, Op1))
793 return replaceInstUsesWith(I, V);
794
795 if (I.hasAllowReassoc())
796 if (Instruction *FoldedMul = foldFMulReassoc(I))
797 return FoldedMul;
798
799 // log2(X * 0.5) * Y = log2(X) * Y - Y
800 if (I.isFast()) {
801 IntrinsicInst *Log2 = nullptr;
802 if (match(Op0, m_OneUse(m_Intrinsic<Intrinsic::log2>(
803 m_OneUse(m_FMul(m_Value(X), m_SpecificFP(0.5))))))) {
804 Log2 = cast<IntrinsicInst>(Op0);
805 Y = Op1;
806 }
807 if (match(Op1, m_OneUse(m_Intrinsic<Intrinsic::log2>(
808 m_OneUse(m_FMul(m_Value(X), m_SpecificFP(0.5))))))) {
809 Log2 = cast<IntrinsicInst>(Op1);
810 Y = Op0;
811 }
812 if (Log2) {
813 Value *Log2 = Builder.CreateUnaryIntrinsic(Intrinsic::log2, X, &I);
814 Value *LogXTimesY = Builder.CreateFMulFMF(Log2, Y, &I);
815 return BinaryOperator::CreateFSubFMF(LogXTimesY, Y, &I);
816 }
817 }
818
819 // Simplify FMUL recurrences starting with 0.0 to 0.0 if nnan and nsz are set.
820 // Given a phi node with entry value as 0 and it used in fmul operation,
821 // we can replace fmul with 0 safely and eleminate loop operation.
822 PHINode *PN = nullptr;
823 Value *Start = nullptr, *Step = nullptr;
824 if (matchSimpleRecurrence(&I, PN, Start, Step) && I.hasNoNaNs() &&
825 I.hasNoSignedZeros() && match(Start, m_Zero()))
826 return replaceInstUsesWith(I, Start);
827
828 // minimum(X, Y) * maximum(X, Y) => X * Y.
829 if (match(&I,
830 m_c_FMul(m_Intrinsic<Intrinsic::maximum>(m_Value(X), m_Value(Y)),
831 m_c_Intrinsic<Intrinsic::minimum>(m_Deferred(X),
832 m_Deferred(Y))))) {
834 // We cannot preserve ninf if nnan flag is not set.
835 // If X is NaN and Y is Inf then in original program we had NaN * NaN,
836 // while in optimized version NaN * Inf and this is a poison with ninf flag.
837 if (!Result->hasNoNaNs())
838 Result->setHasNoInfs(false);
839 return Result;
840 }
841
842 return nullptr;
843}
844
845/// Fold a divide or remainder with a select instruction divisor when one of the
846/// select operands is zero. In that case, we can use the other select operand
847/// because div/rem by zero is undefined.
849 SelectInst *SI = dyn_cast<SelectInst>(I.getOperand(1));
850 if (!SI)
851 return false;
852
853 int NonNullOperand;
854 if (match(SI->getTrueValue(), m_Zero()))
855 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
856 NonNullOperand = 2;
857 else if (match(SI->getFalseValue(), m_Zero()))
858 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
859 NonNullOperand = 1;
860 else
861 return false;
862
863 // Change the div/rem to use 'Y' instead of the select.
864 replaceOperand(I, 1, SI->getOperand(NonNullOperand));
865
866 // Okay, we know we replace the operand of the div/rem with 'Y' with no
867 // problem. However, the select, or the condition of the select may have
868 // multiple uses. Based on our knowledge that the operand must be non-zero,
869 // propagate the known value for the select into other uses of it, and
870 // propagate a known value of the condition into its other users.
871
872 // If the select and condition only have a single use, don't bother with this,
873 // early exit.
874 Value *SelectCond = SI->getCondition();
875 if (SI->use_empty() && SelectCond->hasOneUse())
876 return true;
877
878 // Scan the current block backward, looking for other uses of SI.
879 BasicBlock::iterator BBI = I.getIterator(), BBFront = I.getParent()->begin();
880 Type *CondTy = SelectCond->getType();
881 while (BBI != BBFront) {
882 --BBI;
883 // If we found an instruction that we can't assume will return, so
884 // information from below it cannot be propagated above it.
886 break;
887
888 // Replace uses of the select or its condition with the known values.
889 for (Use &Op : BBI->operands()) {
890 if (Op == SI) {
891 replaceUse(Op, SI->getOperand(NonNullOperand));
892 Worklist.push(&*BBI);
893 } else if (Op == SelectCond) {
894 replaceUse(Op, NonNullOperand == 1 ? ConstantInt::getTrue(CondTy)
895 : ConstantInt::getFalse(CondTy));
896 Worklist.push(&*BBI);
897 }
898 }
899
900 // If we past the instruction, quit looking for it.
901 if (&*BBI == SI)
902 SI = nullptr;
903 if (&*BBI == SelectCond)
904 SelectCond = nullptr;
905
906 // If we ran out of things to eliminate, break out of the loop.
907 if (!SelectCond && !SI)
908 break;
909
910 }
911 return true;
912}
913
914/// True if the multiply can not be expressed in an int this size.
915static bool multiplyOverflows(const APInt &C1, const APInt &C2, APInt &Product,
916 bool IsSigned) {
917 bool Overflow;
918 Product = IsSigned ? C1.smul_ov(C2, Overflow) : C1.umul_ov(C2, Overflow);
919 return Overflow;
920}
921
922/// True if C1 is a multiple of C2. Quotient contains C1/C2.
923static bool isMultiple(const APInt &C1, const APInt &C2, APInt &Quotient,
924 bool IsSigned) {
925 assert(C1.getBitWidth() == C2.getBitWidth() && "Constant widths not equal");
926
927 // Bail if we will divide by zero.
928 if (C2.isZero())
929 return false;
930
931 // Bail if we would divide INT_MIN by -1.
932 if (IsSigned && C1.isMinSignedValue() && C2.isAllOnes())
933 return false;
934
935 APInt Remainder(C1.getBitWidth(), /*val=*/0ULL, IsSigned);
936 if (IsSigned)
937 APInt::sdivrem(C1, C2, Quotient, Remainder);
938 else
939 APInt::udivrem(C1, C2, Quotient, Remainder);
940
941 return Remainder.isMinValue();
942}
943
945 assert((I.getOpcode() == Instruction::SDiv ||
946 I.getOpcode() == Instruction::UDiv) &&
947 "Expected integer divide");
948
949 bool IsSigned = I.getOpcode() == Instruction::SDiv;
950 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
951 Type *Ty = I.getType();
952
953 Value *X, *Y, *Z;
954
955 // With appropriate no-wrap constraints, remove a common factor in the
956 // dividend and divisor that is disguised as a left-shifted value.
957 if (match(Op1, m_Shl(m_Value(X), m_Value(Z))) &&
958 match(Op0, m_c_Mul(m_Specific(X), m_Value(Y)))) {
959 // Both operands must have the matching no-wrap for this kind of division.
960 auto *Mul = cast<OverflowingBinaryOperator>(Op0);
961 auto *Shl = cast<OverflowingBinaryOperator>(Op1);
962 bool HasNUW = Mul->hasNoUnsignedWrap() && Shl->hasNoUnsignedWrap();
963 bool HasNSW = Mul->hasNoSignedWrap() && Shl->hasNoSignedWrap();
964
965 // (X * Y) u/ (X << Z) --> Y u>> Z
966 if (!IsSigned && HasNUW)
967 return Builder.CreateLShr(Y, Z, "", I.isExact());
968
969 // (X * Y) s/ (X << Z) --> Y s/ (1 << Z)
970 if (IsSigned && HasNSW && (Op0->hasOneUse() || Op1->hasOneUse())) {
971 Value *Shl = Builder.CreateShl(ConstantInt::get(Ty, 1), Z);
972 return Builder.CreateSDiv(Y, Shl, "", I.isExact());
973 }
974 }
975
976 // With appropriate no-wrap constraints, remove a common factor in the
977 // dividend and divisor that is disguised as a left-shift amount.
978 if (match(Op0, m_Shl(m_Value(X), m_Value(Z))) &&
979 match(Op1, m_Shl(m_Value(Y), m_Specific(Z)))) {
980 auto *Shl0 = cast<OverflowingBinaryOperator>(Op0);
981 auto *Shl1 = cast<OverflowingBinaryOperator>(Op1);
982
983 // For unsigned div, we need 'nuw' on both shifts or
984 // 'nsw' on both shifts + 'nuw' on the dividend.
985 // (X << Z) / (Y << Z) --> X / Y
986 if (!IsSigned &&
987 ((Shl0->hasNoUnsignedWrap() && Shl1->hasNoUnsignedWrap()) ||
988 (Shl0->hasNoUnsignedWrap() && Shl0->hasNoSignedWrap() &&
989 Shl1->hasNoSignedWrap())))
990 return Builder.CreateUDiv(X, Y, "", I.isExact());
991
992 // For signed div, we need 'nsw' on both shifts + 'nuw' on the divisor.
993 // (X << Z) / (Y << Z) --> X / Y
994 if (IsSigned && Shl0->hasNoSignedWrap() && Shl1->hasNoSignedWrap() &&
995 Shl1->hasNoUnsignedWrap())
996 return Builder.CreateSDiv(X, Y, "", I.isExact());
997 }
998
999 // If X << Y and X << Z does not overflow, then:
1000 // (X << Y) / (X << Z) -> (1 << Y) / (1 << Z) -> 1 << Y >> Z
1001 if (match(Op0, m_Shl(m_Value(X), m_Value(Y))) &&
1002 match(Op1, m_Shl(m_Specific(X), m_Value(Z)))) {
1003 auto *Shl0 = cast<OverflowingBinaryOperator>(Op0);
1004 auto *Shl1 = cast<OverflowingBinaryOperator>(Op1);
1005
1006 if (IsSigned ? (Shl0->hasNoSignedWrap() && Shl1->hasNoSignedWrap())
1007 : (Shl0->hasNoUnsignedWrap() && Shl1->hasNoUnsignedWrap())) {
1008 Constant *One = ConstantInt::get(X->getType(), 1);
1009 // Only preserve the nsw flag if dividend has nsw
1010 // or divisor has nsw and operator is sdiv.
1011 Value *Dividend = Builder.CreateShl(
1012 One, Y, "shl.dividend",
1013 /*HasNUW*/ true,
1014 /*HasNSW*/
1015 IsSigned ? (Shl0->hasNoUnsignedWrap() || Shl1->hasNoUnsignedWrap())
1016 : Shl0->hasNoSignedWrap());
1017 return Builder.CreateLShr(Dividend, Z, "", I.isExact());
1018 }
1019 }
1020
1021 return nullptr;
1022}
1023
1024/// This function implements the transforms common to both integer division
1025/// instructions (udiv and sdiv). It is called by the visitors to those integer
1026/// division instructions.
1027/// Common integer divide transforms
1030 return Phi;
1031
1032 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1033 bool IsSigned = I.getOpcode() == Instruction::SDiv;
1034 Type *Ty = I.getType();
1035
1036 // The RHS is known non-zero.
1037 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I))
1038 return replaceOperand(I, 1, V);
1039
1040 // Handle cases involving: [su]div X, (select Cond, Y, Z)
1041 // This does not apply for fdiv.
1043 return &I;
1044
1045 // If the divisor is a select-of-constants, try to constant fold all div ops:
1046 // C / (select Cond, TrueC, FalseC) --> select Cond, (C / TrueC), (C / FalseC)
1047 // TODO: Adapt simplifyDivRemOfSelectWithZeroOp to allow this and other folds.
1048 if (match(Op0, m_ImmConstant()) &&
1050 if (Instruction *R = FoldOpIntoSelect(I, cast<SelectInst>(Op1),
1051 /*FoldWithMultiUse*/ true))
1052 return R;
1053 }
1054
1055 const APInt *C2;
1056 if (match(Op1, m_APInt(C2))) {
1057 Value *X;
1058 const APInt *C1;
1059
1060 // (X / C1) / C2 -> X / (C1*C2)
1061 if ((IsSigned && match(Op0, m_SDiv(m_Value(X), m_APInt(C1)))) ||
1062 (!IsSigned && match(Op0, m_UDiv(m_Value(X), m_APInt(C1))))) {
1063 APInt Product(C1->getBitWidth(), /*val=*/0ULL, IsSigned);
1064 if (!multiplyOverflows(*C1, *C2, Product, IsSigned))
1065 return BinaryOperator::Create(I.getOpcode(), X,
1066 ConstantInt::get(Ty, Product));
1067 }
1068
1069 APInt Quotient(C2->getBitWidth(), /*val=*/0ULL, IsSigned);
1070 if ((IsSigned && match(Op0, m_NSWMul(m_Value(X), m_APInt(C1)))) ||
1071 (!IsSigned && match(Op0, m_NUWMul(m_Value(X), m_APInt(C1))))) {
1072
1073 // (X * C1) / C2 -> X / (C2 / C1) if C2 is a multiple of C1.
1074 if (isMultiple(*C2, *C1, Quotient, IsSigned)) {
1075 auto *NewDiv = BinaryOperator::Create(I.getOpcode(), X,
1076 ConstantInt::get(Ty, Quotient));
1077 NewDiv->setIsExact(I.isExact());
1078 return NewDiv;
1079 }
1080
1081 // (X * C1) / C2 -> X * (C1 / C2) if C1 is a multiple of C2.
1082 if (isMultiple(*C1, *C2, Quotient, IsSigned)) {
1083 auto *Mul = BinaryOperator::Create(Instruction::Mul, X,
1084 ConstantInt::get(Ty, Quotient));
1085 auto *OBO = cast<OverflowingBinaryOperator>(Op0);
1086 Mul->setHasNoUnsignedWrap(!IsSigned && OBO->hasNoUnsignedWrap());
1087 Mul->setHasNoSignedWrap(OBO->hasNoSignedWrap());
1088 return Mul;
1089 }
1090 }
1091
1092 if ((IsSigned && match(Op0, m_NSWShl(m_Value(X), m_APInt(C1))) &&
1093 C1->ult(C1->getBitWidth() - 1)) ||
1094 (!IsSigned && match(Op0, m_NUWShl(m_Value(X), m_APInt(C1))) &&
1095 C1->ult(C1->getBitWidth()))) {
1096 APInt C1Shifted = APInt::getOneBitSet(
1097 C1->getBitWidth(), static_cast<unsigned>(C1->getZExtValue()));
1098
1099 // (X << C1) / C2 -> X / (C2 >> C1) if C2 is a multiple of 1 << C1.
1100 if (isMultiple(*C2, C1Shifted, Quotient, IsSigned)) {
1101 auto *BO = BinaryOperator::Create(I.getOpcode(), X,
1102 ConstantInt::get(Ty, Quotient));
1103 BO->setIsExact(I.isExact());
1104 return BO;
1105 }
1106
1107 // (X << C1) / C2 -> X * ((1 << C1) / C2) if 1 << C1 is a multiple of C2.
1108 if (isMultiple(C1Shifted, *C2, Quotient, IsSigned)) {
1109 auto *Mul = BinaryOperator::Create(Instruction::Mul, X,
1110 ConstantInt::get(Ty, Quotient));
1111 auto *OBO = cast<OverflowingBinaryOperator>(Op0);
1112 Mul->setHasNoUnsignedWrap(!IsSigned && OBO->hasNoUnsignedWrap());
1113 Mul->setHasNoSignedWrap(OBO->hasNoSignedWrap());
1114 return Mul;
1115 }
1116 }
1117
1118 // Distribute div over add to eliminate a matching div/mul pair:
1119 // ((X * C2) + C1) / C2 --> X + C1/C2
1120 // We need a multiple of the divisor for a signed add constant, but
1121 // unsigned is fine with any constant pair.
1122 if (IsSigned &&
1124 m_APInt(C1))) &&
1125 isMultiple(*C1, *C2, Quotient, IsSigned)) {
1126 return BinaryOperator::CreateNSWAdd(X, ConstantInt::get(Ty, Quotient));
1127 }
1128 if (!IsSigned &&
1130 m_APInt(C1)))) {
1131 return BinaryOperator::CreateNUWAdd(X,
1132 ConstantInt::get(Ty, C1->udiv(*C2)));
1133 }
1134
1135 if (!C2->isZero()) // avoid X udiv 0
1136 if (Instruction *FoldedDiv = foldBinOpIntoSelectOrPhi(I))
1137 return FoldedDiv;
1138 }
1139
1140 if (match(Op0, m_One())) {
1141 assert(!Ty->isIntOrIntVectorTy(1) && "i1 divide not removed?");
1142 if (IsSigned) {
1143 // 1 / 0 --> undef ; 1 / 1 --> 1 ; 1 / -1 --> -1 ; 1 / anything else --> 0
1144 // (Op1 + 1) u< 3 ? Op1 : 0
1145 // Op1 must be frozen because we are increasing its number of uses.
1146 Value *F1 = Builder.CreateFreeze(Op1, Op1->getName() + ".fr");
1147 Value *Inc = Builder.CreateAdd(F1, Op0);
1148 Value *Cmp = Builder.CreateICmpULT(Inc, ConstantInt::get(Ty, 3));
1149 return SelectInst::Create(Cmp, F1, ConstantInt::get(Ty, 0));
1150 } else {
1151 // If Op1 is 0 then it's undefined behaviour. If Op1 is 1 then the
1152 // result is one, otherwise it's zero.
1153 return new ZExtInst(Builder.CreateICmpEQ(Op1, Op0), Ty);
1154 }
1155 }
1156
1157 // See if we can fold away this div instruction.
1159 return &I;
1160
1161 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
1162 Value *X, *Z;
1163 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) // (X - Z) / Y; Y = Op1
1164 if ((IsSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
1165 (!IsSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
1166 return BinaryOperator::Create(I.getOpcode(), X, Op1);
1167
1168 // (X << Y) / X -> 1 << Y
1169 Value *Y;
1170 if (IsSigned && match(Op0, m_NSWShl(m_Specific(Op1), m_Value(Y))))
1171 return BinaryOperator::CreateNSWShl(ConstantInt::get(Ty, 1), Y);
1172 if (!IsSigned && match(Op0, m_NUWShl(m_Specific(Op1), m_Value(Y))))
1173 return BinaryOperator::CreateNUWShl(ConstantInt::get(Ty, 1), Y);
1174
1175 // X / (X * Y) -> 1 / Y if the multiplication does not overflow.
1176 if (match(Op1, m_c_Mul(m_Specific(Op0), m_Value(Y)))) {
1177 bool HasNSW = cast<OverflowingBinaryOperator>(Op1)->hasNoSignedWrap();
1178 bool HasNUW = cast<OverflowingBinaryOperator>(Op1)->hasNoUnsignedWrap();
1179 if ((IsSigned && HasNSW) || (!IsSigned && HasNUW)) {
1180 replaceOperand(I, 0, ConstantInt::get(Ty, 1));
1181 replaceOperand(I, 1, Y);
1182 return &I;
1183 }
1184 }
1185
1186 // (X << Z) / (X * Y) -> (1 << Z) / Y
1187 // TODO: Handle sdiv.
1188 if (!IsSigned && Op1->hasOneUse() &&
1189 match(Op0, m_NUWShl(m_Value(X), m_Value(Z))) &&
1190 match(Op1, m_c_Mul(m_Specific(X), m_Value(Y))))
1191 if (cast<OverflowingBinaryOperator>(Op1)->hasNoUnsignedWrap()) {
1192 Instruction *NewDiv = BinaryOperator::CreateUDiv(
1193 Builder.CreateShl(ConstantInt::get(Ty, 1), Z, "", /*NUW*/ true), Y);
1194 NewDiv->setIsExact(I.isExact());
1195 return NewDiv;
1196 }
1197
1198 if (Value *R = foldIDivShl(I, Builder))
1199 return replaceInstUsesWith(I, R);
1200
1201 // With the appropriate no-wrap constraint, remove a multiply by the divisor
1202 // after peeking through another divide:
1203 // ((Op1 * X) / Y) / Op1 --> X / Y
1204 if (match(Op0, m_BinOp(I.getOpcode(), m_c_Mul(m_Specific(Op1), m_Value(X)),
1205 m_Value(Y)))) {
1206 auto *InnerDiv = cast<PossiblyExactOperator>(Op0);
1207 auto *Mul = cast<OverflowingBinaryOperator>(InnerDiv->getOperand(0));
1208 Instruction *NewDiv = nullptr;
1209 if (!IsSigned && Mul->hasNoUnsignedWrap())
1210 NewDiv = BinaryOperator::CreateUDiv(X, Y);
1211 else if (IsSigned && Mul->hasNoSignedWrap())
1212 NewDiv = BinaryOperator::CreateSDiv(X, Y);
1213
1214 // Exact propagates only if both of the original divides are exact.
1215 if (NewDiv) {
1216 NewDiv->setIsExact(I.isExact() && InnerDiv->isExact());
1217 return NewDiv;
1218 }
1219 }
1220
1221 // (X * Y) / (X * Z) --> Y / Z (and commuted variants)
1222 if (match(Op0, m_Mul(m_Value(X), m_Value(Y)))) {
1223 auto OB0HasNSW = cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap();
1224 auto OB0HasNUW = cast<OverflowingBinaryOperator>(Op0)->hasNoUnsignedWrap();
1225
1226 auto CreateDivOrNull = [&](Value *A, Value *B) -> Instruction * {
1227 auto OB1HasNSW = cast<OverflowingBinaryOperator>(Op1)->hasNoSignedWrap();
1228 auto OB1HasNUW =
1229 cast<OverflowingBinaryOperator>(Op1)->hasNoUnsignedWrap();
1230 const APInt *C1, *C2;
1231 if (IsSigned && OB0HasNSW) {
1232 if (OB1HasNSW && match(B, m_APInt(C1)) && !C1->isAllOnes())
1233 return BinaryOperator::CreateSDiv(A, B);
1234 }
1235 if (!IsSigned && OB0HasNUW) {
1236 if (OB1HasNUW)
1237 return BinaryOperator::CreateUDiv(A, B);
1238 if (match(A, m_APInt(C1)) && match(B, m_APInt(C2)) && C2->ule(*C1))
1239 return BinaryOperator::CreateUDiv(A, B);
1240 }
1241 return nullptr;
1242 };
1243
1244 if (match(Op1, m_c_Mul(m_Specific(X), m_Value(Z)))) {
1245 if (auto *Val = CreateDivOrNull(Y, Z))
1246 return Val;
1247 }
1248 if (match(Op1, m_c_Mul(m_Specific(Y), m_Value(Z)))) {
1249 if (auto *Val = CreateDivOrNull(X, Z))
1250 return Val;
1251 }
1252 }
1253 return nullptr;
1254}
1255
1256static const unsigned MaxDepth = 6;
1257
1258// Take the exact integer log2 of the value. If DoFold is true, create the
1259// actual instructions, otherwise return a non-null dummy value. Return nullptr
1260// on failure.
1261static Value *takeLog2(IRBuilderBase &Builder, Value *Op, unsigned Depth,
1262 bool AssumeNonZero, bool DoFold) {
1263 auto IfFold = [DoFold](function_ref<Value *()> Fn) {
1264 if (!DoFold)
1265 return reinterpret_cast<Value *>(-1);
1266 return Fn();
1267 };
1268
1269 // FIXME: assert that Op1 isn't/doesn't contain undef.
1270
1271 // log2(2^C) -> C
1272 if (match(Op, m_Power2()))
1273 return IfFold([&]() {
1274 Constant *C = ConstantExpr::getExactLogBase2(cast<Constant>(Op));
1275 if (!C)
1276 llvm_unreachable("Failed to constant fold udiv -> logbase2");
1277 return C;
1278 });
1279
1280 // The remaining tests are all recursive, so bail out if we hit the limit.
1281 if (Depth++ == MaxDepth)
1282 return nullptr;
1283
1284 // log2(zext X) -> zext log2(X)
1285 // FIXME: Require one use?
1286 Value *X, *Y;
1287 if (match(Op, m_ZExt(m_Value(X))))
1288 if (Value *LogX = takeLog2(Builder, X, Depth, AssumeNonZero, DoFold))
1289 return IfFold([&]() { return Builder.CreateZExt(LogX, Op->getType()); });
1290
1291 // log2(X << Y) -> log2(X) + Y
1292 // FIXME: Require one use unless X is 1?
1293 if (match(Op, m_Shl(m_Value(X), m_Value(Y)))) {
1294 auto *BO = cast<OverflowingBinaryOperator>(Op);
1295 // nuw will be set if the `shl` is trivially non-zero.
1296 if (AssumeNonZero || BO->hasNoUnsignedWrap() || BO->hasNoSignedWrap())
1297 if (Value *LogX = takeLog2(Builder, X, Depth, AssumeNonZero, DoFold))
1298 return IfFold([&]() { return Builder.CreateAdd(LogX, Y); });
1299 }
1300
1301 // log2(Cond ? X : Y) -> Cond ? log2(X) : log2(Y)
1302 // FIXME: Require one use?
1303 if (SelectInst *SI = dyn_cast<SelectInst>(Op))
1304 if (Value *LogX = takeLog2(Builder, SI->getOperand(1), Depth,
1305 AssumeNonZero, DoFold))
1306 if (Value *LogY = takeLog2(Builder, SI->getOperand(2), Depth,
1307 AssumeNonZero, DoFold))
1308 return IfFold([&]() {
1309 return Builder.CreateSelect(SI->getOperand(0), LogX, LogY);
1310 });
1311
1312 // log2(umin(X, Y)) -> umin(log2(X), log2(Y))
1313 // log2(umax(X, Y)) -> umax(log2(X), log2(Y))
1314 auto *MinMax = dyn_cast<MinMaxIntrinsic>(Op);
1315 if (MinMax && MinMax->hasOneUse() && !MinMax->isSigned()) {
1316 // Use AssumeNonZero as false here. Otherwise we can hit case where
1317 // log2(umax(X, Y)) != umax(log2(X), log2(Y)) (because overflow).
1318 if (Value *LogX = takeLog2(Builder, MinMax->getLHS(), Depth,
1319 /*AssumeNonZero*/ false, DoFold))
1320 if (Value *LogY = takeLog2(Builder, MinMax->getRHS(), Depth,
1321 /*AssumeNonZero*/ false, DoFold))
1322 return IfFold([&]() {
1323 return Builder.CreateBinaryIntrinsic(MinMax->getIntrinsicID(), LogX,
1324 LogY);
1325 });
1326 }
1327
1328 return nullptr;
1329}
1330
1331/// If we have zero-extended operands of an unsigned div or rem, we may be able
1332/// to narrow the operation (sink the zext below the math).
1334 InstCombinerImpl &IC) {
1335 Instruction::BinaryOps Opcode = I.getOpcode();
1336 Value *N = I.getOperand(0);
1337 Value *D = I.getOperand(1);
1338 Type *Ty = I.getType();
1339 Value *X, *Y;
1340 if (match(N, m_ZExt(m_Value(X))) && match(D, m_ZExt(m_Value(Y))) &&
1341 X->getType() == Y->getType() && (N->hasOneUse() || D->hasOneUse())) {
1342 // udiv (zext X), (zext Y) --> zext (udiv X, Y)
1343 // urem (zext X), (zext Y) --> zext (urem X, Y)
1344 Value *NarrowOp = IC.Builder.CreateBinOp(Opcode, X, Y);
1345 return new ZExtInst(NarrowOp, Ty);
1346 }
1347
1348 Constant *C;
1349 if (isa<Instruction>(N) && match(N, m_OneUse(m_ZExt(m_Value(X)))) &&
1350 match(D, m_Constant(C))) {
1351 // If the constant is the same in the smaller type, use the narrow version.
1352 Constant *TruncC = IC.getLosslessUnsignedTrunc(C, X->getType());
1353 if (!TruncC)
1354 return nullptr;
1355
1356 // udiv (zext X), C --> zext (udiv X, C')
1357 // urem (zext X), C --> zext (urem X, C')
1358 return new ZExtInst(IC.Builder.CreateBinOp(Opcode, X, TruncC), Ty);
1359 }
1360 if (isa<Instruction>(D) && match(D, m_OneUse(m_ZExt(m_Value(X)))) &&
1361 match(N, m_Constant(C))) {
1362 // If the constant is the same in the smaller type, use the narrow version.
1363 Constant *TruncC = IC.getLosslessUnsignedTrunc(C, X->getType());
1364 if (!TruncC)
1365 return nullptr;
1366
1367 // udiv C, (zext X) --> zext (udiv C', X)
1368 // urem C, (zext X) --> zext (urem C', X)
1369 return new ZExtInst(IC.Builder.CreateBinOp(Opcode, TruncC, X), Ty);
1370 }
1371
1372 return nullptr;
1373}
1374
1376 if (Value *V = simplifyUDivInst(I.getOperand(0), I.getOperand(1), I.isExact(),
1378 return replaceInstUsesWith(I, V);
1379
1381 return X;
1382
1383 // Handle the integer div common cases
1384 if (Instruction *Common = commonIDivTransforms(I))
1385 return Common;
1386
1387 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1388 Value *X;
1389 const APInt *C1, *C2;
1390 if (match(Op0, m_LShr(m_Value(X), m_APInt(C1))) && match(Op1, m_APInt(C2))) {
1391 // (X lshr C1) udiv C2 --> X udiv (C2 << C1)
1392 bool Overflow;
1393 APInt C2ShlC1 = C2->ushl_ov(*C1, Overflow);
1394 if (!Overflow) {
1395 bool IsExact = I.isExact() && match(Op0, m_Exact(m_Value()));
1396 BinaryOperator *BO = BinaryOperator::CreateUDiv(
1397 X, ConstantInt::get(X->getType(), C2ShlC1));
1398 if (IsExact)
1399 BO->setIsExact();
1400 return BO;
1401 }
1402 }
1403
1404 // Op0 / C where C is large (negative) --> zext (Op0 >= C)
1405 // TODO: Could use isKnownNegative() to handle non-constant values.
1406 Type *Ty = I.getType();
1407 if (match(Op1, m_Negative())) {
1408 Value *Cmp = Builder.CreateICmpUGE(Op0, Op1);
1409 return CastInst::CreateZExtOrBitCast(Cmp, Ty);
1410 }
1411 // Op0 / (sext i1 X) --> zext (Op0 == -1) (if X is 0, the div is undefined)
1412 if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
1414 return CastInst::CreateZExtOrBitCast(Cmp, Ty);
1415 }
1416
1417 if (Instruction *NarrowDiv = narrowUDivURem(I, *this))
1418 return NarrowDiv;
1419
1420 Value *A, *B;
1421
1422 // Look through a right-shift to find the common factor:
1423 // ((Op1 *nuw A) >> B) / Op1 --> A >> B
1424 if (match(Op0, m_LShr(m_NUWMul(m_Specific(Op1), m_Value(A)), m_Value(B))) ||
1425 match(Op0, m_LShr(m_NUWMul(m_Value(A), m_Specific(Op1)), m_Value(B)))) {
1426 Instruction *Lshr = BinaryOperator::CreateLShr(A, B);
1427 if (I.isExact() && cast<PossiblyExactOperator>(Op0)->isExact())
1428 Lshr->setIsExact();
1429 return Lshr;
1430 }
1431
1432 // Op1 udiv Op2 -> Op1 lshr log2(Op2), if log2() folds away.
1433 if (takeLog2(Builder, Op1, /*Depth*/ 0, /*AssumeNonZero*/ true,
1434 /*DoFold*/ false)) {
1435 Value *Res = takeLog2(Builder, Op1, /*Depth*/ 0,
1436 /*AssumeNonZero*/ true, /*DoFold*/ true);
1437 return replaceInstUsesWith(
1438 I, Builder.CreateLShr(Op0, Res, I.getName(), I.isExact()));
1439 }
1440
1441 return nullptr;
1442}
1443
1445 if (Value *V = simplifySDivInst(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 Type *Ty = I.getType();
1458 Value *X;
1459 // sdiv Op0, -1 --> -Op0
1460 // sdiv Op0, (sext i1 X) --> -Op0 (because if X is 0, the op is undefined)
1461 if (match(Op1, m_AllOnes()) ||
1462 (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)))
1463 return BinaryOperator::CreateNSWNeg(Op0);
1464
1465 // X / INT_MIN --> X == INT_MIN
1466 if (match(Op1, m_SignMask()))
1467 return new ZExtInst(Builder.CreateICmpEQ(Op0, Op1), Ty);
1468
1469 if (I.isExact()) {
1470 // sdiv exact X, 1<<C --> ashr exact X, C iff 1<<C is non-negative
1471 if (match(Op1, m_Power2()) && match(Op1, m_NonNegative())) {
1472 Constant *C = ConstantExpr::getExactLogBase2(cast<Constant>(Op1));
1473 return BinaryOperator::CreateExactAShr(Op0, C);
1474 }
1475
1476 // sdiv exact X, (1<<ShAmt) --> ashr exact X, ShAmt (if shl is non-negative)
1477 Value *ShAmt;
1478 if (match(Op1, m_NSWShl(m_One(), m_Value(ShAmt))))
1479 return BinaryOperator::CreateExactAShr(Op0, ShAmt);
1480
1481 // sdiv exact X, -1<<C --> -(ashr exact X, C)
1482 if (match(Op1, m_NegatedPower2())) {
1483 Constant *NegPow2C = ConstantExpr::getNeg(cast<Constant>(Op1));
1485 Value *Ashr = Builder.CreateAShr(Op0, C, I.getName() + ".neg", true);
1486 return BinaryOperator::CreateNSWNeg(Ashr);
1487 }
1488 }
1489
1490 const APInt *Op1C;
1491 if (match(Op1, m_APInt(Op1C))) {
1492 // If the dividend is sign-extended and the constant divisor is small enough
1493 // to fit in the source type, shrink the division to the narrower type:
1494 // (sext X) sdiv C --> sext (X sdiv C)
1495 Value *Op0Src;
1496 if (match(Op0, m_OneUse(m_SExt(m_Value(Op0Src)))) &&
1497 Op0Src->getType()->getScalarSizeInBits() >=
1498 Op1C->getSignificantBits()) {
1499
1500 // In the general case, we need to make sure that the dividend is not the
1501 // minimum signed value because dividing that by -1 is UB. But here, we
1502 // know that the -1 divisor case is already handled above.
1503
1504 Constant *NarrowDivisor =
1505 ConstantExpr::getTrunc(cast<Constant>(Op1), Op0Src->getType());
1506 Value *NarrowOp = Builder.CreateSDiv(Op0Src, NarrowDivisor);
1507 return new SExtInst(NarrowOp, Ty);
1508 }
1509
1510 // -X / C --> X / -C (if the negation doesn't overflow).
1511 // TODO: This could be enhanced to handle arbitrary vector constants by
1512 // checking if all elements are not the min-signed-val.
1513 if (!Op1C->isMinSignedValue() &&
1514 match(Op0, m_NSWSub(m_Zero(), m_Value(X)))) {
1515 Constant *NegC = ConstantInt::get(Ty, -(*Op1C));
1516 Instruction *BO = BinaryOperator::CreateSDiv(X, NegC);
1517 BO->setIsExact(I.isExact());
1518 return BO;
1519 }
1520 }
1521
1522 // -X / Y --> -(X / Y)
1523 Value *Y;
1526 Builder.CreateSDiv(X, Y, I.getName(), I.isExact()));
1527
1528 // abs(X) / X --> X > -1 ? 1 : -1
1529 // X / abs(X) --> X > -1 ? 1 : -1
1530 if (match(&I, m_c_BinOp(
1531 m_OneUse(m_Intrinsic<Intrinsic::abs>(m_Value(X), m_One())),
1532 m_Deferred(X)))) {
1534 return SelectInst::Create(Cond, ConstantInt::get(Ty, 1),
1536 }
1537
1538 KnownBits KnownDividend = computeKnownBits(Op0, 0, &I);
1539 if (!I.isExact() &&
1540 (match(Op1, m_Power2(Op1C)) || match(Op1, m_NegatedPower2(Op1C))) &&
1541 KnownDividend.countMinTrailingZeros() >= Op1C->countr_zero()) {
1542 I.setIsExact();
1543 return &I;
1544 }
1545
1546 if (KnownDividend.isNonNegative()) {
1547 // If both operands are unsigned, turn this into a udiv.
1549 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1550 BO->setIsExact(I.isExact());
1551 return BO;
1552 }
1553
1554 if (match(Op1, m_NegatedPower2())) {
1555 // X sdiv (-(1 << C)) -> -(X sdiv (1 << C)) ->
1556 // -> -(X udiv (1 << C)) -> -(X u>> C)
1558 ConstantExpr::getNeg(cast<Constant>(Op1)));
1559 Value *Shr = Builder.CreateLShr(Op0, CNegLog2, I.getName(), I.isExact());
1560 return BinaryOperator::CreateNeg(Shr);
1561 }
1562
1563 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/ true, 0, &I)) {
1564 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
1565 // Safe because the only negative value (1 << Y) can take on is
1566 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
1567 // the sign bit set.
1568 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1569 BO->setIsExact(I.isExact());
1570 return BO;
1571 }
1572 }
1573
1574 // -X / X --> X == INT_MIN ? 1 : -1
1575 if (isKnownNegation(Op0, Op1)) {
1577 Value *Cond = Builder.CreateICmpEQ(Op0, ConstantInt::get(Ty, MinVal));
1578 return SelectInst::Create(Cond, ConstantInt::get(Ty, 1),
1580 }
1581 return nullptr;
1582}
1583
1584/// Remove negation and try to convert division into multiplication.
1585Instruction *InstCombinerImpl::foldFDivConstantDivisor(BinaryOperator &I) {
1586 Constant *C;
1587 if (!match(I.getOperand(1), m_Constant(C)))
1588 return nullptr;
1589
1590 // -X / C --> X / -C
1591 Value *X;
1592 const DataLayout &DL = I.getModule()->getDataLayout();
1593 if (match(I.getOperand(0), m_FNeg(m_Value(X))))
1594 if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL))
1595 return BinaryOperator::CreateFDivFMF(X, NegC, &I);
1596
1597 // nnan X / +0.0 -> copysign(inf, X)
1598 // nnan nsz X / -0.0 -> copysign(inf, X)
1599 if (I.hasNoNaNs() &&
1600 (match(I.getOperand(1), m_PosZeroFP()) ||
1601 (I.hasNoSignedZeros() && match(I.getOperand(1), m_AnyZeroFP())))) {
1602 IRBuilder<> B(&I);
1603 CallInst *CopySign = B.CreateIntrinsic(
1604 Intrinsic::copysign, {C->getType()},
1605 {ConstantFP::getInfinity(I.getType()), I.getOperand(0)}, &I);
1606 CopySign->takeName(&I);
1607 return replaceInstUsesWith(I, CopySign);
1608 }
1609
1610 // If the constant divisor has an exact inverse, this is always safe. If not,
1611 // then we can still create a reciprocal if fast-math-flags allow it and the
1612 // constant is a regular number (not zero, infinite, or denormal).
1613 if (!(C->hasExactInverseFP() || (I.hasAllowReciprocal() && C->isNormalFP())))
1614 return nullptr;
1615
1616 // Disallow denormal constants because we don't know what would happen
1617 // on all targets.
1618 // TODO: Use Intrinsic::canonicalize or let function attributes tell us that
1619 // denorms are flushed?
1620 auto *RecipC = ConstantFoldBinaryOpOperands(
1621 Instruction::FDiv, ConstantFP::get(I.getType(), 1.0), C, DL);
1622 if (!RecipC || !RecipC->isNormalFP())
1623 return nullptr;
1624
1625 // X / C --> X * (1 / C)
1626 return BinaryOperator::CreateFMulFMF(I.getOperand(0), RecipC, &I);
1627}
1628
1629/// Remove negation and try to reassociate constant math.
1631 Constant *C;
1632 if (!match(I.getOperand(0), m_Constant(C)))
1633 return nullptr;
1634
1635 // C / -X --> -C / X
1636 Value *X;
1637 const DataLayout &DL = I.getModule()->getDataLayout();
1638 if (match(I.getOperand(1), m_FNeg(m_Value(X))))
1639 if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL))
1640 return BinaryOperator::CreateFDivFMF(NegC, X, &I);
1641
1642 if (!I.hasAllowReassoc() || !I.hasAllowReciprocal())
1643 return nullptr;
1644
1645 // Try to reassociate C / X expressions where X includes another constant.
1646 Constant *C2, *NewC = nullptr;
1647 if (match(I.getOperand(1), m_FMul(m_Value(X), m_Constant(C2)))) {
1648 // C / (X * C2) --> (C / C2) / X
1649 NewC = ConstantFoldBinaryOpOperands(Instruction::FDiv, C, C2, DL);
1650 } else if (match(I.getOperand(1), m_FDiv(m_Value(X), m_Constant(C2)))) {
1651 // C / (X / C2) --> (C * C2) / X
1652 NewC = ConstantFoldBinaryOpOperands(Instruction::FMul, C, C2, DL);
1653 }
1654 // Disallow denormal constants because we don't know what would happen
1655 // on all targets.
1656 // TODO: Use Intrinsic::canonicalize or let function attributes tell us that
1657 // denorms are flushed?
1658 if (!NewC || !NewC->isNormalFP())
1659 return nullptr;
1660
1661 return BinaryOperator::CreateFDivFMF(NewC, X, &I);
1662}
1663
1664/// Negate the exponent of pow/exp to fold division-by-pow() into multiply.
1666 InstCombiner::BuilderTy &Builder) {
1667 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1668 auto *II = dyn_cast<IntrinsicInst>(Op1);
1669 if (!II || !II->hasOneUse() || !I.hasAllowReassoc() ||
1670 !I.hasAllowReciprocal())
1671 return nullptr;
1672
1673 // Z / pow(X, Y) --> Z * pow(X, -Y)
1674 // Z / exp{2}(Y) --> Z * exp{2}(-Y)
1675 // In the general case, this creates an extra instruction, but fmul allows
1676 // for better canonicalization and optimization than fdiv.
1677 Intrinsic::ID IID = II->getIntrinsicID();
1679 switch (IID) {
1680 case Intrinsic::pow:
1681 Args.push_back(II->getArgOperand(0));
1682 Args.push_back(Builder.CreateFNegFMF(II->getArgOperand(1), &I));
1683 break;
1684 case Intrinsic::powi: {
1685 // Require 'ninf' assuming that makes powi(X, -INT_MIN) acceptable.
1686 // That is, X ** (huge negative number) is 0.0, ~1.0, or INF and so
1687 // dividing by that is INF, ~1.0, or 0.0. Code that uses powi allows
1688 // non-standard results, so this corner case should be acceptable if the
1689 // code rules out INF values.
1690 if (!I.hasNoInfs())
1691 return nullptr;
1692 Args.push_back(II->getArgOperand(0));
1693 Args.push_back(Builder.CreateNeg(II->getArgOperand(1)));
1694 Type *Tys[] = {I.getType(), II->getArgOperand(1)->getType()};
1695 Value *Pow = Builder.CreateIntrinsic(IID, Tys, Args, &I);
1696 return BinaryOperator::CreateFMulFMF(Op0, Pow, &I);
1697 }
1698 case Intrinsic::exp:
1699 case Intrinsic::exp2:
1700 Args.push_back(Builder.CreateFNegFMF(II->getArgOperand(0), &I));
1701 break;
1702 default:
1703 return nullptr;
1704 }
1705 Value *Pow = Builder.CreateIntrinsic(IID, I.getType(), Args, &I);
1706 return BinaryOperator::CreateFMulFMF(Op0, Pow, &I);
1707}
1708
1710 Module *M = I.getModule();
1711
1712 if (Value *V = simplifyFDivInst(I.getOperand(0), I.getOperand(1),
1713 I.getFastMathFlags(),
1715 return replaceInstUsesWith(I, V);
1716
1718 return X;
1719
1721 return Phi;
1722
1723 if (Instruction *R = foldFDivConstantDivisor(I))
1724 return R;
1725
1727 return R;
1728
1729 if (Instruction *R = foldFPSignBitOps(I))
1730 return R;
1731
1732 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1733 if (isa<Constant>(Op0))
1734 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1735 if (Instruction *R = FoldOpIntoSelect(I, SI))
1736 return R;
1737
1738 if (isa<Constant>(Op1))
1739 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1740 if (Instruction *R = FoldOpIntoSelect(I, SI))
1741 return R;
1742
1743 if (I.hasAllowReassoc() && I.hasAllowReciprocal()) {
1744 Value *X, *Y;
1745 if (match(Op0, m_OneUse(m_FDiv(m_Value(X), m_Value(Y)))) &&
1746 (!isa<Constant>(Y) || !isa<Constant>(Op1))) {
1747 // (X / Y) / Z => X / (Y * Z)
1748 Value *YZ = Builder.CreateFMulFMF(Y, Op1, &I);
1749 return BinaryOperator::CreateFDivFMF(X, YZ, &I);
1750 }
1751 if (match(Op1, m_OneUse(m_FDiv(m_Value(X), m_Value(Y)))) &&
1752 (!isa<Constant>(Y) || !isa<Constant>(Op0))) {
1753 // Z / (X / Y) => (Y * Z) / X
1754 Value *YZ = Builder.CreateFMulFMF(Y, Op0, &I);
1755 return BinaryOperator::CreateFDivFMF(YZ, X, &I);
1756 }
1757 // Z / (1.0 / Y) => (Y * Z)
1758 //
1759 // This is a special case of Z / (X / Y) => (Y * Z) / X, with X = 1.0. The
1760 // m_OneUse check is avoided because even in the case of the multiple uses
1761 // for 1.0/Y, the number of instructions remain the same and a division is
1762 // replaced by a multiplication.
1763 if (match(Op1, m_FDiv(m_SpecificFP(1.0), m_Value(Y))))
1764 return BinaryOperator::CreateFMulFMF(Y, Op0, &I);
1765 }
1766
1767 if (I.hasAllowReassoc() && Op0->hasOneUse() && Op1->hasOneUse()) {
1768 // sin(X) / cos(X) -> tan(X)
1769 // cos(X) / sin(X) -> 1/tan(X) (cotangent)
1770 Value *X;
1771 bool IsTan = match(Op0, m_Intrinsic<Intrinsic::sin>(m_Value(X))) &&
1772 match(Op1, m_Intrinsic<Intrinsic::cos>(m_Specific(X)));
1773 bool IsCot =
1774 !IsTan && match(Op0, m_Intrinsic<Intrinsic::cos>(m_Value(X))) &&
1775 match(Op1, m_Intrinsic<Intrinsic::sin>(m_Specific(X)));
1776
1777 if ((IsTan || IsCot) && hasFloatFn(M, &TLI, I.getType(), LibFunc_tan,
1778 LibFunc_tanf, LibFunc_tanl)) {
1779 IRBuilder<> B(&I);
1781 B.setFastMathFlags(I.getFastMathFlags());
1782 AttributeList Attrs =
1783 cast<CallBase>(Op0)->getCalledFunction()->getAttributes();
1784 Value *Res = emitUnaryFloatFnCall(X, &TLI, LibFunc_tan, LibFunc_tanf,
1785 LibFunc_tanl, B, Attrs);
1786 if (IsCot)
1787 Res = B.CreateFDiv(ConstantFP::get(I.getType(), 1.0), Res);
1788 return replaceInstUsesWith(I, Res);
1789 }
1790 }
1791
1792 // X / (X * Y) --> 1.0 / Y
1793 // Reassociate to (X / X -> 1.0) is legal when NaNs are not allowed.
1794 // We can ignore the possibility that X is infinity because INF/INF is NaN.
1795 Value *X, *Y;
1796 if (I.hasNoNaNs() && I.hasAllowReassoc() &&
1797 match(Op1, m_c_FMul(m_Specific(Op0), m_Value(Y)))) {
1798 replaceOperand(I, 0, ConstantFP::get(I.getType(), 1.0));
1799 replaceOperand(I, 1, Y);
1800 return &I;
1801 }
1802
1803 // X / fabs(X) -> copysign(1.0, X)
1804 // fabs(X) / X -> copysign(1.0, X)
1805 if (I.hasNoNaNs() && I.hasNoInfs() &&
1806 (match(&I, m_FDiv(m_Value(X), m_FAbs(m_Deferred(X)))) ||
1807 match(&I, m_FDiv(m_FAbs(m_Value(X)), m_Deferred(X))))) {
1809 Intrinsic::copysign, ConstantFP::get(I.getType(), 1.0), X, &I);
1810 return replaceInstUsesWith(I, V);
1811 }
1812
1814 return Mul;
1815
1816 // pow(X, Y) / X --> pow(X, Y-1)
1817 if (I.hasAllowReassoc() &&
1818 match(Op0, m_OneUse(m_Intrinsic<Intrinsic::pow>(m_Specific(Op1),
1819 m_Value(Y))))) {
1820 Value *Y1 =
1821 Builder.CreateFAddFMF(Y, ConstantFP::get(I.getType(), -1.0), &I);
1822 Value *Pow = Builder.CreateBinaryIntrinsic(Intrinsic::pow, Op1, Y1, &I);
1823 return replaceInstUsesWith(I, Pow);
1824 }
1825
1826 // powi(X, Y) / X --> powi(X, Y-1)
1827 // This is legal when (Y - 1) can't wraparound, in which case reassoc and nnan
1828 // are required.
1829 // TODO: Multi-use may be also better off creating Powi(x,y-1)
1830 if (I.hasAllowReassoc() && I.hasNoNaNs() &&
1831 match(Op0, m_OneUse(m_Intrinsic<Intrinsic::powi>(m_Specific(Op1),
1832 m_Value(Y)))) &&
1833 willNotOverflowSignedSub(Y, ConstantInt::get(Y->getType(), 1), I)) {
1834 Constant *NegOne = ConstantInt::getAllOnesValue(Y->getType());
1835 Value *Y1 = Builder.CreateAdd(Y, NegOne);
1836 Type *Types[] = {Op1->getType(), Y1->getType()};
1837 Value *Pow = Builder.CreateIntrinsic(Intrinsic::powi, Types, {Op1, Y1}, &I);
1838 return replaceInstUsesWith(I, Pow);
1839 }
1840
1841 return nullptr;
1842}
1843
1844// Variety of transform for:
1845// (urem/srem (mul X, Y), (mul X, Z))
1846// (urem/srem (shl X, Y), (shl X, Z))
1847// (urem/srem (shl Y, X), (shl Z, X))
1848// NB: The shift cases are really just extensions of the mul case. We treat
1849// shift as Val * (1 << Amt).
1851 InstCombinerImpl &IC) {
1852 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1), *X = nullptr;
1853 APInt Y, Z;
1854 bool ShiftByX = false;
1855
1856 // If V is not nullptr, it will be matched using m_Specific.
1857 auto MatchShiftOrMulXC = [](Value *Op, Value *&V, APInt &C) -> bool {
1858 const APInt *Tmp = nullptr;
1859 if ((!V && match(Op, m_Mul(m_Value(V), m_APInt(Tmp)))) ||
1860 (V && match(Op, m_Mul(m_Specific(V), m_APInt(Tmp)))))
1861 C = *Tmp;
1862 else if ((!V && match(Op, m_Shl(m_Value(V), m_APInt(Tmp)))) ||
1863 (V && match(Op, m_Shl(m_Specific(V), m_APInt(Tmp)))))
1864 C = APInt(Tmp->getBitWidth(), 1) << *Tmp;
1865 if (Tmp != nullptr)
1866 return true;
1867
1868 // Reset `V` so we don't start with specific value on next match attempt.
1869 V = nullptr;
1870 return false;
1871 };
1872
1873 auto MatchShiftCX = [](Value *Op, APInt &C, Value *&V) -> bool {
1874 const APInt *Tmp = nullptr;
1875 if ((!V && match(Op, m_Shl(m_APInt(Tmp), m_Value(V)))) ||
1876 (V && match(Op, m_Shl(m_APInt(Tmp), m_Specific(V))))) {
1877 C = *Tmp;
1878 return true;
1879 }
1880
1881 // Reset `V` so we don't start with specific value on next match attempt.
1882 V = nullptr;
1883 return false;
1884 };
1885
1886 if (MatchShiftOrMulXC(Op0, X, Y) && MatchShiftOrMulXC(Op1, X, Z)) {
1887 // pass
1888 } else if (MatchShiftCX(Op0, Y, X) && MatchShiftCX(Op1, Z, X)) {
1889 ShiftByX = true;
1890 } else {
1891 return nullptr;
1892 }
1893
1894 bool IsSRem = I.getOpcode() == Instruction::SRem;
1895
1896 OverflowingBinaryOperator *BO0 = cast<OverflowingBinaryOperator>(Op0);
1897 // TODO: We may be able to deduce more about nsw/nuw of BO0/BO1 based on Y >=
1898 // Z or Z >= Y.
1899 bool BO0HasNSW = BO0->hasNoSignedWrap();
1900 bool BO0HasNUW = BO0->hasNoUnsignedWrap();
1901 bool BO0NoWrap = IsSRem ? BO0HasNSW : BO0HasNUW;
1902
1903 APInt RemYZ = IsSRem ? Y.srem(Z) : Y.urem(Z);
1904 // (rem (mul nuw/nsw X, Y), (mul X, Z))
1905 // if (rem Y, Z) == 0
1906 // -> 0
1907 if (RemYZ.isZero() && BO0NoWrap)
1908 return IC.replaceInstUsesWith(I, ConstantInt::getNullValue(I.getType()));
1909
1910 // Helper function to emit either (RemSimplificationC << X) or
1911 // (RemSimplificationC * X) depending on whether we matched Op0/Op1 as
1912 // (shl V, X) or (mul V, X) respectively.
1913 auto CreateMulOrShift =
1914 [&](const APInt &RemSimplificationC) -> BinaryOperator * {
1915 Value *RemSimplification =
1916 ConstantInt::get(I.getType(), RemSimplificationC);
1917 return ShiftByX ? BinaryOperator::CreateShl(RemSimplification, X)
1918 : BinaryOperator::CreateMul(X, RemSimplification);
1919 };
1920
1921 OverflowingBinaryOperator *BO1 = cast<OverflowingBinaryOperator>(Op1);
1922 bool BO1HasNSW = BO1->hasNoSignedWrap();
1923 bool BO1HasNUW = BO1->hasNoUnsignedWrap();
1924 bool BO1NoWrap = IsSRem ? BO1HasNSW : BO1HasNUW;
1925 // (rem (mul X, Y), (mul nuw/nsw X, Z))
1926 // if (rem Y, Z) == Y
1927 // -> (mul nuw/nsw X, Y)
1928 if (RemYZ == Y && BO1NoWrap) {
1929 BinaryOperator *BO = CreateMulOrShift(Y);
1930 // Copy any overflow flags from Op0.
1931 BO->setHasNoSignedWrap(IsSRem || BO0HasNSW);
1932 BO->setHasNoUnsignedWrap(!IsSRem || BO0HasNUW);
1933 return BO;
1934 }
1935
1936 // (rem (mul nuw/nsw X, Y), (mul {nsw} X, Z))
1937 // if Y >= Z
1938 // -> (mul {nuw} nsw X, (rem Y, Z))
1939 if (Y.uge(Z) && (IsSRem ? (BO0HasNSW && BO1HasNSW) : BO0HasNUW)) {
1940 BinaryOperator *BO = CreateMulOrShift(RemYZ);
1941 BO->setHasNoSignedWrap();
1942 BO->setHasNoUnsignedWrap(BO0HasNUW);
1943 return BO;
1944 }
1945
1946 return nullptr;
1947}
1948
1949/// This function implements the transforms common to both integer remainder
1950/// instructions (urem and srem). It is called by the visitors to those integer
1951/// remainder instructions.
1952/// Common integer remainder transforms
1955 return Phi;
1956
1957 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1958
1959 // The RHS is known non-zero.
1960 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I))
1961 return replaceOperand(I, 1, V);
1962
1963 // Handle cases involving: rem X, (select Cond, Y, Z)
1965 return &I;
1966
1967 // If the divisor is a select-of-constants, try to constant fold all rem ops:
1968 // C % (select Cond, TrueC, FalseC) --> select Cond, (C % TrueC), (C % FalseC)
1969 // TODO: Adapt simplifyDivRemOfSelectWithZeroOp to allow this and other folds.
1970 if (match(Op0, m_ImmConstant()) &&
1972 if (Instruction *R = FoldOpIntoSelect(I, cast<SelectInst>(Op1),
1973 /*FoldWithMultiUse*/ true))
1974 return R;
1975 }
1976
1977 if (isa<Constant>(Op1)) {
1978 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1979 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1980 if (Instruction *R = FoldOpIntoSelect(I, SI))
1981 return R;
1982 } else if (auto *PN = dyn_cast<PHINode>(Op0I)) {
1983 const APInt *Op1Int;
1984 if (match(Op1, m_APInt(Op1Int)) && !Op1Int->isMinValue() &&
1985 (I.getOpcode() == Instruction::URem ||
1986 !Op1Int->isMinSignedValue())) {
1987 // foldOpIntoPhi will speculate instructions to the end of the PHI's
1988 // predecessor blocks, so do this only if we know the srem or urem
1989 // will not fault.
1990 if (Instruction *NV = foldOpIntoPhi(I, PN))
1991 return NV;
1992 }
1993 }
1994
1995 // See if we can fold away this rem instruction.
1997 return &I;
1998 }
1999 }
2000
2001 if (Instruction *R = simplifyIRemMulShl(I, *this))
2002 return R;
2003
2004 return nullptr;
2005}
2006
2008 if (Value *V = simplifyURemInst(I.getOperand(0), I.getOperand(1),
2010 return replaceInstUsesWith(I, V);
2011
2013 return X;
2014
2015 if (Instruction *common = commonIRemTransforms(I))
2016 return common;
2017
2018 if (Instruction *NarrowRem = narrowUDivURem(I, *this))
2019 return NarrowRem;
2020
2021 // X urem Y -> X and Y-1, where Y is a power of 2,
2022 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2023 Type *Ty = I.getType();
2024 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/ true, 0, &I)) {
2025 // This may increase instruction count, we don't enforce that Y is a
2026 // constant.
2028 Value *Add = Builder.CreateAdd(Op1, N1);
2029 return BinaryOperator::CreateAnd(Op0, Add);
2030 }
2031
2032 // 1 urem X -> zext(X != 1)
2033 if (match(Op0, m_One())) {
2034 Value *Cmp = Builder.CreateICmpNE(Op1, ConstantInt::get(Ty, 1));
2035 return CastInst::CreateZExtOrBitCast(Cmp, Ty);
2036 }
2037
2038 // Op0 urem C -> Op0 < C ? Op0 : Op0 - C, where C >= signbit.
2039 // Op0 must be frozen because we are increasing its number of uses.
2040 if (match(Op1, m_Negative())) {
2041 Value *F0 = Builder.CreateFreeze(Op0, Op0->getName() + ".fr");
2042 Value *Cmp = Builder.CreateICmpULT(F0, Op1);
2043 Value *Sub = Builder.CreateSub(F0, Op1);
2044 return SelectInst::Create(Cmp, F0, Sub);
2045 }
2046
2047 // If the divisor is a sext of a boolean, then the divisor must be max
2048 // unsigned value (-1). Therefore, the remainder is Op0 unless Op0 is also
2049 // max unsigned value. In that case, the remainder is 0:
2050 // urem Op0, (sext i1 X) --> (Op0 == -1) ? 0 : Op0
2051 Value *X;
2052 if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
2053 Value *FrozenOp0 = Builder.CreateFreeze(Op0, Op0->getName() + ".frozen");
2054 Value *Cmp =
2056 return SelectInst::Create(Cmp, ConstantInt::getNullValue(Ty), FrozenOp0);
2057 }
2058
2059 // For "(X + 1) % Op1" and if (X u< Op1) => (X + 1) == Op1 ? 0 : X + 1 .
2060 if (match(Op0, m_Add(m_Value(X), m_One()))) {
2061 Value *Val =
2063 if (Val && match(Val, m_One())) {
2064 Value *FrozenOp0 = Builder.CreateFreeze(Op0, Op0->getName() + ".frozen");
2065 Value *Cmp = Builder.CreateICmpEQ(FrozenOp0, Op1);
2066 return SelectInst::Create(Cmp, ConstantInt::getNullValue(Ty), FrozenOp0);
2067 }
2068 }
2069
2070 return nullptr;
2071}
2072
2074 if (Value *V = simplifySRemInst(I.getOperand(0), I.getOperand(1),
2076 return replaceInstUsesWith(I, V);
2077
2079 return X;
2080
2081 // Handle the integer rem common cases
2082 if (Instruction *Common = commonIRemTransforms(I))
2083 return Common;
2084
2085 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2086 {
2087 const APInt *Y;
2088 // X % -Y -> X % Y
2089 if (match(Op1, m_Negative(Y)) && !Y->isMinSignedValue())
2090 return replaceOperand(I, 1, ConstantInt::get(I.getType(), -*Y));
2091 }
2092
2093 // -X srem Y --> -(X srem Y)
2094 Value *X, *Y;
2097
2098 // If the sign bits of both operands are zero (i.e. we can prove they are
2099 // unsigned inputs), turn this into a urem.
2100 APInt Mask(APInt::getSignMask(I.getType()->getScalarSizeInBits()));
2101 if (MaskedValueIsZero(Op1, Mask, 0, &I) &&
2102 MaskedValueIsZero(Op0, Mask, 0, &I)) {
2103 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2104 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
2105 }
2106
2107 // If it's a constant vector, flip any negative values positive.
2108 if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
2109 Constant *C = cast<Constant>(Op1);
2110 unsigned VWidth = cast<FixedVectorType>(C->getType())->getNumElements();
2111
2112 bool hasNegative = false;
2113 bool hasMissing = false;
2114 for (unsigned i = 0; i != VWidth; ++i) {
2115 Constant *Elt = C->getAggregateElement(i);
2116 if (!Elt) {
2117 hasMissing = true;
2118 break;
2119 }
2120
2121 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
2122 if (RHS->isNegative())
2123 hasNegative = true;
2124 }
2125
2126 if (hasNegative && !hasMissing) {
2127 SmallVector<Constant *, 16> Elts(VWidth);
2128 for (unsigned i = 0; i != VWidth; ++i) {
2129 Elts[i] = C->getAggregateElement(i); // Handle undef, etc.
2130 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
2131 if (RHS->isNegative())
2132 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
2133 }
2134 }
2135
2136 Constant *NewRHSV = ConstantVector::get(Elts);
2137 if (NewRHSV != C) // Don't loop on -MININT
2138 return replaceOperand(I, 1, NewRHSV);
2139 }
2140 }
2141
2142 return nullptr;
2143}
2144
2146 if (Value *V = simplifyFRemInst(I.getOperand(0), I.getOperand(1),
2147 I.getFastMathFlags(),
2149 return replaceInstUsesWith(I, V);
2150
2152 return X;
2153
2155 return Phi;
2156
2157 return nullptr;
2158}
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 * 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
Class for arbitrary precision integers.
Definition: APInt.h:76
APInt umul_ov(const APInt &RHS, bool &Overflow) const
Definition: APInt.cpp:1977
APInt udiv(const APInt &RHS) const
Unsigned division operation.
Definition: APInt.cpp:1579
static void udivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, APInt &Remainder)
Dual division/remainder interface.
Definition: APInt.cpp:1764
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:1485
static void sdivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, APInt &Remainder)
Definition: APInt.cpp:1896
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:1433
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition: APInt.h:1083
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:1583
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:2011
unsigned getSignificantBits() const
Get the minimum bit size for this signed APInt.
Definition: APInt.h:1476
APInt smul_ov(const APInt &RHS, bool &Overflow) const
Definition: APInt.cpp:1966
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition: APInt.h:1122
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:164
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 * CreateFDivFMF(Value *V1, Value *V2, Instruction *FMFSource, const Twine &Name="")
Definition: InstrTypes.h:328
static BinaryOperator * CreateNSWNeg(Value *Op, const Twine &Name, BasicBlock::iterator InsertBefore)
BinaryOps getOpcode() const
Definition: InstrTypes.h:493
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, Instruction *FMFSource, const Twine &Name="")
Definition: InstrTypes.h:323
static BinaryOperator * CreateFSubFMF(Value *V1, Value *V2, Instruction *FMFSource, const Twine &Name="")
Definition: InstrTypes.h:318
static BinaryOperator * CreateFAddFMF(Value *V1, Value *V2, Instruction *FMFSource, const Twine &Name="")
Definition: InstrTypes.h:313
static BinaryOperator * CreateWithCopiedFlags(BinaryOps Opc, Value *V1, Value *V2, Value *CopyO, const Twine &Name, BasicBlock::iterator InsertBefore)
Definition: InstrTypes.h:297
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:1325
@ ICMP_ULT
unsigned less than
Definition: InstrTypes.h:992
static Constant * getShl(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
Definition: Constants.cpp:2562
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:2569
static Constant * getNeg(Constant *C, bool HasNUW=false, bool HasNSW=false)
Definition: Constants.cpp:2525
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:79
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 * 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
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:1541
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:2240
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2006
Value * CreateNeg(Value *V, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1715
Value * CreateSRem(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1404
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:1595
ConstantInt * getTrue()
Get the constant value for i1 true.
Definition: IRBuilder.h:460
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:930
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:1739
Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
Definition: IRBuilder.cpp:1108
Value * CreateFreeze(Value *V, const Twine &Name="")
Definition: IRBuilder.h:2518
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition: IRBuilder.h:1431
Value * CreateIsNotNeg(Value *Arg, const Twine &Name="")
Return a boolean value testing if Arg > -1.
Definition: IRBuilder.h:2542
void setFastMathFlags(FastMathFlags NewFMF)
Set the fast-math flags to be used with generated fp-math operators.
Definition: IRBuilder.h:305
Value * CreateNSWMul(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1364
Value * CreateUDiv(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition: IRBuilder.h:1372
Value * CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:2228
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:2224
Value * CreateIsNeg(Value *Arg, const Twine &Name="")
Return a boolean value testing if Arg < 0.
Definition: IRBuilder.h:2537
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1338
Value * CreateShl(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1410
CallInst * 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 * CreateZExt(Value *V, Type *DestTy, const Twine &Name="", bool IsNonNeg=false)
Definition: IRBuilder.h:2010
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1469
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1321
Value * CreateSDiv(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition: IRBuilder.h:1385
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:1660
Value * CreateICmpUGE(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:2236
Value * CreateAShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition: IRBuilder.h:1450
Value * CreateFNeg(Value *V, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:1729
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1355
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 * 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.
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:75
bool hasNoSignedWrap() const
Test whether this operation is known to never undergo signed overflow, aka the nsw property.
Definition: Operator.h:108
bool hasNoUnsignedWrap() const
Test whether this operation is known to never undergo unsigned overflow, aka the nuw property.
Definition: Operator.h:102
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:189
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:461
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
specific_intval< false > m_SpecificInt(APInt V)
Match a specific integer value or vector with all elements equal to the value.
Definition: PatternMatch.h:862
cst_pred_ty< is_negative > m_Negative()
Match an integer or vector of negative values.
Definition: PatternMatch.h:483
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
Definition: PatternMatch.h:982
class_match< BinaryOperator > m_BinOp()
Match an arbitrary binary operation and ignore it.
Definition: PatternMatch.h:84
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:584
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWAdd(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::AShr > m_AShr(const LHS &L, const RHS &R)
apint_match m_APIntAllowUndef(const APInt *&Res)
Match APInt while allowing undefs in splat vector constants.
Definition: PatternMatch.h:284
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:552
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:144
OverflowingBinaryOp_match< LHS, RHS, Instruction::Sub, OverflowingBinaryOperator::NoSignedWrap > m_NSWSub(const LHS &L, const RHS &R)
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:672
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
Definition: PatternMatch.h:780
cst_pred_ty< is_nonnegative > m_NonNegative()
Match an integer or vector of non-negative values.
Definition: PatternMatch.h:493
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
Definition: PatternMatch.h:525
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:823
m_Intrinsic_Ty< Opnd0 >::Ty m_Sqrt(const Opnd0 &Op0)
BinaryOp_match< LHS, RHS, Instruction::FAdd > m_FAdd(const LHS &L, const RHS &R)
Definition: PatternMatch.h:988
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:798
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:759
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:560
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)
specific_intval< true > m_SpecificIntAllowUndef(APInt V)
Definition: PatternMatch.h:870
apint_match m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
Definition: PatternMatch.h:278
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
Definition: PatternMatch.h:76
AnyBinaryOp_match< LHS, RHS, true > m_c_BinOp(const LHS &L, const RHS &R)
Matches a BinaryOperator with LHS and RHS in either order.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoSignedWrap > m_NSWAdd(const LHS &L, const RHS &R)
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:681
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:545
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)
Definition: PatternMatch.h:994
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.
SelectPatternFlavor
Specific patterns of select instructions we can match.
@ SPF_ABS
Floating point maxnum.
@ SPF_NABS
Absolute value.
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.
SelectPatternResult matchSelectPattern(Value *V, Value *&LHS, Value *&RHS, Instruction::CastOps *CastOp=nullptr, unsigned Depth=0)
Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind and providing the out param...
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 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:99
unsigned countMinTrailingZeros() const
Returns the minimum number of trailing zero bits.
Definition: KnownBits.h:233
SelectPatternFlavor Flavor
SimplifyQuery getWithInstruction(const Instruction *I) const
Definition: SimplifyQuery.h:96