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/IR/GetElementPtrTypeIterator.h"
19 #include "llvm/IR/PatternMatch.h"
21 using namespace PatternMatch;
23 #define DEBUG_TYPE "instcombine"
27 /// Class representing coefficient of floating-point addend.
28 /// This class needs to be highly efficient, which is especially true for
29 /// the constructor. As of I write this comment, the cost of the default
30 /// constructor is merely 4-byte-store-zero (Assuming compiler is able to
31 /// perform write-merging).
35 // The constructor has to initialize a APFloat, which is uncessary for
36 // most addends which have coefficient either 1 or -1. So, the constructor
37 // is expensive. In order to avoid the cost of the constructor, we should
38 // reuse some instances whenever possible. The pre-created instances
39 // FAddCombine::Add[0-5] embodies this idea.
41 FAddendCoef() : IsFp(false), BufHasFpVal(false), IntVal(0) {}
45 assert(!insaneIntVal(C) && "Insane coefficient");
46 IsFp = false; IntVal = C;
49 void set(const APFloat& C);
53 bool isZero() const { return isInt() ? !IntVal : getFpVal().isZero(); }
54 Value *getValue(Type *) const;
56 // If possible, don't define operator+/operator- etc because these
57 // operators inevitably call FAddendCoef's constructor which is not cheap.
58 void operator=(const FAddendCoef &A);
59 void operator+=(const FAddendCoef &A);
60 void operator-=(const FAddendCoef &A);
61 void operator*=(const FAddendCoef &S);
63 bool isOne() const { return isInt() && IntVal == 1; }
64 bool isTwo() const { return isInt() && IntVal == 2; }
65 bool isMinusOne() const { return isInt() && IntVal == -1; }
66 bool isMinusTwo() const { return isInt() && IntVal == -2; }
69 bool insaneIntVal(int V) { return V > 4 || V < -4; }
70 APFloat *getFpValPtr(void)
71 { return reinterpret_cast<APFloat*>(&FpValBuf.buffer[0]); }
72 const APFloat *getFpValPtr(void) const
73 { return reinterpret_cast<const APFloat*>(&FpValBuf.buffer[0]); }
75 const APFloat &getFpVal(void) const {
76 assert(IsFp && BufHasFpVal && "Incorret state");
77 return *getFpValPtr();
80 APFloat &getFpVal(void) {
81 assert(IsFp && BufHasFpVal && "Incorret state");
82 return *getFpValPtr();
85 bool isInt() const { return !IsFp; }
87 // If the coefficient is represented by an integer, promote it to a
89 void convertToFpType(const fltSemantics &Sem);
91 // Construct an APFloat from a signed integer.
92 // TODO: We should get rid of this function when APFloat can be constructed
93 // from an *SIGNED* integer.
94 APFloat createAPFloatFromInt(const fltSemantics &Sem, int Val);
99 // True iff FpValBuf contains an instance of APFloat.
102 // The integer coefficient of an individual addend is either 1 or -1,
103 // and we try to simplify at most 4 addends from neighboring at most
104 // two instructions. So the range of <IntVal> falls in [-4, 4]. APInt
105 // is overkill of this end.
108 AlignedCharArrayUnion<APFloat> FpValBuf;
111 /// FAddend is used to represent floating-point addend. An addend is
112 /// represented as <C, V>, where the V is a symbolic value, and C is a
113 /// constant coefficient. A constant addend is represented as <C, 0>.
117 FAddend() { Val = nullptr; }
119 Value *getSymVal (void) const { return Val; }
120 const FAddendCoef &getCoef(void) const { return Coeff; }
122 bool isConstant() const { return Val == nullptr; }
123 bool isZero() const { return Coeff.isZero(); }
125 void set(short Coefficient, Value *V) { Coeff.set(Coefficient), Val = V; }
126 void set(const APFloat& Coefficient, Value *V)
127 { Coeff.set(Coefficient); Val = V; }
128 void set(const ConstantFP* Coefficient, Value *V)
129 { Coeff.set(Coefficient->getValueAPF()); Val = V; }
131 void negate() { Coeff.negate(); }
133 /// Drill down the U-D chain one step to find the definition of V, and
134 /// try to break the definition into one or two addends.
135 static unsigned drillValueDownOneStep(Value* V, FAddend &A0, FAddend &A1);
137 /// Similar to FAddend::drillDownOneStep() except that the value being
138 /// splitted is the addend itself.
139 unsigned drillAddendDownOneStep(FAddend &Addend0, FAddend &Addend1) const;
141 void operator+=(const FAddend &T) {
142 assert((Val == T.Val) && "Symbolic-values disagree");
147 void Scale(const FAddendCoef& ScaleAmt) { Coeff *= ScaleAmt; }
149 // This addend has the value of "Coeff * Val".
154 /// FAddCombine is the class for optimizing an unsafe fadd/fsub along
155 /// with its neighboring at most two instructions.
159 FAddCombine(InstCombiner::BuilderTy *B) : Builder(B), Instr(nullptr) {}
160 Value *simplify(Instruction *FAdd);
163 typedef SmallVector<const FAddend*, 4> AddendVect;
165 Value *simplifyFAdd(AddendVect& V, unsigned InstrQuota);
167 Value *performFactorization(Instruction *I);
169 /// Convert given addend to a Value
170 Value *createAddendVal(const FAddend &A, bool& NeedNeg);
172 /// Return the number of instructions needed to emit the N-ary addition.
173 unsigned calcInstrNumber(const AddendVect& Vect);
174 Value *createFSub(Value *Opnd0, Value *Opnd1);
175 Value *createFAdd(Value *Opnd0, Value *Opnd1);
176 Value *createFMul(Value *Opnd0, Value *Opnd1);
177 Value *createFDiv(Value *Opnd0, Value *Opnd1);
178 Value *createFNeg(Value *V);
179 Value *createNaryFAdd(const AddendVect& Opnds, unsigned InstrQuota);
180 void createInstPostProc(Instruction *NewInst, bool NoNumber = false);
182 InstCombiner::BuilderTy *Builder;
186 // Debugging stuff are clustered here.
188 unsigned CreateInstrNum;
189 void initCreateInstNum() { CreateInstrNum = 0; }
190 void incCreateInstNum() { CreateInstrNum++; }
192 void initCreateInstNum() {}
193 void incCreateInstNum() {}
198 //===----------------------------------------------------------------------===//
201 // {FAddendCoef, FAddend, FAddition, FAddCombine}.
203 //===----------------------------------------------------------------------===//
204 FAddendCoef::~FAddendCoef() {
206 getFpValPtr()->~APFloat();
209 void FAddendCoef::set(const APFloat& C) {
210 APFloat *P = getFpValPtr();
213 // As the buffer is meanless byte stream, we cannot call
214 // APFloat::operator=().
219 IsFp = BufHasFpVal = true;
222 void FAddendCoef::convertToFpType(const fltSemantics &Sem) {
226 APFloat *P = getFpValPtr();
228 new(P) APFloat(Sem, IntVal);
230 new(P) APFloat(Sem, 0 - IntVal);
233 IsFp = BufHasFpVal = true;
236 APFloat FAddendCoef::createAPFloatFromInt(const fltSemantics &Sem, int Val) {
238 return APFloat(Sem, Val);
240 APFloat T(Sem, 0 - Val);
246 void FAddendCoef::operator=(const FAddendCoef &That) {
250 set(That.getFpVal());
253 void FAddendCoef::operator+=(const FAddendCoef &That) {
254 enum APFloat::roundingMode RndMode = APFloat::rmNearestTiesToEven;
255 if (isInt() == That.isInt()) {
257 IntVal += That.IntVal;
259 getFpVal().add(That.getFpVal(), RndMode);
264 const APFloat &T = That.getFpVal();
265 convertToFpType(T.getSemantics());
266 getFpVal().add(T, RndMode);
270 APFloat &T = getFpVal();
271 T.add(createAPFloatFromInt(T.getSemantics(), That.IntVal), RndMode);
274 void FAddendCoef::operator-=(const FAddendCoef &That) {
275 enum APFloat::roundingMode RndMode = APFloat::rmNearestTiesToEven;
276 if (isInt() == That.isInt()) {
278 IntVal -= That.IntVal;
280 getFpVal().subtract(That.getFpVal(), RndMode);
285 const APFloat &T = That.getFpVal();
286 convertToFpType(T.getSemantics());
287 getFpVal().subtract(T, RndMode);
291 APFloat &T = getFpVal();
292 T.subtract(createAPFloatFromInt(T.getSemantics(), IntVal), RndMode);
295 void FAddendCoef::operator*=(const FAddendCoef &That) {
299 if (That.isMinusOne()) {
304 if (isInt() && That.isInt()) {
305 int Res = IntVal * (int)That.IntVal;
306 assert(!insaneIntVal(Res) && "Insane int value");
311 const fltSemantics &Semantic =
312 isInt() ? That.getFpVal().getSemantics() : getFpVal().getSemantics();
315 convertToFpType(Semantic);
316 APFloat &F0 = getFpVal();
319 F0.multiply(createAPFloatFromInt(Semantic, That.IntVal),
320 APFloat::rmNearestTiesToEven);
322 F0.multiply(That.getFpVal(), APFloat::rmNearestTiesToEven);
327 void FAddendCoef::negate() {
331 getFpVal().changeSign();
334 Value *FAddendCoef::getValue(Type *Ty) const {
336 ConstantFP::get(Ty, float(IntVal)) :
337 ConstantFP::get(Ty->getContext(), getFpVal());
340 // The definition of <Val> Addends
341 // =========================================
342 // A + B <1, A>, <1,B>
343 // A - B <1, A>, <1,B>
346 // A + C <1, A> <C, NULL>
347 // 0 +/- 0 <0, NULL> (corner case)
349 // Legend: A and B are not constant, C is constant
351 unsigned FAddend::drillValueDownOneStep
352 (Value *Val, FAddend &Addend0, FAddend &Addend1) {
353 Instruction *I = nullptr;
354 if (!Val || !(I = dyn_cast<Instruction>(Val)))
357 unsigned Opcode = I->getOpcode();
359 if (Opcode == Instruction::FAdd || Opcode == Instruction::FSub) {
361 Value *Opnd0 = I->getOperand(0);
362 Value *Opnd1 = I->getOperand(1);
363 if ((C0 = dyn_cast<ConstantFP>(Opnd0)) && C0->isZero())
366 if ((C1 = dyn_cast<ConstantFP>(Opnd1)) && C1->isZero())
371 Addend0.set(1, Opnd0);
373 Addend0.set(C0, nullptr);
377 FAddend &Addend = Opnd0 ? Addend1 : Addend0;
379 Addend.set(1, Opnd1);
381 Addend.set(C1, nullptr);
382 if (Opcode == Instruction::FSub)
387 return Opnd0 && Opnd1 ? 2 : 1;
389 // Both operands are zero. Weird!
390 Addend0.set(APFloat(C0->getValueAPF().getSemantics()), nullptr);
394 if (I->getOpcode() == Instruction::FMul) {
395 Value *V0 = I->getOperand(0);
396 Value *V1 = I->getOperand(1);
397 if (ConstantFP *C = dyn_cast<ConstantFP>(V0)) {
402 if (ConstantFP *C = dyn_cast<ConstantFP>(V1)) {
411 // Try to break *this* addend into two addends. e.g. Suppose this addend is
412 // <2.3, V>, and V = X + Y, by calling this function, we obtain two addends,
413 // i.e. <2.3, X> and <2.3, Y>.
415 unsigned FAddend::drillAddendDownOneStep
416 (FAddend &Addend0, FAddend &Addend1) const {
420 unsigned BreakNum = FAddend::drillValueDownOneStep(Val, Addend0, Addend1);
421 if (!BreakNum || Coeff.isOne())
424 Addend0.Scale(Coeff);
427 Addend1.Scale(Coeff);
432 // Try to perform following optimization on the input instruction I. Return the
433 // simplified expression if was successful; otherwise, return 0.
435 // Instruction "I" is Simplified into
436 // -------------------------------------------------------
437 // (x * y) +/- (x * z) x * (y +/- z)
438 // (y / x) +/- (z / x) (y +/- z) / x
440 Value *FAddCombine::performFactorization(Instruction *I) {
441 assert((I->getOpcode() == Instruction::FAdd ||
442 I->getOpcode() == Instruction::FSub) && "Expect add/sub");
444 Instruction *I0 = dyn_cast<Instruction>(I->getOperand(0));
445 Instruction *I1 = dyn_cast<Instruction>(I->getOperand(1));
447 if (!I0 || !I1 || I0->getOpcode() != I1->getOpcode())
451 if (I0->getOpcode() == Instruction::FMul)
453 else if (I0->getOpcode() != Instruction::FDiv)
456 Value *Opnd0_0 = I0->getOperand(0);
457 Value *Opnd0_1 = I0->getOperand(1);
458 Value *Opnd1_0 = I1->getOperand(0);
459 Value *Opnd1_1 = I1->getOperand(1);
461 // Input Instr I Factor AddSub0 AddSub1
462 // ----------------------------------------------
463 // (x*y) +/- (x*z) x y z
464 // (y/x) +/- (z/x) x y z
466 Value *Factor = nullptr;
467 Value *AddSub0 = nullptr, *AddSub1 = nullptr;
470 if (Opnd0_0 == Opnd1_0 || Opnd0_0 == Opnd1_1)
472 else if (Opnd0_1 == Opnd1_0 || Opnd0_1 == Opnd1_1)
476 AddSub0 = (Factor == Opnd0_0) ? Opnd0_1 : Opnd0_0;
477 AddSub1 = (Factor == Opnd1_0) ? Opnd1_1 : Opnd1_0;
479 } else if (Opnd0_1 == Opnd1_1) {
489 Flags.setUnsafeAlgebra();
490 if (I0) Flags &= I->getFastMathFlags();
491 if (I1) Flags &= I->getFastMathFlags();
493 // Create expression "NewAddSub = AddSub0 +/- AddsSub1"
494 Value *NewAddSub = (I->getOpcode() == Instruction::FAdd) ?
495 createFAdd(AddSub0, AddSub1) :
496 createFSub(AddSub0, AddSub1);
497 if (ConstantFP *CFP = dyn_cast<ConstantFP>(NewAddSub)) {
498 const APFloat &F = CFP->getValueAPF();
501 } else if (Instruction *II = dyn_cast<Instruction>(NewAddSub))
502 II->setFastMathFlags(Flags);
505 Value *RI = createFMul(Factor, NewAddSub);
506 if (Instruction *II = dyn_cast<Instruction>(RI))
507 II->setFastMathFlags(Flags);
511 Value *RI = createFDiv(NewAddSub, Factor);
512 if (Instruction *II = dyn_cast<Instruction>(RI))
513 II->setFastMathFlags(Flags);
517 Value *FAddCombine::simplify(Instruction *I) {
518 assert(I->hasUnsafeAlgebra() && "Should be in unsafe mode");
520 // Currently we are not able to handle vector type.
521 if (I->getType()->isVectorTy())
524 assert((I->getOpcode() == Instruction::FAdd ||
525 I->getOpcode() == Instruction::FSub) && "Expect add/sub");
527 // Save the instruction before calling other member-functions.
530 FAddend Opnd0, Opnd1, Opnd0_0, Opnd0_1, Opnd1_0, Opnd1_1;
532 unsigned OpndNum = FAddend::drillValueDownOneStep(I, Opnd0, Opnd1);
534 // Step 1: Expand the 1st addend into Opnd0_0 and Opnd0_1.
535 unsigned Opnd0_ExpNum = 0;
536 unsigned Opnd1_ExpNum = 0;
538 if (!Opnd0.isConstant())
539 Opnd0_ExpNum = Opnd0.drillAddendDownOneStep(Opnd0_0, Opnd0_1);
541 // Step 2: Expand the 2nd addend into Opnd1_0 and Opnd1_1.
542 if (OpndNum == 2 && !Opnd1.isConstant())
543 Opnd1_ExpNum = Opnd1.drillAddendDownOneStep(Opnd1_0, Opnd1_1);
545 // Step 3: Try to optimize Opnd0_0 + Opnd0_1 + Opnd1_0 + Opnd1_1
546 if (Opnd0_ExpNum && Opnd1_ExpNum) {
548 AllOpnds.push_back(&Opnd0_0);
549 AllOpnds.push_back(&Opnd1_0);
550 if (Opnd0_ExpNum == 2)
551 AllOpnds.push_back(&Opnd0_1);
552 if (Opnd1_ExpNum == 2)
553 AllOpnds.push_back(&Opnd1_1);
555 // Compute instruction quota. We should save at least one instruction.
556 unsigned InstQuota = 0;
558 Value *V0 = I->getOperand(0);
559 Value *V1 = I->getOperand(1);
560 InstQuota = ((!isa<Constant>(V0) && V0->hasOneUse()) &&
561 (!isa<Constant>(V1) && V1->hasOneUse())) ? 2 : 1;
563 if (Value *R = simplifyFAdd(AllOpnds, InstQuota))
568 // The input instruction is : "I=0.0 +/- V". If the "V" were able to be
569 // splitted into two addends, say "V = X - Y", the instruction would have
570 // been optimized into "I = Y - X" in the previous steps.
572 const FAddendCoef &CE = Opnd0.getCoef();
573 return CE.isOne() ? Opnd0.getSymVal() : nullptr;
576 // step 4: Try to optimize Opnd0 + Opnd1_0 [+ Opnd1_1]
579 AllOpnds.push_back(&Opnd0);
580 AllOpnds.push_back(&Opnd1_0);
581 if (Opnd1_ExpNum == 2)
582 AllOpnds.push_back(&Opnd1_1);
584 if (Value *R = simplifyFAdd(AllOpnds, 1))
588 // step 5: Try to optimize Opnd1 + Opnd0_0 [+ Opnd0_1]
591 AllOpnds.push_back(&Opnd1);
592 AllOpnds.push_back(&Opnd0_0);
593 if (Opnd0_ExpNum == 2)
594 AllOpnds.push_back(&Opnd0_1);
596 if (Value *R = simplifyFAdd(AllOpnds, 1))
600 // step 6: Try factorization as the last resort,
601 return performFactorization(I);
604 Value *FAddCombine::simplifyFAdd(AddendVect& Addends, unsigned InstrQuota) {
606 unsigned AddendNum = Addends.size();
607 assert(AddendNum <= 4 && "Too many addends");
609 // For saving intermediate results;
610 unsigned NextTmpIdx = 0;
611 FAddend TmpResult[3];
613 // Points to the constant addend of the resulting simplified expression.
614 // If the resulting expr has constant-addend, this constant-addend is
615 // desirable to reside at the top of the resulting expression tree. Placing
616 // constant close to supper-expr(s) will potentially reveal some optimization
617 // opportunities in super-expr(s).
619 const FAddend *ConstAdd = nullptr;
621 // Simplified addends are placed <SimpVect>.
624 // The outer loop works on one symbolic-value at a time. Suppose the input
625 // addends are : <a1, x>, <b1, y>, <a2, x>, <c1, z>, <b2, y>, ...
626 // The symbolic-values will be processed in this order: x, y, z.
628 for (unsigned SymIdx = 0; SymIdx < AddendNum; SymIdx++) {
630 const FAddend *ThisAddend = Addends[SymIdx];
632 // This addend was processed before.
636 Value *Val = ThisAddend->getSymVal();
637 unsigned StartIdx = SimpVect.size();
638 SimpVect.push_back(ThisAddend);
640 // The inner loop collects addends sharing same symbolic-value, and these
641 // addends will be later on folded into a single addend. Following above
642 // example, if the symbolic value "y" is being processed, the inner loop
643 // will collect two addends "<b1,y>" and "<b2,Y>". These two addends will
644 // be later on folded into "<b1+b2, y>".
646 for (unsigned SameSymIdx = SymIdx + 1;
647 SameSymIdx < AddendNum; SameSymIdx++) {
648 const FAddend *T = Addends[SameSymIdx];
649 if (T && T->getSymVal() == Val) {
650 // Set null such that next iteration of the outer loop will not process
651 // this addend again.
652 Addends[SameSymIdx] = nullptr;
653 SimpVect.push_back(T);
657 // If multiple addends share same symbolic value, fold them together.
658 if (StartIdx + 1 != SimpVect.size()) {
659 FAddend &R = TmpResult[NextTmpIdx ++];
660 R = *SimpVect[StartIdx];
661 for (unsigned Idx = StartIdx + 1; Idx < SimpVect.size(); Idx++)
664 // Pop all addends being folded and push the resulting folded addend.
665 SimpVect.resize(StartIdx);
668 SimpVect.push_back(&R);
671 // Don't push constant addend at this time. It will be the last element
678 assert((NextTmpIdx <= array_lengthof(TmpResult) + 1) &&
679 "out-of-bound access");
682 SimpVect.push_back(ConstAdd);
685 if (!SimpVect.empty())
686 Result = createNaryFAdd(SimpVect, InstrQuota);
688 // The addition is folded to 0.0.
689 Result = ConstantFP::get(Instr->getType(), 0.0);
695 Value *FAddCombine::createNaryFAdd
696 (const AddendVect &Opnds, unsigned InstrQuota) {
697 assert(!Opnds.empty() && "Expect at least one addend");
699 // Step 1: Check if the # of instructions needed exceeds the quota.
701 unsigned InstrNeeded = calcInstrNumber(Opnds);
702 if (InstrNeeded > InstrQuota)
707 // step 2: Emit the N-ary addition.
708 // Note that at most three instructions are involved in Fadd-InstCombine: the
709 // addition in question, and at most two neighboring instructions.
710 // The resulting optimized addition should have at least one less instruction
711 // than the original addition expression tree. This implies that the resulting
712 // N-ary addition has at most two instructions, and we don't need to worry
713 // about tree-height when constructing the N-ary addition.
715 Value *LastVal = nullptr;
716 bool LastValNeedNeg = false;
718 // Iterate the addends, creating fadd/fsub using adjacent two addends.
719 for (AddendVect::const_iterator I = Opnds.begin(), E = Opnds.end();
722 Value *V = createAddendVal(**I, NeedNeg);
725 LastValNeedNeg = NeedNeg;
729 if (LastValNeedNeg == NeedNeg) {
730 LastVal = createFAdd(LastVal, V);
735 LastVal = createFSub(V, LastVal);
737 LastVal = createFSub(LastVal, V);
739 LastValNeedNeg = false;
742 if (LastValNeedNeg) {
743 LastVal = createFNeg(LastVal);
747 assert(CreateInstrNum == InstrNeeded &&
748 "Inconsistent in instruction numbers");
754 Value *FAddCombine::createFSub
755 (Value *Opnd0, Value *Opnd1) {
756 Value *V = Builder->CreateFSub(Opnd0, Opnd1);
757 if (Instruction *I = dyn_cast<Instruction>(V))
758 createInstPostProc(I);
762 Value *FAddCombine::createFNeg(Value *V) {
763 Value *Zero = cast<Value>(ConstantFP::get(V->getType(), 0.0));
764 Value *NewV = createFSub(Zero, V);
765 if (Instruction *I = dyn_cast<Instruction>(NewV))
766 createInstPostProc(I, true); // fneg's don't receive instruction numbers.
770 Value *FAddCombine::createFAdd
771 (Value *Opnd0, Value *Opnd1) {
772 Value *V = Builder->CreateFAdd(Opnd0, Opnd1);
773 if (Instruction *I = dyn_cast<Instruction>(V))
774 createInstPostProc(I);
778 Value *FAddCombine::createFMul(Value *Opnd0, Value *Opnd1) {
779 Value *V = Builder->CreateFMul(Opnd0, Opnd1);
780 if (Instruction *I = dyn_cast<Instruction>(V))
781 createInstPostProc(I);
785 Value *FAddCombine::createFDiv(Value *Opnd0, Value *Opnd1) {
786 Value *V = Builder->CreateFDiv(Opnd0, Opnd1);
787 if (Instruction *I = dyn_cast<Instruction>(V))
788 createInstPostProc(I);
792 void FAddCombine::createInstPostProc(Instruction *NewInstr,
794 NewInstr->setDebugLoc(Instr->getDebugLoc());
796 // Keep track of the number of instruction created.
800 // Propagate fast-math flags
801 NewInstr->setFastMathFlags(Instr->getFastMathFlags());
804 // Return the number of instruction needed to emit the N-ary addition.
805 // NOTE: Keep this function in sync with createAddendVal().
806 unsigned FAddCombine::calcInstrNumber(const AddendVect &Opnds) {
807 unsigned OpndNum = Opnds.size();
808 unsigned InstrNeeded = OpndNum - 1;
810 // The number of addends in the form of "(-1)*x".
811 unsigned NegOpndNum = 0;
813 // Adjust the number of instructions needed to emit the N-ary add.
814 for (AddendVect::const_iterator I = Opnds.begin(), E = Opnds.end();
816 const FAddend *Opnd = *I;
817 if (Opnd->isConstant())
820 const FAddendCoef &CE = Opnd->getCoef();
821 if (CE.isMinusOne() || CE.isMinusTwo())
824 // Let the addend be "c * x". If "c == +/-1", the value of the addend
825 // is immediately available; otherwise, it needs exactly one instruction
826 // to evaluate the value.
827 if (!CE.isMinusOne() && !CE.isOne())
830 if (NegOpndNum == OpndNum)
835 // Input Addend Value NeedNeg(output)
836 // ================================================================
837 // Constant C C false
838 // <+/-1, V> V coefficient is -1
839 // <2/-2, V> "fadd V, V" coefficient is -2
840 // <C, V> "fmul V, C" false
842 // NOTE: Keep this function in sync with FAddCombine::calcInstrNumber.
843 Value *FAddCombine::createAddendVal
844 (const FAddend &Opnd, bool &NeedNeg) {
845 const FAddendCoef &Coeff = Opnd.getCoef();
847 if (Opnd.isConstant()) {
849 return Coeff.getValue(Instr->getType());
852 Value *OpndVal = Opnd.getSymVal();
854 if (Coeff.isMinusOne() || Coeff.isOne()) {
855 NeedNeg = Coeff.isMinusOne();
859 if (Coeff.isTwo() || Coeff.isMinusTwo()) {
860 NeedNeg = Coeff.isMinusTwo();
861 return createFAdd(OpndVal, OpndVal);
865 return createFMul(OpndVal, Coeff.getValue(Instr->getType()));
868 // dyn_castFoldableMul - If this value is a multiply that can be folded into
869 // other computations (because it has a constant operand), return the
870 // non-constant operand of the multiply, and set CST to point to the multiplier.
871 // Otherwise, return null.
873 static inline Value *dyn_castFoldableMul(Value *V, Constant *&CST) {
874 if (!V->hasOneUse() || !V->getType()->isIntOrIntVectorTy())
877 Instruction *I = dyn_cast<Instruction>(V);
878 if (!I) return nullptr;
880 if (I->getOpcode() == Instruction::Mul)
881 if ((CST = dyn_cast<Constant>(I->getOperand(1))))
882 return I->getOperand(0);
883 if (I->getOpcode() == Instruction::Shl)
884 if ((CST = dyn_cast<Constant>(I->getOperand(1)))) {
885 // The multiplier is really 1 << CST.
886 CST = ConstantExpr::getShl(ConstantInt::get(V->getType(), 1), CST);
887 return I->getOperand(0);
892 // If one of the operands only has one non-zero bit, and if the other
893 // operand has a known-zero bit in a more significant place than it (not
894 // including the sign bit) the ripple may go up to and fill the zero, but
895 // won't change the sign. For example, (X & ~4) + 1.
896 // FIXME: Handle case where LHS has a zero before the 1 in the RHS, but also
898 static bool CheckRippleForAdd(APInt Op0KnownZero, APInt Op0KnownOne,
899 APInt Op1KnownZero, APInt Op1KnownOne) {
900 // Make sure that one of the operand has only one bit set to 1 and all other
902 if ((~Op1KnownZero).countPopulation() == 1) {
903 int BitWidth = Op0KnownZero.getBitWidth();
905 Op0KnownZero.clearBit(BitWidth - 1);
906 int Op1OnePosition = BitWidth - Op1KnownOne.countLeadingZeros() - 1;
907 int Op0ZeroPosition = BitWidth - Op0KnownZero.countLeadingZeros() - 1;
908 if ((Op0ZeroPosition != (BitWidth - 1)) &&
909 (Op0ZeroPosition >= Op1OnePosition))
915 /// WillNotOverflowSignedAdd - Return true if we can prove that:
916 /// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
917 /// This basically requires proving that the add in the original type would not
918 /// overflow to change the sign bit or have a carry out.
919 /// TODO: Handle this for Vectors.
920 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
921 // There are different heuristics we can use for this. Here are some simple
924 // Add has the property that adding any two 2's complement numbers can only
925 // have one carry bit which can change a sign. As such, if LHS and RHS each
926 // have at least two sign bits, we know that the addition of the two values
927 // will sign extend fine.
928 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
931 if (IntegerType *IT = dyn_cast<IntegerType>(LHS->getType())) {
933 int BitWidth = IT->getBitWidth();
934 APInt LHSKnownZero(BitWidth, 0, /*isSigned*/ true);
935 APInt LHSKnownOne(BitWidth, 0, /*isSigned*/ true);
936 computeKnownBits(LHS, LHSKnownZero, LHSKnownOne);
938 APInt RHSKnownZero(BitWidth, 0, /*isSigned*/ true);
939 APInt RHSKnownOne(BitWidth, 0, /*isSigned*/ true);
940 computeKnownBits(RHS, RHSKnownZero, RHSKnownOne);
942 // Addition of two 2's compliment numbers having opposite signs will never
944 if ((LHSKnownOne[BitWidth - 1] && RHSKnownZero[BitWidth - 1]) ||
945 (LHSKnownZero[BitWidth - 1] && RHSKnownOne[BitWidth - 1]))
948 // Check if carry bit of addition will not cause overflow.
949 if (CheckRippleForAdd(LHSKnownZero, LHSKnownOne, RHSKnownZero, RHSKnownOne))
951 if (CheckRippleForAdd(RHSKnownZero, RHSKnownOne, LHSKnownZero, LHSKnownOne))
957 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
958 bool Changed = SimplifyAssociativeOrCommutative(I);
959 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
961 if (Value *V = SimplifyVectorOp(I))
962 return ReplaceInstUsesWith(I, V);
964 if (Value *V = SimplifyAddInst(LHS, RHS, I.hasNoSignedWrap(),
965 I.hasNoUnsignedWrap(), DL))
966 return ReplaceInstUsesWith(I, V);
968 // (A*B)+(A*C) -> A*(B+C) etc
969 if (Value *V = SimplifyUsingDistributiveLaws(I))
970 return ReplaceInstUsesWith(I, V);
972 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
973 // X + (signbit) --> X ^ signbit
974 const APInt &Val = CI->getValue();
976 return BinaryOperator::CreateXor(LHS, RHS);
978 // See if SimplifyDemandedBits can simplify this. This handles stuff like
979 // (X & 254)+1 -> (X&254)|1
980 if (SimplifyDemandedInstructionBits(I))
983 // zext(bool) + C -> bool ? C + 1 : C
984 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
985 if (ZI->getSrcTy()->isIntegerTy(1))
986 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
988 Value *XorLHS = nullptr; ConstantInt *XorRHS = nullptr;
989 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
990 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
991 const APInt &RHSVal = CI->getValue();
992 unsigned ExtendAmt = 0;
993 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
994 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
995 if (XorRHS->getValue() == -RHSVal) {
996 if (RHSVal.isPowerOf2())
997 ExtendAmt = TySizeBits - RHSVal.logBase2() - 1;
998 else if (XorRHS->getValue().isPowerOf2())
999 ExtendAmt = TySizeBits - XorRHS->getValue().logBase2() - 1;
1003 APInt Mask = APInt::getHighBitsSet(TySizeBits, ExtendAmt);
1004 if (!MaskedValueIsZero(XorLHS, Mask))
1009 Constant *ShAmt = ConstantInt::get(I.getType(), ExtendAmt);
1010 Value *NewShl = Builder->CreateShl(XorLHS, ShAmt, "sext");
1011 return BinaryOperator::CreateAShr(NewShl, ShAmt);
1014 // If this is a xor that was canonicalized from a sub, turn it back into
1015 // a sub and fuse this add with it.
1016 if (LHS->hasOneUse() && (XorRHS->getValue()+1).isPowerOf2()) {
1017 IntegerType *IT = cast<IntegerType>(I.getType());
1018 APInt LHSKnownOne(IT->getBitWidth(), 0);
1019 APInt LHSKnownZero(IT->getBitWidth(), 0);
1020 computeKnownBits(XorLHS, LHSKnownZero, LHSKnownOne);
1021 if ((XorRHS->getValue() | LHSKnownZero).isAllOnesValue())
1022 return BinaryOperator::CreateSub(ConstantExpr::getAdd(XorRHS, CI),
1025 // (X + signbit) + C could have gotten canonicalized to (X ^ signbit) + C,
1026 // transform them into (X + (signbit ^ C))
1027 if (XorRHS->getValue().isSignBit())
1028 return BinaryOperator::CreateAdd(XorLHS,
1029 ConstantExpr::getXor(XorRHS, CI));
1033 if (isa<Constant>(RHS) && isa<PHINode>(LHS))
1034 if (Instruction *NV = FoldOpIntoPhi(I))
1037 if (I.getType()->getScalarType()->isIntegerTy(1))
1038 return BinaryOperator::CreateXor(LHS, RHS);
1042 BinaryOperator *New =
1043 BinaryOperator::CreateShl(LHS, ConstantInt::get(I.getType(), 1));
1044 New->setHasNoSignedWrap(I.hasNoSignedWrap());
1045 New->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
1050 // -A + -B --> -(A + B)
1051 if (Value *LHSV = dyn_castNegVal(LHS)) {
1052 if (!isa<Constant>(RHS))
1053 if (Value *RHSV = dyn_castNegVal(RHS)) {
1054 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
1055 return BinaryOperator::CreateNeg(NewAdd);
1058 return BinaryOperator::CreateSub(RHS, LHSV);
1062 if (!isa<Constant>(RHS))
1063 if (Value *V = dyn_castNegVal(RHS))
1064 return BinaryOperator::CreateSub(LHS, V);
1069 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1070 if (X == RHS) // X*C + X --> X * (C+1)
1071 return BinaryOperator::CreateMul(RHS, AddOne(C2));
1073 // X*C1 + X*C2 --> X * (C1+C2)
1075 if (X == dyn_castFoldableMul(RHS, C1))
1076 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
1079 // X + X*C --> X * (C+1)
1080 if (dyn_castFoldableMul(RHS, C2) == LHS)
1081 return BinaryOperator::CreateMul(LHS, AddOne(C2));
1084 // A+B --> A|B iff A and B have no bits set in common.
1085 if (IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
1086 APInt LHSKnownOne(IT->getBitWidth(), 0);
1087 APInt LHSKnownZero(IT->getBitWidth(), 0);
1088 computeKnownBits(LHS, LHSKnownZero, LHSKnownOne);
1089 if (LHSKnownZero != 0) {
1090 APInt RHSKnownOne(IT->getBitWidth(), 0);
1091 APInt RHSKnownZero(IT->getBitWidth(), 0);
1092 computeKnownBits(RHS, RHSKnownZero, RHSKnownOne);
1094 // No bits in common -> bitwise or.
1095 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
1096 return BinaryOperator::CreateOr(LHS, RHS);
1100 // W*X + Y*Z --> W * (X+Z) iff W == Y
1102 Value *W, *X, *Y, *Z;
1103 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
1104 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
1108 } else if (Y == X) {
1110 } else if (X == Z) {
1117 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
1118 return BinaryOperator::CreateMul(W, NewAdd);
1123 if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
1125 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
1126 return BinaryOperator::CreateSub(SubOne(CRHS), X);
1129 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
1130 // (X & FF00) + xx00 -> (X+xx00) & FF00
1133 if (LHS->hasOneUse() &&
1134 match(LHS, m_And(m_Value(X), m_ConstantInt(C2))) &&
1135 CRHS->getValue() == (CRHS->getValue() & C2->getValue())) {
1136 // See if all bits from the first bit set in the Add RHS up are included
1137 // in the mask. First, get the rightmost bit.
1138 const APInt &AddRHSV = CRHS->getValue();
1140 // Form a mask of all bits from the lowest bit added through the top.
1141 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
1143 // See if the and mask includes all of these bits.
1144 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
1146 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1147 // Okay, the xform is safe. Insert the new add pronto.
1148 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
1149 return BinaryOperator::CreateAnd(NewAdd, C2);
1153 // Try to fold constant add into select arguments.
1154 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
1155 if (Instruction *R = FoldOpIntoSelect(I, SI))
1159 // add (select X 0 (sub n A)) A --> select X A n
1161 SelectInst *SI = dyn_cast<SelectInst>(LHS);
1164 SI = dyn_cast<SelectInst>(RHS);
1167 if (SI && SI->hasOneUse()) {
1168 Value *TV = SI->getTrueValue();
1169 Value *FV = SI->getFalseValue();
1172 // Can we fold the add into the argument of the select?
1173 // We check both true and false select arguments for a matching subtract.
1174 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
1175 // Fold the add into the true select value.
1176 return SelectInst::Create(SI->getCondition(), N, A);
1178 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
1179 // Fold the add into the false select value.
1180 return SelectInst::Create(SI->getCondition(), A, N);
1184 // Check for (add (sext x), y), see if we can merge this into an
1185 // integer add followed by a sext.
1186 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
1187 // (add (sext x), cst) --> (sext (add x, cst'))
1188 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
1190 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
1191 if (LHSConv->hasOneUse() &&
1192 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
1193 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
1194 // Insert the new, smaller add.
1195 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
1197 return new SExtInst(NewAdd, I.getType());
1201 // (add (sext x), (sext y)) --> (sext (add int x, y))
1202 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
1203 // Only do this if x/y have the same type, if at last one of them has a
1204 // single use (so we don't increase the number of sexts), and if the
1205 // integer add will not overflow.
1206 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
1207 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
1208 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
1209 RHSConv->getOperand(0))) {
1210 // Insert the new integer add.
1211 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
1212 RHSConv->getOperand(0), "addconv");
1213 return new SExtInst(NewAdd, I.getType());
1218 // Check for (x & y) + (x ^ y)
1220 Value *A = nullptr, *B = nullptr;
1221 if (match(RHS, m_Xor(m_Value(A), m_Value(B))) &&
1222 (match(LHS, m_And(m_Specific(A), m_Specific(B))) ||
1223 match(LHS, m_And(m_Specific(B), m_Specific(A)))))
1224 return BinaryOperator::CreateOr(A, B);
1226 if (match(LHS, m_Xor(m_Value(A), m_Value(B))) &&
1227 (match(RHS, m_And(m_Specific(A), m_Specific(B))) ||
1228 match(RHS, m_And(m_Specific(B), m_Specific(A)))))
1229 return BinaryOperator::CreateOr(A, B);
1232 return Changed ? &I : nullptr;
1235 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
1236 bool Changed = SimplifyAssociativeOrCommutative(I);
1237 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1239 if (Value *V = SimplifyVectorOp(I))
1240 return ReplaceInstUsesWith(I, V);
1242 if (Value *V = SimplifyFAddInst(LHS, RHS, I.getFastMathFlags(), DL))
1243 return ReplaceInstUsesWith(I, V);
1245 if (isa<Constant>(RHS)) {
1246 if (isa<PHINode>(LHS))
1247 if (Instruction *NV = FoldOpIntoPhi(I))
1250 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
1251 if (Instruction *NV = FoldOpIntoSelect(I, SI))
1256 // -A + -B --> -(A + B)
1257 if (Value *LHSV = dyn_castFNegVal(LHS)) {
1258 Instruction *RI = BinaryOperator::CreateFSub(RHS, LHSV);
1259 RI->copyFastMathFlags(&I);
1264 if (!isa<Constant>(RHS))
1265 if (Value *V = dyn_castFNegVal(RHS)) {
1266 Instruction *RI = BinaryOperator::CreateFSub(LHS, V);
1267 RI->copyFastMathFlags(&I);
1271 // Check for (fadd double (sitofp x), y), see if we can merge this into an
1272 // integer add followed by a promotion.
1273 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
1274 // (fadd double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
1275 // ... if the constant fits in the integer value. This is useful for things
1276 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
1277 // requires a constant pool load, and generally allows the add to be better
1279 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
1281 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
1282 if (LHSConv->hasOneUse() &&
1283 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
1284 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
1285 // Insert the new integer add.
1286 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
1288 return new SIToFPInst(NewAdd, I.getType());
1292 // (fadd double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
1293 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
1294 // Only do this if x/y have the same type, if at last one of them has a
1295 // single use (so we don't increase the number of int->fp conversions),
1296 // and if the integer add will not overflow.
1297 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
1298 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
1299 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
1300 RHSConv->getOperand(0))) {
1301 // Insert the new integer add.
1302 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
1303 RHSConv->getOperand(0),"addconv");
1304 return new SIToFPInst(NewAdd, I.getType());
1309 // select C, 0, B + select C, A, 0 -> select C, A, B
1311 Value *A1, *B1, *C1, *A2, *B2, *C2;
1312 if (match(LHS, m_Select(m_Value(C1), m_Value(A1), m_Value(B1))) &&
1313 match(RHS, m_Select(m_Value(C2), m_Value(A2), m_Value(B2)))) {
1315 Constant *Z1=nullptr, *Z2=nullptr;
1316 Value *A, *B, *C=C1;
1317 if (match(A1, m_AnyZero()) && match(B2, m_AnyZero())) {
1318 Z1 = dyn_cast<Constant>(A1); A = A2;
1319 Z2 = dyn_cast<Constant>(B2); B = B1;
1320 } else if (match(B1, m_AnyZero()) && match(A2, m_AnyZero())) {
1321 Z1 = dyn_cast<Constant>(B1); B = B2;
1322 Z2 = dyn_cast<Constant>(A2); A = A1;
1326 (I.hasNoSignedZeros() ||
1327 (Z1->isNegativeZeroValue() && Z2->isNegativeZeroValue()))) {
1328 return SelectInst::Create(C, A, B);
1334 if (I.hasUnsafeAlgebra()) {
1335 if (Value *V = FAddCombine(Builder).simplify(&I))
1336 return ReplaceInstUsesWith(I, V);
1339 return Changed ? &I : nullptr;
1343 /// Optimize pointer differences into the same array into a size. Consider:
1344 /// &A[10] - &A[0]: we should compile this to "10". LHS/RHS are the pointer
1345 /// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
1347 Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS,
1349 assert(DL && "Must have target data info for this");
1351 // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
1353 bool Swapped = false;
1354 GEPOperator *GEP1 = nullptr, *GEP2 = nullptr;
1356 // For now we require one side to be the base pointer "A" or a constant
1357 // GEP derived from it.
1358 if (GEPOperator *LHSGEP = dyn_cast<GEPOperator>(LHS)) {
1360 if (LHSGEP->getOperand(0) == RHS) {
1363 } else if (GEPOperator *RHSGEP = dyn_cast<GEPOperator>(RHS)) {
1364 // (gep X, ...) - (gep X, ...)
1365 if (LHSGEP->getOperand(0)->stripPointerCasts() ==
1366 RHSGEP->getOperand(0)->stripPointerCasts()) {
1374 if (GEPOperator *RHSGEP = dyn_cast<GEPOperator>(RHS)) {
1376 if (RHSGEP->getOperand(0) == LHS) {
1379 } else if (GEPOperator *LHSGEP = dyn_cast<GEPOperator>(LHS)) {
1380 // (gep X, ...) - (gep X, ...)
1381 if (RHSGEP->getOperand(0)->stripPointerCasts() ==
1382 LHSGEP->getOperand(0)->stripPointerCasts()) {
1390 // Avoid duplicating the arithmetic if GEP2 has non-constant indices and
1393 (GEP2 && !GEP2->hasAllConstantIndices() && !GEP2->hasOneUse()))
1396 // Emit the offset of the GEP and an intptr_t.
1397 Value *Result = EmitGEPOffset(GEP1);
1399 // If we had a constant expression GEP on the other side offsetting the
1400 // pointer, subtract it from the offset we have.
1402 Value *Offset = EmitGEPOffset(GEP2);
1403 Result = Builder->CreateSub(Result, Offset);
1406 // If we have p - gep(p, ...) then we have to negate the result.
1408 Result = Builder->CreateNeg(Result, "diff.neg");
1410 return Builder->CreateIntCast(Result, Ty, true);
1414 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
1415 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1417 if (Value *V = SimplifyVectorOp(I))
1418 return ReplaceInstUsesWith(I, V);
1420 if (Value *V = SimplifySubInst(Op0, Op1, I.hasNoSignedWrap(),
1421 I.hasNoUnsignedWrap(), DL))
1422 return ReplaceInstUsesWith(I, V);
1424 // (A*B)-(A*C) -> A*(B-C) etc
1425 if (Value *V = SimplifyUsingDistributiveLaws(I))
1426 return ReplaceInstUsesWith(I, V);
1428 // If this is a 'B = x-(-A)', change to B = x+A. This preserves NSW/NUW.
1429 if (Value *V = dyn_castNegVal(Op1)) {
1430 BinaryOperator *Res = BinaryOperator::CreateAdd(Op0, V);
1431 Res->setHasNoSignedWrap(I.hasNoSignedWrap());
1432 Res->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
1436 if (I.getType()->isIntegerTy(1))
1437 return BinaryOperator::CreateXor(Op0, Op1);
1439 // Replace (-1 - A) with (~A).
1440 if (match(Op0, m_AllOnes()))
1441 return BinaryOperator::CreateNot(Op1);
1443 if (Constant *C = dyn_cast<Constant>(Op0)) {
1444 // C - ~X == X + (1+C)
1446 if (match(Op1, m_Not(m_Value(X))))
1447 return BinaryOperator::CreateAdd(X, AddOne(C));
1449 // Try to fold constant sub into select arguments.
1450 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1451 if (Instruction *R = FoldOpIntoSelect(I, SI))
1454 // C-(X+C2) --> (C-C2)-X
1456 if (match(Op1, m_Add(m_Value(X), m_Constant(C2))))
1457 return BinaryOperator::CreateSub(ConstantExpr::getSub(C, C2), X);
1459 if (SimplifyDemandedInstructionBits(I))
1462 // Fold (sub 0, (zext bool to B)) --> (sext bool to B)
1463 if (C->isNullValue() && match(Op1, m_ZExt(m_Value(X))))
1464 if (X->getType()->getScalarType()->isIntegerTy(1))
1465 return CastInst::CreateSExtOrBitCast(X, Op1->getType());
1467 // Fold (sub 0, (sext bool to B)) --> (zext bool to B)
1468 if (C->isNullValue() && match(Op1, m_SExt(m_Value(X))))
1469 if (X->getType()->getScalarType()->isIntegerTy(1))
1470 return CastInst::CreateZExtOrBitCast(X, Op1->getType());
1473 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1474 // -(X >>u 31) -> (X >>s 31)
1475 // -(X >>s 31) -> (X >>u 31)
1477 Value *X; ConstantInt *CI;
1478 if (match(Op1, m_LShr(m_Value(X), m_ConstantInt(CI))) &&
1479 // Verify we are shifting out everything but the sign bit.
1480 CI->getValue() == I.getType()->getPrimitiveSizeInBits()-1)
1481 return BinaryOperator::CreateAShr(X, CI);
1483 if (match(Op1, m_AShr(m_Value(X), m_ConstantInt(CI))) &&
1484 // Verify we are shifting out everything but the sign bit.
1485 CI->getValue() == I.getType()->getPrimitiveSizeInBits()-1)
1486 return BinaryOperator::CreateLShr(X, CI);
1492 // X-(X+Y) == -Y X-(Y+X) == -Y
1493 if (match(Op1, m_Add(m_Specific(Op0), m_Value(Y))) ||
1494 match(Op1, m_Add(m_Value(Y), m_Specific(Op0))))
1495 return BinaryOperator::CreateNeg(Y);
1498 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(Y))))
1499 return BinaryOperator::CreateNeg(Y);
1502 if (Op1->hasOneUse()) {
1503 Value *X = nullptr, *Y = nullptr, *Z = nullptr;
1504 Constant *C = nullptr;
1505 Constant *CI = nullptr;
1507 // (X - (Y - Z)) --> (X + (Z - Y)).
1508 if (match(Op1, m_Sub(m_Value(Y), m_Value(Z))))
1509 return BinaryOperator::CreateAdd(Op0,
1510 Builder->CreateSub(Z, Y, Op1->getName()));
1512 // (X - (X & Y)) --> (X & ~Y)
1514 if (match(Op1, m_And(m_Value(Y), m_Specific(Op0))) ||
1515 match(Op1, m_And(m_Specific(Op0), m_Value(Y))))
1516 return BinaryOperator::CreateAnd(Op0,
1517 Builder->CreateNot(Y, Y->getName() + ".not"));
1519 // 0 - (X sdiv C) -> (X sdiv -C)
1520 if (match(Op1, m_SDiv(m_Value(X), m_Constant(C))) &&
1521 match(Op0, m_Zero()))
1522 return BinaryOperator::CreateSDiv(X, ConstantExpr::getNeg(C));
1524 // 0 - (X << Y) -> (-X << Y) when X is freely negatable.
1525 if (match(Op1, m_Shl(m_Value(X), m_Value(Y))) && match(Op0, m_Zero()))
1526 if (Value *XNeg = dyn_castNegVal(X))
1527 return BinaryOperator::CreateShl(XNeg, Y);
1529 // X - X*C --> X * (1-C)
1530 if (match(Op1, m_Mul(m_Specific(Op0), m_Constant(CI)))) {
1531 Constant *CP1 = ConstantExpr::getSub(ConstantInt::get(I.getType(),1), CI);
1532 return BinaryOperator::CreateMul(Op0, CP1);
1535 // X - X<<C --> X * (1-(1<<C))
1536 if (match(Op1, m_Shl(m_Specific(Op0), m_Constant(CI)))) {
1537 Constant *One = ConstantInt::get(I.getType(), 1);
1538 C = ConstantExpr::getSub(One, ConstantExpr::getShl(One, CI));
1539 return BinaryOperator::CreateMul(Op0, C);
1542 // X - A*-B -> X + A*B
1543 // X - -A*B -> X + A*B
1545 if (match(Op1, m_Mul(m_Value(A), m_Neg(m_Value(B)))) ||
1546 match(Op1, m_Mul(m_Neg(m_Value(A)), m_Value(B))))
1547 return BinaryOperator::CreateAdd(Op0, Builder->CreateMul(A, B));
1549 // X - A*CI -> X + A*-CI
1550 // X - CI*A -> X + A*-CI
1551 if (match(Op1, m_Mul(m_Value(A), m_Constant(CI))) ||
1552 match(Op1, m_Mul(m_Constant(CI), m_Value(A)))) {
1553 Value *NewMul = Builder->CreateMul(A, ConstantExpr::getNeg(CI));
1554 return BinaryOperator::CreateAdd(Op0, NewMul);
1559 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
1560 if (X == Op1) // X*C - X --> X * (C-1)
1561 return BinaryOperator::CreateMul(Op1, SubOne(C1));
1563 Constant *C2; // X*C1 - X*C2 -> X * (C1-C2)
1564 if (X == dyn_castFoldableMul(Op1, C2))
1565 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
1568 // Optimize pointer differences into the same array into a size. Consider:
1569 // &A[10] - &A[0]: we should compile this to "10".
1571 Value *LHSOp, *RHSOp;
1572 if (match(Op0, m_PtrToInt(m_Value(LHSOp))) &&
1573 match(Op1, m_PtrToInt(m_Value(RHSOp))))
1574 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
1575 return ReplaceInstUsesWith(I, Res);
1577 // trunc(p)-trunc(q) -> trunc(p-q)
1578 if (match(Op0, m_Trunc(m_PtrToInt(m_Value(LHSOp)))) &&
1579 match(Op1, m_Trunc(m_PtrToInt(m_Value(RHSOp)))))
1580 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
1581 return ReplaceInstUsesWith(I, Res);
1587 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
1588 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1590 if (Value *V = SimplifyVectorOp(I))
1591 return ReplaceInstUsesWith(I, V);
1593 if (Value *V = SimplifyFSubInst(Op0, Op1, I.getFastMathFlags(), DL))
1594 return ReplaceInstUsesWith(I, V);
1596 if (isa<Constant>(Op0))
1597 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1598 if (Instruction *NV = FoldOpIntoSelect(I, SI))
1601 // If this is a 'B = x-(-A)', change to B = x+A, potentially looking
1602 // through FP extensions/truncations along the way.
1603 if (Value *V = dyn_castFNegVal(Op1)) {
1604 Instruction *NewI = BinaryOperator::CreateFAdd(Op0, V);
1605 NewI->copyFastMathFlags(&I);
1608 if (FPTruncInst *FPTI = dyn_cast<FPTruncInst>(Op1)) {
1609 if (Value *V = dyn_castFNegVal(FPTI->getOperand(0))) {
1610 Value *NewTrunc = Builder->CreateFPTrunc(V, I.getType());
1611 Instruction *NewI = BinaryOperator::CreateFAdd(Op0, NewTrunc);
1612 NewI->copyFastMathFlags(&I);
1615 } else if (FPExtInst *FPEI = dyn_cast<FPExtInst>(Op1)) {
1616 if (Value *V = dyn_castFNegVal(FPEI->getOperand(0))) {
1617 Value *NewExt = Builder->CreateFPExt(V, I.getType());
1618 Instruction *NewI = BinaryOperator::CreateFAdd(Op0, NewExt);
1619 NewI->copyFastMathFlags(&I);
1624 if (I.hasUnsafeAlgebra()) {
1625 if (Value *V = FAddCombine(Builder).simplify(&I))
1626 return ReplaceInstUsesWith(I, V);