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