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