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 if (C->isOne() && Op0->hasOneUse()) {
987 // add (sext i1 X), 1 --> zext (not X)
988 // TODO: The smallest IR representation is (select X, 0, 1), and that would
989 // not require the one-use check. But we need to remove a transform in
990 // visitSelect and make sure that IR value tracking for select is equal or
991 // better than for these ops.
992 if (match(V: Op0, P: m_SExt(Op: m_Value(V&: X))) &&
993 X->getType()->getScalarSizeInBits() == 1)
994 return new ZExtInst(Builder.CreateNot(V: X), Ty);
995
996 // Shifts and add used to flip and mask off the low bit:
997 // add (ashr (shl i32 X, 31), 31), 1 --> and (not X), 1
998 const APInt *C3;
999 if (match(V: Op0, P: m_AShr(L: m_Shl(L: m_Value(V&: X), R: m_APInt(Res&: C2)), R: m_APInt(Res&: C3))) &&
1000 C2 == C3 && *C2 == Ty->getScalarSizeInBits() - 1) {
1001 Value *NotX = Builder.CreateNot(V: X);
1002 return BinaryOperator::CreateAnd(V1: NotX, V2: ConstantInt::get(Ty, V: 1));
1003 }
1004 }
1005
1006 // umax(X, C) + -C --> usub.sat(X, C)
1007 if (match(V: Op0, P: m_OneUse(SubPattern: m_UMax(Op0: m_Value(V&: X), Op1: m_SpecificInt(V: -*C)))))
1008 return replaceInstUsesWith(
1009 I&: Add, V: Builder.CreateBinaryIntrinsic(
1010 ID: Intrinsic::usub_sat, LHS: X, RHS: ConstantInt::get(Ty: Add.getType(), V: -*C)));
1011 // uadd.sat(X, C) + -C --> umin(X, ~C)
1012 // The saturating add gives X + C or UMAX, so subtracting C leaves X or
1013 // UMAX - C. Note UMAX - C == ~C.
1014 {
1015 APInt SatC = -*C;
1016 if (match(V: Op0, P: m_OneUse(SubPattern: m_Intrinsic<Intrinsic::uadd_sat>(
1017 Ops: m_Value(V&: X), Ops: m_SpecificInt(V: SatC)))))
1018 return replaceInstUsesWith(
1019 I&: Add, V: Builder.CreateBinaryIntrinsic(ID: Intrinsic::umin, LHS: X,
1020 RHS: ConstantInt::get(Ty, V: ~SatC)));
1021 }
1022 // Fold (add (zext (add X, -C)), C) -> (zext X) if X u>= C.
1023 // Truncate C to the narrow type to avoid mismatched width comparisons.
1024 {
1025 const APInt *InnerC;
1026 if (match(V: Op0, P: m_ZExt(Op: m_Add(L: m_Value(V&: X), R: m_APIntAllowPoison(Res&: InnerC))))) {
1027 unsigned NarrowBW = InnerC->getBitWidth();
1028 if (C->isIntN(N: NarrowBW)) {
1029 APInt NarrowC = C->trunc(width: NarrowBW);
1030 const SimplifyQuery Q = SQ.getWithInstruction(I: &Add);
1031 if (*InnerC == -NarrowC &&
1032 (NarrowC.isOne()
1033 ? llvm::isKnownNonZero(V: X, Q)
1034 : computeKnownBits(V: X, CtxI: &Add).getMinValue().uge(RHS: NarrowC)))
1035 return new ZExtInst(X, Ty);
1036 }
1037 }
1038 }
1039
1040 return nullptr;
1041}
1042
1043// match variations of a^2 + 2*a*b + b^2
1044//
1045// to reuse the code between the FP and Int versions, the instruction OpCodes
1046// and constant types have been turned into template parameters.
1047//
1048// Mul2Rhs: The constant to perform the multiplicative equivalent of X*2 with;
1049// should be `m_SpecificFP(2.0)` for FP and `m_SpecificInt(1)` for Int
1050// (we're matching `X<<1` instead of `X*2` for Int)
1051template <bool FP, typename Mul2Rhs>
1052static bool matchesSquareSum(BinaryOperator &I, Mul2Rhs M2Rhs, Value *&A,
1053 Value *&B) {
1054 constexpr unsigned MulOp = FP ? Instruction::FMul : Instruction::Mul;
1055 constexpr unsigned AddOp = FP ? Instruction::FAdd : Instruction::Add;
1056 constexpr unsigned Mul2Op = FP ? Instruction::FMul : Instruction::Shl;
1057
1058 // (a * a) + (((a * 2) + b) * b)
1059 if (match(&I, m_c_BinOp(
1060 AddOp, m_BinOp(Opcode: MulOp, L: m_Value(V&: A), R: m_Deferred(V: A)),
1061 m_OneUse(m_c_BinOp(
1062 MulOp,
1063 m_c_BinOp(AddOp, m_BinOp(Mul2Op, m_Deferred(V: A), M2Rhs),
1064 m_Value(V&: B)),
1065 m_Deferred(V: B))))))
1066 return true;
1067
1068 // ((a * b) * 2) or ((a * 2) * b)
1069 // +
1070 // (a * a + b * b) or (b * b + a * a)
1071 return match(
1072 &I, m_c_BinOp(
1073 AddOp,
1074 m_CombineOr(
1075 m_OneUse(m_BinOp(
1076 Mul2Op, m_BinOp(Opcode: MulOp, L: m_Value(V&: A), R: m_Value(V&: B)), M2Rhs)),
1077 m_OneUse(m_c_BinOp(MulOp, m_BinOp(Mul2Op, m_Value(V&: A), M2Rhs),
1078 m_Value(V&: B)))),
1079 m_OneUse(
1080 SubPattern: m_c_BinOp(Opcode: AddOp, L: m_BinOp(Opcode: MulOp, L: m_Deferred(V: A), R: m_Deferred(V: A)),
1081 R: m_BinOp(Opcode: MulOp, L: m_Deferred(V: B), R: m_Deferred(V: B))))));
1082}
1083
1084// Fold integer variations of a^2 + 2*a*b + b^2 -> (a + b)^2
1085Instruction *InstCombinerImpl::foldSquareSumInt(BinaryOperator &I) {
1086 Value *A, *B;
1087 if (matchesSquareSum</*FP*/ false>(I, M2Rhs: m_SpecificInt(V: 1), A, B)) {
1088 Value *AB = Builder.CreateAdd(LHS: A, RHS: B);
1089 return BinaryOperator::CreateMul(V1: AB, V2: AB);
1090 }
1091 return nullptr;
1092}
1093
1094// Fold floating point variations of a^2 + 2*a*b + b^2 -> (a + b)^2
1095// Requires `nsz` and `reassoc`.
1096Instruction *InstCombinerImpl::foldSquareSumFP(BinaryOperator &I) {
1097 assert(I.hasAllowReassoc() && I.hasNoSignedZeros() && "Assumption mismatch");
1098 Value *A, *B;
1099 if (matchesSquareSum</*FP*/ true>(I, M2Rhs: m_SpecificFP(V: 2.0), A, B)) {
1100 Value *AB = Builder.CreateFAddFMF(L: A, R: B, FMFSource: &I);
1101 return BinaryOperator::CreateFMulFMF(V1: AB, V2: AB, FMFSource: &I);
1102 }
1103 return nullptr;
1104}
1105
1106// Matches multiplication expression Op * C where C is a constant. Returns the
1107// constant value in C and the other operand in Op. Returns true if such a
1108// match is found.
1109static bool MatchMul(Value *E, Value *&Op, APInt &C) {
1110 const APInt *AI;
1111 if (match(V: E, P: m_Mul(L: m_Value(V&: Op), R: m_APInt(Res&: AI)))) {
1112 C = *AI;
1113 return true;
1114 }
1115 if (match(V: E, P: m_Shl(L: m_Value(V&: Op), R: m_APInt(Res&: AI)))) {
1116 C = APInt(AI->getBitWidth(), 1);
1117 C <<= *AI;
1118 return true;
1119 }
1120 return false;
1121}
1122
1123// Matches remainder expression Op % C where C is a constant. Returns the
1124// constant value in C and the other operand in Op. Returns the signedness of
1125// the remainder operation in IsSigned. Returns true if such a match is
1126// found.
1127static bool MatchRem(Value *E, Value *&Op, APInt &C, bool &IsSigned) {
1128 const APInt *AI;
1129 IsSigned = false;
1130 if (match(V: E, P: m_SRem(L: m_Value(V&: Op), R: m_APInt(Res&: AI)))) {
1131 IsSigned = true;
1132 C = *AI;
1133 return true;
1134 }
1135 if (match(V: E, P: m_URem(L: m_Value(V&: Op), R: m_APInt(Res&: AI)))) {
1136 C = *AI;
1137 return true;
1138 }
1139 if (match(V: E, P: m_And(L: m_Value(V&: Op), R: m_APInt(Res&: AI))) && (*AI + 1).isPowerOf2()) {
1140 C = *AI + 1;
1141 return true;
1142 }
1143 return false;
1144}
1145
1146// Matches division expression Op / C with the given signedness as indicated
1147// by IsSigned, where C is a constant. Returns the constant value in C and the
1148// other operand in Op. Returns true if such a match is found.
1149static bool MatchDiv(Value *E, Value *&Op, APInt &C, bool IsSigned) {
1150 const APInt *AI;
1151 if (IsSigned && match(V: E, P: m_SDiv(L: m_Value(V&: Op), R: m_APInt(Res&: AI)))) {
1152 C = *AI;
1153 return true;
1154 }
1155 if (!IsSigned) {
1156 if (match(V: E, P: m_UDiv(L: m_Value(V&: Op), R: m_APInt(Res&: AI)))) {
1157 C = *AI;
1158 return true;
1159 }
1160 if (match(V: E, P: m_LShr(L: m_Value(V&: Op), R: m_APInt(Res&: AI)))) {
1161 C = APInt(AI->getBitWidth(), 1);
1162 C <<= *AI;
1163 return true;
1164 }
1165 }
1166 return false;
1167}
1168
1169// Returns whether C0 * C1 with the given signedness overflows.
1170static bool MulWillOverflow(APInt &C0, APInt &C1, bool IsSigned) {
1171 bool overflow;
1172 if (IsSigned)
1173 (void)C0.smul_ov(RHS: C1, Overflow&: overflow);
1174 else
1175 (void)C0.umul_ov(RHS: C1, Overflow&: overflow);
1176 return overflow;
1177}
1178
1179// Simplifies X % C0 + (( X / C0 ) % C1) * C0 to X % (C0 * C1), where (C0 * C1)
1180// does not overflow.
1181// Simplifies (X / C0) * C1 + (X % C0) * C2 to
1182// (X / C0) * (C1 - C2 * C0) + X * C2
1183Value *InstCombinerImpl::SimplifyAddWithRemainder(BinaryOperator &I) {
1184 Value *LHS = I.getOperand(i_nocapture: 0), *RHS = I.getOperand(i_nocapture: 1);
1185 Value *X, *MulOpV;
1186 APInt C0, MulOpC;
1187 bool IsSigned;
1188 // Match I = X % C0 + MulOpV * C0
1189 if (((MatchRem(E: LHS, Op&: X, C&: C0, IsSigned) && MatchMul(E: RHS, Op&: MulOpV, C&: MulOpC)) ||
1190 (MatchRem(E: RHS, Op&: X, C&: C0, IsSigned) && MatchMul(E: LHS, Op&: MulOpV, C&: MulOpC))) &&
1191 C0 == MulOpC) {
1192 Value *RemOpV;
1193 APInt C1;
1194 bool Rem2IsSigned;
1195 // Match MulOpC = RemOpV % C1
1196 if (MatchRem(E: MulOpV, Op&: RemOpV, C&: C1, IsSigned&: Rem2IsSigned) &&
1197 IsSigned == Rem2IsSigned) {
1198 Value *DivOpV;
1199 APInt DivOpC;
1200 // Match RemOpV = X / C0
1201 if (MatchDiv(E: RemOpV, Op&: DivOpV, C&: DivOpC, IsSigned) && X == DivOpV &&
1202 C0 == DivOpC && !MulWillOverflow(C0, C1, IsSigned)) {
1203 Value *NewDivisor = ConstantInt::get(Ty: X->getType(), V: C0 * C1);
1204 return IsSigned ? Builder.CreateSRem(LHS: X, RHS: NewDivisor, Name: "srem")
1205 : Builder.CreateURem(LHS: X, RHS: NewDivisor, Name: "urem");
1206 }
1207 }
1208 }
1209
1210 // Match I = (X / C0) * C1 + (X % C0) * C2.
1211 auto FoldDivRem = [&](Value *DivSide, Value *RemSide) -> Value * {
1212 Value *Div, *Rem;
1213 APInt C1, C2;
1214 if (!DivSide->hasOneUse() || !MatchMul(E: DivSide, Op&: Div, C&: C1))
1215 Div = DivSide, C1 = APInt(I.getType()->getScalarSizeInBits(), 1);
1216 if (!RemSide->hasOneUse() || !MatchMul(E: RemSide, Op&: Rem, C&: C2))
1217 Rem = RemSide, C2 = APInt(I.getType()->getScalarSizeInBits(), 1);
1218 Value *DivOpV;
1219 APInt DivOpC;
1220 if (MatchRem(E: Rem, Op&: X, C&: C0, IsSigned) &&
1221 MatchDiv(E: Div, Op&: DivOpV, C&: DivOpC, IsSigned) && X == DivOpV &&
1222 C0 == DivOpC &&
1223 // Avoid unprofitable replacement of and with mul.
1224 !(C1.isOne() && !IsSigned && DivOpC.isPowerOf2() && DivOpC != 2)) {
1225 APInt NewC = C1 - C2 * C0;
1226 if (!NewC.isZero() && !Rem->hasOneUse())
1227 return nullptr;
1228 if (!isGuaranteedNotToBeUndef(V: X, AC: &AC, CtxI: &I, DT: &DT))
1229 return nullptr;
1230 Value *MulXC2 = Builder.CreateMul(LHS: X, RHS: ConstantInt::get(Ty: X->getType(), V: C2));
1231 if (NewC.isZero())
1232 return MulXC2;
1233 return Builder.CreateAdd(
1234 LHS: Builder.CreateMul(LHS: Div, RHS: ConstantInt::get(Ty: X->getType(), V: NewC)), RHS: MulXC2);
1235 }
1236 return nullptr;
1237 };
1238 if (Value *V = FoldDivRem(LHS, RHS))
1239 return V;
1240 if (Value *V = FoldDivRem(RHS, LHS))
1241 return V;
1242
1243 return nullptr;
1244}
1245
1246/// Fold
1247/// (1 << NBits) - 1
1248/// Into:
1249/// ~(-(1 << NBits))
1250/// Because a 'not' is better for bit-tracking analysis and other transforms
1251/// than an 'add'. The new shl is always nsw, and is nuw if old `and` was.
1252static Instruction *canonicalizeLowbitMask(BinaryOperator &I,
1253 InstCombiner::BuilderTy &Builder) {
1254 Value *NBits;
1255 if (!match(V: &I, P: m_Add(L: m_OneUse(SubPattern: m_Shl(L: m_One(), R: m_Value(V&: NBits))), R: m_AllOnes())))
1256 return nullptr;
1257
1258 Constant *MinusOne = Constant::getAllOnesValue(Ty: NBits->getType());
1259 Value *NotMask = Builder.CreateShl(LHS: MinusOne, RHS: NBits, Name: "notmask");
1260 // Be wary of constant folding.
1261 if (auto *BOp = dyn_cast<BinaryOperator>(Val: NotMask)) {
1262 // Always NSW. But NUW propagates from `add`.
1263 BOp->setHasNoSignedWrap();
1264 BOp->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
1265 }
1266
1267 return BinaryOperator::CreateNot(Op: NotMask, Name: I.getName());
1268}
1269
1270static Instruction *foldToUnsignedSaturatedAdd(BinaryOperator &I) {
1271 assert(I.getOpcode() == Instruction::Add && "Expecting add instruction");
1272 Type *Ty = I.getType();
1273 auto getUAddSat = [&]() {
1274 return Intrinsic::getOrInsertDeclaration(M: I.getModule(), id: Intrinsic::uadd_sat,
1275 OverloadTys: Ty);
1276 };
1277
1278 // add (umin X, ~Y), Y --> uaddsat X, Y
1279 Value *X, *Y;
1280 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))),
1281 R: m_Deferred(V: Y))))
1282 return CallInst::Create(Func: getUAddSat(), Args: { X, Y });
1283
1284 // add (umin X, ~C), C --> uaddsat X, C
1285 const APInt *C, *NotC;
1286 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))) &&
1287 *C == ~*NotC)
1288 return CallInst::Create(Func: getUAddSat(), Args: { X, ConstantInt::get(Ty, V: *C) });
1289
1290 return nullptr;
1291}
1292
1293// Transform:
1294// (add A, (shl (neg B), Y))
1295// -> (sub A, (shl B, Y))
1296static Instruction *combineAddSubWithShlAddSub(InstCombiner::BuilderTy &Builder,
1297 const BinaryOperator &I) {
1298 Value *A, *B, *Cnt;
1299 if (match(V: &I,
1300 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))),
1301 R: m_Value(V&: A)))) {
1302 Value *NewShl = Builder.CreateShl(LHS: B, RHS: Cnt);
1303 return BinaryOperator::CreateSub(V1: A, V2: NewShl);
1304 }
1305 return nullptr;
1306}
1307
1308/// Try to reduce signed division by power-of-2 to an arithmetic shift right.
1309static Instruction *foldAddToAshr(BinaryOperator &Add) {
1310 // Division must be by power-of-2, but not the minimum signed value.
1311 Value *X;
1312 const APInt *DivC;
1313 if (!match(V: Add.getOperand(i_nocapture: 0), P: m_SDiv(L: m_Value(V&: X), R: m_Power2(V&: DivC))) ||
1314 DivC->isNegative())
1315 return nullptr;
1316
1317 // Rounding is done by adding -1 if the dividend (X) is negative and has any
1318 // low bits set. It recognizes two canonical patterns:
1319 // 1. For an 'ugt' cmp with the signed minimum value (SMIN), the
1320 // pattern is: sext (icmp ugt (X & (DivC - 1)), SMIN).
1321 // 2. For an 'eq' cmp, the pattern's: sext (icmp eq X & (SMIN + 1), SMIN + 1).
1322 // Note that, by the time we end up here, if possible, ugt has been
1323 // canonicalized into eq.
1324 const APInt *MaskC, *MaskCCmp;
1325 CmpPredicate Pred;
1326 if (!match(V: Add.getOperand(i_nocapture: 1),
1327 P: m_SExt(Op: m_ICmp(Pred, L: m_And(L: m_Specific(V: X), R: m_APInt(Res&: MaskC)),
1328 R: m_APInt(Res&: MaskCCmp)))))
1329 return nullptr;
1330
1331 if ((Pred != ICmpInst::ICMP_UGT || !MaskCCmp->isSignMask()) &&
1332 (Pred != ICmpInst::ICMP_EQ || *MaskCCmp != *MaskC))
1333 return nullptr;
1334
1335 APInt SMin = APInt::getSignedMinValue(numBits: Add.getType()->getScalarSizeInBits());
1336 bool IsMaskValid = Pred == ICmpInst::ICMP_UGT
1337 ? (*MaskC == (SMin | (*DivC - 1)))
1338 : (*DivC == 2 && *MaskC == SMin + 1);
1339 if (!IsMaskValid)
1340 return nullptr;
1341
1342 // (X / DivC) + sext ((X & (SMin | (DivC - 1)) >u SMin) --> X >>s log2(DivC)
1343 return BinaryOperator::CreateAShr(
1344 V1: X, V2: ConstantInt::get(Ty: Add.getType(), V: DivC->exactLogBase2()));
1345}
1346
1347Instruction *InstCombinerImpl::foldAddLikeCommutative(Value *LHS, Value *RHS,
1348 bool NSW, bool NUW) {
1349 Value *A, *B, *C;
1350 if (match(V: LHS, P: m_Sub(L: m_Value(V&: A), R: m_Value(V&: B))) &&
1351 match(V: RHS, P: m_Sub(L: m_Value(V&: C), R: m_Specific(V: A)))) {
1352 Instruction *R = BinaryOperator::CreateSub(V1: C, V2: B);
1353 bool NSWOut = NSW && match(V: LHS, P: m_NSWSub(L: m_Value(), R: m_Value())) &&
1354 match(V: RHS, P: m_NSWSub(L: m_Value(), R: m_Value()));
1355
1356 bool NUWOut = match(V: LHS, P: m_NUWSub(L: m_Value(), R: m_Value())) &&
1357 match(V: RHS, P: m_NUWSub(L: m_Value(), R: m_Value()));
1358 R->setHasNoSignedWrap(NSWOut);
1359 R->setHasNoUnsignedWrap(NUWOut);
1360 return R;
1361 }
1362
1363 // ((X s/ C1) << C2) + X => X s% -C1 where -C1 is 1 << C2
1364 const APInt *C1, *C2;
1365 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)))) {
1366 APInt One(C2->getBitWidth(), 1);
1367 APInt MinusC1 = -(*C1);
1368 if (MinusC1 == (One << *C2)) {
1369 Constant *NewRHS = ConstantInt::get(Ty: RHS->getType(), V: MinusC1);
1370 return BinaryOperator::CreateSRem(V1: RHS, V2: NewRHS);
1371 }
1372 }
1373
1374 // (A + C) + (B & ~C) == A + (B | C)
1375 if (match(V: LHS, P: m_c_Add(L: m_Value(V&: A), R: m_APInt(Res&: C1))) &&
1376 match(V: RHS, P: m_c_And(L: m_Value(V&: B), R: m_SpecificInt(V: ~*C1)))) {
1377 // Replacing one add with {or, add}. Avoid growth if both sides are shared.
1378 if (!LHS->hasOneUse() && !RHS->hasOneUse())
1379 return nullptr;
1380
1381 bool NSWOut = NSW && match(V: LHS, P: m_NSWAdd(L: m_Value(), R: m_Value()));
1382 bool NUWOut = NUW && match(V: LHS, P: m_NUWAdd(L: m_Value(), R: m_Value()));
1383 Value *NewOr =
1384 Builder.CreateOr(LHS: B, RHS: Constant::getIntegerValue(Ty: LHS->getType(), V: *C1));
1385 Instruction *NewAdd = BinaryOperator::CreateAdd(V1: A, V2: NewOr);
1386 NewAdd->setHasNoSignedWrap(NSWOut);
1387 NewAdd->setHasNoUnsignedWrap(NUWOut);
1388 return NewAdd;
1389 }
1390
1391 return nullptr;
1392}
1393
1394Instruction *InstCombinerImpl::
1395 canonicalizeCondSignextOfHighBitExtractToSignextHighBitExtract(
1396 BinaryOperator &I) {
1397 assert((I.getOpcode() == Instruction::Add ||
1398 I.getOpcode() == Instruction::Or ||
1399 I.getOpcode() == Instruction::Sub) &&
1400 "Expecting add/or/sub instruction");
1401
1402 // We have a subtraction/addition between a (potentially truncated) *logical*
1403 // right-shift of X and a "select".
1404 Value *X, *Select;
1405 Instruction *LowBitsToSkip, *Extract;
1406 if (!match(V: &I, P: m_c_BinOp(L: m_TruncOrSelf(Op: m_Instruction(
1407 I&: Extract, P: m_LShr(L: m_Value(V&: X),
1408 R: m_Instruction(I&: LowBitsToSkip)))),
1409 R: m_Value(V&: Select))))
1410 return nullptr;
1411
1412 // `add`/`or` is commutative; but for `sub`, "select" *must* be on RHS.
1413 if (I.getOpcode() == Instruction::Sub && I.getOperand(i_nocapture: 1) != Select)
1414 return nullptr;
1415
1416 Type *XTy = X->getType();
1417 bool HadTrunc = I.getType() != XTy;
1418
1419 // If there was a truncation of extracted value, then we'll need to produce
1420 // one extra instruction, so we need to ensure one instruction will go away.
1421 if (HadTrunc && !match(V: &I, P: m_c_BinOp(L: m_OneUse(SubPattern: m_Value()), R: m_Value())))
1422 return nullptr;
1423
1424 // Extraction should extract high NBits bits, with shift amount calculated as:
1425 // low bits to skip = shift bitwidth - high bits to extract
1426 // The shift amount itself may be extended, and we need to look past zero-ext
1427 // when matching NBits, that will matter for matching later.
1428 Value *NBits;
1429 if (!match(V: LowBitsToSkip,
1430 P: m_ZExtOrSelf(Op: m_Sub(L: m_SpecificInt(V: XTy->getScalarSizeInBits()),
1431 R: m_ZExtOrSelf(Op: m_Value(V&: NBits))))))
1432 return nullptr;
1433
1434 // Sign-extending value can be zero-extended if we `sub`tract it,
1435 // or sign-extended otherwise.
1436 auto SkipExtInMagic = [&I](Value *&V) {
1437 if (I.getOpcode() == Instruction::Sub)
1438 match(V, P: m_ZExtOrSelf(Op: m_Value(V)));
1439 else
1440 match(V, P: m_SExtOrSelf(Op: m_Value(V)));
1441 };
1442
1443 // Now, finally validate the sign-extending magic.
1444 // `select` itself may be appropriately extended, look past that.
1445 SkipExtInMagic(Select);
1446
1447 CmpPredicate Pred;
1448 const APInt *Thr;
1449 Value *SignExtendingValue, *Zero;
1450 bool ShouldSignext;
1451 // It must be a select between two values we will later establish to be a
1452 // sign-extending value and a zero constant. The condition guarding the
1453 // sign-extension must be based on a sign bit of the same X we had in `lshr`.
1454 if (!match(V: Select, P: m_Select(C: m_ICmp(Pred, L: m_Specific(V: X), R: m_APInt(Res&: Thr)),
1455 L: m_Value(V&: SignExtendingValue), R: m_Value(V&: Zero))) ||
1456 !isSignBitCheck(Pred, RHS: *Thr, TrueIfSigned&: ShouldSignext))
1457 return nullptr;
1458
1459 // icmp-select pair is commutative.
1460 if (!ShouldSignext)
1461 std::swap(a&: SignExtendingValue, b&: Zero);
1462
1463 // If we should not perform sign-extension then we must add/or/subtract zero.
1464 if (!match(V: Zero, P: m_Zero()))
1465 return nullptr;
1466 // Otherwise, it should be some constant, left-shifted by the same NBits we
1467 // had in `lshr`. Said left-shift can also be appropriately extended.
1468 // Again, we must look past zero-ext when looking for NBits.
1469 SkipExtInMagic(SignExtendingValue);
1470 Constant *SignExtendingValueBaseConstant;
1471 if (!match(V: SignExtendingValue,
1472 P: m_Shl(L: m_Constant(C&: SignExtendingValueBaseConstant),
1473 R: m_ZExtOrSelf(Op: m_Specific(V: NBits)))))
1474 return nullptr;
1475 // If we `sub`, then the constant should be one, else it should be all-ones.
1476 if (I.getOpcode() == Instruction::Sub
1477 ? !match(V: SignExtendingValueBaseConstant, P: m_One())
1478 : !match(V: SignExtendingValueBaseConstant, P: m_AllOnes()))
1479 return nullptr;
1480
1481 auto *NewAShr = BinaryOperator::CreateAShr(V1: X, V2: LowBitsToSkip,
1482 Name: Extract->getName() + ".sext");
1483 NewAShr->copyIRFlags(V: Extract); // Preserve `exact`-ness.
1484 if (!HadTrunc)
1485 return NewAShr;
1486
1487 Builder.Insert(I: NewAShr);
1488 return TruncInst::CreateTruncOrBitCast(S: NewAShr, Ty: I.getType());
1489}
1490
1491/// This is a specialization of a more general transform from
1492/// foldUsingDistributiveLaws. If that code can be made to work optimally
1493/// for multi-use cases or propagating nsw/nuw, then we would not need this.
1494static Instruction *factorizeMathWithShlOps(BinaryOperator &I,
1495 InstCombiner::BuilderTy &Builder) {
1496 // TODO: Also handle mul by doubling the shift amount?
1497 assert((I.getOpcode() == Instruction::Add ||
1498 I.getOpcode() == Instruction::Sub) &&
1499 "Expected add/sub");
1500 auto *Op0 = dyn_cast<BinaryOperator>(Val: I.getOperand(i_nocapture: 0));
1501 auto *Op1 = dyn_cast<BinaryOperator>(Val: I.getOperand(i_nocapture: 1));
1502 if (!Op0 || !Op1 || !(Op0->hasOneUse() || Op1->hasOneUse()))
1503 return nullptr;
1504
1505 Value *X, *Y, *ShAmt;
1506 if (!match(V: Op0, P: m_Shl(L: m_Value(V&: X), R: m_Value(V&: ShAmt))) ||
1507 !match(V: Op1, P: m_Shl(L: m_Value(V&: Y), R: m_Specific(V: ShAmt))))
1508 return nullptr;
1509
1510 // No-wrap propagates only when all ops have no-wrap.
1511 bool HasNSW = I.hasNoSignedWrap() && Op0->hasNoSignedWrap() &&
1512 Op1->hasNoSignedWrap();
1513 bool HasNUW = I.hasNoUnsignedWrap() && Op0->hasNoUnsignedWrap() &&
1514 Op1->hasNoUnsignedWrap();
1515
1516 // add/sub (X << ShAmt), (Y << ShAmt) --> (add/sub X, Y) << ShAmt
1517 Value *NewMath = Builder.CreateBinOp(Opc: I.getOpcode(), LHS: X, RHS: Y);
1518 if (auto *NewI = dyn_cast<BinaryOperator>(Val: NewMath)) {
1519 NewI->setHasNoSignedWrap(HasNSW);
1520 NewI->setHasNoUnsignedWrap(HasNUW);
1521 }
1522 auto *NewShl = BinaryOperator::CreateShl(V1: NewMath, V2: ShAmt);
1523 NewShl->setHasNoSignedWrap(HasNSW);
1524 NewShl->setHasNoUnsignedWrap(HasNUW);
1525 return NewShl;
1526}
1527
1528/// Reduce a sequence of masked half-width multiplies to a single multiply.
1529/// ((XLow * YHigh) + (YLow * XHigh)) << HalfBits) + (XLow * YLow) --> X * Y
1530static Instruction *foldBoxMultiply(BinaryOperator &I) {
1531 unsigned BitWidth = I.getType()->getScalarSizeInBits();
1532 // Skip the odd bitwidth types.
1533 if ((BitWidth & 0x1))
1534 return nullptr;
1535
1536 unsigned HalfBits = BitWidth >> 1;
1537 APInt HalfMask = APInt::getMaxValue(numBits: HalfBits);
1538
1539 // ResLo = (CrossSum << HalfBits) + (YLo * XLo)
1540 Value *XLo, *YLo;
1541 Value *CrossSum;
1542 // Require one-use on the multiply to avoid increasing the number of
1543 // multiplications.
1544 if (!match(V: &I, P: m_c_Add(L: m_Shl(L: m_Value(V&: CrossSum), R: m_SpecificInt(V: HalfBits)),
1545 R: m_OneUse(SubPattern: m_Mul(L: m_Value(V&: YLo), R: m_Value(V&: XLo))))))
1546 return nullptr;
1547
1548 // XLo = X & HalfMask
1549 // YLo = Y & HalfMask
1550 // TODO: Refactor with SimplifyDemandedBits or KnownBits known leading zeros
1551 // to enhance robustness
1552 Value *X, *Y;
1553 if (!match(V: XLo, P: m_And(L: m_Value(V&: X), R: m_SpecificInt(V: HalfMask))) ||
1554 !match(V: YLo, P: m_And(L: m_Value(V&: Y), R: m_SpecificInt(V: HalfMask))))
1555 return nullptr;
1556
1557 // CrossSum = (X' * (Y >> Halfbits)) + (Y' * (X >> HalfBits))
1558 // X' can be either X or XLo in the pattern (and the same for Y')
1559 if (match(V: CrossSum,
1560 P: m_c_Add(L: m_c_Mul(L: m_LShr(L: m_Specific(V: Y), R: m_SpecificInt(V: HalfBits)),
1561 R: m_CombineOr(Ps: m_Specific(V: X), Ps: m_Specific(V: XLo))),
1562 R: m_c_Mul(L: m_LShr(L: m_Specific(V: X), R: m_SpecificInt(V: HalfBits)),
1563 R: m_CombineOr(Ps: m_Specific(V: Y), Ps: m_Specific(V: YLo))))))
1564 return BinaryOperator::CreateMul(V1: X, V2: Y);
1565
1566 return nullptr;
1567}
1568
1569/// Return true if X + (Y-1) is provably non-wrapping in X's type
1570static bool checkDivCeilNUW(Value *X, Value *Y, const SimplifyQuery &SQ) {
1571 ConstantRange CRX = computeConstantRange(V: X, /*ForSigned=*/false, SQ);
1572 ConstantRange CRY = computeConstantRange(V: Y, /*ForSigned=*/false, SQ);
1573 APInt MinY = CRY.getUnsignedMin();
1574 APInt MaxX = CRX.getUnsignedMax();
1575 APInt MaxY = CRY.getUnsignedMax();
1576
1577 return !MinY.isZero() && !MaxX.ugt(RHS: -MaxY);
1578}
1579
1580/// Fold the div_ceil idiom in both forms:
1581/// add(udiv(X, Y), zext(icmp ne(urem(X, Y), 0)))
1582/// -> udiv(add nuw(X, Y - 1), Y)
1583/// add(zext(udiv(X, Y)), zext(icmp ne(urem(X, Y), 0)))
1584/// -> zext(udiv(add nuw(X, Y - 1), Y))
1585/// The zext form applies when udiv/urem operate in a narrower type than the
1586/// add.
1587Instruction *InstCombinerImpl::foldDivCeil(BinaryOperator &I) {
1588 Value *X, *Y;
1589
1590 auto UDivPat = m_OneUse(SubPattern: m_UDiv(L: m_Value(V&: X), R: m_Value(V&: Y)));
1591 auto URemPat = m_OneUse(SubPattern: m_URem(L: m_Deferred(V: X), R: m_Deferred(V: Y)));
1592 auto ICmpPat = m_OneUse(SubPattern: m_SpecificICmp(MatchPred: ICmpInst::ICMP_NE, L: URemPat, R: m_Zero()));
1593 auto DivPat = m_OneUse(SubPattern: m_ZExtOrSelf(Op: UDivPat));
1594 auto ZExtCmpPat = m_OneUse(SubPattern: m_ZExt(Op: ICmpPat));
1595
1596 if (!match(V: &I, P: m_c_Add(L: DivPat, R: ZExtCmpPat)) ||
1597 !checkDivCeilNUW(X, Y, SQ: SQ.getWithInstruction(I: &I)))
1598 return nullptr;
1599
1600 Value *YMinusOne =
1601 Builder.CreateAdd(LHS: Y, RHS: ConstantInt::getAllOnesValue(Ty: Y->getType()));
1602 Value *NUWAdd = Builder.CreateNUWAdd(LHS: X, RHS: YMinusOne);
1603 if (X->getType() != I.getType()) {
1604 Value *Div = Builder.CreateUDiv(LHS: NUWAdd, RHS: Y);
1605 return new ZExtInst(Div, I.getType());
1606 }
1607 return BinaryOperator::CreateUDiv(V1: NUWAdd, V2: Y);
1608}
1609
1610Instruction *InstCombinerImpl::visitAdd(BinaryOperator &I) {
1611 if (Value *V = simplifyAddInst(LHS: I.getOperand(i_nocapture: 0), RHS: I.getOperand(i_nocapture: 1),
1612 IsNSW: I.hasNoSignedWrap(), IsNUW: I.hasNoUnsignedWrap(),
1613 Q: SQ.getWithInstruction(I: &I)))
1614 return replaceInstUsesWith(I, V);
1615
1616 if (SimplifyAssociativeOrCommutative(I))
1617 return &I;
1618
1619 if (Instruction *X = foldVectorBinop(Inst&: I))
1620 return X;
1621
1622 if (Instruction *Phi = foldBinopWithPhiOperands(BO&: I))
1623 return Phi;
1624
1625 // (A*B)+(A*C) -> A*(B+C) etc
1626 if (Value *V = foldUsingDistributiveLaws(I))
1627 return replaceInstUsesWith(I, V);
1628
1629 if (Instruction *R = foldBoxMultiply(I))
1630 return R;
1631
1632 if (Instruction *R = factorizeMathWithShlOps(I, Builder))
1633 return R;
1634
1635 if (Instruction *X = foldAddWithConstant(Add&: I))
1636 return X;
1637
1638 if (Instruction *X = foldNoWrapAdd(Add&: I, Builder))
1639 return X;
1640
1641 if (Instruction *R = foldBinOpShiftWithShift(I))
1642 return R;
1643
1644 if (Instruction *R = combineAddSubWithShlAddSub(Builder, I))
1645 return R;
1646
1647 Value *LHS = I.getOperand(i_nocapture: 0), *RHS = I.getOperand(i_nocapture: 1);
1648 if (Instruction *R = foldAddLikeCommutative(LHS, RHS, NSW: I.hasNoSignedWrap(),
1649 NUW: I.hasNoUnsignedWrap()))
1650 return R;
1651 if (Instruction *R = foldAddLikeCommutative(LHS: RHS, RHS: LHS, NSW: I.hasNoSignedWrap(),
1652 NUW: I.hasNoUnsignedWrap()))
1653 return R;
1654 Type *Ty = I.getType();
1655 if (Ty->isIntOrIntVectorTy(BitWidth: 1))
1656 return BinaryOperator::CreateXor(V1: LHS, V2: RHS);
1657
1658 // X + X --> X << 1
1659 if (LHS == RHS) {
1660 auto *Shl = BinaryOperator::CreateShl(V1: LHS, V2: ConstantInt::get(Ty, V: 1));
1661 Shl->setHasNoSignedWrap(I.hasNoSignedWrap());
1662 Shl->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
1663 return Shl;
1664 }
1665
1666 Value *A, *B;
1667 if (match(V: LHS, P: m_Neg(V: m_Value(V&: A)))) {
1668 // -A + -B --> -(A + B)
1669 if (match(V: RHS, P: m_Neg(V: m_Value(V&: B))))
1670 return BinaryOperator::CreateNeg(Op: Builder.CreateAdd(LHS: A, RHS: B));
1671
1672 // -A + B --> B - A
1673 auto *Sub = BinaryOperator::CreateSub(V1: RHS, V2: A);
1674 auto *OB0 = cast<OverflowingBinaryOperator>(Val: LHS);
1675 Sub->setHasNoSignedWrap(I.hasNoSignedWrap() && OB0->hasNoSignedWrap());
1676
1677 return Sub;
1678 }
1679
1680 // A + -B --> A - B
1681 if (match(V: RHS, P: m_Neg(V: m_Value(V&: B)))) {
1682 auto *Sub = BinaryOperator::CreateSub(V1: LHS, V2: B);
1683 auto *OBO = cast<OverflowingBinaryOperator>(Val: RHS);
1684 Sub->setHasNoSignedWrap(I.hasNoSignedWrap() && OBO->hasNoSignedWrap());
1685 return Sub;
1686 }
1687
1688 if (Value *V = checkForNegativeOperand(I, Builder))
1689 return replaceInstUsesWith(I, V);
1690
1691 // (A + 1) + ~B --> A - B
1692 // ~B + (A + 1) --> A - B
1693 // (~B + A) + 1 --> A - B
1694 // (A + ~B) + 1 --> A - B
1695 // This relies on the ~B == -1-B identity.
1696 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)))) ||
1697 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())))
1698 return BinaryOperator::CreateSub(V1: A, V2: B);
1699
1700 {
1701 // (A + C) + ~B --> A - B + (C-1)
1702 // ~B + (A + C) --> A - B + (C-1)
1703 // (~B + A) + C --> A - B + (C-1)
1704 // (A + ~B) + C --> A - B + (C-1)
1705 // With constant C, subtraction of one is free, so we replace three ops
1706 // (two adds and a bitwise-not) with two (sub and add).
1707 const APInt *C;
1708 if (match(V: &I, P: m_c_BinOp(L: m_OneUse(SubPattern: m_Add(L: m_Value(V&: A), R: m_APIntAllowPoison(Res&: C))),
1709 R: m_Not(V: m_Value(V&: B)))) ||
1710 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))),
1711 R: m_APIntAllowPoison(Res&: C)))) {
1712 Value *Sub = Builder.CreateSub(LHS: A, RHS: B);
1713 return BinaryOperator::CreateAdd(V1: Sub, V2: ConstantInt::get(Ty, V: *C - 1));
1714 }
1715 }
1716
1717 // (A + RHS) + RHS --> A + (RHS << 1)
1718 if (match(V: LHS, P: m_OneUse(SubPattern: m_c_Add(L: m_Value(V&: A), R: m_Specific(V: RHS)))))
1719 return BinaryOperator::CreateAdd(V1: A, V2: Builder.CreateShl(LHS: RHS, RHS: 1, Name: "reass.add"));
1720
1721 // LHS + (A + LHS) --> A + (LHS << 1)
1722 if (match(V: RHS, P: m_OneUse(SubPattern: m_c_Add(L: m_Value(V&: A), R: m_Specific(V: LHS)))))
1723 return BinaryOperator::CreateAdd(V1: A, V2: Builder.CreateShl(LHS, RHS: 1, Name: "reass.add"));
1724
1725 {
1726 // (A + C1) + (C2 - B) --> (A - B) + (C1 + C2)
1727 Constant *C1, *C2;
1728 if (match(V: &I, P: m_c_Add(L: m_Add(L: m_Value(V&: A), R: m_ImmConstant(C&: C1)),
1729 R: m_Sub(L: m_ImmConstant(C&: C2), R: m_Value(V&: B)))) &&
1730 (LHS->hasOneUse() || RHS->hasOneUse())) {
1731 Value *Sub = Builder.CreateSub(LHS: A, RHS: B);
1732 return BinaryOperator::CreateAdd(V1: Sub, V2: ConstantExpr::getAdd(C1, C2));
1733 }
1734
1735 // Canonicalize a constant sub operand as an add operand for better folding:
1736 // (C1 - A) + B --> (B - A) + C1
1737 if (match(V: &I, P: m_c_Add(L: m_OneUse(SubPattern: m_Sub(L: m_ImmConstant(C&: C1), R: m_Value(V&: A))),
1738 R: m_Value(V&: B)))) {
1739 Value *Sub = Builder.CreateSub(LHS: B, RHS: A, Name: "reass.sub");
1740 return BinaryOperator::CreateAdd(V1: Sub, V2: C1);
1741 }
1742 }
1743
1744 // X % C0 + (( X / C0 ) % C1) * C0 => X % (C0 * C1)
1745 if (Value *V = SimplifyAddWithRemainder(I)) return replaceInstUsesWith(I, V);
1746
1747 const APInt *C1;
1748 // (A & 2^C1) + A => A & (2^C1 - 1) iff bit C1 in A is a sign bit
1749 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))) &&
1750 C1->isPowerOf2() && (ComputeNumSignBits(Op: A) > C1->countl_zero())) {
1751 Constant *NewMask = ConstantInt::get(Ty: RHS->getType(), V: *C1 - 1);
1752 return BinaryOperator::CreateAnd(V1: A, V2: NewMask);
1753 }
1754
1755 // ZExt (B - A) + ZExt(A) --> ZExt(B)
1756 if ((match(V: RHS, P: m_ZExt(Op: m_Value(V&: A))) &&
1757 match(V: LHS, P: m_ZExt(Op: m_NUWSub(L: m_Value(V&: B), R: m_Specific(V: A))))) ||
1758 (match(V: LHS, P: m_ZExt(Op: m_Value(V&: A))) &&
1759 match(V: RHS, P: m_ZExt(Op: m_NUWSub(L: m_Value(V&: B), R: m_Specific(V: A))))))
1760 return new ZExtInst(B, LHS->getType());
1761
1762 // zext(A) + sext(A) --> 0 if A is i1
1763 if (match(V: &I, P: m_c_BinOp(L: m_ZExt(Op: m_Value(V&: A)), R: m_SExt(Op: m_Deferred(V: A)))) &&
1764 A->getType()->isIntOrIntVectorTy(BitWidth: 1))
1765 return replaceInstUsesWith(I, V: Constant::getNullValue(Ty: I.getType()));
1766
1767 // sext(A < B) + zext(A > B) => ucmp/scmp(A, B)
1768 CmpPredicate LTPred, GTPred;
1769 if (match(V: &I,
1770 P: m_c_Add(L: m_SExt(Op: m_c_ICmp(Pred&: LTPred, L: m_Value(V&: A), R: m_Value(V&: B))),
1771 R: m_ZExt(Op: m_c_ICmp(Pred&: GTPred, L: m_Deferred(V: A), R: m_Deferred(V: B))))) &&
1772 A->getType()->isIntOrIntVectorTy()) {
1773 if (ICmpInst::isGT(P: LTPred)) {
1774 std::swap(a&: LTPred, b&: GTPred);
1775 std::swap(a&: A, b&: B);
1776 }
1777
1778 if (ICmpInst::isLT(P: LTPred) && ICmpInst::isGT(P: GTPred) &&
1779 ICmpInst::isSigned(Pred: LTPred) == ICmpInst::isSigned(Pred: GTPred))
1780 return replaceInstUsesWith(
1781 I, V: Builder.CreateIntrinsic(
1782 RetTy: Ty,
1783 ID: ICmpInst::isSigned(Pred: LTPred) ? Intrinsic::scmp : Intrinsic::ucmp,
1784 Args: {A, B}));
1785 }
1786
1787 // A+B --> A|B iff A and B have no bits set in common.
1788 WithCache<const Value *> LHSCache(LHS), RHSCache(RHS);
1789 switch (
1790 getNoCommonBitsSetResult(LHSCache, RHSCache, SQ: SQ.getWithInstruction(I: &I))) {
1791 case NoCommonBitsSetResult::Known:
1792 return BinaryOperator::CreateDisjointOr(V1: LHS, V2: RHS);
1793 case NoCommonBitsSetResult::OnlyIfUndefIgnored:
1794 return BinaryOperator::CreateOr(V1: LHS, V2: RHS);
1795 case NoCommonBitsSetResult::Unknown:
1796 break;
1797 }
1798
1799 if (Instruction *Ext = narrowMathIfNoOverflow(I))
1800 return Ext;
1801
1802 // (add (xor A, B) (and A, B)) --> (or A, B)
1803 // (add (and A, B) (xor A, B)) --> (or A, B)
1804 if (match(V: &I, P: m_c_BinOp(L: m_Xor(L: m_Value(V&: A), R: m_Value(V&: B)),
1805 R: m_c_And(L: m_Deferred(V: A), R: m_Deferred(V: B)))))
1806 return BinaryOperator::CreateOr(V1: A, V2: B);
1807
1808 // (add (or A, B) (and A, B)) --> (add A, B)
1809 // (add (and A, B) (or A, B)) --> (add A, B)
1810 if (match(V: &I, P: m_c_BinOp(L: m_Or(L: m_Value(V&: A), R: m_Value(V&: B)),
1811 R: m_c_And(L: m_Deferred(V: A), R: m_Deferred(V: B))))) {
1812 // Replacing operands in-place to preserve nuw/nsw flags.
1813 replaceOperand(I, OpNum: 0, V: A);
1814 replaceOperand(I, OpNum: 1, V: B);
1815 return &I;
1816 }
1817
1818 // (add A (or A, -A)) --> (and (add A, -1) A)
1819 // (add A (or -A, A)) --> (and (add A, -1) A)
1820 // (add (or A, -A) A) --> (and (add A, -1) A)
1821 // (add (or -A, A) A) --> (and (add A, -1) A)
1822 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)),
1823 R: m_Deferred(V: A)))))) {
1824 Value *Add =
1825 Builder.CreateAdd(LHS: A, RHS: Constant::getAllOnesValue(Ty: A->getType()), Name: "",
1826 HasNUW: I.hasNoUnsignedWrap(), HasNSW: I.hasNoSignedWrap());
1827 return BinaryOperator::CreateAnd(V1: Add, V2: A);
1828 }
1829
1830 // Align-up idiom:
1831 // X + ((-X) & (C - 1)) --> (X + C - 1) & -C
1832 // ((X - 1) | (C - 1)) + 1 -> (X + C - 1) & -C
1833 // For a power-of-two C. Note -C == ~(C - 1), so the mask is simply the
1834 // inverted low-bit mask.
1835 {
1836 const APInt *LowMask;
1837 if (match(V: &I,
1838 P: m_c_Add(L: m_OneUse(SubPattern: m_And(L: m_Neg(V: m_Value(V&: A)), R: m_LowBitMask(V&: LowMask))),
1839 R: m_Deferred(V: A))) ||
1840 match(V: &I, P: m_Add(L: m_OneUse(SubPattern: m_Or(L: m_Add(L: m_Value(V&: A), R: m_AllOnes()),
1841 R: m_LowBitMask(V&: LowMask))),
1842 R: m_One()))
1843
1844 ) {
1845 Value *NewAdd = Builder.CreateAdd(LHS: A, RHS: ConstantInt::get(Ty, V: *LowMask));
1846 return BinaryOperator::CreateAnd(V1: NewAdd, V2: ConstantInt::get(Ty, V: ~*LowMask));
1847 }
1848 }
1849
1850 // Canonicalize ((A & -A) - 1) --> ((A - 1) & ~A)
1851 // Forms all commutable operations, and simplifies ctpop -> cttz folds.
1852 if (match(V: &I,
1853 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))))),
1854 R: m_AllOnes()))) {
1855 Constant *AllOnes = ConstantInt::getAllOnesValue(Ty: RHS->getType());
1856 Value *Dec = Builder.CreateAdd(LHS: A, RHS: AllOnes);
1857 Value *Not = Builder.CreateXor(LHS: A, RHS: AllOnes);
1858 return BinaryOperator::CreateAnd(V1: Dec, V2: Not);
1859 }
1860
1861 // Disguised reassociation/factorization:
1862 // ~(A * C1) + A
1863 // ((A * -C1) - 1) + A
1864 // ((A * -C1) + A) - 1
1865 // (A * (1 - C1)) - 1
1866 if (match(V: &I,
1867 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))))),
1868 R: m_Deferred(V: A)))) {
1869 Type *Ty = I.getType();
1870 Constant *NewMulC = ConstantInt::get(Ty, V: 1 - *C1);
1871 Value *NewMul = Builder.CreateMul(LHS: A, RHS: NewMulC);
1872 return BinaryOperator::CreateAdd(V1: NewMul, V2: ConstantInt::getAllOnesValue(Ty));
1873 }
1874
1875 // (A * -2**C) + B --> B - (A << C)
1876 const APInt *NegPow2C;
1877 if (match(V: &I, P: m_c_Add(L: m_OneUse(SubPattern: m_Mul(L: m_Value(V&: A), R: m_NegatedPower2(V&: NegPow2C))),
1878 R: m_Value(V&: B)))) {
1879 Constant *ShiftAmtC = ConstantInt::get(Ty, V: NegPow2C->countr_zero());
1880 Value *Shl = Builder.CreateShl(LHS: A, RHS: ShiftAmtC);
1881 return BinaryOperator::CreateSub(V1: B, V2: Shl);
1882 }
1883
1884 // Canonicalize signum variant that ends in add:
1885 // (A s>> (BW - 1)) + (zext (A s> 0)) --> (A s>> (BW - 1)) | (zext (A != 0))
1886 uint64_t BitWidth = Ty->getScalarSizeInBits();
1887 if (match(V: LHS, P: m_AShr(L: m_Value(V&: A), R: m_SpecificIntAllowPoison(V: BitWidth - 1))) &&
1888 match(V: RHS, P: m_OneUse(SubPattern: m_ZExt(Op: m_OneUse(SubPattern: m_SpecificICmp(
1889 MatchPred: CmpInst::ICMP_SGT, L: m_Specific(V: A), R: m_ZeroInt())))))) {
1890 Value *NotZero = Builder.CreateIsNotNull(Arg: A, Name: "isnotnull");
1891 Value *Zext = Builder.CreateZExt(V: NotZero, DestTy: Ty, Name: "isnotnull.zext");
1892 return BinaryOperator::CreateOr(V1: LHS, V2: Zext);
1893 }
1894
1895 {
1896 Value *Cond, *Ext;
1897 Constant *C;
1898 // (add X, (sext/zext (icmp eq X, C)))
1899 // -> (select (icmp eq X, C), (add C, (sext/zext 1)), X)
1900 auto CondMatcher =
1901 m_Value(V&: Cond, P: m_SpecificICmp(MatchPred: ICmpInst::ICMP_EQ, L: m_Deferred(V: A),
1902 R: m_ImmConstant(C)));
1903
1904 if (match(V: &I,
1905 P: m_c_Add(L: m_Value(V&: A), R: m_Value(V&: Ext, P: m_ZExtOrSExt(Op: CondMatcher)))) &&
1906 Ext->hasOneUse()) {
1907 Value *Add = isa<ZExtInst>(Val: Ext) ? InstCombiner::AddOne(C)
1908 : InstCombiner::SubOne(C);
1909 return replaceInstUsesWith(I, V: Builder.CreateSelect(C: Cond, True: Add, False: A));
1910 }
1911 }
1912
1913 // (add (add A, 1), (sext (icmp ne A, 0))) => call umax(A, 1)
1914 if (match(V: LHS, P: m_Add(L: m_Value(V&: A), R: m_One())) &&
1915 match(V: RHS, P: m_OneUse(SubPattern: m_SExt(Op: m_OneUse(SubPattern: m_SpecificICmp(
1916 MatchPred: ICmpInst::ICMP_NE, L: m_Specific(V: A), R: m_ZeroInt())))))) {
1917 Value *OneConst = ConstantInt::get(Ty: A->getType(), V: 1);
1918 Value *UMax = Builder.CreateBinaryIntrinsic(ID: Intrinsic::umax, LHS: A, RHS: OneConst);
1919 return replaceInstUsesWith(I, V: UMax);
1920 }
1921
1922 if (Instruction *Ashr = foldAddToAshr(Add&: I))
1923 return Ashr;
1924
1925 // Ceiling division by power-of-2:
1926 // (X >> log2(N)) + zext(X & (N-1) != 0) --> (X + (N-1)) >> log2(N)
1927 // This is valid when adding (N-1) to X doesn't overflow.
1928 {
1929 Value *X;
1930 const APInt *ShiftAmt, *Mask;
1931 CmpPredicate Pred;
1932
1933 // Match: (X >> C) + zext((X & Mask) != 0)
1934 // or: zext((X & Mask) != 0) + (X >> C)
1935 if (match(V: &I,
1936 P: m_c_Add(L: m_ZExt(Op: m_SpecificICmp(
1937 MatchPred: ICmpInst::ICMP_NE,
1938 L: m_And(L: m_Value(V&: X), R: m_LowBitMask(V&: Mask)), R: m_ZeroInt())),
1939 R: m_OneUse(SubPattern: m_ZExtOrSelf(Op: m_OneUse(
1940 SubPattern: m_LShr(L: m_Deferred(V: X), R: m_APInt(Res&: ShiftAmt))))))) &&
1941 Mask->popcount() == *ShiftAmt) {
1942
1943 // Check if X + Mask doesn't overflow
1944 unsigned Xbits = X->getType()->getScalarSizeInBits();
1945 unsigned Ibits = Ty->getScalarSizeInBits();
1946 bool NeedZext = Ibits > Xbits;
1947 Constant *MaskC = ConstantInt::get(Ty, V: Mask->zext(width: Ibits));
1948 if (NeedZext || willNotOverflowUnsignedAdd(LHS: X, RHS: MaskC, CtxI: I)) {
1949 if (NeedZext)
1950 X = Builder.CreateZExt(V: X, DestTy: Ty);
1951 // (X + Mask) >> ShiftAmt
1952 Value *Add = Builder.CreateNUWAdd(LHS: X, RHS: MaskC);
1953 return BinaryOperator::CreateLShr(
1954 V1: Add, V2: ConstantInt::get(Ty, V: ShiftAmt->zext(width: Ibits)));
1955 }
1956 }
1957 }
1958
1959 // (~X) + (~Y) --> -2 - (X + Y)
1960 {
1961 // To ensure we can save instructions we need to ensure that we consume both
1962 // LHS/RHS (i.e they have a `not`).
1963 bool ConsumesLHS, ConsumesRHS;
1964 if (isFreeToInvert(V: LHS, WillInvertAllUses: LHS->hasOneUse(), DoesConsume&: ConsumesLHS) && ConsumesLHS &&
1965 isFreeToInvert(V: RHS, WillInvertAllUses: RHS->hasOneUse(), DoesConsume&: ConsumesRHS) && ConsumesRHS) {
1966 Value *NotLHS = getFreelyInverted(V: LHS, WillInvertAllUses: LHS->hasOneUse(), Builder: &Builder);
1967 Value *NotRHS = getFreelyInverted(V: RHS, WillInvertAllUses: RHS->hasOneUse(), Builder: &Builder);
1968 assert(NotLHS != nullptr && NotRHS != nullptr &&
1969 "isFreeToInvert desynced with getFreelyInverted");
1970 Value *LHSPlusRHS = Builder.CreateAdd(LHS: NotLHS, RHS: NotRHS);
1971 return BinaryOperator::CreateSub(
1972 V1: ConstantInt::getSigned(Ty: RHS->getType(), V: -2), V2: LHSPlusRHS);
1973 }
1974 }
1975
1976 if (Instruction *R = tryFoldInstWithCtpopWithNot(I: &I))
1977 return R;
1978
1979 // TODO(jingyue): Consider willNotOverflowSignedAdd and
1980 // willNotOverflowUnsignedAdd to reduce the number of invocations of
1981 // computeKnownBits.
1982 bool Changed = false;
1983 if (!I.hasNoSignedWrap() && willNotOverflowSignedAdd(LHS: LHSCache, RHS: RHSCache, CtxI: I)) {
1984 Changed = true;
1985 I.setHasNoSignedWrap(true);
1986 }
1987 if (!I.hasNoUnsignedWrap() &&
1988 willNotOverflowUnsignedAdd(LHS: LHSCache, RHS: RHSCache, CtxI: I)) {
1989 Changed = true;
1990 I.setHasNoUnsignedWrap(true);
1991 }
1992
1993 if (Instruction *V = canonicalizeLowbitMask(I, Builder))
1994 return V;
1995
1996 if (Instruction *V =
1997 canonicalizeCondSignextOfHighBitExtractToSignextHighBitExtract(I))
1998 return V;
1999
2000 if (Instruction *SatAdd = foldToUnsignedSaturatedAdd(I))
2001 return SatAdd;
2002
2003 // usub.sat(A, B) + B => umax(A, B)
2004 if (match(V: &I, P: m_c_BinOp(
2005 L: m_OneUse(SubPattern: m_Intrinsic<Intrinsic::usub_sat>(Ops: m_Value(V&: A), Ops: m_Value(V&: B))),
2006 R: m_Deferred(V: B)))) {
2007 return replaceInstUsesWith(I,
2008 V: Builder.CreateIntrinsic(ID: Intrinsic::umax, OverloadTypes: {I.getType()}, Args: {A, B}));
2009 }
2010
2011 // ctpop(A) + ctpop(B) => ctpop(A | B) if A and B have no bits set in common.
2012 if (match(V: LHS, P: m_OneUse(SubPattern: m_Ctpop(Op0: m_Value(V&: A)))) &&
2013 match(V: RHS, P: m_OneUse(SubPattern: m_Ctpop(Op0: m_Value(V&: B)))) &&
2014 haveNoCommonBitsSet(LHSCache: A, RHSCache: B, SQ: SQ.getWithInstruction(I: &I)))
2015 return replaceInstUsesWith(
2016 I, V: Builder.CreateIntrinsic(ID: Intrinsic::ctpop, OverloadTypes: {I.getType()},
2017 Args: {Builder.CreateDisjointOr(LHS: A, RHS: B)}));
2018
2019 // Fold the log2_ceil idiom:
2020 // zext(ctpop(A) >u/!= 1) + (ctlz(A, true) ^ (BW - 1))
2021 // -->
2022 // BW - ctlz(A - 1, false)
2023 const APInt *XorC;
2024 CmpPredicate Pred;
2025 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())),
2026 R: m_OneUse(SubPattern: m_ZExtOrSelf(Op: m_OneUse(
2027 SubPattern: m_Xor(L: m_OneUse(SubPattern: m_TruncOrSelf(Op: m_OneUse(
2028 SubPattern: m_Ctlz(Op0: m_Deferred(V: A), Op1: m_One())))),
2029 R: m_APInt(Res&: XorC))))))) &&
2030 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_NE) &&
2031 *XorC == A->getType()->getScalarSizeInBits() - 1) {
2032 Value *Sub = Builder.CreateAdd(LHS: A, RHS: Constant::getAllOnesValue(Ty: A->getType()));
2033 Value *Ctlz = Builder.CreateIntrinsic(ID: Intrinsic::ctlz, OverloadTypes: {A->getType()},
2034 Args: {Sub, Builder.getFalse()});
2035 Value *Ret = Builder.CreateSub(
2036 LHS: ConstantInt::get(Ty: A->getType(), V: A->getType()->getScalarSizeInBits()),
2037 RHS: Ctlz, Name: "", /*HasNUW=*/true, /*HasNSW=*/true);
2038 return replaceInstUsesWith(I, V: Builder.CreateZExtOrTrunc(V: Ret, DestTy: I.getType()));
2039 }
2040
2041 if (Instruction *Res = foldSquareSumInt(I))
2042 return Res;
2043
2044 if (Instruction *Res = foldBinOpOfDisplacedShifts(I))
2045 return Res;
2046
2047 if (Instruction *Res = foldBinOpOfSelectAndCastOfSelectCondition(I))
2048 return Res;
2049
2050 if (Instruction *Res = foldDivCeil(I))
2051 return Res;
2052
2053 // (A | -2) + A -> (A - 1) & -2
2054 APInt NegTwo(Ty->getScalarSizeInBits(), -2, /*isSigned=*/true);
2055 if (match(V: &I, P: m_c_BinOp(L: m_OneUse(SubPattern: m_Or(L: m_Value(V&: A), R: m_SpecificInt(V: NegTwo))),
2056 R: m_Deferred(V: A)))) {
2057 Value *Ret = Builder.CreateAdd(
2058 LHS: A, RHS: ConstantInt::get(
2059 Ty, V: APInt(Ty->getScalarSizeInBits(), -1, /*isSigned=*/true)));
2060 return BinaryOperator::CreateAnd(V1: Ret, V2: ConstantInt::get(Ty, V: NegTwo));
2061 }
2062
2063 // Re-enqueue users of the induction variable of add recurrence if we infer
2064 // new nuw/nsw flags.
2065 if (Changed) {
2066 PHINode *PHI;
2067 Value *Start, *Step;
2068 if (matchSimpleRecurrence(I: &I, P&: PHI, Start, Step))
2069 Worklist.pushUsersToWorkList(I&: *PHI);
2070 }
2071
2072 return Changed ? &I : nullptr;
2073}
2074
2075/// Eliminate an op from a linear interpolation (lerp) pattern.
2076static Instruction *factorizeLerp(BinaryOperator &I,
2077 InstCombiner::BuilderTy &Builder) {
2078 Value *X, *Y, *Z;
2079 if (!match(V: &I, P: m_c_FAdd(L: m_OneUse(SubPattern: m_c_FMul(L: m_Value(V&: Y),
2080 R: m_OneUse(SubPattern: m_FSub(L: m_FPOne(),
2081 R: m_Value(V&: Z))))),
2082 R: m_OneUse(SubPattern: m_c_FMul(L: m_Value(V&: X), R: m_Deferred(V: Z))))))
2083 return nullptr;
2084
2085 // (Y * (1.0 - Z)) + (X * Z) --> Y + Z * (X - Y) [8 commuted variants]
2086 Value *XY = Builder.CreateFSubFMF(L: X, R: Y, FMFSource: &I);
2087 Value *MulZ = Builder.CreateFMulFMF(L: Z, R: XY, FMFSource: &I);
2088 return BinaryOperator::CreateFAddFMF(V1: Y, V2: MulZ, FMFSource: &I);
2089}
2090
2091/// Factor a common operand out of fadd/fsub of fmul/fdiv.
2092static Instruction *factorizeFAddFSub(BinaryOperator &I,
2093 InstCombiner::BuilderTy &Builder) {
2094 assert((I.getOpcode() == Instruction::FAdd ||
2095 I.getOpcode() == Instruction::FSub) && "Expecting fadd/fsub");
2096 assert(I.hasAllowReassoc() && I.hasNoSignedZeros() &&
2097 "FP factorization requires FMF");
2098
2099 if (Instruction *Lerp = factorizeLerp(I, Builder))
2100 return Lerp;
2101
2102 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
2103 if (!Op0->hasOneUse() || !Op1->hasOneUse())
2104 return nullptr;
2105
2106 Value *X, *Y, *Z;
2107 bool IsFMul;
2108 if ((match(V: Op0, P: m_FMul(L: m_Value(V&: X), R: m_Value(V&: Z))) &&
2109 match(V: Op1, P: m_c_FMul(L: m_Value(V&: Y), R: m_Specific(V: Z)))) ||
2110 (match(V: Op0, P: m_FMul(L: m_Value(V&: Z), R: m_Value(V&: X))) &&
2111 match(V: Op1, P: m_c_FMul(L: m_Value(V&: Y), R: m_Specific(V: Z)))))
2112 IsFMul = true;
2113 else if (match(V: Op0, P: m_FDiv(L: m_Value(V&: X), R: m_Value(V&: Z))) &&
2114 match(V: Op1, P: m_FDiv(L: m_Value(V&: Y), R: m_Specific(V: Z))))
2115 IsFMul = false;
2116 else
2117 return nullptr;
2118
2119 // (X * Z) + (Y * Z) --> (X + Y) * Z
2120 // (X * Z) - (Y * Z) --> (X - Y) * Z
2121 // (X / Z) + (Y / Z) --> (X + Y) / Z
2122 // (X / Z) - (Y / Z) --> (X - Y) / Z
2123 bool IsFAdd = I.getOpcode() == Instruction::FAdd;
2124 Value *XY = IsFAdd ? Builder.CreateFAddFMF(L: X, R: Y, FMFSource: &I)
2125 : Builder.CreateFSubFMF(L: X, R: Y, FMFSource: &I);
2126
2127 // Bail out if we just created a denormal constant.
2128 // TODO: This is copied from a previous implementation. Is it necessary?
2129 const APFloat *C;
2130 if (match(V: XY, P: m_APFloat(Res&: C)) && !C->isNormal())
2131 return nullptr;
2132
2133 return IsFMul ? BinaryOperator::CreateFMulFMF(V1: XY, V2: Z, FMFSource: &I)
2134 : BinaryOperator::CreateFDivFMF(V1: XY, V2: Z, FMFSource: &I);
2135}
2136
2137Instruction *InstCombinerImpl::visitFAdd(BinaryOperator &I) {
2138 if (Value *V = simplifyFAddInst(LHS: I.getOperand(i_nocapture: 0), RHS: I.getOperand(i_nocapture: 1),
2139 FMF: I.getFastMathFlags(),
2140 Q: SQ.getWithInstruction(I: &I)))
2141 return replaceInstUsesWith(I, V);
2142
2143 if (SimplifyAssociativeOrCommutative(I))
2144 return &I;
2145
2146 if (Instruction *X = foldVectorBinop(Inst&: I))
2147 return X;
2148
2149 if (Instruction *Phi = foldBinopWithPhiOperands(BO&: I))
2150 return Phi;
2151
2152 if (Instruction *FoldedFAdd = foldBinOpIntoSelectOrPhi(I))
2153 return FoldedFAdd;
2154
2155 // B = fadd A, 0.0
2156 // Z = Op B
2157 // can be transformed into
2158 // Z = Op A
2159 // Where Op is such that we can ignore sign of 0 in fadd
2160 Value *A;
2161 if (match(V: &I, P: m_OneUse(SubPattern: m_FAdd(L: m_Value(V&: A), R: m_AnyZeroFP()))) &&
2162 canIgnoreSignBitOfZero(U: *I.use_begin()))
2163 return replaceInstUsesWith(I, V: A);
2164
2165 // (-X) + Y --> Y - X
2166 Value *X, *Y;
2167 if (match(V: &I, P: m_c_FAdd(L: m_FNeg(X: m_Value(V&: X)), R: m_Value(V&: Y))))
2168 return BinaryOperator::CreateFSubFMF(V1: Y, V2: X, FMFSource: &I);
2169
2170 // Similar to above, but look through fmul/fdiv for the negated term.
2171 // (-X * Y) + Z --> Z - (X * Y) [4 commuted variants]
2172 Value *Z;
2173 if (match(V: &I, P: m_c_FAdd(L: m_OneUse(SubPattern: m_c_FMul(L: m_FNeg(X: m_Value(V&: X)), R: m_Value(V&: Y))),
2174 R: m_Value(V&: Z)))) {
2175 Value *XY = Builder.CreateFMulFMF(L: X, R: Y, FMFSource: &I);
2176 return BinaryOperator::CreateFSubFMF(V1: Z, V2: XY, FMFSource: &I);
2177 }
2178 // (-X / Y) + Z --> Z - (X / Y) [2 commuted variants]
2179 // (X / -Y) + Z --> Z - (X / Y) [2 commuted variants]
2180 if (match(V: &I, P: m_c_FAdd(L: m_OneUse(SubPattern: m_FDiv(L: m_FNeg(X: m_Value(V&: X)), R: m_Value(V&: Y))),
2181 R: m_Value(V&: Z))) ||
2182 match(V: &I, P: m_c_FAdd(L: m_OneUse(SubPattern: m_FDiv(L: m_Value(V&: X), R: m_FNeg(X: m_Value(V&: Y)))),
2183 R: m_Value(V&: Z)))) {
2184 Value *XY = Builder.CreateFDivFMF(L: X, R: Y, FMFSource: &I);
2185 return BinaryOperator::CreateFSubFMF(V1: Z, V2: XY, FMFSource: &I);
2186 }
2187
2188 // Check for (fadd double (sitofp x), y), see if we can merge this into an
2189 // integer add followed by a promotion.
2190 if (Instruction *R = foldFBinOpOfIntCasts(I))
2191 return R;
2192
2193 Value *LHS = I.getOperand(i_nocapture: 0), *RHS = I.getOperand(i_nocapture: 1);
2194 // Handle specials cases for FAdd with selects feeding the operation
2195 if (Value *V = SimplifySelectsFeedingBinaryOp(I, LHS, RHS))
2196 return replaceInstUsesWith(I, V);
2197
2198 if (I.hasAllowReassoc() && I.hasNoSignedZeros()) {
2199 if (Instruction *F = factorizeFAddFSub(I, Builder))
2200 return F;
2201
2202 if (Instruction *F = foldSquareSumFP(I))
2203 return F;
2204
2205 // Try to fold fadd into start value of reduction intrinsic.
2206 if (match(V: &I, P: m_c_FAdd(L: m_OneUse(SubPattern: m_Intrinsic<Intrinsic::vector_reduce_fadd>(
2207 Ops: m_AnyZeroFP(), Ops: m_Value(V&: X))),
2208 R: m_Value(V&: Y)))) {
2209 // fadd (rdx 0.0, X), Y --> rdx Y, X
2210 return replaceInstUsesWith(
2211 I, V: Builder.CreateIntrinsic(ID: Intrinsic::vector_reduce_fadd,
2212 OverloadTypes: {X->getType()}, Args: {Y, X}, FMFSource: &I));
2213 }
2214 const APFloat *StartC, *C;
2215 if (match(V: LHS, P: m_OneUse(SubPattern: m_Intrinsic<Intrinsic::vector_reduce_fadd>(
2216 Ops: m_APFloat(Res&: StartC), Ops: m_Value(V&: X)))) &&
2217 match(V: RHS, P: m_APFloat(Res&: C))) {
2218 // fadd (rdx StartC, X), C --> rdx (C + StartC), X
2219 Constant *NewStartC = ConstantFP::get(Ty: I.getType(), V: *C + *StartC);
2220 return replaceInstUsesWith(
2221 I, V: Builder.CreateIntrinsic(ID: Intrinsic::vector_reduce_fadd,
2222 OverloadTypes: {X->getType()}, Args: {NewStartC, X}, FMFSource: &I));
2223 }
2224
2225 // (X * MulC) + X --> X * (MulC + 1.0)
2226 Constant *MulC;
2227 if (match(V: &I, P: m_c_FAdd(L: m_FMul(L: m_Value(V&: X), R: m_ImmConstant(C&: MulC)),
2228 R: m_Deferred(V: X)))) {
2229 if (Constant *NewMulC = ConstantFoldBinaryOpOperands(
2230 Opcode: Instruction::FAdd, LHS: MulC, RHS: ConstantFP::get(Ty: I.getType(), V: 1.0), DL))
2231 return BinaryOperator::CreateFMulFMF(V1: X, V2: NewMulC, FMFSource: &I);
2232 }
2233
2234 // (-X - Y) + (X + Z) --> Z - Y
2235 if (match(V: &I, P: m_c_FAdd(L: m_FSub(L: m_FNeg(X: m_Value(V&: X)), R: m_Value(V&: Y)),
2236 R: m_c_FAdd(L: m_Deferred(V: X), R: m_Value(V&: Z)))))
2237 return BinaryOperator::CreateFSubFMF(V1: Z, V2: Y, FMFSource: &I);
2238
2239 if (Value *V = FAddCombine(Builder).simplify(I: &I))
2240 return replaceInstUsesWith(I, V);
2241 }
2242
2243 // minumum(X, Y) + maximum(X, Y) => X + Y.
2244 if (match(V: &I,
2245 P: m_c_FAdd(L: m_Intrinsic<Intrinsic::maximum>(Ops: m_Value(V&: X), Ops: m_Value(V&: Y)),
2246 R: m_c_Intrinsic<Intrinsic::minimum>(Op0: m_Deferred(V: X),
2247 Op1: m_Deferred(V: Y))))) {
2248 BinaryOperator *Result = BinaryOperator::CreateFAddFMF(V1: X, V2: Y, FMFSource: &I);
2249 // We cannot preserve ninf if nnan flag is not set.
2250 // If X is NaN and Y is Inf then in original program we had NaN + NaN,
2251 // while in optimized version NaN + Inf and this is a poison with ninf flag.
2252 if (!Result->hasNoNaNs())
2253 Result->setHasNoInfs(false);
2254 return Result;
2255 }
2256
2257 return nullptr;
2258}
2259
2260CommonPointerBase CommonPointerBase::compute(Value *LHS, Value *RHS) {
2261 CommonPointerBase Base;
2262
2263 if (LHS->getType() != RHS->getType())
2264 return Base;
2265
2266 // Collect all base pointers of LHS.
2267 SmallPtrSet<Value *, 16> Ptrs;
2268 Value *Ptr = LHS;
2269 while (true) {
2270 Ptrs.insert(Ptr);
2271 if (auto *GEP = dyn_cast<GEPOperator>(Val: Ptr))
2272 Ptr = GEP->getPointerOperand();
2273 else
2274 break;
2275 }
2276
2277 // Find common base and collect RHS GEPs.
2278 bool First = true;
2279 while (true) {
2280 if (Ptrs.contains(Ptr: RHS)) {
2281 Base.Ptr = RHS;
2282 break;
2283 }
2284
2285 if (auto *GEP = dyn_cast<GEPOperator>(Val: RHS)) {
2286 Base.RHSGEPs.push_back(Elt: GEP);
2287 if (First) {
2288 First = false;
2289 Base.RHSNW = GEP->getNoWrapFlags();
2290 } else {
2291 Base.RHSNW = Base.RHSNW.intersectForOffsetAdd(Other: GEP->getNoWrapFlags());
2292 }
2293 RHS = GEP->getPointerOperand();
2294 } else {
2295 // No common base.
2296 return Base;
2297 }
2298 }
2299
2300 // Collect LHS GEPs.
2301 First = true;
2302 while (true) {
2303 if (LHS == Base.Ptr)
2304 break;
2305
2306 auto *GEP = cast<GEPOperator>(Val: LHS);
2307 Base.LHSGEPs.push_back(Elt: GEP);
2308 if (First) {
2309 First = false;
2310 Base.LHSNW = GEP->getNoWrapFlags();
2311 } else {
2312 Base.LHSNW = Base.LHSNW.intersectForOffsetAdd(Other: GEP->getNoWrapFlags());
2313 }
2314 LHS = GEP->getPointerOperand();
2315 }
2316
2317 return Base;
2318}
2319
2320bool CommonPointerBase::isExpensive() const {
2321 unsigned NumGEPs = 0;
2322 auto ProcessGEPs = [&NumGEPs](ArrayRef<GEPOperator *> GEPs) {
2323 bool SeenMultiUse = false;
2324 for (GEPOperator *GEP : GEPs) {
2325 // Only count multi-use GEPs, excluding the first one. For the first one,
2326 // we will directly reuse the offset. For one-use GEPs, their offset will
2327 // be folded into a multi-use GEP.
2328 if (!GEP->hasOneUse()) {
2329 if (SeenMultiUse)
2330 ++NumGEPs;
2331 SeenMultiUse = true;
2332 }
2333 }
2334 };
2335 ProcessGEPs(LHSGEPs);
2336 ProcessGEPs(RHSGEPs);
2337 return NumGEPs > 2;
2338}
2339
2340/// Optimize pointer differences into the same array into a size. Consider:
2341/// &A[10] - &A[0]: we should compile this to "10". LHS/RHS are the pointer
2342/// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
2343Value *InstCombinerImpl::OptimizePointerDifference(Value *LHS, Value *RHS,
2344 Type *Ty, bool IsNUW) {
2345 CommonPointerBase Base = CommonPointerBase::compute(LHS, RHS);
2346 if (!Base.Ptr || Base.isExpensive())
2347 return nullptr;
2348
2349 // To avoid duplicating the offset arithmetic, rewrite the GEP to use the
2350 // computed offset.
2351 // TODO: We should probably do this even if there is only one GEP.
2352 bool RewriteGEPs = !Base.LHSGEPs.empty() && !Base.RHSGEPs.empty();
2353
2354 Type *IdxTy = DL.getIndexType(PtrTy: LHS->getType());
2355 Value *Result = EmitGEPOffsets(GEPs: Base.LHSGEPs, NW: Base.LHSNW, IdxTy, RewriteGEPs);
2356 Value *Offset2 = EmitGEPOffsets(GEPs: Base.RHSGEPs, NW: Base.RHSNW, IdxTy, RewriteGEPs);
2357
2358 // If this is a single inbounds GEP and the original sub was nuw,
2359 // then the final multiplication is also nuw.
2360 if (auto *I = dyn_cast<OverflowingBinaryOperator>(Val: Result))
2361 if (IsNUW && match(V: Offset2, P: m_Zero()) && Base.LHSNW.isInBounds() &&
2362 (I->use_empty() || I->hasOneUse()) && I->hasNoSignedWrap() &&
2363 !I->hasNoUnsignedWrap() &&
2364 ((I->getOpcode() == Instruction::Mul &&
2365 match(V: I->getOperand(i_nocapture: 1), P: m_NonNegative())) ||
2366 I->getOpcode() == Instruction::Shl))
2367 cast<Instruction>(Val: I)->setHasNoUnsignedWrap();
2368
2369 // If we have a 2nd GEP of the same base pointer, subtract the offsets.
2370 // If both GEPs are inbounds, then the subtract does not have signed overflow.
2371 // If both GEPs are nuw and the original sub is nuw, the new sub is also nuw.
2372 if (!match(V: Offset2, P: m_Zero())) {
2373 Result =
2374 Builder.CreateSub(LHS: Result, RHS: Offset2, Name: "gepdiff",
2375 HasNUW: IsNUW && Base.LHSNW.hasNoUnsignedWrap() &&
2376 Base.RHSNW.hasNoUnsignedWrap(),
2377 HasNSW: Base.LHSNW.isInBounds() && Base.RHSNW.isInBounds());
2378 }
2379
2380 return Builder.CreateIntCast(V: Result, DestTy: Ty, isSigned: true);
2381}
2382
2383static Instruction *foldSubOfMinMax(BinaryOperator &I,
2384 InstCombiner::BuilderTy &Builder) {
2385 Value *Op0 = I.getOperand(i_nocapture: 0);
2386 Value *Op1 = I.getOperand(i_nocapture: 1);
2387 Type *Ty = I.getType();
2388 auto *MinMax = dyn_cast<MinMaxIntrinsic>(Val: Op1);
2389 if (!MinMax)
2390 return nullptr;
2391
2392 // sub(add(X,Y), s/umin(X,Y)) --> s/umax(X,Y)
2393 // sub(add(X,Y), s/umax(X,Y)) --> s/umin(X,Y)
2394 Value *X = MinMax->getLHS();
2395 Value *Y = MinMax->getRHS();
2396 if (match(V: Op0, P: m_c_Add(L: m_Specific(V: X), R: m_Specific(V: Y))) &&
2397 (Op0->hasOneUse() || Op1->hasOneUse())) {
2398 Intrinsic::ID InvID = getInverseMinMaxIntrinsic(MinMaxID: MinMax->getIntrinsicID());
2399 Function *F = Intrinsic::getOrInsertDeclaration(M: I.getModule(), id: InvID, OverloadTys: Ty);
2400 return CallInst::Create(Func: F, Args: {X, Y});
2401 }
2402
2403 // sub(add(X,Y),umin(Y,Z)) --> add(X,usub.sat(Y,Z))
2404 // sub(add(X,Z),umin(Y,Z)) --> add(X,usub.sat(Z,Y))
2405 Value *Z;
2406 if (match(V: Op1, P: m_OneUse(SubPattern: m_UMin(Op0: m_Value(V&: Y), Op1: m_Value(V&: Z))))) {
2407 if (match(V: Op0, P: m_OneUse(SubPattern: m_c_Add(L: m_Specific(V: Y), R: m_Value(V&: X))))) {
2408 Value *USub = Builder.CreateIntrinsic(ID: Intrinsic::usub_sat, OverloadTypes: Ty, Args: {Y, Z});
2409 return BinaryOperator::CreateAdd(V1: X, V2: USub);
2410 }
2411 if (match(V: Op0, P: m_OneUse(SubPattern: m_c_Add(L: m_Specific(V: Z), R: m_Value(V&: X))))) {
2412 Value *USub = Builder.CreateIntrinsic(ID: Intrinsic::usub_sat, OverloadTypes: Ty, Args: {Z, Y});
2413 return BinaryOperator::CreateAdd(V1: X, V2: USub);
2414 }
2415 }
2416
2417 // sub Op0, smin((sub nsw Op0, Z), 0) --> smax Op0, Z
2418 // sub Op0, smax((sub nsw Op0, Z), 0) --> smin Op0, Z
2419 if (MinMax->isSigned() && match(V: Y, P: m_ZeroInt()) &&
2420 match(V: X, P: m_NSWSub(L: m_Specific(V: Op0), R: m_Value(V&: Z)))) {
2421 Intrinsic::ID InvID = getInverseMinMaxIntrinsic(MinMaxID: MinMax->getIntrinsicID());
2422 Function *F = Intrinsic::getOrInsertDeclaration(M: I.getModule(), id: InvID, OverloadTys: Ty);
2423 return CallInst::Create(Func: F, Args: {Op0, Z});
2424 }
2425
2426 return nullptr;
2427}
2428
2429Instruction *InstCombinerImpl::visitSub(BinaryOperator &I) {
2430 if (Value *V = simplifySubInst(LHS: I.getOperand(i_nocapture: 0), RHS: I.getOperand(i_nocapture: 1),
2431 IsNSW: I.hasNoSignedWrap(), IsNUW: I.hasNoUnsignedWrap(),
2432 Q: SQ.getWithInstruction(I: &I)))
2433 return replaceInstUsesWith(I, V);
2434
2435 if (Instruction *X = foldVectorBinop(Inst&: I))
2436 return X;
2437
2438 if (Instruction *Phi = foldBinopWithPhiOperands(BO&: I))
2439 return Phi;
2440
2441 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
2442
2443 // If this is a 'B = x-(-A)', change to B = x+A.
2444 // We deal with this without involving Negator to preserve NSW flag.
2445 if (Value *V = dyn_castNegVal(V: Op1)) {
2446 BinaryOperator *Res = BinaryOperator::CreateAdd(V1: Op0, V2: V);
2447
2448 if (const auto *BO = dyn_cast<BinaryOperator>(Val: Op1)) {
2449 assert(BO->getOpcode() == Instruction::Sub &&
2450 "Expected a subtraction operator!");
2451 if (BO->hasNoSignedWrap() && I.hasNoSignedWrap())
2452 Res->setHasNoSignedWrap(true);
2453 } else {
2454 if (cast<Constant>(Val: Op1)->isNotMinSignedValue() && I.hasNoSignedWrap())
2455 Res->setHasNoSignedWrap(true);
2456 }
2457
2458 return Res;
2459 }
2460
2461 // Try this before Negator to preserve NSW flag.
2462 if (Instruction *R = factorizeMathWithShlOps(I, Builder))
2463 return R;
2464
2465 Constant *C;
2466 if (match(V: Op0, P: m_ImmConstant(C))) {
2467 Value *X;
2468 Constant *C2;
2469
2470 // C-(X+C2) --> (C-C2)-X
2471 if (match(V: Op1, P: m_AddLike(L: m_Value(V&: X), R: m_ImmConstant(C&: C2)))) {
2472 // C-C2 never overflow, and C-(X+C2), (X+C2) has NSW/NUW
2473 // => (C-C2)-X can have NSW/NUW
2474 bool WillNotSOV = willNotOverflowSignedSub(LHS: C, RHS: C2, CtxI: I);
2475 BinaryOperator *Res =
2476 BinaryOperator::CreateSub(V1: ConstantExpr::getSub(C1: C, C2), V2: X);
2477
2478 // or disjoint is equivalent to add nuw nsw.
2479 bool Op1NSW = true;
2480 bool Op1NUW = true;
2481
2482 if (auto *OBO1 = dyn_cast<OverflowingBinaryOperator>(Val: Op1)) {
2483 Op1NSW = OBO1->hasNoSignedWrap();
2484 Op1NUW = OBO1->hasNoUnsignedWrap();
2485 }
2486
2487 Res->setHasNoSignedWrap(I.hasNoSignedWrap() && Op1NSW && WillNotSOV);
2488 Res->setHasNoUnsignedWrap(I.hasNoUnsignedWrap() && Op1NUW);
2489 return Res;
2490 }
2491 }
2492
2493 auto TryToNarrowDeduceFlags = [this, &I, &Op0, &Op1]() -> Instruction * {
2494 if (Instruction *Ext = narrowMathIfNoOverflow(I))
2495 return Ext;
2496
2497 bool Changed = false;
2498 if (!I.hasNoSignedWrap() && willNotOverflowSignedSub(LHS: Op0, RHS: Op1, CtxI: I)) {
2499 Changed = true;
2500 I.setHasNoSignedWrap(true);
2501 }
2502 if (!I.hasNoUnsignedWrap() && willNotOverflowUnsignedSub(LHS: Op0, RHS: Op1, CtxI: I)) {
2503 Changed = true;
2504 I.setHasNoUnsignedWrap(true);
2505 }
2506
2507 return Changed ? &I : nullptr;
2508 };
2509
2510 // First, let's try to interpret `sub a, b` as `add a, (sub 0, b)`,
2511 // and let's try to sink `(sub 0, b)` into `b` itself. But only if this isn't
2512 // a pure negation used by a select that looks like abs/nabs.
2513 bool IsNegation = match(V: Op0, P: m_ZeroInt());
2514 if (!IsNegation || none_of(Range: I.users(), P: match_fn(P: m_c_Select(L: m_Specific(V: Op1),
2515 R: m_Specific(V: &I))))) {
2516 if (Value *NegOp1 = Negator::Negate(LHSIsZero: IsNegation, /* IsNSW */ IsNegation &&
2517 I.hasNoSignedWrap(),
2518 Root: Op1, IC&: *this))
2519 return BinaryOperator::CreateAdd(V1: NegOp1, V2: Op0);
2520 }
2521 if (IsNegation)
2522 return TryToNarrowDeduceFlags(); // Should have been handled in Negator!
2523
2524 // (A*B)-(A*C) -> A*(B-C) etc
2525 if (Value *V = foldUsingDistributiveLaws(I))
2526 return replaceInstUsesWith(I, V);
2527
2528 if (I.getType()->isIntOrIntVectorTy(BitWidth: 1))
2529 return BinaryOperator::CreateXor(V1: Op0, V2: Op1);
2530
2531 // Replace (-1 - A) with (~A).
2532 if (match(V: Op0, P: m_AllOnes()))
2533 return BinaryOperator::CreateNot(Op: Op1);
2534
2535 // (X + -1) - Y --> ~Y + X
2536 Value *X, *Y;
2537 if (match(V: Op0, P: m_OneUse(SubPattern: m_Add(L: m_Value(V&: X), R: m_AllOnes()))))
2538 return BinaryOperator::CreateAdd(V1: Builder.CreateNot(V: Op1), V2: X);
2539
2540 // if (C1 & C2) == C2 then (X & C1) - (X & C2) -> X & (C1 ^ C2)
2541 Constant *C1, *C2;
2542 if (match(V: Op0, P: m_And(L: m_Value(V&: X), R: m_ImmConstant(C&: C1))) &&
2543 match(V: Op1, P: m_And(L: m_Specific(V: X), R: m_ImmConstant(C&: C2)))) {
2544 Value *AndC = ConstantFoldBinaryInstruction(Opcode: Instruction::And, V1: C1, V2: C2);
2545 if (C2->isElementWiseEqual(Y: AndC))
2546 return BinaryOperator::CreateAnd(
2547 V1: X, V2: ConstantFoldBinaryInstruction(Opcode: Instruction::Xor, V1: C1, V2: C2));
2548 }
2549
2550 // Reassociate sub/add sequences to create more add instructions and
2551 // reduce dependency chains:
2552 // ((X - Y) + Z) - Op1 --> (X + Z) - (Y + Op1)
2553 Value *Z;
2554 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))),
2555 R: m_Value(V&: Z))))) {
2556 Value *XZ = Builder.CreateAdd(LHS: X, RHS: Z);
2557 Value *YW = Builder.CreateAdd(LHS: Y, RHS: Op1);
2558 return BinaryOperator::CreateSub(V1: XZ, V2: YW);
2559 }
2560
2561 // ((X - Y) - Op1) --> X - (Y + Op1)
2562 if (match(V: Op0, P: m_OneUse(SubPattern: m_Sub(L: m_Value(V&: X), R: m_Value(V&: Y))))) {
2563 OverflowingBinaryOperator *LHSSub = cast<OverflowingBinaryOperator>(Val: Op0);
2564 bool HasNUW = I.hasNoUnsignedWrap() && LHSSub->hasNoUnsignedWrap();
2565 bool HasNSW = HasNUW && I.hasNoSignedWrap() && LHSSub->hasNoSignedWrap();
2566 Value *Add = Builder.CreateAdd(LHS: Y, RHS: Op1, Name: "", /*HasNUW=*/HasNUW,
2567 /*HasNSW=*/HasNSW);
2568 BinaryOperator *Sub = BinaryOperator::CreateSub(V1: X, V2: Add);
2569 Sub->setHasNoUnsignedWrap(HasNUW);
2570 Sub->setHasNoSignedWrap(HasNSW);
2571 return Sub;
2572 }
2573
2574 // (X + C0) - (Y + C1) --> (X - Y) + (C0 - C1)
2575 {
2576 Constant *CX, *CY;
2577 if (match(V: Op0, P: m_OneUse(SubPattern: m_Add(L: m_Value(V&: X), R: m_ImmConstant(C&: CX)))) &&
2578 match(V: Op1, P: m_OneUse(SubPattern: m_Add(L: m_Value(V&: Y), R: m_ImmConstant(C&: CY))))) {
2579 Value *OpsSub = Builder.CreateSub(LHS: X, RHS: Y);
2580 Constant *ConstsSub = ConstantExpr::getSub(C1: CX, C2: CY);
2581 return BinaryOperator::CreateAdd(V1: OpsSub, V2: ConstsSub);
2582 }
2583 }
2584
2585 // (X + Z) - (Y + Z) --> (X - Y)
2586 {
2587 Value *W, *Z;
2588 if (match(V: Op0, P: m_AddLike(L: m_Value(V&: W), R: m_Value(V&: X))) &&
2589 match(V: Op1, P: m_AddLike(L: m_Value(V&: Y), R: m_Value(V&: Z)))) {
2590 Instruction *R = nullptr;
2591 if (W == Y)
2592 R = BinaryOperator::CreateSub(V1: X, V2: Z);
2593 else if (W == Z)
2594 R = BinaryOperator::CreateSub(V1: X, V2: Y);
2595 else if (X == Y)
2596 R = BinaryOperator::CreateSub(V1: W, V2: Z);
2597 else if (X == Z)
2598 R = BinaryOperator::CreateSub(V1: W, V2: Y);
2599 if (R) {
2600 bool NSW = I.hasNoSignedWrap() &&
2601 match(V: Op0, P: m_NSWAddLike(L: m_Value(), R: m_Value())) &&
2602 match(V: Op1, P: m_NSWAddLike(L: m_Value(), R: m_Value()));
2603
2604 bool NUW = I.hasNoUnsignedWrap() &&
2605 match(V: Op1, P: m_NUWAddLike(L: m_Value(), R: m_Value()));
2606 R->setHasNoSignedWrap(NSW);
2607 R->setHasNoUnsignedWrap(NUW);
2608 return R;
2609 }
2610 }
2611 }
2612
2613 // (~X) - (~Y) --> Y - X
2614 {
2615 // Need to ensure we can consume at least one of the `not` instructions,
2616 // otherwise this can inf loop.
2617 bool ConsumesOp0, ConsumesOp1;
2618 if (isFreeToInvert(V: Op0, WillInvertAllUses: Op0->hasOneUse(), DoesConsume&: ConsumesOp0) &&
2619 isFreeToInvert(V: Op1, WillInvertAllUses: Op1->hasOneUse(), DoesConsume&: ConsumesOp1) &&
2620 (ConsumesOp0 || ConsumesOp1)) {
2621 Value *NotOp0 = getFreelyInverted(V: Op0, WillInvertAllUses: Op0->hasOneUse(), Builder: &Builder);
2622 Value *NotOp1 = getFreelyInverted(V: Op1, WillInvertAllUses: Op1->hasOneUse(), Builder: &Builder);
2623 assert(NotOp0 != nullptr && NotOp1 != nullptr &&
2624 "isFreeToInvert desynced with getFreelyInverted");
2625 return BinaryOperator::CreateSub(V1: NotOp1, V2: NotOp0);
2626 }
2627 }
2628
2629 auto m_AddRdx = [](Value *&Vec) {
2630 return m_OneUse(SubPattern: m_Intrinsic<Intrinsic::vector_reduce_add>(Ops: m_Value(V&: Vec)));
2631 };
2632 Value *V0, *V1;
2633 if (match(V: Op0, P: m_AddRdx(V0)) && match(V: Op1, P: m_AddRdx(V1)) &&
2634 V0->getType() == V1->getType()) {
2635 // Difference of sums is sum of differences:
2636 // add_rdx(V0) - add_rdx(V1) --> add_rdx(V0 - V1)
2637 Value *Sub = Builder.CreateSub(LHS: V0, RHS: V1);
2638 Value *Rdx = Builder.CreateIntrinsic(ID: Intrinsic::vector_reduce_add,
2639 OverloadTypes: {Sub->getType()}, Args: {Sub});
2640 return replaceInstUsesWith(I, V: Rdx);
2641 }
2642
2643 if (Constant *C = dyn_cast<Constant>(Val: Op0)) {
2644 Value *X;
2645 if (match(V: Op1, P: m_ZExt(Op: m_Value(V&: X))) && X->getType()->isIntOrIntVectorTy(BitWidth: 1)) {
2646 // C - (zext bool) --> bool ? C - 1 : C
2647 SelectInst *SI = SelectInst::Create(C: X, S1: InstCombiner::SubOne(C), S2: C);
2648 // We know nothing about the distribution of the condition, so mark the
2649 // branch weights as unknown.
2650 setExplicitlyUnknownBranchWeightsIfProfiled(I&: *SI, DEBUG_TYPE, F: &F);
2651 return SI;
2652 }
2653 if (match(V: Op1, P: m_SExt(Op: m_Value(V&: X))) && X->getType()->isIntOrIntVectorTy(BitWidth: 1)) {
2654 // C - (sext bool) --> bool ? C + 1 : C
2655 SelectInst *SI = SelectInst::Create(C: X, S1: InstCombiner::AddOne(C), S2: C);
2656 // We know nothing about the distribution of the condition, so mark the
2657 // branch weights as unknown.
2658 setExplicitlyUnknownBranchWeightsIfProfiled(I&: *SI, DEBUG_TYPE, F: &F);
2659 return SI;
2660 }
2661
2662 // C - ~X == X + (1+C)
2663 if (match(V: Op1, P: m_Not(V: m_Value(V&: X))))
2664 return BinaryOperator::CreateAdd(V1: X, V2: InstCombiner::AddOne(C));
2665
2666 // Try to fold constant sub into select arguments.
2667 if (SelectInst *SI = dyn_cast<SelectInst>(Val: Op1))
2668 if (Instruction *R = FoldOpIntoSelect(Op&: I, SI))
2669 return R;
2670
2671 // Try to fold constant sub into PHI values.
2672 if (PHINode *PN = dyn_cast<PHINode>(Val: Op1))
2673 if (Instruction *R = foldOpIntoPhi(I, PN))
2674 return R;
2675
2676 Constant *C2;
2677
2678 // C-(C2-X) --> X+(C-C2)
2679 if (match(V: Op1, P: m_Sub(L: m_ImmConstant(C&: C2), R: m_Value(V&: X))))
2680 return BinaryOperator::CreateAdd(V1: X, V2: ConstantExpr::getSub(C1: C, C2));
2681 }
2682
2683 const APInt *Op0C;
2684 if (match(V: Op0, P: m_APInt(Res&: Op0C))) {
2685 if (Op0C->isMask()) {
2686 // Turn this into a xor if LHS is 2^n-1 and the remaining bits are known
2687 // zero. We don't use information from dominating conditions so this
2688 // transform is easier to reverse if necessary.
2689 KnownBits RHSKnown = llvm::computeKnownBits(
2690 V: Op1, Q: SQ.getWithInstruction(I: &I).getWithoutDomCondCache());
2691 if ((*Op0C | RHSKnown.Zero).isAllOnes())
2692 return BinaryOperator::CreateXor(V1: Op1, V2: Op0);
2693 }
2694
2695 // C - ((C3 -nuw X) & C2) --> (C - (C2 & C3)) + (X & C2) when:
2696 // (C3 - ((C2 & C3) - 1)) is pow2
2697 // ((C2 + C3) & ((C2 & C3) - 1)) == ((C2 & C3) - 1)
2698 // C2 is negative pow2 || sub nuw
2699 const APInt *C2, *C3;
2700 BinaryOperator *InnerSub;
2701 if (match(V: Op1, P: m_OneUse(SubPattern: m_And(L: m_BinOp(I&: InnerSub), R: m_APInt(Res&: C2)))) &&
2702 match(V: InnerSub, P: m_Sub(L: m_APInt(Res&: C3), R: m_Value(V&: X))) &&
2703 (InnerSub->hasNoUnsignedWrap() || C2->isNegatedPowerOf2())) {
2704 APInt C2AndC3 = *C2 & *C3;
2705 APInt C2AndC3Minus1 = C2AndC3 - 1;
2706 APInt C2AddC3 = *C2 + *C3;
2707 if ((*C3 - C2AndC3Minus1).isPowerOf2() &&
2708 C2AndC3Minus1.isSubsetOf(RHS: C2AddC3)) {
2709 Value *And = Builder.CreateAnd(LHS: X, RHS: ConstantInt::get(Ty: I.getType(), V: *C2));
2710 return BinaryOperator::CreateAdd(
2711 V1: And, V2: ConstantInt::get(Ty: I.getType(), V: *Op0C - C2AndC3));
2712 }
2713 }
2714 }
2715
2716 {
2717 Value *Y;
2718 // X-(X+Y) == -Y X-(Y+X) == -Y
2719 if (match(V: Op1, P: m_c_Add(L: m_Specific(V: Op0), R: m_Value(V&: Y))))
2720 return BinaryOperator::CreateNeg(Op: Y);
2721
2722 // (X-Y)-X == -Y
2723 if (match(V: Op0, P: m_Sub(L: m_Specific(V: Op1), R: m_Value(V&: Y))))
2724 return BinaryOperator::CreateNeg(Op: Y);
2725 }
2726
2727 // (sub (or A, B) (and A, B)) --> (xor A, B)
2728 {
2729 Value *A, *B;
2730 if (match(V: Op1, P: m_And(L: m_Value(V&: A), R: m_Value(V&: B))) &&
2731 match(V: Op0, P: m_c_Or(L: m_Specific(V: A), R: m_Specific(V: B))))
2732 return BinaryOperator::CreateXor(V1: A, V2: B);
2733 }
2734
2735 // (sub (add A, B) (or A, B)) --> (and A, B)
2736 {
2737 Value *A, *B;
2738 if (match(V: Op0, P: m_Add(L: m_Value(V&: A), R: m_Value(V&: B))) &&
2739 match(V: Op1, P: m_c_Or(L: m_Specific(V: A), R: m_Specific(V: B))))
2740 return BinaryOperator::CreateAnd(V1: A, V2: B);
2741 }
2742
2743 // (sub (add A, B) (and A, B)) --> (or A, B)
2744 {
2745 Value *A, *B;
2746 if (match(V: Op0, P: m_Add(L: m_Value(V&: A), R: m_Value(V&: B))) &&
2747 match(V: Op1, P: m_c_And(L: m_Specific(V: A), R: m_Specific(V: B))))
2748 return BinaryOperator::CreateOr(V1: A, V2: B);
2749 }
2750
2751 // (sub (and A, B) (or A, B)) --> neg (xor A, B)
2752 {
2753 Value *A, *B;
2754 if (match(V: Op0, P: m_And(L: m_Value(V&: A), R: m_Value(V&: B))) &&
2755 match(V: Op1, P: m_c_Or(L: m_Specific(V: A), R: m_Specific(V: B))) &&
2756 (Op0->hasOneUse() || Op1->hasOneUse()))
2757 return BinaryOperator::CreateNeg(Op: Builder.CreateXor(LHS: A, RHS: B));
2758 }
2759
2760 // (sub (or A, B), (xor A, B)) --> (and A, B)
2761 {
2762 Value *A, *B;
2763 if (match(V: Op1, P: m_Xor(L: m_Value(V&: A), R: m_Value(V&: B))) &&
2764 match(V: Op0, P: m_c_Or(L: m_Specific(V: A), R: m_Specific(V: B))))
2765 return BinaryOperator::CreateAnd(V1: A, V2: B);
2766 }
2767
2768 // (sub (xor A, B) (or A, B)) --> neg (and A, B)
2769 {
2770 Value *A, *B;
2771 if (match(V: Op0, P: m_Xor(L: m_Value(V&: A), R: m_Value(V&: B))) &&
2772 match(V: Op1, P: m_c_Or(L: m_Specific(V: A), R: m_Specific(V: B))) &&
2773 (Op0->hasOneUse() || Op1->hasOneUse()))
2774 return BinaryOperator::CreateNeg(Op: Builder.CreateAnd(LHS: A, RHS: B));
2775 }
2776
2777 {
2778 Value *Y;
2779 // ((X | Y) - X) --> (~X & Y)
2780 if (match(V: Op0, P: m_OneUse(SubPattern: m_c_Or(L: m_Value(V&: Y), R: m_Specific(V: Op1)))))
2781 return BinaryOperator::CreateAnd(
2782 V1: Y, V2: Builder.CreateNot(V: Op1, Name: Op1->getName() + ".not"));
2783 }
2784
2785 {
2786 // (sub (and Op1, (neg X)), Op1) --> neg (and Op1, (add X, -1))
2787 Value *X;
2788 if (match(V: Op0, P: m_OneUse(SubPattern: m_c_And(L: m_Specific(V: Op1),
2789 R: m_OneUse(SubPattern: m_Neg(V: m_Value(V&: X))))))) {
2790 return BinaryOperator::CreateNeg(Op: Builder.CreateAnd(
2791 LHS: Op1, RHS: Builder.CreateAdd(LHS: X, RHS: Constant::getAllOnesValue(Ty: I.getType()))));
2792 }
2793 }
2794
2795 {
2796 // (sub (and Op1, C), Op1) --> neg (and Op1, ~C)
2797 Constant *C;
2798 if (match(V: Op0, P: m_OneUse(SubPattern: m_And(L: m_Specific(V: Op1), R: m_Constant(C))))) {
2799 return BinaryOperator::CreateNeg(
2800 Op: Builder.CreateAnd(LHS: Op1, RHS: Builder.CreateNot(V: C)));
2801 }
2802 }
2803
2804 {
2805 // (sub (xor X, (sext C)), (sext C)) => (select C, (neg X), X)
2806 // (sub (sext C), (xor X, (sext C))) => (select C, X, (neg X))
2807 Value *C, *X;
2808 auto m_SubXorCmp = [&C, &X](Value *LHS, Value *RHS) {
2809 return match(V: LHS, P: m_OneUse(SubPattern: m_c_Xor(L: m_Value(V&: X), R: m_Specific(V: RHS)))) &&
2810 match(V: RHS, P: m_SExt(Op: m_Value(V&: C))) &&
2811 (C->getType()->getScalarSizeInBits() == 1);
2812 };
2813 if (m_SubXorCmp(Op0, Op1))
2814 return createSelectInstWithUnknownProfile(C, S1: Builder.CreateNeg(V: X), S2: X);
2815 if (m_SubXorCmp(Op1, Op0))
2816 return createSelectInstWithUnknownProfile(C, S1: X, S2: Builder.CreateNeg(V: X));
2817 }
2818
2819 if (Instruction *R = tryFoldInstWithCtpopWithNot(I: &I))
2820 return R;
2821
2822 if (Instruction *R = foldSubOfMinMax(I, Builder))
2823 return R;
2824
2825 {
2826 // If we have a subtraction between some value and a select between
2827 // said value and something else, sink subtraction into select hands, i.e.:
2828 // sub (select %Cond, %TrueVal, %FalseVal), %Op1
2829 // ->
2830 // select %Cond, (sub %TrueVal, %Op1), (sub %FalseVal, %Op1)
2831 // or
2832 // sub %Op0, (select %Cond, %TrueVal, %FalseVal)
2833 // ->
2834 // select %Cond, (sub %Op0, %TrueVal), (sub %Op0, %FalseVal)
2835 // This will result in select between new subtraction and 0.
2836 auto SinkSubIntoSelect =
2837 [Ty = I.getType()](Value *Select, Value *OtherHandOfSub,
2838 auto SubBuilder) -> Instruction * {
2839 Value *Cond, *TrueVal, *FalseVal;
2840 if (!match(V: Select, P: m_OneUse(SubPattern: m_Select(C: m_Value(V&: Cond), L: m_Value(V&: TrueVal),
2841 R: m_Value(V&: FalseVal)))))
2842 return nullptr;
2843 if (OtherHandOfSub != TrueVal && OtherHandOfSub != FalseVal)
2844 return nullptr;
2845 // While it is really tempting to just create two subtractions and let
2846 // InstCombine fold one of those to 0, it isn't possible to do so
2847 // because of worklist visitation order. So ugly it is.
2848 bool OtherHandOfSubIsTrueVal = OtherHandOfSub == TrueVal;
2849 Value *NewSub = SubBuilder(OtherHandOfSubIsTrueVal ? FalseVal : TrueVal);
2850 Constant *Zero = Constant::getNullValue(Ty);
2851 SelectInst *NewSel =
2852 SelectInst::Create(C: Cond, S1: OtherHandOfSubIsTrueVal ? Zero : NewSub,
2853 S2: OtherHandOfSubIsTrueVal ? NewSub : Zero);
2854 // Preserve prof metadata if any.
2855 NewSel->copyMetadata(SrcInst: cast<Instruction>(Val&: *Select));
2856 return NewSel;
2857 };
2858 if (Instruction *NewSel = SinkSubIntoSelect(
2859 /*Select=*/Op0, /*OtherHandOfSub=*/Op1,
2860 [Builder = &Builder, Op1](Value *OtherHandOfSelect) {
2861 return Builder->CreateSub(LHS: OtherHandOfSelect,
2862 /*OtherHandOfSub=*/RHS: Op1);
2863 }))
2864 return NewSel;
2865 if (Instruction *NewSel = SinkSubIntoSelect(
2866 /*Select=*/Op1, /*OtherHandOfSub=*/Op0,
2867 [Builder = &Builder, Op0](Value *OtherHandOfSelect) {
2868 return Builder->CreateSub(/*OtherHandOfSub=*/LHS: Op0,
2869 RHS: OtherHandOfSelect);
2870 }))
2871 return NewSel;
2872 }
2873
2874 // (X - (X & Y)) --> (X & ~Y)
2875 if (match(V: Op1, P: m_c_And(L: m_Specific(V: Op0), R: m_Value(V&: Y))) &&
2876 (Op1->hasOneUse() || isa<Constant>(Val: Y)))
2877 return BinaryOperator::CreateAnd(
2878 V1: Op0, V2: Builder.CreateNot(V: Y, Name: Y->getName() + ".not"));
2879
2880 // ~X - Min/Max(~X, Y) -> ~Min/Max(X, ~Y) - X
2881 // ~X - Min/Max(Y, ~X) -> ~Min/Max(X, ~Y) - X
2882 // Min/Max(~X, Y) - ~X -> X - ~Min/Max(X, ~Y)
2883 // Min/Max(Y, ~X) - ~X -> X - ~Min/Max(X, ~Y)
2884 // As long as Y is freely invertible, this will be neutral or a win.
2885 // Note: We don't generate the inverse max/min, just create the 'not' of
2886 // it and let other folds do the rest.
2887 if (match(V: Op0, P: m_Not(V: m_Value(V&: X))) &&
2888 match(V: Op1, P: m_c_MaxOrMin(L: m_Specific(V: Op0), R: m_Value(V&: Y))) &&
2889 !Op0->hasNUsesOrMore(N: 3) && isFreeToInvert(V: Y, WillInvertAllUses: Y->hasOneUse())) {
2890 Value *Not = Builder.CreateNot(V: Op1);
2891 return BinaryOperator::CreateSub(V1: Not, V2: X);
2892 }
2893 if (match(V: Op1, P: m_Not(V: m_Value(V&: X))) &&
2894 match(V: Op0, P: m_c_MaxOrMin(L: m_Specific(V: Op1), R: m_Value(V&: Y))) &&
2895 !Op1->hasNUsesOrMore(N: 3) && isFreeToInvert(V: Y, WillInvertAllUses: Y->hasOneUse())) {
2896 Value *Not = Builder.CreateNot(V: Op0);
2897 return BinaryOperator::CreateSub(V1: X, V2: Not);
2898 }
2899
2900 // min(X+1, Y) - min(X, Y) --> zext X < Y
2901 // Replacing a sub and at least one min with an icmp
2902 // and a zext is a potential improvement.
2903 if (match(V: Op0, P: m_c_SMin(L: m_NSWAddLike(L: m_Value(V&: X), R: m_One()), R: m_Value(V&: Y))) &&
2904 match(V: Op1, P: m_c_SMin(L: m_Specific(V: X), R: m_Specific(V: Y))) &&
2905 I.getType()->getScalarSizeInBits() != 1 &&
2906 (Op0->hasOneUse() || Op1->hasOneUse())) {
2907 Value *Cond = Builder.CreateICmpSLT(LHS: X, RHS: Y);
2908 return new ZExtInst(Cond, I.getType());
2909 }
2910 if (match(V: Op0, P: m_c_UMin(L: m_NUWAddLike(L: m_Value(V&: X), R: m_One()), R: m_Value(V&: Y))) &&
2911 match(V: Op1, P: m_c_UMin(L: m_Specific(V: X), R: m_Specific(V: Y))) &&
2912 I.getType()->getScalarSizeInBits() != 1 &&
2913 (Op0->hasOneUse() || Op1->hasOneUse())) {
2914 Value *Cond = Builder.CreateICmpULT(LHS: X, RHS: Y);
2915 return new ZExtInst(Cond, I.getType());
2916 }
2917
2918 // Optimize pointer differences into the same array into a size. Consider:
2919 // &A[10] - &A[0]: we should compile this to "10".
2920 Value *LHSOp, *RHSOp;
2921 if (match(V: Op0, P: m_PtrToIntOrAddr(Op: m_Value(V&: LHSOp))) &&
2922 match(V: Op1, P: m_PtrToIntOrAddr(Op: m_Value(V&: RHSOp))))
2923 if (Value *Res = OptimizePointerDifference(LHS: LHSOp, RHS: RHSOp, Ty: I.getType(),
2924 IsNUW: I.hasNoUnsignedWrap()))
2925 return replaceInstUsesWith(I, V: Res);
2926
2927 // trunc(p)-trunc(q) -> trunc(p-q)
2928 if (match(V: Op0, P: m_Trunc(Op: m_PtrToIntOrAddr(Op: m_Value(V&: LHSOp)))) &&
2929 match(V: Op1, P: m_Trunc(Op: m_PtrToIntOrAddr(Op: m_Value(V&: RHSOp)))))
2930 if (Value *Res = OptimizePointerDifference(LHS: LHSOp, RHS: RHSOp, Ty: I.getType(),
2931 /* IsNUW */ false))
2932 return replaceInstUsesWith(I, V: Res);
2933
2934 auto MatchSubOfZExtOfPtrToIntOrAddr = [&]() {
2935 if (match(V: Op0, P: m_ZExt(Op: m_PtrToIntSameSize(DL, Op: m_Value(V&: LHSOp)))) &&
2936 match(V: Op1, P: m_ZExt(Op: m_PtrToIntSameSize(DL, Op: m_Value(V&: RHSOp)))))
2937 return true;
2938 if (match(V: Op0, P: m_ZExt(Op: m_PtrToAddr(Op: m_Value(V&: LHSOp)))) &&
2939 match(V: Op1, P: m_ZExt(Op: m_PtrToAddr(Op: m_Value(V&: RHSOp)))))
2940 return true;
2941 // Special case for non-canonical ptrtoint in constant expression,
2942 // where the zext has been folded into the ptrtoint.
2943 if (match(V: Op0, P: m_ZExt(Op: m_PtrToIntSameSize(DL, Op: m_Value(V&: LHSOp)))) &&
2944 match(V: Op1, P: m_PtrToInt(Op: m_Value(V&: RHSOp))))
2945 return true;
2946 return false;
2947 };
2948 if (MatchSubOfZExtOfPtrToIntOrAddr()) {
2949 if (auto *GEP = dyn_cast<GEPOperator>(Val: LHSOp)) {
2950 if (GEP->getPointerOperand() == RHSOp) {
2951 if (GEP->hasNoUnsignedWrap() || GEP->hasNoUnsignedSignedWrap()) {
2952 Value *Offset = EmitGEPOffset(GEP);
2953 Value *Res = GEP->hasNoUnsignedWrap()
2954 ? Builder.CreateZExt(
2955 V: Offset, DestTy: I.getType(), Name: "",
2956 /*IsNonNeg=*/GEP->hasNoUnsignedSignedWrap())
2957 : Builder.CreateSExt(V: Offset, DestTy: I.getType());
2958 return replaceInstUsesWith(I, V: Res);
2959 }
2960 }
2961 }
2962 }
2963
2964 // Canonicalize a shifty way to code absolute value to the common pattern.
2965 // There are 2 potential commuted variants.
2966 // We're relying on the fact that we only do this transform when the shift has
2967 // exactly 2 uses and the xor has exactly 1 use (otherwise, we might increase
2968 // instructions).
2969 Value *A;
2970 const APInt *ShAmt;
2971 Type *Ty = I.getType();
2972 unsigned BitWidth = Ty->getScalarSizeInBits();
2973 if (match(V: Op1, P: m_AShr(L: m_Value(V&: A), R: m_APInt(Res&: ShAmt))) &&
2974 Op1->hasNUses(N: 2) && *ShAmt == BitWidth - 1 &&
2975 match(V: Op0, P: m_OneUse(SubPattern: m_c_Xor(L: m_Specific(V: A), R: m_Specific(V: Op1))))) {
2976 // B = ashr i32 A, 31 ; smear the sign bit
2977 // sub (xor A, B), B ; flip bits if negative and subtract -1 (add 1)
2978 // --> (A < 0) ? -A : A
2979 Value *IsNeg = Builder.CreateIsNeg(Arg: A);
2980 // Copy the nsw flags from the sub to the negate.
2981 Value *NegA = I.hasNoUnsignedWrap()
2982 ? Constant::getNullValue(Ty: A->getType())
2983 : Builder.CreateNeg(V: A, Name: "", HasNSW: I.hasNoSignedWrap());
2984 return SelectInst::Create(C: IsNeg, S1: NegA, S2: A);
2985 }
2986
2987 // If we are subtracting a low-bit masked subset of some value from an add
2988 // of that same value with no low bits changed, that is clearing some low bits
2989 // of the sum:
2990 // sub (X + AddC), (X & AndC) --> and (X + AddC), ~AndC
2991 const APInt *AddC, *AndC;
2992 if (match(V: Op0, P: m_Add(L: m_Value(V&: X), R: m_APInt(Res&: AddC))) &&
2993 match(V: Op1, P: m_And(L: m_Specific(V: X), R: m_APInt(Res&: AndC)))) {
2994 unsigned Cttz = AddC->countr_zero();
2995 APInt HighMask(APInt::getHighBitsSet(numBits: BitWidth, hiBitsSet: BitWidth - Cttz));
2996 if ((HighMask & *AndC).isZero())
2997 return BinaryOperator::CreateAnd(V1: Op0, V2: ConstantInt::get(Ty, V: ~(*AndC)));
2998 }
2999
3000 if (Instruction *V =
3001 canonicalizeCondSignextOfHighBitExtractToSignextHighBitExtract(I))
3002 return V;
3003
3004 // X - usub.sat(X, Y) => umin(X, Y)
3005 if (match(V: Op1, P: m_OneUse(SubPattern: m_Intrinsic<Intrinsic::usub_sat>(Ops: m_Specific(V: Op0),
3006 Ops: m_Value(V&: Y)))))
3007 return replaceInstUsesWith(
3008 I, V: Builder.CreateIntrinsic(ID: Intrinsic::umin, OverloadTypes: {I.getType()}, Args: {Op0, Y}));
3009
3010 // umax(X, Op1) - Op1 --> usub.sat(X, Op1)
3011 // TODO: The one-use restriction is not strictly necessary, but it may
3012 // require improving other pattern matching and/or codegen.
3013 if (match(V: Op0, P: m_OneUse(SubPattern: m_c_UMax(L: m_Value(V&: X), R: m_Specific(V: Op1)))))
3014 return replaceInstUsesWith(
3015 I, V: Builder.CreateIntrinsic(ID: Intrinsic::usub_sat, OverloadTypes: {Ty}, Args: {X, Op1}));
3016
3017 // Op0 - umin(X, Op0) --> usub.sat(Op0, X)
3018 if (match(V: Op1, P: m_OneUse(SubPattern: m_c_UMin(L: m_Value(V&: X), R: m_Specific(V: Op0)))))
3019 return replaceInstUsesWith(
3020 I, V: Builder.CreateIntrinsic(ID: Intrinsic::usub_sat, OverloadTypes: {Ty}, Args: {Op0, X}));
3021
3022 // Op0 - umax(X, Op0) --> 0 - usub.sat(X, Op0)
3023 if (match(V: Op1, P: m_OneUse(SubPattern: m_c_UMax(L: m_Value(V&: X), R: m_Specific(V: Op0))))) {
3024 Value *USub = Builder.CreateIntrinsic(ID: Intrinsic::usub_sat, OverloadTypes: {Ty}, Args: {X, Op0});
3025 return BinaryOperator::CreateNeg(Op: USub);
3026 }
3027
3028 // umin(X, Op1) - Op1 --> 0 - usub.sat(Op1, X)
3029 if (match(V: Op0, P: m_OneUse(SubPattern: m_c_UMin(L: m_Value(V&: X), R: m_Specific(V: Op1))))) {
3030 Value *USub = Builder.CreateIntrinsic(ID: Intrinsic::usub_sat, OverloadTypes: {Ty}, Args: {Op1, X});
3031 return BinaryOperator::CreateNeg(Op: USub);
3032 }
3033
3034 // C - ctpop(X) => ctpop(~X) if C is bitwidth
3035 if (match(V: Op0, P: m_SpecificInt(V: BitWidth)) &&
3036 match(V: Op1, P: m_OneUse(SubPattern: m_Ctpop(Op0: m_Value(V&: X)))))
3037 return replaceInstUsesWith(
3038 I, V: Builder.CreateIntrinsic(ID: Intrinsic::ctpop, OverloadTypes: {I.getType()},
3039 Args: {Builder.CreateNot(V: X)}));
3040
3041 // Reduce multiplies for difference-of-squares by factoring:
3042 // (X * X) - (Y * Y) --> (X + Y) * (X - Y)
3043 if (match(V: Op0, P: m_OneUse(SubPattern: m_Mul(L: m_Value(V&: X), R: m_Deferred(V: X)))) &&
3044 match(V: Op1, P: m_OneUse(SubPattern: m_Mul(L: m_Value(V&: Y), R: m_Deferred(V: Y))))) {
3045 auto *OBO0 = cast<OverflowingBinaryOperator>(Val: Op0);
3046 auto *OBO1 = cast<OverflowingBinaryOperator>(Val: Op1);
3047 bool PropagateNSW = I.hasNoSignedWrap() && OBO0->hasNoSignedWrap() &&
3048 OBO1->hasNoSignedWrap() && BitWidth > 2;
3049 bool PropagateNUW = I.hasNoUnsignedWrap() && OBO0->hasNoUnsignedWrap() &&
3050 OBO1->hasNoUnsignedWrap() && BitWidth > 1;
3051 Value *Add = Builder.CreateAdd(LHS: X, RHS: Y, Name: "add", HasNUW: PropagateNUW, HasNSW: PropagateNSW);
3052 Value *Sub = Builder.CreateSub(LHS: X, RHS: Y, Name: "sub", HasNUW: PropagateNUW, HasNSW: PropagateNSW);
3053 Value *Mul = Builder.CreateMul(LHS: Add, RHS: Sub, Name: "", HasNUW: PropagateNUW, HasNSW: PropagateNSW);
3054 return replaceInstUsesWith(I, V: Mul);
3055 }
3056
3057 // max(X,Y) nsw/nuw - min(X,Y) --> abs(X nsw - Y)
3058 if (match(V: Op0, P: m_OneUse(SubPattern: m_c_SMax(L: m_Value(V&: X), R: m_Value(V&: Y)))) &&
3059 match(V: Op1, P: m_OneUse(SubPattern: m_c_SMin(L: m_Specific(V: X), R: m_Specific(V: Y))))) {
3060 if (I.hasNoUnsignedWrap() || I.hasNoSignedWrap()) {
3061 Value *Sub =
3062 Builder.CreateSub(LHS: X, RHS: Y, Name: "sub", /*HasNUW=*/false, /*HasNSW=*/true);
3063 Value *Call =
3064 Builder.CreateBinaryIntrinsic(ID: Intrinsic::abs, LHS: Sub, RHS: Builder.getTrue());
3065 return replaceInstUsesWith(I, V: Call);
3066 }
3067 }
3068
3069 if (Instruction *Res = foldBinOpOfSelectAndCastOfSelectCondition(I))
3070 return Res;
3071
3072 // (sub (sext (add nsw (X, Y)), sext (X))) --> (sext (Y))
3073 if (match(V: Op1, P: m_SExtLike(Op: m_Value(V&: X))) &&
3074 match(V: Op0, P: m_SExtLike(Op: m_c_NSWAdd(L: m_Specific(V: X), R: m_Value(V&: Y))))) {
3075 Value *SExtY = Builder.CreateSExt(V: Y, DestTy: I.getType());
3076 return replaceInstUsesWith(I, V: SExtY);
3077 }
3078
3079 // (sub[ nsw] (sext (add nsw (X, Y)), sext (add nsw (X, Z)))) -->
3080 // --> (sub[ nsw] (sext (Y), sext (Z)))
3081 {
3082 Value *Z, *Add0, *Add1;
3083 if (match(V: Op0, P: m_SExtLike(Op: m_Value(V&: Add0))) &&
3084 match(V: Op1, P: m_SExtLike(Op: m_Value(V&: Add1))) &&
3085 ((match(V: Add0, P: m_NSWAdd(L: m_Value(V&: X), R: m_Value(V&: Y))) &&
3086 match(V: Add1, P: m_c_NSWAdd(L: m_Specific(V: X), R: m_Value(V&: Z)))) ||
3087 (match(V: Add0, P: m_NSWAdd(L: m_Value(V&: Y), R: m_Value(V&: X))) &&
3088 match(V: Add1, P: m_c_NSWAdd(L: m_Specific(V: X), R: m_Value(V&: Z)))))) {
3089 unsigned NumOfNewInstrs = 0;
3090 // Non-constant Y, Z require new SExt.
3091 NumOfNewInstrs += !isa<Constant>(Val: Y) ? 1 : 0;
3092 NumOfNewInstrs += !isa<Constant>(Val: Z) ? 1 : 0;
3093 // Check if we can trade some of the old instructions for the new ones.
3094 unsigned NumOfDeadInstrs = 0;
3095 if (Op0->hasOneUse()) {
3096 // If Op0 (sext) has multiple uses, then we keep it
3097 // and the add that it uses, otherwise, we can remove
3098 // the sext and probably the add (depending on the number of its uses).
3099 ++NumOfDeadInstrs;
3100 NumOfDeadInstrs += Add0->hasOneUse() ? 1 : 0;
3101 }
3102 if (Op1->hasOneUse()) {
3103 ++NumOfDeadInstrs;
3104 NumOfDeadInstrs += Add1->hasOneUse() ? 1 : 0;
3105 }
3106 if (NumOfDeadInstrs >= NumOfNewInstrs) {
3107 Value *SExtY = Builder.CreateSExt(V: Y, DestTy: I.getType());
3108 Value *SExtZ = Builder.CreateSExt(V: Z, DestTy: I.getType());
3109 Value *Sub = Builder.CreateSub(LHS: SExtY, RHS: SExtZ, Name: "",
3110 /*HasNUW=*/false,
3111 /*HasNSW=*/I.hasNoSignedWrap());
3112 return replaceInstUsesWith(I, V: Sub);
3113 }
3114 }
3115 }
3116
3117 return TryToNarrowDeduceFlags();
3118}
3119
3120/// This eliminates floating-point negation in either 'fneg(X)' or
3121/// 'fsub(-0.0, X)' form by combining into a constant operand.
3122static Instruction *foldFNegIntoConstant(Instruction &I, const DataLayout &DL) {
3123 // This is limited with one-use because fneg is assumed better for
3124 // reassociation and cheaper in codegen than fmul/fdiv.
3125 // TODO: Should the m_OneUse restriction be removed?
3126 Instruction *FNegOp;
3127 if (!match(V: &I, P: m_FNeg(X: m_OneUse(SubPattern: m_Instruction(I&: FNegOp)))))
3128 return nullptr;
3129
3130 Value *X;
3131 Constant *C;
3132
3133 // Fold negation into constant operand.
3134 // -(X * C) --> X * (-C)
3135 if (match(V: FNegOp, P: m_FMul(L: m_Value(V&: X), R: m_Constant(C))))
3136 if (Constant *NegC = ConstantFoldUnaryOpOperand(Opcode: Instruction::FNeg, Op: C, DL)) {
3137 FastMathFlags FNegF = I.getFastMathFlags();
3138 FastMathFlags OpF = FNegOp->getFastMathFlags();
3139 FastMathFlags FMF = FastMathFlags::unionValue(LHS: FNegF, RHS: OpF) |
3140 FastMathFlags::intersectRewrite(LHS: FNegF, RHS: OpF);
3141 FMF.setNoInfs(FNegF.noInfs() && OpF.noInfs());
3142 return BinaryOperator::CreateFMulFMF(V1: X, V2: NegC, FMF);
3143 }
3144 // -(X / C) --> X / (-C)
3145 if (match(V: FNegOp, P: m_FDiv(L: m_Value(V&: X), R: m_Constant(C)))) {
3146 if (Constant *NegC = ConstantFoldUnaryOpOperand(Opcode: Instruction::FNeg, Op: C, DL)) {
3147 Instruction *FDiv = BinaryOperator::CreateFDivFMF(V1: X, V2: NegC, FMFSource: &I);
3148
3149 // Intersect 'nsz' and 'ninf' because those special value exceptions may
3150 // not apply to the fdiv. Everything else propagates from the fneg.
3151 FastMathFlags FMF = I.getFastMathFlags();
3152 FastMathFlags OpFMF = FNegOp->getFastMathFlags();
3153 FDiv->setHasNoSignedZeros(FMF.noSignedZeros() && OpFMF.noSignedZeros());
3154 FDiv->setHasNoInfs(FMF.noInfs() && OpFMF.noInfs());
3155 FDiv->copyMetadata(SrcInst: *FNegOp);
3156 return FDiv;
3157 }
3158 }
3159 // -(C / X) --> (-C) / X
3160 if (match(V: FNegOp, P: m_FDiv(L: m_Constant(C), R: m_Value(V&: X))))
3161 if (Constant *NegC = ConstantFoldUnaryOpOperand(Opcode: Instruction::FNeg, Op: C, DL)) {
3162 Instruction *FDiv = BinaryOperator::CreateFDivFMF(V1: NegC, V2: X, FMFSource: &I);
3163
3164 // Intersect 'nsz' and 'ninf' because those special value exceptions may
3165 // not apply to the fdiv. Everything else propagates from the fneg.
3166 // TODO: We could propagate nsz/ninf from fdiv alone?
3167 FastMathFlags FMF = I.getFastMathFlags();
3168 FastMathFlags OpFMF = FNegOp->getFastMathFlags();
3169 FDiv->setHasNoSignedZeros(FMF.noSignedZeros() && OpFMF.noSignedZeros());
3170 FDiv->setHasNoInfs(FMF.noInfs() && OpFMF.noInfs());
3171 FDiv->copyMetadata(SrcInst: *FNegOp);
3172 return FDiv;
3173 }
3174 // With NSZ [ counter-example with -0.0: -(-0.0 + 0.0) != 0.0 + -0.0 ]:
3175 // -(X + C) --> -X + -C --> -C - X
3176 if (I.hasNoSignedZeros() && match(V: FNegOp, P: m_FAdd(L: m_Value(V&: X), R: m_Constant(C))))
3177 if (Constant *NegC = ConstantFoldUnaryOpOperand(Opcode: Instruction::FNeg, Op: C, DL))
3178 return BinaryOperator::CreateFSubFMF(V1: NegC, V2: X, FMFSource: &I);
3179
3180 return nullptr;
3181}
3182
3183Instruction *InstCombinerImpl::hoistFNegAboveFMulFDiv(Value *FNegOp,
3184 Instruction &FMFSource) {
3185 Value *X, *Y;
3186 if (match(V: FNegOp, P: m_FMul(L: m_Value(V&: X), R: m_Value(V&: Y)))) {
3187 // Push into RHS which is more likely to simplify (const or another fneg).
3188 // FIXME: It would be better to invert the transform.
3189 return cast<Instruction>(Val: Builder.CreateFMulFMF(
3190 L: X, R: Builder.CreateFNegFMF(V: Y, FMFSource: &FMFSource), FMFSource: &FMFSource));
3191 }
3192
3193 if (match(V: FNegOp, P: m_FDiv(L: m_Value(V&: X), R: m_Value(V&: Y)))) {
3194 auto *FDiv = cast<Instruction>(Val: Builder.CreateFDivFMF(
3195 L: Builder.CreateFNegFMF(V: X, FMFSource: &FMFSource), R: Y, FMFSource: &FMFSource));
3196 FDiv->copyMetadata(SrcInst: *cast<Instruction>(Val: FNegOp));
3197 return FDiv;
3198 }
3199
3200 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Val: FNegOp)) {
3201 // Make sure to preserve flags and metadata on the call.
3202 if (II->getIntrinsicID() == Intrinsic::ldexp) {
3203 FastMathFlags FMF = FMFSource.getFastMathFlags() | II->getFastMathFlags();
3204 CallInst *New =
3205 Builder.CreateCall(Callee: II->getCalledFunction(),
3206 Args: {Builder.CreateFNegFMF(V: II->getArgOperand(i: 0), FMFSource: FMF),
3207 II->getArgOperand(i: 1)});
3208 New->setFastMathFlags(FMF);
3209 New->copyMetadata(SrcInst: *II);
3210 return New;
3211 }
3212 }
3213
3214 return nullptr;
3215}
3216
3217Instruction *InstCombinerImpl::visitFNeg(UnaryOperator &I) {
3218 Value *Op = I.getOperand(i_nocapture: 0);
3219
3220 if (Value *V = simplifyFNegInst(Op, FMF: I.getFastMathFlags(),
3221 Q: getSimplifyQuery().getWithInstruction(I: &I)))
3222 return replaceInstUsesWith(I, V);
3223
3224 if (Instruction *X = foldFNegIntoConstant(I, DL))
3225 return X;
3226
3227 Value *X, *Y;
3228
3229 // If we can ignore the sign of zeros: -(X - Y) --> (Y - X)
3230 if (I.hasNoSignedZeros() &&
3231 match(V: Op, P: m_OneUse(SubPattern: m_FSub(L: m_Value(V&: X), R: m_Value(V&: Y)))))
3232 return BinaryOperator::CreateFSubFMF(V1: Y, V2: X, FMFSource: &I);
3233
3234 Value *OneUse;
3235 if (!match(V: Op, P: m_OneUse(SubPattern: m_Value(V&: OneUse))))
3236 return nullptr;
3237
3238 if (Instruction *R = hoistFNegAboveFMulFDiv(FNegOp: OneUse, FMFSource&: I))
3239 return replaceInstUsesWith(I, V: R);
3240
3241 // Try to eliminate fneg if at least 1 arm of the select is negated.
3242 Value *Cond;
3243 if (match(V: OneUse, P: m_Select(C: m_Value(V&: Cond), L: m_Value(V&: X), R: m_Value(V&: Y)))) {
3244 // Unlike most transforms, this one is not safe to propagate nsz unless
3245 // it is present on the original select. We union the flags from the select
3246 // and fneg and then remove nsz if needed.
3247 auto propagateSelectFMF = [&](SelectInst *S, bool CommonOperand) {
3248 S->copyFastMathFlags(I: &I);
3249 if (auto *OldSel = dyn_cast<SelectInst>(Val: Op)) {
3250 FastMathFlags FMF = I.getFastMathFlags() | OldSel->getFastMathFlags();
3251 S->setFastMathFlags(FMF);
3252 if (!OldSel->hasNoSignedZeros() && !CommonOperand &&
3253 !isGuaranteedNotToBeUndefOrPoison(V: OldSel->getCondition()))
3254 S->setHasNoSignedZeros(false);
3255 }
3256 };
3257 // -(Cond ? -P : Y) --> Cond ? P : -Y
3258 Value *P;
3259 if (match(V: X, P: m_FNeg(X: m_Value(V&: P)))) {
3260 Value *NegY = Builder.CreateFNegFMF(V: Y, FMFSource: &I, Name: Y->getName() + ".neg");
3261 SelectInst *NewSel = SelectInst::Create(
3262 C: Cond, S1: P, S2: NegY, NameStr: "", InsertBefore: nullptr,
3263 MDFrom: ProfcheckDisableMetadataFixes ? nullptr : cast<SelectInst>(Val: Op));
3264 propagateSelectFMF(NewSel, P == Y);
3265 return NewSel;
3266 }
3267 // -(Cond ? X : -P) --> Cond ? -X : P
3268 if (match(V: Y, P: m_FNeg(X: m_Value(V&: P)))) {
3269 Value *NegX = Builder.CreateFNegFMF(V: X, FMFSource: &I, Name: X->getName() + ".neg");
3270 SelectInst *NewSel = SelectInst::Create(
3271 C: Cond, S1: NegX, S2: P, NameStr: "", InsertBefore: nullptr,
3272 MDFrom: ProfcheckDisableMetadataFixes ? nullptr : cast<SelectInst>(Val: Op));
3273 propagateSelectFMF(NewSel, P == X);
3274 return NewSel;
3275 }
3276
3277 // -(Cond ? X : C) --> Cond ? -X : -C
3278 // -(Cond ? C : Y) --> Cond ? -C : -Y
3279 if (match(V: X, P: m_ImmConstant()) || match(V: Y, P: m_ImmConstant())) {
3280 Value *NegX = Builder.CreateFNegFMF(V: X, FMFSource: &I, Name: X->getName() + ".neg");
3281 Value *NegY = Builder.CreateFNegFMF(V: Y, FMFSource: &I, Name: Y->getName() + ".neg");
3282 SelectInst *NewSel = SelectInst::Create(
3283 C: Cond, S1: NegX, S2: NegY, NameStr: "", InsertBefore: nullptr,
3284 MDFrom: ProfcheckDisableMetadataFixes ? nullptr : cast<SelectInst>(Val: Op));
3285 propagateSelectFMF(NewSel, /*CommonOperand=*/true);
3286 return NewSel;
3287 }
3288 }
3289
3290 // fneg (copysign x, y) -> copysign x, (fneg y)
3291 if (match(V: OneUse, P: m_CopySign(Op0: m_Value(V&: X), Op1: m_Value(V&: Y)))) {
3292 // The source copysign has an additional value input, so we can't propagate
3293 // flags the copysign doesn't also have.
3294 FastMathFlags FMF = I.getFastMathFlags();
3295 FMF &= cast<FPMathOperator>(Val: OneUse)->getFastMathFlags();
3296 Value *NegY = Builder.CreateFNegFMF(V: Y, FMFSource: FMF);
3297 Value *NewCopySign = Builder.CreateCopySign(LHS: X, RHS: NegY, FMFSource: FMF);
3298 return replaceInstUsesWith(I, V: NewCopySign);
3299 }
3300
3301 // fneg (shuffle x, Mask) --> shuffle (fneg x), Mask
3302 ArrayRef<int> Mask;
3303 if (match(V: OneUse, P: m_Shuffle(v1: m_Value(V&: X), v2: m_Poison(), mask: m_Mask(Mask))))
3304 return new ShuffleVectorInst(Builder.CreateFNegFMF(V: X, FMFSource: &I), Mask);
3305
3306 // fneg (reverse x) --> reverse (fneg x)
3307 if (match(V: OneUse, P: m_VecReverse(Op0: m_Value(V&: X)))) {
3308 Value *Reverse = Builder.CreateVectorReverse(V: Builder.CreateFNegFMF(V: X, FMFSource: &I));
3309 return replaceInstUsesWith(I, V: Reverse);
3310 }
3311
3312 return nullptr;
3313}
3314
3315Instruction *InstCombinerImpl::visitFSub(BinaryOperator &I) {
3316 if (Value *V = simplifyFSubInst(LHS: I.getOperand(i_nocapture: 0), RHS: I.getOperand(i_nocapture: 1),
3317 FMF: I.getFastMathFlags(),
3318 Q: getSimplifyQuery().getWithInstruction(I: &I)))
3319 return replaceInstUsesWith(I, V);
3320
3321 if (Instruction *X = foldVectorBinop(Inst&: I))
3322 return X;
3323
3324 if (Instruction *Phi = foldBinopWithPhiOperands(BO&: I))
3325 return Phi;
3326
3327 // Subtraction from -0.0 is the canonical form of fneg.
3328 // fsub -0.0, X ==> fneg X
3329 // fsub nsz 0.0, X ==> fneg nsz X
3330 //
3331 // FIXME This matcher does not respect FTZ or DAZ yet:
3332 // fsub -0.0, Denorm ==> +-0
3333 // fneg Denorm ==> -Denorm
3334 Value *Op;
3335 if (match(V: &I, P: m_FNeg(X: m_Value(V&: Op))))
3336 return UnaryOperator::CreateFNegFMF(Op, FMFSource: &I);
3337
3338 if (Instruction *X = foldFNegIntoConstant(I, DL))
3339 return X;
3340
3341 if (Instruction *R = foldFBinOpOfIntCasts(I))
3342 return R;
3343
3344 Value *X, *Y;
3345 Constant *C;
3346
3347 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
3348 // If Op0 is not -0.0 or we can ignore -0.0: Z - (X - Y) --> Z + (Y - X)
3349 // Canonicalize to fadd to make analysis easier.
3350 // This can also help codegen because fadd is commutative.
3351 // Note that if this fsub was really an fneg, the fadd with -0.0 will get
3352 // killed later. We still limit that particular transform with 'hasOneUse'
3353 // because an fneg is assumed better/cheaper than a generic fsub.
3354 if (I.hasNoSignedZeros() ||
3355 cannotBeNegativeZero(V: Op0, SQ: getSimplifyQuery().getWithInstruction(I: &I))) {
3356 if (match(V: Op1, P: m_OneUse(SubPattern: m_FSub(L: m_Value(V&: X), R: m_Value(V&: Y))))) {
3357 Value *NewSub = Builder.CreateFSubFMF(L: Y, R: X, FMFSource: &I);
3358 return BinaryOperator::CreateFAddFMF(V1: Op0, V2: NewSub, FMFSource: &I);
3359 }
3360 }
3361
3362 // (-X) - Op1 --> -(X + Op1)
3363 if (I.hasNoSignedZeros() && !isa<ConstantExpr>(Val: Op0) &&
3364 match(V: Op0, P: m_OneUse(SubPattern: m_FNeg(X: m_Value(V&: X))))) {
3365 Value *FAdd = Builder.CreateFAddFMF(L: X, R: Op1, FMFSource: &I);
3366 return UnaryOperator::CreateFNegFMF(Op: FAdd, FMFSource: &I);
3367 }
3368
3369 if (isa<Constant>(Val: Op0))
3370 if (SelectInst *SI = dyn_cast<SelectInst>(Val: Op1))
3371 if (Instruction *NV = FoldOpIntoSelect(Op&: I, SI))
3372 return NV;
3373
3374 // X - C --> X + (-C)
3375 // But don't transform constant expressions because there's an inverse fold
3376 // for X + (-Y) --> X - Y.
3377 if (match(V: Op1, P: m_ImmConstant(C)))
3378 if (Constant *NegC = ConstantFoldUnaryOpOperand(Opcode: Instruction::FNeg, Op: C, DL))
3379 return BinaryOperator::CreateFAddFMF(V1: Op0, V2: NegC, FMFSource: &I);
3380
3381 // X - (-Y) --> X + Y
3382 if (match(V: Op1, P: m_FNeg(X: m_Value(V&: Y))))
3383 return BinaryOperator::CreateFAddFMF(V1: Op0, V2: Y, FMFSource: &I);
3384
3385 // Similar to above, but look through a cast of the negated value:
3386 // X - (fptrunc(-Y)) --> X + fptrunc(Y)
3387 Type *Ty = I.getType();
3388 if (match(V: Op1, P: m_OneUse(SubPattern: m_FPTrunc(Op: m_FNeg(X: m_Value(V&: Y))))))
3389 return BinaryOperator::CreateFAddFMF(V1: Op0, V2: Builder.CreateFPTrunc(V: Y, DestTy: Ty), FMFSource: &I);
3390
3391 // X - (fpext(-Y)) --> X + fpext(Y)
3392 if (match(V: Op1, P: m_OneUse(SubPattern: m_FPExt(Op: m_FNeg(X: m_Value(V&: Y))))))
3393 return BinaryOperator::CreateFAddFMF(V1: Op0, V2: Builder.CreateFPExt(V: Y, DestTy: Ty), FMFSource: &I);
3394
3395 // Similar to above, but look through fmul/fdiv of the negated value:
3396 // Op0 - (-X * Y) --> Op0 + (X * Y)
3397 // Op0 - (Y * -X) --> Op0 + (X * Y)
3398 if (match(V: Op1, P: m_OneUse(SubPattern: m_c_FMul(L: m_FNeg(X: m_Value(V&: X)), R: m_Value(V&: Y))))) {
3399 Value *FMul = Builder.CreateFMulFMF(L: X, R: Y, FMFSource: &I);
3400 return BinaryOperator::CreateFAddFMF(V1: Op0, V2: FMul, FMFSource: &I);
3401 }
3402 // Op0 - (-X / Y) --> Op0 + (X / Y)
3403 // Op0 - (X / -Y) --> Op0 + (X / Y)
3404 if (match(V: Op1, P: m_OneUse(SubPattern: m_FDiv(L: m_FNeg(X: m_Value(V&: X)), R: m_Value(V&: Y)))) ||
3405 match(V: Op1, P: m_OneUse(SubPattern: m_FDiv(L: m_Value(V&: X), R: m_FNeg(X: m_Value(V&: Y)))))) {
3406 Value *FDiv = Builder.CreateFDivFMF(L: X, R: Y, FMFSource: &I);
3407 return BinaryOperator::CreateFAddFMF(V1: Op0, V2: FDiv, FMFSource: &I);
3408 }
3409
3410 // Handle special cases for FSub with selects feeding the operation
3411 if (Value *V = SimplifySelectsFeedingBinaryOp(I, LHS: Op0, RHS: Op1))
3412 return replaceInstUsesWith(I, V);
3413
3414 if (I.hasAllowReassoc() && I.hasNoSignedZeros()) {
3415 // (Y - X) - Y --> -X
3416 if (match(V: Op0, P: m_FSub(L: m_Specific(V: Op1), R: m_Value(V&: X))))
3417 return UnaryOperator::CreateFNegFMF(Op: X, FMFSource: &I);
3418
3419 // Y - (X + Y) --> -X
3420 // Y - (Y + X) --> -X
3421 if (match(V: Op1, P: m_c_FAdd(L: m_Specific(V: Op0), R: m_Value(V&: X))))
3422 return UnaryOperator::CreateFNegFMF(Op: X, FMFSource: &I);
3423
3424 // (X * C) - X --> X * (C - 1.0)
3425 if (match(V: Op0, P: m_FMul(L: m_Specific(V: Op1), R: m_Constant(C)))) {
3426 if (Constant *CSubOne = ConstantFoldBinaryOpOperands(
3427 Opcode: Instruction::FSub, LHS: C, RHS: ConstantFP::get(Ty, V: 1.0), DL))
3428 return BinaryOperator::CreateFMulFMF(V1: Op1, V2: CSubOne, FMFSource: &I);
3429 }
3430 // X - (X * C) --> X * (1.0 - C)
3431 if (match(V: Op1, P: m_FMul(L: m_Specific(V: Op0), R: m_Constant(C)))) {
3432 if (Constant *OneSubC = ConstantFoldBinaryOpOperands(
3433 Opcode: Instruction::FSub, LHS: ConstantFP::get(Ty, V: 1.0), RHS: C, DL))
3434 return BinaryOperator::CreateFMulFMF(V1: Op0, V2: OneSubC, FMFSource: &I);
3435 }
3436
3437 // Reassociate fsub/fadd sequences to create more fadd instructions and
3438 // reduce dependency chains:
3439 // ((X - Y) + Z) - Op1 --> (X + Z) - (Y + Op1)
3440 Value *Z;
3441 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))),
3442 R: m_Value(V&: Z))))) {
3443 Value *XZ = Builder.CreateFAddFMF(L: X, R: Z, FMFSource: &I);
3444 Value *YW = Builder.CreateFAddFMF(L: Y, R: Op1, FMFSource: &I);
3445 return BinaryOperator::CreateFSubFMF(V1: XZ, V2: YW, FMFSource: &I);
3446 }
3447
3448 auto m_FaddRdx = [](Value *&Sum, Value *&Vec) {
3449 return m_OneUse(SubPattern: m_Intrinsic<Intrinsic::vector_reduce_fadd>(Ops: m_Value(V&: Sum),
3450 Ops: m_Value(V&: Vec)));
3451 };
3452 Value *A0, *A1, *V0, *V1;
3453 if (match(V: Op0, P: m_FaddRdx(A0, V0)) && match(V: Op1, P: m_FaddRdx(A1, V1)) &&
3454 V0->getType() == V1->getType()) {
3455 // Difference of sums is sum of differences:
3456 // add_rdx(A0, V0) - add_rdx(A1, V1) --> add_rdx(A0, V0 - V1) - A1
3457 Value *Sub = Builder.CreateFSubFMF(L: V0, R: V1, FMFSource: &I);
3458 Value *Rdx = Builder.CreateIntrinsic(ID: Intrinsic::vector_reduce_fadd,
3459 OverloadTypes: {Sub->getType()}, Args: {A0, Sub}, FMFSource: &I);
3460 return BinaryOperator::CreateFSubFMF(V1: Rdx, V2: A1, FMFSource: &I);
3461 }
3462
3463 if (Instruction *F = factorizeFAddFSub(I, Builder))
3464 return F;
3465
3466 // TODO: This performs reassociative folds for FP ops. Some fraction of the
3467 // functionality has been subsumed by simple pattern matching here and in
3468 // InstSimplify. We should let a dedicated reassociation pass handle more
3469 // complex pattern matching and remove this from InstCombine.
3470 if (Value *V = FAddCombine(Builder).simplify(I: &I))
3471 return replaceInstUsesWith(I, V);
3472
3473 // (X - Y) - Op1 --> X - (Y + Op1)
3474 if (match(V: Op0, P: m_OneUse(SubPattern: m_FSub(L: m_Value(V&: X), R: m_Value(V&: Y))))) {
3475 Value *FAdd = Builder.CreateFAddFMF(L: Y, R: Op1, FMFSource: &I);
3476 return BinaryOperator::CreateFSubFMF(V1: X, V2: FAdd, FMFSource: &I);
3477 }
3478 }
3479
3480 return nullptr;
3481}
3482