ConstantHoisting.cpp [plain text]
#include "llvm/Transforms/Scalar.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/Pass.h"
#include "llvm/Support/Debug.h"
#include <tuple>
using namespace llvm;
#define DEBUG_TYPE "consthoist"
STATISTIC(NumConstantsHoisted, "Number of constants hoisted");
STATISTIC(NumConstantsRebased, "Number of constants rebased");
namespace {
struct ConstantUser;
struct RebasedConstantInfo;
typedef SmallVector<ConstantUser, 8> ConstantUseListType;
typedef SmallVector<RebasedConstantInfo, 4> RebasedConstantListType;
struct ConstantUser {
Instruction *Inst;
unsigned OpndIdx;
ConstantUser(Instruction *Inst, unsigned Idx) : Inst(Inst), OpndIdx(Idx) { }
};
struct ConstantCandidate {
ConstantUseListType Uses;
ConstantInt *ConstInt;
unsigned CumulativeCost;
ConstantCandidate(ConstantInt *ConstInt)
: ConstInt(ConstInt), CumulativeCost(0) { }
void addUser(Instruction *Inst, unsigned Idx, unsigned Cost) {
CumulativeCost += Cost;
Uses.push_back(ConstantUser(Inst, Idx));
}
};
struct RebasedConstantInfo {
ConstantUseListType Uses;
Constant *Offset;
RebasedConstantInfo(ConstantUseListType &&Uses, Constant *Offset)
: Uses(std::move(Uses)), Offset(Offset) { }
};
struct ConstantInfo {
ConstantInt *BaseConstant;
RebasedConstantListType RebasedConstants;
};
class ConstantHoisting : public FunctionPass {
typedef DenseMap<ConstantInt *, unsigned> ConstCandMapType;
typedef std::vector<ConstantCandidate> ConstCandVecType;
const TargetTransformInfo *TTI;
DominatorTree *DT;
BasicBlock *Entry;
ConstCandVecType ConstCandVec;
SmallDenseMap<Instruction *, Instruction *> ClonedCastMap;
SmallVector<ConstantInfo, 8> ConstantVec;
public:
static char ID; ConstantHoisting() : FunctionPass(ID), TTI(nullptr), DT(nullptr),
Entry(nullptr) {
initializeConstantHoistingPass(*PassRegistry::getPassRegistry());
}
bool runOnFunction(Function &Fn) override;
const char *getPassName() const override { return "Constant Hoisting"; }
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.setPreservesCFG();
AU.addRequired<DominatorTreeWrapperPass>();
AU.addRequired<TargetTransformInfoWrapperPass>();
}
private:
void setup(Function &Fn) {
DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(Fn);
Entry = &Fn.getEntryBlock();
}
void cleanup() {
ConstantVec.clear();
ClonedCastMap.clear();
ConstCandVec.clear();
TTI = nullptr;
DT = nullptr;
Entry = nullptr;
}
Instruction *findMatInsertPt(Instruction *Inst, unsigned Idx = ~0U) const;
Instruction *findConstantInsertionPoint(const ConstantInfo &ConstInfo) const;
void collectConstantCandidates(ConstCandMapType &ConstCandMap,
Instruction *Inst, unsigned Idx,
ConstantInt *ConstInt);
void collectConstantCandidates(ConstCandMapType &ConstCandMap,
Instruction *Inst);
void collectConstantCandidates(Function &Fn);
void findAndMakeBaseConstant(ConstCandVecType::iterator S,
ConstCandVecType::iterator E);
void findBaseConstants();
void emitBaseConstants(Instruction *Base, Constant *Offset,
const ConstantUser &ConstUser);
bool emitBaseConstants();
void deleteDeadCastInst() const;
bool optimizeConstants(Function &Fn);
};
}
char ConstantHoisting::ID = 0;
INITIALIZE_PASS_BEGIN(ConstantHoisting, "consthoist", "Constant Hoisting",
false, false)
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
INITIALIZE_PASS_END(ConstantHoisting, "consthoist", "Constant Hoisting",
false, false)
FunctionPass *llvm::createConstantHoistingPass() {
return new ConstantHoisting();
}
bool ConstantHoisting::runOnFunction(Function &Fn) {
DEBUG(dbgs() << "********** Begin Constant Hoisting **********\n");
DEBUG(dbgs() << "********** Function: " << Fn.getName() << '\n');
setup(Fn);
bool MadeChange = optimizeConstants(Fn);
if (MadeChange) {
DEBUG(dbgs() << "********** Function after Constant Hoisting: "
<< Fn.getName() << '\n');
DEBUG(dbgs() << Fn);
}
DEBUG(dbgs() << "********** End Constant Hoisting **********\n");
cleanup();
return MadeChange;
}
Instruction *ConstantHoisting::findMatInsertPt(Instruction *Inst,
unsigned Idx) const {
if (Idx != ~0U) {
Value *Opnd = Inst->getOperand(Idx);
if (auto CastInst = dyn_cast<Instruction>(Opnd))
if (CastInst->isCast())
return CastInst;
}
if (!isa<PHINode>(Inst) && !isa<LandingPadInst>(Inst))
return Inst;
assert(Entry != Inst->getParent() && "PHI or landing pad in entry block!");
if (Idx != ~0U && isa<PHINode>(Inst))
return cast<PHINode>(Inst)->getIncomingBlock(Idx)->getTerminator();
BasicBlock *IDom = DT->getNode(Inst->getParent())->getIDom()->getBlock();
return IDom->getTerminator();
}
Instruction *ConstantHoisting::
findConstantInsertionPoint(const ConstantInfo &ConstInfo) const {
assert(!ConstInfo.RebasedConstants.empty() && "Invalid constant info entry.");
SmallPtrSet<BasicBlock *, 8> BBs;
for (auto const &RCI : ConstInfo.RebasedConstants)
for (auto const &U : RCI.Uses)
BBs.insert(findMatInsertPt(U.Inst, U.OpndIdx)->getParent());
if (BBs.count(Entry))
return &Entry->front();
while (BBs.size() >= 2) {
BasicBlock *BB, *BB1, *BB2;
BB1 = *BBs.begin();
BB2 = *std::next(BBs.begin());
BB = DT->findNearestCommonDominator(BB1, BB2);
if (BB == Entry)
return &Entry->front();
BBs.erase(BB1);
BBs.erase(BB2);
BBs.insert(BB);
}
assert((BBs.size() == 1) && "Expected only one element.");
Instruction &FirstInst = (*BBs.begin())->front();
return findMatInsertPt(&FirstInst);
}
void ConstantHoisting::collectConstantCandidates(ConstCandMapType &ConstCandMap,
Instruction *Inst,
unsigned Idx,
ConstantInt *ConstInt) {
unsigned Cost;
if (auto IntrInst = dyn_cast<IntrinsicInst>(Inst))
Cost = TTI->getIntImmCost(IntrInst->getIntrinsicID(), Idx,
ConstInt->getValue(), ConstInt->getType());
else
Cost = TTI->getIntImmCost(Inst->getOpcode(), Idx, ConstInt->getValue(),
ConstInt->getType());
if (Cost > TargetTransformInfo::TCC_Basic) {
ConstCandMapType::iterator Itr;
bool Inserted;
std::tie(Itr, Inserted) = ConstCandMap.insert(std::make_pair(ConstInt, 0));
if (Inserted) {
ConstCandVec.push_back(ConstantCandidate(ConstInt));
Itr->second = ConstCandVec.size() - 1;
}
ConstCandVec[Itr->second].addUser(Inst, Idx, Cost);
DEBUG(if (isa<ConstantInt>(Inst->getOperand(Idx)))
dbgs() << "Collect constant " << *ConstInt << " from " << *Inst
<< " with cost " << Cost << '\n';
else
dbgs() << "Collect constant " << *ConstInt << " indirectly from "
<< *Inst << " via " << *Inst->getOperand(Idx) << " with cost "
<< Cost << '\n';
);
}
}
void ConstantHoisting::collectConstantCandidates(ConstCandMapType &ConstCandMap,
Instruction *Inst) {
if (Inst->isCast())
return;
if (auto Call = dyn_cast<CallInst>(Inst))
if (isa<InlineAsm>(Call->getCalledValue()))
return;
for (unsigned Idx = 0, E = Inst->getNumOperands(); Idx != E; ++Idx) {
Value *Opnd = Inst->getOperand(Idx);
if (auto ConstInt = dyn_cast<ConstantInt>(Opnd)) {
collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
continue;
}
if (auto CastInst = dyn_cast<Instruction>(Opnd)) {
if (!CastInst->isCast())
continue;
if (auto *ConstInt = dyn_cast<ConstantInt>(CastInst->getOperand(0))) {
collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
continue;
}
}
if (auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) {
if (!ConstExpr->isCast())
continue;
if (auto ConstInt = dyn_cast<ConstantInt>(ConstExpr->getOperand(0))) {
collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
continue;
}
}
} }
void ConstantHoisting::collectConstantCandidates(Function &Fn) {
ConstCandMapType ConstCandMap;
for (Function::iterator BB : Fn)
for (BasicBlock::iterator Inst : *BB)
collectConstantCandidates(ConstCandMap, Inst);
}
void ConstantHoisting::findAndMakeBaseConstant(ConstCandVecType::iterator S,
ConstCandVecType::iterator E) {
auto MaxCostItr = S;
unsigned NumUses = 0;
for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
NumUses += ConstCand->Uses.size();
if (ConstCand->CumulativeCost > MaxCostItr->CumulativeCost)
MaxCostItr = ConstCand;
}
if (NumUses <= 1)
return;
ConstantInfo ConstInfo;
ConstInfo.BaseConstant = MaxCostItr->ConstInt;
Type *Ty = ConstInfo.BaseConstant->getType();
for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
APInt Diff = ConstCand->ConstInt->getValue() -
ConstInfo.BaseConstant->getValue();
Constant *Offset = Diff == 0 ? nullptr : ConstantInt::get(Ty, Diff);
ConstInfo.RebasedConstants.push_back(
RebasedConstantInfo(std::move(ConstCand->Uses), Offset));
}
ConstantVec.push_back(std::move(ConstInfo));
}
void ConstantHoisting::findBaseConstants() {
std::sort(ConstCandVec.begin(), ConstCandVec.end(),
[](const ConstantCandidate &LHS, const ConstantCandidate &RHS) {
if (LHS.ConstInt->getType() != RHS.ConstInt->getType())
return LHS.ConstInt->getType()->getBitWidth() <
RHS.ConstInt->getType()->getBitWidth();
return LHS.ConstInt->getValue().ult(RHS.ConstInt->getValue());
});
auto MinValItr = ConstCandVec.begin();
for (auto CC = std::next(ConstCandVec.begin()), E = ConstCandVec.end();
CC != E; ++CC) {
if (MinValItr->ConstInt->getType() == CC->ConstInt->getType()) {
APInt Diff = CC->ConstInt->getValue() - MinValItr->ConstInt->getValue();
if ((Diff.getBitWidth() <= 64) &&
TTI->isLegalAddImmediate(Diff.getSExtValue()))
continue;
}
findAndMakeBaseConstant(MinValItr, CC);
MinValItr = CC;
}
findAndMakeBaseConstant(MinValItr, ConstCandVec.end());
}
static bool updateOperand(Instruction *Inst, unsigned Idx, Instruction *Mat) {
if (auto PHI = dyn_cast<PHINode>(Inst)) {
BasicBlock *IncomingBB = PHI->getIncomingBlock(Idx);
for (unsigned i = 0; i < Idx; ++i) {
if (PHI->getIncomingBlock(i) == IncomingBB) {
Value *IncomingVal = PHI->getIncomingValue(i);
Inst->setOperand(Idx, IncomingVal);
return false;
}
}
}
Inst->setOperand(Idx, Mat);
return true;
}
void ConstantHoisting::emitBaseConstants(Instruction *Base, Constant *Offset,
const ConstantUser &ConstUser) {
Instruction *Mat = Base;
if (Offset) {
Instruction *InsertionPt = findMatInsertPt(ConstUser.Inst,
ConstUser.OpndIdx);
Mat = BinaryOperator::Create(Instruction::Add, Base, Offset,
"const_mat", InsertionPt);
DEBUG(dbgs() << "Materialize constant (" << *Base->getOperand(0)
<< " + " << *Offset << ") in BB "
<< Mat->getParent()->getName() << '\n' << *Mat << '\n');
Mat->setDebugLoc(ConstUser.Inst->getDebugLoc());
}
Value *Opnd = ConstUser.Inst->getOperand(ConstUser.OpndIdx);
if (isa<ConstantInt>(Opnd)) {
DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
if (!updateOperand(ConstUser.Inst, ConstUser.OpndIdx, Mat) && Offset)
Mat->eraseFromParent();
DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
return;
}
if (auto CastInst = dyn_cast<Instruction>(Opnd)) {
assert(CastInst->isCast() && "Expected an cast instruction!");
Instruction *&ClonedCastInst = ClonedCastMap[CastInst];
if (!ClonedCastInst) {
ClonedCastInst = CastInst->clone();
ClonedCastInst->setOperand(0, Mat);
ClonedCastInst->insertAfter(CastInst);
ClonedCastInst->setDebugLoc(CastInst->getDebugLoc());
DEBUG(dbgs() << "Clone instruction: " << *CastInst << '\n'
<< "To : " << *ClonedCastInst << '\n');
}
DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
updateOperand(ConstUser.Inst, ConstUser.OpndIdx, ClonedCastInst);
DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
return;
}
if (auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) {
Instruction *ConstExprInst = ConstExpr->getAsInstruction();
ConstExprInst->setOperand(0, Mat);
ConstExprInst->insertBefore(findMatInsertPt(ConstUser.Inst,
ConstUser.OpndIdx));
ConstExprInst->setDebugLoc(ConstUser.Inst->getDebugLoc());
DEBUG(dbgs() << "Create instruction: " << *ConstExprInst << '\n'
<< "From : " << *ConstExpr << '\n');
DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
if (!updateOperand(ConstUser.Inst, ConstUser.OpndIdx, ConstExprInst)) {
ConstExprInst->eraseFromParent();
if (Offset)
Mat->eraseFromParent();
}
DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
return;
}
}
bool ConstantHoisting::emitBaseConstants() {
bool MadeChange = false;
for (auto const &ConstInfo : ConstantVec) {
Instruction *IP = findConstantInsertionPoint(ConstInfo);
IntegerType *Ty = ConstInfo.BaseConstant->getType();
Instruction *Base =
new BitCastInst(ConstInfo.BaseConstant, Ty, "const", IP);
DEBUG(dbgs() << "Hoist constant (" << *ConstInfo.BaseConstant << ") to BB "
<< IP->getParent()->getName() << '\n' << *Base << '\n');
NumConstantsHoisted++;
for (auto const &RCI : ConstInfo.RebasedConstants) {
NumConstantsRebased++;
for (auto const &U : RCI.Uses)
emitBaseConstants(Base, RCI.Offset, U);
}
assert(!Base->use_empty() && "The use list is empty!?");
assert(isa<Instruction>(Base->user_back()) &&
"All uses should be instructions.");
Base->setDebugLoc(cast<Instruction>(Base->user_back())->getDebugLoc());
NumConstantsRebased--;
MadeChange = true;
}
return MadeChange;
}
void ConstantHoisting::deleteDeadCastInst() const {
for (auto const &I : ClonedCastMap)
if (I.first->use_empty())
I.first->eraseFromParent();
}
bool ConstantHoisting::optimizeConstants(Function &Fn) {
collectConstantCandidates(Fn);
if (ConstCandVec.empty())
return false;
findBaseConstants();
if (ConstantVec.empty())
return false;
bool MadeChange = emitBaseConstants();
deleteDeadCastInst();
return MadeChange;
}