1//===- InstCombineAddSub.cpp ------------------------------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the visit functions for add, fadd, sub, and fsub.
10//
11//===----------------------------------------------------------------------===//
12
13#include "InstCombineInternal.h"
14#include "llvm/ADT/APFloat.h"
15#include "llvm/ADT/APInt.h"
16#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/SmallVector.h"
18#include "llvm/Analysis/InstructionSimplify.h"
19#include "llvm/Analysis/ValueTracking.h"
20#include "llvm/IR/Constant.h"
21#include "llvm/IR/Constants.h"
22#include "llvm/IR/InstrTypes.h"
23#include "llvm/IR/Instruction.h"
24#include "llvm/IR/Instructions.h"
25#include "llvm/IR/Operator.h"
26#include "llvm/IR/PatternMatch.h"
27#include "llvm/IR/Type.h"
28#include "llvm/IR/Value.h"
29#include "llvm/Support/AlignOf.h"
30#include "llvm/Support/Casting.h"
31#include "llvm/Support/KnownBits.h"
32#include "llvm/Transforms/InstCombine/InstCombiner.h"
33#include <cassert>
34#include <utility>
35
36using namespace llvm;
37using namespace PatternMatch;
38
39#define DEBUG_TYPE "instcombine"
40
41namespace {
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() { return reinterpret_cast<APFloat *>(&FpValBuf); }
86
87    const APFloat *getFpValPtr() const {
88      return reinterpret_cast<const APFloat *>(&FpValBuf);
89    }
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
123    AlignedCharArrayUnion<APFloat> FpValBuf;
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    /// Convert given addend to a Value
190    Value *createAddendVal(const FAddend &A, bool& NeedNeg);
191
192    /// Return the number of instructions needed to emit the N-ary addition.
193    unsigned calcInstrNumber(const AddendVect& Vect);
194
195    Value *createFSub(Value *Opnd0, Value *Opnd1);
196    Value *createFAdd(Value *Opnd0, Value *Opnd1);
197    Value *createFMul(Value *Opnd0, Value *Opnd1);
198    Value *createFNeg(Value *V);
199    Value *createNaryFAdd(const AddendVect& Opnds, unsigned InstrQuota);
200    void createInstPostProc(Instruction *NewInst, bool NoNumber = false);
201
202     // Debugging stuff are clustered here.
203    #ifndef NDEBUG
204      unsigned CreateInstrNum;
205      void initCreateInstNum() { CreateInstrNum = 0; }
206      void incCreateInstNum() { CreateInstrNum++; }
207    #else
208      void initCreateInstNum() {}
209      void incCreateInstNum() {}
210    #endif
211
212    InstCombiner::BuilderTy &Builder;
213    Instruction *Instr = nullptr;
214  };
215
216} // end anonymous namespace
217
218//===----------------------------------------------------------------------===//
219//
220// Implementation of
221//    {FAddendCoef, FAddend, FAddition, FAddCombine}.
222//
223//===----------------------------------------------------------------------===//
224FAddendCoef::~FAddendCoef() {
225  if (BufHasFpVal)
226    getFpValPtr()->~APFloat();
227}
228
229void FAddendCoef::set(const APFloat& C) {
230  APFloat *P = getFpValPtr();
231
232  if (isInt()) {
233    // As the buffer is meanless byte stream, we cannot call
234    // APFloat::operator=().
235    new(P) APFloat(C);
236  } else
237    *P = C;
238
239  IsFp = BufHasFpVal = true;
240}
241
242void FAddendCoef::convertToFpType(const fltSemantics &Sem) {
243  if (!isInt())
244    return;
245
246  APFloat *P = getFpValPtr();
247  if (IntVal > 0)
248    new(P) APFloat(Sem, IntVal);
249  else {
250    new(P) APFloat(Sem, 0 - IntVal);
251    P->changeSign();
252  }
253  IsFp = BufHasFpVal = true;
254}
255
256APFloat FAddendCoef::createAPFloatFromInt(const fltSemantics &Sem, int Val) {
257  if (Val >= 0)
258    return APFloat(Sem, Val);
259
260  APFloat T(Sem, 0 - Val);
261  T.changeSign();
262
263  return T;
264}
265
266void FAddendCoef::operator=(const FAddendCoef &That) {
267  if (That.isInt())
268    set(That.IntVal);
269  else
270    set(That.getFpVal());
271}
272
273void FAddendCoef::operator+=(const FAddendCoef &That) {
274  RoundingMode RndMode = RoundingMode::NearestTiesToEven;
275  if (isInt() == That.isInt()) {
276    if (isInt())
277      IntVal += That.IntVal;
278    else
279      getFpVal().add(That.getFpVal(), RndMode);
280    return;
281  }
282
283  if (isInt()) {
284    const APFloat &T = That.getFpVal();
285    convertToFpType(T.getSemantics());
286    getFpVal().add(T, RndMode);
287    return;
288  }
289
290  APFloat &T = getFpVal();
291  T.add(createAPFloatFromInt(T.getSemantics(), That.IntVal), RndMode);
292}
293
294void FAddendCoef::operator*=(const FAddendCoef &That) {
295  if (That.isOne())
296    return;
297
298  if (That.isMinusOne()) {
299    negate();
300    return;
301  }
302
303  if (isInt() && That.isInt()) {
304    int Res = IntVal * (int)That.IntVal;
305    assert(!insaneIntVal(Res) && "Insane int value");
306    IntVal = Res;
307    return;
308  }
309
310  const fltSemantics &Semantic =
311    isInt() ? That.getFpVal().getSemantics() : getFpVal().getSemantics();
312
313  if (isInt())
314    convertToFpType(Semantic);
315  APFloat &F0 = getFpVal();
316
317  if (That.isInt())
318    F0.multiply(createAPFloatFromInt(Semantic, That.IntVal),
319                APFloat::rmNearestTiesToEven);
320  else
321    F0.multiply(That.getFpVal(), APFloat::rmNearestTiesToEven);
322}
323
324void FAddendCoef::negate() {
325  if (isInt())
326    IntVal = 0 - IntVal;
327  else
328    getFpVal().changeSign();
329}
330
331Value *FAddendCoef::getValue(Type *Ty) const {
332  return isInt() ?
333    ConstantFP::get(Ty, float(IntVal)) :
334    ConstantFP::get(Ty->getContext(), getFpVal());
335}
336
337// The definition of <Val>     Addends
338// =========================================
339//  A + B                     <1, A>, <1,B>
340//  A - B                     <1, A>, <1,B>
341//  0 - B                     <-1, B>
342//  C * A,                    <C, A>
343//  A + C                     <1, A> <C, NULL>
344//  0 +/- 0                   <0, NULL> (corner case)
345//
346// Legend: A and B are not constant, C is constant
347unsigned FAddend::drillValueDownOneStep
348  (Value *Val, FAddend &Addend0, FAddend &Addend1) {
349  Instruction *I = nullptr;
350  if (!Val || !(I = dyn_cast<Instruction>(Val)))
351    return 0;
352
353  unsigned Opcode = I->getOpcode();
354
355  if (Opcode == Instruction::FAdd || Opcode == Instruction::FSub) {
356    ConstantFP *C0, *C1;
357    Value *Opnd0 = I->getOperand(0);
358    Value *Opnd1 = I->getOperand(1);
359    if ((C0 = dyn_cast<ConstantFP>(Opnd0)) && C0->isZero())
360      Opnd0 = nullptr;
361
362    if ((C1 = dyn_cast<ConstantFP>(Opnd1)) && C1->isZero())
363      Opnd1 = nullptr;
364
365    if (Opnd0) {
366      if (!C0)
367        Addend0.set(1, Opnd0);
368      else
369        Addend0.set(C0, nullptr);
370    }
371
372    if (Opnd1) {
373      FAddend &Addend = Opnd0 ? Addend1 : Addend0;
374      if (!C1)
375        Addend.set(1, Opnd1);
376      else
377        Addend.set(C1, nullptr);
378      if (Opcode == Instruction::FSub)
379        Addend.negate();
380    }
381
382    if (Opnd0 || Opnd1)
383      return Opnd0 && Opnd1 ? 2 : 1;
384
385    // Both operands are zero. Weird!
386    Addend0.set(APFloat(C0->getValueAPF().getSemantics()), nullptr);
387    return 1;
388  }
389
390  if (I->getOpcode() == Instruction::FMul) {
391    Value *V0 = I->getOperand(0);
392    Value *V1 = I->getOperand(1);
393    if (ConstantFP *C = dyn_cast<ConstantFP>(V0)) {
394      Addend0.set(C, V1);
395      return 1;
396    }
397
398    if (ConstantFP *C = dyn_cast<ConstantFP>(V1)) {
399      Addend0.set(C, V0);
400      return 1;
401    }
402  }
403
404  return 0;
405}
406
407// Try to break *this* addend into two addends. e.g. Suppose this addend is
408// <2.3, V>, and V = X + Y, by calling this function, we obtain two addends,
409// i.e. <2.3, X> and <2.3, Y>.
410unsigned FAddend::drillAddendDownOneStep
411  (FAddend &Addend0, FAddend &Addend1) const {
412  if (isConstant())
413    return 0;
414
415  unsigned BreakNum = FAddend::drillValueDownOneStep(Val, Addend0, Addend1);
416  if (!BreakNum || Coeff.isOne())
417    return BreakNum;
418
419  Addend0.Scale(Coeff);
420
421  if (BreakNum == 2)
422    Addend1.Scale(Coeff);
423
424  return BreakNum;
425}
426
427Value *FAddCombine::simplify(Instruction *I) {
428  assert(I->hasAllowReassoc() && I->hasNoSignedZeros() &&
429         "Expected 'reassoc'+'nsz' instruction");
430
431  // Currently we are not able to handle vector type.
432  if (I->getType()->isVectorTy())
433    return nullptr;
434
435  assert((I->getOpcode() == Instruction::FAdd ||
436          I->getOpcode() == Instruction::FSub) && "Expect add/sub");
437
438  // Save the instruction before calling other member-functions.
439  Instr = I;
440
441  FAddend Opnd0, Opnd1, Opnd0_0, Opnd0_1, Opnd1_0, Opnd1_1;
442
443  unsigned OpndNum = FAddend::drillValueDownOneStep(I, Opnd0, Opnd1);
444
445  // Step 1: Expand the 1st addend into Opnd0_0 and Opnd0_1.
446  unsigned Opnd0_ExpNum = 0;
447  unsigned Opnd1_ExpNum = 0;
448
449  if (!Opnd0.isConstant())
450    Opnd0_ExpNum = Opnd0.drillAddendDownOneStep(Opnd0_0, Opnd0_1);
451
452  // Step 2: Expand the 2nd addend into Opnd1_0 and Opnd1_1.
453  if (OpndNum == 2 && !Opnd1.isConstant())
454    Opnd1_ExpNum = Opnd1.drillAddendDownOneStep(Opnd1_0, Opnd1_1);
455
456  // Step 3: Try to optimize Opnd0_0 + Opnd0_1 + Opnd1_0 + Opnd1_1
457  if (Opnd0_ExpNum && Opnd1_ExpNum) {
458    AddendVect AllOpnds;
459    AllOpnds.push_back(&Opnd0_0);
460    AllOpnds.push_back(&Opnd1_0);
461    if (Opnd0_ExpNum == 2)
462      AllOpnds.push_back(&Opnd0_1);
463    if (Opnd1_ExpNum == 2)
464      AllOpnds.push_back(&Opnd1_1);
465
466    // Compute instruction quota. We should save at least one instruction.
467    unsigned InstQuota = 0;
468
469    Value *V0 = I->getOperand(0);
470    Value *V1 = I->getOperand(1);
471    InstQuota = ((!isa<Constant>(V0) && V0->hasOneUse()) &&
472                 (!isa<Constant>(V1) && V1->hasOneUse())) ? 2 : 1;
473
474    if (Value *R = simplifyFAdd(AllOpnds, InstQuota))
475      return R;
476  }
477
478  if (OpndNum != 2) {
479    // The input instruction is : "I=0.0 +/- V". If the "V" were able to be
480    // splitted into two addends, say "V = X - Y", the instruction would have
481    // been optimized into "I = Y - X" in the previous steps.
482    //
483    const FAddendCoef &CE = Opnd0.getCoef();
484    return CE.isOne() ? Opnd0.getSymVal() : nullptr;
485  }
486
487  // step 4: Try to optimize Opnd0 + Opnd1_0 [+ Opnd1_1]
488  if (Opnd1_ExpNum) {
489    AddendVect AllOpnds;
490    AllOpnds.push_back(&Opnd0);
491    AllOpnds.push_back(&Opnd1_0);
492    if (Opnd1_ExpNum == 2)
493      AllOpnds.push_back(&Opnd1_1);
494
495    if (Value *R = simplifyFAdd(AllOpnds, 1))
496      return R;
497  }
498
499  // step 5: Try to optimize Opnd1 + Opnd0_0 [+ Opnd0_1]
500  if (Opnd0_ExpNum) {
501    AddendVect AllOpnds;
502    AllOpnds.push_back(&Opnd1);
503    AllOpnds.push_back(&Opnd0_0);
504    if (Opnd0_ExpNum == 2)
505      AllOpnds.push_back(&Opnd0_1);
506
507    if (Value *R = simplifyFAdd(AllOpnds, 1))
508      return R;
509  }
510
511  return nullptr;
512}
513
514Value *FAddCombine::simplifyFAdd(AddendVect& Addends, unsigned InstrQuota) {
515  unsigned AddendNum = Addends.size();
516  assert(AddendNum <= 4 && "Too many addends");
517
518  // For saving intermediate results;
519  unsigned NextTmpIdx = 0;
520  FAddend TmpResult[3];
521
522  // Simplified addends are placed <SimpVect>.
523  AddendVect SimpVect;
524
525  // The outer loop works on one symbolic-value at a time. Suppose the input
526  // addends are : <a1, x>, <b1, y>, <a2, x>, <c1, z>, <b2, y>, ...
527  // The symbolic-values will be processed in this order: x, y, z.
528  for (unsigned SymIdx = 0; SymIdx < AddendNum; SymIdx++) {
529
530    const FAddend *ThisAddend = Addends[SymIdx];
531    if (!ThisAddend) {
532      // This addend was processed before.
533      continue;
534    }
535
536    Value *Val = ThisAddend->getSymVal();
537
538    // If the resulting expr has constant-addend, this constant-addend is
539    // desirable to reside at the top of the resulting expression tree. Placing
540    // constant close to super-expr(s) will potentially reveal some
541    // optimization opportunities in super-expr(s). Here we do not implement
542    // this logic intentionally and rely on SimplifyAssociativeOrCommutative
543    // call later.
544
545    unsigned StartIdx = SimpVect.size();
546    SimpVect.push_back(ThisAddend);
547
548    // The inner loop collects addends sharing same symbolic-value, and these
549    // addends will be later on folded into a single addend. Following above
550    // example, if the symbolic value "y" is being processed, the inner loop
551    // will collect two addends "<b1,y>" and "<b2,Y>". These two addends will
552    // be later on folded into "<b1+b2, y>".
553    for (unsigned SameSymIdx = SymIdx + 1;
554         SameSymIdx < AddendNum; SameSymIdx++) {
555      const FAddend *T = Addends[SameSymIdx];
556      if (T && T->getSymVal() == Val) {
557        // Set null such that next iteration of the outer loop will not process
558        // this addend again.
559        Addends[SameSymIdx] = nullptr;
560        SimpVect.push_back(T);
561      }
562    }
563
564    // If multiple addends share same symbolic value, fold them together.
565    if (StartIdx + 1 != SimpVect.size()) {
566      FAddend &R = TmpResult[NextTmpIdx ++];
567      R = *SimpVect[StartIdx];
568      for (unsigned Idx = StartIdx + 1; Idx < SimpVect.size(); Idx++)
569        R += *SimpVect[Idx];
570
571      // Pop all addends being folded and push the resulting folded addend.
572      SimpVect.resize(StartIdx);
573      if (!R.isZero()) {
574        SimpVect.push_back(&R);
575      }
576    }
577  }
578
579  assert((NextTmpIdx <= std::size(TmpResult) + 1) && "out-of-bound access");
580
581  Value *Result;
582  if (!SimpVect.empty())
583    Result = createNaryFAdd(SimpVect, InstrQuota);
584  else {
585    // The addition is folded to 0.0.
586    Result = ConstantFP::get(Instr->getType(), 0.0);
587  }
588
589  return Result;
590}
591
592Value *FAddCombine::createNaryFAdd
593  (const AddendVect &Opnds, unsigned InstrQuota) {
594  assert(!Opnds.empty() && "Expect at least one addend");
595
596  // Step 1: Check if the # of instructions needed exceeds the quota.
597
598  unsigned InstrNeeded = calcInstrNumber(Opnds);
599  if (InstrNeeded > InstrQuota)
600    return nullptr;
601
602  initCreateInstNum();
603
604  // step 2: Emit the N-ary addition.
605  // Note that at most three instructions are involved in Fadd-InstCombine: the
606  // addition in question, and at most two neighboring instructions.
607  // The resulting optimized addition should have at least one less instruction
608  // than the original addition expression tree. This implies that the resulting
609  // N-ary addition has at most two instructions, and we don't need to worry
610  // about tree-height when constructing the N-ary addition.
611
612  Value *LastVal = nullptr;
613  bool LastValNeedNeg = false;
614
615  // Iterate the addends, creating fadd/fsub using adjacent two addends.
616  for (const FAddend *Opnd : Opnds) {
617    bool NeedNeg;
618    Value *V = createAddendVal(*Opnd, NeedNeg);
619    if (!LastVal) {
620      LastVal = V;
621      LastValNeedNeg = NeedNeg;
622      continue;
623    }
624
625    if (LastValNeedNeg == NeedNeg) {
626      LastVal = createFAdd(LastVal, V);
627      continue;
628    }
629
630    if (LastValNeedNeg)
631      LastVal = createFSub(V, LastVal);
632    else
633      LastVal = createFSub(LastVal, V);
634
635    LastValNeedNeg = false;
636  }
637
638  if (LastValNeedNeg) {
639    LastVal = createFNeg(LastVal);
640  }
641
642#ifndef NDEBUG
643  assert(CreateInstrNum == InstrNeeded &&
644         "Inconsistent in instruction numbers");
645#endif
646
647  return LastVal;
648}
649
650Value *FAddCombine::createFSub(Value *Opnd0, Value *Opnd1) {
651  Value *V = Builder.CreateFSub(Opnd0, Opnd1);
652  if (Instruction *I = dyn_cast<Instruction>(V))
653    createInstPostProc(I);
654  return V;
655}
656
657Value *FAddCombine::createFNeg(Value *V) {
658  Value *NewV = Builder.CreateFNeg(V);
659  if (Instruction *I = dyn_cast<Instruction>(NewV))
660    createInstPostProc(I, true); // fneg's don't receive instruction numbers.
661  return NewV;
662}
663
664Value *FAddCombine::createFAdd(Value *Opnd0, Value *Opnd1) {
665  Value *V = Builder.CreateFAdd(Opnd0, Opnd1);
666  if (Instruction *I = dyn_cast<Instruction>(V))
667    createInstPostProc(I);
668  return V;
669}
670
671Value *FAddCombine::createFMul(Value *Opnd0, Value *Opnd1) {
672  Value *V = Builder.CreateFMul(Opnd0, Opnd1);
673  if (Instruction *I = dyn_cast<Instruction>(V))
674    createInstPostProc(I);
675  return V;
676}
677
678void FAddCombine::createInstPostProc(Instruction *NewInstr, bool NoNumber) {
679  NewInstr->setDebugLoc(Instr->getDebugLoc());
680
681  // Keep track of the number of instruction created.
682  if (!NoNumber)
683    incCreateInstNum();
684
685  // Propagate fast-math flags
686  NewInstr->setFastMathFlags(Instr->getFastMathFlags());
687}
688
689// Return the number of instruction needed to emit the N-ary addition.
690// NOTE: Keep this function in sync with createAddendVal().
691unsigned FAddCombine::calcInstrNumber(const AddendVect &Opnds) {
692  unsigned OpndNum = Opnds.size();
693  unsigned InstrNeeded = OpndNum - 1;
694
695  // Adjust the number of instructions needed to emit the N-ary add.
696  for (const FAddend *Opnd : Opnds) {
697    if (Opnd->isConstant())
698      continue;
699
700    // The constant check above is really for a few special constant
701    // coefficients.
702    if (isa<UndefValue>(Opnd->getSymVal()))
703      continue;
704
705    const FAddendCoef &CE = Opnd->getCoef();
706    // Let the addend be "c * x". If "c == +/-1", the value of the addend
707    // is immediately available; otherwise, it needs exactly one instruction
708    // to evaluate the value.
709    if (!CE.isMinusOne() && !CE.isOne())
710      InstrNeeded++;
711  }
712  return InstrNeeded;
713}
714
715// Input Addend        Value           NeedNeg(output)
716// ================================================================
717// Constant C          C               false
718// <+/-1, V>           V               coefficient is -1
719// <2/-2, V>          "fadd V, V"      coefficient is -2
720// <C, V>             "fmul V, C"      false
721//
722// NOTE: Keep this function in sync with FAddCombine::calcInstrNumber.
723Value *FAddCombine::createAddendVal(const FAddend &Opnd, bool &NeedNeg) {
724  const FAddendCoef &Coeff = Opnd.getCoef();
725
726  if (Opnd.isConstant()) {
727    NeedNeg = false;
728    return Coeff.getValue(Instr->getType());
729  }
730
731  Value *OpndVal = Opnd.getSymVal();
732
733  if (Coeff.isMinusOne() || Coeff.isOne()) {
734    NeedNeg = Coeff.isMinusOne();
735    return OpndVal;
736  }
737
738  if (Coeff.isTwo() || Coeff.isMinusTwo()) {
739    NeedNeg = Coeff.isMinusTwo();
740    return createFAdd(OpndVal, OpndVal);
741  }
742
743  NeedNeg = false;
744  return createFMul(OpndVal, Coeff.getValue(Instr->getType()));
745}
746
747// Checks if any operand is negative and we can convert add to sub.
748// This function checks for following negative patterns
749//   ADD(XOR(OR(Z, NOT(C)), C)), 1) == NEG(AND(Z, C))
750//   ADD(XOR(AND(Z, C), C), 1) == NEG(OR(Z, ~C))
751//   XOR(AND(Z, C), (C + 1)) == NEG(OR(Z, ~C)) if C is even
752static Value *checkForNegativeOperand(BinaryOperator &I,
753                                      InstCombiner::BuilderTy &Builder) {
754  Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
755
756  // This function creates 2 instructions to replace ADD, we need at least one
757  // of LHS or RHS to have one use to ensure benefit in transform.
758  if (!LHS->hasOneUse() && !RHS->hasOneUse())
759    return nullptr;
760
761  Value *X = nullptr, *Y = nullptr, *Z = nullptr;
762  const APInt *C1 = nullptr, *C2 = nullptr;
763
764  // if ONE is on other side, swap
765  if (match(RHS, m_Add(m_Value(X), m_One())))
766    std::swap(LHS, RHS);
767
768  if (match(LHS, m_Add(m_Value(X), m_One()))) {
769    // if XOR on other side, swap
770    if (match(RHS, m_Xor(m_Value(Y), m_APInt(C1))))
771      std::swap(X, RHS);
772
773    if (match(X, m_Xor(m_Value(Y), m_APInt(C1)))) {
774      // X = XOR(Y, C1), Y = OR(Z, C2), C2 = NOT(C1) ==> X == NOT(AND(Z, C1))
775      // ADD(ADD(X, 1), RHS) == ADD(X, ADD(RHS, 1)) == SUB(RHS, AND(Z, C1))
776      if (match(Y, m_Or(m_Value(Z), m_APInt(C2))) && (*C2 == ~(*C1))) {
777        Value *NewAnd = Builder.CreateAnd(Z, *C1);
778        return Builder.CreateSub(RHS, NewAnd, "sub");
779      } else if (match(Y, m_And(m_Value(Z), m_APInt(C2))) && (*C1 == *C2)) {
780        // X = XOR(Y, C1), Y = AND(Z, C2), C2 == C1 ==> X == NOT(OR(Z, ~C1))
781        // ADD(ADD(X, 1), RHS) == ADD(X, ADD(RHS, 1)) == SUB(RHS, OR(Z, ~C1))
782        Value *NewOr = Builder.CreateOr(Z, ~(*C1));
783        return Builder.CreateSub(RHS, NewOr, "sub");
784      }
785    }
786  }
787
788  // Restore LHS and RHS
789  LHS = I.getOperand(0);
790  RHS = I.getOperand(1);
791
792  // if XOR is on other side, swap
793  if (match(RHS, m_Xor(m_Value(Y), m_APInt(C1))))
794    std::swap(LHS, RHS);
795
796  // C2 is ODD
797  // LHS = XOR(Y, C1), Y = AND(Z, C2), C1 == (C2 + 1) => LHS == NEG(OR(Z, ~C2))
798  // ADD(LHS, RHS) == SUB(RHS, OR(Z, ~C2))
799  if (match(LHS, m_Xor(m_Value(Y), m_APInt(C1))))
800    if (C1->countr_zero() == 0)
801      if (match(Y, m_And(m_Value(Z), m_APInt(C2))) && *C1 == (*C2 + 1)) {
802        Value *NewOr = Builder.CreateOr(Z, ~(*C2));
803        return Builder.CreateSub(RHS, NewOr, "sub");
804      }
805  return nullptr;
806}
807
808/// Wrapping flags may allow combining constants separated by an extend.
809static Instruction *foldNoWrapAdd(BinaryOperator &Add,
810                                  InstCombiner::BuilderTy &Builder) {
811  Value *Op0 = Add.getOperand(0), *Op1 = Add.getOperand(1);
812  Type *Ty = Add.getType();
813  Constant *Op1C;
814  if (!match(Op1, m_Constant(Op1C)))
815    return nullptr;
816
817  // Try this match first because it results in an add in the narrow type.
818  // (zext (X +nuw C2)) + C1 --> zext (X + (C2 + trunc(C1)))
819  Value *X;
820  const APInt *C1, *C2;
821  if (match(Op1, m_APInt(C1)) &&
822      match(Op0, m_OneUse(m_ZExt(m_NUWAdd(m_Value(X), m_APInt(C2))))) &&
823      C1->isNegative() && C1->sge(-C2->sext(C1->getBitWidth()))) {
824    Constant *NewC =
825        ConstantInt::get(X->getType(), *C2 + C1->trunc(C2->getBitWidth()));
826    return new ZExtInst(Builder.CreateNUWAdd(X, NewC), Ty);
827  }
828
829  // More general combining of constants in the wide type.
830  // (sext (X +nsw NarrowC)) + C --> (sext X) + (sext(NarrowC) + C)
831  Constant *NarrowC;
832  if (match(Op0, m_OneUse(m_SExt(m_NSWAdd(m_Value(X), m_Constant(NarrowC)))))) {
833    Value *WideC = Builder.CreateSExt(NarrowC, Ty);
834    Value *NewC = Builder.CreateAdd(WideC, Op1C);
835    Value *WideX = Builder.CreateSExt(X, Ty);
836    return BinaryOperator::CreateAdd(WideX, NewC);
837  }
838  // (zext (X +nuw NarrowC)) + C --> (zext X) + (zext(NarrowC) + C)
839  if (match(Op0, m_OneUse(m_ZExt(m_NUWAdd(m_Value(X), m_Constant(NarrowC)))))) {
840    Value *WideC = Builder.CreateZExt(NarrowC, Ty);
841    Value *NewC = Builder.CreateAdd(WideC, Op1C);
842    Value *WideX = Builder.CreateZExt(X, Ty);
843    return BinaryOperator::CreateAdd(WideX, NewC);
844  }
845
846  return nullptr;
847}
848
849Instruction *InstCombinerImpl::foldAddWithConstant(BinaryOperator &Add) {
850  Value *Op0 = Add.getOperand(0), *Op1 = Add.getOperand(1);
851  Type *Ty = Add.getType();
852  Constant *Op1C;
853  if (!match(Op1, m_ImmConstant(Op1C)))
854    return nullptr;
855
856  if (Instruction *NV = foldBinOpIntoSelectOrPhi(Add))
857    return NV;
858
859  Value *X;
860  Constant *Op00C;
861
862  // add (sub C1, X), C2 --> sub (add C1, C2), X
863  if (match(Op0, m_Sub(m_Constant(Op00C), m_Value(X))))
864    return BinaryOperator::CreateSub(ConstantExpr::getAdd(Op00C, Op1C), X);
865
866  Value *Y;
867
868  // add (sub X, Y), -1 --> add (not Y), X
869  if (match(Op0, m_OneUse(m_Sub(m_Value(X), m_Value(Y)))) &&
870      match(Op1, m_AllOnes()))
871    return BinaryOperator::CreateAdd(Builder.CreateNot(Y), X);
872
873  // zext(bool) + C -> bool ? C + 1 : C
874  if (match(Op0, m_ZExt(m_Value(X))) &&
875      X->getType()->getScalarSizeInBits() == 1)
876    return SelectInst::Create(X, InstCombiner::AddOne(Op1C), Op1);
877  // sext(bool) + C -> bool ? C - 1 : C
878  if (match(Op0, m_SExt(m_Value(X))) &&
879      X->getType()->getScalarSizeInBits() == 1)
880    return SelectInst::Create(X, InstCombiner::SubOne(Op1C), Op1);
881
882  // ~X + C --> (C-1) - X
883  if (match(Op0, m_Not(m_Value(X)))) {
884    // ~X + C has NSW and (C-1) won't oveflow => (C-1)-X can have NSW
885    auto *COne = ConstantInt::get(Op1C->getType(), 1);
886    bool WillNotSOV = willNotOverflowSignedSub(Op1C, COne, Add);
887    BinaryOperator *Res =
888        BinaryOperator::CreateSub(ConstantExpr::getSub(Op1C, COne), X);
889    Res->setHasNoSignedWrap(Add.hasNoSignedWrap() && WillNotSOV);
890    return Res;
891  }
892
893  // (iN X s>> (N - 1)) + 1 --> zext (X > -1)
894  const APInt *C;
895  unsigned BitWidth = Ty->getScalarSizeInBits();
896  if (match(Op0, m_OneUse(m_AShr(m_Value(X),
897                                 m_SpecificIntAllowUndef(BitWidth - 1)))) &&
898      match(Op1, m_One()))
899    return new ZExtInst(Builder.CreateIsNotNeg(X, "isnotneg"), Ty);
900
901  if (!match(Op1, m_APInt(C)))
902    return nullptr;
903
904  // (X | Op01C) + Op1C --> X + (Op01C + Op1C) iff the `or` is actually an `add`
905  Constant *Op01C;
906  if (match(Op0, m_DisjointOr(m_Value(X), m_ImmConstant(Op01C))))
907    return BinaryOperator::CreateAdd(X, ConstantExpr::getAdd(Op01C, Op1C));
908
909  // (X | C2) + C --> (X | C2) ^ C2 iff (C2 == -C)
910  const APInt *C2;
911  if (match(Op0, m_Or(m_Value(), m_APInt(C2))) && *C2 == -*C)
912    return BinaryOperator::CreateXor(Op0, ConstantInt::get(Add.getType(), *C2));
913
914  if (C->isSignMask()) {
915    // If wrapping is not allowed, then the addition must set the sign bit:
916    // X + (signmask) --> X | signmask
917    if (Add.hasNoSignedWrap() || Add.hasNoUnsignedWrap())
918      return BinaryOperator::CreateOr(Op0, Op1);
919
920    // If wrapping is allowed, then the addition flips the sign bit of LHS:
921    // X + (signmask) --> X ^ signmask
922    return BinaryOperator::CreateXor(Op0, Op1);
923  }
924
925  // Is this add the last step in a convoluted sext?
926  // add(zext(xor i16 X, -32768), -32768) --> sext X
927  if (match(Op0, m_ZExt(m_Xor(m_Value(X), m_APInt(C2)))) &&
928      C2->isMinSignedValue() && C2->sext(Ty->getScalarSizeInBits()) == *C)
929    return CastInst::Create(Instruction::SExt, X, Ty);
930
931  if (match(Op0, m_Xor(m_Value(X), m_APInt(C2)))) {
932    // (X ^ signmask) + C --> (X + (signmask ^ C))
933    if (C2->isSignMask())
934      return BinaryOperator::CreateAdd(X, ConstantInt::get(Ty, *C2 ^ *C));
935
936    // If X has no high-bits set above an xor mask:
937    // add (xor X, LowMaskC), C --> sub (LowMaskC + C), X
938    if (C2->isMask()) {
939      KnownBits LHSKnown = computeKnownBits(X, 0, &Add);
940      if ((*C2 | LHSKnown.Zero).isAllOnes())
941        return BinaryOperator::CreateSub(ConstantInt::get(Ty, *C2 + *C), X);
942    }
943
944    // Look for a math+logic pattern that corresponds to sext-in-register of a
945    // value with cleared high bits. Convert that into a pair of shifts:
946    // add (xor X, 0x80), 0xF..F80 --> (X << ShAmtC) >>s ShAmtC
947    // add (xor X, 0xF..F80), 0x80 --> (X << ShAmtC) >>s ShAmtC
948    if (Op0->hasOneUse() && *C2 == -(*C)) {
949      unsigned BitWidth = Ty->getScalarSizeInBits();
950      unsigned ShAmt = 0;
951      if (C->isPowerOf2())
952        ShAmt = BitWidth - C->logBase2() - 1;
953      else if (C2->isPowerOf2())
954        ShAmt = BitWidth - C2->logBase2() - 1;
955      if (ShAmt && MaskedValueIsZero(X, APInt::getHighBitsSet(BitWidth, ShAmt),
956                                     0, &Add)) {
957        Constant *ShAmtC = ConstantInt::get(Ty, ShAmt);
958        Value *NewShl = Builder.CreateShl(X, ShAmtC, "sext");
959        return BinaryOperator::CreateAShr(NewShl, ShAmtC);
960      }
961    }
962  }
963
964  if (C->isOne() && Op0->hasOneUse()) {
965    // add (sext i1 X), 1 --> zext (not X)
966    // TODO: The smallest IR representation is (select X, 0, 1), and that would
967    // not require the one-use check. But we need to remove a transform in
968    // visitSelect and make sure that IR value tracking for select is equal or
969    // better than for these ops.
970    if (match(Op0, m_SExt(m_Value(X))) &&
971        X->getType()->getScalarSizeInBits() == 1)
972      return new ZExtInst(Builder.CreateNot(X), Ty);
973
974    // Shifts and add used to flip and mask off the low bit:
975    // add (ashr (shl i32 X, 31), 31), 1 --> and (not X), 1
976    const APInt *C3;
977    if (match(Op0, m_AShr(m_Shl(m_Value(X), m_APInt(C2)), m_APInt(C3))) &&
978        C2 == C3 && *C2 == Ty->getScalarSizeInBits() - 1) {
979      Value *NotX = Builder.CreateNot(X);
980      return BinaryOperator::CreateAnd(NotX, ConstantInt::get(Ty, 1));
981    }
982  }
983
984  // Fold (add (zext (add X, -1)), 1) -> (zext X) if X is non-zero.
985  // TODO: There's a general form for any constant on the outer add.
986  if (C->isOne()) {
987    if (match(Op0, m_ZExt(m_Add(m_Value(X), m_AllOnes())))) {
988      const SimplifyQuery Q = SQ.getWithInstruction(&Add);
989      if (llvm::isKnownNonZero(X, DL, 0, Q.AC, Q.CxtI, Q.DT))
990        return new ZExtInst(X, Ty);
991    }
992  }
993
994  return nullptr;
995}
996
997// match variations of a^2 + 2*a*b + b^2
998//
999// to reuse the code between the FP and Int versions, the instruction OpCodes
1000//  and constant types have been turned into template parameters.
1001//
1002// Mul2Rhs: The constant to perform the multiplicative equivalent of X*2 with;
1003//  should be `m_SpecificFP(2.0)` for FP and `m_SpecificInt(1)` for Int
1004//  (we're matching `X<<1` instead of `X*2` for Int)
1005template <bool FP, typename Mul2Rhs>
1006static bool matchesSquareSum(BinaryOperator &I, Mul2Rhs M2Rhs, Value *&A,
1007                             Value *&B) {
1008  constexpr unsigned MulOp = FP ? Instruction::FMul : Instruction::Mul;
1009  constexpr unsigned AddOp = FP ? Instruction::FAdd : Instruction::Add;
1010  constexpr unsigned Mul2Op = FP ? Instruction::FMul : Instruction::Shl;
1011
1012  // (a * a) + (((a * 2) + b) * b)
1013  if (match(&I, m_c_BinOp(
1014                    AddOp, m_OneUse(m_BinOp(MulOp, m_Value(A), m_Deferred(A))),
1015                    m_OneUse(m_BinOp(
1016                        MulOp,
1017                        m_c_BinOp(AddOp, m_BinOp(Mul2Op, m_Deferred(A), M2Rhs),
1018                                  m_Value(B)),
1019                        m_Deferred(B))))))
1020    return true;
1021
1022  // ((a * b) * 2)  or ((a * 2) * b)
1023  // +
1024  // (a * a + b * b) or (b * b + a * a)
1025  return match(
1026      &I,
1027      m_c_BinOp(AddOp,
1028                m_CombineOr(
1029                    m_OneUse(m_BinOp(
1030                        Mul2Op, m_BinOp(MulOp, m_Value(A), m_Value(B)), M2Rhs)),
1031                    m_OneUse(m_BinOp(MulOp, m_BinOp(Mul2Op, m_Value(A), M2Rhs),
1032                                     m_Value(B)))),
1033                m_OneUse(m_c_BinOp(
1034                    AddOp, m_BinOp(MulOp, m_Deferred(A), m_Deferred(A)),
1035                    m_BinOp(MulOp, m_Deferred(B), m_Deferred(B))))));
1036}
1037
1038// Fold integer variations of a^2 + 2*a*b + b^2 -> (a + b)^2
1039Instruction *InstCombinerImpl::foldSquareSumInt(BinaryOperator &I) {
1040  Value *A, *B;
1041  if (matchesSquareSum</*FP*/ false>(I, m_SpecificInt(1), A, B)) {
1042    Value *AB = Builder.CreateAdd(A, B);
1043    return BinaryOperator::CreateMul(AB, AB);
1044  }
1045  return nullptr;
1046}
1047
1048// Fold floating point variations of a^2 + 2*a*b + b^2 -> (a + b)^2
1049// Requires `nsz` and `reassoc`.
1050Instruction *InstCombinerImpl::foldSquareSumFP(BinaryOperator &I) {
1051  assert(I.hasAllowReassoc() && I.hasNoSignedZeros() && "Assumption mismatch");
1052  Value *A, *B;
1053  if (matchesSquareSum</*FP*/ true>(I, m_SpecificFP(2.0), A, B)) {
1054    Value *AB = Builder.CreateFAddFMF(A, B, &I);
1055    return BinaryOperator::CreateFMulFMF(AB, AB, &I);
1056  }
1057  return nullptr;
1058}
1059
1060// Matches multiplication expression Op * C where C is a constant. Returns the
1061// constant value in C and the other operand in Op. Returns true if such a
1062// match is found.
1063static bool MatchMul(Value *E, Value *&Op, APInt &C) {
1064  const APInt *AI;
1065  if (match(E, m_Mul(m_Value(Op), m_APInt(AI)))) {
1066    C = *AI;
1067    return true;
1068  }
1069  if (match(E, m_Shl(m_Value(Op), m_APInt(AI)))) {
1070    C = APInt(AI->getBitWidth(), 1);
1071    C <<= *AI;
1072    return true;
1073  }
1074  return false;
1075}
1076
1077// Matches remainder expression Op % C where C is a constant. Returns the
1078// constant value in C and the other operand in Op. Returns the signedness of
1079// the remainder operation in IsSigned. Returns true if such a match is
1080// found.
1081static bool MatchRem(Value *E, Value *&Op, APInt &C, bool &IsSigned) {
1082  const APInt *AI;
1083  IsSigned = false;
1084  if (match(E, m_SRem(m_Value(Op), m_APInt(AI)))) {
1085    IsSigned = true;
1086    C = *AI;
1087    return true;
1088  }
1089  if (match(E, m_URem(m_Value(Op), m_APInt(AI)))) {
1090    C = *AI;
1091    return true;
1092  }
1093  if (match(E, m_And(m_Value(Op), m_APInt(AI))) && (*AI + 1).isPowerOf2()) {
1094    C = *AI + 1;
1095    return true;
1096  }
1097  return false;
1098}
1099
1100// Matches division expression Op / C with the given signedness as indicated
1101// by IsSigned, where C is a constant. Returns the constant value in C and the
1102// other operand in Op. Returns true if such a match is found.
1103static bool MatchDiv(Value *E, Value *&Op, APInt &C, bool IsSigned) {
1104  const APInt *AI;
1105  if (IsSigned && match(E, m_SDiv(m_Value(Op), m_APInt(AI)))) {
1106    C = *AI;
1107    return true;
1108  }
1109  if (!IsSigned) {
1110    if (match(E, m_UDiv(m_Value(Op), m_APInt(AI)))) {
1111      C = *AI;
1112      return true;
1113    }
1114    if (match(E, m_LShr(m_Value(Op), m_APInt(AI)))) {
1115      C = APInt(AI->getBitWidth(), 1);
1116      C <<= *AI;
1117      return true;
1118    }
1119  }
1120  return false;
1121}
1122
1123// Returns whether C0 * C1 with the given signedness overflows.
1124static bool MulWillOverflow(APInt &C0, APInt &C1, bool IsSigned) {
1125  bool overflow;
1126  if (IsSigned)
1127    (void)C0.smul_ov(C1, overflow);
1128  else
1129    (void)C0.umul_ov(C1, overflow);
1130  return overflow;
1131}
1132
1133// Simplifies X % C0 + (( X / C0 ) % C1) * C0 to X % (C0 * C1), where (C0 * C1)
1134// does not overflow.
1135Value *InstCombinerImpl::SimplifyAddWithRemainder(BinaryOperator &I) {
1136  Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1137  Value *X, *MulOpV;
1138  APInt C0, MulOpC;
1139  bool IsSigned;
1140  // Match I = X % C0 + MulOpV * C0
1141  if (((MatchRem(LHS, X, C0, IsSigned) && MatchMul(RHS, MulOpV, MulOpC)) ||
1142       (MatchRem(RHS, X, C0, IsSigned) && MatchMul(LHS, MulOpV, MulOpC))) &&
1143      C0 == MulOpC) {
1144    Value *RemOpV;
1145    APInt C1;
1146    bool Rem2IsSigned;
1147    // Match MulOpC = RemOpV % C1
1148    if (MatchRem(MulOpV, RemOpV, C1, Rem2IsSigned) &&
1149        IsSigned == Rem2IsSigned) {
1150      Value *DivOpV;
1151      APInt DivOpC;
1152      // Match RemOpV = X / C0
1153      if (MatchDiv(RemOpV, DivOpV, DivOpC, IsSigned) && X == DivOpV &&
1154          C0 == DivOpC && !MulWillOverflow(C0, C1, IsSigned)) {
1155        Value *NewDivisor = ConstantInt::get(X->getType(), C0 * C1);
1156        return IsSigned ? Builder.CreateSRem(X, NewDivisor, "srem")
1157                        : Builder.CreateURem(X, NewDivisor, "urem");
1158      }
1159    }
1160  }
1161
1162  return nullptr;
1163}
1164
1165/// Fold
1166///   (1 << NBits) - 1
1167/// Into:
1168///   ~(-(1 << NBits))
1169/// Because a 'not' is better for bit-tracking analysis and other transforms
1170/// than an 'add'. The new shl is always nsw, and is nuw if old `and` was.
1171static Instruction *canonicalizeLowbitMask(BinaryOperator &I,
1172                                           InstCombiner::BuilderTy &Builder) {
1173  Value *NBits;
1174  if (!match(&I, m_Add(m_OneUse(m_Shl(m_One(), m_Value(NBits))), m_AllOnes())))
1175    return nullptr;
1176
1177  Constant *MinusOne = Constant::getAllOnesValue(NBits->getType());
1178  Value *NotMask = Builder.CreateShl(MinusOne, NBits, "notmask");
1179  // Be wary of constant folding.
1180  if (auto *BOp = dyn_cast<BinaryOperator>(NotMask)) {
1181    // Always NSW. But NUW propagates from `add`.
1182    BOp->setHasNoSignedWrap();
1183    BOp->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
1184  }
1185
1186  return BinaryOperator::CreateNot(NotMask, I.getName());
1187}
1188
1189static Instruction *foldToUnsignedSaturatedAdd(BinaryOperator &I) {
1190  assert(I.getOpcode() == Instruction::Add && "Expecting add instruction");
1191  Type *Ty = I.getType();
1192  auto getUAddSat = [&]() {
1193    return Intrinsic::getDeclaration(I.getModule(), Intrinsic::uadd_sat, Ty);
1194  };
1195
1196  // add (umin X, ~Y), Y --> uaddsat X, Y
1197  Value *X, *Y;
1198  if (match(&I, m_c_Add(m_c_UMin(m_Value(X), m_Not(m_Value(Y))),
1199                        m_Deferred(Y))))
1200    return CallInst::Create(getUAddSat(), { X, Y });
1201
1202  // add (umin X, ~C), C --> uaddsat X, C
1203  const APInt *C, *NotC;
1204  if (match(&I, m_Add(m_UMin(m_Value(X), m_APInt(NotC)), m_APInt(C))) &&
1205      *C == ~*NotC)
1206    return CallInst::Create(getUAddSat(), { X, ConstantInt::get(Ty, *C) });
1207
1208  return nullptr;
1209}
1210
1211// Transform:
1212//  (add A, (shl (neg B), Y))
1213//      -> (sub A, (shl B, Y))
1214static Instruction *combineAddSubWithShlAddSub(InstCombiner::BuilderTy &Builder,
1215                                               const BinaryOperator &I) {
1216  Value *A, *B, *Cnt;
1217  if (match(&I,
1218            m_c_Add(m_OneUse(m_Shl(m_OneUse(m_Neg(m_Value(B))), m_Value(Cnt))),
1219                    m_Value(A)))) {
1220    Value *NewShl = Builder.CreateShl(B, Cnt);
1221    return BinaryOperator::CreateSub(A, NewShl);
1222  }
1223  return nullptr;
1224}
1225
1226/// Try to reduce signed division by power-of-2 to an arithmetic shift right.
1227static Instruction *foldAddToAshr(BinaryOperator &Add) {
1228  // Division must be by power-of-2, but not the minimum signed value.
1229  Value *X;
1230  const APInt *DivC;
1231  if (!match(Add.getOperand(0), m_SDiv(m_Value(X), m_Power2(DivC))) ||
1232      DivC->isNegative())
1233    return nullptr;
1234
1235  // Rounding is done by adding -1 if the dividend (X) is negative and has any
1236  // low bits set. It recognizes two canonical patterns:
1237  // 1. For an 'ugt' cmp with the signed minimum value (SMIN), the
1238  //    pattern is: sext (icmp ugt (X & (DivC - 1)), SMIN).
1239  // 2. For an 'eq' cmp, the pattern's: sext (icmp eq X & (SMIN + 1), SMIN + 1).
1240  // Note that, by the time we end up here, if possible, ugt has been
1241  // canonicalized into eq.
1242  const APInt *MaskC, *MaskCCmp;
1243  ICmpInst::Predicate Pred;
1244  if (!match(Add.getOperand(1),
1245             m_SExt(m_ICmp(Pred, m_And(m_Specific(X), m_APInt(MaskC)),
1246                           m_APInt(MaskCCmp)))))
1247    return nullptr;
1248
1249  if ((Pred != ICmpInst::ICMP_UGT || !MaskCCmp->isSignMask()) &&
1250      (Pred != ICmpInst::ICMP_EQ || *MaskCCmp != *MaskC))
1251    return nullptr;
1252
1253  APInt SMin = APInt::getSignedMinValue(Add.getType()->getScalarSizeInBits());
1254  bool IsMaskValid = Pred == ICmpInst::ICMP_UGT
1255                         ? (*MaskC == (SMin | (*DivC - 1)))
1256                         : (*DivC == 2 && *MaskC == SMin + 1);
1257  if (!IsMaskValid)
1258    return nullptr;
1259
1260  // (X / DivC) + sext ((X & (SMin | (DivC - 1)) >u SMin) --> X >>s log2(DivC)
1261  return BinaryOperator::CreateAShr(
1262      X, ConstantInt::get(Add.getType(), DivC->exactLogBase2()));
1263}
1264
1265Instruction *InstCombinerImpl::
1266    canonicalizeCondSignextOfHighBitExtractToSignextHighBitExtract(
1267        BinaryOperator &I) {
1268  assert((I.getOpcode() == Instruction::Add ||
1269          I.getOpcode() == Instruction::Or ||
1270          I.getOpcode() == Instruction::Sub) &&
1271         "Expecting add/or/sub instruction");
1272
1273  // We have a subtraction/addition between a (potentially truncated) *logical*
1274  // right-shift of X and a "select".
1275  Value *X, *Select;
1276  Instruction *LowBitsToSkip, *Extract;
1277  if (!match(&I, m_c_BinOp(m_TruncOrSelf(m_CombineAnd(
1278                               m_LShr(m_Value(X), m_Instruction(LowBitsToSkip)),
1279                               m_Instruction(Extract))),
1280                           m_Value(Select))))
1281    return nullptr;
1282
1283  // `add`/`or` is commutative; but for `sub`, "select" *must* be on RHS.
1284  if (I.getOpcode() == Instruction::Sub && I.getOperand(1) != Select)
1285    return nullptr;
1286
1287  Type *XTy = X->getType();
1288  bool HadTrunc = I.getType() != XTy;
1289
1290  // If there was a truncation of extracted value, then we'll need to produce
1291  // one extra instruction, so we need to ensure one instruction will go away.
1292  if (HadTrunc && !match(&I, m_c_BinOp(m_OneUse(m_Value()), m_Value())))
1293    return nullptr;
1294
1295  // Extraction should extract high NBits bits, with shift amount calculated as:
1296  //   low bits to skip = shift bitwidth - high bits to extract
1297  // The shift amount itself may be extended, and we need to look past zero-ext
1298  // when matching NBits, that will matter for matching later.
1299  Constant *C;
1300  Value *NBits;
1301  if (!match(
1302          LowBitsToSkip,
1303          m_ZExtOrSelf(m_Sub(m_Constant(C), m_ZExtOrSelf(m_Value(NBits))))) ||
1304      !match(C, m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_EQ,
1305                                   APInt(C->getType()->getScalarSizeInBits(),
1306                                         X->getType()->getScalarSizeInBits()))))
1307    return nullptr;
1308
1309  // Sign-extending value can be zero-extended if we `sub`tract it,
1310  // or sign-extended otherwise.
1311  auto SkipExtInMagic = [&I](Value *&V) {
1312    if (I.getOpcode() == Instruction::Sub)
1313      match(V, m_ZExtOrSelf(m_Value(V)));
1314    else
1315      match(V, m_SExtOrSelf(m_Value(V)));
1316  };
1317
1318  // Now, finally validate the sign-extending magic.
1319  // `select` itself may be appropriately extended, look past that.
1320  SkipExtInMagic(Select);
1321
1322  ICmpInst::Predicate Pred;
1323  const APInt *Thr;
1324  Value *SignExtendingValue, *Zero;
1325  bool ShouldSignext;
1326  // It must be a select between two values we will later establish to be a
1327  // sign-extending value and a zero constant. The condition guarding the
1328  // sign-extension must be based on a sign bit of the same X we had in `lshr`.
1329  if (!match(Select, m_Select(m_ICmp(Pred, m_Specific(X), m_APInt(Thr)),
1330                              m_Value(SignExtendingValue), m_Value(Zero))) ||
1331      !isSignBitCheck(Pred, *Thr, ShouldSignext))
1332    return nullptr;
1333
1334  // icmp-select pair is commutative.
1335  if (!ShouldSignext)
1336    std::swap(SignExtendingValue, Zero);
1337
1338  // If we should not perform sign-extension then we must add/or/subtract zero.
1339  if (!match(Zero, m_Zero()))
1340    return nullptr;
1341  // Otherwise, it should be some constant, left-shifted by the same NBits we
1342  // had in `lshr`. Said left-shift can also be appropriately extended.
1343  // Again, we must look past zero-ext when looking for NBits.
1344  SkipExtInMagic(SignExtendingValue);
1345  Constant *SignExtendingValueBaseConstant;
1346  if (!match(SignExtendingValue,
1347             m_Shl(m_Constant(SignExtendingValueBaseConstant),
1348                   m_ZExtOrSelf(m_Specific(NBits)))))
1349    return nullptr;
1350  // If we `sub`, then the constant should be one, else it should be all-ones.
1351  if (I.getOpcode() == Instruction::Sub
1352          ? !match(SignExtendingValueBaseConstant, m_One())
1353          : !match(SignExtendingValueBaseConstant, m_AllOnes()))
1354    return nullptr;
1355
1356  auto *NewAShr = BinaryOperator::CreateAShr(X, LowBitsToSkip,
1357                                             Extract->getName() + ".sext");
1358  NewAShr->copyIRFlags(Extract); // Preserve `exact`-ness.
1359  if (!HadTrunc)
1360    return NewAShr;
1361
1362  Builder.Insert(NewAShr);
1363  return TruncInst::CreateTruncOrBitCast(NewAShr, I.getType());
1364}
1365
1366/// This is a specialization of a more general transform from
1367/// foldUsingDistributiveLaws. If that code can be made to work optimally
1368/// for multi-use cases or propagating nsw/nuw, then we would not need this.
1369static Instruction *factorizeMathWithShlOps(BinaryOperator &I,
1370                                            InstCombiner::BuilderTy &Builder) {
1371  // TODO: Also handle mul by doubling the shift amount?
1372  assert((I.getOpcode() == Instruction::Add ||
1373          I.getOpcode() == Instruction::Sub) &&
1374         "Expected add/sub");
1375  auto *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0));
1376  auto *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1));
1377  if (!Op0 || !Op1 || !(Op0->hasOneUse() || Op1->hasOneUse()))
1378    return nullptr;
1379
1380  Value *X, *Y, *ShAmt;
1381  if (!match(Op0, m_Shl(m_Value(X), m_Value(ShAmt))) ||
1382      !match(Op1, m_Shl(m_Value(Y), m_Specific(ShAmt))))
1383    return nullptr;
1384
1385  // No-wrap propagates only when all ops have no-wrap.
1386  bool HasNSW = I.hasNoSignedWrap() && Op0->hasNoSignedWrap() &&
1387                Op1->hasNoSignedWrap();
1388  bool HasNUW = I.hasNoUnsignedWrap() && Op0->hasNoUnsignedWrap() &&
1389                Op1->hasNoUnsignedWrap();
1390
1391  // add/sub (X << ShAmt), (Y << ShAmt) --> (add/sub X, Y) << ShAmt
1392  Value *NewMath = Builder.CreateBinOp(I.getOpcode(), X, Y);
1393  if (auto *NewI = dyn_cast<BinaryOperator>(NewMath)) {
1394    NewI->setHasNoSignedWrap(HasNSW);
1395    NewI->setHasNoUnsignedWrap(HasNUW);
1396  }
1397  auto *NewShl = BinaryOperator::CreateShl(NewMath, ShAmt);
1398  NewShl->setHasNoSignedWrap(HasNSW);
1399  NewShl->setHasNoUnsignedWrap(HasNUW);
1400  return NewShl;
1401}
1402
1403/// Reduce a sequence of masked half-width multiplies to a single multiply.
1404/// ((XLow * YHigh) + (YLow * XHigh)) << HalfBits) + (XLow * YLow) --> X * Y
1405static Instruction *foldBoxMultiply(BinaryOperator &I) {
1406  unsigned BitWidth = I.getType()->getScalarSizeInBits();
1407  // Skip the odd bitwidth types.
1408  if ((BitWidth & 0x1))
1409    return nullptr;
1410
1411  unsigned HalfBits = BitWidth >> 1;
1412  APInt HalfMask = APInt::getMaxValue(HalfBits);
1413
1414  // ResLo = (CrossSum << HalfBits) + (YLo * XLo)
1415  Value *XLo, *YLo;
1416  Value *CrossSum;
1417  // Require one-use on the multiply to avoid increasing the number of
1418  // multiplications.
1419  if (!match(&I, m_c_Add(m_Shl(m_Value(CrossSum), m_SpecificInt(HalfBits)),
1420                         m_OneUse(m_Mul(m_Value(YLo), m_Value(XLo))))))
1421    return nullptr;
1422
1423  // XLo = X & HalfMask
1424  // YLo = Y & HalfMask
1425  // TODO: Refactor with SimplifyDemandedBits or KnownBits known leading zeros
1426  // to enhance robustness
1427  Value *X, *Y;
1428  if (!match(XLo, m_And(m_Value(X), m_SpecificInt(HalfMask))) ||
1429      !match(YLo, m_And(m_Value(Y), m_SpecificInt(HalfMask))))
1430    return nullptr;
1431
1432  // CrossSum = (X' * (Y >> Halfbits)) + (Y' * (X >> HalfBits))
1433  // X' can be either X or XLo in the pattern (and the same for Y')
1434  if (match(CrossSum,
1435            m_c_Add(m_c_Mul(m_LShr(m_Specific(Y), m_SpecificInt(HalfBits)),
1436                            m_CombineOr(m_Specific(X), m_Specific(XLo))),
1437                    m_c_Mul(m_LShr(m_Specific(X), m_SpecificInt(HalfBits)),
1438                            m_CombineOr(m_Specific(Y), m_Specific(YLo))))))
1439    return BinaryOperator::CreateMul(X, Y);
1440
1441  return nullptr;
1442}
1443
1444Instruction *InstCombinerImpl::visitAdd(BinaryOperator &I) {
1445  if (Value *V = simplifyAddInst(I.getOperand(0), I.getOperand(1),
1446                                 I.hasNoSignedWrap(), I.hasNoUnsignedWrap(),
1447                                 SQ.getWithInstruction(&I)))
1448    return replaceInstUsesWith(I, V);
1449
1450  if (SimplifyAssociativeOrCommutative(I))
1451    return &I;
1452
1453  if (Instruction *X = foldVectorBinop(I))
1454    return X;
1455
1456  if (Instruction *Phi = foldBinopWithPhiOperands(I))
1457    return Phi;
1458
1459  // (A*B)+(A*C) -> A*(B+C) etc
1460  if (Value *V = foldUsingDistributiveLaws(I))
1461    return replaceInstUsesWith(I, V);
1462
1463  if (Instruction *R = foldBoxMultiply(I))
1464    return R;
1465
1466  if (Instruction *R = factorizeMathWithShlOps(I, Builder))
1467    return R;
1468
1469  if (Instruction *X = foldAddWithConstant(I))
1470    return X;
1471
1472  if (Instruction *X = foldNoWrapAdd(I, Builder))
1473    return X;
1474
1475  if (Instruction *R = foldBinOpShiftWithShift(I))
1476    return R;
1477
1478  if (Instruction *R = combineAddSubWithShlAddSub(Builder, I))
1479    return R;
1480
1481  Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1482  Type *Ty = I.getType();
1483  if (Ty->isIntOrIntVectorTy(1))
1484    return BinaryOperator::CreateXor(LHS, RHS);
1485
1486  // X + X --> X << 1
1487  if (LHS == RHS) {
1488    auto *Shl = BinaryOperator::CreateShl(LHS, ConstantInt::get(Ty, 1));
1489    Shl->setHasNoSignedWrap(I.hasNoSignedWrap());
1490    Shl->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
1491    return Shl;
1492  }
1493
1494  Value *A, *B;
1495  if (match(LHS, m_Neg(m_Value(A)))) {
1496    // -A + -B --> -(A + B)
1497    if (match(RHS, m_Neg(m_Value(B))))
1498      return BinaryOperator::CreateNeg(Builder.CreateAdd(A, B));
1499
1500    // -A + B --> B - A
1501    auto *Sub = BinaryOperator::CreateSub(RHS, A);
1502    auto *OB0 = cast<OverflowingBinaryOperator>(LHS);
1503    Sub->setHasNoSignedWrap(I.hasNoSignedWrap() && OB0->hasNoSignedWrap());
1504
1505    return Sub;
1506  }
1507
1508  // A + -B  -->  A - B
1509  if (match(RHS, m_Neg(m_Value(B))))
1510    return BinaryOperator::CreateSub(LHS, B);
1511
1512  if (Value *V = checkForNegativeOperand(I, Builder))
1513    return replaceInstUsesWith(I, V);
1514
1515  // (A + 1) + ~B --> A - B
1516  // ~B + (A + 1) --> A - B
1517  // (~B + A) + 1 --> A - B
1518  // (A + ~B) + 1 --> A - B
1519  if (match(&I, m_c_BinOp(m_Add(m_Value(A), m_One()), m_Not(m_Value(B)))) ||
1520      match(&I, m_BinOp(m_c_Add(m_Not(m_Value(B)), m_Value(A)), m_One())))
1521    return BinaryOperator::CreateSub(A, B);
1522
1523  // (A + RHS) + RHS --> A + (RHS << 1)
1524  if (match(LHS, m_OneUse(m_c_Add(m_Value(A), m_Specific(RHS)))))
1525    return BinaryOperator::CreateAdd(A, Builder.CreateShl(RHS, 1, "reass.add"));
1526
1527  // LHS + (A + LHS) --> A + (LHS << 1)
1528  if (match(RHS, m_OneUse(m_c_Add(m_Value(A), m_Specific(LHS)))))
1529    return BinaryOperator::CreateAdd(A, Builder.CreateShl(LHS, 1, "reass.add"));
1530
1531  {
1532    // (A + C1) + (C2 - B) --> (A - B) + (C1 + C2)
1533    Constant *C1, *C2;
1534    if (match(&I, m_c_Add(m_Add(m_Value(A), m_ImmConstant(C1)),
1535                          m_Sub(m_ImmConstant(C2), m_Value(B)))) &&
1536        (LHS->hasOneUse() || RHS->hasOneUse())) {
1537      Value *Sub = Builder.CreateSub(A, B);
1538      return BinaryOperator::CreateAdd(Sub, ConstantExpr::getAdd(C1, C2));
1539    }
1540
1541    // Canonicalize a constant sub operand as an add operand for better folding:
1542    // (C1 - A) + B --> (B - A) + C1
1543    if (match(&I, m_c_Add(m_OneUse(m_Sub(m_ImmConstant(C1), m_Value(A))),
1544                          m_Value(B)))) {
1545      Value *Sub = Builder.CreateSub(B, A, "reass.sub");
1546      return BinaryOperator::CreateAdd(Sub, C1);
1547    }
1548  }
1549
1550  // X % C0 + (( X / C0 ) % C1) * C0 => X % (C0 * C1)
1551  if (Value *V = SimplifyAddWithRemainder(I)) return replaceInstUsesWith(I, V);
1552
1553  // ((X s/ C1) << C2) + X => X s% -C1 where -C1 is 1 << C2
1554  const APInt *C1, *C2;
1555  if (match(LHS, m_Shl(m_SDiv(m_Specific(RHS), m_APInt(C1)), m_APInt(C2)))) {
1556    APInt one(C2->getBitWidth(), 1);
1557    APInt minusC1 = -(*C1);
1558    if (minusC1 == (one << *C2)) {
1559      Constant *NewRHS = ConstantInt::get(RHS->getType(), minusC1);
1560      return BinaryOperator::CreateSRem(RHS, NewRHS);
1561    }
1562  }
1563
1564  // (A & 2^C1) + A => A & (2^C1 - 1) iff bit C1 in A is a sign bit
1565  if (match(&I, m_c_Add(m_And(m_Value(A), m_APInt(C1)), m_Deferred(A))) &&
1566      C1->isPowerOf2() && (ComputeNumSignBits(A) > C1->countl_zero())) {
1567    Constant *NewMask = ConstantInt::get(RHS->getType(), *C1 - 1);
1568    return BinaryOperator::CreateAnd(A, NewMask);
1569  }
1570
1571  // ZExt (B - A) + ZExt(A) --> ZExt(B)
1572  if ((match(RHS, m_ZExt(m_Value(A))) &&
1573       match(LHS, m_ZExt(m_NUWSub(m_Value(B), m_Specific(A))))) ||
1574      (match(LHS, m_ZExt(m_Value(A))) &&
1575       match(RHS, m_ZExt(m_NUWSub(m_Value(B), m_Specific(A))))))
1576    return new ZExtInst(B, LHS->getType());
1577
1578  // zext(A) + sext(A) --> 0 if A is i1
1579  if (match(&I, m_c_BinOp(m_ZExt(m_Value(A)), m_SExt(m_Deferred(A)))) &&
1580      A->getType()->isIntOrIntVectorTy(1))
1581    return replaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1582
1583  // A+B --> A|B iff A and B have no bits set in common.
1584  WithCache<const Value *> LHSCache(LHS), RHSCache(RHS);
1585  if (haveNoCommonBitsSet(LHSCache, RHSCache, SQ.getWithInstruction(&I)))
1586    return BinaryOperator::CreateDisjointOr(LHS, RHS);
1587
1588  if (Instruction *Ext = narrowMathIfNoOverflow(I))
1589    return Ext;
1590
1591  // (add (xor A, B) (and A, B)) --> (or A, B)
1592  // (add (and A, B) (xor A, B)) --> (or A, B)
1593  if (match(&I, m_c_BinOp(m_Xor(m_Value(A), m_Value(B)),
1594                          m_c_And(m_Deferred(A), m_Deferred(B)))))
1595    return BinaryOperator::CreateOr(A, B);
1596
1597  // (add (or A, B) (and A, B)) --> (add A, B)
1598  // (add (and A, B) (or A, B)) --> (add A, B)
1599  if (match(&I, m_c_BinOp(m_Or(m_Value(A), m_Value(B)),
1600                          m_c_And(m_Deferred(A), m_Deferred(B))))) {
1601    // Replacing operands in-place to preserve nuw/nsw flags.
1602    replaceOperand(I, 0, A);
1603    replaceOperand(I, 1, B);
1604    return &I;
1605  }
1606
1607  // (add A (or A, -A)) --> (and (add A, -1) A)
1608  // (add A (or -A, A)) --> (and (add A, -1) A)
1609  // (add (or A, -A) A) --> (and (add A, -1) A)
1610  // (add (or -A, A) A) --> (and (add A, -1) A)
1611  if (match(&I, m_c_BinOp(m_Value(A), m_OneUse(m_c_Or(m_Neg(m_Deferred(A)),
1612                                                      m_Deferred(A)))))) {
1613    Value *Add =
1614        Builder.CreateAdd(A, Constant::getAllOnesValue(A->getType()), "",
1615                          I.hasNoUnsignedWrap(), I.hasNoSignedWrap());
1616    return BinaryOperator::CreateAnd(Add, A);
1617  }
1618
1619  // Canonicalize ((A & -A) - 1) --> ((A - 1) & ~A)
1620  // Forms all commutable operations, and simplifies ctpop -> cttz folds.
1621  if (match(&I,
1622            m_Add(m_OneUse(m_c_And(m_Value(A), m_OneUse(m_Neg(m_Deferred(A))))),
1623                  m_AllOnes()))) {
1624    Constant *AllOnes = ConstantInt::getAllOnesValue(RHS->getType());
1625    Value *Dec = Builder.CreateAdd(A, AllOnes);
1626    Value *Not = Builder.CreateXor(A, AllOnes);
1627    return BinaryOperator::CreateAnd(Dec, Not);
1628  }
1629
1630  // Disguised reassociation/factorization:
1631  // ~(A * C1) + A
1632  // ((A * -C1) - 1) + A
1633  // ((A * -C1) + A) - 1
1634  // (A * (1 - C1)) - 1
1635  if (match(&I,
1636            m_c_Add(m_OneUse(m_Not(m_OneUse(m_Mul(m_Value(A), m_APInt(C1))))),
1637                    m_Deferred(A)))) {
1638    Type *Ty = I.getType();
1639    Constant *NewMulC = ConstantInt::get(Ty, 1 - *C1);
1640    Value *NewMul = Builder.CreateMul(A, NewMulC);
1641    return BinaryOperator::CreateAdd(NewMul, ConstantInt::getAllOnesValue(Ty));
1642  }
1643
1644  // (A * -2**C) + B --> B - (A << C)
1645  const APInt *NegPow2C;
1646  if (match(&I, m_c_Add(m_OneUse(m_Mul(m_Value(A), m_NegatedPower2(NegPow2C))),
1647                        m_Value(B)))) {
1648    Constant *ShiftAmtC = ConstantInt::get(Ty, NegPow2C->countr_zero());
1649    Value *Shl = Builder.CreateShl(A, ShiftAmtC);
1650    return BinaryOperator::CreateSub(B, Shl);
1651  }
1652
1653  // Canonicalize signum variant that ends in add:
1654  // (A s>> (BW - 1)) + (zext (A s> 0)) --> (A s>> (BW - 1)) | (zext (A != 0))
1655  ICmpInst::Predicate Pred;
1656  uint64_t BitWidth = Ty->getScalarSizeInBits();
1657  if (match(LHS, m_AShr(m_Value(A), m_SpecificIntAllowUndef(BitWidth - 1))) &&
1658      match(RHS, m_OneUse(m_ZExt(
1659                     m_OneUse(m_ICmp(Pred, m_Specific(A), m_ZeroInt()))))) &&
1660      Pred == CmpInst::ICMP_SGT) {
1661    Value *NotZero = Builder.CreateIsNotNull(A, "isnotnull");
1662    Value *Zext = Builder.CreateZExt(NotZero, Ty, "isnotnull.zext");
1663    return BinaryOperator::CreateOr(LHS, Zext);
1664  }
1665
1666  if (Instruction *Ashr = foldAddToAshr(I))
1667    return Ashr;
1668
1669  // (~X) + (~Y) --> -2 - (X + Y)
1670  {
1671    // To ensure we can save instructions we need to ensure that we consume both
1672    // LHS/RHS (i.e they have a `not`).
1673    bool ConsumesLHS, ConsumesRHS;
1674    if (isFreeToInvert(LHS, LHS->hasOneUse(), ConsumesLHS) && ConsumesLHS &&
1675        isFreeToInvert(RHS, RHS->hasOneUse(), ConsumesRHS) && ConsumesRHS) {
1676      Value *NotLHS = getFreelyInverted(LHS, LHS->hasOneUse(), &Builder);
1677      Value *NotRHS = getFreelyInverted(RHS, RHS->hasOneUse(), &Builder);
1678      assert(NotLHS != nullptr && NotRHS != nullptr &&
1679             "isFreeToInvert desynced with getFreelyInverted");
1680      Value *LHSPlusRHS = Builder.CreateAdd(NotLHS, NotRHS);
1681      return BinaryOperator::CreateSub(
1682          ConstantInt::getSigned(RHS->getType(), -2), LHSPlusRHS);
1683    }
1684  }
1685
1686  if (Instruction *R = tryFoldInstWithCtpopWithNot(&I))
1687    return R;
1688
1689  // TODO(jingyue): Consider willNotOverflowSignedAdd and
1690  // willNotOverflowUnsignedAdd to reduce the number of invocations of
1691  // computeKnownBits.
1692  bool Changed = false;
1693  if (!I.hasNoSignedWrap() && willNotOverflowSignedAdd(LHSCache, RHSCache, I)) {
1694    Changed = true;
1695    I.setHasNoSignedWrap(true);
1696  }
1697  if (!I.hasNoUnsignedWrap() &&
1698      willNotOverflowUnsignedAdd(LHSCache, RHSCache, I)) {
1699    Changed = true;
1700    I.setHasNoUnsignedWrap(true);
1701  }
1702
1703  if (Instruction *V = canonicalizeLowbitMask(I, Builder))
1704    return V;
1705
1706  if (Instruction *V =
1707          canonicalizeCondSignextOfHighBitExtractToSignextHighBitExtract(I))
1708    return V;
1709
1710  if (Instruction *SatAdd = foldToUnsignedSaturatedAdd(I))
1711    return SatAdd;
1712
1713  // usub.sat(A, B) + B => umax(A, B)
1714  if (match(&I, m_c_BinOp(
1715          m_OneUse(m_Intrinsic<Intrinsic::usub_sat>(m_Value(A), m_Value(B))),
1716          m_Deferred(B)))) {
1717    return replaceInstUsesWith(I,
1718        Builder.CreateIntrinsic(Intrinsic::umax, {I.getType()}, {A, B}));
1719  }
1720
1721  // ctpop(A) + ctpop(B) => ctpop(A | B) if A and B have no bits set in common.
1722  if (match(LHS, m_OneUse(m_Intrinsic<Intrinsic::ctpop>(m_Value(A)))) &&
1723      match(RHS, m_OneUse(m_Intrinsic<Intrinsic::ctpop>(m_Value(B)))) &&
1724      haveNoCommonBitsSet(A, B, SQ.getWithInstruction(&I)))
1725    return replaceInstUsesWith(
1726        I, Builder.CreateIntrinsic(Intrinsic::ctpop, {I.getType()},
1727                                   {Builder.CreateOr(A, B)}));
1728
1729  // Fold the log2_ceil idiom:
1730  // zext(ctpop(A) >u/!= 1) + (ctlz(A, true) ^ (BW - 1))
1731  // -->
1732  // BW - ctlz(A - 1, false)
1733  const APInt *XorC;
1734  if (match(&I,
1735            m_c_Add(
1736                m_ZExt(m_ICmp(Pred, m_Intrinsic<Intrinsic::ctpop>(m_Value(A)),
1737                              m_One())),
1738                m_OneUse(m_ZExtOrSelf(m_OneUse(m_Xor(
1739                    m_OneUse(m_TruncOrSelf(m_OneUse(
1740                        m_Intrinsic<Intrinsic::ctlz>(m_Deferred(A), m_One())))),
1741                    m_APInt(XorC))))))) &&
1742      (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_NE) &&
1743      *XorC == A->getType()->getScalarSizeInBits() - 1) {
1744    Value *Sub = Builder.CreateAdd(A, Constant::getAllOnesValue(A->getType()));
1745    Value *Ctlz = Builder.CreateIntrinsic(Intrinsic::ctlz, {A->getType()},
1746                                          {Sub, Builder.getFalse()});
1747    Value *Ret = Builder.CreateSub(
1748        ConstantInt::get(A->getType(), A->getType()->getScalarSizeInBits()),
1749        Ctlz, "", /*HasNUW*/ true, /*HasNSW*/ true);
1750    return replaceInstUsesWith(I, Builder.CreateZExtOrTrunc(Ret, I.getType()));
1751  }
1752
1753  if (Instruction *Res = foldSquareSumInt(I))
1754    return Res;
1755
1756  if (Instruction *Res = foldBinOpOfDisplacedShifts(I))
1757    return Res;
1758
1759  if (Instruction *Res = foldBinOpOfSelectAndCastOfSelectCondition(I))
1760    return Res;
1761
1762  return Changed ? &I : nullptr;
1763}
1764
1765/// Eliminate an op from a linear interpolation (lerp) pattern.
1766static Instruction *factorizeLerp(BinaryOperator &I,
1767                                  InstCombiner::BuilderTy &Builder) {
1768  Value *X, *Y, *Z;
1769  if (!match(&I, m_c_FAdd(m_OneUse(m_c_FMul(m_Value(Y),
1770                                            m_OneUse(m_FSub(m_FPOne(),
1771                                                            m_Value(Z))))),
1772                          m_OneUse(m_c_FMul(m_Value(X), m_Deferred(Z))))))
1773    return nullptr;
1774
1775  // (Y * (1.0 - Z)) + (X * Z) --> Y + Z * (X - Y) [8 commuted variants]
1776  Value *XY = Builder.CreateFSubFMF(X, Y, &I);
1777  Value *MulZ = Builder.CreateFMulFMF(Z, XY, &I);
1778  return BinaryOperator::CreateFAddFMF(Y, MulZ, &I);
1779}
1780
1781/// Factor a common operand out of fadd/fsub of fmul/fdiv.
1782static Instruction *factorizeFAddFSub(BinaryOperator &I,
1783                                      InstCombiner::BuilderTy &Builder) {
1784  assert((I.getOpcode() == Instruction::FAdd ||
1785          I.getOpcode() == Instruction::FSub) && "Expecting fadd/fsub");
1786  assert(I.hasAllowReassoc() && I.hasNoSignedZeros() &&
1787         "FP factorization requires FMF");
1788
1789  if (Instruction *Lerp = factorizeLerp(I, Builder))
1790    return Lerp;
1791
1792  Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1793  if (!Op0->hasOneUse() || !Op1->hasOneUse())
1794    return nullptr;
1795
1796  Value *X, *Y, *Z;
1797  bool IsFMul;
1798  if ((match(Op0, m_FMul(m_Value(X), m_Value(Z))) &&
1799       match(Op1, m_c_FMul(m_Value(Y), m_Specific(Z)))) ||
1800      (match(Op0, m_FMul(m_Value(Z), m_Value(X))) &&
1801       match(Op1, m_c_FMul(m_Value(Y), m_Specific(Z)))))
1802    IsFMul = true;
1803  else if (match(Op0, m_FDiv(m_Value(X), m_Value(Z))) &&
1804           match(Op1, m_FDiv(m_Value(Y), m_Specific(Z))))
1805    IsFMul = false;
1806  else
1807    return nullptr;
1808
1809  // (X * Z) + (Y * Z) --> (X + Y) * Z
1810  // (X * Z) - (Y * Z) --> (X - Y) * Z
1811  // (X / Z) + (Y / Z) --> (X + Y) / Z
1812  // (X / Z) - (Y / Z) --> (X - Y) / Z
1813  bool IsFAdd = I.getOpcode() == Instruction::FAdd;
1814  Value *XY = IsFAdd ? Builder.CreateFAddFMF(X, Y, &I)
1815                     : Builder.CreateFSubFMF(X, Y, &I);
1816
1817  // Bail out if we just created a denormal constant.
1818  // TODO: This is copied from a previous implementation. Is it necessary?
1819  const APFloat *C;
1820  if (match(XY, m_APFloat(C)) && !C->isNormal())
1821    return nullptr;
1822
1823  return IsFMul ? BinaryOperator::CreateFMulFMF(XY, Z, &I)
1824                : BinaryOperator::CreateFDivFMF(XY, Z, &I);
1825}
1826
1827Instruction *InstCombinerImpl::visitFAdd(BinaryOperator &I) {
1828  if (Value *V = simplifyFAddInst(I.getOperand(0), I.getOperand(1),
1829                                  I.getFastMathFlags(),
1830                                  SQ.getWithInstruction(&I)))
1831    return replaceInstUsesWith(I, V);
1832
1833  if (SimplifyAssociativeOrCommutative(I))
1834    return &I;
1835
1836  if (Instruction *X = foldVectorBinop(I))
1837    return X;
1838
1839  if (Instruction *Phi = foldBinopWithPhiOperands(I))
1840    return Phi;
1841
1842  if (Instruction *FoldedFAdd = foldBinOpIntoSelectOrPhi(I))
1843    return FoldedFAdd;
1844
1845  // (-X) + Y --> Y - X
1846  Value *X, *Y;
1847  if (match(&I, m_c_FAdd(m_FNeg(m_Value(X)), m_Value(Y))))
1848    return BinaryOperator::CreateFSubFMF(Y, X, &I);
1849
1850  // Similar to above, but look through fmul/fdiv for the negated term.
1851  // (-X * Y) + Z --> Z - (X * Y) [4 commuted variants]
1852  Value *Z;
1853  if (match(&I, m_c_FAdd(m_OneUse(m_c_FMul(m_FNeg(m_Value(X)), m_Value(Y))),
1854                         m_Value(Z)))) {
1855    Value *XY = Builder.CreateFMulFMF(X, Y, &I);
1856    return BinaryOperator::CreateFSubFMF(Z, XY, &I);
1857  }
1858  // (-X / Y) + Z --> Z - (X / Y) [2 commuted variants]
1859  // (X / -Y) + Z --> Z - (X / Y) [2 commuted variants]
1860  if (match(&I, m_c_FAdd(m_OneUse(m_FDiv(m_FNeg(m_Value(X)), m_Value(Y))),
1861                         m_Value(Z))) ||
1862      match(&I, m_c_FAdd(m_OneUse(m_FDiv(m_Value(X), m_FNeg(m_Value(Y)))),
1863                         m_Value(Z)))) {
1864    Value *XY = Builder.CreateFDivFMF(X, Y, &I);
1865    return BinaryOperator::CreateFSubFMF(Z, XY, &I);
1866  }
1867
1868  // Check for (fadd double (sitofp x), y), see if we can merge this into an
1869  // integer add followed by a promotion.
1870  Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1871  if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
1872    Value *LHSIntVal = LHSConv->getOperand(0);
1873    Type *FPType = LHSConv->getType();
1874
1875    // TODO: This check is overly conservative. In many cases known bits
1876    // analysis can tell us that the result of the addition has less significant
1877    // bits than the integer type can hold.
1878    auto IsValidPromotion = [](Type *FTy, Type *ITy) {
1879      Type *FScalarTy = FTy->getScalarType();
1880      Type *IScalarTy = ITy->getScalarType();
1881
1882      // Do we have enough bits in the significand to represent the result of
1883      // the integer addition?
1884      unsigned MaxRepresentableBits =
1885          APFloat::semanticsPrecision(FScalarTy->getFltSemantics());
1886      return IScalarTy->getIntegerBitWidth() <= MaxRepresentableBits;
1887    };
1888
1889    // (fadd double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
1890    // ... if the constant fits in the integer value.  This is useful for things
1891    // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
1892    // requires a constant pool load, and generally allows the add to be better
1893    // instcombined.
1894    if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
1895      if (IsValidPromotion(FPType, LHSIntVal->getType())) {
1896        Constant *CI = ConstantFoldCastOperand(Instruction::FPToSI, CFP,
1897                                               LHSIntVal->getType(), DL);
1898        if (LHSConv->hasOneUse() &&
1899            ConstantFoldCastOperand(Instruction::SIToFP, CI, I.getType(), DL) ==
1900                CFP &&
1901            willNotOverflowSignedAdd(LHSIntVal, CI, I)) {
1902          // Insert the new integer add.
1903          Value *NewAdd = Builder.CreateNSWAdd(LHSIntVal, CI, "addconv");
1904          return new SIToFPInst(NewAdd, I.getType());
1905        }
1906      }
1907
1908    // (fadd double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
1909    if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
1910      Value *RHSIntVal = RHSConv->getOperand(0);
1911      // It's enough to check LHS types only because we require int types to
1912      // be the same for this transform.
1913      if (IsValidPromotion(FPType, LHSIntVal->getType())) {
1914        // Only do this if x/y have the same type, if at least one of them has a
1915        // single use (so we don't increase the number of int->fp conversions),
1916        // and if the integer add will not overflow.
1917        if (LHSIntVal->getType() == RHSIntVal->getType() &&
1918            (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
1919            willNotOverflowSignedAdd(LHSIntVal, RHSIntVal, I)) {
1920          // Insert the new integer add.
1921          Value *NewAdd = Builder.CreateNSWAdd(LHSIntVal, RHSIntVal, "addconv");
1922          return new SIToFPInst(NewAdd, I.getType());
1923        }
1924      }
1925    }
1926  }
1927
1928  // Handle specials cases for FAdd with selects feeding the operation
1929  if (Value *V = SimplifySelectsFeedingBinaryOp(I, LHS, RHS))
1930    return replaceInstUsesWith(I, V);
1931
1932  if (I.hasAllowReassoc() && I.hasNoSignedZeros()) {
1933    if (Instruction *F = factorizeFAddFSub(I, Builder))
1934      return F;
1935
1936    if (Instruction *F = foldSquareSumFP(I))
1937      return F;
1938
1939    // Try to fold fadd into start value of reduction intrinsic.
1940    if (match(&I, m_c_FAdd(m_OneUse(m_Intrinsic<Intrinsic::vector_reduce_fadd>(
1941                               m_AnyZeroFP(), m_Value(X))),
1942                           m_Value(Y)))) {
1943      // fadd (rdx 0.0, X), Y --> rdx Y, X
1944      return replaceInstUsesWith(
1945          I, Builder.CreateIntrinsic(Intrinsic::vector_reduce_fadd,
1946                                     {X->getType()}, {Y, X}, &I));
1947    }
1948    const APFloat *StartC, *C;
1949    if (match(LHS, m_OneUse(m_Intrinsic<Intrinsic::vector_reduce_fadd>(
1950                       m_APFloat(StartC), m_Value(X)))) &&
1951        match(RHS, m_APFloat(C))) {
1952      // fadd (rdx StartC, X), C --> rdx (C + StartC), X
1953      Constant *NewStartC = ConstantFP::get(I.getType(), *C + *StartC);
1954      return replaceInstUsesWith(
1955          I, Builder.CreateIntrinsic(Intrinsic::vector_reduce_fadd,
1956                                     {X->getType()}, {NewStartC, X}, &I));
1957    }
1958
1959    // (X * MulC) + X --> X * (MulC + 1.0)
1960    Constant *MulC;
1961    if (match(&I, m_c_FAdd(m_FMul(m_Value(X), m_ImmConstant(MulC)),
1962                           m_Deferred(X)))) {
1963      if (Constant *NewMulC = ConstantFoldBinaryOpOperands(
1964              Instruction::FAdd, MulC, ConstantFP::get(I.getType(), 1.0), DL))
1965        return BinaryOperator::CreateFMulFMF(X, NewMulC, &I);
1966    }
1967
1968    // (-X - Y) + (X + Z) --> Z - Y
1969    if (match(&I, m_c_FAdd(m_FSub(m_FNeg(m_Value(X)), m_Value(Y)),
1970                           m_c_FAdd(m_Deferred(X), m_Value(Z)))))
1971      return BinaryOperator::CreateFSubFMF(Z, Y, &I);
1972
1973    if (Value *V = FAddCombine(Builder).simplify(&I))
1974      return replaceInstUsesWith(I, V);
1975  }
1976
1977  // minumum(X, Y) + maximum(X, Y) => X + Y.
1978  if (match(&I,
1979            m_c_FAdd(m_Intrinsic<Intrinsic::maximum>(m_Value(X), m_Value(Y)),
1980                     m_c_Intrinsic<Intrinsic::minimum>(m_Deferred(X),
1981                                                       m_Deferred(Y))))) {
1982    BinaryOperator *Result = BinaryOperator::CreateFAddFMF(X, Y, &I);
1983    // We cannot preserve ninf if nnan flag is not set.
1984    // If X is NaN and Y is Inf then in original program we had NaN + NaN,
1985    // while in optimized version NaN + Inf and this is a poison with ninf flag.
1986    if (!Result->hasNoNaNs())
1987      Result->setHasNoInfs(false);
1988    return Result;
1989  }
1990
1991  return nullptr;
1992}
1993
1994/// Optimize pointer differences into the same array into a size.  Consider:
1995///  &A[10] - &A[0]: we should compile this to "10".  LHS/RHS are the pointer
1996/// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
1997Value *InstCombinerImpl::OptimizePointerDifference(Value *LHS, Value *RHS,
1998                                                   Type *Ty, bool IsNUW) {
1999  // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
2000  // this.
2001  bool Swapped = false;
2002  GEPOperator *GEP1 = nullptr, *GEP2 = nullptr;
2003  if (!isa<GEPOperator>(LHS) && isa<GEPOperator>(RHS)) {
2004    std::swap(LHS, RHS);
2005    Swapped = true;
2006  }
2007
2008  // Require at least one GEP with a common base pointer on both sides.
2009  if (auto *LHSGEP = dyn_cast<GEPOperator>(LHS)) {
2010    // (gep X, ...) - X
2011    if (LHSGEP->getOperand(0)->stripPointerCasts() ==
2012        RHS->stripPointerCasts()) {
2013      GEP1 = LHSGEP;
2014    } else if (auto *RHSGEP = dyn_cast<GEPOperator>(RHS)) {
2015      // (gep X, ...) - (gep X, ...)
2016      if (LHSGEP->getOperand(0)->stripPointerCasts() ==
2017          RHSGEP->getOperand(0)->stripPointerCasts()) {
2018        GEP1 = LHSGEP;
2019        GEP2 = RHSGEP;
2020      }
2021    }
2022  }
2023
2024  if (!GEP1)
2025    return nullptr;
2026
2027  if (GEP2) {
2028    // (gep X, ...) - (gep X, ...)
2029    //
2030    // Avoid duplicating the arithmetic if there are more than one non-constant
2031    // indices between the two GEPs and either GEP has a non-constant index and
2032    // multiple users. If zero non-constant index, the result is a constant and
2033    // there is no duplication. If one non-constant index, the result is an add
2034    // or sub with a constant, which is no larger than the original code, and
2035    // there's no duplicated arithmetic, even if either GEP has multiple
2036    // users. If more than one non-constant indices combined, as long as the GEP
2037    // with at least one non-constant index doesn't have multiple users, there
2038    // is no duplication.
2039    unsigned NumNonConstantIndices1 = GEP1->countNonConstantIndices();
2040    unsigned NumNonConstantIndices2 = GEP2->countNonConstantIndices();
2041    if (NumNonConstantIndices1 + NumNonConstantIndices2 > 1 &&
2042        ((NumNonConstantIndices1 > 0 && !GEP1->hasOneUse()) ||
2043         (NumNonConstantIndices2 > 0 && !GEP2->hasOneUse()))) {
2044      return nullptr;
2045    }
2046  }
2047
2048  // Emit the offset of the GEP and an intptr_t.
2049  Value *Result = EmitGEPOffset(GEP1);
2050
2051  // If this is a single inbounds GEP and the original sub was nuw,
2052  // then the final multiplication is also nuw.
2053  if (auto *I = dyn_cast<Instruction>(Result))
2054    if (IsNUW && !GEP2 && !Swapped && GEP1->isInBounds() &&
2055        I->getOpcode() == Instruction::Mul)
2056      I->setHasNoUnsignedWrap();
2057
2058  // If we have a 2nd GEP of the same base pointer, subtract the offsets.
2059  // If both GEPs are inbounds, then the subtract does not have signed overflow.
2060  if (GEP2) {
2061    Value *Offset = EmitGEPOffset(GEP2);
2062    Result = Builder.CreateSub(Result, Offset, "gepdiff", /* NUW */ false,
2063                               GEP1->isInBounds() && GEP2->isInBounds());
2064  }
2065
2066  // If we have p - gep(p, ...)  then we have to negate the result.
2067  if (Swapped)
2068    Result = Builder.CreateNeg(Result, "diff.neg");
2069
2070  return Builder.CreateIntCast(Result, Ty, true);
2071}
2072
2073static Instruction *foldSubOfMinMax(BinaryOperator &I,
2074                                    InstCombiner::BuilderTy &Builder) {
2075  Value *Op0 = I.getOperand(0);
2076  Value *Op1 = I.getOperand(1);
2077  Type *Ty = I.getType();
2078  auto *MinMax = dyn_cast<MinMaxIntrinsic>(Op1);
2079  if (!MinMax)
2080    return nullptr;
2081
2082  // sub(add(X,Y), s/umin(X,Y)) --> s/umax(X,Y)
2083  // sub(add(X,Y), s/umax(X,Y)) --> s/umin(X,Y)
2084  Value *X = MinMax->getLHS();
2085  Value *Y = MinMax->getRHS();
2086  if (match(Op0, m_c_Add(m_Specific(X), m_Specific(Y))) &&
2087      (Op0->hasOneUse() || Op1->hasOneUse())) {
2088    Intrinsic::ID InvID = getInverseMinMaxIntrinsic(MinMax->getIntrinsicID());
2089    Function *F = Intrinsic::getDeclaration(I.getModule(), InvID, Ty);
2090    return CallInst::Create(F, {X, Y});
2091  }
2092
2093  // sub(add(X,Y),umin(Y,Z)) --> add(X,usub.sat(Y,Z))
2094  // sub(add(X,Z),umin(Y,Z)) --> add(X,usub.sat(Z,Y))
2095  Value *Z;
2096  if (match(Op1, m_OneUse(m_UMin(m_Value(Y), m_Value(Z))))) {
2097    if (match(Op0, m_OneUse(m_c_Add(m_Specific(Y), m_Value(X))))) {
2098      Value *USub = Builder.CreateIntrinsic(Intrinsic::usub_sat, Ty, {Y, Z});
2099      return BinaryOperator::CreateAdd(X, USub);
2100    }
2101    if (match(Op0, m_OneUse(m_c_Add(m_Specific(Z), m_Value(X))))) {
2102      Value *USub = Builder.CreateIntrinsic(Intrinsic::usub_sat, Ty, {Z, Y});
2103      return BinaryOperator::CreateAdd(X, USub);
2104    }
2105  }
2106
2107  // sub Op0, smin((sub nsw Op0, Z), 0) --> smax Op0, Z
2108  // sub Op0, smax((sub nsw Op0, Z), 0) --> smin Op0, Z
2109  if (MinMax->isSigned() && match(Y, m_ZeroInt()) &&
2110      match(X, m_NSWSub(m_Specific(Op0), m_Value(Z)))) {
2111    Intrinsic::ID InvID = getInverseMinMaxIntrinsic(MinMax->getIntrinsicID());
2112    Function *F = Intrinsic::getDeclaration(I.getModule(), InvID, Ty);
2113    return CallInst::Create(F, {Op0, Z});
2114  }
2115
2116  return nullptr;
2117}
2118
2119Instruction *InstCombinerImpl::visitSub(BinaryOperator &I) {
2120  if (Value *V = simplifySubInst(I.getOperand(0), I.getOperand(1),
2121                                 I.hasNoSignedWrap(), I.hasNoUnsignedWrap(),
2122                                 SQ.getWithInstruction(&I)))
2123    return replaceInstUsesWith(I, V);
2124
2125  if (Instruction *X = foldVectorBinop(I))
2126    return X;
2127
2128  if (Instruction *Phi = foldBinopWithPhiOperands(I))
2129    return Phi;
2130
2131  Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2132
2133  // If this is a 'B = x-(-A)', change to B = x+A.
2134  // We deal with this without involving Negator to preserve NSW flag.
2135  if (Value *V = dyn_castNegVal(Op1)) {
2136    BinaryOperator *Res = BinaryOperator::CreateAdd(Op0, V);
2137
2138    if (const auto *BO = dyn_cast<BinaryOperator>(Op1)) {
2139      assert(BO->getOpcode() == Instruction::Sub &&
2140             "Expected a subtraction operator!");
2141      if (BO->hasNoSignedWrap() && I.hasNoSignedWrap())
2142        Res->setHasNoSignedWrap(true);
2143    } else {
2144      if (cast<Constant>(Op1)->isNotMinSignedValue() && I.hasNoSignedWrap())
2145        Res->setHasNoSignedWrap(true);
2146    }
2147
2148    return Res;
2149  }
2150
2151  // Try this before Negator to preserve NSW flag.
2152  if (Instruction *R = factorizeMathWithShlOps(I, Builder))
2153    return R;
2154
2155  Constant *C;
2156  if (match(Op0, m_ImmConstant(C))) {
2157    Value *X;
2158    Constant *C2;
2159
2160    // C-(X+C2) --> (C-C2)-X
2161    if (match(Op1, m_Add(m_Value(X), m_ImmConstant(C2)))) {
2162      // C-C2 never overflow, and C-(X+C2), (X+C2) has NSW/NUW
2163      // => (C-C2)-X can have NSW/NUW
2164      bool WillNotSOV = willNotOverflowSignedSub(C, C2, I);
2165      BinaryOperator *Res =
2166          BinaryOperator::CreateSub(ConstantExpr::getSub(C, C2), X);
2167      auto *OBO1 = cast<OverflowingBinaryOperator>(Op1);
2168      Res->setHasNoSignedWrap(I.hasNoSignedWrap() && OBO1->hasNoSignedWrap() &&
2169                              WillNotSOV);
2170      Res->setHasNoUnsignedWrap(I.hasNoUnsignedWrap() &&
2171                                OBO1->hasNoUnsignedWrap());
2172      return Res;
2173    }
2174  }
2175
2176  auto TryToNarrowDeduceFlags = [this, &I, &Op0, &Op1]() -> Instruction * {
2177    if (Instruction *Ext = narrowMathIfNoOverflow(I))
2178      return Ext;
2179
2180    bool Changed = false;
2181    if (!I.hasNoSignedWrap() && willNotOverflowSignedSub(Op0, Op1, I)) {
2182      Changed = true;
2183      I.setHasNoSignedWrap(true);
2184    }
2185    if (!I.hasNoUnsignedWrap() && willNotOverflowUnsignedSub(Op0, Op1, I)) {
2186      Changed = true;
2187      I.setHasNoUnsignedWrap(true);
2188    }
2189
2190    return Changed ? &I : nullptr;
2191  };
2192
2193  // First, let's try to interpret `sub a, b` as `add a, (sub 0, b)`,
2194  // and let's try to sink `(sub 0, b)` into `b` itself. But only if this isn't
2195  // a pure negation used by a select that looks like abs/nabs.
2196  bool IsNegation = match(Op0, m_ZeroInt());
2197  if (!IsNegation || none_of(I.users(), [&I, Op1](const User *U) {
2198        const Instruction *UI = dyn_cast<Instruction>(U);
2199        if (!UI)
2200          return false;
2201        return match(UI,
2202                     m_Select(m_Value(), m_Specific(Op1), m_Specific(&I))) ||
2203               match(UI, m_Select(m_Value(), m_Specific(&I), m_Specific(Op1)));
2204      })) {
2205    if (Value *NegOp1 = Negator::Negate(IsNegation, /* IsNSW */ IsNegation &&
2206                                                        I.hasNoSignedWrap(),
2207                                        Op1, *this))
2208      return BinaryOperator::CreateAdd(NegOp1, Op0);
2209  }
2210  if (IsNegation)
2211    return TryToNarrowDeduceFlags(); // Should have been handled in Negator!
2212
2213  // (A*B)-(A*C) -> A*(B-C) etc
2214  if (Value *V = foldUsingDistributiveLaws(I))
2215    return replaceInstUsesWith(I, V);
2216
2217  if (I.getType()->isIntOrIntVectorTy(1))
2218    return BinaryOperator::CreateXor(Op0, Op1);
2219
2220  // Replace (-1 - A) with (~A).
2221  if (match(Op0, m_AllOnes()))
2222    return BinaryOperator::CreateNot(Op1);
2223
2224  // (X + -1) - Y --> ~Y + X
2225  Value *X, *Y;
2226  if (match(Op0, m_OneUse(m_Add(m_Value(X), m_AllOnes()))))
2227    return BinaryOperator::CreateAdd(Builder.CreateNot(Op1), X);
2228
2229  // Reassociate sub/add sequences to create more add instructions and
2230  // reduce dependency chains:
2231  // ((X - Y) + Z) - Op1 --> (X + Z) - (Y + Op1)
2232  Value *Z;
2233  if (match(Op0, m_OneUse(m_c_Add(m_OneUse(m_Sub(m_Value(X), m_Value(Y))),
2234                                  m_Value(Z))))) {
2235    Value *XZ = Builder.CreateAdd(X, Z);
2236    Value *YW = Builder.CreateAdd(Y, Op1);
2237    return BinaryOperator::CreateSub(XZ, YW);
2238  }
2239
2240  // ((X - Y) - Op1)  -->  X - (Y + Op1)
2241  if (match(Op0, m_OneUse(m_Sub(m_Value(X), m_Value(Y))))) {
2242    OverflowingBinaryOperator *LHSSub = cast<OverflowingBinaryOperator>(Op0);
2243    bool HasNUW = I.hasNoUnsignedWrap() && LHSSub->hasNoUnsignedWrap();
2244    bool HasNSW = HasNUW && I.hasNoSignedWrap() && LHSSub->hasNoSignedWrap();
2245    Value *Add = Builder.CreateAdd(Y, Op1, "", /* HasNUW */ HasNUW,
2246                                   /* HasNSW */ HasNSW);
2247    BinaryOperator *Sub = BinaryOperator::CreateSub(X, Add);
2248    Sub->setHasNoUnsignedWrap(HasNUW);
2249    Sub->setHasNoSignedWrap(HasNSW);
2250    return Sub;
2251  }
2252
2253  {
2254    // (X + Z) - (Y + Z) --> (X - Y)
2255    // This is done in other passes, but we want to be able to consume this
2256    // pattern in InstCombine so we can generate it without creating infinite
2257    // loops.
2258    if (match(Op0, m_Add(m_Value(X), m_Value(Z))) &&
2259        match(Op1, m_c_Add(m_Value(Y), m_Specific(Z))))
2260      return BinaryOperator::CreateSub(X, Y);
2261
2262    // (X + C0) - (Y + C1) --> (X - Y) + (C0 - C1)
2263    Constant *CX, *CY;
2264    if (match(Op0, m_OneUse(m_Add(m_Value(X), m_ImmConstant(CX)))) &&
2265        match(Op1, m_OneUse(m_Add(m_Value(Y), m_ImmConstant(CY))))) {
2266      Value *OpsSub = Builder.CreateSub(X, Y);
2267      Constant *ConstsSub = ConstantExpr::getSub(CX, CY);
2268      return BinaryOperator::CreateAdd(OpsSub, ConstsSub);
2269    }
2270  }
2271
2272  // (~X) - (~Y) --> Y - X
2273  {
2274    // Need to ensure we can consume at least one of the `not` instructions,
2275    // otherwise this can inf loop.
2276    bool ConsumesOp0, ConsumesOp1;
2277    if (isFreeToInvert(Op0, Op0->hasOneUse(), ConsumesOp0) &&
2278        isFreeToInvert(Op1, Op1->hasOneUse(), ConsumesOp1) &&
2279        (ConsumesOp0 || ConsumesOp1)) {
2280      Value *NotOp0 = getFreelyInverted(Op0, Op0->hasOneUse(), &Builder);
2281      Value *NotOp1 = getFreelyInverted(Op1, Op1->hasOneUse(), &Builder);
2282      assert(NotOp0 != nullptr && NotOp1 != nullptr &&
2283             "isFreeToInvert desynced with getFreelyInverted");
2284      return BinaryOperator::CreateSub(NotOp1, NotOp0);
2285    }
2286  }
2287
2288  auto m_AddRdx = [](Value *&Vec) {
2289    return m_OneUse(m_Intrinsic<Intrinsic::vector_reduce_add>(m_Value(Vec)));
2290  };
2291  Value *V0, *V1;
2292  if (match(Op0, m_AddRdx(V0)) && match(Op1, m_AddRdx(V1)) &&
2293      V0->getType() == V1->getType()) {
2294    // Difference of sums is sum of differences:
2295    // add_rdx(V0) - add_rdx(V1) --> add_rdx(V0 - V1)
2296    Value *Sub = Builder.CreateSub(V0, V1);
2297    Value *Rdx = Builder.CreateIntrinsic(Intrinsic::vector_reduce_add,
2298                                         {Sub->getType()}, {Sub});
2299    return replaceInstUsesWith(I, Rdx);
2300  }
2301
2302  if (Constant *C = dyn_cast<Constant>(Op0)) {
2303    Value *X;
2304    if (match(Op1, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
2305      // C - (zext bool) --> bool ? C - 1 : C
2306      return SelectInst::Create(X, InstCombiner::SubOne(C), C);
2307    if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
2308      // C - (sext bool) --> bool ? C + 1 : C
2309      return SelectInst::Create(X, InstCombiner::AddOne(C), C);
2310
2311    // C - ~X == X + (1+C)
2312    if (match(Op1, m_Not(m_Value(X))))
2313      return BinaryOperator::CreateAdd(X, InstCombiner::AddOne(C));
2314
2315    // Try to fold constant sub into select arguments.
2316    if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2317      if (Instruction *R = FoldOpIntoSelect(I, SI))
2318        return R;
2319
2320    // Try to fold constant sub into PHI values.
2321    if (PHINode *PN = dyn_cast<PHINode>(Op1))
2322      if (Instruction *R = foldOpIntoPhi(I, PN))
2323        return R;
2324
2325    Constant *C2;
2326
2327    // C-(C2-X) --> X+(C-C2)
2328    if (match(Op1, m_Sub(m_ImmConstant(C2), m_Value(X))))
2329      return BinaryOperator::CreateAdd(X, ConstantExpr::getSub(C, C2));
2330  }
2331
2332  const APInt *Op0C;
2333  if (match(Op0, m_APInt(Op0C))) {
2334    if (Op0C->isMask()) {
2335      // Turn this into a xor if LHS is 2^n-1 and the remaining bits are known
2336      // zero.
2337      KnownBits RHSKnown = computeKnownBits(Op1, 0, &I);
2338      if ((*Op0C | RHSKnown.Zero).isAllOnes())
2339        return BinaryOperator::CreateXor(Op1, Op0);
2340    }
2341
2342    // C - ((C3 -nuw X) & C2) --> (C - (C2 & C3)) + (X & C2) when:
2343    // (C3 - ((C2 & C3) - 1)) is pow2
2344    // ((C2 + C3) & ((C2 & C3) - 1)) == ((C2 & C3) - 1)
2345    // C2 is negative pow2 || sub nuw
2346    const APInt *C2, *C3;
2347    BinaryOperator *InnerSub;
2348    if (match(Op1, m_OneUse(m_And(m_BinOp(InnerSub), m_APInt(C2)))) &&
2349        match(InnerSub, m_Sub(m_APInt(C3), m_Value(X))) &&
2350        (InnerSub->hasNoUnsignedWrap() || C2->isNegatedPowerOf2())) {
2351      APInt C2AndC3 = *C2 & *C3;
2352      APInt C2AndC3Minus1 = C2AndC3 - 1;
2353      APInt C2AddC3 = *C2 + *C3;
2354      if ((*C3 - C2AndC3Minus1).isPowerOf2() &&
2355          C2AndC3Minus1.isSubsetOf(C2AddC3)) {
2356        Value *And = Builder.CreateAnd(X, ConstantInt::get(I.getType(), *C2));
2357        return BinaryOperator::CreateAdd(
2358            And, ConstantInt::get(I.getType(), *Op0C - C2AndC3));
2359      }
2360    }
2361  }
2362
2363  {
2364    Value *Y;
2365    // X-(X+Y) == -Y    X-(Y+X) == -Y
2366    if (match(Op1, m_c_Add(m_Specific(Op0), m_Value(Y))))
2367      return BinaryOperator::CreateNeg(Y);
2368
2369    // (X-Y)-X == -Y
2370    if (match(Op0, m_Sub(m_Specific(Op1), m_Value(Y))))
2371      return BinaryOperator::CreateNeg(Y);
2372  }
2373
2374  // (sub (or A, B) (and A, B)) --> (xor A, B)
2375  {
2376    Value *A, *B;
2377    if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
2378        match(Op0, m_c_Or(m_Specific(A), m_Specific(B))))
2379      return BinaryOperator::CreateXor(A, B);
2380  }
2381
2382  // (sub (add A, B) (or A, B)) --> (and A, B)
2383  {
2384    Value *A, *B;
2385    if (match(Op0, m_Add(m_Value(A), m_Value(B))) &&
2386        match(Op1, m_c_Or(m_Specific(A), m_Specific(B))))
2387      return BinaryOperator::CreateAnd(A, B);
2388  }
2389
2390  // (sub (add A, B) (and A, B)) --> (or A, B)
2391  {
2392    Value *A, *B;
2393    if (match(Op0, m_Add(m_Value(A), m_Value(B))) &&
2394        match(Op1, m_c_And(m_Specific(A), m_Specific(B))))
2395      return BinaryOperator::CreateOr(A, B);
2396  }
2397
2398  // (sub (and A, B) (or A, B)) --> neg (xor A, B)
2399  {
2400    Value *A, *B;
2401    if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
2402        match(Op1, m_c_Or(m_Specific(A), m_Specific(B))) &&
2403        (Op0->hasOneUse() || Op1->hasOneUse()))
2404      return BinaryOperator::CreateNeg(Builder.CreateXor(A, B));
2405  }
2406
2407  // (sub (or A, B), (xor A, B)) --> (and A, B)
2408  {
2409    Value *A, *B;
2410    if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
2411        match(Op0, m_c_Or(m_Specific(A), m_Specific(B))))
2412      return BinaryOperator::CreateAnd(A, B);
2413  }
2414
2415  // (sub (xor A, B) (or A, B)) --> neg (and A, B)
2416  {
2417    Value *A, *B;
2418    if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
2419        match(Op1, m_c_Or(m_Specific(A), m_Specific(B))) &&
2420        (Op0->hasOneUse() || Op1->hasOneUse()))
2421      return BinaryOperator::CreateNeg(Builder.CreateAnd(A, B));
2422  }
2423
2424  {
2425    Value *Y;
2426    // ((X | Y) - X) --> (~X & Y)
2427    if (match(Op0, m_OneUse(m_c_Or(m_Value(Y), m_Specific(Op1)))))
2428      return BinaryOperator::CreateAnd(
2429          Y, Builder.CreateNot(Op1, Op1->getName() + ".not"));
2430  }
2431
2432  {
2433    // (sub (and Op1, (neg X)), Op1) --> neg (and Op1, (add X, -1))
2434    Value *X;
2435    if (match(Op0, m_OneUse(m_c_And(m_Specific(Op1),
2436                                    m_OneUse(m_Neg(m_Value(X))))))) {
2437      return BinaryOperator::CreateNeg(Builder.CreateAnd(
2438          Op1, Builder.CreateAdd(X, Constant::getAllOnesValue(I.getType()))));
2439    }
2440  }
2441
2442  {
2443    // (sub (and Op1, C), Op1) --> neg (and Op1, ~C)
2444    Constant *C;
2445    if (match(Op0, m_OneUse(m_And(m_Specific(Op1), m_Constant(C))))) {
2446      return BinaryOperator::CreateNeg(
2447          Builder.CreateAnd(Op1, Builder.CreateNot(C)));
2448    }
2449  }
2450
2451  if (Instruction *R = tryFoldInstWithCtpopWithNot(&I))
2452    return R;
2453
2454  if (Instruction *R = foldSubOfMinMax(I, Builder))
2455    return R;
2456
2457  {
2458    // If we have a subtraction between some value and a select between
2459    // said value and something else, sink subtraction into select hands, i.e.:
2460    //   sub (select %Cond, %TrueVal, %FalseVal), %Op1
2461    //     ->
2462    //   select %Cond, (sub %TrueVal, %Op1), (sub %FalseVal, %Op1)
2463    //  or
2464    //   sub %Op0, (select %Cond, %TrueVal, %FalseVal)
2465    //     ->
2466    //   select %Cond, (sub %Op0, %TrueVal), (sub %Op0, %FalseVal)
2467    // This will result in select between new subtraction and 0.
2468    auto SinkSubIntoSelect =
2469        [Ty = I.getType()](Value *Select, Value *OtherHandOfSub,
2470                           auto SubBuilder) -> Instruction * {
2471      Value *Cond, *TrueVal, *FalseVal;
2472      if (!match(Select, m_OneUse(m_Select(m_Value(Cond), m_Value(TrueVal),
2473                                           m_Value(FalseVal)))))
2474        return nullptr;
2475      if (OtherHandOfSub != TrueVal && OtherHandOfSub != FalseVal)
2476        return nullptr;
2477      // While it is really tempting to just create two subtractions and let
2478      // InstCombine fold one of those to 0, it isn't possible to do so
2479      // because of worklist visitation order. So ugly it is.
2480      bool OtherHandOfSubIsTrueVal = OtherHandOfSub == TrueVal;
2481      Value *NewSub = SubBuilder(OtherHandOfSubIsTrueVal ? FalseVal : TrueVal);
2482      Constant *Zero = Constant::getNullValue(Ty);
2483      SelectInst *NewSel =
2484          SelectInst::Create(Cond, OtherHandOfSubIsTrueVal ? Zero : NewSub,
2485                             OtherHandOfSubIsTrueVal ? NewSub : Zero);
2486      // Preserve prof metadata if any.
2487      NewSel->copyMetadata(cast<Instruction>(*Select));
2488      return NewSel;
2489    };
2490    if (Instruction *NewSel = SinkSubIntoSelect(
2491            /*Select=*/Op0, /*OtherHandOfSub=*/Op1,
2492            [Builder = &Builder, Op1](Value *OtherHandOfSelect) {
2493              return Builder->CreateSub(OtherHandOfSelect,
2494                                        /*OtherHandOfSub=*/Op1);
2495            }))
2496      return NewSel;
2497    if (Instruction *NewSel = SinkSubIntoSelect(
2498            /*Select=*/Op1, /*OtherHandOfSub=*/Op0,
2499            [Builder = &Builder, Op0](Value *OtherHandOfSelect) {
2500              return Builder->CreateSub(/*OtherHandOfSub=*/Op0,
2501                                        OtherHandOfSelect);
2502            }))
2503      return NewSel;
2504  }
2505
2506  // (X - (X & Y))   -->   (X & ~Y)
2507  if (match(Op1, m_c_And(m_Specific(Op0), m_Value(Y))) &&
2508      (Op1->hasOneUse() || isa<Constant>(Y)))
2509    return BinaryOperator::CreateAnd(
2510        Op0, Builder.CreateNot(Y, Y->getName() + ".not"));
2511
2512  // ~X - Min/Max(~X, Y) -> ~Min/Max(X, ~Y) - X
2513  // ~X - Min/Max(Y, ~X) -> ~Min/Max(X, ~Y) - X
2514  // Min/Max(~X, Y) - ~X -> X - ~Min/Max(X, ~Y)
2515  // Min/Max(Y, ~X) - ~X -> X - ~Min/Max(X, ~Y)
2516  // As long as Y is freely invertible, this will be neutral or a win.
2517  // Note: We don't generate the inverse max/min, just create the 'not' of
2518  // it and let other folds do the rest.
2519  if (match(Op0, m_Not(m_Value(X))) &&
2520      match(Op1, m_c_MaxOrMin(m_Specific(Op0), m_Value(Y))) &&
2521      !Op0->hasNUsesOrMore(3) && isFreeToInvert(Y, Y->hasOneUse())) {
2522    Value *Not = Builder.CreateNot(Op1);
2523    return BinaryOperator::CreateSub(Not, X);
2524  }
2525  if (match(Op1, m_Not(m_Value(X))) &&
2526      match(Op0, m_c_MaxOrMin(m_Specific(Op1), m_Value(Y))) &&
2527      !Op1->hasNUsesOrMore(3) && isFreeToInvert(Y, Y->hasOneUse())) {
2528    Value *Not = Builder.CreateNot(Op0);
2529    return BinaryOperator::CreateSub(X, Not);
2530  }
2531
2532  // Optimize pointer differences into the same array into a size.  Consider:
2533  //  &A[10] - &A[0]: we should compile this to "10".
2534  Value *LHSOp, *RHSOp;
2535  if (match(Op0, m_PtrToInt(m_Value(LHSOp))) &&
2536      match(Op1, m_PtrToInt(m_Value(RHSOp))))
2537    if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType(),
2538                                               I.hasNoUnsignedWrap()))
2539      return replaceInstUsesWith(I, Res);
2540
2541  // trunc(p)-trunc(q) -> trunc(p-q)
2542  if (match(Op0, m_Trunc(m_PtrToInt(m_Value(LHSOp)))) &&
2543      match(Op1, m_Trunc(m_PtrToInt(m_Value(RHSOp)))))
2544    if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType(),
2545                                               /* IsNUW */ false))
2546      return replaceInstUsesWith(I, Res);
2547
2548  // Canonicalize a shifty way to code absolute value to the common pattern.
2549  // There are 2 potential commuted variants.
2550  // We're relying on the fact that we only do this transform when the shift has
2551  // exactly 2 uses and the xor has exactly 1 use (otherwise, we might increase
2552  // instructions).
2553  Value *A;
2554  const APInt *ShAmt;
2555  Type *Ty = I.getType();
2556  unsigned BitWidth = Ty->getScalarSizeInBits();
2557  if (match(Op1, m_AShr(m_Value(A), m_APInt(ShAmt))) &&
2558      Op1->hasNUses(2) && *ShAmt == BitWidth - 1 &&
2559      match(Op0, m_OneUse(m_c_Xor(m_Specific(A), m_Specific(Op1))))) {
2560    // B = ashr i32 A, 31 ; smear the sign bit
2561    // sub (xor A, B), B  ; flip bits if negative and subtract -1 (add 1)
2562    // --> (A < 0) ? -A : A
2563    Value *IsNeg = Builder.CreateIsNeg(A);
2564    // Copy the nuw/nsw flags from the sub to the negate.
2565    Value *NegA = Builder.CreateNeg(A, "", I.hasNoUnsignedWrap(),
2566                                    I.hasNoSignedWrap());
2567    return SelectInst::Create(IsNeg, NegA, A);
2568  }
2569
2570  // If we are subtracting a low-bit masked subset of some value from an add
2571  // of that same value with no low bits changed, that is clearing some low bits
2572  // of the sum:
2573  // sub (X + AddC), (X & AndC) --> and (X + AddC), ~AndC
2574  const APInt *AddC, *AndC;
2575  if (match(Op0, m_Add(m_Value(X), m_APInt(AddC))) &&
2576      match(Op1, m_And(m_Specific(X), m_APInt(AndC)))) {
2577    unsigned Cttz = AddC->countr_zero();
2578    APInt HighMask(APInt::getHighBitsSet(BitWidth, BitWidth - Cttz));
2579    if ((HighMask & *AndC).isZero())
2580      return BinaryOperator::CreateAnd(Op0, ConstantInt::get(Ty, ~(*AndC)));
2581  }
2582
2583  if (Instruction *V =
2584          canonicalizeCondSignextOfHighBitExtractToSignextHighBitExtract(I))
2585    return V;
2586
2587  // X - usub.sat(X, Y) => umin(X, Y)
2588  if (match(Op1, m_OneUse(m_Intrinsic<Intrinsic::usub_sat>(m_Specific(Op0),
2589                                                           m_Value(Y)))))
2590    return replaceInstUsesWith(
2591        I, Builder.CreateIntrinsic(Intrinsic::umin, {I.getType()}, {Op0, Y}));
2592
2593  // umax(X, Op1) - Op1 --> usub.sat(X, Op1)
2594  // TODO: The one-use restriction is not strictly necessary, but it may
2595  //       require improving other pattern matching and/or codegen.
2596  if (match(Op0, m_OneUse(m_c_UMax(m_Value(X), m_Specific(Op1)))))
2597    return replaceInstUsesWith(
2598        I, Builder.CreateIntrinsic(Intrinsic::usub_sat, {Ty}, {X, Op1}));
2599
2600  // Op0 - umin(X, Op0) --> usub.sat(Op0, X)
2601  if (match(Op1, m_OneUse(m_c_UMin(m_Value(X), m_Specific(Op0)))))
2602    return replaceInstUsesWith(
2603        I, Builder.CreateIntrinsic(Intrinsic::usub_sat, {Ty}, {Op0, X}));
2604
2605  // Op0 - umax(X, Op0) --> 0 - usub.sat(X, Op0)
2606  if (match(Op1, m_OneUse(m_c_UMax(m_Value(X), m_Specific(Op0))))) {
2607    Value *USub = Builder.CreateIntrinsic(Intrinsic::usub_sat, {Ty}, {X, Op0});
2608    return BinaryOperator::CreateNeg(USub);
2609  }
2610
2611  // umin(X, Op1) - Op1 --> 0 - usub.sat(Op1, X)
2612  if (match(Op0, m_OneUse(m_c_UMin(m_Value(X), m_Specific(Op1))))) {
2613    Value *USub = Builder.CreateIntrinsic(Intrinsic::usub_sat, {Ty}, {Op1, X});
2614    return BinaryOperator::CreateNeg(USub);
2615  }
2616
2617  // C - ctpop(X) => ctpop(~X) if C is bitwidth
2618  if (match(Op0, m_SpecificInt(BitWidth)) &&
2619      match(Op1, m_OneUse(m_Intrinsic<Intrinsic::ctpop>(m_Value(X)))))
2620    return replaceInstUsesWith(
2621        I, Builder.CreateIntrinsic(Intrinsic::ctpop, {I.getType()},
2622                                   {Builder.CreateNot(X)}));
2623
2624  // Reduce multiplies for difference-of-squares by factoring:
2625  // (X * X) - (Y * Y) --> (X + Y) * (X - Y)
2626  if (match(Op0, m_OneUse(m_Mul(m_Value(X), m_Deferred(X)))) &&
2627      match(Op1, m_OneUse(m_Mul(m_Value(Y), m_Deferred(Y))))) {
2628    auto *OBO0 = cast<OverflowingBinaryOperator>(Op0);
2629    auto *OBO1 = cast<OverflowingBinaryOperator>(Op1);
2630    bool PropagateNSW = I.hasNoSignedWrap() && OBO0->hasNoSignedWrap() &&
2631                        OBO1->hasNoSignedWrap() && BitWidth > 2;
2632    bool PropagateNUW = I.hasNoUnsignedWrap() && OBO0->hasNoUnsignedWrap() &&
2633                        OBO1->hasNoUnsignedWrap() && BitWidth > 1;
2634    Value *Add = Builder.CreateAdd(X, Y, "add", PropagateNUW, PropagateNSW);
2635    Value *Sub = Builder.CreateSub(X, Y, "sub", PropagateNUW, PropagateNSW);
2636    Value *Mul = Builder.CreateMul(Add, Sub, "", PropagateNUW, PropagateNSW);
2637    return replaceInstUsesWith(I, Mul);
2638  }
2639
2640  // max(X,Y) nsw/nuw - min(X,Y) --> abs(X nsw - Y)
2641  if (match(Op0, m_OneUse(m_c_SMax(m_Value(X), m_Value(Y)))) &&
2642      match(Op1, m_OneUse(m_c_SMin(m_Specific(X), m_Specific(Y))))) {
2643    if (I.hasNoUnsignedWrap() || I.hasNoSignedWrap()) {
2644      Value *Sub =
2645          Builder.CreateSub(X, Y, "sub", /*HasNUW=*/false, /*HasNSW=*/true);
2646      Value *Call =
2647          Builder.CreateBinaryIntrinsic(Intrinsic::abs, Sub, Builder.getTrue());
2648      return replaceInstUsesWith(I, Call);
2649    }
2650  }
2651
2652  if (Instruction *Res = foldBinOpOfSelectAndCastOfSelectCondition(I))
2653    return Res;
2654
2655  return TryToNarrowDeduceFlags();
2656}
2657
2658/// This eliminates floating-point negation in either 'fneg(X)' or
2659/// 'fsub(-0.0, X)' form by combining into a constant operand.
2660static Instruction *foldFNegIntoConstant(Instruction &I, const DataLayout &DL) {
2661  // This is limited with one-use because fneg is assumed better for
2662  // reassociation and cheaper in codegen than fmul/fdiv.
2663  // TODO: Should the m_OneUse restriction be removed?
2664  Instruction *FNegOp;
2665  if (!match(&I, m_FNeg(m_OneUse(m_Instruction(FNegOp)))))
2666    return nullptr;
2667
2668  Value *X;
2669  Constant *C;
2670
2671  // Fold negation into constant operand.
2672  // -(X * C) --> X * (-C)
2673  if (match(FNegOp, m_FMul(m_Value(X), m_Constant(C))))
2674    if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL))
2675      return BinaryOperator::CreateFMulFMF(X, NegC, &I);
2676  // -(X / C) --> X / (-C)
2677  if (match(FNegOp, m_FDiv(m_Value(X), m_Constant(C))))
2678    if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL))
2679      return BinaryOperator::CreateFDivFMF(X, NegC, &I);
2680  // -(C / X) --> (-C) / X
2681  if (match(FNegOp, m_FDiv(m_Constant(C), m_Value(X))))
2682    if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL)) {
2683      Instruction *FDiv = BinaryOperator::CreateFDivFMF(NegC, X, &I);
2684
2685      // Intersect 'nsz' and 'ninf' because those special value exceptions may
2686      // not apply to the fdiv. Everything else propagates from the fneg.
2687      // TODO: We could propagate nsz/ninf from fdiv alone?
2688      FastMathFlags FMF = I.getFastMathFlags();
2689      FastMathFlags OpFMF = FNegOp->getFastMathFlags();
2690      FDiv->setHasNoSignedZeros(FMF.noSignedZeros() && OpFMF.noSignedZeros());
2691      FDiv->setHasNoInfs(FMF.noInfs() && OpFMF.noInfs());
2692      return FDiv;
2693    }
2694  // With NSZ [ counter-example with -0.0: -(-0.0 + 0.0) != 0.0 + -0.0 ]:
2695  // -(X + C) --> -X + -C --> -C - X
2696  if (I.hasNoSignedZeros() && match(FNegOp, m_FAdd(m_Value(X), m_Constant(C))))
2697    if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL))
2698      return BinaryOperator::CreateFSubFMF(NegC, X, &I);
2699
2700  return nullptr;
2701}
2702
2703Instruction *InstCombinerImpl::hoistFNegAboveFMulFDiv(Value *FNegOp,
2704                                                      Instruction &FMFSource) {
2705  Value *X, *Y;
2706  if (match(FNegOp, m_FMul(m_Value(X), m_Value(Y)))) {
2707    return cast<Instruction>(Builder.CreateFMulFMF(
2708        Builder.CreateFNegFMF(X, &FMFSource), Y, &FMFSource));
2709  }
2710
2711  if (match(FNegOp, m_FDiv(m_Value(X), m_Value(Y)))) {
2712    return cast<Instruction>(Builder.CreateFDivFMF(
2713        Builder.CreateFNegFMF(X, &FMFSource), Y, &FMFSource));
2714  }
2715
2716  if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(FNegOp)) {
2717    // Make sure to preserve flags and metadata on the call.
2718    if (II->getIntrinsicID() == Intrinsic::ldexp) {
2719      FastMathFlags FMF = FMFSource.getFastMathFlags() | II->getFastMathFlags();
2720      IRBuilder<>::FastMathFlagGuard FMFGuard(Builder);
2721      Builder.setFastMathFlags(FMF);
2722
2723      CallInst *New = Builder.CreateCall(
2724          II->getCalledFunction(),
2725          {Builder.CreateFNeg(II->getArgOperand(0)), II->getArgOperand(1)});
2726      New->copyMetadata(*II);
2727      return New;
2728    }
2729  }
2730
2731  return nullptr;
2732}
2733
2734Instruction *InstCombinerImpl::visitFNeg(UnaryOperator &I) {
2735  Value *Op = I.getOperand(0);
2736
2737  if (Value *V = simplifyFNegInst(Op, I.getFastMathFlags(),
2738                                  getSimplifyQuery().getWithInstruction(&I)))
2739    return replaceInstUsesWith(I, V);
2740
2741  if (Instruction *X = foldFNegIntoConstant(I, DL))
2742    return X;
2743
2744  Value *X, *Y;
2745
2746  // If we can ignore the sign of zeros: -(X - Y) --> (Y - X)
2747  if (I.hasNoSignedZeros() &&
2748      match(Op, m_OneUse(m_FSub(m_Value(X), m_Value(Y)))))
2749    return BinaryOperator::CreateFSubFMF(Y, X, &I);
2750
2751  Value *OneUse;
2752  if (!match(Op, m_OneUse(m_Value(OneUse))))
2753    return nullptr;
2754
2755  if (Instruction *R = hoistFNegAboveFMulFDiv(OneUse, I))
2756    return replaceInstUsesWith(I, R);
2757
2758  // Try to eliminate fneg if at least 1 arm of the select is negated.
2759  Value *Cond;
2760  if (match(OneUse, m_Select(m_Value(Cond), m_Value(X), m_Value(Y)))) {
2761    // Unlike most transforms, this one is not safe to propagate nsz unless
2762    // it is present on the original select. We union the flags from the select
2763    // and fneg and then remove nsz if needed.
2764    auto propagateSelectFMF = [&](SelectInst *S, bool CommonOperand) {
2765      S->copyFastMathFlags(&I);
2766      if (auto *OldSel = dyn_cast<SelectInst>(Op)) {
2767        FastMathFlags FMF = I.getFastMathFlags() | OldSel->getFastMathFlags();
2768        S->setFastMathFlags(FMF);
2769        if (!OldSel->hasNoSignedZeros() && !CommonOperand &&
2770            !isGuaranteedNotToBeUndefOrPoison(OldSel->getCondition()))
2771          S->setHasNoSignedZeros(false);
2772      }
2773    };
2774    // -(Cond ? -P : Y) --> Cond ? P : -Y
2775    Value *P;
2776    if (match(X, m_FNeg(m_Value(P)))) {
2777      Value *NegY = Builder.CreateFNegFMF(Y, &I, Y->getName() + ".neg");
2778      SelectInst *NewSel = SelectInst::Create(Cond, P, NegY);
2779      propagateSelectFMF(NewSel, P == Y);
2780      return NewSel;
2781    }
2782    // -(Cond ? X : -P) --> Cond ? -X : P
2783    if (match(Y, m_FNeg(m_Value(P)))) {
2784      Value *NegX = Builder.CreateFNegFMF(X, &I, X->getName() + ".neg");
2785      SelectInst *NewSel = SelectInst::Create(Cond, NegX, P);
2786      propagateSelectFMF(NewSel, P == X);
2787      return NewSel;
2788    }
2789  }
2790
2791  // fneg (copysign x, y) -> copysign x, (fneg y)
2792  if (match(OneUse, m_CopySign(m_Value(X), m_Value(Y)))) {
2793    // The source copysign has an additional value input, so we can't propagate
2794    // flags the copysign doesn't also have.
2795    FastMathFlags FMF = I.getFastMathFlags();
2796    FMF &= cast<FPMathOperator>(OneUse)->getFastMathFlags();
2797
2798    IRBuilder<>::FastMathFlagGuard FMFGuard(Builder);
2799    Builder.setFastMathFlags(FMF);
2800
2801    Value *NegY = Builder.CreateFNeg(Y);
2802    Value *NewCopySign = Builder.CreateCopySign(X, NegY);
2803    return replaceInstUsesWith(I, NewCopySign);
2804  }
2805
2806  return nullptr;
2807}
2808
2809Instruction *InstCombinerImpl::visitFSub(BinaryOperator &I) {
2810  if (Value *V = simplifyFSubInst(I.getOperand(0), I.getOperand(1),
2811                                  I.getFastMathFlags(),
2812                                  getSimplifyQuery().getWithInstruction(&I)))
2813    return replaceInstUsesWith(I, V);
2814
2815  if (Instruction *X = foldVectorBinop(I))
2816    return X;
2817
2818  if (Instruction *Phi = foldBinopWithPhiOperands(I))
2819    return Phi;
2820
2821  // Subtraction from -0.0 is the canonical form of fneg.
2822  // fsub -0.0, X ==> fneg X
2823  // fsub nsz 0.0, X ==> fneg nsz X
2824  //
2825  // FIXME This matcher does not respect FTZ or DAZ yet:
2826  // fsub -0.0, Denorm ==> +-0
2827  // fneg Denorm ==> -Denorm
2828  Value *Op;
2829  if (match(&I, m_FNeg(m_Value(Op))))
2830    return UnaryOperator::CreateFNegFMF(Op, &I);
2831
2832  if (Instruction *X = foldFNegIntoConstant(I, DL))
2833    return X;
2834
2835  Value *X, *Y;
2836  Constant *C;
2837
2838  Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2839  // If Op0 is not -0.0 or we can ignore -0.0: Z - (X - Y) --> Z + (Y - X)
2840  // Canonicalize to fadd to make analysis easier.
2841  // This can also help codegen because fadd is commutative.
2842  // Note that if this fsub was really an fneg, the fadd with -0.0 will get
2843  // killed later. We still limit that particular transform with 'hasOneUse'
2844  // because an fneg is assumed better/cheaper than a generic fsub.
2845  if (I.hasNoSignedZeros() || cannotBeNegativeZero(Op0, SQ.DL, SQ.TLI)) {
2846    if (match(Op1, m_OneUse(m_FSub(m_Value(X), m_Value(Y))))) {
2847      Value *NewSub = Builder.CreateFSubFMF(Y, X, &I);
2848      return BinaryOperator::CreateFAddFMF(Op0, NewSub, &I);
2849    }
2850  }
2851
2852  // (-X) - Op1 --> -(X + Op1)
2853  if (I.hasNoSignedZeros() && !isa<ConstantExpr>(Op0) &&
2854      match(Op0, m_OneUse(m_FNeg(m_Value(X))))) {
2855    Value *FAdd = Builder.CreateFAddFMF(X, Op1, &I);
2856    return UnaryOperator::CreateFNegFMF(FAdd, &I);
2857  }
2858
2859  if (isa<Constant>(Op0))
2860    if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2861      if (Instruction *NV = FoldOpIntoSelect(I, SI))
2862        return NV;
2863
2864  // X - C --> X + (-C)
2865  // But don't transform constant expressions because there's an inverse fold
2866  // for X + (-Y) --> X - Y.
2867  if (match(Op1, m_ImmConstant(C)))
2868    if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL))
2869      return BinaryOperator::CreateFAddFMF(Op0, NegC, &I);
2870
2871  // X - (-Y) --> X + Y
2872  if (match(Op1, m_FNeg(m_Value(Y))))
2873    return BinaryOperator::CreateFAddFMF(Op0, Y, &I);
2874
2875  // Similar to above, but look through a cast of the negated value:
2876  // X - (fptrunc(-Y)) --> X + fptrunc(Y)
2877  Type *Ty = I.getType();
2878  if (match(Op1, m_OneUse(m_FPTrunc(m_FNeg(m_Value(Y))))))
2879    return BinaryOperator::CreateFAddFMF(Op0, Builder.CreateFPTrunc(Y, Ty), &I);
2880
2881  // X - (fpext(-Y)) --> X + fpext(Y)
2882  if (match(Op1, m_OneUse(m_FPExt(m_FNeg(m_Value(Y))))))
2883    return BinaryOperator::CreateFAddFMF(Op0, Builder.CreateFPExt(Y, Ty), &I);
2884
2885  // Similar to above, but look through fmul/fdiv of the negated value:
2886  // Op0 - (-X * Y) --> Op0 + (X * Y)
2887  // Op0 - (Y * -X) --> Op0 + (X * Y)
2888  if (match(Op1, m_OneUse(m_c_FMul(m_FNeg(m_Value(X)), m_Value(Y))))) {
2889    Value *FMul = Builder.CreateFMulFMF(X, Y, &I);
2890    return BinaryOperator::CreateFAddFMF(Op0, FMul, &I);
2891  }
2892  // Op0 - (-X / Y) --> Op0 + (X / Y)
2893  // Op0 - (X / -Y) --> Op0 + (X / Y)
2894  if (match(Op1, m_OneUse(m_FDiv(m_FNeg(m_Value(X)), m_Value(Y)))) ||
2895      match(Op1, m_OneUse(m_FDiv(m_Value(X), m_FNeg(m_Value(Y)))))) {
2896    Value *FDiv = Builder.CreateFDivFMF(X, Y, &I);
2897    return BinaryOperator::CreateFAddFMF(Op0, FDiv, &I);
2898  }
2899
2900  // Handle special cases for FSub with selects feeding the operation
2901  if (Value *V = SimplifySelectsFeedingBinaryOp(I, Op0, Op1))
2902    return replaceInstUsesWith(I, V);
2903
2904  if (I.hasAllowReassoc() && I.hasNoSignedZeros()) {
2905    // (Y - X) - Y --> -X
2906    if (match(Op0, m_FSub(m_Specific(Op1), m_Value(X))))
2907      return UnaryOperator::CreateFNegFMF(X, &I);
2908
2909    // Y - (X + Y) --> -X
2910    // Y - (Y + X) --> -X
2911    if (match(Op1, m_c_FAdd(m_Specific(Op0), m_Value(X))))
2912      return UnaryOperator::CreateFNegFMF(X, &I);
2913
2914    // (X * C) - X --> X * (C - 1.0)
2915    if (match(Op0, m_FMul(m_Specific(Op1), m_Constant(C)))) {
2916      if (Constant *CSubOne = ConstantFoldBinaryOpOperands(
2917              Instruction::FSub, C, ConstantFP::get(Ty, 1.0), DL))
2918        return BinaryOperator::CreateFMulFMF(Op1, CSubOne, &I);
2919    }
2920    // X - (X * C) --> X * (1.0 - C)
2921    if (match(Op1, m_FMul(m_Specific(Op0), m_Constant(C)))) {
2922      if (Constant *OneSubC = ConstantFoldBinaryOpOperands(
2923              Instruction::FSub, ConstantFP::get(Ty, 1.0), C, DL))
2924        return BinaryOperator::CreateFMulFMF(Op0, OneSubC, &I);
2925    }
2926
2927    // Reassociate fsub/fadd sequences to create more fadd instructions and
2928    // reduce dependency chains:
2929    // ((X - Y) + Z) - Op1 --> (X + Z) - (Y + Op1)
2930    Value *Z;
2931    if (match(Op0, m_OneUse(m_c_FAdd(m_OneUse(m_FSub(m_Value(X), m_Value(Y))),
2932                                     m_Value(Z))))) {
2933      Value *XZ = Builder.CreateFAddFMF(X, Z, &I);
2934      Value *YW = Builder.CreateFAddFMF(Y, Op1, &I);
2935      return BinaryOperator::CreateFSubFMF(XZ, YW, &I);
2936    }
2937
2938    auto m_FaddRdx = [](Value *&Sum, Value *&Vec) {
2939      return m_OneUse(m_Intrinsic<Intrinsic::vector_reduce_fadd>(m_Value(Sum),
2940                                                                 m_Value(Vec)));
2941    };
2942    Value *A0, *A1, *V0, *V1;
2943    if (match(Op0, m_FaddRdx(A0, V0)) && match(Op1, m_FaddRdx(A1, V1)) &&
2944        V0->getType() == V1->getType()) {
2945      // Difference of sums is sum of differences:
2946      // add_rdx(A0, V0) - add_rdx(A1, V1) --> add_rdx(A0, V0 - V1) - A1
2947      Value *Sub = Builder.CreateFSubFMF(V0, V1, &I);
2948      Value *Rdx = Builder.CreateIntrinsic(Intrinsic::vector_reduce_fadd,
2949                                           {Sub->getType()}, {A0, Sub}, &I);
2950      return BinaryOperator::CreateFSubFMF(Rdx, A1, &I);
2951    }
2952
2953    if (Instruction *F = factorizeFAddFSub(I, Builder))
2954      return F;
2955
2956    // TODO: This performs reassociative folds for FP ops. Some fraction of the
2957    // functionality has been subsumed by simple pattern matching here and in
2958    // InstSimplify. We should let a dedicated reassociation pass handle more
2959    // complex pattern matching and remove this from InstCombine.
2960    if (Value *V = FAddCombine(Builder).simplify(&I))
2961      return replaceInstUsesWith(I, V);
2962
2963    // (X - Y) - Op1 --> X - (Y + Op1)
2964    if (match(Op0, m_OneUse(m_FSub(m_Value(X), m_Value(Y))))) {
2965      Value *FAdd = Builder.CreateFAddFMF(Y, Op1, &I);
2966      return BinaryOperator::CreateFSubFMF(X, FAdd, &I);
2967    }
2968  }
2969
2970  return nullptr;
2971}
2972