#include "llvm/Transforms/IPO/CalledValuePropagation.h"
#include "llvm/Analysis/SparsePropagation.h"
#include "llvm/Analysis/ValueLatticeUtils.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/MDBuilder.h"
#include "llvm/InitializePasses.h"
#include "llvm/Pass.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Transforms/IPO.h"
using namespace llvm;
#define DEBUG_TYPE "called-value-propagation"
static cl::opt<unsigned> MaxFunctionsPerValue(
"cvp-max-functions-per-value", cl::Hidden, cl::init(4),
cl::desc("The maximum number of functions to track per lattice value"));
namespace {
enum class IPOGrouping { Register, Return, Memory };
using CVPLatticeKey = PointerIntPair<Value *, 2, IPOGrouping>;
class CVPLatticeVal {
public:
enum CVPLatticeStateTy { Undefined, FunctionSet, Overdefined, Untracked };
struct Compare {
bool operator()(const Function *LHS, const Function *RHS) const {
return LHS->getName() < RHS->getName();
}
};
CVPLatticeVal() = default;
CVPLatticeVal(CVPLatticeStateTy LatticeState) : LatticeState(LatticeState) {}
CVPLatticeVal(std::vector<Function *> &&Functions)
: LatticeState(FunctionSet), Functions(std::move(Functions)) {
assert(llvm::is_sorted(this->Functions, Compare()));
}
const std::vector<Function *> &getFunctions() const {
return Functions;
}
bool isFunctionSet() const { return LatticeState == FunctionSet; }
bool operator==(const CVPLatticeVal &RHS) const {
return LatticeState == RHS.LatticeState && Functions == RHS.Functions;
}
bool operator!=(const CVPLatticeVal &RHS) const {
return LatticeState != RHS.LatticeState || Functions != RHS.Functions;
}
private:
CVPLatticeStateTy LatticeState = Undefined;
std::vector<Function *> Functions;
};
class CVPLatticeFunc
: public AbstractLatticeFunction<CVPLatticeKey, CVPLatticeVal> {
public:
CVPLatticeFunc()
: AbstractLatticeFunction(CVPLatticeVal(CVPLatticeVal::Undefined),
CVPLatticeVal(CVPLatticeVal::Overdefined),
CVPLatticeVal(CVPLatticeVal::Untracked)) {}
CVPLatticeVal ComputeLatticeVal(CVPLatticeKey Key) override {
switch (Key.getInt()) {
case IPOGrouping::Register:
if (isa<Instruction>(Key.getPointer())) {
return getUndefVal();
} else if (auto *A = dyn_cast<Argument>(Key.getPointer())) {
if (canTrackArgumentsInterprocedurally(A->getParent()))
return getUndefVal();
} else if (auto *C = dyn_cast<Constant>(Key.getPointer())) {
return computeConstant(C);
}
return getOverdefinedVal();
case IPOGrouping::Memory:
case IPOGrouping::Return:
if (auto *GV = dyn_cast<GlobalVariable>(Key.getPointer())) {
if (canTrackGlobalVariableInterprocedurally(GV))
return computeConstant(GV->getInitializer());
} else if (auto *F = cast<Function>(Key.getPointer()))
if (canTrackReturnsInterprocedurally(F))
return getUndefVal();
}
return getOverdefinedVal();
}
CVPLatticeVal MergeValues(CVPLatticeVal X, CVPLatticeVal Y) override {
if (X == getOverdefinedVal() || Y == getOverdefinedVal())
return getOverdefinedVal();
if (X == getUndefVal() && Y == getUndefVal())
return getUndefVal();
std::vector<Function *> Union;
std::set_union(X.getFunctions().begin(), X.getFunctions().end(),
Y.getFunctions().begin(), Y.getFunctions().end(),
std::back_inserter(Union), CVPLatticeVal::Compare{});
if (Union.size() > MaxFunctionsPerValue)
return getOverdefinedVal();
return CVPLatticeVal(std::move(Union));
}
void ComputeInstructionState(
Instruction &I, DenseMap<CVPLatticeKey, CVPLatticeVal> &ChangedValues,
SparseSolver<CVPLatticeKey, CVPLatticeVal> &SS) override {
switch (I.getOpcode()) {
case Instruction::Call:
case Instruction::Invoke:
return visitCallBase(cast<CallBase>(I), ChangedValues, SS);
case Instruction::Load:
return visitLoad(*cast<LoadInst>(&I), ChangedValues, SS);
case Instruction::Ret:
return visitReturn(*cast<ReturnInst>(&I), ChangedValues, SS);
case Instruction::Select:
return visitSelect(*cast<SelectInst>(&I), ChangedValues, SS);
case Instruction::Store:
return visitStore(*cast<StoreInst>(&I), ChangedValues, SS);
default:
return visitInst(I, ChangedValues, SS);
}
}
void PrintLatticeVal(CVPLatticeVal LV, raw_ostream &OS) override {
if (LV == getUndefVal())
OS << "Undefined ";
else if (LV == getOverdefinedVal())
OS << "Overdefined";
else if (LV == getUntrackedVal())
OS << "Untracked ";
else
OS << "FunctionSet";
}
void PrintLatticeKey(CVPLatticeKey Key, raw_ostream &OS) override {
if (Key.getInt() == IPOGrouping::Register)
OS << "<reg> ";
else if (Key.getInt() == IPOGrouping::Memory)
OS << "<mem> ";
else if (Key.getInt() == IPOGrouping::Return)
OS << "<ret> ";
if (isa<Function>(Key.getPointer()))
OS << Key.getPointer()->getName();
else
OS << *Key.getPointer();
}
SmallPtrSetImpl<CallBase *> &getIndirectCalls() { return IndirectCalls; }
private:
SmallPtrSet<CallBase *, 32> IndirectCalls;
CVPLatticeVal computeConstant(Constant *C) {
if (isa<ConstantPointerNull>(C))
return CVPLatticeVal(CVPLatticeVal::FunctionSet);
if (auto *F = dyn_cast<Function>(C->stripPointerCasts()))
return CVPLatticeVal({F});
return getOverdefinedVal();
}
void visitReturn(ReturnInst &I,
DenseMap<CVPLatticeKey, CVPLatticeVal> &ChangedValues,
SparseSolver<CVPLatticeKey, CVPLatticeVal> &SS) {
Function *F = I.getParent()->getParent();
if (F->getReturnType()->isVoidTy())
return;
auto RegI = CVPLatticeKey(I.getReturnValue(), IPOGrouping::Register);
auto RetF = CVPLatticeKey(F, IPOGrouping::Return);
ChangedValues[RetF] =
MergeValues(SS.getValueState(RegI), SS.getValueState(RetF));
}
void visitCallBase(CallBase &CB,
DenseMap<CVPLatticeKey, CVPLatticeVal> &ChangedValues,
SparseSolver<CVPLatticeKey, CVPLatticeVal> &SS) {
Function *F = CB.getCalledFunction();
auto RegI = CVPLatticeKey(&CB, IPOGrouping::Register);
if (!F)
IndirectCalls.insert(&CB);
if (!F || !canTrackReturnsInterprocedurally(F)) {
if (CB.getType()->isVoidTy())
return;
ChangedValues[RegI] = getOverdefinedVal();
return;
}
SS.MarkBlockExecutable(&F->front());
auto RetF = CVPLatticeKey(F, IPOGrouping::Return);
for (Argument &A : F->args()) {
auto RegFormal = CVPLatticeKey(&A, IPOGrouping::Register);
auto RegActual =
CVPLatticeKey(CB.getArgOperand(A.getArgNo()), IPOGrouping::Register);
ChangedValues[RegFormal] =
MergeValues(SS.getValueState(RegFormal), SS.getValueState(RegActual));
}
if (CB.getType()->isVoidTy())
return;
ChangedValues[RegI] =
MergeValues(SS.getValueState(RegI), SS.getValueState(RetF));
}
void visitSelect(SelectInst &I,
DenseMap<CVPLatticeKey, CVPLatticeVal> &ChangedValues,
SparseSolver<CVPLatticeKey, CVPLatticeVal> &SS) {
auto RegI = CVPLatticeKey(&I, IPOGrouping::Register);
auto RegT = CVPLatticeKey(I.getTrueValue(), IPOGrouping::Register);
auto RegF = CVPLatticeKey(I.getFalseValue(), IPOGrouping::Register);
ChangedValues[RegI] =
MergeValues(SS.getValueState(RegT), SS.getValueState(RegF));
}
void visitLoad(LoadInst &I,
DenseMap<CVPLatticeKey, CVPLatticeVal> &ChangedValues,
SparseSolver<CVPLatticeKey, CVPLatticeVal> &SS) {
auto RegI = CVPLatticeKey(&I, IPOGrouping::Register);
if (auto *GV = dyn_cast<GlobalVariable>(I.getPointerOperand())) {
auto MemGV = CVPLatticeKey(GV, IPOGrouping::Memory);
ChangedValues[RegI] =
MergeValues(SS.getValueState(RegI), SS.getValueState(MemGV));
} else {
ChangedValues[RegI] = getOverdefinedVal();
}
}
void visitStore(StoreInst &I,
DenseMap<CVPLatticeKey, CVPLatticeVal> &ChangedValues,
SparseSolver<CVPLatticeKey, CVPLatticeVal> &SS) {
auto *GV = dyn_cast<GlobalVariable>(I.getPointerOperand());
if (!GV)
return;
auto RegI = CVPLatticeKey(I.getValueOperand(), IPOGrouping::Register);
auto MemGV = CVPLatticeKey(GV, IPOGrouping::Memory);
ChangedValues[MemGV] =
MergeValues(SS.getValueState(RegI), SS.getValueState(MemGV));
}
void visitInst(Instruction &I,
DenseMap<CVPLatticeKey, CVPLatticeVal> &ChangedValues,
SparseSolver<CVPLatticeKey, CVPLatticeVal> &SS) {
if (I.use_empty())
return;
auto RegI = CVPLatticeKey(&I, IPOGrouping::Register);
ChangedValues[RegI] = getOverdefinedVal();
}
};
}
namespace llvm {
template <> struct LatticeKeyInfo<CVPLatticeKey> {
static inline Value *getValueFromLatticeKey(CVPLatticeKey Key) {
return Key.getPointer();
}
static inline CVPLatticeKey getLatticeKeyFromValue(Value *V) {
return CVPLatticeKey(V, IPOGrouping::Register);
}
};
}
static bool runCVP(Module &M) {
CVPLatticeFunc Lattice;
SparseSolver<CVPLatticeKey, CVPLatticeVal> Solver(&Lattice);
for (Function &F : M)
if (!F.isDeclaration() && !canTrackArgumentsInterprocedurally(&F))
Solver.MarkBlockExecutable(&F.front());
Solver.Solve();
bool Changed = false;
MDBuilder MDB(M.getContext());
for (CallBase *C : Lattice.getIndirectCalls()) {
auto RegI = CVPLatticeKey(C->getCalledOperand(), IPOGrouping::Register);
CVPLatticeVal LV = Solver.getExistingValueState(RegI);
if (!LV.isFunctionSet() || LV.getFunctions().empty())
continue;
MDNode *Callees = MDB.createCallees(LV.getFunctions());
C->setMetadata(LLVMContext::MD_callees, Callees);
Changed = true;
}
return Changed;
}
PreservedAnalyses CalledValuePropagationPass::run(Module &M,
ModuleAnalysisManager &) {
runCVP(M);
return PreservedAnalyses::all();
}
namespace {
class CalledValuePropagationLegacyPass : public ModulePass {
public:
static char ID;
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.setPreservesAll();
}
CalledValuePropagationLegacyPass() : ModulePass(ID) {
initializeCalledValuePropagationLegacyPassPass(
*PassRegistry::getPassRegistry());
}
bool runOnModule(Module &M) override {
if (skipModule(M))
return false;
return runCVP(M);
}
};
}
char CalledValuePropagationLegacyPass::ID = 0;
INITIALIZE_PASS(CalledValuePropagationLegacyPass, "called-value-propagation",
"Called Value Propagation", false, false)
ModulePass *llvm::createCalledValuePropagationPass() {
return new CalledValuePropagationLegacyPass();
}