InstCombineSelect.cpp [plain text]
#include "InstCombineInternal.h"
#include "llvm/Analysis/ConstantFolding.h"
#include "llvm/Analysis/InstructionSimplify.h"
#include "llvm/IR/PatternMatch.h"
using namespace llvm;
using namespace PatternMatch;
#define DEBUG_TYPE "instcombine"
static SelectPatternFlavor
MatchSelectPattern(Value *V, Value *&LHS, Value *&RHS) {
SelectInst *SI = dyn_cast<SelectInst>(V);
if (!SI) return SPF_UNKNOWN;
ICmpInst *ICI = dyn_cast<ICmpInst>(SI->getCondition());
if (!ICI) return SPF_UNKNOWN;
ICmpInst::Predicate Pred = ICI->getPredicate();
Value *CmpLHS = ICI->getOperand(0);
Value *CmpRHS = ICI->getOperand(1);
Value *TrueVal = SI->getTrueValue();
Value *FalseVal = SI->getFalseValue();
LHS = CmpLHS;
RHS = CmpRHS;
if (TrueVal == CmpLHS && FalseVal == CmpRHS) {
switch (Pred) {
default: return SPF_UNKNOWN; case ICmpInst::ICMP_UGT:
case ICmpInst::ICMP_UGE: return SPF_UMAX;
case ICmpInst::ICMP_SGT:
case ICmpInst::ICMP_SGE: return SPF_SMAX;
case ICmpInst::ICMP_ULT:
case ICmpInst::ICMP_ULE: return SPF_UMIN;
case ICmpInst::ICMP_SLT:
case ICmpInst::ICMP_SLE: return SPF_SMIN;
}
}
if (TrueVal == CmpRHS && FalseVal == CmpLHS) {
switch (Pred) {
default: return SPF_UNKNOWN; case ICmpInst::ICMP_UGT:
case ICmpInst::ICMP_UGE: return SPF_UMIN;
case ICmpInst::ICMP_SGT:
case ICmpInst::ICMP_SGE: return SPF_SMIN;
case ICmpInst::ICMP_ULT:
case ICmpInst::ICMP_ULE: return SPF_UMAX;
case ICmpInst::ICMP_SLT:
case ICmpInst::ICMP_SLE: return SPF_SMAX;
}
}
if (ConstantInt *C1 = dyn_cast<ConstantInt>(CmpRHS)) {
if ((CmpLHS == TrueVal && match(FalseVal, m_Neg(m_Specific(CmpLHS)))) ||
(CmpLHS == FalseVal && match(TrueVal, m_Neg(m_Specific(CmpLHS))))) {
if (Pred == ICmpInst::ICMP_SGT && (C1->isZero() || C1->isMinusOne())) {
return (CmpLHS == TrueVal) ? SPF_ABS : SPF_NABS;
}
if (Pred == ICmpInst::ICMP_SLT && (C1->isZero() || C1->isOne())) {
return (CmpLHS == FalseVal) ? SPF_ABS : SPF_NABS;
}
}
}
return SPF_UNKNOWN;
}
static unsigned GetSelectFoldableOperands(Instruction *I) {
switch (I->getOpcode()) {
case Instruction::Add:
case Instruction::Mul:
case Instruction::And:
case Instruction::Or:
case Instruction::Xor:
return 3; case Instruction::Sub: case Instruction::Shl: case Instruction::LShr:
case Instruction::AShr:
return 1;
default:
return 0; }
}
static Constant *GetSelectFoldableConstant(Instruction *I) {
switch (I->getOpcode()) {
default: llvm_unreachable("This cannot happen!");
case Instruction::Add:
case Instruction::Sub:
case Instruction::Or:
case Instruction::Xor:
case Instruction::Shl:
case Instruction::LShr:
case Instruction::AShr:
return Constant::getNullValue(I->getType());
case Instruction::And:
return Constant::getAllOnesValue(I->getType());
case Instruction::Mul:
return ConstantInt::get(I->getType(), 1);
}
}
Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
Instruction *FI) {
if (TI->getNumOperands() == 1) {
if (TI->isCast()) {
Type *FIOpndTy = FI->getOperand(0)->getType();
if (TI->getOperand(0)->getType() != FIOpndTy)
return nullptr;
Type *CondTy = SI.getCondition()->getType();
if (CondTy->isVectorTy() && (!FIOpndTy->isVectorTy() ||
CondTy->getVectorNumElements() != FIOpndTy->getVectorNumElements()))
return nullptr;
} else {
return nullptr; }
Value *NewSI = Builder->CreateSelect(SI.getCondition(), TI->getOperand(0),
FI->getOperand(0), SI.getName()+".v");
return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
TI->getType());
}
if (!isa<BinaryOperator>(TI))
return nullptr;
Value *MatchOp, *OtherOpT, *OtherOpF;
bool MatchIsOpZero;
if (TI->getOperand(0) == FI->getOperand(0)) {
MatchOp = TI->getOperand(0);
OtherOpT = TI->getOperand(1);
OtherOpF = FI->getOperand(1);
MatchIsOpZero = true;
} else if (TI->getOperand(1) == FI->getOperand(1)) {
MatchOp = TI->getOperand(1);
OtherOpT = TI->getOperand(0);
OtherOpF = FI->getOperand(0);
MatchIsOpZero = false;
} else if (!TI->isCommutative()) {
return nullptr;
} else if (TI->getOperand(0) == FI->getOperand(1)) {
MatchOp = TI->getOperand(0);
OtherOpT = TI->getOperand(1);
OtherOpF = FI->getOperand(0);
MatchIsOpZero = true;
} else if (TI->getOperand(1) == FI->getOperand(0)) {
MatchOp = TI->getOperand(1);
OtherOpT = TI->getOperand(0);
OtherOpF = FI->getOperand(1);
MatchIsOpZero = true;
} else {
return nullptr;
}
Value *NewSI = Builder->CreateSelect(SI.getCondition(), OtherOpT,
OtherOpF, SI.getName()+".v");
if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
if (MatchIsOpZero)
return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
else
return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
}
llvm_unreachable("Shouldn't get here");
}
static bool isSelect01(Constant *C1, Constant *C2) {
ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
if (!C1I)
return false;
ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
if (!C2I)
return false;
if (!C1I->isZero() && !C2I->isZero()) return false;
return C1I->isOne() || C1I->isAllOnesValue() ||
C2I->isOne() || C2I->isAllOnesValue();
}
Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
Value *FalseVal) {
if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
!isa<Constant>(FalseVal)) {
if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
unsigned OpToFold = 0;
if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
OpToFold = 1;
} else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
OpToFold = 2;
}
if (OpToFold) {
Constant *C = GetSelectFoldableConstant(TVI);
Value *OOp = TVI->getOperand(2-OpToFold);
if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
Value *NewSel = Builder->CreateSelect(SI.getCondition(), OOp, C);
NewSel->takeName(TVI);
BinaryOperator *TVI_BO = cast<BinaryOperator>(TVI);
BinaryOperator *BO = BinaryOperator::Create(TVI_BO->getOpcode(),
FalseVal, NewSel);
if (isa<PossiblyExactOperator>(BO))
BO->setIsExact(TVI_BO->isExact());
if (isa<OverflowingBinaryOperator>(BO)) {
BO->setHasNoUnsignedWrap(TVI_BO->hasNoUnsignedWrap());
BO->setHasNoSignedWrap(TVI_BO->hasNoSignedWrap());
}
return BO;
}
}
}
}
}
if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
!isa<Constant>(TrueVal)) {
if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
unsigned OpToFold = 0;
if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
OpToFold = 1;
} else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
OpToFold = 2;
}
if (OpToFold) {
Constant *C = GetSelectFoldableConstant(FVI);
Value *OOp = FVI->getOperand(2-OpToFold);
if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
Value *NewSel = Builder->CreateSelect(SI.getCondition(), C, OOp);
NewSel->takeName(FVI);
BinaryOperator *FVI_BO = cast<BinaryOperator>(FVI);
BinaryOperator *BO = BinaryOperator::Create(FVI_BO->getOpcode(),
TrueVal, NewSel);
if (isa<PossiblyExactOperator>(BO))
BO->setIsExact(FVI_BO->isExact());
if (isa<OverflowingBinaryOperator>(BO)) {
BO->setHasNoUnsignedWrap(FVI_BO->hasNoUnsignedWrap());
BO->setHasNoSignedWrap(FVI_BO->hasNoSignedWrap());
}
return BO;
}
}
}
}
}
return nullptr;
}
static Value *SimplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
const TargetLibraryInfo *TLI,
const DataLayout &DL, DominatorTree *DT,
AssumptionCache *AC) {
if (V == Op)
return RepOp;
Instruction *I = dyn_cast<Instruction>(V);
if (!I)
return nullptr;
if (BinaryOperator *B = dyn_cast<BinaryOperator>(I)) {
if (B->getOperand(0) == Op)
return SimplifyBinOp(B->getOpcode(), RepOp, B->getOperand(1), DL, TLI);
if (B->getOperand(1) == Op)
return SimplifyBinOp(B->getOpcode(), B->getOperand(0), RepOp, DL, TLI);
}
if (CmpInst *C = dyn_cast<CmpInst>(I)) {
if (C->getOperand(0) == Op)
return SimplifyCmpInst(C->getPredicate(), RepOp, C->getOperand(1), DL,
TLI, DT, AC);
if (C->getOperand(1) == Op)
return SimplifyCmpInst(C->getPredicate(), C->getOperand(0), RepOp, DL,
TLI, DT, AC);
}
if (Constant *CRepOp = dyn_cast<Constant>(RepOp)) {
SmallVector<Constant*, 8> ConstOps;
for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
if (I->getOperand(i) == Op)
ConstOps.push_back(CRepOp);
else if (Constant *COp = dyn_cast<Constant>(I->getOperand(i)))
ConstOps.push_back(COp);
else
break;
}
if (ConstOps.size() == I->getNumOperands()) {
if (CmpInst *C = dyn_cast<CmpInst>(I))
return ConstantFoldCompareInstOperands(C->getPredicate(), ConstOps[0],
ConstOps[1], DL, TLI);
if (LoadInst *LI = dyn_cast<LoadInst>(I))
if (!LI->isVolatile())
return ConstantFoldLoadFromConstPtr(ConstOps[0], DL);
return ConstantFoldInstOperands(I->getOpcode(), I->getType(), ConstOps,
DL, TLI);
}
}
return nullptr;
}
static Value *foldSelectICmpAndOr(const SelectInst &SI, Value *TrueVal,
Value *FalseVal,
InstCombiner::BuilderTy *Builder) {
const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition());
if (!IC || !IC->isEquality() || !SI.getType()->isIntegerTy())
return nullptr;
Value *CmpLHS = IC->getOperand(0);
Value *CmpRHS = IC->getOperand(1);
if (!match(CmpRHS, m_Zero()))
return nullptr;
Value *X;
const APInt *C1;
if (!match(CmpLHS, m_And(m_Value(X), m_Power2(C1))))
return nullptr;
const APInt *C2;
bool OrOnTrueVal = false;
bool OrOnFalseVal = match(FalseVal, m_Or(m_Specific(TrueVal), m_Power2(C2)));
if (!OrOnFalseVal)
OrOnTrueVal = match(TrueVal, m_Or(m_Specific(FalseVal), m_Power2(C2)));
if (!OrOnFalseVal && !OrOnTrueVal)
return nullptr;
Value *V = CmpLHS;
Value *Y = OrOnFalseVal ? TrueVal : FalseVal;
unsigned C1Log = C1->logBase2();
unsigned C2Log = C2->logBase2();
if (C2Log > C1Log) {
V = Builder->CreateZExtOrTrunc(V, Y->getType());
V = Builder->CreateShl(V, C2Log - C1Log);
} else if (C1Log > C2Log) {
V = Builder->CreateLShr(V, C1Log - C2Log);
V = Builder->CreateZExtOrTrunc(V, Y->getType());
} else
V = Builder->CreateZExtOrTrunc(V, Y->getType());
ICmpInst::Predicate Pred = IC->getPredicate();
if ((Pred == ICmpInst::ICMP_NE && OrOnFalseVal) ||
(Pred == ICmpInst::ICMP_EQ && OrOnTrueVal))
V = Builder->CreateXor(V, *C2);
return Builder->CreateOr(V, Y);
}
static Value *foldSelectCttzCtlz(ICmpInst *ICI, Value *TrueVal, Value *FalseVal,
InstCombiner::BuilderTy *Builder) {
ICmpInst::Predicate Pred = ICI->getPredicate();
Value *CmpLHS = ICI->getOperand(0);
Value *CmpRHS = ICI->getOperand(1);
if (!ICI->isEquality() || !match(CmpRHS, m_Zero()))
return nullptr;
Value *Count = FalseVal;
Value *ValueOnZero = TrueVal;
if (Pred == ICmpInst::ICMP_NE)
std::swap(Count, ValueOnZero);
Value *V = nullptr;
if (match(Count, m_ZExt(m_Value(V))) ||
match(Count, m_Trunc(m_Value(V))))
Count = V;
unsigned SizeOfInBits = Count->getType()->getScalarSizeInBits();
if (!match(ValueOnZero, m_SpecificInt(SizeOfInBits)))
return nullptr;
if (match(Count, m_Intrinsic<Intrinsic::cttz>(m_Specific(CmpLHS))) ||
match(Count, m_Intrinsic<Intrinsic::ctlz>(m_Specific(CmpLHS)))) {
IntrinsicInst *II = cast<IntrinsicInst>(Count);
IRBuilder<> Builder(II);
IntrinsicInst *NewI = cast<IntrinsicInst>(II->clone());
Type *Ty = NewI->getArgOperand(1)->getType();
NewI->setArgOperand(1, Constant::getNullValue(Ty));
Builder.Insert(NewI);
return Builder.CreateZExtOrTrunc(NewI, ValueOnZero->getType());
}
return nullptr;
}
Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
ICmpInst *ICI) {
bool Changed = false;
ICmpInst::Predicate Pred = ICI->getPredicate();
Value *CmpLHS = ICI->getOperand(0);
Value *CmpRHS = ICI->getOperand(1);
Value *TrueVal = SI.getTrueValue();
Value *FalseVal = SI.getFalseValue();
if (ICI->hasOneUse())
if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
if ((Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT)
&& CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
return ReplaceInstUsesWith(SI, FalseVal);
else if ((Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_UGT)
&& CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
return ReplaceInstUsesWith(SI, FalseVal);
switch (Pred) {
default: break;
case ICmpInst::ICMP_ULT:
case ICmpInst::ICMP_SLT:
case ICmpInst::ICMP_UGT:
case ICmpInst::ICMP_SGT: {
IntegerType *SelectTy = dyn_cast<IntegerType>(SI.getType());
if (!SelectTy)
break;
Constant *AdjustedRHS;
if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SGT)
AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() + 1);
else AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() - 1);
if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
(CmpLHS == FalseVal && AdjustedRHS == TrueVal))
;
else if (CmpRHS->getType()->getScalarSizeInBits()
< SelectTy->getBitWidth()) {
Constant *sextRHS = ConstantExpr::getSExt(AdjustedRHS, SelectTy);
if (match(TrueVal, m_SExt(m_Specific(CmpLHS))) &&
sextRHS == FalseVal) {
CmpLHS = TrueVal;
AdjustedRHS = sextRHS;
} else if (match(FalseVal, m_SExt(m_Specific(CmpLHS))) &&
sextRHS == TrueVal) {
CmpLHS = FalseVal;
AdjustedRHS = sextRHS;
} else if (ICI->isUnsigned()) {
Constant *zextRHS = ConstantExpr::getZExt(AdjustedRHS, SelectTy);
if (match(TrueVal, m_ZExt(m_Specific(CmpLHS))) &&
zextRHS == FalseVal) {
CmpLHS = TrueVal;
AdjustedRHS = zextRHS;
} else if (match(FalseVal, m_ZExt(m_Specific(CmpLHS))) &&
zextRHS == TrueVal) {
CmpLHS = FalseVal;
AdjustedRHS = zextRHS;
} else
break;
} else
break;
} else
break;
Pred = ICmpInst::getSwappedPredicate(Pred);
CmpRHS = AdjustedRHS;
std::swap(FalseVal, TrueVal);
ICI->setPredicate(Pred);
ICI->setOperand(0, CmpLHS);
ICI->setOperand(1, CmpRHS);
SI.setOperand(1, TrueVal);
SI.setOperand(2, FalseVal);
ICI->moveBefore(&SI);
Changed = true;
break;
}
}
}
if (IntegerType *Ty = dyn_cast<IntegerType>(CmpLHS->getType())) {
if (TrueVal->getType() == Ty) {
if (ConstantInt *Cmp = dyn_cast<ConstantInt>(CmpRHS)) {
ConstantInt *C1 = nullptr, *C2 = nullptr;
if (Pred == ICmpInst::ICMP_SGT && Cmp->isAllOnesValue()) {
C1 = dyn_cast<ConstantInt>(TrueVal);
C2 = dyn_cast<ConstantInt>(FalseVal);
} else if (Pred == ICmpInst::ICMP_SLT && Cmp->isNullValue()) {
C1 = dyn_cast<ConstantInt>(FalseVal);
C2 = dyn_cast<ConstantInt>(TrueVal);
}
if (C1 && C2) {
Value *AShr = Builder->CreateAShr(CmpLHS, Ty->getBitWidth()-1);
if (C2->isAllOnesValue())
return ReplaceInstUsesWith(SI, Builder->CreateOr(AShr, C1));
Value *And = Builder->CreateAnd(AShr, C2->getValue()-C1->getValue());
return ReplaceInstUsesWith(SI, Builder->CreateAdd(And, C1));
}
}
}
}
if (Pred == ICmpInst::ICMP_EQ) {
if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, TLI, DL, DT, AC) ==
TrueVal ||
SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, TLI, DL, DT, AC) ==
TrueVal)
return ReplaceInstUsesWith(SI, FalseVal);
if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, TLI, DL, DT, AC) ==
FalseVal ||
SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, TLI, DL, DT, AC) ==
FalseVal)
return ReplaceInstUsesWith(SI, FalseVal);
} else if (Pred == ICmpInst::ICMP_NE) {
if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, TLI, DL, DT, AC) ==
FalseVal ||
SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, TLI, DL, DT, AC) ==
FalseVal)
return ReplaceInstUsesWith(SI, TrueVal);
if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, TLI, DL, DT, AC) ==
TrueVal ||
SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, TLI, DL, DT, AC) ==
TrueVal)
return ReplaceInstUsesWith(SI, TrueVal);
}
if (CmpRHS != CmpLHS && isa<Constant>(CmpRHS)) {
if (CmpLHS == TrueVal && Pred == ICmpInst::ICMP_EQ) {
SI.setOperand(1, CmpRHS);
Changed = true;
} else if (CmpLHS == FalseVal && Pred == ICmpInst::ICMP_NE) {
SI.setOperand(2, CmpRHS);
Changed = true;
}
}
if (unsigned BitWidth = TrueVal->getType()->getScalarSizeInBits()) {
APInt MinSignedValue = APInt::getSignBit(BitWidth);
Value *X;
const APInt *Y, *C;
bool TrueWhenUnset;
bool IsBitTest = false;
if (ICmpInst::isEquality(Pred) &&
match(CmpLHS, m_And(m_Value(X), m_Power2(Y))) &&
match(CmpRHS, m_Zero())) {
IsBitTest = true;
TrueWhenUnset = Pred == ICmpInst::ICMP_EQ;
} else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) {
X = CmpLHS;
Y = &MinSignedValue;
IsBitTest = true;
TrueWhenUnset = false;
} else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) {
X = CmpLHS;
Y = &MinSignedValue;
IsBitTest = true;
TrueWhenUnset = true;
}
if (IsBitTest) {
Value *V = nullptr;
if (TrueWhenUnset && TrueVal == X &&
match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
V = Builder->CreateAnd(X, ~(*Y));
else if (!TrueWhenUnset && FalseVal == X &&
match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
V = Builder->CreateAnd(X, ~(*Y));
else if (TrueWhenUnset && FalseVal == X &&
match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
V = Builder->CreateOr(X, *Y);
else if (!TrueWhenUnset && TrueVal == X &&
match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
V = Builder->CreateOr(X, *Y);
if (V)
return ReplaceInstUsesWith(SI, V);
}
}
if (Value *V = foldSelectICmpAndOr(SI, TrueVal, FalseVal, Builder))
return ReplaceInstUsesWith(SI, V);
if (Value *V = foldSelectCttzCtlz(ICI, TrueVal, FalseVal, Builder))
return ReplaceInstUsesWith(SI, V);
return Changed ? &SI : nullptr;
}
static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
const SelectInst &SI) {
const Instruction *I = dyn_cast<Instruction>(V);
if (!I) return true;
const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
if (const PHINode *VP = dyn_cast<PHINode>(I))
if (VP->getParent() == CondPHI->getParent())
return true;
if (SI.getParent() == CondPHI->getParent() &&
I->getParent() != CondPHI->getParent())
return true;
return false;
}
Instruction *InstCombiner::FoldSPFofSPF(Instruction *Inner,
SelectPatternFlavor SPF1,
Value *A, Value *B,
Instruction &Outer,
SelectPatternFlavor SPF2, Value *C) {
if (C == A || C == B) {
if (SPF1 == SPF2)
return ReplaceInstUsesWith(Outer, Inner);
if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
(SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
(SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
(SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
return ReplaceInstUsesWith(Outer, C);
}
if (SPF1 == SPF2) {
if (ConstantInt *CB = dyn_cast<ConstantInt>(B)) {
if (ConstantInt *CC = dyn_cast<ConstantInt>(C)) {
APInt ACB = CB->getValue();
APInt ACC = CC->getValue();
if ((SPF1 == SPF_UMIN && ACB.ule(ACC)) ||
(SPF1 == SPF_SMIN && ACB.sle(ACC)) ||
(SPF1 == SPF_UMAX && ACB.uge(ACC)) ||
(SPF1 == SPF_SMAX && ACB.sge(ACC)))
return ReplaceInstUsesWith(Outer, Inner);
if ((SPF1 == SPF_UMIN && ACB.ugt(ACC)) ||
(SPF1 == SPF_SMIN && ACB.sgt(ACC)) ||
(SPF1 == SPF_UMAX && ACB.ult(ACC)) ||
(SPF1 == SPF_SMAX && ACB.slt(ACC))) {
Outer.replaceUsesOfWith(Inner, A);
return &Outer;
}
}
}
}
if (SPF1 == SPF2 && (SPF1 == SPF_ABS || SPF1 == SPF_NABS)) {
return ReplaceInstUsesWith(Outer, Inner);
}
if ((SPF1 == SPF_ABS && SPF2 == SPF_NABS) ||
(SPF1 == SPF_NABS && SPF2 == SPF_ABS)) {
SelectInst *SI = cast<SelectInst>(Inner);
Value *NewSI = Builder->CreateSelect(
SI->getCondition(), SI->getFalseValue(), SI->getTrueValue());
return ReplaceInstUsesWith(Outer, NewSI);
}
return nullptr;
}
static Value *foldSelectICmpAnd(const SelectInst &SI, ConstantInt *TrueVal,
ConstantInt *FalseVal,
InstCombiner::BuilderTy *Builder) {
const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition());
if (!IC || !IC->isEquality() || !SI.getType()->isIntegerTy())
return nullptr;
if (!match(IC->getOperand(1), m_Zero()))
return nullptr;
ConstantInt *AndRHS;
Value *LHS = IC->getOperand(0);
if (!match(LHS, m_And(m_Value(), m_ConstantInt(AndRHS))))
return nullptr;
ConstantInt *Offset = nullptr;
if (!TrueVal->isZero() && !FalseVal->isZero()) {
if ((TrueVal->getValue() - FalseVal->getValue()).isPowerOf2())
Offset = FalseVal;
else if ((FalseVal->getValue() - TrueVal->getValue()).isPowerOf2())
Offset = TrueVal;
else
return nullptr;
TrueVal = ConstantInt::get(Builder->getContext(),
TrueVal->getValue() - Offset->getValue());
FalseVal = ConstantInt::get(Builder->getContext(),
FalseVal->getValue() - Offset->getValue());
}
if (!AndRHS->getValue().isPowerOf2() ||
(!TrueVal->getValue().isPowerOf2() &&
!FalseVal->getValue().isPowerOf2()))
return nullptr;
ConstantInt *ValC = !TrueVal->isZero() ? TrueVal : FalseVal;
unsigned ValZeros = ValC->getValue().logBase2();
unsigned AndZeros = AndRHS->getValue().logBase2();
if (AndZeros >= ValC->getBitWidth())
return nullptr;
Value *V = Builder->CreateZExtOrTrunc(LHS, SI.getType());
if (ValZeros > AndZeros)
V = Builder->CreateShl(V, ValZeros - AndZeros);
else if (ValZeros < AndZeros)
V = Builder->CreateLShr(V, AndZeros - ValZeros);
bool ShouldNotVal = !TrueVal->isZero();
ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
if (ShouldNotVal)
V = Builder->CreateXor(V, ValC);
if (Offset)
V = Builder->CreateAdd(V, Offset);
return V;
}
Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Value *CondVal = SI.getCondition();
Value *TrueVal = SI.getTrueValue();
Value *FalseVal = SI.getFalseValue();
if (Value *V =
SimplifySelectInst(CondVal, TrueVal, FalseVal, DL, TLI, DT, AC))
return ReplaceInstUsesWith(SI, V);
if (SI.getType()->isIntegerTy(1)) {
if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
if (C->getZExtValue()) {
return BinaryOperator::CreateOr(CondVal, FalseVal);
}
Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
return BinaryOperator::CreateAnd(NotCond, FalseVal);
}
if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
if (C->getZExtValue() == false) {
return BinaryOperator::CreateAnd(CondVal, TrueVal);
}
Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
return BinaryOperator::CreateOr(NotCond, TrueVal);
}
if (CondVal == TrueVal)
return BinaryOperator::CreateOr(CondVal, FalseVal);
if (CondVal == FalseVal)
return BinaryOperator::CreateAnd(CondVal, TrueVal);
if (match(TrueVal, m_Not(m_Specific(CondVal))))
return BinaryOperator::CreateAnd(TrueVal, FalseVal);
if (match(FalseVal, m_Not(m_Specific(CondVal))))
return BinaryOperator::CreateOr(TrueVal, FalseVal);
}
if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
if (FalseValC->isZero() && TrueValC->getValue() == 1)
return new ZExtInst(CondVal, SI.getType());
if (FalseValC->isZero() && TrueValC->isAllOnesValue())
return new SExtInst(CondVal, SI.getType());
if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
return new ZExtInst(NotCond, SI.getType());
}
if (TrueValC->isZero() && FalseValC->isAllOnesValue()) {
Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
return new SExtInst(NotCond, SI.getType());
}
if (Value *V = foldSelectICmpAnd(SI, TrueValC, FalseValC, Builder))
return ReplaceInstUsesWith(SI, V);
}
if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
ConstantFP *CFPt, *CFPf;
if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
!CFPt->getValueAPF().isZero()) ||
((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
!CFPf->getValueAPF().isZero()))
return ReplaceInstUsesWith(SI, FalseVal);
}
if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
ConstantFP *CFPt, *CFPf;
if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
!CFPt->getValueAPF().isZero()) ||
((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
!CFPf->getValueAPF().isZero()))
return ReplaceInstUsesWith(SI, TrueVal);
}
if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
FCmpInst::Predicate InvPred = FCI->getInversePredicate();
Value *NewCond = Builder->CreateFCmp(InvPred, TrueVal, FalseVal,
FCI->getName() + ".inv");
return SelectInst::Create(NewCond, FalseVal, TrueVal,
SI.getName() + ".p");
}
} else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
ConstantFP *CFPt, *CFPf;
if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
!CFPt->getValueAPF().isZero()) ||
((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
!CFPf->getValueAPF().isZero()))
return ReplaceInstUsesWith(SI, FalseVal);
}
if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
ConstantFP *CFPt, *CFPf;
if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
!CFPt->getValueAPF().isZero()) ||
((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
!CFPf->getValueAPF().isZero()))
return ReplaceInstUsesWith(SI, TrueVal);
}
if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
FCmpInst::Predicate InvPred = FCI->getInversePredicate();
Value *NewCond = Builder->CreateFCmp(InvPred, FalseVal, TrueVal,
FCI->getName() + ".inv");
return SelectInst::Create(NewCond, FalseVal, TrueVal,
SI.getName() + ".p");
}
}
}
if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
return Result;
if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
if (TI->hasOneUse() && FI->hasOneUse()) {
Instruction *AddOp = nullptr, *SubOp = nullptr;
if (TI->getOpcode() == FI->getOpcode())
if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
return IV;
if ((TI->getOpcode() == Instruction::Sub &&
FI->getOpcode() == Instruction::Add) ||
(TI->getOpcode() == Instruction::FSub &&
FI->getOpcode() == Instruction::FAdd)) {
AddOp = FI; SubOp = TI;
} else if ((FI->getOpcode() == Instruction::Sub &&
TI->getOpcode() == Instruction::Add) ||
(FI->getOpcode() == Instruction::FSub &&
TI->getOpcode() == Instruction::FAdd)) {
AddOp = TI; SubOp = FI;
}
if (AddOp) {
Value *OtherAddOp = nullptr;
if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
OtherAddOp = AddOp->getOperand(1);
} else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
OtherAddOp = AddOp->getOperand(0);
}
if (OtherAddOp) {
Value *NegVal; if (SI.getType()->isFPOrFPVectorTy()) {
NegVal = Builder->CreateFNeg(SubOp->getOperand(1));
if (Instruction *NegInst = dyn_cast<Instruction>(NegVal)) {
FastMathFlags Flags = AddOp->getFastMathFlags();
Flags &= SubOp->getFastMathFlags();
NegInst->setFastMathFlags(Flags);
}
} else {
NegVal = Builder->CreateNeg(SubOp->getOperand(1));
}
Value *NewTrueOp = OtherAddOp;
Value *NewFalseOp = NegVal;
if (AddOp != TI)
std::swap(NewTrueOp, NewFalseOp);
Value *NewSel =
Builder->CreateSelect(CondVal, NewTrueOp,
NewFalseOp, SI.getName() + ".p");
if (SI.getType()->isFPOrFPVectorTy()) {
Instruction *RI =
BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel);
FastMathFlags Flags = AddOp->getFastMathFlags();
Flags &= SubOp->getFastMathFlags();
RI->setFastMathFlags(Flags);
return RI;
} else
return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
}
}
}
if (SI.getType()->isIntegerTy()) {
if (Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal))
return FoldI;
Value *LHS, *RHS, *LHS2, *RHS2;
if (SelectPatternFlavor SPF = MatchSelectPattern(&SI, LHS, RHS)) {
if (SelectPatternFlavor SPF2 = MatchSelectPattern(LHS, LHS2, RHS2))
if (Instruction *R = FoldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2,
SI, SPF, RHS))
return R;
if (SelectPatternFlavor SPF2 = MatchSelectPattern(RHS, LHS2, RHS2))
if (Instruction *R = FoldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2,
SI, SPF, LHS))
return R;
}
}
if (isa<PHINode>(SI.getCondition()))
if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
if (Instruction *NV = FoldOpIntoPhi(SI))
return NV;
if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) {
if (TrueSI->getCondition()->getType() == CondVal->getType()) {
if (TrueSI->getCondition() == CondVal) {
if (SI.getTrueValue() == TrueSI->getTrueValue())
return nullptr;
SI.setOperand(1, TrueSI->getTrueValue());
return &SI;
}
if (TrueSI->getFalseValue() == FalseVal && TrueSI->hasOneUse()) {
Value *And = Builder->CreateAnd(CondVal, TrueSI->getCondition());
SI.setOperand(0, And);
SI.setOperand(1, TrueSI->getTrueValue());
return &SI;
}
}
}
if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) {
if (FalseSI->getCondition()->getType() == CondVal->getType()) {
if (FalseSI->getCondition() == CondVal) {
if (SI.getFalseValue() == FalseSI->getFalseValue())
return nullptr;
SI.setOperand(2, FalseSI->getFalseValue());
return &SI;
}
if (FalseSI->getTrueValue() == TrueVal && FalseSI->hasOneUse()) {
Value *Or = Builder->CreateOr(CondVal, FalseSI->getCondition());
SI.setOperand(0, Or);
SI.setOperand(2, FalseSI->getFalseValue());
return &SI;
}
}
}
if (BinaryOperator::isNot(CondVal)) {
SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
SI.setOperand(1, FalseVal);
SI.setOperand(2, TrueVal);
return &SI;
}
if (VectorType* VecTy = dyn_cast<VectorType>(SI.getType())) {
unsigned VWidth = VecTy->getNumElements();
APInt UndefElts(VWidth, 0);
APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
if (Value *V = SimplifyDemandedVectorElts(&SI, AllOnesEltMask, UndefElts)) {
if (V != &SI)
return ReplaceInstUsesWith(SI, V);
return &SI;
}
if (isa<ConstantAggregateZero>(CondVal)) {
return ReplaceInstUsesWith(SI, FalseVal);
}
}
return nullptr;
}