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