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