#include "InstCombineInternal.h"
#include "llvm/ADT/APFloat.h"
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Analysis/InstructionSimplify.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/IR/Constant.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/InstrTypes.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Operator.h"
#include "llvm/IR/PatternMatch.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/Value.h"
#include "llvm/Support/AlignOf.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/KnownBits.h"
#include "llvm/Transforms/InstCombine/InstCombiner.h"
#include <cassert>
#include <utility>
using namespace llvm;
using namespace PatternMatch;
#define DEBUG_TYPE "instcombine"
namespace {
class FAddendCoef {
public:
FAddendCoef() = default;
~FAddendCoef();
void operator=(const FAddendCoef &A);
void operator+=(const FAddendCoef &A);
void operator*=(const FAddendCoef &S);
void set(short C) {
assert(!insaneIntVal(C) && "Insane coefficient");
IsFp = false; IntVal = C;
}
void set(const APFloat& C);
void negate();
bool isZero() const { return isInt() ? !IntVal : getFpVal().isZero(); }
Value *getValue(Type *) const;
bool isOne() const { return isInt() && IntVal == 1; }
bool isTwo() const { return isInt() && IntVal == 2; }
bool isMinusOne() const { return isInt() && IntVal == -1; }
bool isMinusTwo() const { return isInt() && IntVal == -2; }
private:
bool insaneIntVal(int V) { return V > 4 || V < -4; }
APFloat *getFpValPtr() { return reinterpret_cast<APFloat *>(&FpValBuf); }
const APFloat *getFpValPtr() const {
return reinterpret_cast<const APFloat *>(&FpValBuf);
}
const APFloat &getFpVal() const {
assert(IsFp && BufHasFpVal && "Incorret state");
return *getFpValPtr();
}
APFloat &getFpVal() {
assert(IsFp && BufHasFpVal && "Incorret state");
return *getFpValPtr();
}
bool isInt() const { return !IsFp; }
void convertToFpType(const fltSemantics &Sem);
APFloat createAPFloatFromInt(const fltSemantics &Sem, int Val);
bool IsFp = false;
bool BufHasFpVal = false;
short IntVal = 0;
AlignedCharArrayUnion<APFloat> FpValBuf;
};
class FAddend {
public:
FAddend() = default;
void operator+=(const FAddend &T) {
assert((Val == T.Val) && "Symbolic-values disagree");
Coeff += T.Coeff;
}
Value *getSymVal() const { return Val; }
const FAddendCoef &getCoef() const { return Coeff; }
bool isConstant() const { return Val == nullptr; }
bool isZero() const { return Coeff.isZero(); }
void set(short Coefficient, Value *V) {
Coeff.set(Coefficient);
Val = V;
}
void set(const APFloat &Coefficient, Value *V) {
Coeff.set(Coefficient);
Val = V;
}
void set(const ConstantFP *Coefficient, Value *V) {
Coeff.set(Coefficient->getValueAPF());
Val = V;
}
void negate() { Coeff.negate(); }
static unsigned drillValueDownOneStep(Value* V, FAddend &A0, FAddend &A1);
unsigned drillAddendDownOneStep(FAddend &Addend0, FAddend &Addend1) const;
private:
void Scale(const FAddendCoef& ScaleAmt) { Coeff *= ScaleAmt; }
Value *Val = nullptr;
FAddendCoef Coeff;
};
class FAddCombine {
public:
FAddCombine(InstCombiner::BuilderTy &B) : Builder(B) {}
Value *simplify(Instruction *FAdd);
private:
using AddendVect = SmallVector<const FAddend *, 4>;
Value *simplifyFAdd(AddendVect& V, unsigned InstrQuota);
Value *createAddendVal(const FAddend &A, bool& NeedNeg);
unsigned calcInstrNumber(const AddendVect& Vect);
Value *createFSub(Value *Opnd0, Value *Opnd1);
Value *createFAdd(Value *Opnd0, Value *Opnd1);
Value *createFMul(Value *Opnd0, Value *Opnd1);
Value *createFNeg(Value *V);
Value *createNaryFAdd(const AddendVect& Opnds, unsigned InstrQuota);
void createInstPostProc(Instruction *NewInst, bool NoNumber = false);
#ifndef NDEBUG
unsigned CreateInstrNum;
void initCreateInstNum() { CreateInstrNum = 0; }
void incCreateInstNum() { CreateInstrNum++; }
#else
void initCreateInstNum() {}
void incCreateInstNum() {}
#endif
InstCombiner::BuilderTy &Builder;
Instruction *Instr = nullptr;
};
}
FAddendCoef::~FAddendCoef() {
if (BufHasFpVal)
getFpValPtr()->~APFloat();
}
void FAddendCoef::set(const APFloat& C) {
APFloat *P = getFpValPtr();
if (isInt()) {
new(P) APFloat(C);
} else
*P = C;
IsFp = BufHasFpVal = true;
}
void FAddendCoef::convertToFpType(const fltSemantics &Sem) {
if (!isInt())
return;
APFloat *P = getFpValPtr();
if (IntVal > 0)
new(P) APFloat(Sem, IntVal);
else {
new(P) APFloat(Sem, 0 - IntVal);
P->changeSign();
}
IsFp = BufHasFpVal = true;
}
APFloat FAddendCoef::createAPFloatFromInt(const fltSemantics &Sem, int Val) {
if (Val >= 0)
return APFloat(Sem, Val);
APFloat T(Sem, 0 - Val);
T.changeSign();
return T;
}
void FAddendCoef::operator=(const FAddendCoef &That) {
if (That.isInt())
set(That.IntVal);
else
set(That.getFpVal());
}
void FAddendCoef::operator+=(const FAddendCoef &That) {
RoundingMode RndMode = RoundingMode::NearestTiesToEven;
if (isInt() == That.isInt()) {
if (isInt())
IntVal += That.IntVal;
else
getFpVal().add(That.getFpVal(), RndMode);
return;
}
if (isInt()) {
const APFloat &T = That.getFpVal();
convertToFpType(T.getSemantics());
getFpVal().add(T, RndMode);
return;
}
APFloat &T = getFpVal();
T.add(createAPFloatFromInt(T.getSemantics(), That.IntVal), RndMode);
}
void FAddendCoef::operator*=(const FAddendCoef &That) {
if (That.isOne())
return;
if (That.isMinusOne()) {
negate();
return;
}
if (isInt() && That.isInt()) {
int Res = IntVal * (int)That.IntVal;
assert(!insaneIntVal(Res) && "Insane int value");
IntVal = Res;
return;
}
const fltSemantics &Semantic =
isInt() ? That.getFpVal().getSemantics() : getFpVal().getSemantics();
if (isInt())
convertToFpType(Semantic);
APFloat &F0 = getFpVal();
if (That.isInt())
F0.multiply(createAPFloatFromInt(Semantic, That.IntVal),
APFloat::rmNearestTiesToEven);
else
F0.multiply(That.getFpVal(), APFloat::rmNearestTiesToEven);
}
void FAddendCoef::negate() {
if (isInt())
IntVal = 0 - IntVal;
else
getFpVal().changeSign();
}
Value *FAddendCoef::getValue(Type *Ty) const {
return isInt() ?
ConstantFP::get(Ty, float(IntVal)) :
ConstantFP::get(Ty->getContext(), getFpVal());
}
unsigned FAddend::drillValueDownOneStep
(Value *Val, FAddend &Addend0, FAddend &Addend1) {
Instruction *I = nullptr;
if (!Val || !(I = dyn_cast<Instruction>(Val)))
return 0;
unsigned Opcode = I->getOpcode();
if (Opcode == Instruction::FAdd || Opcode == Instruction::FSub) {
ConstantFP *C0, *C1;
Value *Opnd0 = I->getOperand(0);
Value *Opnd1 = I->getOperand(1);
if ((C0 = dyn_cast<ConstantFP>(Opnd0)) && C0->isZero())
Opnd0 = nullptr;
if ((C1 = dyn_cast<ConstantFP>(Opnd1)) && C1->isZero())
Opnd1 = nullptr;
if (Opnd0) {
if (!C0)
Addend0.set(1, Opnd0);
else
Addend0.set(C0, nullptr);
}
if (Opnd1) {
FAddend &Addend = Opnd0 ? Addend1 : Addend0;
if (!C1)
Addend.set(1, Opnd1);
else
Addend.set(C1, nullptr);
if (Opcode == Instruction::FSub)
Addend.negate();
}
if (Opnd0 || Opnd1)
return Opnd0 && Opnd1 ? 2 : 1;
Addend0.set(APFloat(C0->getValueAPF().getSemantics()), nullptr);
return 1;
}
if (I->getOpcode() == Instruction::FMul) {
Value *V0 = I->getOperand(0);
Value *V1 = I->getOperand(1);
if (ConstantFP *C = dyn_cast<ConstantFP>(V0)) {
Addend0.set(C, V1);
return 1;
}
if (ConstantFP *C = dyn_cast<ConstantFP>(V1)) {
Addend0.set(C, V0);
return 1;
}
}
return 0;
}
unsigned FAddend::drillAddendDownOneStep
(FAddend &Addend0, FAddend &Addend1) const {
if (isConstant())
return 0;
unsigned BreakNum = FAddend::drillValueDownOneStep(Val, Addend0, Addend1);
if (!BreakNum || Coeff.isOne())
return BreakNum;
Addend0.Scale(Coeff);
if (BreakNum == 2)
Addend1.Scale(Coeff);
return BreakNum;
}
Value *FAddCombine::simplify(Instruction *I) {
assert(I->hasAllowReassoc() && I->hasNoSignedZeros() &&
"Expected 'reassoc'+'nsz' instruction");
if (I->getType()->isVectorTy())
return nullptr;
assert((I->getOpcode() == Instruction::FAdd ||
I->getOpcode() == Instruction::FSub) && "Expect add/sub");
Instr = I;
FAddend Opnd0, Opnd1, Opnd0_0, Opnd0_1, Opnd1_0, Opnd1_1;
unsigned OpndNum = FAddend::drillValueDownOneStep(I, Opnd0, Opnd1);
unsigned Opnd0_ExpNum = 0;
unsigned Opnd1_ExpNum = 0;
if (!Opnd0.isConstant())
Opnd0_ExpNum = Opnd0.drillAddendDownOneStep(Opnd0_0, Opnd0_1);
if (OpndNum == 2 && !Opnd1.isConstant())
Opnd1_ExpNum = Opnd1.drillAddendDownOneStep(Opnd1_0, Opnd1_1);
if (Opnd0_ExpNum && Opnd1_ExpNum) {
AddendVect AllOpnds;
AllOpnds.push_back(&Opnd0_0);
AllOpnds.push_back(&Opnd1_0);
if (Opnd0_ExpNum == 2)
AllOpnds.push_back(&Opnd0_1);
if (Opnd1_ExpNum == 2)
AllOpnds.push_back(&Opnd1_1);
unsigned InstQuota = 0;
Value *V0 = I->getOperand(0);
Value *V1 = I->getOperand(1);
InstQuota = ((!isa<Constant>(V0) && V0->hasOneUse()) &&
(!isa<Constant>(V1) && V1->hasOneUse())) ? 2 : 1;
if (Value *R = simplifyFAdd(AllOpnds, InstQuota))
return R;
}
if (OpndNum != 2) {
const FAddendCoef &CE = Opnd0.getCoef();
return CE.isOne() ? Opnd0.getSymVal() : nullptr;
}
if (Opnd1_ExpNum) {
AddendVect AllOpnds;
AllOpnds.push_back(&Opnd0);
AllOpnds.push_back(&Opnd1_0);
if (Opnd1_ExpNum == 2)
AllOpnds.push_back(&Opnd1_1);
if (Value *R = simplifyFAdd(AllOpnds, 1))
return R;
}
if (Opnd0_ExpNum) {
AddendVect AllOpnds;
AllOpnds.push_back(&Opnd1);
AllOpnds.push_back(&Opnd0_0);
if (Opnd0_ExpNum == 2)
AllOpnds.push_back(&Opnd0_1);
if (Value *R = simplifyFAdd(AllOpnds, 1))
return R;
}
return nullptr;
}
Value *FAddCombine::simplifyFAdd(AddendVect& Addends, unsigned InstrQuota) {
unsigned AddendNum = Addends.size();
assert(AddendNum <= 4 && "Too many addends");
unsigned NextTmpIdx = 0;
FAddend TmpResult[3];
AddendVect SimpVect;
for (unsigned SymIdx = 0; SymIdx < AddendNum; SymIdx++) {
const FAddend *ThisAddend = Addends[SymIdx];
if (!ThisAddend) {
continue;
}
Value *Val = ThisAddend->getSymVal();
unsigned StartIdx = SimpVect.size();
SimpVect.push_back(ThisAddend);
for (unsigned SameSymIdx = SymIdx + 1;
SameSymIdx < AddendNum; SameSymIdx++) {
const FAddend *T = Addends[SameSymIdx];
if (T && T->getSymVal() == Val) {
Addends[SameSymIdx] = nullptr;
SimpVect.push_back(T);
}
}
if (StartIdx + 1 != SimpVect.size()) {
FAddend &R = TmpResult[NextTmpIdx ++];
R = *SimpVect[StartIdx];
for (unsigned Idx = StartIdx + 1; Idx < SimpVect.size(); Idx++)
R += *SimpVect[Idx];
SimpVect.resize(StartIdx);
if (!R.isZero()) {
SimpVect.push_back(&R);
}
}
}
assert((NextTmpIdx <= array_lengthof(TmpResult) + 1) &&
"out-of-bound access");
Value *Result;
if (!SimpVect.empty())
Result = createNaryFAdd(SimpVect, InstrQuota);
else {
Result = ConstantFP::get(Instr->getType(), 0.0);
}
return Result;
}
Value *FAddCombine::createNaryFAdd
(const AddendVect &Opnds, unsigned InstrQuota) {
assert(!Opnds.empty() && "Expect at least one addend");
unsigned InstrNeeded = calcInstrNumber(Opnds);
if (InstrNeeded > InstrQuota)
return nullptr;
initCreateInstNum();
Value *LastVal = nullptr;
bool LastValNeedNeg = false;
for (const FAddend *Opnd : Opnds) {
bool NeedNeg;
Value *V = createAddendVal(*Opnd, NeedNeg);
if (!LastVal) {
LastVal = V;
LastValNeedNeg = NeedNeg;
continue;
}
if (LastValNeedNeg == NeedNeg) {
LastVal = createFAdd(LastVal, V);
continue;
}
if (LastValNeedNeg)
LastVal = createFSub(V, LastVal);
else
LastVal = createFSub(LastVal, V);
LastValNeedNeg = false;
}
if (LastValNeedNeg) {
LastVal = createFNeg(LastVal);
}
#ifndef NDEBUG
assert(CreateInstrNum == InstrNeeded &&
"Inconsistent in instruction numbers");
#endif
return LastVal;
}
Value *FAddCombine::createFSub(Value *Opnd0, Value *Opnd1) {
Value *V = Builder.CreateFSub(Opnd0, Opnd1);
if (Instruction *I = dyn_cast<Instruction>(V))
createInstPostProc(I);
return V;
}
Value *FAddCombine::createFNeg(Value *V) {
Value *NewV = Builder.CreateFNeg(V);
if (Instruction *I = dyn_cast<Instruction>(NewV))
createInstPostProc(I, true); return NewV;
}
Value *FAddCombine::createFAdd(Value *Opnd0, Value *Opnd1) {
Value *V = Builder.CreateFAdd(Opnd0, Opnd1);
if (Instruction *I = dyn_cast<Instruction>(V))
createInstPostProc(I);
return V;
}
Value *FAddCombine::createFMul(Value *Opnd0, Value *Opnd1) {
Value *V = Builder.CreateFMul(Opnd0, Opnd1);
if (Instruction *I = dyn_cast<Instruction>(V))
createInstPostProc(I);
return V;
}
void FAddCombine::createInstPostProc(Instruction *NewInstr, bool NoNumber) {
NewInstr->setDebugLoc(Instr->getDebugLoc());
if (!NoNumber)
incCreateInstNum();
NewInstr->setFastMathFlags(Instr->getFastMathFlags());
}
unsigned FAddCombine::calcInstrNumber(const AddendVect &Opnds) {
unsigned OpndNum = Opnds.size();
unsigned InstrNeeded = OpndNum - 1;
for (const FAddend *Opnd : Opnds) {
if (Opnd->isConstant())
continue;
if (isa<UndefValue>(Opnd->getSymVal()))
continue;
const FAddendCoef &CE = Opnd->getCoef();
if (!CE.isMinusOne() && !CE.isOne())
InstrNeeded++;
}
return InstrNeeded;
}
Value *FAddCombine::createAddendVal(const FAddend &Opnd, bool &NeedNeg) {
const FAddendCoef &Coeff = Opnd.getCoef();
if (Opnd.isConstant()) {
NeedNeg = false;
return Coeff.getValue(Instr->getType());
}
Value *OpndVal = Opnd.getSymVal();
if (Coeff.isMinusOne() || Coeff.isOne()) {
NeedNeg = Coeff.isMinusOne();
return OpndVal;
}
if (Coeff.isTwo() || Coeff.isMinusTwo()) {
NeedNeg = Coeff.isMinusTwo();
return createFAdd(OpndVal, OpndVal);
}
NeedNeg = false;
return createFMul(OpndVal, Coeff.getValue(Instr->getType()));
}
static Value *checkForNegativeOperand(BinaryOperator &I,
InstCombiner::BuilderTy &Builder) {
Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
if (!LHS->hasOneUse() && !RHS->hasOneUse())
return nullptr;
Value *X = nullptr, *Y = nullptr, *Z = nullptr;
const APInt *C1 = nullptr, *C2 = nullptr;
if (match(RHS, m_Add(m_Value(X), m_One())))
std::swap(LHS, RHS);
if (match(LHS, m_Add(m_Value(X), m_One()))) {
if (match(RHS, m_Xor(m_Value(Y), m_APInt(C1))))
std::swap(X, RHS);
if (match(X, m_Xor(m_Value(Y), m_APInt(C1)))) {
if (match(Y, m_Or(m_Value(Z), m_APInt(C2))) && (*C2 == ~(*C1))) {
Value *NewAnd = Builder.CreateAnd(Z, *C1);
return Builder.CreateSub(RHS, NewAnd, "sub");
} else if (match(Y, m_And(m_Value(Z), m_APInt(C2))) && (*C1 == *C2)) {
Value *NewOr = Builder.CreateOr(Z, ~(*C1));
return Builder.CreateSub(RHS, NewOr, "sub");
}
}
}
LHS = I.getOperand(0);
RHS = I.getOperand(1);
if (match(RHS, m_Xor(m_Value(Y), m_APInt(C1))))
std::swap(LHS, RHS);
if (match(LHS, m_Xor(m_Value(Y), m_APInt(C1))))
if (C1->countTrailingZeros() == 0)
if (match(Y, m_And(m_Value(Z), m_APInt(C2))) && *C1 == (*C2 + 1)) {
Value *NewOr = Builder.CreateOr(Z, ~(*C2));
return Builder.CreateSub(RHS, NewOr, "sub");
}
return nullptr;
}
static Instruction *foldNoWrapAdd(BinaryOperator &Add,
InstCombiner::BuilderTy &Builder) {
Value *Op0 = Add.getOperand(0), *Op1 = Add.getOperand(1);
Type *Ty = Add.getType();
Constant *Op1C;
if (!match(Op1, m_Constant(Op1C)))
return nullptr;
Value *X;
const APInt *C1, *C2;
if (match(Op1, m_APInt(C1)) &&
match(Op0, m_OneUse(m_ZExt(m_NUWAdd(m_Value(X), m_APInt(C2))))) &&
C1->isNegative() && C1->sge(-C2->sext(C1->getBitWidth()))) {
Constant *NewC =
ConstantInt::get(X->getType(), *C2 + C1->trunc(C2->getBitWidth()));
return new ZExtInst(Builder.CreateNUWAdd(X, NewC), Ty);
}
Constant *NarrowC;
if (match(Op0, m_OneUse(m_SExt(m_NSWAdd(m_Value(X), m_Constant(NarrowC)))))) {
Constant *WideC = ConstantExpr::getSExt(NarrowC, Ty);
Constant *NewC = ConstantExpr::getAdd(WideC, Op1C);
Value *WideX = Builder.CreateSExt(X, Ty);
return BinaryOperator::CreateAdd(WideX, NewC);
}
if (match(Op0, m_OneUse(m_ZExt(m_NUWAdd(m_Value(X), m_Constant(NarrowC)))))) {
Constant *WideC = ConstantExpr::getZExt(NarrowC, Ty);
Constant *NewC = ConstantExpr::getAdd(WideC, Op1C);
Value *WideX = Builder.CreateZExt(X, Ty);
return BinaryOperator::CreateAdd(WideX, NewC);
}
return nullptr;
}
Instruction *InstCombinerImpl::foldAddWithConstant(BinaryOperator &Add) {
Value *Op0 = Add.getOperand(0), *Op1 = Add.getOperand(1);
Constant *Op1C;
if (!match(Op1, m_ImmConstant(Op1C)))
return nullptr;
if (Instruction *NV = foldBinOpIntoSelectOrPhi(Add))
return NV;
Value *X;
Constant *Op00C;
if (match(Op0, m_Sub(m_Constant(Op00C), m_Value(X))))
return BinaryOperator::CreateSub(ConstantExpr::getAdd(Op00C, Op1C), X);
Value *Y;
if (match(Op0, m_OneUse(m_Sub(m_Value(X), m_Value(Y)))) &&
match(Op1, m_AllOnes()))
return BinaryOperator::CreateAdd(Builder.CreateNot(Y), X);
if (match(Op0, m_ZExt(m_Value(X))) &&
X->getType()->getScalarSizeInBits() == 1)
return SelectInst::Create(X, InstCombiner::AddOne(Op1C), Op1);
if (match(Op0, m_SExt(m_Value(X))) &&
X->getType()->getScalarSizeInBits() == 1)
return SelectInst::Create(X, InstCombiner::SubOne(Op1C), Op1);
if (match(Op0, m_Not(m_Value(X))))
return BinaryOperator::CreateSub(InstCombiner::SubOne(Op1C), X);
const APInt *C;
if (!match(Op1, m_APInt(C)))
return nullptr;
Constant *Op01C;
if (match(Op0, m_Or(m_Value(X), m_ImmConstant(Op01C))) &&
haveNoCommonBitsSet(X, Op01C, DL, &AC, &Add, &DT))
return BinaryOperator::CreateAdd(X, ConstantExpr::getAdd(Op01C, Op1C));
const APInt *C2;
if (match(Op0, m_Or(m_Value(), m_APInt(C2))) && *C2 == -*C)
return BinaryOperator::CreateXor(Op0, ConstantInt::get(Add.getType(), *C2));
if (C->isSignMask()) {
if (Add.hasNoSignedWrap() || Add.hasNoUnsignedWrap())
return BinaryOperator::CreateOr(Op0, Op1);
return BinaryOperator::CreateXor(Op0, Op1);
}
Type *Ty = Add.getType();
if (match(Op0, m_ZExt(m_Xor(m_Value(X), m_APInt(C2)))) &&
C2->isMinSignedValue() && C2->sext(Ty->getScalarSizeInBits()) == *C)
return CastInst::Create(Instruction::SExt, X, Ty);
if (match(Op0, m_Xor(m_Value(X), m_APInt(C2)))) {
if (C2->isSignMask())
return BinaryOperator::CreateAdd(X, ConstantInt::get(Ty, *C2 ^ *C));
if (C2->isMask()) {
KnownBits LHSKnown = computeKnownBits(X, 0, &Add);
if ((*C2 | LHSKnown.Zero).isAllOnes())
return BinaryOperator::CreateSub(ConstantInt::get(Ty, *C2 + *C), X);
}
if (Op0->hasOneUse() && *C2 == -(*C)) {
unsigned BitWidth = Ty->getScalarSizeInBits();
unsigned ShAmt = 0;
if (C->isPowerOf2())
ShAmt = BitWidth - C->logBase2() - 1;
else if (C2->isPowerOf2())
ShAmt = BitWidth - C2->logBase2() - 1;
if (ShAmt && MaskedValueIsZero(X, APInt::getHighBitsSet(BitWidth, ShAmt),
0, &Add)) {
Constant *ShAmtC = ConstantInt::get(Ty, ShAmt);
Value *NewShl = Builder.CreateShl(X, ShAmtC, "sext");
return BinaryOperator::CreateAShr(NewShl, ShAmtC);
}
}
}
if (C->isOne() && Op0->hasOneUse()) {
if (match(Op0, m_SExt(m_Value(X))) &&
X->getType()->getScalarSizeInBits() == 1)
return new ZExtInst(Builder.CreateNot(X), Ty);
const APInt *C3;
if (match(Op0, m_AShr(m_Shl(m_Value(X), m_APInt(C2)), m_APInt(C3))) &&
C2 == C3 && *C2 == Ty->getScalarSizeInBits() - 1) {
Value *NotX = Builder.CreateNot(X);
return BinaryOperator::CreateAnd(NotX, ConstantInt::get(Ty, 1));
}
}
if (match(Op0, m_OneUse(m_And(m_Value(X), m_APInt(C2)))) &&
C2->isNegative() && C2->isShiftedMask() && *C == (*C & *C2)) {
Value *NewAdd = Builder.CreateAdd(X, ConstantInt::get(Ty, *C));
return BinaryOperator::CreateAnd(NewAdd, ConstantInt::get(Ty, *C2));
}
return nullptr;
}
static bool MatchMul(Value *E, Value *&Op, APInt &C) {
const APInt *AI;
if (match(E, m_Mul(m_Value(Op), m_APInt(AI)))) {
C = *AI;
return true;
}
if (match(E, m_Shl(m_Value(Op), m_APInt(AI)))) {
C = APInt(AI->getBitWidth(), 1);
C <<= *AI;
return true;
}
return false;
}
static bool MatchRem(Value *E, Value *&Op, APInt &C, bool &IsSigned) {
const APInt *AI;
IsSigned = false;
if (match(E, m_SRem(m_Value(Op), m_APInt(AI)))) {
IsSigned = true;
C = *AI;
return true;
}
if (match(E, m_URem(m_Value(Op), m_APInt(AI)))) {
C = *AI;
return true;
}
if (match(E, m_And(m_Value(Op), m_APInt(AI))) && (*AI + 1).isPowerOf2()) {
C = *AI + 1;
return true;
}
return false;
}
static bool MatchDiv(Value *E, Value *&Op, APInt &C, bool IsSigned) {
const APInt *AI;
if (IsSigned && match(E, m_SDiv(m_Value(Op), m_APInt(AI)))) {
C = *AI;
return true;
}
if (!IsSigned) {
if (match(E, m_UDiv(m_Value(Op), m_APInt(AI)))) {
C = *AI;
return true;
}
if (match(E, m_LShr(m_Value(Op), m_APInt(AI)))) {
C = APInt(AI->getBitWidth(), 1);
C <<= *AI;
return true;
}
}
return false;
}
static bool MulWillOverflow(APInt &C0, APInt &C1, bool IsSigned) {
bool overflow;
if (IsSigned)
(void)C0.smul_ov(C1, overflow);
else
(void)C0.umul_ov(C1, overflow);
return overflow;
}
Value *InstCombinerImpl::SimplifyAddWithRemainder(BinaryOperator &I) {
Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Value *X, *MulOpV;
APInt C0, MulOpC;
bool IsSigned;
if (((MatchRem(LHS, X, C0, IsSigned) && MatchMul(RHS, MulOpV, MulOpC)) ||
(MatchRem(RHS, X, C0, IsSigned) && MatchMul(LHS, MulOpV, MulOpC))) &&
C0 == MulOpC) {
Value *RemOpV;
APInt C1;
bool Rem2IsSigned;
if (MatchRem(MulOpV, RemOpV, C1, Rem2IsSigned) &&
IsSigned == Rem2IsSigned) {
Value *DivOpV;
APInt DivOpC;
if (MatchDiv(RemOpV, DivOpV, DivOpC, IsSigned) && X == DivOpV &&
C0 == DivOpC && !MulWillOverflow(C0, C1, IsSigned)) {
Value *NewDivisor = ConstantInt::get(X->getType(), C0 * C1);
return IsSigned ? Builder.CreateSRem(X, NewDivisor, "srem")
: Builder.CreateURem(X, NewDivisor, "urem");
}
}
}
return nullptr;
}
static Instruction *canonicalizeLowbitMask(BinaryOperator &I,
InstCombiner::BuilderTy &Builder) {
Value *NBits;
if (!match(&I, m_Add(m_OneUse(m_Shl(m_One(), m_Value(NBits))), m_AllOnes())))
return nullptr;
Constant *MinusOne = Constant::getAllOnesValue(NBits->getType());
Value *NotMask = Builder.CreateShl(MinusOne, NBits, "notmask");
if (auto *BOp = dyn_cast<BinaryOperator>(NotMask)) {
BOp->setHasNoSignedWrap();
BOp->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
}
return BinaryOperator::CreateNot(NotMask, I.getName());
}
static Instruction *foldToUnsignedSaturatedAdd(BinaryOperator &I) {
assert(I.getOpcode() == Instruction::Add && "Expecting add instruction");
Type *Ty = I.getType();
auto getUAddSat = [&]() {
return Intrinsic::getDeclaration(I.getModule(), Intrinsic::uadd_sat, Ty);
};
Value *X, *Y;
if (match(&I, m_c_Add(m_c_UMin(m_Value(X), m_Not(m_Value(Y))),
m_Deferred(Y))))
return CallInst::Create(getUAddSat(), { X, Y });
const APInt *C, *NotC;
if (match(&I, m_Add(m_UMin(m_Value(X), m_APInt(NotC)), m_APInt(C))) &&
*C == ~*NotC)
return CallInst::Create(getUAddSat(), { X, ConstantInt::get(Ty, *C) });
return nullptr;
}
Instruction *InstCombinerImpl::
canonicalizeCondSignextOfHighBitExtractToSignextHighBitExtract(
BinaryOperator &I) {
assert((I.getOpcode() == Instruction::Add ||
I.getOpcode() == Instruction::Or ||
I.getOpcode() == Instruction::Sub) &&
"Expecting add/or/sub instruction");
Value *X, *Select;
Instruction *LowBitsToSkip, *Extract;
if (!match(&I, m_c_BinOp(m_TruncOrSelf(m_CombineAnd(
m_LShr(m_Value(X), m_Instruction(LowBitsToSkip)),
m_Instruction(Extract))),
m_Value(Select))))
return nullptr;
if (I.getOpcode() == Instruction::Sub && I.getOperand(1) != Select)
return nullptr;
Type *XTy = X->getType();
bool HadTrunc = I.getType() != XTy;
if (HadTrunc && !match(&I, m_c_BinOp(m_OneUse(m_Value()), m_Value())))
return nullptr;
Constant *C;
Value *NBits;
if (!match(
LowBitsToSkip,
m_ZExtOrSelf(m_Sub(m_Constant(C), m_ZExtOrSelf(m_Value(NBits))))) ||
!match(C, m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_EQ,
APInt(C->getType()->getScalarSizeInBits(),
X->getType()->getScalarSizeInBits()))))
return nullptr;
auto SkipExtInMagic = [&I](Value *&V) {
if (I.getOpcode() == Instruction::Sub)
match(V, m_ZExtOrSelf(m_Value(V)));
else
match(V, m_SExtOrSelf(m_Value(V)));
};
SkipExtInMagic(Select);
ICmpInst::Predicate Pred;
const APInt *Thr;
Value *SignExtendingValue, *Zero;
bool ShouldSignext;
if (!match(Select, m_Select(m_ICmp(Pred, m_Specific(X), m_APInt(Thr)),
m_Value(SignExtendingValue), m_Value(Zero))) ||
!isSignBitCheck(Pred, *Thr, ShouldSignext))
return nullptr;
if (!ShouldSignext)
std::swap(SignExtendingValue, Zero);
if (!match(Zero, m_Zero()))
return nullptr;
SkipExtInMagic(SignExtendingValue);
Constant *SignExtendingValueBaseConstant;
if (!match(SignExtendingValue,
m_Shl(m_Constant(SignExtendingValueBaseConstant),
m_ZExtOrSelf(m_Specific(NBits)))))
return nullptr;
if (I.getOpcode() == Instruction::Sub
? !match(SignExtendingValueBaseConstant, m_One())
: !match(SignExtendingValueBaseConstant, m_AllOnes()))
return nullptr;
auto *NewAShr = BinaryOperator::CreateAShr(X, LowBitsToSkip,
Extract->getName() + ".sext");
NewAShr->copyIRFlags(Extract); if (!HadTrunc)
return NewAShr;
Builder.Insert(NewAShr);
return TruncInst::CreateTruncOrBitCast(NewAShr, I.getType());
}
static Instruction *factorizeMathWithShlOps(BinaryOperator &I,
InstCombiner::BuilderTy &Builder) {
assert((I.getOpcode() == Instruction::Add ||
I.getOpcode() == Instruction::Sub) &&
"Expected add/sub");
auto *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0));
auto *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1));
if (!Op0 || !Op1 || !(Op0->hasOneUse() || Op1->hasOneUse()))
return nullptr;
Value *X, *Y, *ShAmt;
if (!match(Op0, m_Shl(m_Value(X), m_Value(ShAmt))) ||
!match(Op1, m_Shl(m_Value(Y), m_Specific(ShAmt))))
return nullptr;
bool HasNSW = I.hasNoSignedWrap() && Op0->hasNoSignedWrap() &&
Op1->hasNoSignedWrap();
bool HasNUW = I.hasNoUnsignedWrap() && Op0->hasNoUnsignedWrap() &&
Op1->hasNoUnsignedWrap();
Value *NewMath = Builder.CreateBinOp(I.getOpcode(), X, Y);
if (auto *NewI = dyn_cast<BinaryOperator>(NewMath)) {
NewI->setHasNoSignedWrap(HasNSW);
NewI->setHasNoUnsignedWrap(HasNUW);
}
auto *NewShl = BinaryOperator::CreateShl(NewMath, ShAmt);
NewShl->setHasNoSignedWrap(HasNSW);
NewShl->setHasNoUnsignedWrap(HasNUW);
return NewShl;
}
Instruction *InstCombinerImpl::visitAdd(BinaryOperator &I) {
if (Value *V = simplifyAddInst(I.getOperand(0), I.getOperand(1),
I.hasNoSignedWrap(), I.hasNoUnsignedWrap(),
SQ.getWithInstruction(&I)))
return replaceInstUsesWith(I, V);
if (SimplifyAssociativeOrCommutative(I))
return &I;
if (Instruction *X = foldVectorBinop(I))
return X;
if (Instruction *Phi = foldBinopWithPhiOperands(I))
return Phi;
if (Value *V = SimplifyUsingDistributiveLaws(I))
return replaceInstUsesWith(I, V);
if (Instruction *R = factorizeMathWithShlOps(I, Builder))
return R;
if (Instruction *X = foldAddWithConstant(I))
return X;
if (Instruction *X = foldNoWrapAdd(I, Builder))
return X;
Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Type *Ty = I.getType();
if (Ty->isIntOrIntVectorTy(1))
return BinaryOperator::CreateXor(LHS, RHS);
if (LHS == RHS) {
auto *Shl = BinaryOperator::CreateShl(LHS, ConstantInt::get(Ty, 1));
Shl->setHasNoSignedWrap(I.hasNoSignedWrap());
Shl->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
return Shl;
}
Value *A, *B;
if (match(LHS, m_Neg(m_Value(A)))) {
if (match(RHS, m_Neg(m_Value(B))))
return BinaryOperator::CreateNeg(Builder.CreateAdd(A, B));
return BinaryOperator::CreateSub(RHS, A);
}
if (match(RHS, m_Neg(m_Value(B))))
return BinaryOperator::CreateSub(LHS, B);
if (Value *V = checkForNegativeOperand(I, Builder))
return replaceInstUsesWith(I, V);
if (match(&I, m_c_BinOp(m_Add(m_Value(A), m_One()), m_Not(m_Value(B)))) ||
match(&I, m_BinOp(m_c_Add(m_Not(m_Value(B)), m_Value(A)), m_One())))
return BinaryOperator::CreateSub(A, B);
if (match(LHS, m_OneUse(m_c_Add(m_Value(A), m_Specific(RHS)))))
return BinaryOperator::CreateAdd(A, Builder.CreateShl(RHS, 1, "reass.add"));
if (match(RHS, m_OneUse(m_c_Add(m_Value(A), m_Specific(LHS)))))
return BinaryOperator::CreateAdd(A, Builder.CreateShl(LHS, 1, "reass.add"));
{
Constant *C1, *C2;
if (match(&I, m_c_Add(m_Add(m_Value(A), m_ImmConstant(C1)),
m_Sub(m_ImmConstant(C2), m_Value(B)))) &&
(LHS->hasOneUse() || RHS->hasOneUse())) {
Value *Sub = Builder.CreateSub(A, B);
return BinaryOperator::CreateAdd(Sub, ConstantExpr::getAdd(C1, C2));
}
}
if (Value *V = SimplifyAddWithRemainder(I)) return replaceInstUsesWith(I, V);
const APInt *C1, *C2;
if (match(LHS, m_Shl(m_SDiv(m_Specific(RHS), m_APInt(C1)), m_APInt(C2)))) {
APInt one(C2->getBitWidth(), 1);
APInt minusC1 = -(*C1);
if (minusC1 == (one << *C2)) {
Constant *NewRHS = ConstantInt::get(RHS->getType(), minusC1);
return BinaryOperator::CreateSRem(RHS, NewRHS);
}
}
if (match(&I, m_c_Add(m_And(m_Value(A), m_APInt(C1)), m_Deferred(A))) &&
C1->isPowerOf2() && (ComputeNumSignBits(A) > C1->countLeadingZeros())) {
Constant *NewMask = ConstantInt::get(RHS->getType(), *C1 - 1);
return BinaryOperator::CreateAnd(A, NewMask);
}
if (haveNoCommonBitsSet(LHS, RHS, DL, &AC, &I, &DT))
return BinaryOperator::CreateOr(LHS, RHS);
{
SelectInst *SI = dyn_cast<SelectInst>(LHS);
Value *A = RHS;
if (!SI) {
SI = dyn_cast<SelectInst>(RHS);
A = LHS;
}
if (SI && SI->hasOneUse()) {
Value *TV = SI->getTrueValue();
Value *FV = SI->getFalseValue();
Value *N;
if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
return SelectInst::Create(SI->getCondition(), N, A);
if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
return SelectInst::Create(SI->getCondition(), A, N);
}
}
if (Instruction *Ext = narrowMathIfNoOverflow(I))
return Ext;
if (match(&I, m_c_BinOp(m_Xor(m_Value(A), m_Value(B)),
m_c_And(m_Deferred(A), m_Deferred(B)))))
return BinaryOperator::CreateOr(A, B);
if (match(&I, m_c_BinOp(m_Or(m_Value(A), m_Value(B)),
m_c_And(m_Deferred(A), m_Deferred(B))))) {
replaceOperand(I, 0, A);
replaceOperand(I, 1, B);
return &I;
}
bool Changed = false;
if (!I.hasNoSignedWrap() && willNotOverflowSignedAdd(LHS, RHS, I)) {
Changed = true;
I.setHasNoSignedWrap(true);
}
if (!I.hasNoUnsignedWrap() && willNotOverflowUnsignedAdd(LHS, RHS, I)) {
Changed = true;
I.setHasNoUnsignedWrap(true);
}
if (Instruction *V = canonicalizeLowbitMask(I, Builder))
return V;
if (Instruction *V =
canonicalizeCondSignextOfHighBitExtractToSignextHighBitExtract(I))
return V;
if (Instruction *SatAdd = foldToUnsignedSaturatedAdd(I))
return SatAdd;
if (match(&I, m_c_BinOp(
m_OneUse(m_Intrinsic<Intrinsic::usub_sat>(m_Value(A), m_Value(B))),
m_Deferred(B)))) {
return replaceInstUsesWith(I,
Builder.CreateIntrinsic(Intrinsic::umax, {I.getType()}, {A, B}));
}
if (match(LHS, m_OneUse(m_Intrinsic<Intrinsic::ctpop>(m_Value(A)))) &&
match(RHS, m_OneUse(m_Intrinsic<Intrinsic::ctpop>(m_Value(B)))) &&
haveNoCommonBitsSet(A, B, DL, &AC, &I, &DT))
return replaceInstUsesWith(
I, Builder.CreateIntrinsic(Intrinsic::ctpop, {I.getType()},
{Builder.CreateOr(A, B)}));
return Changed ? &I : nullptr;
}
static Instruction *factorizeLerp(BinaryOperator &I,
InstCombiner::BuilderTy &Builder) {
Value *X, *Y, *Z;
if (!match(&I, m_c_FAdd(m_OneUse(m_c_FMul(m_Value(Y),
m_OneUse(m_FSub(m_FPOne(),
m_Value(Z))))),
m_OneUse(m_c_FMul(m_Value(X), m_Deferred(Z))))))
return nullptr;
Value *XY = Builder.CreateFSubFMF(X, Y, &I);
Value *MulZ = Builder.CreateFMulFMF(Z, XY, &I);
return BinaryOperator::CreateFAddFMF(Y, MulZ, &I);
}
static Instruction *factorizeFAddFSub(BinaryOperator &I,
InstCombiner::BuilderTy &Builder) {
assert((I.getOpcode() == Instruction::FAdd ||
I.getOpcode() == Instruction::FSub) && "Expecting fadd/fsub");
assert(I.hasAllowReassoc() && I.hasNoSignedZeros() &&
"FP factorization requires FMF");
if (Instruction *Lerp = factorizeLerp(I, Builder))
return Lerp;
Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
if (!Op0->hasOneUse() || !Op1->hasOneUse())
return nullptr;
Value *X, *Y, *Z;
bool IsFMul;
if ((match(Op0, m_FMul(m_Value(X), m_Value(Z))) &&
match(Op1, m_c_FMul(m_Value(Y), m_Specific(Z)))) ||
(match(Op0, m_FMul(m_Value(Z), m_Value(X))) &&
match(Op1, m_c_FMul(m_Value(Y), m_Specific(Z)))))
IsFMul = true;
else if (match(Op0, m_FDiv(m_Value(X), m_Value(Z))) &&
match(Op1, m_FDiv(m_Value(Y), m_Specific(Z))))
IsFMul = false;
else
return nullptr;
bool IsFAdd = I.getOpcode() == Instruction::FAdd;
Value *XY = IsFAdd ? Builder.CreateFAddFMF(X, Y, &I)
: Builder.CreateFSubFMF(X, Y, &I);
const APFloat *C;
if (match(XY, m_APFloat(C)) && !C->isNormal())
return nullptr;
return IsFMul ? BinaryOperator::CreateFMulFMF(XY, Z, &I)
: BinaryOperator::CreateFDivFMF(XY, Z, &I);
}
Instruction *InstCombinerImpl::visitFAdd(BinaryOperator &I) {
if (Value *V = simplifyFAddInst(I.getOperand(0), I.getOperand(1),
I.getFastMathFlags(),
SQ.getWithInstruction(&I)))
return replaceInstUsesWith(I, V);
if (SimplifyAssociativeOrCommutative(I))
return &I;
if (Instruction *X = foldVectorBinop(I))
return X;
if (Instruction *Phi = foldBinopWithPhiOperands(I))
return Phi;
if (Instruction *FoldedFAdd = foldBinOpIntoSelectOrPhi(I))
return FoldedFAdd;
Value *X, *Y;
if (match(&I, m_c_FAdd(m_FNeg(m_Value(X)), m_Value(Y))))
return BinaryOperator::CreateFSubFMF(Y, X, &I);
Value *Z;
if (match(&I, m_c_FAdd(m_OneUse(m_c_FMul(m_FNeg(m_Value(X)), m_Value(Y))),
m_Value(Z)))) {
Value *XY = Builder.CreateFMulFMF(X, Y, &I);
return BinaryOperator::CreateFSubFMF(Z, XY, &I);
}
if (match(&I, m_c_FAdd(m_OneUse(m_FDiv(m_FNeg(m_Value(X)), m_Value(Y))),
m_Value(Z))) ||
match(&I, m_c_FAdd(m_OneUse(m_FDiv(m_Value(X), m_FNeg(m_Value(Y)))),
m_Value(Z)))) {
Value *XY = Builder.CreateFDivFMF(X, Y, &I);
return BinaryOperator::CreateFSubFMF(Z, XY, &I);
}
Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
Value *LHSIntVal = LHSConv->getOperand(0);
Type *FPType = LHSConv->getType();
auto IsValidPromotion = [](Type *FTy, Type *ITy) {
Type *FScalarTy = FTy->getScalarType();
Type *IScalarTy = ITy->getScalarType();
unsigned MaxRepresentableBits =
APFloat::semanticsPrecision(FScalarTy->getFltSemantics());
return IScalarTy->getIntegerBitWidth() <= MaxRepresentableBits;
};
if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
if (IsValidPromotion(FPType, LHSIntVal->getType())) {
Constant *CI =
ConstantExpr::getFPToSI(CFP, LHSIntVal->getType());
if (LHSConv->hasOneUse() &&
ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
willNotOverflowSignedAdd(LHSIntVal, CI, I)) {
Value *NewAdd = Builder.CreateNSWAdd(LHSIntVal, CI, "addconv");
return new SIToFPInst(NewAdd, I.getType());
}
}
if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
Value *RHSIntVal = RHSConv->getOperand(0);
if (IsValidPromotion(FPType, LHSIntVal->getType())) {
if (LHSIntVal->getType() == RHSIntVal->getType() &&
(LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
willNotOverflowSignedAdd(LHSIntVal, RHSIntVal, I)) {
Value *NewAdd = Builder.CreateNSWAdd(LHSIntVal, RHSIntVal, "addconv");
return new SIToFPInst(NewAdd, I.getType());
}
}
}
}
if (Value *V = SimplifySelectsFeedingBinaryOp(I, LHS, RHS))
return replaceInstUsesWith(I, V);
if (I.hasAllowReassoc() && I.hasNoSignedZeros()) {
if (Instruction *F = factorizeFAddFSub(I, Builder))
return F;
if (match(&I, m_c_FAdd(m_OneUse(m_Intrinsic<Intrinsic::vector_reduce_fadd>(
m_AnyZeroFP(), m_Value(X))),
m_Value(Y)))) {
return replaceInstUsesWith(
I, Builder.CreateIntrinsic(Intrinsic::vector_reduce_fadd,
{X->getType()}, {Y, X}, &I));
}
const APFloat *StartC, *C;
if (match(LHS, m_OneUse(m_Intrinsic<Intrinsic::vector_reduce_fadd>(
m_APFloat(StartC), m_Value(X)))) &&
match(RHS, m_APFloat(C))) {
Constant *NewStartC = ConstantFP::get(I.getType(), *C + *StartC);
return replaceInstUsesWith(
I, Builder.CreateIntrinsic(Intrinsic::vector_reduce_fadd,
{X->getType()}, {NewStartC, X}, &I));
}
Constant *MulC;
if (match(&I, m_c_FAdd(m_FMul(m_Value(X), m_ImmConstant(MulC)),
m_Deferred(X)))) {
if (Constant *NewMulC = ConstantFoldBinaryOpOperands(
Instruction::FAdd, MulC, ConstantFP::get(I.getType(), 1.0), DL))
return BinaryOperator::CreateFMulFMF(X, NewMulC, &I);
}
if (Value *V = FAddCombine(Builder).simplify(&I))
return replaceInstUsesWith(I, V);
}
return nullptr;
}
Value *InstCombinerImpl::OptimizePointerDifference(Value *LHS, Value *RHS,
Type *Ty, bool IsNUW) {
bool Swapped = false;
GEPOperator *GEP1 = nullptr, *GEP2 = nullptr;
if (!isa<GEPOperator>(LHS) && isa<GEPOperator>(RHS)) {
std::swap(LHS, RHS);
Swapped = true;
}
if (auto *LHSGEP = dyn_cast<GEPOperator>(LHS)) {
if (LHSGEP->getOperand(0)->stripPointerCasts() ==
RHS->stripPointerCasts()) {
GEP1 = LHSGEP;
} else if (auto *RHSGEP = dyn_cast<GEPOperator>(RHS)) {
if (LHSGEP->getOperand(0)->stripPointerCasts() ==
RHSGEP->getOperand(0)->stripPointerCasts()) {
GEP1 = LHSGEP;
GEP2 = RHSGEP;
}
}
}
if (!GEP1)
return nullptr;
if (GEP2) {
unsigned NumNonConstantIndices1 = GEP1->countNonConstantIndices();
unsigned NumNonConstantIndices2 = GEP2->countNonConstantIndices();
if (NumNonConstantIndices1 + NumNonConstantIndices2 > 1 &&
((NumNonConstantIndices1 > 0 && !GEP1->hasOneUse()) ||
(NumNonConstantIndices2 > 0 && !GEP2->hasOneUse()))) {
return nullptr;
}
}
Value *Result = EmitGEPOffset(GEP1);
if (auto *I = dyn_cast<Instruction>(Result))
if (IsNUW && !GEP2 && !Swapped && GEP1->isInBounds() &&
I->getOpcode() == Instruction::Mul)
I->setHasNoUnsignedWrap();
if (GEP2) {
Value *Offset = EmitGEPOffset(GEP2);
Result = Builder.CreateSub(Result, Offset, "gepdiff", false,
GEP1->isInBounds() && GEP2->isInBounds());
}
if (Swapped)
Result = Builder.CreateNeg(Result, "diff.neg");
return Builder.CreateIntCast(Result, Ty, true);
}
static Instruction *foldSubOfMinMax(BinaryOperator &I,
InstCombiner::BuilderTy &Builder) {
Value *Op0 = I.getOperand(0);
Value *Op1 = I.getOperand(1);
Type *Ty = I.getType();
auto *MinMax = dyn_cast<MinMaxIntrinsic>(Op1);
if (!MinMax)
return nullptr;
Value *X = MinMax->getLHS();
Value *Y = MinMax->getRHS();
if (match(Op0, m_c_Add(m_Specific(X), m_Specific(Y))) &&
(Op0->hasOneUse() || Op1->hasOneUse())) {
Intrinsic::ID InvID = getInverseMinMaxIntrinsic(MinMax->getIntrinsicID());
Function *F = Intrinsic::getDeclaration(I.getModule(), InvID, Ty);
return CallInst::Create(F, {X, Y});
}
Value *Z;
if (match(Op1, m_OneUse(m_UMin(m_Value(Y), m_Value(Z))))) {
if (match(Op0, m_OneUse(m_c_Add(m_Specific(Y), m_Value(X))))) {
Value *USub = Builder.CreateIntrinsic(Intrinsic::usub_sat, Ty, {Y, Z});
return BinaryOperator::CreateAdd(X, USub);
}
if (match(Op0, m_OneUse(m_c_Add(m_Specific(Z), m_Value(X))))) {
Value *USub = Builder.CreateIntrinsic(Intrinsic::usub_sat, Ty, {Z, Y});
return BinaryOperator::CreateAdd(X, USub);
}
}
if (MinMax->isSigned() && match(Y, m_ZeroInt()) &&
match(X, m_NSWSub(m_Specific(Op0), m_Value(Z)))) {
Intrinsic::ID InvID = getInverseMinMaxIntrinsic(MinMax->getIntrinsicID());
Function *F = Intrinsic::getDeclaration(I.getModule(), InvID, Ty);
return CallInst::Create(F, {Op0, Z});
}
return nullptr;
}
Instruction *InstCombinerImpl::visitSub(BinaryOperator &I) {
if (Value *V = simplifySubInst(I.getOperand(0), I.getOperand(1),
I.hasNoSignedWrap(), I.hasNoUnsignedWrap(),
SQ.getWithInstruction(&I)))
return replaceInstUsesWith(I, V);
if (Instruction *X = foldVectorBinop(I))
return X;
if (Instruction *Phi = foldBinopWithPhiOperands(I))
return Phi;
Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
if (Value *V = dyn_castNegVal(Op1)) {
BinaryOperator *Res = BinaryOperator::CreateAdd(Op0, V);
if (const auto *BO = dyn_cast<BinaryOperator>(Op1)) {
assert(BO->getOpcode() == Instruction::Sub &&
"Expected a subtraction operator!");
if (BO->hasNoSignedWrap() && I.hasNoSignedWrap())
Res->setHasNoSignedWrap(true);
} else {
if (cast<Constant>(Op1)->isNotMinSignedValue() && I.hasNoSignedWrap())
Res->setHasNoSignedWrap(true);
}
return Res;
}
if (Instruction *R = factorizeMathWithShlOps(I, Builder))
return R;
Constant *C;
if (match(Op0, m_ImmConstant(C))) {
Value *X;
Constant *C2;
if (match(Op1, m_Add(m_Value(X), m_ImmConstant(C2))))
return BinaryOperator::CreateSub(ConstantExpr::getSub(C, C2), X);
}
auto TryToNarrowDeduceFlags = [this, &I, &Op0, &Op1]() -> Instruction * {
if (Instruction *Ext = narrowMathIfNoOverflow(I))
return Ext;
bool Changed = false;
if (!I.hasNoSignedWrap() && willNotOverflowSignedSub(Op0, Op1, I)) {
Changed = true;
I.setHasNoSignedWrap(true);
}
if (!I.hasNoUnsignedWrap() && willNotOverflowUnsignedSub(Op0, Op1, I)) {
Changed = true;
I.setHasNoUnsignedWrap(true);
}
return Changed ? &I : nullptr;
};
bool IsNegation = match(Op0, m_ZeroInt());
if (!IsNegation || none_of(I.users(), [&I, Op1](const User *U) {
const Instruction *UI = dyn_cast<Instruction>(U);
if (!UI)
return false;
return match(UI,
m_Select(m_Value(), m_Specific(Op1), m_Specific(&I))) ||
match(UI, m_Select(m_Value(), m_Specific(&I), m_Specific(Op1)));
})) {
if (Value *NegOp1 = Negator::Negate(IsNegation, Op1, *this))
return BinaryOperator::CreateAdd(NegOp1, Op0);
}
if (IsNegation)
return TryToNarrowDeduceFlags();
if (Value *V = SimplifyUsingDistributiveLaws(I))
return replaceInstUsesWith(I, V);
if (I.getType()->isIntOrIntVectorTy(1))
return BinaryOperator::CreateXor(Op0, Op1);
if (match(Op0, m_AllOnes()))
return BinaryOperator::CreateNot(Op1);
Value *X, *Y;
if (match(Op0, m_OneUse(m_Add(m_Value(X), m_AllOnes()))))
return BinaryOperator::CreateAdd(Builder.CreateNot(Op1), X);
Value *Z;
if (match(Op0, m_OneUse(m_c_Add(m_OneUse(m_Sub(m_Value(X), m_Value(Y))),
m_Value(Z))))) {
Value *XZ = Builder.CreateAdd(X, Z);
Value *YW = Builder.CreateAdd(Y, Op1);
return BinaryOperator::CreateSub(XZ, YW);
}
if (match(Op0, m_OneUse(m_Sub(m_Value(X), m_Value(Y))))) {
Value *Add = Builder.CreateAdd(Y, Op1);
return BinaryOperator::CreateSub(X, Add);
}
if (isFreeToInvert(Op0, Op0->hasOneUse()) &&
isFreeToInvert(Op1, Op1->hasOneUse()) &&
!match(Op0, m_Sub(m_ImmConstant(), m_Value()))) {
Value *NotOp0 = Builder.CreateNot(Op0);
Value *NotOp1 = Builder.CreateNot(Op1);
return BinaryOperator::CreateSub(NotOp1, NotOp0);
}
auto m_AddRdx = [](Value *&Vec) {
return m_OneUse(m_Intrinsic<Intrinsic::vector_reduce_add>(m_Value(Vec)));
};
Value *V0, *V1;
if (match(Op0, m_AddRdx(V0)) && match(Op1, m_AddRdx(V1)) &&
V0->getType() == V1->getType()) {
Value *Sub = Builder.CreateSub(V0, V1);
Value *Rdx = Builder.CreateIntrinsic(Intrinsic::vector_reduce_add,
{Sub->getType()}, {Sub});
return replaceInstUsesWith(I, Rdx);
}
if (Constant *C = dyn_cast<Constant>(Op0)) {
Value *X;
if (match(Op1, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
return SelectInst::Create(X, InstCombiner::SubOne(C), C);
if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
return SelectInst::Create(X, InstCombiner::AddOne(C), C);
if (match(Op1, m_Not(m_Value(X))))
return BinaryOperator::CreateAdd(X, InstCombiner::AddOne(C));
if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
if (Instruction *R = FoldOpIntoSelect(I, SI))
return R;
if (PHINode *PN = dyn_cast<PHINode>(Op1))
if (Instruction *R = foldOpIntoPhi(I, PN))
return R;
Constant *C2;
if (match(Op1, m_Sub(m_ImmConstant(C2), m_Value(X))))
return BinaryOperator::CreateAdd(X, ConstantExpr::getSub(C, C2));
}
const APInt *Op0C;
if (match(Op0, m_APInt(Op0C)) && Op0C->isMask()) {
KnownBits RHSKnown = computeKnownBits(Op1, 0, &I);
if ((*Op0C | RHSKnown.Zero).isAllOnes())
return BinaryOperator::CreateXor(Op1, Op0);
}
{
Value *Y;
if (match(Op1, m_c_Add(m_Specific(Op0), m_Value(Y))))
return BinaryOperator::CreateNeg(Y);
if (match(Op0, m_Sub(m_Specific(Op1), m_Value(Y))))
return BinaryOperator::CreateNeg(Y);
}
{
Value *A, *B;
if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
match(Op0, m_c_Or(m_Specific(A), m_Specific(B))))
return BinaryOperator::CreateXor(A, B);
}
{
Value *A, *B;
if (match(Op0, m_Add(m_Value(A), m_Value(B))) &&
match(Op1, m_c_Or(m_Specific(A), m_Specific(B))))
return BinaryOperator::CreateAnd(A, B);
}
{
Value *A, *B;
if (match(Op0, m_Add(m_Value(A), m_Value(B))) &&
match(Op1, m_c_And(m_Specific(A), m_Specific(B))))
return BinaryOperator::CreateOr(A, B);
}
{
Value *A, *B;
if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
match(Op1, m_c_Or(m_Specific(A), m_Specific(B))) &&
(Op0->hasOneUse() || Op1->hasOneUse()))
return BinaryOperator::CreateNeg(Builder.CreateXor(A, B));
}
{
Value *A, *B;
if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
match(Op0, m_c_Or(m_Specific(A), m_Specific(B))))
return BinaryOperator::CreateAnd(A, B);
}
{
Value *A, *B;
if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
match(Op1, m_c_Or(m_Specific(A), m_Specific(B))) &&
(Op0->hasOneUse() || Op1->hasOneUse()))
return BinaryOperator::CreateNeg(Builder.CreateAnd(A, B));
}
{
Value *Y;
if (match(Op0, m_OneUse(m_c_Or(m_Value(Y), m_Specific(Op1)))))
return BinaryOperator::CreateAnd(
Y, Builder.CreateNot(Op1, Op1->getName() + ".not"));
}
{
Value *X;
if (match(Op0, m_OneUse(m_c_And(m_Specific(Op1),
m_OneUse(m_Neg(m_Value(X))))))) {
return BinaryOperator::CreateNeg(Builder.CreateAnd(
Op1, Builder.CreateAdd(X, Constant::getAllOnesValue(I.getType()))));
}
}
{
Constant *C;
if (match(Op0, m_OneUse(m_And(m_Specific(Op1), m_Constant(C))))) {
return BinaryOperator::CreateNeg(
Builder.CreateAnd(Op1, Builder.CreateNot(C)));
}
}
if (Instruction *R = foldSubOfMinMax(I, Builder))
return R;
{
auto SinkSubIntoSelect =
[Ty = I.getType()](Value *Select, Value *OtherHandOfSub,
auto SubBuilder) -> Instruction * {
Value *Cond, *TrueVal, *FalseVal;
if (!match(Select, m_OneUse(m_Select(m_Value(Cond), m_Value(TrueVal),
m_Value(FalseVal)))))
return nullptr;
if (OtherHandOfSub != TrueVal && OtherHandOfSub != FalseVal)
return nullptr;
bool OtherHandOfSubIsTrueVal = OtherHandOfSub == TrueVal;
Value *NewSub = SubBuilder(OtherHandOfSubIsTrueVal ? FalseVal : TrueVal);
Constant *Zero = Constant::getNullValue(Ty);
SelectInst *NewSel =
SelectInst::Create(Cond, OtherHandOfSubIsTrueVal ? Zero : NewSub,
OtherHandOfSubIsTrueVal ? NewSub : Zero);
NewSel->copyMetadata(cast<Instruction>(*Select));
return NewSel;
};
if (Instruction *NewSel = SinkSubIntoSelect(
Op0, Op1,
[Builder = &Builder, Op1](Value *OtherHandOfSelect) {
return Builder->CreateSub(OtherHandOfSelect,
Op1);
}))
return NewSel;
if (Instruction *NewSel = SinkSubIntoSelect(
Op1, Op0,
[Builder = &Builder, Op0](Value *OtherHandOfSelect) {
return Builder->CreateSub(Op0,
OtherHandOfSelect);
}))
return NewSel;
}
if (match(Op1, m_c_And(m_Specific(Op0), m_Value(Y))) &&
(Op1->hasOneUse() || isa<Constant>(Y)))
return BinaryOperator::CreateAnd(
Op0, Builder.CreateNot(Y, Y->getName() + ".not"));
if (match(Op0, m_Not(m_Value(X))) &&
match(Op1, m_c_MaxOrMin(m_Specific(Op0), m_Value(Y))) &&
!Op0->hasNUsesOrMore(3) && isFreeToInvert(Y, Y->hasOneUse())) {
Value *Not = Builder.CreateNot(Op1);
return BinaryOperator::CreateSub(Not, X);
}
if (match(Op1, m_Not(m_Value(X))) &&
match(Op0, m_c_MaxOrMin(m_Specific(Op1), m_Value(Y))) &&
!Op1->hasNUsesOrMore(3) && isFreeToInvert(Y, Y->hasOneUse())) {
Value *Not = Builder.CreateNot(Op0);
return BinaryOperator::CreateSub(X, Not);
}
Value *LHSOp, *RHSOp;
if (match(Op0, m_PtrToInt(m_Value(LHSOp))) &&
match(Op1, m_PtrToInt(m_Value(RHSOp))))
if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType(),
I.hasNoUnsignedWrap()))
return replaceInstUsesWith(I, Res);
if (match(Op0, m_Trunc(m_PtrToInt(m_Value(LHSOp)))) &&
match(Op1, m_Trunc(m_PtrToInt(m_Value(RHSOp)))))
if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType(),
false))
return replaceInstUsesWith(I, Res);
Value *A;
const APInt *ShAmt;
Type *Ty = I.getType();
if (match(Op1, m_AShr(m_Value(A), m_APInt(ShAmt))) &&
Op1->hasNUses(2) && *ShAmt == Ty->getScalarSizeInBits() - 1 &&
match(Op0, m_OneUse(m_c_Xor(m_Specific(A), m_Specific(Op1))))) {
Value *IsNeg = Builder.CreateIsNeg(A);
Value *NegA = Builder.CreateNeg(A, "", I.hasNoUnsignedWrap(),
I.hasNoSignedWrap());
return SelectInst::Create(IsNeg, NegA, A);
}
const APInt *AddC, *AndC;
if (match(Op0, m_Add(m_Value(X), m_APInt(AddC))) &&
match(Op1, m_And(m_Specific(X), m_APInt(AndC)))) {
unsigned BitWidth = Ty->getScalarSizeInBits();
unsigned Cttz = AddC->countTrailingZeros();
APInt HighMask(APInt::getHighBitsSet(BitWidth, BitWidth - Cttz));
if ((HighMask & *AndC).isZero())
return BinaryOperator::CreateAnd(Op0, ConstantInt::get(Ty, ~(*AndC)));
}
if (Instruction *V =
canonicalizeCondSignextOfHighBitExtractToSignextHighBitExtract(I))
return V;
if (match(Op1, m_OneUse(m_Intrinsic<Intrinsic::usub_sat>(m_Specific(Op0),
m_Value(Y)))))
return replaceInstUsesWith(
I, Builder.CreateIntrinsic(Intrinsic::umin, {I.getType()}, {Op0, Y}));
if (match(Op0, m_OneUse(m_c_UMax(m_Value(X), m_Specific(Op1)))))
return replaceInstUsesWith(
I, Builder.CreateIntrinsic(Intrinsic::usub_sat, {Ty}, {X, Op1}));
if (match(Op1, m_OneUse(m_c_UMin(m_Value(X), m_Specific(Op0)))))
return replaceInstUsesWith(
I, Builder.CreateIntrinsic(Intrinsic::usub_sat, {Ty}, {Op0, X}));
if (match(Op1, m_OneUse(m_c_UMax(m_Value(X), m_Specific(Op0))))) {
Value *USub = Builder.CreateIntrinsic(Intrinsic::usub_sat, {Ty}, {X, Op0});
return BinaryOperator::CreateNeg(USub);
}
if (match(Op0, m_OneUse(m_c_UMin(m_Value(X), m_Specific(Op1))))) {
Value *USub = Builder.CreateIntrinsic(Intrinsic::usub_sat, {Ty}, {Op1, X});
return BinaryOperator::CreateNeg(USub);
}
if (match(Op0, m_SpecificInt(Ty->getScalarSizeInBits())) &&
match(Op1, m_OneUse(m_Intrinsic<Intrinsic::ctpop>(m_Value(X)))))
return replaceInstUsesWith(
I, Builder.CreateIntrinsic(Intrinsic::ctpop, {I.getType()},
{Builder.CreateNot(X)}));
return TryToNarrowDeduceFlags();
}
static Instruction *foldFNegIntoConstant(Instruction &I) {
Instruction *FNegOp;
if (!match(&I, m_FNeg(m_OneUse(m_Instruction(FNegOp)))))
return nullptr;
Value *X;
Constant *C;
if (match(FNegOp, m_FMul(m_Value(X), m_Constant(C))))
return BinaryOperator::CreateFMulFMF(X, ConstantExpr::getFNeg(C), &I);
if (match(FNegOp, m_FDiv(m_Value(X), m_Constant(C))))
return BinaryOperator::CreateFDivFMF(X, ConstantExpr::getFNeg(C), &I);
if (match(FNegOp, m_FDiv(m_Constant(C), m_Value(X)))) {
Instruction *FDiv =
BinaryOperator::CreateFDivFMF(ConstantExpr::getFNeg(C), X, &I);
FastMathFlags FMF = I.getFastMathFlags();
FastMathFlags OpFMF = FNegOp->getFastMathFlags();
FDiv->setHasNoSignedZeros(FMF.noSignedZeros() && OpFMF.noSignedZeros());
FDiv->setHasNoInfs(FMF.noInfs() && OpFMF.noInfs());
return FDiv;
}
if (I.hasNoSignedZeros() && match(FNegOp, m_FAdd(m_Value(X), m_Constant(C))))
return BinaryOperator::CreateFSubFMF(ConstantExpr::getFNeg(C), X, &I);
return nullptr;
}
static Instruction *hoistFNegAboveFMulFDiv(Instruction &I,
InstCombiner::BuilderTy &Builder) {
Value *FNeg;
if (!match(&I, m_FNeg(m_Value(FNeg))))
return nullptr;
Value *X, *Y;
if (match(FNeg, m_OneUse(m_FMul(m_Value(X), m_Value(Y)))))
return BinaryOperator::CreateFMulFMF(Builder.CreateFNegFMF(X, &I), Y, &I);
if (match(FNeg, m_OneUse(m_FDiv(m_Value(X), m_Value(Y)))))
return BinaryOperator::CreateFDivFMF(Builder.CreateFNegFMF(X, &I), Y, &I);
return nullptr;
}
Instruction *InstCombinerImpl::visitFNeg(UnaryOperator &I) {
Value *Op = I.getOperand(0);
if (Value *V = simplifyFNegInst(Op, I.getFastMathFlags(),
getSimplifyQuery().getWithInstruction(&I)))
return replaceInstUsesWith(I, V);
if (Instruction *X = foldFNegIntoConstant(I))
return X;
Value *X, *Y;
if (I.hasNoSignedZeros() &&
match(Op, m_OneUse(m_FSub(m_Value(X), m_Value(Y)))))
return BinaryOperator::CreateFSubFMF(Y, X, &I);
if (Instruction *R = hoistFNegAboveFMulFDiv(I, Builder))
return R;
Value *Cond;
if (match(Op, m_OneUse(m_Select(m_Value(Cond), m_Value(X), m_Value(Y))))) {
auto propagateSelectFMF = [&](SelectInst *S, bool CommonOperand) {
S->copyFastMathFlags(&I);
if (auto *OldSel = dyn_cast<SelectInst>(Op))
if (!OldSel->hasNoSignedZeros() && !CommonOperand &&
!isGuaranteedNotToBeUndefOrPoison(OldSel->getCondition()))
S->setHasNoSignedZeros(false);
};
Value *P;
if (match(X, m_FNeg(m_Value(P)))) {
Value *NegY = Builder.CreateFNegFMF(Y, &I, Y->getName() + ".neg");
SelectInst *NewSel = SelectInst::Create(Cond, P, NegY);
propagateSelectFMF(NewSel, P == Y);
return NewSel;
}
if (match(Y, m_FNeg(m_Value(P)))) {
Value *NegX = Builder.CreateFNegFMF(X, &I, X->getName() + ".neg");
SelectInst *NewSel = SelectInst::Create(Cond, NegX, P);
propagateSelectFMF(NewSel, P == X);
return NewSel;
}
}
return nullptr;
}
Instruction *InstCombinerImpl::visitFSub(BinaryOperator &I) {
if (Value *V = simplifyFSubInst(I.getOperand(0), I.getOperand(1),
I.getFastMathFlags(),
getSimplifyQuery().getWithInstruction(&I)))
return replaceInstUsesWith(I, V);
if (Instruction *X = foldVectorBinop(I))
return X;
if (Instruction *Phi = foldBinopWithPhiOperands(I))
return Phi;
Value *Op;
if (match(&I, m_FNeg(m_Value(Op))))
return UnaryOperator::CreateFNegFMF(Op, &I);
if (Instruction *X = foldFNegIntoConstant(I))
return X;
if (Instruction *R = hoistFNegAboveFMulFDiv(I, Builder))
return R;
Value *X, *Y;
Constant *C;
Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
if (I.hasNoSignedZeros() || CannotBeNegativeZero(Op0, SQ.TLI)) {
if (match(Op1, m_OneUse(m_FSub(m_Value(X), m_Value(Y))))) {
Value *NewSub = Builder.CreateFSubFMF(Y, X, &I);
return BinaryOperator::CreateFAddFMF(Op0, NewSub, &I);
}
}
if (I.hasNoSignedZeros() && !isa<ConstantExpr>(Op0) &&
match(Op0, m_OneUse(m_FNeg(m_Value(X))))) {
Value *FAdd = Builder.CreateFAddFMF(X, Op1, &I);
return UnaryOperator::CreateFNegFMF(FAdd, &I);
}
if (isa<Constant>(Op0))
if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
if (Instruction *NV = FoldOpIntoSelect(I, SI))
return NV;
if (match(Op1, m_ImmConstant(C)))
return BinaryOperator::CreateFAddFMF(Op0, ConstantExpr::getFNeg(C), &I);
if (match(Op1, m_FNeg(m_Value(Y))))
return BinaryOperator::CreateFAddFMF(Op0, Y, &I);
Type *Ty = I.getType();
if (match(Op1, m_OneUse(m_FPTrunc(m_FNeg(m_Value(Y))))))
return BinaryOperator::CreateFAddFMF(Op0, Builder.CreateFPTrunc(Y, Ty), &I);
if (match(Op1, m_OneUse(m_FPExt(m_FNeg(m_Value(Y))))))
return BinaryOperator::CreateFAddFMF(Op0, Builder.CreateFPExt(Y, Ty), &I);
if (match(Op1, m_OneUse(m_c_FMul(m_FNeg(m_Value(X)), m_Value(Y))))) {
Value *FMul = Builder.CreateFMulFMF(X, Y, &I);
return BinaryOperator::CreateFAddFMF(Op0, FMul, &I);
}
if (match(Op1, m_OneUse(m_FDiv(m_FNeg(m_Value(X)), m_Value(Y)))) ||
match(Op1, m_OneUse(m_FDiv(m_Value(X), m_FNeg(m_Value(Y)))))) {
Value *FDiv = Builder.CreateFDivFMF(X, Y, &I);
return BinaryOperator::CreateFAddFMF(Op0, FDiv, &I);
}
if (Value *V = SimplifySelectsFeedingBinaryOp(I, Op0, Op1))
return replaceInstUsesWith(I, V);
if (I.hasAllowReassoc() && I.hasNoSignedZeros()) {
if (match(Op0, m_FSub(m_Specific(Op1), m_Value(X))))
return UnaryOperator::CreateFNegFMF(X, &I);
if (match(Op1, m_c_FAdd(m_Specific(Op0), m_Value(X))))
return UnaryOperator::CreateFNegFMF(X, &I);
if (match(Op0, m_FMul(m_Specific(Op1), m_Constant(C)))) {
if (Constant *CSubOne = ConstantFoldBinaryOpOperands(
Instruction::FSub, C, ConstantFP::get(Ty, 1.0), DL))
return BinaryOperator::CreateFMulFMF(Op1, CSubOne, &I);
}
if (match(Op1, m_FMul(m_Specific(Op0), m_Constant(C)))) {
if (Constant *OneSubC = ConstantFoldBinaryOpOperands(
Instruction::FSub, ConstantFP::get(Ty, 1.0), C, DL))
return BinaryOperator::CreateFMulFMF(Op0, OneSubC, &I);
}
Value *Z;
if (match(Op0, m_OneUse(m_c_FAdd(m_OneUse(m_FSub(m_Value(X), m_Value(Y))),
m_Value(Z))))) {
Value *XZ = Builder.CreateFAddFMF(X, Z, &I);
Value *YW = Builder.CreateFAddFMF(Y, Op1, &I);
return BinaryOperator::CreateFSubFMF(XZ, YW, &I);
}
auto m_FaddRdx = [](Value *&Sum, Value *&Vec) {
return m_OneUse(m_Intrinsic<Intrinsic::vector_reduce_fadd>(m_Value(Sum),
m_Value(Vec)));
};
Value *A0, *A1, *V0, *V1;
if (match(Op0, m_FaddRdx(A0, V0)) && match(Op1, m_FaddRdx(A1, V1)) &&
V0->getType() == V1->getType()) {
Value *Sub = Builder.CreateFSubFMF(V0, V1, &I);
Value *Rdx = Builder.CreateIntrinsic(Intrinsic::vector_reduce_fadd,
{Sub->getType()}, {A0, Sub}, &I);
return BinaryOperator::CreateFSubFMF(Rdx, A1, &I);
}
if (Instruction *F = factorizeFAddFSub(I, Builder))
return F;
if (Value *V = FAddCombine(Builder).simplify(&I))
return replaceInstUsesWith(I, V);
if (match(Op0, m_OneUse(m_FSub(m_Value(X), m_Value(Y))))) {
Value *FAdd = Builder.CreateFAddFMF(Y, Op1, &I);
return BinaryOperator::CreateFSubFMF(X, FAdd, &I);
}
}
return nullptr;
}