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