1 //===- InstCombineAddSub.cpp ----------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the visit functions for add, fadd, sub, and fsub.
12 //===----------------------------------------------------------------------===//
14 #include "InstCombine.h"
15 #include "llvm/Analysis/InstructionSimplify.h"
16 #include "llvm/IR/DataLayout.h"
17 #include "llvm/Support/GetElementPtrTypeIterator.h"
18 #include "llvm/Support/PatternMatch.h"
20 using namespace PatternMatch;
24 /// Class representing coefficient of floating-point addend.
25 /// This class needs to be highly efficient, which is especially true for
26 /// the constructor. As of I write this comment, the cost of the default
27 /// constructor is merely 4-byte-store-zero (Assuming compiler is able to
28 /// perform write-merging).
32 // The constructor has to initialize a APFloat, which is uncessary for
33 // most addends which have coefficient either 1 or -1. So, the constructor
34 // is expensive. In order to avoid the cost of the constructor, we should
35 // reuse some instances whenever possible. The pre-created instances
36 // FAddCombine::Add[0-5] embodies this idea.
38 FAddendCoef() : IsFp(false), BufHasFpVal(false), IntVal(0) {}
42 assert(!insaneIntVal(C) && "Insane coefficient");
43 IsFp = false; IntVal = C;
46 void set(const APFloat& C);
50 bool isZero() const { return isInt() ? !IntVal : getFpVal().isZero(); }
51 Value *getValue(Type *) const;
53 // If possible, don't define operator+/operator- etc because these
54 // operators inevitably call FAddendCoef's constructor which is not cheap.
55 void operator=(const FAddendCoef &A);
56 void operator+=(const FAddendCoef &A);
57 void operator-=(const FAddendCoef &A);
58 void operator*=(const FAddendCoef &S);
60 bool isOne() const { return isInt() && IntVal == 1; }
61 bool isTwo() const { return isInt() && IntVal == 2; }
62 bool isMinusOne() const { return isInt() && IntVal == -1; }
63 bool isMinusTwo() const { return isInt() && IntVal == -2; }
66 bool insaneIntVal(int V) { return V > 4 || V < -4; }
67 APFloat *getFpValPtr(void)
68 { return reinterpret_cast<APFloat*>(&FpValBuf.buffer[0]); }
69 const APFloat *getFpValPtr(void) const
70 { return reinterpret_cast<const APFloat*>(&FpValBuf.buffer[0]); }
72 const APFloat &getFpVal(void) const {
73 assert(IsFp && BufHasFpVal && "Incorret state");
74 return *getFpValPtr();
77 APFloat &getFpVal(void)
78 { assert(IsFp && BufHasFpVal && "Incorret state"); return *getFpValPtr(); }
80 bool isInt() const { return !IsFp; }
82 // If the coefficient is represented by an integer, promote it to a
84 void convertToFpType(const fltSemantics &Sem);
86 // Construct an APFloat from a signed integer.
87 // TODO: We should get rid of this function when APFloat can be constructed
88 // from an *SIGNED* integer.
89 APFloat createAPFloatFromInt(const fltSemantics &Sem, int Val);
94 // True iff FpValBuf contains an instance of APFloat.
97 // The integer coefficient of an individual addend is either 1 or -1,
98 // and we try to simplify at most 4 addends from neighboring at most
99 // two instructions. So the range of <IntVal> falls in [-4, 4]. APInt
100 // is overkill of this end.
103 AlignedCharArrayUnion<APFloat> FpValBuf;
106 /// FAddend is used to represent floating-point addend. An addend is
107 /// represented as <C, V>, where the V is a symbolic value, and C is a
108 /// constant coefficient. A constant addend is represented as <C, 0>.
112 FAddend() { Val = 0; }
114 Value *getSymVal (void) const { return Val; }
115 const FAddendCoef &getCoef(void) const { return Coeff; }
117 bool isConstant() const { return Val == 0; }
118 bool isZero() const { return Coeff.isZero(); }
120 void set(short Coefficient, Value *V) { Coeff.set(Coefficient), Val = V; }
121 void set(const APFloat& Coefficient, Value *V)
122 { Coeff.set(Coefficient); Val = V; }
123 void set(const ConstantFP* Coefficient, Value *V)
124 { Coeff.set(Coefficient->getValueAPF()); Val = V; }
126 void negate() { Coeff.negate(); }
128 /// Drill down the U-D chain one step to find the definition of V, and
129 /// try to break the definition into one or two addends.
130 static unsigned drillValueDownOneStep(Value* V, FAddend &A0, FAddend &A1);
132 /// Similar to FAddend::drillDownOneStep() except that the value being
133 /// splitted is the addend itself.
134 unsigned drillAddendDownOneStep(FAddend &Addend0, FAddend &Addend1) const;
136 void operator+=(const FAddend &T) {
137 assert((Val == T.Val) && "Symbolic-values disagree");
142 void Scale(const FAddendCoef& ScaleAmt) { Coeff *= ScaleAmt; }
144 // This addend has the value of "Coeff * Val".
149 /// FAddCombine is the class for optimizing an unsafe fadd/fsub along
150 /// with its neighboring at most two instructions.
154 FAddCombine(InstCombiner::BuilderTy *B) : Builder(B), Instr(0) {}
155 Value *simplify(Instruction *FAdd);
158 typedef SmallVector<const FAddend*, 4> AddendVect;
160 Value *simplifyFAdd(AddendVect& V, unsigned InstrQuota);
162 Value *performFactorization(Instruction *I);
164 /// Convert given addend to a Value
165 Value *createAddendVal(const FAddend &A, bool& NeedNeg);
167 /// Return the number of instructions needed to emit the N-ary addition.
168 unsigned calcInstrNumber(const AddendVect& Vect);
169 Value *createFSub(Value *Opnd0, Value *Opnd1);
170 Value *createFAdd(Value *Opnd0, Value *Opnd1);
171 Value *createFMul(Value *Opnd0, Value *Opnd1);
172 Value *createFDiv(Value *Opnd0, Value *Opnd1);
173 Value *createFNeg(Value *V);
174 Value *createNaryFAdd(const AddendVect& Opnds, unsigned InstrQuota);
175 void createInstPostProc(Instruction *NewInst);
177 InstCombiner::BuilderTy *Builder;
181 // Debugging stuff are clustered here.
183 unsigned CreateInstrNum;
184 void initCreateInstNum() { CreateInstrNum = 0; }
185 void incCreateInstNum() { CreateInstrNum++; }
187 void initCreateInstNum() {}
188 void incCreateInstNum() {}
193 //===----------------------------------------------------------------------===//
196 // {FAddendCoef, FAddend, FAddition, FAddCombine}.
198 //===----------------------------------------------------------------------===//
199 FAddendCoef::~FAddendCoef() {
201 getFpValPtr()->~APFloat();
204 void FAddendCoef::set(const APFloat& C) {
205 APFloat *P = getFpValPtr();
208 // As the buffer is meanless byte stream, we cannot call
209 // APFloat::operator=().
214 IsFp = BufHasFpVal = true;
217 void FAddendCoef::convertToFpType(const fltSemantics &Sem) {
221 APFloat *P = getFpValPtr();
223 new(P) APFloat(Sem, IntVal);
225 new(P) APFloat(Sem, 0 - IntVal);
228 IsFp = BufHasFpVal = true;
231 APFloat FAddendCoef::createAPFloatFromInt(const fltSemantics &Sem, int Val) {
233 return APFloat(Sem, Val);
235 APFloat T(Sem, 0 - Val);
241 void FAddendCoef::operator=(const FAddendCoef &That) {
245 set(That.getFpVal());
248 void FAddendCoef::operator+=(const FAddendCoef &That) {
249 enum APFloat::roundingMode RndMode = APFloat::rmNearestTiesToEven;
250 if (isInt() == That.isInt()) {
252 IntVal += That.IntVal;
254 getFpVal().add(That.getFpVal(), RndMode);
259 const APFloat &T = That.getFpVal();
260 convertToFpType(T.getSemantics());
261 getFpVal().add(T, RndMode);
265 APFloat &T = getFpVal();
266 T.add(createAPFloatFromInt(T.getSemantics(), That.IntVal), RndMode);
269 void FAddendCoef::operator-=(const FAddendCoef &That) {
270 enum APFloat::roundingMode RndMode = APFloat::rmNearestTiesToEven;
271 if (isInt() == That.isInt()) {
273 IntVal -= That.IntVal;
275 getFpVal().subtract(That.getFpVal(), RndMode);
280 const APFloat &T = That.getFpVal();
281 convertToFpType(T.getSemantics());
282 getFpVal().subtract(T, RndMode);
286 APFloat &T = getFpVal();
287 T.subtract(createAPFloatFromInt(T.getSemantics(), IntVal), RndMode);
290 void FAddendCoef::operator*=(const FAddendCoef &That) {
294 if (That.isMinusOne()) {
299 if (isInt() && That.isInt()) {
300 int Res = IntVal * (int)That.IntVal;
301 assert(!insaneIntVal(Res) && "Insane int value");
306 const fltSemantics &Semantic =
307 isInt() ? That.getFpVal().getSemantics() : getFpVal().getSemantics();
310 convertToFpType(Semantic);
311 APFloat &F0 = getFpVal();
314 F0.multiply(createAPFloatFromInt(Semantic, That.IntVal),
315 APFloat::rmNearestTiesToEven);
317 F0.multiply(That.getFpVal(), APFloat::rmNearestTiesToEven);
322 void FAddendCoef::negate() {
326 getFpVal().changeSign();
329 Value *FAddendCoef::getValue(Type *Ty) const {
331 ConstantFP::get(Ty, float(IntVal)) :
332 ConstantFP::get(Ty->getContext(), getFpVal());
335 // The definition of <Val> Addends
336 // =========================================
337 // A + B <1, A>, <1,B>
338 // A - B <1, A>, <1,B>
341 // A + C <1, A> <C, NULL>
342 // 0 +/- 0 <0, NULL> (corner case)
344 // Legend: A and B are not constant, C is constant
346 unsigned FAddend::drillValueDownOneStep
347 (Value *Val, FAddend &Addend0, FAddend &Addend1) {
349 if (Val == 0 || !(I = dyn_cast<Instruction>(Val)))
352 unsigned Opcode = I->getOpcode();
354 if (Opcode == Instruction::FAdd || Opcode == Instruction::FSub) {
356 Value *Opnd0 = I->getOperand(0);
357 Value *Opnd1 = I->getOperand(1);
358 if ((C0 = dyn_cast<ConstantFP>(Opnd0)) && C0->isZero())
361 if ((C1 = dyn_cast<ConstantFP>(Opnd1)) && C1->isZero())
366 Addend0.set(1, Opnd0);
372 FAddend &Addend = Opnd0 ? Addend1 : Addend0;
374 Addend.set(1, Opnd1);
377 if (Opcode == Instruction::FSub)
382 return Opnd0 && Opnd1 ? 2 : 1;
384 // Both operands are zero. Weird!
385 Addend0.set(APFloat(C0->getValueAPF().getSemantics()), 0);
389 if (I->getOpcode() == Instruction::FMul) {
390 Value *V0 = I->getOperand(0);
391 Value *V1 = I->getOperand(1);
392 if (ConstantFP *C = dyn_cast<ConstantFP>(V0)) {
397 if (ConstantFP *C = dyn_cast<ConstantFP>(V1)) {
406 // Try to break *this* addend into two addends. e.g. Suppose this addend is
407 // <2.3, V>, and V = X + Y, by calling this function, we obtain two addends,
408 // i.e. <2.3, X> and <2.3, Y>.
410 unsigned FAddend::drillAddendDownOneStep
411 (FAddend &Addend0, FAddend &Addend1) const {
415 unsigned BreakNum = FAddend::drillValueDownOneStep(Val, Addend0, Addend1);
416 if (!BreakNum || Coeff.isOne())
419 Addend0.Scale(Coeff);
422 Addend1.Scale(Coeff);
427 // Try to perform following optimization on the input instruction I. Return the
428 // simplified expression if was successful; otherwise, return 0.
430 // Instruction "I" is Simplified into
431 // -------------------------------------------------------
432 // (x * y) +/- (x * z) x * (y +/- z)
433 // (y / x) +/- (z / x) (y +/- z) / x
435 Value *FAddCombine::performFactorization(Instruction *I) {
436 assert((I->getOpcode() == Instruction::FAdd ||
437 I->getOpcode() == Instruction::FSub) && "Expect add/sub");
439 Instruction *I0 = dyn_cast<Instruction>(I->getOperand(0));
440 Instruction *I1 = dyn_cast<Instruction>(I->getOperand(1));
442 if (!I0 || !I1 || I0->getOpcode() != I1->getOpcode())
446 if (I0->getOpcode() == Instruction::FMul)
448 else if (I0->getOpcode() != Instruction::FDiv)
451 Value *Opnd0_0 = I0->getOperand(0);
452 Value *Opnd0_1 = I0->getOperand(1);
453 Value *Opnd1_0 = I1->getOperand(0);
454 Value *Opnd1_1 = I1->getOperand(1);
456 // Input Instr I Factor AddSub0 AddSub1
457 // ----------------------------------------------
458 // (x*y) +/- (x*z) x y z
459 // (y/x) +/- (z/x) x y z
462 Value *AddSub0 = 0, *AddSub1 = 0;
465 if (Opnd0_0 == Opnd1_0 || Opnd0_0 == Opnd1_1)
467 else if (Opnd0_1 == Opnd1_0 || Opnd0_1 == Opnd1_1)
471 AddSub0 = (Factor == Opnd0_0) ? Opnd0_1 : Opnd0_0;
472 AddSub1 = (Factor == Opnd1_0) ? Opnd1_1 : Opnd1_0;
474 } else if (Opnd0_1 == Opnd1_1) {
483 // Create expression "NewAddSub = AddSub0 +/- AddsSub1"
484 Value *NewAddSub = (I->getOpcode() == Instruction::FAdd) ?
485 createFAdd(AddSub0, AddSub1) :
486 createFSub(AddSub0, AddSub1);
487 if (ConstantFP *CFP = dyn_cast<ConstantFP>(NewAddSub)) {
488 const APFloat &F = CFP->getValueAPF();
489 if (!F.isNormal() || F.isDenormal())
494 return createFMul(Factor, NewAddSub);
496 return createFDiv(NewAddSub, Factor);
499 Value *FAddCombine::simplify(Instruction *I) {
500 assert(I->hasUnsafeAlgebra() && "Should be in unsafe mode");
502 // Currently we are not able to handle vector type.
503 if (I->getType()->isVectorTy())
506 assert((I->getOpcode() == Instruction::FAdd ||
507 I->getOpcode() == Instruction::FSub) && "Expect add/sub");
509 // Save the instruction before calling other member-functions.
512 FAddend Opnd0, Opnd1, Opnd0_0, Opnd0_1, Opnd1_0, Opnd1_1;
514 unsigned OpndNum = FAddend::drillValueDownOneStep(I, Opnd0, Opnd1);
516 // Step 1: Expand the 1st addend into Opnd0_0 and Opnd0_1.
517 unsigned Opnd0_ExpNum = 0;
518 unsigned Opnd1_ExpNum = 0;
520 if (!Opnd0.isConstant())
521 Opnd0_ExpNum = Opnd0.drillAddendDownOneStep(Opnd0_0, Opnd0_1);
523 // Step 2: Expand the 2nd addend into Opnd1_0 and Opnd1_1.
524 if (OpndNum == 2 && !Opnd1.isConstant())
525 Opnd1_ExpNum = Opnd1.drillAddendDownOneStep(Opnd1_0, Opnd1_1);
527 // Step 3: Try to optimize Opnd0_0 + Opnd0_1 + Opnd1_0 + Opnd1_1
528 if (Opnd0_ExpNum && Opnd1_ExpNum) {
530 AllOpnds.push_back(&Opnd0_0);
531 AllOpnds.push_back(&Opnd1_0);
532 if (Opnd0_ExpNum == 2)
533 AllOpnds.push_back(&Opnd0_1);
534 if (Opnd1_ExpNum == 2)
535 AllOpnds.push_back(&Opnd1_1);
537 // Compute instruction quota. We should save at least one instruction.
538 unsigned InstQuota = 0;
540 Value *V0 = I->getOperand(0);
541 Value *V1 = I->getOperand(1);
542 InstQuota = ((!isa<Constant>(V0) && V0->hasOneUse()) &&
543 (!isa<Constant>(V1) && V1->hasOneUse())) ? 2 : 1;
545 if (Value *R = simplifyFAdd(AllOpnds, InstQuota))
550 // The input instruction is : "I=0.0 +/- V". If the "V" were able to be
551 // splitted into two addends, say "V = X - Y", the instruction would have
552 // been optimized into "I = Y - X" in the previous steps.
554 const FAddendCoef &CE = Opnd0.getCoef();
555 return CE.isOne() ? Opnd0.getSymVal() : 0;
558 // step 4: Try to optimize Opnd0 + Opnd1_0 [+ Opnd1_1]
561 AllOpnds.push_back(&Opnd0);
562 AllOpnds.push_back(&Opnd1_0);
563 if (Opnd1_ExpNum == 2)
564 AllOpnds.push_back(&Opnd1_1);
566 if (Value *R = simplifyFAdd(AllOpnds, 1))
570 // step 5: Try to optimize Opnd1 + Opnd0_0 [+ Opnd0_1]
573 AllOpnds.push_back(&Opnd1);
574 AllOpnds.push_back(&Opnd0_0);
575 if (Opnd0_ExpNum == 2)
576 AllOpnds.push_back(&Opnd0_1);
578 if (Value *R = simplifyFAdd(AllOpnds, 1))
582 // step 6: Try factorization as the last resort,
583 return performFactorization(I);
586 Value *FAddCombine::simplifyFAdd(AddendVect& Addends, unsigned InstrQuota) {
588 unsigned AddendNum = Addends.size();
589 assert(AddendNum <= 4 && "Too many addends");
591 // For saving intermediate results;
592 unsigned NextTmpIdx = 0;
593 FAddend TmpResult[3];
595 // Points to the constant addend of the resulting simplified expression.
596 // If the resulting expr has constant-addend, this constant-addend is
597 // desirable to reside at the top of the resulting expression tree. Placing
598 // constant close to supper-expr(s) will potentially reveal some optimization
599 // opportunities in super-expr(s).
601 const FAddend *ConstAdd = 0;
603 // Simplified addends are placed <SimpVect>.
606 // The outer loop works on one symbolic-value at a time. Suppose the input
607 // addends are : <a1, x>, <b1, y>, <a2, x>, <c1, z>, <b2, y>, ...
608 // The symbolic-values will be processed in this order: x, y, z.
610 for (unsigned SymIdx = 0; SymIdx < AddendNum; SymIdx++) {
612 const FAddend *ThisAddend = Addends[SymIdx];
614 // This addend was processed before.
618 Value *Val = ThisAddend->getSymVal();
619 unsigned StartIdx = SimpVect.size();
620 SimpVect.push_back(ThisAddend);
622 // The inner loop collects addends sharing same symbolic-value, and these
623 // addends will be later on folded into a single addend. Following above
624 // example, if the symbolic value "y" is being processed, the inner loop
625 // will collect two addends "<b1,y>" and "<b2,Y>". These two addends will
626 // be later on folded into "<b1+b2, y>".
628 for (unsigned SameSymIdx = SymIdx + 1;
629 SameSymIdx < AddendNum; SameSymIdx++) {
630 const FAddend *T = Addends[SameSymIdx];
631 if (T && T->getSymVal() == Val) {
632 // Set null such that next iteration of the outer loop will not process
633 // this addend again.
634 Addends[SameSymIdx] = 0;
635 SimpVect.push_back(T);
639 // If multiple addends share same symbolic value, fold them together.
640 if (StartIdx + 1 != SimpVect.size()) {
641 FAddend &R = TmpResult[NextTmpIdx ++];
642 R = *SimpVect[StartIdx];
643 for (unsigned Idx = StartIdx + 1; Idx < SimpVect.size(); Idx++)
646 // Pop all addends being folded and push the resulting folded addend.
647 SimpVect.resize(StartIdx);
650 SimpVect.push_back(&R);
653 // Don't push constant addend at this time. It will be the last element
660 assert((NextTmpIdx <= sizeof(TmpResult)/sizeof(TmpResult[0]) + 1) &&
661 "out-of-bound access");
664 SimpVect.push_back(ConstAdd);
667 if (!SimpVect.empty())
668 Result = createNaryFAdd(SimpVect, InstrQuota);
670 // The addition is folded to 0.0.
671 Result = ConstantFP::get(Instr->getType(), 0.0);
677 Value *FAddCombine::createNaryFAdd
678 (const AddendVect &Opnds, unsigned InstrQuota) {
679 assert(!Opnds.empty() && "Expect at least one addend");
681 // Step 1: Check if the # of instructions needed exceeds the quota.
683 unsigned InstrNeeded = calcInstrNumber(Opnds);
684 if (InstrNeeded > InstrQuota)
689 // step 2: Emit the N-ary addition.
690 // Note that at most three instructions are involved in Fadd-InstCombine: the
691 // addition in question, and at most two neighboring instructions.
692 // The resulting optimized addition should have at least one less instruction
693 // than the original addition expression tree. This implies that the resulting
694 // N-ary addition has at most two instructions, and we don't need to worry
695 // about tree-height when constructing the N-ary addition.
698 bool LastValNeedNeg = false;
700 // Iterate the addends, creating fadd/fsub using adjacent two addends.
701 for (AddendVect::const_iterator I = Opnds.begin(), E = Opnds.end();
704 Value *V = createAddendVal(**I, NeedNeg);
707 LastValNeedNeg = NeedNeg;
711 if (LastValNeedNeg == NeedNeg) {
712 LastVal = createFAdd(LastVal, V);
717 LastVal = createFSub(V, LastVal);
719 LastVal = createFSub(LastVal, V);
721 LastValNeedNeg = false;
724 if (LastValNeedNeg) {
725 LastVal = createFNeg(LastVal);
729 assert(CreateInstrNum == InstrNeeded &&
730 "Inconsistent in instruction numbers");
736 Value *FAddCombine::createFSub
737 (Value *Opnd0, Value *Opnd1) {
738 Value *V = Builder->CreateFSub(Opnd0, Opnd1);
739 if (Instruction *I = dyn_cast<Instruction>(V))
740 createInstPostProc(I);
744 Value *FAddCombine::createFNeg(Value *V) {
745 Value *Zero = cast<Value>(ConstantFP::get(V->getType(), 0.0));
746 return createFSub(Zero, V);
749 Value *FAddCombine::createFAdd
750 (Value *Opnd0, Value *Opnd1) {
751 Value *V = Builder->CreateFAdd(Opnd0, Opnd1);
752 if (Instruction *I = dyn_cast<Instruction>(V))
753 createInstPostProc(I);
757 Value *FAddCombine::createFMul(Value *Opnd0, Value *Opnd1) {
758 Value *V = Builder->CreateFMul(Opnd0, Opnd1);
759 if (Instruction *I = dyn_cast<Instruction>(V))
760 createInstPostProc(I);
764 Value *FAddCombine::createFDiv(Value *Opnd0, Value *Opnd1) {
765 Value *V = Builder->CreateFDiv(Opnd0, Opnd1);
766 if (Instruction *I = dyn_cast<Instruction>(V))
767 createInstPostProc(I);
771 void FAddCombine::createInstPostProc(Instruction *NewInstr) {
772 NewInstr->setDebugLoc(Instr->getDebugLoc());
774 // Keep track of the number of instruction created.
777 // Propagate fast-math flags
778 NewInstr->setFastMathFlags(Instr->getFastMathFlags());
781 // Return the number of instruction needed to emit the N-ary addition.
782 // NOTE: Keep this function in sync with createAddendVal().
783 unsigned FAddCombine::calcInstrNumber(const AddendVect &Opnds) {
784 unsigned OpndNum = Opnds.size();
785 unsigned InstrNeeded = OpndNum - 1;
787 // The number of addends in the form of "(-1)*x".
788 unsigned NegOpndNum = 0;
790 // Adjust the number of instructions needed to emit the N-ary add.
791 for (AddendVect::const_iterator I = Opnds.begin(), E = Opnds.end();
793 const FAddend *Opnd = *I;
794 if (Opnd->isConstant())
797 const FAddendCoef &CE = Opnd->getCoef();
798 if (CE.isMinusOne() || CE.isMinusTwo())
801 // Let the addend be "c * x". If "c == +/-1", the value of the addend
802 // is immediately available; otherwise, it needs exactly one instruction
803 // to evaluate the value.
804 if (!CE.isMinusOne() && !CE.isOne())
807 if (NegOpndNum == OpndNum)
812 // Input Addend Value NeedNeg(output)
813 // ================================================================
814 // Constant C C false
815 // <+/-1, V> V coefficient is -1
816 // <2/-2, V> "fadd V, V" coefficient is -2
817 // <C, V> "fmul V, C" false
819 // NOTE: Keep this function in sync with FAddCombine::calcInstrNumber.
820 Value *FAddCombine::createAddendVal
821 (const FAddend &Opnd, bool &NeedNeg) {
822 const FAddendCoef &Coeff = Opnd.getCoef();
824 if (Opnd.isConstant()) {
826 return Coeff.getValue(Instr->getType());
829 Value *OpndVal = Opnd.getSymVal();
831 if (Coeff.isMinusOne() || Coeff.isOne()) {
832 NeedNeg = Coeff.isMinusOne();
836 if (Coeff.isTwo() || Coeff.isMinusTwo()) {
837 NeedNeg = Coeff.isMinusTwo();
838 return createFAdd(OpndVal, OpndVal);
842 return createFMul(OpndVal, Coeff.getValue(Instr->getType()));
845 /// AddOne - Add one to a ConstantInt.
846 static Constant *AddOne(Constant *C) {
847 return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
850 /// SubOne - Subtract one from a ConstantInt.
851 static Constant *SubOne(ConstantInt *C) {
852 return ConstantInt::get(C->getContext(), C->getValue()-1);
856 // dyn_castFoldableMul - If this value is a multiply that can be folded into
857 // other computations (because it has a constant operand), return the
858 // non-constant operand of the multiply, and set CST to point to the multiplier.
859 // Otherwise, return null.
861 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
862 if (!V->hasOneUse() || !V->getType()->isIntegerTy())
865 Instruction *I = dyn_cast<Instruction>(V);
866 if (I == 0) return 0;
868 if (I->getOpcode() == Instruction::Mul)
869 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
870 return I->getOperand(0);
871 if (I->getOpcode() == Instruction::Shl)
872 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
873 // The multiplier is really 1 << CST.
874 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
875 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
876 CST = ConstantInt::get(V->getType()->getContext(),
877 APInt(BitWidth, 1).shl(CSTVal));
878 return I->getOperand(0);
884 /// WillNotOverflowSignedAdd - Return true if we can prove that:
885 /// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
886 /// This basically requires proving that the add in the original type would not
887 /// overflow to change the sign bit or have a carry out.
888 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
889 // There are different heuristics we can use for this. Here are some simple
892 // Add has the property that adding any two 2's complement numbers can only
893 // have one carry bit which can change a sign. As such, if LHS and RHS each
894 // have at least two sign bits, we know that the addition of the two values
895 // will sign extend fine.
896 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
900 // If one of the operands only has one non-zero bit, and if the other operand
901 // has a known-zero bit in a more significant place than it (not including the
902 // sign bit) the ripple may go up to and fill the zero, but won't change the
903 // sign. For example, (X & ~4) + 1.
910 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
911 bool Changed = SimplifyAssociativeOrCommutative(I);
912 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
914 if (Value *V = SimplifyAddInst(LHS, RHS, I.hasNoSignedWrap(),
915 I.hasNoUnsignedWrap(), TD))
916 return ReplaceInstUsesWith(I, V);
918 // (A*B)+(A*C) -> A*(B+C) etc
919 if (Value *V = SimplifyUsingDistributiveLaws(I))
920 return ReplaceInstUsesWith(I, V);
922 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
923 // X + (signbit) --> X ^ signbit
924 const APInt &Val = CI->getValue();
926 return BinaryOperator::CreateXor(LHS, RHS);
928 // See if SimplifyDemandedBits can simplify this. This handles stuff like
929 // (X & 254)+1 -> (X&254)|1
930 if (SimplifyDemandedInstructionBits(I))
933 // zext(bool) + C -> bool ? C + 1 : C
934 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
935 if (ZI->getSrcTy()->isIntegerTy(1))
936 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
938 Value *XorLHS = 0; ConstantInt *XorRHS = 0;
939 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
940 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
941 const APInt &RHSVal = CI->getValue();
942 unsigned ExtendAmt = 0;
943 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
944 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
945 if (XorRHS->getValue() == -RHSVal) {
946 if (RHSVal.isPowerOf2())
947 ExtendAmt = TySizeBits - RHSVal.logBase2() - 1;
948 else if (XorRHS->getValue().isPowerOf2())
949 ExtendAmt = TySizeBits - XorRHS->getValue().logBase2() - 1;
953 APInt Mask = APInt::getHighBitsSet(TySizeBits, ExtendAmt);
954 if (!MaskedValueIsZero(XorLHS, Mask))
959 Constant *ShAmt = ConstantInt::get(I.getType(), ExtendAmt);
960 Value *NewShl = Builder->CreateShl(XorLHS, ShAmt, "sext");
961 return BinaryOperator::CreateAShr(NewShl, ShAmt);
964 // If this is a xor that was canonicalized from a sub, turn it back into
965 // a sub and fuse this add with it.
966 if (LHS->hasOneUse() && (XorRHS->getValue()+1).isPowerOf2()) {
967 IntegerType *IT = cast<IntegerType>(I.getType());
968 APInt LHSKnownOne(IT->getBitWidth(), 0);
969 APInt LHSKnownZero(IT->getBitWidth(), 0);
970 ComputeMaskedBits(XorLHS, LHSKnownZero, LHSKnownOne);
971 if ((XorRHS->getValue() | LHSKnownZero).isAllOnesValue())
972 return BinaryOperator::CreateSub(ConstantExpr::getAdd(XorRHS, CI),
978 if (isa<Constant>(RHS) && isa<PHINode>(LHS))
979 if (Instruction *NV = FoldOpIntoPhi(I))
982 if (I.getType()->isIntegerTy(1))
983 return BinaryOperator::CreateXor(LHS, RHS);
987 BinaryOperator *New =
988 BinaryOperator::CreateShl(LHS, ConstantInt::get(I.getType(), 1));
989 New->setHasNoSignedWrap(I.hasNoSignedWrap());
990 New->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
995 // -A + -B --> -(A + B)
996 if (Value *LHSV = dyn_castNegVal(LHS)) {
997 if (!isa<Constant>(RHS))
998 if (Value *RHSV = dyn_castNegVal(RHS)) {
999 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
1000 return BinaryOperator::CreateNeg(NewAdd);
1003 return BinaryOperator::CreateSub(RHS, LHSV);
1007 if (!isa<Constant>(RHS))
1008 if (Value *V = dyn_castNegVal(RHS))
1009 return BinaryOperator::CreateSub(LHS, V);
1013 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1014 if (X == RHS) // X*C + X --> X * (C+1)
1015 return BinaryOperator::CreateMul(RHS, AddOne(C2));
1017 // X*C1 + X*C2 --> X * (C1+C2)
1019 if (X == dyn_castFoldableMul(RHS, C1))
1020 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
1023 // X + X*C --> X * (C+1)
1024 if (dyn_castFoldableMul(RHS, C2) == LHS)
1025 return BinaryOperator::CreateMul(LHS, AddOne(C2));
1027 // A+B --> A|B iff A and B have no bits set in common.
1028 if (IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
1029 APInt LHSKnownOne(IT->getBitWidth(), 0);
1030 APInt LHSKnownZero(IT->getBitWidth(), 0);
1031 ComputeMaskedBits(LHS, LHSKnownZero, LHSKnownOne);
1032 if (LHSKnownZero != 0) {
1033 APInt RHSKnownOne(IT->getBitWidth(), 0);
1034 APInt RHSKnownZero(IT->getBitWidth(), 0);
1035 ComputeMaskedBits(RHS, RHSKnownZero, RHSKnownOne);
1037 // No bits in common -> bitwise or.
1038 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
1039 return BinaryOperator::CreateOr(LHS, RHS);
1043 // W*X + Y*Z --> W * (X+Z) iff W == Y
1045 Value *W, *X, *Y, *Z;
1046 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
1047 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
1051 } else if (Y == X) {
1053 } else if (X == Z) {
1060 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
1061 return BinaryOperator::CreateMul(W, NewAdd);
1066 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
1068 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
1069 return BinaryOperator::CreateSub(SubOne(CRHS), X);
1071 // (X & FF00) + xx00 -> (X+xx00) & FF00
1072 if (LHS->hasOneUse() &&
1073 match(LHS, m_And(m_Value(X), m_ConstantInt(C2))) &&
1074 CRHS->getValue() == (CRHS->getValue() & C2->getValue())) {
1075 // See if all bits from the first bit set in the Add RHS up are included
1076 // in the mask. First, get the rightmost bit.
1077 const APInt &AddRHSV = CRHS->getValue();
1079 // Form a mask of all bits from the lowest bit added through the top.
1080 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
1082 // See if the and mask includes all of these bits.
1083 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
1085 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1086 // Okay, the xform is safe. Insert the new add pronto.
1087 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
1088 return BinaryOperator::CreateAnd(NewAdd, C2);
1092 // Try to fold constant add into select arguments.
1093 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
1094 if (Instruction *R = FoldOpIntoSelect(I, SI))
1098 // add (select X 0 (sub n A)) A --> select X A n
1100 SelectInst *SI = dyn_cast<SelectInst>(LHS);
1103 SI = dyn_cast<SelectInst>(RHS);
1106 if (SI && SI->hasOneUse()) {
1107 Value *TV = SI->getTrueValue();
1108 Value *FV = SI->getFalseValue();
1111 // Can we fold the add into the argument of the select?
1112 // We check both true and false select arguments for a matching subtract.
1113 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
1114 // Fold the add into the true select value.
1115 return SelectInst::Create(SI->getCondition(), N, A);
1117 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
1118 // Fold the add into the false select value.
1119 return SelectInst::Create(SI->getCondition(), A, N);
1123 // Check for (add (sext x), y), see if we can merge this into an
1124 // integer add followed by a sext.
1125 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
1126 // (add (sext x), cst) --> (sext (add x, cst'))
1127 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
1129 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
1130 if (LHSConv->hasOneUse() &&
1131 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
1132 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
1133 // Insert the new, smaller add.
1134 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
1136 return new SExtInst(NewAdd, I.getType());
1140 // (add (sext x), (sext y)) --> (sext (add int x, y))
1141 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
1142 // Only do this if x/y have the same type, if at last one of them has a
1143 // single use (so we don't increase the number of sexts), and if the
1144 // integer add will not overflow.
1145 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
1146 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
1147 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
1148 RHSConv->getOperand(0))) {
1149 // Insert the new integer add.
1150 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
1151 RHSConv->getOperand(0), "addconv");
1152 return new SExtInst(NewAdd, I.getType());
1157 // Check for (x & y) + (x ^ y)
1159 Value *A = 0, *B = 0;
1160 if (match(RHS, m_Xor(m_Value(A), m_Value(B))) &&
1161 (match(LHS, m_And(m_Specific(A), m_Specific(B))) ||
1162 match(LHS, m_And(m_Specific(B), m_Specific(A)))))
1163 return BinaryOperator::CreateOr(A, B);
1165 if (match(LHS, m_Xor(m_Value(A), m_Value(B))) &&
1166 (match(RHS, m_And(m_Specific(A), m_Specific(B))) ||
1167 match(RHS, m_And(m_Specific(B), m_Specific(A)))))
1168 return BinaryOperator::CreateOr(A, B);
1171 return Changed ? &I : 0;
1174 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
1175 bool Changed = SimplifyAssociativeOrCommutative(I);
1176 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1178 if (Value *V = SimplifyFAddInst(LHS, RHS, I.getFastMathFlags(), TD))
1179 return ReplaceInstUsesWith(I, V);
1181 if (isa<Constant>(RHS) && isa<PHINode>(LHS))
1182 if (Instruction *NV = FoldOpIntoPhi(I))
1186 // -A + -B --> -(A + B)
1187 if (Value *LHSV = dyn_castFNegVal(LHS))
1188 return BinaryOperator::CreateFSub(RHS, LHSV);
1191 if (!isa<Constant>(RHS))
1192 if (Value *V = dyn_castFNegVal(RHS))
1193 return BinaryOperator::CreateFSub(LHS, V);
1195 // Check for (fadd double (sitofp x), y), see if we can merge this into an
1196 // integer add followed by a promotion.
1197 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
1198 // (fadd double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
1199 // ... if the constant fits in the integer value. This is useful for things
1200 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
1201 // requires a constant pool load, and generally allows the add to be better
1203 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
1205 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
1206 if (LHSConv->hasOneUse() &&
1207 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
1208 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
1209 // Insert the new integer add.
1210 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
1212 return new SIToFPInst(NewAdd, I.getType());
1216 // (fadd double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
1217 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
1218 // Only do this if x/y have the same type, if at last one of them has a
1219 // single use (so we don't increase the number of int->fp conversions),
1220 // and if the integer add will not overflow.
1221 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
1222 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
1223 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
1224 RHSConv->getOperand(0))) {
1225 // Insert the new integer add.
1226 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
1227 RHSConv->getOperand(0),"addconv");
1228 return new SIToFPInst(NewAdd, I.getType());
1233 if (I.hasUnsafeAlgebra()) {
1234 if (Value *V = FAddCombine(Builder).simplify(&I))
1235 return ReplaceInstUsesWith(I, V);
1238 return Changed ? &I : 0;
1242 /// Optimize pointer differences into the same array into a size. Consider:
1243 /// &A[10] - &A[0]: we should compile this to "10". LHS/RHS are the pointer
1244 /// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
1246 Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS,
1248 assert(TD && "Must have target data info for this");
1250 // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
1252 bool Swapped = false;
1253 GEPOperator *GEP1 = 0, *GEP2 = 0;
1255 // For now we require one side to be the base pointer "A" or a constant
1256 // GEP derived from it.
1257 if (GEPOperator *LHSGEP = dyn_cast<GEPOperator>(LHS)) {
1259 if (LHSGEP->getOperand(0) == RHS) {
1262 } else if (GEPOperator *RHSGEP = dyn_cast<GEPOperator>(RHS)) {
1263 // (gep X, ...) - (gep X, ...)
1264 if (LHSGEP->getOperand(0)->stripPointerCasts() ==
1265 RHSGEP->getOperand(0)->stripPointerCasts()) {
1273 if (GEPOperator *RHSGEP = dyn_cast<GEPOperator>(RHS)) {
1275 if (RHSGEP->getOperand(0) == LHS) {
1278 } else if (GEPOperator *LHSGEP = dyn_cast<GEPOperator>(LHS)) {
1279 // (gep X, ...) - (gep X, ...)
1280 if (RHSGEP->getOperand(0)->stripPointerCasts() ==
1281 LHSGEP->getOperand(0)->stripPointerCasts()) {
1289 // Avoid duplicating the arithmetic if GEP2 has non-constant indices and
1292 (GEP2 != 0 && !GEP2->hasAllConstantIndices() && !GEP2->hasOneUse()))
1295 // Emit the offset of the GEP and an intptr_t.
1296 Value *Result = EmitGEPOffset(GEP1);
1298 // If we had a constant expression GEP on the other side offsetting the
1299 // pointer, subtract it from the offset we have.
1301 Value *Offset = EmitGEPOffset(GEP2);
1302 Result = Builder->CreateSub(Result, Offset);
1305 // If we have p - gep(p, ...) then we have to negate the result.
1307 Result = Builder->CreateNeg(Result, "diff.neg");
1309 return Builder->CreateIntCast(Result, Ty, true);
1313 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
1314 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1316 if (Value *V = SimplifySubInst(Op0, Op1, I.hasNoSignedWrap(),
1317 I.hasNoUnsignedWrap(), TD))
1318 return ReplaceInstUsesWith(I, V);
1320 // (A*B)-(A*C) -> A*(B-C) etc
1321 if (Value *V = SimplifyUsingDistributiveLaws(I))
1322 return ReplaceInstUsesWith(I, V);
1324 // If this is a 'B = x-(-A)', change to B = x+A. This preserves NSW/NUW.
1325 if (Value *V = dyn_castNegVal(Op1)) {
1326 BinaryOperator *Res = BinaryOperator::CreateAdd(Op0, V);
1327 Res->setHasNoSignedWrap(I.hasNoSignedWrap());
1328 Res->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
1332 if (I.getType()->isIntegerTy(1))
1333 return BinaryOperator::CreateXor(Op0, Op1);
1335 // Replace (-1 - A) with (~A).
1336 if (match(Op0, m_AllOnes()))
1337 return BinaryOperator::CreateNot(Op1);
1339 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1340 // C - ~X == X + (1+C)
1342 if (match(Op1, m_Not(m_Value(X))))
1343 return BinaryOperator::CreateAdd(X, AddOne(C));
1345 // -(X >>u 31) -> (X >>s 31)
1346 // -(X >>s 31) -> (X >>u 31)
1348 Value *X; ConstantInt *CI;
1349 if (match(Op1, m_LShr(m_Value(X), m_ConstantInt(CI))) &&
1350 // Verify we are shifting out everything but the sign bit.
1351 CI->getValue() == I.getType()->getPrimitiveSizeInBits()-1)
1352 return BinaryOperator::CreateAShr(X, CI);
1354 if (match(Op1, m_AShr(m_Value(X), m_ConstantInt(CI))) &&
1355 // Verify we are shifting out everything but the sign bit.
1356 CI->getValue() == I.getType()->getPrimitiveSizeInBits()-1)
1357 return BinaryOperator::CreateLShr(X, CI);
1360 // Try to fold constant sub into select arguments.
1361 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1362 if (Instruction *R = FoldOpIntoSelect(I, SI))
1365 // C-(X+C2) --> (C-C2)-X
1367 if (match(Op1, m_Add(m_Value(X), m_ConstantInt(C2))))
1368 return BinaryOperator::CreateSub(ConstantExpr::getSub(C, C2), X);
1370 if (SimplifyDemandedInstructionBits(I))
1373 // Fold (sub 0, (zext bool to B)) --> (sext bool to B)
1374 if (C->isZero() && match(Op1, m_ZExt(m_Value(X))))
1375 if (X->getType()->isIntegerTy(1))
1376 return CastInst::CreateSExtOrBitCast(X, Op1->getType());
1378 // Fold (sub 0, (sext bool to B)) --> (zext bool to B)
1379 if (C->isZero() && match(Op1, m_SExt(m_Value(X))))
1380 if (X->getType()->isIntegerTy(1))
1381 return CastInst::CreateZExtOrBitCast(X, Op1->getType());
1386 // X-(X+Y) == -Y X-(Y+X) == -Y
1387 if (match(Op1, m_Add(m_Specific(Op0), m_Value(Y))) ||
1388 match(Op1, m_Add(m_Value(Y), m_Specific(Op0))))
1389 return BinaryOperator::CreateNeg(Y);
1392 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(Y))))
1393 return BinaryOperator::CreateNeg(Y);
1396 if (Op1->hasOneUse()) {
1397 Value *X = 0, *Y = 0, *Z = 0;
1399 ConstantInt *CI = 0;
1401 // (X - (Y - Z)) --> (X + (Z - Y)).
1402 if (match(Op1, m_Sub(m_Value(Y), m_Value(Z))))
1403 return BinaryOperator::CreateAdd(Op0,
1404 Builder->CreateSub(Z, Y, Op1->getName()));
1406 // (X - (X & Y)) --> (X & ~Y)
1408 if (match(Op1, m_And(m_Value(Y), m_Specific(Op0))) ||
1409 match(Op1, m_And(m_Specific(Op0), m_Value(Y))))
1410 return BinaryOperator::CreateAnd(Op0,
1411 Builder->CreateNot(Y, Y->getName() + ".not"));
1413 // 0 - (X sdiv C) -> (X sdiv -C)
1414 if (match(Op1, m_SDiv(m_Value(X), m_Constant(C))) &&
1415 match(Op0, m_Zero()))
1416 return BinaryOperator::CreateSDiv(X, ConstantExpr::getNeg(C));
1418 // 0 - (X << Y) -> (-X << Y) when X is freely negatable.
1419 if (match(Op1, m_Shl(m_Value(X), m_Value(Y))) && match(Op0, m_Zero()))
1420 if (Value *XNeg = dyn_castNegVal(X))
1421 return BinaryOperator::CreateShl(XNeg, Y);
1423 // X - X*C --> X * (1-C)
1424 if (match(Op1, m_Mul(m_Specific(Op0), m_ConstantInt(CI)))) {
1425 Constant *CP1 = ConstantExpr::getSub(ConstantInt::get(I.getType(),1), CI);
1426 return BinaryOperator::CreateMul(Op0, CP1);
1429 // X - X<<C --> X * (1-(1<<C))
1430 if (match(Op1, m_Shl(m_Specific(Op0), m_ConstantInt(CI)))) {
1431 Constant *One = ConstantInt::get(I.getType(), 1);
1432 C = ConstantExpr::getSub(One, ConstantExpr::getShl(One, CI));
1433 return BinaryOperator::CreateMul(Op0, C);
1436 // X - A*-B -> X + A*B
1437 // X - -A*B -> X + A*B
1439 if (match(Op1, m_Mul(m_Value(A), m_Neg(m_Value(B)))) ||
1440 match(Op1, m_Mul(m_Neg(m_Value(A)), m_Value(B))))
1441 return BinaryOperator::CreateAdd(Op0, Builder->CreateMul(A, B));
1443 // X - A*CI -> X + A*-CI
1444 // X - CI*A -> X + A*-CI
1445 if (match(Op1, m_Mul(m_Value(A), m_ConstantInt(CI))) ||
1446 match(Op1, m_Mul(m_ConstantInt(CI), m_Value(A)))) {
1447 Value *NewMul = Builder->CreateMul(A, ConstantExpr::getNeg(CI));
1448 return BinaryOperator::CreateAdd(Op0, NewMul);
1453 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
1454 if (X == Op1) // X*C - X --> X * (C-1)
1455 return BinaryOperator::CreateMul(Op1, SubOne(C1));
1457 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
1458 if (X == dyn_castFoldableMul(Op1, C2))
1459 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
1462 // Optimize pointer differences into the same array into a size. Consider:
1463 // &A[10] - &A[0]: we should compile this to "10".
1465 Value *LHSOp, *RHSOp;
1466 if (match(Op0, m_PtrToInt(m_Value(LHSOp))) &&
1467 match(Op1, m_PtrToInt(m_Value(RHSOp))))
1468 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
1469 return ReplaceInstUsesWith(I, Res);
1471 // trunc(p)-trunc(q) -> trunc(p-q)
1472 if (match(Op0, m_Trunc(m_PtrToInt(m_Value(LHSOp)))) &&
1473 match(Op1, m_Trunc(m_PtrToInt(m_Value(RHSOp)))))
1474 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
1475 return ReplaceInstUsesWith(I, Res);
1481 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
1482 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1484 if (Value *V = SimplifyFSubInst(Op0, Op1, I.getFastMathFlags(), TD))
1485 return ReplaceInstUsesWith(I, V);
1487 // If this is a 'B = x-(-A)', change to B = x+A...
1488 if (Value *V = dyn_castFNegVal(Op1))
1489 return BinaryOperator::CreateFAdd(Op0, V);
1491 if (I.hasUnsafeAlgebra()) {
1492 if (Value *V = FAddCombine(Builder).simplify(&I))
1493 return ReplaceInstUsesWith(I, V);