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/Type.h"
28 #include "llvm/IR/Value.h"
29 #include "llvm/Support/Casting.h"
30 #include "llvm/Support/KnownBits.h"
31 #include "llvm/Transforms/InstCombine/InstCombiner.h"
32 #include <cassert>
33 #include <utility>
34 
35 using namespace llvm;
36 using namespace PatternMatch;
37 
38 #define DEBUG_TYPE "instcombine"
39 
40 namespace {
41 
42   /// Class representing coefficient of floating-point addend.
43   /// This class needs to be highly efficient, which is especially true for
44   /// the constructor. As of I write this comment, the cost of the default
45   /// constructor is merely 4-byte-store-zero (Assuming compiler is able to
46   /// perform write-merging).
47   ///
48   class FAddendCoef {
49   public:
50     // The constructor has to initialize a APFloat, which is unnecessary for
51     // most addends which have coefficient either 1 or -1. So, the constructor
52     // is expensive. In order to avoid the cost of the constructor, we should
53     // reuse some instances whenever possible. The pre-created instances
54     // FAddCombine::Add[0-5] embodies this idea.
55     FAddendCoef() = default;
56     ~FAddendCoef();
57 
58     // If possible, don't define operator+/operator- etc because these
59     // operators inevitably call FAddendCoef's constructor which is not cheap.
60     void operator=(const FAddendCoef &A);
61     void operator+=(const FAddendCoef &A);
62     void operator*=(const FAddendCoef &S);
63 
64     void set(short C) {
65       assert(!insaneIntVal(C) && "Insane coefficient");
66       IsFp = false; IntVal = C;
67     }
68 
69     void set(const APFloat& C);
70 
71     void negate();
72 
73     bool isZero() const { return isInt() ? !IntVal : getFpVal().isZero(); }
74     Value *getValue(Type *) const;
75 
76     bool isOne() const { return isInt() && IntVal == 1; }
77     bool isTwo() const { return isInt() && IntVal == 2; }
78     bool isMinusOne() const { return isInt() && IntVal == -1; }
79     bool isMinusTwo() const { return isInt() && IntVal == -2; }
80 
81   private:
82     bool insaneIntVal(int V) { return V > 4 || V < -4; }
83 
84     APFloat *getFpValPtr() { return reinterpret_cast<APFloat *>(&FpValBuf); }
85 
86     const APFloat *getFpValPtr() const {
87       return reinterpret_cast<const APFloat *>(&FpValBuf);
88     }
89 
90     const APFloat &getFpVal() const {
91       assert(IsFp && BufHasFpVal && "Incorret state");
92       return *getFpValPtr();
93     }
94 
95     APFloat &getFpVal() {
96       assert(IsFp && BufHasFpVal && "Incorret state");
97       return *getFpValPtr();
98     }
99 
100     bool isInt() const { return !IsFp; }
101 
102     // If the coefficient is represented by an integer, promote it to a
103     // floating point.
104     void convertToFpType(const fltSemantics &Sem);
105 
106     // Construct an APFloat from a signed integer.
107     // TODO: We should get rid of this function when APFloat can be constructed
108     //       from an *SIGNED* integer.
109     APFloat createAPFloatFromInt(const fltSemantics &Sem, int Val);
110 
111     bool IsFp = false;
112 
113     // True iff FpValBuf contains an instance of APFloat.
114     bool BufHasFpVal = false;
115 
116     // The integer coefficient of an individual addend is either 1 or -1,
117     // and we try to simplify at most 4 addends from neighboring at most
118     // two instructions. So the range of <IntVal> falls in [-4, 4]. APInt
119     // is overkill of this end.
120     short IntVal = 0;
121 
122     std::aligned_union_t<1, APFloat> FpValBuf;
123   };
124 
125   /// FAddend is used to represent floating-point addend. An addend is
126   /// represented as <C, V>, where the V is a symbolic value, and C is a
127   /// constant coefficient. A constant addend is represented as <C, 0>.
128   class FAddend {
129   public:
130     FAddend() = default;
131 
132     void operator+=(const FAddend &T) {
133       assert((Val == T.Val) && "Symbolic-values disagree");
134       Coeff += T.Coeff;
135     }
136 
137     Value *getSymVal() const { return Val; }
138     const FAddendCoef &getCoef() const { return Coeff; }
139 
140     bool isConstant() const { return Val == nullptr; }
141     bool isZero() const { return Coeff.isZero(); }
142 
143     void set(short Coefficient, Value *V) {
144       Coeff.set(Coefficient);
145       Val = V;
146     }
147     void set(const APFloat &Coefficient, Value *V) {
148       Coeff.set(Coefficient);
149       Val = V;
150     }
151     void set(const ConstantFP *Coefficient, Value *V) {
152       Coeff.set(Coefficient->getValueAPF());
153       Val = V;
154     }
155 
156     void negate() { Coeff.negate(); }
157 
158     /// Drill down the U-D chain one step to find the definition of V, and
159     /// try to break the definition into one or two addends.
160     static unsigned drillValueDownOneStep(Value* V, FAddend &A0, FAddend &A1);
161 
162     /// Similar to FAddend::drillDownOneStep() except that the value being
163     /// splitted is the addend itself.
164     unsigned drillAddendDownOneStep(FAddend &Addend0, FAddend &Addend1) const;
165 
166   private:
167     void Scale(const FAddendCoef& ScaleAmt) { Coeff *= ScaleAmt; }
168 
169     // This addend has the value of "Coeff * Val".
170     Value *Val = nullptr;
171     FAddendCoef Coeff;
172   };
173 
174   /// FAddCombine is the class for optimizing an unsafe fadd/fsub along
175   /// with its neighboring at most two instructions.
176   ///
177   class FAddCombine {
178   public:
179     FAddCombine(InstCombiner::BuilderTy &B) : Builder(B) {}
180 
181     Value *simplify(Instruction *FAdd);
182 
183   private:
184     using AddendVect = SmallVector<const FAddend *, 4>;
185 
186     Value *simplifyFAdd(AddendVect& V, unsigned InstrQuota);
187 
188     /// Convert given addend to a Value
189     Value *createAddendVal(const FAddend &A, bool& NeedNeg);
190 
191     /// Return the number of instructions needed to emit the N-ary addition.
192     unsigned calcInstrNumber(const AddendVect& Vect);
193 
194     Value *createFSub(Value *Opnd0, Value *Opnd1);
195     Value *createFAdd(Value *Opnd0, Value *Opnd1);
196     Value *createFMul(Value *Opnd0, Value *Opnd1);
197     Value *createFNeg(Value *V);
198     Value *createNaryFAdd(const AddendVect& Opnds, unsigned InstrQuota);
199     void createInstPostProc(Instruction *NewInst, bool NoNumber = false);
200 
201      // Debugging stuff are clustered here.
202     #ifndef NDEBUG
203       unsigned CreateInstrNum;
204       void initCreateInstNum() { CreateInstrNum = 0; }
205       void incCreateInstNum() { CreateInstrNum++; }
206     #else
207       void initCreateInstNum() {}
208       void incCreateInstNum() {}
209     #endif
210 
211     InstCombiner::BuilderTy &Builder;
212     Instruction *Instr = nullptr;
213   };
214 
215 } // end anonymous namespace
216 
217 //===----------------------------------------------------------------------===//
218 //
219 // Implementation of
220 //    {FAddendCoef, FAddend, FAddition, FAddCombine}.
221 //
222 //===----------------------------------------------------------------------===//
223 FAddendCoef::~FAddendCoef() {
224   if (BufHasFpVal)
225     getFpValPtr()->~APFloat();
226 }
227 
228 void FAddendCoef::set(const APFloat& C) {
229   APFloat *P = getFpValPtr();
230 
231   if (isInt()) {
232     // As the buffer is meanless byte stream, we cannot call
233     // APFloat::operator=().
234     new(P) APFloat(C);
235   } else
236     *P = C;
237 
238   IsFp = BufHasFpVal = true;
239 }
240 
241 void FAddendCoef::convertToFpType(const fltSemantics &Sem) {
242   if (!isInt())
243     return;
244 
245   APFloat *P = getFpValPtr();
246   if (IntVal > 0)
247     new(P) APFloat(Sem, IntVal);
248   else {
249     new(P) APFloat(Sem, 0 - IntVal);
250     P->changeSign();
251   }
252   IsFp = BufHasFpVal = true;
253 }
254 
255 APFloat FAddendCoef::createAPFloatFromInt(const fltSemantics &Sem, int Val) {
256   if (Val >= 0)
257     return APFloat(Sem, Val);
258 
259   APFloat T(Sem, 0 - Val);
260   T.changeSign();
261 
262   return T;
263 }
264 
265 void FAddendCoef::operator=(const FAddendCoef &That) {
266   if (That.isInt())
267     set(That.IntVal);
268   else
269     set(That.getFpVal());
270 }
271 
272 void FAddendCoef::operator+=(const FAddendCoef &That) {
273   RoundingMode RndMode = RoundingMode::NearestTiesToEven;
274   if (isInt() == That.isInt()) {
275     if (isInt())
276       IntVal += That.IntVal;
277     else
278       getFpVal().add(That.getFpVal(), RndMode);
279     return;
280   }
281 
282   if (isInt()) {
283     const APFloat &T = That.getFpVal();
284     convertToFpType(T.getSemantics());
285     getFpVal().add(T, RndMode);
286     return;
287   }
288 
289   APFloat &T = getFpVal();
290   T.add(createAPFloatFromInt(T.getSemantics(), That.IntVal), RndMode);
291 }
292 
293 void FAddendCoef::operator*=(const FAddendCoef &That) {
294   if (That.isOne())
295     return;
296 
297   if (That.isMinusOne()) {
298     negate();
299     return;
300   }
301 
302   if (isInt() && That.isInt()) {
303     int Res = IntVal * (int)That.IntVal;
304     assert(!insaneIntVal(Res) && "Insane int value");
305     IntVal = Res;
306     return;
307   }
308 
309   const fltSemantics &Semantic =
310     isInt() ? That.getFpVal().getSemantics() : getFpVal().getSemantics();
311 
312   if (isInt())
313     convertToFpType(Semantic);
314   APFloat &F0 = getFpVal();
315 
316   if (That.isInt())
317     F0.multiply(createAPFloatFromInt(Semantic, That.IntVal),
318                 APFloat::rmNearestTiesToEven);
319   else
320     F0.multiply(That.getFpVal(), APFloat::rmNearestTiesToEven);
321 }
322 
323 void FAddendCoef::negate() {
324   if (isInt())
325     IntVal = 0 - IntVal;
326   else
327     getFpVal().changeSign();
328 }
329 
330 Value *FAddendCoef::getValue(Type *Ty) const {
331   return isInt() ?
332     ConstantFP::get(Ty, float(IntVal)) :
333     ConstantFP::get(Ty->getContext(), getFpVal());
334 }
335 
336 // The definition of <Val>     Addends
337 // =========================================
338 //  A + B                     <1, A>, <1,B>
339 //  A - B                     <1, A>, <1,B>
340 //  0 - B                     <-1, B>
341 //  C * A,                    <C, A>
342 //  A + C                     <1, A> <C, NULL>
343 //  0 +/- 0                   <0, NULL> (corner case)
344 //
345 // Legend: A and B are not constant, C is constant
346 unsigned FAddend::drillValueDownOneStep
347   (Value *Val, FAddend &Addend0, FAddend &Addend1) {
348   Instruction *I = nullptr;
349   if (!Val || !(I = dyn_cast<Instruction>(Val)))
350     return 0;
351 
352   unsigned Opcode = I->getOpcode();
353 
354   if (Opcode == Instruction::FAdd || Opcode == Instruction::FSub) {
355     ConstantFP *C0, *C1;
356     Value *Opnd0 = I->getOperand(0);
357     Value *Opnd1 = I->getOperand(1);
358     if ((C0 = dyn_cast<ConstantFP>(Opnd0)) && C0->isZero())
359       Opnd0 = nullptr;
360 
361     if ((C1 = dyn_cast<ConstantFP>(Opnd1)) && C1->isZero())
362       Opnd1 = nullptr;
363 
364     if (Opnd0) {
365       if (!C0)
366         Addend0.set(1, Opnd0);
367       else
368         Addend0.set(C0, nullptr);
369     }
370 
371     if (Opnd1) {
372       FAddend &Addend = Opnd0 ? Addend1 : Addend0;
373       if (!C1)
374         Addend.set(1, Opnd1);
375       else
376         Addend.set(C1, nullptr);
377       if (Opcode == Instruction::FSub)
378         Addend.negate();
379     }
380 
381     if (Opnd0 || Opnd1)
382       return Opnd0 && Opnd1 ? 2 : 1;
383 
384     // Both operands are zero. Weird!
385     Addend0.set(APFloat(C0->getValueAPF().getSemantics()), nullptr);
386     return 1;
387   }
388 
389   if (I->getOpcode() == Instruction::FMul) {
390     Value *V0 = I->getOperand(0);
391     Value *V1 = I->getOperand(1);
392     if (ConstantFP *C = dyn_cast<ConstantFP>(V0)) {
393       Addend0.set(C, V1);
394       return 1;
395     }
396 
397     if (ConstantFP *C = dyn_cast<ConstantFP>(V1)) {
398       Addend0.set(C, V0);
399       return 1;
400     }
401   }
402 
403   return 0;
404 }
405 
406 // Try to break *this* addend into two addends. e.g. Suppose this addend is
407 // <2.3, V>, and V = X + Y, by calling this function, we obtain two addends,
408 // i.e. <2.3, X> and <2.3, Y>.
409 unsigned FAddend::drillAddendDownOneStep
410   (FAddend &Addend0, FAddend &Addend1) const {
411   if (isConstant())
412     return 0;
413 
414   unsigned BreakNum = FAddend::drillValueDownOneStep(Val, Addend0, Addend1);
415   if (!BreakNum || Coeff.isOne())
416     return BreakNum;
417 
418   Addend0.Scale(Coeff);
419 
420   if (BreakNum == 2)
421     Addend1.Scale(Coeff);
422 
423   return BreakNum;
424 }
425 
426 Value *FAddCombine::simplify(Instruction *I) {
427   assert(I->hasAllowReassoc() && I->hasNoSignedZeros() &&
428          "Expected 'reassoc'+'nsz' instruction");
429 
430   // Currently we are not able to handle vector type.
431   if (I->getType()->isVectorTy())
432     return nullptr;
433 
434   assert((I->getOpcode() == Instruction::FAdd ||
435           I->getOpcode() == Instruction::FSub) && "Expect add/sub");
436 
437   // Save the instruction before calling other member-functions.
438   Instr = I;
439 
440   FAddend Opnd0, Opnd1, Opnd0_0, Opnd0_1, Opnd1_0, Opnd1_1;
441 
442   unsigned OpndNum = FAddend::drillValueDownOneStep(I, Opnd0, Opnd1);
443 
444   // Step 1: Expand the 1st addend into Opnd0_0 and Opnd0_1.
445   unsigned Opnd0_ExpNum = 0;
446   unsigned Opnd1_ExpNum = 0;
447 
448   if (!Opnd0.isConstant())
449     Opnd0_ExpNum = Opnd0.drillAddendDownOneStep(Opnd0_0, Opnd0_1);
450 
451   // Step 2: Expand the 2nd addend into Opnd1_0 and Opnd1_1.
452   if (OpndNum == 2 && !Opnd1.isConstant())
453     Opnd1_ExpNum = Opnd1.drillAddendDownOneStep(Opnd1_0, Opnd1_1);
454 
455   // Step 3: Try to optimize Opnd0_0 + Opnd0_1 + Opnd1_0 + Opnd1_1
456   if (Opnd0_ExpNum && Opnd1_ExpNum) {
457     AddendVect AllOpnds;
458     AllOpnds.push_back(&Opnd0_0);
459     AllOpnds.push_back(&Opnd1_0);
460     if (Opnd0_ExpNum == 2)
461       AllOpnds.push_back(&Opnd0_1);
462     if (Opnd1_ExpNum == 2)
463       AllOpnds.push_back(&Opnd1_1);
464 
465     // Compute instruction quota. We should save at least one instruction.
466     unsigned InstQuota = 0;
467 
468     Value *V0 = I->getOperand(0);
469     Value *V1 = I->getOperand(1);
470     InstQuota = ((!isa<Constant>(V0) && V0->hasOneUse()) &&
471                  (!isa<Constant>(V1) && V1->hasOneUse())) ? 2 : 1;
472 
473     if (Value *R = simplifyFAdd(AllOpnds, InstQuota))
474       return R;
475   }
476 
477   if (OpndNum != 2) {
478     // The input instruction is : "I=0.0 +/- V". If the "V" were able to be
479     // splitted into two addends, say "V = X - Y", the instruction would have
480     // been optimized into "I = Y - X" in the previous steps.
481     //
482     const FAddendCoef &CE = Opnd0.getCoef();
483     return CE.isOne() ? Opnd0.getSymVal() : nullptr;
484   }
485 
486   // step 4: Try to optimize Opnd0 + Opnd1_0 [+ Opnd1_1]
487   if (Opnd1_ExpNum) {
488     AddendVect AllOpnds;
489     AllOpnds.push_back(&Opnd0);
490     AllOpnds.push_back(&Opnd1_0);
491     if (Opnd1_ExpNum == 2)
492       AllOpnds.push_back(&Opnd1_1);
493 
494     if (Value *R = simplifyFAdd(AllOpnds, 1))
495       return R;
496   }
497 
498   // step 5: Try to optimize Opnd1 + Opnd0_0 [+ Opnd0_1]
499   if (Opnd0_ExpNum) {
500     AddendVect AllOpnds;
501     AllOpnds.push_back(&Opnd1);
502     AllOpnds.push_back(&Opnd0_0);
503     if (Opnd0_ExpNum == 2)
504       AllOpnds.push_back(&Opnd0_1);
505 
506     if (Value *R = simplifyFAdd(AllOpnds, 1))
507       return R;
508   }
509 
510   return nullptr;
511 }
512 
513 Value *FAddCombine::simplifyFAdd(AddendVect& Addends, unsigned InstrQuota) {
514   unsigned AddendNum = Addends.size();
515   assert(AddendNum <= 4 && "Too many addends");
516 
517   // For saving intermediate results;
518   unsigned NextTmpIdx = 0;
519   FAddend TmpResult[3];
520 
521   // Points to the constant addend of the resulting simplified expression.
522   // If the resulting expr has constant-addend, this constant-addend is
523   // desirable to reside at the top of the resulting expression tree. Placing
524   // constant close to supper-expr(s) will potentially reveal some optimization
525   // opportunities in super-expr(s).
526   const FAddend *ConstAdd = nullptr;
527 
528   // Simplified addends are placed <SimpVect>.
529   AddendVect SimpVect;
530 
531   // The outer loop works on one symbolic-value at a time. Suppose the input
532   // addends are : <a1, x>, <b1, y>, <a2, x>, <c1, z>, <b2, y>, ...
533   // The symbolic-values will be processed in this order: x, y, z.
534   for (unsigned SymIdx = 0; SymIdx < AddendNum; SymIdx++) {
535 
536     const FAddend *ThisAddend = Addends[SymIdx];
537     if (!ThisAddend) {
538       // This addend was processed before.
539       continue;
540     }
541 
542     Value *Val = ThisAddend->getSymVal();
543     unsigned StartIdx = SimpVect.size();
544     SimpVect.push_back(ThisAddend);
545 
546     // The inner loop collects addends sharing same symbolic-value, and these
547     // addends will be later on folded into a single addend. Following above
548     // example, if the symbolic value "y" is being processed, the inner loop
549     // will collect two addends "<b1,y>" and "<b2,Y>". These two addends will
550     // be later on folded into "<b1+b2, y>".
551     for (unsigned SameSymIdx = SymIdx + 1;
552          SameSymIdx < AddendNum; SameSymIdx++) {
553       const FAddend *T = Addends[SameSymIdx];
554       if (T && T->getSymVal() == Val) {
555         // Set null such that next iteration of the outer loop will not process
556         // this addend again.
557         Addends[SameSymIdx] = nullptr;
558         SimpVect.push_back(T);
559       }
560     }
561 
562     // If multiple addends share same symbolic value, fold them together.
563     if (StartIdx + 1 != SimpVect.size()) {
564       FAddend &R = TmpResult[NextTmpIdx ++];
565       R = *SimpVect[StartIdx];
566       for (unsigned Idx = StartIdx + 1; Idx < SimpVect.size(); Idx++)
567         R += *SimpVect[Idx];
568 
569       // Pop all addends being folded and push the resulting folded addend.
570       SimpVect.resize(StartIdx);
571       if (Val) {
572         if (!R.isZero()) {
573           SimpVect.push_back(&R);
574         }
575       } else {
576         // Don't push constant addend at this time. It will be the last element
577         // of <SimpVect>.
578         ConstAdd = &R;
579       }
580     }
581   }
582 
583   assert((NextTmpIdx <= array_lengthof(TmpResult) + 1) &&
584          "out-of-bound access");
585 
586   if (ConstAdd)
587     SimpVect.push_back(ConstAdd);
588 
589   Value *Result;
590   if (!SimpVect.empty())
591     Result = createNaryFAdd(SimpVect, InstrQuota);
592   else {
593     // The addition is folded to 0.0.
594     Result = ConstantFP::get(Instr->getType(), 0.0);
595   }
596 
597   return Result;
598 }
599 
600 Value *FAddCombine::createNaryFAdd
601   (const AddendVect &Opnds, unsigned InstrQuota) {
602   assert(!Opnds.empty() && "Expect at least one addend");
603 
604   // Step 1: Check if the # of instructions needed exceeds the quota.
605 
606   unsigned InstrNeeded = calcInstrNumber(Opnds);
607   if (InstrNeeded > InstrQuota)
608     return nullptr;
609 
610   initCreateInstNum();
611 
612   // step 2: Emit the N-ary addition.
613   // Note that at most three instructions are involved in Fadd-InstCombine: the
614   // addition in question, and at most two neighboring instructions.
615   // The resulting optimized addition should have at least one less instruction
616   // than the original addition expression tree. This implies that the resulting
617   // N-ary addition has at most two instructions, and we don't need to worry
618   // about tree-height when constructing the N-ary addition.
619 
620   Value *LastVal = nullptr;
621   bool LastValNeedNeg = false;
622 
623   // Iterate the addends, creating fadd/fsub using adjacent two addends.
624   for (const FAddend *Opnd : Opnds) {
625     bool NeedNeg;
626     Value *V = createAddendVal(*Opnd, NeedNeg);
627     if (!LastVal) {
628       LastVal = V;
629       LastValNeedNeg = NeedNeg;
630       continue;
631     }
632 
633     if (LastValNeedNeg == NeedNeg) {
634       LastVal = createFAdd(LastVal, V);
635       continue;
636     }
637 
638     if (LastValNeedNeg)
639       LastVal = createFSub(V, LastVal);
640     else
641       LastVal = createFSub(LastVal, V);
642 
643     LastValNeedNeg = false;
644   }
645 
646   if (LastValNeedNeg) {
647     LastVal = createFNeg(LastVal);
648   }
649 
650 #ifndef NDEBUG
651   assert(CreateInstrNum == InstrNeeded &&
652          "Inconsistent in instruction numbers");
653 #endif
654 
655   return LastVal;
656 }
657 
658 Value *FAddCombine::createFSub(Value *Opnd0, Value *Opnd1) {
659   Value *V = Builder.CreateFSub(Opnd0, Opnd1);
660   if (Instruction *I = dyn_cast<Instruction>(V))
661     createInstPostProc(I);
662   return V;
663 }
664 
665 Value *FAddCombine::createFNeg(Value *V) {
666   Value *NewV = Builder.CreateFNeg(V);
667   if (Instruction *I = dyn_cast<Instruction>(NewV))
668     createInstPostProc(I, true); // fneg's don't receive instruction numbers.
669   return NewV;
670 }
671 
672 Value *FAddCombine::createFAdd(Value *Opnd0, Value *Opnd1) {
673   Value *V = Builder.CreateFAdd(Opnd0, Opnd1);
674   if (Instruction *I = dyn_cast<Instruction>(V))
675     createInstPostProc(I);
676   return V;
677 }
678 
679 Value *FAddCombine::createFMul(Value *Opnd0, Value *Opnd1) {
680   Value *V = Builder.CreateFMul(Opnd0, Opnd1);
681   if (Instruction *I = dyn_cast<Instruction>(V))
682     createInstPostProc(I);
683   return V;
684 }
685 
686 void FAddCombine::createInstPostProc(Instruction *NewInstr, bool NoNumber) {
687   NewInstr->setDebugLoc(Instr->getDebugLoc());
688 
689   // Keep track of the number of instruction created.
690   if (!NoNumber)
691     incCreateInstNum();
692 
693   // Propagate fast-math flags
694   NewInstr->setFastMathFlags(Instr->getFastMathFlags());
695 }
696 
697 // Return the number of instruction needed to emit the N-ary addition.
698 // NOTE: Keep this function in sync with createAddendVal().
699 unsigned FAddCombine::calcInstrNumber(const AddendVect &Opnds) {
700   unsigned OpndNum = Opnds.size();
701   unsigned InstrNeeded = OpndNum - 1;
702 
703   // The number of addends in the form of "(-1)*x".
704   unsigned NegOpndNum = 0;
705 
706   // Adjust the number of instructions needed to emit the N-ary add.
707   for (const FAddend *Opnd : Opnds) {
708     if (Opnd->isConstant())
709       continue;
710 
711     // The constant check above is really for a few special constant
712     // coefficients.
713     if (isa<UndefValue>(Opnd->getSymVal()))
714       continue;
715 
716     const FAddendCoef &CE = Opnd->getCoef();
717     if (CE.isMinusOne() || CE.isMinusTwo())
718       NegOpndNum++;
719 
720     // Let the addend be "c * x". If "c == +/-1", the value of the addend
721     // is immediately available; otherwise, it needs exactly one instruction
722     // to evaluate the value.
723     if (!CE.isMinusOne() && !CE.isOne())
724       InstrNeeded++;
725   }
726   return InstrNeeded;
727 }
728 
729 // Input Addend        Value           NeedNeg(output)
730 // ================================================================
731 // Constant C          C               false
732 // <+/-1, V>           V               coefficient is -1
733 // <2/-2, V>          "fadd V, V"      coefficient is -2
734 // <C, V>             "fmul V, C"      false
735 //
736 // NOTE: Keep this function in sync with FAddCombine::calcInstrNumber.
737 Value *FAddCombine::createAddendVal(const FAddend &Opnd, bool &NeedNeg) {
738   const FAddendCoef &Coeff = Opnd.getCoef();
739 
740   if (Opnd.isConstant()) {
741     NeedNeg = false;
742     return Coeff.getValue(Instr->getType());
743   }
744 
745   Value *OpndVal = Opnd.getSymVal();
746 
747   if (Coeff.isMinusOne() || Coeff.isOne()) {
748     NeedNeg = Coeff.isMinusOne();
749     return OpndVal;
750   }
751 
752   if (Coeff.isTwo() || Coeff.isMinusTwo()) {
753     NeedNeg = Coeff.isMinusTwo();
754     return createFAdd(OpndVal, OpndVal);
755   }
756 
757   NeedNeg = false;
758   return createFMul(OpndVal, Coeff.getValue(Instr->getType()));
759 }
760 
761 // Checks if any operand is negative and we can convert add to sub.
762 // This function checks for following negative patterns
763 //   ADD(XOR(OR(Z, NOT(C)), C)), 1) == NEG(AND(Z, C))
764 //   ADD(XOR(AND(Z, C), C), 1) == NEG(OR(Z, ~C))
765 //   XOR(AND(Z, C), (C + 1)) == NEG(OR(Z, ~C)) if C is even
766 static Value *checkForNegativeOperand(BinaryOperator &I,
767                                       InstCombiner::BuilderTy &Builder) {
768   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
769 
770   // This function creates 2 instructions to replace ADD, we need at least one
771   // of LHS or RHS to have one use to ensure benefit in transform.
772   if (!LHS->hasOneUse() && !RHS->hasOneUse())
773     return nullptr;
774 
775   Value *X = nullptr, *Y = nullptr, *Z = nullptr;
776   const APInt *C1 = nullptr, *C2 = nullptr;
777 
778   // if ONE is on other side, swap
779   if (match(RHS, m_Add(m_Value(X), m_One())))
780     std::swap(LHS, RHS);
781 
782   if (match(LHS, m_Add(m_Value(X), m_One()))) {
783     // if XOR on other side, swap
784     if (match(RHS, m_Xor(m_Value(Y), m_APInt(C1))))
785       std::swap(X, RHS);
786 
787     if (match(X, m_Xor(m_Value(Y), m_APInt(C1)))) {
788       // X = XOR(Y, C1), Y = OR(Z, C2), C2 = NOT(C1) ==> X == NOT(AND(Z, C1))
789       // ADD(ADD(X, 1), RHS) == ADD(X, ADD(RHS, 1)) == SUB(RHS, AND(Z, C1))
790       if (match(Y, m_Or(m_Value(Z), m_APInt(C2))) && (*C2 == ~(*C1))) {
791         Value *NewAnd = Builder.CreateAnd(Z, *C1);
792         return Builder.CreateSub(RHS, NewAnd, "sub");
793       } else if (match(Y, m_And(m_Value(Z), m_APInt(C2))) && (*C1 == *C2)) {
794         // X = XOR(Y, C1), Y = AND(Z, C2), C2 == C1 ==> X == NOT(OR(Z, ~C1))
795         // ADD(ADD(X, 1), RHS) == ADD(X, ADD(RHS, 1)) == SUB(RHS, OR(Z, ~C1))
796         Value *NewOr = Builder.CreateOr(Z, ~(*C1));
797         return Builder.CreateSub(RHS, NewOr, "sub");
798       }
799     }
800   }
801 
802   // Restore LHS and RHS
803   LHS = I.getOperand(0);
804   RHS = I.getOperand(1);
805 
806   // if XOR is on other side, swap
807   if (match(RHS, m_Xor(m_Value(Y), m_APInt(C1))))
808     std::swap(LHS, RHS);
809 
810   // C2 is ODD
811   // LHS = XOR(Y, C1), Y = AND(Z, C2), C1 == (C2 + 1) => LHS == NEG(OR(Z, ~C2))
812   // ADD(LHS, RHS) == SUB(RHS, OR(Z, ~C2))
813   if (match(LHS, m_Xor(m_Value(Y), m_APInt(C1))))
814     if (C1->countTrailingZeros() == 0)
815       if (match(Y, m_And(m_Value(Z), m_APInt(C2))) && *C1 == (*C2 + 1)) {
816         Value *NewOr = Builder.CreateOr(Z, ~(*C2));
817         return Builder.CreateSub(RHS, NewOr, "sub");
818       }
819   return nullptr;
820 }
821 
822 /// Wrapping flags may allow combining constants separated by an extend.
823 static Instruction *foldNoWrapAdd(BinaryOperator &Add,
824                                   InstCombiner::BuilderTy &Builder) {
825   Value *Op0 = Add.getOperand(0), *Op1 = Add.getOperand(1);
826   Type *Ty = Add.getType();
827   Constant *Op1C;
828   if (!match(Op1, m_Constant(Op1C)))
829     return nullptr;
830 
831   // Try this match first because it results in an add in the narrow type.
832   // (zext (X +nuw C2)) + C1 --> zext (X + (C2 + trunc(C1)))
833   Value *X;
834   const APInt *C1, *C2;
835   if (match(Op1, m_APInt(C1)) &&
836       match(Op0, m_OneUse(m_ZExt(m_NUWAdd(m_Value(X), m_APInt(C2))))) &&
837       C1->isNegative() && C1->sge(-C2->sext(C1->getBitWidth()))) {
838     Constant *NewC =
839         ConstantInt::get(X->getType(), *C2 + C1->trunc(C2->getBitWidth()));
840     return new ZExtInst(Builder.CreateNUWAdd(X, NewC), Ty);
841   }
842 
843   // More general combining of constants in the wide type.
844   // (sext (X +nsw NarrowC)) + C --> (sext X) + (sext(NarrowC) + C)
845   Constant *NarrowC;
846   if (match(Op0, m_OneUse(m_SExt(m_NSWAdd(m_Value(X), m_Constant(NarrowC)))))) {
847     Constant *WideC = ConstantExpr::getSExt(NarrowC, Ty);
848     Constant *NewC = ConstantExpr::getAdd(WideC, Op1C);
849     Value *WideX = Builder.CreateSExt(X, Ty);
850     return BinaryOperator::CreateAdd(WideX, NewC);
851   }
852   // (zext (X +nuw NarrowC)) + C --> (zext X) + (zext(NarrowC) + C)
853   if (match(Op0, m_OneUse(m_ZExt(m_NUWAdd(m_Value(X), m_Constant(NarrowC)))))) {
854     Constant *WideC = ConstantExpr::getZExt(NarrowC, Ty);
855     Constant *NewC = ConstantExpr::getAdd(WideC, Op1C);
856     Value *WideX = Builder.CreateZExt(X, Ty);
857     return BinaryOperator::CreateAdd(WideX, NewC);
858   }
859 
860   return nullptr;
861 }
862 
863 Instruction *InstCombinerImpl::foldAddWithConstant(BinaryOperator &Add) {
864   Value *Op0 = Add.getOperand(0), *Op1 = Add.getOperand(1);
865   Constant *Op1C;
866   if (!match(Op1, m_Constant(Op1C)))
867     return nullptr;
868 
869   if (Instruction *NV = foldBinOpIntoSelectOrPhi(Add))
870     return NV;
871 
872   Value *X;
873   Constant *Op00C;
874 
875   // add (sub C1, X), C2 --> sub (add C1, C2), X
876   if (match(Op0, m_Sub(m_Constant(Op00C), m_Value(X))))
877     return BinaryOperator::CreateSub(ConstantExpr::getAdd(Op00C, Op1C), X);
878 
879   Value *Y;
880 
881   // add (sub X, Y), -1 --> add (not Y), X
882   if (match(Op0, m_OneUse(m_Sub(m_Value(X), m_Value(Y)))) &&
883       match(Op1, m_AllOnes()))
884     return BinaryOperator::CreateAdd(Builder.CreateNot(Y), X);
885 
886   // zext(bool) + C -> bool ? C + 1 : C
887   if (match(Op0, m_ZExt(m_Value(X))) &&
888       X->getType()->getScalarSizeInBits() == 1)
889     return SelectInst::Create(X, InstCombiner::AddOne(Op1C), Op1);
890   // sext(bool) + C -> bool ? C - 1 : C
891   if (match(Op0, m_SExt(m_Value(X))) &&
892       X->getType()->getScalarSizeInBits() == 1)
893     return SelectInst::Create(X, InstCombiner::SubOne(Op1C), Op1);
894 
895   // ~X + C --> (C-1) - X
896   if (match(Op0, m_Not(m_Value(X))))
897     return BinaryOperator::CreateSub(InstCombiner::SubOne(Op1C), X);
898 
899   const APInt *C;
900   if (!match(Op1, m_APInt(C)))
901     return nullptr;
902 
903   // (X | C2) + C --> (X | C2) ^ C2 iff (C2 == -C)
904   const APInt *C2;
905   if (match(Op0, m_Or(m_Value(), m_APInt(C2))) && *C2 == -*C)
906     return BinaryOperator::CreateXor(Op0, ConstantInt::get(Add.getType(), *C2));
907 
908   if (C->isSignMask()) {
909     // If wrapping is not allowed, then the addition must set the sign bit:
910     // X + (signmask) --> X | signmask
911     if (Add.hasNoSignedWrap() || Add.hasNoUnsignedWrap())
912       return BinaryOperator::CreateOr(Op0, Op1);
913 
914     // If wrapping is allowed, then the addition flips the sign bit of LHS:
915     // X + (signmask) --> X ^ signmask
916     return BinaryOperator::CreateXor(Op0, Op1);
917   }
918 
919   // Is this add the last step in a convoluted sext?
920   // add(zext(xor i16 X, -32768), -32768) --> sext X
921   Type *Ty = Add.getType();
922   if (match(Op0, m_ZExt(m_Xor(m_Value(X), m_APInt(C2)))) &&
923       C2->isMinSignedValue() && C2->sext(Ty->getScalarSizeInBits()) == *C)
924     return CastInst::Create(Instruction::SExt, X, Ty);
925 
926   if (match(Op0, m_Xor(m_Value(X), m_APInt(C2)))) {
927     // (X ^ signmask) + C --> (X + (signmask ^ C))
928     if (C2->isSignMask())
929       return BinaryOperator::CreateAdd(X, ConstantInt::get(Ty, *C2 ^ *C));
930 
931     // If X has no high-bits set above an xor mask:
932     // add (xor X, LowMaskC), C --> sub (LowMaskC + C), X
933     if (C2->isMask()) {
934       KnownBits LHSKnown = computeKnownBits(X, 0, &Add);
935       if ((*C2 | LHSKnown.Zero).isAllOnesValue())
936         return BinaryOperator::CreateSub(ConstantInt::get(Ty, *C2 + *C), X);
937     }
938 
939     // Look for a math+logic pattern that corresponds to sext-in-register of a
940     // value with cleared high bits. Convert that into a pair of shifts:
941     // add (xor X, 0x80), 0xF..F80 --> (X << ShAmtC) >>s ShAmtC
942     // add (xor X, 0xF..F80), 0x80 --> (X << ShAmtC) >>s ShAmtC
943     if (Op0->hasOneUse() && *C2 == -(*C)) {
944       unsigned BitWidth = Ty->getScalarSizeInBits();
945       unsigned ShAmt = 0;
946       if (C->isPowerOf2())
947         ShAmt = BitWidth - C->logBase2() - 1;
948       else if (C2->isPowerOf2())
949         ShAmt = BitWidth - C2->logBase2() - 1;
950       if (ShAmt && MaskedValueIsZero(X, APInt::getHighBitsSet(BitWidth, ShAmt),
951                                      0, &Add)) {
952         Constant *ShAmtC = ConstantInt::get(Ty, ShAmt);
953         Value *NewShl = Builder.CreateShl(X, ShAmtC, "sext");
954         return BinaryOperator::CreateAShr(NewShl, ShAmtC);
955       }
956     }
957   }
958 
959   if (C->isOneValue() && Op0->hasOneUse()) {
960     // add (sext i1 X), 1 --> zext (not X)
961     // TODO: The smallest IR representation is (select X, 0, 1), and that would
962     // not require the one-use check. But we need to remove a transform in
963     // visitSelect and make sure that IR value tracking for select is equal or
964     // better than for these ops.
965     if (match(Op0, m_SExt(m_Value(X))) &&
966         X->getType()->getScalarSizeInBits() == 1)
967       return new ZExtInst(Builder.CreateNot(X), Ty);
968 
969     // Shifts and add used to flip and mask off the low bit:
970     // add (ashr (shl i32 X, 31), 31), 1 --> and (not X), 1
971     const APInt *C3;
972     if (match(Op0, m_AShr(m_Shl(m_Value(X), m_APInt(C2)), m_APInt(C3))) &&
973         C2 == C3 && *C2 == Ty->getScalarSizeInBits() - 1) {
974       Value *NotX = Builder.CreateNot(X);
975       return BinaryOperator::CreateAnd(NotX, ConstantInt::get(Ty, 1));
976     }
977   }
978 
979   // If all bits affected by the add are included in a high-bit-mask, do the
980   // add before the mask op:
981   // (X & 0xFF00) + xx00 --> (X + xx00) & 0xFF00
982   if (match(Op0, m_OneUse(m_And(m_Value(X), m_APInt(C2)))) &&
983       C2->isNegative() && C2->isShiftedMask() && *C == (*C & *C2)) {
984     Value *NewAdd = Builder.CreateAdd(X, ConstantInt::get(Ty, *C));
985     return BinaryOperator::CreateAnd(NewAdd, ConstantInt::get(Ty, *C2));
986   }
987 
988   return nullptr;
989 }
990 
991 // Matches multiplication expression Op * C where C is a constant. Returns the
992 // constant value in C and the other operand in Op. Returns true if such a
993 // match is found.
994 static bool MatchMul(Value *E, Value *&Op, APInt &C) {
995   const APInt *AI;
996   if (match(E, m_Mul(m_Value(Op), m_APInt(AI)))) {
997     C = *AI;
998     return true;
999   }
1000   if (match(E, m_Shl(m_Value(Op), m_APInt(AI)))) {
1001     C = APInt(AI->getBitWidth(), 1);
1002     C <<= *AI;
1003     return true;
1004   }
1005   return false;
1006 }
1007 
1008 // Matches remainder expression Op % C where C is a constant. Returns the
1009 // constant value in C and the other operand in Op. Returns the signedness of
1010 // the remainder operation in IsSigned. Returns true if such a match is
1011 // found.
1012 static bool MatchRem(Value *E, Value *&Op, APInt &C, bool &IsSigned) {
1013   const APInt *AI;
1014   IsSigned = false;
1015   if (match(E, m_SRem(m_Value(Op), m_APInt(AI)))) {
1016     IsSigned = true;
1017     C = *AI;
1018     return true;
1019   }
1020   if (match(E, m_URem(m_Value(Op), m_APInt(AI)))) {
1021     C = *AI;
1022     return true;
1023   }
1024   if (match(E, m_And(m_Value(Op), m_APInt(AI))) && (*AI + 1).isPowerOf2()) {
1025     C = *AI + 1;
1026     return true;
1027   }
1028   return false;
1029 }
1030 
1031 // Matches division expression Op / C with the given signedness as indicated
1032 // by IsSigned, where C is a constant. Returns the constant value in C and the
1033 // other operand in Op. Returns true if such a match is found.
1034 static bool MatchDiv(Value *E, Value *&Op, APInt &C, bool IsSigned) {
1035   const APInt *AI;
1036   if (IsSigned && match(E, m_SDiv(m_Value(Op), m_APInt(AI)))) {
1037     C = *AI;
1038     return true;
1039   }
1040   if (!IsSigned) {
1041     if (match(E, m_UDiv(m_Value(Op), m_APInt(AI)))) {
1042       C = *AI;
1043       return true;
1044     }
1045     if (match(E, m_LShr(m_Value(Op), m_APInt(AI)))) {
1046       C = APInt(AI->getBitWidth(), 1);
1047       C <<= *AI;
1048       return true;
1049     }
1050   }
1051   return false;
1052 }
1053 
1054 // Returns whether C0 * C1 with the given signedness overflows.
1055 static bool MulWillOverflow(APInt &C0, APInt &C1, bool IsSigned) {
1056   bool overflow;
1057   if (IsSigned)
1058     (void)C0.smul_ov(C1, overflow);
1059   else
1060     (void)C0.umul_ov(C1, overflow);
1061   return overflow;
1062 }
1063 
1064 // Simplifies X % C0 + (( X / C0 ) % C1) * C0 to X % (C0 * C1), where (C0 * C1)
1065 // does not overflow.
1066 Value *InstCombinerImpl::SimplifyAddWithRemainder(BinaryOperator &I) {
1067   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1068   Value *X, *MulOpV;
1069   APInt C0, MulOpC;
1070   bool IsSigned;
1071   // Match I = X % C0 + MulOpV * C0
1072   if (((MatchRem(LHS, X, C0, IsSigned) && MatchMul(RHS, MulOpV, MulOpC)) ||
1073        (MatchRem(RHS, X, C0, IsSigned) && MatchMul(LHS, MulOpV, MulOpC))) &&
1074       C0 == MulOpC) {
1075     Value *RemOpV;
1076     APInt C1;
1077     bool Rem2IsSigned;
1078     // Match MulOpC = RemOpV % C1
1079     if (MatchRem(MulOpV, RemOpV, C1, Rem2IsSigned) &&
1080         IsSigned == Rem2IsSigned) {
1081       Value *DivOpV;
1082       APInt DivOpC;
1083       // Match RemOpV = X / C0
1084       if (MatchDiv(RemOpV, DivOpV, DivOpC, IsSigned) && X == DivOpV &&
1085           C0 == DivOpC && !MulWillOverflow(C0, C1, IsSigned)) {
1086         Value *NewDivisor = ConstantInt::get(X->getType(), C0 * C1);
1087         return IsSigned ? Builder.CreateSRem(X, NewDivisor, "srem")
1088                         : Builder.CreateURem(X, NewDivisor, "urem");
1089       }
1090     }
1091   }
1092 
1093   return nullptr;
1094 }
1095 
1096 /// Fold
1097 ///   (1 << NBits) - 1
1098 /// Into:
1099 ///   ~(-(1 << NBits))
1100 /// Because a 'not' is better for bit-tracking analysis and other transforms
1101 /// than an 'add'. The new shl is always nsw, and is nuw if old `and` was.
1102 static Instruction *canonicalizeLowbitMask(BinaryOperator &I,
1103                                            InstCombiner::BuilderTy &Builder) {
1104   Value *NBits;
1105   if (!match(&I, m_Add(m_OneUse(m_Shl(m_One(), m_Value(NBits))), m_AllOnes())))
1106     return nullptr;
1107 
1108   Constant *MinusOne = Constant::getAllOnesValue(NBits->getType());
1109   Value *NotMask = Builder.CreateShl(MinusOne, NBits, "notmask");
1110   // Be wary of constant folding.
1111   if (auto *BOp = dyn_cast<BinaryOperator>(NotMask)) {
1112     // Always NSW. But NUW propagates from `add`.
1113     BOp->setHasNoSignedWrap();
1114     BOp->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
1115   }
1116 
1117   return BinaryOperator::CreateNot(NotMask, I.getName());
1118 }
1119 
1120 static Instruction *foldToUnsignedSaturatedAdd(BinaryOperator &I) {
1121   assert(I.getOpcode() == Instruction::Add && "Expecting add instruction");
1122   Type *Ty = I.getType();
1123   auto getUAddSat = [&]() {
1124     return Intrinsic::getDeclaration(I.getModule(), Intrinsic::uadd_sat, Ty);
1125   };
1126 
1127   // add (umin X, ~Y), Y --> uaddsat X, Y
1128   Value *X, *Y;
1129   if (match(&I, m_c_Add(m_c_UMin(m_Value(X), m_Not(m_Value(Y))),
1130                         m_Deferred(Y))))
1131     return CallInst::Create(getUAddSat(), { X, Y });
1132 
1133   // add (umin X, ~C), C --> uaddsat X, C
1134   const APInt *C, *NotC;
1135   if (match(&I, m_Add(m_UMin(m_Value(X), m_APInt(NotC)), m_APInt(C))) &&
1136       *C == ~*NotC)
1137     return CallInst::Create(getUAddSat(), { X, ConstantInt::get(Ty, *C) });
1138 
1139   return nullptr;
1140 }
1141 
1142 Instruction *InstCombinerImpl::
1143     canonicalizeCondSignextOfHighBitExtractToSignextHighBitExtract(
1144         BinaryOperator &I) {
1145   assert((I.getOpcode() == Instruction::Add ||
1146           I.getOpcode() == Instruction::Or ||
1147           I.getOpcode() == Instruction::Sub) &&
1148          "Expecting add/or/sub instruction");
1149 
1150   // We have a subtraction/addition between a (potentially truncated) *logical*
1151   // right-shift of X and a "select".
1152   Value *X, *Select;
1153   Instruction *LowBitsToSkip, *Extract;
1154   if (!match(&I, m_c_BinOp(m_TruncOrSelf(m_CombineAnd(
1155                                m_LShr(m_Value(X), m_Instruction(LowBitsToSkip)),
1156                                m_Instruction(Extract))),
1157                            m_Value(Select))))
1158     return nullptr;
1159 
1160   // `add`/`or` is commutative; but for `sub`, "select" *must* be on RHS.
1161   if (I.getOpcode() == Instruction::Sub && I.getOperand(1) != Select)
1162     return nullptr;
1163 
1164   Type *XTy = X->getType();
1165   bool HadTrunc = I.getType() != XTy;
1166 
1167   // If there was a truncation of extracted value, then we'll need to produce
1168   // one extra instruction, so we need to ensure one instruction will go away.
1169   if (HadTrunc && !match(&I, m_c_BinOp(m_OneUse(m_Value()), m_Value())))
1170     return nullptr;
1171 
1172   // Extraction should extract high NBits bits, with shift amount calculated as:
1173   //   low bits to skip = shift bitwidth - high bits to extract
1174   // The shift amount itself may be extended, and we need to look past zero-ext
1175   // when matching NBits, that will matter for matching later.
1176   Constant *C;
1177   Value *NBits;
1178   if (!match(
1179           LowBitsToSkip,
1180           m_ZExtOrSelf(m_Sub(m_Constant(C), m_ZExtOrSelf(m_Value(NBits))))) ||
1181       !match(C, m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_EQ,
1182                                    APInt(C->getType()->getScalarSizeInBits(),
1183                                          X->getType()->getScalarSizeInBits()))))
1184     return nullptr;
1185 
1186   // Sign-extending value can be zero-extended if we `sub`tract it,
1187   // or sign-extended otherwise.
1188   auto SkipExtInMagic = [&I](Value *&V) {
1189     if (I.getOpcode() == Instruction::Sub)
1190       match(V, m_ZExtOrSelf(m_Value(V)));
1191     else
1192       match(V, m_SExtOrSelf(m_Value(V)));
1193   };
1194 
1195   // Now, finally validate the sign-extending magic.
1196   // `select` itself may be appropriately extended, look past that.
1197   SkipExtInMagic(Select);
1198 
1199   ICmpInst::Predicate Pred;
1200   const APInt *Thr;
1201   Value *SignExtendingValue, *Zero;
1202   bool ShouldSignext;
1203   // It must be a select between two values we will later establish to be a
1204   // sign-extending value and a zero constant. The condition guarding the
1205   // sign-extension must be based on a sign bit of the same X we had in `lshr`.
1206   if (!match(Select, m_Select(m_ICmp(Pred, m_Specific(X), m_APInt(Thr)),
1207                               m_Value(SignExtendingValue), m_Value(Zero))) ||
1208       !isSignBitCheck(Pred, *Thr, ShouldSignext))
1209     return nullptr;
1210 
1211   // icmp-select pair is commutative.
1212   if (!ShouldSignext)
1213     std::swap(SignExtendingValue, Zero);
1214 
1215   // If we should not perform sign-extension then we must add/or/subtract zero.
1216   if (!match(Zero, m_Zero()))
1217     return nullptr;
1218   // Otherwise, it should be some constant, left-shifted by the same NBits we
1219   // had in `lshr`. Said left-shift can also be appropriately extended.
1220   // Again, we must look past zero-ext when looking for NBits.
1221   SkipExtInMagic(SignExtendingValue);
1222   Constant *SignExtendingValueBaseConstant;
1223   if (!match(SignExtendingValue,
1224              m_Shl(m_Constant(SignExtendingValueBaseConstant),
1225                    m_ZExtOrSelf(m_Specific(NBits)))))
1226     return nullptr;
1227   // If we `sub`, then the constant should be one, else it should be all-ones.
1228   if (I.getOpcode() == Instruction::Sub
1229           ? !match(SignExtendingValueBaseConstant, m_One())
1230           : !match(SignExtendingValueBaseConstant, m_AllOnes()))
1231     return nullptr;
1232 
1233   auto *NewAShr = BinaryOperator::CreateAShr(X, LowBitsToSkip,
1234                                              Extract->getName() + ".sext");
1235   NewAShr->copyIRFlags(Extract); // Preserve `exact`-ness.
1236   if (!HadTrunc)
1237     return NewAShr;
1238 
1239   Builder.Insert(NewAShr);
1240   return TruncInst::CreateTruncOrBitCast(NewAShr, I.getType());
1241 }
1242 
1243 /// This is a specialization of a more general transform from
1244 /// SimplifyUsingDistributiveLaws. If that code can be made to work optimally
1245 /// for multi-use cases or propagating nsw/nuw, then we would not need this.
1246 static Instruction *factorizeMathWithShlOps(BinaryOperator &I,
1247                                             InstCombiner::BuilderTy &Builder) {
1248   // TODO: Also handle mul by doubling the shift amount?
1249   assert((I.getOpcode() == Instruction::Add ||
1250           I.getOpcode() == Instruction::Sub) &&
1251          "Expected add/sub");
1252   auto *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0));
1253   auto *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1));
1254   if (!Op0 || !Op1 || !(Op0->hasOneUse() || Op1->hasOneUse()))
1255     return nullptr;
1256 
1257   Value *X, *Y, *ShAmt;
1258   if (!match(Op0, m_Shl(m_Value(X), m_Value(ShAmt))) ||
1259       !match(Op1, m_Shl(m_Value(Y), m_Specific(ShAmt))))
1260     return nullptr;
1261 
1262   // No-wrap propagates only when all ops have no-wrap.
1263   bool HasNSW = I.hasNoSignedWrap() && Op0->hasNoSignedWrap() &&
1264                 Op1->hasNoSignedWrap();
1265   bool HasNUW = I.hasNoUnsignedWrap() && Op0->hasNoUnsignedWrap() &&
1266                 Op1->hasNoUnsignedWrap();
1267 
1268   // add/sub (X << ShAmt), (Y << ShAmt) --> (add/sub X, Y) << ShAmt
1269   Value *NewMath = Builder.CreateBinOp(I.getOpcode(), X, Y);
1270   if (auto *NewI = dyn_cast<BinaryOperator>(NewMath)) {
1271     NewI->setHasNoSignedWrap(HasNSW);
1272     NewI->setHasNoUnsignedWrap(HasNUW);
1273   }
1274   auto *NewShl = BinaryOperator::CreateShl(NewMath, ShAmt);
1275   NewShl->setHasNoSignedWrap(HasNSW);
1276   NewShl->setHasNoUnsignedWrap(HasNUW);
1277   return NewShl;
1278 }
1279 
1280 Instruction *InstCombinerImpl::visitAdd(BinaryOperator &I) {
1281   if (Value *V = SimplifyAddInst(I.getOperand(0), I.getOperand(1),
1282                                  I.hasNoSignedWrap(), I.hasNoUnsignedWrap(),
1283                                  SQ.getWithInstruction(&I)))
1284     return replaceInstUsesWith(I, V);
1285 
1286   if (SimplifyAssociativeOrCommutative(I))
1287     return &I;
1288 
1289   if (Instruction *X = foldVectorBinop(I))
1290     return X;
1291 
1292   // (A*B)+(A*C) -> A*(B+C) etc
1293   if (Value *V = SimplifyUsingDistributiveLaws(I))
1294     return replaceInstUsesWith(I, V);
1295 
1296   if (Instruction *R = factorizeMathWithShlOps(I, Builder))
1297     return R;
1298 
1299   if (Instruction *X = foldAddWithConstant(I))
1300     return X;
1301 
1302   if (Instruction *X = foldNoWrapAdd(I, Builder))
1303     return X;
1304 
1305   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1306   Type *Ty = I.getType();
1307   if (Ty->isIntOrIntVectorTy(1))
1308     return BinaryOperator::CreateXor(LHS, RHS);
1309 
1310   // X + X --> X << 1
1311   if (LHS == RHS) {
1312     auto *Shl = BinaryOperator::CreateShl(LHS, ConstantInt::get(Ty, 1));
1313     Shl->setHasNoSignedWrap(I.hasNoSignedWrap());
1314     Shl->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
1315     return Shl;
1316   }
1317 
1318   Value *A, *B;
1319   if (match(LHS, m_Neg(m_Value(A)))) {
1320     // -A + -B --> -(A + B)
1321     if (match(RHS, m_Neg(m_Value(B))))
1322       return BinaryOperator::CreateNeg(Builder.CreateAdd(A, B));
1323 
1324     // -A + B --> B - A
1325     return BinaryOperator::CreateSub(RHS, A);
1326   }
1327 
1328   // A + -B  -->  A - B
1329   if (match(RHS, m_Neg(m_Value(B))))
1330     return BinaryOperator::CreateSub(LHS, B);
1331 
1332   if (Value *V = checkForNegativeOperand(I, Builder))
1333     return replaceInstUsesWith(I, V);
1334 
1335   // (A + 1) + ~B --> A - B
1336   // ~B + (A + 1) --> A - B
1337   // (~B + A) + 1 --> A - B
1338   // (A + ~B) + 1 --> A - B
1339   if (match(&I, m_c_BinOp(m_Add(m_Value(A), m_One()), m_Not(m_Value(B)))) ||
1340       match(&I, m_BinOp(m_c_Add(m_Not(m_Value(B)), m_Value(A)), m_One())))
1341     return BinaryOperator::CreateSub(A, B);
1342 
1343   // (A + RHS) + RHS --> A + (RHS << 1)
1344   if (match(LHS, m_OneUse(m_c_Add(m_Value(A), m_Specific(RHS)))))
1345     return BinaryOperator::CreateAdd(A, Builder.CreateShl(RHS, 1, "reass.add"));
1346 
1347   // LHS + (A + LHS) --> A + (LHS << 1)
1348   if (match(RHS, m_OneUse(m_c_Add(m_Value(A), m_Specific(LHS)))))
1349     return BinaryOperator::CreateAdd(A, Builder.CreateShl(LHS, 1, "reass.add"));
1350 
1351   // X % C0 + (( X / C0 ) % C1) * C0 => X % (C0 * C1)
1352   if (Value *V = SimplifyAddWithRemainder(I)) return replaceInstUsesWith(I, V);
1353 
1354   // ((X s/ C1) << C2) + X => X s% -C1 where -C1 is 1 << C2
1355   const APInt *C1, *C2;
1356   if (match(LHS, m_Shl(m_SDiv(m_Specific(RHS), m_APInt(C1)), m_APInt(C2)))) {
1357     APInt one(C2->getBitWidth(), 1);
1358     APInt minusC1 = -(*C1);
1359     if (minusC1 == (one << *C2)) {
1360       Constant *NewRHS = ConstantInt::get(RHS->getType(), minusC1);
1361       return BinaryOperator::CreateSRem(RHS, NewRHS);
1362     }
1363   }
1364 
1365   // A+B --> A|B iff A and B have no bits set in common.
1366   if (haveNoCommonBitsSet(LHS, RHS, DL, &AC, &I, &DT))
1367     return BinaryOperator::CreateOr(LHS, RHS);
1368 
1369   // add (select X 0 (sub n A)) A  -->  select X A n
1370   {
1371     SelectInst *SI = dyn_cast<SelectInst>(LHS);
1372     Value *A = RHS;
1373     if (!SI) {
1374       SI = dyn_cast<SelectInst>(RHS);
1375       A = LHS;
1376     }
1377     if (SI && SI->hasOneUse()) {
1378       Value *TV = SI->getTrueValue();
1379       Value *FV = SI->getFalseValue();
1380       Value *N;
1381 
1382       // Can we fold the add into the argument of the select?
1383       // We check both true and false select arguments for a matching subtract.
1384       if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
1385         // Fold the add into the true select value.
1386         return SelectInst::Create(SI->getCondition(), N, A);
1387 
1388       if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
1389         // Fold the add into the false select value.
1390         return SelectInst::Create(SI->getCondition(), A, N);
1391     }
1392   }
1393 
1394   if (Instruction *Ext = narrowMathIfNoOverflow(I))
1395     return Ext;
1396 
1397   // (add (xor A, B) (and A, B)) --> (or A, B)
1398   // (add (and A, B) (xor A, B)) --> (or A, B)
1399   if (match(&I, m_c_BinOp(m_Xor(m_Value(A), m_Value(B)),
1400                           m_c_And(m_Deferred(A), m_Deferred(B)))))
1401     return BinaryOperator::CreateOr(A, B);
1402 
1403   // (add (or A, B) (and A, B)) --> (add A, B)
1404   // (add (and A, B) (or A, B)) --> (add A, B)
1405   if (match(&I, m_c_BinOp(m_Or(m_Value(A), m_Value(B)),
1406                           m_c_And(m_Deferred(A), m_Deferred(B))))) {
1407     // Replacing operands in-place to preserve nuw/nsw flags.
1408     replaceOperand(I, 0, A);
1409     replaceOperand(I, 1, B);
1410     return &I;
1411   }
1412 
1413   // TODO(jingyue): Consider willNotOverflowSignedAdd and
1414   // willNotOverflowUnsignedAdd to reduce the number of invocations of
1415   // computeKnownBits.
1416   bool Changed = false;
1417   if (!I.hasNoSignedWrap() && willNotOverflowSignedAdd(LHS, RHS, I)) {
1418     Changed = true;
1419     I.setHasNoSignedWrap(true);
1420   }
1421   if (!I.hasNoUnsignedWrap() && willNotOverflowUnsignedAdd(LHS, RHS, I)) {
1422     Changed = true;
1423     I.setHasNoUnsignedWrap(true);
1424   }
1425 
1426   if (Instruction *V = canonicalizeLowbitMask(I, Builder))
1427     return V;
1428 
1429   if (Instruction *V =
1430           canonicalizeCondSignextOfHighBitExtractToSignextHighBitExtract(I))
1431     return V;
1432 
1433   if (Instruction *SatAdd = foldToUnsignedSaturatedAdd(I))
1434     return SatAdd;
1435 
1436   // usub.sat(A, B) + B => umax(A, B)
1437   if (match(&I, m_c_BinOp(
1438           m_OneUse(m_Intrinsic<Intrinsic::usub_sat>(m_Value(A), m_Value(B))),
1439           m_Deferred(B)))) {
1440     return replaceInstUsesWith(I,
1441         Builder.CreateIntrinsic(Intrinsic::umax, {I.getType()}, {A, B}));
1442   }
1443 
1444   return Changed ? &I : nullptr;
1445 }
1446 
1447 /// Eliminate an op from a linear interpolation (lerp) pattern.
1448 static Instruction *factorizeLerp(BinaryOperator &I,
1449                                   InstCombiner::BuilderTy &Builder) {
1450   Value *X, *Y, *Z;
1451   if (!match(&I, m_c_FAdd(m_OneUse(m_c_FMul(m_Value(Y),
1452                                             m_OneUse(m_FSub(m_FPOne(),
1453                                                             m_Value(Z))))),
1454                           m_OneUse(m_c_FMul(m_Value(X), m_Deferred(Z))))))
1455     return nullptr;
1456 
1457   // (Y * (1.0 - Z)) + (X * Z) --> Y + Z * (X - Y) [8 commuted variants]
1458   Value *XY = Builder.CreateFSubFMF(X, Y, &I);
1459   Value *MulZ = Builder.CreateFMulFMF(Z, XY, &I);
1460   return BinaryOperator::CreateFAddFMF(Y, MulZ, &I);
1461 }
1462 
1463 /// Factor a common operand out of fadd/fsub of fmul/fdiv.
1464 static Instruction *factorizeFAddFSub(BinaryOperator &I,
1465                                       InstCombiner::BuilderTy &Builder) {
1466   assert((I.getOpcode() == Instruction::FAdd ||
1467           I.getOpcode() == Instruction::FSub) && "Expecting fadd/fsub");
1468   assert(I.hasAllowReassoc() && I.hasNoSignedZeros() &&
1469          "FP factorization requires FMF");
1470 
1471   if (Instruction *Lerp = factorizeLerp(I, Builder))
1472     return Lerp;
1473 
1474   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1475   Value *X, *Y, *Z;
1476   bool IsFMul;
1477   if ((match(Op0, m_OneUse(m_FMul(m_Value(X), m_Value(Z)))) &&
1478        match(Op1, m_OneUse(m_c_FMul(m_Value(Y), m_Specific(Z))))) ||
1479       (match(Op0, m_OneUse(m_FMul(m_Value(Z), m_Value(X)))) &&
1480        match(Op1, m_OneUse(m_c_FMul(m_Value(Y), m_Specific(Z))))))
1481     IsFMul = true;
1482   else if (match(Op0, m_OneUse(m_FDiv(m_Value(X), m_Value(Z)))) &&
1483            match(Op1, m_OneUse(m_FDiv(m_Value(Y), m_Specific(Z)))))
1484     IsFMul = false;
1485   else
1486     return nullptr;
1487 
1488   // (X * Z) + (Y * Z) --> (X + Y) * Z
1489   // (X * Z) - (Y * Z) --> (X - Y) * Z
1490   // (X / Z) + (Y / Z) --> (X + Y) / Z
1491   // (X / Z) - (Y / Z) --> (X - Y) / Z
1492   bool IsFAdd = I.getOpcode() == Instruction::FAdd;
1493   Value *XY = IsFAdd ? Builder.CreateFAddFMF(X, Y, &I)
1494                      : Builder.CreateFSubFMF(X, Y, &I);
1495 
1496   // Bail out if we just created a denormal constant.
1497   // TODO: This is copied from a previous implementation. Is it necessary?
1498   const APFloat *C;
1499   if (match(XY, m_APFloat(C)) && !C->isNormal())
1500     return nullptr;
1501 
1502   return IsFMul ? BinaryOperator::CreateFMulFMF(XY, Z, &I)
1503                 : BinaryOperator::CreateFDivFMF(XY, Z, &I);
1504 }
1505 
1506 Instruction *InstCombinerImpl::visitFAdd(BinaryOperator &I) {
1507   if (Value *V = SimplifyFAddInst(I.getOperand(0), I.getOperand(1),
1508                                   I.getFastMathFlags(),
1509                                   SQ.getWithInstruction(&I)))
1510     return replaceInstUsesWith(I, V);
1511 
1512   if (SimplifyAssociativeOrCommutative(I))
1513     return &I;
1514 
1515   if (Instruction *X = foldVectorBinop(I))
1516     return X;
1517 
1518   if (Instruction *FoldedFAdd = foldBinOpIntoSelectOrPhi(I))
1519     return FoldedFAdd;
1520 
1521   // (-X) + Y --> Y - X
1522   Value *X, *Y;
1523   if (match(&I, m_c_FAdd(m_FNeg(m_Value(X)), m_Value(Y))))
1524     return BinaryOperator::CreateFSubFMF(Y, X, &I);
1525 
1526   // Similar to above, but look through fmul/fdiv for the negated term.
1527   // (-X * Y) + Z --> Z - (X * Y) [4 commuted variants]
1528   Value *Z;
1529   if (match(&I, m_c_FAdd(m_OneUse(m_c_FMul(m_FNeg(m_Value(X)), m_Value(Y))),
1530                          m_Value(Z)))) {
1531     Value *XY = Builder.CreateFMulFMF(X, Y, &I);
1532     return BinaryOperator::CreateFSubFMF(Z, XY, &I);
1533   }
1534   // (-X / Y) + Z --> Z - (X / Y) [2 commuted variants]
1535   // (X / -Y) + Z --> Z - (X / Y) [2 commuted variants]
1536   if (match(&I, m_c_FAdd(m_OneUse(m_FDiv(m_FNeg(m_Value(X)), m_Value(Y))),
1537                          m_Value(Z))) ||
1538       match(&I, m_c_FAdd(m_OneUse(m_FDiv(m_Value(X), m_FNeg(m_Value(Y)))),
1539                          m_Value(Z)))) {
1540     Value *XY = Builder.CreateFDivFMF(X, Y, &I);
1541     return BinaryOperator::CreateFSubFMF(Z, XY, &I);
1542   }
1543 
1544   // Check for (fadd double (sitofp x), y), see if we can merge this into an
1545   // integer add followed by a promotion.
1546   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1547   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
1548     Value *LHSIntVal = LHSConv->getOperand(0);
1549     Type *FPType = LHSConv->getType();
1550 
1551     // TODO: This check is overly conservative. In many cases known bits
1552     // analysis can tell us that the result of the addition has less significant
1553     // bits than the integer type can hold.
1554     auto IsValidPromotion = [](Type *FTy, Type *ITy) {
1555       Type *FScalarTy = FTy->getScalarType();
1556       Type *IScalarTy = ITy->getScalarType();
1557 
1558       // Do we have enough bits in the significand to represent the result of
1559       // the integer addition?
1560       unsigned MaxRepresentableBits =
1561           APFloat::semanticsPrecision(FScalarTy->getFltSemantics());
1562       return IScalarTy->getIntegerBitWidth() <= MaxRepresentableBits;
1563     };
1564 
1565     // (fadd double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
1566     // ... if the constant fits in the integer value.  This is useful for things
1567     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
1568     // requires a constant pool load, and generally allows the add to be better
1569     // instcombined.
1570     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
1571       if (IsValidPromotion(FPType, LHSIntVal->getType())) {
1572         Constant *CI =
1573           ConstantExpr::getFPToSI(CFP, LHSIntVal->getType());
1574         if (LHSConv->hasOneUse() &&
1575             ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
1576             willNotOverflowSignedAdd(LHSIntVal, CI, I)) {
1577           // Insert the new integer add.
1578           Value *NewAdd = Builder.CreateNSWAdd(LHSIntVal, CI, "addconv");
1579           return new SIToFPInst(NewAdd, I.getType());
1580         }
1581       }
1582 
1583     // (fadd double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
1584     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
1585       Value *RHSIntVal = RHSConv->getOperand(0);
1586       // It's enough to check LHS types only because we require int types to
1587       // be the same for this transform.
1588       if (IsValidPromotion(FPType, LHSIntVal->getType())) {
1589         // Only do this if x/y have the same type, if at least one of them has a
1590         // single use (so we don't increase the number of int->fp conversions),
1591         // and if the integer add will not overflow.
1592         if (LHSIntVal->getType() == RHSIntVal->getType() &&
1593             (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
1594             willNotOverflowSignedAdd(LHSIntVal, RHSIntVal, I)) {
1595           // Insert the new integer add.
1596           Value *NewAdd = Builder.CreateNSWAdd(LHSIntVal, RHSIntVal, "addconv");
1597           return new SIToFPInst(NewAdd, I.getType());
1598         }
1599       }
1600     }
1601   }
1602 
1603   // Handle specials cases for FAdd with selects feeding the operation
1604   if (Value *V = SimplifySelectsFeedingBinaryOp(I, LHS, RHS))
1605     return replaceInstUsesWith(I, V);
1606 
1607   if (I.hasAllowReassoc() && I.hasNoSignedZeros()) {
1608     if (Instruction *F = factorizeFAddFSub(I, Builder))
1609       return F;
1610     if (Value *V = FAddCombine(Builder).simplify(&I))
1611       return replaceInstUsesWith(I, V);
1612   }
1613 
1614   return nullptr;
1615 }
1616 
1617 /// Optimize pointer differences into the same array into a size.  Consider:
1618 ///  &A[10] - &A[0]: we should compile this to "10".  LHS/RHS are the pointer
1619 /// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
1620 Value *InstCombinerImpl::OptimizePointerDifference(Value *LHS, Value *RHS,
1621                                                    Type *Ty, bool IsNUW) {
1622   // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
1623   // this.
1624   bool Swapped = false;
1625   GEPOperator *GEP1 = nullptr, *GEP2 = nullptr;
1626   if (!isa<GEPOperator>(LHS) && isa<GEPOperator>(RHS)) {
1627     std::swap(LHS, RHS);
1628     Swapped = true;
1629   }
1630 
1631   // Require at least one GEP with a common base pointer on both sides.
1632   if (auto *LHSGEP = dyn_cast<GEPOperator>(LHS)) {
1633     // (gep X, ...) - X
1634     if (LHSGEP->getOperand(0) == RHS) {
1635       GEP1 = LHSGEP;
1636     } else if (auto *RHSGEP = dyn_cast<GEPOperator>(RHS)) {
1637       // (gep X, ...) - (gep X, ...)
1638       if (LHSGEP->getOperand(0)->stripPointerCasts() ==
1639           RHSGEP->getOperand(0)->stripPointerCasts()) {
1640         GEP1 = LHSGEP;
1641         GEP2 = RHSGEP;
1642       }
1643     }
1644   }
1645 
1646   if (!GEP1)
1647     return nullptr;
1648 
1649   if (GEP2) {
1650     // (gep X, ...) - (gep X, ...)
1651     //
1652     // Avoid duplicating the arithmetic if there are more than one non-constant
1653     // indices between the two GEPs and either GEP has a non-constant index and
1654     // multiple users. If zero non-constant index, the result is a constant and
1655     // there is no duplication. If one non-constant index, the result is an add
1656     // or sub with a constant, which is no larger than the original code, and
1657     // there's no duplicated arithmetic, even if either GEP has multiple
1658     // users. If more than one non-constant indices combined, as long as the GEP
1659     // with at least one non-constant index doesn't have multiple users, there
1660     // is no duplication.
1661     unsigned NumNonConstantIndices1 = GEP1->countNonConstantIndices();
1662     unsigned NumNonConstantIndices2 = GEP2->countNonConstantIndices();
1663     if (NumNonConstantIndices1 + NumNonConstantIndices2 > 1 &&
1664         ((NumNonConstantIndices1 > 0 && !GEP1->hasOneUse()) ||
1665          (NumNonConstantIndices2 > 0 && !GEP2->hasOneUse()))) {
1666       return nullptr;
1667     }
1668   }
1669 
1670   // Emit the offset of the GEP and an intptr_t.
1671   Value *Result = EmitGEPOffset(GEP1);
1672 
1673   // If this is a single inbounds GEP and the original sub was nuw,
1674   // then the final multiplication is also nuw.
1675   if (auto *I = dyn_cast<Instruction>(Result))
1676     if (IsNUW && !GEP2 && !Swapped && GEP1->isInBounds() &&
1677         I->getOpcode() == Instruction::Mul)
1678       I->setHasNoUnsignedWrap();
1679 
1680   // If we have a 2nd GEP of the same base pointer, subtract the offsets.
1681   // If both GEPs are inbounds, then the subtract does not have signed overflow.
1682   if (GEP2) {
1683     Value *Offset = EmitGEPOffset(GEP2);
1684     Result = Builder.CreateSub(Result, Offset, "gepdiff", /* NUW */ false,
1685                                GEP1->isInBounds() && GEP2->isInBounds());
1686   }
1687 
1688   // If we have p - gep(p, ...)  then we have to negate the result.
1689   if (Swapped)
1690     Result = Builder.CreateNeg(Result, "diff.neg");
1691 
1692   return Builder.CreateIntCast(Result, Ty, true);
1693 }
1694 
1695 Instruction *InstCombinerImpl::visitSub(BinaryOperator &I) {
1696   if (Value *V = SimplifySubInst(I.getOperand(0), I.getOperand(1),
1697                                  I.hasNoSignedWrap(), I.hasNoUnsignedWrap(),
1698                                  SQ.getWithInstruction(&I)))
1699     return replaceInstUsesWith(I, V);
1700 
1701   if (Instruction *X = foldVectorBinop(I))
1702     return X;
1703 
1704   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1705 
1706   // If this is a 'B = x-(-A)', change to B = x+A.
1707   // We deal with this without involving Negator to preserve NSW flag.
1708   if (Value *V = dyn_castNegVal(Op1)) {
1709     BinaryOperator *Res = BinaryOperator::CreateAdd(Op0, V);
1710 
1711     if (const auto *BO = dyn_cast<BinaryOperator>(Op1)) {
1712       assert(BO->getOpcode() == Instruction::Sub &&
1713              "Expected a subtraction operator!");
1714       if (BO->hasNoSignedWrap() && I.hasNoSignedWrap())
1715         Res->setHasNoSignedWrap(true);
1716     } else {
1717       if (cast<Constant>(Op1)->isNotMinSignedValue() && I.hasNoSignedWrap())
1718         Res->setHasNoSignedWrap(true);
1719     }
1720 
1721     return Res;
1722   }
1723 
1724   // Try this before Negator to preserve NSW flag.
1725   if (Instruction *R = factorizeMathWithShlOps(I, Builder))
1726     return R;
1727 
1728   if (Constant *C = dyn_cast<Constant>(Op0)) {
1729     Value *X;
1730     Constant *C2;
1731 
1732     // C-(X+C2) --> (C-C2)-X
1733     if (match(Op1, m_Add(m_Value(X), m_Constant(C2))))
1734       return BinaryOperator::CreateSub(ConstantExpr::getSub(C, C2), X);
1735   }
1736 
1737   auto TryToNarrowDeduceFlags = [this, &I, &Op0, &Op1]() -> Instruction * {
1738     if (Instruction *Ext = narrowMathIfNoOverflow(I))
1739       return Ext;
1740 
1741     bool Changed = false;
1742     if (!I.hasNoSignedWrap() && willNotOverflowSignedSub(Op0, Op1, I)) {
1743       Changed = true;
1744       I.setHasNoSignedWrap(true);
1745     }
1746     if (!I.hasNoUnsignedWrap() && willNotOverflowUnsignedSub(Op0, Op1, I)) {
1747       Changed = true;
1748       I.setHasNoUnsignedWrap(true);
1749     }
1750 
1751     return Changed ? &I : nullptr;
1752   };
1753 
1754   // First, let's try to interpret `sub a, b` as `add a, (sub 0, b)`,
1755   // and let's try to sink `(sub 0, b)` into `b` itself. But only if this isn't
1756   // a pure negation used by a select that looks like abs/nabs.
1757   bool IsNegation = match(Op0, m_ZeroInt());
1758   if (!IsNegation || none_of(I.users(), [&I, Op1](const User *U) {
1759         const Instruction *UI = dyn_cast<Instruction>(U);
1760         if (!UI)
1761           return false;
1762         return match(UI,
1763                      m_Select(m_Value(), m_Specific(Op1), m_Specific(&I))) ||
1764                match(UI, m_Select(m_Value(), m_Specific(&I), m_Specific(Op1)));
1765       })) {
1766     if (Value *NegOp1 = Negator::Negate(IsNegation, Op1, *this))
1767       return BinaryOperator::CreateAdd(NegOp1, Op0);
1768   }
1769   if (IsNegation)
1770     return TryToNarrowDeduceFlags(); // Should have been handled in Negator!
1771 
1772   // (A*B)-(A*C) -> A*(B-C) etc
1773   if (Value *V = SimplifyUsingDistributiveLaws(I))
1774     return replaceInstUsesWith(I, V);
1775 
1776   if (I.getType()->isIntOrIntVectorTy(1))
1777     return BinaryOperator::CreateXor(Op0, Op1);
1778 
1779   // Replace (-1 - A) with (~A).
1780   if (match(Op0, m_AllOnes()))
1781     return BinaryOperator::CreateNot(Op1);
1782 
1783   // (~X) - (~Y) --> Y - X
1784   Value *X, *Y;
1785   if (match(Op0, m_Not(m_Value(X))) && match(Op1, m_Not(m_Value(Y))))
1786     return BinaryOperator::CreateSub(Y, X);
1787 
1788   // (X + -1) - Y --> ~Y + X
1789   if (match(Op0, m_OneUse(m_Add(m_Value(X), m_AllOnes()))))
1790     return BinaryOperator::CreateAdd(Builder.CreateNot(Op1), X);
1791 
1792   // Reassociate sub/add sequences to create more add instructions and
1793   // reduce dependency chains:
1794   // ((X - Y) + Z) - Op1 --> (X + Z) - (Y + Op1)
1795   Value *Z;
1796   if (match(Op0, m_OneUse(m_c_Add(m_OneUse(m_Sub(m_Value(X), m_Value(Y))),
1797                                   m_Value(Z))))) {
1798     Value *XZ = Builder.CreateAdd(X, Z);
1799     Value *YW = Builder.CreateAdd(Y, Op1);
1800     return BinaryOperator::CreateSub(XZ, YW);
1801   }
1802 
1803   auto m_AddRdx = [](Value *&Vec) {
1804     return m_OneUse(m_Intrinsic<Intrinsic::vector_reduce_add>(m_Value(Vec)));
1805   };
1806   Value *V0, *V1;
1807   if (match(Op0, m_AddRdx(V0)) && match(Op1, m_AddRdx(V1)) &&
1808       V0->getType() == V1->getType()) {
1809     // Difference of sums is sum of differences:
1810     // add_rdx(V0) - add_rdx(V1) --> add_rdx(V0 - V1)
1811     Value *Sub = Builder.CreateSub(V0, V1);
1812     Value *Rdx = Builder.CreateIntrinsic(Intrinsic::vector_reduce_add,
1813                                          {Sub->getType()}, {Sub});
1814     return replaceInstUsesWith(I, Rdx);
1815   }
1816 
1817   if (Constant *C = dyn_cast<Constant>(Op0)) {
1818     Value *X;
1819     if (match(Op1, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
1820       // C - (zext bool) --> bool ? C - 1 : C
1821       return SelectInst::Create(X, InstCombiner::SubOne(C), C);
1822     if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
1823       // C - (sext bool) --> bool ? C + 1 : C
1824       return SelectInst::Create(X, InstCombiner::AddOne(C), C);
1825 
1826     // C - ~X == X + (1+C)
1827     if (match(Op1, m_Not(m_Value(X))))
1828       return BinaryOperator::CreateAdd(X, InstCombiner::AddOne(C));
1829 
1830     // Try to fold constant sub into select arguments.
1831     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1832       if (Instruction *R = FoldOpIntoSelect(I, SI))
1833         return R;
1834 
1835     // Try to fold constant sub into PHI values.
1836     if (PHINode *PN = dyn_cast<PHINode>(Op1))
1837       if (Instruction *R = foldOpIntoPhi(I, PN))
1838         return R;
1839 
1840     Constant *C2;
1841 
1842     // C-(C2-X) --> X+(C-C2)
1843     if (match(Op1, m_Sub(m_Constant(C2), m_Value(X))) && !isa<ConstantExpr>(C2))
1844       return BinaryOperator::CreateAdd(X, ConstantExpr::getSub(C, C2));
1845   }
1846 
1847   const APInt *Op0C;
1848   if (match(Op0, m_APInt(Op0C)) && Op0C->isMask()) {
1849     // Turn this into a xor if LHS is 2^n-1 and the remaining bits are known
1850     // zero.
1851     KnownBits RHSKnown = computeKnownBits(Op1, 0, &I);
1852     if ((*Op0C | RHSKnown.Zero).isAllOnesValue())
1853       return BinaryOperator::CreateXor(Op1, Op0);
1854   }
1855 
1856   {
1857     Value *Y;
1858     // X-(X+Y) == -Y    X-(Y+X) == -Y
1859     if (match(Op1, m_c_Add(m_Specific(Op0), m_Value(Y))))
1860       return BinaryOperator::CreateNeg(Y);
1861 
1862     // (X-Y)-X == -Y
1863     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(Y))))
1864       return BinaryOperator::CreateNeg(Y);
1865   }
1866 
1867   // (sub (or A, B) (and A, B)) --> (xor A, B)
1868   {
1869     Value *A, *B;
1870     if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
1871         match(Op0, m_c_Or(m_Specific(A), m_Specific(B))))
1872       return BinaryOperator::CreateXor(A, B);
1873   }
1874 
1875   // (sub (and A, B) (or A, B)) --> neg (xor A, B)
1876   {
1877     Value *A, *B;
1878     if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
1879         match(Op1, m_c_Or(m_Specific(A), m_Specific(B))) &&
1880         (Op0->hasOneUse() || Op1->hasOneUse()))
1881       return BinaryOperator::CreateNeg(Builder.CreateXor(A, B));
1882   }
1883 
1884   // (sub (or A, B), (xor A, B)) --> (and A, B)
1885   {
1886     Value *A, *B;
1887     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
1888         match(Op0, m_c_Or(m_Specific(A), m_Specific(B))))
1889       return BinaryOperator::CreateAnd(A, B);
1890   }
1891 
1892   // (sub (xor A, B) (or A, B)) --> neg (and A, B)
1893   {
1894     Value *A, *B;
1895     if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
1896         match(Op1, m_c_Or(m_Specific(A), m_Specific(B))) &&
1897         (Op0->hasOneUse() || Op1->hasOneUse()))
1898       return BinaryOperator::CreateNeg(Builder.CreateAnd(A, B));
1899   }
1900 
1901   {
1902     Value *Y;
1903     // ((X | Y) - X) --> (~X & Y)
1904     if (match(Op0, m_OneUse(m_c_Or(m_Value(Y), m_Specific(Op1)))))
1905       return BinaryOperator::CreateAnd(
1906           Y, Builder.CreateNot(Op1, Op1->getName() + ".not"));
1907   }
1908 
1909   {
1910     // (sub (and Op1, (neg X)), Op1) --> neg (and Op1, (add X, -1))
1911     Value *X;
1912     if (match(Op0, m_OneUse(m_c_And(m_Specific(Op1),
1913                                     m_OneUse(m_Neg(m_Value(X))))))) {
1914       return BinaryOperator::CreateNeg(Builder.CreateAnd(
1915           Op1, Builder.CreateAdd(X, Constant::getAllOnesValue(I.getType()))));
1916     }
1917   }
1918 
1919   {
1920     // (sub (and Op1, C), Op1) --> neg (and Op1, ~C)
1921     Constant *C;
1922     if (match(Op0, m_OneUse(m_And(m_Specific(Op1), m_Constant(C))))) {
1923       return BinaryOperator::CreateNeg(
1924           Builder.CreateAnd(Op1, Builder.CreateNot(C)));
1925     }
1926   }
1927 
1928   {
1929     // If we have a subtraction between some value and a select between
1930     // said value and something else, sink subtraction into select hands, i.e.:
1931     //   sub (select %Cond, %TrueVal, %FalseVal), %Op1
1932     //     ->
1933     //   select %Cond, (sub %TrueVal, %Op1), (sub %FalseVal, %Op1)
1934     //  or
1935     //   sub %Op0, (select %Cond, %TrueVal, %FalseVal)
1936     //     ->
1937     //   select %Cond, (sub %Op0, %TrueVal), (sub %Op0, %FalseVal)
1938     // This will result in select between new subtraction and 0.
1939     auto SinkSubIntoSelect =
1940         [Ty = I.getType()](Value *Select, Value *OtherHandOfSub,
1941                            auto SubBuilder) -> Instruction * {
1942       Value *Cond, *TrueVal, *FalseVal;
1943       if (!match(Select, m_OneUse(m_Select(m_Value(Cond), m_Value(TrueVal),
1944                                            m_Value(FalseVal)))))
1945         return nullptr;
1946       if (OtherHandOfSub != TrueVal && OtherHandOfSub != FalseVal)
1947         return nullptr;
1948       // While it is really tempting to just create two subtractions and let
1949       // InstCombine fold one of those to 0, it isn't possible to do so
1950       // because of worklist visitation order. So ugly it is.
1951       bool OtherHandOfSubIsTrueVal = OtherHandOfSub == TrueVal;
1952       Value *NewSub = SubBuilder(OtherHandOfSubIsTrueVal ? FalseVal : TrueVal);
1953       Constant *Zero = Constant::getNullValue(Ty);
1954       SelectInst *NewSel =
1955           SelectInst::Create(Cond, OtherHandOfSubIsTrueVal ? Zero : NewSub,
1956                              OtherHandOfSubIsTrueVal ? NewSub : Zero);
1957       // Preserve prof metadata if any.
1958       NewSel->copyMetadata(cast<Instruction>(*Select));
1959       return NewSel;
1960     };
1961     if (Instruction *NewSel = SinkSubIntoSelect(
1962             /*Select=*/Op0, /*OtherHandOfSub=*/Op1,
1963             [Builder = &Builder, Op1](Value *OtherHandOfSelect) {
1964               return Builder->CreateSub(OtherHandOfSelect,
1965                                         /*OtherHandOfSub=*/Op1);
1966             }))
1967       return NewSel;
1968     if (Instruction *NewSel = SinkSubIntoSelect(
1969             /*Select=*/Op1, /*OtherHandOfSub=*/Op0,
1970             [Builder = &Builder, Op0](Value *OtherHandOfSelect) {
1971               return Builder->CreateSub(/*OtherHandOfSub=*/Op0,
1972                                         OtherHandOfSelect);
1973             }))
1974       return NewSel;
1975   }
1976 
1977   // (X - (X & Y))   -->   (X & ~Y)
1978   if (match(Op1, m_c_And(m_Specific(Op0), m_Value(Y))) &&
1979       (Op1->hasOneUse() || isa<Constant>(Y)))
1980     return BinaryOperator::CreateAnd(
1981         Op0, Builder.CreateNot(Y, Y->getName() + ".not"));
1982 
1983   {
1984     // ~A - Min/Max(~A, O) -> Max/Min(A, ~O) - A
1985     // ~A - Min/Max(O, ~A) -> Max/Min(A, ~O) - A
1986     // Min/Max(~A, O) - ~A -> A - Max/Min(A, ~O)
1987     // Min/Max(O, ~A) - ~A -> A - Max/Min(A, ~O)
1988     // So long as O here is freely invertible, this will be neutral or a win.
1989     Value *LHS, *RHS, *A;
1990     Value *NotA = Op0, *MinMax = Op1;
1991     SelectPatternFlavor SPF = matchSelectPattern(MinMax, LHS, RHS).Flavor;
1992     if (!SelectPatternResult::isMinOrMax(SPF)) {
1993       NotA = Op1;
1994       MinMax = Op0;
1995       SPF = matchSelectPattern(MinMax, LHS, RHS).Flavor;
1996     }
1997     if (SelectPatternResult::isMinOrMax(SPF) &&
1998         match(NotA, m_Not(m_Value(A))) && (NotA == LHS || NotA == RHS)) {
1999       if (NotA == LHS)
2000         std::swap(LHS, RHS);
2001       // LHS is now O above and expected to have at least 2 uses (the min/max)
2002       // NotA is epected to have 2 uses from the min/max and 1 from the sub.
2003       if (isFreeToInvert(LHS, !LHS->hasNUsesOrMore(3)) &&
2004           !NotA->hasNUsesOrMore(4)) {
2005         // Note: We don't generate the inverse max/min, just create the not of
2006         // it and let other folds do the rest.
2007         Value *Not = Builder.CreateNot(MinMax);
2008         if (NotA == Op0)
2009           return BinaryOperator::CreateSub(Not, A);
2010         else
2011           return BinaryOperator::CreateSub(A, Not);
2012       }
2013     }
2014   }
2015 
2016   // Optimize pointer differences into the same array into a size.  Consider:
2017   //  &A[10] - &A[0]: we should compile this to "10".
2018   Value *LHSOp, *RHSOp;
2019   if (match(Op0, m_PtrToInt(m_Value(LHSOp))) &&
2020       match(Op1, m_PtrToInt(m_Value(RHSOp))))
2021     if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType(),
2022                                                I.hasNoUnsignedWrap()))
2023       return replaceInstUsesWith(I, Res);
2024 
2025   // trunc(p)-trunc(q) -> trunc(p-q)
2026   if (match(Op0, m_Trunc(m_PtrToInt(m_Value(LHSOp)))) &&
2027       match(Op1, m_Trunc(m_PtrToInt(m_Value(RHSOp)))))
2028     if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType(),
2029                                                /* IsNUW */ false))
2030       return replaceInstUsesWith(I, Res);
2031 
2032   // Canonicalize a shifty way to code absolute value to the common pattern.
2033   // There are 2 potential commuted variants.
2034   // We're relying on the fact that we only do this transform when the shift has
2035   // exactly 2 uses and the xor has exactly 1 use (otherwise, we might increase
2036   // instructions).
2037   Value *A;
2038   const APInt *ShAmt;
2039   Type *Ty = I.getType();
2040   if (match(Op1, m_AShr(m_Value(A), m_APInt(ShAmt))) &&
2041       Op1->hasNUses(2) && *ShAmt == Ty->getScalarSizeInBits() - 1 &&
2042       match(Op0, m_OneUse(m_c_Xor(m_Specific(A), m_Specific(Op1))))) {
2043     // B = ashr i32 A, 31 ; smear the sign bit
2044     // sub (xor A, B), B  ; flip bits if negative and subtract -1 (add 1)
2045     // --> (A < 0) ? -A : A
2046     Value *Cmp = Builder.CreateICmpSLT(A, ConstantInt::getNullValue(Ty));
2047     // Copy the nuw/nsw flags from the sub to the negate.
2048     Value *Neg = Builder.CreateNeg(A, "", I.hasNoUnsignedWrap(),
2049                                    I.hasNoSignedWrap());
2050     return SelectInst::Create(Cmp, Neg, A);
2051   }
2052 
2053   // If we are subtracting a low-bit masked subset of some value from an add
2054   // of that same value with no low bits changed, that is clearing some low bits
2055   // of the sum:
2056   // sub (X + AddC), (X & AndC) --> and (X + AddC), ~AndC
2057   const APInt *AddC, *AndC;
2058   if (match(Op0, m_Add(m_Value(X), m_APInt(AddC))) &&
2059       match(Op1, m_And(m_Specific(X), m_APInt(AndC)))) {
2060     unsigned BitWidth = Ty->getScalarSizeInBits();
2061     unsigned Cttz = AddC->countTrailingZeros();
2062     APInt HighMask(APInt::getHighBitsSet(BitWidth, BitWidth - Cttz));
2063     if ((HighMask & *AndC).isNullValue())
2064       return BinaryOperator::CreateAnd(Op0, ConstantInt::get(Ty, ~(*AndC)));
2065   }
2066 
2067   if (Instruction *V =
2068           canonicalizeCondSignextOfHighBitExtractToSignextHighBitExtract(I))
2069     return V;
2070 
2071   return TryToNarrowDeduceFlags();
2072 }
2073 
2074 /// This eliminates floating-point negation in either 'fneg(X)' or
2075 /// 'fsub(-0.0, X)' form by combining into a constant operand.
2076 static Instruction *foldFNegIntoConstant(Instruction &I) {
2077   Value *X;
2078   Constant *C;
2079 
2080   // Fold negation into constant operand. This is limited with one-use because
2081   // fneg is assumed better for analysis and cheaper in codegen than fmul/fdiv.
2082   // -(X * C) --> X * (-C)
2083   // FIXME: It's arguable whether these should be m_OneUse or not. The current
2084   // belief is that the FNeg allows for better reassociation opportunities.
2085   if (match(&I, m_FNeg(m_OneUse(m_FMul(m_Value(X), m_Constant(C))))))
2086     return BinaryOperator::CreateFMulFMF(X, ConstantExpr::getFNeg(C), &I);
2087   // -(X / C) --> X / (-C)
2088   if (match(&I, m_FNeg(m_OneUse(m_FDiv(m_Value(X), m_Constant(C))))))
2089     return BinaryOperator::CreateFDivFMF(X, ConstantExpr::getFNeg(C), &I);
2090   // -(C / X) --> (-C) / X
2091   if (match(&I, m_FNeg(m_OneUse(m_FDiv(m_Constant(C), m_Value(X))))))
2092     return BinaryOperator::CreateFDivFMF(ConstantExpr::getFNeg(C), X, &I);
2093 
2094   // With NSZ [ counter-example with -0.0: -(-0.0 + 0.0) != 0.0 + -0.0 ]:
2095   // -(X + C) --> -X + -C --> -C - X
2096   if (I.hasNoSignedZeros() &&
2097       match(&I, m_FNeg(m_OneUse(m_FAdd(m_Value(X), m_Constant(C))))))
2098     return BinaryOperator::CreateFSubFMF(ConstantExpr::getFNeg(C), X, &I);
2099 
2100   return nullptr;
2101 }
2102 
2103 static Instruction *hoistFNegAboveFMulFDiv(Instruction &I,
2104                                            InstCombiner::BuilderTy &Builder) {
2105   Value *FNeg;
2106   if (!match(&I, m_FNeg(m_Value(FNeg))))
2107     return nullptr;
2108 
2109   Value *X, *Y;
2110   if (match(FNeg, m_OneUse(m_FMul(m_Value(X), m_Value(Y)))))
2111     return BinaryOperator::CreateFMulFMF(Builder.CreateFNegFMF(X, &I), Y, &I);
2112 
2113   if (match(FNeg, m_OneUse(m_FDiv(m_Value(X), m_Value(Y)))))
2114     return BinaryOperator::CreateFDivFMF(Builder.CreateFNegFMF(X, &I), Y, &I);
2115 
2116   return nullptr;
2117 }
2118 
2119 Instruction *InstCombinerImpl::visitFNeg(UnaryOperator &I) {
2120   Value *Op = I.getOperand(0);
2121 
2122   if (Value *V = SimplifyFNegInst(Op, I.getFastMathFlags(),
2123                                   getSimplifyQuery().getWithInstruction(&I)))
2124     return replaceInstUsesWith(I, V);
2125 
2126   if (Instruction *X = foldFNegIntoConstant(I))
2127     return X;
2128 
2129   Value *X, *Y;
2130 
2131   // If we can ignore the sign of zeros: -(X - Y) --> (Y - X)
2132   if (I.hasNoSignedZeros() &&
2133       match(Op, m_OneUse(m_FSub(m_Value(X), m_Value(Y)))))
2134     return BinaryOperator::CreateFSubFMF(Y, X, &I);
2135 
2136   if (Instruction *R = hoistFNegAboveFMulFDiv(I, Builder))
2137     return R;
2138 
2139   return nullptr;
2140 }
2141 
2142 Instruction *InstCombinerImpl::visitFSub(BinaryOperator &I) {
2143   if (Value *V = SimplifyFSubInst(I.getOperand(0), I.getOperand(1),
2144                                   I.getFastMathFlags(),
2145                                   getSimplifyQuery().getWithInstruction(&I)))
2146     return replaceInstUsesWith(I, V);
2147 
2148   if (Instruction *X = foldVectorBinop(I))
2149     return X;
2150 
2151   // Subtraction from -0.0 is the canonical form of fneg.
2152   // fsub -0.0, X ==> fneg X
2153   // fsub nsz 0.0, X ==> fneg nsz X
2154   //
2155   // FIXME This matcher does not respect FTZ or DAZ yet:
2156   // fsub -0.0, Denorm ==> +-0
2157   // fneg Denorm ==> -Denorm
2158   Value *Op;
2159   if (match(&I, m_FNeg(m_Value(Op))))
2160     return UnaryOperator::CreateFNegFMF(Op, &I);
2161 
2162   if (Instruction *X = foldFNegIntoConstant(I))
2163     return X;
2164 
2165   if (Instruction *R = hoistFNegAboveFMulFDiv(I, Builder))
2166     return R;
2167 
2168   Value *X, *Y;
2169   Constant *C;
2170 
2171   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2172   // If Op0 is not -0.0 or we can ignore -0.0: Z - (X - Y) --> Z + (Y - X)
2173   // Canonicalize to fadd to make analysis easier.
2174   // This can also help codegen because fadd is commutative.
2175   // Note that if this fsub was really an fneg, the fadd with -0.0 will get
2176   // killed later. We still limit that particular transform with 'hasOneUse'
2177   // because an fneg is assumed better/cheaper than a generic fsub.
2178   if (I.hasNoSignedZeros() || CannotBeNegativeZero(Op0, SQ.TLI)) {
2179     if (match(Op1, m_OneUse(m_FSub(m_Value(X), m_Value(Y))))) {
2180       Value *NewSub = Builder.CreateFSubFMF(Y, X, &I);
2181       return BinaryOperator::CreateFAddFMF(Op0, NewSub, &I);
2182     }
2183   }
2184 
2185   // (-X) - Op1 --> -(X + Op1)
2186   if (I.hasNoSignedZeros() && !isa<ConstantExpr>(Op0) &&
2187       match(Op0, m_OneUse(m_FNeg(m_Value(X))))) {
2188     Value *FAdd = Builder.CreateFAddFMF(X, Op1, &I);
2189     return UnaryOperator::CreateFNegFMF(FAdd, &I);
2190   }
2191 
2192   if (isa<Constant>(Op0))
2193     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2194       if (Instruction *NV = FoldOpIntoSelect(I, SI))
2195         return NV;
2196 
2197   // X - C --> X + (-C)
2198   // But don't transform constant expressions because there's an inverse fold
2199   // for X + (-Y) --> X - Y.
2200   if (match(Op1, m_Constant(C)) && !isa<ConstantExpr>(Op1))
2201     return BinaryOperator::CreateFAddFMF(Op0, ConstantExpr::getFNeg(C), &I);
2202 
2203   // X - (-Y) --> X + Y
2204   if (match(Op1, m_FNeg(m_Value(Y))))
2205     return BinaryOperator::CreateFAddFMF(Op0, Y, &I);
2206 
2207   // Similar to above, but look through a cast of the negated value:
2208   // X - (fptrunc(-Y)) --> X + fptrunc(Y)
2209   Type *Ty = I.getType();
2210   if (match(Op1, m_OneUse(m_FPTrunc(m_FNeg(m_Value(Y))))))
2211     return BinaryOperator::CreateFAddFMF(Op0, Builder.CreateFPTrunc(Y, Ty), &I);
2212 
2213   // X - (fpext(-Y)) --> X + fpext(Y)
2214   if (match(Op1, m_OneUse(m_FPExt(m_FNeg(m_Value(Y))))))
2215     return BinaryOperator::CreateFAddFMF(Op0, Builder.CreateFPExt(Y, Ty), &I);
2216 
2217   // Similar to above, but look through fmul/fdiv of the negated value:
2218   // Op0 - (-X * Y) --> Op0 + (X * Y)
2219   // Op0 - (Y * -X) --> Op0 + (X * Y)
2220   if (match(Op1, m_OneUse(m_c_FMul(m_FNeg(m_Value(X)), m_Value(Y))))) {
2221     Value *FMul = Builder.CreateFMulFMF(X, Y, &I);
2222     return BinaryOperator::CreateFAddFMF(Op0, FMul, &I);
2223   }
2224   // Op0 - (-X / Y) --> Op0 + (X / Y)
2225   // Op0 - (X / -Y) --> Op0 + (X / Y)
2226   if (match(Op1, m_OneUse(m_FDiv(m_FNeg(m_Value(X)), m_Value(Y)))) ||
2227       match(Op1, m_OneUse(m_FDiv(m_Value(X), m_FNeg(m_Value(Y)))))) {
2228     Value *FDiv = Builder.CreateFDivFMF(X, Y, &I);
2229     return BinaryOperator::CreateFAddFMF(Op0, FDiv, &I);
2230   }
2231 
2232   // Handle special cases for FSub with selects feeding the operation
2233   if (Value *V = SimplifySelectsFeedingBinaryOp(I, Op0, Op1))
2234     return replaceInstUsesWith(I, V);
2235 
2236   if (I.hasAllowReassoc() && I.hasNoSignedZeros()) {
2237     // (Y - X) - Y --> -X
2238     if (match(Op0, m_FSub(m_Specific(Op1), m_Value(X))))
2239       return UnaryOperator::CreateFNegFMF(X, &I);
2240 
2241     // Y - (X + Y) --> -X
2242     // Y - (Y + X) --> -X
2243     if (match(Op1, m_c_FAdd(m_Specific(Op0), m_Value(X))))
2244       return UnaryOperator::CreateFNegFMF(X, &I);
2245 
2246     // (X * C) - X --> X * (C - 1.0)
2247     if (match(Op0, m_FMul(m_Specific(Op1), m_Constant(C)))) {
2248       Constant *CSubOne = ConstantExpr::getFSub(C, ConstantFP::get(Ty, 1.0));
2249       return BinaryOperator::CreateFMulFMF(Op1, CSubOne, &I);
2250     }
2251     // X - (X * C) --> X * (1.0 - C)
2252     if (match(Op1, m_FMul(m_Specific(Op0), m_Constant(C)))) {
2253       Constant *OneSubC = ConstantExpr::getFSub(ConstantFP::get(Ty, 1.0), C);
2254       return BinaryOperator::CreateFMulFMF(Op0, OneSubC, &I);
2255     }
2256 
2257     // Reassociate fsub/fadd sequences to create more fadd instructions and
2258     // reduce dependency chains:
2259     // ((X - Y) + Z) - Op1 --> (X + Z) - (Y + Op1)
2260     Value *Z;
2261     if (match(Op0, m_OneUse(m_c_FAdd(m_OneUse(m_FSub(m_Value(X), m_Value(Y))),
2262                                      m_Value(Z))))) {
2263       Value *XZ = Builder.CreateFAddFMF(X, Z, &I);
2264       Value *YW = Builder.CreateFAddFMF(Y, Op1, &I);
2265       return BinaryOperator::CreateFSubFMF(XZ, YW, &I);
2266     }
2267 
2268     auto m_FaddRdx = [](Value *&Sum, Value *&Vec) {
2269       return m_OneUse(m_Intrinsic<Intrinsic::vector_reduce_fadd>(m_Value(Sum),
2270                                                                  m_Value(Vec)));
2271     };
2272     Value *A0, *A1, *V0, *V1;
2273     if (match(Op0, m_FaddRdx(A0, V0)) && match(Op1, m_FaddRdx(A1, V1)) &&
2274         V0->getType() == V1->getType()) {
2275       // Difference of sums is sum of differences:
2276       // add_rdx(A0, V0) - add_rdx(A1, V1) --> add_rdx(A0, V0 - V1) - A1
2277       Value *Sub = Builder.CreateFSubFMF(V0, V1, &I);
2278       Value *Rdx = Builder.CreateIntrinsic(Intrinsic::vector_reduce_fadd,
2279                                            {Sub->getType()}, {A0, Sub}, &I);
2280       return BinaryOperator::CreateFSubFMF(Rdx, A1, &I);
2281     }
2282 
2283     if (Instruction *F = factorizeFAddFSub(I, Builder))
2284       return F;
2285 
2286     // TODO: This performs reassociative folds for FP ops. Some fraction of the
2287     // functionality has been subsumed by simple pattern matching here and in
2288     // InstSimplify. We should let a dedicated reassociation pass handle more
2289     // complex pattern matching and remove this from InstCombine.
2290     if (Value *V = FAddCombine(Builder).simplify(&I))
2291       return replaceInstUsesWith(I, V);
2292 
2293     // (X - Y) - Op1 --> X - (Y + Op1)
2294     if (match(Op0, m_OneUse(m_FSub(m_Value(X), m_Value(Y))))) {
2295       Value *FAdd = Builder.CreateFAddFMF(Y, Op1, &I);
2296       return BinaryOperator::CreateFSubFMF(X, FAdd, &I);
2297     }
2298   }
2299 
2300   return nullptr;
2301 }
2302