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