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