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