#ifndef LLVM_ANALYSIS_SPARSEPROPAGATION_H
#define LLVM_ANALYSIS_SPARSEPROPAGATION_H
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Instructions.h"
#include "llvm/Support/Debug.h"
#include <set>
#define DEBUG_TYPE "sparseprop"
namespace llvm {
template <class LatticeKey> struct LatticeKeyInfo {
};
template <class LatticeKey, class LatticeVal,
class KeyInfo = LatticeKeyInfo<LatticeKey>>
class SparseSolver;
template <class LatticeKey, class LatticeVal> class AbstractLatticeFunction {
private:
LatticeVal UndefVal, OverdefinedVal, UntrackedVal;
public:
AbstractLatticeFunction(LatticeVal undefVal, LatticeVal overdefinedVal,
LatticeVal untrackedVal) {
UndefVal = undefVal;
OverdefinedVal = overdefinedVal;
UntrackedVal = untrackedVal;
}
virtual ~AbstractLatticeFunction() = default;
LatticeVal getUndefVal() const { return UndefVal; }
LatticeVal getOverdefinedVal() const { return OverdefinedVal; }
LatticeVal getUntrackedVal() const { return UntrackedVal; }
virtual bool IsUntrackedValue(LatticeKey Key) { return false; }
virtual LatticeVal ComputeLatticeVal(LatticeKey Key) {
return getOverdefinedVal();
}
virtual bool IsSpecialCasedPHI(PHINode *PN) { return false; }
virtual LatticeVal MergeValues(LatticeVal X, LatticeVal Y) {
return getOverdefinedVal(); }
virtual void
ComputeInstructionState(Instruction &I,
DenseMap<LatticeKey, LatticeVal> &ChangedValues,
SparseSolver<LatticeKey, LatticeVal> &SS) = 0;
virtual void PrintLatticeVal(LatticeVal LV, raw_ostream &OS);
virtual void PrintLatticeKey(LatticeKey Key, raw_ostream &OS);
virtual Value *GetValueFromLatticeVal(LatticeVal LV, Type *Ty = nullptr) {
return nullptr;
}
};
template <class LatticeKey, class LatticeVal, class KeyInfo>
class SparseSolver {
AbstractLatticeFunction<LatticeKey, LatticeVal> *LatticeFunc;
DenseMap<LatticeKey, LatticeVal> ValueState;
SmallPtrSet<BasicBlock *, 16> BBExecutable;
SmallVector<Value *, 64> ValueWorkList;
SmallVector<BasicBlock *, 64> BBWorkList;
using Edge = std::pair<BasicBlock *, BasicBlock *>;
std::set<Edge> KnownFeasibleEdges;
public:
explicit SparseSolver(
AbstractLatticeFunction<LatticeKey, LatticeVal> *Lattice)
: LatticeFunc(Lattice) {}
SparseSolver(const SparseSolver &) = delete;
SparseSolver &operator=(const SparseSolver &) = delete;
void Solve();
void Print(raw_ostream &OS) const;
LatticeVal getExistingValueState(LatticeKey Key) const {
auto I = ValueState.find(Key);
return I != ValueState.end() ? I->second : LatticeFunc->getUntrackedVal();
}
LatticeVal getValueState(LatticeKey Key);
bool isEdgeFeasible(BasicBlock *From, BasicBlock *To,
bool AggressiveUndef = false);
bool isBlockExecutable(BasicBlock *BB) const {
return BBExecutable.count(BB);
}
void MarkBlockExecutable(BasicBlock *BB);
private:
void UpdateState(LatticeKey Key, LatticeVal LV);
void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest);
void getFeasibleSuccessors(Instruction &TI, SmallVectorImpl<bool> &Succs,
bool AggressiveUndef);
void visitInst(Instruction &I);
void visitPHINode(PHINode &I);
void visitTerminator(Instruction &TI);
};
template <class LatticeKey, class LatticeVal>
void AbstractLatticeFunction<LatticeKey, LatticeVal>::PrintLatticeVal(
LatticeVal V, raw_ostream &OS) {
if (V == UndefVal)
OS << "undefined";
else if (V == OverdefinedVal)
OS << "overdefined";
else if (V == UntrackedVal)
OS << "untracked";
else
OS << "unknown lattice value";
}
template <class LatticeKey, class LatticeVal>
void AbstractLatticeFunction<LatticeKey, LatticeVal>::PrintLatticeKey(
LatticeKey Key, raw_ostream &OS) {
OS << "unknown lattice key";
}
template <class LatticeKey, class LatticeVal, class KeyInfo>
LatticeVal
SparseSolver<LatticeKey, LatticeVal, KeyInfo>::getValueState(LatticeKey Key) {
auto I = ValueState.find(Key);
if (I != ValueState.end())
return I->second;
if (LatticeFunc->IsUntrackedValue(Key))
return LatticeFunc->getUntrackedVal();
LatticeVal LV = LatticeFunc->ComputeLatticeVal(Key);
if (LV == LatticeFunc->getUntrackedVal())
return LV;
return ValueState[Key] = std::move(LV);
}
template <class LatticeKey, class LatticeVal, class KeyInfo>
void SparseSolver<LatticeKey, LatticeVal, KeyInfo>::UpdateState(LatticeKey Key,
LatticeVal LV) {
auto I = ValueState.find(Key);
if (I != ValueState.end() && I->second == LV)
return;
ValueState[Key] = std::move(LV);
if (Value *V = KeyInfo::getValueFromLatticeKey(Key))
ValueWorkList.push_back(V);
}
template <class LatticeKey, class LatticeVal, class KeyInfo>
void SparseSolver<LatticeKey, LatticeVal, KeyInfo>::MarkBlockExecutable(
BasicBlock *BB) {
if (!BBExecutable.insert(BB).second)
return;
LLVM_DEBUG(dbgs() << "Marking Block Executable: " << BB->getName() << "\n");
BBWorkList.push_back(BB); }
template <class LatticeKey, class LatticeVal, class KeyInfo>
void SparseSolver<LatticeKey, LatticeVal, KeyInfo>::markEdgeExecutable(
BasicBlock *Source, BasicBlock *Dest) {
if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
return;
LLVM_DEBUG(dbgs() << "Marking Edge Executable: " << Source->getName()
<< " -> " << Dest->getName() << "\n");
if (BBExecutable.count(Dest)) {
for (BasicBlock::iterator I = Dest->begin(); isa<PHINode>(I); ++I)
visitPHINode(*cast<PHINode>(I));
} else {
MarkBlockExecutable(Dest);
}
}
template <class LatticeKey, class LatticeVal, class KeyInfo>
void SparseSolver<LatticeKey, LatticeVal, KeyInfo>::getFeasibleSuccessors(
Instruction &TI, SmallVectorImpl<bool> &Succs, bool AggressiveUndef) {
Succs.resize(TI.getNumSuccessors());
if (TI.getNumSuccessors() == 0)
return;
if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
if (BI->isUnconditional()) {
Succs[0] = true;
return;
}
LatticeVal BCValue;
if (AggressiveUndef)
BCValue =
getValueState(KeyInfo::getLatticeKeyFromValue(BI->getCondition()));
else
BCValue = getExistingValueState(
KeyInfo::getLatticeKeyFromValue(BI->getCondition()));
if (BCValue == LatticeFunc->getOverdefinedVal() ||
BCValue == LatticeFunc->getUntrackedVal()) {
Succs[0] = Succs[1] = true;
return;
}
if (BCValue == LatticeFunc->getUndefVal())
return;
Constant *C =
dyn_cast_or_null<Constant>(LatticeFunc->GetValueFromLatticeVal(
std::move(BCValue), BI->getCondition()->getType()));
if (!C || !isa<ConstantInt>(C)) {
Succs[0] = Succs[1] = true;
return;
}
Succs[C->isNullValue()] = true;
return;
}
if (!isa<SwitchInst>(TI)) {
Succs.assign(Succs.size(), true);
return;
}
SwitchInst &SI = cast<SwitchInst>(TI);
LatticeVal SCValue;
if (AggressiveUndef)
SCValue = getValueState(KeyInfo::getLatticeKeyFromValue(SI.getCondition()));
else
SCValue = getExistingValueState(
KeyInfo::getLatticeKeyFromValue(SI.getCondition()));
if (SCValue == LatticeFunc->getOverdefinedVal() ||
SCValue == LatticeFunc->getUntrackedVal()) {
Succs.assign(TI.getNumSuccessors(), true);
return;
}
if (SCValue == LatticeFunc->getUndefVal())
return;
Constant *C = dyn_cast_or_null<Constant>(LatticeFunc->GetValueFromLatticeVal(
std::move(SCValue), SI.getCondition()->getType()));
if (!C || !isa<ConstantInt>(C)) {
Succs.assign(TI.getNumSuccessors(), true);
return;
}
SwitchInst::CaseHandle Case = *SI.findCaseValue(cast<ConstantInt>(C));
Succs[Case.getSuccessorIndex()] = true;
}
template <class LatticeKey, class LatticeVal, class KeyInfo>
bool SparseSolver<LatticeKey, LatticeVal, KeyInfo>::isEdgeFeasible(
BasicBlock *From, BasicBlock *To, bool AggressiveUndef) {
SmallVector<bool, 16> SuccFeasible;
Instruction *TI = From->getTerminator();
getFeasibleSuccessors(*TI, SuccFeasible, AggressiveUndef);
for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
if (TI->getSuccessor(i) == To && SuccFeasible[i])
return true;
return false;
}
template <class LatticeKey, class LatticeVal, class KeyInfo>
void SparseSolver<LatticeKey, LatticeVal, KeyInfo>::visitTerminator(
Instruction &TI) {
SmallVector<bool, 16> SuccFeasible;
getFeasibleSuccessors(TI, SuccFeasible, true);
BasicBlock *BB = TI.getParent();
for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
if (SuccFeasible[i])
markEdgeExecutable(BB, TI.getSuccessor(i));
}
template <class LatticeKey, class LatticeVal, class KeyInfo>
void SparseSolver<LatticeKey, LatticeVal, KeyInfo>::visitPHINode(PHINode &PN) {
if (LatticeFunc->IsSpecialCasedPHI(&PN)) {
DenseMap<LatticeKey, LatticeVal> ChangedValues;
LatticeFunc->ComputeInstructionState(PN, ChangedValues, *this);
for (auto &ChangedValue : ChangedValues)
if (ChangedValue.second != LatticeFunc->getUntrackedVal())
UpdateState(std::move(ChangedValue.first),
std::move(ChangedValue.second));
return;
}
LatticeKey Key = KeyInfo::getLatticeKeyFromValue(&PN);
LatticeVal PNIV = getValueState(Key);
LatticeVal Overdefined = LatticeFunc->getOverdefinedVal();
if (PNIV == Overdefined || PNIV == LatticeFunc->getUntrackedVal())
return;
if (PN.getNumIncomingValues() > 64) {
UpdateState(Key, Overdefined);
return;
}
for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
if (!isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent(), true))
continue;
LatticeVal OpVal =
getValueState(KeyInfo::getLatticeKeyFromValue(PN.getIncomingValue(i)));
if (OpVal != PNIV)
PNIV = LatticeFunc->MergeValues(PNIV, OpVal);
if (PNIV == Overdefined)
break; }
UpdateState(Key, PNIV);
}
template <class LatticeKey, class LatticeVal, class KeyInfo>
void SparseSolver<LatticeKey, LatticeVal, KeyInfo>::visitInst(Instruction &I) {
if (PHINode *PN = dyn_cast<PHINode>(&I))
return visitPHINode(*PN);
DenseMap<LatticeKey, LatticeVal> ChangedValues;
LatticeFunc->ComputeInstructionState(I, ChangedValues, *this);
for (auto &ChangedValue : ChangedValues)
if (ChangedValue.second != LatticeFunc->getUntrackedVal())
UpdateState(ChangedValue.first, ChangedValue.second);
if (I.isTerminator())
visitTerminator(I);
}
template <class LatticeKey, class LatticeVal, class KeyInfo>
void SparseSolver<LatticeKey, LatticeVal, KeyInfo>::Solve() {
while (!BBWorkList.empty() || !ValueWorkList.empty()) {
while (!ValueWorkList.empty()) {
Value *V = ValueWorkList.pop_back_val();
LLVM_DEBUG(dbgs() << "\nPopped off V-WL: " << *V << "\n");
for (User *U : V->users())
if (Instruction *Inst = dyn_cast<Instruction>(U))
if (BBExecutable.count(Inst->getParent())) visitInst(*Inst);
}
while (!BBWorkList.empty()) {
BasicBlock *BB = BBWorkList.pop_back_val();
LLVM_DEBUG(dbgs() << "\nPopped off BBWL: " << *BB);
for (Instruction &I : *BB)
visitInst(I);
}
}
}
template <class LatticeKey, class LatticeVal, class KeyInfo>
void SparseSolver<LatticeKey, LatticeVal, KeyInfo>::Print(
raw_ostream &OS) const {
if (ValueState.empty())
return;
LatticeKey Key;
LatticeVal LV;
OS << "ValueState:\n";
for (auto &Entry : ValueState) {
std::tie(Key, LV) = Entry;
if (LV == LatticeFunc->getUntrackedVal())
continue;
OS << "\t";
LatticeFunc->PrintLatticeVal(LV, OS);
OS << ": ";
LatticeFunc->PrintLatticeKey(Key, OS);
OS << "\n";
}
}
}
#undef DEBUG_TYPE
#endif