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/ADT/STLExtras.h"
16 #include "llvm/Analysis/InstructionSimplify.h"
17 #include "llvm/IR/DataLayout.h"
18 #include "llvm/Support/GetElementPtrTypeIterator.h"
19 #include "llvm/Support/PatternMatch.h"
21 using namespace PatternMatch;
25 /// Class representing coefficient of floating-point addend.
26 /// This class needs to be highly efficient, which is especially true for
27 /// the constructor. As of I write this comment, the cost of the default
28 /// constructor is merely 4-byte-store-zero (Assuming compiler is able to
29 /// perform write-merging).
33 // The constructor has to initialize a APFloat, which is uncessary for
34 // most addends which have coefficient either 1 or -1. So, the constructor
35 // is expensive. In order to avoid the cost of the constructor, we should
36 // reuse some instances whenever possible. The pre-created instances
37 // FAddCombine::Add[0-5] embodies this idea.
39 FAddendCoef() : IsFp(false), BufHasFpVal(false), IntVal(0) {}
43 assert(!insaneIntVal(C) && "Insane coefficient");
44 IsFp = false; IntVal = C;
47 void set(const APFloat& C);
51 bool isZero() const { return isInt() ? !IntVal : getFpVal().isZero(); }
52 Value *getValue(Type *) const;
54 // If possible, don't define operator+/operator- etc because these
55 // operators inevitably call FAddendCoef's constructor which is not cheap.
56 void operator=(const FAddendCoef &A);
57 void operator+=(const FAddendCoef &A);
58 void operator-=(const FAddendCoef &A);
59 void operator*=(const FAddendCoef &S);
61 bool isOne() const { return isInt() && IntVal == 1; }
62 bool isTwo() const { return isInt() && IntVal == 2; }
63 bool isMinusOne() const { return isInt() && IntVal == -1; }
64 bool isMinusTwo() const { return isInt() && IntVal == -2; }
67 bool insaneIntVal(int V) { return V > 4 || V < -4; }
68 APFloat *getFpValPtr(void)
69 { return reinterpret_cast<APFloat*>(&FpValBuf.buffer[0]); }
70 const APFloat *getFpValPtr(void) const
71 { return reinterpret_cast<const APFloat*>(&FpValBuf.buffer[0]); }
73 const APFloat &getFpVal(void) const {
74 assert(IsFp && BufHasFpVal && "Incorret state");
75 return *getFpValPtr();
78 APFloat &getFpVal(void) {
79 assert(IsFp && BufHasFpVal && "Incorret state");
80 return *getFpValPtr();
83 bool isInt() const { return !IsFp; }
85 // If the coefficient is represented by an integer, promote it to a
87 void convertToFpType(const fltSemantics &Sem);
89 // Construct an APFloat from a signed integer.
90 // TODO: We should get rid of this function when APFloat can be constructed
91 // from an *SIGNED* integer.
92 APFloat createAPFloatFromInt(const fltSemantics &Sem, int Val);
97 // True iff FpValBuf contains an instance of APFloat.
100 // The integer coefficient of an individual addend is either 1 or -1,
101 // and we try to simplify at most 4 addends from neighboring at most
102 // two instructions. So the range of <IntVal> falls in [-4, 4]. APInt
103 // is overkill of this end.
106 AlignedCharArrayUnion<APFloat> FpValBuf;
109 /// FAddend is used to represent floating-point addend. An addend is
110 /// represented as <C, V>, where the V is a symbolic value, and C is a
111 /// constant coefficient. A constant addend is represented as <C, 0>.
115 FAddend() { Val = 0; }
117 Value *getSymVal (void) const { return Val; }
118 const FAddendCoef &getCoef(void) const { return Coeff; }
120 bool isConstant() const { return Val == 0; }
121 bool isZero() const { return Coeff.isZero(); }
123 void set(short Coefficient, Value *V) { Coeff.set(Coefficient), Val = V; }
124 void set(const APFloat& Coefficient, Value *V)
125 { Coeff.set(Coefficient); Val = V; }
126 void set(const ConstantFP* Coefficient, Value *V)
127 { Coeff.set(Coefficient->getValueAPF()); Val = V; }
129 void negate() { Coeff.negate(); }
131 /// Drill down the U-D chain one step to find the definition of V, and
132 /// try to break the definition into one or two addends.
133 static unsigned drillValueDownOneStep(Value* V, FAddend &A0, FAddend &A1);
135 /// Similar to FAddend::drillDownOneStep() except that the value being
136 /// splitted is the addend itself.
137 unsigned drillAddendDownOneStep(FAddend &Addend0, FAddend &Addend1) const;
139 void operator+=(const FAddend &T) {
140 assert((Val == T.Val) && "Symbolic-values disagree");
145 void Scale(const FAddendCoef& ScaleAmt) { Coeff *= ScaleAmt; }
147 // This addend has the value of "Coeff * Val".
152 /// FAddCombine is the class for optimizing an unsafe fadd/fsub along
153 /// with its neighboring at most two instructions.
157 FAddCombine(InstCombiner::BuilderTy *B) : Builder(B), Instr(0) {}
158 Value *simplify(Instruction *FAdd);
161 typedef SmallVector<const FAddend*, 4> AddendVect;
163 Value *simplifyFAdd(AddendVect& V, unsigned InstrQuota);
165 Value *performFactorization(Instruction *I);
167 /// Convert given addend to a Value
168 Value *createAddendVal(const FAddend &A, bool& NeedNeg);
170 /// Return the number of instructions needed to emit the N-ary addition.
171 unsigned calcInstrNumber(const AddendVect& Vect);
172 Value *createFSub(Value *Opnd0, Value *Opnd1);
173 Value *createFAdd(Value *Opnd0, Value *Opnd1);
174 Value *createFMul(Value *Opnd0, Value *Opnd1);
175 Value *createFDiv(Value *Opnd0, Value *Opnd1);
176 Value *createFNeg(Value *V);
177 Value *createNaryFAdd(const AddendVect& Opnds, unsigned InstrQuota);
178 void createInstPostProc(Instruction *NewInst);
180 InstCombiner::BuilderTy *Builder;
184 // Debugging stuff are clustered here.
186 unsigned CreateInstrNum;
187 void initCreateInstNum() { CreateInstrNum = 0; }
188 void incCreateInstNum() { CreateInstrNum++; }
190 void initCreateInstNum() {}
191 void incCreateInstNum() {}
196 //===----------------------------------------------------------------------===//
199 // {FAddendCoef, FAddend, FAddition, FAddCombine}.
201 //===----------------------------------------------------------------------===//
202 FAddendCoef::~FAddendCoef() {
204 getFpValPtr()->~APFloat();
207 void FAddendCoef::set(const APFloat& C) {
208 APFloat *P = getFpValPtr();
211 // As the buffer is meanless byte stream, we cannot call
212 // APFloat::operator=().
217 IsFp = BufHasFpVal = true;
220 void FAddendCoef::convertToFpType(const fltSemantics &Sem) {
224 APFloat *P = getFpValPtr();
226 new(P) APFloat(Sem, IntVal);
228 new(P) APFloat(Sem, 0 - IntVal);
231 IsFp = BufHasFpVal = true;
234 APFloat FAddendCoef::createAPFloatFromInt(const fltSemantics &Sem, int Val) {
236 return APFloat(Sem, Val);
238 APFloat T(Sem, 0 - Val);
244 void FAddendCoef::operator=(const FAddendCoef &That) {
248 set(That.getFpVal());
251 void FAddendCoef::operator+=(const FAddendCoef &That) {
252 enum APFloat::roundingMode RndMode = APFloat::rmNearestTiesToEven;
253 if (isInt() == That.isInt()) {
255 IntVal += That.IntVal;
257 getFpVal().add(That.getFpVal(), RndMode);
262 const APFloat &T = That.getFpVal();
263 convertToFpType(T.getSemantics());
264 getFpVal().add(T, RndMode);
268 APFloat &T = getFpVal();
269 T.add(createAPFloatFromInt(T.getSemantics(), That.IntVal), RndMode);
272 void FAddendCoef::operator-=(const FAddendCoef &That) {
273 enum APFloat::roundingMode RndMode = APFloat::rmNearestTiesToEven;
274 if (isInt() == That.isInt()) {
276 IntVal -= That.IntVal;
278 getFpVal().subtract(That.getFpVal(), RndMode);
283 const APFloat &T = That.getFpVal();
284 convertToFpType(T.getSemantics());
285 getFpVal().subtract(T, RndMode);
289 APFloat &T = getFpVal();
290 T.subtract(createAPFloatFromInt(T.getSemantics(), IntVal), RndMode);
293 void FAddendCoef::operator*=(const FAddendCoef &That) {
297 if (That.isMinusOne()) {
302 if (isInt() && That.isInt()) {
303 int Res = IntVal * (int)That.IntVal;
304 assert(!insaneIntVal(Res) && "Insane int value");
309 const fltSemantics &Semantic =
310 isInt() ? That.getFpVal().getSemantics() : getFpVal().getSemantics();
313 convertToFpType(Semantic);
314 APFloat &F0 = getFpVal();
317 F0.multiply(createAPFloatFromInt(Semantic, That.IntVal),
318 APFloat::rmNearestTiesToEven);
320 F0.multiply(That.getFpVal(), APFloat::rmNearestTiesToEven);
325 void FAddendCoef::negate() {
329 getFpVal().changeSign();
332 Value *FAddendCoef::getValue(Type *Ty) const {
334 ConstantFP::get(Ty, float(IntVal)) :
335 ConstantFP::get(Ty->getContext(), getFpVal());
338 // The definition of <Val> Addends
339 // =========================================
340 // A + B <1, A>, <1,B>
341 // A - B <1, A>, <1,B>
344 // A + C <1, A> <C, NULL>
345 // 0 +/- 0 <0, NULL> (corner case)
347 // Legend: A and B are not constant, C is constant
349 unsigned FAddend::drillValueDownOneStep
350 (Value *Val, FAddend &Addend0, FAddend &Addend1) {
352 if (Val == 0 || !(I = dyn_cast<Instruction>(Val)))
355 unsigned Opcode = I->getOpcode();
357 if (Opcode == Instruction::FAdd || Opcode == Instruction::FSub) {
359 Value *Opnd0 = I->getOperand(0);
360 Value *Opnd1 = I->getOperand(1);
361 if ((C0 = dyn_cast<ConstantFP>(Opnd0)) && C0->isZero())
364 if ((C1 = dyn_cast<ConstantFP>(Opnd1)) && C1->isZero())
369 Addend0.set(1, Opnd0);
375 FAddend &Addend = Opnd0 ? Addend1 : Addend0;
377 Addend.set(1, Opnd1);
380 if (Opcode == Instruction::FSub)
385 return Opnd0 && Opnd1 ? 2 : 1;
387 // Both operands are zero. Weird!
388 Addend0.set(APFloat(C0->getValueAPF().getSemantics()), 0);
392 if (I->getOpcode() == Instruction::FMul) {
393 Value *V0 = I->getOperand(0);
394 Value *V1 = I->getOperand(1);
395 if (ConstantFP *C = dyn_cast<ConstantFP>(V0)) {
400 if (ConstantFP *C = dyn_cast<ConstantFP>(V1)) {
409 // Try to break *this* addend into two addends. e.g. Suppose this addend is
410 // <2.3, V>, and V = X + Y, by calling this function, we obtain two addends,
411 // i.e. <2.3, X> and <2.3, Y>.
413 unsigned FAddend::drillAddendDownOneStep
414 (FAddend &Addend0, FAddend &Addend1) const {
418 unsigned BreakNum = FAddend::drillValueDownOneStep(Val, Addend0, Addend1);
419 if (!BreakNum || Coeff.isOne())
422 Addend0.Scale(Coeff);
425 Addend1.Scale(Coeff);
430 // Try to perform following optimization on the input instruction I. Return the
431 // simplified expression if was successful; otherwise, return 0.
433 // Instruction "I" is Simplified into
434 // -------------------------------------------------------
435 // (x * y) +/- (x * z) x * (y +/- z)
436 // (y / x) +/- (z / x) (y +/- z) / x
438 Value *FAddCombine::performFactorization(Instruction *I) {
439 assert((I->getOpcode() == Instruction::FAdd ||
440 I->getOpcode() == Instruction::FSub) && "Expect add/sub");
442 Instruction *I0 = dyn_cast<Instruction>(I->getOperand(0));
443 Instruction *I1 = dyn_cast<Instruction>(I->getOperand(1));
445 if (!I0 || !I1 || I0->getOpcode() != I1->getOpcode())
449 if (I0->getOpcode() == Instruction::FMul)
451 else if (I0->getOpcode() != Instruction::FDiv)
454 Value *Opnd0_0 = I0->getOperand(0);
455 Value *Opnd0_1 = I0->getOperand(1);
456 Value *Opnd1_0 = I1->getOperand(0);
457 Value *Opnd1_1 = I1->getOperand(1);
459 // Input Instr I Factor AddSub0 AddSub1
460 // ----------------------------------------------
461 // (x*y) +/- (x*z) x y z
462 // (y/x) +/- (z/x) x y z
465 Value *AddSub0 = 0, *AddSub1 = 0;
468 if (Opnd0_0 == Opnd1_0 || Opnd0_0 == Opnd1_1)
470 else if (Opnd0_1 == Opnd1_0 || Opnd0_1 == Opnd1_1)
474 AddSub0 = (Factor == Opnd0_0) ? Opnd0_1 : Opnd0_0;
475 AddSub1 = (Factor == Opnd1_0) ? Opnd1_1 : Opnd1_0;
477 } else if (Opnd0_1 == Opnd1_1) {
486 // Create expression "NewAddSub = AddSub0 +/- AddsSub1"
487 Value *NewAddSub = (I->getOpcode() == Instruction::FAdd) ?
488 createFAdd(AddSub0, AddSub1) :
489 createFSub(AddSub0, AddSub1);
490 if (ConstantFP *CFP = dyn_cast<ConstantFP>(NewAddSub)) {
491 const APFloat &F = CFP->getValueAPF();
497 return createFMul(Factor, NewAddSub);
499 return createFDiv(NewAddSub, Factor);
502 Value *FAddCombine::simplify(Instruction *I) {
503 assert(I->hasUnsafeAlgebra() && "Should be in unsafe mode");
505 // Currently we are not able to handle vector type.
506 if (I->getType()->isVectorTy())
509 assert((I->getOpcode() == Instruction::FAdd ||
510 I->getOpcode() == Instruction::FSub) && "Expect add/sub");
512 // Save the instruction before calling other member-functions.
515 FAddend Opnd0, Opnd1, Opnd0_0, Opnd0_1, Opnd1_0, Opnd1_1;
517 unsigned OpndNum = FAddend::drillValueDownOneStep(I, Opnd0, Opnd1);
519 // Step 1: Expand the 1st addend into Opnd0_0 and Opnd0_1.
520 unsigned Opnd0_ExpNum = 0;
521 unsigned Opnd1_ExpNum = 0;
523 if (!Opnd0.isConstant())
524 Opnd0_ExpNum = Opnd0.drillAddendDownOneStep(Opnd0_0, Opnd0_1);
526 // Step 2: Expand the 2nd addend into Opnd1_0 and Opnd1_1.
527 if (OpndNum == 2 && !Opnd1.isConstant())
528 Opnd1_ExpNum = Opnd1.drillAddendDownOneStep(Opnd1_0, Opnd1_1);
530 // Step 3: Try to optimize Opnd0_0 + Opnd0_1 + Opnd1_0 + Opnd1_1
531 if (Opnd0_ExpNum && Opnd1_ExpNum) {
533 AllOpnds.push_back(&Opnd0_0);
534 AllOpnds.push_back(&Opnd1_0);
535 if (Opnd0_ExpNum == 2)
536 AllOpnds.push_back(&Opnd0_1);
537 if (Opnd1_ExpNum == 2)
538 AllOpnds.push_back(&Opnd1_1);
540 // Compute instruction quota. We should save at least one instruction.
541 unsigned InstQuota = 0;
543 Value *V0 = I->getOperand(0);
544 Value *V1 = I->getOperand(1);
545 InstQuota = ((!isa<Constant>(V0) && V0->hasOneUse()) &&
546 (!isa<Constant>(V1) && V1->hasOneUse())) ? 2 : 1;
548 if (Value *R = simplifyFAdd(AllOpnds, InstQuota))
553 // The input instruction is : "I=0.0 +/- V". If the "V" were able to be
554 // splitted into two addends, say "V = X - Y", the instruction would have
555 // been optimized into "I = Y - X" in the previous steps.
557 const FAddendCoef &CE = Opnd0.getCoef();
558 return CE.isOne() ? Opnd0.getSymVal() : 0;
561 // step 4: Try to optimize Opnd0 + Opnd1_0 [+ Opnd1_1]
564 AllOpnds.push_back(&Opnd0);
565 AllOpnds.push_back(&Opnd1_0);
566 if (Opnd1_ExpNum == 2)
567 AllOpnds.push_back(&Opnd1_1);
569 if (Value *R = simplifyFAdd(AllOpnds, 1))
573 // step 5: Try to optimize Opnd1 + Opnd0_0 [+ Opnd0_1]
576 AllOpnds.push_back(&Opnd1);
577 AllOpnds.push_back(&Opnd0_0);
578 if (Opnd0_ExpNum == 2)
579 AllOpnds.push_back(&Opnd0_1);
581 if (Value *R = simplifyFAdd(AllOpnds, 1))
585 // step 6: Try factorization as the last resort,
586 return performFactorization(I);
589 Value *FAddCombine::simplifyFAdd(AddendVect& Addends, unsigned InstrQuota) {
591 unsigned AddendNum = Addends.size();
592 assert(AddendNum <= 4 && "Too many addends");
594 // For saving intermediate results;
595 unsigned NextTmpIdx = 0;
596 FAddend TmpResult[3];
598 // Points to the constant addend of the resulting simplified expression.
599 // If the resulting expr has constant-addend, this constant-addend is
600 // desirable to reside at the top of the resulting expression tree. Placing
601 // constant close to supper-expr(s) will potentially reveal some optimization
602 // opportunities in super-expr(s).
604 const FAddend *ConstAdd = 0;
606 // Simplified addends are placed <SimpVect>.
609 // The outer loop works on one symbolic-value at a time. Suppose the input
610 // addends are : <a1, x>, <b1, y>, <a2, x>, <c1, z>, <b2, y>, ...
611 // The symbolic-values will be processed in this order: x, y, z.
613 for (unsigned SymIdx = 0; SymIdx < AddendNum; SymIdx++) {
615 const FAddend *ThisAddend = Addends[SymIdx];
617 // This addend was processed before.
621 Value *Val = ThisAddend->getSymVal();
622 unsigned StartIdx = SimpVect.size();
623 SimpVect.push_back(ThisAddend);
625 // The inner loop collects addends sharing same symbolic-value, and these
626 // addends will be later on folded into a single addend. Following above
627 // example, if the symbolic value "y" is being processed, the inner loop
628 // will collect two addends "<b1,y>" and "<b2,Y>". These two addends will
629 // be later on folded into "<b1+b2, y>".
631 for (unsigned SameSymIdx = SymIdx + 1;
632 SameSymIdx < AddendNum; SameSymIdx++) {
633 const FAddend *T = Addends[SameSymIdx];
634 if (T && T->getSymVal() == Val) {
635 // Set null such that next iteration of the outer loop will not process
636 // this addend again.
637 Addends[SameSymIdx] = 0;
638 SimpVect.push_back(T);
642 // If multiple addends share same symbolic value, fold them together.
643 if (StartIdx + 1 != SimpVect.size()) {
644 FAddend &R = TmpResult[NextTmpIdx ++];
645 R = *SimpVect[StartIdx];
646 for (unsigned Idx = StartIdx + 1; Idx < SimpVect.size(); Idx++)
649 // Pop all addends being folded and push the resulting folded addend.
650 SimpVect.resize(StartIdx);
653 SimpVect.push_back(&R);
656 // Don't push constant addend at this time. It will be the last element
663 assert((NextTmpIdx <= array_lengthof(TmpResult) + 1) &&
664 "out-of-bound access");
667 SimpVect.push_back(ConstAdd);
670 if (!SimpVect.empty())
671 Result = createNaryFAdd(SimpVect, InstrQuota);
673 // The addition is folded to 0.0.
674 Result = ConstantFP::get(Instr->getType(), 0.0);
680 Value *FAddCombine::createNaryFAdd
681 (const AddendVect &Opnds, unsigned InstrQuota) {
682 assert(!Opnds.empty() && "Expect at least one addend");
684 // Step 1: Check if the # of instructions needed exceeds the quota.
686 unsigned InstrNeeded = calcInstrNumber(Opnds);
687 if (InstrNeeded > InstrQuota)
692 // step 2: Emit the N-ary addition.
693 // Note that at most three instructions are involved in Fadd-InstCombine: the
694 // addition in question, and at most two neighboring instructions.
695 // The resulting optimized addition should have at least one less instruction
696 // than the original addition expression tree. This implies that the resulting
697 // N-ary addition has at most two instructions, and we don't need to worry
698 // about tree-height when constructing the N-ary addition.
701 bool LastValNeedNeg = false;
703 // Iterate the addends, creating fadd/fsub using adjacent two addends.
704 for (AddendVect::const_iterator I = Opnds.begin(), E = Opnds.end();
707 Value *V = createAddendVal(**I, NeedNeg);
710 LastValNeedNeg = NeedNeg;
714 if (LastValNeedNeg == NeedNeg) {
715 LastVal = createFAdd(LastVal, V);
720 LastVal = createFSub(V, LastVal);
722 LastVal = createFSub(LastVal, V);
724 LastValNeedNeg = false;
727 if (LastValNeedNeg) {
728 LastVal = createFNeg(LastVal);
732 assert(CreateInstrNum == InstrNeeded &&
733 "Inconsistent in instruction numbers");
739 Value *FAddCombine::createFSub
740 (Value *Opnd0, Value *Opnd1) {
741 Value *V = Builder->CreateFSub(Opnd0, Opnd1);
742 if (Instruction *I = dyn_cast<Instruction>(V))
743 createInstPostProc(I);
747 Value *FAddCombine::createFNeg(Value *V) {
748 Value *Zero = cast<Value>(ConstantFP::get(V->getType(), 0.0));
749 return createFSub(Zero, V);
752 Value *FAddCombine::createFAdd
753 (Value *Opnd0, Value *Opnd1) {
754 Value *V = Builder->CreateFAdd(Opnd0, Opnd1);
755 if (Instruction *I = dyn_cast<Instruction>(V))
756 createInstPostProc(I);
760 Value *FAddCombine::createFMul(Value *Opnd0, Value *Opnd1) {
761 Value *V = Builder->CreateFMul(Opnd0, Opnd1);
762 if (Instruction *I = dyn_cast<Instruction>(V))
763 createInstPostProc(I);
767 Value *FAddCombine::createFDiv(Value *Opnd0, Value *Opnd1) {
768 Value *V = Builder->CreateFDiv(Opnd0, Opnd1);
769 if (Instruction *I = dyn_cast<Instruction>(V))
770 createInstPostProc(I);
774 void FAddCombine::createInstPostProc(Instruction *NewInstr) {
775 NewInstr->setDebugLoc(Instr->getDebugLoc());
777 // Keep track of the number of instruction created.
780 // Propagate fast-math flags
781 NewInstr->setFastMathFlags(Instr->getFastMathFlags());
784 // Return the number of instruction needed to emit the N-ary addition.
785 // NOTE: Keep this function in sync with createAddendVal().
786 unsigned FAddCombine::calcInstrNumber(const AddendVect &Opnds) {
787 unsigned OpndNum = Opnds.size();
788 unsigned InstrNeeded = OpndNum - 1;
790 // The number of addends in the form of "(-1)*x".
791 unsigned NegOpndNum = 0;
793 // Adjust the number of instructions needed to emit the N-ary add.
794 for (AddendVect::const_iterator I = Opnds.begin(), E = Opnds.end();
796 const FAddend *Opnd = *I;
797 if (Opnd->isConstant())
800 const FAddendCoef &CE = Opnd->getCoef();
801 if (CE.isMinusOne() || CE.isMinusTwo())
804 // Let the addend be "c * x". If "c == +/-1", the value of the addend
805 // is immediately available; otherwise, it needs exactly one instruction
806 // to evaluate the value.
807 if (!CE.isMinusOne() && !CE.isOne())
810 if (NegOpndNum == OpndNum)
815 // Input Addend Value NeedNeg(output)
816 // ================================================================
817 // Constant C C false
818 // <+/-1, V> V coefficient is -1
819 // <2/-2, V> "fadd V, V" coefficient is -2
820 // <C, V> "fmul V, C" false
822 // NOTE: Keep this function in sync with FAddCombine::calcInstrNumber.
823 Value *FAddCombine::createAddendVal
824 (const FAddend &Opnd, bool &NeedNeg) {
825 const FAddendCoef &Coeff = Opnd.getCoef();
827 if (Opnd.isConstant()) {
829 return Coeff.getValue(Instr->getType());
832 Value *OpndVal = Opnd.getSymVal();
834 if (Coeff.isMinusOne() || Coeff.isOne()) {
835 NeedNeg = Coeff.isMinusOne();
839 if (Coeff.isTwo() || Coeff.isMinusTwo()) {
840 NeedNeg = Coeff.isMinusTwo();
841 return createFAdd(OpndVal, OpndVal);
845 return createFMul(OpndVal, Coeff.getValue(Instr->getType()));
848 /// AddOne - Add one to a ConstantInt.
849 static Constant *AddOne(Constant *C) {
850 return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
853 /// SubOne - Subtract one from a ConstantInt.
854 static Constant *SubOne(Constant *C) {
855 return ConstantExpr::getAdd(C, ConstantInt::getAllOnesValue(C->getType()));
859 // dyn_castFoldableMul - If this value is a multiply that can be folded into
860 // other computations (because it has a constant operand), return the
861 // non-constant operand of the multiply, and set CST to point to the multiplier.
862 // Otherwise, return null.
864 static inline Value *dyn_castFoldableMul(Value *V, Constant *&CST) {
865 if (!V->hasOneUse() || !V->getType()->isIntOrIntVectorTy())
868 Instruction *I = dyn_cast<Instruction>(V);
869 if (I == 0) return 0;
871 if (I->getOpcode() == Instruction::Mul)
872 if ((CST = dyn_cast<Constant>(I->getOperand(1))))
873 return I->getOperand(0);
874 if (I->getOpcode() == Instruction::Shl)
875 if ((CST = dyn_cast<Constant>(I->getOperand(1)))) {
876 // The multiplier is really 1 << CST.
877 CST = ConstantExpr::getShl(ConstantInt::get(V->getType(), 1), CST);
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),
975 // (X + signbit) + C could have gotten canonicalized to (X ^ signbit) + C,
976 // transform them into (X + (signbit ^ C))
977 if (XorRHS->getValue().isSignBit())
978 return BinaryOperator::CreateAdd(XorLHS,
979 ConstantExpr::getXor(XorRHS, CI));
983 if (isa<Constant>(RHS) && isa<PHINode>(LHS))
984 if (Instruction *NV = FoldOpIntoPhi(I))
987 if (I.getType()->getScalarType()->isIntegerTy(1))
988 return BinaryOperator::CreateXor(LHS, RHS);
992 BinaryOperator *New =
993 BinaryOperator::CreateShl(LHS, ConstantInt::get(I.getType(), 1));
994 New->setHasNoSignedWrap(I.hasNoSignedWrap());
995 New->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
1000 // -A + -B --> -(A + B)
1001 if (Value *LHSV = dyn_castNegVal(LHS)) {
1002 if (!isa<Constant>(RHS))
1003 if (Value *RHSV = dyn_castNegVal(RHS)) {
1004 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
1005 return BinaryOperator::CreateNeg(NewAdd);
1008 return BinaryOperator::CreateSub(RHS, LHSV);
1012 if (!isa<Constant>(RHS))
1013 if (Value *V = dyn_castNegVal(RHS))
1014 return BinaryOperator::CreateSub(LHS, V);
1019 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1020 if (X == RHS) // X*C + X --> X * (C+1)
1021 return BinaryOperator::CreateMul(RHS, AddOne(C2));
1023 // X*C1 + X*C2 --> X * (C1+C2)
1025 if (X == dyn_castFoldableMul(RHS, C1))
1026 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
1029 // X + X*C --> X * (C+1)
1030 if (dyn_castFoldableMul(RHS, C2) == LHS)
1031 return BinaryOperator::CreateMul(LHS, AddOne(C2));
1034 // A+B --> A|B iff A and B have no bits set in common.
1035 if (IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
1036 APInt LHSKnownOne(IT->getBitWidth(), 0);
1037 APInt LHSKnownZero(IT->getBitWidth(), 0);
1038 ComputeMaskedBits(LHS, LHSKnownZero, LHSKnownOne);
1039 if (LHSKnownZero != 0) {
1040 APInt RHSKnownOne(IT->getBitWidth(), 0);
1041 APInt RHSKnownZero(IT->getBitWidth(), 0);
1042 ComputeMaskedBits(RHS, RHSKnownZero, RHSKnownOne);
1044 // No bits in common -> bitwise or.
1045 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
1046 return BinaryOperator::CreateOr(LHS, RHS);
1050 // W*X + Y*Z --> W * (X+Z) iff W == Y
1052 Value *W, *X, *Y, *Z;
1053 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
1054 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
1058 } else if (Y == X) {
1060 } else if (X == Z) {
1067 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
1068 return BinaryOperator::CreateMul(W, NewAdd);
1073 if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
1075 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
1076 return BinaryOperator::CreateSub(SubOne(CRHS), X);
1079 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
1080 // (X & FF00) + xx00 -> (X+xx00) & FF00
1083 if (LHS->hasOneUse() &&
1084 match(LHS, m_And(m_Value(X), m_ConstantInt(C2))) &&
1085 CRHS->getValue() == (CRHS->getValue() & C2->getValue())) {
1086 // See if all bits from the first bit set in the Add RHS up are included
1087 // in the mask. First, get the rightmost bit.
1088 const APInt &AddRHSV = CRHS->getValue();
1090 // Form a mask of all bits from the lowest bit added through the top.
1091 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
1093 // See if the and mask includes all of these bits.
1094 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
1096 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1097 // Okay, the xform is safe. Insert the new add pronto.
1098 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
1099 return BinaryOperator::CreateAnd(NewAdd, C2);
1103 // Try to fold constant add into select arguments.
1104 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
1105 if (Instruction *R = FoldOpIntoSelect(I, SI))
1109 // add (select X 0 (sub n A)) A --> select X A n
1111 SelectInst *SI = dyn_cast<SelectInst>(LHS);
1114 SI = dyn_cast<SelectInst>(RHS);
1117 if (SI && SI->hasOneUse()) {
1118 Value *TV = SI->getTrueValue();
1119 Value *FV = SI->getFalseValue();
1122 // Can we fold the add into the argument of the select?
1123 // We check both true and false select arguments for a matching subtract.
1124 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
1125 // Fold the add into the true select value.
1126 return SelectInst::Create(SI->getCondition(), N, A);
1128 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
1129 // Fold the add into the false select value.
1130 return SelectInst::Create(SI->getCondition(), A, N);
1134 // Check for (add (sext x), y), see if we can merge this into an
1135 // integer add followed by a sext.
1136 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
1137 // (add (sext x), cst) --> (sext (add x, cst'))
1138 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
1140 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
1141 if (LHSConv->hasOneUse() &&
1142 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
1143 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
1144 // Insert the new, smaller add.
1145 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
1147 return new SExtInst(NewAdd, I.getType());
1151 // (add (sext x), (sext y)) --> (sext (add int x, y))
1152 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
1153 // Only do this if x/y have the same type, if at last one of them has a
1154 // single use (so we don't increase the number of sexts), and if the
1155 // integer add will not overflow.
1156 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
1157 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
1158 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
1159 RHSConv->getOperand(0))) {
1160 // Insert the new integer add.
1161 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
1162 RHSConv->getOperand(0), "addconv");
1163 return new SExtInst(NewAdd, I.getType());
1168 // Check for (x & y) + (x ^ y)
1170 Value *A = 0, *B = 0;
1171 if (match(RHS, m_Xor(m_Value(A), m_Value(B))) &&
1172 (match(LHS, m_And(m_Specific(A), m_Specific(B))) ||
1173 match(LHS, m_And(m_Specific(B), m_Specific(A)))))
1174 return BinaryOperator::CreateOr(A, B);
1176 if (match(LHS, m_Xor(m_Value(A), m_Value(B))) &&
1177 (match(RHS, m_And(m_Specific(A), m_Specific(B))) ||
1178 match(RHS, m_And(m_Specific(B), m_Specific(A)))))
1179 return BinaryOperator::CreateOr(A, B);
1182 return Changed ? &I : 0;
1185 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
1186 bool Changed = SimplifyAssociativeOrCommutative(I);
1187 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1189 if (Value *V = SimplifyFAddInst(LHS, RHS, I.getFastMathFlags(), TD))
1190 return ReplaceInstUsesWith(I, V);
1192 if (isa<Constant>(RHS)) {
1193 if (isa<PHINode>(LHS))
1194 if (Instruction *NV = FoldOpIntoPhi(I))
1197 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
1198 if (Instruction *NV = FoldOpIntoSelect(I, SI))
1203 // -A + -B --> -(A + B)
1204 if (Value *LHSV = dyn_castFNegVal(LHS)) {
1205 Instruction *RI = BinaryOperator::CreateFSub(RHS, LHSV);
1206 RI->copyFastMathFlags(&I);
1211 if (!isa<Constant>(RHS))
1212 if (Value *V = dyn_castFNegVal(RHS)) {
1213 Instruction *RI = BinaryOperator::CreateFSub(LHS, V);
1214 RI->copyFastMathFlags(&I);
1218 // Check for (fadd double (sitofp x), y), see if we can merge this into an
1219 // integer add followed by a promotion.
1220 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
1221 // (fadd double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
1222 // ... if the constant fits in the integer value. This is useful for things
1223 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
1224 // requires a constant pool load, and generally allows the add to be better
1226 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
1228 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
1229 if (LHSConv->hasOneUse() &&
1230 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
1231 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
1232 // Insert the new integer add.
1233 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
1235 return new SIToFPInst(NewAdd, I.getType());
1239 // (fadd double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
1240 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
1241 // Only do this if x/y have the same type, if at last one of them has a
1242 // single use (so we don't increase the number of int->fp conversions),
1243 // and if the integer add will not overflow.
1244 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
1245 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
1246 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
1247 RHSConv->getOperand(0))) {
1248 // Insert the new integer add.
1249 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
1250 RHSConv->getOperand(0),"addconv");
1251 return new SIToFPInst(NewAdd, I.getType());
1256 // select C, 0, B + select C, A, 0 -> select C, A, B
1258 Value *A1, *B1, *C1, *A2, *B2, *C2;
1259 if (match(LHS, m_Select(m_Value(C1), m_Value(A1), m_Value(B1))) &&
1260 match(RHS, m_Select(m_Value(C2), m_Value(A2), m_Value(B2)))) {
1262 Constant *Z1=0, *Z2=0;
1263 Value *A, *B, *C=C1;
1264 if (match(A1, m_AnyZero()) && match(B2, m_AnyZero())) {
1265 Z1 = dyn_cast<Constant>(A1); A = A2;
1266 Z2 = dyn_cast<Constant>(B2); B = B1;
1267 } else if (match(B1, m_AnyZero()) && match(A2, m_AnyZero())) {
1268 Z1 = dyn_cast<Constant>(B1); B = B2;
1269 Z2 = dyn_cast<Constant>(A2); A = A1;
1273 (I.hasNoSignedZeros() ||
1274 (Z1->isNegativeZeroValue() && Z2->isNegativeZeroValue()))) {
1275 return SelectInst::Create(C, A, B);
1281 if (I.hasUnsafeAlgebra()) {
1282 if (Value *V = FAddCombine(Builder).simplify(&I))
1283 return ReplaceInstUsesWith(I, V);
1286 return Changed ? &I : 0;
1290 /// Optimize pointer differences into the same array into a size. Consider:
1291 /// &A[10] - &A[0]: we should compile this to "10". LHS/RHS are the pointer
1292 /// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
1294 Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS,
1296 assert(TD && "Must have target data info for this");
1298 // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
1300 bool Swapped = false;
1301 GEPOperator *GEP1 = 0, *GEP2 = 0;
1303 // For now we require one side to be the base pointer "A" or a constant
1304 // GEP derived from it.
1305 if (GEPOperator *LHSGEP = dyn_cast<GEPOperator>(LHS)) {
1307 if (LHSGEP->getOperand(0) == RHS) {
1310 } else if (GEPOperator *RHSGEP = dyn_cast<GEPOperator>(RHS)) {
1311 // (gep X, ...) - (gep X, ...)
1312 if (LHSGEP->getOperand(0)->stripPointerCasts() ==
1313 RHSGEP->getOperand(0)->stripPointerCasts()) {
1321 if (GEPOperator *RHSGEP = dyn_cast<GEPOperator>(RHS)) {
1323 if (RHSGEP->getOperand(0) == LHS) {
1326 } else if (GEPOperator *LHSGEP = dyn_cast<GEPOperator>(LHS)) {
1327 // (gep X, ...) - (gep X, ...)
1328 if (RHSGEP->getOperand(0)->stripPointerCasts() ==
1329 LHSGEP->getOperand(0)->stripPointerCasts()) {
1337 // Avoid duplicating the arithmetic if GEP2 has non-constant indices and
1340 (GEP2 != 0 && !GEP2->hasAllConstantIndices() && !GEP2->hasOneUse()))
1343 // Emit the offset of the GEP and an intptr_t.
1344 Value *Result = EmitGEPOffset(GEP1);
1346 // If we had a constant expression GEP on the other side offsetting the
1347 // pointer, subtract it from the offset we have.
1349 Value *Offset = EmitGEPOffset(GEP2);
1350 Result = Builder->CreateSub(Result, Offset);
1353 // If we have p - gep(p, ...) then we have to negate the result.
1355 Result = Builder->CreateNeg(Result, "diff.neg");
1357 return Builder->CreateIntCast(Result, Ty, true);
1361 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
1362 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1364 if (Value *V = SimplifySubInst(Op0, Op1, I.hasNoSignedWrap(),
1365 I.hasNoUnsignedWrap(), TD))
1366 return ReplaceInstUsesWith(I, V);
1368 // (A*B)-(A*C) -> A*(B-C) etc
1369 if (Value *V = SimplifyUsingDistributiveLaws(I))
1370 return ReplaceInstUsesWith(I, V);
1372 // If this is a 'B = x-(-A)', change to B = x+A. This preserves NSW/NUW.
1373 if (Value *V = dyn_castNegVal(Op1)) {
1374 BinaryOperator *Res = BinaryOperator::CreateAdd(Op0, V);
1375 Res->setHasNoSignedWrap(I.hasNoSignedWrap());
1376 Res->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
1380 if (I.getType()->isIntegerTy(1))
1381 return BinaryOperator::CreateXor(Op0, Op1);
1383 // Replace (-1 - A) with (~A).
1384 if (match(Op0, m_AllOnes()))
1385 return BinaryOperator::CreateNot(Op1);
1387 if (Constant *C = dyn_cast<Constant>(Op0)) {
1388 // C - ~X == X + (1+C)
1390 if (match(Op1, m_Not(m_Value(X))))
1391 return BinaryOperator::CreateAdd(X, AddOne(C));
1393 // Try to fold constant sub into select arguments.
1394 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1395 if (Instruction *R = FoldOpIntoSelect(I, SI))
1398 // C-(X+C2) --> (C-C2)-X
1400 if (match(Op1, m_Add(m_Value(X), m_Constant(C2))))
1401 return BinaryOperator::CreateSub(ConstantExpr::getSub(C, C2), X);
1403 if (SimplifyDemandedInstructionBits(I))
1406 // Fold (sub 0, (zext bool to B)) --> (sext bool to B)
1407 if (C->isNullValue() && match(Op1, m_ZExt(m_Value(X))))
1408 if (X->getType()->getScalarType()->isIntegerTy(1))
1409 return CastInst::CreateSExtOrBitCast(X, Op1->getType());
1411 // Fold (sub 0, (sext bool to B)) --> (zext bool to B)
1412 if (C->isNullValue() && match(Op1, m_SExt(m_Value(X))))
1413 if (X->getType()->getScalarType()->isIntegerTy(1))
1414 return CastInst::CreateZExtOrBitCast(X, Op1->getType());
1417 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1418 // -(X >>u 31) -> (X >>s 31)
1419 // -(X >>s 31) -> (X >>u 31)
1421 Value *X; ConstantInt *CI;
1422 if (match(Op1, m_LShr(m_Value(X), m_ConstantInt(CI))) &&
1423 // Verify we are shifting out everything but the sign bit.
1424 CI->getValue() == I.getType()->getPrimitiveSizeInBits()-1)
1425 return BinaryOperator::CreateAShr(X, CI);
1427 if (match(Op1, m_AShr(m_Value(X), m_ConstantInt(CI))) &&
1428 // Verify we are shifting out everything but the sign bit.
1429 CI->getValue() == I.getType()->getPrimitiveSizeInBits()-1)
1430 return BinaryOperator::CreateLShr(X, CI);
1436 // X-(X+Y) == -Y X-(Y+X) == -Y
1437 if (match(Op1, m_Add(m_Specific(Op0), m_Value(Y))) ||
1438 match(Op1, m_Add(m_Value(Y), m_Specific(Op0))))
1439 return BinaryOperator::CreateNeg(Y);
1442 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(Y))))
1443 return BinaryOperator::CreateNeg(Y);
1446 if (Op1->hasOneUse()) {
1447 Value *X = 0, *Y = 0, *Z = 0;
1451 // (X - (Y - Z)) --> (X + (Z - Y)).
1452 if (match(Op1, m_Sub(m_Value(Y), m_Value(Z))))
1453 return BinaryOperator::CreateAdd(Op0,
1454 Builder->CreateSub(Z, Y, Op1->getName()));
1456 // (X - (X & Y)) --> (X & ~Y)
1458 if (match(Op1, m_And(m_Value(Y), m_Specific(Op0))) ||
1459 match(Op1, m_And(m_Specific(Op0), m_Value(Y))))
1460 return BinaryOperator::CreateAnd(Op0,
1461 Builder->CreateNot(Y, Y->getName() + ".not"));
1463 // 0 - (X sdiv C) -> (X sdiv -C)
1464 if (match(Op1, m_SDiv(m_Value(X), m_Constant(C))) &&
1465 match(Op0, m_Zero()))
1466 return BinaryOperator::CreateSDiv(X, ConstantExpr::getNeg(C));
1468 // 0 - (X << Y) -> (-X << Y) when X is freely negatable.
1469 if (match(Op1, m_Shl(m_Value(X), m_Value(Y))) && match(Op0, m_Zero()))
1470 if (Value *XNeg = dyn_castNegVal(X))
1471 return BinaryOperator::CreateShl(XNeg, Y);
1473 // X - X*C --> X * (1-C)
1474 if (match(Op1, m_Mul(m_Specific(Op0), m_Constant(CI)))) {
1475 Constant *CP1 = ConstantExpr::getSub(ConstantInt::get(I.getType(),1), CI);
1476 return BinaryOperator::CreateMul(Op0, CP1);
1479 // X - X<<C --> X * (1-(1<<C))
1480 if (match(Op1, m_Shl(m_Specific(Op0), m_Constant(CI)))) {
1481 Constant *One = ConstantInt::get(I.getType(), 1);
1482 C = ConstantExpr::getSub(One, ConstantExpr::getShl(One, CI));
1483 return BinaryOperator::CreateMul(Op0, C);
1486 // X - A*-B -> X + A*B
1487 // X - -A*B -> X + A*B
1489 if (match(Op1, m_Mul(m_Value(A), m_Neg(m_Value(B)))) ||
1490 match(Op1, m_Mul(m_Neg(m_Value(A)), m_Value(B))))
1491 return BinaryOperator::CreateAdd(Op0, Builder->CreateMul(A, B));
1493 // X - A*CI -> X + A*-CI
1494 // X - CI*A -> X + A*-CI
1495 if (match(Op1, m_Mul(m_Value(A), m_Constant(CI))) ||
1496 match(Op1, m_Mul(m_Constant(CI), m_Value(A)))) {
1497 Value *NewMul = Builder->CreateMul(A, ConstantExpr::getNeg(CI));
1498 return BinaryOperator::CreateAdd(Op0, NewMul);
1503 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
1504 if (X == Op1) // X*C - X --> X * (C-1)
1505 return BinaryOperator::CreateMul(Op1, SubOne(C1));
1507 Constant *C2; // X*C1 - X*C2 -> X * (C1-C2)
1508 if (X == dyn_castFoldableMul(Op1, C2))
1509 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
1512 // Optimize pointer differences into the same array into a size. Consider:
1513 // &A[10] - &A[0]: we should compile this to "10".
1515 Value *LHSOp, *RHSOp;
1516 if (match(Op0, m_PtrToInt(m_Value(LHSOp))) &&
1517 match(Op1, m_PtrToInt(m_Value(RHSOp))))
1518 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
1519 return ReplaceInstUsesWith(I, Res);
1521 // trunc(p)-trunc(q) -> trunc(p-q)
1522 if (match(Op0, m_Trunc(m_PtrToInt(m_Value(LHSOp)))) &&
1523 match(Op1, m_Trunc(m_PtrToInt(m_Value(RHSOp)))))
1524 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
1525 return ReplaceInstUsesWith(I, Res);
1531 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
1532 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1534 if (Value *V = SimplifyFSubInst(Op0, Op1, I.getFastMathFlags(), TD))
1535 return ReplaceInstUsesWith(I, V);
1537 if (isa<Constant>(Op0))
1538 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1539 if (Instruction *NV = FoldOpIntoSelect(I, SI))
1542 // If this is a 'B = x-(-A)', change to B = x+A, potentially looking
1543 // through FP extensions/truncations along the way.
1544 if (Value *V = dyn_castFNegVal(Op1)) {
1545 Instruction *NewI = BinaryOperator::CreateFAdd(Op0, V);
1546 NewI->copyFastMathFlags(&I);
1549 if (FPTruncInst *FPTI = dyn_cast<FPTruncInst>(Op1)) {
1550 if (Value *V = dyn_castFNegVal(FPTI->getOperand(0))) {
1551 Value *NewTrunc = Builder->CreateFPTrunc(V, I.getType());
1552 Instruction *NewI = BinaryOperator::CreateFAdd(Op0, NewTrunc);
1553 NewI->copyFastMathFlags(&I);
1556 } else if (FPExtInst *FPEI = dyn_cast<FPExtInst>(Op1)) {
1557 if (Value *V = dyn_castFNegVal(FPEI->getOperand(0))) {
1558 Value *NewExt = Builder->CreateFPExt(V, I.getType());
1559 Instruction *NewI = BinaryOperator::CreateFAdd(Op0, NewExt);
1560 NewI->copyFastMathFlags(&I);
1565 if (I.hasUnsafeAlgebra()) {
1566 if (Value *V = FAddCombine(Builder).simplify(&I))
1567 return ReplaceInstUsesWith(I, V);