[Modules] Sink all the DEBUG_TYPE defines for InstCombine out of the
[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 #define DEBUG_TYPE "instcombine"
15 #include "InstCombine.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/Analysis/InstructionSimplify.h"
18 #include "llvm/IR/DataLayout.h"
19 #include "llvm/IR/GetElementPtrTypeIterator.h"
20 #include "llvm/IR/PatternMatch.h"
21 using namespace llvm;
22 using namespace PatternMatch;
23
24 namespace {
25
26   /// Class representing coefficient of floating-point addend.
27   /// This class needs to be highly efficient, which is especially true for
28   /// the constructor. As of I write this comment, the cost of the default
29   /// constructor is merely 4-byte-store-zero (Assuming compiler is able to
30   /// perform write-merging).
31   ///
32   class FAddendCoef {
33   public:
34     // The constructor has to initialize a APFloat, which is uncessary for
35     // most addends which have coefficient either 1 or -1. So, the constructor
36     // is expensive. In order to avoid the cost of the constructor, we should
37     // reuse some instances whenever possible. The pre-created instances
38     // FAddCombine::Add[0-5] embodies this idea.
39     //
40     FAddendCoef() : IsFp(false), BufHasFpVal(false), IntVal(0) {}
41     ~FAddendCoef();
42
43     void set(short C) {
44       assert(!insaneIntVal(C) && "Insane coefficient");
45       IsFp = false; IntVal = C;
46     }
47
48     void set(const APFloat& C);
49
50     void negate();
51
52     bool isZero() const { return isInt() ? !IntVal : getFpVal().isZero(); }
53     Value *getValue(Type *) const;
54
55     // If possible, don't define operator+/operator- etc because these
56     // operators inevitably call FAddendCoef's constructor which is not cheap.
57     void operator=(const FAddendCoef &A);
58     void operator+=(const FAddendCoef &A);
59     void operator-=(const FAddendCoef &A);
60     void operator*=(const FAddendCoef &S);
61
62     bool isOne() const { return isInt() && IntVal == 1; }
63     bool isTwo() const { return isInt() && IntVal == 2; }
64     bool isMinusOne() const { return isInt() && IntVal == -1; }
65     bool isMinusTwo() const { return isInt() && IntVal == -2; }
66
67   private:
68     bool insaneIntVal(int V) { return V > 4 || V < -4; }
69     APFloat *getFpValPtr(void)
70       { return reinterpret_cast<APFloat*>(&FpValBuf.buffer[0]); }
71     const APFloat *getFpValPtr(void) const
72       { return reinterpret_cast<const APFloat*>(&FpValBuf.buffer[0]); }
73
74     const APFloat &getFpVal(void) const {
75       assert(IsFp && BufHasFpVal && "Incorret state");
76       return *getFpValPtr();
77     }
78
79     APFloat &getFpVal(void) {
80       assert(IsFp && BufHasFpVal && "Incorret state");
81       return *getFpValPtr();
82     }
83
84     bool isInt() const { return !IsFp; }
85
86     // If the coefficient is represented by an integer, promote it to a
87     // floating point.
88     void convertToFpType(const fltSemantics &Sem);
89
90     // Construct an APFloat from a signed integer.
91     // TODO: We should get rid of this function when APFloat can be constructed
92     //       from an *SIGNED* integer.
93     APFloat createAPFloatFromInt(const fltSemantics &Sem, int Val);
94   private:
95
96     bool IsFp;
97
98     // True iff FpValBuf contains an instance of APFloat.
99     bool BufHasFpVal;
100
101     // The integer coefficient of an individual addend is either 1 or -1,
102     // and we try to simplify at most 4 addends from neighboring at most
103     // two instructions. So the range of <IntVal> falls in [-4, 4]. APInt
104     // is overkill of this end.
105     short IntVal;
106
107     AlignedCharArrayUnion<APFloat> FpValBuf;
108   };
109
110   /// FAddend is used to represent floating-point addend. An addend is
111   /// represented as <C, V>, where the V is a symbolic value, and C is a
112   /// constant coefficient. A constant addend is represented as <C, 0>.
113   ///
114   class FAddend {
115   public:
116     FAddend() { Val = 0; }
117
118     Value *getSymVal (void) const { return Val; }
119     const FAddendCoef &getCoef(void) const { return Coeff; }
120
121     bool isConstant() const { return Val == 0; }
122     bool isZero() const { return Coeff.isZero(); }
123
124     void set(short Coefficient, Value *V) { Coeff.set(Coefficient), Val = V; }
125     void set(const APFloat& Coefficient, Value *V)
126       { Coeff.set(Coefficient); Val = V; }
127     void set(const ConstantFP* Coefficient, Value *V)
128       { Coeff.set(Coefficient->getValueAPF()); Val = V; }
129
130     void negate() { Coeff.negate(); }
131
132     /// Drill down the U-D chain one step to find the definition of V, and
133     /// try to break the definition into one or two addends.
134     static unsigned drillValueDownOneStep(Value* V, FAddend &A0, FAddend &A1);
135
136     /// Similar to FAddend::drillDownOneStep() except that the value being
137     /// splitted is the addend itself.
138     unsigned drillAddendDownOneStep(FAddend &Addend0, FAddend &Addend1) const;
139
140     void operator+=(const FAddend &T) {
141       assert((Val == T.Val) && "Symbolic-values disagree");
142       Coeff += T.Coeff;
143     }
144
145   private:
146     void Scale(const FAddendCoef& ScaleAmt) { Coeff *= ScaleAmt; }
147
148     // This addend has the value of "Coeff * Val".
149     Value *Val;
150     FAddendCoef Coeff;
151   };
152
153   /// FAddCombine is the class for optimizing an unsafe fadd/fsub along
154   /// with its neighboring at most two instructions.
155   ///
156   class FAddCombine {
157   public:
158     FAddCombine(InstCombiner::BuilderTy *B) : Builder(B), Instr(0) {}
159     Value *simplify(Instruction *FAdd);
160
161   private:
162     typedef SmallVector<const FAddend*, 4> AddendVect;
163
164     Value *simplifyFAdd(AddendVect& V, unsigned InstrQuota);
165
166     Value *performFactorization(Instruction *I);
167
168     /// Convert given addend to a Value
169     Value *createAddendVal(const FAddend &A, bool& NeedNeg);
170
171     /// Return the number of instructions needed to emit the N-ary addition.
172     unsigned calcInstrNumber(const AddendVect& Vect);
173     Value *createFSub(Value *Opnd0, Value *Opnd1);
174     Value *createFAdd(Value *Opnd0, Value *Opnd1);
175     Value *createFMul(Value *Opnd0, Value *Opnd1);
176     Value *createFDiv(Value *Opnd0, Value *Opnd1);
177     Value *createFNeg(Value *V);
178     Value *createNaryFAdd(const AddendVect& Opnds, unsigned InstrQuota);
179     void createInstPostProc(Instruction *NewInst, bool NoNumber = false);
180
181     InstCombiner::BuilderTy *Builder;
182     Instruction *Instr;
183
184   private:
185      // Debugging stuff are clustered here.
186     #ifndef NDEBUG
187       unsigned CreateInstrNum;
188       void initCreateInstNum() { CreateInstrNum = 0; }
189       void incCreateInstNum() { CreateInstrNum++; }
190     #else
191       void initCreateInstNum() {}
192       void incCreateInstNum() {}
193     #endif
194   };
195 }
196
197 //===----------------------------------------------------------------------===//
198 //
199 // Implementation of
200 //    {FAddendCoef, FAddend, FAddition, FAddCombine}.
201 //
202 //===----------------------------------------------------------------------===//
203 FAddendCoef::~FAddendCoef() {
204   if (BufHasFpVal)
205     getFpValPtr()->~APFloat();
206 }
207
208 void FAddendCoef::set(const APFloat& C) {
209   APFloat *P = getFpValPtr();
210
211   if (isInt()) {
212     // As the buffer is meanless byte stream, we cannot call
213     // APFloat::operator=().
214     new(P) APFloat(C);
215   } else
216     *P = C;
217
218   IsFp = BufHasFpVal = true;
219 }
220
221 void FAddendCoef::convertToFpType(const fltSemantics &Sem) {
222   if (!isInt())
223     return;
224
225   APFloat *P = getFpValPtr();
226   if (IntVal > 0)
227     new(P) APFloat(Sem, IntVal);
228   else {
229     new(P) APFloat(Sem, 0 - IntVal);
230     P->changeSign();
231   }
232   IsFp = BufHasFpVal = true;
233 }
234
235 APFloat FAddendCoef::createAPFloatFromInt(const fltSemantics &Sem, int Val) {
236   if (Val >= 0)
237     return APFloat(Sem, Val);
238
239   APFloat T(Sem, 0 - Val);
240   T.changeSign();
241
242   return T;
243 }
244
245 void FAddendCoef::operator=(const FAddendCoef &That) {
246   if (That.isInt())
247     set(That.IntVal);
248   else
249     set(That.getFpVal());
250 }
251
252 void FAddendCoef::operator+=(const FAddendCoef &That) {
253   enum APFloat::roundingMode RndMode = APFloat::rmNearestTiesToEven;
254   if (isInt() == That.isInt()) {
255     if (isInt())
256       IntVal += That.IntVal;
257     else
258       getFpVal().add(That.getFpVal(), RndMode);
259     return;
260   }
261
262   if (isInt()) {
263     const APFloat &T = That.getFpVal();
264     convertToFpType(T.getSemantics());
265     getFpVal().add(T, RndMode);
266     return;
267   }
268
269   APFloat &T = getFpVal();
270   T.add(createAPFloatFromInt(T.getSemantics(), That.IntVal), RndMode);
271 }
272
273 void FAddendCoef::operator-=(const FAddendCoef &That) {
274   enum APFloat::roundingMode RndMode = APFloat::rmNearestTiesToEven;
275   if (isInt() == That.isInt()) {
276     if (isInt())
277       IntVal -= That.IntVal;
278     else
279       getFpVal().subtract(That.getFpVal(), RndMode);
280     return;
281   }
282
283   if (isInt()) {
284     const APFloat &T = That.getFpVal();
285     convertToFpType(T.getSemantics());
286     getFpVal().subtract(T, RndMode);
287     return;
288   }
289
290   APFloat &T = getFpVal();
291   T.subtract(createAPFloatFromInt(T.getSemantics(), IntVal), RndMode);
292 }
293
294 void FAddendCoef::operator*=(const FAddendCoef &That) {
295   if (That.isOne())
296     return;
297
298   if (That.isMinusOne()) {
299     negate();
300     return;
301   }
302
303   if (isInt() && That.isInt()) {
304     int Res = IntVal * (int)That.IntVal;
305     assert(!insaneIntVal(Res) && "Insane int value");
306     IntVal = Res;
307     return;
308   }
309
310   const fltSemantics &Semantic =
311     isInt() ? That.getFpVal().getSemantics() : getFpVal().getSemantics();
312
313   if (isInt())
314     convertToFpType(Semantic);
315   APFloat &F0 = getFpVal();
316
317   if (That.isInt())
318     F0.multiply(createAPFloatFromInt(Semantic, That.IntVal),
319                 APFloat::rmNearestTiesToEven);
320   else
321     F0.multiply(That.getFpVal(), APFloat::rmNearestTiesToEven);
322
323   return;
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 = 0;
353   if (Val == 0 || !(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 = 0;
364
365     if ((C1 = dyn_cast<ConstantFP>(Opnd1)) && C1->isZero())
366       Opnd1 = 0;
367
368     if (Opnd0) {
369       if (!C0)
370         Addend0.set(1, Opnd0);
371       else
372         Addend0.set(C0, 0);
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, 0);
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()), 0);
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 0;
448
449   bool isMpy = false;
450   if (I0->getOpcode() == Instruction::FMul)
451     isMpy = true;
452   else if (I0->getOpcode() != Instruction::FDiv)
453     return 0;
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 = 0;
466   Value *AddSub0 = 0, *AddSub1 = 0;
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 0;
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 0;
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 0;
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() : 0;
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
605   unsigned AddendNum = Addends.size();
606   assert(AddendNum <= 4 && "Too many addends");
607
608   // For saving intermediate results;
609   unsigned NextTmpIdx = 0;
610   FAddend TmpResult[3];
611
612   // Points to the constant addend of the resulting simplified expression.
613   // If the resulting expr has constant-addend, this constant-addend is
614   // desirable to reside at the top of the resulting expression tree. Placing
615   // constant close to supper-expr(s) will potentially reveal some optimization
616   // opportunities in super-expr(s).
617   //
618   const FAddend *ConstAdd = 0;
619
620   // Simplified addends are placed <SimpVect>.
621   AddendVect SimpVect;
622
623   // The outer loop works on one symbolic-value at a time. Suppose the input
624   // addends are : <a1, x>, <b1, y>, <a2, x>, <c1, z>, <b2, y>, ...
625   // The symbolic-values will be processed in this order: x, y, z.
626   //
627   for (unsigned SymIdx = 0; SymIdx < AddendNum; SymIdx++) {
628
629     const FAddend *ThisAddend = Addends[SymIdx];
630     if (!ThisAddend) {
631       // This addend was processed before.
632       continue;
633     }
634
635     Value *Val = ThisAddend->getSymVal();
636     unsigned StartIdx = SimpVect.size();
637     SimpVect.push_back(ThisAddend);
638
639     // The inner loop collects addends sharing same symbolic-value, and these
640     // addends will be later on folded into a single addend. Following above
641     // example, if the symbolic value "y" is being processed, the inner loop
642     // will collect two addends "<b1,y>" and "<b2,Y>". These two addends will
643     // be later on folded into "<b1+b2, y>".
644     //
645     for (unsigned SameSymIdx = SymIdx + 1;
646          SameSymIdx < AddendNum; SameSymIdx++) {
647       const FAddend *T = Addends[SameSymIdx];
648       if (T && T->getSymVal() == Val) {
649         // Set null such that next iteration of the outer loop will not process
650         // this addend again.
651         Addends[SameSymIdx] = 0;
652         SimpVect.push_back(T);
653       }
654     }
655
656     // If multiple addends share same symbolic value, fold them together.
657     if (StartIdx + 1 != SimpVect.size()) {
658       FAddend &R = TmpResult[NextTmpIdx ++];
659       R = *SimpVect[StartIdx];
660       for (unsigned Idx = StartIdx + 1; Idx < SimpVect.size(); Idx++)
661         R += *SimpVect[Idx];
662
663       // Pop all addends being folded and push the resulting folded addend.
664       SimpVect.resize(StartIdx);
665       if (Val != 0) {
666         if (!R.isZero()) {
667           SimpVect.push_back(&R);
668         }
669       } else {
670         // Don't push constant addend at this time. It will be the last element
671         // of <SimpVect>.
672         ConstAdd = &R;
673       }
674     }
675   }
676
677   assert((NextTmpIdx <= array_lengthof(TmpResult) + 1) &&
678          "out-of-bound access");
679
680   if (ConstAdd)
681     SimpVect.push_back(ConstAdd);
682
683   Value *Result;
684   if (!SimpVect.empty())
685     Result = createNaryFAdd(SimpVect, InstrQuota);
686   else {
687     // The addition is folded to 0.0.
688     Result = ConstantFP::get(Instr->getType(), 0.0);
689   }
690
691   return Result;
692 }
693
694 Value *FAddCombine::createNaryFAdd
695   (const AddendVect &Opnds, unsigned InstrQuota) {
696   assert(!Opnds.empty() && "Expect at least one addend");
697
698   // Step 1: Check if the # of instructions needed exceeds the quota.
699   //
700   unsigned InstrNeeded = calcInstrNumber(Opnds);
701   if (InstrNeeded > InstrQuota)
702     return 0;
703
704   initCreateInstNum();
705
706   // step 2: Emit the N-ary addition.
707   // Note that at most three instructions are involved in Fadd-InstCombine: the
708   // addition in question, and at most two neighboring instructions.
709   // The resulting optimized addition should have at least one less instruction
710   // than the original addition expression tree. This implies that the resulting
711   // N-ary addition has at most two instructions, and we don't need to worry
712   // about tree-height when constructing the N-ary addition.
713
714   Value *LastVal = 0;
715   bool LastValNeedNeg = false;
716
717   // Iterate the addends, creating fadd/fsub using adjacent two addends.
718   for (AddendVect::const_iterator I = Opnds.begin(), E = Opnds.end();
719        I != E; I++) {
720     bool NeedNeg;
721     Value *V = createAddendVal(**I, NeedNeg);
722     if (!LastVal) {
723       LastVal = V;
724       LastValNeedNeg = NeedNeg;
725       continue;
726     }
727
728     if (LastValNeedNeg == NeedNeg) {
729       LastVal = createFAdd(LastVal, V);
730       continue;
731     }
732
733     if (LastValNeedNeg)
734       LastVal = createFSub(V, LastVal);
735     else
736       LastVal = createFSub(LastVal, V);
737
738     LastValNeedNeg = false;
739   }
740
741   if (LastValNeedNeg) {
742     LastVal = createFNeg(LastVal);
743   }
744
745   #ifndef NDEBUG
746     assert(CreateInstrNum == InstrNeeded &&
747            "Inconsistent in instruction numbers");
748   #endif
749
750   return LastVal;
751 }
752
753 Value *FAddCombine::createFSub
754   (Value *Opnd0, Value *Opnd1) {
755   Value *V = Builder->CreateFSub(Opnd0, Opnd1);
756   if (Instruction *I = dyn_cast<Instruction>(V))
757     createInstPostProc(I);
758   return V;
759 }
760
761 Value *FAddCombine::createFNeg(Value *V) {
762   Value *Zero = cast<Value>(ConstantFP::get(V->getType(), 0.0));
763   Value *NewV = createFSub(Zero, V);
764   if (Instruction *I = dyn_cast<Instruction>(NewV))
765     createInstPostProc(I, true); // fneg's don't receive instruction numbers.
766   return NewV;
767 }
768
769 Value *FAddCombine::createFAdd
770   (Value *Opnd0, Value *Opnd1) {
771   Value *V = Builder->CreateFAdd(Opnd0, Opnd1);
772   if (Instruction *I = dyn_cast<Instruction>(V))
773     createInstPostProc(I);
774   return V;
775 }
776
777 Value *FAddCombine::createFMul(Value *Opnd0, Value *Opnd1) {
778   Value *V = Builder->CreateFMul(Opnd0, Opnd1);
779   if (Instruction *I = dyn_cast<Instruction>(V))
780     createInstPostProc(I);
781   return V;
782 }
783
784 Value *FAddCombine::createFDiv(Value *Opnd0, Value *Opnd1) {
785   Value *V = Builder->CreateFDiv(Opnd0, Opnd1);
786   if (Instruction *I = dyn_cast<Instruction>(V))
787     createInstPostProc(I);
788   return V;
789 }
790
791 void FAddCombine::createInstPostProc(Instruction *NewInstr,
792                                      bool NoNumber) {
793   NewInstr->setDebugLoc(Instr->getDebugLoc());
794
795   // Keep track of the number of instruction created.
796   if (!NoNumber)
797     incCreateInstNum();
798
799   // Propagate fast-math flags
800   NewInstr->setFastMathFlags(Instr->getFastMathFlags());
801 }
802
803 // Return the number of instruction needed to emit the N-ary addition.
804 // NOTE: Keep this function in sync with createAddendVal().
805 unsigned FAddCombine::calcInstrNumber(const AddendVect &Opnds) {
806   unsigned OpndNum = Opnds.size();
807   unsigned InstrNeeded = OpndNum - 1;
808
809   // The number of addends in the form of "(-1)*x".
810   unsigned NegOpndNum = 0;
811
812   // Adjust the number of instructions needed to emit the N-ary add.
813   for (AddendVect::const_iterator I = Opnds.begin(), E = Opnds.end();
814        I != E; I++) {
815     const FAddend *Opnd = *I;
816     if (Opnd->isConstant())
817       continue;
818
819     const FAddendCoef &CE = Opnd->getCoef();
820     if (CE.isMinusOne() || CE.isMinusTwo())
821       NegOpndNum++;
822
823     // Let the addend be "c * x". If "c == +/-1", the value of the addend
824     // is immediately available; otherwise, it needs exactly one instruction
825     // to evaluate the value.
826     if (!CE.isMinusOne() && !CE.isOne())
827       InstrNeeded++;
828   }
829   if (NegOpndNum == OpndNum)
830     InstrNeeded++;
831   return InstrNeeded;
832 }
833
834 // Input Addend        Value           NeedNeg(output)
835 // ================================================================
836 // Constant C          C               false
837 // <+/-1, V>           V               coefficient is -1
838 // <2/-2, V>          "fadd V, V"      coefficient is -2
839 // <C, V>             "fmul V, C"      false
840 //
841 // NOTE: Keep this function in sync with FAddCombine::calcInstrNumber.
842 Value *FAddCombine::createAddendVal
843   (const FAddend &Opnd, bool &NeedNeg) {
844   const FAddendCoef &Coeff = Opnd.getCoef();
845
846   if (Opnd.isConstant()) {
847     NeedNeg = false;
848     return Coeff.getValue(Instr->getType());
849   }
850
851   Value *OpndVal = Opnd.getSymVal();
852
853   if (Coeff.isMinusOne() || Coeff.isOne()) {
854     NeedNeg = Coeff.isMinusOne();
855     return OpndVal;
856   }
857
858   if (Coeff.isTwo() || Coeff.isMinusTwo()) {
859     NeedNeg = Coeff.isMinusTwo();
860     return createFAdd(OpndVal, OpndVal);
861   }
862
863   NeedNeg = false;
864   return createFMul(OpndVal, Coeff.getValue(Instr->getType()));
865 }
866
867 // dyn_castFoldableMul - If this value is a multiply that can be folded into
868 // other computations (because it has a constant operand), return the
869 // non-constant operand of the multiply, and set CST to point to the multiplier.
870 // Otherwise, return null.
871 //
872 static inline Value *dyn_castFoldableMul(Value *V, Constant *&CST) {
873   if (!V->hasOneUse() || !V->getType()->isIntOrIntVectorTy())
874     return 0;
875
876   Instruction *I = dyn_cast<Instruction>(V);
877   if (I == 0) return 0;
878
879   if (I->getOpcode() == Instruction::Mul)
880     if ((CST = dyn_cast<Constant>(I->getOperand(1))))
881       return I->getOperand(0);
882   if (I->getOpcode() == Instruction::Shl)
883     if ((CST = dyn_cast<Constant>(I->getOperand(1)))) {
884       // The multiplier is really 1 << CST.
885       CST = ConstantExpr::getShl(ConstantInt::get(V->getType(), 1), CST);
886       return I->getOperand(0);
887     }
888   return 0;
889 }
890
891
892 /// WillNotOverflowSignedAdd - Return true if we can prove that:
893 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
894 /// This basically requires proving that the add in the original type would not
895 /// overflow to change the sign bit or have a carry out.
896 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
897   // There are different heuristics we can use for this.  Here are some simple
898   // ones.
899
900   // Add has the property that adding any two 2's complement numbers can only
901   // have one carry bit which can change a sign.  As such, if LHS and RHS each
902   // have at least two sign bits, we know that the addition of the two values
903   // will sign extend fine.
904   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
905     return true;
906
907
908   // If one of the operands only has one non-zero bit, and if the other operand
909   // has a known-zero bit in a more significant place than it (not including the
910   // sign bit) the ripple may go up to and fill the zero, but won't change the
911   // sign.  For example, (X & ~4) + 1.
912
913   // TODO: Implement.
914
915   return false;
916 }
917
918 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
919   bool Changed = SimplifyAssociativeOrCommutative(I);
920   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
921
922   if (Value *V = SimplifyAddInst(LHS, RHS, I.hasNoSignedWrap(),
923                                  I.hasNoUnsignedWrap(), DL))
924     return ReplaceInstUsesWith(I, V);
925
926   // (A*B)+(A*C) -> A*(B+C) etc
927   if (Value *V = SimplifyUsingDistributiveLaws(I))
928     return ReplaceInstUsesWith(I, V);
929
930   if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
931     // X + (signbit) --> X ^ signbit
932     const APInt &Val = CI->getValue();
933     if (Val.isSignBit())
934       return BinaryOperator::CreateXor(LHS, RHS);
935
936     // See if SimplifyDemandedBits can simplify this.  This handles stuff like
937     // (X & 254)+1 -> (X&254)|1
938     if (SimplifyDemandedInstructionBits(I))
939       return &I;
940
941     // zext(bool) + C -> bool ? C + 1 : C
942     if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
943       if (ZI->getSrcTy()->isIntegerTy(1))
944         return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
945
946     Value *XorLHS = 0; ConstantInt *XorRHS = 0;
947     if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
948       uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
949       const APInt &RHSVal = CI->getValue();
950       unsigned ExtendAmt = 0;
951       // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
952       // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
953       if (XorRHS->getValue() == -RHSVal) {
954         if (RHSVal.isPowerOf2())
955           ExtendAmt = TySizeBits - RHSVal.logBase2() - 1;
956         else if (XorRHS->getValue().isPowerOf2())
957           ExtendAmt = TySizeBits - XorRHS->getValue().logBase2() - 1;
958       }
959
960       if (ExtendAmt) {
961         APInt Mask = APInt::getHighBitsSet(TySizeBits, ExtendAmt);
962         if (!MaskedValueIsZero(XorLHS, Mask))
963           ExtendAmt = 0;
964       }
965
966       if (ExtendAmt) {
967         Constant *ShAmt = ConstantInt::get(I.getType(), ExtendAmt);
968         Value *NewShl = Builder->CreateShl(XorLHS, ShAmt, "sext");
969         return BinaryOperator::CreateAShr(NewShl, ShAmt);
970       }
971
972       // If this is a xor that was canonicalized from a sub, turn it back into
973       // a sub and fuse this add with it.
974       if (LHS->hasOneUse() && (XorRHS->getValue()+1).isPowerOf2()) {
975         IntegerType *IT = cast<IntegerType>(I.getType());
976         APInt LHSKnownOne(IT->getBitWidth(), 0);
977         APInt LHSKnownZero(IT->getBitWidth(), 0);
978         ComputeMaskedBits(XorLHS, LHSKnownZero, LHSKnownOne);
979         if ((XorRHS->getValue() | LHSKnownZero).isAllOnesValue())
980           return BinaryOperator::CreateSub(ConstantExpr::getAdd(XorRHS, CI),
981                                            XorLHS);
982       }
983       // (X + signbit) + C could have gotten canonicalized to (X ^ signbit) + C,
984       // transform them into (X + (signbit ^ C))
985       if (XorRHS->getValue().isSignBit())
986           return BinaryOperator::CreateAdd(XorLHS,
987                                            ConstantExpr::getXor(XorRHS, CI));
988     }
989   }
990
991   if (isa<Constant>(RHS) && isa<PHINode>(LHS))
992     if (Instruction *NV = FoldOpIntoPhi(I))
993       return NV;
994
995   if (I.getType()->getScalarType()->isIntegerTy(1))
996     return BinaryOperator::CreateXor(LHS, RHS);
997
998   // X + X --> X << 1
999   if (LHS == RHS) {
1000     BinaryOperator *New =
1001       BinaryOperator::CreateShl(LHS, ConstantInt::get(I.getType(), 1));
1002     New->setHasNoSignedWrap(I.hasNoSignedWrap());
1003     New->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
1004     return New;
1005   }
1006
1007   // -A + B  -->  B - A
1008   // -A + -B  -->  -(A + B)
1009   if (Value *LHSV = dyn_castNegVal(LHS)) {
1010     if (!isa<Constant>(RHS))
1011       if (Value *RHSV = dyn_castNegVal(RHS)) {
1012         Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
1013         return BinaryOperator::CreateNeg(NewAdd);
1014       }
1015
1016     return BinaryOperator::CreateSub(RHS, LHSV);
1017   }
1018
1019   // A + -B  -->  A - B
1020   if (!isa<Constant>(RHS))
1021     if (Value *V = dyn_castNegVal(RHS))
1022       return BinaryOperator::CreateSub(LHS, V);
1023
1024
1025   {
1026     Constant *C2;
1027     if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1028       if (X == RHS) // X*C + X --> X * (C+1)
1029         return BinaryOperator::CreateMul(RHS, AddOne(C2));
1030
1031       // X*C1 + X*C2 --> X * (C1+C2)
1032       Constant *C1;
1033       if (X == dyn_castFoldableMul(RHS, C1))
1034         return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
1035     }
1036
1037     // X + X*C --> X * (C+1)
1038     if (dyn_castFoldableMul(RHS, C2) == LHS)
1039       return BinaryOperator::CreateMul(LHS, AddOne(C2));
1040   }
1041
1042   // A+B --> A|B iff A and B have no bits set in common.
1043   if (IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
1044     APInt LHSKnownOne(IT->getBitWidth(), 0);
1045     APInt LHSKnownZero(IT->getBitWidth(), 0);
1046     ComputeMaskedBits(LHS, LHSKnownZero, LHSKnownOne);
1047     if (LHSKnownZero != 0) {
1048       APInt RHSKnownOne(IT->getBitWidth(), 0);
1049       APInt RHSKnownZero(IT->getBitWidth(), 0);
1050       ComputeMaskedBits(RHS, RHSKnownZero, RHSKnownOne);
1051
1052       // No bits in common -> bitwise or.
1053       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
1054         return BinaryOperator::CreateOr(LHS, RHS);
1055     }
1056   }
1057
1058   // W*X + Y*Z --> W * (X+Z)  iff W == Y
1059   {
1060     Value *W, *X, *Y, *Z;
1061     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
1062         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
1063       if (W != Y) {
1064         if (W == Z) {
1065           std::swap(Y, Z);
1066         } else if (Y == X) {
1067           std::swap(W, X);
1068         } else if (X == Z) {
1069           std::swap(Y, Z);
1070           std::swap(W, X);
1071         }
1072       }
1073
1074       if (W == Y) {
1075         Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
1076         return BinaryOperator::CreateMul(W, NewAdd);
1077       }
1078     }
1079   }
1080
1081   if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
1082     Value *X;
1083     if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
1084       return BinaryOperator::CreateSub(SubOne(CRHS), X);
1085   }
1086
1087   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
1088     // (X & FF00) + xx00  -> (X+xx00) & FF00
1089     Value *X;
1090     ConstantInt *C2;
1091     if (LHS->hasOneUse() &&
1092         match(LHS, m_And(m_Value(X), m_ConstantInt(C2))) &&
1093         CRHS->getValue() == (CRHS->getValue() & C2->getValue())) {
1094       // See if all bits from the first bit set in the Add RHS up are included
1095       // in the mask.  First, get the rightmost bit.
1096       const APInt &AddRHSV = CRHS->getValue();
1097
1098       // Form a mask of all bits from the lowest bit added through the top.
1099       APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
1100
1101       // See if the and mask includes all of these bits.
1102       APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
1103
1104       if (AddRHSHighBits == AddRHSHighBitsAnd) {
1105         // Okay, the xform is safe.  Insert the new add pronto.
1106         Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
1107         return BinaryOperator::CreateAnd(NewAdd, C2);
1108       }
1109     }
1110
1111     // Try to fold constant add into select arguments.
1112     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
1113       if (Instruction *R = FoldOpIntoSelect(I, SI))
1114         return R;
1115   }
1116
1117   // add (select X 0 (sub n A)) A  -->  select X A n
1118   {
1119     SelectInst *SI = dyn_cast<SelectInst>(LHS);
1120     Value *A = RHS;
1121     if (!SI) {
1122       SI = dyn_cast<SelectInst>(RHS);
1123       A = LHS;
1124     }
1125     if (SI && SI->hasOneUse()) {
1126       Value *TV = SI->getTrueValue();
1127       Value *FV = SI->getFalseValue();
1128       Value *N;
1129
1130       // Can we fold the add into the argument of the select?
1131       // We check both true and false select arguments for a matching subtract.
1132       if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
1133         // Fold the add into the true select value.
1134         return SelectInst::Create(SI->getCondition(), N, A);
1135
1136       if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
1137         // Fold the add into the false select value.
1138         return SelectInst::Create(SI->getCondition(), A, N);
1139     }
1140   }
1141
1142   // Check for (add (sext x), y), see if we can merge this into an
1143   // integer add followed by a sext.
1144   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
1145     // (add (sext x), cst) --> (sext (add x, cst'))
1146     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
1147       Constant *CI =
1148         ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
1149       if (LHSConv->hasOneUse() &&
1150           ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
1151           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
1152         // Insert the new, smaller add.
1153         Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
1154                                               CI, "addconv");
1155         return new SExtInst(NewAdd, I.getType());
1156       }
1157     }
1158
1159     // (add (sext x), (sext y)) --> (sext (add int x, y))
1160     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
1161       // Only do this if x/y have the same type, if at last one of them has a
1162       // single use (so we don't increase the number of sexts), and if the
1163       // integer add will not overflow.
1164       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
1165           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
1166           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
1167                                    RHSConv->getOperand(0))) {
1168         // Insert the new integer add.
1169         Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
1170                                              RHSConv->getOperand(0), "addconv");
1171         return new SExtInst(NewAdd, I.getType());
1172       }
1173     }
1174   }
1175
1176   // Check for (x & y) + (x ^ y)
1177   {
1178     Value *A = 0, *B = 0;
1179     if (match(RHS, m_Xor(m_Value(A), m_Value(B))) &&
1180         (match(LHS, m_And(m_Specific(A), m_Specific(B))) ||
1181          match(LHS, m_And(m_Specific(B), m_Specific(A)))))
1182       return BinaryOperator::CreateOr(A, B);
1183
1184     if (match(LHS, m_Xor(m_Value(A), m_Value(B))) &&
1185         (match(RHS, m_And(m_Specific(A), m_Specific(B))) ||
1186          match(RHS, m_And(m_Specific(B), m_Specific(A)))))
1187       return BinaryOperator::CreateOr(A, B);
1188   }
1189
1190   return Changed ? &I : 0;
1191 }
1192
1193 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
1194   bool Changed = SimplifyAssociativeOrCommutative(I);
1195   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1196
1197   if (Value *V = SimplifyFAddInst(LHS, RHS, I.getFastMathFlags(), DL))
1198     return ReplaceInstUsesWith(I, V);
1199
1200   if (isa<Constant>(RHS)) {
1201     if (isa<PHINode>(LHS))
1202       if (Instruction *NV = FoldOpIntoPhi(I))
1203         return NV;
1204
1205     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
1206       if (Instruction *NV = FoldOpIntoSelect(I, SI))
1207         return NV;
1208   }
1209
1210   // -A + B  -->  B - A
1211   // -A + -B  -->  -(A + B)
1212   if (Value *LHSV = dyn_castFNegVal(LHS)) {
1213     Instruction *RI = BinaryOperator::CreateFSub(RHS, LHSV);
1214     RI->copyFastMathFlags(&I);
1215     return RI;
1216   }
1217
1218   // A + -B  -->  A - B
1219   if (!isa<Constant>(RHS))
1220     if (Value *V = dyn_castFNegVal(RHS)) {
1221       Instruction *RI = BinaryOperator::CreateFSub(LHS, V);
1222       RI->copyFastMathFlags(&I);
1223       return RI;
1224     }
1225
1226   // Check for (fadd double (sitofp x), y), see if we can merge this into an
1227   // integer add followed by a promotion.
1228   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
1229     // (fadd double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
1230     // ... if the constant fits in the integer value.  This is useful for things
1231     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
1232     // requires a constant pool load, and generally allows the add to be better
1233     // instcombined.
1234     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
1235       Constant *CI =
1236       ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
1237       if (LHSConv->hasOneUse() &&
1238           ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
1239           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
1240         // Insert the new integer add.
1241         Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
1242                                               CI, "addconv");
1243         return new SIToFPInst(NewAdd, I.getType());
1244       }
1245     }
1246
1247     // (fadd double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
1248     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
1249       // Only do this if x/y have the same type, if at last one of them has a
1250       // single use (so we don't increase the number of int->fp conversions),
1251       // and if the integer add will not overflow.
1252       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
1253           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
1254           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
1255                                    RHSConv->getOperand(0))) {
1256         // Insert the new integer add.
1257         Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
1258                                               RHSConv->getOperand(0),"addconv");
1259         return new SIToFPInst(NewAdd, I.getType());
1260       }
1261     }
1262   }
1263
1264   // select C, 0, B + select C, A, 0 -> select C, A, B
1265   {
1266     Value *A1, *B1, *C1, *A2, *B2, *C2;
1267     if (match(LHS, m_Select(m_Value(C1), m_Value(A1), m_Value(B1))) &&
1268         match(RHS, m_Select(m_Value(C2), m_Value(A2), m_Value(B2)))) {
1269       if (C1 == C2) {
1270         Constant *Z1=0, *Z2=0;
1271         Value *A, *B, *C=C1;
1272         if (match(A1, m_AnyZero()) && match(B2, m_AnyZero())) {
1273             Z1 = dyn_cast<Constant>(A1); A = A2;
1274             Z2 = dyn_cast<Constant>(B2); B = B1;
1275         } else if (match(B1, m_AnyZero()) && match(A2, m_AnyZero())) {
1276             Z1 = dyn_cast<Constant>(B1); B = B2;
1277             Z2 = dyn_cast<Constant>(A2); A = A1; 
1278         }
1279         
1280         if (Z1 && Z2 && 
1281             (I.hasNoSignedZeros() || 
1282              (Z1->isNegativeZeroValue() && Z2->isNegativeZeroValue()))) {
1283           return SelectInst::Create(C, A, B);
1284         }
1285       }
1286     }
1287   }
1288
1289   if (I.hasUnsafeAlgebra()) {
1290     if (Value *V = FAddCombine(Builder).simplify(&I))
1291       return ReplaceInstUsesWith(I, V);
1292   }
1293
1294   return Changed ? &I : 0;
1295 }
1296
1297
1298 /// Optimize pointer differences into the same array into a size.  Consider:
1299 ///  &A[10] - &A[0]: we should compile this to "10".  LHS/RHS are the pointer
1300 /// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
1301 ///
1302 Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS,
1303                                                Type *Ty) {
1304   assert(DL && "Must have target data info for this");
1305
1306   // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
1307   // this.
1308   bool Swapped = false;
1309   GEPOperator *GEP1 = 0, *GEP2 = 0;
1310
1311   // For now we require one side to be the base pointer "A" or a constant
1312   // GEP derived from it.
1313   if (GEPOperator *LHSGEP = dyn_cast<GEPOperator>(LHS)) {
1314     // (gep X, ...) - X
1315     if (LHSGEP->getOperand(0) == RHS) {
1316       GEP1 = LHSGEP;
1317       Swapped = false;
1318     } else if (GEPOperator *RHSGEP = dyn_cast<GEPOperator>(RHS)) {
1319       // (gep X, ...) - (gep X, ...)
1320       if (LHSGEP->getOperand(0)->stripPointerCasts() ==
1321             RHSGEP->getOperand(0)->stripPointerCasts()) {
1322         GEP2 = RHSGEP;
1323         GEP1 = LHSGEP;
1324         Swapped = false;
1325       }
1326     }
1327   }
1328
1329   if (GEPOperator *RHSGEP = dyn_cast<GEPOperator>(RHS)) {
1330     // X - (gep X, ...)
1331     if (RHSGEP->getOperand(0) == LHS) {
1332       GEP1 = RHSGEP;
1333       Swapped = true;
1334     } else if (GEPOperator *LHSGEP = dyn_cast<GEPOperator>(LHS)) {
1335       // (gep X, ...) - (gep X, ...)
1336       if (RHSGEP->getOperand(0)->stripPointerCasts() ==
1337             LHSGEP->getOperand(0)->stripPointerCasts()) {
1338         GEP2 = LHSGEP;
1339         GEP1 = RHSGEP;
1340         Swapped = true;
1341       }
1342     }
1343   }
1344
1345   // Avoid duplicating the arithmetic if GEP2 has non-constant indices and
1346   // multiple users.
1347   if (GEP1 == 0 ||
1348       (GEP2 != 0 && !GEP2->hasAllConstantIndices() && !GEP2->hasOneUse()))
1349     return 0;
1350
1351   // Emit the offset of the GEP and an intptr_t.
1352   Value *Result = EmitGEPOffset(GEP1);
1353
1354   // If we had a constant expression GEP on the other side offsetting the
1355   // pointer, subtract it from the offset we have.
1356   if (GEP2) {
1357     Value *Offset = EmitGEPOffset(GEP2);
1358     Result = Builder->CreateSub(Result, Offset);
1359   }
1360
1361   // If we have p - gep(p, ...)  then we have to negate the result.
1362   if (Swapped)
1363     Result = Builder->CreateNeg(Result, "diff.neg");
1364
1365   return Builder->CreateIntCast(Result, Ty, true);
1366 }
1367
1368
1369 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
1370   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1371
1372   if (Value *V = SimplifySubInst(Op0, Op1, I.hasNoSignedWrap(),
1373                                  I.hasNoUnsignedWrap(), DL))
1374     return ReplaceInstUsesWith(I, V);
1375
1376   // (A*B)-(A*C) -> A*(B-C) etc
1377   if (Value *V = SimplifyUsingDistributiveLaws(I))
1378     return ReplaceInstUsesWith(I, V);
1379
1380   // If this is a 'B = x-(-A)', change to B = x+A.  This preserves NSW/NUW.
1381   if (Value *V = dyn_castNegVal(Op1)) {
1382     BinaryOperator *Res = BinaryOperator::CreateAdd(Op0, V);
1383     Res->setHasNoSignedWrap(I.hasNoSignedWrap());
1384     Res->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
1385     return Res;
1386   }
1387
1388   if (I.getType()->isIntegerTy(1))
1389     return BinaryOperator::CreateXor(Op0, Op1);
1390
1391   // Replace (-1 - A) with (~A).
1392   if (match(Op0, m_AllOnes()))
1393     return BinaryOperator::CreateNot(Op1);
1394
1395   if (Constant *C = dyn_cast<Constant>(Op0)) {
1396     // C - ~X == X + (1+C)
1397     Value *X = 0;
1398     if (match(Op1, m_Not(m_Value(X))))
1399       return BinaryOperator::CreateAdd(X, AddOne(C));
1400
1401     // Try to fold constant sub into select arguments.
1402     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1403       if (Instruction *R = FoldOpIntoSelect(I, SI))
1404         return R;
1405
1406     // C-(X+C2) --> (C-C2)-X
1407     Constant *C2;
1408     if (match(Op1, m_Add(m_Value(X), m_Constant(C2))))
1409       return BinaryOperator::CreateSub(ConstantExpr::getSub(C, C2), X);
1410
1411     if (SimplifyDemandedInstructionBits(I))
1412       return &I;
1413
1414     // Fold (sub 0, (zext bool to B)) --> (sext bool to B)
1415     if (C->isNullValue() && match(Op1, m_ZExt(m_Value(X))))
1416       if (X->getType()->getScalarType()->isIntegerTy(1))
1417         return CastInst::CreateSExtOrBitCast(X, Op1->getType());
1418
1419     // Fold (sub 0, (sext bool to B)) --> (zext bool to B)
1420     if (C->isNullValue() && match(Op1, m_SExt(m_Value(X))))
1421       if (X->getType()->getScalarType()->isIntegerTy(1))
1422         return CastInst::CreateZExtOrBitCast(X, Op1->getType());
1423   }
1424
1425   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1426     // -(X >>u 31) -> (X >>s 31)
1427     // -(X >>s 31) -> (X >>u 31)
1428     if (C->isZero()) {
1429       Value *X; ConstantInt *CI;
1430       if (match(Op1, m_LShr(m_Value(X), m_ConstantInt(CI))) &&
1431           // Verify we are shifting out everything but the sign bit.
1432           CI->getValue() == I.getType()->getPrimitiveSizeInBits()-1)
1433         return BinaryOperator::CreateAShr(X, CI);
1434
1435       if (match(Op1, m_AShr(m_Value(X), m_ConstantInt(CI))) &&
1436           // Verify we are shifting out everything but the sign bit.
1437           CI->getValue() == I.getType()->getPrimitiveSizeInBits()-1)
1438         return BinaryOperator::CreateLShr(X, CI);
1439     }
1440   }
1441
1442
1443   { Value *Y;
1444     // X-(X+Y) == -Y    X-(Y+X) == -Y
1445     if (match(Op1, m_Add(m_Specific(Op0), m_Value(Y))) ||
1446         match(Op1, m_Add(m_Value(Y), m_Specific(Op0))))
1447       return BinaryOperator::CreateNeg(Y);
1448
1449     // (X-Y)-X == -Y
1450     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(Y))))
1451       return BinaryOperator::CreateNeg(Y);
1452   }
1453
1454   if (Op1->hasOneUse()) {
1455     Value *X = 0, *Y = 0, *Z = 0;
1456     Constant *C = 0;
1457     Constant *CI = 0;
1458
1459     // (X - (Y - Z))  -->  (X + (Z - Y)).
1460     if (match(Op1, m_Sub(m_Value(Y), m_Value(Z))))
1461       return BinaryOperator::CreateAdd(Op0,
1462                                       Builder->CreateSub(Z, Y, Op1->getName()));
1463
1464     // (X - (X & Y))   -->   (X & ~Y)
1465     //
1466     if (match(Op1, m_And(m_Value(Y), m_Specific(Op0))) ||
1467         match(Op1, m_And(m_Specific(Op0), m_Value(Y))))
1468       return BinaryOperator::CreateAnd(Op0,
1469                                   Builder->CreateNot(Y, Y->getName() + ".not"));
1470
1471     // 0 - (X sdiv C)  -> (X sdiv -C)
1472     if (match(Op1, m_SDiv(m_Value(X), m_Constant(C))) &&
1473         match(Op0, m_Zero()))
1474       return BinaryOperator::CreateSDiv(X, ConstantExpr::getNeg(C));
1475
1476     // 0 - (X << Y)  -> (-X << Y)   when X is freely negatable.
1477     if (match(Op1, m_Shl(m_Value(X), m_Value(Y))) && match(Op0, m_Zero()))
1478       if (Value *XNeg = dyn_castNegVal(X))
1479         return BinaryOperator::CreateShl(XNeg, Y);
1480
1481     // X - X*C --> X * (1-C)
1482     if (match(Op1, m_Mul(m_Specific(Op0), m_Constant(CI)))) {
1483       Constant *CP1 = ConstantExpr::getSub(ConstantInt::get(I.getType(),1), CI);
1484       return BinaryOperator::CreateMul(Op0, CP1);
1485     }
1486
1487     // X - X<<C --> X * (1-(1<<C))
1488     if (match(Op1, m_Shl(m_Specific(Op0), m_Constant(CI)))) {
1489       Constant *One = ConstantInt::get(I.getType(), 1);
1490       C = ConstantExpr::getSub(One, ConstantExpr::getShl(One, CI));
1491       return BinaryOperator::CreateMul(Op0, C);
1492     }
1493
1494     // X - A*-B -> X + A*B
1495     // X - -A*B -> X + A*B
1496     Value *A, *B;
1497     if (match(Op1, m_Mul(m_Value(A), m_Neg(m_Value(B)))) ||
1498         match(Op1, m_Mul(m_Neg(m_Value(A)), m_Value(B))))
1499       return BinaryOperator::CreateAdd(Op0, Builder->CreateMul(A, B));
1500
1501     // X - A*CI -> X + A*-CI
1502     // X - CI*A -> X + A*-CI
1503     if (match(Op1, m_Mul(m_Value(A), m_Constant(CI))) ||
1504         match(Op1, m_Mul(m_Constant(CI), m_Value(A)))) {
1505       Value *NewMul = Builder->CreateMul(A, ConstantExpr::getNeg(CI));
1506       return BinaryOperator::CreateAdd(Op0, NewMul);
1507     }
1508   }
1509
1510   Constant *C1;
1511   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
1512     if (X == Op1)  // X*C - X --> X * (C-1)
1513       return BinaryOperator::CreateMul(Op1, SubOne(C1));
1514
1515     Constant *C2;   // X*C1 - X*C2 -> X * (C1-C2)
1516     if (X == dyn_castFoldableMul(Op1, C2))
1517       return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
1518   }
1519
1520   // Optimize pointer differences into the same array into a size.  Consider:
1521   //  &A[10] - &A[0]: we should compile this to "10".
1522   if (DL) {
1523     Value *LHSOp, *RHSOp;
1524     if (match(Op0, m_PtrToInt(m_Value(LHSOp))) &&
1525         match(Op1, m_PtrToInt(m_Value(RHSOp))))
1526       if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
1527         return ReplaceInstUsesWith(I, Res);
1528
1529     // trunc(p)-trunc(q) -> trunc(p-q)
1530     if (match(Op0, m_Trunc(m_PtrToInt(m_Value(LHSOp)))) &&
1531         match(Op1, m_Trunc(m_PtrToInt(m_Value(RHSOp)))))
1532       if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
1533         return ReplaceInstUsesWith(I, Res);
1534   }
1535
1536   return 0;
1537 }
1538
1539 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
1540   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1541
1542   if (Value *V = SimplifyFSubInst(Op0, Op1, I.getFastMathFlags(), DL))
1543     return ReplaceInstUsesWith(I, V);
1544
1545   if (isa<Constant>(Op0))
1546     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1547       if (Instruction *NV = FoldOpIntoSelect(I, SI))
1548         return NV;
1549
1550   // If this is a 'B = x-(-A)', change to B = x+A, potentially looking
1551   // through FP extensions/truncations along the way.
1552   if (Value *V = dyn_castFNegVal(Op1)) {
1553     Instruction *NewI = BinaryOperator::CreateFAdd(Op0, V);
1554     NewI->copyFastMathFlags(&I);
1555     return NewI;
1556   }
1557   if (FPTruncInst *FPTI = dyn_cast<FPTruncInst>(Op1)) {
1558     if (Value *V = dyn_castFNegVal(FPTI->getOperand(0))) {
1559       Value *NewTrunc = Builder->CreateFPTrunc(V, I.getType());
1560       Instruction *NewI = BinaryOperator::CreateFAdd(Op0, NewTrunc);
1561       NewI->copyFastMathFlags(&I);
1562       return NewI;
1563     }
1564   } else if (FPExtInst *FPEI = dyn_cast<FPExtInst>(Op1)) {
1565     if (Value *V = dyn_castFNegVal(FPEI->getOperand(0))) {
1566       Value *NewExt = Builder->CreateFPExt(V, I.getType());
1567       Instruction *NewI = BinaryOperator::CreateFAdd(Op0, NewExt);
1568       NewI->copyFastMathFlags(&I);
1569       return NewI;
1570     }
1571   }
1572
1573   if (I.hasUnsafeAlgebra()) {
1574     if (Value *V = FAddCombine(Builder).simplify(&I))
1575       return ReplaceInstUsesWith(I, V);
1576   }
1577
1578   return 0;
1579 }