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