#include "InstCombineInternal.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Analysis/InstructionSimplify.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/IR/PatternMatch.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Transforms/InstCombine/InstCombiner.h"
#include "llvm/Transforms/Utils/Local.h"
using namespace llvm;
using namespace llvm::PatternMatch;
#define DEBUG_TYPE "instcombine"
static cl::opt<unsigned>
MaxNumPhis("instcombine-max-num-phis", cl::init(512),
cl::desc("Maximum number phis to handle in intptr/ptrint folding"));
STATISTIC(NumPHIsOfInsertValues,
"Number of phi-of-insertvalue turned into insertvalue-of-phis");
STATISTIC(NumPHIsOfExtractValues,
"Number of phi-of-extractvalue turned into extractvalue-of-phi");
STATISTIC(NumPHICSEs, "Number of PHI's that got CSE'd");
void InstCombinerImpl::PHIArgMergedDebugLoc(Instruction *Inst, PHINode &PN) {
auto *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Inst->setDebugLoc(FirstInst->getDebugLoc());
assert(!isa<CallInst>(Inst));
for (Value *V : drop_begin(PN.incoming_values())) {
auto *I = cast<Instruction>(V);
Inst->applyMergedLocation(Inst->getDebugLoc(), I->getDebugLoc());
}
}
Instruction *InstCombinerImpl::foldIntegerTypedPHI(PHINode &PN) {
if (!PN.getType()->isIntegerTy())
return nullptr;
if (!PN.hasOneUse())
return nullptr;
auto *IntToPtr = dyn_cast<IntToPtrInst>(PN.user_back());
if (!IntToPtr)
return nullptr;
auto HasPointerUse = [](Instruction *IIP) {
for (User *U : IIP->users()) {
Value *Ptr = nullptr;
if (LoadInst *LoadI = dyn_cast<LoadInst>(U)) {
Ptr = LoadI->getPointerOperand();
} else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Ptr = SI->getPointerOperand();
} else if (GetElementPtrInst *GI = dyn_cast<GetElementPtrInst>(U)) {
Ptr = GI->getPointerOperand();
}
if (Ptr && Ptr == IIP)
return true;
}
return false;
};
if (!HasPointerUse(IntToPtr))
return nullptr;
if (DL.getPointerSizeInBits(IntToPtr->getAddressSpace()) !=
DL.getTypeSizeInBits(IntToPtr->getOperand(0)->getType()))
return nullptr;
SmallVector<Value *, 4> AvailablePtrVals;
for (auto Incoming : zip(PN.blocks(), PN.incoming_values())) {
BasicBlock *BB = std::get<0>(Incoming);
Value *Arg = std::get<1>(Incoming);
if (auto *PI = dyn_cast<PtrToIntInst>(Arg)) {
AvailablePtrVals.emplace_back(PI->getOperand(0));
continue;
}
Value *ArgIntToPtr = nullptr;
for (User *U : Arg->users()) {
if (isa<IntToPtrInst>(U) && U->getType() == IntToPtr->getType() &&
(DT.dominates(cast<Instruction>(U), BB) ||
cast<Instruction>(U)->getParent() == BB)) {
ArgIntToPtr = U;
break;
}
}
if (ArgIntToPtr) {
AvailablePtrVals.emplace_back(ArgIntToPtr);
continue;
}
if (isa<PHINode>(Arg)) {
AvailablePtrVals.emplace_back(Arg);
continue;
}
auto *LoadI = dyn_cast<LoadInst>(Arg);
if (!LoadI)
return nullptr;
if (!LoadI->hasOneUse())
return nullptr;
AvailablePtrVals.emplace_back(LoadI);
}
auto *BB = PN.getParent();
assert(AvailablePtrVals.size() == PN.getNumIncomingValues() &&
"Not enough available ptr typed incoming values");
PHINode *MatchingPtrPHI = nullptr;
unsigned NumPhis = 0;
for (PHINode &PtrPHI : BB->phis()) {
if (NumPhis++ > MaxNumPhis)
return nullptr;
if (&PtrPHI == &PN || PtrPHI.getType() != IntToPtr->getType())
continue;
if (any_of(zip(PN.blocks(), AvailablePtrVals),
[&](const auto &BlockAndValue) {
BasicBlock *BB = std::get<0>(BlockAndValue);
Value *V = std::get<1>(BlockAndValue);
return PtrPHI.getIncomingValueForBlock(BB) != V;
}))
continue;
MatchingPtrPHI = &PtrPHI;
break;
}
if (MatchingPtrPHI) {
assert(MatchingPtrPHI->getType() == IntToPtr->getType() &&
"Phi's Type does not match with IntToPtr");
return CastInst::CreateBitOrPointerCast(MatchingPtrPHI,
IntToPtr->getOperand(0)->getType());
}
if (all_of(AvailablePtrVals, [&](Value *V) {
return (V->getType() != IntToPtr->getType()) || isa<IntToPtrInst>(V);
}))
return nullptr;
if (any_of(AvailablePtrVals, [&](Value *V) {
if (V->getType() == IntToPtr->getType())
return false;
auto *Inst = dyn_cast<Instruction>(V);
if (!Inst)
return false;
if (Inst->isTerminator())
return true;
auto *BB = Inst->getParent();
if (isa<PHINode>(Inst) && BB->getFirstInsertionPt() == BB->end())
return true;
return false;
}))
return nullptr;
PHINode *NewPtrPHI = PHINode::Create(
IntToPtr->getType(), PN.getNumIncomingValues(), PN.getName() + ".ptr");
InsertNewInstBefore(NewPtrPHI, PN);
SmallDenseMap<Value *, Instruction *> Casts;
for (auto Incoming : zip(PN.blocks(), AvailablePtrVals)) {
auto *IncomingBB = std::get<0>(Incoming);
auto *IncomingVal = std::get<1>(Incoming);
if (IncomingVal->getType() == IntToPtr->getType()) {
NewPtrPHI->addIncoming(IncomingVal, IncomingBB);
continue;
}
#ifndef NDEBUG
LoadInst *LoadI = dyn_cast<LoadInst>(IncomingVal);
assert((isa<PHINode>(IncomingVal) ||
IncomingVal->getType()->isPointerTy() ||
(LoadI && LoadI->hasOneUse())) &&
"Can not replace LoadInst with multiple uses");
#endif
Instruction *&CI = Casts[IncomingVal];
if (!CI) {
CI = CastInst::CreateBitOrPointerCast(IncomingVal, IntToPtr->getType(),
IncomingVal->getName() + ".ptr");
if (auto *IncomingI = dyn_cast<Instruction>(IncomingVal)) {
BasicBlock::iterator InsertPos(IncomingI);
InsertPos++;
BasicBlock *BB = IncomingI->getParent();
if (isa<PHINode>(IncomingI))
InsertPos = BB->getFirstInsertionPt();
assert(InsertPos != BB->end() && "should have checked above");
InsertNewInstBefore(CI, *InsertPos);
} else {
auto *InsertBB = &IncomingBB->getParent()->getEntryBlock();
InsertNewInstBefore(CI, *InsertBB->getFirstInsertionPt());
}
}
NewPtrPHI->addIncoming(CI, IncomingBB);
}
return CastInst::CreateBitOrPointerCast(NewPtrPHI,
IntToPtr->getOperand(0)->getType());
}
Instruction *InstCombinerImpl::foldPHIArgIntToPtrToPHI(PHINode &PN) {
if (!all_of(PN.users(), [](User *U) { return isa<PtrToIntInst>(U); }))
return nullptr;
bool OperandWithRoundTripCast = false;
for (unsigned OpNum = 0; OpNum != PN.getNumIncomingValues(); ++OpNum) {
if (auto *NewOp =
simplifyIntToPtrRoundTripCast(PN.getIncomingValue(OpNum))) {
PN.setIncomingValue(OpNum, NewOp);
OperandWithRoundTripCast = true;
}
}
if (!OperandWithRoundTripCast)
return nullptr;
return &PN;
}
Instruction *
InstCombinerImpl::foldPHIArgInsertValueInstructionIntoPHI(PHINode &PN) {
auto *FirstIVI = cast<InsertValueInst>(PN.getIncomingValue(0));
for (Value *V : drop_begin(PN.incoming_values())) {
auto *I = dyn_cast<InsertValueInst>(V);
if (!I || !I->hasOneUser() || I->getIndices() != FirstIVI->getIndices())
return nullptr;
}
std::array<PHINode *, 2> NewOperands;
for (int OpIdx : {0, 1}) {
auto *&NewOperand = NewOperands[OpIdx];
NewOperand = PHINode::Create(
FirstIVI->getOperand(OpIdx)->getType(), PN.getNumIncomingValues(),
FirstIVI->getOperand(OpIdx)->getName() + ".pn");
for (auto Incoming : zip(PN.blocks(), PN.incoming_values()))
NewOperand->addIncoming(
cast<InsertValueInst>(std::get<1>(Incoming))->getOperand(OpIdx),
std::get<0>(Incoming));
InsertNewInstBefore(NewOperand, PN);
}
auto *NewIVI = InsertValueInst::Create(NewOperands[0], NewOperands[1],
FirstIVI->getIndices(), PN.getName());
PHIArgMergedDebugLoc(NewIVI, PN);
++NumPHIsOfInsertValues;
return NewIVI;
}
Instruction *
InstCombinerImpl::foldPHIArgExtractValueInstructionIntoPHI(PHINode &PN) {
auto *FirstEVI = cast<ExtractValueInst>(PN.getIncomingValue(0));
for (Value *V : drop_begin(PN.incoming_values())) {
auto *I = dyn_cast<ExtractValueInst>(V);
if (!I || !I->hasOneUser() || I->getIndices() != FirstEVI->getIndices() ||
I->getAggregateOperand()->getType() !=
FirstEVI->getAggregateOperand()->getType())
return nullptr;
}
auto *NewAggregateOperand = PHINode::Create(
FirstEVI->getAggregateOperand()->getType(), PN.getNumIncomingValues(),
FirstEVI->getAggregateOperand()->getName() + ".pn");
for (auto Incoming : zip(PN.blocks(), PN.incoming_values()))
NewAggregateOperand->addIncoming(
cast<ExtractValueInst>(std::get<1>(Incoming))->getAggregateOperand(),
std::get<0>(Incoming));
InsertNewInstBefore(NewAggregateOperand, PN);
auto *NewEVI = ExtractValueInst::Create(NewAggregateOperand,
FirstEVI->getIndices(), PN.getName());
PHIArgMergedDebugLoc(NewEVI, PN);
++NumPHIsOfExtractValues;
return NewEVI;
}
Instruction *InstCombinerImpl::foldPHIArgBinOpIntoPHI(PHINode &PN) {
Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
unsigned Opc = FirstInst->getOpcode();
Value *LHSVal = FirstInst->getOperand(0);
Value *RHSVal = FirstInst->getOperand(1);
Type *LHSType = LHSVal->getType();
Type *RHSType = RHSVal->getType();
for (Value *V : drop_begin(PN.incoming_values())) {
Instruction *I = dyn_cast<Instruction>(V);
if (!I || I->getOpcode() != Opc || !I->hasOneUser() ||
I->getOperand(0)->getType() != LHSType ||
I->getOperand(1)->getType() != RHSType)
return nullptr;
if (CmpInst *CI = dyn_cast<CmpInst>(I))
if (CI->getPredicate() != cast<CmpInst>(FirstInst)->getPredicate())
return nullptr;
if (I->getOperand(0) != LHSVal) LHSVal = nullptr;
if (I->getOperand(1) != RHSVal) RHSVal = nullptr;
}
if (!LHSVal && !RHSVal)
return nullptr;
Value *InLHS = FirstInst->getOperand(0);
Value *InRHS = FirstInst->getOperand(1);
PHINode *NewLHS = nullptr, *NewRHS = nullptr;
if (!LHSVal) {
NewLHS = PHINode::Create(LHSType, PN.getNumIncomingValues(),
FirstInst->getOperand(0)->getName() + ".pn");
NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
InsertNewInstBefore(NewLHS, PN);
LHSVal = NewLHS;
}
if (!RHSVal) {
NewRHS = PHINode::Create(RHSType, PN.getNumIncomingValues(),
FirstInst->getOperand(1)->getName() + ".pn");
NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
InsertNewInstBefore(NewRHS, PN);
RHSVal = NewRHS;
}
if (NewLHS || NewRHS) {
for (auto Incoming : drop_begin(zip(PN.blocks(), PN.incoming_values()))) {
BasicBlock *InBB = std::get<0>(Incoming);
Value *InVal = std::get<1>(Incoming);
Instruction *InInst = cast<Instruction>(InVal);
if (NewLHS) {
Value *NewInLHS = InInst->getOperand(0);
NewLHS->addIncoming(NewInLHS, InBB);
}
if (NewRHS) {
Value *NewInRHS = InInst->getOperand(1);
NewRHS->addIncoming(NewInRHS, InBB);
}
}
}
if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst)) {
CmpInst *NewCI = CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
LHSVal, RHSVal);
PHIArgMergedDebugLoc(NewCI, PN);
return NewCI;
}
BinaryOperator *BinOp = cast<BinaryOperator>(FirstInst);
BinaryOperator *NewBinOp =
BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
NewBinOp->copyIRFlags(PN.getIncomingValue(0));
for (Value *V : drop_begin(PN.incoming_values()))
NewBinOp->andIRFlags(V);
PHIArgMergedDebugLoc(NewBinOp, PN);
return NewBinOp;
}
Instruction *InstCombinerImpl::foldPHIArgGEPIntoPHI(PHINode &PN) {
GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
FirstInst->op_end());
bool AllBasePointersAreAllocas = true;
bool NeededPhi = false;
bool AllInBounds = true;
for (Value *V : drop_begin(PN.incoming_values())) {
GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V);
if (!GEP || !GEP->hasOneUser() ||
GEP->getSourceElementType() != FirstInst->getSourceElementType() ||
GEP->getNumOperands() != FirstInst->getNumOperands())
return nullptr;
AllInBounds &= GEP->isInBounds();
if (AllBasePointersAreAllocas &&
(!isa<AllocaInst>(GEP->getOperand(0)) ||
!GEP->hasAllConstantIndices()))
AllBasePointersAreAllocas = false;
for (unsigned Op = 0, E = FirstInst->getNumOperands(); Op != E; ++Op) {
if (FirstInst->getOperand(Op) == GEP->getOperand(Op))
continue;
if (isa<ConstantInt>(FirstInst->getOperand(Op)) ||
isa<ConstantInt>(GEP->getOperand(Op)))
return nullptr;
if (FirstInst->getOperand(Op)->getType() !=
GEP->getOperand(Op)->getType())
return nullptr;
if (NeededPhi)
return nullptr;
FixedOperands[Op] = nullptr; NeededPhi = true;
}
}
if (AllBasePointersAreAllocas)
return nullptr;
SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
bool HasAnyPHIs = false;
for (unsigned I = 0, E = FixedOperands.size(); I != E; ++I) {
if (FixedOperands[I])
continue; Value *FirstOp = FirstInst->getOperand(I);
PHINode *NewPN =
PHINode::Create(FirstOp->getType(), E, FirstOp->getName() + ".pn");
InsertNewInstBefore(NewPN, PN);
NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
OperandPhis[I] = NewPN;
FixedOperands[I] = NewPN;
HasAnyPHIs = true;
}
if (HasAnyPHIs) {
for (auto Incoming : drop_begin(zip(PN.blocks(), PN.incoming_values()))) {
BasicBlock *InBB = std::get<0>(Incoming);
Value *InVal = std::get<1>(Incoming);
GetElementPtrInst *InGEP = cast<GetElementPtrInst>(InVal);
for (unsigned Op = 0, E = OperandPhis.size(); Op != E; ++Op)
if (PHINode *OpPhi = OperandPhis[Op])
OpPhi->addIncoming(InGEP->getOperand(Op), InBB);
}
}
Value *Base = FixedOperands[0];
GetElementPtrInst *NewGEP =
GetElementPtrInst::Create(FirstInst->getSourceElementType(), Base,
makeArrayRef(FixedOperands).slice(1));
if (AllInBounds) NewGEP->setIsInBounds();
PHIArgMergedDebugLoc(NewGEP, PN);
return NewGEP;
}
static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
BasicBlock::iterator BBI = L->getIterator(), E = L->getParent()->end();
for (++BBI; BBI != E; ++BBI)
if (BBI->mayWriteToMemory()) {
if (auto *CB = dyn_cast<CallBase>(BBI))
if (CB->onlyAccessesInaccessibleMemory())
continue;
return false;
}
if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
bool IsAddressTaken = false;
for (User *U : AI->users()) {
if (isa<LoadInst>(U)) continue;
if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
if (SI->getOperand(1) == AI) continue;
}
IsAddressTaken = true;
break;
}
if (!IsAddressTaken && AI->isStaticAlloca())
return false;
}
if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
return false;
return true;
}
Instruction *InstCombinerImpl::foldPHIArgLoadIntoPHI(PHINode &PN) {
LoadInst *FirstLI = cast<LoadInst>(PN.getIncomingValue(0));
if (FirstLI->getOperand(0)->isSwiftError())
return nullptr;
if (FirstLI->isAtomic())
return nullptr;
bool IsVolatile = FirstLI->isVolatile();
Align LoadAlignment = FirstLI->getAlign();
const unsigned LoadAddrSpace = FirstLI->getPointerAddressSpace();
if (FirstLI->getParent() != PN.getIncomingBlock(0) ||
!isSafeAndProfitableToSinkLoad(FirstLI))
return nullptr;
if (IsVolatile &&
FirstLI->getParent()->getTerminator()->getNumSuccessors() != 1)
return nullptr;
for (auto Incoming : drop_begin(zip(PN.blocks(), PN.incoming_values()))) {
BasicBlock *InBB = std::get<0>(Incoming);
Value *InVal = std::get<1>(Incoming);
LoadInst *LI = dyn_cast<LoadInst>(InVal);
if (!LI || !LI->hasOneUser() || LI->isAtomic())
return nullptr;
if (LI->isVolatile() != IsVolatile ||
LI->getPointerAddressSpace() != LoadAddrSpace)
return nullptr;
if (LI->getOperand(0)->isSwiftError())
return nullptr;
if (LI->getParent() != InBB || !isSafeAndProfitableToSinkLoad(LI))
return nullptr;
LoadAlignment = std::min(LoadAlignment, LI->getAlign());
if (IsVolatile && LI->getParent()->getTerminator()->getNumSuccessors() != 1)
return nullptr;
}
PHINode *NewPN = PHINode::Create(FirstLI->getOperand(0)->getType(),
PN.getNumIncomingValues(),
PN.getName()+".in");
Value *InVal = FirstLI->getOperand(0);
NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
LoadInst *NewLI =
new LoadInst(FirstLI->getType(), NewPN, "", IsVolatile, LoadAlignment);
unsigned KnownIDs[] = {
LLVMContext::MD_tbaa,
LLVMContext::MD_range,
LLVMContext::MD_invariant_load,
LLVMContext::MD_alias_scope,
LLVMContext::MD_noalias,
LLVMContext::MD_nonnull,
LLVMContext::MD_align,
LLVMContext::MD_dereferenceable,
LLVMContext::MD_dereferenceable_or_null,
LLVMContext::MD_access_group,
};
for (unsigned ID : KnownIDs)
NewLI->setMetadata(ID, FirstLI->getMetadata(ID));
for (auto Incoming : drop_begin(zip(PN.blocks(), PN.incoming_values()))) {
BasicBlock *BB = std::get<0>(Incoming);
Value *V = std::get<1>(Incoming);
LoadInst *LI = cast<LoadInst>(V);
combineMetadata(NewLI, LI, KnownIDs, true);
Value *NewInVal = LI->getOperand(0);
if (NewInVal != InVal)
InVal = nullptr;
NewPN->addIncoming(NewInVal, BB);
}
if (InVal) {
NewLI->setOperand(0, InVal);
delete NewPN;
} else {
InsertNewInstBefore(NewPN, PN);
}
if (IsVolatile)
for (Value *IncValue : PN.incoming_values())
cast<LoadInst>(IncValue)->setVolatile(false);
PHIArgMergedDebugLoc(NewLI, PN);
return NewLI;
}
Instruction *InstCombinerImpl::foldPHIArgZextsIntoPHI(PHINode &Phi) {
if (Instruction *TI = Phi.getParent()->getTerminator())
if (TI->isEHPad())
return nullptr;
unsigned NumIncomingValues = Phi.getNumIncomingValues();
if (NumIncomingValues < 3)
return nullptr;
Type *NarrowType = nullptr;
for (Value *V : Phi.incoming_values()) {
if (auto *Zext = dyn_cast<ZExtInst>(V)) {
NarrowType = Zext->getSrcTy();
break;
}
}
if (!NarrowType)
return nullptr;
SmallVector<Value *, 4> NewIncoming;
unsigned NumZexts = 0;
unsigned NumConsts = 0;
for (Value *V : Phi.incoming_values()) {
if (auto *Zext = dyn_cast<ZExtInst>(V)) {
if (Zext->getSrcTy() != NarrowType || !Zext->hasOneUser())
return nullptr;
NewIncoming.push_back(Zext->getOperand(0));
NumZexts++;
} else if (auto *C = dyn_cast<Constant>(V)) {
Constant *Trunc = ConstantExpr::getTrunc(C, NarrowType);
if (ConstantExpr::getZExt(Trunc, C->getType()) != C)
return nullptr;
NewIncoming.push_back(Trunc);
NumConsts++;
} else {
return nullptr;
}
}
if (NumConsts == 0 || NumZexts < 2)
return nullptr;
PHINode *NewPhi = PHINode::Create(NarrowType, NumIncomingValues,
Phi.getName() + ".shrunk");
for (unsigned I = 0; I != NumIncomingValues; ++I)
NewPhi->addIncoming(NewIncoming[I], Phi.getIncomingBlock(I));
InsertNewInstBefore(NewPhi, Phi);
return CastInst::CreateZExtOrBitCast(NewPhi, Phi.getType());
}
Instruction *InstCombinerImpl::foldPHIArgOpIntoPHI(PHINode &PN) {
if (Instruction *TI = PN.getParent()->getTerminator())
if (TI->isEHPad())
return nullptr;
Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
if (isa<GetElementPtrInst>(FirstInst))
return foldPHIArgGEPIntoPHI(PN);
if (isa<LoadInst>(FirstInst))
return foldPHIArgLoadIntoPHI(PN);
if (isa<InsertValueInst>(FirstInst))
return foldPHIArgInsertValueInstructionIntoPHI(PN);
if (isa<ExtractValueInst>(FirstInst))
return foldPHIArgExtractValueInstructionIntoPHI(PN);
Constant *ConstantOp = nullptr;
Type *CastSrcTy = nullptr;
if (isa<CastInst>(FirstInst)) {
CastSrcTy = FirstInst->getOperand(0)->getType();
if (PN.getType()->isIntegerTy() && CastSrcTy->isIntegerTy()) {
if (!shouldChangeType(PN.getType(), CastSrcTy))
return nullptr;
}
} else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
if (!ConstantOp)
return foldPHIArgBinOpIntoPHI(PN);
} else {
return nullptr; }
for (Value *V : drop_begin(PN.incoming_values())) {
Instruction *I = dyn_cast<Instruction>(V);
if (!I || !I->hasOneUser() || !I->isSameOperationAs(FirstInst))
return nullptr;
if (CastSrcTy) {
if (I->getOperand(0)->getType() != CastSrcTy)
return nullptr; } else if (I->getOperand(1) != ConstantOp) {
return nullptr;
}
}
PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
PN.getNumIncomingValues(),
PN.getName()+".in");
Value *InVal = FirstInst->getOperand(0);
NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
for (auto Incoming : drop_begin(zip(PN.blocks(), PN.incoming_values()))) {
BasicBlock *BB = std::get<0>(Incoming);
Value *V = std::get<1>(Incoming);
Value *NewInVal = cast<Instruction>(V)->getOperand(0);
if (NewInVal != InVal)
InVal = nullptr;
NewPN->addIncoming(NewInVal, BB);
}
Value *PhiVal;
if (InVal) {
PhiVal = InVal;
delete NewPN;
} else {
InsertNewInstBefore(NewPN, PN);
PhiVal = NewPN;
}
if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst)) {
CastInst *NewCI = CastInst::Create(FirstCI->getOpcode(), PhiVal,
PN.getType());
PHIArgMergedDebugLoc(NewCI, PN);
return NewCI;
}
if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst)) {
BinOp = BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
BinOp->copyIRFlags(PN.getIncomingValue(0));
for (Value *V : drop_begin(PN.incoming_values()))
BinOp->andIRFlags(V);
PHIArgMergedDebugLoc(BinOp, PN);
return BinOp;
}
CmpInst *CIOp = cast<CmpInst>(FirstInst);
CmpInst *NewCI = CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
PhiVal, ConstantOp);
PHIArgMergedDebugLoc(NewCI, PN);
return NewCI;
}
static bool isDeadPHICycle(PHINode *PN,
SmallPtrSetImpl<PHINode *> &PotentiallyDeadPHIs) {
if (PN->use_empty()) return true;
if (!PN->hasOneUse()) return false;
if (!PotentiallyDeadPHIs.insert(PN).second)
return true;
if (PotentiallyDeadPHIs.size() == 16)
return false;
if (PHINode *PU = dyn_cast<PHINode>(PN->user_back()))
return isDeadPHICycle(PU, PotentiallyDeadPHIs);
return false;
}
static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
SmallPtrSetImpl<PHINode*> &ValueEqualPHIs) {
if (!ValueEqualPHIs.insert(PN).second)
return true;
if (ValueEqualPHIs.size() == 16)
return false;
for (Value *Op : PN->incoming_values()) {
if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
return false;
} else if (Op != NonPhiInVal)
return false;
}
return true;
}
static ConstantInt *getAnyNonZeroConstInt(PHINode &PN) {
assert(isa<IntegerType>(PN.getType()) && "Expect only integer type phi");
for (Value *V : PN.operands())
if (auto *ConstVA = dyn_cast<ConstantInt>(V))
if (!ConstVA->isZero())
return ConstVA;
return ConstantInt::get(cast<IntegerType>(PN.getType()), 1);
}
namespace {
struct PHIUsageRecord {
unsigned PHIId; unsigned Shift; Instruction *Inst;
PHIUsageRecord(unsigned Pn, unsigned Sh, Instruction *User)
: PHIId(Pn), Shift(Sh), Inst(User) {}
bool operator<(const PHIUsageRecord &RHS) const {
if (PHIId < RHS.PHIId) return true;
if (PHIId > RHS.PHIId) return false;
if (Shift < RHS.Shift) return true;
if (Shift > RHS.Shift) return false;
return Inst->getType()->getPrimitiveSizeInBits() <
RHS.Inst->getType()->getPrimitiveSizeInBits();
}
};
struct LoweredPHIRecord {
PHINode *PN; unsigned Shift; unsigned Width;
LoweredPHIRecord(PHINode *Phi, unsigned Sh, Type *Ty)
: PN(Phi), Shift(Sh), Width(Ty->getPrimitiveSizeInBits()) {}
LoweredPHIRecord(PHINode *Phi, unsigned Sh) : PN(Phi), Shift(Sh), Width(0) {}
};
}
namespace llvm {
template<>
struct DenseMapInfo<LoweredPHIRecord> {
static inline LoweredPHIRecord getEmptyKey() {
return LoweredPHIRecord(nullptr, 0);
}
static inline LoweredPHIRecord getTombstoneKey() {
return LoweredPHIRecord(nullptr, 1);
}
static unsigned getHashValue(const LoweredPHIRecord &Val) {
return DenseMapInfo<PHINode*>::getHashValue(Val.PN) ^ (Val.Shift>>3) ^
(Val.Width>>3);
}
static bool isEqual(const LoweredPHIRecord &LHS,
const LoweredPHIRecord &RHS) {
return LHS.PN == RHS.PN && LHS.Shift == RHS.Shift &&
LHS.Width == RHS.Width;
}
};
}
Instruction *InstCombinerImpl::SliceUpIllegalIntegerPHI(PHINode &FirstPhi) {
SmallVector<PHIUsageRecord, 16> PHIUsers;
SmallVector<PHINode*, 8> PHIsToSlice;
SmallPtrSet<PHINode*, 8> PHIsInspected;
PHIsToSlice.push_back(&FirstPhi);
PHIsInspected.insert(&FirstPhi);
for (unsigned PHIId = 0; PHIId != PHIsToSlice.size(); ++PHIId) {
PHINode *PN = PHIsToSlice[PHIId];
for (auto Incoming : zip(PN->blocks(), PN->incoming_values())) {
BasicBlock *BB = std::get<0>(Incoming);
Value *V = std::get<1>(Incoming);
InvokeInst *II = dyn_cast<InvokeInst>(V);
if (!II)
continue;
if (II->getParent() != BB)
continue;
return nullptr;
}
for (auto *Pred : PN->blocks())
if (Pred->getFirstInsertionPt() == Pred->end())
return nullptr;
for (User *U : PN->users()) {
Instruction *UserI = cast<Instruction>(U);
if (PHINode *UserPN = dyn_cast<PHINode>(UserI)) {
if (PHIsInspected.insert(UserPN).second)
PHIsToSlice.push_back(UserPN);
continue;
}
if (isa<TruncInst>(UserI)) {
PHIUsers.push_back(PHIUsageRecord(PHIId, 0, UserI));
continue;
}
if (UserI->getOpcode() != Instruction::LShr ||
!UserI->hasOneUse() || !isa<TruncInst>(UserI->user_back()) ||
!isa<ConstantInt>(UserI->getOperand(1)))
return nullptr;
unsigned SizeInBits = UserI->getType()->getScalarSizeInBits();
if (cast<ConstantInt>(UserI->getOperand(1))->getValue().uge(SizeInBits))
return nullptr;
unsigned Shift = cast<ConstantInt>(UserI->getOperand(1))->getZExtValue();
PHIUsers.push_back(PHIUsageRecord(PHIId, Shift, UserI->user_back()));
}
}
if (PHIUsers.empty())
return replaceInstUsesWith(FirstPhi, PoisonValue::get(FirstPhi.getType()));
array_pod_sort(PHIUsers.begin(), PHIUsers.end());
LLVM_DEBUG(dbgs() << "SLICING UP PHI: " << FirstPhi << '\n';
for (unsigned I = 1; I != PHIsToSlice.size(); ++I) dbgs()
<< "AND USER PHI #" << I << ": " << *PHIsToSlice[I] << '\n');
DenseMap<BasicBlock*, Value*> PredValues;
DenseMap<LoweredPHIRecord, PHINode*> ExtractedVals;
for (unsigned UserI = 0, UserE = PHIUsers.size(); UserI != UserE; ++UserI) {
unsigned PHIId = PHIUsers[UserI].PHIId;
PHINode *PN = PHIsToSlice[PHIId];
unsigned Offset = PHIUsers[UserI].Shift;
Type *Ty = PHIUsers[UserI].Inst->getType();
PHINode *EltPHI;
if ((EltPHI = ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)]) == nullptr) {
EltPHI = PHINode::Create(Ty, PN->getNumIncomingValues(),
PN->getName()+".off"+Twine(Offset), PN);
assert(EltPHI->getType() != PN->getType() &&
"Truncate didn't shrink phi?");
for (auto Incoming : zip(PN->blocks(), PN->incoming_values())) {
BasicBlock *Pred = std::get<0>(Incoming);
Value *InVal = std::get<1>(Incoming);
Value *&PredVal = PredValues[Pred];
if (PredVal) {
EltPHI->addIncoming(PredVal, Pred);
continue;
}
if (InVal == PN) {
PredVal = EltPHI;
EltPHI->addIncoming(PredVal, Pred);
continue;
}
if (PHINode *InPHI = dyn_cast<PHINode>(PN)) {
if (Value *Res = ExtractedVals[LoweredPHIRecord(InPHI, Offset, Ty)]) {
PredVal = Res;
EltPHI->addIncoming(PredVal, Pred);
continue;
}
}
Builder.SetInsertPoint(Pred->getTerminator());
Value *Res = InVal;
if (Offset)
Res = Builder.CreateLShr(
Res, ConstantInt::get(InVal->getType(), Offset), "extract");
Res = Builder.CreateTrunc(Res, Ty, "extract.t");
PredVal = Res;
EltPHI->addIncoming(Res, Pred);
if (PHINode *OldInVal = dyn_cast<PHINode>(InVal))
if (PHIsInspected.count(OldInVal)) {
unsigned RefPHIId =
find(PHIsToSlice, OldInVal) - PHIsToSlice.begin();
PHIUsers.push_back(
PHIUsageRecord(RefPHIId, Offset, cast<Instruction>(Res)));
++UserE;
}
}
PredValues.clear();
LLVM_DEBUG(dbgs() << " Made element PHI for offset " << Offset << ": "
<< *EltPHI << '\n');
ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)] = EltPHI;
}
replaceInstUsesWith(*PHIUsers[UserI].Inst, EltPHI);
}
Value *Poison = PoisonValue::get(FirstPhi.getType());
for (PHINode *PHI : drop_begin(PHIsToSlice))
replaceInstUsesWith(*PHI, Poison);
return replaceInstUsesWith(FirstPhi, Poison);
}
static Value *simplifyUsingControlFlow(InstCombiner &Self, PHINode &PN,
const DominatorTree &DT) {
if (!all_of(PN.operands(), [](Value *V) { return isa<ConstantInt>(V); }))
return nullptr;
BasicBlock *BB = PN.getParent();
if (!DT.isReachableFromEntry(BB))
return nullptr;
LLVMContext &Context = PN.getContext();
auto *IDom = DT.getNode(BB)->getIDom()->getBlock();
Value *Cond;
SmallDenseMap<ConstantInt *, BasicBlock *, 8> SuccForValue;
SmallDenseMap<BasicBlock *, unsigned, 8> SuccCount;
auto AddSucc = [&](ConstantInt *C, BasicBlock *Succ) {
SuccForValue[C] = Succ;
++SuccCount[Succ];
};
if (auto *BI = dyn_cast<BranchInst>(IDom->getTerminator())) {
if (BI->isUnconditional())
return nullptr;
Cond = BI->getCondition();
AddSucc(ConstantInt::getTrue(Context), BI->getSuccessor(0));
AddSucc(ConstantInt::getFalse(Context), BI->getSuccessor(1));
} else if (auto *SI = dyn_cast<SwitchInst>(IDom->getTerminator())) {
Cond = SI->getCondition();
++SuccCount[SI->getDefaultDest()];
for (auto Case : SI->cases())
AddSucc(Case.getCaseValue(), Case.getCaseSuccessor());
} else {
return nullptr;
}
if (Cond->getType() != PN.getType())
return nullptr;
Optional<bool> Invert;
for (auto Pair : zip(PN.incoming_values(), PN.blocks())) {
auto *Input = cast<ConstantInt>(std::get<0>(Pair));
BasicBlock *Pred = std::get<1>(Pair);
auto IsCorrectInput = [&](ConstantInt *Input) {
auto It = SuccForValue.find(Input);
return It != SuccForValue.end() && SuccCount[It->second] == 1 &&
DT.dominates(BasicBlockEdge(IDom, It->second),
BasicBlockEdge(Pred, BB));
};
bool NeedsInvert;
if (IsCorrectInput(Input))
NeedsInvert = false;
else if (IsCorrectInput(cast<ConstantInt>(ConstantExpr::getNot(Input))))
NeedsInvert = true;
else
return nullptr;
if (Invert && *Invert != NeedsInvert)
return nullptr;
Invert = NeedsInvert;
}
if (!*Invert)
return Cond;
auto InsertPt = BB->getFirstInsertionPt();
if (InsertPt != BB->end()) {
Self.Builder.SetInsertPoint(&*InsertPt);
return Self.Builder.CreateNot(Cond);
}
return nullptr;
}
Instruction *InstCombinerImpl::visitPHINode(PHINode &PN) {
if (Value *V = simplifyInstruction(&PN, SQ.getWithInstruction(&PN)))
return replaceInstUsesWith(PN, V);
if (Instruction *Result = foldPHIArgZextsIntoPHI(PN))
return Result;
if (Instruction *Result = foldPHIArgIntToPtrToPHI(PN))
return Result;
if (isa<Instruction>(PN.getIncomingValue(0)) &&
isa<Instruction>(PN.getIncomingValue(1)) &&
cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
PN.getIncomingValue(0)->hasOneUser())
if (Instruction *Result = foldPHIArgOpIntoPHI(PN))
return Result;
if (PN.getType()->isPointerTy() &&
PN.getParent()->getFirstInsertionPt() != PN.getParent()->end()) {
Value *IV0 = PN.getIncomingValue(0);
Value *IV0Stripped = IV0->stripPointerCasts();
SmallPtrSet<Value *, 4> CheckedIVs;
CheckedIVs.insert(IV0);
if (IV0 != IV0Stripped &&
all_of(PN.incoming_values(), [&CheckedIVs, IV0Stripped](Value *IV) {
return !CheckedIVs.insert(IV).second ||
IV0Stripped == IV->stripPointerCasts();
})) {
return CastInst::CreatePointerCast(IV0Stripped, PN.getType());
}
}
if (PN.hasOneUse()) {
if (Instruction *Result = foldIntegerTypedPHI(PN))
return Result;
Instruction *PHIUser = cast<Instruction>(PN.user_back());
if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
PotentiallyDeadPHIs.insert(&PN);
if (isDeadPHICycle(PU, PotentiallyDeadPHIs))
return replaceInstUsesWith(PN, PoisonValue::get(PN.getType()));
}
if (PHIUser->hasOneUse() &&
(isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
PHIUser->user_back() == &PN) {
return replaceInstUsesWith(PN, PoisonValue::get(PN.getType()));
}
auto *CmpInst = dyn_cast<ICmpInst>(PHIUser);
if (CmpInst && isa<IntegerType>(PN.getType()) && CmpInst->isEquality() &&
match(CmpInst->getOperand(1), m_Zero())) {
ConstantInt *NonZeroConst = nullptr;
bool MadeChange = false;
for (unsigned I = 0, E = PN.getNumIncomingValues(); I != E; ++I) {
Instruction *CtxI = PN.getIncomingBlock(I)->getTerminator();
Value *VA = PN.getIncomingValue(I);
if (isKnownNonZero(VA, DL, 0, &AC, CtxI, &DT)) {
if (!NonZeroConst)
NonZeroConst = getAnyNonZeroConstInt(PN);
if (NonZeroConst != VA) {
replaceOperand(PN, I, NonZeroConst);
MadeChange = true;
}
}
}
if (MadeChange)
return &PN;
}
}
{
unsigned InValNo = 0, NumIncomingVals = PN.getNumIncomingValues();
while (InValNo != NumIncomingVals &&
isa<PHINode>(PN.getIncomingValue(InValNo)))
++InValNo;
if (InValNo != NumIncomingVals) {
Value *NonPhiInVal = PN.getIncomingValue(InValNo);
for (++InValNo; InValNo != NumIncomingVals; ++InValNo) {
Value *OpVal = PN.getIncomingValue(InValNo);
if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
break;
}
if (InValNo == NumIncomingVals) {
SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
return replaceInstUsesWith(PN, NonPhiInVal);
}
}
}
PHINode *FirstPN = cast<PHINode>(PN.getParent()->begin());
if (&PN != FirstPN)
for (unsigned I = 0, E = FirstPN->getNumIncomingValues(); I != E; ++I) {
BasicBlock *BBA = PN.getIncomingBlock(I);
BasicBlock *BBB = FirstPN->getIncomingBlock(I);
if (BBA != BBB) {
Value *VA = PN.getIncomingValue(I);
unsigned J = PN.getBasicBlockIndex(BBB);
Value *VB = PN.getIncomingValue(J);
PN.setIncomingBlock(I, BBB);
PN.setIncomingValue(I, VB);
PN.setIncomingBlock(J, BBA);
PN.setIncomingValue(J, VA);
}
}
for (PHINode &IdenticalPN : PN.getParent()->phis()) {
if (&IdenticalPN == &PN)
continue;
if (!PN.isIdenticalToWhenDefined(&IdenticalPN))
continue;
++NumPHICSEs;
return replaceInstUsesWith(PN, &IdenticalPN);
}
if (PN.getType()->isIntegerTy() &&
!DL.isLegalInteger(PN.getType()->getPrimitiveSizeInBits()))
if (Instruction *Res = SliceUpIllegalIntegerPHI(PN))
return Res;
if (auto *V = simplifyUsingControlFlow(*this, PN, DT))
return replaceInstUsesWith(PN, V);
return nullptr;
}