LLVM 24.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"
21#include "llvm/IR/BasicBlock.h"
22#include "llvm/IR/Constant.h"
23#include "llvm/IR/Constants.h"
24#include "llvm/IR/InstrTypes.h"
25#include "llvm/IR/Instruction.h"
28#include "llvm/IR/Intrinsics.h"
29#include "llvm/IR/Operator.h"
32#include "llvm/IR/Type.h"
33#include "llvm/IR/Value.h"
38#include <cassert>
39
40#define DEBUG_TYPE "instcombine"
42
43using namespace llvm;
44using namespace PatternMatch;
45
46/// The specific integer value is used in a context where it is known to be
47/// non-zero. If this allows us to simplify the computation, do so and return
48/// the new operand, otherwise return null.
50 Instruction &CtxI) {
51 // If V has multiple uses, then we would have to do more analysis to determine
52 // if this is safe. For example, the use could be in dynamically unreached
53 // code.
54 if (!V->hasOneUse()) return nullptr;
55
56 bool MadeChange = false;
57
58 // ((1 << A) >>u B) --> (1 << (A-B))
59 // Because V cannot be zero, we know that B is less than A.
60 Value *A = nullptr, *B = nullptr, *One = nullptr;
61 if (match(V, m_LShr(m_OneUse(m_Shl(m_Value(One), m_Value(A))), m_Value(B))) &&
62 match(One, m_One())) {
63 A = IC.Builder.CreateSub(A, B);
64 return IC.Builder.CreateShl(One, A);
65 }
66
67 // (PowerOfTwo >>u B) --> isExact since shifting out the result would make it
68 // inexact. Similarly for <<.
70 if (I && I->isLogicalShift() &&
71 IC.isKnownToBeAPowerOfTwo(I->getOperand(0), false, &CtxI)) {
72 // We know that this is an exact/nuw shift and that the input is a
73 // non-zero context as well.
74 {
77 if (Value *V2 = simplifyValueKnownNonZero(I->getOperand(0), IC, CtxI)) {
78 IC.replaceOperand(*I, 0, V2);
79 MadeChange = true;
80 }
81 }
82
83 if (I->getOpcode() == Instruction::LShr && !I->isExact()) {
84 I->setIsExact();
85 MadeChange = true;
86 }
87
88 if (I->getOpcode() == Instruction::Shl && !I->hasNoUnsignedWrap()) {
89 I->setHasNoUnsignedWrap();
90 MadeChange = true;
91 }
92 }
93
94 // TODO: Lots more we could do here:
95 // If V is a phi node, we can call this on each of its operands.
96 // "select cond, X, 0" can simplify to "X".
97
98 return MadeChange ? V : nullptr;
99}
100
101// TODO: This is a specific form of a much more general pattern.
102// We could detect a select with any binop identity constant, or we
103// could use SimplifyBinOp to see if either arm of the select reduces.
104// But that needs to be done carefully and/or while removing potential
105// reverse canonicalizations as in InstCombiner::foldSelectIntoOp().
107 InstCombiner::BuilderTy &Builder) {
108 Value *Cond, *OtherOp;
109 Instruction *SI = nullptr;
110
111 // mul (select Cond, 1, -1), OtherOp --> select Cond, OtherOp, -OtherOp
112 // mul OtherOp, (select Cond, 1, -1) --> select Cond, OtherOp, -OtherOp
115 m_Value(OtherOp)))) {
116 bool HasAnyNoWrap = I.hasNoSignedWrap() || I.hasNoUnsignedWrap();
117 Value *Neg = Builder.CreateNeg(OtherOp, "", HasAnyNoWrap);
118 return Builder.CreateSelect(Cond, OtherOp, Neg, "",
120 }
121 // mul (select Cond, -1, 1), OtherOp --> select Cond, -OtherOp, OtherOp
122 // mul OtherOp, (select Cond, -1, 1) --> select Cond, -OtherOp, OtherOp
125 m_Value(OtherOp)))) {
126 bool HasAnyNoWrap = I.hasNoSignedWrap() || I.hasNoUnsignedWrap();
127 Value *Neg = Builder.CreateNeg(OtherOp, "", HasAnyNoWrap);
128 return Builder.CreateSelect(Cond, Neg, OtherOp, "",
130 }
131
132 // fmul (select Cond, 1.0, -1.0), OtherOp --> select Cond, OtherOp, -OtherOp
133 // fmul OtherOp, (select Cond, 1.0, -1.0) --> select Cond, OtherOp, -OtherOp
136 m_SpecificFP(-1.0)))),
137 m_Value(OtherOp))))
138 return Builder.CreateSelectFMF(
139 Cond, OtherOp, Builder.CreateFNegFMF(OtherOp, &I), &I, "",
141
142 // fmul (select Cond, -1.0, 1.0), OtherOp --> select Cond, -OtherOp, OtherOp
143 // fmul OtherOp, (select Cond, -1.0, 1.0) --> select Cond, -OtherOp, OtherOp
146 m_SpecificFP(1.0)))),
147 m_Value(OtherOp))))
148 return Builder.CreateSelectFMF(
149 Cond, Builder.CreateFNegFMF(OtherOp, &I), OtherOp, &I, "",
151
152 return nullptr;
153}
154
155/// Reduce integer multiplication patterns that contain a (+/-1 << Z) factor.
156/// Callers are expected to call this twice to handle commuted patterns.
157static Value *foldMulShl1(BinaryOperator &Mul, bool CommuteOperands,
158 InstCombiner::BuilderTy &Builder) {
159 Value *X = Mul.getOperand(0), *Y = Mul.getOperand(1);
160 if (CommuteOperands)
161 std::swap(X, Y);
162
163 const bool HasNSW = Mul.hasNoSignedWrap();
164 const bool HasNUW = Mul.hasNoUnsignedWrap();
165
166 // X * (1 << Z) --> X << Z
167 Value *Z;
168 if (match(Y, m_Shl(m_One(), m_Value(Z)))) {
169 bool PropagateNSW = HasNSW && cast<ShlOperator>(Y)->hasNoSignedWrap();
170 return Builder.CreateShl(X, Z, Mul.getName(), HasNUW, PropagateNSW);
171 }
172
173 // Similar to above, but an increment of the shifted value becomes an add:
174 // X * ((1 << Z) + 1) --> (X * (1 << Z)) + X --> (X << Z) + X
175 // This increases uses of X, so it may require a freeze, but that is still
176 // expected to be an improvement because it removes the multiply.
177 BinaryOperator *Shift;
178 if (match(Y, m_OneUse(m_Add(m_BinOp(Shift), m_One()))) &&
179 match(Shift, m_OneUse(m_Shl(m_One(), m_Value(Z))))) {
180 bool PropagateNSW = HasNSW && Shift->hasNoSignedWrap();
181 Value *FrX = X;
183 FrX = Builder.CreateFreeze(X, X->getName() + ".fr");
184 Value *Shl = Builder.CreateShl(FrX, Z, "mulshl", HasNUW, PropagateNSW);
185 return Builder.CreateAdd(Shl, FrX, Mul.getName(), HasNUW, PropagateNSW);
186 }
187
188 // Similar to above, but a decrement of the shifted value is disguised as
189 // 'not' and becomes a sub:
190 // X * (~(-1 << Z)) --> X * ((1 << Z) - 1) --> (X << Z) - X
191 // This increases uses of X, so it may require a freeze, but that is still
192 // expected to be an improvement because it removes the multiply.
194 Value *FrX = X;
196 FrX = Builder.CreateFreeze(X, X->getName() + ".fr");
197 Value *Shl = Builder.CreateShl(FrX, Z, "mulshl");
198 return Builder.CreateSub(Shl, FrX, Mul.getName());
199 }
200
201 return nullptr;
202}
203
205 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
206 if (Value *V =
207 simplifyMulInst(Op0, Op1, I.hasNoSignedWrap(), I.hasNoUnsignedWrap(),
208 SQ.getWithInstruction(&I)))
209 return replaceInstUsesWith(I, V);
210
212 return &I;
213
215 return X;
216
218 return Phi;
219
221 return replaceInstUsesWith(I, V);
222
223 Type *Ty = I.getType();
224 const unsigned BitWidth = Ty->getScalarSizeInBits();
225 const bool HasNSW = I.hasNoSignedWrap();
226 const bool HasNUW = I.hasNoUnsignedWrap();
227
228 // X * -1 --> 0 - X
229 if (match(Op1, m_AllOnes())) {
230 return HasNSW ? BinaryOperator::CreateNSWNeg(Op0)
232 }
233
234 // Also allow combining multiply instructions on vectors.
235 {
236 Value *NewOp;
237 Constant *C1, *C2;
238 const APInt *IVal;
239 if (match(&I, m_Mul(m_Shl(m_Value(NewOp), m_ImmConstant(C2)),
240 m_ImmConstant(C1))) &&
241 match(C1, m_APInt(IVal))) {
242 // ((X << C2)*C1) == (X * (C1 << C2))
243 Constant *Shl =
244 ConstantFoldBinaryOpOperands(Instruction::Shl, C1, C2, DL);
245 assert(Shl && "Constant folding of immediate constants failed");
246 BinaryOperator *Mul = cast<BinaryOperator>(I.getOperand(0));
247 BinaryOperator *BO = BinaryOperator::CreateMul(NewOp, Shl);
248 if (HasNUW && Mul->hasNoUnsignedWrap())
250 if (HasNSW && Mul->hasNoSignedWrap() && Shl->isNotMinSignedValue())
251 BO->setHasNoSignedWrap();
252 return BO;
253 }
254
255 if (match(&I, m_Mul(m_Value(NewOp), m_Constant(C1)))) {
256 // Replace X*(2^C) with X << C, where C is either a scalar or a vector.
258 BinaryOperator *Shl = BinaryOperator::CreateShl(NewOp, NewCst);
259
260 if (HasNUW)
262 if (HasNSW) {
263 const APInt *V;
264 if (match(NewCst, m_APInt(V)) && *V != V->getBitWidth() - 1)
265 Shl->setHasNoSignedWrap();
266 }
267
268 return Shl;
269 }
270 }
271 }
272
273 // mul (shr exact X, N), (2^N + 1) -> add (X, shr exact (X, N))
274 {
275 Value *NewOp;
276 const APInt *ShiftC;
277 const APInt *MulAP;
278 if (BitWidth > 2 &&
279 match(&I, m_Mul(m_Exact(m_Shr(m_Value(NewOp), m_APInt(ShiftC))),
280 m_APInt(MulAP))) &&
281 (*MulAP - 1).isPowerOf2() && *ShiftC == MulAP->logBase2()) {
282 Value *BinOp = Op0;
284
285 // mul nuw (ashr exact X, N) -> add nuw (X, lshr exact (X, N))
286 if (HasNUW && OpBO->getOpcode() == Instruction::AShr && OpBO->hasOneUse())
287 BinOp = Builder.CreateLShr(NewOp, ConstantInt::get(Ty, *ShiftC), "",
288 /*isExact=*/true);
289
290 auto *NewAdd = BinaryOperator::CreateAdd(NewOp, BinOp);
291 if (HasNSW && (HasNUW || OpBO->getOpcode() == Instruction::LShr ||
292 ShiftC->getZExtValue() < BitWidth - 1))
293 NewAdd->setHasNoSignedWrap(true);
294
295 NewAdd->setHasNoUnsignedWrap(HasNUW);
296 return NewAdd;
297 }
298 }
299
300 if (Op0->hasOneUse() && match(Op1, m_NegatedPower2())) {
301 // Interpret X * (-1<<C) as (-X) * (1<<C) and try to sink the negation.
302 // The "* (1<<C)" thus becomes a potential shifting opportunity.
303 if (Value *NegOp0 =
304 Negator::Negate(/*IsNegation*/ true, HasNSW, Op0, *this)) {
305 auto *Op1C = cast<Constant>(Op1);
306 return replaceInstUsesWith(
307 I, Builder.CreateMul(NegOp0, ConstantExpr::getNeg(Op1C), "",
308 /*HasNUW=*/false,
309 HasNSW && Op1C->isNotMinSignedValue()));
310 }
311
312 // Try to convert multiply of extended operand to narrow negate and shift
313 // for better analysis.
314 // This is valid if the shift amount (trailing zeros in the multiplier
315 // constant) clears more high bits than the bitwidth difference between
316 // source and destination types:
317 // ({z/s}ext X) * (-1<<C) --> (zext (-X)) << C
318 const APInt *NegPow2C;
319 Value *X;
320 if (match(Op0, m_ZExtOrSExt(m_Value(X))) &&
321 match(Op1, m_APIntAllowPoison(NegPow2C))) {
322 unsigned SrcWidth = X->getType()->getScalarSizeInBits();
323 unsigned ShiftAmt = NegPow2C->countr_zero();
324 if (ShiftAmt >= BitWidth - SrcWidth) {
325 Value *N = Builder.CreateNeg(X, X->getName() + ".neg");
326 Value *Z = Builder.CreateZExt(N, Ty, N->getName() + ".z");
327 return BinaryOperator::CreateShl(Z, ConstantInt::get(Ty, ShiftAmt));
328 }
329 }
330 }
331
332 if (Instruction *FoldedMul = foldBinOpIntoSelectOrPhi(I))
333 return FoldedMul;
334
335 if (Instruction *FoldedLogic = foldBinOpSelectBinOp(I))
336 return FoldedLogic;
337
338 if (Value *FoldedMul = foldMulSelectToNegate(I, Builder))
339 return replaceInstUsesWith(I, FoldedMul);
340
341 // (shl X, C1)*(select cond, C2, C3)--> X * (select cond, C2<<C1, C3<<C1)
342 // (mul X, C1)*(select cond, C2, C3)--> X * (select cond, C2*C1, C3*C1)
343 // (Includes commuted forms)
344
345 {
346 Value *NewOp, *Cond, *OtherValue;
347 Constant *C1, *C2, *C3;
348 Instruction *SI = nullptr;
349
350 if (match(&I, m_c_Mul(m_OneUse(m_Value(OtherValue)),
353 m_ImmConstant(C3)))))) &&
354 (match(OtherValue, m_Mul(m_Value(NewOp), m_ImmConstant(C1))) ||
355 match(OtherValue, m_Shl(m_Value(NewOp), m_ImmConstant(C1))))) {
356
357 auto *OtherInst = cast<OverflowingBinaryOperator>(OtherValue);
358 auto Opc = OtherInst->getOpcode();
359
362
363 if (NewTV && NewFV) {
364 Value *NewSel = Builder.CreateSelect(Cond, NewTV, NewFV, "", SI);
365 BinaryOperator *BO = BinaryOperator::CreateMul(NewOp, NewSel);
366
367 if (HasNUW && OtherInst->hasNoUnsignedWrap())
369 if (HasNSW && OtherInst->hasNoSignedWrap() &&
370 NewTV->isNotMinSignedValue() && NewFV->isNotMinSignedValue())
371 BO->setHasNoSignedWrap();
372
373 return BO;
374 }
375 }
376 }
377
378 // Simplify mul instructions with a constant RHS.
379 Constant *MulC;
380 if (match(Op1, m_ImmConstant(MulC))) {
381 // Canonicalize (X+C1)*MulC -> X*MulC+C1*MulC.
382 // Canonicalize (X|C1)*MulC -> X*MulC+C1*MulC.
383 Value *X;
384 Constant *C1;
386 // C1*MulC simplifies to a tidier constant.
387 Value *NewC = Builder.CreateMul(C1, MulC);
388 auto *BOp0 = cast<BinaryOperator>(Op0);
389 bool Op0NUW =
390 (BOp0->getOpcode() == Instruction::Or || BOp0->hasNoUnsignedWrap());
391 Value *NewMul = Builder.CreateMul(X, MulC);
392 auto *BO = BinaryOperator::CreateAdd(NewMul, NewC);
393 if (HasNUW && Op0NUW) {
394 // If NewMulBO is constant we also can set BO to nuw.
395 if (auto *NewMulBO = dyn_cast<BinaryOperator>(NewMul))
396 NewMulBO->setHasNoUnsignedWrap();
397 BO->setHasNoUnsignedWrap();
398 }
399 return BO;
400 }
401 }
402
403 // abs(X) * abs(X) -> X * X
404 Value *X;
405 if (Op0 == Op1 && match(Op0, m_Intrinsic<Intrinsic::abs>(m_Value(X))))
406 return BinaryOperator::CreateMul(X, X);
407
408 {
409 Value *Y;
410 // abs(X) * abs(Y) -> abs(X * Y)
411 if (I.hasNoSignedWrap() &&
412 match(Op0,
415 return replaceInstUsesWith(
416 I, Builder.CreateBinaryIntrinsic(Intrinsic::abs,
417 Builder.CreateNSWMul(X, Y),
418 Builder.getTrue()));
419 }
420
421 // -X * C --> X * -C
422 Value *Y;
423 Constant *Op1C;
424 if (match(Op0, m_Neg(m_Value(X))) && match(Op1, m_Constant(Op1C)))
425 return BinaryOperator::CreateMul(X, ConstantExpr::getNeg(Op1C));
426
427 // -X * -Y --> X * Y
428 if (match(Op0, m_Neg(m_Value(X))) && match(Op1, m_Neg(m_Value(Y)))) {
429 auto *NewMul = BinaryOperator::CreateMul(X, Y);
430 if (HasNSW && cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap() &&
432 NewMul->setHasNoSignedWrap();
433 return NewMul;
434 }
435
436 // -X * Y --> -(X * Y)
437 // X * -Y --> -(X * Y)
439 return BinaryOperator::CreateNeg(Builder.CreateMul(X, Y));
440
441 // (-X * Y) * -X --> (X * Y) * X
442 // (-X << Y) * -X --> (X << Y) * X
443 if (match(Op1, m_Neg(m_Value(X)))) {
444 if (Value *NegOp0 = Negator::Negate(false, /*IsNSW*/ false, Op0, *this))
445 return BinaryOperator::CreateMul(NegOp0, X);
446 }
447
448 if (Op0->hasOneUse()) {
449 // (mul (div exact X, C0), C1)
450 // -> (div exact X, C0 / C1)
451 // iff C0 % C1 == 0 and X / (C0 / C1) doesn't create UB.
452 const APInt *C1;
453 auto UDivCheck = [&C1](const APInt &C) { return C.urem(*C1).isZero(); };
454 auto SDivCheck = [&C1](const APInt &C) {
455 APInt Quot, Rem;
456 APInt::sdivrem(C, *C1, Quot, Rem);
457 return Rem.isZero() && !Quot.isAllOnes();
458 };
459 if (match(Op1, m_APInt(C1)) &&
460 (match(Op0, m_Exact(m_UDiv(m_Value(X), m_CheckedInt(UDivCheck)))) ||
461 match(Op0, m_Exact(m_SDiv(m_Value(X), m_CheckedInt(SDivCheck)))))) {
462 auto BOpc = cast<BinaryOperator>(Op0)->getOpcode();
464 BOpc, X,
465 Builder.CreateBinOp(BOpc, cast<BinaryOperator>(Op0)->getOperand(1),
466 Op1));
467 }
468 }
469
470 // (X / Y) * Y = X - (X % Y)
471 // (X / Y) * -Y = (X % Y) - X
472 {
473 Value *Y = Op1;
475 if (!Div || (Div->getOpcode() != Instruction::UDiv &&
476 Div->getOpcode() != Instruction::SDiv)) {
477 Y = Op0;
479 }
480 Value *Neg = dyn_castNegVal(Y);
481 if (Div && Div->hasOneUse() &&
482 (Div->getOperand(1) == Y || Div->getOperand(1) == Neg) &&
483 (Div->getOpcode() == Instruction::UDiv ||
484 Div->getOpcode() == Instruction::SDiv)) {
485 Value *X = Div->getOperand(0), *DivOp1 = Div->getOperand(1);
486
487 // If the division is exact, X % Y is zero, so we end up with X or -X.
488 if (Div->isExact()) {
489 if (DivOp1 == Y)
490 return replaceInstUsesWith(I, X);
492 }
493
494 auto RemOpc = Div->getOpcode() == Instruction::UDiv ? Instruction::URem
495 : Instruction::SRem;
496 // X must be frozen because we are increasing its number of uses.
497 Value *XFreeze = X;
499 XFreeze = Builder.CreateFreeze(X, X->getName() + ".fr");
500 Value *Rem = Builder.CreateBinOp(RemOpc, XFreeze, DivOp1);
501 if (DivOp1 == Y)
502 return BinaryOperator::CreateSub(XFreeze, Rem);
503 return BinaryOperator::CreateSub(Rem, XFreeze);
504 }
505 }
506
507 // Fold the following two scenarios:
508 // 1) i1 mul -> i1 and.
509 // 2) X * Y --> X & Y, iff X, Y can be only {0,1}.
510 // Note: We could use known bits to generalize this and related patterns with
511 // shifts/truncs
512 if (Ty->isIntOrIntVectorTy(1) ||
513 (match(Op0, m_And(m_Value(), m_One())) &&
514 match(Op1, m_And(m_Value(), m_One()))))
515 return BinaryOperator::CreateAnd(Op0, Op1);
516
517 if (Value *R = foldMulShl1(I, /* CommuteOperands */ false, Builder))
518 return replaceInstUsesWith(I, R);
519 if (Value *R = foldMulShl1(I, /* CommuteOperands */ true, Builder))
520 return replaceInstUsesWith(I, R);
521
522 // (zext bool X) * (zext bool Y) --> zext (and X, Y)
523 // (sext bool X) * (sext bool Y) --> zext (and X, Y)
524 // Note: -1 * -1 == 1 * 1 == 1 (if the extends match, the result is the same)
525 if (((match(Op0, m_ZExt(m_Value(X))) && match(Op1, m_ZExt(m_Value(Y)))) ||
526 (match(Op0, m_SExt(m_Value(X))) && match(Op1, m_SExt(m_Value(Y))))) &&
527 X->getType()->isIntOrIntVectorTy(1) && X->getType() == Y->getType() &&
528 (Op0->hasOneUse() || Op1->hasOneUse() || X == Y)) {
529 Value *And = Builder.CreateAnd(X, Y, "mulbool");
530 return CastInst::Create(Instruction::ZExt, And, Ty);
531 }
532 // (sext bool X) * (zext bool Y) --> sext (and X, Y)
533 // (zext bool X) * (sext bool Y) --> sext (and X, Y)
534 // Note: -1 * 1 == 1 * -1 == -1
535 if (((match(Op0, m_SExt(m_Value(X))) && match(Op1, m_ZExt(m_Value(Y)))) ||
536 (match(Op0, m_ZExt(m_Value(X))) && match(Op1, m_SExt(m_Value(Y))))) &&
537 X->getType()->isIntOrIntVectorTy(1) && X->getType() == Y->getType() &&
538 (Op0->hasOneUse() || Op1->hasOneUse())) {
539 Value *And = Builder.CreateAnd(X, Y, "mulbool");
540 return CastInst::Create(Instruction::SExt, And, Ty);
541 }
542
543 // (zext bool X) * Y --> X ? Y : 0
544 // Y * (zext bool X) --> X ? Y : 0
545 if (match(Op0, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
546 return createSelectInstWithUnknownProfile(X, Op1,
548 if (match(Op1, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
549 return createSelectInstWithUnknownProfile(X, Op0,
551
552 // mul (sext X), Y -> select X, -Y, 0
553 // mul Y, (sext X) -> select X, -Y, 0
554 if (match(&I, m_c_Mul(m_OneUse(m_SExt(m_Value(X))), m_Value(Y))) &&
555 X->getType()->isIntOrIntVectorTy(1))
556 return createSelectInstWithUnknownProfile(
557 X, Builder.CreateNeg(Y, "", I.hasNoSignedWrap()),
559
560 Constant *ImmC;
561 if (match(Op1, m_ImmConstant(ImmC))) {
562 // (sext bool X) * C --> X ? -C : 0
563 if (match(Op0, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
564 Constant *NegC = ConstantExpr::getNeg(ImmC);
565 return createSelectInstWithUnknownProfile(X, NegC,
567 }
568
569 // (ashr i32 X, 31) * C --> (X < 0) ? -C : 0
570 const APInt *C;
571 if (match(Op0, m_OneUse(m_AShr(m_Value(X), m_APInt(C)))) &&
572 *C == C->getBitWidth() - 1) {
573 Constant *NegC = ConstantExpr::getNeg(ImmC);
574 Value *IsNeg = Builder.CreateIsNeg(X, "isneg");
575 return createSelectInstWithUnknownProfile(IsNeg, NegC,
577 }
578 }
579
580 // (lshr X, 31) * Y --> (X < 0) ? Y : 0
581 // TODO: We are not checking one-use because the elimination of the multiply
582 // is better for analysis?
583 const APInt *C;
584 if (match(&I, m_c_BinOp(m_LShr(m_Value(X), m_APInt(C)), m_Value(Y))) &&
585 *C == C->getBitWidth() - 1) {
586 Value *IsNeg = Builder.CreateIsNeg(X, "isneg");
587 return createSelectInstWithUnknownProfile(IsNeg, Y,
589 }
590
591 // (and X, 1) * Y --> (trunc X) ? Y : 0
592 if (match(&I, m_c_BinOp(m_OneUse(m_And(m_Value(X), m_One())), m_Value(Y)))) {
593 Value *Tr = Builder.CreateTrunc(X, CmpInst::makeCmpResultType(Ty));
594 return createSelectInstWithUnknownProfile(Tr, Y,
596 }
597
598 // ((ashr X, 31) | 1) * X --> abs(X)
599 // X * ((ashr X, 31) | 1) --> abs(X)
602 m_One()),
603 m_Deferred(X)))) {
604 Value *Abs = Builder.CreateBinaryIntrinsic(
605 Intrinsic::abs, X, ConstantInt::getBool(I.getContext(), HasNSW));
606 Abs->takeName(&I);
607 return replaceInstUsesWith(I, Abs);
608 }
609
610 if (Instruction *Ext = narrowMathIfNoOverflow(I))
611 return Ext;
612
614 return Res;
615
616 // (mul Op0 Op1):
617 // if Log2(Op0) folds away ->
618 // (shl Op1, Log2(Op0))
619 // if Log2(Op1) folds away ->
620 // (shl Op0, Log2(Op1))
621 if (Value *Res = tryGetLog2(Op0, /*AssumeNonZero=*/false)) {
622 BinaryOperator *Shl = BinaryOperator::CreateShl(Op1, Res);
623 // We can only propegate nuw flag.
624 Shl->setHasNoUnsignedWrap(HasNUW);
625 return Shl;
626 }
627 if (Value *Res = tryGetLog2(Op1, /*AssumeNonZero=*/false)) {
628 BinaryOperator *Shl = BinaryOperator::CreateShl(Op0, Res);
629 // We can only propegate nuw flag.
630 Shl->setHasNoUnsignedWrap(HasNUW);
631 return Shl;
632 }
633
634 bool Changed = false;
635 if (!HasNSW && willNotOverflowSignedMul(Op0, Op1, I)) {
636 Changed = true;
637 I.setHasNoSignedWrap(true);
638 }
639
640 if (!HasNUW && willNotOverflowUnsignedMul(Op0, Op1, I, I.hasNoSignedWrap())) {
641 Changed = true;
642 I.setHasNoUnsignedWrap(true);
643 }
644
645 return Changed ? &I : nullptr;
646}
647
648Instruction *InstCombinerImpl::foldFPSignBitOps(BinaryOperator &I) {
649 BinaryOperator::BinaryOps Opcode = I.getOpcode();
650 assert((Opcode == Instruction::FMul || Opcode == Instruction::FDiv) &&
651 "Expected fmul or fdiv");
652
653 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
654 Value *X, *Y;
655
656 // -X * -Y --> X * Y
657 // -X / -Y --> X / Y
658 // TODO: Confirm whether m_FNegOrFSubNegZero is correct.
659 if (match(Op0, m_FNegOrFSubNegZero(m_Value(X))) &&
661 return BinaryOperator::CreateWithCopiedFlags(Opcode, X, Y, &I);
662
663 // fabs(X) * fabs(X) -> X * X
664 // fabs(X) / fabs(X) -> X / X
665 if (Op0 == Op1 && match(Op0, m_FAbs(m_Value(X))))
666 return BinaryOperator::CreateWithCopiedFlags(Opcode, X, X, &I);
667
668 // fabs(X) * fabs(Y) --> fabs(X * Y)
669 // fabs(X) / fabs(Y) --> fabs(X / Y)
670 if (match(Op0, m_FAbs(m_Value(X))) && match(Op1, m_FAbs(m_Value(Y))) &&
671 (Op0->hasOneUse() || Op1->hasOneUse())) {
672 Value *XY = Builder.CreateBinOpFMF(Opcode, X, Y, &I);
673 Value *Fabs = Builder.CreateFAbs(XY, &I, I.getName());
674 return replaceInstUsesWith(I, Fabs);
675 }
676
677 return nullptr;
678}
679
681 auto createPowiExpr = [](BinaryOperator &I, InstCombinerImpl &IC, Value *X,
682 Value *Y, Value *Z) {
683 InstCombiner::BuilderTy &Builder = IC.Builder;
684 Value *YZ = Builder.CreateNSWAdd(Y, Z);
685 Value *NewPow = Builder.CreateIntrinsic(
686 Intrinsic::powi, {X->getType(), YZ->getType()}, {X, YZ}, &I);
687
688 return NewPow;
689 };
690
691 Value *X, *Y, *Z;
692 unsigned Opcode = I.getOpcode();
693 assert((Opcode == Instruction::FMul || Opcode == Instruction::FDiv) &&
694 "Unexpected opcode");
695
696 // powi(X, Y) * X --> powi(X, Y+1)
697 // X * powi(X, Y) --> powi(X, Y+1)
699 m_Value(X), m_Value(Y)))),
700 m_Deferred(X)))) {
701 Constant *One = ConstantInt::get(Y->getType(), 1);
702 if (willNotOverflowSignedAdd(Y, One, I)) {
703 Value *NewPow = createPowiExpr(I, *this, X, Y, One);
704 return replaceInstUsesWith(I, NewPow);
705 }
706 }
707
708 // powi(x, y) * powi(x, z) -> powi(x, y + z)
709 Value *Op0 = I.getOperand(0);
710 Value *Op1 = I.getOperand(1);
711 if (Opcode == Instruction::FMul && I.isOnlyUserOfAnyOperand() &&
715 m_Value(Z)))) &&
716 Y->getType() == Z->getType() && willNotOverflowSignedAdd(Y, Z, I)) {
717 Value *NewPow = createPowiExpr(I, *this, X, Y, Z);
718 return replaceInstUsesWith(I, NewPow);
719 }
720
721 if (Opcode == Instruction::FDiv && I.hasAllowReassoc() && I.hasNoNaNs()) {
722 // powi(X, Y) / X --> powi(X, Y-1)
723 // This is legal when (Y - 1) can't wraparound, in which case reassoc and
724 // nnan are required.
725 // TODO: Multi-use may be also better off creating Powi(x,y-1)
727 m_Specific(Op1), m_Value(Y))))) &&
728 willNotOverflowSignedSub(Y, ConstantInt::get(Y->getType(), 1), I)) {
729 Constant *NegOne = ConstantInt::getAllOnesValue(Y->getType());
730 Value *NewPow = createPowiExpr(I, *this, Op1, Y, NegOne);
731 return replaceInstUsesWith(I, NewPow);
732 }
733
734 // powi(X, Y) / (X * Z) --> powi(X, Y-1) / Z
735 // This is legal when (Y - 1) can't wraparound, in which case reassoc and
736 // nnan are required.
737 // TODO: Multi-use may be also better off creating Powi(x,y-1)
739 m_Value(X), m_Value(Y))))) &&
741 willNotOverflowSignedSub(Y, ConstantInt::get(Y->getType(), 1), I)) {
742 Constant *NegOne = ConstantInt::getAllOnesValue(Y->getType());
743 auto *NewPow = createPowiExpr(I, *this, X, Y, NegOne);
744 return BinaryOperator::CreateFDivFMF(NewPow, Z, &I);
745 }
746 }
747
748 return nullptr;
749}
750
751// If we have the following pattern,
752// X = 1.0/sqrt(a)
753// R1 = X * X
754// R2 = a/sqrt(a)
755// then this method collects all the instructions that match R1 and R2.
759 Value *A;
760 if (match(Div, m_FDiv(m_FPOne(), m_Sqrt(m_Value(A)))) ||
762 for (User *U : Div->users()) {
765 R1.insert(I);
766 }
767
768 CallInst *CI = cast<CallInst>(Div->getOperand(1));
769 for (User *U : CI->users()) {
772 R2.insert(I);
773 }
774 }
775 return !R1.empty() && !R2.empty();
776}
777
778// Check legality for transforming
779// x = 1.0/sqrt(a)
780// r1 = x * x;
781// r2 = a/sqrt(a);
782//
783// TO
784//
785// r1 = 1/a
786// r2 = sqrt(a)
787// x = r1 * r2
788// This transform works only when 'a' is known positive.
792 // Check if the required pattern for the transformation exists.
793 if (!getFSqrtDivOptPattern(X, R1, R2))
794 return false;
795
796 BasicBlock *BBx = X->getParent();
797 BasicBlock *BBr1 = (*R1.begin())->getParent();
798 BasicBlock *BBr2 = (*R2.begin())->getParent();
799
800 CallInst *FSqrt = cast<CallInst>(X->getOperand(1));
801 if (!FSqrt->hasAllowReassoc() || !FSqrt->hasNoNaNs() ||
802 !FSqrt->hasNoSignedZeros() || !FSqrt->hasNoInfs())
803 return false;
804
805 // We change x = 1/sqrt(a) to x = sqrt(a) * 1/a . This change isn't allowed
806 // by recip fp as it is strictly meant to transform ops of type a/b to
807 // a * 1/b. So, this can be considered as algebraic rewrite and reassoc flag
808 // has been used(rather abused)in the past for algebraic rewrites.
809 if (!X->hasAllowReassoc() || !X->hasAllowReciprocal() || !X->hasNoInfs())
810 return false;
811
812 // Check the constraints on X, R1 and R2 combined.
813 // fdiv instruction and one of the multiplications must reside in the same
814 // block. If not, the optimized code may execute more ops than before and
815 // this may hamper the performance.
816 if (BBx != BBr1 && BBx != BBr2)
817 return false;
818
819 // Check the constraints on instructions in R1.
820 if (any_of(R1, [BBr1](Instruction *I) {
821 // When you have multiple instructions residing in R1 and R2
822 // respectively, it's difficult to generate combinations of (R1,R2) and
823 // then check if we have the required pattern. So, for now, just be
824 // conservative.
825 return (I->getParent() != BBr1 || !I->hasAllowReassoc());
826 }))
827 return false;
828
829 // Check the constraints on instructions in R2.
830 return all_of(R2, [BBr2](Instruction *I) {
831 // When you have multiple instructions residing in R1 and R2
832 // respectively, it's difficult to generate combination of (R1,R2) and
833 // then check if we have the required pattern. So, for now, just be
834 // conservative.
835 return (I->getParent() == BBr2 && I->hasAllowReassoc());
836 });
837}
838
840 Value *Op0 = I.getOperand(0);
841 Value *Op1 = I.getOperand(1);
842 Value *X, *Y;
843 Constant *C;
844 BinaryOperator *Op0BinOp;
845
846 // Reassociate constant RHS with another constant to form constant
847 // expression.
848 if (match(Op1, m_Constant(C)) && C->isFiniteNonZeroFP() &&
849 match(Op0, m_AllowReassoc(m_BinOp(Op0BinOp)))) {
850 // Everything in this scope folds I with Op0, intersecting their FMF.
851 FastMathFlags FMF = I.getFastMathFlags() & Op0BinOp->getFastMathFlags();
852 Constant *C1;
853 if (match(Op0, m_OneUse(m_FDiv(m_Constant(C1), m_Value(X))))) {
854 // (C1 / X) * C --> (C * C1) / X
855 Constant *CC1 =
856 ConstantFoldBinaryOpOperands(Instruction::FMul, C, C1, DL);
857 if (CC1 && CC1->isNormalFP())
858 return BinaryOperator::CreateFDivFMF(CC1, X, FMF);
859 }
860 if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) {
861 // FIXME: This seems like it should also be checking for arcp
862 // (X / C1) * C --> X * (C / C1)
863 Constant *CDivC1 =
864 ConstantFoldBinaryOpOperands(Instruction::FDiv, C, C1, DL);
865 if (CDivC1 && CDivC1->isNormalFP())
866 return BinaryOperator::CreateFMulFMF(X, CDivC1, FMF);
867
868 // If the constant was a denormal, try reassociating differently.
869 // (X / C1) * C --> X / (C1 / C)
870 Constant *C1DivC =
871 ConstantFoldBinaryOpOperands(Instruction::FDiv, C1, C, DL);
872 if (C1DivC && Op0->hasOneUse() && C1DivC->isNormalFP())
873 return BinaryOperator::CreateFDivFMF(X, C1DivC, FMF);
874 }
875
876 // We do not need to match 'fadd C, X' and 'fsub X, C' because they are
877 // canonicalized to 'fadd X, C'. Distributing the multiply may allow
878 // further folds and (X * C) + C2 is 'fma'.
879 if (match(Op0, m_OneUse(m_FAdd(m_Value(X), m_Constant(C1))))) {
880 // (X + C1) * C --> (X * C) + (C * C1)
881 if (Constant *CC1 =
882 ConstantFoldBinaryOpOperands(Instruction::FMul, C, C1, DL)) {
883 Value *XC = Builder.CreateFMulFMF(X, C, FMF);
884 return BinaryOperator::CreateFAddFMF(XC, CC1, FMF);
885 }
886 }
887 if (match(Op0, m_OneUse(m_FSub(m_Constant(C1), m_Value(X))))) {
888 // (C1 - X) * C --> (C * C1) - (X * C)
889 if (Constant *CC1 =
890 ConstantFoldBinaryOpOperands(Instruction::FMul, C, C1, DL)) {
891 Value *XC = Builder.CreateFMulFMF(X, C, FMF);
892 return BinaryOperator::CreateFSubFMF(CC1, XC, FMF);
893 }
894 }
895 }
896
897 Value *Z;
898 if (match(&I,
900 m_Value(Z)))) {
901 BinaryOperator *DivOp = cast<BinaryOperator>(((Z == Op0) ? Op1 : Op0));
902 FastMathFlags FMF = I.getFastMathFlags() & DivOp->getFastMathFlags();
903 if (FMF.allowReassoc()) {
904 // Sink division: (X / Y) * Z --> (X * Z) / Y
905 auto *NewFMul = Builder.CreateFMulFMF(X, Z, FMF);
906 return BinaryOperator::CreateFDivFMF(NewFMul, Y, FMF);
907 }
908 }
909
910 // sqrt(X) * sqrt(Y) -> sqrt(X * Y)
911 // nnan disallows the possibility of returning a number if both operands are
912 // negative (in that case, we should return NaN).
913 if (I.hasNoNaNs() && match(Op0, m_OneUse(m_Sqrt(m_Value(X)))) &&
914 match(Op1, m_OneUse(m_Sqrt(m_Value(Y))))) {
915 Value *XY = Builder.CreateFMulFMF(X, Y, &I);
916 Value *Sqrt = Builder.CreateUnaryIntrinsic(Intrinsic::sqrt, XY, &I);
917 return replaceInstUsesWith(I, Sqrt);
918 }
919
920 // The following transforms are done irrespective of the number of uses
921 // for the expression "1.0/sqrt(X)".
922 // 1) 1.0/sqrt(X) * X -> X/sqrt(X)
923 // 2) X * 1.0/sqrt(X) -> X/sqrt(X)
924 // We always expect the backend to reduce X/sqrt(X) to sqrt(X), if it
925 // has the necessary (reassoc) fast-math-flags.
926 if (I.hasNoSignedZeros() &&
927 match(Op0, (m_FDiv(m_SpecificFP(1.0), m_Value(Y)))) &&
928 match(Y, m_Sqrt(m_Value(X))) && Op1 == X)
930 if (I.hasNoSignedZeros() &&
931 match(Op1, (m_FDiv(m_SpecificFP(1.0), m_Value(Y)))) &&
932 match(Y, m_Sqrt(m_Value(X))) && Op0 == X)
934
935 // Like the similar transform in instsimplify, this requires 'nsz' because
936 // sqrt(-0.0) = -0.0, and -0.0 * -0.0 does not simplify to -0.0.
937 if (I.hasNoNaNs() && I.hasNoSignedZeros() && Op0 == Op1 && Op0->hasNUses(2)) {
938 // Peek through fdiv to find squaring of square root:
939 // (X / sqrt(Y)) * (X / sqrt(Y)) --> (X * X) / Y
940 if (match(Op0, m_FDiv(m_Value(X), m_Sqrt(m_Value(Y))))) {
941 Value *XX = Builder.CreateFMulFMF(X, X, &I);
942 return BinaryOperator::CreateFDivFMF(XX, Y, &I);
943 }
944 // (sqrt(Y) / X) * (sqrt(Y) / X) --> Y / (X * X)
945 if (match(Op0, m_FDiv(m_Sqrt(m_Value(Y)), m_Value(X)))) {
946 Value *XX = Builder.CreateFMulFMF(X, X, &I);
947 return BinaryOperator::CreateFDivFMF(Y, XX, &I);
948 }
949 }
950
951 // pow(X, Y) * X --> pow(X, Y+1)
952 // X * pow(X, Y) --> pow(X, Y+1)
954 m_Value(Y))),
955 m_Deferred(X)))) {
956 Value *Y1 = Builder.CreateFAddFMF(Y, ConstantFP::get(I.getType(), 1.0), &I);
957 Value *Pow = Builder.CreateBinaryIntrinsic(Intrinsic::pow, X, Y1, &I);
958 return replaceInstUsesWith(I, Pow);
959 }
960
961 if (Instruction *FoldedPowi = foldPowiReassoc(I))
962 return FoldedPowi;
963
964 if (I.isOnlyUserOfAnyOperand()) {
965 // pow(X, Y) * pow(X, Z) -> pow(X, Y + Z)
968 auto *YZ = Builder.CreateFAddFMF(Y, Z, &I);
969 auto *NewPow = Builder.CreateBinaryIntrinsic(Intrinsic::pow, X, YZ, &I);
970 return replaceInstUsesWith(I, NewPow);
971 }
972 // pow(X, Y) * pow(Z, Y) -> pow(X * Z, Y)
975 auto *XZ = Builder.CreateFMulFMF(X, Z, &I);
976 auto *NewPow = Builder.CreateBinaryIntrinsic(Intrinsic::pow, XZ, Y, &I);
977 return replaceInstUsesWith(I, NewPow);
978 }
979
980 // exp(X) * exp(Y) -> exp(X + Y)
983 Value *XY = Builder.CreateFAddFMF(X, Y, &I);
984 Value *Exp = Builder.CreateUnaryIntrinsic(Intrinsic::exp, XY, &I);
985 return replaceInstUsesWith(I, Exp);
986 }
987
988 // exp2(X) * exp2(Y) -> exp2(X + Y)
991 Value *XY = Builder.CreateFAddFMF(X, Y, &I);
992 Value *Exp2 = Builder.CreateUnaryIntrinsic(Intrinsic::exp2, XY, &I);
993 return replaceInstUsesWith(I, Exp2);
994 }
995 }
996
997 // (X*Y) * X => (X*X) * Y where Y != X
998 // The purpose is two-fold:
999 // 1) to form a power expression (of X).
1000 // 2) potentially shorten the critical path: After transformation, the
1001 // latency of the instruction Y is amortized by the expression of X*X,
1002 // and therefore Y is in a "less critical" position compared to what it
1003 // was before the transformation.
1004 if (match(Op0, m_OneUse(m_c_FMul(m_Specific(Op1), m_Value(Y)))) && Op1 != Y) {
1005 Value *XX = Builder.CreateFMulFMF(Op1, Op1, &I);
1006 return BinaryOperator::CreateFMulFMF(XX, Y, &I);
1007 }
1008 if (match(Op1, m_OneUse(m_c_FMul(m_Specific(Op0), m_Value(Y)))) && Op0 != Y) {
1009 Value *XX = Builder.CreateFMulFMF(Op0, Op0, &I);
1010 return BinaryOperator::CreateFMulFMF(XX, Y, &I);
1011 }
1012
1013 return nullptr;
1014}
1015
1017 if (Value *V = simplifyFMulInst(I.getOperand(0), I.getOperand(1),
1018 I.getFastMathFlags(),
1019 SQ.getWithInstruction(&I)))
1020 return replaceInstUsesWith(I, V);
1021
1023 return &I;
1024
1026 return X;
1027
1029 return Phi;
1030
1031 if (Instruction *FoldedMul = foldBinOpIntoSelectOrPhi(I))
1032 return FoldedMul;
1033
1034 if (Value *FoldedMul = foldMulSelectToNegate(I, Builder))
1035 return replaceInstUsesWith(I, FoldedMul);
1036
1037 if (Instruction *R = foldFPSignBitOps(I))
1038 return R;
1039
1040 if (Instruction *R = foldFBinOpOfIntCasts(I))
1041 return R;
1042
1043 // X * -1.0 --> -X
1044 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1045 if (match(Op1, m_SpecificFP(-1.0)))
1046 return UnaryOperator::CreateFNegFMF(Op0, &I);
1047
1048 // -X * C --> X * -C
1049 Value *X, *Y;
1050 Constant *C;
1051 // TODO: Confirm whether m_FNegOrFSubNegZero is correct.
1052 if (match(Op0, m_FNegOrFSubNegZero(m_Value(X))) && match(Op1, m_Constant(C)))
1053 if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL))
1054 return BinaryOperator::CreateFMulFMF(X, NegC, &I);
1055
1056 if (I.hasNoNaNs() && I.hasNoSignedZeros()) {
1057 // (uitofp bool X) * Y --> X ? Y : 0
1058 // Y * (uitofp bool X) --> X ? Y : 0
1059 // Note INF * 0 is NaN.
1060 if (match(Op0, m_UIToFP(m_Value(X))) &&
1061 X->getType()->isIntOrIntVectorTy(1)) {
1062 auto *SI = createSelectInstWithUnknownProfile(
1063 X, Op1, ConstantFP::get(I.getType(), 0.0));
1064 SI->copyFastMathFlags(I.getFastMathFlags());
1065 return SI;
1066 }
1067 if (match(Op1, m_UIToFP(m_Value(X))) &&
1068 X->getType()->isIntOrIntVectorTy(1)) {
1069 auto *SI = createSelectInstWithUnknownProfile(
1070 X, Op0, ConstantFP::get(I.getType(), 0.0));
1071 SI->copyFastMathFlags(I.getFastMathFlags());
1072 return SI;
1073 }
1074 }
1075
1076 // (select A, B, C) * (select A, D, E) --> select A, (B*D), (C*E)
1077 if (Value *V = SimplifySelectsFeedingBinaryOp(I, Op0, Op1))
1078 return replaceInstUsesWith(I, V);
1079
1080 if (I.hasAllowReassoc())
1081 if (Instruction *FoldedMul = foldFMulReassoc(I))
1082 return FoldedMul;
1083
1084 // log2(X * 0.5) * Y = log2(X) * Y - Y
1085 if (I.isFast()) {
1086 IntrinsicInst *Log2 = nullptr;
1088 m_OneUse(m_FMul(m_Value(X), m_SpecificFP(0.5))))))) {
1090 Y = Op1;
1091 }
1093 m_OneUse(m_FMul(m_Value(X), m_SpecificFP(0.5))))))) {
1095 Y = Op0;
1096 }
1097 if (Log2) {
1098 Value *Log2 = Builder.CreateUnaryIntrinsic(Intrinsic::log2, X, &I);
1099 Value *LogXTimesY = Builder.CreateFMulFMF(Log2, Y, &I);
1100 return BinaryOperator::CreateFSubFMF(LogXTimesY, Y, &I);
1101 }
1102 }
1103
1104 // Simplify FMUL recurrences starting with 0.0 to 0.0 if nnan and nsz are set.
1105 // Given a phi node with entry value as 0 and it used in fmul operation,
1106 // we can replace fmul with 0 safely and eleminate loop operation.
1107 PHINode *PN = nullptr;
1108 Value *Start = nullptr, *Step = nullptr;
1109 if (matchSimpleRecurrence(&I, PN, Start, Step) && I.hasNoNaNs() &&
1110 I.hasNoSignedZeros() && match(Start, m_Zero()))
1111 return replaceInstUsesWith(I, Start);
1112
1113 // minimum(X, Y) * maximum(X, Y) => X * Y.
1114 if (match(&I,
1117 m_Deferred(Y))))) {
1119 // We cannot preserve ninf if nnan flag is not set.
1120 // If X is NaN and Y is Inf then in original program we had NaN * NaN,
1121 // while in optimized version NaN * Inf and this is a poison with ninf flag.
1122 if (!Result->hasNoNaNs())
1123 Result->setHasNoInfs(false);
1124 return Result;
1125 }
1126
1127 // tan(X) * cos(X) -> sin(X)
1128 if (I.hasAllowContract() &&
1129 match(&I,
1132 Value *Sin = Builder.CreateUnaryIntrinsic(Intrinsic::sin, X, &I);
1133 if (auto *Metadata = I.getMetadata(LLVMContext::MD_fpmath))
1134 if (auto *SinI = dyn_cast<Instruction>(Sin))
1135 SinI->setMetadata(LLVMContext::MD_fpmath, Metadata);
1136 return replaceInstUsesWith(I, Sin);
1137 }
1138
1139 // X * ldexp(1.0, Y) -> ldexp(X, Y)
1141 m_Value(X),
1143 m_FPOne(), m_Value(Y))))))))
1144 return replaceInstUsesWith(
1145 I, Builder.CreateIntrinsic(Intrinsic::ldexp,
1146 {X->getType(), Y->getType()}, {X, Y}, &I));
1147
1149 return &I;
1150
1151 return nullptr;
1152}
1153
1154/// Fold a divide or remainder with a select instruction divisor when one of the
1155/// select operands is zero. In that case, we can use the other select operand
1156/// because div/rem by zero is undefined.
1158 SelectInst *SI = dyn_cast<SelectInst>(I.getOperand(1));
1159 if (!SI)
1160 return false;
1161
1162 int NonNullOperand;
1163 if (match(SI->getTrueValue(), m_Zero()))
1164 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
1165 NonNullOperand = 2;
1166 else if (match(SI->getFalseValue(), m_Zero()))
1167 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
1168 NonNullOperand = 1;
1169 else
1170 return false;
1171
1172 // Change the div/rem to use 'Y' instead of the select.
1173 replaceOperand(I, 1, SI->getOperand(NonNullOperand));
1174
1175 // Okay, we know we replace the operand of the div/rem with 'Y' with no
1176 // problem. However, the select, or the condition of the select may have
1177 // multiple uses. Based on our knowledge that the operand must be non-zero,
1178 // propagate the known value for the select into other uses of it, and
1179 // propagate a known value of the condition into its other users.
1180
1181 // If the select and condition only have a single use, don't bother with this,
1182 // early exit.
1183 Value *SelectCond = SI->getCondition();
1184 if (SI->use_empty() && SelectCond->hasOneUse())
1185 return true;
1186
1187 // Scan the current block backward, looking for other uses of SI.
1188 BasicBlock::iterator BBI = I.getIterator(), BBFront = I.getParent()->begin();
1189 Type *CondTy = SelectCond->getType();
1190 while (BBI != BBFront) {
1191 --BBI;
1192 // If we found an instruction that we can't assume will return, so
1193 // information from below it cannot be propagated above it.
1195 break;
1196
1197 // Replace uses of the select or its condition with the known values.
1198 for (Use &Op : BBI->operands()) {
1199 if (Op == SI) {
1200 replaceUse(Op, SI->getOperand(NonNullOperand));
1201 Worklist.push(&*BBI);
1202 } else if (Op == SelectCond) {
1203 replaceUse(Op, NonNullOperand == 1 ? ConstantInt::getTrue(CondTy)
1204 : ConstantInt::getFalse(CondTy));
1205 Worklist.push(&*BBI);
1206 }
1207 }
1208
1209 // If we past the instruction, quit looking for it.
1210 if (&*BBI == SI)
1211 SI = nullptr;
1212 if (&*BBI == SelectCond)
1213 SelectCond = nullptr;
1214
1215 // If we ran out of things to eliminate, break out of the loop.
1216 if (!SelectCond && !SI)
1217 break;
1218
1219 }
1220 return true;
1221}
1222
1223/// True if the multiply can not be expressed in an int this size.
1224static bool multiplyOverflows(const APInt &C1, const APInt &C2, APInt &Product,
1225 bool IsSigned) {
1226 bool Overflow;
1227 Product = IsSigned ? C1.smul_ov(C2, Overflow) : C1.umul_ov(C2, Overflow);
1228 return Overflow;
1229}
1230
1231/// True if C1 is a multiple of C2. Quotient contains C1/C2.
1232static bool isMultiple(const APInt &C1, const APInt &C2, APInt &Quotient,
1233 bool IsSigned) {
1234 assert(C1.getBitWidth() == C2.getBitWidth() && "Constant widths not equal");
1235
1236 // Bail if we will divide by zero.
1237 if (C2.isZero())
1238 return false;
1239
1240 // Bail if we would divide INT_MIN by -1.
1241 if (IsSigned && C1.isMinSignedValue() && C2.isAllOnes())
1242 return false;
1243
1244 APInt Remainder(C1.getBitWidth(), /*val=*/0ULL, IsSigned);
1245 if (IsSigned)
1246 APInt::sdivrem(C1, C2, Quotient, Remainder);
1247 else
1248 APInt::udivrem(C1, C2, Quotient, Remainder);
1249
1250 return Remainder.isMinValue();
1251}
1252
1254 assert((I.getOpcode() == Instruction::SDiv ||
1255 I.getOpcode() == Instruction::UDiv) &&
1256 "Expected integer divide");
1257
1258 bool IsSigned = I.getOpcode() == Instruction::SDiv;
1259 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1260 Type *Ty = I.getType();
1261
1262 Value *X, *Y, *Z;
1263
1264 // With appropriate no-wrap constraints, remove a common factor in the
1265 // dividend and divisor that is disguised as a left-shifted value.
1266 if (match(Op1, m_Shl(m_Value(X), m_Value(Z))) &&
1267 match(Op0, m_c_Mul(m_Specific(X), m_Value(Y)))) {
1268 // Both operands must have the matching no-wrap for this kind of division.
1270 auto *Shl = cast<OverflowingBinaryOperator>(Op1);
1271 bool HasNUW = Mul->hasNoUnsignedWrap() && Shl->hasNoUnsignedWrap();
1272 bool HasNSW = Mul->hasNoSignedWrap() && Shl->hasNoSignedWrap();
1273
1274 // (X * Y) u/ (X << Z) --> Y u>> Z
1275 if (!IsSigned && HasNUW)
1276 return Builder.CreateLShr(Y, Z, "", I.isExact());
1277
1278 // (X * Y) s/ (X << Z) --> Y s/ (1 << Z)
1279 if (IsSigned && HasNSW && (Op0->hasOneUse() || Op1->hasOneUse())) {
1280 Value *Shl = Builder.CreateShl(ConstantInt::get(Ty, 1), Z);
1281 return Builder.CreateSDiv(Y, Shl, "", I.isExact());
1282 }
1283 }
1284
1285 // With appropriate no-wrap constraints, remove a common factor in the
1286 // dividend and divisor that is disguised as a left-shift amount.
1287 if (match(Op0, m_Shl(m_Value(X), m_Value(Z))) &&
1288 match(Op1, m_Shl(m_Value(Y), m_Specific(Z)))) {
1289 auto *Shl0 = cast<OverflowingBinaryOperator>(Op0);
1290 auto *Shl1 = cast<OverflowingBinaryOperator>(Op1);
1291
1292 // For unsigned div, we need 'nuw' on both shifts or
1293 // 'nsw' on both shifts + 'nuw' on the dividend.
1294 // (X << Z) / (Y << Z) --> X / Y
1295 if (!IsSigned &&
1296 ((Shl0->hasNoUnsignedWrap() && Shl1->hasNoUnsignedWrap()) ||
1297 (Shl0->hasNoUnsignedWrap() && Shl0->hasNoSignedWrap() &&
1298 Shl1->hasNoSignedWrap())))
1299 return Builder.CreateUDiv(X, Y, "", I.isExact());
1300
1301 // For signed div, we need 'nsw' on both shifts + 'nuw' on the divisor.
1302 // (X << Z) / (Y << Z) --> X / Y
1303 if (IsSigned && Shl0->hasNoSignedWrap() && Shl1->hasNoSignedWrap() &&
1304 Shl1->hasNoUnsignedWrap())
1305 return Builder.CreateSDiv(X, Y, "", I.isExact());
1306 }
1307
1308 // If X << Y and X << Z does not overflow, then:
1309 // (X << Y) / (X << Z) -> (1 << Y) / (1 << Z) -> 1 << Y >> Z
1310 if (match(Op0, m_Shl(m_Value(X), m_Value(Y))) &&
1311 match(Op1, m_Shl(m_Specific(X), m_Value(Z)))) {
1312 auto *Shl0 = cast<OverflowingBinaryOperator>(Op0);
1313 auto *Shl1 = cast<OverflowingBinaryOperator>(Op1);
1314
1315 if (IsSigned ? (Shl0->hasNoSignedWrap() && Shl1->hasNoSignedWrap())
1316 : (Shl0->hasNoUnsignedWrap() && Shl1->hasNoUnsignedWrap())) {
1317 Constant *One = ConstantInt::get(X->getType(), 1);
1318 // Only preserve the nsw flag if dividend has nsw
1319 // or divisor has nsw and operator is sdiv.
1320 Value *Dividend = Builder.CreateShl(
1321 One, Y, "shl.dividend",
1322 /*HasNUW=*/true,
1323 /*HasNSW=*/
1324 IsSigned ? (Shl0->hasNoUnsignedWrap() || Shl1->hasNoUnsignedWrap())
1325 : Shl0->hasNoSignedWrap());
1326 return Builder.CreateLShr(Dividend, Z, "", I.isExact());
1327 }
1328 }
1329
1330 return nullptr;
1331}
1332
1333/// Return true if a matching remainder is known to be zero at the division.
1335 const SimplifyQuery &Q) {
1336 assert((Div.getOpcode() == Instruction::SDiv ||
1337 Div.getOpcode() == Instruction::UDiv) &&
1338 "Expected integer divide");
1339
1340 // The condition cache does not track vector lanes independently.
1341 if (!Div.getType()->isIntegerTy())
1342 return false;
1343
1344 unsigned RemOpcode = Div.getOpcode() == Instruction::SDiv ? Instruction::SRem
1345 : Instruction::URem;
1346
1347 Value *Op0 = Div.getOperand(0);
1348 Value *Op1 = Div.getOperand(1);
1349
1350 auto IsKnownZeroRemainder = [&](Value *Cond) {
1351 auto *Cmp = dyn_cast<ICmpInst>(Cond);
1352 if (!Cmp || !Cmp->isEquality())
1353 return false;
1354
1355 // Search for a remainder being compared to zero.
1356 BinaryOperator *Rem;
1357 if (!match(Cmp, m_c_ICmp(m_BinOp(Rem), m_Zero())))
1358 return false;
1359 if (Rem->getOpcode() != RemOpcode || Rem->getOperand(0) != Op0 ||
1360 Rem->getOperand(1) != Op1)
1361 return false;
1362
1365 return Known.isZero();
1366 };
1367
1368 // findValuesAffectedByCondition() records both operands of a remainder that
1369 // is compared against zero, so looking up one non-constant operand finds
1370 // every candidate condition.
1371 Value *V = isa<Constant>(Op0) ? Op1 : Op0;
1372
1373 if (Q.DC && Q.DT) {
1374 for (CondBrInst *BI : Q.DC->conditionsFor(V))
1375 if (IsKnownZeroRemainder(BI->getCondition()))
1376 return true;
1377 }
1378
1379 if (Q.AC) {
1380 for (auto &AssumeValueHandle : Q.AC->assumptionsFor(V)) {
1381 if (!AssumeValueHandle)
1382 continue;
1383 auto *Assume = cast<AssumeInst>(AssumeValueHandle);
1384 if (IsKnownZeroRemainder(Assume->getArgOperand(0)))
1385 return true;
1386 }
1387 }
1388
1389 return false;
1390}
1391
1392/// Common integer divide/remainder transforms
1394 assert(I.isIntDivRem() && "Unexpected instruction");
1395 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1396
1397 // If any element of a constant divisor fixed width vector is zero or undef
1398 // the behavior is undefined and we can fold the whole op to poison.
1401 return replaceInstUsesWith(I, PoisonValue::get(I.getType()));
1402 }
1403
1405 return Phi;
1406
1407 // The RHS is known non-zero.
1408 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I))
1409 return replaceOperand(I, 1, V);
1410
1411 // Handle cases involving: div/rem X, (select Cond, Y, Z)
1413 return &I;
1414
1415 // If the divisor is a select-of-constants, try to constant fold all div ops:
1416 // C div/rem (select Cond, TrueC, FalseC) --> select Cond, (C div/rem TrueC),
1417 // (C div/rem FalseC)
1418 // TODO: Adapt simplifyDivRemOfSelectWithZeroOp to allow this and other folds.
1419 if (match(Op0, m_ImmConstant()) &&
1422 /*FoldWithMultiUse*/ true))
1423 return R;
1424 }
1425
1426 return nullptr;
1427}
1428
1429/// This function implements the transforms common to both integer division
1430/// instructions (udiv and sdiv). It is called by the visitors to those integer
1431/// division instructions.
1432/// Common integer divide transforms
1435 return Res;
1436
1437 if (!I.isExact() && isKnownExactFromRem(I, SQ)) {
1438 I.setIsExact();
1439 return &I;
1440 }
1441
1442 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1443 bool IsSigned = I.getOpcode() == Instruction::SDiv;
1444 Type *Ty = I.getType();
1445
1446 const APInt *C2;
1447 if (match(Op1, m_APInt(C2))) {
1448 Value *X;
1449 const APInt *C1;
1450
1451 // (X / C1) / C2 -> X / (C1*C2)
1452 if ((IsSigned && match(Op0, m_SDiv(m_Value(X), m_APInt(C1)))) ||
1453 (!IsSigned && match(Op0, m_UDiv(m_Value(X), m_APInt(C1))))) {
1454 APInt Product(C1->getBitWidth(), /*val=*/0ULL, IsSigned);
1455 if (!multiplyOverflows(*C1, *C2, Product, IsSigned))
1456 return BinaryOperator::Create(I.getOpcode(), X,
1457 ConstantInt::get(Ty, Product));
1458 }
1459
1460 APInt Quotient(C2->getBitWidth(), /*val=*/0ULL, IsSigned);
1461 if ((IsSigned && match(Op0, m_NSWMul(m_Value(X), m_APInt(C1)))) ||
1462 (!IsSigned && match(Op0, m_NUWMul(m_Value(X), m_APInt(C1))))) {
1463
1464 // (X * C1) / C2 -> X / (C2 / C1) if C2 is a multiple of C1.
1465 if (isMultiple(*C2, *C1, Quotient, IsSigned)) {
1466 auto *NewDiv = BinaryOperator::Create(I.getOpcode(), X,
1467 ConstantInt::get(Ty, Quotient));
1468 NewDiv->setIsExact(I.isExact());
1469 return NewDiv;
1470 }
1471
1472 // (X * C1) / C2 -> X * (C1 / C2) if C1 is a multiple of C2.
1473 if (isMultiple(*C1, *C2, Quotient, IsSigned)) {
1474 auto *Mul = BinaryOperator::Create(Instruction::Mul, X,
1475 ConstantInt::get(Ty, Quotient));
1476 auto *OBO = cast<OverflowingBinaryOperator>(Op0);
1477 Mul->setHasNoUnsignedWrap(!IsSigned && OBO->hasNoUnsignedWrap());
1478 Mul->setHasNoSignedWrap(OBO->hasNoSignedWrap());
1479 return Mul;
1480 }
1481
1482 // (X * C1) / C2 -> (X * (C1/D)) / (C2/D) if D = gcd(C1, C2) > 1.
1483 if (Op0->hasOneUse()) {
1484 APInt GCD = APIntOps::GreatestCommonDivisor(*C1, *C2, IsSigned);
1485 if (GCD.ugt(1)) {
1486 APInt NewC1 = IsSigned ? C1->sdiv(GCD) : C1->udiv(GCD);
1487 APInt NewC2 = IsSigned ? C2->sdiv(GCD) : C2->udiv(GCD);
1488
1489 auto *OldMul = cast<OverflowingBinaryOperator>(Op0);
1490 Value *NewMul = Builder.CreateMul(X, ConstantInt::get(Ty, NewC1), "",
1491 OldMul->hasNoUnsignedWrap(),
1492 OldMul->hasNoSignedWrap());
1493 NewMul->takeName(OldMul);
1494
1495 Constant *NewDivisor = ConstantInt::get(Ty, NewC2);
1496 auto *NewDiv =
1497 BinaryOperator::Create(I.getOpcode(), NewMul, NewDivisor);
1498 NewDiv->setIsExact(I.isExact());
1499 return NewDiv;
1500 }
1501 }
1502 }
1503
1504 if ((IsSigned && match(Op0, m_NSWShl(m_Value(X), m_APInt(C1))) &&
1505 C1->ult(C1->getBitWidth() - 1)) ||
1506 (!IsSigned && match(Op0, m_NUWShl(m_Value(X), m_APInt(C1))) &&
1507 C1->ult(C1->getBitWidth()))) {
1508 APInt C1Shifted = APInt::getOneBitSet(
1509 C1->getBitWidth(), static_cast<unsigned>(C1->getZExtValue()));
1510
1511 // (X << C1) / C2 -> X / (C2 >> C1) if C2 is a multiple of 1 << C1.
1512 if (isMultiple(*C2, C1Shifted, Quotient, IsSigned)) {
1513 auto *BO = BinaryOperator::Create(I.getOpcode(), X,
1514 ConstantInt::get(Ty, Quotient));
1515 BO->setIsExact(I.isExact());
1516 return BO;
1517 }
1518
1519 // (X << C1) / C2 -> X * ((1 << C1) / C2) if 1 << C1 is a multiple of C2.
1520 if (isMultiple(C1Shifted, *C2, Quotient, IsSigned)) {
1521 auto *Mul = BinaryOperator::Create(Instruction::Mul, X,
1522 ConstantInt::get(Ty, Quotient));
1523 auto *OBO = cast<OverflowingBinaryOperator>(Op0);
1524 Mul->setHasNoUnsignedWrap(!IsSigned && OBO->hasNoUnsignedWrap());
1525 Mul->setHasNoSignedWrap(OBO->hasNoSignedWrap());
1526 return Mul;
1527 }
1528
1529 // (X << C1) / C2 -> (X << (C1 - K)) / (C2 / (1 << K))
1530 // Where K = min(C1, countr_zero(C2)), the shared power of 2.
1531 if (Op0->hasOneUse()) {
1532 unsigned ShiftAmt = static_cast<unsigned>(C1->getZExtValue());
1533 unsigned K = std::min(C2->countr_zero(), ShiftAmt);
1534 if (K > 0) {
1535 unsigned NewShiftAmt = ShiftAmt - K;
1536 APInt NewC2 = IsSigned ? C2->ashr(K) : C2->lshr(K);
1537
1538 auto *OldShift = cast<OverflowingBinaryOperator>(Op0);
1539 Value *NewShift = Builder.CreateShl(
1540 X, ConstantInt::get(Ty, NewShiftAmt), "",
1541 OldShift->hasNoUnsignedWrap(), OldShift->hasNoSignedWrap());
1542 NewShift->takeName(OldShift);
1543
1544 Constant *NewDivisor = ConstantInt::get(Ty, NewC2);
1545 auto *NewDiv =
1546 BinaryOperator::Create(I.getOpcode(), NewShift, NewDivisor);
1547 NewDiv->setIsExact(I.isExact());
1548 return NewDiv;
1549 }
1550 }
1551 }
1552
1553 // Distribute div over add to eliminate a matching div/mul pair:
1554 // ((X * C2) + C1) / C2 --> X + C1/C2
1555 // We need a multiple of the divisor for a signed add constant, but
1556 // unsigned is fine with any constant pair.
1557 if (IsSigned &&
1559 m_APInt(C1))) &&
1560 isMultiple(*C1, *C2, Quotient, IsSigned)) {
1561 return BinaryOperator::CreateNSWAdd(X, ConstantInt::get(Ty, Quotient));
1562 }
1563 if (!IsSigned &&
1565 m_APInt(C1)))) {
1566 return BinaryOperator::CreateNUWAdd(X,
1567 ConstantInt::get(Ty, C1->udiv(*C2)));
1568 }
1569
1570 if (!C2->isZero()) // avoid X udiv 0
1571 if (Instruction *FoldedDiv = foldBinOpIntoSelectOrPhi(I))
1572 return FoldedDiv;
1573 }
1574
1575 if (match(Op0, m_One())) {
1576 assert(!Ty->isIntOrIntVectorTy(1) && "i1 divide not removed?");
1577 if (IsSigned) {
1578 // 1 / 0 --> undef ; 1 / 1 --> 1 ; 1 / -1 --> -1 ; 1 / anything else --> 0
1579 // (Op1 + 1) u< 3 ? Op1 : 0
1580 // Op1 must be frozen because we are increasing its number of uses.
1581 Value *F1 = Op1;
1582 if (!isGuaranteedNotToBeUndef(Op1))
1583 F1 = Builder.CreateFreeze(Op1, Op1->getName() + ".fr");
1584 Value *Inc = Builder.CreateAdd(F1, Op0);
1585 Value *Cmp = Builder.CreateICmpULT(Inc, ConstantInt::get(Ty, 3));
1586 return createSelectInstWithUnknownProfile(Cmp, F1,
1587 ConstantInt::get(Ty, 0));
1588 } else {
1589 // If Op1 is 0 then it's undefined behaviour. If Op1 is 1 then the
1590 // result is one, otherwise it's zero.
1591 return new ZExtInst(Builder.CreateICmpEQ(Op1, Op0), Ty);
1592 }
1593 }
1594
1595 // See if we can fold away this div instruction.
1597 return &I;
1598
1599 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
1600 Value *X, *Z;
1601 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) // (X - Z) / Y; Y = Op1
1602 if ((IsSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
1603 (!IsSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
1604 return BinaryOperator::Create(I.getOpcode(), X, Op1);
1605
1606 // (X << Y) / X -> 1 << Y
1607 Value *Y;
1608 if (IsSigned && match(Op0, m_NSWShl(m_Specific(Op1), m_Value(Y))))
1609 return BinaryOperator::CreateNSWShl(ConstantInt::get(Ty, 1), Y);
1610 if (!IsSigned && match(Op0, m_NUWShl(m_Specific(Op1), m_Value(Y))))
1611 return BinaryOperator::CreateNUWShl(ConstantInt::get(Ty, 1), Y);
1612
1613 // X / (X * Y) -> 1 / Y if the multiplication does not overflow.
1614 if (match(Op1, m_c_Mul(m_Specific(Op0), m_Value(Y)))) {
1615 bool HasNSW = cast<OverflowingBinaryOperator>(Op1)->hasNoSignedWrap();
1616 bool HasNUW = cast<OverflowingBinaryOperator>(Op1)->hasNoUnsignedWrap();
1617 if ((IsSigned && HasNSW) || (!IsSigned && HasNUW)) {
1618 replaceOperand(I, 0, ConstantInt::get(Ty, 1));
1619 replaceOperand(I, 1, Y);
1620 return &I;
1621 }
1622 }
1623
1624 // (X << Z) / (X * Y) -> (1 << Z) / Y
1625 // TODO: Handle sdiv.
1626 if (!IsSigned && Op1->hasOneUse() &&
1627 match(Op0, m_NUWShl(m_Value(X), m_Value(Z))) &&
1628 match(Op1, m_c_Mul(m_Specific(X), m_Value(Y))))
1630 Instruction *NewDiv = BinaryOperator::CreateUDiv(
1631 Builder.CreateShl(ConstantInt::get(Ty, 1), Z, "", /*NUW*/ true), Y);
1632 NewDiv->setIsExact(I.isExact());
1633 return NewDiv;
1634 }
1635
1636 if (Value *R = foldIDivShl(I, Builder))
1637 return replaceInstUsesWith(I, R);
1638
1639 // With the appropriate no-wrap constraint, remove a multiply by the divisor
1640 // after peeking through another divide:
1641 // ((Op1 * X) / Y) / Op1 --> X / Y
1642 if (match(Op0, m_BinOp(I.getOpcode(), m_c_Mul(m_Specific(Op1), m_Value(X)),
1643 m_Value(Y)))) {
1644 auto *InnerDiv = cast<PossiblyExactOperator>(Op0);
1645 auto *Mul = cast<OverflowingBinaryOperator>(InnerDiv->getOperand(0));
1646 Instruction *NewDiv = nullptr;
1647 if (!IsSigned && Mul->hasNoUnsignedWrap())
1648 NewDiv = BinaryOperator::CreateUDiv(X, Y);
1649 else if (IsSigned && Mul->hasNoSignedWrap())
1650 NewDiv = BinaryOperator::CreateSDiv(X, Y);
1651
1652 // Exact propagates only if both of the original divides are exact.
1653 if (NewDiv) {
1654 NewDiv->setIsExact(I.isExact() && InnerDiv->isExact());
1655 return NewDiv;
1656 }
1657 }
1658
1659 // X / (select Cond, 1, Y) --> select Cond, X, (X / Y)
1660 // X / (select Cond, Y, 1) --> select Cond, (X / Y), X
1661 // Division by 1 is a no-op, so we sink the division into the non-1 arm.
1662 // For sdiv, limit Y to constant to avoid signed overflow concern.
1663 {
1664 Value *Cond, *DivY;
1665 const APInt *C;
1666 auto IsSafeDivisor = [&](Value *V) {
1667 if (IsSigned)
1668 return match(V, m_APInt(C)) && !C->isZero() && !C->isAllOnes();
1669 return isKnownNonZero(V, SQ.getWithInstruction(&I)) &&
1670 isGuaranteedNotToBePoison(V, SQ.AC, &I, SQ.DT);
1671 };
1672 if (match(Op1, m_OneUse(m_Select(m_Value(Cond), m_One(), m_Value(DivY)))) &&
1673 IsSafeDivisor(DivY)) {
1674 Value *NewDiv =
1675 Builder.CreateExactBinOp(I.getOpcode(), Op0, DivY, I.isExact());
1676 return SelectInst::Create(Cond, Op0, NewDiv, "", nullptr,
1677 cast<SelectInst>(Op1));
1678 }
1679 if (match(Op1, m_OneUse(m_Select(m_Value(Cond), m_Value(DivY), m_One()))) &&
1680 IsSafeDivisor(DivY)) {
1681 Value *NewDiv =
1682 Builder.CreateExactBinOp(I.getOpcode(), Op0, DivY, I.isExact());
1683 return SelectInst::Create(Cond, NewDiv, Op0, "", nullptr,
1684 cast<SelectInst>(Op1));
1685 }
1686 }
1687
1688 // (X * Y) / (X * Z) --> Y / Z (and commuted variants)
1689 if (match(Op0, m_Mul(m_Value(X), m_Value(Y)))) {
1690 auto OB0HasNSW = cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap();
1691 auto OB0HasNUW = cast<OverflowingBinaryOperator>(Op0)->hasNoUnsignedWrap();
1692
1693 auto CreateDivOrNull = [&](Value *A, Value *B) -> Instruction * {
1694 auto OB1HasNSW = cast<OverflowingBinaryOperator>(Op1)->hasNoSignedWrap();
1695 auto OB1HasNUW =
1696 cast<OverflowingBinaryOperator>(Op1)->hasNoUnsignedWrap();
1697 const APInt *C1, *C2;
1698 if (IsSigned && OB0HasNSW) {
1699 if (OB1HasNSW && match(B, m_APInt(C1)) && !C1->isAllOnes())
1700 return BinaryOperator::CreateSDiv(A, B);
1701 }
1702 if (!IsSigned && OB0HasNUW) {
1703 if (OB1HasNUW)
1704 return BinaryOperator::CreateUDiv(A, B);
1705 if (match(A, m_APInt(C1)) && match(B, m_APInt(C2)) && C2->ule(*C1))
1706 return BinaryOperator::CreateUDiv(A, B);
1707 }
1708 return nullptr;
1709 };
1710
1711 if (match(Op1, m_c_Mul(m_Specific(X), m_Value(Z)))) {
1712 if (auto *Val = CreateDivOrNull(Y, Z))
1713 return Val;
1714 }
1715 if (match(Op1, m_c_Mul(m_Specific(Y), m_Value(Z)))) {
1716 if (auto *Val = CreateDivOrNull(X, Z))
1717 return Val;
1718 }
1719 }
1720 return nullptr;
1721}
1722
1723Value *InstCombinerImpl::takeLog2(Value *Op, unsigned Depth, bool AssumeNonZero,
1724 bool DoFold) {
1725 auto IfFold = [DoFold](function_ref<Value *()> Fn) {
1726 if (!DoFold)
1727 return reinterpret_cast<Value *>(-1);
1728 return Fn();
1729 };
1730
1731 // FIXME: assert that Op1 isn't/doesn't contain undef.
1732
1733 // log2(2^C) -> C
1734 if (match(Op, m_Power2()))
1735 return IfFold([&]() {
1737 if (!C)
1738 llvm_unreachable("Failed to constant fold udiv -> logbase2");
1739 return C;
1740 });
1741
1742 // The remaining tests are all recursive, so bail out if we hit the limit.
1744 return nullptr;
1745
1746 // log2(zext X) -> zext log2(X)
1747 // FIXME: Require one use?
1748 Value *X, *Y;
1749 if (match(Op, m_ZExt(m_Value(X))))
1750 if (Value *LogX = takeLog2(X, Depth, AssumeNonZero, DoFold))
1751 return IfFold([&]() { return Builder.CreateZExt(LogX, Op->getType()); });
1752
1753 // log2(trunc x) -> trunc log2(X)
1754 // FIXME: Require one use?
1755 if (match(Op, m_Trunc(m_Value(X)))) {
1756 auto *TI = cast<TruncInst>(Op);
1757 if (AssumeNonZero || TI->hasNoUnsignedWrap())
1758 if (Value *LogX = takeLog2(X, Depth, AssumeNonZero, DoFold))
1759 return IfFold([&]() {
1760 return Builder.CreateTrunc(LogX, Op->getType(), "",
1761 /*IsNUW=*/TI->hasNoUnsignedWrap());
1762 });
1763 }
1764
1765 // log2(X << Y) -> log2(X) + Y
1766 // FIXME: Require one use unless X is 1?
1767 if (match(Op, m_Shl(m_Value(X), m_Value(Y)))) {
1769 // nuw will be set if the `shl` is trivially non-zero.
1770 if (AssumeNonZero || BO->hasNoUnsignedWrap() || BO->hasNoSignedWrap())
1771 if (Value *LogX = takeLog2(X, Depth, AssumeNonZero, DoFold))
1772 return IfFold([&]() { return Builder.CreateAdd(LogX, Y); });
1773 }
1774
1775 // log2(X >>u Y) -> log2(X) - Y
1776 // FIXME: Require one use?
1777 if (match(Op, m_LShr(m_Value(X), m_Value(Y)))) {
1778 auto *PEO = cast<PossiblyExactOperator>(Op);
1779 if (AssumeNonZero || PEO->isExact())
1780 if (Value *LogX = takeLog2(X, Depth, AssumeNonZero, DoFold))
1781 return IfFold([&]() { return Builder.CreateSub(LogX, Y); });
1782 }
1783
1784 // log2(X & Y) -> either log2(X) or log2(Y)
1785 // This requires `AssumeNonZero` as `X & Y` may be zero when X != Y.
1786 if (AssumeNonZero && match(Op, m_And(m_Value(X), m_Value(Y)))) {
1787 if (Value *LogX = takeLog2(X, Depth, AssumeNonZero, DoFold))
1788 return IfFold([&]() { return LogX; });
1789 if (Value *LogY = takeLog2(Y, Depth, AssumeNonZero, DoFold))
1790 return IfFold([&]() { return LogY; });
1791 }
1792
1793 // log2(Cond ? X : Y) -> Cond ? log2(X) : log2(Y)
1794 // FIXME: Require one use?
1796 if (Value *LogX = takeLog2(SI->getOperand(1), Depth, AssumeNonZero, DoFold))
1797 if (Value *LogY =
1798 takeLog2(SI->getOperand(2), Depth, AssumeNonZero, DoFold))
1799 return IfFold([&]() {
1800 return Builder.CreateSelect(SI->getOperand(0), LogX, LogY, "", SI);
1801 });
1802
1803 // log2(umin(X, Y)) -> umin(log2(X), log2(Y))
1804 // log2(umax(X, Y)) -> umax(log2(X), log2(Y))
1806 if (MinMax && MinMax->hasOneUse() && !MinMax->isSigned()) {
1807 // Use AssumeNonZero as false here. Otherwise we can hit case where
1808 // log2(umax(X, Y)) != umax(log2(X), log2(Y)) (because overflow).
1809 if (Value *LogX = takeLog2(MinMax->getLHS(), Depth,
1810 /*AssumeNonZero*/ false, DoFold))
1811 if (Value *LogY = takeLog2(MinMax->getRHS(), Depth,
1812 /*AssumeNonZero*/ false, DoFold))
1813 return IfFold([&]() {
1814 return Builder.CreateBinaryIntrinsic(MinMax->getIntrinsicID(), LogX,
1815 LogY);
1816 });
1817 }
1818
1819 // log2(X + 1) IIF X[0,1] -> X
1820 if (Op->getType()->getScalarSizeInBits() != 1 &&
1821 match(Op, m_Add(m_Value(X), m_One())) &&
1822 computeKnownBits(X, cast<Instruction>(Op)).countMaxActiveBits() == 1)
1823 return IfFold([&]() { return X; });
1824
1825 return nullptr;
1826}
1827
1828/// If we have zero-extended operands of an unsigned div or rem, we may be able
1829/// to narrow the operation (sink the zext below the math).
1831 InstCombinerImpl &IC) {
1832 Instruction::BinaryOps Opcode = I.getOpcode();
1833 Value *N = I.getOperand(0);
1834 Value *D = I.getOperand(1);
1835 Type *Ty = I.getType();
1836 Value *X, *Y;
1837 if (match(N, m_ZExt(m_Value(X))) && match(D, m_ZExt(m_Value(Y))) &&
1838 X->getType() == Y->getType() && (N->hasOneUse() || D->hasOneUse())) {
1839 // udiv (zext X), (zext Y) --> zext (udiv X, Y)
1840 // urem (zext X), (zext Y) --> zext (urem X, Y)
1841 Value *NarrowOp = IC.Builder.CreateBinOp(Opcode, X, Y);
1842 return new ZExtInst(NarrowOp, Ty);
1843 }
1844
1845 Constant *C;
1846 auto &DL = IC.getDataLayout();
1848 match(D, m_Constant(C))) {
1849 // If the constant is the same in the smaller type, use the narrow version.
1850 Constant *TruncC = getLosslessUnsignedTrunc(C, X->getType(), DL);
1851 if (!TruncC)
1852 return nullptr;
1853
1854 // udiv (zext X), C --> zext (udiv X, C')
1855 // urem (zext X), C --> zext (urem X, C')
1856 return new ZExtInst(IC.Builder.CreateBinOp(Opcode, X, TruncC), Ty);
1857 }
1859 match(N, m_Constant(C))) {
1860 // If the constant is the same in the smaller type, use the narrow version.
1861 Constant *TruncC = getLosslessUnsignedTrunc(C, X->getType(), DL);
1862 if (!TruncC)
1863 return nullptr;
1864
1865 // udiv C, (zext X) --> zext (udiv C', X)
1866 // urem C, (zext X) --> zext (urem C', X)
1867 return new ZExtInst(IC.Builder.CreateBinOp(Opcode, TruncC, X), Ty);
1868 }
1869
1870 return nullptr;
1871}
1872
1874 if (Value *V = simplifyUDivInst(I.getOperand(0), I.getOperand(1), I.isExact(),
1875 SQ.getWithInstruction(&I)))
1876 return replaceInstUsesWith(I, V);
1877
1879 return X;
1880
1881 // Handle the integer div common cases
1882 if (Instruction *Common = commonIDivTransforms(I))
1883 return Common;
1884
1885 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1886 Value *X;
1887 const APInt *C1, *C2;
1888 if (match(Op0, m_LShr(m_Value(X), m_APInt(C1))) && match(Op1, m_APInt(C2))) {
1889 // (X lshr C1) udiv C2 --> X udiv (C2 << C1)
1890 bool Overflow;
1891 APInt C2ShlC1 = C2->ushl_ov(*C1, Overflow);
1892 if (!Overflow) {
1893 bool IsExact = I.isExact() && match(Op0, m_Exact(m_Value()));
1894 BinaryOperator *BO = BinaryOperator::CreateUDiv(
1895 X, ConstantInt::get(X->getType(), C2ShlC1));
1896 if (IsExact)
1897 BO->setIsExact();
1898 return BO;
1899 }
1900 }
1901
1902 // (X udiv Y) udiv Z --> X udiv (Y * Z), if Y * Z does not overflow.
1903 // This is the variable-operand version of the (X / C1) / C2 fold in
1904 // commonIDivTransforms().
1905 Value *Y;
1906 if (match(Op0, m_OneUse(m_UDiv(m_Value(X), m_Value(Y)))) &&
1907 willNotOverflowUnsignedMul(Y, Op1, I)) {
1908 Value *YZ = Builder.CreateNUWMul(Y, Op1);
1909 auto *NewDiv = BinaryOperator::CreateUDiv(X, YZ);
1910 // The result is exact only if both of the original divides are exact.
1911 if (I.isExact() && cast<PossiblyExactOperator>(Op0)->isExact())
1912 NewDiv->setIsExact();
1913 return NewDiv;
1914 }
1915
1916 // Op0 / C where C is large (negative) --> zext (Op0 >= C)
1917 // This also handles non-constant values where the sign bit is known to be
1918 // set.
1919 Type *Ty = I.getType();
1920 if (isKnownNegative(Op1, SQ.getWithInstruction(&I))) {
1921 Value *Cmp = Builder.CreateICmpUGE(Op0, Op1);
1922 return CastInst::CreateZExtOrBitCast(Cmp, Ty);
1923 }
1924 // Op0 / (sext i1 X) --> zext (Op0 == -1) (if X is 0, the div is undefined)
1925 if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
1926 Value *Cmp = Builder.CreateICmpEQ(Op0, ConstantInt::getAllOnesValue(Ty));
1927 return CastInst::CreateZExtOrBitCast(Cmp, Ty);
1928 }
1929
1930 if (Instruction *NarrowDiv = narrowUDivURem(I, *this))
1931 return NarrowDiv;
1932
1933 Value *A, *B;
1934
1935 // Look through a right-shift to find the common factor:
1936 // ((Op1 *nuw A) >> B) / Op1 --> A >> B
1937 if (match(Op0, m_LShr(m_NUWMul(m_Specific(Op1), m_Value(A)), m_Value(B))) ||
1938 match(Op0, m_LShr(m_NUWMul(m_Value(A), m_Specific(Op1)), m_Value(B)))) {
1939 Instruction *Lshr = BinaryOperator::CreateLShr(A, B);
1940 if (I.isExact() && cast<PossiblyExactOperator>(Op0)->isExact())
1941 Lshr->setIsExact();
1942 return Lshr;
1943 }
1944
1945 auto GetShiftableDenom = [&](Value *Denom) -> Value * {
1946 // Op0 udiv Op1 -> Op0 lshr log2(Op1), if log2() folds away.
1947 if (Value *Log2 = tryGetLog2(Op1, /*AssumeNonZero=*/true))
1948 return Log2;
1949
1950 // Op0 udiv Op1 -> Op0 lshr cttz(Op1), if Op1 is a power of 2.
1951 if (isKnownToBeAPowerOfTwo(Denom, /*OrZero=*/true, &I))
1952 // This will increase instruction count but it's okay
1953 // since bitwise operations are substantially faster than
1954 // division.
1955 return Builder.CreateBinaryIntrinsic(Intrinsic::cttz, Denom,
1956 Builder.getTrue());
1957
1958 return nullptr;
1959 };
1960
1961 if (auto *Res = GetShiftableDenom(Op1))
1962 return replaceInstUsesWith(
1963 I, Builder.CreateLShr(Op0, Res, I.getName(), I.isExact()));
1964
1965 return nullptr;
1966}
1967
1969 if (Value *V = simplifySDivInst(I.getOperand(0), I.getOperand(1), I.isExact(),
1970 SQ.getWithInstruction(&I)))
1971 return replaceInstUsesWith(I, V);
1972
1974 return X;
1975
1976 // Handle the integer div common cases
1977 if (Instruction *Common = commonIDivTransforms(I))
1978 return Common;
1979
1980 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1981 Type *Ty = I.getType();
1982 Value *X;
1983 // sdiv Op0, -1 --> -Op0
1984 // sdiv Op0, (sext i1 X) --> -Op0 (because if X is 0, the op is undefined)
1985 if (match(Op1, m_AllOnes()) ||
1986 (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)))
1987 return BinaryOperator::CreateNSWNeg(Op0);
1988
1989 // X / INT_MIN --> X == INT_MIN
1990 if (match(Op1, m_SignMask()))
1991 return new ZExtInst(Builder.CreateICmpEQ(Op0, Op1), Ty);
1992
1993 if (I.isExact()) {
1994 // sdiv exact X, 1<<C --> ashr exact X, C iff 1<<C is non-negative
1995 if (match(Op1, m_Power2()) && match(Op1, m_NonNegative())) {
1997 return BinaryOperator::CreateExactAShr(Op0, C);
1998 }
1999
2000 // sdiv exact X, (1<<ShAmt) --> ashr exact X, ShAmt (if shl is non-negative)
2001 Value *ShAmt;
2002 if (match(Op1, m_NSWShl(m_One(), m_Value(ShAmt))))
2003 return BinaryOperator::CreateExactAShr(Op0, ShAmt);
2004
2005 // sdiv exact X, -1<<C --> -(ashr exact X, C)
2006 if (match(Op1, m_NegatedPower2())) {
2009 Value *Ashr = Builder.CreateAShr(Op0, C, I.getName() + ".neg", true);
2010 return BinaryOperator::CreateNSWNeg(Ashr);
2011 }
2012 }
2013
2014 const APInt *Op1C;
2015 if (match(Op1, m_APInt(Op1C))) {
2016 // If the dividend is sign-extended and the constant divisor is small enough
2017 // to fit in the source type, shrink the division to the narrower type:
2018 // (sext X) sdiv C --> sext (X sdiv C)
2019 Value *Op0Src;
2020 if (match(Op0, m_OneUse(m_SExt(m_Value(Op0Src)))) &&
2021 Op0Src->getType()->getScalarSizeInBits() >=
2022 Op1C->getSignificantBits()) {
2023
2024 // In the general case, we need to make sure that the dividend is not the
2025 // minimum signed value because dividing that by -1 is UB. But here, we
2026 // know that the -1 divisor case is already handled above.
2027
2028 Constant *NarrowDivisor =
2030 Value *NarrowOp = Builder.CreateSDiv(Op0Src, NarrowDivisor);
2031 return new SExtInst(NarrowOp, Ty);
2032 }
2033
2034 // -X / C --> X / -C (if the negation doesn't overflow).
2035 // TODO: This could be enhanced to handle arbitrary vector constants by
2036 // checking if all elements are not the min-signed-val.
2037 if (!Op1C->isMinSignedValue() && match(Op0, m_NSWNeg(m_Value(X)))) {
2038 Constant *NegC = ConstantInt::get(Ty, -(*Op1C));
2039 Instruction *BO = BinaryOperator::CreateSDiv(X, NegC);
2040 BO->setIsExact(I.isExact());
2041 return BO;
2042 }
2043 }
2044
2045 Value *Y;
2046 // -X / -Y --> X / Y, unless X == INT_MIN and Y == -1.
2047 if (Value *NegOp0 = dyn_castNegVal(Op0))
2048 if (Value *NegOp1 = dyn_castNegVal(Op1))
2049 if (!computeKnownBits(NegOp0, &I)
2050 .getSignedMinValue()
2051 .isMinSignedValue() ||
2052 (match(Op0, m_NSWNeg(m_Value())) &&
2053 !computeKnownBits(NegOp1, &I).Zero.isZero())) {
2054 auto *BO = BinaryOperator::CreateSDiv(NegOp0, NegOp1);
2055 BO->setIsExact(I.isExact());
2056 return BO;
2057 }
2058
2059 // -X / Y --> -(X / Y)
2062 Builder.CreateSDiv(X, Y, I.getName(), I.isExact()));
2063
2064 // abs(X) / X --> X > -1 ? 1 : -1
2065 // X / abs(X) --> X > -1 ? 1 : -1
2066 if (match(&I, m_c_BinOp(
2068 m_Deferred(X)))) {
2069 Value *Cond = Builder.CreateIsNotNeg(X);
2070 return createSelectInstWithUnknownProfile(Cond, ConstantInt::get(Ty, 1),
2072 }
2073
2074 KnownBits KnownDividend = computeKnownBits(Op0, &I);
2075 if (!I.isExact() &&
2076 (match(Op1, m_Power2(Op1C)) || match(Op1, m_NegatedPower2(Op1C))) &&
2077 KnownDividend.countMinTrailingZeros() >= Op1C->countr_zero()) {
2078 I.setIsExact();
2079 return &I;
2080 }
2081
2082 if (KnownDividend.isNonNegative()) {
2083 // If both operands are unsigned, turn this into a udiv.
2084 if (isKnownNonNegative(Op1, SQ.getWithInstruction(&I))) {
2085 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
2086 BO->setIsExact(I.isExact());
2087 return BO;
2088 }
2089
2090 if (match(Op1, m_NegatedPower2())) {
2091 // X sdiv (-(1 << C)) -> -(X sdiv (1 << C)) ->
2092 // -> -(X udiv (1 << C)) -> -(X u>> C)
2095 Value *Shr = Builder.CreateLShr(Op0, CNegLog2, I.getName(), I.isExact());
2096 return BinaryOperator::CreateNeg(Shr);
2097 }
2098
2099 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/ true, &I)) {
2100 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
2101 // Safe because the only negative value (1 << Y) can take on is
2102 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
2103 // the sign bit set.
2104 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
2105 BO->setIsExact(I.isExact());
2106 return BO;
2107 }
2108 }
2109
2110 // -X / X --> X == INT_MIN ? 1 : -1
2111 if (isKnownNegation(Op0, Op1)) {
2112 APInt MinVal = APInt::getSignedMinValue(Ty->getScalarSizeInBits());
2113 Value *Cond = Builder.CreateICmpEQ(Op0, ConstantInt::get(Ty, MinVal));
2114 return createSelectInstWithUnknownProfile(Cond, ConstantInt::get(Ty, 1),
2116 }
2117 return nullptr;
2118}
2119
2120/// Remove negation and try to convert division into multiplication.
2121Instruction *InstCombinerImpl::foldFDivConstantDivisor(BinaryOperator &I) {
2122 Constant *C;
2123 if (!match(I.getOperand(1), m_Constant(C)))
2124 return nullptr;
2125
2126 // -X / C --> X / -C
2127 Value *X;
2128 const DataLayout &DL = I.getDataLayout();
2129 // TODO: Confirm whether m_FNegOrFSubNegZero is correct.
2130 if (match(I.getOperand(0), m_FNegOrFSubNegZero(m_Value(X))))
2131 if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL))
2132 return BinaryOperator::CreateFDivFMF(X, NegC, &I);
2133
2134 // nnan X / +0.0 -> copysign(inf, X)
2135 // nnan nsz X / -0.0 -> copysign(inf, X)
2136 if (I.hasNoNaNs() &&
2137 (match(I.getOperand(1), m_PosZeroFP()) ||
2138 (I.hasNoSignedZeros() && match(I.getOperand(1), m_AnyZeroFP())))) {
2139 IRBuilder<> B(&I);
2140 Value *CopySign = B.CreateIntrinsic(
2141 Intrinsic::copysign, {C->getType()},
2142 {ConstantFP::getInfinity(I.getType()), I.getOperand(0)}, &I);
2143 CopySign->takeName(&I);
2144 return replaceInstUsesWith(I, CopySign);
2145 }
2146
2147 // If the constant divisor has an exact inverse, this is always safe. If not,
2148 // then we can still create a reciprocal if fast-math-flags allow it and the
2149 // constant is a regular number (not zero, infinite, or denormal).
2150 if (!(C->hasExactInverseFP() || (I.hasAllowReciprocal() && C->isNormalFP())))
2151 return nullptr;
2152
2153 // Disallow denormal constants because we don't know what would happen
2154 // on all targets.
2155 // TODO: Use Intrinsic::canonicalize or let function attributes tell us that
2156 // denorms are flushed?
2157 auto *RecipC = ConstantFoldBinaryOpOperands(
2158 Instruction::FDiv, ConstantFP::get(I.getType(), 1.0), C, DL);
2159 if (!RecipC || !RecipC->isNormalFP())
2160 return nullptr;
2161
2162 // X / C --> X * (1 / C)
2163 return BinaryOperator::CreateFMulFMF(I.getOperand(0), RecipC, &I);
2164}
2165
2166/// Remove negation and try to reassociate constant math.
2168 Constant *C;
2169 if (!match(I.getOperand(0), m_Constant(C)))
2170 return nullptr;
2171
2172 // C / -X --> -C / X
2173 Value *X;
2174 const DataLayout &DL = I.getDataLayout();
2175 // TODO: Confirm whether m_FNegOrFSubNegZero is correct.
2176 if (match(I.getOperand(1), m_FNegOrFSubNegZero(m_Value(X))))
2177 if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL))
2178 return BinaryOperator::CreateFDivFMF(NegC, X, &I);
2179
2180 if (!I.hasAllowReassoc() || !I.hasAllowReciprocal())
2181 return nullptr;
2182
2183 // Try to reassociate C / X expressions where X includes another constant.
2184 Constant *C2, *NewC = nullptr;
2185 if (match(I.getOperand(1), m_FMul(m_Value(X), m_Constant(C2)))) {
2186 // C / (X * C2) --> (C / C2) / X
2187 NewC = ConstantFoldBinaryOpOperands(Instruction::FDiv, C, C2, DL);
2188 } else if (match(I.getOperand(1), m_FDiv(m_Value(X), m_Constant(C2)))) {
2189 // C / (X / C2) --> (C * C2) / X
2190 NewC = ConstantFoldBinaryOpOperands(Instruction::FMul, C, C2, DL);
2191 }
2192 // Disallow denormal constants because we don't know what would happen
2193 // on all targets.
2194 // TODO: Use Intrinsic::canonicalize or let function attributes tell us that
2195 // denorms are flushed?
2196 if (!NewC || !NewC->isNormalFP())
2197 return nullptr;
2198
2199 return BinaryOperator::CreateFDivFMF(NewC, X, &I);
2200}
2201
2202/// Negate the exponent of pow/exp to fold division-by-pow() into multiply.
2204 InstCombiner::BuilderTy &Builder) {
2205 // Z / pow(X, Y) --> Z * pow(X, -Y)
2206 // Z / exp{2}(Y) --> Z * exp{2}(-Y)
2207 // Z / splat(pow(X, Y)) --> Z * splat(pow(X, -Y))
2208 // In the general case, this creates an extra instruction, but fmul allows
2209 // for better canonicalization and optimization than fdiv.
2210 if (!I.hasAllowReassoc() || !I.hasAllowReciprocal())
2211 return nullptr;
2212
2213 Value *Op0 = I.getOperand(0);
2214 Value *Op1 = I.getOperand(1);
2215
2216 Value *Divisor = Op1;
2217 Value *Splat = nullptr;
2218 if (match(Op1,
2221 m_Value(), m_ZeroMask()))))
2222 Divisor = Splat;
2223
2224 auto *II = dyn_cast<IntrinsicInst>(Divisor);
2225 if (!II || !II->hasOneUse())
2226 return nullptr;
2227
2228 Intrinsic::ID IID = II->getIntrinsicID();
2229 SmallVector<Type *, 2> Tys = {II->getType()};
2231 switch (IID) {
2232 case Intrinsic::pow:
2233 Args.push_back(II->getArgOperand(0));
2234 Args.push_back(Builder.CreateFNegFMF(II->getArgOperand(1), &I));
2235 break;
2236 case Intrinsic::powi: {
2237 // Require 'ninf' assuming that makes powi(X, -INT_MIN) acceptable.
2238 // That is, X ** (huge negative number) is 0.0, ~1.0, or INF and so
2239 // dividing by that is INF, ~1.0, or 0.0. Code that uses powi allows
2240 // non-standard results, so this corner case should be acceptable if the
2241 // code rules out INF values.
2242 if (!I.hasNoInfs())
2243 return nullptr;
2244 Args.push_back(II->getArgOperand(0));
2245 Args.push_back(Builder.CreateNeg(II->getArgOperand(1)));
2246 Tys.push_back(II->getArgOperand(1)->getType());
2247 break;
2248 }
2249 case Intrinsic::exp:
2250 case Intrinsic::exp2:
2251 Args.push_back(Builder.CreateFNegFMF(II->getArgOperand(0), &I));
2252 break;
2253 default:
2254 return nullptr;
2255 }
2256
2257 Value *Pow = Builder.CreateIntrinsic(IID, Tys, Args, &I);
2258 if (Pow->getType() != I.getType())
2259 Pow = Builder.CreateVectorSplat(
2260 cast<VectorType>(I.getType())->getElementCount(), Pow);
2261
2262 return BinaryOperator::CreateFMulFMF(Op0, Pow, &I);
2263}
2264
2265/// Convert div to mul if we have an sqrt divisor iff sqrt's operand is a fdiv
2266/// instruction.
2268 InstCombiner::BuilderTy &Builder) {
2269 // X / sqrt(Y / Z) --> X * sqrt(Z / Y)
2270 if (!I.hasAllowReassoc() || !I.hasAllowReciprocal())
2271 return nullptr;
2272 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2273 auto *II = dyn_cast<IntrinsicInst>(Op1);
2274 if (!II || II->getIntrinsicID() != Intrinsic::sqrt || !II->hasOneUse() ||
2275 !II->hasAllowReassoc() || !II->hasAllowReciprocal())
2276 return nullptr;
2277
2278 Value *Y, *Z;
2279 auto *DivOp = dyn_cast<Instruction>(II->getOperand(0));
2280 if (!DivOp)
2281 return nullptr;
2282 if (!match(DivOp, m_FDiv(m_Value(Y), m_Value(Z))))
2283 return nullptr;
2284 if (!DivOp->hasAllowReassoc() || !I.hasAllowReciprocal() ||
2285 !DivOp->hasOneUse())
2286 return nullptr;
2287 Value *SwapDiv = Builder.CreateFDivFMF(Z, Y, DivOp);
2288 Value *NewSqrt =
2289 Builder.CreateUnaryIntrinsic(II->getIntrinsicID(), SwapDiv, II);
2290 return BinaryOperator::CreateFMulFMF(Op0, NewSqrt, &I);
2291}
2292
2293// Change
2294// X = 1/sqrt(a)
2295// R1 = X * X
2296// R2 = a * X
2297//
2298// TO
2299//
2300// FDiv = 1/a
2301// FSqrt = sqrt(a)
2302// FMul = FDiv * FSqrt
2303// Replace Uses Of R1 With FDiv
2304// Replace Uses Of R2 With FSqrt
2305// Replace Uses Of X With FMul
2306static Instruction *
2311
2312 B.SetInsertPoint(X);
2313
2314 // Have an instruction that is representative of all of instructions in R1 and
2315 // get the most common fpmath metadata and fast-math flags on it.
2316 Value *SqrtOp = CI->getArgOperand(0);
2317 auto *FDiv = cast<Instruction>(
2318 B.CreateFDiv(ConstantFP::get(X->getType(), 1.0), SqrtOp));
2319 auto *R1FPMathMDNode = (*R1.begin())->getMetadata(LLVMContext::MD_fpmath);
2320 FastMathFlags R1FMF = (*R1.begin())->getFastMathFlags(); // Common FMF
2321 for (Instruction *I : R1) {
2322 R1FPMathMDNode = MDNode::getMostGenericFPMath(
2323 R1FPMathMDNode, I->getMetadata(LLVMContext::MD_fpmath));
2324 R1FMF &= I->getFastMathFlags();
2325 IC->replaceInstUsesWith(*I, FDiv);
2327 }
2328 FDiv->setMetadata(LLVMContext::MD_fpmath, R1FPMathMDNode);
2329 FDiv->copyFastMathFlags(R1FMF);
2330
2331 // Have a single sqrt call instruction that is representative of all of
2332 // instructions in R2 and get the most common fpmath metadata and fast-math
2333 // flags on it.
2334 auto *FSqrt = cast<CallInst>(CI->clone());
2335 FSqrt->insertBefore(CI->getIterator());
2336 auto *R2FPMathMDNode = (*R2.begin())->getMetadata(LLVMContext::MD_fpmath);
2337 FastMathFlags R2FMF = (*R2.begin())->getFastMathFlags(); // Common FMF
2338 for (Instruction *I : R2) {
2339 R2FPMathMDNode = MDNode::getMostGenericFPMath(
2340 R2FPMathMDNode, I->getMetadata(LLVMContext::MD_fpmath));
2341 R2FMF &= I->getFastMathFlags();
2342 IC->replaceInstUsesWith(*I, FSqrt);
2344 }
2345 FSqrt->setMetadata(LLVMContext::MD_fpmath, R2FPMathMDNode);
2346 FSqrt->copyFastMathFlags(R2FMF);
2347
2349 // If X = -1/sqrt(a) initially,then FMul = -(FDiv * FSqrt)
2350 if (match(X, m_FDiv(m_SpecificFP(-1.0), m_Specific(CI)))) {
2351 Value *Mul = B.CreateFMul(FDiv, FSqrt);
2352 FMul = cast<Instruction>(B.CreateFNeg(Mul));
2353 } else
2354 FMul = cast<Instruction>(B.CreateFMul(FDiv, FSqrt));
2355 FMul->copyMetadata(*X);
2356 FMul->copyFastMathFlags(FastMathFlags::intersectRewrite(R1FMF, R2FMF) |
2357 FastMathFlags::unionValue(R1FMF, R2FMF));
2358 return IC->replaceInstUsesWith(*X, FMul);
2359}
2360
2362 Module *M = I.getModule();
2363
2364 if (Value *V = simplifyFDivInst(I.getOperand(0), I.getOperand(1),
2365 I.getFastMathFlags(),
2366 SQ.getWithInstruction(&I)))
2367 return replaceInstUsesWith(I, V);
2368
2370 return X;
2371
2373 return Phi;
2374
2375 if (Instruction *R = foldFDivConstantDivisor(I))
2376 return R;
2377
2379 return R;
2380
2381 if (Instruction *R = foldFPSignBitOps(I))
2382 return R;
2383
2384 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2385
2386 // Convert
2387 // x = 1.0/sqrt(a)
2388 // r1 = x * x;
2389 // r2 = a/sqrt(a);
2390 //
2391 // TO
2392 //
2393 // r1 = 1/a
2394 // r2 = sqrt(a)
2395 // x = r1 * r2
2397 if (isFSqrtDivToFMulLegal(&I, R1, R2)) {
2398 CallInst *CI = cast<CallInst>(I.getOperand(1));
2399 if (Instruction *D = convertFSqrtDivIntoFMul(CI, &I, R1, R2, Builder, this))
2400 return D;
2401 }
2402
2403 if (isa<Constant>(Op0))
2405 if (Instruction *R = FoldOpIntoSelect(I, SI))
2406 return R;
2407
2408 if (isa<Constant>(Op1))
2410 if (Instruction *R = FoldOpIntoSelect(I, SI))
2411 return R;
2412
2413 if (I.hasAllowReassoc() && I.hasAllowReciprocal()) {
2414 Value *X, *Y;
2415 if (match(Op0, m_OneUse(m_FDiv(m_Value(X), m_Value(Y)))) &&
2416 (!isa<Constant>(Y) || !isa<Constant>(Op1))) {
2417 // (X / Y) / Z => X / (Y * Z)
2418 Value *YZ = Builder.CreateFMulFMF(Y, Op1, &I);
2419 return BinaryOperator::CreateFDivFMF(X, YZ, &I);
2420 }
2421 if (match(Op1, m_OneUse(m_FDiv(m_Value(X), m_Value(Y)))) &&
2422 (!isa<Constant>(Y) || !isa<Constant>(Op0))) {
2423 // Z / (X / Y) => (Y * Z) / X
2424 Value *YZ = Builder.CreateFMulFMF(Y, Op0, &I);
2425 return BinaryOperator::CreateFDivFMF(YZ, X, &I);
2426 }
2427 // Z / (1.0 / Y) => (Y * Z)
2428 //
2429 // This is a special case of Z / (X / Y) => (Y * Z) / X, with X = 1.0. The
2430 // m_OneUse check is avoided because even in the case of the multiple uses
2431 // for 1.0/Y, the number of instructions remain the same and a division is
2432 // replaced by a multiplication.
2433 if (match(Op1, m_FDiv(m_SpecificFP(1.0), m_Value(Y))))
2434 return BinaryOperator::CreateFMulFMF(Y, Op0, &I);
2435 }
2436
2437 if (I.hasAllowReassoc() && Op0->hasOneUse() && Op1->hasOneUse()) {
2438 // sin(X) / cos(X) -> tan(X)
2439 // cos(X) / sin(X) -> 1/tan(X) (cotangent)
2440 Value *X;
2441 bool IsTan = match(Op0, m_Intrinsic<Intrinsic::sin>(m_Value(X))) &&
2443 bool IsCot =
2444 !IsTan && match(Op0, m_Intrinsic<Intrinsic::cos>(m_Value(X))) &&
2446
2447 if ((IsTan || IsCot) && hasFloatFn(M, &TLI, I.getType(), LibFunc_tan,
2448 LibFunc_tanf, LibFunc_tanl)) {
2449 IRBuilder<> B(&I);
2451 B.setFastMathFlags(I.getFastMathFlags());
2452 AttributeList Attrs =
2453 cast<CallBase>(Op0)->getCalledFunction()->getAttributes();
2454 Value *Res = emitUnaryFloatFnCall(X, &TLI, LibFunc_tan, LibFunc_tanf,
2455 LibFunc_tanl, B, Attrs);
2456 if (IsCot)
2457 Res = B.CreateFDiv(ConstantFP::get(I.getType(), 1.0), Res);
2458 return replaceInstUsesWith(I, Res);
2459 }
2460 }
2461
2462 // X / (X * Y) --> 1.0 / Y
2463 // Reassociate to (X / X -> 1.0) is legal when NaNs are not allowed.
2464 // We can ignore the possibility that X is infinity because INF/INF is NaN.
2465 Value *X, *Y;
2466 if (I.hasNoNaNs() && I.hasAllowReassoc() &&
2467 match(Op1, m_c_FMul(m_Specific(Op0), m_Value(Y)))) {
2468 replaceOperand(I, 0, ConstantFP::get(I.getType(), 1.0));
2469 replaceOperand(I, 1, Y);
2470 return &I;
2471 }
2472
2473 // X / fabs(X) -> copysign(1.0, X)
2474 // fabs(X) / X -> copysign(1.0, X)
2475 if (I.hasNoNaNs() && I.hasNoInfs() &&
2476 (match(&I, m_FDiv(m_Value(X), m_FAbs(m_Deferred(X)))) ||
2477 match(&I, m_FDiv(m_FAbs(m_Value(X)), m_Deferred(X))))) {
2478 Value *V = Builder.CreateBinaryIntrinsic(
2479 Intrinsic::copysign, ConstantFP::get(I.getType(), 1.0), X, &I);
2480 return replaceInstUsesWith(I, V);
2481 }
2482
2484 return Mul;
2485
2487 return Mul;
2488
2489 // pow(X, Y) / X --> pow(X, Y-1)
2490 if (I.hasAllowReassoc() &&
2492 m_Value(Y))))) {
2493 Value *Y1 =
2494 Builder.CreateFAddFMF(Y, ConstantFP::get(I.getType(), -1.0), &I);
2495 Value *Pow = Builder.CreateBinaryIntrinsic(Intrinsic::pow, Op1, Y1, &I);
2496 return replaceInstUsesWith(I, Pow);
2497 }
2498
2499 if (Instruction *FoldedPowi = foldPowiReassoc(I))
2500 return FoldedPowi;
2501
2502 return nullptr;
2503}
2504
2505// Variety of transform for:
2506// (urem/srem (mul X, Y), (mul X, Z))
2507// (urem/srem (shl X, Y), (shl X, Z))
2508// (urem/srem (shl Y, X), (shl Z, X))
2509// NB: The shift cases are really just extensions of the mul case. We treat
2510// shift as Val * (1 << Amt).
2512 InstCombinerImpl &IC) {
2513 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1), *X = nullptr;
2514 APInt Y, Z;
2515 bool ShiftByX = false;
2516
2517 // If V is not nullptr, it will be matched using m_Specific.
2518 auto MatchShiftOrMulXC = [](Value *Op, Value *&V, APInt &C,
2519 bool &PreserveNSW) -> bool {
2520 const APInt *Tmp = nullptr;
2521 if ((!V && match(Op, m_Mul(m_Value(V), m_APInt(Tmp)))) ||
2522 (V && match(Op, m_Mul(m_Specific(V), m_APInt(Tmp)))))
2523 C = *Tmp;
2524 else if ((!V && match(Op, m_Shl(m_Value(V), m_APInt(Tmp)))) ||
2525 (V && match(Op, m_Shl(m_Specific(V), m_APInt(Tmp))))) {
2526 C = APInt(Tmp->getBitWidth(), 1) << *Tmp;
2527 // We cannot preserve NSW when shifting by BW - 1.
2528 PreserveNSW = Tmp->ult(Tmp->getBitWidth() - 1);
2529 }
2530 if (Tmp != nullptr)
2531 return true;
2532
2533 // Reset `V` so we don't start with specific value on next match attempt.
2534 V = nullptr;
2535 return false;
2536 };
2537
2538 auto MatchShiftCX = [](Value *Op, APInt &C, Value *&V) -> bool {
2539 const APInt *Tmp = nullptr;
2540 if ((!V && match(Op, m_Shl(m_APInt(Tmp), m_Value(V)))) ||
2541 (V && match(Op, m_Shl(m_APInt(Tmp), m_Specific(V))))) {
2542 C = *Tmp;
2543 return true;
2544 }
2545
2546 // Reset `V` so we don't start with specific value on next match attempt.
2547 V = nullptr;
2548 return false;
2549 };
2550
2551 bool Op0PreserveNSW = true, Op1PreserveNSW = true;
2552 if (MatchShiftOrMulXC(Op0, X, Y, Op0PreserveNSW) &&
2553 MatchShiftOrMulXC(Op1, X, Z, Op1PreserveNSW)) {
2554 // pass
2555 } else if (MatchShiftCX(Op0, Y, X) && MatchShiftCX(Op1, Z, X)) {
2556 ShiftByX = true;
2557 } else {
2558 return nullptr;
2559 }
2560
2561 bool IsSRem = I.getOpcode() == Instruction::SRem;
2562
2564 // TODO: We may be able to deduce more about nsw/nuw of BO0/BO1 based on Y >=
2565 // Z or Z >= Y.
2566 bool BO0HasNSW = Op0PreserveNSW && BO0->hasNoSignedWrap();
2567 bool BO0HasNUW = BO0->hasNoUnsignedWrap();
2568 bool BO0NoWrap = IsSRem ? BO0HasNSW : BO0HasNUW;
2569
2570 APInt RemYZ = IsSRem ? Y.srem(Z) : Y.urem(Z);
2571 // (rem (mul nuw/nsw X, Y), (mul X, Z))
2572 // if (rem Y, Z) == 0
2573 // -> 0
2574 if (RemYZ.isZero() && BO0NoWrap)
2575 return IC.replaceInstUsesWith(I, ConstantInt::getNullValue(I.getType()));
2576
2577 // Helper function to emit either (RemSimplificationC << X) or
2578 // (RemSimplificationC * X) depending on whether we matched Op0/Op1 as
2579 // (shl V, X) or (mul V, X) respectively.
2580 auto CreateMulOrShift =
2581 [&](const APInt &RemSimplificationC) -> BinaryOperator * {
2582 Value *RemSimplification =
2583 ConstantInt::get(I.getType(), RemSimplificationC);
2584 return ShiftByX ? BinaryOperator::CreateShl(RemSimplification, X)
2585 : BinaryOperator::CreateMul(X, RemSimplification);
2586 };
2587
2589 bool BO1HasNSW = Op1PreserveNSW && BO1->hasNoSignedWrap();
2590 bool BO1HasNUW = BO1->hasNoUnsignedWrap();
2591 bool BO1NoWrap = IsSRem ? BO1HasNSW : BO1HasNUW;
2592 // (rem (mul X, Y), (mul nuw/nsw X, Z))
2593 // if (rem Y, Z) == Y
2594 // -> (mul nuw/nsw X, Y)
2595 if (RemYZ == Y && BO1NoWrap) {
2596 BinaryOperator *BO = CreateMulOrShift(Y);
2597 // Copy any overflow flags from Op0.
2598 BO->setHasNoSignedWrap(IsSRem || BO0HasNSW);
2599 BO->setHasNoUnsignedWrap(!IsSRem || BO0HasNUW);
2600 return BO;
2601 }
2602
2603 // (rem (mul nuw/nsw X, Y), (mul {nsw} X, Z))
2604 // if Y >= Z
2605 // -> (mul {nuw} nsw X, (rem Y, Z))
2606 if (Y.uge(Z) && (IsSRem ? (BO0HasNSW && BO1HasNSW) : BO0HasNUW)) {
2607 BinaryOperator *BO = CreateMulOrShift(RemYZ);
2608 BO->setHasNoSignedWrap();
2609 BO->setHasNoUnsignedWrap(BO0HasNUW);
2610 return BO;
2611 }
2612
2613 return nullptr;
2614}
2615
2616/// This function implements the transforms common to both integer remainder
2617/// instructions (urem and srem). It is called by the visitors to those integer
2618/// remainder instructions.
2619/// Common integer remainder transforms
2622 return Res;
2623
2624 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2625
2626 if (isa<Constant>(Op1)) {
2627 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2628 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2629 if (Instruction *R = FoldOpIntoSelect(I, SI))
2630 return R;
2631 } else if (auto *PN = dyn_cast<PHINode>(Op0I)) {
2632 const APInt *Op1Int;
2633 if (match(Op1, m_APInt(Op1Int)) && !Op1Int->isMinValue() &&
2634 (I.getOpcode() == Instruction::URem ||
2635 !Op1Int->isMinSignedValue())) {
2636 // foldOpIntoPhi will speculate instructions to the end of the PHI's
2637 // predecessor blocks, so do this only if we know the srem or urem
2638 // will not fault.
2639 if (Instruction *NV = foldOpIntoPhi(I, PN))
2640 return NV;
2641 }
2642 }
2643
2644 // See if we can fold away this rem instruction.
2646 return &I;
2647 }
2648 }
2649
2650 if (Instruction *R = simplifyIRemMulShl(I, *this))
2651 return R;
2652
2653 return nullptr;
2654}
2655
2657 if (Value *V = simplifyURemInst(I.getOperand(0), I.getOperand(1),
2658 SQ.getWithInstruction(&I)))
2659 return replaceInstUsesWith(I, V);
2660
2662 return X;
2663
2664 if (Instruction *common = commonIRemTransforms(I))
2665 return common;
2666
2667 if (Instruction *NarrowRem = narrowUDivURem(I, *this))
2668 return NarrowRem;
2669
2670 // X urem Y -> X and Y-1, where Y is a power of 2,
2671 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2672 Type *Ty = I.getType();
2673 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/ true, &I)) {
2674 // This may increase instruction count, we don't enforce that Y is a
2675 // constant.
2677 Value *Add = Builder.CreateAdd(Op1, N1);
2678 return BinaryOperator::CreateAnd(Op0, Add);
2679 }
2680
2681 // 1 urem X -> zext(X != 1)
2682 if (match(Op0, m_One())) {
2683 Value *Cmp = Builder.CreateICmpNE(Op1, ConstantInt::get(Ty, 1));
2684 return CastInst::CreateZExtOrBitCast(Cmp, Ty);
2685 }
2686
2687 // Op0 urem C -> Op0 < C ? Op0 : Op0 - C, where C >= signbit.
2688 // Op0 must be frozen because we are increasing its number of uses.
2689 if (match(Op1, m_Negative())) {
2690 Value *F0 = Op0;
2691 if (!isGuaranteedNotToBeUndef(Op0))
2692 F0 = Builder.CreateFreeze(Op0, Op0->getName() + ".fr");
2693 Value *Cmp = Builder.CreateICmpULT(F0, Op1);
2694 Value *Sub = Builder.CreateSub(F0, Op1);
2695 return createSelectInstWithUnknownProfile(Cmp, F0, Sub);
2696 }
2697
2698 // If the divisor is a sext of a boolean, then the divisor must be max
2699 // unsigned value (-1). Therefore, the remainder is Op0 unless Op0 is also
2700 // max unsigned value. In that case, the remainder is 0:
2701 // urem Op0, (sext i1 X) --> (Op0 == -1) ? 0 : Op0
2702 Value *X;
2703 if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
2704 Value *FrozenOp0 = Op0;
2705 if (!isGuaranteedNotToBeUndef(Op0))
2706 FrozenOp0 = Builder.CreateFreeze(Op0, Op0->getName() + ".frozen");
2707 Value *Cmp =
2708 Builder.CreateICmpEQ(FrozenOp0, ConstantInt::getAllOnesValue(Ty));
2709 return createSelectInstWithUnknownProfile(
2710 Cmp, ConstantInt::getNullValue(Ty), FrozenOp0);
2711 }
2712
2713 // For "(X + 1) % Op1" and if (X u< Op1) => (X + 1) == Op1 ? 0 : X + 1 .
2714 if (match(Op0, m_Add(m_Value(X), m_One()))) {
2715 Value *Val =
2716 simplifyICmpInst(ICmpInst::ICMP_ULT, X, Op1, SQ.getWithInstruction(&I));
2717 if (Val && match(Val, m_One())) {
2718 Value *FrozenOp0 = Op0;
2719 if (!isGuaranteedNotToBeUndef(Op0))
2720 FrozenOp0 = Builder.CreateFreeze(Op0, Op0->getName() + ".frozen");
2721 Value *Cmp = Builder.CreateICmpEQ(FrozenOp0, Op1);
2722 return createSelectInstWithUnknownProfile(
2723 Cmp, ConstantInt::getNullValue(Ty), FrozenOp0);
2724 }
2725 }
2726
2727 return nullptr;
2728}
2729
2731 if (Value *V = simplifySRemInst(I.getOperand(0), I.getOperand(1),
2732 SQ.getWithInstruction(&I)))
2733 return replaceInstUsesWith(I, V);
2734
2736 return X;
2737
2738 // Handle the integer rem common cases
2739 if (Instruction *Common = commonIRemTransforms(I))
2740 return Common;
2741
2742 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2743 {
2744 const APInt *Y;
2745 // X % -Y -> X % Y
2746 if (match(Op1, m_Negative(Y)) && !Y->isMinSignedValue())
2747 return replaceOperand(I, 1, ConstantInt::get(I.getType(), -*Y));
2748 }
2749
2750 // -X srem Y --> -(X srem Y)
2751 Value *X, *Y;
2753 return BinaryOperator::CreateNSWNeg(Builder.CreateSRem(X, Y));
2754
2755 // If the sign bits of both operands are zero (i.e. we can prove they are
2756 // unsigned inputs), turn this into a urem.
2757 APInt Mask(APInt::getSignMask(I.getType()->getScalarSizeInBits()));
2758 if (MaskedValueIsZero(Op1, Mask, &I) && MaskedValueIsZero(Op0, Mask, &I)) {
2759 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2760 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
2761 }
2762
2763 // If it's a constant vector, flip any negative values positive.
2765 Constant *C = cast<Constant>(Op1);
2766 unsigned VWidth = cast<FixedVectorType>(C->getType())->getNumElements();
2767
2768 bool hasNegative = false;
2769 bool hasMissing = false;
2770 for (unsigned i = 0; i != VWidth; ++i) {
2771 Constant *Elt = C->getAggregateElement(i);
2772 if (!Elt) {
2773 hasMissing = true;
2774 break;
2775 }
2776
2777 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
2778 if (RHS->isNegative())
2779 hasNegative = true;
2780 }
2781
2782 if (hasNegative && !hasMissing) {
2783 SmallVector<Constant *, 16> Elts(VWidth);
2784 for (unsigned i = 0; i != VWidth; ++i) {
2785 Elts[i] = C->getAggregateElement(i); // Handle undef, etc.
2786 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
2787 if (RHS->isNegative())
2789 }
2790 }
2791
2792 Constant *NewRHSV = ConstantVector::get(Elts);
2793 if (NewRHSV != C) // Don't loop on -MININT
2794 return replaceOperand(I, 1, NewRHSV);
2795 }
2796 }
2797
2798 return nullptr;
2799}
2800
2802 if (Value *V = simplifyFRemInst(I.getOperand(0), I.getOperand(1),
2803 I.getFastMathFlags(),
2804 SQ.getWithInstruction(&I)))
2805 return replaceInstUsesWith(I, V);
2806
2808 return X;
2809
2811 return Phi;
2812
2813 // Cases:
2814 // frem(x, -y) -> frem(x, y)
2815 // frem(x, |y|) -> frem(x, y)
2816 // frem(x, copysign(y, z)) -> frem(x, y)
2817 Value *Y = I.getOperand(1);
2818 Value *StrippedY = stripSignOnlyFPOps(Y);
2819 if (StrippedY != Y)
2820 return replaceOperand(I, 1, StrippedY);
2821
2822 return nullptr;
2823}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file provides internal interfaces used to implement the InstCombine.
static Instruction * convertFSqrtDivIntoFMul(CallInst *CI, Instruction *X, const SmallPtrSetImpl< Instruction * > &R1, const SmallPtrSetImpl< Instruction * > &R2, InstCombiner::BuilderTy &B, InstCombinerImpl *IC)
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 bool getFSqrtDivOptPattern(Instruction *Div, SmallPtrSetImpl< Instruction * > &R1, SmallPtrSetImpl< Instruction * > &R2)
static Value * foldMulSelectToNegate(BinaryOperator &I, InstCombiner::BuilderTy &Builder)
static bool isFSqrtDivToFMulLegal(Instruction *X, SmallPtrSetImpl< Instruction * > &R1, SmallPtrSetImpl< Instruction * > &R2)
static Instruction * foldFDivPowDivisor(BinaryOperator &I, InstCombiner::BuilderTy &Builder)
Negate the exponent of pow/exp to fold division-by-pow() into multiply.
static Value * simplifyValueKnownNonZero(Value *V, InstCombinerImpl &IC, Instruction &CtxI)
The specific integer value is used in a context where it is known to be non-zero.
static bool multiplyOverflows(const APInt &C1, const APInt &C2, APInt &Product, bool IsSigned)
True if the multiply can not be expressed in an int this size.
static Value * foldMulShl1(BinaryOperator &Mul, bool CommuteOperands, InstCombiner::BuilderTy &Builder)
Reduce integer multiplication patterns that contain a (+/-1 << Z) factor.
static bool isMultiple(const APInt &C1, const APInt &C2, APInt &Quotient, bool IsSigned)
True if C1 is a multiple of C2. Quotient contains C1/C2.
static Instruction * foldFDivSqrtDivisor(BinaryOperator &I, InstCombiner::BuilderTy &Builder)
Convert div to mul if we have an sqrt divisor iff sqrt's operand is a fdiv instruction.
static Instruction * foldFDivConstantDividend(BinaryOperator &I)
Remove negation and try to reassociate constant math.
static Value * foldIDivShl(BinaryOperator &I, InstCombiner::BuilderTy &Builder)
static bool isKnownExactFromRem(const BinaryOperator &Div, const SimplifyQuery &Q)
Return true if a matching remainder is known to be zero at the division.
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:57
#define R2(n)
uint64_t IntrinsicInst * II
This file contains the declarations for profiling metadata utility functions.
SmallVector< MachineOperand, 4 > Cond
int64_t C1
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
BinaryOperator * Mul
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt udiv(const APInt &RHS) const
Unsigned division operation.
Definition APInt.cpp:1602
static LLVM_ABI void udivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, APInt &Remainder)
Dual division/remainder interface.
Definition APInt.cpp:1796
static APInt getSignMask(unsigned BitWidth)
Get the SignMask for a specific bit width.
Definition APInt.h:225
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition APInt.h:419
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
static LLVM_ABI void sdivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, APInt &Remainder)
Definition APInt.cpp:1928
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:367
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition APInt.h:1186
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:376
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1115
bool isMinValue() const
Determine if this is the smallest unsigned value.
Definition APInt.h:413
LLVM_ABI APInt sdiv(const APInt &RHS) const
Signed division function for APInt.
Definition APInt.cpp:1673
unsigned countr_zero() const
Count the number of trailing zero bits.
Definition APInt.h:1659
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:215
LLVM_ABI APInt ushl_ov(const APInt &Amt, bool &Overflow) const
Definition APInt.cpp:2052
unsigned getSignificantBits() const
Get the minimum bit size for this signed APInt.
Definition APInt.h:1551
unsigned logBase2() const
Definition APInt.h:1781
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
Definition APInt.h:829
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition APInt.h:1154
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:235
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition APInt.h:853
MutableArrayRef< ResultElem > assumptionsFor(const Value *V)
Access the list of assumptions which affect this value.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
static BinaryOperator * CreateFAddFMF(Value *V1, Value *V2, FastMathFlags FMF, const Twine &Name="")
Definition InstrTypes.h:271
static LLVM_ABI 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:409
static BinaryOperator * CreateExact(BinaryOps Opc, Value *V1, Value *V2, const Twine &Name="")
Definition InstrTypes.h:344
static LLVM_ABI 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:279
static BinaryOperator * CreateFDivFMF(Value *V1, Value *V2, FastMathFlags FMF, const Twine &Name="")
Definition InstrTypes.h:283
static BinaryOperator * CreateFSubFMF(Value *V1, Value *V2, FastMathFlags FMF, const Twine &Name="")
Definition InstrTypes.h:275
static BinaryOperator * CreateWithCopiedFlags(BinaryOps Opc, Value *V1, Value *V2, Value *CopyO, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Definition InstrTypes.h:254
static LLVM_ABI BinaryOperator * CreateNSWNeg(Value *Op, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Value * getArgOperand(unsigned i) const
This class represents a function call, abstracting a target machine's calling convention.
static LLVM_ABI CastInst * CreateZExtOrBitCast(Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Create a ZExt or BitCast cast instruction.
static LLVM_ABI 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.
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
Conditional Branch instruction.
static LLVM_ABI Constant * getNeg(Constant *C, bool HasNSW=false)
static LLVM_ABI Constant * getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI 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...
static LLVM_ABI ConstantFP * getInfinity(Type *Ty, bool Negative=false)
This is the shared class of boolean and integer constants.
Definition Constants.h:87
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
static LLVM_ABI ConstantInt * getBool(LLVMContext &Context, bool V)
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
This is an important base class in LLVM.
Definition Constant.h:44
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
LLVM_ABI bool isNormalFP() const
Return true if this is a normal (as opposed to denormal, infinity, nan, or zero) floating-point scala...
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
LLVM_ABI bool isNotMinSignedValue() const
Return true if the value is not the smallest signed value, or, for vectors, does not contain smallest...
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
ArrayRef< CondBrInst * > conditionsFor(const Value *V) const
Access the list of branches which affect this value.
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:23
static FastMathFlags intersectRewrite(FastMathFlags LHS, FastMathFlags RHS)
Intersect rewrite-based flags.
Definition FMF.h:116
static FastMathFlags unionValue(FastMathFlags LHS, FastMathFlags RHS)
Union value flags.
Definition FMF.h:124
bool allowReassoc() const
Flag queries.
Definition FMF.h:64
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1441
Value * CreateShl(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1513
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:1733
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition IRBuilder.h:197
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2990
Instruction * visitMul(BinaryOperator &I)
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)
bool SimplifyDemandedInstructionFPClass(Instruction &Inst)
Instruction * foldOpIntoPhi(Instruction &I, PHINode *PN, bool AllowMultipleUses=false)
Given a binary operator, cast instruction, or select which has a PHI node as operand #0,...
Value * takeLog2(Value *Op, unsigned Depth, bool AssumeNonZero, bool DoFold)
Take the exact integer log2 of the value.
Instruction * visitSRem(BinaryOperator &I)
Instruction * foldBinOpSelectBinOp(BinaryOperator &Op)
In some cases it is beneficial to fold a select into a binary operator.
Instruction * visitFDiv(BinaryOperator &I)
Instruction * FoldOpIntoSelect(Instruction &Op, SelectInst *SI, bool FoldWithMultiUse=false, bool SimplifyBothArms=false)
Given an instruction with a select as one operand and a constant as the other operand,...
bool simplifyDivRemOfSelectWithZeroOp(BinaryOperator &I)
Fold a divide or remainder with a select instruction divisor when one of the select operands is zero.
Instruction * eraseInstFromFunction(Instruction &I) override
Combiner aware instruction erasure.
Instruction * commonIDivRemTransforms(BinaryOperator &I)
Common integer divide/remainder transforms.
Value * tryGetLog2(Value *Op, bool AssumeNonZero)
Instruction * commonIDivTransforms(BinaryOperator &I)
This function implements the transforms common to both integer division instructions (udiv and sdiv).
Instruction * foldBinopWithPhiOperands(BinaryOperator &BO)
For a binary operator with 2 phi operands, try to hoist the binary operation before the phi.
Instruction * visitFRem(BinaryOperator &I)
InstCombinerImpl(InstructionWorklist &Worklist, Function &F, AAResults *AA, AssumptionCache &AC, TargetLibraryInfo &TLI, TargetTransformInfo &TTI, DominatorTree &DT, OptimizationRemarkEmitter &ORE, BlockFrequencyInfo *BFI, BranchProbabilityInfo *BPI, ProfileSummaryInfo *PSI, const DataLayout &DL, ReversePostOrderTraversal< BasicBlock * > &RPOT, const InstCombineCLOptions &CLOpts)
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
const DataLayout & getDataLayout() const
bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero=false, const Instruction *CtxI=nullptr, unsigned Depth=0)
TargetLibraryInfo & TLI
Instruction * replaceInstUsesWith(Instruction &I, Value *V)
A combiner-aware RAUW-like routine.
void replaceUse(Use &U, Value *NewValue)
Replace use and add the previously used value to the worklist.
InstructionWorklist & Worklist
A worklist of the instructions that need to be simplified.
const DataLayout & DL
bool MaskedValueIsZero(const Value *V, const APInt &Mask, const Instruction *CtxI=nullptr, unsigned Depth=0) const
IRBuilder< TargetFolder, IRBuilderInstCombineInserter > BuilderTy
An IRBuilder that automatically inserts new instructions into the worklist.
static Value * stripSignOnlyFPOps(Value *Val)
Ignore all operations which only change the sign of a value, returning the underlying magnitude value...
Instruction * replaceOperand(Instruction &I, unsigned OpNum, Value *V)
Replace operand of instruction and add old operand to the worklist.
void computeKnownBits(const Value *V, KnownBits &Known, const Instruction *CtxI, unsigned Depth=0) const
LLVM_ABI Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following:
LLVM_ABI void setHasNoUnsignedWrap(bool b=true)
Set or clear the nuw flag on this instruction, which must be an operator which supports this flag.
LLVM_ABI bool hasNoNaNs() const LLVM_READONLY
Determine whether the no-NaNs flag is set.
LLVM_ABI bool hasNoInfs() const LLVM_READONLY
Determine whether the no-infs flag is set.
LLVM_ABI bool hasNoSignedZeros() const LLVM_READONLY
Determine whether the no-signed-zeros flag is set.
LLVM_ABI bool hasNoSignedWrap() const LLVM_READONLY
Determine whether the no signed wrap flag is set.
LLVM_ABI void setHasNoSignedWrap(bool b=true)
Set or clear the nsw flag on this instruction, which must be an operator which supports this flag.
iterator_range< user_iterator > users()
LLVM_ABI FastMathFlags getFastMathFlags() const LLVM_READONLY
Convenience function for getting all the fast-math flags, which must be an operator which supports th...
LLVM_ABI void setIsExact(bool b=true)
Set or clear the exact flag on this instruction, which must be an operator which supports this flag.
LLVM_ABI bool hasAllowReassoc() const LLVM_READONLY
Determine whether the allow-reassociation flag is set.
A wrapper class for inspecting calls to intrinsic functions.
static LLVM_ABI MDNode * getMostGenericFPMath(MDNode *A, MDNode *B)
Root of the metadata hierarchy.
Definition Metadata.h:65
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
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:78
bool hasNoSignedWrap() const
Test whether this operation is known to never undergo signed overflow, aka the nsw property.
Definition Operator.h:113
bool hasNoUnsignedWrap() const
Test whether this operation is known to never undergo unsigned overflow, aka the nuw property.
Definition Operator.h:107
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
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, const Instruction *MDFrom=nullptr)
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
iterator begin() const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.h:354
static UnaryOperator * CreateFNegFMF(Value *Op, Instruction *FMFSource, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Definition InstrTypes.h:156
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
Value * getOperand(unsigned i) const
Definition User.h:207
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
LLVM_ABI bool hasNUses(unsigned N) const
Return true if this Value has exactly N uses.
Definition Value.cpp:142
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:395
This class represents zero extension of integer types.
An efficient, type-erasing, non-owning reference to a callable.
self_iterator getIterator()
Definition ilist_node.h:123
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LLVM_ABI APInt GreatestCommonDivisor(APInt A, APInt B, bool IsSigned=false)
Compute GCD of two APInt values.
Definition APInt.cpp:826
SpecificConstantMatch m_ZeroInt()
Convenience matchers for specific integer values.
auto m_PosZeroFP()
Matches a floating-point positive zero.
BinaryOp_match< SpecificConstantMatch, SrcTy, TargetOpcode::G_SUB > m_Neg(const SrcTy &&Src)
Matches a register negated by a G_SUB.
AllOnesConstantMatch m_AllOnes()
BinaryOp_match< SrcTy, SpecificConstantMatch, TargetOpcode::G_XOR, true > m_Not(const SrcTy &&Src)
Matches a register not-ed by a G_XOR.
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
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.
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
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.
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.
BinaryOp_match< LHS, RHS, Instruction::URem > m_URem(const LHS &L, const RHS &R)
CommutativeBinaryIntrinsic_match< IntrID, T0, T1 > m_c_Intrinsic(const T0 &Op0, const T1 &Op1)
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
CastInst_match< OpTy, TruncInst > m_Trunc(const OpTy &Op)
Matches Trunc.
auto m_Sqrt(const Opnd0 &Op0)
ap_match< APInt > m_APIntAllowPoison(const APInt *&Res)
Match APInt while allowing poison in splat vector constants.
specific_intval< false > m_SpecificInt(const APInt &V)
Match a specific integer value or vector with all elements equal to the value.
BinaryOp_match< LHS, RHS, Instruction::FMul > m_FMul(const LHS &L, const RHS &R)
bool match(Val *V, const Pattern &P)
match_bind< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
match_deferred< 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()...
cstfp_pred_ty< is_any_zero_fp > m_AnyZeroFP()
Match a floating-point negative zero or positive zero.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
BinOpPred_match< LHS, RHS, is_right_shift_op > m_Shr(const LHS &L, const RHS &R)
Matches logical shift operations.
specific_intval< true > m_SpecificIntAllowPoison(const APInt &V)
CmpClass_match< LHS, RHS, ICmpInst, true > m_c_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
Matches an ICmp with a predicate over LHS and RHS in either order.
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.
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_BinOp()
Match an arbitrary binary operation and ignore it.
specific_fpval m_SpecificFP(double V)
Match a specific floating point value or vector with all elements equal to the value.
auto m_Value()
Match an arbitrary value and ignore it.
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)
auto m_UndefValue()
Match an arbitrary UndefValue constant.
auto m_Constant()
Match an arbitrary Constant and ignore it.
ContainsMatchingVectorElement_match< SPTy > m_ContainsMatchingVectorElement(const SPTy &SubPattern)
Match a vector constant where at least one of its elements matches the subpattern.
TwoOps_match< V1_t, V2_t, Instruction::ShuffleVector > m_Shuffle(const V1_t &v1, const V2_t &v2)
Matches ShuffleVectorInst independently of mask value.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Shl, OverflowingBinaryOperator::NoSignedWrap > m_NSWShl(const LHS &L, const RHS &R)
AllowFmf_match< T, FastMathFlags::AllowReassoc > m_AllowReassoc(const T &SubPattern)
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)
is_zero< true > m_Zero()
Match any null constant or a vector with all elements equal to 0.
cst_pred_ty< is_negated_power2 > m_NegatedPower2()
Match a integer or vector negated power-of-2.
match_immconstant_ty m_ImmConstant()
Match an arbitrary immediate Constant and ignore it.
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.
specific_fpval m_FPOne()
Match a float 1.0 or vector with all elements equal to 1.0.
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)
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
BinaryOp_match< LHS, RHS, Instruction::SDiv > m_SDiv(const LHS &L, const RHS &R)
FNeg_match< OpTy, true > m_FNegOrFSubNegZero(const OpTy &X)
Match fneg X or fsub -0.0, X.
auto m_FAbs(const Opnd0 &Op0)
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".
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)
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< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
CastInst_match< OpTy, SExtInst > m_SExt(const OpTy &Op)
Matches SExt.
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".
ThreeOps_match< Val_t, Elt_t, Idx_t, Instruction::InsertElement > m_InsertElt(const Val_t &Val, const Elt_t &Elt, const Idx_t &Idx)
Matches InsertElementInst.
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.
LLVM_ABI 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.
LLVM_ABI cl::opt< bool > ProfcheckDisableMetadataFixes
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
LLVM_ABI 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.
LLVM_ABI void computeKnownBitsFromContext(const Value *V, KnownBits &Known, const SimplifyQuery &Q, unsigned Depth=0)
Merge bits known from context-dependent facts into Known.
@ Known
Known to have no common set bits.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI Value * simplifySDivInst(Value *LHS, Value *RHS, bool IsExact, const SimplifyQuery &Q)
Given operands for an SDiv, fold the result or return null.
LLVM_ABI Value * simplifyMulInst(Value *LHS, Value *RHS, bool IsNSW, bool IsNUW, const SimplifyQuery &Q)
Given operands for a Mul, fold the result or return null.
LLVM_ABI 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.
LLVM_ABI bool isKnownNegative(const WithCache< const Value * > &V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the given value is known be negative (i.e.
LLVM_ABI bool isGuaranteedNotToBeUndef(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be undef, but may be poison.
LLVM_ABI 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,...
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
constexpr unsigned MaxAnalysisRecursionDepth
LLVM_ABI Constant * ConstantFoldUnaryOpOperand(unsigned Opcode, Constant *Op, const DataLayout &DL)
Attempt to constant fold a unary operation with the specified operand.
LLVM_ABI Constant * getLosslessUnsignedTrunc(Constant *C, Type *DestTy, const DataLayout &DL, PreservedCastFlags *Flags=nullptr)
LLVM_ABI 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.
LLVM_ABI Value * simplifyICmpInst(CmpPredicate Pred, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for an ICmpInst, fold the result or return null.
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI Constant * ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS, Constant *RHS, const DataLayout &DL)
Attempt to constant fold a binary operation with the specified operands.
LLVM_ABI 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.
LLVM_ABI bool isKnownNonZero(const Value *V, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to be non-zero when defined.
@ Mul
Product of integers.
@ FMul
Product of floats.
@ Sub
Subtraction of integers.
@ Add
Sum of integers.
LLVM_ABI 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
LLVM_ABI bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I)
Return true if this function can prove that the instruction I will always transfer execution to one o...
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI 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:202
LLVM_ABI bool isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be poison, but may be undef.
LLVM_ABI bool isKnownNegation(const Value *X, const Value *Y, bool NeedNSW=false, bool AllowPoison=true)
Return true if the two given values are negation.
LLVM_ABI bool isKnownNonNegative(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the give value is known to be non-negative.
LLVM_ABI 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:881
#define N
bool isNonNegative() const
Returns true if this value is known to be non-negative.
Definition KnownBits.h:106
unsigned countMinTrailingZeros() const
Returns the minimum number of trailing zero bits.
Definition KnownBits.h:256
Matching combinators.
const DominatorTree * DT
SimplifyQuery getWithInstruction(const Instruction *I) const
AssumptionCache * AC
const DomConditionCache * DC