1//===- InstCombineAddSub.cpp ------------------------------------*- C++ -*-===//
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 add, fadd, sub, and fsub.
10//
11//===----------------------------------------------------------------------===//
12
13#include "InstCombineInternal.h"
14#include "llvm/ADT/APFloat.h"
15#include "llvm/ADT/APInt.h"
16#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/SmallVector.h"
18#include "llvm/Analysis/InstructionSimplify.h"
19#include "llvm/Analysis/ValueTracking.h"
20#include "llvm/IR/Constant.h"
21#include "llvm/IR/Constants.h"
22#include "llvm/IR/InstrTypes.h"
23#include "llvm/IR/Instruction.h"
24#include "llvm/IR/Instructions.h"
25#include "llvm/IR/Operator.h"
26#include "llvm/IR/PatternMatch.h"
27#include "llvm/IR/ProfDataUtils.h"
28#include "llvm/IR/Type.h"
29#include "llvm/IR/Value.h"
30#include "llvm/Support/AlignOf.h"
31#include "llvm/Support/Casting.h"
32#include "llvm/Support/KnownBits.h"
33#include "llvm/Transforms/InstCombine/InstCombiner.h"
34#include <cassert>
35#include <utility>
36
37using namespace llvm;
38using namespace PatternMatch;
39
40#define DEBUG_TYPE "instcombine"
41
42namespace llvm {
43extern cl::opt<bool> ProfcheckDisableMetadataFixes;
44}
45
46namespace {
47
48 /// Class representing coefficient of floating-point addend.
49 /// This class needs to be highly efficient, which is especially true for
50 /// the constructor. As of I write this comment, the cost of the default
51 /// constructor is merely 4-byte-store-zero (Assuming compiler is able to
52 /// perform write-merging).
53 ///
54 class FAddendCoef {
55 public:
56 // The constructor has to initialize a APFloat, which is unnecessary for
57 // most addends which have coefficient either 1 or -1. So, the constructor
58 // is expensive. In order to avoid the cost of the constructor, we should
59 // reuse some instances whenever possible. The pre-created instances
60 // FAddCombine::Add[0-5] embodies this idea.
61 FAddendCoef() = default;
62 ~FAddendCoef();
63
64 // If possible, don't define operator+/operator- etc because these
65 // operators inevitably call FAddendCoef's constructor which is not cheap.
66 void operator=(const FAddendCoef &A);
67 void operator+=(const FAddendCoef &A);
68 void operator*=(const FAddendCoef &S);
69
70 void set(short C) {
71 assert(!insaneIntVal(C) && "Insane coefficient");
72 IsFp = false; IntVal = C;
73 }
74
75 void set(const APFloat& C);
76
77 void negate();
78
79 bool isZero() const { return isInt() ? !IntVal : getFpVal().isZero(); }
80 Value *getValue(Type *) const;
81
82 bool isOne() const { return isInt() && IntVal == 1; }
83 bool isTwo() const { return isInt() && IntVal == 2; }
84 bool isMinusOne() const { return isInt() && IntVal == -1; }
85 bool isMinusTwo() const { return isInt() && IntVal == -2; }
86
87 private:
88 bool insaneIntVal(int V) { return V > 4 || V < -4; }
89
90 APFloat *getFpValPtr() { return reinterpret_cast<APFloat *>(&FpValBuf); }
91
92 const APFloat *getFpValPtr() const {
93 return reinterpret_cast<const APFloat *>(&FpValBuf);
94 }
95
96 const APFloat &getFpVal() const {
97 assert(IsFp && BufHasFpVal && "Incorrect state");
98 return *getFpValPtr();
99 }
100
101 APFloat &getFpVal() {
102 assert(IsFp && BufHasFpVal && "Incorrect state");
103 return *getFpValPtr();
104 }
105
106 bool isInt() const { return !IsFp; }
107
108 // If the coefficient is represented by an integer, promote it to a
109 // floating point.
110 void convertToFpType(const fltSemantics &Sem);
111
112 // Construct an APFloat from a signed integer.
113 // TODO: We should get rid of this function when APFloat can be constructed
114 // from an *SIGNED* integer.
115 APFloat createAPFloatFromInt(const fltSemantics &Sem, int Val);
116
117 bool IsFp = false;
118
119 // True iff FpValBuf contains an instance of APFloat.
120 bool BufHasFpVal = false;
121
122 // The integer coefficient of an individual addend is either 1 or -1,
123 // and we try to simplify at most 4 addends from neighboring at most
124 // two instructions. So the range of <IntVal> falls in [-4, 4]. APInt
125 // is overkill of this end.
126 short IntVal = 0;
127
128 AlignedCharArrayUnion<APFloat> FpValBuf;
129 };
130
131 /// FAddend is used to represent floating-point addend. An addend is
132 /// represented as <C, V>, where the V is a symbolic value, and C is a
133 /// constant coefficient. A constant addend is represented as <C, 0>.
134 class FAddend {
135 public:
136 FAddend() = default;
137
138 void operator+=(const FAddend &T) {
139 assert((Val == T.Val) && "Symbolic-values disagree");
140 Coeff += T.Coeff;
141 }
142
143 Value *getSymVal() const { return Val; }
144 const FAddendCoef &getCoef() const { return Coeff; }
145
146 bool isConstant() const { return Val == nullptr; }
147 bool isZero() const { return Coeff.isZero(); }
148
149 void set(short Coefficient, Value *V) {
150 Coeff.set(Coefficient);
151 Val = V;
152 }
153 void set(const APFloat &Coefficient, Value *V) {
154 Coeff.set(Coefficient);
155 Val = V;
156 }
157 void set(const ConstantFP *Coefficient, Value *V) {
158 Coeff.set(Coefficient->getValueAPF());
159 Val = V;
160 }
161
162 void negate() { Coeff.negate(); }
163
164 /// Drill down the U-D chain one step to find the definition of V, and
165 /// try to break the definition into one or two addends.
166 static unsigned drillValueDownOneStep(Value* V, FAddend &A0, FAddend &A1);
167
168 /// Similar to FAddend::drillDownOneStep() except that the value being
169 /// splitted is the addend itself.
170 unsigned drillAddendDownOneStep(FAddend &Addend0, FAddend &Addend1) const;
171
172 private:
173 void Scale(const FAddendCoef& ScaleAmt) { Coeff *= ScaleAmt; }
174
175 // This addend has the value of "Coeff * Val".
176 Value *Val = nullptr;
177 FAddendCoef Coeff;
178 };
179
180 /// FAddCombine is the class for optimizing an unsafe fadd/fsub along
181 /// with its neighboring at most two instructions.
182 ///
183 class FAddCombine {
184 public:
185 FAddCombine(InstCombiner::BuilderTy &B) : Builder(B) {}
186
187 Value *simplify(Instruction *FAdd);
188
189 private:
190 using AddendVect = SmallVector<const FAddend *, 4>;
191
192 Value *simplifyFAdd(AddendVect& V, unsigned InstrQuota);
193
194 /// Convert given addend to a Value
195 Value *createAddendVal(const FAddend &A, bool& NeedNeg);
196
197 /// Return the number of instructions needed to emit the N-ary addition.
198 unsigned calcInstrNumber(const AddendVect& Vect);
199
200 Value *createFSub(Value *Opnd0, Value *Opnd1);
201 Value *createFAdd(Value *Opnd0, Value *Opnd1);
202 Value *createFMul(Value *Opnd0, Value *Opnd1);
203 Value *createFNeg(Value *V);
204 Value *createNaryFAdd(const AddendVect& Opnds, unsigned InstrQuota);
205 void createInstPostProc(Instruction *NewInst, bool NoNumber = false);
206
207 // Debugging stuff are clustered here.
208 #ifndef NDEBUG
209 unsigned CreateInstrNum;
210 void initCreateInstNum() { CreateInstrNum = 0; }
211 void incCreateInstNum() { CreateInstrNum++; }
212 #else
213 void initCreateInstNum() {}
214 void incCreateInstNum() {}
215 #endif
216
217 InstCombiner::BuilderTy &Builder;
218 Instruction *Instr = nullptr;
219 };
220
221} // end anonymous namespace
222
223//===----------------------------------------------------------------------===//
224//
225// Implementation of
226// {FAddendCoef, FAddend, FAddition, FAddCombine}.
227//
228//===----------------------------------------------------------------------===//
229FAddendCoef::~FAddendCoef() {
230 if (BufHasFpVal)
231 getFpValPtr()->~APFloat();
232}
233
234void FAddendCoef::set(const APFloat& C) {
235 APFloat *P = getFpValPtr();
236
237 if (isInt()) {
238 // As the buffer is meanless byte stream, we cannot call
239 // APFloat::operator=().
240 new(P) APFloat(C);
241 } else
242 *P = C;
243
244 IsFp = BufHasFpVal = true;
245}
246
247void FAddendCoef::convertToFpType(const fltSemantics &Sem) {
248 if (!isInt())
249 return;
250
251 APFloat *P = getFpValPtr();
252 if (IntVal > 0)
253 new(P) APFloat(Sem, IntVal);
254 else {
255 new(P) APFloat(Sem, 0 - IntVal);
256 P->changeSign();
257 }
258 IsFp = BufHasFpVal = true;
259}
260
261APFloat FAddendCoef::createAPFloatFromInt(const fltSemantics &Sem, int Val) {
262 if (Val >= 0)
263 return APFloat(Sem, Val);
264
265 APFloat T(Sem, 0 - Val);
266 T.changeSign();
267
268 return T;
269}
270
271void FAddendCoef::operator=(const FAddendCoef &That) {
272 if (That.isInt())
273 set(That.IntVal);
274 else
275 set(That.getFpVal());
276}
277
278void FAddendCoef::operator+=(const FAddendCoef &That) {
279 RoundingMode RndMode = RoundingMode::NearestTiesToEven;
280 if (isInt() == That.isInt()) {
281 if (isInt())
282 IntVal += That.IntVal;
283 else
284 getFpVal().add(RHS: That.getFpVal(), RM: RndMode);
285 return;
286 }
287
288 if (isInt()) {
289 const APFloat &T = That.getFpVal();
290 convertToFpType(Sem: T.getSemantics());
291 getFpVal().add(RHS: T, RM: RndMode);
292 return;
293 }
294
295 APFloat &T = getFpVal();
296 T.add(RHS: createAPFloatFromInt(Sem: T.getSemantics(), Val: That.IntVal), RM: RndMode);
297}
298
299void FAddendCoef::operator*=(const FAddendCoef &That) {
300 if (That.isOne())
301 return;
302
303 if (That.isMinusOne()) {
304 negate();
305 return;
306 }
307
308 if (isInt() && That.isInt()) {
309 int Res = IntVal * (int)That.IntVal;
310 assert(!insaneIntVal(Res) && "Insane int value");
311 IntVal = Res;
312 return;
313 }
314
315 const fltSemantics &Semantic =
316 isInt() ? That.getFpVal().getSemantics() : getFpVal().getSemantics();
317
318 if (isInt())
319 convertToFpType(Sem: Semantic);
320 APFloat &F0 = getFpVal();
321
322 if (That.isInt())
323 F0.multiply(RHS: createAPFloatFromInt(Sem: Semantic, Val: That.IntVal),
324 RM: APFloat::rmNearestTiesToEven);
325 else
326 F0.multiply(RHS: That.getFpVal(), RM: APFloat::rmNearestTiesToEven);
327}
328
329void FAddendCoef::negate() {
330 if (isInt())
331 IntVal = 0 - IntVal;
332 else
333 getFpVal().changeSign();
334}
335
336Value *FAddendCoef::getValue(Type *Ty) const {
337 return isInt() ?
338 ConstantFP::get(Ty, V: float(IntVal)) :
339 ConstantFP::get(Context&: Ty->getContext(), V: getFpVal());
340}
341
342// The definition of <Val> Addends
343// =========================================
344// A + B <1, A>, <1,B>
345// A - B <1, A>, <1,B>
346// 0 - B <-1, B>
347// C * A, <C, A>
348// A + C <1, A> <C, NULL>
349// 0 +/- 0 <0, NULL> (corner case)
350//
351// Legend: A and B are not constant, C is constant
352unsigned FAddend::drillValueDownOneStep
353 (Value *Val, FAddend &Addend0, FAddend &Addend1) {
354 Instruction *I = nullptr;
355 if (!Val || !(I = dyn_cast<Instruction>(Val)))
356 return 0;
357
358 unsigned Opcode = I->getOpcode();
359
360 if (Opcode == Instruction::FAdd || Opcode == Instruction::FSub) {
361 ConstantFP *C0, *C1;
362 Value *Opnd0 = I->getOperand(i: 0);
363 Value *Opnd1 = I->getOperand(i: 1);
364 if ((C0 = dyn_cast<ConstantFP>(Val: Opnd0)) && C0->isZero())
365 Opnd0 = nullptr;
366
367 if ((C1 = dyn_cast<ConstantFP>(Val: Opnd1)) && C1->isZero())
368 Opnd1 = nullptr;
369
370 if (Opnd0) {
371 if (!C0)
372 Addend0.set(Coefficient: 1, V: Opnd0);
373 else
374 Addend0.set(Coefficient: C0, V: nullptr);
375 }
376
377 if (Opnd1) {
378 FAddend &Addend = Opnd0 ? Addend1 : Addend0;
379 if (!C1)
380 Addend.set(Coefficient: 1, V: Opnd1);
381 else
382 Addend.set(Coefficient: C1, V: nullptr);
383 if (Opcode == Instruction::FSub)
384 Addend.negate();
385 }
386
387 if (Opnd0 || Opnd1)
388 return Opnd0 && Opnd1 ? 2 : 1;
389
390 // Both operands are zero. Weird!
391 Addend0.set(Coefficient: APFloat(C0->getValueAPF().getSemantics()), V: nullptr);
392 return 1;
393 }
394
395 if (I->getOpcode() == Instruction::FMul) {
396 Value *V0 = I->getOperand(i: 0);
397 Value *V1 = I->getOperand(i: 1);
398 if (ConstantFP *C = dyn_cast<ConstantFP>(Val: V0)) {
399 Addend0.set(Coefficient: C, V: V1);
400 return 1;
401 }
402
403 if (ConstantFP *C = dyn_cast<ConstantFP>(Val: V1)) {
404 Addend0.set(Coefficient: C, V: V0);
405 return 1;
406 }
407 }
408
409 return 0;
410}
411
412// Try to break *this* addend into two addends. e.g. Suppose this addend is
413// <2.3, V>, and V = X + Y, by calling this function, we obtain two addends,
414// i.e. <2.3, X> and <2.3, Y>.
415unsigned FAddend::drillAddendDownOneStep
416 (FAddend &Addend0, FAddend &Addend1) const {
417 if (isConstant())
418 return 0;
419
420 unsigned BreakNum = FAddend::drillValueDownOneStep(Val, Addend0, Addend1);
421 if (!BreakNum || Coeff.isOne())
422 return BreakNum;
423
424 Addend0.Scale(ScaleAmt: Coeff);
425
426 if (BreakNum == 2)
427 Addend1.Scale(ScaleAmt: Coeff);
428
429 return BreakNum;
430}
431
432Value *FAddCombine::simplify(Instruction *I) {
433 assert(I->hasAllowReassoc() && I->hasNoSignedZeros() &&
434 "Expected 'reassoc'+'nsz' instruction");
435
436 // Currently we are not able to handle vector type.
437 if (I->getType()->isVectorTy())
438 return nullptr;
439
440 assert((I->getOpcode() == Instruction::FAdd ||
441 I->getOpcode() == Instruction::FSub) && "Expect add/sub");
442
443 // Save the instruction before calling other member-functions.
444 Instr = I;
445
446 FAddend Opnd0, Opnd1, Opnd0_0, Opnd0_1, Opnd1_0, Opnd1_1;
447
448 unsigned OpndNum = FAddend::drillValueDownOneStep(Val: I, Addend0&: Opnd0, Addend1&: Opnd1);
449
450 // Step 1: Expand the 1st addend into Opnd0_0 and Opnd0_1.
451 unsigned Opnd0_ExpNum = 0;
452 unsigned Opnd1_ExpNum = 0;
453
454 if (!Opnd0.isConstant())
455 Opnd0_ExpNum = Opnd0.drillAddendDownOneStep(Addend0&: Opnd0_0, Addend1&: Opnd0_1);
456
457 // Step 2: Expand the 2nd addend into Opnd1_0 and Opnd1_1.
458 if (OpndNum == 2 && !Opnd1.isConstant())
459 Opnd1_ExpNum = Opnd1.drillAddendDownOneStep(Addend0&: Opnd1_0, Addend1&: Opnd1_1);
460
461 // Step 3: Try to optimize Opnd0_0 + Opnd0_1 + Opnd1_0 + Opnd1_1
462 if (Opnd0_ExpNum && Opnd1_ExpNum) {
463 AddendVect AllOpnds;
464 AllOpnds.push_back(Elt: &Opnd0_0);
465 AllOpnds.push_back(Elt: &Opnd1_0);
466 if (Opnd0_ExpNum == 2)
467 AllOpnds.push_back(Elt: &Opnd0_1);
468 if (Opnd1_ExpNum == 2)
469 AllOpnds.push_back(Elt: &Opnd1_1);
470
471 // Compute instruction quota. We should save at least one instruction.
472 unsigned InstQuota = 0;
473
474 Value *V0 = I->getOperand(i: 0);
475 Value *V1 = I->getOperand(i: 1);
476 InstQuota = ((!isa<Constant>(Val: V0) && V0->hasOneUse()) &&
477 (!isa<Constant>(Val: V1) && V1->hasOneUse())) ? 2 : 1;
478
479 if (Value *R = simplifyFAdd(V&: AllOpnds, InstrQuota: InstQuota))
480 return R;
481 }
482
483 if (OpndNum != 2) {
484 // The input instruction is : "I=0.0 +/- V". If the "V" were able to be
485 // splitted into two addends, say "V = X - Y", the instruction would have
486 // been optimized into "I = Y - X" in the previous steps.
487 //
488 const FAddendCoef &CE = Opnd0.getCoef();
489 return CE.isOne() ? Opnd0.getSymVal() : nullptr;
490 }
491
492 // step 4: Try to optimize Opnd0 + Opnd1_0 [+ Opnd1_1]
493 if (Opnd1_ExpNum) {
494 AddendVect AllOpnds;
495 AllOpnds.push_back(Elt: &Opnd0);
496 AllOpnds.push_back(Elt: &Opnd1_0);
497 if (Opnd1_ExpNum == 2)
498 AllOpnds.push_back(Elt: &Opnd1_1);
499
500 if (Value *R = simplifyFAdd(V&: AllOpnds, InstrQuota: 1))
501 return R;
502 }
503
504 // step 5: Try to optimize Opnd1 + Opnd0_0 [+ Opnd0_1]
505 if (Opnd0_ExpNum) {
506 AddendVect AllOpnds;
507 AllOpnds.push_back(Elt: &Opnd1);
508 AllOpnds.push_back(Elt: &Opnd0_0);
509 if (Opnd0_ExpNum == 2)
510 AllOpnds.push_back(Elt: &Opnd0_1);
511
512 if (Value *R = simplifyFAdd(V&: AllOpnds, InstrQuota: 1))
513 return R;
514 }
515
516 return nullptr;
517}
518
519Value *FAddCombine::simplifyFAdd(AddendVect& Addends, unsigned InstrQuota) {
520 unsigned AddendNum = Addends.size();
521 assert(AddendNum <= 4 && "Too many addends");
522
523 // For saving intermediate results;
524 unsigned NextTmpIdx = 0;
525 FAddend TmpResult[3];
526
527 // Simplified addends are placed <SimpVect>.
528 AddendVect SimpVect;
529
530 // The outer loop works on one symbolic-value at a time. Suppose the input
531 // addends are : <a1, x>, <b1, y>, <a2, x>, <c1, z>, <b2, y>, ...
532 // The symbolic-values will be processed in this order: x, y, z.
533 for (unsigned SymIdx = 0; SymIdx < AddendNum; SymIdx++) {
534
535 const FAddend *ThisAddend = Addends[SymIdx];
536 if (!ThisAddend) {
537 // This addend was processed before.
538 continue;
539 }
540
541 Value *Val = ThisAddend->getSymVal();
542
543 // If the resulting expr has constant-addend, this constant-addend is
544 // desirable to reside at the top of the resulting expression tree. Placing
545 // constant close to super-expr(s) will potentially reveal some
546 // optimization opportunities in super-expr(s). Here we do not implement
547 // this logic intentionally and rely on SimplifyAssociativeOrCommutative
548 // call later.
549
550 unsigned StartIdx = SimpVect.size();
551 SimpVect.push_back(Elt: ThisAddend);
552
553 // The inner loop collects addends sharing same symbolic-value, and these
554 // addends will be later on folded into a single addend. Following above
555 // example, if the symbolic value "y" is being processed, the inner loop
556 // will collect two addends "<b1,y>" and "<b2,Y>". These two addends will
557 // be later on folded into "<b1+b2, y>".
558 for (unsigned SameSymIdx = SymIdx + 1;
559 SameSymIdx < AddendNum; SameSymIdx++) {
560 const FAddend *T = Addends[SameSymIdx];
561 if (T && T->getSymVal() == Val) {
562 // Set null such that next iteration of the outer loop will not process
563 // this addend again.
564 Addends[SameSymIdx] = nullptr;
565 SimpVect.push_back(Elt: T);
566 }
567 }
568
569 // If multiple addends share same symbolic value, fold them together.
570 if (StartIdx + 1 != SimpVect.size()) {
571 FAddend &R = TmpResult[NextTmpIdx ++];
572 R = *SimpVect[StartIdx];
573 for (unsigned Idx = StartIdx + 1; Idx < SimpVect.size(); Idx++)
574 R += *SimpVect[Idx];
575
576 // Pop all addends being folded and push the resulting folded addend.
577 SimpVect.resize(N: StartIdx);
578 if (!R.isZero()) {
579 SimpVect.push_back(Elt: &R);
580 }
581 }
582 }
583
584 assert((NextTmpIdx <= std::size(TmpResult) + 1) && "out-of-bound access");
585
586 Value *Result;
587 if (!SimpVect.empty())
588 Result = createNaryFAdd(Opnds: SimpVect, InstrQuota);
589 else {
590 // The addition is folded to 0.0.
591 Result = ConstantFP::get(Ty: Instr->getType(), V: 0.0);
592 }
593
594 return Result;
595}
596
597Value *FAddCombine::createNaryFAdd
598 (const AddendVect &Opnds, unsigned InstrQuota) {
599 assert(!Opnds.empty() && "Expect at least one addend");
600
601 // Step 1: Check if the # of instructions needed exceeds the quota.
602
603 unsigned InstrNeeded = calcInstrNumber(Vect: Opnds);
604 if (InstrNeeded > InstrQuota)
605 return nullptr;
606
607 initCreateInstNum();
608
609 // step 2: Emit the N-ary addition.
610 // Note that at most three instructions are involved in Fadd-InstCombine: the
611 // addition in question, and at most two neighboring instructions.
612 // The resulting optimized addition should have at least one less instruction
613 // than the original addition expression tree. This implies that the resulting
614 // N-ary addition has at most two instructions, and we don't need to worry
615 // about tree-height when constructing the N-ary addition.
616
617 Value *LastVal = nullptr;
618 bool LastValNeedNeg = false;
619
620 // Iterate the addends, creating fadd/fsub using adjacent two addends.
621 for (const FAddend *Opnd : Opnds) {
622 bool NeedNeg;
623 Value *V = createAddendVal(A: *Opnd, NeedNeg);
624 if (!LastVal) {
625 LastVal = V;
626 LastValNeedNeg = NeedNeg;
627 continue;
628 }
629
630 if (LastValNeedNeg == NeedNeg) {
631 LastVal = createFAdd(Opnd0: LastVal, Opnd1: V);
632 continue;
633 }
634
635 if (LastValNeedNeg)
636 LastVal = createFSub(Opnd0: V, Opnd1: LastVal);
637 else
638 LastVal = createFSub(Opnd0: LastVal, Opnd1: V);
639
640 LastValNeedNeg = false;
641 }
642
643 if (LastValNeedNeg) {
644 LastVal = createFNeg(V: LastVal);
645 }
646
647#ifndef NDEBUG
648 assert(CreateInstrNum == InstrNeeded &&
649 "Inconsistent in instruction numbers");
650#endif
651
652 return LastVal;
653}
654
655Value *FAddCombine::createFSub(Value *Opnd0, Value *Opnd1) {
656 Value *V = Builder.CreateFSub(L: Opnd0, R: Opnd1);
657 if (Instruction *I = dyn_cast<Instruction>(Val: V))
658 createInstPostProc(NewInst: I);
659 return V;
660}
661
662Value *FAddCombine::createFNeg(Value *V) {
663 Value *NewV = Builder.CreateFNeg(V);
664 if (Instruction *I = dyn_cast<Instruction>(Val: NewV))
665 createInstPostProc(NewInst: I, NoNumber: true); // fneg's don't receive instruction numbers.
666 return NewV;
667}
668
669Value *FAddCombine::createFAdd(Value *Opnd0, Value *Opnd1) {
670 Value *V = Builder.CreateFAdd(L: Opnd0, R: Opnd1);
671 if (Instruction *I = dyn_cast<Instruction>(Val: V))
672 createInstPostProc(NewInst: I);
673 return V;
674}
675
676Value *FAddCombine::createFMul(Value *Opnd0, Value *Opnd1) {
677 Value *V = Builder.CreateFMul(L: Opnd0, R: Opnd1);
678 if (Instruction *I = dyn_cast<Instruction>(Val: V))
679 createInstPostProc(NewInst: I);
680 return V;
681}
682
683void FAddCombine::createInstPostProc(Instruction *NewInstr, bool NoNumber) {
684 NewInstr->setDebugLoc(Instr->getDebugLoc());
685
686 // Keep track of the number of instruction created.
687 if (!NoNumber)
688 incCreateInstNum();
689
690 // Propagate fast-math flags
691 NewInstr->setFastMathFlags(Instr->getFastMathFlags());
692}
693
694// Return the number of instruction needed to emit the N-ary addition.
695// NOTE: Keep this function in sync with createAddendVal().
696unsigned FAddCombine::calcInstrNumber(const AddendVect &Opnds) {
697 unsigned OpndNum = Opnds.size();
698 unsigned InstrNeeded = OpndNum - 1;
699
700 // Adjust the number of instructions needed to emit the N-ary add.
701 for (const FAddend *Opnd : Opnds) {
702 if (Opnd->isConstant())
703 continue;
704
705 // The constant check above is really for a few special constant
706 // coefficients.
707 if (isa<UndefValue>(Val: Opnd->getSymVal()))
708 continue;
709
710 const FAddendCoef &CE = Opnd->getCoef();
711 // Let the addend be "c * x". If "c == +/-1", the value of the addend
712 // is immediately available; otherwise, it needs exactly one instruction
713 // to evaluate the value.
714 if (!CE.isMinusOne() && !CE.isOne())
715 InstrNeeded++;
716 }
717 return InstrNeeded;
718}
719
720// Input Addend Value NeedNeg(output)
721// ================================================================
722// Constant C C false
723// <+/-1, V> V coefficient is -1
724// <2/-2, V> "fadd V, V" coefficient is -2
725// <C, V> "fmul V, C" false
726//
727// NOTE: Keep this function in sync with FAddCombine::calcInstrNumber.
728Value *FAddCombine::createAddendVal(const FAddend &Opnd, bool &NeedNeg) {
729 const FAddendCoef &Coeff = Opnd.getCoef();
730
731 if (Opnd.isConstant()) {
732 NeedNeg = false;
733 return Coeff.getValue(Ty: Instr->getType());
734 }
735
736 Value *OpndVal = Opnd.getSymVal();
737
738 if (Coeff.isMinusOne() || Coeff.isOne()) {
739 NeedNeg = Coeff.isMinusOne();
740 return OpndVal;
741 }
742
743 if (Coeff.isTwo() || Coeff.isMinusTwo()) {
744 NeedNeg = Coeff.isMinusTwo();
745 return createFAdd(Opnd0: OpndVal, Opnd1: OpndVal);
746 }
747
748 NeedNeg = false;
749 return createFMul(Opnd0: OpndVal, Opnd1: Coeff.getValue(Ty: Instr->getType()));
750}
751
752// Checks if any operand is negative and we can convert add to sub.
753// This function checks for following negative patterns
754// ADD(XOR(OR(Z, NOT(C)), C)), 1) == NEG(AND(Z, C))
755// ADD(XOR(AND(Z, C), C), 1) == NEG(OR(Z, ~C))
756// XOR(AND(Z, C), (C + 1)) == NEG(OR(Z, ~C)) if C is even
757static Value *checkForNegativeOperand(BinaryOperator &I,
758 InstCombiner::BuilderTy &Builder) {
759 Value *LHS = I.getOperand(i_nocapture: 0), *RHS = I.getOperand(i_nocapture: 1);
760
761 // This function creates 2 instructions to replace ADD, we need at least one
762 // of LHS or RHS to have one use to ensure benefit in transform.
763 if (!LHS->hasOneUse() && !RHS->hasOneUse())
764 return nullptr;
765
766 Value *X = nullptr, *Y = nullptr, *Z = nullptr;
767 const APInt *C1 = nullptr, *C2 = nullptr;
768
769 // if ONE is on other side, swap
770 if (match(V: RHS, P: m_Add(L: m_Value(V&: X), R: m_One())))
771 std::swap(a&: LHS, b&: RHS);
772
773 if (match(V: LHS, P: m_Add(L: m_Value(V&: X), R: m_One()))) {
774 // if XOR on other side, swap
775 if (match(V: RHS, P: m_Xor(L: m_Value(V&: Y), R: m_APInt(Res&: C1))))
776 std::swap(a&: X, b&: RHS);
777
778 if (match(V: X, P: m_Xor(L: m_Value(V&: Y), R: m_APInt(Res&: C1)))) {
779 // X = XOR(Y, C1), Y = OR(Z, C2), C2 = NOT(C1) ==> X == NOT(AND(Z, C1))
780 // ADD(ADD(X, 1), RHS) == ADD(X, ADD(RHS, 1)) == SUB(RHS, AND(Z, C1))
781 if (match(V: Y, P: m_Or(L: m_Value(V&: Z), R: m_APInt(Res&: C2))) && (*C2 == ~(*C1))) {
782 Value *NewAnd = Builder.CreateAnd(LHS: Z, RHS: *C1);
783 return Builder.CreateSub(LHS: RHS, RHS: NewAnd, Name: "sub");
784 } else if (match(V: Y, P: m_And(L: m_Value(V&: Z), R: m_APInt(Res&: C2))) && (*C1 == *C2)) {
785 // X = XOR(Y, C1), Y = AND(Z, C2), C2 == C1 ==> X == NOT(OR(Z, ~C1))
786 // ADD(ADD(X, 1), RHS) == ADD(X, ADD(RHS, 1)) == SUB(RHS, OR(Z, ~C1))
787 Value *NewOr = Builder.CreateOr(LHS: Z, RHS: ~(*C1));
788 return Builder.CreateSub(LHS: RHS, RHS: NewOr, Name: "sub");
789 }
790 }
791 }
792
793 // Restore LHS and RHS
794 LHS = I.getOperand(i_nocapture: 0);
795 RHS = I.getOperand(i_nocapture: 1);
796
797 // if XOR is on other side, swap
798 if (match(V: RHS, P: m_Xor(L: m_Value(V&: Y), R: m_APInt(Res&: C1))))
799 std::swap(a&: LHS, b&: RHS);
800
801 // C2 is ODD
802 // LHS = XOR(Y, C1), Y = AND(Z, C2), C1 == (C2 + 1) => LHS == NEG(OR(Z, ~C2))
803 // ADD(LHS, RHS) == SUB(RHS, OR(Z, ~C2))
804 if (match(V: LHS, P: m_Xor(L: m_Value(V&: Y), R: m_APInt(Res&: C1))))
805 if (C1->countr_zero() == 0)
806 if (match(V: Y, P: m_And(L: m_Value(V&: Z), R: m_APInt(Res&: C2))) && *C1 == (*C2 + 1)) {
807 Value *NewOr = Builder.CreateOr(LHS: Z, RHS: ~(*C2));
808 return Builder.CreateSub(LHS: RHS, RHS: NewOr, Name: "sub");
809 }
810 return nullptr;
811}
812
813/// Wrapping flags may allow combining constants separated by an extend.
814static Instruction *foldNoWrapAdd(BinaryOperator &Add,
815 InstCombiner::BuilderTy &Builder) {
816 Value *Op0 = Add.getOperand(i_nocapture: 0), *Op1 = Add.getOperand(i_nocapture: 1);
817 Type *Ty = Add.getType();
818 Constant *Op1C;
819 if (!match(V: Op1, P: m_Constant(C&: Op1C)))
820 return nullptr;
821
822 // Try this match first because it results in an add in the narrow type.
823 // (zext (X +nuw C2)) + C1 --> zext (X + (C2 + trunc(C1)))
824 Value *X;
825 const APInt *C1, *C2;
826 if (match(V: Op1, P: m_APInt(Res&: C1)) &&
827 match(V: Op0, P: m_ZExt(Op: m_NUWAddLike(L: m_Value(V&: X), R: m_APInt(Res&: C2)))) &&
828 C1->isNegative() && C1->sge(RHS: -C2->sext(width: C1->getBitWidth()))) {
829 APInt NewC = *C2 + C1->trunc(width: C2->getBitWidth());
830 // If the smaller add will fold to zero, we don't need to check one use.
831 if (NewC.isZero())
832 return new ZExtInst(X, Ty);
833 // Otherwise only do this if the existing zero extend will be removed.
834 if (Op0->hasOneUse())
835 return new ZExtInst(
836 Builder.CreateNUWAdd(LHS: X, RHS: ConstantInt::get(Ty: X->getType(), V: NewC)), Ty);
837 }
838
839 // More general combining of constants in the wide type.
840 // (sext (X +nsw NarrowC)) + C --> (sext X) + (sext(NarrowC) + C)
841 // or (zext nneg (X +nsw NarrowC)) + C --> (sext X) + (sext(NarrowC) + C)
842 Constant *NarrowC;
843 if (match(V: Op0, P: m_OneUse(SubPattern: m_SExtLike(
844 Op: m_NSWAddLike(L: m_Value(V&: X), R: m_Constant(C&: NarrowC)))))) {
845 Value *WideC = Builder.CreateSExt(V: NarrowC, DestTy: Ty);
846 Value *NewC = Builder.CreateAdd(LHS: WideC, RHS: Op1C);
847 Value *WideX = Builder.CreateSExt(V: X, DestTy: Ty);
848 return BinaryOperator::CreateAdd(V1: WideX, V2: NewC);
849 }
850 // (zext (X +nuw NarrowC)) + C --> (zext X) + (zext(NarrowC) + C)
851 if (match(V: Op0,
852 P: m_OneUse(SubPattern: m_ZExt(Op: m_NUWAddLike(L: m_Value(V&: X), R: m_Constant(C&: NarrowC)))))) {
853 Value *WideC = Builder.CreateZExt(V: NarrowC, DestTy: Ty);
854 Value *NewC = Builder.CreateAdd(LHS: WideC, RHS: Op1C);
855 Value *WideX = Builder.CreateZExt(V: X, DestTy: Ty);
856 return BinaryOperator::CreateAdd(V1: WideX, V2: NewC);
857 }
858 return nullptr;
859}
860
861Instruction *InstCombinerImpl::foldAddWithConstant(BinaryOperator &Add) {
862 Value *Op0 = Add.getOperand(i_nocapture: 0), *Op1 = Add.getOperand(i_nocapture: 1);
863 Type *Ty = Add.getType();
864 Constant *Op1C;
865 if (!match(V: Op1, P: m_ImmConstant(C&: Op1C)))
866 return nullptr;
867
868 if (Instruction *NV = foldBinOpIntoSelectOrPhi(I&: Add))
869 return NV;
870
871 if (Instruction *FoldedLogic = foldBinOpSelectBinOp(Op&: Add))
872 return FoldedLogic;
873
874 Value *X;
875 Constant *Op00C;
876
877 // add (sub C1, X), C2 --> sub (add C1, C2), X
878 if (match(V: Op0, P: m_Sub(L: m_Constant(C&: Op00C), R: m_Value(V&: X))))
879 return BinaryOperator::CreateSub(V1: ConstantExpr::getAdd(C1: Op00C, C2: Op1C), V2: X);
880
881 Value *Y;
882
883 // add (sub X, Y), -1 --> add (not Y), X
884 if (match(V: Op0, P: m_OneUse(SubPattern: m_Sub(L: m_Value(V&: X), R: m_Value(V&: Y)))) &&
885 match(V: Op1, P: m_AllOnes()))
886 return BinaryOperator::CreateAdd(V1: Builder.CreateNot(V: Y), V2: X);
887
888 // zext(bool) + C -> bool ? C + 1 : C
889 if (match(V: Op0, P: m_ZExt(Op: m_Value(V&: X))) &&
890 X->getType()->getScalarSizeInBits() == 1)
891 return createSelectInstWithUnknownProfile(C: X, S1: InstCombiner::AddOne(C: Op1C),
892 S2: Op1);
893 // sext(bool) + C -> bool ? C - 1 : C
894 if (match(V: Op0, P: m_SExt(Op: m_Value(V&: X))) &&
895 X->getType()->getScalarSizeInBits() == 1)
896 return createSelectInstWithUnknownProfile(C: X, S1: InstCombiner::SubOne(C: Op1C),
897 S2: Op1);
898
899 // ~X + C --> (C-1) - X
900 if (match(V: Op0, P: m_Not(V: m_Value(V&: X)))) {
901 // ~X + C has NSW and (C-1) won't oveflow => (C-1)-X can have NSW
902 auto *COne = ConstantInt::get(Ty: Op1C->getType(), V: 1);
903 bool WillNotSOV = willNotOverflowSignedSub(LHS: Op1C, RHS: COne, CtxI: Add);
904 BinaryOperator *Res =
905 BinaryOperator::CreateSub(V1: ConstantExpr::getSub(C1: Op1C, C2: COne), V2: X);
906 Res->setHasNoSignedWrap(Add.hasNoSignedWrap() && WillNotSOV);
907 return Res;
908 }
909
910 // (iN X s>> (N - 1)) + 1 --> zext (X > -1)
911 const APInt *C;
912 unsigned BitWidth = Ty->getScalarSizeInBits();
913 if (match(V: Op0, P: m_OneUse(SubPattern: m_AShr(L: m_Value(V&: X),
914 R: m_SpecificIntAllowPoison(V: BitWidth - 1)))) &&
915 match(V: Op1, P: m_One()))
916 return new ZExtInst(Builder.CreateIsNotNeg(Arg: X, Name: "isnotneg"), Ty);
917
918 if (!match(V: Op1, P: m_APInt(Res&: C)))
919 return nullptr;
920
921 // (X | Op01C) + Op1C --> X + (Op01C + Op1C) iff the `or` is actually an `add`
922 Constant *Op01C;
923 if (match(V: Op0, P: m_DisjointOr(L: m_Value(V&: X), R: m_ImmConstant(C&: Op01C)))) {
924 BinaryOperator *NewAdd =
925 BinaryOperator::CreateAdd(V1: X, V2: ConstantExpr::getAdd(C1: Op01C, C2: Op1C));
926 NewAdd->setHasNoSignedWrap(Add.hasNoSignedWrap() &&
927 willNotOverflowSignedAdd(LHS: Op01C, RHS: Op1C, CtxI: Add));
928 NewAdd->setHasNoUnsignedWrap(Add.hasNoUnsignedWrap());
929 return NewAdd;
930 }
931
932 // (X | C2) + C --> (X | C2) ^ C2 iff (C2 == -C)
933 const APInt *C2;
934 if (match(V: Op0, P: m_Or(L: m_Value(), R: m_APInt(Res&: C2))) && *C2 == -*C)
935 return BinaryOperator::CreateXor(V1: Op0, V2: ConstantInt::get(Ty: Add.getType(), V: *C2));
936
937 if (C->isSignMask()) {
938 // If wrapping is not allowed, then the addition must set the sign bit:
939 // X + (signmask) --> X | signmask
940 if (Add.hasNoSignedWrap() || Add.hasNoUnsignedWrap())
941 return BinaryOperator::CreateDisjointOr(V1: Op0, V2: Op1);
942
943 // If wrapping is allowed, then the addition flips the sign bit of LHS:
944 // X + (signmask) --> X ^ signmask
945 return BinaryOperator::CreateXor(V1: Op0, V2: Op1);
946 }
947
948 // Is this add the last step in a convoluted sext?
949 // add(zext(xor i16 X, -32768), -32768) --> sext X
950 if (match(V: Op0, P: m_ZExt(Op: m_Xor(L: m_Value(V&: X), R: m_APInt(Res&: C2)))) &&
951 C2->isMinSignedValue() && C2->sext(width: Ty->getScalarSizeInBits()) == *C)
952 return CastInst::Create(Instruction::SExt, S: X, Ty);
953
954 if (match(V: Op0, P: m_Xor(L: m_Value(V&: X), R: m_APInt(Res&: C2)))) {
955 // (X ^ signmask) + C --> (X + (signmask ^ C))
956 if (C2->isSignMask())
957 return BinaryOperator::CreateAdd(V1: X, V2: ConstantInt::get(Ty, V: *C2 ^ *C));
958
959 // If X has no bits set other than an xor mask,
960 // xor is equivalent to sub with no borrow between bits:
961 // add (xor X, C2), C --> sub (C2 + C), X
962 KnownBits LHSKnown = computeKnownBits(V: X, CtxI: &Add);
963 if ((*C2 | LHSKnown.Zero).isAllOnes())
964 return BinaryOperator::CreateSub(V1: ConstantInt::get(Ty, V: *C2 + *C), V2: X);
965
966 // Look for a math+logic pattern that corresponds to sext-in-register of a
967 // value with cleared high bits. Convert that into a pair of shifts:
968 // add (xor X, 0x80), 0xF..F80 --> (X << ShAmtC) >>s ShAmtC
969 // add (xor X, 0xF..F80), 0x80 --> (X << ShAmtC) >>s ShAmtC
970 if (Op0->hasOneUse() && *C2 == -(*C)) {
971 unsigned BitWidth = Ty->getScalarSizeInBits();
972 unsigned ShAmt = 0;
973 if (C->isPowerOf2())
974 ShAmt = BitWidth - C->logBase2() - 1;
975 else if (C2->isPowerOf2())
976 ShAmt = BitWidth - C2->logBase2() - 1;
977 if (ShAmt &&
978 MaskedValueIsZero(V: X, Mask: APInt::getHighBitsSet(numBits: BitWidth, hiBitsSet: ShAmt), CtxI: &Add)) {
979 Constant *ShAmtC = ConstantInt::get(Ty, V: ShAmt);
980 Value *NewShl = Builder.CreateShl(LHS: X, RHS: ShAmtC, Name: "sext");
981 return BinaryOperator::CreateAShr(V1: NewShl, V2: ShAmtC);
982 }
983 }
984 }
985
986 // umax(X, C) + -C --> usub.sat(X, C)
987 if (match(V: Op0, P: m_OneUse(SubPattern: m_UMax(Op0: m_Value(V&: X), Op1: m_SpecificInt(V: -*C)))))
988 return replaceInstUsesWith(
989 I&: Add, V: Builder.CreateBinaryIntrinsic(
990 ID: Intrinsic::usub_sat, LHS: X, RHS: ConstantInt::get(Ty: Add.getType(), V: -*C)));
991 // uadd.sat(X, C) + -C --> umin(X, ~C)
992 // The saturating add gives X + C or UMAX, so subtracting C leaves X or
993 // UMAX - C. Note UMAX - C == ~C.
994 {
995 APInt SatC = -*C;
996 if (match(V: Op0, P: m_OneUse(SubPattern: m_Intrinsic<Intrinsic::uadd_sat>(
997 Ops: m_Value(V&: X), Ops: m_SpecificInt(V: SatC)))))
998 return replaceInstUsesWith(
999 I&: Add, V: Builder.CreateBinaryIntrinsic(ID: Intrinsic::umin, LHS: X,
1000 RHS: ConstantInt::get(Ty, V: ~SatC)));
1001 }
1002 // Fold (add (zext (add X, -C)), C) -> (zext X) if X u>= C.
1003 // Truncate C to the narrow type to avoid mismatched width comparisons.
1004 {
1005 const APInt *InnerC;
1006 if (match(V: Op0, P: m_ZExt(Op: m_Add(L: m_Value(V&: X), R: m_APIntAllowPoison(Res&: InnerC))))) {
1007 unsigned NarrowBW = InnerC->getBitWidth();
1008 if (C->isIntN(N: NarrowBW)) {
1009 APInt NarrowC = C->trunc(width: NarrowBW);
1010 const SimplifyQuery Q = SQ.getWithInstruction(I: &Add);
1011 if (*InnerC == -NarrowC &&
1012 (NarrowC.isOne()
1013 ? llvm::isKnownNonZero(V: X, Q)
1014 : computeKnownBits(V: X, CtxI: &Add).getMinValue().uge(RHS: NarrowC)))
1015 return new ZExtInst(X, Ty);
1016 }
1017 }
1018 }
1019
1020 return nullptr;
1021}
1022
1023// match variations of a^2 + 2*a*b + b^2
1024//
1025// to reuse the code between the FP and Int versions, the instruction OpCodes
1026// and constant types have been turned into template parameters.
1027//
1028// Mul2Rhs: The constant to perform the multiplicative equivalent of X*2 with;
1029// should be `m_SpecificFP(2.0)` for FP and `m_SpecificInt(1)` for Int
1030// (we're matching `X<<1` instead of `X*2` for Int)
1031template <bool FP, typename Mul2Rhs>
1032static bool matchesSquareSum(BinaryOperator &I, Mul2Rhs M2Rhs, Value *&A,
1033 Value *&B) {
1034 constexpr unsigned MulOp = FP ? Instruction::FMul : Instruction::Mul;
1035 constexpr unsigned AddOp = FP ? Instruction::FAdd : Instruction::Add;
1036 constexpr unsigned Mul2Op = FP ? Instruction::FMul : Instruction::Shl;
1037
1038 // (a * a) + (((a * 2) + b) * b)
1039 if (match(&I, m_c_BinOp(
1040 AddOp, m_BinOp(Opcode: MulOp, L: m_Value(V&: A), R: m_Deferred(V: A)),
1041 m_OneUse(m_c_BinOp(
1042 MulOp,
1043 m_c_BinOp(AddOp, m_BinOp(Mul2Op, m_Deferred(V: A), M2Rhs),
1044 m_Value(V&: B)),
1045 m_Deferred(V: B))))))
1046 return true;
1047
1048 // ((a * b) * 2) or ((a * 2) * b)
1049 // +
1050 // (a * a + b * b) or (b * b + a * a)
1051 return match(
1052 &I, m_c_BinOp(
1053 AddOp,
1054 m_CombineOr(
1055 m_OneUse(m_BinOp(
1056 Mul2Op, m_BinOp(Opcode: MulOp, L: m_Value(V&: A), R: m_Value(V&: B)), M2Rhs)),
1057 m_OneUse(m_c_BinOp(MulOp, m_BinOp(Mul2Op, m_Value(V&: A), M2Rhs),
1058 m_Value(V&: B)))),
1059 m_OneUse(
1060 SubPattern: m_c_BinOp(Opcode: AddOp, L: m_BinOp(Opcode: MulOp, L: m_Deferred(V: A), R: m_Deferred(V: A)),
1061 R: m_BinOp(Opcode: MulOp, L: m_Deferred(V: B), R: m_Deferred(V: B))))));
1062}
1063
1064// Fold integer variations of a^2 + 2*a*b + b^2 -> (a + b)^2
1065Instruction *InstCombinerImpl::foldSquareSumInt(BinaryOperator &I) {
1066 Value *A, *B;
1067 if (matchesSquareSum</*FP*/ false>(I, M2Rhs: m_SpecificInt(V: 1), A, B)) {
1068 Value *AB = Builder.CreateAdd(LHS: A, RHS: B);
1069 return BinaryOperator::CreateMul(V1: AB, V2: AB);
1070 }
1071 return nullptr;
1072}
1073
1074// Fold floating point variations of a^2 + 2*a*b + b^2 -> (a + b)^2
1075// Requires `nsz` and `reassoc`.
1076Instruction *InstCombinerImpl::foldSquareSumFP(BinaryOperator &I) {
1077 assert(I.hasAllowReassoc() && I.hasNoSignedZeros() && "Assumption mismatch");
1078 Value *A, *B;
1079 if (matchesSquareSum</*FP*/ true>(I, M2Rhs: m_SpecificFP(V: 2.0), A, B)) {
1080 Value *AB = Builder.CreateFAddFMF(L: A, R: B, FMFSource: &I);
1081 return BinaryOperator::CreateFMulFMF(V1: AB, V2: AB, FMFSource: &I);
1082 }
1083 return nullptr;
1084}
1085
1086// Matches multiplication expression Op * C where C is a constant. Returns the
1087// constant value in C and the other operand in Op. Returns true if such a
1088// match is found.
1089static bool MatchMul(Value *E, Value *&Op, APInt &C) {
1090 const APInt *AI;
1091 if (match(V: E, P: m_Mul(L: m_Value(V&: Op), R: m_APInt(Res&: AI)))) {
1092 C = *AI;
1093 return true;
1094 }
1095 if (match(V: E, P: m_Shl(L: m_Value(V&: Op), R: m_APInt(Res&: AI)))) {
1096 C = APInt(AI->getBitWidth(), 1);
1097 C <<= *AI;
1098 return true;
1099 }
1100 return false;
1101}
1102
1103// Matches remainder expression Op % C where C is a constant. Returns the
1104// constant value in C and the other operand in Op. Returns the signedness of
1105// the remainder operation in IsSigned. Returns true if such a match is
1106// found.
1107static bool MatchRem(Value *E, Value *&Op, APInt &C, bool &IsSigned) {
1108 const APInt *AI;
1109 IsSigned = false;
1110 if (match(V: E, P: m_SRem(L: m_Value(V&: Op), R: m_APInt(Res&: AI)))) {
1111 IsSigned = true;
1112 C = *AI;
1113 return true;
1114 }
1115 if (match(V: E, P: m_URem(L: m_Value(V&: Op), R: m_APInt(Res&: AI)))) {
1116 C = *AI;
1117 return true;
1118 }
1119 if (match(V: E, P: m_And(L: m_Value(V&: Op), R: m_APInt(Res&: AI))) && (*AI + 1).isPowerOf2()) {
1120 C = *AI + 1;
1121 return true;
1122 }
1123 return false;
1124}
1125
1126// Matches division expression Op / C with the given signedness as indicated
1127// by IsSigned, where C is a constant. Returns the constant value in C and the
1128// other operand in Op. Returns true if such a match is found.
1129static bool MatchDiv(Value *E, Value *&Op, APInt &C, bool IsSigned) {
1130 const APInt *AI;
1131 if (IsSigned && match(V: E, P: m_SDiv(L: m_Value(V&: Op), R: m_APInt(Res&: AI)))) {
1132 C = *AI;
1133 return true;
1134 }
1135 if (!IsSigned) {
1136 if (match(V: E, P: m_UDiv(L: m_Value(V&: Op), R: m_APInt(Res&: AI)))) {
1137 C = *AI;
1138 return true;
1139 }
1140 if (match(V: E, P: m_LShr(L: m_Value(V&: Op), R: m_APInt(Res&: AI)))) {
1141 C = APInt(AI->getBitWidth(), 1);
1142 C <<= *AI;
1143 return true;
1144 }
1145 }
1146 return false;
1147}
1148
1149// Returns whether C0 * C1 with the given signedness overflows.
1150static bool MulWillOverflow(APInt &C0, APInt &C1, bool IsSigned) {
1151 bool overflow;
1152 if (IsSigned)
1153 (void)C0.smul_ov(RHS: C1, Overflow&: overflow);
1154 else
1155 (void)C0.umul_ov(RHS: C1, Overflow&: overflow);
1156 return overflow;
1157}
1158
1159// Simplifies X % C0 + (( X / C0 ) % C1) * C0 to X % (C0 * C1), where (C0 * C1)
1160// does not overflow.
1161// Simplifies (X / C0) * C1 + (X % C0) * C2 to
1162// (X / C0) * (C1 - C2 * C0) + X * C2
1163Value *InstCombinerImpl::SimplifyAddWithRemainder(BinaryOperator &I) {
1164 Value *LHS = I.getOperand(i_nocapture: 0), *RHS = I.getOperand(i_nocapture: 1);
1165 Value *X, *MulOpV;
1166 APInt C0, MulOpC;
1167 bool IsSigned;
1168 // Match I = X % C0 + MulOpV * C0
1169 if (((MatchRem(E: LHS, Op&: X, C&: C0, IsSigned) && MatchMul(E: RHS, Op&: MulOpV, C&: MulOpC)) ||
1170 (MatchRem(E: RHS, Op&: X, C&: C0, IsSigned) && MatchMul(E: LHS, Op&: MulOpV, C&: MulOpC))) &&
1171 C0 == MulOpC) {
1172 Value *RemOpV;
1173 APInt C1;
1174 bool Rem2IsSigned;
1175 // Match MulOpC = RemOpV % C1
1176 if (MatchRem(E: MulOpV, Op&: RemOpV, C&: C1, IsSigned&: Rem2IsSigned) &&
1177 IsSigned == Rem2IsSigned) {
1178 Value *DivOpV;
1179 APInt DivOpC;
1180 // Match RemOpV = X / C0
1181 if (MatchDiv(E: RemOpV, Op&: DivOpV, C&: DivOpC, IsSigned) && X == DivOpV &&
1182 C0 == DivOpC && !MulWillOverflow(C0, C1, IsSigned)) {
1183 Value *NewDivisor = ConstantInt::get(Ty: X->getType(), V: C0 * C1);
1184 return IsSigned ? Builder.CreateSRem(LHS: X, RHS: NewDivisor, Name: "srem")
1185 : Builder.CreateURem(LHS: X, RHS: NewDivisor, Name: "urem");
1186 }
1187 }
1188 }
1189
1190 // Match I = (X / C0) * C1 + (X % C0) * C2.
1191 auto FoldDivRem = [&](Value *DivSide, Value *RemSide) -> Value * {
1192 Value *Div, *Rem;
1193 APInt C1, C2;
1194 if (!DivSide->hasOneUse() || !MatchMul(E: DivSide, Op&: Div, C&: C1))
1195 Div = DivSide, C1 = APInt(I.getType()->getScalarSizeInBits(), 1);
1196 if (!RemSide->hasOneUse() || !MatchMul(E: RemSide, Op&: Rem, C&: C2))
1197 Rem = RemSide, C2 = APInt(I.getType()->getScalarSizeInBits(), 1);
1198 Value *DivOpV;
1199 APInt DivOpC;
1200 if (MatchRem(E: Rem, Op&: X, C&: C0, IsSigned) &&
1201 MatchDiv(E: Div, Op&: DivOpV, C&: DivOpC, IsSigned) && X == DivOpV &&
1202 C0 == DivOpC &&
1203 // Avoid unprofitable replacement of and with mul.
1204 !(C1.isOne() && !IsSigned && DivOpC.isPowerOf2() && DivOpC != 2)) {
1205 APInt NewC = C1 - C2 * C0;
1206 if (!NewC.isZero() && !Rem->hasOneUse())
1207 return nullptr;
1208 if (!isGuaranteedNotToBeUndef(V: X, AC: &AC, CtxI: &I, DT: &DT))
1209 return nullptr;
1210 Value *MulXC2 = Builder.CreateMul(LHS: X, RHS: ConstantInt::get(Ty: X->getType(), V: C2));
1211 if (NewC.isZero())
1212 return MulXC2;
1213 return Builder.CreateAdd(
1214 LHS: Builder.CreateMul(LHS: Div, RHS: ConstantInt::get(Ty: X->getType(), V: NewC)), RHS: MulXC2);
1215 }
1216 return nullptr;
1217 };
1218 if (Value *V = FoldDivRem(LHS, RHS))
1219 return V;
1220 if (Value *V = FoldDivRem(RHS, LHS))
1221 return V;
1222
1223 return nullptr;
1224}
1225
1226/// Fold
1227/// (1 << NBits) - 1
1228/// Into:
1229/// ~(-(1 << NBits))
1230/// Because a 'not' is better for bit-tracking analysis and other transforms
1231/// than an 'add'. The new shl is always nsw, and is nuw if old `and` was.
1232static Instruction *canonicalizeLowbitMask(BinaryOperator &I,
1233 InstCombiner::BuilderTy &Builder) {
1234 Value *NBits;
1235 if (!match(V: &I, P: m_Add(L: m_OneUse(SubPattern: m_Shl(L: m_One(), R: m_Value(V&: NBits))), R: m_AllOnes())))
1236 return nullptr;
1237
1238 Constant *MinusOne = Constant::getAllOnesValue(Ty: NBits->getType());
1239 Value *NotMask = Builder.CreateShl(LHS: MinusOne, RHS: NBits, Name: "notmask");
1240 // Be wary of constant folding.
1241 if (auto *BOp = dyn_cast<BinaryOperator>(Val: NotMask)) {
1242 // Always NSW. But NUW propagates from `add`.
1243 BOp->setHasNoSignedWrap();
1244 BOp->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
1245 }
1246
1247 return BinaryOperator::CreateNot(Op: NotMask, Name: I.getName());
1248}
1249
1250static Instruction *foldToUnsignedSaturatedAdd(BinaryOperator &I) {
1251 assert(I.getOpcode() == Instruction::Add && "Expecting add instruction");
1252 Type *Ty = I.getType();
1253 auto getUAddSat = [&]() {
1254 return Intrinsic::getOrInsertDeclaration(M: I.getModule(), id: Intrinsic::uadd_sat,
1255 OverloadTys: Ty);
1256 };
1257
1258 // add (umin X, ~Y), Y --> uaddsat X, Y
1259 Value *X, *Y;
1260 if (match(V: &I, P: m_c_Add(L: m_c_UMin(L: m_Value(V&: X), R: m_Not(V: m_Value(V&: Y))),
1261 R: m_Deferred(V: Y))))
1262 return CallInst::Create(Func: getUAddSat(), Args: { X, Y });
1263
1264 // add (umin X, ~C), C --> uaddsat X, C
1265 const APInt *C, *NotC;
1266 if (match(V: &I, P: m_Add(L: m_UMin(Op0: m_Value(V&: X), Op1: m_APInt(Res&: NotC)), R: m_APInt(Res&: C))) &&
1267 *C == ~*NotC)
1268 return CallInst::Create(Func: getUAddSat(), Args: { X, ConstantInt::get(Ty, V: *C) });
1269
1270 return nullptr;
1271}
1272
1273// Transform:
1274// (add A, (shl (neg B), Y))
1275// -> (sub A, (shl B, Y))
1276static Instruction *combineAddSubWithShlAddSub(InstCombiner::BuilderTy &Builder,
1277 const BinaryOperator &I) {
1278 Value *A, *B, *Cnt;
1279 if (match(V: &I,
1280 P: m_c_Add(L: m_OneUse(SubPattern: m_Shl(L: m_OneUse(SubPattern: m_Neg(V: m_Value(V&: B))), R: m_Value(V&: Cnt))),
1281 R: m_Value(V&: A)))) {
1282 Value *NewShl = Builder.CreateShl(LHS: B, RHS: Cnt);
1283 return BinaryOperator::CreateSub(V1: A, V2: NewShl);
1284 }
1285 return nullptr;
1286}
1287
1288/// Try to reduce signed division by power-of-2 to an arithmetic shift right.
1289static Instruction *foldAddToAshr(BinaryOperator &Add) {
1290 // Division must be by power-of-2, but not the minimum signed value.
1291 Value *X;
1292 const APInt *DivC;
1293 if (!match(V: Add.getOperand(i_nocapture: 0), P: m_SDiv(L: m_Value(V&: X), R: m_Power2(V&: DivC))) ||
1294 DivC->isNegative())
1295 return nullptr;
1296
1297 // Rounding is done by adding -1 if the dividend (X) is negative and has any
1298 // low bits set. It recognizes two canonical patterns:
1299 // 1. For an 'ugt' cmp with the signed minimum value (SMIN), the
1300 // pattern is: sext (icmp ugt (X & (DivC - 1)), SMIN).
1301 // 2. For an 'eq' cmp, the pattern's: sext (icmp eq X & (SMIN + 1), SMIN + 1).
1302 // Note that, by the time we end up here, if possible, ugt has been
1303 // canonicalized into eq.
1304 const APInt *MaskC, *MaskCCmp;
1305 CmpPredicate Pred;
1306 if (!match(V: Add.getOperand(i_nocapture: 1),
1307 P: m_SExt(Op: m_ICmp(Pred, L: m_And(L: m_Specific(V: X), R: m_APInt(Res&: MaskC)),
1308 R: m_APInt(Res&: MaskCCmp)))))
1309 return nullptr;
1310
1311 if ((Pred != ICmpInst::ICMP_UGT || !MaskCCmp->isSignMask()) &&
1312 (Pred != ICmpInst::ICMP_EQ || *MaskCCmp != *MaskC))
1313 return nullptr;
1314
1315 APInt SMin = APInt::getSignedMinValue(numBits: Add.getType()->getScalarSizeInBits());
1316 bool IsMaskValid = Pred == ICmpInst::ICMP_UGT
1317 ? (*MaskC == (SMin | (*DivC - 1)))
1318 : (*DivC == 2 && *MaskC == SMin + 1);
1319 if (!IsMaskValid)
1320 return nullptr;
1321
1322 // (X / DivC) + sext ((X & (SMin | (DivC - 1)) >u SMin) --> X >>s log2(DivC)
1323 return BinaryOperator::CreateAShr(
1324 V1: X, V2: ConstantInt::get(Ty: Add.getType(), V: DivC->exactLogBase2()));
1325}
1326
1327Instruction *InstCombinerImpl::foldAddLikeCommutative(Value *LHS, Value *RHS,
1328 bool NSW, bool NUW) {
1329 Value *A, *B, *C;
1330 if (match(V: LHS, P: m_Sub(L: m_Value(V&: A), R: m_Value(V&: B))) &&
1331 match(V: RHS, P: m_Sub(L: m_Value(V&: C), R: m_Specific(V: A)))) {
1332 Instruction *R = BinaryOperator::CreateSub(V1: C, V2: B);
1333 bool NSWOut = NSW && match(V: LHS, P: m_NSWSub(L: m_Value(), R: m_Value())) &&
1334 match(V: RHS, P: m_NSWSub(L: m_Value(), R: m_Value()));
1335
1336 bool NUWOut = match(V: LHS, P: m_NUWSub(L: m_Value(), R: m_Value())) &&
1337 match(V: RHS, P: m_NUWSub(L: m_Value(), R: m_Value()));
1338 R->setHasNoSignedWrap(NSWOut);
1339 R->setHasNoUnsignedWrap(NUWOut);
1340 return R;
1341 }
1342
1343 // ((X s/ C1) << C2) + X => X s% -C1 where -C1 is 1 << C2
1344 const APInt *C1, *C2;
1345 if (match(V: LHS, P: m_Shl(L: m_SDiv(L: m_Specific(V: RHS), R: m_APInt(Res&: C1)), R: m_APInt(Res&: C2)))) {
1346 APInt One(C2->getBitWidth(), 1);
1347 APInt MinusC1 = -(*C1);
1348 if (MinusC1 == (One << *C2)) {
1349 Constant *NewRHS = ConstantInt::get(Ty: RHS->getType(), V: MinusC1);
1350 return BinaryOperator::CreateSRem(V1: RHS, V2: NewRHS);
1351 }
1352 }
1353
1354 // (A + C) + (B & ~C) == A + (B | C)
1355 if (match(V: LHS, P: m_c_Add(L: m_Value(V&: A), R: m_APInt(Res&: C1))) &&
1356 match(V: RHS, P: m_c_And(L: m_Value(V&: B), R: m_SpecificInt(V: ~*C1)))) {
1357 // Replacing one add with {or, add}. Avoid growth if both sides are shared.
1358 if (!LHS->hasOneUse() && !RHS->hasOneUse())
1359 return nullptr;
1360
1361 bool NSWOut = NSW && match(V: LHS, P: m_NSWAdd(L: m_Value(), R: m_Value()));
1362 bool NUWOut = NUW && match(V: LHS, P: m_NUWAdd(L: m_Value(), R: m_Value()));
1363 Value *NewOr =
1364 Builder.CreateOr(LHS: B, RHS: Constant::getIntegerValue(Ty: LHS->getType(), V: *C1));
1365 Instruction *NewAdd = BinaryOperator::CreateAdd(V1: A, V2: NewOr);
1366 NewAdd->setHasNoSignedWrap(NSWOut);
1367 NewAdd->setHasNoUnsignedWrap(NUWOut);
1368 return NewAdd;
1369 }
1370
1371 return nullptr;
1372}
1373
1374Instruction *InstCombinerImpl::
1375 canonicalizeCondSignextOfHighBitExtractToSignextHighBitExtract(
1376 BinaryOperator &I) {
1377 assert((I.getOpcode() == Instruction::Add ||
1378 I.getOpcode() == Instruction::Or ||
1379 I.getOpcode() == Instruction::Sub) &&
1380 "Expecting add/or/sub instruction");
1381
1382 // We have a subtraction/addition between a (potentially truncated) *logical*
1383 // right-shift of X and a "select".
1384 Value *X, *Select;
1385 Instruction *LowBitsToSkip, *Extract;
1386 if (!match(V: &I, P: m_c_BinOp(L: m_TruncOrSelf(Op: m_Instruction(
1387 I&: Extract, P: m_LShr(L: m_Value(V&: X),
1388 R: m_Instruction(I&: LowBitsToSkip)))),
1389 R: m_Value(V&: Select))))
1390 return nullptr;
1391
1392 // `add`/`or` is commutative; but for `sub`, "select" *must* be on RHS.
1393 if (I.getOpcode() == Instruction::Sub && I.getOperand(i_nocapture: 1) != Select)
1394 return nullptr;
1395
1396 Type *XTy = X->getType();
1397 bool HadTrunc = I.getType() != XTy;
1398
1399 // If there was a truncation of extracted value, then we'll need to produce
1400 // one extra instruction, so we need to ensure one instruction will go away.
1401 if (HadTrunc && !match(V: &I, P: m_c_BinOp(L: m_OneUse(SubPattern: m_Value()), R: m_Value())))
1402 return nullptr;
1403
1404 // Extraction should extract high NBits bits, with shift amount calculated as:
1405 // low bits to skip = shift bitwidth - high bits to extract
1406 // The shift amount itself may be extended, and we need to look past zero-ext
1407 // when matching NBits, that will matter for matching later.
1408 Value *NBits;
1409 if (!match(V: LowBitsToSkip,
1410 P: m_ZExtOrSelf(Op: m_Sub(L: m_SpecificInt(V: XTy->getScalarSizeInBits()),
1411 R: m_ZExtOrSelf(Op: m_Value(V&: NBits))))))
1412 return nullptr;
1413
1414 // Sign-extending value can be zero-extended if we `sub`tract it,
1415 // or sign-extended otherwise.
1416 auto SkipExtInMagic = [&I](Value *&V) {
1417 if (I.getOpcode() == Instruction::Sub)
1418 match(V, P: m_ZExtOrSelf(Op: m_Value(V)));
1419 else
1420 match(V, P: m_SExtOrSelf(Op: m_Value(V)));
1421 };
1422
1423 // Now, finally validate the sign-extending magic.
1424 // `select` itself may be appropriately extended, look past that.
1425 SkipExtInMagic(Select);
1426
1427 CmpPredicate Pred;
1428 const APInt *Thr;
1429 Value *SignExtendingValue, *Zero;
1430 bool ShouldSignext;
1431 // It must be a select between two values we will later establish to be a
1432 // sign-extending value and a zero constant. The condition guarding the
1433 // sign-extension must be based on a sign bit of the same X we had in `lshr`.
1434 if (!match(V: Select, P: m_Select(C: m_ICmp(Pred, L: m_Specific(V: X), R: m_APInt(Res&: Thr)),
1435 L: m_Value(V&: SignExtendingValue), R: m_Value(V&: Zero))) ||
1436 !isSignBitCheck(Pred, RHS: *Thr, TrueIfSigned&: ShouldSignext))
1437 return nullptr;
1438
1439 // icmp-select pair is commutative.
1440 if (!ShouldSignext)
1441 std::swap(a&: SignExtendingValue, b&: Zero);
1442
1443 // If we should not perform sign-extension then we must add/or/subtract zero.
1444 if (!match(V: Zero, P: m_Zero()))
1445 return nullptr;
1446 // Otherwise, it should be some constant, left-shifted by the same NBits we
1447 // had in `lshr`. Said left-shift can also be appropriately extended.
1448 // Again, we must look past zero-ext when looking for NBits.
1449 SkipExtInMagic(SignExtendingValue);
1450 Constant *SignExtendingValueBaseConstant;
1451 if (!match(V: SignExtendingValue,
1452 P: m_Shl(L: m_Constant(C&: SignExtendingValueBaseConstant),
1453 R: m_ZExtOrSelf(Op: m_Specific(V: NBits)))))
1454 return nullptr;
1455 // If we `sub`, then the constant should be one, else it should be all-ones.
1456 if (I.getOpcode() == Instruction::Sub
1457 ? !match(V: SignExtendingValueBaseConstant, P: m_One())
1458 : !match(V: SignExtendingValueBaseConstant, P: m_AllOnes()))
1459 return nullptr;
1460
1461 auto *NewAShr = BinaryOperator::CreateAShr(V1: X, V2: LowBitsToSkip,
1462 Name: Extract->getName() + ".sext");
1463 NewAShr->copyIRFlags(V: Extract); // Preserve `exact`-ness.
1464 if (!HadTrunc)
1465 return NewAShr;
1466
1467 Builder.Insert(I: NewAShr);
1468 return TruncInst::CreateTruncOrBitCast(S: NewAShr, Ty: I.getType());
1469}
1470
1471/// This is a specialization of a more general transform from
1472/// foldUsingDistributiveLaws. If that code can be made to work optimally
1473/// for multi-use cases or propagating nsw/nuw, then we would not need this.
1474static Instruction *factorizeMathWithShlOps(BinaryOperator &I,
1475 InstCombiner::BuilderTy &Builder) {
1476 // TODO: Also handle mul by doubling the shift amount?
1477 assert((I.getOpcode() == Instruction::Add ||
1478 I.getOpcode() == Instruction::Sub) &&
1479 "Expected add/sub");
1480 auto *Op0 = dyn_cast<BinaryOperator>(Val: I.getOperand(i_nocapture: 0));
1481 auto *Op1 = dyn_cast<BinaryOperator>(Val: I.getOperand(i_nocapture: 1));
1482 if (!Op0 || !Op1 || !(Op0->hasOneUse() || Op1->hasOneUse()))
1483 return nullptr;
1484
1485 Value *X, *Y, *ShAmt;
1486 if (!match(V: Op0, P: m_Shl(L: m_Value(V&: X), R: m_Value(V&: ShAmt))) ||
1487 !match(V: Op1, P: m_Shl(L: m_Value(V&: Y), R: m_Specific(V: ShAmt))))
1488 return nullptr;
1489
1490 // No-wrap propagates only when all ops have no-wrap.
1491 bool HasNSW = I.hasNoSignedWrap() && Op0->hasNoSignedWrap() &&
1492 Op1->hasNoSignedWrap();
1493 bool HasNUW = I.hasNoUnsignedWrap() && Op0->hasNoUnsignedWrap() &&
1494 Op1->hasNoUnsignedWrap();
1495
1496 // add/sub (X << ShAmt), (Y << ShAmt) --> (add/sub X, Y) << ShAmt
1497 Value *NewMath = Builder.CreateBinOp(Opc: I.getOpcode(), LHS: X, RHS: Y);
1498 if (auto *NewI = dyn_cast<BinaryOperator>(Val: NewMath)) {
1499 NewI->setHasNoSignedWrap(HasNSW);
1500 NewI->setHasNoUnsignedWrap(HasNUW);
1501 }
1502 auto *NewShl = BinaryOperator::CreateShl(V1: NewMath, V2: ShAmt);
1503 NewShl->setHasNoSignedWrap(HasNSW);
1504 NewShl->setHasNoUnsignedWrap(HasNUW);
1505 return NewShl;
1506}
1507
1508/// Reduce a sequence of masked half-width multiplies to a single multiply.
1509/// ((XLow * YHigh) + (YLow * XHigh)) << HalfBits) + (XLow * YLow) --> X * Y
1510static Instruction *foldBoxMultiply(BinaryOperator &I) {
1511 unsigned BitWidth = I.getType()->getScalarSizeInBits();
1512 // Skip the odd bitwidth types.
1513 if ((BitWidth & 0x1))
1514 return nullptr;
1515
1516 unsigned HalfBits = BitWidth >> 1;
1517 APInt HalfMask = APInt::getMaxValue(numBits: HalfBits);
1518
1519 // ResLo = (CrossSum << HalfBits) + (YLo * XLo)
1520 Value *XLo, *YLo;
1521 Value *CrossSum;
1522 // Require one-use on the multiply to avoid increasing the number of
1523 // multiplications.
1524 if (!match(V: &I, P: m_c_Add(L: m_Shl(L: m_Value(V&: CrossSum), R: m_SpecificInt(V: HalfBits)),
1525 R: m_OneUse(SubPattern: m_Mul(L: m_Value(V&: YLo), R: m_Value(V&: XLo))))))
1526 return nullptr;
1527
1528 // XLo = X & HalfMask
1529 // YLo = Y & HalfMask
1530 // TODO: Refactor with SimplifyDemandedBits or KnownBits known leading zeros
1531 // to enhance robustness
1532 Value *X, *Y;
1533 if (!match(V: XLo, P: m_And(L: m_Value(V&: X), R: m_SpecificInt(V: HalfMask))) ||
1534 !match(V: YLo, P: m_And(L: m_Value(V&: Y), R: m_SpecificInt(V: HalfMask))))
1535 return nullptr;
1536
1537 // CrossSum = (X' * (Y >> Halfbits)) + (Y' * (X >> HalfBits))
1538 // X' can be either X or XLo in the pattern (and the same for Y')
1539 if (match(V: CrossSum,
1540 P: m_c_Add(L: m_c_Mul(L: m_LShr(L: m_Specific(V: Y), R: m_SpecificInt(V: HalfBits)),
1541 R: m_CombineOr(Ps: m_Specific(V: X), Ps: m_Specific(V: XLo))),
1542 R: m_c_Mul(L: m_LShr(L: m_Specific(V: X), R: m_SpecificInt(V: HalfBits)),
1543 R: m_CombineOr(Ps: m_Specific(V: Y), Ps: m_Specific(V: YLo))))))
1544 return BinaryOperator::CreateMul(V1: X, V2: Y);
1545
1546 return nullptr;
1547}
1548
1549/// Return true if X + (Y-1) is provably non-wrapping in X's type
1550static bool checkDivCeilNUW(Value *X, Value *Y, const SimplifyQuery &SQ) {
1551 ConstantRange CRX = computeConstantRange(V: X, /*ForSigned=*/false, SQ);
1552 ConstantRange CRY = computeConstantRange(V: Y, /*ForSigned=*/false, SQ);
1553 APInt MinY = CRY.getUnsignedMin();
1554 APInt MaxX = CRX.getUnsignedMax();
1555 APInt MaxY = CRY.getUnsignedMax();
1556
1557 return !MinY.isZero() && !MaxX.ugt(RHS: -MaxY);
1558}
1559
1560/// Fold the div_ceil idiom in both forms:
1561/// add(udiv(X, Y), zext(icmp ne(urem(X, Y), 0)))
1562/// -> udiv(add nuw(X, Y - 1), Y)
1563/// add(zext(udiv(X, Y)), zext(icmp ne(urem(X, Y), 0)))
1564/// -> zext(udiv(add nuw(X, Y - 1), Y))
1565/// The zext form applies when udiv/urem operate in a narrower type than the
1566/// add.
1567Instruction *InstCombinerImpl::foldDivCeil(BinaryOperator &I) {
1568 Value *X, *Y;
1569
1570 auto UDivPat = m_OneUse(SubPattern: m_UDiv(L: m_Value(V&: X), R: m_Value(V&: Y)));
1571 auto URemPat = m_OneUse(SubPattern: m_URem(L: m_Deferred(V: X), R: m_Deferred(V: Y)));
1572 auto ICmpPat = m_OneUse(SubPattern: m_SpecificICmp(MatchPred: ICmpInst::ICMP_NE, L: URemPat, R: m_Zero()));
1573 auto DivPat = m_OneUse(SubPattern: m_ZExtOrSelf(Op: UDivPat));
1574 auto ZExtCmpPat = m_OneUse(SubPattern: m_ZExt(Op: ICmpPat));
1575
1576 if (!match(V: &I, P: m_c_Add(L: DivPat, R: ZExtCmpPat)) ||
1577 !checkDivCeilNUW(X, Y, SQ: SQ.getWithInstruction(I: &I)))
1578 return nullptr;
1579
1580 Value *YMinusOne =
1581 Builder.CreateAdd(LHS: Y, RHS: ConstantInt::getAllOnesValue(Ty: Y->getType()));
1582 Value *NUWAdd = Builder.CreateNUWAdd(LHS: X, RHS: YMinusOne);
1583 if (X->getType() != I.getType()) {
1584 Value *Div = Builder.CreateUDiv(LHS: NUWAdd, RHS: Y);
1585 return new ZExtInst(Div, I.getType());
1586 }
1587 return BinaryOperator::CreateUDiv(V1: NUWAdd, V2: Y);
1588}
1589
1590Instruction *InstCombinerImpl::visitAdd(BinaryOperator &I) {
1591 if (Value *V = simplifyAddInst(LHS: I.getOperand(i_nocapture: 0), RHS: I.getOperand(i_nocapture: 1),
1592 IsNSW: I.hasNoSignedWrap(), IsNUW: I.hasNoUnsignedWrap(),
1593 Q: SQ.getWithInstruction(I: &I)))
1594 return replaceInstUsesWith(I, V);
1595
1596 if (SimplifyAssociativeOrCommutative(I))
1597 return &I;
1598
1599 if (Instruction *X = foldVectorBinop(Inst&: I))
1600 return X;
1601
1602 if (Instruction *Phi = foldBinopWithPhiOperands(BO&: I))
1603 return Phi;
1604
1605 // (A*B)+(A*C) -> A*(B+C) etc
1606 if (Value *V = foldUsingDistributiveLaws(I))
1607 return replaceInstUsesWith(I, V);
1608
1609 if (Instruction *R = foldBoxMultiply(I))
1610 return R;
1611
1612 if (Instruction *R = factorizeMathWithShlOps(I, Builder))
1613 return R;
1614
1615 if (Instruction *X = foldAddWithConstant(Add&: I))
1616 return X;
1617
1618 if (Instruction *X = foldNoWrapAdd(Add&: I, Builder))
1619 return X;
1620
1621 if (Instruction *R = foldBinOpShiftWithShift(I))
1622 return R;
1623
1624 if (Instruction *R = combineAddSubWithShlAddSub(Builder, I))
1625 return R;
1626
1627 Value *LHS = I.getOperand(i_nocapture: 0), *RHS = I.getOperand(i_nocapture: 1);
1628 if (Instruction *R = foldAddLikeCommutative(LHS, RHS, NSW: I.hasNoSignedWrap(),
1629 NUW: I.hasNoUnsignedWrap()))
1630 return R;
1631 if (Instruction *R = foldAddLikeCommutative(LHS: RHS, RHS: LHS, NSW: I.hasNoSignedWrap(),
1632 NUW: I.hasNoUnsignedWrap()))
1633 return R;
1634 Type *Ty = I.getType();
1635 if (Ty->isIntOrIntVectorTy(BitWidth: 1))
1636 return BinaryOperator::CreateXor(V1: LHS, V2: RHS);
1637
1638 // X + X --> X << 1
1639 if (LHS == RHS) {
1640 auto *Shl = BinaryOperator::CreateShl(V1: LHS, V2: ConstantInt::get(Ty, V: 1));
1641 Shl->setHasNoSignedWrap(I.hasNoSignedWrap());
1642 Shl->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
1643 return Shl;
1644 }
1645
1646 Value *A, *B;
1647 if (match(V: LHS, P: m_Neg(V: m_Value(V&: A)))) {
1648 // -A + -B --> -(A + B)
1649 if (match(V: RHS, P: m_Neg(V: m_Value(V&: B))))
1650 return BinaryOperator::CreateNeg(Op: Builder.CreateAdd(LHS: A, RHS: B));
1651
1652 // -A + B --> B - A
1653 auto *Sub = BinaryOperator::CreateSub(V1: RHS, V2: A);
1654 auto *OB0 = cast<OverflowingBinaryOperator>(Val: LHS);
1655 Sub->setHasNoSignedWrap(I.hasNoSignedWrap() && OB0->hasNoSignedWrap());
1656
1657 return Sub;
1658 }
1659
1660 // A + -B --> A - B
1661 if (match(V: RHS, P: m_Neg(V: m_Value(V&: B)))) {
1662 auto *Sub = BinaryOperator::CreateSub(V1: LHS, V2: B);
1663 auto *OBO = cast<OverflowingBinaryOperator>(Val: RHS);
1664 Sub->setHasNoSignedWrap(I.hasNoSignedWrap() && OBO->hasNoSignedWrap());
1665 return Sub;
1666 }
1667
1668 if (Value *V = checkForNegativeOperand(I, Builder))
1669 return replaceInstUsesWith(I, V);
1670
1671 // (A + 1) + ~B --> A - B
1672 // ~B + (A + 1) --> A - B
1673 // (~B + A) + 1 --> A - B
1674 // (A + ~B) + 1 --> A - B
1675 // This relies on the ~B == -1-B identity.
1676 if (match(V: &I, P: m_c_BinOp(L: m_Add(L: m_Value(V&: A), R: m_One()), R: m_Not(V: m_Value(V&: B)))) ||
1677 match(V: &I, P: m_BinOp(L: m_c_Add(L: m_Not(V: m_Value(V&: B)), R: m_Value(V&: A)), R: m_One())))
1678 return BinaryOperator::CreateSub(V1: A, V2: B);
1679
1680 {
1681 // (A + C) + ~B --> A - B + (C-1)
1682 // ~B + (A + C) --> A - B + (C-1)
1683 // (~B + A) + C --> A - B + (C-1)
1684 // (A + ~B) + C --> A - B + (C-1)
1685 // With constant C, subtraction of one is free, so we replace three ops
1686 // (two adds and a bitwise-not) with two (sub and add).
1687 const APInt *C;
1688 if (match(V: &I, P: m_c_BinOp(L: m_OneUse(SubPattern: m_Add(L: m_Value(V&: A), R: m_APIntAllowPoison(Res&: C))),
1689 R: m_Not(V: m_Value(V&: B)))) ||
1690 match(V: &I, P: m_BinOp(L: m_OneUse(SubPattern: m_c_Add(L: m_Not(V: m_Value(V&: B)), R: m_Value(V&: A))),
1691 R: m_APIntAllowPoison(Res&: C)))) {
1692 Value *Sub = Builder.CreateSub(LHS: A, RHS: B);
1693 return BinaryOperator::CreateAdd(V1: Sub, V2: ConstantInt::get(Ty, V: *C - 1));
1694 }
1695 }
1696
1697 // (A + RHS) + RHS --> A + (RHS << 1)
1698 if (match(V: LHS, P: m_OneUse(SubPattern: m_c_Add(L: m_Value(V&: A), R: m_Specific(V: RHS)))))
1699 return BinaryOperator::CreateAdd(V1: A, V2: Builder.CreateShl(LHS: RHS, RHS: 1, Name: "reass.add"));
1700
1701 // LHS + (A + LHS) --> A + (LHS << 1)
1702 if (match(V: RHS, P: m_OneUse(SubPattern: m_c_Add(L: m_Value(V&: A), R: m_Specific(V: LHS)))))
1703 return BinaryOperator::CreateAdd(V1: A, V2: Builder.CreateShl(LHS, RHS: 1, Name: "reass.add"));
1704
1705 {
1706 // (A + C1) + (C2 - B) --> (A - B) + (C1 + C2)
1707 Constant *C1, *C2;
1708 if (match(V: &I, P: m_c_Add(L: m_Add(L: m_Value(V&: A), R: m_ImmConstant(C&: C1)),
1709 R: m_Sub(L: m_ImmConstant(C&: C2), R: m_Value(V&: B)))) &&
1710 (LHS->hasOneUse() || RHS->hasOneUse())) {
1711 Value *Sub = Builder.CreateSub(LHS: A, RHS: B);
1712 return BinaryOperator::CreateAdd(V1: Sub, V2: ConstantExpr::getAdd(C1, C2));
1713 }
1714
1715 // Canonicalize a constant sub operand as an add operand for better folding:
1716 // (C1 - A) + B --> (B - A) + C1
1717 if (match(V: &I, P: m_c_Add(L: m_OneUse(SubPattern: m_Sub(L: m_ImmConstant(C&: C1), R: m_Value(V&: A))),
1718 R: m_Value(V&: B)))) {
1719 Value *Sub = Builder.CreateSub(LHS: B, RHS: A, Name: "reass.sub");
1720 return BinaryOperator::CreateAdd(V1: Sub, V2: C1);
1721 }
1722 }
1723
1724 // X % C0 + (( X / C0 ) % C1) * C0 => X % (C0 * C1)
1725 if (Value *V = SimplifyAddWithRemainder(I)) return replaceInstUsesWith(I, V);
1726
1727 const APInt *C1;
1728 // (A & 2^C1) + A => A & (2^C1 - 1) iff bit C1 in A is a sign bit
1729 if (match(V: &I, P: m_c_Add(L: m_And(L: m_Value(V&: A), R: m_APInt(Res&: C1)), R: m_Deferred(V: A))) &&
1730 C1->isPowerOf2() && (ComputeNumSignBits(Op: A) > C1->countl_zero())) {
1731 Constant *NewMask = ConstantInt::get(Ty: RHS->getType(), V: *C1 - 1);
1732 return BinaryOperator::CreateAnd(V1: A, V2: NewMask);
1733 }
1734
1735 // ZExt (B - A) + ZExt(A) --> ZExt(B)
1736 if ((match(V: RHS, P: m_ZExt(Op: m_Value(V&: A))) &&
1737 match(V: LHS, P: m_ZExt(Op: m_NUWSub(L: m_Value(V&: B), R: m_Specific(V: A))))) ||
1738 (match(V: LHS, P: m_ZExt(Op: m_Value(V&: A))) &&
1739 match(V: RHS, P: m_ZExt(Op: m_NUWSub(L: m_Value(V&: B), R: m_Specific(V: A))))))
1740 return new ZExtInst(B, LHS->getType());
1741
1742 // zext(A) + sext(A) --> 0 if A is i1
1743 if (match(V: &I, P: m_c_BinOp(L: m_ZExt(Op: m_Value(V&: A)), R: m_SExt(Op: m_Deferred(V: A)))) &&
1744 A->getType()->isIntOrIntVectorTy(BitWidth: 1))
1745 return replaceInstUsesWith(I, V: Constant::getNullValue(Ty: I.getType()));
1746
1747 // sext(A < B) + zext(A > B) => ucmp/scmp(A, B)
1748 CmpPredicate LTPred, GTPred;
1749 if (match(V: &I,
1750 P: m_c_Add(L: m_SExt(Op: m_c_ICmp(Pred&: LTPred, L: m_Value(V&: A), R: m_Value(V&: B))),
1751 R: m_ZExt(Op: m_c_ICmp(Pred&: GTPred, L: m_Deferred(V: A), R: m_Deferred(V: B))))) &&
1752 A->getType()->isIntOrIntVectorTy()) {
1753 if (ICmpInst::isGT(P: LTPred)) {
1754 std::swap(a&: LTPred, b&: GTPred);
1755 std::swap(a&: A, b&: B);
1756 }
1757
1758 if (ICmpInst::isLT(P: LTPred) && ICmpInst::isGT(P: GTPred) &&
1759 ICmpInst::isSigned(Pred: LTPred) == ICmpInst::isSigned(Pred: GTPred))
1760 return replaceInstUsesWith(
1761 I, V: Builder.CreateIntrinsic(
1762 RetTy: Ty,
1763 ID: ICmpInst::isSigned(Pred: LTPred) ? Intrinsic::scmp : Intrinsic::ucmp,
1764 Args: {A, B}));
1765 }
1766
1767 // A+B --> A|B iff A and B have no bits set in common.
1768 WithCache<const Value *> LHSCache(LHS), RHSCache(RHS);
1769 switch (
1770 getNoCommonBitsSetResult(LHSCache, RHSCache, SQ: SQ.getWithInstruction(I: &I))) {
1771 case NoCommonBitsSetResult::Known:
1772 return BinaryOperator::CreateDisjointOr(V1: LHS, V2: RHS);
1773 case NoCommonBitsSetResult::OnlyIfUndefIgnored:
1774 return BinaryOperator::CreateOr(V1: LHS, V2: RHS);
1775 case NoCommonBitsSetResult::Unknown:
1776 break;
1777 }
1778
1779 if (Instruction *Ext = narrowMathIfNoOverflow(I))
1780 return Ext;
1781
1782 // (add (xor A, B) (and A, B)) --> (or A, B)
1783 // (add (and A, B) (xor A, B)) --> (or A, B)
1784 if (match(V: &I, P: m_c_BinOp(L: m_Xor(L: m_Value(V&: A), R: m_Value(V&: B)),
1785 R: m_c_And(L: m_Deferred(V: A), R: m_Deferred(V: B)))))
1786 return BinaryOperator::CreateOr(V1: A, V2: B);
1787
1788 // (add (or A, B) (and A, B)) --> (add A, B)
1789 // (add (and A, B) (or A, B)) --> (add A, B)
1790 if (match(V: &I, P: m_c_BinOp(L: m_Or(L: m_Value(V&: A), R: m_Value(V&: B)),
1791 R: m_c_And(L: m_Deferred(V: A), R: m_Deferred(V: B))))) {
1792 // Replacing operands in-place to preserve nuw/nsw flags.
1793 replaceOperand(I, OpNum: 0, V: A);
1794 replaceOperand(I, OpNum: 1, V: B);
1795 return &I;
1796 }
1797
1798 // (add A (or A, -A)) --> (and (add A, -1) A)
1799 // (add A (or -A, A)) --> (and (add A, -1) A)
1800 // (add (or A, -A) A) --> (and (add A, -1) A)
1801 // (add (or -A, A) A) --> (and (add A, -1) A)
1802 if (match(V: &I, P: m_c_BinOp(L: m_Value(V&: A), R: m_OneUse(SubPattern: m_c_Or(L: m_Neg(V: m_Deferred(V: A)),
1803 R: m_Deferred(V: A)))))) {
1804 Value *Add =
1805 Builder.CreateAdd(LHS: A, RHS: Constant::getAllOnesValue(Ty: A->getType()), Name: "",
1806 HasNUW: I.hasNoUnsignedWrap(), HasNSW: I.hasNoSignedWrap());
1807 return BinaryOperator::CreateAnd(V1: Add, V2: A);
1808 }
1809
1810 // Align-up idiom:
1811 // X + ((-X) & (C - 1)) --> (X + C - 1) & -C
1812 // ((X - 1) | (C - 1)) + 1 -> (X + C - 1) & -C
1813 // For a power-of-two C. Note -C == ~(C - 1), so the mask is simply the
1814 // inverted low-bit mask.
1815 {
1816 const APInt *LowMask;
1817 if (match(V: &I,
1818 P: m_c_Add(L: m_OneUse(SubPattern: m_And(L: m_Neg(V: m_Value(V&: A)), R: m_LowBitMask(V&: LowMask))),
1819 R: m_Deferred(V: A))) ||
1820 match(V: &I, P: m_Add(L: m_OneUse(SubPattern: m_Or(L: m_Add(L: m_Value(V&: A), R: m_AllOnes()),
1821 R: m_LowBitMask(V&: LowMask))),
1822 R: m_One()))
1823
1824 ) {
1825 Value *NewAdd = Builder.CreateAdd(LHS: A, RHS: ConstantInt::get(Ty, V: *LowMask));
1826 return BinaryOperator::CreateAnd(V1: NewAdd, V2: ConstantInt::get(Ty, V: ~*LowMask));
1827 }
1828 }
1829
1830 // Canonicalize ((A & -A) - 1) --> ((A - 1) & ~A)
1831 // Forms all commutable operations, and simplifies ctpop -> cttz folds.
1832 if (match(V: &I,
1833 P: m_Add(L: m_OneUse(SubPattern: m_c_And(L: m_Value(V&: A), R: m_OneUse(SubPattern: m_Neg(V: m_Deferred(V: A))))),
1834 R: m_AllOnes()))) {
1835 Constant *AllOnes = ConstantInt::getAllOnesValue(Ty: RHS->getType());
1836 Value *Dec = Builder.CreateAdd(LHS: A, RHS: AllOnes);
1837 Value *Not = Builder.CreateXor(LHS: A, RHS: AllOnes);
1838 return BinaryOperator::CreateAnd(V1: Dec, V2: Not);
1839 }
1840
1841 // Disguised reassociation/factorization:
1842 // ~(A * C1) + A
1843 // ((A * -C1) - 1) + A
1844 // ((A * -C1) + A) - 1
1845 // (A * (1 - C1)) - 1
1846 if (match(V: &I,
1847 P: m_c_Add(L: m_OneUse(SubPattern: m_Not(V: m_OneUse(SubPattern: m_Mul(L: m_Value(V&: A), R: m_APInt(Res&: C1))))),
1848 R: m_Deferred(V: A)))) {
1849 Type *Ty = I.getType();
1850 Constant *NewMulC = ConstantInt::get(Ty, V: 1 - *C1);
1851 Value *NewMul = Builder.CreateMul(LHS: A, RHS: NewMulC);
1852 return BinaryOperator::CreateAdd(V1: NewMul, V2: ConstantInt::getAllOnesValue(Ty));
1853 }
1854
1855 // (A * -2**C) + B --> B - (A << C)
1856 const APInt *NegPow2C;
1857 if (match(V: &I, P: m_c_Add(L: m_OneUse(SubPattern: m_Mul(L: m_Value(V&: A), R: m_NegatedPower2(V&: NegPow2C))),
1858 R: m_Value(V&: B)))) {
1859 Constant *ShiftAmtC = ConstantInt::get(Ty, V: NegPow2C->countr_zero());
1860 Value *Shl = Builder.CreateShl(LHS: A, RHS: ShiftAmtC);
1861 return BinaryOperator::CreateSub(V1: B, V2: Shl);
1862 }
1863
1864 // Canonicalize signum variant that ends in add:
1865 // (A s>> (BW - 1)) + (zext (A s> 0)) --> (A s>> (BW - 1)) | (zext (A != 0))
1866 uint64_t BitWidth = Ty->getScalarSizeInBits();
1867 if (match(V: LHS, P: m_AShr(L: m_Value(V&: A), R: m_SpecificIntAllowPoison(V: BitWidth - 1))) &&
1868 match(V: RHS, P: m_OneUse(SubPattern: m_ZExt(Op: m_OneUse(SubPattern: m_SpecificICmp(
1869 MatchPred: CmpInst::ICMP_SGT, L: m_Specific(V: A), R: m_ZeroInt())))))) {
1870 Value *NotZero = Builder.CreateIsNotNull(Arg: A, Name: "isnotnull");
1871 Value *Zext = Builder.CreateZExt(V: NotZero, DestTy: Ty, Name: "isnotnull.zext");
1872 return BinaryOperator::CreateOr(V1: LHS, V2: Zext);
1873 }
1874
1875 {
1876 Value *Cond, *Ext;
1877 Constant *C;
1878 // (add X, (sext/zext (icmp eq X, C)))
1879 // -> (select (icmp eq X, C), (add C, (sext/zext 1)), X)
1880 auto CondMatcher =
1881 m_Value(V&: Cond, P: m_SpecificICmp(MatchPred: ICmpInst::ICMP_EQ, L: m_Deferred(V: A),
1882 R: m_ImmConstant(C)));
1883
1884 if (match(V: &I,
1885 P: m_c_Add(L: m_Value(V&: A), R: m_Value(V&: Ext, P: m_ZExtOrSExt(Op: CondMatcher)))) &&
1886 Ext->hasOneUse()) {
1887 Value *Add = isa<ZExtInst>(Val: Ext) ? InstCombiner::AddOne(C)
1888 : InstCombiner::SubOne(C);
1889 return replaceInstUsesWith(I, V: Builder.CreateSelect(C: Cond, True: Add, False: A));
1890 }
1891 }
1892
1893 // (add (add A, 1), (sext (icmp ne A, 0))) => call umax(A, 1)
1894 if (match(V: LHS, P: m_Add(L: m_Value(V&: A), R: m_One())) &&
1895 match(V: RHS, P: m_OneUse(SubPattern: m_SExt(Op: m_SpecificICmp(
1896 MatchPred: ICmpInst::ICMP_NE, L: m_Specific(V: A), R: m_ZeroInt()))))) {
1897 Value *OneConst = ConstantInt::get(Ty: A->getType(), V: 1);
1898 Value *UMax = Builder.CreateBinaryIntrinsic(ID: Intrinsic::umax, LHS: A, RHS: OneConst);
1899 return replaceInstUsesWith(I, V: UMax);
1900 }
1901
1902 if (Instruction *Ashr = foldAddToAshr(Add&: I))
1903 return Ashr;
1904
1905 // Ceiling division by power-of-2:
1906 // (X >> log2(N)) + zext(X & (N-1) != 0) --> (X + (N-1)) >> log2(N)
1907 // This is valid when adding (N-1) to X doesn't overflow.
1908 {
1909 Value *X;
1910 const APInt *ShiftAmt, *Mask;
1911 CmpPredicate Pred;
1912
1913 // Match: (X >> C) + zext((X & Mask) != 0)
1914 // or: zext((X & Mask) != 0) + (X >> C)
1915 if (match(V: &I,
1916 P: m_c_Add(L: m_ZExt(Op: m_SpecificICmp(
1917 MatchPred: ICmpInst::ICMP_NE,
1918 L: m_And(L: m_Value(V&: X), R: m_LowBitMask(V&: Mask)), R: m_ZeroInt())),
1919 R: m_OneUse(SubPattern: m_ZExtOrSelf(Op: m_OneUse(
1920 SubPattern: m_LShr(L: m_Deferred(V: X), R: m_APInt(Res&: ShiftAmt))))))) &&
1921 Mask->popcount() == *ShiftAmt) {
1922
1923 // Check if X + Mask doesn't overflow
1924 unsigned Xbits = X->getType()->getScalarSizeInBits();
1925 unsigned Ibits = Ty->getScalarSizeInBits();
1926 bool NeedZext = Ibits > Xbits;
1927 Constant *MaskC = ConstantInt::get(Ty, V: Mask->zext(width: Ibits));
1928 if (NeedZext || willNotOverflowUnsignedAdd(LHS: X, RHS: MaskC, CtxI: I)) {
1929 if (NeedZext)
1930 X = Builder.CreateZExt(V: X, DestTy: Ty);
1931 // (X + Mask) >> ShiftAmt
1932 Value *Add = Builder.CreateNUWAdd(LHS: X, RHS: MaskC);
1933 return BinaryOperator::CreateLShr(
1934 V1: Add, V2: ConstantInt::get(Ty, V: ShiftAmt->zext(width: Ibits)));
1935 }
1936 }
1937 }
1938
1939 // (~X) + (~Y) --> -2 - (X + Y)
1940 {
1941 // To ensure we can save instructions we need to ensure that we consume both
1942 // LHS/RHS (i.e they have a `not`).
1943 bool ConsumesLHS, ConsumesRHS;
1944 if (isFreeToInvert(V: LHS, WillInvertAllUses: LHS->hasOneUse(), DoesConsume&: ConsumesLHS) && ConsumesLHS &&
1945 isFreeToInvert(V: RHS, WillInvertAllUses: RHS->hasOneUse(), DoesConsume&: ConsumesRHS) && ConsumesRHS) {
1946 Value *NotLHS = getFreelyInverted(V: LHS, WillInvertAllUses: LHS->hasOneUse(), Builder: &Builder);
1947 Value *NotRHS = getFreelyInverted(V: RHS, WillInvertAllUses: RHS->hasOneUse(), Builder: &Builder);
1948 assert(NotLHS != nullptr && NotRHS != nullptr &&
1949 "isFreeToInvert desynced with getFreelyInverted");
1950 Value *LHSPlusRHS = Builder.CreateAdd(LHS: NotLHS, RHS: NotRHS);
1951 return BinaryOperator::CreateSub(
1952 V1: ConstantInt::getSigned(Ty: RHS->getType(), V: -2), V2: LHSPlusRHS);
1953 }
1954 }
1955
1956 if (Instruction *R = tryFoldInstWithCtpopWithNot(I: &I))
1957 return R;
1958
1959 // TODO(jingyue): Consider willNotOverflowSignedAdd and
1960 // willNotOverflowUnsignedAdd to reduce the number of invocations of
1961 // computeKnownBits.
1962 bool Changed = false;
1963 if (!I.hasNoSignedWrap() && willNotOverflowSignedAdd(LHS: LHSCache, RHS: RHSCache, CtxI: I)) {
1964 Changed = true;
1965 I.setHasNoSignedWrap(true);
1966 }
1967 if (!I.hasNoUnsignedWrap() &&
1968 willNotOverflowUnsignedAdd(LHS: LHSCache, RHS: RHSCache, CtxI: I)) {
1969 Changed = true;
1970 I.setHasNoUnsignedWrap(true);
1971 }
1972
1973 if (Instruction *V = canonicalizeLowbitMask(I, Builder))
1974 return V;
1975
1976 if (Instruction *V =
1977 canonicalizeCondSignextOfHighBitExtractToSignextHighBitExtract(I))
1978 return V;
1979
1980 if (Instruction *SatAdd = foldToUnsignedSaturatedAdd(I))
1981 return SatAdd;
1982
1983 // usub.sat(A, B) + B => umax(A, B)
1984 if (match(V: &I, P: m_c_BinOp(
1985 L: m_OneUse(SubPattern: m_Intrinsic<Intrinsic::usub_sat>(Ops: m_Value(V&: A), Ops: m_Value(V&: B))),
1986 R: m_Deferred(V: B)))) {
1987 return replaceInstUsesWith(I,
1988 V: Builder.CreateIntrinsic(ID: Intrinsic::umax, OverloadTypes: {I.getType()}, Args: {A, B}));
1989 }
1990
1991 // ctpop(A) + ctpop(B) => ctpop(A | B) if A and B have no bits set in common.
1992 if (match(V: LHS, P: m_OneUse(SubPattern: m_Ctpop(Op0: m_Value(V&: A)))) &&
1993 match(V: RHS, P: m_OneUse(SubPattern: m_Ctpop(Op0: m_Value(V&: B)))) &&
1994 haveNoCommonBitsSet(LHSCache: A, RHSCache: B, SQ: SQ.getWithInstruction(I: &I)))
1995 return replaceInstUsesWith(
1996 I, V: Builder.CreateIntrinsic(ID: Intrinsic::ctpop, OverloadTypes: {I.getType()},
1997 Args: {Builder.CreateDisjointOr(LHS: A, RHS: B)}));
1998
1999 // Fold the log2_ceil idiom:
2000 // zext(ctpop(A) >u/!= 1) + (ctlz(A, true) ^ (BW - 1))
2001 // -->
2002 // BW - ctlz(A - 1, false)
2003 const APInt *XorC;
2004 CmpPredicate Pred;
2005 if (match(V: &I, P: m_c_Add(L: m_ZExt(Op: m_ICmp(Pred, L: m_Ctpop(Op0: m_Value(V&: A)), R: m_One())),
2006 R: m_OneUse(SubPattern: m_ZExtOrSelf(Op: m_OneUse(
2007 SubPattern: m_Xor(L: m_OneUse(SubPattern: m_TruncOrSelf(Op: m_OneUse(
2008 SubPattern: m_Ctlz(Op0: m_Deferred(V: A), Op1: m_One())))),
2009 R: m_APInt(Res&: XorC))))))) &&
2010 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_NE) &&
2011 *XorC == A->getType()->getScalarSizeInBits() - 1 &&
2012 isPowerOf2_32(Value: A->getType()->getScalarSizeInBits())) {
2013 Value *Sub = Builder.CreateAdd(LHS: A, RHS: Constant::getAllOnesValue(Ty: A->getType()));
2014 Value *Ctlz = Builder.CreateIntrinsic(ID: Intrinsic::ctlz, OverloadTypes: {A->getType()},
2015 Args: {Sub, Builder.getFalse()});
2016 Value *Ret = Builder.CreateSub(
2017 LHS: ConstantInt::get(Ty: A->getType(), V: A->getType()->getScalarSizeInBits()),
2018 RHS: Ctlz, Name: "", /*HasNUW=*/true, /*HasNSW=*/true);
2019 return replaceInstUsesWith(I, V: Builder.CreateZExtOrTrunc(V: Ret, DestTy: I.getType()));
2020 }
2021
2022 if (Instruction *Res = foldSquareSumInt(I))
2023 return Res;
2024
2025 if (Instruction *Res = foldBinOpOfDisplacedShifts(I))
2026 return Res;
2027
2028 if (Instruction *Res = foldBinOpOfSelectAndCastOfSelectCondition(I))
2029 return Res;
2030
2031 if (Instruction *Res = foldDivCeil(I))
2032 return Res;
2033
2034 // (A | -2) + A -> (A - 1) & -2
2035 APInt NegTwo(Ty->getScalarSizeInBits(), -2, /*isSigned=*/true);
2036 if (match(V: &I, P: m_c_BinOp(L: m_OneUse(SubPattern: m_Or(L: m_Value(V&: A), R: m_SpecificInt(V: NegTwo))),
2037 R: m_Deferred(V: A)))) {
2038 Value *Ret = Builder.CreateAdd(
2039 LHS: A, RHS: ConstantInt::get(
2040 Ty, V: APInt(Ty->getScalarSizeInBits(), -1, /*isSigned=*/true)));
2041 return BinaryOperator::CreateAnd(V1: Ret, V2: ConstantInt::get(Ty, V: NegTwo));
2042 }
2043
2044 // Re-enqueue users of the induction variable of add recurrence if we infer
2045 // new nuw/nsw flags.
2046 if (Changed) {
2047 PHINode *PHI;
2048 Value *Start, *Step;
2049 if (matchSimpleRecurrence(I: &I, P&: PHI, Start, Step))
2050 Worklist.pushUsersToWorkList(I&: *PHI);
2051 }
2052
2053 return Changed ? &I : nullptr;
2054}
2055
2056/// Eliminate an op from a linear interpolation (lerp) pattern.
2057static Instruction *factorizeLerp(BinaryOperator &I,
2058 InstCombiner::BuilderTy &Builder) {
2059 Value *X, *Y, *Z;
2060 if (!match(V: &I, P: m_c_FAdd(L: m_OneUse(SubPattern: m_c_FMul(L: m_Value(V&: Y),
2061 R: m_OneUse(SubPattern: m_FSub(L: m_FPOne(),
2062 R: m_Value(V&: Z))))),
2063 R: m_OneUse(SubPattern: m_c_FMul(L: m_Value(V&: X), R: m_Deferred(V: Z))))))
2064 return nullptr;
2065
2066 // (Y * (1.0 - Z)) + (X * Z) --> Y + Z * (X - Y) [8 commuted variants]
2067 Value *XY = Builder.CreateFSubFMF(L: X, R: Y, FMFSource: &I);
2068 Value *MulZ = Builder.CreateFMulFMF(L: Z, R: XY, FMFSource: &I);
2069 return BinaryOperator::CreateFAddFMF(V1: Y, V2: MulZ, FMFSource: &I);
2070}
2071
2072/// Factor a common operand out of fadd/fsub of fmul/fdiv.
2073static Instruction *factorizeFAddFSub(BinaryOperator &I,
2074 InstCombiner::BuilderTy &Builder) {
2075 assert((I.getOpcode() == Instruction::FAdd ||
2076 I.getOpcode() == Instruction::FSub) && "Expecting fadd/fsub");
2077 assert(I.hasAllowReassoc() && I.hasNoSignedZeros() &&
2078 "FP factorization requires FMF");
2079
2080 if (Instruction *Lerp = factorizeLerp(I, Builder))
2081 return Lerp;
2082
2083 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
2084 if (!Op0->hasOneUse() || !Op1->hasOneUse())
2085 return nullptr;
2086
2087 Value *X, *Y, *Z;
2088 bool IsFMul;
2089 if ((match(V: Op0, P: m_FMul(L: m_Value(V&: X), R: m_Value(V&: Z))) &&
2090 match(V: Op1, P: m_c_FMul(L: m_Value(V&: Y), R: m_Specific(V: Z)))) ||
2091 (match(V: Op0, P: m_FMul(L: m_Value(V&: Z), R: m_Value(V&: X))) &&
2092 match(V: Op1, P: m_c_FMul(L: m_Value(V&: Y), R: m_Specific(V: Z)))))
2093 IsFMul = true;
2094 else if (match(V: Op0, P: m_FDiv(L: m_Value(V&: X), R: m_Value(V&: Z))) &&
2095 match(V: Op1, P: m_FDiv(L: m_Value(V&: Y), R: m_Specific(V: Z))))
2096 IsFMul = false;
2097 else
2098 return nullptr;
2099
2100 // (X * Z) + (Y * Z) --> (X + Y) * Z
2101 // (X * Z) - (Y * Z) --> (X - Y) * Z
2102 // (X / Z) + (Y / Z) --> (X + Y) / Z
2103 // (X / Z) - (Y / Z) --> (X - Y) / Z
2104 bool IsFAdd = I.getOpcode() == Instruction::FAdd;
2105 Value *XY = IsFAdd ? Builder.CreateFAddFMF(L: X, R: Y, FMFSource: &I)
2106 : Builder.CreateFSubFMF(L: X, R: Y, FMFSource: &I);
2107
2108 // Bail out if we just created a denormal constant.
2109 // TODO: This is copied from a previous implementation. Is it necessary?
2110 const APFloat *C;
2111 if (match(V: XY, P: m_APFloat(Res&: C)) && !C->isNormal())
2112 return nullptr;
2113
2114 return IsFMul ? BinaryOperator::CreateFMulFMF(V1: XY, V2: Z, FMFSource: &I)
2115 : BinaryOperator::CreateFDivFMF(V1: XY, V2: Z, FMFSource: &I);
2116}
2117
2118Instruction *InstCombinerImpl::visitFAdd(BinaryOperator &I) {
2119 if (Value *V = simplifyFAddInst(LHS: I.getOperand(i_nocapture: 0), RHS: I.getOperand(i_nocapture: 1),
2120 FMF: I.getFastMathFlags(),
2121 Q: SQ.getWithInstruction(I: &I)))
2122 return replaceInstUsesWith(I, V);
2123
2124 if (SimplifyAssociativeOrCommutative(I))
2125 return &I;
2126
2127 if (Instruction *X = foldVectorBinop(Inst&: I))
2128 return X;
2129
2130 if (Instruction *Phi = foldBinopWithPhiOperands(BO&: I))
2131 return Phi;
2132
2133 if (Instruction *FoldedFAdd = foldBinOpIntoSelectOrPhi(I))
2134 return FoldedFAdd;
2135
2136 // B = fadd A, 0.0
2137 // Z = Op B
2138 // can be transformed into
2139 // Z = Op A
2140 // Where Op is such that we can ignore sign of 0 in fadd
2141 Value *A;
2142 if (match(V: &I, P: m_OneUse(SubPattern: m_FAdd(L: m_Value(V&: A), R: m_AnyZeroFP()))) &&
2143 canIgnoreSignBitOfZero(U: *I.use_begin()))
2144 return replaceInstUsesWith(I, V: A);
2145
2146 // (-X) + Y --> Y - X
2147 Value *X, *Y;
2148 // TODO: Confirm whether m_FNegOrFSubNegZero is correct.
2149 if (match(V: &I, P: m_c_FAdd(L: m_FNegOrFSubNegZero(X: m_Value(V&: X)), R: m_Value(V&: Y))))
2150 return BinaryOperator::CreateFSubFMF(V1: Y, V2: X, FMFSource: &I);
2151
2152 // Similar to above, but look through fmul/fdiv for the negated term.
2153 // (-X * Y) + Z --> Z - (X * Y) [4 commuted variants]
2154 Value *Z;
2155 // TODO: Confirm whether m_FNegOrFSubNegZero is correct.
2156 if (match(V: &I, P: m_c_FAdd(L: m_OneUse(SubPattern: m_c_FMul(L: m_FNegOrFSubNegZero(X: m_Value(V&: X)),
2157 R: m_Value(V&: Y))),
2158 R: m_Value(V&: Z)))) {
2159 Value *XY = Builder.CreateFMulFMF(L: X, R: Y, FMFSource: &I);
2160 return BinaryOperator::CreateFSubFMF(V1: Z, V2: XY, FMFSource: &I);
2161 }
2162 // (-X / Y) + Z --> Z - (X / Y) [2 commuted variants]
2163 // (X / -Y) + Z --> Z - (X / Y) [2 commuted variants]
2164 // TODO: Confirm whether m_FNegOrFSubNegZero is correct.
2165 if (match(V: &I, P: m_c_FAdd(L: m_OneUse(SubPattern: m_FDiv(L: m_FNegOrFSubNegZero(X: m_Value(V&: X)),
2166 R: m_Value(V&: Y))),
2167 R: m_Value(V&: Z))) ||
2168 match(V: &I, P: m_c_FAdd(L: m_OneUse(SubPattern: m_FDiv(L: m_Value(V&: X),
2169 R: m_FNegOrFSubNegZero(X: m_Value(V&: Y)))),
2170 R: m_Value(V&: Z)))) {
2171 Value *XY = Builder.CreateFDivFMF(L: X, R: Y, FMFSource: &I);
2172 return BinaryOperator::CreateFSubFMF(V1: Z, V2: XY, FMFSource: &I);
2173 }
2174
2175 // Check for (fadd double (sitofp x), y), see if we can merge this into an
2176 // integer add followed by a promotion.
2177 if (Instruction *R = foldFBinOpOfIntCasts(I))
2178 return R;
2179
2180 Value *LHS = I.getOperand(i_nocapture: 0), *RHS = I.getOperand(i_nocapture: 1);
2181 // Handle specials cases for FAdd with selects feeding the operation
2182 if (Value *V = SimplifySelectsFeedingBinaryOp(I, LHS, RHS))
2183 return replaceInstUsesWith(I, V);
2184
2185 if (I.hasAllowReassoc() && I.hasNoSignedZeros()) {
2186 if (Instruction *F = factorizeFAddFSub(I, Builder))
2187 return F;
2188
2189 if (Instruction *F = foldSquareSumFP(I))
2190 return F;
2191
2192 // Try to fold fadd into start value of reduction intrinsic.
2193 if (match(V: &I, P: m_c_FAdd(L: m_OneUse(SubPattern: m_Intrinsic<Intrinsic::vector_reduce_fadd>(
2194 Ops: m_AnyZeroFP(), Ops: m_Value(V&: X))),
2195 R: m_Value(V&: Y)))) {
2196 // fadd (rdx 0.0, X), Y --> rdx Y, X
2197 return replaceInstUsesWith(
2198 I, V: Builder.CreateIntrinsic(ID: Intrinsic::vector_reduce_fadd,
2199 OverloadTypes: {X->getType()}, Args: {Y, X}, FMFSource: &I));
2200 }
2201 const APFloat *StartC, *C;
2202 if (match(V: LHS, P: m_OneUse(SubPattern: m_Intrinsic<Intrinsic::vector_reduce_fadd>(
2203 Ops: m_APFloat(Res&: StartC), Ops: m_Value(V&: X)))) &&
2204 match(V: RHS, P: m_APFloat(Res&: C))) {
2205 // fadd (rdx StartC, X), C --> rdx (C + StartC), X
2206 Constant *NewStartC = ConstantFP::get(Ty: I.getType(), V: *C + *StartC);
2207 return replaceInstUsesWith(
2208 I, V: Builder.CreateIntrinsic(ID: Intrinsic::vector_reduce_fadd,
2209 OverloadTypes: {X->getType()}, Args: {NewStartC, X}, FMFSource: &I));
2210 }
2211
2212 // (X * MulC) + X --> X * (MulC + 1.0)
2213 Constant *MulC;
2214 if (match(V: &I, P: m_c_FAdd(L: m_FMul(L: m_Value(V&: X), R: m_ImmConstant(C&: MulC)),
2215 R: m_Deferred(V: X)))) {
2216 if (Constant *NewMulC = ConstantFoldBinaryOpOperands(
2217 Opcode: Instruction::FAdd, LHS: MulC, RHS: ConstantFP::get(Ty: I.getType(), V: 1.0), DL))
2218 return BinaryOperator::CreateFMulFMF(V1: X, V2: NewMulC, FMFSource: &I);
2219 }
2220
2221 // (-X - Y) + (X + Z) --> Z - Y
2222 // TODO: Confirm whether m_FNegOrFSubNegZero is correct.
2223 if (match(V: &I, P: m_c_FAdd(L: m_FSub(L: m_FNegOrFSubNegZero(X: m_Value(V&: X)), R: m_Value(V&: Y)),
2224 R: m_c_FAdd(L: m_Deferred(V: X), R: m_Value(V&: Z)))))
2225 return BinaryOperator::CreateFSubFMF(V1: Z, V2: Y, FMFSource: &I);
2226
2227 if (Value *V = FAddCombine(Builder).simplify(I: &I))
2228 return replaceInstUsesWith(I, V);
2229 }
2230
2231 // minumum(X, Y) + maximum(X, Y) => X + Y.
2232 if (match(V: &I,
2233 P: m_c_FAdd(L: m_Intrinsic<Intrinsic::maximum>(Ops: m_Value(V&: X), Ops: m_Value(V&: Y)),
2234 R: m_c_Intrinsic<Intrinsic::minimum>(Op0: m_Deferred(V: X),
2235 Op1: m_Deferred(V: Y))))) {
2236 BinaryOperator *Result = BinaryOperator::CreateFAddFMF(V1: X, V2: Y, FMFSource: &I);
2237 // We cannot preserve ninf if nnan flag is not set.
2238 // If X is NaN and Y is Inf then in original program we had NaN + NaN,
2239 // while in optimized version NaN + Inf and this is a poison with ninf flag.
2240 if (!Result->hasNoNaNs())
2241 Result->setHasNoInfs(false);
2242 return Result;
2243 }
2244
2245 return nullptr;
2246}
2247
2248CommonPointerBase CommonPointerBase::compute(Value *LHS, Value *RHS) {
2249 CommonPointerBase Base;
2250
2251 if (LHS->getType() != RHS->getType())
2252 return Base;
2253
2254 // Collect all base pointers of LHS.
2255 SmallPtrSet<Value *, 16> Ptrs;
2256 Value *Ptr = LHS;
2257 while (true) {
2258 Ptrs.insert(Ptr);
2259 if (auto *GEP = dyn_cast<GEPOperator>(Val: Ptr))
2260 Ptr = GEP->getPointerOperand();
2261 else
2262 break;
2263 }
2264
2265 // Find common base and collect RHS GEPs.
2266 bool First = true;
2267 while (true) {
2268 if (Ptrs.contains(Ptr: RHS)) {
2269 Base.Ptr = RHS;
2270 break;
2271 }
2272
2273 if (auto *GEP = dyn_cast<GEPOperator>(Val: RHS)) {
2274 Base.RHSGEPs.push_back(Elt: GEP);
2275 if (First) {
2276 First = false;
2277 Base.RHSNW = GEP->getNoWrapFlags();
2278 } else {
2279 Base.RHSNW = Base.RHSNW.intersectForOffsetAdd(Other: GEP->getNoWrapFlags());
2280 }
2281 RHS = GEP->getPointerOperand();
2282 } else {
2283 // No common base.
2284 return Base;
2285 }
2286 }
2287
2288 // Collect LHS GEPs.
2289 First = true;
2290 while (true) {
2291 if (LHS == Base.Ptr)
2292 break;
2293
2294 auto *GEP = cast<GEPOperator>(Val: LHS);
2295 Base.LHSGEPs.push_back(Elt: GEP);
2296 if (First) {
2297 First = false;
2298 Base.LHSNW = GEP->getNoWrapFlags();
2299 } else {
2300 Base.LHSNW = Base.LHSNW.intersectForOffsetAdd(Other: GEP->getNoWrapFlags());
2301 }
2302 LHS = GEP->getPointerOperand();
2303 }
2304
2305 return Base;
2306}
2307
2308bool CommonPointerBase::isExpensive() const {
2309 unsigned NumGEPs = 0;
2310 auto ProcessGEPs = [&NumGEPs](ArrayRef<GEPOperator *> GEPs) {
2311 bool SeenMultiUse = false;
2312 for (GEPOperator *GEP : GEPs) {
2313 // Only count multi-use GEPs, excluding the first one. For the first one,
2314 // we will directly reuse the offset. For one-use GEPs, their offset will
2315 // be folded into a multi-use GEP.
2316 if (!GEP->hasOneUse()) {
2317 if (SeenMultiUse)
2318 ++NumGEPs;
2319 SeenMultiUse = true;
2320 }
2321 }
2322 };
2323 ProcessGEPs(LHSGEPs);
2324 ProcessGEPs(RHSGEPs);
2325 return NumGEPs > 2;
2326}
2327
2328/// Optimize pointer differences into the same array into a size. Consider:
2329/// &A[10] - &A[0]: we should compile this to "10". LHS/RHS are the pointer
2330/// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
2331Value *InstCombinerImpl::OptimizePointerDifference(Value *LHS, Value *RHS,
2332 Type *Ty, bool IsNUW) {
2333 CommonPointerBase Base = CommonPointerBase::compute(LHS, RHS);
2334 if (!Base.Ptr || Base.isExpensive())
2335 return nullptr;
2336
2337 // To avoid duplicating the offset arithmetic, rewrite the GEP to use the
2338 // computed offset.
2339 // TODO: We should probably do this even if there is only one GEP.
2340 bool RewriteGEPs = !Base.LHSGEPs.empty() && !Base.RHSGEPs.empty();
2341
2342 Type *IdxTy = DL.getIndexType(PtrTy: LHS->getType());
2343 Value *Result = EmitGEPOffsets(GEPs: Base.LHSGEPs, NW: Base.LHSNW, IdxTy, RewriteGEPs);
2344 Value *Offset2 = EmitGEPOffsets(GEPs: Base.RHSGEPs, NW: Base.RHSNW, IdxTy, RewriteGEPs);
2345
2346 // If this is a single inbounds GEP and the original sub was nuw,
2347 // then the final multiplication is also nuw.
2348 if (auto *I = dyn_cast<OverflowingBinaryOperator>(Val: Result))
2349 if (IsNUW && match(V: Offset2, P: m_Zero()) && Base.LHSNW.isInBounds() &&
2350 (I->use_empty() || I->hasOneUse()) && I->hasNoSignedWrap() &&
2351 !I->hasNoUnsignedWrap() &&
2352 ((I->getOpcode() == Instruction::Mul &&
2353 match(V: I->getOperand(i_nocapture: 1), P: m_NonNegative())) ||
2354 I->getOpcode() == Instruction::Shl))
2355 cast<Instruction>(Val: I)->setHasNoUnsignedWrap();
2356
2357 // If we have a 2nd GEP of the same base pointer, subtract the offsets.
2358 // If both GEPs are inbounds, then the subtract does not have signed overflow.
2359 // If both GEPs are nuw and the original sub is nuw, the new sub is also nuw.
2360 if (!match(V: Offset2, P: m_Zero())) {
2361 Result =
2362 Builder.CreateSub(LHS: Result, RHS: Offset2, Name: "gepdiff",
2363 HasNUW: IsNUW && Base.LHSNW.hasNoUnsignedWrap() &&
2364 Base.RHSNW.hasNoUnsignedWrap(),
2365 HasNSW: Base.LHSNW.isInBounds() && Base.RHSNW.isInBounds());
2366 }
2367
2368 return Builder.CreateIntCast(V: Result, DestTy: Ty, isSigned: true);
2369}
2370
2371static Instruction *foldSubOfMinMax(BinaryOperator &I,
2372 InstCombiner::BuilderTy &Builder) {
2373 Value *Op0 = I.getOperand(i_nocapture: 0);
2374 Value *Op1 = I.getOperand(i_nocapture: 1);
2375 Type *Ty = I.getType();
2376 auto *MinMax = dyn_cast<MinMaxIntrinsic>(Val: Op1);
2377 if (!MinMax)
2378 return nullptr;
2379
2380 // sub(add(X,Y), s/umin(X,Y)) --> s/umax(X,Y)
2381 // sub(add(X,Y), s/umax(X,Y)) --> s/umin(X,Y)
2382 Value *X = MinMax->getLHS();
2383 Value *Y = MinMax->getRHS();
2384 if (match(V: Op0, P: m_c_Add(L: m_Specific(V: X), R: m_Specific(V: Y))) &&
2385 (Op0->hasOneUse() || Op1->hasOneUse())) {
2386 Intrinsic::ID InvID = getInverseMinMaxIntrinsic(MinMaxID: MinMax->getIntrinsicID());
2387 Function *F = Intrinsic::getOrInsertDeclaration(M: I.getModule(), id: InvID, OverloadTys: Ty);
2388 return CallInst::Create(Func: F, Args: {X, Y});
2389 }
2390
2391 // sub(add(X,Y),umin(Y,Z)) --> add(X,usub.sat(Y,Z))
2392 // sub(add(X,Z),umin(Y,Z)) --> add(X,usub.sat(Z,Y))
2393 Value *Z;
2394 if (match(V: Op1, P: m_OneUse(SubPattern: m_UMin(Op0: m_Value(V&: Y), Op1: m_Value(V&: Z))))) {
2395 if (match(V: Op0, P: m_OneUse(SubPattern: m_c_Add(L: m_Specific(V: Y), R: m_Value(V&: X))))) {
2396 Value *USub = Builder.CreateIntrinsic(ID: Intrinsic::usub_sat, OverloadTypes: Ty, Args: {Y, Z});
2397 return BinaryOperator::CreateAdd(V1: X, V2: USub);
2398 }
2399 if (match(V: Op0, P: m_OneUse(SubPattern: m_c_Add(L: m_Specific(V: Z), R: m_Value(V&: X))))) {
2400 Value *USub = Builder.CreateIntrinsic(ID: Intrinsic::usub_sat, OverloadTypes: Ty, Args: {Z, Y});
2401 return BinaryOperator::CreateAdd(V1: X, V2: USub);
2402 }
2403 }
2404
2405 // sub Op0, smin((sub nsw Op0, Z), 0) --> smax Op0, Z
2406 // sub Op0, smax((sub nsw Op0, Z), 0) --> smin Op0, Z
2407 if (MinMax->isSigned() && match(V: Y, P: m_ZeroInt()) &&
2408 match(V: X, P: m_NSWSub(L: m_Specific(V: Op0), R: m_Value(V&: Z)))) {
2409 Intrinsic::ID InvID = getInverseMinMaxIntrinsic(MinMaxID: MinMax->getIntrinsicID());
2410 Function *F = Intrinsic::getOrInsertDeclaration(M: I.getModule(), id: InvID, OverloadTys: Ty);
2411 return CallInst::Create(Func: F, Args: {Op0, Z});
2412 }
2413
2414 return nullptr;
2415}
2416
2417/// sub nuw (and X, LowMask), (zext Y) --> zext (sub nuw (trunc X), Y)
2418/// sub nuw (zext Y), (and X, LowMask) --> zext (sub nuw Y, (trunc X))
2419/// where LowMask has exactly as many low bits set as Y's width, so the 'and'
2420/// is zext(trunc X) and the wide nuw implies the narrow sub does not wrap.
2421static Instruction *foldSubNUWOfMaskAndZExt(BinaryOperator &I,
2422 InstCombiner::BuilderTy &Builder) {
2423 if (!I.hasNoUnsignedWrap())
2424 return nullptr;
2425
2426 Value *X, *Y;
2427 const APInt *Mask;
2428 auto MaskPat = m_OneUse(SubPattern: m_And(L: m_Value(V&: X), R: m_LowBitMask(V&: Mask)));
2429 auto ZExtPat = m_OneUse(SubPattern: m_ZExt(Op: m_Value(V&: Y)));
2430 bool MaskIsLHS = match(V: &I, P: m_Sub(L: MaskPat, R: ZExtPat));
2431 if ((!MaskIsLHS && !match(V: &I, P: m_Sub(L: ZExtPat, R: MaskPat))) ||
2432 Mask->countr_one() != Y->getType()->getScalarSizeInBits())
2433 return nullptr;
2434
2435 Value *TruncX = Builder.CreateTrunc(V: X, DestTy: Y->getType());
2436 Value *NarrowSub = MaskIsLHS ? Builder.CreateNUWSub(LHS: TruncX, RHS: Y)
2437 : Builder.CreateNUWSub(LHS: Y, RHS: TruncX);
2438 return new ZExtInst(NarrowSub, I.getType());
2439}
2440
2441Instruction *InstCombinerImpl::visitSub(BinaryOperator &I) {
2442 if (Value *V = simplifySubInst(LHS: I.getOperand(i_nocapture: 0), RHS: I.getOperand(i_nocapture: 1),
2443 IsNSW: I.hasNoSignedWrap(), IsNUW: I.hasNoUnsignedWrap(),
2444 Q: SQ.getWithInstruction(I: &I)))
2445 return replaceInstUsesWith(I, V);
2446
2447 if (Instruction *X = foldVectorBinop(Inst&: I))
2448 return X;
2449
2450 if (Instruction *Phi = foldBinopWithPhiOperands(BO&: I))
2451 return Phi;
2452
2453 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
2454
2455 // If this is a 'B = x-(-A)', change to B = x+A.
2456 // We deal with this without involving Negator to preserve NSW flag.
2457 if (Value *V = dyn_castNegVal(V: Op1)) {
2458 BinaryOperator *Res = BinaryOperator::CreateAdd(V1: Op0, V2: V);
2459
2460 if (const auto *BO = dyn_cast<BinaryOperator>(Val: Op1)) {
2461 assert(BO->getOpcode() == Instruction::Sub &&
2462 "Expected a subtraction operator!");
2463 if (BO->hasNoSignedWrap() && I.hasNoSignedWrap())
2464 Res->setHasNoSignedWrap(true);
2465 } else {
2466 if (cast<Constant>(Val: Op1)->isNotMinSignedValue() && I.hasNoSignedWrap())
2467 Res->setHasNoSignedWrap(true);
2468 }
2469
2470 return Res;
2471 }
2472
2473 // Try this before Negator to preserve NSW flag.
2474 if (Instruction *R = factorizeMathWithShlOps(I, Builder))
2475 return R;
2476
2477 Constant *C;
2478 if (match(V: Op0, P: m_ImmConstant(C))) {
2479 Value *X;
2480 Constant *C2;
2481
2482 // C-(X+C2) --> (C-C2)-X
2483 if (match(V: Op1, P: m_AddLike(L: m_Value(V&: X), R: m_ImmConstant(C&: C2)))) {
2484 // C-C2 never overflow, and C-(X+C2), (X+C2) has NSW/NUW
2485 // => (C-C2)-X can have NSW/NUW
2486 bool WillNotSOV = willNotOverflowSignedSub(LHS: C, RHS: C2, CtxI: I);
2487 BinaryOperator *Res =
2488 BinaryOperator::CreateSub(V1: ConstantExpr::getSub(C1: C, C2), V2: X);
2489
2490 // or disjoint is equivalent to add nuw nsw.
2491 bool Op1NSW = true;
2492 bool Op1NUW = true;
2493
2494 if (auto *OBO1 = dyn_cast<OverflowingBinaryOperator>(Val: Op1)) {
2495 Op1NSW = OBO1->hasNoSignedWrap();
2496 Op1NUW = OBO1->hasNoUnsignedWrap();
2497 }
2498
2499 Res->setHasNoSignedWrap(I.hasNoSignedWrap() && Op1NSW && WillNotSOV);
2500 Res->setHasNoUnsignedWrap(I.hasNoUnsignedWrap() && Op1NUW);
2501 return Res;
2502 }
2503 }
2504
2505 auto TryToNarrowDeduceFlags = [this, &I, &Op0, &Op1]() -> Instruction * {
2506 if (Instruction *Ext = narrowMathIfNoOverflow(I))
2507 return Ext;
2508
2509 bool Changed = false;
2510 if (!I.hasNoSignedWrap() && willNotOverflowSignedSub(LHS: Op0, RHS: Op1, CtxI: I)) {
2511 Changed = true;
2512 I.setHasNoSignedWrap(true);
2513 }
2514 if (!I.hasNoUnsignedWrap() && willNotOverflowUnsignedSub(LHS: Op0, RHS: Op1, CtxI: I)) {
2515 Changed = true;
2516 I.setHasNoUnsignedWrap(true);
2517 }
2518
2519 return Changed ? &I : nullptr;
2520 };
2521
2522 if (Instruction *R = foldSubNUWOfMaskAndZExt(I, Builder))
2523 return R;
2524
2525 // First, let's try to interpret `sub a, b` as `add a, (sub 0, b)`,
2526 // and let's try to sink `(sub 0, b)` into `b` itself. But only if this isn't
2527 // a pure negation used by a select that looks like abs/nabs.
2528 bool IsNegation = match(V: Op0, P: m_ZeroInt());
2529 if (!IsNegation || none_of(Range: I.users(), P: match_fn(P: m_c_Select(L: m_Specific(V: Op1),
2530 R: m_Specific(V: &I))))) {
2531 if (Value *NegOp1 = Negator::Negate(LHSIsZero: IsNegation, /* IsNSW */ IsNegation &&
2532 I.hasNoSignedWrap(),
2533 Root: Op1, IC&: *this))
2534 return BinaryOperator::CreateAdd(V1: NegOp1, V2: Op0);
2535 }
2536 if (IsNegation)
2537 return TryToNarrowDeduceFlags(); // Should have been handled in Negator!
2538
2539 // (A*B)-(A*C) -> A*(B-C) etc
2540 if (Value *V = foldUsingDistributiveLaws(I))
2541 return replaceInstUsesWith(I, V);
2542
2543 if (I.getType()->isIntOrIntVectorTy(BitWidth: 1))
2544 return BinaryOperator::CreateXor(V1: Op0, V2: Op1);
2545
2546 // Replace (-1 - A) with (~A).
2547 if (match(V: Op0, P: m_AllOnes()))
2548 return BinaryOperator::CreateNot(Op: Op1);
2549
2550 // (X + -1) - Y --> ~Y + X
2551 Value *X, *Y;
2552 if (match(V: Op0, P: m_OneUse(SubPattern: m_Add(L: m_Value(V&: X), R: m_AllOnes()))))
2553 return BinaryOperator::CreateAdd(V1: Builder.CreateNot(V: Op1), V2: X);
2554
2555 // if (C1 & C2) == C2 then (X & C1) - (X & C2) -> X & (C1 ^ C2)
2556 Constant *C1, *C2;
2557 if (match(V: Op0, P: m_And(L: m_Value(V&: X), R: m_ImmConstant(C&: C1))) &&
2558 match(V: Op1, P: m_And(L: m_Specific(V: X), R: m_ImmConstant(C&: C2)))) {
2559 Value *AndC = ConstantFoldBinaryInstruction(Opcode: Instruction::And, V1: C1, V2: C2);
2560 if (C2->isElementWiseEqual(Y: AndC))
2561 return BinaryOperator::CreateAnd(
2562 V1: X, V2: ConstantFoldBinaryInstruction(Opcode: Instruction::Xor, V1: C1, V2: C2));
2563 }
2564
2565 // Reassociate sub/add sequences to create more add instructions and
2566 // reduce dependency chains:
2567 // ((X - Y) + Z) - Op1 --> (X + Z) - (Y + Op1)
2568 Value *Z;
2569 if (match(V: Op0, P: m_OneUse(SubPattern: m_c_Add(L: m_OneUse(SubPattern: m_Sub(L: m_Value(V&: X), R: m_Value(V&: Y))),
2570 R: m_Value(V&: Z))))) {
2571 Value *XZ = Builder.CreateAdd(LHS: X, RHS: Z);
2572 Value *YW = Builder.CreateAdd(LHS: Y, RHS: Op1);
2573 return BinaryOperator::CreateSub(V1: XZ, V2: YW);
2574 }
2575
2576 // ((X - Y) - Op1) --> X - (Y + Op1)
2577 if (match(V: Op0, P: m_OneUse(SubPattern: m_Sub(L: m_Value(V&: X), R: m_Value(V&: Y))))) {
2578 OverflowingBinaryOperator *LHSSub = cast<OverflowingBinaryOperator>(Val: Op0);
2579 bool HasNUW = I.hasNoUnsignedWrap() && LHSSub->hasNoUnsignedWrap();
2580 bool HasNSW = HasNUW && I.hasNoSignedWrap() && LHSSub->hasNoSignedWrap();
2581 Value *Add = Builder.CreateAdd(LHS: Y, RHS: Op1, Name: "", /*HasNUW=*/HasNUW,
2582 /*HasNSW=*/HasNSW);
2583 BinaryOperator *Sub = BinaryOperator::CreateSub(V1: X, V2: Add);
2584 Sub->setHasNoUnsignedWrap(HasNUW);
2585 Sub->setHasNoSignedWrap(HasNSW);
2586 return Sub;
2587 }
2588
2589 // (X + C0) - (Y + C1) --> (X - Y) + (C0 - C1)
2590 {
2591 Constant *CX, *CY;
2592 if (match(V: Op0, P: m_OneUse(SubPattern: m_Add(L: m_Value(V&: X), R: m_ImmConstant(C&: CX)))) &&
2593 match(V: Op1, P: m_OneUse(SubPattern: m_Add(L: m_Value(V&: Y), R: m_ImmConstant(C&: CY))))) {
2594 Value *OpsSub = Builder.CreateSub(LHS: X, RHS: Y);
2595 Constant *ConstsSub = ConstantExpr::getSub(C1: CX, C2: CY);
2596 return BinaryOperator::CreateAdd(V1: OpsSub, V2: ConstsSub);
2597 }
2598 }
2599
2600 // (X + Z) - (Y + Z) --> (X - Y)
2601 {
2602 Value *W, *Z;
2603 if (match(V: Op0, P: m_AddLike(L: m_Value(V&: W), R: m_Value(V&: X))) &&
2604 match(V: Op1, P: m_AddLike(L: m_Value(V&: Y), R: m_Value(V&: Z)))) {
2605 Instruction *R = nullptr;
2606 if (W == Y)
2607 R = BinaryOperator::CreateSub(V1: X, V2: Z);
2608 else if (W == Z)
2609 R = BinaryOperator::CreateSub(V1: X, V2: Y);
2610 else if (X == Y)
2611 R = BinaryOperator::CreateSub(V1: W, V2: Z);
2612 else if (X == Z)
2613 R = BinaryOperator::CreateSub(V1: W, V2: Y);
2614 if (R) {
2615 bool NSW = I.hasNoSignedWrap() &&
2616 match(V: Op0, P: m_NSWAddLike(L: m_Value(), R: m_Value())) &&
2617 match(V: Op1, P: m_NSWAddLike(L: m_Value(), R: m_Value()));
2618
2619 bool NUW = I.hasNoUnsignedWrap() &&
2620 match(V: Op1, P: m_NUWAddLike(L: m_Value(), R: m_Value()));
2621 R->setHasNoSignedWrap(NSW);
2622 R->setHasNoUnsignedWrap(NUW);
2623 return R;
2624 }
2625 }
2626 }
2627
2628 // (~X) - (~Y) --> Y - X
2629 {
2630 // Need to ensure we can consume at least one of the `not` instructions,
2631 // otherwise this can inf loop.
2632 bool ConsumesOp0, ConsumesOp1;
2633 if (isFreeToInvert(V: Op0, WillInvertAllUses: Op0->hasOneUse(), DoesConsume&: ConsumesOp0) &&
2634 isFreeToInvert(V: Op1, WillInvertAllUses: Op1->hasOneUse(), DoesConsume&: ConsumesOp1) &&
2635 (ConsumesOp0 || ConsumesOp1)) {
2636 Value *NotOp0 = getFreelyInverted(V: Op0, WillInvertAllUses: Op0->hasOneUse(), Builder: &Builder);
2637 Value *NotOp1 = getFreelyInverted(V: Op1, WillInvertAllUses: Op1->hasOneUse(), Builder: &Builder);
2638 assert(NotOp0 != nullptr && NotOp1 != nullptr &&
2639 "isFreeToInvert desynced with getFreelyInverted");
2640 return BinaryOperator::CreateSub(V1: NotOp1, V2: NotOp0);
2641 }
2642 }
2643
2644 auto m_AddRdx = [](Value *&Vec) {
2645 return m_OneUse(SubPattern: m_Intrinsic<Intrinsic::vector_reduce_add>(Ops: m_Value(V&: Vec)));
2646 };
2647 Value *V0, *V1;
2648 if (match(V: Op0, P: m_AddRdx(V0)) && match(V: Op1, P: m_AddRdx(V1)) &&
2649 V0->getType() == V1->getType()) {
2650 // Difference of sums is sum of differences:
2651 // add_rdx(V0) - add_rdx(V1) --> add_rdx(V0 - V1)
2652 Value *Sub = Builder.CreateSub(LHS: V0, RHS: V1);
2653 Value *Rdx = Builder.CreateIntrinsic(ID: Intrinsic::vector_reduce_add,
2654 OverloadTypes: {Sub->getType()}, Args: {Sub});
2655 return replaceInstUsesWith(I, V: Rdx);
2656 }
2657
2658 if (Constant *C = dyn_cast<Constant>(Val: Op0)) {
2659 Value *X;
2660 if (match(V: Op1, P: m_ZExt(Op: m_Value(V&: X))) && X->getType()->isIntOrIntVectorTy(BitWidth: 1)) {
2661 // C - (zext bool) --> bool ? C - 1 : C
2662 SelectInst *SI = SelectInst::Create(C: X, S1: InstCombiner::SubOne(C), S2: C);
2663 // We know nothing about the distribution of the condition, so mark the
2664 // branch weights as unknown.
2665 setExplicitlyUnknownBranchWeightsIfProfiled(I&: *SI, DEBUG_TYPE, F: &F);
2666 return SI;
2667 }
2668 if (match(V: Op1, P: m_SExt(Op: m_Value(V&: X))) && X->getType()->isIntOrIntVectorTy(BitWidth: 1)) {
2669 // C - (sext bool) --> bool ? C + 1 : C
2670 SelectInst *SI = SelectInst::Create(C: X, S1: InstCombiner::AddOne(C), S2: C);
2671 // We know nothing about the distribution of the condition, so mark the
2672 // branch weights as unknown.
2673 setExplicitlyUnknownBranchWeightsIfProfiled(I&: *SI, DEBUG_TYPE, F: &F);
2674 return SI;
2675 }
2676
2677 // C - ~X == X + (1+C)
2678 if (match(V: Op1, P: m_Not(V: m_Value(V&: X))))
2679 return BinaryOperator::CreateAdd(V1: X, V2: InstCombiner::AddOne(C));
2680
2681 // Try to fold constant sub into select arguments.
2682 if (SelectInst *SI = dyn_cast<SelectInst>(Val: Op1))
2683 if (Instruction *R = FoldOpIntoSelect(Op&: I, SI))
2684 return R;
2685
2686 // Try to fold constant sub into PHI values.
2687 if (PHINode *PN = dyn_cast<PHINode>(Val: Op1))
2688 if (Instruction *R = foldOpIntoPhi(I, PN))
2689 return R;
2690
2691 Constant *C2;
2692
2693 // C-(C2-X) --> X+(C-C2)
2694 if (match(V: Op1, P: m_Sub(L: m_ImmConstant(C&: C2), R: m_Value(V&: X))))
2695 return BinaryOperator::CreateAdd(V1: X, V2: ConstantExpr::getSub(C1: C, C2));
2696 }
2697
2698 const APInt *Op0C;
2699 if (match(V: Op0, P: m_APInt(Res&: Op0C))) {
2700 if (Op0C->isMask()) {
2701 // Turn this into a xor if LHS is 2^n-1 and the remaining bits are known
2702 // zero. We don't use information from dominating conditions so this
2703 // transform is easier to reverse if necessary.
2704 KnownBits RHSKnown = llvm::computeKnownBits(
2705 V: Op1, Q: SQ.getWithInstruction(I: &I).getWithoutDomCondCache());
2706 if ((*Op0C | RHSKnown.Zero).isAllOnes())
2707 return BinaryOperator::CreateXor(V1: Op1, V2: Op0);
2708 }
2709
2710 // C - ((C3 -nuw X) & C2) --> (C - (C2 & C3)) + (X & C2) when:
2711 // (C3 - ((C2 & C3) - 1)) is pow2
2712 // ((C2 + C3) & ((C2 & C3) - 1)) == ((C2 & C3) - 1)
2713 // C2 is negative pow2 || sub nuw
2714 const APInt *C2, *C3;
2715 BinaryOperator *InnerSub;
2716 if (match(V: Op1, P: m_OneUse(SubPattern: m_And(L: m_BinOp(I&: InnerSub), R: m_APInt(Res&: C2)))) &&
2717 match(V: InnerSub, P: m_Sub(L: m_APInt(Res&: C3), R: m_Value(V&: X))) &&
2718 (InnerSub->hasNoUnsignedWrap() || C2->isNegatedPowerOf2())) {
2719 APInt C2AndC3 = *C2 & *C3;
2720 APInt C2AndC3Minus1 = C2AndC3 - 1;
2721 APInt C2AddC3 = *C2 + *C3;
2722 if ((*C3 - C2AndC3Minus1).isPowerOf2() &&
2723 C2AndC3Minus1.isSubsetOf(RHS: C2AddC3)) {
2724 Value *And = Builder.CreateAnd(LHS: X, RHS: ConstantInt::get(Ty: I.getType(), V: *C2));
2725 return BinaryOperator::CreateAdd(
2726 V1: And, V2: ConstantInt::get(Ty: I.getType(), V: *Op0C - C2AndC3));
2727 }
2728 }
2729 }
2730
2731 {
2732 Value *Y;
2733 // X-(X+Y) == -Y X-(Y+X) == -Y
2734 if (match(V: Op1, P: m_c_Add(L: m_Specific(V: Op0), R: m_Value(V&: Y))))
2735 return BinaryOperator::CreateNeg(Op: Y);
2736
2737 // (X-Y)-X == -Y
2738 if (match(V: Op0, P: m_Sub(L: m_Specific(V: Op1), R: m_Value(V&: Y))))
2739 return BinaryOperator::CreateNeg(Op: Y);
2740 }
2741
2742 // (sub (or A, B) (and A, B)) --> (xor A, B)
2743 {
2744 Value *A, *B;
2745 if (match(V: Op1, P: m_And(L: m_Value(V&: A), R: m_Value(V&: B))) &&
2746 match(V: Op0, P: m_c_Or(L: m_Specific(V: A), R: m_Specific(V: B))))
2747 return BinaryOperator::CreateXor(V1: A, V2: B);
2748 }
2749
2750 // (sub (add A, B) (or A, B)) --> (and A, B)
2751 {
2752 Value *A, *B;
2753 if (match(V: Op0, P: m_Add(L: m_Value(V&: A), R: m_Value(V&: B))) &&
2754 match(V: Op1, P: m_c_Or(L: m_Specific(V: A), R: m_Specific(V: B))))
2755 return BinaryOperator::CreateAnd(V1: A, V2: B);
2756 }
2757
2758 // (sub (add A, B) (and A, B)) --> (or A, B)
2759 {
2760 Value *A, *B;
2761 if (match(V: Op0, P: m_Add(L: m_Value(V&: A), R: m_Value(V&: B))) &&
2762 match(V: Op1, P: m_c_And(L: m_Specific(V: A), R: m_Specific(V: B))))
2763 return BinaryOperator::CreateOr(V1: A, V2: B);
2764 }
2765
2766 // (sub (and A, B) (or A, B)) --> neg (xor A, B)
2767 {
2768 Value *A, *B;
2769 if (match(V: Op0, P: m_And(L: m_Value(V&: A), R: m_Value(V&: B))) &&
2770 match(V: Op1, P: m_c_Or(L: m_Specific(V: A), R: m_Specific(V: B))) &&
2771 (Op0->hasOneUse() || Op1->hasOneUse()))
2772 return BinaryOperator::CreateNeg(Op: Builder.CreateXor(LHS: A, RHS: B));
2773 }
2774
2775 // (sub (or A, B), (xor A, B)) --> (and A, B)
2776 {
2777 Value *A, *B;
2778 if (match(V: Op1, P: m_Xor(L: m_Value(V&: A), R: m_Value(V&: B))) &&
2779 match(V: Op0, P: m_c_Or(L: m_Specific(V: A), R: m_Specific(V: B))))
2780 return BinaryOperator::CreateAnd(V1: A, V2: B);
2781 }
2782
2783 // (sub (xor A, B) (or A, B)) --> neg (and A, B)
2784 {
2785 Value *A, *B;
2786 if (match(V: Op0, P: m_Xor(L: m_Value(V&: A), R: m_Value(V&: B))) &&
2787 match(V: Op1, P: m_c_Or(L: m_Specific(V: A), R: m_Specific(V: B))) &&
2788 (Op0->hasOneUse() || Op1->hasOneUse()))
2789 return BinaryOperator::CreateNeg(Op: Builder.CreateAnd(LHS: A, RHS: B));
2790 }
2791
2792 {
2793 Value *Y;
2794 // ((X | Y) - X) --> (~X & Y)
2795 if (match(V: Op0, P: m_OneUse(SubPattern: m_c_Or(L: m_Value(V&: Y), R: m_Specific(V: Op1)))))
2796 return BinaryOperator::CreateAnd(
2797 V1: Y, V2: Builder.CreateNot(V: Op1, Name: Op1->getName() + ".not"));
2798 }
2799
2800 {
2801 // (sub (and Op1, (neg X)), Op1) --> neg (and Op1, (add X, -1))
2802 Value *X;
2803 if (match(V: Op0, P: m_OneUse(SubPattern: m_c_And(L: m_Specific(V: Op1),
2804 R: m_OneUse(SubPattern: m_Neg(V: m_Value(V&: X))))))) {
2805 return BinaryOperator::CreateNeg(Op: Builder.CreateAnd(
2806 LHS: Op1, RHS: Builder.CreateAdd(LHS: X, RHS: Constant::getAllOnesValue(Ty: I.getType()))));
2807 }
2808 }
2809
2810 {
2811 // (sub (and Op1, C), Op1) --> neg (and Op1, ~C)
2812 Constant *C;
2813 if (match(V: Op0, P: m_OneUse(SubPattern: m_And(L: m_Specific(V: Op1), R: m_Constant(C))))) {
2814 return BinaryOperator::CreateNeg(
2815 Op: Builder.CreateAnd(LHS: Op1, RHS: Builder.CreateNot(V: C)));
2816 }
2817 }
2818
2819 {
2820 // (sub (xor X, (sext C)), (sext C)) => (select C, (neg X), X)
2821 // (sub (sext C), (xor X, (sext C))) => (select C, X, (neg X))
2822 Value *C, *X;
2823 auto m_SubXorCmp = [&C, &X](Value *LHS, Value *RHS) {
2824 return match(V: LHS, P: m_OneUse(SubPattern: m_c_Xor(L: m_Value(V&: X), R: m_Specific(V: RHS)))) &&
2825 match(V: RHS, P: m_SExt(Op: m_Value(V&: C))) &&
2826 (C->getType()->getScalarSizeInBits() == 1);
2827 };
2828 if (m_SubXorCmp(Op0, Op1))
2829 return createSelectInstWithUnknownProfile(C, S1: Builder.CreateNeg(V: X), S2: X);
2830 if (m_SubXorCmp(Op1, Op0))
2831 return createSelectInstWithUnknownProfile(C, S1: X, S2: Builder.CreateNeg(V: X));
2832 }
2833
2834 if (Instruction *R = tryFoldInstWithCtpopWithNot(I: &I))
2835 return R;
2836
2837 if (Instruction *R = foldSubOfMinMax(I, Builder))
2838 return R;
2839
2840 {
2841 // If we have a subtraction between some value and a select between
2842 // said value and something else, sink subtraction into select hands, i.e.:
2843 // sub (select %Cond, %TrueVal, %FalseVal), %Op1
2844 // ->
2845 // select %Cond, (sub %TrueVal, %Op1), (sub %FalseVal, %Op1)
2846 // or
2847 // sub %Op0, (select %Cond, %TrueVal, %FalseVal)
2848 // ->
2849 // select %Cond, (sub %Op0, %TrueVal), (sub %Op0, %FalseVal)
2850 // This will result in select between new subtraction and 0.
2851 auto SinkSubIntoSelect =
2852 [Ty = I.getType()](Value *Select, Value *OtherHandOfSub,
2853 auto SubBuilder) -> Instruction * {
2854 Value *Cond, *TrueVal, *FalseVal;
2855 if (!match(V: Select, P: m_OneUse(SubPattern: m_Select(C: m_Value(V&: Cond), L: m_Value(V&: TrueVal),
2856 R: m_Value(V&: FalseVal)))))
2857 return nullptr;
2858 if (OtherHandOfSub != TrueVal && OtherHandOfSub != FalseVal)
2859 return nullptr;
2860 // While it is really tempting to just create two subtractions and let
2861 // InstCombine fold one of those to 0, it isn't possible to do so
2862 // because of worklist visitation order. So ugly it is.
2863 bool OtherHandOfSubIsTrueVal = OtherHandOfSub == TrueVal;
2864 Value *NewSub = SubBuilder(OtherHandOfSubIsTrueVal ? FalseVal : TrueVal);
2865 Constant *Zero = Constant::getNullValue(Ty);
2866 SelectInst *NewSel =
2867 SelectInst::Create(C: Cond, S1: OtherHandOfSubIsTrueVal ? Zero : NewSub,
2868 S2: OtherHandOfSubIsTrueVal ? NewSub : Zero);
2869 // Preserve prof metadata if any.
2870 NewSel->copyMetadata(SrcInst: cast<Instruction>(Val&: *Select));
2871 return NewSel;
2872 };
2873 if (Instruction *NewSel = SinkSubIntoSelect(
2874 /*Select=*/Op0, /*OtherHandOfSub=*/Op1,
2875 [Builder = &Builder, Op1](Value *OtherHandOfSelect) {
2876 return Builder->CreateSub(LHS: OtherHandOfSelect,
2877 /*OtherHandOfSub=*/RHS: Op1);
2878 }))
2879 return NewSel;
2880 if (Instruction *NewSel = SinkSubIntoSelect(
2881 /*Select=*/Op1, /*OtherHandOfSub=*/Op0,
2882 [Builder = &Builder, Op0](Value *OtherHandOfSelect) {
2883 return Builder->CreateSub(/*OtherHandOfSub=*/LHS: Op0,
2884 RHS: OtherHandOfSelect);
2885 }))
2886 return NewSel;
2887 }
2888
2889 // (X - (X & Y)) --> (X & ~Y)
2890 if (match(V: Op1, P: m_c_And(L: m_Specific(V: Op0), R: m_Value(V&: Y))) &&
2891 (Op1->hasOneUse() || isa<Constant>(Val: Y)))
2892 return BinaryOperator::CreateAnd(
2893 V1: Op0, V2: Builder.CreateNot(V: Y, Name: Y->getName() + ".not"));
2894
2895 // ~X - Min/Max(~X, Y) -> ~Min/Max(X, ~Y) - X
2896 // ~X - Min/Max(Y, ~X) -> ~Min/Max(X, ~Y) - X
2897 // Min/Max(~X, Y) - ~X -> X - ~Min/Max(X, ~Y)
2898 // Min/Max(Y, ~X) - ~X -> X - ~Min/Max(X, ~Y)
2899 // As long as Y is freely invertible, this will be neutral or a win.
2900 // Note: We don't generate the inverse max/min, just create the 'not' of
2901 // it and let other folds do the rest.
2902 if (match(V: Op0, P: m_Not(V: m_Value(V&: X))) &&
2903 match(V: Op1, P: m_c_MaxOrMin(L: m_Specific(V: Op0), R: m_Value(V&: Y))) &&
2904 !Op0->hasNUsesOrMore(N: 3) && isFreeToInvert(V: Y, WillInvertAllUses: Y->hasOneUse())) {
2905 Value *Not = Builder.CreateNot(V: Op1);
2906 return BinaryOperator::CreateSub(V1: Not, V2: X);
2907 }
2908 if (match(V: Op1, P: m_Not(V: m_Value(V&: X))) &&
2909 match(V: Op0, P: m_c_MaxOrMin(L: m_Specific(V: Op1), R: m_Value(V&: Y))) &&
2910 !Op1->hasNUsesOrMore(N: 3) && isFreeToInvert(V: Y, WillInvertAllUses: Y->hasOneUse())) {
2911 Value *Not = Builder.CreateNot(V: Op0);
2912 return BinaryOperator::CreateSub(V1: X, V2: Not);
2913 }
2914
2915 // min(X+1, Y) - min(X, Y) --> zext X < Y
2916 // Replacing a sub and at least one min with an icmp
2917 // and a zext is a potential improvement.
2918 if (match(V: Op0, P: m_c_SMin(L: m_NSWAddLike(L: m_Value(V&: X), R: m_One()), R: m_Value(V&: Y))) &&
2919 match(V: Op1, P: m_c_SMin(L: m_Specific(V: X), R: m_Specific(V: Y))) &&
2920 I.getType()->getScalarSizeInBits() != 1 &&
2921 (Op0->hasOneUse() || Op1->hasOneUse())) {
2922 Value *Cond = Builder.CreateICmpSLT(LHS: X, RHS: Y);
2923 return new ZExtInst(Cond, I.getType());
2924 }
2925 if (match(V: Op0, P: m_c_UMin(L: m_NUWAddLike(L: m_Value(V&: X), R: m_One()), R: m_Value(V&: Y))) &&
2926 match(V: Op1, P: m_c_UMin(L: m_Specific(V: X), R: m_Specific(V: Y))) &&
2927 I.getType()->getScalarSizeInBits() != 1 &&
2928 (Op0->hasOneUse() || Op1->hasOneUse())) {
2929 Value *Cond = Builder.CreateICmpULT(LHS: X, RHS: Y);
2930 return new ZExtInst(Cond, I.getType());
2931 }
2932
2933 // Optimize pointer differences into the same array into a size. Consider:
2934 // &A[10] - &A[0]: we should compile this to "10".
2935 Value *LHSOp, *RHSOp;
2936 if (match(V: Op0, P: m_PtrToIntOrAddr(Op: m_Value(V&: LHSOp))) &&
2937 match(V: Op1, P: m_PtrToIntOrAddr(Op: m_Value(V&: RHSOp))))
2938 if (Value *Res = OptimizePointerDifference(LHS: LHSOp, RHS: RHSOp, Ty: I.getType(),
2939 IsNUW: I.hasNoUnsignedWrap()))
2940 return replaceInstUsesWith(I, V: Res);
2941
2942 // trunc(p)-trunc(q) -> trunc(p-q)
2943 if (match(V: Op0, P: m_Trunc(Op: m_PtrToIntOrAddr(Op: m_Value(V&: LHSOp)))) &&
2944 match(V: Op1, P: m_Trunc(Op: m_PtrToIntOrAddr(Op: m_Value(V&: RHSOp)))))
2945 if (Value *Res = OptimizePointerDifference(LHS: LHSOp, RHS: RHSOp, Ty: I.getType(),
2946 /* IsNUW */ false))
2947 return replaceInstUsesWith(I, V: Res);
2948
2949 auto MatchSubOfZExtOfPtrToIntOrAddr = [&]() {
2950 if (match(V: Op0, P: m_ZExt(Op: m_PtrToIntSameSize(DL, Op: m_Value(V&: LHSOp)))) &&
2951 match(V: Op1, P: m_ZExt(Op: m_PtrToIntSameSize(DL, Op: m_Value(V&: RHSOp)))))
2952 return true;
2953 if (match(V: Op0, P: m_ZExt(Op: m_PtrToAddr(Op: m_Value(V&: LHSOp)))) &&
2954 match(V: Op1, P: m_ZExt(Op: m_PtrToAddr(Op: m_Value(V&: RHSOp)))))
2955 return true;
2956 // Special case for non-canonical ptrtoint in constant expression,
2957 // where the zext has been folded into the ptrtoint.
2958 if (match(V: Op0, P: m_ZExt(Op: m_PtrToIntSameSize(DL, Op: m_Value(V&: LHSOp)))) &&
2959 match(V: Op1, P: m_PtrToInt(Op: m_Value(V&: RHSOp))))
2960 return true;
2961 return false;
2962 };
2963 if (MatchSubOfZExtOfPtrToIntOrAddr()) {
2964 if (auto *GEP = dyn_cast<GEPOperator>(Val: LHSOp)) {
2965 if (GEP->getPointerOperand() == RHSOp) {
2966 if (GEP->hasNoUnsignedWrap() || GEP->hasNoUnsignedSignedWrap()) {
2967 Value *Offset = EmitGEPOffset(GEP);
2968 Value *Res = GEP->hasNoUnsignedWrap()
2969 ? Builder.CreateZExt(
2970 V: Offset, DestTy: I.getType(), Name: "",
2971 /*IsNonNeg=*/GEP->hasNoUnsignedSignedWrap())
2972 : Builder.CreateSExt(V: Offset, DestTy: I.getType());
2973 return replaceInstUsesWith(I, V: Res);
2974 }
2975 }
2976 }
2977 }
2978
2979 // Canonicalize a shifty way to code absolute value to the common pattern.
2980 // There are 2 potential commuted variants.
2981 // We're relying on the fact that we only do this transform when the shift has
2982 // exactly 2 uses and the xor has exactly 1 use (otherwise, we might increase
2983 // instructions).
2984 Value *A;
2985 const APInt *ShAmt;
2986 Type *Ty = I.getType();
2987 unsigned BitWidth = Ty->getScalarSizeInBits();
2988 if (match(V: Op1, P: m_AShr(L: m_Value(V&: A), R: m_APInt(Res&: ShAmt))) &&
2989 Op1->hasNUses(N: 2) && *ShAmt == BitWidth - 1 &&
2990 match(V: Op0, P: m_OneUse(SubPattern: m_c_Xor(L: m_Specific(V: A), R: m_Specific(V: Op1))))) {
2991 // B = ashr i32 A, 31 ; smear the sign bit
2992 // sub (xor A, B), B ; flip bits if negative and subtract -1 (add 1)
2993 // --> (A < 0) ? -A : A
2994 Value *IsNeg = Builder.CreateIsNeg(Arg: A);
2995 // Copy the nsw flags from the sub to the negate.
2996 Value *NegA = I.hasNoUnsignedWrap()
2997 ? Constant::getNullValue(Ty: A->getType())
2998 : Builder.CreateNeg(V: A, Name: "", HasNSW: I.hasNoSignedWrap());
2999 return SelectInst::Create(C: IsNeg, S1: NegA, S2: A);
3000 }
3001
3002 // If we are subtracting a low-bit masked subset of some value from an add
3003 // of that same value with no low bits changed, that is clearing some low bits
3004 // of the sum:
3005 // sub (X + AddC), (X & AndC) --> and (X + AddC), ~AndC
3006 const APInt *AddC, *AndC;
3007 if (match(V: Op0, P: m_Add(L: m_Value(V&: X), R: m_APInt(Res&: AddC))) &&
3008 match(V: Op1, P: m_And(L: m_Specific(V: X), R: m_APInt(Res&: AndC)))) {
3009 unsigned Cttz = AddC->countr_zero();
3010 APInt HighMask(APInt::getHighBitsSet(numBits: BitWidth, hiBitsSet: BitWidth - Cttz));
3011 if ((HighMask & *AndC).isZero())
3012 return BinaryOperator::CreateAnd(V1: Op0, V2: ConstantInt::get(Ty, V: ~(*AndC)));
3013 }
3014
3015 if (Instruction *V =
3016 canonicalizeCondSignextOfHighBitExtractToSignextHighBitExtract(I))
3017 return V;
3018
3019 // X - usub.sat(X, Y) => umin(X, Y)
3020 if (match(V: Op1, P: m_OneUse(SubPattern: m_Intrinsic<Intrinsic::usub_sat>(Ops: m_Specific(V: Op0),
3021 Ops: m_Value(V&: Y)))))
3022 return replaceInstUsesWith(
3023 I, V: Builder.CreateIntrinsic(ID: Intrinsic::umin, OverloadTypes: {I.getType()}, Args: {Op0, Y}));
3024
3025 // umax(X, Op1) - Op1 --> usub.sat(X, Op1)
3026 // TODO: The one-use restriction is not strictly necessary, but it may
3027 // require improving other pattern matching and/or codegen.
3028 if (match(V: Op0, P: m_OneUse(SubPattern: m_c_UMax(L: m_Value(V&: X), R: m_Specific(V: Op1)))))
3029 return replaceInstUsesWith(
3030 I, V: Builder.CreateIntrinsic(ID: Intrinsic::usub_sat, OverloadTypes: {Ty}, Args: {X, Op1}));
3031
3032 // Op0 - umin(X, Op0) --> usub.sat(Op0, X)
3033 if (match(V: Op1, P: m_OneUse(SubPattern: m_c_UMin(L: m_Value(V&: X), R: m_Specific(V: Op0)))))
3034 return replaceInstUsesWith(
3035 I, V: Builder.CreateIntrinsic(ID: Intrinsic::usub_sat, OverloadTypes: {Ty}, Args: {Op0, X}));
3036
3037 // Op0 - umax(X, Op0) --> 0 - usub.sat(X, Op0)
3038 if (match(V: Op1, P: m_OneUse(SubPattern: m_c_UMax(L: m_Value(V&: X), R: m_Specific(V: Op0))))) {
3039 Value *USub = Builder.CreateIntrinsic(ID: Intrinsic::usub_sat, OverloadTypes: {Ty}, Args: {X, Op0});
3040 return BinaryOperator::CreateNeg(Op: USub);
3041 }
3042
3043 // umin(X, Op1) - Op1 --> 0 - usub.sat(Op1, X)
3044 if (match(V: Op0, P: m_OneUse(SubPattern: m_c_UMin(L: m_Value(V&: X), R: m_Specific(V: Op1))))) {
3045 Value *USub = Builder.CreateIntrinsic(ID: Intrinsic::usub_sat, OverloadTypes: {Ty}, Args: {Op1, X});
3046 return BinaryOperator::CreateNeg(Op: USub);
3047 }
3048
3049 // C - ctpop(X) => ctpop(~X) if C is bitwidth
3050 if (match(V: Op0, P: m_SpecificInt(V: BitWidth)) &&
3051 match(V: Op1, P: m_OneUse(SubPattern: m_Ctpop(Op0: m_Value(V&: X)))))
3052 return replaceInstUsesWith(
3053 I, V: Builder.CreateIntrinsic(ID: Intrinsic::ctpop, OverloadTypes: {I.getType()},
3054 Args: {Builder.CreateNot(V: X)}));
3055
3056 // Reduce multiplies for difference-of-squares by factoring:
3057 // (X * X) - (Y * Y) --> (X + Y) * (X - Y)
3058 if (match(V: Op0, P: m_OneUse(SubPattern: m_Mul(L: m_Value(V&: X), R: m_Deferred(V: X)))) &&
3059 match(V: Op1, P: m_OneUse(SubPattern: m_Mul(L: m_Value(V&: Y), R: m_Deferred(V: Y))))) {
3060 auto *OBO0 = cast<OverflowingBinaryOperator>(Val: Op0);
3061 auto *OBO1 = cast<OverflowingBinaryOperator>(Val: Op1);
3062 bool PropagateNSW = I.hasNoSignedWrap() && OBO0->hasNoSignedWrap() &&
3063 OBO1->hasNoSignedWrap() && BitWidth > 2;
3064 bool PropagateNUW = I.hasNoUnsignedWrap() && OBO0->hasNoUnsignedWrap() &&
3065 OBO1->hasNoUnsignedWrap() && BitWidth > 1;
3066 Value *Add = Builder.CreateAdd(LHS: X, RHS: Y, Name: "add", HasNUW: PropagateNUW, HasNSW: PropagateNSW);
3067 Value *Sub = Builder.CreateSub(LHS: X, RHS: Y, Name: "sub", HasNUW: PropagateNUW, HasNSW: PropagateNSW);
3068 Value *Mul = Builder.CreateMul(LHS: Add, RHS: Sub, Name: "", HasNUW: PropagateNUW, HasNSW: PropagateNSW);
3069 return replaceInstUsesWith(I, V: Mul);
3070 }
3071
3072 // max(X,Y) nsw/nuw - min(X,Y) --> abs(X nsw - Y)
3073 if (match(V: Op0, P: m_OneUse(SubPattern: m_c_SMax(L: m_Value(V&: X), R: m_Value(V&: Y)))) &&
3074 match(V: Op1, P: m_OneUse(SubPattern: m_c_SMin(L: m_Specific(V: X), R: m_Specific(V: Y))))) {
3075 if (I.hasNoUnsignedWrap() || I.hasNoSignedWrap()) {
3076 Value *Sub =
3077 Builder.CreateSub(LHS: X, RHS: Y, Name: "sub", /*HasNUW=*/false, /*HasNSW=*/true);
3078 Value *Call =
3079 Builder.CreateBinaryIntrinsic(ID: Intrinsic::abs, LHS: Sub, RHS: Builder.getTrue());
3080 return replaceInstUsesWith(I, V: Call);
3081 }
3082 }
3083
3084 if (Instruction *Res = foldBinOpOfSelectAndCastOfSelectCondition(I))
3085 return Res;
3086
3087 // (sub (sext (add nsw (X, Y)), sext (X))) --> (sext (Y))
3088 if (match(V: Op1, P: m_SExtLike(Op: m_Value(V&: X))) &&
3089 match(V: Op0, P: m_SExtLike(Op: m_c_NSWAdd(L: m_Specific(V: X), R: m_Value(V&: Y))))) {
3090 Value *SExtY = Builder.CreateSExt(V: Y, DestTy: I.getType());
3091 return replaceInstUsesWith(I, V: SExtY);
3092 }
3093
3094 // (sub[ nsw] (sext (add nsw (X, Y)), sext (add nsw (X, Z)))) -->
3095 // --> (sub[ nsw] (sext (Y), sext (Z)))
3096 {
3097 Value *Z, *Add0, *Add1;
3098 if (match(V: Op0, P: m_SExtLike(Op: m_Value(V&: Add0))) &&
3099 match(V: Op1, P: m_SExtLike(Op: m_Value(V&: Add1))) &&
3100 ((match(V: Add0, P: m_NSWAdd(L: m_Value(V&: X), R: m_Value(V&: Y))) &&
3101 match(V: Add1, P: m_c_NSWAdd(L: m_Specific(V: X), R: m_Value(V&: Z)))) ||
3102 (match(V: Add0, P: m_NSWAdd(L: m_Value(V&: Y), R: m_Value(V&: X))) &&
3103 match(V: Add1, P: m_c_NSWAdd(L: m_Specific(V: X), R: m_Value(V&: Z)))))) {
3104 unsigned NumOfNewInstrs = 0;
3105 // Non-constant Y, Z require new SExt.
3106 NumOfNewInstrs += !isa<Constant>(Val: Y) ? 1 : 0;
3107 NumOfNewInstrs += !isa<Constant>(Val: Z) ? 1 : 0;
3108 // Check if we can trade some of the old instructions for the new ones.
3109 unsigned NumOfDeadInstrs = 0;
3110 if (Op0->hasOneUse()) {
3111 // If Op0 (sext) has multiple uses, then we keep it
3112 // and the add that it uses, otherwise, we can remove
3113 // the sext and probably the add (depending on the number of its uses).
3114 ++NumOfDeadInstrs;
3115 NumOfDeadInstrs += Add0->hasOneUse() ? 1 : 0;
3116 }
3117 if (Op1->hasOneUse()) {
3118 ++NumOfDeadInstrs;
3119 NumOfDeadInstrs += Add1->hasOneUse() ? 1 : 0;
3120 }
3121 if (NumOfDeadInstrs >= NumOfNewInstrs) {
3122 Value *SExtY = Builder.CreateSExt(V: Y, DestTy: I.getType());
3123 Value *SExtZ = Builder.CreateSExt(V: Z, DestTy: I.getType());
3124 Value *Sub = Builder.CreateSub(LHS: SExtY, RHS: SExtZ, Name: "",
3125 /*HasNUW=*/false,
3126 /*HasNSW=*/I.hasNoSignedWrap());
3127 return replaceInstUsesWith(I, V: Sub);
3128 }
3129 }
3130 }
3131
3132 // ((X + C) & ~C) - X -> X & C where C is a power of 2.
3133 if (match(V: Op0,
3134 P: m_And(L: m_Add(L: m_Specific(V: Op1), R: m_Power2(V&: AddC)), R: m_APInt(Res&: AndC))) &&
3135 *AddC == ~*AndC) {
3136 return BinaryOperator::CreateAnd(V1: Op1, V2: ConstantInt::get(Ty, V: *AddC));
3137 }
3138
3139 return TryToNarrowDeduceFlags();
3140}
3141
3142/// This eliminates floating-point negation in either 'fneg(X)' or
3143/// 'fsub(-0.0, X)' form by combining into a constant operand.
3144static Instruction *foldFNegIntoConstant(Instruction &I, const DataLayout &DL) {
3145 // This is limited with one-use because fneg is assumed better for
3146 // reassociation and cheaper in codegen than fmul/fdiv.
3147 // TODO: Should the m_OneUse restriction be removed?
3148 Instruction *FNegOp;
3149 // TODO: Confirm whether m_FNegOrFSubNegZero is correct.
3150 if (!match(V: &I, P: m_FNegOrFSubNegZero(X: m_OneUse(SubPattern: m_Instruction(I&: FNegOp)))))
3151 return nullptr;
3152
3153 Value *X;
3154 Constant *C;
3155
3156 // Fold negation into constant operand.
3157 // -(X * C) --> X * (-C)
3158 if (match(V: FNegOp, P: m_FMul(L: m_Value(V&: X), R: m_Constant(C))))
3159 if (Constant *NegC = ConstantFoldUnaryOpOperand(Opcode: Instruction::FNeg, Op: C, DL)) {
3160 FastMathFlags FNegF = I.getFastMathFlags();
3161 FastMathFlags OpF = FNegOp->getFastMathFlags();
3162 FastMathFlags FMF = FastMathFlags::unionValue(LHS: FNegF, RHS: OpF) |
3163 FastMathFlags::intersectRewrite(LHS: FNegF, RHS: OpF);
3164 FMF.setNoInfs(FNegF.noInfs() && OpF.noInfs());
3165 return BinaryOperator::CreateFMulFMF(V1: X, V2: NegC, FMF);
3166 }
3167 // -(X / C) --> X / (-C)
3168 if (match(V: FNegOp, P: m_FDiv(L: m_Value(V&: X), R: m_Constant(C)))) {
3169 if (Constant *NegC = ConstantFoldUnaryOpOperand(Opcode: Instruction::FNeg, Op: C, DL)) {
3170 Instruction *FDiv = BinaryOperator::CreateFDivFMF(V1: X, V2: NegC, FMFSource: &I);
3171
3172 // Intersect 'nsz' and 'ninf' because those special value exceptions may
3173 // not apply to the fdiv. Everything else propagates from the fneg.
3174 FastMathFlags FMF = I.getFastMathFlags();
3175 FastMathFlags OpFMF = FNegOp->getFastMathFlags();
3176 FDiv->setHasNoSignedZeros(FMF.noSignedZeros() && OpFMF.noSignedZeros());
3177 FDiv->setHasNoInfs(FMF.noInfs() && OpFMF.noInfs());
3178 FDiv->copyMetadata(SrcInst: *FNegOp);
3179 return FDiv;
3180 }
3181 }
3182 // -(C / X) --> (-C) / X
3183 if (match(V: FNegOp, P: m_FDiv(L: m_Constant(C), R: m_Value(V&: X))))
3184 if (Constant *NegC = ConstantFoldUnaryOpOperand(Opcode: Instruction::FNeg, Op: C, DL)) {
3185 Instruction *FDiv = BinaryOperator::CreateFDivFMF(V1: NegC, V2: X, FMFSource: &I);
3186
3187 // Intersect 'nsz' and 'ninf' because those special value exceptions may
3188 // not apply to the fdiv. Everything else propagates from the fneg.
3189 // TODO: We could propagate nsz/ninf from fdiv alone?
3190 FastMathFlags FMF = I.getFastMathFlags();
3191 FastMathFlags OpFMF = FNegOp->getFastMathFlags();
3192 FDiv->setHasNoSignedZeros(FMF.noSignedZeros() && OpFMF.noSignedZeros());
3193 FDiv->setHasNoInfs(FMF.noInfs() && OpFMF.noInfs());
3194 FDiv->copyMetadata(SrcInst: *FNegOp);
3195 return FDiv;
3196 }
3197 // With NSZ [ counter-example with -0.0: -(-0.0 + 0.0) != 0.0 + -0.0 ]:
3198 // -(X + C) --> -X + -C --> -C - X
3199 if (I.hasNoSignedZeros() && match(V: FNegOp, P: m_FAdd(L: m_Value(V&: X), R: m_Constant(C))))
3200 if (Constant *NegC = ConstantFoldUnaryOpOperand(Opcode: Instruction::FNeg, Op: C, DL))
3201 return BinaryOperator::CreateFSubFMF(V1: NegC, V2: X, FMFSource: &I);
3202
3203 return nullptr;
3204}
3205
3206Instruction *InstCombinerImpl::hoistFNegAboveFMulFDiv(Value *FNegOp,
3207 Instruction &FMFSource) {
3208 Value *X, *Y;
3209 if (match(V: FNegOp, P: m_FMul(L: m_Value(V&: X), R: m_Value(V&: Y)))) {
3210 // Push into RHS which is more likely to simplify (const or another fneg).
3211 // FIXME: It would be better to invert the transform.
3212 return cast<Instruction>(Val: Builder.CreateFMulFMF(
3213 L: X, R: Builder.CreateFNegFMF(V: Y, FMFSource: &FMFSource), FMFSource: &FMFSource));
3214 }
3215
3216 if (match(V: FNegOp, P: m_FDiv(L: m_Value(V&: X), R: m_Value(V&: Y)))) {
3217 auto *FDiv = cast<Instruction>(Val: Builder.CreateFDivFMF(
3218 L: Builder.CreateFNegFMF(V: X, FMFSource: &FMFSource), R: Y, FMFSource: &FMFSource));
3219 FDiv->copyMetadata(SrcInst: *cast<Instruction>(Val: FNegOp));
3220 return FDiv;
3221 }
3222
3223 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Val: FNegOp)) {
3224 // Make sure to preserve flags and metadata on the call.
3225 if (II->getIntrinsicID() == Intrinsic::ldexp) {
3226 FastMathFlags FMF = FMFSource.getFastMathFlags() | II->getFastMathFlags();
3227 CallInst *New =
3228 Builder.CreateCall(Callee: II->getCalledFunction(),
3229 Args: {Builder.CreateFNegFMF(V: II->getArgOperand(i: 0), FMFSource: FMF),
3230 II->getArgOperand(i: 1)});
3231 New->setFastMathFlags(FMF);
3232 New->copyMetadata(SrcInst: *II);
3233 return New;
3234 }
3235 }
3236
3237 return nullptr;
3238}
3239
3240Instruction *InstCombinerImpl::visitFNeg(UnaryOperator &I) {
3241 Value *Op = I.getOperand(i_nocapture: 0);
3242
3243 if (Value *V = simplifyFNegInst(Op, FMF: I.getFastMathFlags(),
3244 Q: getSimplifyQuery().getWithInstruction(I: &I)))
3245 return replaceInstUsesWith(I, V);
3246
3247 if (Instruction *X = foldFNegIntoConstant(I, DL))
3248 return X;
3249
3250 Value *X, *Y;
3251
3252 // If we can ignore the sign of zeros: -(X - Y) --> (Y - X)
3253 if (I.hasNoSignedZeros() &&
3254 match(V: Op, P: m_OneUse(SubPattern: m_FSub(L: m_Value(V&: X), R: m_Value(V&: Y)))))
3255 return BinaryOperator::CreateFSubFMF(V1: Y, V2: X, FMFSource: &I);
3256
3257 Value *OneUse;
3258 if (!match(V: Op, P: m_OneUse(SubPattern: m_Value(V&: OneUse))))
3259 return nullptr;
3260
3261 if (Instruction *R = hoistFNegAboveFMulFDiv(FNegOp: OneUse, FMFSource&: I))
3262 return replaceInstUsesWith(I, V: R);
3263
3264 // Try to eliminate fneg if at least 1 arm of the select is negated.
3265 Value *Cond;
3266 if (match(V: OneUse, P: m_Select(C: m_Value(V&: Cond), L: m_Value(V&: X), R: m_Value(V&: Y)))) {
3267 // Unlike most transforms, this one is not safe to propagate nsz unless
3268 // it is present on the original select. We union the flags from the select
3269 // and fneg and then remove nsz if needed.
3270 auto propagateSelectFMF = [&](SelectInst *S, bool CommonOperand) {
3271 S->copyFastMathFlags(I: &I);
3272 if (auto *OldSel = dyn_cast<SelectInst>(Val: Op)) {
3273 FastMathFlags FMF = I.getFastMathFlags() | OldSel->getFastMathFlags();
3274 S->setFastMathFlags(FMF);
3275 if (!OldSel->hasNoSignedZeros() && !CommonOperand &&
3276 !isGuaranteedNotToBeUndefOrPoison(V: OldSel->getCondition()))
3277 S->setHasNoSignedZeros(false);
3278 }
3279 };
3280 // -(Cond ? -P : Y) --> Cond ? P : -Y
3281 Value *P;
3282 // TODO: Confirm whether m_FNegOrFSubNegZero is correct.
3283 if (match(V: X, P: m_FNegOrFSubNegZero(X: m_Value(V&: P)))) {
3284 Value *NegY = Builder.CreateFNegFMF(V: Y, FMFSource: &I, Name: Y->getName() + ".neg");
3285 SelectInst *NewSel = SelectInst::Create(
3286 C: Cond, S1: P, S2: NegY, NameStr: "", InsertBefore: nullptr,
3287 MDFrom: ProfcheckDisableMetadataFixes ? nullptr : cast<SelectInst>(Val: Op));
3288 propagateSelectFMF(NewSel, P == Y);
3289 return NewSel;
3290 }
3291 // -(Cond ? X : -P) --> Cond ? -X : P
3292 // TODO: Confirm whether m_FNegOrFSubNegZero is correct.
3293 if (match(V: Y, P: m_FNegOrFSubNegZero(X: m_Value(V&: P)))) {
3294 Value *NegX = Builder.CreateFNegFMF(V: X, FMFSource: &I, Name: X->getName() + ".neg");
3295 SelectInst *NewSel = SelectInst::Create(
3296 C: Cond, S1: NegX, S2: P, NameStr: "", InsertBefore: nullptr,
3297 MDFrom: ProfcheckDisableMetadataFixes ? nullptr : cast<SelectInst>(Val: Op));
3298 propagateSelectFMF(NewSel, P == X);
3299 return NewSel;
3300 }
3301
3302 // -(Cond ? X : C) --> Cond ? -X : -C
3303 // -(Cond ? C : Y) --> Cond ? -C : -Y
3304 if (match(V: X, P: m_ImmConstant()) || match(V: Y, P: m_ImmConstant())) {
3305 Value *NegX = Builder.CreateFNegFMF(V: X, FMFSource: &I, Name: X->getName() + ".neg");
3306 Value *NegY = Builder.CreateFNegFMF(V: Y, FMFSource: &I, Name: Y->getName() + ".neg");
3307 SelectInst *NewSel = SelectInst::Create(
3308 C: Cond, S1: NegX, S2: NegY, NameStr: "", InsertBefore: nullptr,
3309 MDFrom: ProfcheckDisableMetadataFixes ? nullptr : cast<SelectInst>(Val: Op));
3310 propagateSelectFMF(NewSel, /*CommonOperand=*/true);
3311 return NewSel;
3312 }
3313 }
3314
3315 // fneg (copysign x, y) -> copysign x, (fneg y)
3316 if (match(V: OneUse, P: m_CopySign(Op0: m_Value(V&: X), Op1: m_Value(V&: Y)))) {
3317 // The source copysign has an additional value input, so we can't propagate
3318 // flags the copysign doesn't also have.
3319 FastMathFlags FMF = I.getFastMathFlags();
3320 FMF &= cast<FPMathOperator>(Val: OneUse)->getFastMathFlags();
3321 Value *NegY = Builder.CreateFNegFMF(V: Y, FMFSource: FMF);
3322 Value *NewCopySign = Builder.CreateCopySign(LHS: X, RHS: NegY, FMFSource: FMF);
3323 return replaceInstUsesWith(I, V: NewCopySign);
3324 }
3325
3326 // fneg (shuffle x, Mask) --> shuffle (fneg x), Mask
3327 ArrayRef<int> Mask;
3328 if (match(V: OneUse, P: m_Shuffle(v1: m_Value(V&: X), v2: m_Poison(), mask: m_Mask(Mask))))
3329 return new ShuffleVectorInst(Builder.CreateFNegFMF(V: X, FMFSource: &I), Mask);
3330
3331 // fneg (reverse x) --> reverse (fneg x)
3332 if (match(V: OneUse, P: m_VecReverse(Op0: m_Value(V&: X)))) {
3333 Value *Reverse = Builder.CreateVectorReverse(V: Builder.CreateFNegFMF(V: X, FMFSource: &I));
3334 return replaceInstUsesWith(I, V: Reverse);
3335 }
3336
3337 return nullptr;
3338}
3339
3340Instruction *InstCombinerImpl::visitFSub(BinaryOperator &I) {
3341 if (Value *V = simplifyFSubInst(LHS: I.getOperand(i_nocapture: 0), RHS: I.getOperand(i_nocapture: 1),
3342 FMF: I.getFastMathFlags(),
3343 Q: getSimplifyQuery().getWithInstruction(I: &I)))
3344 return replaceInstUsesWith(I, V);
3345
3346 if (Instruction *X = foldVectorBinop(Inst&: I))
3347 return X;
3348
3349 if (Instruction *Phi = foldBinopWithPhiOperands(BO&: I))
3350 return Phi;
3351
3352 // Subtraction from -0.0 is the canonical form of fneg.
3353 // fsub -0.0, X ==> fneg X
3354 // fsub nsz 0.0, X ==> fneg nsz X
3355 //
3356 // FIXME This matcher does not respect FTZ or DAZ yet:
3357 // fsub -0.0, Denorm ==> +-0
3358 // fneg Denorm ==> -Denorm
3359 Value *Op;
3360 // TODO: Confirm whether m_FNegOrFSubNegZero is correct.
3361 if (match(V: &I, P: m_FNegOrFSubNegZero(X: m_Value(V&: Op))))
3362 return UnaryOperator::CreateFNegFMF(Op, FMFSource: &I);
3363
3364 if (Instruction *X = foldFNegIntoConstant(I, DL))
3365 return X;
3366
3367 if (Instruction *R = foldFBinOpOfIntCasts(I))
3368 return R;
3369
3370 Value *X, *Y;
3371 Constant *C;
3372
3373 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
3374 // If Op0 is not -0.0 or we can ignore -0.0: Z - (X - Y) --> Z + (Y - X)
3375 // Canonicalize to fadd to make analysis easier.
3376 // This can also help codegen because fadd is commutative.
3377 // Note that if this fsub was really an fneg, the fadd with -0.0 will get
3378 // killed later. We still limit that particular transform with 'hasOneUse'
3379 // because an fneg is assumed better/cheaper than a generic fsub.
3380 if (I.hasNoSignedZeros() ||
3381 cannotBeNegativeZero(V: Op0, SQ: getSimplifyQuery().getWithInstruction(I: &I))) {
3382 if (match(V: Op1, P: m_OneUse(SubPattern: m_FSub(L: m_Value(V&: X), R: m_Value(V&: Y))))) {
3383 Value *NewSub = Builder.CreateFSubFMF(L: Y, R: X, FMFSource: &I);
3384 return BinaryOperator::CreateFAddFMF(V1: Op0, V2: NewSub, FMFSource: &I);
3385 }
3386 }
3387
3388 // (-X) - Op1 --> -(X + Op1)
3389 // TODO: Confirm whether m_FNegOrFSubNegZero is correct.
3390 if (I.hasNoSignedZeros() && !isa<ConstantExpr>(Val: Op0) &&
3391 match(V: Op0, P: m_OneUse(SubPattern: m_FNegOrFSubNegZero(X: m_Value(V&: X))))) {
3392 Value *FAdd = Builder.CreateFAddFMF(L: X, R: Op1, FMFSource: &I);
3393 return UnaryOperator::CreateFNegFMF(Op: FAdd, FMFSource: &I);
3394 }
3395
3396 if (isa<Constant>(Val: Op0))
3397 if (SelectInst *SI = dyn_cast<SelectInst>(Val: Op1))
3398 if (Instruction *NV = FoldOpIntoSelect(Op&: I, SI))
3399 return NV;
3400
3401 // X - C --> X + (-C)
3402 // But don't transform constant expressions because there's an inverse fold
3403 // for X + (-Y) --> X - Y.
3404 if (match(V: Op1, P: m_ImmConstant(C)))
3405 if (Constant *NegC = ConstantFoldUnaryOpOperand(Opcode: Instruction::FNeg, Op: C, DL))
3406 return BinaryOperator::CreateFAddFMF(V1: Op0, V2: NegC, FMFSource: &I);
3407
3408 // X - (-Y) --> X + Y
3409 // TODO: Confirm whether m_FNegOrFSubNegZero is correct.
3410 if (match(V: Op1, P: m_FNegOrFSubNegZero(X: m_Value(V&: Y))))
3411 return BinaryOperator::CreateFAddFMF(V1: Op0, V2: Y, FMFSource: &I);
3412
3413 // Similar to above, but look through a cast of the negated value:
3414 // X - (fptrunc(-Y)) --> X + fptrunc(Y)
3415 Type *Ty = I.getType();
3416 // TODO: Confirm whether m_FNegOrFSubNegZero is correct.
3417 if (match(V: Op1, P: m_OneUse(SubPattern: m_FPTrunc(Op: m_FNegOrFSubNegZero(X: m_Value(V&: Y))))))
3418 return BinaryOperator::CreateFAddFMF(V1: Op0, V2: Builder.CreateFPTrunc(V: Y, DestTy: Ty), FMFSource: &I);
3419
3420 // X - (fpext(-Y)) --> X + fpext(Y)
3421 // TODO: Confirm whether m_FNegOrFSubNegZero is correct.
3422 if (match(V: Op1, P: m_OneUse(SubPattern: m_FPExt(Op: m_FNegOrFSubNegZero(X: m_Value(V&: Y))))))
3423 return BinaryOperator::CreateFAddFMF(V1: Op0, V2: Builder.CreateFPExt(V: Y, DestTy: Ty), FMFSource: &I);
3424
3425 // Similar to above, but look through fmul/fdiv of the negated value:
3426 // Op0 - (-X * Y) --> Op0 + (X * Y)
3427 // Op0 - (Y * -X) --> Op0 + (X * Y)
3428 // TODO: Confirm whether m_FNegOrFSubNegZero is correct.
3429 if (match(V: Op1,
3430 P: m_OneUse(SubPattern: m_c_FMul(L: m_FNegOrFSubNegZero(X: m_Value(V&: X)), R: m_Value(V&: Y))))) {
3431 Value *FMul = Builder.CreateFMulFMF(L: X, R: Y, FMFSource: &I);
3432 return BinaryOperator::CreateFAddFMF(V1: Op0, V2: FMul, FMFSource: &I);
3433 }
3434 // Op0 - (-X / Y) --> Op0 + (X / Y)
3435 // Op0 - (X / -Y) --> Op0 + (X / Y)
3436 // TODO: Confirm whether m_FNegOrFSubNegZero is correct.
3437 if (match(V: Op1,
3438 P: m_OneUse(SubPattern: m_FDiv(L: m_FNegOrFSubNegZero(X: m_Value(V&: X)), R: m_Value(V&: Y)))) ||
3439 match(V: Op1,
3440 P: m_OneUse(SubPattern: m_FDiv(L: m_Value(V&: X), R: m_FNegOrFSubNegZero(X: m_Value(V&: Y)))))) {
3441 Value *FDiv = Builder.CreateFDivFMF(L: X, R: Y, FMFSource: &I);
3442 return BinaryOperator::CreateFAddFMF(V1: Op0, V2: FDiv, FMFSource: &I);
3443 }
3444
3445 // Handle special cases for FSub with selects feeding the operation
3446 if (Value *V = SimplifySelectsFeedingBinaryOp(I, LHS: Op0, RHS: Op1))
3447 return replaceInstUsesWith(I, V);
3448
3449 if (I.hasAllowReassoc() && I.hasNoSignedZeros()) {
3450 // (Y - X) - Y --> -X
3451 if (match(V: Op0, P: m_FSub(L: m_Specific(V: Op1), R: m_Value(V&: X))))
3452 return UnaryOperator::CreateFNegFMF(Op: X, FMFSource: &I);
3453
3454 // Y - (X + Y) --> -X
3455 // Y - (Y + X) --> -X
3456 if (match(V: Op1, P: m_c_FAdd(L: m_Specific(V: Op0), R: m_Value(V&: X))))
3457 return UnaryOperator::CreateFNegFMF(Op: X, FMFSource: &I);
3458
3459 // (X * C) - X --> X * (C - 1.0)
3460 if (match(V: Op0, P: m_FMul(L: m_Specific(V: Op1), R: m_Constant(C)))) {
3461 if (Constant *CSubOne = ConstantFoldBinaryOpOperands(
3462 Opcode: Instruction::FSub, LHS: C, RHS: ConstantFP::get(Ty, V: 1.0), DL))
3463 return BinaryOperator::CreateFMulFMF(V1: Op1, V2: CSubOne, FMFSource: &I);
3464 }
3465 // X - (X * C) --> X * (1.0 - C)
3466 if (match(V: Op1, P: m_FMul(L: m_Specific(V: Op0), R: m_Constant(C)))) {
3467 if (Constant *OneSubC = ConstantFoldBinaryOpOperands(
3468 Opcode: Instruction::FSub, LHS: ConstantFP::get(Ty, V: 1.0), RHS: C, DL))
3469 return BinaryOperator::CreateFMulFMF(V1: Op0, V2: OneSubC, FMFSource: &I);
3470 }
3471
3472 // Reassociate fsub/fadd sequences to create more fadd instructions and
3473 // reduce dependency chains:
3474 // ((X - Y) + Z) - Op1 --> (X + Z) - (Y + Op1)
3475 Value *Z;
3476 if (match(V: Op0, P: m_OneUse(SubPattern: m_c_FAdd(L: m_OneUse(SubPattern: m_FSub(L: m_Value(V&: X), R: m_Value(V&: Y))),
3477 R: m_Value(V&: Z))))) {
3478 Value *XZ = Builder.CreateFAddFMF(L: X, R: Z, FMFSource: &I);
3479 Value *YW = Builder.CreateFAddFMF(L: Y, R: Op1, FMFSource: &I);
3480 return BinaryOperator::CreateFSubFMF(V1: XZ, V2: YW, FMFSource: &I);
3481 }
3482
3483 auto m_FaddRdx = [](Value *&Sum, Value *&Vec) {
3484 return m_OneUse(SubPattern: m_Intrinsic<Intrinsic::vector_reduce_fadd>(Ops: m_Value(V&: Sum),
3485 Ops: m_Value(V&: Vec)));
3486 };
3487 Value *A0, *A1, *V0, *V1;
3488 if (match(V: Op0, P: m_FaddRdx(A0, V0)) && match(V: Op1, P: m_FaddRdx(A1, V1)) &&
3489 V0->getType() == V1->getType()) {
3490 // Difference of sums is sum of differences:
3491 // add_rdx(A0, V0) - add_rdx(A1, V1) --> add_rdx(A0, V0 - V1) - A1
3492 Value *Sub = Builder.CreateFSubFMF(L: V0, R: V1, FMFSource: &I);
3493 Value *Rdx = Builder.CreateIntrinsic(ID: Intrinsic::vector_reduce_fadd,
3494 OverloadTypes: {Sub->getType()}, Args: {A0, Sub}, FMFSource: &I);
3495 return BinaryOperator::CreateFSubFMF(V1: Rdx, V2: A1, FMFSource: &I);
3496 }
3497
3498 if (Instruction *F = factorizeFAddFSub(I, Builder))
3499 return F;
3500
3501 // TODO: This performs reassociative folds for FP ops. Some fraction of the
3502 // functionality has been subsumed by simple pattern matching here and in
3503 // InstSimplify. We should let a dedicated reassociation pass handle more
3504 // complex pattern matching and remove this from InstCombine.
3505 if (Value *V = FAddCombine(Builder).simplify(I: &I))
3506 return replaceInstUsesWith(I, V);
3507
3508 // (X - Y) - Op1 --> X - (Y + Op1)
3509 if (match(V: Op0, P: m_OneUse(SubPattern: m_FSub(L: m_Value(V&: X), R: m_Value(V&: Y))))) {
3510 Value *FAdd = Builder.CreateFAddFMF(L: Y, R: Op1, FMFSource: &I);
3511 return BinaryOperator::CreateFSubFMF(V1: X, V2: FAdd, FMFSource: &I);
3512 }
3513 }
3514
3515 return nullptr;
3516}
3517