1 //===- InstCombineAddSub.cpp ------------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the visit functions for add, fadd, sub, and fsub.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "InstCombineInternal.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/Analysis/InstructionSimplify.h"
17 #include "llvm/IR/DataLayout.h"
18 #include "llvm/IR/GetElementPtrTypeIterator.h"
19 #include "llvm/IR/PatternMatch.h"
20 
21 using namespace llvm;
22 using namespace PatternMatch;
23 
24 #define DEBUG_TYPE "instcombine"
25 
26 namespace {
27 
28   /// Class representing coefficient of floating-point addend.
29   /// This class needs to be highly efficient, which is especially true for
30   /// the constructor. As of I write this comment, the cost of the default
31   /// constructor is merely 4-byte-store-zero (Assuming compiler is able to
32   /// perform write-merging).
33   ///
34   class FAddendCoef {
35   public:
36     // The constructor has to initialize a APFloat, which is unnecessary for
37     // most addends which have coefficient either 1 or -1. So, the constructor
38     // is expensive. In order to avoid the cost of the constructor, we should
39     // reuse some instances whenever possible. The pre-created instances
40     // FAddCombine::Add[0-5] embodies this idea.
41     //
42     FAddendCoef() : IsFp(false), BufHasFpVal(false), IntVal(0) {}
43     ~FAddendCoef();
44 
45     void set(short C) {
46       assert(!insaneIntVal(C) && "Insane coefficient");
47       IsFp = false; IntVal = C;
48     }
49 
50     void set(const APFloat& C);
51 
52     void negate();
53 
54     bool isZero() const { return isInt() ? !IntVal : getFpVal().isZero(); }
55     Value *getValue(Type *) const;
56 
57     // If possible, don't define operator+/operator- etc because these
58     // operators inevitably call FAddendCoef's constructor which is not cheap.
59     void operator=(const FAddendCoef &A);
60     void operator+=(const FAddendCoef &A);
61     void operator-=(const FAddendCoef &A);
62     void operator*=(const FAddendCoef &S);
63 
64     bool isOne() const { return isInt() && IntVal == 1; }
65     bool isTwo() const { return isInt() && IntVal == 2; }
66     bool isMinusOne() const { return isInt() && IntVal == -1; }
67     bool isMinusTwo() const { return isInt() && IntVal == -2; }
68 
69   private:
70     bool insaneIntVal(int V) { return V > 4 || V < -4; }
71     APFloat *getFpValPtr()
72       { return reinterpret_cast<APFloat*>(&FpValBuf.buffer[0]); }
73     const APFloat *getFpValPtr() const
74       { return reinterpret_cast<const APFloat*>(&FpValBuf.buffer[0]); }
75 
76     const APFloat &getFpVal() const {
77       assert(IsFp && BufHasFpVal && "Incorret state");
78       return *getFpValPtr();
79     }
80 
81     APFloat &getFpVal() {
82       assert(IsFp && BufHasFpVal && "Incorret state");
83       return *getFpValPtr();
84     }
85 
86     bool isInt() const { return !IsFp; }
87 
88     // If the coefficient is represented by an integer, promote it to a
89     // floating point.
90     void convertToFpType(const fltSemantics &Sem);
91 
92     // Construct an APFloat from a signed integer.
93     // TODO: We should get rid of this function when APFloat can be constructed
94     //       from an *SIGNED* integer.
95     APFloat createAPFloatFromInt(const fltSemantics &Sem, int Val);
96 
97   private:
98     bool IsFp;
99 
100     // True iff FpValBuf contains an instance of APFloat.
101     bool BufHasFpVal;
102 
103     // The integer coefficient of an individual addend is either 1 or -1,
104     // and we try to simplify at most 4 addends from neighboring at most
105     // two instructions. So the range of <IntVal> falls in [-4, 4]. APInt
106     // is overkill of this end.
107     short IntVal;
108 
109     AlignedCharArrayUnion<APFloat> FpValBuf;
110   };
111 
112   /// FAddend is used to represent floating-point addend. An addend is
113   /// represented as <C, V>, where the V is a symbolic value, and C is a
114   /// constant coefficient. A constant addend is represented as <C, 0>.
115   ///
116   class FAddend {
117   public:
118     FAddend() : Val(nullptr) {}
119 
120     Value *getSymVal() const { return Val; }
121     const FAddendCoef &getCoef() const { return Coeff; }
122 
123     bool isConstant() const { return Val == nullptr; }
124     bool isZero() const { return Coeff.isZero(); }
125 
126     void set(short Coefficient, Value *V) { Coeff.set(Coefficient), Val = V; }
127     void set(const APFloat& Coefficient, Value *V)
128       { Coeff.set(Coefficient); Val = V; }
129     void set(const ConstantFP* Coefficient, Value *V)
130       { Coeff.set(Coefficient->getValueAPF()); Val = V; }
131 
132     void negate() { Coeff.negate(); }
133 
134     /// Drill down the U-D chain one step to find the definition of V, and
135     /// try to break the definition into one or two addends.
136     static unsigned drillValueDownOneStep(Value* V, FAddend &A0, FAddend &A1);
137 
138     /// Similar to FAddend::drillDownOneStep() except that the value being
139     /// splitted is the addend itself.
140     unsigned drillAddendDownOneStep(FAddend &Addend0, FAddend &Addend1) const;
141 
142     void operator+=(const FAddend &T) {
143       assert((Val == T.Val) && "Symbolic-values disagree");
144       Coeff += T.Coeff;
145     }
146 
147   private:
148     void Scale(const FAddendCoef& ScaleAmt) { Coeff *= ScaleAmt; }
149 
150     // This addend has the value of "Coeff * Val".
151     Value *Val;
152     FAddendCoef Coeff;
153   };
154 
155   /// FAddCombine is the class for optimizing an unsafe fadd/fsub along
156   /// with its neighboring at most two instructions.
157   ///
158   class FAddCombine {
159   public:
160     FAddCombine(InstCombiner::BuilderTy *B) : Builder(B), Instr(nullptr) {}
161     Value *simplify(Instruction *FAdd);
162 
163   private:
164     typedef SmallVector<const FAddend*, 4> AddendVect;
165 
166     Value *simplifyFAdd(AddendVect& V, unsigned InstrQuota);
167 
168     Value *performFactorization(Instruction *I);
169 
170     /// Convert given addend to a Value
171     Value *createAddendVal(const FAddend &A, bool& NeedNeg);
172 
173     /// Return the number of instructions needed to emit the N-ary addition.
174     unsigned calcInstrNumber(const AddendVect& Vect);
175     Value *createFSub(Value *Opnd0, Value *Opnd1);
176     Value *createFAdd(Value *Opnd0, Value *Opnd1);
177     Value *createFMul(Value *Opnd0, Value *Opnd1);
178     Value *createFDiv(Value *Opnd0, Value *Opnd1);
179     Value *createFNeg(Value *V);
180     Value *createNaryFAdd(const AddendVect& Opnds, unsigned InstrQuota);
181     void createInstPostProc(Instruction *NewInst, bool NoNumber = false);
182 
183     InstCombiner::BuilderTy *Builder;
184     Instruction *Instr;
185 
186      // Debugging stuff are clustered here.
187     #ifndef NDEBUG
188       unsigned CreateInstrNum;
189       void initCreateInstNum() { CreateInstrNum = 0; }
190       void incCreateInstNum() { CreateInstrNum++; }
191     #else
192       void initCreateInstNum() {}
193       void incCreateInstNum() {}
194     #endif
195   };
196 
197 } // anonymous namespace
198 
199 //===----------------------------------------------------------------------===//
200 //
201 // Implementation of
202 //    {FAddendCoef, FAddend, FAddition, FAddCombine}.
203 //
204 //===----------------------------------------------------------------------===//
205 FAddendCoef::~FAddendCoef() {
206   if (BufHasFpVal)
207     getFpValPtr()->~APFloat();
208 }
209 
210 void FAddendCoef::set(const APFloat& C) {
211   APFloat *P = getFpValPtr();
212 
213   if (isInt()) {
214     // As the buffer is meanless byte stream, we cannot call
215     // APFloat::operator=().
216     new(P) APFloat(C);
217   } else
218     *P = C;
219 
220   IsFp = BufHasFpVal = true;
221 }
222 
223 void FAddendCoef::convertToFpType(const fltSemantics &Sem) {
224   if (!isInt())
225     return;
226 
227   APFloat *P = getFpValPtr();
228   if (IntVal > 0)
229     new(P) APFloat(Sem, IntVal);
230   else {
231     new(P) APFloat(Sem, 0 - IntVal);
232     P->changeSign();
233   }
234   IsFp = BufHasFpVal = true;
235 }
236 
237 APFloat FAddendCoef::createAPFloatFromInt(const fltSemantics &Sem, int Val) {
238   if (Val >= 0)
239     return APFloat(Sem, Val);
240 
241   APFloat T(Sem, 0 - Val);
242   T.changeSign();
243 
244   return T;
245 }
246 
247 void FAddendCoef::operator=(const FAddendCoef &That) {
248   if (That.isInt())
249     set(That.IntVal);
250   else
251     set(That.getFpVal());
252 }
253 
254 void FAddendCoef::operator+=(const FAddendCoef &That) {
255   enum APFloat::roundingMode RndMode = APFloat::rmNearestTiesToEven;
256   if (isInt() == That.isInt()) {
257     if (isInt())
258       IntVal += That.IntVal;
259     else
260       getFpVal().add(That.getFpVal(), RndMode);
261     return;
262   }
263 
264   if (isInt()) {
265     const APFloat &T = That.getFpVal();
266     convertToFpType(T.getSemantics());
267     getFpVal().add(T, RndMode);
268     return;
269   }
270 
271   APFloat &T = getFpVal();
272   T.add(createAPFloatFromInt(T.getSemantics(), That.IntVal), RndMode);
273 }
274 
275 void FAddendCoef::operator-=(const FAddendCoef &That) {
276   enum APFloat::roundingMode RndMode = APFloat::rmNearestTiesToEven;
277   if (isInt() == That.isInt()) {
278     if (isInt())
279       IntVal -= That.IntVal;
280     else
281       getFpVal().subtract(That.getFpVal(), RndMode);
282     return;
283   }
284 
285   if (isInt()) {
286     const APFloat &T = That.getFpVal();
287     convertToFpType(T.getSemantics());
288     getFpVal().subtract(T, RndMode);
289     return;
290   }
291 
292   APFloat &T = getFpVal();
293   T.subtract(createAPFloatFromInt(T.getSemantics(), IntVal), RndMode);
294 }
295 
296 void FAddendCoef::operator*=(const FAddendCoef &That) {
297   if (That.isOne())
298     return;
299 
300   if (That.isMinusOne()) {
301     negate();
302     return;
303   }
304 
305   if (isInt() && That.isInt()) {
306     int Res = IntVal * (int)That.IntVal;
307     assert(!insaneIntVal(Res) && "Insane int value");
308     IntVal = Res;
309     return;
310   }
311 
312   const fltSemantics &Semantic =
313     isInt() ? That.getFpVal().getSemantics() : getFpVal().getSemantics();
314 
315   if (isInt())
316     convertToFpType(Semantic);
317   APFloat &F0 = getFpVal();
318 
319   if (That.isInt())
320     F0.multiply(createAPFloatFromInt(Semantic, That.IntVal),
321                 APFloat::rmNearestTiesToEven);
322   else
323     F0.multiply(That.getFpVal(), APFloat::rmNearestTiesToEven);
324 }
325 
326 void FAddendCoef::negate() {
327   if (isInt())
328     IntVal = 0 - IntVal;
329   else
330     getFpVal().changeSign();
331 }
332 
333 Value *FAddendCoef::getValue(Type *Ty) const {
334   return isInt() ?
335     ConstantFP::get(Ty, float(IntVal)) :
336     ConstantFP::get(Ty->getContext(), getFpVal());
337 }
338 
339 // The definition of <Val>     Addends
340 // =========================================
341 //  A + B                     <1, A>, <1,B>
342 //  A - B                     <1, A>, <1,B>
343 //  0 - B                     <-1, B>
344 //  C * A,                    <C, A>
345 //  A + C                     <1, A> <C, NULL>
346 //  0 +/- 0                   <0, NULL> (corner case)
347 //
348 // Legend: A and B are not constant, C is constant
349 //
350 unsigned FAddend::drillValueDownOneStep
351   (Value *Val, FAddend &Addend0, FAddend &Addend1) {
352   Instruction *I = nullptr;
353   if (!Val || !(I = dyn_cast<Instruction>(Val)))
354     return 0;
355 
356   unsigned Opcode = I->getOpcode();
357 
358   if (Opcode == Instruction::FAdd || Opcode == Instruction::FSub) {
359     ConstantFP *C0, *C1;
360     Value *Opnd0 = I->getOperand(0);
361     Value *Opnd1 = I->getOperand(1);
362     if ((C0 = dyn_cast<ConstantFP>(Opnd0)) && C0->isZero())
363       Opnd0 = nullptr;
364 
365     if ((C1 = dyn_cast<ConstantFP>(Opnd1)) && C1->isZero())
366       Opnd1 = nullptr;
367 
368     if (Opnd0) {
369       if (!C0)
370         Addend0.set(1, Opnd0);
371       else
372         Addend0.set(C0, nullptr);
373     }
374 
375     if (Opnd1) {
376       FAddend &Addend = Opnd0 ? Addend1 : Addend0;
377       if (!C1)
378         Addend.set(1, Opnd1);
379       else
380         Addend.set(C1, nullptr);
381       if (Opcode == Instruction::FSub)
382         Addend.negate();
383     }
384 
385     if (Opnd0 || Opnd1)
386       return Opnd0 && Opnd1 ? 2 : 1;
387 
388     // Both operands are zero. Weird!
389     Addend0.set(APFloat(C0->getValueAPF().getSemantics()), nullptr);
390     return 1;
391   }
392 
393   if (I->getOpcode() == Instruction::FMul) {
394     Value *V0 = I->getOperand(0);
395     Value *V1 = I->getOperand(1);
396     if (ConstantFP *C = dyn_cast<ConstantFP>(V0)) {
397       Addend0.set(C, V1);
398       return 1;
399     }
400 
401     if (ConstantFP *C = dyn_cast<ConstantFP>(V1)) {
402       Addend0.set(C, V0);
403       return 1;
404     }
405   }
406 
407   return 0;
408 }
409 
410 // Try to break *this* addend into two addends. e.g. Suppose this addend is
411 // <2.3, V>, and V = X + Y, by calling this function, we obtain two addends,
412 // i.e. <2.3, X> and <2.3, Y>.
413 //
414 unsigned FAddend::drillAddendDownOneStep
415   (FAddend &Addend0, FAddend &Addend1) const {
416   if (isConstant())
417     return 0;
418 
419   unsigned BreakNum = FAddend::drillValueDownOneStep(Val, Addend0, Addend1);
420   if (!BreakNum || Coeff.isOne())
421     return BreakNum;
422 
423   Addend0.Scale(Coeff);
424 
425   if (BreakNum == 2)
426     Addend1.Scale(Coeff);
427 
428   return BreakNum;
429 }
430 
431 // Try to perform following optimization on the input instruction I. Return the
432 // simplified expression if was successful; otherwise, return 0.
433 //
434 //   Instruction "I" is                Simplified into
435 // -------------------------------------------------------
436 //   (x * y) +/- (x * z)               x * (y +/- z)
437 //   (y / x) +/- (z / x)               (y +/- z) / x
438 //
439 Value *FAddCombine::performFactorization(Instruction *I) {
440   assert((I->getOpcode() == Instruction::FAdd ||
441           I->getOpcode() == Instruction::FSub) && "Expect add/sub");
442 
443   Instruction *I0 = dyn_cast<Instruction>(I->getOperand(0));
444   Instruction *I1 = dyn_cast<Instruction>(I->getOperand(1));
445 
446   if (!I0 || !I1 || I0->getOpcode() != I1->getOpcode())
447     return nullptr;
448 
449   bool isMpy = false;
450   if (I0->getOpcode() == Instruction::FMul)
451     isMpy = true;
452   else if (I0->getOpcode() != Instruction::FDiv)
453     return nullptr;
454 
455   Value *Opnd0_0 = I0->getOperand(0);
456   Value *Opnd0_1 = I0->getOperand(1);
457   Value *Opnd1_0 = I1->getOperand(0);
458   Value *Opnd1_1 = I1->getOperand(1);
459 
460   //  Input Instr I       Factor   AddSub0  AddSub1
461   //  ----------------------------------------------
462   // (x*y) +/- (x*z)        x        y         z
463   // (y/x) +/- (z/x)        x        y         z
464   //
465   Value *Factor = nullptr;
466   Value *AddSub0 = nullptr, *AddSub1 = nullptr;
467 
468   if (isMpy) {
469     if (Opnd0_0 == Opnd1_0 || Opnd0_0 == Opnd1_1)
470       Factor = Opnd0_0;
471     else if (Opnd0_1 == Opnd1_0 || Opnd0_1 == Opnd1_1)
472       Factor = Opnd0_1;
473 
474     if (Factor) {
475       AddSub0 = (Factor == Opnd0_0) ? Opnd0_1 : Opnd0_0;
476       AddSub1 = (Factor == Opnd1_0) ? Opnd1_1 : Opnd1_0;
477     }
478   } else if (Opnd0_1 == Opnd1_1) {
479     Factor = Opnd0_1;
480     AddSub0 = Opnd0_0;
481     AddSub1 = Opnd1_0;
482   }
483 
484   if (!Factor)
485     return nullptr;
486 
487   FastMathFlags Flags;
488   Flags.setUnsafeAlgebra();
489   if (I0) Flags &= I->getFastMathFlags();
490   if (I1) Flags &= I->getFastMathFlags();
491 
492   // Create expression "NewAddSub = AddSub0 +/- AddsSub1"
493   Value *NewAddSub = (I->getOpcode() == Instruction::FAdd) ?
494                       createFAdd(AddSub0, AddSub1) :
495                       createFSub(AddSub0, AddSub1);
496   if (ConstantFP *CFP = dyn_cast<ConstantFP>(NewAddSub)) {
497     const APFloat &F = CFP->getValueAPF();
498     if (!F.isNormal())
499       return nullptr;
500   } else if (Instruction *II = dyn_cast<Instruction>(NewAddSub))
501     II->setFastMathFlags(Flags);
502 
503   if (isMpy) {
504     Value *RI = createFMul(Factor, NewAddSub);
505     if (Instruction *II = dyn_cast<Instruction>(RI))
506       II->setFastMathFlags(Flags);
507     return RI;
508   }
509 
510   Value *RI = createFDiv(NewAddSub, Factor);
511   if (Instruction *II = dyn_cast<Instruction>(RI))
512     II->setFastMathFlags(Flags);
513   return RI;
514 }
515 
516 Value *FAddCombine::simplify(Instruction *I) {
517   assert(I->hasUnsafeAlgebra() && "Should be in unsafe mode");
518 
519   // Currently we are not able to handle vector type.
520   if (I->getType()->isVectorTy())
521     return nullptr;
522 
523   assert((I->getOpcode() == Instruction::FAdd ||
524           I->getOpcode() == Instruction::FSub) && "Expect add/sub");
525 
526   // Save the instruction before calling other member-functions.
527   Instr = I;
528 
529   FAddend Opnd0, Opnd1, Opnd0_0, Opnd0_1, Opnd1_0, Opnd1_1;
530 
531   unsigned OpndNum = FAddend::drillValueDownOneStep(I, Opnd0, Opnd1);
532 
533   // Step 1: Expand the 1st addend into Opnd0_0 and Opnd0_1.
534   unsigned Opnd0_ExpNum = 0;
535   unsigned Opnd1_ExpNum = 0;
536 
537   if (!Opnd0.isConstant())
538     Opnd0_ExpNum = Opnd0.drillAddendDownOneStep(Opnd0_0, Opnd0_1);
539 
540   // Step 2: Expand the 2nd addend into Opnd1_0 and Opnd1_1.
541   if (OpndNum == 2 && !Opnd1.isConstant())
542     Opnd1_ExpNum = Opnd1.drillAddendDownOneStep(Opnd1_0, Opnd1_1);
543 
544   // Step 3: Try to optimize Opnd0_0 + Opnd0_1 + Opnd1_0 + Opnd1_1
545   if (Opnd0_ExpNum && Opnd1_ExpNum) {
546     AddendVect AllOpnds;
547     AllOpnds.push_back(&Opnd0_0);
548     AllOpnds.push_back(&Opnd1_0);
549     if (Opnd0_ExpNum == 2)
550       AllOpnds.push_back(&Opnd0_1);
551     if (Opnd1_ExpNum == 2)
552       AllOpnds.push_back(&Opnd1_1);
553 
554     // Compute instruction quota. We should save at least one instruction.
555     unsigned InstQuota = 0;
556 
557     Value *V0 = I->getOperand(0);
558     Value *V1 = I->getOperand(1);
559     InstQuota = ((!isa<Constant>(V0) && V0->hasOneUse()) &&
560                  (!isa<Constant>(V1) && V1->hasOneUse())) ? 2 : 1;
561 
562     if (Value *R = simplifyFAdd(AllOpnds, InstQuota))
563       return R;
564   }
565 
566   if (OpndNum != 2) {
567     // The input instruction is : "I=0.0 +/- V". If the "V" were able to be
568     // splitted into two addends, say "V = X - Y", the instruction would have
569     // been optimized into "I = Y - X" in the previous steps.
570     //
571     const FAddendCoef &CE = Opnd0.getCoef();
572     return CE.isOne() ? Opnd0.getSymVal() : nullptr;
573   }
574 
575   // step 4: Try to optimize Opnd0 + Opnd1_0 [+ Opnd1_1]
576   if (Opnd1_ExpNum) {
577     AddendVect AllOpnds;
578     AllOpnds.push_back(&Opnd0);
579     AllOpnds.push_back(&Opnd1_0);
580     if (Opnd1_ExpNum == 2)
581       AllOpnds.push_back(&Opnd1_1);
582 
583     if (Value *R = simplifyFAdd(AllOpnds, 1))
584       return R;
585   }
586 
587   // step 5: Try to optimize Opnd1 + Opnd0_0 [+ Opnd0_1]
588   if (Opnd0_ExpNum) {
589     AddendVect AllOpnds;
590     AllOpnds.push_back(&Opnd1);
591     AllOpnds.push_back(&Opnd0_0);
592     if (Opnd0_ExpNum == 2)
593       AllOpnds.push_back(&Opnd0_1);
594 
595     if (Value *R = simplifyFAdd(AllOpnds, 1))
596       return R;
597   }
598 
599   // step 6: Try factorization as the last resort,
600   return performFactorization(I);
601 }
602 
603 Value *FAddCombine::simplifyFAdd(AddendVect& Addends, unsigned InstrQuota) {
604   unsigned AddendNum = Addends.size();
605   assert(AddendNum <= 4 && "Too many addends");
606 
607   // For saving intermediate results;
608   unsigned NextTmpIdx = 0;
609   FAddend TmpResult[3];
610 
611   // Points to the constant addend of the resulting simplified expression.
612   // If the resulting expr has constant-addend, this constant-addend is
613   // desirable to reside at the top of the resulting expression tree. Placing
614   // constant close to supper-expr(s) will potentially reveal some optimization
615   // opportunities in super-expr(s).
616   //
617   const FAddend *ConstAdd = nullptr;
618 
619   // Simplified addends are placed <SimpVect>.
620   AddendVect SimpVect;
621 
622   // The outer loop works on one symbolic-value at a time. Suppose the input
623   // addends are : <a1, x>, <b1, y>, <a2, x>, <c1, z>, <b2, y>, ...
624   // The symbolic-values will be processed in this order: x, y, z.
625   //
626   for (unsigned SymIdx = 0; SymIdx < AddendNum; SymIdx++) {
627 
628     const FAddend *ThisAddend = Addends[SymIdx];
629     if (!ThisAddend) {
630       // This addend was processed before.
631       continue;
632     }
633 
634     Value *Val = ThisAddend->getSymVal();
635     unsigned StartIdx = SimpVect.size();
636     SimpVect.push_back(ThisAddend);
637 
638     // The inner loop collects addends sharing same symbolic-value, and these
639     // addends will be later on folded into a single addend. Following above
640     // example, if the symbolic value "y" is being processed, the inner loop
641     // will collect two addends "<b1,y>" and "<b2,Y>". These two addends will
642     // be later on folded into "<b1+b2, y>".
643     //
644     for (unsigned SameSymIdx = SymIdx + 1;
645          SameSymIdx < AddendNum; SameSymIdx++) {
646       const FAddend *T = Addends[SameSymIdx];
647       if (T && T->getSymVal() == Val) {
648         // Set null such that next iteration of the outer loop will not process
649         // this addend again.
650         Addends[SameSymIdx] = nullptr;
651         SimpVect.push_back(T);
652       }
653     }
654 
655     // If multiple addends share same symbolic value, fold them together.
656     if (StartIdx + 1 != SimpVect.size()) {
657       FAddend &R = TmpResult[NextTmpIdx ++];
658       R = *SimpVect[StartIdx];
659       for (unsigned Idx = StartIdx + 1; Idx < SimpVect.size(); Idx++)
660         R += *SimpVect[Idx];
661 
662       // Pop all addends being folded and push the resulting folded addend.
663       SimpVect.resize(StartIdx);
664       if (Val) {
665         if (!R.isZero()) {
666           SimpVect.push_back(&R);
667         }
668       } else {
669         // Don't push constant addend at this time. It will be the last element
670         // of <SimpVect>.
671         ConstAdd = &R;
672       }
673     }
674   }
675 
676   assert((NextTmpIdx <= array_lengthof(TmpResult) + 1) &&
677          "out-of-bound access");
678 
679   if (ConstAdd)
680     SimpVect.push_back(ConstAdd);
681 
682   Value *Result;
683   if (!SimpVect.empty())
684     Result = createNaryFAdd(SimpVect, InstrQuota);
685   else {
686     // The addition is folded to 0.0.
687     Result = ConstantFP::get(Instr->getType(), 0.0);
688   }
689 
690   return Result;
691 }
692 
693 Value *FAddCombine::createNaryFAdd
694   (const AddendVect &Opnds, unsigned InstrQuota) {
695   assert(!Opnds.empty() && "Expect at least one addend");
696 
697   // Step 1: Check if the # of instructions needed exceeds the quota.
698   //
699   unsigned InstrNeeded = calcInstrNumber(Opnds);
700   if (InstrNeeded > InstrQuota)
701     return nullptr;
702 
703   initCreateInstNum();
704 
705   // step 2: Emit the N-ary addition.
706   // Note that at most three instructions are involved in Fadd-InstCombine: the
707   // addition in question, and at most two neighboring instructions.
708   // The resulting optimized addition should have at least one less instruction
709   // than the original addition expression tree. This implies that the resulting
710   // N-ary addition has at most two instructions, and we don't need to worry
711   // about tree-height when constructing the N-ary addition.
712 
713   Value *LastVal = nullptr;
714   bool LastValNeedNeg = false;
715 
716   // Iterate the addends, creating fadd/fsub using adjacent two addends.
717   for (AddendVect::const_iterator I = Opnds.begin(), E = Opnds.end();
718        I != E; I++) {
719     bool NeedNeg;
720     Value *V = createAddendVal(**I, NeedNeg);
721     if (!LastVal) {
722       LastVal = V;
723       LastValNeedNeg = NeedNeg;
724       continue;
725     }
726 
727     if (LastValNeedNeg == NeedNeg) {
728       LastVal = createFAdd(LastVal, V);
729       continue;
730     }
731 
732     if (LastValNeedNeg)
733       LastVal = createFSub(V, LastVal);
734     else
735       LastVal = createFSub(LastVal, V);
736 
737     LastValNeedNeg = false;
738   }
739 
740   if (LastValNeedNeg) {
741     LastVal = createFNeg(LastVal);
742   }
743 
744   #ifndef NDEBUG
745     assert(CreateInstrNum == InstrNeeded &&
746            "Inconsistent in instruction numbers");
747   #endif
748 
749   return LastVal;
750 }
751 
752 Value *FAddCombine::createFSub(Value *Opnd0, Value *Opnd1) {
753   Value *V = Builder->CreateFSub(Opnd0, Opnd1);
754   if (Instruction *I = dyn_cast<Instruction>(V))
755     createInstPostProc(I);
756   return V;
757 }
758 
759 Value *FAddCombine::createFNeg(Value *V) {
760   Value *Zero = cast<Value>(ConstantFP::getZeroValueForNegation(V->getType()));
761   Value *NewV = createFSub(Zero, V);
762   if (Instruction *I = dyn_cast<Instruction>(NewV))
763     createInstPostProc(I, true); // fneg's don't receive instruction numbers.
764   return NewV;
765 }
766 
767 Value *FAddCombine::createFAdd(Value *Opnd0, Value *Opnd1) {
768   Value *V = Builder->CreateFAdd(Opnd0, Opnd1);
769   if (Instruction *I = dyn_cast<Instruction>(V))
770     createInstPostProc(I);
771   return V;
772 }
773 
774 Value *FAddCombine::createFMul(Value *Opnd0, Value *Opnd1) {
775   Value *V = Builder->CreateFMul(Opnd0, Opnd1);
776   if (Instruction *I = dyn_cast<Instruction>(V))
777     createInstPostProc(I);
778   return V;
779 }
780 
781 Value *FAddCombine::createFDiv(Value *Opnd0, Value *Opnd1) {
782   Value *V = Builder->CreateFDiv(Opnd0, Opnd1);
783   if (Instruction *I = dyn_cast<Instruction>(V))
784     createInstPostProc(I);
785   return V;
786 }
787 
788 void FAddCombine::createInstPostProc(Instruction *NewInstr, bool NoNumber) {
789   NewInstr->setDebugLoc(Instr->getDebugLoc());
790 
791   // Keep track of the number of instruction created.
792   if (!NoNumber)
793     incCreateInstNum();
794 
795   // Propagate fast-math flags
796   NewInstr->setFastMathFlags(Instr->getFastMathFlags());
797 }
798 
799 // Return the number of instruction needed to emit the N-ary addition.
800 // NOTE: Keep this function in sync with createAddendVal().
801 unsigned FAddCombine::calcInstrNumber(const AddendVect &Opnds) {
802   unsigned OpndNum = Opnds.size();
803   unsigned InstrNeeded = OpndNum - 1;
804 
805   // The number of addends in the form of "(-1)*x".
806   unsigned NegOpndNum = 0;
807 
808   // Adjust the number of instructions needed to emit the N-ary add.
809   for (AddendVect::const_iterator I = Opnds.begin(), E = Opnds.end();
810        I != E; I++) {
811     const FAddend *Opnd = *I;
812     if (Opnd->isConstant())
813       continue;
814 
815     const FAddendCoef &CE = Opnd->getCoef();
816     if (CE.isMinusOne() || CE.isMinusTwo())
817       NegOpndNum++;
818 
819     // Let the addend be "c * x". If "c == +/-1", the value of the addend
820     // is immediately available; otherwise, it needs exactly one instruction
821     // to evaluate the value.
822     if (!CE.isMinusOne() && !CE.isOne())
823       InstrNeeded++;
824   }
825   if (NegOpndNum == OpndNum)
826     InstrNeeded++;
827   return InstrNeeded;
828 }
829 
830 // Input Addend        Value           NeedNeg(output)
831 // ================================================================
832 // Constant C          C               false
833 // <+/-1, V>           V               coefficient is -1
834 // <2/-2, V>          "fadd V, V"      coefficient is -2
835 // <C, V>             "fmul V, C"      false
836 //
837 // NOTE: Keep this function in sync with FAddCombine::calcInstrNumber.
838 Value *FAddCombine::createAddendVal(const FAddend &Opnd, bool &NeedNeg) {
839   const FAddendCoef &Coeff = Opnd.getCoef();
840 
841   if (Opnd.isConstant()) {
842     NeedNeg = false;
843     return Coeff.getValue(Instr->getType());
844   }
845 
846   Value *OpndVal = Opnd.getSymVal();
847 
848   if (Coeff.isMinusOne() || Coeff.isOne()) {
849     NeedNeg = Coeff.isMinusOne();
850     return OpndVal;
851   }
852 
853   if (Coeff.isTwo() || Coeff.isMinusTwo()) {
854     NeedNeg = Coeff.isMinusTwo();
855     return createFAdd(OpndVal, OpndVal);
856   }
857 
858   NeedNeg = false;
859   return createFMul(OpndVal, Coeff.getValue(Instr->getType()));
860 }
861 
862 // If one of the operands only has one non-zero bit, and if the other
863 // operand has a known-zero bit in a more significant place than it (not
864 // including the sign bit) the ripple may go up to and fill the zero, but
865 // won't change the sign. For example, (X & ~4) + 1.
866 static bool checkRippleForAdd(const APInt &Op0KnownZero,
867                               const APInt &Op1KnownZero) {
868   APInt Op1MaybeOne = ~Op1KnownZero;
869   // Make sure that one of the operand has at most one bit set to 1.
870   if (Op1MaybeOne.countPopulation() != 1)
871     return false;
872 
873   // Find the most significant known 0 other than the sign bit.
874   int BitWidth = Op0KnownZero.getBitWidth();
875   APInt Op0KnownZeroTemp(Op0KnownZero);
876   Op0KnownZeroTemp.clearBit(BitWidth - 1);
877   int Op0ZeroPosition = BitWidth - Op0KnownZeroTemp.countLeadingZeros() - 1;
878 
879   int Op1OnePosition = BitWidth - Op1MaybeOne.countLeadingZeros() - 1;
880   assert(Op1OnePosition >= 0);
881 
882   // This also covers the case of no known zero, since in that case
883   // Op0ZeroPosition is -1.
884   return Op0ZeroPosition >= Op1OnePosition;
885 }
886 
887 /// Return true if we can prove that:
888 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
889 /// This basically requires proving that the add in the original type would not
890 /// overflow to change the sign bit or have a carry out.
891 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS,
892                                             Instruction &CxtI) {
893   // There are different heuristics we can use for this.  Here are some simple
894   // ones.
895 
896   // If LHS and RHS each have at least two sign bits, the addition will look
897   // like
898   //
899   // XX..... +
900   // YY.....
901   //
902   // If the carry into the most significant position is 0, X and Y can't both
903   // be 1 and therefore the carry out of the addition is also 0.
904   //
905   // If the carry into the most significant position is 1, X and Y can't both
906   // be 0 and therefore the carry out of the addition is also 1.
907   //
908   // Since the carry into the most significant position is always equal to
909   // the carry out of the addition, there is no signed overflow.
910   if (ComputeNumSignBits(LHS, 0, &CxtI) > 1 &&
911       ComputeNumSignBits(RHS, 0, &CxtI) > 1)
912     return true;
913 
914   unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
915   APInt LHSKnownZero(BitWidth, 0);
916   APInt LHSKnownOne(BitWidth, 0);
917   computeKnownBits(LHS, LHSKnownZero, LHSKnownOne, 0, &CxtI);
918 
919   APInt RHSKnownZero(BitWidth, 0);
920   APInt RHSKnownOne(BitWidth, 0);
921   computeKnownBits(RHS, RHSKnownZero, RHSKnownOne, 0, &CxtI);
922 
923   // Addition of two 2's compliment numbers having opposite signs will never
924   // overflow.
925   if ((LHSKnownOne[BitWidth - 1] && RHSKnownZero[BitWidth - 1]) ||
926       (LHSKnownZero[BitWidth - 1] && RHSKnownOne[BitWidth - 1]))
927     return true;
928 
929   // Check if carry bit of addition will not cause overflow.
930   if (checkRippleForAdd(LHSKnownZero, RHSKnownZero))
931     return true;
932   if (checkRippleForAdd(RHSKnownZero, LHSKnownZero))
933     return true;
934 
935   return false;
936 }
937 
938 /// \brief Return true if we can prove that:
939 ///    (sub LHS, RHS)  === (sub nsw LHS, RHS)
940 /// This basically requires proving that the add in the original type would not
941 /// overflow to change the sign bit or have a carry out.
942 /// TODO: Handle this for Vectors.
943 bool InstCombiner::WillNotOverflowSignedSub(Value *LHS, Value *RHS,
944                                             Instruction &CxtI) {
945   // If LHS and RHS each have at least two sign bits, the subtraction
946   // cannot overflow.
947   if (ComputeNumSignBits(LHS, 0, &CxtI) > 1 &&
948       ComputeNumSignBits(RHS, 0, &CxtI) > 1)
949     return true;
950 
951   unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
952   APInt LHSKnownZero(BitWidth, 0);
953   APInt LHSKnownOne(BitWidth, 0);
954   computeKnownBits(LHS, LHSKnownZero, LHSKnownOne, 0, &CxtI);
955 
956   APInt RHSKnownZero(BitWidth, 0);
957   APInt RHSKnownOne(BitWidth, 0);
958   computeKnownBits(RHS, RHSKnownZero, RHSKnownOne, 0, &CxtI);
959 
960   // Subtraction of two 2's compliment numbers having identical signs will
961   // never overflow.
962   if ((LHSKnownOne[BitWidth - 1] && RHSKnownOne[BitWidth - 1]) ||
963       (LHSKnownZero[BitWidth - 1] && RHSKnownZero[BitWidth - 1]))
964     return true;
965 
966   // TODO: implement logic similar to checkRippleForAdd
967   return false;
968 }
969 
970 /// \brief Return true if we can prove that:
971 ///    (sub LHS, RHS)  === (sub nuw LHS, RHS)
972 bool InstCombiner::WillNotOverflowUnsignedSub(Value *LHS, Value *RHS,
973                                               Instruction &CxtI) {
974   // If the LHS is negative and the RHS is non-negative, no unsigned wrap.
975   bool LHSKnownNonNegative, LHSKnownNegative;
976   bool RHSKnownNonNegative, RHSKnownNegative;
977   ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, /*Depth=*/0,
978                  &CxtI);
979   ComputeSignBit(RHS, RHSKnownNonNegative, RHSKnownNegative, /*Depth=*/0,
980                  &CxtI);
981   if (LHSKnownNegative && RHSKnownNonNegative)
982     return true;
983 
984   return false;
985 }
986 
987 // Checks if any operand is negative and we can convert add to sub.
988 // This function checks for following negative patterns
989 //   ADD(XOR(OR(Z, NOT(C)), C)), 1) == NEG(AND(Z, C))
990 //   ADD(XOR(AND(Z, C), C), 1) == NEG(OR(Z, ~C))
991 //   XOR(AND(Z, C), (C + 1)) == NEG(OR(Z, ~C)) if C is even
992 static Value *checkForNegativeOperand(BinaryOperator &I,
993                                       InstCombiner::BuilderTy *Builder) {
994   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
995 
996   // This function creates 2 instructions to replace ADD, we need at least one
997   // of LHS or RHS to have one use to ensure benefit in transform.
998   if (!LHS->hasOneUse() && !RHS->hasOneUse())
999     return nullptr;
1000 
1001   Value *X = nullptr, *Y = nullptr, *Z = nullptr;
1002   const APInt *C1 = nullptr, *C2 = nullptr;
1003 
1004   // if ONE is on other side, swap
1005   if (match(RHS, m_Add(m_Value(X), m_One())))
1006     std::swap(LHS, RHS);
1007 
1008   if (match(LHS, m_Add(m_Value(X), m_One()))) {
1009     // if XOR on other side, swap
1010     if (match(RHS, m_Xor(m_Value(Y), m_APInt(C1))))
1011       std::swap(X, RHS);
1012 
1013     if (match(X, m_Xor(m_Value(Y), m_APInt(C1)))) {
1014       // X = XOR(Y, C1), Y = OR(Z, C2), C2 = NOT(C1) ==> X == NOT(AND(Z, C1))
1015       // ADD(ADD(X, 1), RHS) == ADD(X, ADD(RHS, 1)) == SUB(RHS, AND(Z, C1))
1016       if (match(Y, m_Or(m_Value(Z), m_APInt(C2))) && (*C2 == ~(*C1))) {
1017         Value *NewAnd = Builder->CreateAnd(Z, *C1);
1018         return Builder->CreateSub(RHS, NewAnd, "sub");
1019       } else if (match(Y, m_And(m_Value(Z), m_APInt(C2))) && (*C1 == *C2)) {
1020         // X = XOR(Y, C1), Y = AND(Z, C2), C2 == C1 ==> X == NOT(OR(Z, ~C1))
1021         // ADD(ADD(X, 1), RHS) == ADD(X, ADD(RHS, 1)) == SUB(RHS, OR(Z, ~C1))
1022         Value *NewOr = Builder->CreateOr(Z, ~(*C1));
1023         return Builder->CreateSub(RHS, NewOr, "sub");
1024       }
1025     }
1026   }
1027 
1028   // Restore LHS and RHS
1029   LHS = I.getOperand(0);
1030   RHS = I.getOperand(1);
1031 
1032   // if XOR is on other side, swap
1033   if (match(RHS, m_Xor(m_Value(Y), m_APInt(C1))))
1034     std::swap(LHS, RHS);
1035 
1036   // C2 is ODD
1037   // LHS = XOR(Y, C1), Y = AND(Z, C2), C1 == (C2 + 1) => LHS == NEG(OR(Z, ~C2))
1038   // ADD(LHS, RHS) == SUB(RHS, OR(Z, ~C2))
1039   if (match(LHS, m_Xor(m_Value(Y), m_APInt(C1))))
1040     if (C1->countTrailingZeros() == 0)
1041       if (match(Y, m_And(m_Value(Z), m_APInt(C2))) && *C1 == (*C2 + 1)) {
1042         Value *NewOr = Builder->CreateOr(Z, ~(*C2));
1043         return Builder->CreateSub(RHS, NewOr, "sub");
1044       }
1045   return nullptr;
1046 }
1047 
1048 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1049   bool Changed = SimplifyAssociativeOrCommutative(I);
1050   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1051 
1052   if (Value *V = SimplifyVectorOp(I))
1053     return replaceInstUsesWith(I, V);
1054 
1055   if (Value *V = SimplifyAddInst(LHS, RHS, I.hasNoSignedWrap(),
1056                                  I.hasNoUnsignedWrap(), DL, TLI, DT, AC))
1057     return replaceInstUsesWith(I, V);
1058 
1059    // (A*B)+(A*C) -> A*(B+C) etc
1060   if (Value *V = SimplifyUsingDistributiveLaws(I))
1061     return replaceInstUsesWith(I, V);
1062 
1063   if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1064     // X + (signbit) --> X ^ signbit
1065     const APInt &Val = CI->getValue();
1066     if (Val.isSignBit())
1067       return BinaryOperator::CreateXor(LHS, RHS);
1068 
1069     // See if SimplifyDemandedBits can simplify this.  This handles stuff like
1070     // (X & 254)+1 -> (X&254)|1
1071     if (SimplifyDemandedInstructionBits(I))
1072       return &I;
1073 
1074     // zext(bool) + C -> bool ? C + 1 : C
1075     if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
1076       if (ZI->getSrcTy()->isIntegerTy(1))
1077         return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
1078 
1079     Value *XorLHS = nullptr; ConstantInt *XorRHS = nullptr;
1080     if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1081       uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
1082       const APInt &RHSVal = CI->getValue();
1083       unsigned ExtendAmt = 0;
1084       // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1085       // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1086       if (XorRHS->getValue() == -RHSVal) {
1087         if (RHSVal.isPowerOf2())
1088           ExtendAmt = TySizeBits - RHSVal.logBase2() - 1;
1089         else if (XorRHS->getValue().isPowerOf2())
1090           ExtendAmt = TySizeBits - XorRHS->getValue().logBase2() - 1;
1091       }
1092 
1093       if (ExtendAmt) {
1094         APInt Mask = APInt::getHighBitsSet(TySizeBits, ExtendAmt);
1095         if (!MaskedValueIsZero(XorLHS, Mask, 0, &I))
1096           ExtendAmt = 0;
1097       }
1098 
1099       if (ExtendAmt) {
1100         Constant *ShAmt = ConstantInt::get(I.getType(), ExtendAmt);
1101         Value *NewShl = Builder->CreateShl(XorLHS, ShAmt, "sext");
1102         return BinaryOperator::CreateAShr(NewShl, ShAmt);
1103       }
1104 
1105       // If this is a xor that was canonicalized from a sub, turn it back into
1106       // a sub and fuse this add with it.
1107       if (LHS->hasOneUse() && (XorRHS->getValue()+1).isPowerOf2()) {
1108         IntegerType *IT = cast<IntegerType>(I.getType());
1109         APInt LHSKnownOne(IT->getBitWidth(), 0);
1110         APInt LHSKnownZero(IT->getBitWidth(), 0);
1111         computeKnownBits(XorLHS, LHSKnownZero, LHSKnownOne, 0, &I);
1112         if ((XorRHS->getValue() | LHSKnownZero).isAllOnesValue())
1113           return BinaryOperator::CreateSub(ConstantExpr::getAdd(XorRHS, CI),
1114                                            XorLHS);
1115       }
1116       // (X + signbit) + C could have gotten canonicalized to (X ^ signbit) + C,
1117       // transform them into (X + (signbit ^ C))
1118       if (XorRHS->getValue().isSignBit())
1119         return BinaryOperator::CreateAdd(XorLHS,
1120                                          ConstantExpr::getXor(XorRHS, CI));
1121     }
1122   }
1123 
1124   if (isa<Constant>(RHS) && isa<PHINode>(LHS))
1125     if (Instruction *NV = FoldOpIntoPhi(I))
1126       return NV;
1127 
1128   if (I.getType()->getScalarType()->isIntegerTy(1))
1129     return BinaryOperator::CreateXor(LHS, RHS);
1130 
1131   // X + X --> X << 1
1132   if (LHS == RHS) {
1133     BinaryOperator *New =
1134       BinaryOperator::CreateShl(LHS, ConstantInt::get(I.getType(), 1));
1135     New->setHasNoSignedWrap(I.hasNoSignedWrap());
1136     New->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
1137     return New;
1138   }
1139 
1140   // -A + B  -->  B - A
1141   // -A + -B  -->  -(A + B)
1142   if (Value *LHSV = dyn_castNegVal(LHS)) {
1143     if (!isa<Constant>(RHS))
1144       if (Value *RHSV = dyn_castNegVal(RHS)) {
1145         Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
1146         return BinaryOperator::CreateNeg(NewAdd);
1147       }
1148 
1149     return BinaryOperator::CreateSub(RHS, LHSV);
1150   }
1151 
1152   // A + -B  -->  A - B
1153   if (!isa<Constant>(RHS))
1154     if (Value *V = dyn_castNegVal(RHS))
1155       return BinaryOperator::CreateSub(LHS, V);
1156 
1157   if (Value *V = checkForNegativeOperand(I, Builder))
1158     return replaceInstUsesWith(I, V);
1159 
1160   // A+B --> A|B iff A and B have no bits set in common.
1161   if (haveNoCommonBitsSet(LHS, RHS, DL, AC, &I, DT))
1162     return BinaryOperator::CreateOr(LHS, RHS);
1163 
1164   if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
1165     Value *X;
1166     if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
1167       return BinaryOperator::CreateSub(SubOne(CRHS), X);
1168   }
1169 
1170   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
1171     // (X & FF00) + xx00  -> (X+xx00) & FF00
1172     Value *X;
1173     ConstantInt *C2;
1174     if (LHS->hasOneUse() &&
1175         match(LHS, m_And(m_Value(X), m_ConstantInt(C2))) &&
1176         CRHS->getValue() == (CRHS->getValue() & C2->getValue())) {
1177       // See if all bits from the first bit set in the Add RHS up are included
1178       // in the mask.  First, get the rightmost bit.
1179       const APInt &AddRHSV = CRHS->getValue();
1180 
1181       // Form a mask of all bits from the lowest bit added through the top.
1182       APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
1183 
1184       // See if the and mask includes all of these bits.
1185       APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
1186 
1187       if (AddRHSHighBits == AddRHSHighBitsAnd) {
1188         // Okay, the xform is safe.  Insert the new add pronto.
1189         Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
1190         return BinaryOperator::CreateAnd(NewAdd, C2);
1191       }
1192     }
1193 
1194     // Try to fold constant add into select arguments.
1195     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
1196       if (Instruction *R = FoldOpIntoSelect(I, SI))
1197         return R;
1198   }
1199 
1200   // add (select X 0 (sub n A)) A  -->  select X A n
1201   {
1202     SelectInst *SI = dyn_cast<SelectInst>(LHS);
1203     Value *A = RHS;
1204     if (!SI) {
1205       SI = dyn_cast<SelectInst>(RHS);
1206       A = LHS;
1207     }
1208     if (SI && SI->hasOneUse()) {
1209       Value *TV = SI->getTrueValue();
1210       Value *FV = SI->getFalseValue();
1211       Value *N;
1212 
1213       // Can we fold the add into the argument of the select?
1214       // We check both true and false select arguments for a matching subtract.
1215       if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
1216         // Fold the add into the true select value.
1217         return SelectInst::Create(SI->getCondition(), N, A);
1218 
1219       if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
1220         // Fold the add into the false select value.
1221         return SelectInst::Create(SI->getCondition(), A, N);
1222     }
1223   }
1224 
1225   // Check for (add (sext x), y), see if we can merge this into an
1226   // integer add followed by a sext.
1227   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
1228     // (add (sext x), cst) --> (sext (add x, cst'))
1229     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
1230       Constant *CI =
1231         ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
1232       if (LHSConv->hasOneUse() &&
1233           ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
1234           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI, I)) {
1235         // Insert the new, smaller add.
1236         Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
1237                                               CI, "addconv");
1238         return new SExtInst(NewAdd, I.getType());
1239       }
1240     }
1241 
1242     // (add (sext x), (sext y)) --> (sext (add int x, y))
1243     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
1244       // Only do this if x/y have the same type, if at last one of them has a
1245       // single use (so we don't increase the number of sexts), and if the
1246       // integer add will not overflow.
1247       if (LHSConv->getOperand(0)->getType() ==
1248               RHSConv->getOperand(0)->getType() &&
1249           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
1250           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
1251                                    RHSConv->getOperand(0), I)) {
1252         // Insert the new integer add.
1253         Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
1254                                              RHSConv->getOperand(0), "addconv");
1255         return new SExtInst(NewAdd, I.getType());
1256       }
1257     }
1258   }
1259 
1260   // (add (xor A, B) (and A, B)) --> (or A, B)
1261   {
1262     Value *A = nullptr, *B = nullptr;
1263     if (match(RHS, m_Xor(m_Value(A), m_Value(B))) &&
1264         (match(LHS, m_And(m_Specific(A), m_Specific(B))) ||
1265          match(LHS, m_And(m_Specific(B), m_Specific(A)))))
1266       return BinaryOperator::CreateOr(A, B);
1267 
1268     if (match(LHS, m_Xor(m_Value(A), m_Value(B))) &&
1269         (match(RHS, m_And(m_Specific(A), m_Specific(B))) ||
1270          match(RHS, m_And(m_Specific(B), m_Specific(A)))))
1271       return BinaryOperator::CreateOr(A, B);
1272   }
1273 
1274   // (add (or A, B) (and A, B)) --> (add A, B)
1275   {
1276     Value *A = nullptr, *B = nullptr;
1277     if (match(RHS, m_Or(m_Value(A), m_Value(B))) &&
1278         (match(LHS, m_And(m_Specific(A), m_Specific(B))) ||
1279          match(LHS, m_And(m_Specific(B), m_Specific(A))))) {
1280       auto *New = BinaryOperator::CreateAdd(A, B);
1281       New->setHasNoSignedWrap(I.hasNoSignedWrap());
1282       New->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
1283       return New;
1284     }
1285 
1286     if (match(LHS, m_Or(m_Value(A), m_Value(B))) &&
1287         (match(RHS, m_And(m_Specific(A), m_Specific(B))) ||
1288          match(RHS, m_And(m_Specific(B), m_Specific(A))))) {
1289       auto *New = BinaryOperator::CreateAdd(A, B);
1290       New->setHasNoSignedWrap(I.hasNoSignedWrap());
1291       New->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
1292       return New;
1293     }
1294   }
1295 
1296   // TODO(jingyue): Consider WillNotOverflowSignedAdd and
1297   // WillNotOverflowUnsignedAdd to reduce the number of invocations of
1298   // computeKnownBits.
1299   if (!I.hasNoSignedWrap() && WillNotOverflowSignedAdd(LHS, RHS, I)) {
1300     Changed = true;
1301     I.setHasNoSignedWrap(true);
1302   }
1303   if (!I.hasNoUnsignedWrap() &&
1304       computeOverflowForUnsignedAdd(LHS, RHS, &I) ==
1305           OverflowResult::NeverOverflows) {
1306     Changed = true;
1307     I.setHasNoUnsignedWrap(true);
1308   }
1309 
1310   return Changed ? &I : nullptr;
1311 }
1312 
1313 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
1314   bool Changed = SimplifyAssociativeOrCommutative(I);
1315   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1316 
1317   if (Value *V = SimplifyVectorOp(I))
1318     return replaceInstUsesWith(I, V);
1319 
1320   if (Value *V =
1321           SimplifyFAddInst(LHS, RHS, I.getFastMathFlags(), DL, TLI, DT, AC))
1322     return replaceInstUsesWith(I, V);
1323 
1324   if (isa<Constant>(RHS)) {
1325     if (isa<PHINode>(LHS))
1326       if (Instruction *NV = FoldOpIntoPhi(I))
1327         return NV;
1328 
1329     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
1330       if (Instruction *NV = FoldOpIntoSelect(I, SI))
1331         return NV;
1332   }
1333 
1334   // -A + B  -->  B - A
1335   // -A + -B  -->  -(A + B)
1336   if (Value *LHSV = dyn_castFNegVal(LHS)) {
1337     Instruction *RI = BinaryOperator::CreateFSub(RHS, LHSV);
1338     RI->copyFastMathFlags(&I);
1339     return RI;
1340   }
1341 
1342   // A + -B  -->  A - B
1343   if (!isa<Constant>(RHS))
1344     if (Value *V = dyn_castFNegVal(RHS)) {
1345       Instruction *RI = BinaryOperator::CreateFSub(LHS, V);
1346       RI->copyFastMathFlags(&I);
1347       return RI;
1348     }
1349 
1350   // Check for (fadd double (sitofp x), y), see if we can merge this into an
1351   // integer add followed by a promotion.
1352   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
1353     // (fadd double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
1354     // ... if the constant fits in the integer value.  This is useful for things
1355     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
1356     // requires a constant pool load, and generally allows the add to be better
1357     // instcombined.
1358     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
1359       Constant *CI =
1360       ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
1361       if (LHSConv->hasOneUse() &&
1362           ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
1363           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI, I)) {
1364         // Insert the new integer add.
1365         Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
1366                                               CI, "addconv");
1367         return new SIToFPInst(NewAdd, I.getType());
1368       }
1369     }
1370 
1371     // (fadd double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
1372     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
1373       // Only do this if x/y have the same type, if at last one of them has a
1374       // single use (so we don't increase the number of int->fp conversions),
1375       // and if the integer add will not overflow.
1376       if (LHSConv->getOperand(0)->getType() ==
1377               RHSConv->getOperand(0)->getType() &&
1378           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
1379           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
1380                                    RHSConv->getOperand(0), I)) {
1381         // Insert the new integer add.
1382         Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
1383                                               RHSConv->getOperand(0),"addconv");
1384         return new SIToFPInst(NewAdd, I.getType());
1385       }
1386     }
1387   }
1388 
1389   // select C, 0, B + select C, A, 0 -> select C, A, B
1390   {
1391     Value *A1, *B1, *C1, *A2, *B2, *C2;
1392     if (match(LHS, m_Select(m_Value(C1), m_Value(A1), m_Value(B1))) &&
1393         match(RHS, m_Select(m_Value(C2), m_Value(A2), m_Value(B2)))) {
1394       if (C1 == C2) {
1395         Constant *Z1=nullptr, *Z2=nullptr;
1396         Value *A, *B, *C=C1;
1397         if (match(A1, m_AnyZero()) && match(B2, m_AnyZero())) {
1398             Z1 = dyn_cast<Constant>(A1); A = A2;
1399             Z2 = dyn_cast<Constant>(B2); B = B1;
1400         } else if (match(B1, m_AnyZero()) && match(A2, m_AnyZero())) {
1401             Z1 = dyn_cast<Constant>(B1); B = B2;
1402             Z2 = dyn_cast<Constant>(A2); A = A1;
1403         }
1404 
1405         if (Z1 && Z2 &&
1406             (I.hasNoSignedZeros() ||
1407              (Z1->isNegativeZeroValue() && Z2->isNegativeZeroValue()))) {
1408           return SelectInst::Create(C, A, B);
1409         }
1410       }
1411     }
1412   }
1413 
1414   if (I.hasUnsafeAlgebra()) {
1415     if (Value *V = FAddCombine(Builder).simplify(&I))
1416       return replaceInstUsesWith(I, V);
1417   }
1418 
1419   return Changed ? &I : nullptr;
1420 }
1421 
1422 /// Optimize pointer differences into the same array into a size.  Consider:
1423 ///  &A[10] - &A[0]: we should compile this to "10".  LHS/RHS are the pointer
1424 /// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
1425 ///
1426 Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS,
1427                                                Type *Ty) {
1428   // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
1429   // this.
1430   bool Swapped = false;
1431   GEPOperator *GEP1 = nullptr, *GEP2 = nullptr;
1432 
1433   // For now we require one side to be the base pointer "A" or a constant
1434   // GEP derived from it.
1435   if (GEPOperator *LHSGEP = dyn_cast<GEPOperator>(LHS)) {
1436     // (gep X, ...) - X
1437     if (LHSGEP->getOperand(0) == RHS) {
1438       GEP1 = LHSGEP;
1439       Swapped = false;
1440     } else if (GEPOperator *RHSGEP = dyn_cast<GEPOperator>(RHS)) {
1441       // (gep X, ...) - (gep X, ...)
1442       if (LHSGEP->getOperand(0)->stripPointerCasts() ==
1443             RHSGEP->getOperand(0)->stripPointerCasts()) {
1444         GEP2 = RHSGEP;
1445         GEP1 = LHSGEP;
1446         Swapped = false;
1447       }
1448     }
1449   }
1450 
1451   if (GEPOperator *RHSGEP = dyn_cast<GEPOperator>(RHS)) {
1452     // X - (gep X, ...)
1453     if (RHSGEP->getOperand(0) == LHS) {
1454       GEP1 = RHSGEP;
1455       Swapped = true;
1456     } else if (GEPOperator *LHSGEP = dyn_cast<GEPOperator>(LHS)) {
1457       // (gep X, ...) - (gep X, ...)
1458       if (RHSGEP->getOperand(0)->stripPointerCasts() ==
1459             LHSGEP->getOperand(0)->stripPointerCasts()) {
1460         GEP2 = LHSGEP;
1461         GEP1 = RHSGEP;
1462         Swapped = true;
1463       }
1464     }
1465   }
1466 
1467   // Avoid duplicating the arithmetic if GEP2 has non-constant indices and
1468   // multiple users.
1469   if (!GEP1 ||
1470       (GEP2 && !GEP2->hasAllConstantIndices() && !GEP2->hasOneUse()))
1471     return nullptr;
1472 
1473   // Emit the offset of the GEP and an intptr_t.
1474   Value *Result = EmitGEPOffset(GEP1);
1475 
1476   // If we had a constant expression GEP on the other side offsetting the
1477   // pointer, subtract it from the offset we have.
1478   if (GEP2) {
1479     Value *Offset = EmitGEPOffset(GEP2);
1480     Result = Builder->CreateSub(Result, Offset);
1481   }
1482 
1483   // If we have p - gep(p, ...)  then we have to negate the result.
1484   if (Swapped)
1485     Result = Builder->CreateNeg(Result, "diff.neg");
1486 
1487   return Builder->CreateIntCast(Result, Ty, true);
1488 }
1489 
1490 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
1491   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1492 
1493   if (Value *V = SimplifyVectorOp(I))
1494     return replaceInstUsesWith(I, V);
1495 
1496   if (Value *V = SimplifySubInst(Op0, Op1, I.hasNoSignedWrap(),
1497                                  I.hasNoUnsignedWrap(), DL, TLI, DT, AC))
1498     return replaceInstUsesWith(I, V);
1499 
1500   // (A*B)-(A*C) -> A*(B-C) etc
1501   if (Value *V = SimplifyUsingDistributiveLaws(I))
1502     return replaceInstUsesWith(I, V);
1503 
1504   // If this is a 'B = x-(-A)', change to B = x+A.
1505   if (Value *V = dyn_castNegVal(Op1)) {
1506     BinaryOperator *Res = BinaryOperator::CreateAdd(Op0, V);
1507 
1508     if (const auto *BO = dyn_cast<BinaryOperator>(Op1)) {
1509       assert(BO->getOpcode() == Instruction::Sub &&
1510              "Expected a subtraction operator!");
1511       if (BO->hasNoSignedWrap() && I.hasNoSignedWrap())
1512         Res->setHasNoSignedWrap(true);
1513     } else {
1514       if (cast<Constant>(Op1)->isNotMinSignedValue() && I.hasNoSignedWrap())
1515         Res->setHasNoSignedWrap(true);
1516     }
1517 
1518     return Res;
1519   }
1520 
1521   if (I.getType()->isIntegerTy(1))
1522     return BinaryOperator::CreateXor(Op0, Op1);
1523 
1524   // Replace (-1 - A) with (~A).
1525   if (match(Op0, m_AllOnes()))
1526     return BinaryOperator::CreateNot(Op1);
1527 
1528   if (Constant *C = dyn_cast<Constant>(Op0)) {
1529     // C - ~X == X + (1+C)
1530     Value *X = nullptr;
1531     if (match(Op1, m_Not(m_Value(X))))
1532       return BinaryOperator::CreateAdd(X, AddOne(C));
1533 
1534     // Try to fold constant sub into select arguments.
1535     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1536       if (Instruction *R = FoldOpIntoSelect(I, SI))
1537         return R;
1538 
1539     // C-(X+C2) --> (C-C2)-X
1540     Constant *C2;
1541     if (match(Op1, m_Add(m_Value(X), m_Constant(C2))))
1542       return BinaryOperator::CreateSub(ConstantExpr::getSub(C, C2), X);
1543 
1544     if (SimplifyDemandedInstructionBits(I))
1545       return &I;
1546 
1547     // Fold (sub 0, (zext bool to B)) --> (sext bool to B)
1548     if (C->isNullValue() && match(Op1, m_ZExt(m_Value(X))))
1549       if (X->getType()->getScalarType()->isIntegerTy(1))
1550         return CastInst::CreateSExtOrBitCast(X, Op1->getType());
1551 
1552     // Fold (sub 0, (sext bool to B)) --> (zext bool to B)
1553     if (C->isNullValue() && match(Op1, m_SExt(m_Value(X))))
1554       if (X->getType()->getScalarType()->isIntegerTy(1))
1555         return CastInst::CreateZExtOrBitCast(X, Op1->getType());
1556   }
1557 
1558   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1559     // -(X >>u 31) -> (X >>s 31)
1560     // -(X >>s 31) -> (X >>u 31)
1561     if (C->isZero()) {
1562       Value *X;
1563       ConstantInt *CI;
1564       if (match(Op1, m_LShr(m_Value(X), m_ConstantInt(CI))) &&
1565           // Verify we are shifting out everything but the sign bit.
1566           CI->getValue() == I.getType()->getPrimitiveSizeInBits() - 1)
1567         return BinaryOperator::CreateAShr(X, CI);
1568 
1569       if (match(Op1, m_AShr(m_Value(X), m_ConstantInt(CI))) &&
1570           // Verify we are shifting out everything but the sign bit.
1571           CI->getValue() == I.getType()->getPrimitiveSizeInBits() - 1)
1572         return BinaryOperator::CreateLShr(X, CI);
1573     }
1574 
1575     // Turn this into a xor if LHS is 2^n-1 and the remaining bits are known
1576     // zero.
1577     APInt IntVal = C->getValue();
1578     if ((IntVal + 1).isPowerOf2()) {
1579       unsigned BitWidth = I.getType()->getScalarSizeInBits();
1580       APInt KnownZero(BitWidth, 0);
1581       APInt KnownOne(BitWidth, 0);
1582       computeKnownBits(&I, KnownZero, KnownOne, 0, &I);
1583       if ((IntVal | KnownZero).isAllOnesValue()) {
1584         return BinaryOperator::CreateXor(Op1, C);
1585       }
1586     }
1587   }
1588 
1589   {
1590     Value *Y;
1591     // X-(X+Y) == -Y    X-(Y+X) == -Y
1592     if (match(Op1, m_Add(m_Specific(Op0), m_Value(Y))) ||
1593         match(Op1, m_Add(m_Value(Y), m_Specific(Op0))))
1594       return BinaryOperator::CreateNeg(Y);
1595 
1596     // (X-Y)-X == -Y
1597     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(Y))))
1598       return BinaryOperator::CreateNeg(Y);
1599   }
1600 
1601   // (sub (or A, B) (xor A, B)) --> (and A, B)
1602   {
1603     Value *A = nullptr, *B = nullptr;
1604     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
1605         (match(Op0, m_Or(m_Specific(A), m_Specific(B))) ||
1606          match(Op0, m_Or(m_Specific(B), m_Specific(A)))))
1607       return BinaryOperator::CreateAnd(A, B);
1608   }
1609 
1610   if (Op0->hasOneUse()) {
1611     Value *Y = nullptr;
1612     // ((X | Y) - X) --> (~X & Y)
1613     if (match(Op0, m_Or(m_Value(Y), m_Specific(Op1))) ||
1614         match(Op0, m_Or(m_Specific(Op1), m_Value(Y))))
1615       return BinaryOperator::CreateAnd(
1616           Y, Builder->CreateNot(Op1, Op1->getName() + ".not"));
1617   }
1618 
1619   if (Op1->hasOneUse()) {
1620     Value *X = nullptr, *Y = nullptr, *Z = nullptr;
1621     Constant *C = nullptr;
1622     Constant *CI = nullptr;
1623 
1624     // (X - (Y - Z))  -->  (X + (Z - Y)).
1625     if (match(Op1, m_Sub(m_Value(Y), m_Value(Z))))
1626       return BinaryOperator::CreateAdd(Op0,
1627                                       Builder->CreateSub(Z, Y, Op1->getName()));
1628 
1629     // (X - (X & Y))   -->   (X & ~Y)
1630     //
1631     if (match(Op1, m_And(m_Value(Y), m_Specific(Op0))) ||
1632         match(Op1, m_And(m_Specific(Op0), m_Value(Y))))
1633       return BinaryOperator::CreateAnd(Op0,
1634                                   Builder->CreateNot(Y, Y->getName() + ".not"));
1635 
1636     // 0 - (X sdiv C)  -> (X sdiv -C)  provided the negation doesn't overflow.
1637     if (match(Op1, m_SDiv(m_Value(X), m_Constant(C))) && match(Op0, m_Zero()) &&
1638         C->isNotMinSignedValue() && !C->isOneValue())
1639       return BinaryOperator::CreateSDiv(X, ConstantExpr::getNeg(C));
1640 
1641     // 0 - (X << Y)  -> (-X << Y)   when X is freely negatable.
1642     if (match(Op1, m_Shl(m_Value(X), m_Value(Y))) && match(Op0, m_Zero()))
1643       if (Value *XNeg = dyn_castNegVal(X))
1644         return BinaryOperator::CreateShl(XNeg, Y);
1645 
1646     // X - A*-B -> X + A*B
1647     // X - -A*B -> X + A*B
1648     Value *A, *B;
1649     if (match(Op1, m_Mul(m_Value(A), m_Neg(m_Value(B)))) ||
1650         match(Op1, m_Mul(m_Neg(m_Value(A)), m_Value(B))))
1651       return BinaryOperator::CreateAdd(Op0, Builder->CreateMul(A, B));
1652 
1653     // X - A*CI -> X + A*-CI
1654     // X - CI*A -> X + A*-CI
1655     if (match(Op1, m_Mul(m_Value(A), m_Constant(CI))) ||
1656         match(Op1, m_Mul(m_Constant(CI), m_Value(A)))) {
1657       Value *NewMul = Builder->CreateMul(A, ConstantExpr::getNeg(CI));
1658       return BinaryOperator::CreateAdd(Op0, NewMul);
1659     }
1660   }
1661 
1662   // Optimize pointer differences into the same array into a size.  Consider:
1663   //  &A[10] - &A[0]: we should compile this to "10".
1664   Value *LHSOp, *RHSOp;
1665   if (match(Op0, m_PtrToInt(m_Value(LHSOp))) &&
1666       match(Op1, m_PtrToInt(m_Value(RHSOp))))
1667     if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
1668       return replaceInstUsesWith(I, Res);
1669 
1670   // trunc(p)-trunc(q) -> trunc(p-q)
1671   if (match(Op0, m_Trunc(m_PtrToInt(m_Value(LHSOp)))) &&
1672       match(Op1, m_Trunc(m_PtrToInt(m_Value(RHSOp)))))
1673     if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
1674       return replaceInstUsesWith(I, Res);
1675 
1676   bool Changed = false;
1677   if (!I.hasNoSignedWrap() && WillNotOverflowSignedSub(Op0, Op1, I)) {
1678     Changed = true;
1679     I.setHasNoSignedWrap(true);
1680   }
1681   if (!I.hasNoUnsignedWrap() && WillNotOverflowUnsignedSub(Op0, Op1, I)) {
1682     Changed = true;
1683     I.setHasNoUnsignedWrap(true);
1684   }
1685 
1686   return Changed ? &I : nullptr;
1687 }
1688 
1689 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
1690   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1691 
1692   if (Value *V = SimplifyVectorOp(I))
1693     return replaceInstUsesWith(I, V);
1694 
1695   if (Value *V =
1696           SimplifyFSubInst(Op0, Op1, I.getFastMathFlags(), DL, TLI, DT, AC))
1697     return replaceInstUsesWith(I, V);
1698 
1699   // fsub nsz 0, X ==> fsub nsz -0.0, X
1700   if (I.getFastMathFlags().noSignedZeros() && match(Op0, m_Zero())) {
1701     // Subtraction from -0.0 is the canonical form of fneg.
1702     Instruction *NewI = BinaryOperator::CreateFNeg(Op1);
1703     NewI->copyFastMathFlags(&I);
1704     return NewI;
1705   }
1706 
1707   if (isa<Constant>(Op0))
1708     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1709       if (Instruction *NV = FoldOpIntoSelect(I, SI))
1710         return NV;
1711 
1712   // If this is a 'B = x-(-A)', change to B = x+A, potentially looking
1713   // through FP extensions/truncations along the way.
1714   if (Value *V = dyn_castFNegVal(Op1)) {
1715     Instruction *NewI = BinaryOperator::CreateFAdd(Op0, V);
1716     NewI->copyFastMathFlags(&I);
1717     return NewI;
1718   }
1719   if (FPTruncInst *FPTI = dyn_cast<FPTruncInst>(Op1)) {
1720     if (Value *V = dyn_castFNegVal(FPTI->getOperand(0))) {
1721       Value *NewTrunc = Builder->CreateFPTrunc(V, I.getType());
1722       Instruction *NewI = BinaryOperator::CreateFAdd(Op0, NewTrunc);
1723       NewI->copyFastMathFlags(&I);
1724       return NewI;
1725     }
1726   } else if (FPExtInst *FPEI = dyn_cast<FPExtInst>(Op1)) {
1727     if (Value *V = dyn_castFNegVal(FPEI->getOperand(0))) {
1728       Value *NewExt = Builder->CreateFPExt(V, I.getType());
1729       Instruction *NewI = BinaryOperator::CreateFAdd(Op0, NewExt);
1730       NewI->copyFastMathFlags(&I);
1731       return NewI;
1732     }
1733   }
1734 
1735   if (I.hasUnsafeAlgebra()) {
1736     if (Value *V = FAddCombine(Builder).simplify(&I))
1737       return replaceInstUsesWith(I, V);
1738   }
1739 
1740   return nullptr;
1741 }
1742