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