1 //===- InstCombineAddSub.cpp ------------------------------------*- C++ -*-===//
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 "InstCombineInternal.h"
15 #include "llvm/ADT/APFloat.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/Analysis/InstructionSimplify.h"
20 #include "llvm/Analysis/ValueTracking.h"
21 #include "llvm/IR/Constant.h"
22 #include "llvm/IR/Constants.h"
23 #include "llvm/IR/InstrTypes.h"
24 #include "llvm/IR/Instruction.h"
25 #include "llvm/IR/Instructions.h"
26 #include "llvm/IR/Operator.h"
27 #include "llvm/IR/PatternMatch.h"
28 #include "llvm/IR/Type.h"
29 #include "llvm/IR/Value.h"
30 #include "llvm/Support/AlignOf.h"
31 #include "llvm/Support/Casting.h"
32 #include "llvm/Support/KnownBits.h"
37 using namespace PatternMatch;
39 #define DEBUG_TYPE "instcombine"
43 /// Class representing coefficient of floating-point addend.
44 /// This class needs to be highly efficient, which is especially true for
45 /// the constructor. As of I write this comment, the cost of the default
46 /// constructor is merely 4-byte-store-zero (Assuming compiler is able to
47 /// perform write-merging).
51 // The constructor has to initialize a APFloat, which is unnecessary for
52 // most addends which have coefficient either 1 or -1. So, the constructor
53 // is expensive. In order to avoid the cost of the constructor, we should
54 // reuse some instances whenever possible. The pre-created instances
55 // FAddCombine::Add[0-5] embodies this idea.
56 FAddendCoef() = default;
59 // If possible, don't define operator+/operator- etc because these
60 // operators inevitably call FAddendCoef's constructor which is not cheap.
61 void operator=(const FAddendCoef &A);
62 void operator+=(const FAddendCoef &A);
63 void operator*=(const FAddendCoef &S);
66 assert(!insaneIntVal(C) && "Insane coefficient");
67 IsFp = false; IntVal = C;
70 void set(const APFloat& C);
74 bool isZero() const { return isInt() ? !IntVal : getFpVal().isZero(); }
75 Value *getValue(Type *) const;
77 bool isOne() const { return isInt() && IntVal == 1; }
78 bool isTwo() const { return isInt() && IntVal == 2; }
79 bool isMinusOne() const { return isInt() && IntVal == -1; }
80 bool isMinusTwo() const { return isInt() && IntVal == -2; }
83 bool insaneIntVal(int V) { return V > 4 || V < -4; }
85 APFloat *getFpValPtr()
86 { return reinterpret_cast<APFloat *>(&FpValBuf.buffer[0]); }
88 const APFloat *getFpValPtr() const
89 { return reinterpret_cast<const APFloat *>(&FpValBuf.buffer[0]); }
91 const APFloat &getFpVal() const {
92 assert(IsFp && BufHasFpVal && "Incorret state");
93 return *getFpValPtr();
97 assert(IsFp && BufHasFpVal && "Incorret state");
98 return *getFpValPtr();
101 bool isInt() const { return !IsFp; }
103 // If the coefficient is represented by an integer, promote it to a
105 void convertToFpType(const fltSemantics &Sem);
107 // Construct an APFloat from a signed integer.
108 // TODO: We should get rid of this function when APFloat can be constructed
109 // from an *SIGNED* integer.
110 APFloat createAPFloatFromInt(const fltSemantics &Sem, int Val);
114 // True iff FpValBuf contains an instance of APFloat.
115 bool BufHasFpVal = false;
117 // The integer coefficient of an individual addend is either 1 or -1,
118 // and we try to simplify at most 4 addends from neighboring at most
119 // two instructions. So the range of <IntVal> falls in [-4, 4]. APInt
120 // is overkill of this end.
123 AlignedCharArrayUnion<APFloat> FpValBuf;
126 /// FAddend is used to represent floating-point addend. An addend is
127 /// represented as <C, V>, where the V is a symbolic value, and C is a
128 /// constant coefficient. A constant addend is represented as <C, 0>.
133 void operator+=(const FAddend &T) {
134 assert((Val == T.Val) && "Symbolic-values disagree");
138 Value *getSymVal() const { return Val; }
139 const FAddendCoef &getCoef() const { return Coeff; }
141 bool isConstant() const { return Val == nullptr; }
142 bool isZero() const { return Coeff.isZero(); }
144 void set(short Coefficient, Value *V) {
145 Coeff.set(Coefficient);
148 void set(const APFloat &Coefficient, Value *V) {
149 Coeff.set(Coefficient);
152 void set(const ConstantFP *Coefficient, Value *V) {
153 Coeff.set(Coefficient->getValueAPF());
157 void negate() { Coeff.negate(); }
159 /// Drill down the U-D chain one step to find the definition of V, and
160 /// try to break the definition into one or two addends.
161 static unsigned drillValueDownOneStep(Value* V, FAddend &A0, FAddend &A1);
163 /// Similar to FAddend::drillDownOneStep() except that the value being
164 /// splitted is the addend itself.
165 unsigned drillAddendDownOneStep(FAddend &Addend0, FAddend &Addend1) const;
168 void Scale(const FAddendCoef& ScaleAmt) { Coeff *= ScaleAmt; }
170 // This addend has the value of "Coeff * Val".
171 Value *Val = nullptr;
175 /// FAddCombine is the class for optimizing an unsafe fadd/fsub along
176 /// with its neighboring at most two instructions.
180 FAddCombine(InstCombiner::BuilderTy &B) : Builder(B) {}
182 Value *simplify(Instruction *FAdd);
185 using AddendVect = SmallVector<const FAddend *, 4>;
187 Value *simplifyFAdd(AddendVect& V, unsigned InstrQuota);
189 Value *performFactorization(Instruction *I);
191 /// Convert given addend to a Value
192 Value *createAddendVal(const FAddend &A, bool& NeedNeg);
194 /// Return the number of instructions needed to emit the N-ary addition.
195 unsigned calcInstrNumber(const AddendVect& Vect);
197 Value *createFSub(Value *Opnd0, Value *Opnd1);
198 Value *createFAdd(Value *Opnd0, Value *Opnd1);
199 Value *createFMul(Value *Opnd0, Value *Opnd1);
200 Value *createFDiv(Value *Opnd0, Value *Opnd1);
201 Value *createFNeg(Value *V);
202 Value *createNaryFAdd(const AddendVect& Opnds, unsigned InstrQuota);
203 void createInstPostProc(Instruction *NewInst, bool NoNumber = false);
205 // Debugging stuff are clustered here.
207 unsigned CreateInstrNum;
208 void initCreateInstNum() { CreateInstrNum = 0; }
209 void incCreateInstNum() { CreateInstrNum++; }
211 void initCreateInstNum() {}
212 void incCreateInstNum() {}
215 InstCombiner::BuilderTy &Builder;
216 Instruction *Instr = nullptr;
219 } // end anonymous namespace
221 //===----------------------------------------------------------------------===//
224 // {FAddendCoef, FAddend, FAddition, FAddCombine}.
226 //===----------------------------------------------------------------------===//
227 FAddendCoef::~FAddendCoef() {
229 getFpValPtr()->~APFloat();
232 void FAddendCoef::set(const APFloat& C) {
233 APFloat *P = getFpValPtr();
236 // As the buffer is meanless byte stream, we cannot call
237 // APFloat::operator=().
242 IsFp = BufHasFpVal = true;
245 void FAddendCoef::convertToFpType(const fltSemantics &Sem) {
249 APFloat *P = getFpValPtr();
251 new(P) APFloat(Sem, IntVal);
253 new(P) APFloat(Sem, 0 - IntVal);
256 IsFp = BufHasFpVal = true;
259 APFloat FAddendCoef::createAPFloatFromInt(const fltSemantics &Sem, int Val) {
261 return APFloat(Sem, Val);
263 APFloat T(Sem, 0 - Val);
269 void FAddendCoef::operator=(const FAddendCoef &That) {
273 set(That.getFpVal());
276 void FAddendCoef::operator+=(const FAddendCoef &That) {
277 enum APFloat::roundingMode RndMode = APFloat::rmNearestTiesToEven;
278 if (isInt() == That.isInt()) {
280 IntVal += That.IntVal;
282 getFpVal().add(That.getFpVal(), RndMode);
287 const APFloat &T = That.getFpVal();
288 convertToFpType(T.getSemantics());
289 getFpVal().add(T, RndMode);
293 APFloat &T = getFpVal();
294 T.add(createAPFloatFromInt(T.getSemantics(), That.IntVal), RndMode);
297 void FAddendCoef::operator*=(const FAddendCoef &That) {
301 if (That.isMinusOne()) {
306 if (isInt() && That.isInt()) {
307 int Res = IntVal * (int)That.IntVal;
308 assert(!insaneIntVal(Res) && "Insane int value");
313 const fltSemantics &Semantic =
314 isInt() ? That.getFpVal().getSemantics() : getFpVal().getSemantics();
317 convertToFpType(Semantic);
318 APFloat &F0 = getFpVal();
321 F0.multiply(createAPFloatFromInt(Semantic, That.IntVal),
322 APFloat::rmNearestTiesToEven);
324 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
350 unsigned FAddend::drillValueDownOneStep
351 (Value *Val, FAddend &Addend0, FAddend &Addend1) {
352 Instruction *I = nullptr;
353 if (!Val || !(I = dyn_cast<Instruction>(Val)))
356 unsigned Opcode = I->getOpcode();
358 if (Opcode == Instruction::FAdd || Opcode == Instruction::FSub) {
360 Value *Opnd0 = I->getOperand(0);
361 Value *Opnd1 = I->getOperand(1);
362 if ((C0 = dyn_cast<ConstantFP>(Opnd0)) && C0->isZero())
365 if ((C1 = dyn_cast<ConstantFP>(Opnd1)) && C1->isZero())
370 Addend0.set(1, Opnd0);
372 Addend0.set(C0, nullptr);
376 FAddend &Addend = Opnd0 ? Addend1 : Addend0;
378 Addend.set(1, Opnd1);
380 Addend.set(C1, nullptr);
381 if (Opcode == Instruction::FSub)
386 return Opnd0 && Opnd1 ? 2 : 1;
388 // Both operands are zero. Weird!
389 Addend0.set(APFloat(C0->getValueAPF().getSemantics()), nullptr);
393 if (I->getOpcode() == Instruction::FMul) {
394 Value *V0 = I->getOperand(0);
395 Value *V1 = I->getOperand(1);
396 if (ConstantFP *C = dyn_cast<ConstantFP>(V0)) {
401 if (ConstantFP *C = dyn_cast<ConstantFP>(V1)) {
410 // Try to break *this* addend into two addends. e.g. Suppose this addend is
411 // <2.3, V>, and V = X + Y, by calling this function, we obtain two addends,
412 // i.e. <2.3, X> and <2.3, Y>.
413 unsigned FAddend::drillAddendDownOneStep
414 (FAddend &Addend0, FAddend &Addend1) const {
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
437 Value *FAddCombine::performFactorization(Instruction *I) {
438 assert((I->getOpcode() == Instruction::FAdd ||
439 I->getOpcode() == Instruction::FSub) && "Expect add/sub");
441 Instruction *I0 = dyn_cast<Instruction>(I->getOperand(0));
442 Instruction *I1 = dyn_cast<Instruction>(I->getOperand(1));
444 if (!I0 || !I1 || I0->getOpcode() != I1->getOpcode())
448 if (I0->getOpcode() == Instruction::FMul)
450 else if (I0->getOpcode() != Instruction::FDiv)
453 Value *Opnd0_0 = I0->getOperand(0);
454 Value *Opnd0_1 = I0->getOperand(1);
455 Value *Opnd1_0 = I1->getOperand(0);
456 Value *Opnd1_1 = I1->getOperand(1);
458 // Input Instr I Factor AddSub0 AddSub1
459 // ----------------------------------------------
460 // (x*y) +/- (x*z) x y z
461 // (y/x) +/- (z/x) x y z
462 Value *Factor = nullptr;
463 Value *AddSub0 = nullptr, *AddSub1 = nullptr;
466 if (Opnd0_0 == Opnd1_0 || Opnd0_0 == Opnd1_1)
468 else if (Opnd0_1 == Opnd1_0 || Opnd0_1 == Opnd1_1)
472 AddSub0 = (Factor == Opnd0_0) ? Opnd0_1 : Opnd0_0;
473 AddSub1 = (Factor == Opnd1_0) ? Opnd1_1 : Opnd1_0;
475 } else if (Opnd0_1 == Opnd1_1) {
486 if (I0) Flags &= I->getFastMathFlags();
487 if (I1) Flags &= I->getFastMathFlags();
489 // Create expression "NewAddSub = AddSub0 +/- AddsSub1"
490 Value *NewAddSub = (I->getOpcode() == Instruction::FAdd) ?
491 createFAdd(AddSub0, AddSub1) :
492 createFSub(AddSub0, AddSub1);
493 if (ConstantFP *CFP = dyn_cast<ConstantFP>(NewAddSub)) {
494 const APFloat &F = CFP->getValueAPF();
497 } else if (Instruction *II = dyn_cast<Instruction>(NewAddSub))
498 II->setFastMathFlags(Flags);
501 Value *RI = createFMul(Factor, NewAddSub);
502 if (Instruction *II = dyn_cast<Instruction>(RI))
503 II->setFastMathFlags(Flags);
507 Value *RI = createFDiv(NewAddSub, Factor);
508 if (Instruction *II = dyn_cast<Instruction>(RI))
509 II->setFastMathFlags(Flags);
513 Value *FAddCombine::simplify(Instruction *I) {
514 assert(I->hasAllowReassoc() && I->hasNoSignedZeros() &&
515 "Expected 'reassoc'+'nsz' instruction");
517 // Currently we are not able to handle vector type.
518 if (I->getType()->isVectorTy())
521 assert((I->getOpcode() == Instruction::FAdd ||
522 I->getOpcode() == Instruction::FSub) && "Expect add/sub");
524 // Save the instruction before calling other member-functions.
527 FAddend Opnd0, Opnd1, Opnd0_0, Opnd0_1, Opnd1_0, Opnd1_1;
529 unsigned OpndNum = FAddend::drillValueDownOneStep(I, Opnd0, Opnd1);
531 // Step 1: Expand the 1st addend into Opnd0_0 and Opnd0_1.
532 unsigned Opnd0_ExpNum = 0;
533 unsigned Opnd1_ExpNum = 0;
535 if (!Opnd0.isConstant())
536 Opnd0_ExpNum = Opnd0.drillAddendDownOneStep(Opnd0_0, Opnd0_1);
538 // Step 2: Expand the 2nd addend into Opnd1_0 and Opnd1_1.
539 if (OpndNum == 2 && !Opnd1.isConstant())
540 Opnd1_ExpNum = Opnd1.drillAddendDownOneStep(Opnd1_0, Opnd1_1);
542 // Step 3: Try to optimize Opnd0_0 + Opnd0_1 + Opnd1_0 + Opnd1_1
543 if (Opnd0_ExpNum && Opnd1_ExpNum) {
545 AllOpnds.push_back(&Opnd0_0);
546 AllOpnds.push_back(&Opnd1_0);
547 if (Opnd0_ExpNum == 2)
548 AllOpnds.push_back(&Opnd0_1);
549 if (Opnd1_ExpNum == 2)
550 AllOpnds.push_back(&Opnd1_1);
552 // Compute instruction quota. We should save at least one instruction.
553 unsigned InstQuota = 0;
555 Value *V0 = I->getOperand(0);
556 Value *V1 = I->getOperand(1);
557 InstQuota = ((!isa<Constant>(V0) && V0->hasOneUse()) &&
558 (!isa<Constant>(V1) && V1->hasOneUse())) ? 2 : 1;
560 if (Value *R = simplifyFAdd(AllOpnds, InstQuota))
565 // The input instruction is : "I=0.0 +/- V". If the "V" were able to be
566 // splitted into two addends, say "V = X - Y", the instruction would have
567 // been optimized into "I = Y - X" in the previous steps.
569 const FAddendCoef &CE = Opnd0.getCoef();
570 return CE.isOne() ? Opnd0.getSymVal() : nullptr;
573 // step 4: Try to optimize Opnd0 + Opnd1_0 [+ Opnd1_1]
576 AllOpnds.push_back(&Opnd0);
577 AllOpnds.push_back(&Opnd1_0);
578 if (Opnd1_ExpNum == 2)
579 AllOpnds.push_back(&Opnd1_1);
581 if (Value *R = simplifyFAdd(AllOpnds, 1))
585 // step 5: Try to optimize Opnd1 + Opnd0_0 [+ Opnd0_1]
588 AllOpnds.push_back(&Opnd1);
589 AllOpnds.push_back(&Opnd0_0);
590 if (Opnd0_ExpNum == 2)
591 AllOpnds.push_back(&Opnd0_1);
593 if (Value *R = simplifyFAdd(AllOpnds, 1))
597 // step 6: Try factorization as the last resort,
598 return performFactorization(I);
601 Value *FAddCombine::simplifyFAdd(AddendVect& Addends, unsigned InstrQuota) {
602 unsigned AddendNum = Addends.size();
603 assert(AddendNum <= 4 && "Too many addends");
605 // For saving intermediate results;
606 unsigned NextTmpIdx = 0;
607 FAddend TmpResult[3];
609 // Points to the constant addend of the resulting simplified expression.
610 // If the resulting expr has constant-addend, this constant-addend is
611 // desirable to reside at the top of the resulting expression tree. Placing
612 // constant close to supper-expr(s) will potentially reveal some optimization
613 // opportunities in super-expr(s).
614 const FAddend *ConstAdd = nullptr;
616 // Simplified addends are placed <SimpVect>.
619 // The outer loop works on one symbolic-value at a time. Suppose the input
620 // addends are : <a1, x>, <b1, y>, <a2, x>, <c1, z>, <b2, y>, ...
621 // The symbolic-values will be processed in this order: x, y, z.
622 for (unsigned SymIdx = 0; SymIdx < AddendNum; SymIdx++) {
624 const FAddend *ThisAddend = Addends[SymIdx];
626 // This addend was processed before.
630 Value *Val = ThisAddend->getSymVal();
631 unsigned StartIdx = SimpVect.size();
632 SimpVect.push_back(ThisAddend);
634 // The inner loop collects addends sharing same symbolic-value, and these
635 // addends will be later on folded into a single addend. Following above
636 // example, if the symbolic value "y" is being processed, the inner loop
637 // will collect two addends "<b1,y>" and "<b2,Y>". These two addends will
638 // be later on folded into "<b1+b2, y>".
639 for (unsigned SameSymIdx = SymIdx + 1;
640 SameSymIdx < AddendNum; SameSymIdx++) {
641 const FAddend *T = Addends[SameSymIdx];
642 if (T && T->getSymVal() == Val) {
643 // Set null such that next iteration of the outer loop will not process
644 // this addend again.
645 Addends[SameSymIdx] = nullptr;
646 SimpVect.push_back(T);
650 // If multiple addends share same symbolic value, fold them together.
651 if (StartIdx + 1 != SimpVect.size()) {
652 FAddend &R = TmpResult[NextTmpIdx ++];
653 R = *SimpVect[StartIdx];
654 for (unsigned Idx = StartIdx + 1; Idx < SimpVect.size(); Idx++)
657 // Pop all addends being folded and push the resulting folded addend.
658 SimpVect.resize(StartIdx);
661 SimpVect.push_back(&R);
664 // Don't push constant addend at this time. It will be the last element
671 assert((NextTmpIdx <= array_lengthof(TmpResult) + 1) &&
672 "out-of-bound access");
675 SimpVect.push_back(ConstAdd);
678 if (!SimpVect.empty())
679 Result = createNaryFAdd(SimpVect, InstrQuota);
681 // The addition is folded to 0.0.
682 Result = ConstantFP::get(Instr->getType(), 0.0);
688 Value *FAddCombine::createNaryFAdd
689 (const AddendVect &Opnds, unsigned InstrQuota) {
690 assert(!Opnds.empty() && "Expect at least one addend");
692 // Step 1: Check if the # of instructions needed exceeds the quota.
694 unsigned InstrNeeded = calcInstrNumber(Opnds);
695 if (InstrNeeded > InstrQuota)
700 // step 2: Emit the N-ary addition.
701 // Note that at most three instructions are involved in Fadd-InstCombine: the
702 // addition in question, and at most two neighboring instructions.
703 // The resulting optimized addition should have at least one less instruction
704 // than the original addition expression tree. This implies that the resulting
705 // N-ary addition has at most two instructions, and we don't need to worry
706 // about tree-height when constructing the N-ary addition.
708 Value *LastVal = nullptr;
709 bool LastValNeedNeg = false;
711 // Iterate the addends, creating fadd/fsub using adjacent two addends.
712 for (const FAddend *Opnd : Opnds) {
714 Value *V = createAddendVal(*Opnd, NeedNeg);
717 LastValNeedNeg = NeedNeg;
721 if (LastValNeedNeg == NeedNeg) {
722 LastVal = createFAdd(LastVal, V);
727 LastVal = createFSub(V, LastVal);
729 LastVal = createFSub(LastVal, V);
731 LastValNeedNeg = false;
734 if (LastValNeedNeg) {
735 LastVal = createFNeg(LastVal);
739 assert(CreateInstrNum == InstrNeeded &&
740 "Inconsistent in instruction numbers");
746 Value *FAddCombine::createFSub(Value *Opnd0, Value *Opnd1) {
747 Value *V = Builder.CreateFSub(Opnd0, Opnd1);
748 if (Instruction *I = dyn_cast<Instruction>(V))
749 createInstPostProc(I);
753 Value *FAddCombine::createFNeg(Value *V) {
754 Value *Zero = cast<Value>(ConstantFP::getZeroValueForNegation(V->getType()));
755 Value *NewV = createFSub(Zero, V);
756 if (Instruction *I = dyn_cast<Instruction>(NewV))
757 createInstPostProc(I, true); // fneg's don't receive instruction numbers.
761 Value *FAddCombine::createFAdd(Value *Opnd0, Value *Opnd1) {
762 Value *V = Builder.CreateFAdd(Opnd0, Opnd1);
763 if (Instruction *I = dyn_cast<Instruction>(V))
764 createInstPostProc(I);
768 Value *FAddCombine::createFMul(Value *Opnd0, Value *Opnd1) {
769 Value *V = Builder.CreateFMul(Opnd0, Opnd1);
770 if (Instruction *I = dyn_cast<Instruction>(V))
771 createInstPostProc(I);
775 Value *FAddCombine::createFDiv(Value *Opnd0, Value *Opnd1) {
776 Value *V = Builder.CreateFDiv(Opnd0, Opnd1);
777 if (Instruction *I = dyn_cast<Instruction>(V))
778 createInstPostProc(I);
782 void FAddCombine::createInstPostProc(Instruction *NewInstr, bool NoNumber) {
783 NewInstr->setDebugLoc(Instr->getDebugLoc());
785 // Keep track of the number of instruction created.
789 // Propagate fast-math flags
790 NewInstr->setFastMathFlags(Instr->getFastMathFlags());
793 // Return the number of instruction needed to emit the N-ary addition.
794 // NOTE: Keep this function in sync with createAddendVal().
795 unsigned FAddCombine::calcInstrNumber(const AddendVect &Opnds) {
796 unsigned OpndNum = Opnds.size();
797 unsigned InstrNeeded = OpndNum - 1;
799 // The number of addends in the form of "(-1)*x".
800 unsigned NegOpndNum = 0;
802 // Adjust the number of instructions needed to emit the N-ary add.
803 for (const FAddend *Opnd : Opnds) {
804 if (Opnd->isConstant())
807 // The constant check above is really for a few special constant
809 if (isa<UndefValue>(Opnd->getSymVal()))
812 const FAddendCoef &CE = Opnd->getCoef();
813 if (CE.isMinusOne() || CE.isMinusTwo())
816 // Let the addend be "c * x". If "c == +/-1", the value of the addend
817 // is immediately available; otherwise, it needs exactly one instruction
818 // to evaluate the value.
819 if (!CE.isMinusOne() && !CE.isOne())
822 if (NegOpndNum == OpndNum)
827 // Input Addend Value NeedNeg(output)
828 // ================================================================
829 // Constant C C false
830 // <+/-1, V> V coefficient is -1
831 // <2/-2, V> "fadd V, V" coefficient is -2
832 // <C, V> "fmul V, C" false
834 // NOTE: Keep this function in sync with FAddCombine::calcInstrNumber.
835 Value *FAddCombine::createAddendVal(const FAddend &Opnd, bool &NeedNeg) {
836 const FAddendCoef &Coeff = Opnd.getCoef();
838 if (Opnd.isConstant()) {
840 return Coeff.getValue(Instr->getType());
843 Value *OpndVal = Opnd.getSymVal();
845 if (Coeff.isMinusOne() || Coeff.isOne()) {
846 NeedNeg = Coeff.isMinusOne();
850 if (Coeff.isTwo() || Coeff.isMinusTwo()) {
851 NeedNeg = Coeff.isMinusTwo();
852 return createFAdd(OpndVal, OpndVal);
856 return createFMul(OpndVal, Coeff.getValue(Instr->getType()));
859 // Checks if any operand is negative and we can convert add to sub.
860 // This function checks for following negative patterns
861 // ADD(XOR(OR(Z, NOT(C)), C)), 1) == NEG(AND(Z, C))
862 // ADD(XOR(AND(Z, C), C), 1) == NEG(OR(Z, ~C))
863 // XOR(AND(Z, C), (C + 1)) == NEG(OR(Z, ~C)) if C is even
864 static Value *checkForNegativeOperand(BinaryOperator &I,
865 InstCombiner::BuilderTy &Builder) {
866 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
868 // This function creates 2 instructions to replace ADD, we need at least one
869 // of LHS or RHS to have one use to ensure benefit in transform.
870 if (!LHS->hasOneUse() && !RHS->hasOneUse())
873 Value *X = nullptr, *Y = nullptr, *Z = nullptr;
874 const APInt *C1 = nullptr, *C2 = nullptr;
876 // if ONE is on other side, swap
877 if (match(RHS, m_Add(m_Value(X), m_One())))
880 if (match(LHS, m_Add(m_Value(X), m_One()))) {
881 // if XOR on other side, swap
882 if (match(RHS, m_Xor(m_Value(Y), m_APInt(C1))))
885 if (match(X, m_Xor(m_Value(Y), m_APInt(C1)))) {
886 // X = XOR(Y, C1), Y = OR(Z, C2), C2 = NOT(C1) ==> X == NOT(AND(Z, C1))
887 // ADD(ADD(X, 1), RHS) == ADD(X, ADD(RHS, 1)) == SUB(RHS, AND(Z, C1))
888 if (match(Y, m_Or(m_Value(Z), m_APInt(C2))) && (*C2 == ~(*C1))) {
889 Value *NewAnd = Builder.CreateAnd(Z, *C1);
890 return Builder.CreateSub(RHS, NewAnd, "sub");
891 } else if (match(Y, m_And(m_Value(Z), m_APInt(C2))) && (*C1 == *C2)) {
892 // X = XOR(Y, C1), Y = AND(Z, C2), C2 == C1 ==> X == NOT(OR(Z, ~C1))
893 // ADD(ADD(X, 1), RHS) == ADD(X, ADD(RHS, 1)) == SUB(RHS, OR(Z, ~C1))
894 Value *NewOr = Builder.CreateOr(Z, ~(*C1));
895 return Builder.CreateSub(RHS, NewOr, "sub");
900 // Restore LHS and RHS
901 LHS = I.getOperand(0);
902 RHS = I.getOperand(1);
904 // if XOR is on other side, swap
905 if (match(RHS, m_Xor(m_Value(Y), m_APInt(C1))))
909 // LHS = XOR(Y, C1), Y = AND(Z, C2), C1 == (C2 + 1) => LHS == NEG(OR(Z, ~C2))
910 // ADD(LHS, RHS) == SUB(RHS, OR(Z, ~C2))
911 if (match(LHS, m_Xor(m_Value(Y), m_APInt(C1))))
912 if (C1->countTrailingZeros() == 0)
913 if (match(Y, m_And(m_Value(Z), m_APInt(C2))) && *C1 == (*C2 + 1)) {
914 Value *NewOr = Builder.CreateOr(Z, ~(*C2));
915 return Builder.CreateSub(RHS, NewOr, "sub");
920 Instruction *InstCombiner::foldAddWithConstant(BinaryOperator &Add) {
921 Value *Op0 = Add.getOperand(0), *Op1 = Add.getOperand(1);
923 if (!match(Op1, m_Constant(Op1C)))
926 if (Instruction *NV = foldBinOpIntoSelectOrPhi(Add))
930 // zext(bool) + C -> bool ? C + 1 : C
931 if (match(Op0, m_ZExt(m_Value(X))) &&
932 X->getType()->getScalarSizeInBits() == 1)
933 return SelectInst::Create(X, AddOne(Op1C), Op1);
935 // ~X + C --> (C-1) - X
936 if (match(Op0, m_Not(m_Value(X))))
937 return BinaryOperator::CreateSub(SubOne(Op1C), X);
940 if (!match(Op1, m_APInt(C)))
943 if (C->isSignMask()) {
944 // If wrapping is not allowed, then the addition must set the sign bit:
945 // X + (signmask) --> X | signmask
946 if (Add.hasNoSignedWrap() || Add.hasNoUnsignedWrap())
947 return BinaryOperator::CreateOr(Op0, Op1);
949 // If wrapping is allowed, then the addition flips the sign bit of LHS:
950 // X + (signmask) --> X ^ signmask
951 return BinaryOperator::CreateXor(Op0, Op1);
954 // Is this add the last step in a convoluted sext?
955 // add(zext(xor i16 X, -32768), -32768) --> sext X
956 Type *Ty = Add.getType();
958 if (match(Op0, m_ZExt(m_Xor(m_Value(X), m_APInt(C2)))) &&
959 C2->isMinSignedValue() && C2->sext(Ty->getScalarSizeInBits()) == *C)
960 return CastInst::Create(Instruction::SExt, X, Ty);
962 // (add (zext (add nuw X, C2)), C) --> (zext (add nuw X, C2 + C))
963 if (match(Op0, m_OneUse(m_ZExt(m_NUWAdd(m_Value(X), m_APInt(C2))))) &&
964 C->isNegative() && C->sge(-C2->sext(C->getBitWidth()))) {
966 ConstantInt::get(X->getType(), *C2 + C->trunc(C2->getBitWidth()));
967 return new ZExtInst(Builder.CreateNUWAdd(X, NewC), Ty);
970 if (C->isOneValue() && Op0->hasOneUse()) {
971 // add (sext i1 X), 1 --> zext (not X)
972 // TODO: The smallest IR representation is (select X, 0, 1), and that would
973 // not require the one-use check. But we need to remove a transform in
974 // visitSelect and make sure that IR value tracking for select is equal or
975 // better than for these ops.
976 if (match(Op0, m_SExt(m_Value(X))) &&
977 X->getType()->getScalarSizeInBits() == 1)
978 return new ZExtInst(Builder.CreateNot(X), Ty);
980 // Shifts and add used to flip and mask off the low bit:
981 // add (ashr (shl i32 X, 31), 31), 1 --> and (not X), 1
983 if (match(Op0, m_AShr(m_Shl(m_Value(X), m_APInt(C2)), m_APInt(C3))) &&
984 C2 == C3 && *C2 == Ty->getScalarSizeInBits() - 1) {
985 Value *NotX = Builder.CreateNot(X);
986 return BinaryOperator::CreateAnd(NotX, ConstantInt::get(Ty, 1));
993 // Matches multiplication expression Op * C where C is a constant. Returns the
994 // constant value in C and the other operand in Op. Returns true if such a
996 static bool MatchMul(Value *E, Value *&Op, APInt &C) {
998 if (match(E, m_Mul(m_Value(Op), m_APInt(AI)))) {
1002 if (match(E, m_Shl(m_Value(Op), m_APInt(AI)))) {
1003 C = APInt(AI->getBitWidth(), 1);
1010 // Matches remainder expression Op % C where C is a constant. Returns the
1011 // constant value in C and the other operand in Op. Returns the signedness of
1012 // the remainder operation in IsSigned. Returns true if such a match is
1014 static bool MatchRem(Value *E, Value *&Op, APInt &C, bool &IsSigned) {
1017 if (match(E, m_SRem(m_Value(Op), m_APInt(AI)))) {
1022 if (match(E, m_URem(m_Value(Op), m_APInt(AI)))) {
1026 if (match(E, m_And(m_Value(Op), m_APInt(AI))) && (*AI + 1).isPowerOf2()) {
1033 // Matches division expression Op / C with the given signedness as indicated
1034 // by IsSigned, where C is a constant. Returns the constant value in C and the
1035 // other operand in Op. Returns true if such a match is found.
1036 static bool MatchDiv(Value *E, Value *&Op, APInt &C, bool IsSigned) {
1038 if (IsSigned && match(E, m_SDiv(m_Value(Op), m_APInt(AI)))) {
1043 if (match(E, m_UDiv(m_Value(Op), m_APInt(AI)))) {
1047 if (match(E, m_LShr(m_Value(Op), m_APInt(AI)))) {
1048 C = APInt(AI->getBitWidth(), 1);
1056 // Returns whether C0 * C1 with the given signedness overflows.
1057 static bool MulWillOverflow(APInt &C0, APInt &C1, bool IsSigned) {
1060 (void)C0.smul_ov(C1, overflow);
1062 (void)C0.umul_ov(C1, overflow);
1066 // Simplifies X % C0 + (( X / C0 ) % C1) * C0 to X % (C0 * C1), where (C0 * C1)
1067 // does not overflow.
1068 Value *InstCombiner::SimplifyAddWithRemainder(BinaryOperator &I) {
1069 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1073 // Match I = X % C0 + MulOpV * C0
1074 if (((MatchRem(LHS, X, C0, IsSigned) && MatchMul(RHS, MulOpV, MulOpC)) ||
1075 (MatchRem(RHS, X, C0, IsSigned) && MatchMul(LHS, MulOpV, MulOpC))) &&
1080 // Match MulOpC = RemOpV % C1
1081 if (MatchRem(MulOpV, RemOpV, C1, Rem2IsSigned) &&
1082 IsSigned == Rem2IsSigned) {
1085 // Match RemOpV = X / C0
1086 if (MatchDiv(RemOpV, DivOpV, DivOpC, IsSigned) && X == DivOpV &&
1087 C0 == DivOpC && !MulWillOverflow(C0, C1, IsSigned)) {
1089 ConstantInt::get(X->getType()->getContext(), C0 * C1);
1090 return IsSigned ? Builder.CreateSRem(X, NewDivisor, "srem")
1091 : Builder.CreateURem(X, NewDivisor, "urem");
1100 /// (1 << NBits) - 1
1102 /// ~(-(1 << NBits))
1103 /// Because a 'not' is better for bit-tracking analysis and other transforms
1104 /// than an 'add'. The new shl is always nsw, and is nuw if old `and` was.
1105 static Instruction *canonicalizeLowbitMask(BinaryOperator &I,
1106 InstCombiner::BuilderTy &Builder) {
1108 if (!match(&I, m_Add(m_OneUse(m_Shl(m_One(), m_Value(NBits))), m_AllOnes())))
1111 Constant *MinusOne = Constant::getAllOnesValue(NBits->getType());
1112 Value *NotMask = Builder.CreateShl(MinusOne, NBits, "notmask");
1113 // Be wary of constant folding.
1114 if (auto *BOp = dyn_cast<BinaryOperator>(NotMask)) {
1115 // Always NSW. But NUW propagates from `add`.
1116 BOp->setHasNoSignedWrap();
1117 BOp->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
1120 return BinaryOperator::CreateNot(NotMask, I.getName());
1123 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1124 if (Value *V = SimplifyAddInst(I.getOperand(0), I.getOperand(1),
1125 I.hasNoSignedWrap(), I.hasNoUnsignedWrap(),
1126 SQ.getWithInstruction(&I)))
1127 return replaceInstUsesWith(I, V);
1129 if (SimplifyAssociativeOrCommutative(I))
1132 if (Instruction *X = foldShuffledBinop(I))
1135 // (A*B)+(A*C) -> A*(B+C) etc
1136 if (Value *V = SimplifyUsingDistributiveLaws(I))
1137 return replaceInstUsesWith(I, V);
1139 if (Instruction *X = foldAddWithConstant(I))
1142 // FIXME: This should be moved into the above helper function to allow these
1143 // transforms for general constant or constant splat vectors.
1144 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1145 Type *Ty = I.getType();
1146 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1147 Value *XorLHS = nullptr; ConstantInt *XorRHS = nullptr;
1148 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1149 unsigned TySizeBits = Ty->getScalarSizeInBits();
1150 const APInt &RHSVal = CI->getValue();
1151 unsigned ExtendAmt = 0;
1152 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1153 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1154 if (XorRHS->getValue() == -RHSVal) {
1155 if (RHSVal.isPowerOf2())
1156 ExtendAmt = TySizeBits - RHSVal.logBase2() - 1;
1157 else if (XorRHS->getValue().isPowerOf2())
1158 ExtendAmt = TySizeBits - XorRHS->getValue().logBase2() - 1;
1162 APInt Mask = APInt::getHighBitsSet(TySizeBits, ExtendAmt);
1163 if (!MaskedValueIsZero(XorLHS, Mask, 0, &I))
1168 Constant *ShAmt = ConstantInt::get(Ty, ExtendAmt);
1169 Value *NewShl = Builder.CreateShl(XorLHS, ShAmt, "sext");
1170 return BinaryOperator::CreateAShr(NewShl, ShAmt);
1173 // If this is a xor that was canonicalized from a sub, turn it back into
1174 // a sub and fuse this add with it.
1175 if (LHS->hasOneUse() && (XorRHS->getValue()+1).isPowerOf2()) {
1176 KnownBits LHSKnown = computeKnownBits(XorLHS, 0, &I);
1177 if ((XorRHS->getValue() | LHSKnown.Zero).isAllOnesValue())
1178 return BinaryOperator::CreateSub(ConstantExpr::getAdd(XorRHS, CI),
1181 // (X + signmask) + C could have gotten canonicalized to (X^signmask) + C,
1182 // transform them into (X + (signmask ^ C))
1183 if (XorRHS->getValue().isSignMask())
1184 return BinaryOperator::CreateAdd(XorLHS,
1185 ConstantExpr::getXor(XorRHS, CI));
1189 if (Ty->isIntOrIntVectorTy(1))
1190 return BinaryOperator::CreateXor(LHS, RHS);
1194 auto *Shl = BinaryOperator::CreateShl(LHS, ConstantInt::get(Ty, 1));
1195 Shl->setHasNoSignedWrap(I.hasNoSignedWrap());
1196 Shl->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
1201 if (match(LHS, m_Neg(m_Value(A)))) {
1202 // -A + -B --> -(A + B)
1203 if (match(RHS, m_Neg(m_Value(B))))
1204 return BinaryOperator::CreateNeg(Builder.CreateAdd(A, B));
1207 return BinaryOperator::CreateSub(RHS, A);
1211 if (match(RHS, m_Neg(m_Value(B))))
1212 return BinaryOperator::CreateSub(LHS, B);
1214 if (Value *V = checkForNegativeOperand(I, Builder))
1215 return replaceInstUsesWith(I, V);
1217 // (A + 1) + ~B --> A - B
1218 // ~B + (A + 1) --> A - B
1219 if (match(&I, m_c_BinOp(m_Add(m_Value(A), m_One()), m_Not(m_Value(B)))))
1220 return BinaryOperator::CreateSub(A, B);
1222 // X % C0 + (( X / C0 ) % C1) * C0 => X % (C0 * C1)
1223 if (Value *V = SimplifyAddWithRemainder(I)) return replaceInstUsesWith(I, V);
1225 // A+B --> A|B iff A and B have no bits set in common.
1226 if (haveNoCommonBitsSet(LHS, RHS, DL, &AC, &I, &DT))
1227 return BinaryOperator::CreateOr(LHS, RHS);
1229 // FIXME: We already did a check for ConstantInt RHS above this.
1230 // FIXME: Is this pattern covered by another fold? No regression tests fail on
1232 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
1233 // (X & FF00) + xx00 -> (X+xx00) & FF00
1236 if (LHS->hasOneUse() &&
1237 match(LHS, m_And(m_Value(X), m_ConstantInt(C2))) &&
1238 CRHS->getValue() == (CRHS->getValue() & C2->getValue())) {
1239 // See if all bits from the first bit set in the Add RHS up are included
1240 // in the mask. First, get the rightmost bit.
1241 const APInt &AddRHSV = CRHS->getValue();
1243 // Form a mask of all bits from the lowest bit added through the top.
1244 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
1246 // See if the and mask includes all of these bits.
1247 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
1249 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1250 // Okay, the xform is safe. Insert the new add pronto.
1251 Value *NewAdd = Builder.CreateAdd(X, CRHS, LHS->getName());
1252 return BinaryOperator::CreateAnd(NewAdd, C2);
1257 // add (select X 0 (sub n A)) A --> select X A n
1259 SelectInst *SI = dyn_cast<SelectInst>(LHS);
1262 SI = dyn_cast<SelectInst>(RHS);
1265 if (SI && SI->hasOneUse()) {
1266 Value *TV = SI->getTrueValue();
1267 Value *FV = SI->getFalseValue();
1270 // Can we fold the add into the argument of the select?
1271 // We check both true and false select arguments for a matching subtract.
1272 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
1273 // Fold the add into the true select value.
1274 return SelectInst::Create(SI->getCondition(), N, A);
1276 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
1277 // Fold the add into the false select value.
1278 return SelectInst::Create(SI->getCondition(), A, N);
1282 // Check for (add (sext x), y), see if we can merge this into an
1283 // integer add followed by a sext.
1284 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
1285 // (add (sext x), cst) --> (sext (add x, cst'))
1286 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
1287 if (LHSConv->hasOneUse()) {
1289 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
1290 if (ConstantExpr::getSExt(CI, Ty) == RHSC &&
1291 willNotOverflowSignedAdd(LHSConv->getOperand(0), CI, I)) {
1292 // Insert the new, smaller add.
1294 Builder.CreateNSWAdd(LHSConv->getOperand(0), CI, "addconv");
1295 return new SExtInst(NewAdd, Ty);
1300 // (add (sext x), (sext y)) --> (sext (add int x, y))
1301 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
1302 // Only do this if x/y have the same type, if at least one of them has a
1303 // single use (so we don't increase the number of sexts), and if the
1304 // integer add will not overflow.
1305 if (LHSConv->getOperand(0)->getType() ==
1306 RHSConv->getOperand(0)->getType() &&
1307 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
1308 willNotOverflowSignedAdd(LHSConv->getOperand(0),
1309 RHSConv->getOperand(0), I)) {
1310 // Insert the new integer add.
1311 Value *NewAdd = Builder.CreateNSWAdd(LHSConv->getOperand(0),
1312 RHSConv->getOperand(0), "addconv");
1313 return new SExtInst(NewAdd, Ty);
1318 // Check for (add (zext x), y), see if we can merge this into an
1319 // integer add followed by a zext.
1320 if (auto *LHSConv = dyn_cast<ZExtInst>(LHS)) {
1321 // (add (zext x), cst) --> (zext (add x, cst'))
1322 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
1323 if (LHSConv->hasOneUse()) {
1325 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
1326 if (ConstantExpr::getZExt(CI, Ty) == RHSC &&
1327 willNotOverflowUnsignedAdd(LHSConv->getOperand(0), CI, I)) {
1328 // Insert the new, smaller add.
1330 Builder.CreateNUWAdd(LHSConv->getOperand(0), CI, "addconv");
1331 return new ZExtInst(NewAdd, Ty);
1336 // (add (zext x), (zext y)) --> (zext (add int x, y))
1337 if (auto *RHSConv = dyn_cast<ZExtInst>(RHS)) {
1338 // Only do this if x/y have the same type, if at least one of them has a
1339 // single use (so we don't increase the number of zexts), and if the
1340 // integer add will not overflow.
1341 if (LHSConv->getOperand(0)->getType() ==
1342 RHSConv->getOperand(0)->getType() &&
1343 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
1344 willNotOverflowUnsignedAdd(LHSConv->getOperand(0),
1345 RHSConv->getOperand(0), I)) {
1346 // Insert the new integer add.
1347 Value *NewAdd = Builder.CreateNUWAdd(
1348 LHSConv->getOperand(0), RHSConv->getOperand(0), "addconv");
1349 return new ZExtInst(NewAdd, Ty);
1354 // (add (xor A, B) (and A, B)) --> (or A, B)
1355 // (add (and A, B) (xor A, B)) --> (or A, B)
1356 if (match(&I, m_c_BinOp(m_Xor(m_Value(A), m_Value(B)),
1357 m_c_And(m_Deferred(A), m_Deferred(B)))))
1358 return BinaryOperator::CreateOr(A, B);
1360 // (add (or A, B) (and A, B)) --> (add A, B)
1361 // (add (and A, B) (or A, B)) --> (add A, B)
1362 if (match(&I, m_c_BinOp(m_Or(m_Value(A), m_Value(B)),
1363 m_c_And(m_Deferred(A), m_Deferred(B))))) {
1369 // TODO(jingyue): Consider willNotOverflowSignedAdd and
1370 // willNotOverflowUnsignedAdd to reduce the number of invocations of
1371 // computeKnownBits.
1372 bool Changed = false;
1373 if (!I.hasNoSignedWrap() && willNotOverflowSignedAdd(LHS, RHS, I)) {
1375 I.setHasNoSignedWrap(true);
1377 if (!I.hasNoUnsignedWrap() && willNotOverflowUnsignedAdd(LHS, RHS, I)) {
1379 I.setHasNoUnsignedWrap(true);
1382 if (Instruction *V = canonicalizeLowbitMask(I, Builder))
1385 return Changed ? &I : nullptr;
1388 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
1389 if (Value *V = SimplifyFAddInst(I.getOperand(0), I.getOperand(1),
1390 I.getFastMathFlags(),
1391 SQ.getWithInstruction(&I)))
1392 return replaceInstUsesWith(I, V);
1394 if (SimplifyAssociativeOrCommutative(I))
1397 if (Instruction *X = foldShuffledBinop(I))
1400 if (Instruction *FoldedFAdd = foldBinOpIntoSelectOrPhi(I))
1403 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1405 // (-X) + Y --> Y - X
1406 if (match(LHS, m_FNeg(m_Value(X))))
1407 return BinaryOperator::CreateFSubFMF(RHS, X, &I);
1408 // Y + (-X) --> Y - X
1409 if (match(RHS, m_FNeg(m_Value(X))))
1410 return BinaryOperator::CreateFSubFMF(LHS, X, &I);
1412 // Check for (fadd double (sitofp x), y), see if we can merge this into an
1413 // integer add followed by a promotion.
1414 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
1415 Value *LHSIntVal = LHSConv->getOperand(0);
1416 Type *FPType = LHSConv->getType();
1418 // TODO: This check is overly conservative. In many cases known bits
1419 // analysis can tell us that the result of the addition has less significant
1420 // bits than the integer type can hold.
1421 auto IsValidPromotion = [](Type *FTy, Type *ITy) {
1422 Type *FScalarTy = FTy->getScalarType();
1423 Type *IScalarTy = ITy->getScalarType();
1425 // Do we have enough bits in the significand to represent the result of
1426 // the integer addition?
1427 unsigned MaxRepresentableBits =
1428 APFloat::semanticsPrecision(FScalarTy->getFltSemantics());
1429 return IScalarTy->getIntegerBitWidth() <= MaxRepresentableBits;
1432 // (fadd double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
1433 // ... if the constant fits in the integer value. This is useful for things
1434 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
1435 // requires a constant pool load, and generally allows the add to be better
1437 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
1438 if (IsValidPromotion(FPType, LHSIntVal->getType())) {
1440 ConstantExpr::getFPToSI(CFP, LHSIntVal->getType());
1441 if (LHSConv->hasOneUse() &&
1442 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
1443 willNotOverflowSignedAdd(LHSIntVal, CI, I)) {
1444 // Insert the new integer add.
1445 Value *NewAdd = Builder.CreateNSWAdd(LHSIntVal, CI, "addconv");
1446 return new SIToFPInst(NewAdd, I.getType());
1450 // (fadd double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
1451 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
1452 Value *RHSIntVal = RHSConv->getOperand(0);
1453 // It's enough to check LHS types only because we require int types to
1454 // be the same for this transform.
1455 if (IsValidPromotion(FPType, LHSIntVal->getType())) {
1456 // Only do this if x/y have the same type, if at least one of them has a
1457 // single use (so we don't increase the number of int->fp conversions),
1458 // and if the integer add will not overflow.
1459 if (LHSIntVal->getType() == RHSIntVal->getType() &&
1460 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
1461 willNotOverflowSignedAdd(LHSIntVal, RHSIntVal, I)) {
1462 // Insert the new integer add.
1463 Value *NewAdd = Builder.CreateNSWAdd(LHSIntVal, RHSIntVal, "addconv");
1464 return new SIToFPInst(NewAdd, I.getType());
1470 // Handle specials cases for FAdd with selects feeding the operation
1471 if (Value *V = SimplifySelectsFeedingBinaryOp(I, LHS, RHS))
1472 return replaceInstUsesWith(I, V);
1474 if (I.hasAllowReassoc() && I.hasNoSignedZeros()) {
1475 if (Value *V = FAddCombine(Builder).simplify(&I))
1476 return replaceInstUsesWith(I, V);
1482 /// Optimize pointer differences into the same array into a size. Consider:
1483 /// &A[10] - &A[0]: we should compile this to "10". LHS/RHS are the pointer
1484 /// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
1485 Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS,
1487 // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
1489 bool Swapped = false;
1490 GEPOperator *GEP1 = nullptr, *GEP2 = nullptr;
1492 // For now we require one side to be the base pointer "A" or a constant
1493 // GEP derived from it.
1494 if (GEPOperator *LHSGEP = dyn_cast<GEPOperator>(LHS)) {
1496 if (LHSGEP->getOperand(0) == RHS) {
1499 } else if (GEPOperator *RHSGEP = dyn_cast<GEPOperator>(RHS)) {
1500 // (gep X, ...) - (gep X, ...)
1501 if (LHSGEP->getOperand(0)->stripPointerCasts() ==
1502 RHSGEP->getOperand(0)->stripPointerCasts()) {
1510 if (GEPOperator *RHSGEP = dyn_cast<GEPOperator>(RHS)) {
1512 if (RHSGEP->getOperand(0) == LHS) {
1515 } else if (GEPOperator *LHSGEP = dyn_cast<GEPOperator>(LHS)) {
1516 // (gep X, ...) - (gep X, ...)
1517 if (RHSGEP->getOperand(0)->stripPointerCasts() ==
1518 LHSGEP->getOperand(0)->stripPointerCasts()) {
1531 // (gep X, ...) - (gep X, ...)
1533 // Avoid duplicating the arithmetic if there are more than one non-constant
1534 // indices between the two GEPs and either GEP has a non-constant index and
1535 // multiple users. If zero non-constant index, the result is a constant and
1536 // there is no duplication. If one non-constant index, the result is an add
1537 // or sub with a constant, which is no larger than the original code, and
1538 // there's no duplicated arithmetic, even if either GEP has multiple
1539 // users. If more than one non-constant indices combined, as long as the GEP
1540 // with at least one non-constant index doesn't have multiple users, there
1541 // is no duplication.
1542 unsigned NumNonConstantIndices1 = GEP1->countNonConstantIndices();
1543 unsigned NumNonConstantIndices2 = GEP2->countNonConstantIndices();
1544 if (NumNonConstantIndices1 + NumNonConstantIndices2 > 1 &&
1545 ((NumNonConstantIndices1 > 0 && !GEP1->hasOneUse()) ||
1546 (NumNonConstantIndices2 > 0 && !GEP2->hasOneUse()))) {
1551 // Emit the offset of the GEP and an intptr_t.
1552 Value *Result = EmitGEPOffset(GEP1);
1554 // If we had a constant expression GEP on the other side offsetting the
1555 // pointer, subtract it from the offset we have.
1557 Value *Offset = EmitGEPOffset(GEP2);
1558 Result = Builder.CreateSub(Result, Offset);
1561 // If we have p - gep(p, ...) then we have to negate the result.
1563 Result = Builder.CreateNeg(Result, "diff.neg");
1565 return Builder.CreateIntCast(Result, Ty, true);
1568 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
1569 if (Value *V = SimplifySubInst(I.getOperand(0), I.getOperand(1),
1570 I.hasNoSignedWrap(), I.hasNoUnsignedWrap(),
1571 SQ.getWithInstruction(&I)))
1572 return replaceInstUsesWith(I, V);
1574 if (Instruction *X = foldShuffledBinop(I))
1577 // (A*B)-(A*C) -> A*(B-C) etc
1578 if (Value *V = SimplifyUsingDistributiveLaws(I))
1579 return replaceInstUsesWith(I, V);
1581 // If this is a 'B = x-(-A)', change to B = x+A.
1582 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1583 if (Value *V = dyn_castNegVal(Op1)) {
1584 BinaryOperator *Res = BinaryOperator::CreateAdd(Op0, V);
1586 if (const auto *BO = dyn_cast<BinaryOperator>(Op1)) {
1587 assert(BO->getOpcode() == Instruction::Sub &&
1588 "Expected a subtraction operator!");
1589 if (BO->hasNoSignedWrap() && I.hasNoSignedWrap())
1590 Res->setHasNoSignedWrap(true);
1592 if (cast<Constant>(Op1)->isNotMinSignedValue() && I.hasNoSignedWrap())
1593 Res->setHasNoSignedWrap(true);
1599 if (I.getType()->isIntOrIntVectorTy(1))
1600 return BinaryOperator::CreateXor(Op0, Op1);
1602 // Replace (-1 - A) with (~A).
1603 if (match(Op0, m_AllOnes()))
1604 return BinaryOperator::CreateNot(Op1);
1606 // (~X) - (~Y) --> Y - X
1608 if (match(Op0, m_Not(m_Value(X))) && match(Op1, m_Not(m_Value(Y))))
1609 return BinaryOperator::CreateSub(Y, X);
1611 if (Constant *C = dyn_cast<Constant>(Op0)) {
1612 bool IsNegate = match(C, m_ZeroInt());
1614 if (match(Op1, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
1615 // 0 - (zext bool) --> sext bool
1616 // C - (zext bool) --> bool ? C - 1 : C
1618 return CastInst::CreateSExtOrBitCast(X, I.getType());
1619 return SelectInst::Create(X, SubOne(C), C);
1621 if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
1622 // 0 - (sext bool) --> zext bool
1623 // C - (sext bool) --> bool ? C + 1 : C
1625 return CastInst::CreateZExtOrBitCast(X, I.getType());
1626 return SelectInst::Create(X, AddOne(C), C);
1629 // C - ~X == X + (1+C)
1630 if (match(Op1, m_Not(m_Value(X))))
1631 return BinaryOperator::CreateAdd(X, AddOne(C));
1633 // Try to fold constant sub into select arguments.
1634 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1635 if (Instruction *R = FoldOpIntoSelect(I, SI))
1638 // Try to fold constant sub into PHI values.
1639 if (PHINode *PN = dyn_cast<PHINode>(Op1))
1640 if (Instruction *R = foldOpIntoPhi(I, PN))
1643 // C-(X+C2) --> (C-C2)-X
1645 if (match(Op1, m_Add(m_Value(X), m_Constant(C2))))
1646 return BinaryOperator::CreateSub(ConstantExpr::getSub(C, C2), X);
1650 if (match(Op0, m_APInt(Op0C))) {
1651 unsigned BitWidth = I.getType()->getScalarSizeInBits();
1653 // -(X >>u 31) -> (X >>s 31)
1654 // -(X >>s 31) -> (X >>u 31)
1655 if (Op0C->isNullValue()) {
1658 if (match(Op1, m_LShr(m_Value(X), m_APInt(ShAmt))) &&
1659 *ShAmt == BitWidth - 1) {
1660 Value *ShAmtOp = cast<Instruction>(Op1)->getOperand(1);
1661 return BinaryOperator::CreateAShr(X, ShAmtOp);
1663 if (match(Op1, m_AShr(m_Value(X), m_APInt(ShAmt))) &&
1664 *ShAmt == BitWidth - 1) {
1665 Value *ShAmtOp = cast<Instruction>(Op1)->getOperand(1);
1666 return BinaryOperator::CreateLShr(X, ShAmtOp);
1669 if (Op1->hasOneUse()) {
1671 SelectPatternFlavor SPF = matchSelectPattern(Op1, LHS, RHS).Flavor;
1672 if (SPF == SPF_ABS || SPF == SPF_NABS) {
1673 // This is a negate of an ABS/NABS pattern. Just swap the operands
1675 SelectInst *SI = cast<SelectInst>(Op1);
1676 Value *TrueVal = SI->getTrueValue();
1677 Value *FalseVal = SI->getFalseValue();
1678 SI->setTrueValue(FalseVal);
1679 SI->setFalseValue(TrueVal);
1680 // Don't swap prof metadata, we didn't change the branch behavior.
1681 return replaceInstUsesWith(I, SI);
1686 // Turn this into a xor if LHS is 2^n-1 and the remaining bits are known
1688 if (Op0C->isMask()) {
1689 KnownBits RHSKnown = computeKnownBits(Op1, 0, &I);
1690 if ((*Op0C | RHSKnown.Zero).isAllOnesValue())
1691 return BinaryOperator::CreateXor(Op1, Op0);
1697 // X-(X+Y) == -Y X-(Y+X) == -Y
1698 if (match(Op1, m_c_Add(m_Specific(Op0), m_Value(Y))))
1699 return BinaryOperator::CreateNeg(Y);
1702 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(Y))))
1703 return BinaryOperator::CreateNeg(Y);
1706 // (sub (or A, B), (xor A, B)) --> (and A, B)
1709 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
1710 match(Op0, m_c_Or(m_Specific(A), m_Specific(B))))
1711 return BinaryOperator::CreateAnd(A, B);
1716 // ((X | Y) - X) --> (~X & Y)
1717 if (match(Op0, m_OneUse(m_c_Or(m_Value(Y), m_Specific(Op1)))))
1718 return BinaryOperator::CreateAnd(
1719 Y, Builder.CreateNot(Op1, Op1->getName() + ".not"));
1722 if (Op1->hasOneUse()) {
1723 Value *X = nullptr, *Y = nullptr, *Z = nullptr;
1724 Constant *C = nullptr;
1726 // (X - (Y - Z)) --> (X + (Z - Y)).
1727 if (match(Op1, m_Sub(m_Value(Y), m_Value(Z))))
1728 return BinaryOperator::CreateAdd(Op0,
1729 Builder.CreateSub(Z, Y, Op1->getName()));
1731 // (X - (X & Y)) --> (X & ~Y)
1732 if (match(Op1, m_c_And(m_Value(Y), m_Specific(Op0))))
1733 return BinaryOperator::CreateAnd(Op0,
1734 Builder.CreateNot(Y, Y->getName() + ".not"));
1736 // 0 - (X sdiv C) -> (X sdiv -C) provided the negation doesn't overflow.
1737 if (match(Op1, m_SDiv(m_Value(X), m_Constant(C))) && match(Op0, m_Zero()) &&
1738 C->isNotMinSignedValue() && !C->isOneValue())
1739 return BinaryOperator::CreateSDiv(X, ConstantExpr::getNeg(C));
1741 // 0 - (X << Y) -> (-X << Y) when X is freely negatable.
1742 if (match(Op1, m_Shl(m_Value(X), m_Value(Y))) && match(Op0, m_Zero()))
1743 if (Value *XNeg = dyn_castNegVal(X))
1744 return BinaryOperator::CreateShl(XNeg, Y);
1746 // Subtracting -1/0 is the same as adding 1/0:
1747 // sub [nsw] Op0, sext(bool Y) -> add [nsw] Op0, zext(bool Y)
1748 // 'nuw' is dropped in favor of the canonical form.
1749 if (match(Op1, m_SExt(m_Value(Y))) &&
1750 Y->getType()->getScalarSizeInBits() == 1) {
1751 Value *Zext = Builder.CreateZExt(Y, I.getType());
1752 BinaryOperator *Add = BinaryOperator::CreateAdd(Op0, Zext);
1753 Add->setHasNoSignedWrap(I.hasNoSignedWrap());
1757 // X - A*-B -> X + A*B
1758 // X - -A*B -> X + A*B
1761 if (match(Op1, m_c_Mul(m_Value(A), m_Neg(m_Value(B)))))
1762 return BinaryOperator::CreateAdd(Op0, Builder.CreateMul(A, B));
1764 // X - A*CI -> X + A*-CI
1765 // No need to handle commuted multiply because multiply handling will
1766 // ensure constant will be move to the right hand side.
1767 if (match(Op1, m_Mul(m_Value(A), m_Constant(CI)))) {
1768 Value *NewMul = Builder.CreateMul(A, ConstantExpr::getNeg(CI));
1769 return BinaryOperator::CreateAdd(Op0, NewMul);
1773 // Optimize pointer differences into the same array into a size. Consider:
1774 // &A[10] - &A[0]: we should compile this to "10".
1775 Value *LHSOp, *RHSOp;
1776 if (match(Op0, m_PtrToInt(m_Value(LHSOp))) &&
1777 match(Op1, m_PtrToInt(m_Value(RHSOp))))
1778 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
1779 return replaceInstUsesWith(I, Res);
1781 // trunc(p)-trunc(q) -> trunc(p-q)
1782 if (match(Op0, m_Trunc(m_PtrToInt(m_Value(LHSOp)))) &&
1783 match(Op1, m_Trunc(m_PtrToInt(m_Value(RHSOp)))))
1784 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
1785 return replaceInstUsesWith(I, Res);
1787 // Canonicalize a shifty way to code absolute value to the common pattern.
1788 // There are 2 potential commuted variants.
1789 // We're relying on the fact that we only do this transform when the shift has
1790 // exactly 2 uses and the xor has exactly 1 use (otherwise, we might increase
1794 Type *Ty = I.getType();
1795 if (match(Op1, m_AShr(m_Value(A), m_APInt(ShAmt))) &&
1796 Op1->hasNUses(2) && *ShAmt == Ty->getScalarSizeInBits() - 1 &&
1797 match(Op0, m_OneUse(m_c_Xor(m_Specific(A), m_Specific(Op1))))) {
1798 // B = ashr i32 A, 31 ; smear the sign bit
1799 // sub (xor A, B), B ; flip bits if negative and subtract -1 (add 1)
1800 // --> (A < 0) ? -A : A
1801 Value *Cmp = Builder.CreateICmpSLT(A, ConstantInt::getNullValue(Ty));
1802 // Copy the nuw/nsw flags from the sub to the negate.
1803 Value *Neg = Builder.CreateNeg(A, "", I.hasNoUnsignedWrap(),
1804 I.hasNoSignedWrap());
1805 return SelectInst::Create(Cmp, Neg, A);
1808 bool Changed = false;
1809 if (!I.hasNoSignedWrap() && willNotOverflowSignedSub(Op0, Op1, I)) {
1811 I.setHasNoSignedWrap(true);
1813 if (!I.hasNoUnsignedWrap() && willNotOverflowUnsignedSub(Op0, Op1, I)) {
1815 I.setHasNoUnsignedWrap(true);
1818 return Changed ? &I : nullptr;
1821 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
1822 if (Value *V = SimplifyFSubInst(I.getOperand(0), I.getOperand(1),
1823 I.getFastMathFlags(),
1824 SQ.getWithInstruction(&I)))
1825 return replaceInstUsesWith(I, V);
1827 if (Instruction *X = foldShuffledBinop(I))
1830 // Subtraction from -0.0 is the canonical form of fneg.
1831 // fsub nsz 0, X ==> fsub nsz -0.0, X
1832 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1833 if (I.hasNoSignedZeros() && match(Op0, m_PosZeroFP()))
1834 return BinaryOperator::CreateFNegFMF(Op1, &I);
1836 // If Op0 is not -0.0 or we can ignore -0.0: Z - (X - Y) --> Z + (Y - X)
1837 // Canonicalize to fadd to make analysis easier.
1838 // This can also help codegen because fadd is commutative.
1839 // Note that if this fsub was really an fneg, the fadd with -0.0 will get
1840 // killed later. We still limit that particular transform with 'hasOneUse'
1841 // because an fneg is assumed better/cheaper than a generic fsub.
1843 if (I.hasNoSignedZeros() || CannotBeNegativeZero(Op0, SQ.TLI)) {
1844 if (match(Op1, m_OneUse(m_FSub(m_Value(X), m_Value(Y))))) {
1845 Value *NewSub = Builder.CreateFSubFMF(Y, X, &I);
1846 return BinaryOperator::CreateFAddFMF(Op0, NewSub, &I);
1850 if (isa<Constant>(Op0))
1851 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1852 if (Instruction *NV = FoldOpIntoSelect(I, SI))
1855 // X - C --> X + (-C)
1856 // But don't transform constant expressions because there's an inverse fold
1857 // for X + (-Y) --> X - Y.
1859 if (match(Op1, m_Constant(C)) && !isa<ConstantExpr>(Op1))
1860 return BinaryOperator::CreateFAddFMF(Op0, ConstantExpr::getFNeg(C), &I);
1862 // X - (-Y) --> X + Y
1863 if (match(Op1, m_FNeg(m_Value(Y))))
1864 return BinaryOperator::CreateFAddFMF(Op0, Y, &I);
1866 // Similar to above, but look through a cast of the negated value:
1867 // X - (fptrunc(-Y)) --> X + fptrunc(Y)
1868 if (match(Op1, m_OneUse(m_FPTrunc(m_FNeg(m_Value(Y)))))) {
1869 Value *TruncY = Builder.CreateFPTrunc(Y, I.getType());
1870 return BinaryOperator::CreateFAddFMF(Op0, TruncY, &I);
1872 // X - (fpext(-Y)) --> X + fpext(Y)
1873 if (match(Op1, m_OneUse(m_FPExt(m_FNeg(m_Value(Y)))))) {
1874 Value *ExtY = Builder.CreateFPExt(Y, I.getType());
1875 return BinaryOperator::CreateFAddFMF(Op0, ExtY, &I);
1878 // Handle specials cases for FSub with selects feeding the operation
1879 if (Value *V = SimplifySelectsFeedingBinaryOp(I, Op0, Op1))
1880 return replaceInstUsesWith(I, V);
1882 if (I.hasAllowReassoc() && I.hasNoSignedZeros()) {
1883 if (Value *V = FAddCombine(Builder).simplify(&I))
1884 return replaceInstUsesWith(I, V);