#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/iterator_range.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Analysis/GlobalsModRef.h"
#include "llvm/Analysis/IteratedDominanceFrontier.h"
#include "llvm/Analysis/MemoryDependenceAnalysis.h"
#include "llvm/Analysis/MemorySSA.h"
#include "llvm/Analysis/MemorySSAUpdater.h"
#include "llvm/Analysis/PostDominators.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/IR/Argument.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/CFG.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/PassManager.h"
#include "llvm/IR/Use.h"
#include "llvm/IR/User.h"
#include "llvm/IR/Value.h"
#include "llvm/InitializePasses.h"
#include "llvm/Pass.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Scalar/GVN.h"
#include "llvm/Transforms/Utils/Local.h"
#include <algorithm>
#include <cassert>
#include <iterator>
#include <memory>
#include <utility>
#include <vector>
using namespace llvm;
#define DEBUG_TYPE "gvn-hoist"
STATISTIC(NumHoisted, "Number of instructions hoisted");
STATISTIC(NumRemoved, "Number of instructions removed");
STATISTIC(NumLoadsHoisted, "Number of loads hoisted");
STATISTIC(NumLoadsRemoved, "Number of loads removed");
STATISTIC(NumStoresHoisted, "Number of stores hoisted");
STATISTIC(NumStoresRemoved, "Number of stores removed");
STATISTIC(NumCallsHoisted, "Number of calls hoisted");
STATISTIC(NumCallsRemoved, "Number of calls removed");
static cl::opt<int>
MaxHoistedThreshold("gvn-max-hoisted", cl::Hidden, cl::init(-1),
cl::desc("Max number of instructions to hoist "
"(default unlimited = -1)"));
static cl::opt<int> MaxNumberOfBBSInPath(
"gvn-hoist-max-bbs", cl::Hidden, cl::init(4),
cl::desc("Max number of basic blocks on the path between "
"hoisting locations (default = 4, unlimited = -1)"));
static cl::opt<int> MaxDepthInBB(
"gvn-hoist-max-depth", cl::Hidden, cl::init(100),
cl::desc("Hoist instructions from the beginning of the BB up to the "
"maximum specified depth (default = 100, unlimited = -1)"));
static cl::opt<int>
MaxChainLength("gvn-hoist-max-chain-length", cl::Hidden, cl::init(10),
cl::desc("Maximum length of dependent chains to hoist "
"(default = 10, unlimited = -1)"));
namespace llvm {
using BBSideEffectsSet = DenseMap<const BasicBlock *, bool>;
using SmallVecInsn = SmallVector<Instruction *, 4>;
using SmallVecImplInsn = SmallVectorImpl<Instruction *>;
using HoistingPointInfo = std::pair<BasicBlock *, SmallVecInsn>;
using HoistingPointList = SmallVector<HoistingPointInfo, 4>;
using VNType = std::pair<unsigned, uintptr_t>;
using VNtoInsns = DenseMap<VNType, SmallVector<Instruction *, 4>>;
struct CHIArg {
VNType VN;
BasicBlock *Dest;
Instruction *I;
bool operator==(const CHIArg &A) const { return VN == A.VN; }
bool operator!=(const CHIArg &A) const { return !(*this == A); }
};
using CHIIt = SmallVectorImpl<CHIArg>::iterator;
using CHIArgs = iterator_range<CHIIt>;
using OutValuesType = DenseMap<BasicBlock *, SmallVector<CHIArg, 2>>;
using InValuesType =
DenseMap<BasicBlock *, SmallVector<std::pair<VNType, Instruction *>, 2>>;
enum : uintptr_t { InvalidVN = ~(uintptr_t)2 };
class InsnInfo {
VNtoInsns VNtoScalars;
public:
void insert(Instruction *I, GVNPass::ValueTable &VN) {
unsigned V = VN.lookupOrAdd(I);
VNtoScalars[{V, InvalidVN}].push_back(I);
}
const VNtoInsns &getVNTable() const { return VNtoScalars; }
};
class LoadInfo {
VNtoInsns VNtoLoads;
public:
void insert(LoadInst *Load, GVNPass::ValueTable &VN) {
if (Load->isSimple()) {
unsigned V = VN.lookupOrAdd(Load->getPointerOperand());
VNtoLoads[{V, (uintptr_t)Load->getType()}].push_back(Load);
}
}
const VNtoInsns &getVNTable() const { return VNtoLoads; }
};
class StoreInfo {
VNtoInsns VNtoStores;
public:
void insert(StoreInst *Store, GVNPass::ValueTable &VN) {
if (!Store->isSimple())
return;
Value *Ptr = Store->getPointerOperand();
Value *Val = Store->getValueOperand();
VNtoStores[{VN.lookupOrAdd(Ptr), VN.lookupOrAdd(Val)}].push_back(Store);
}
const VNtoInsns &getVNTable() const { return VNtoStores; }
};
class CallInfo {
VNtoInsns VNtoCallsScalars;
VNtoInsns VNtoCallsLoads;
VNtoInsns VNtoCallsStores;
public:
void insert(CallInst *Call, GVNPass::ValueTable &VN) {
unsigned V = VN.lookupOrAdd(Call);
auto Entry = std::make_pair(V, InvalidVN);
if (Call->doesNotAccessMemory())
VNtoCallsScalars[Entry].push_back(Call);
else if (Call->onlyReadsMemory())
VNtoCallsLoads[Entry].push_back(Call);
else
VNtoCallsStores[Entry].push_back(Call);
}
const VNtoInsns &getScalarVNTable() const { return VNtoCallsScalars; }
const VNtoInsns &getLoadVNTable() const { return VNtoCallsLoads; }
const VNtoInsns &getStoreVNTable() const { return VNtoCallsStores; }
};
static void combineKnownMetadata(Instruction *ReplInst, Instruction *I) {
static const unsigned KnownIDs[] = {LLVMContext::MD_tbaa,
LLVMContext::MD_alias_scope,
LLVMContext::MD_noalias,
LLVMContext::MD_range,
LLVMContext::MD_fpmath,
LLVMContext::MD_invariant_load,
LLVMContext::MD_invariant_group,
LLVMContext::MD_access_group};
combineMetadata(ReplInst, I, KnownIDs, true);
}
class GVNHoist {
public:
GVNHoist(DominatorTree *DT, PostDominatorTree *PDT, AliasAnalysis *AA,
MemoryDependenceResults *MD, MemorySSA *MSSA)
: DT(DT), PDT(PDT), AA(AA), MD(MD), MSSA(MSSA),
MSSAUpdater(std::make_unique<MemorySSAUpdater>(MSSA)) {
MSSA->ensureOptimizedUses();
}
bool run(Function &F);
unsigned int rank(const Value *V) const;
private:
GVNPass::ValueTable VN;
DominatorTree *DT;
PostDominatorTree *PDT;
AliasAnalysis *AA;
MemoryDependenceResults *MD;
MemorySSA *MSSA;
std::unique_ptr<MemorySSAUpdater> MSSAUpdater;
DenseMap<const Value *, unsigned> DFSNumber;
BBSideEffectsSet BBSideEffects;
DenseSet<const BasicBlock *> HoistBarrier;
SmallVector<BasicBlock *, 32> IDFBlocks;
unsigned NumFuncArgs;
const bool HoistingGeps = false;
enum InsKind { Unknown, Scalar, Load, Store };
bool hasEH(const BasicBlock *BB);
bool firstInBB(const Instruction *I1, const Instruction *I2) {
assert(I1->getParent() == I2->getParent());
unsigned I1DFS = DFSNumber.lookup(I1);
unsigned I2DFS = DFSNumber.lookup(I2);
assert(I1DFS && I2DFS);
return I1DFS < I2DFS;
}
bool hasMemoryUse(const Instruction *NewPt, MemoryDef *Def,
const BasicBlock *BB);
bool hasEHhelper(const BasicBlock *BB, const BasicBlock *SrcBB,
int &NBBsOnAllPaths);
bool hasEHOrLoadsOnPath(const Instruction *NewPt, MemoryDef *Def,
int &NBBsOnAllPaths);
bool hasEHOnPath(const BasicBlock *HoistPt, const BasicBlock *SrcBB,
int &NBBsOnAllPaths);
bool safeToHoistLdSt(const Instruction *NewPt, const Instruction *OldPt,
MemoryUseOrDef *U, InsKind K, int &NBBsOnAllPaths);
bool safeToHoistScalar(const BasicBlock *HoistBB, const BasicBlock *BB,
int &NBBsOnAllPaths) {
return !hasEHOnPath(HoistBB, BB, NBBsOnAllPaths);
}
bool valueAnticipable(CHIArgs C, Instruction *TI) const;
void checkSafety(CHIArgs C, BasicBlock *BB, InsKind K,
SmallVectorImpl<CHIArg> &Safe);
using RenameStackType = DenseMap<VNType, SmallVector<Instruction *, 2>>;
void fillRenameStack(BasicBlock *BB, InValuesType &ValueBBs,
RenameStackType &RenameStack);
void fillChiArgs(BasicBlock *BB, OutValuesType &CHIBBs,
RenameStackType &RenameStack);
void insertCHI(InValuesType &ValueBBs, OutValuesType &CHIBBs) {
auto Root = PDT->getNode(nullptr);
if (!Root)
return;
for (auto Node : depth_first(Root)) {
BasicBlock *BB = Node->getBlock();
if (!BB)
continue;
RenameStackType RenameStack;
fillRenameStack(BB, ValueBBs, RenameStack);
fillChiArgs(BB, CHIBBs, RenameStack);
}
}
void findHoistableCandidates(OutValuesType &CHIBBs, InsKind K,
HoistingPointList &HPL);
void computeInsertionPoints(const VNtoInsns &Map, HoistingPointList &HPL,
InsKind K) {
std::vector<VNType> Ranks;
for (const auto &Entry : Map) {
Ranks.push_back(Entry.first);
}
llvm::sort(Ranks, [this, &Map](const VNType &r1, const VNType &r2) {
return (rank(*Map.lookup(r1).begin()) < rank(*Map.lookup(r2).begin()));
});
SmallVector<BasicBlock *, 2> IDFBlocks;
ReverseIDFCalculator IDFs(*PDT);
OutValuesType OutValue;
InValuesType InValue;
for (const auto &R : Ranks) {
const SmallVecInsn &V = Map.lookup(R);
if (V.size() < 2)
continue;
const VNType &VN = R;
SmallPtrSet<BasicBlock *, 2> VNBlocks;
for (auto &I : V) {
BasicBlock *BBI = I->getParent();
if (!hasEH(BBI))
VNBlocks.insert(BBI);
}
IDFs.setDefiningBlocks(VNBlocks);
IDFBlocks.clear();
IDFs.calculate(IDFBlocks);
for (unsigned i = 0; i < V.size(); ++i) {
InValue[V[i]->getParent()].push_back(std::make_pair(VN, V[i]));
}
CHIArg EmptyChi = {VN, nullptr, nullptr};
for (auto *IDFBB : IDFBlocks) {
for (unsigned i = 0; i < V.size(); ++i) {
if (DT->properlyDominates(IDFBB, V[i]->getParent())) {
OutValue[IDFBB].push_back(EmptyChi);
LLVM_DEBUG(dbgs() << "\nInserting a CHI for BB: "
<< IDFBB->getName() << ", for Insn: " << *V[i]);
}
}
}
}
insertCHI(InValue, OutValue);
findHoistableCandidates(OutValue, K, HPL);
}
bool allOperandsAvailable(const Instruction *I,
const BasicBlock *HoistPt) const;
bool allGepOperandsAvailable(const Instruction *I,
const BasicBlock *HoistPt) const;
void makeGepsAvailable(Instruction *Repl, BasicBlock *HoistPt,
const SmallVecInsn &InstructionsToHoist,
Instruction *Gep) const;
void updateAlignment(Instruction *I, Instruction *Repl);
unsigned rauw(const SmallVecInsn &Candidates, Instruction *Repl,
MemoryUseOrDef *NewMemAcc);
void raMPHIuw(MemoryUseOrDef *NewMemAcc);
unsigned removeAndReplace(const SmallVecInsn &Candidates, Instruction *Repl,
BasicBlock *DestBB, bool MoveAccess);
bool makeGepOperandsAvailable(Instruction *Repl, BasicBlock *HoistPt,
const SmallVecInsn &InstructionsToHoist) const;
std::pair<unsigned, unsigned> hoist(HoistingPointList &HPL);
std::pair<unsigned, unsigned> hoistExpressions(Function &F);
};
class GVNHoistLegacyPass : public FunctionPass {
public:
static char ID;
GVNHoistLegacyPass() : FunctionPass(ID) {
initializeGVNHoistLegacyPassPass(*PassRegistry::getPassRegistry());
}
bool runOnFunction(Function &F) override {
if (skipFunction(F))
return false;
auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
auto &PDT = getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree();
auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
auto &MD = getAnalysis<MemoryDependenceWrapperPass>().getMemDep();
auto &MSSA = getAnalysis<MemorySSAWrapperPass>().getMSSA();
GVNHoist G(&DT, &PDT, &AA, &MD, &MSSA);
return G.run(F);
}
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequired<DominatorTreeWrapperPass>();
AU.addRequired<PostDominatorTreeWrapperPass>();
AU.addRequired<AAResultsWrapperPass>();
AU.addRequired<MemoryDependenceWrapperPass>();
AU.addRequired<MemorySSAWrapperPass>();
AU.addPreserved<DominatorTreeWrapperPass>();
AU.addPreserved<MemorySSAWrapperPass>();
AU.addPreserved<GlobalsAAWrapperPass>();
}
};
bool GVNHoist::run(Function &F) {
NumFuncArgs = F.arg_size();
VN.setDomTree(DT);
VN.setAliasAnalysis(AA);
VN.setMemDep(MD);
bool Res = false;
unsigned BBI = 0;
for (const BasicBlock *BB : depth_first(&F.getEntryBlock())) {
DFSNumber[BB] = ++BBI;
unsigned I = 0;
for (auto &Inst : *BB)
DFSNumber[&Inst] = ++I;
}
int ChainLength = 0;
while (true) {
if (MaxChainLength != -1 && ++ChainLength >= MaxChainLength)
return Res;
auto HoistStat = hoistExpressions(F);
if (HoistStat.first + HoistStat.second == 0)
return Res;
if (HoistStat.second > 0)
VN.clear();
Res = true;
}
return Res;
}
unsigned int GVNHoist::rank(const Value *V) const {
if (isa<ConstantExpr>(V))
return 2;
if (isa<UndefValue>(V))
return 1;
if (isa<Constant>(V))
return 0;
else if (auto *A = dyn_cast<Argument>(V))
return 3 + A->getArgNo();
auto Result = DFSNumber.lookup(V);
if (Result > 0)
return 4 + NumFuncArgs + Result;
return ~0;
}
bool GVNHoist::hasEH(const BasicBlock *BB) {
auto It = BBSideEffects.find(BB);
if (It != BBSideEffects.end())
return It->second;
if (BB->isEHPad() || BB->hasAddressTaken()) {
BBSideEffects[BB] = true;
return true;
}
if (BB->getTerminator()->mayThrow()) {
BBSideEffects[BB] = true;
return true;
}
BBSideEffects[BB] = false;
return false;
}
bool GVNHoist::hasMemoryUse(const Instruction *NewPt, MemoryDef *Def,
const BasicBlock *BB) {
const MemorySSA::AccessList *Acc = MSSA->getBlockAccesses(BB);
if (!Acc)
return false;
Instruction *OldPt = Def->getMemoryInst();
const BasicBlock *OldBB = OldPt->getParent();
const BasicBlock *NewBB = NewPt->getParent();
bool ReachedNewPt = false;
for (const MemoryAccess &MA : *Acc)
if (const MemoryUse *MU = dyn_cast<MemoryUse>(&MA)) {
Instruction *Insn = MU->getMemoryInst();
if (BB == OldBB && firstInBB(OldPt, Insn))
break;
if (BB == NewBB) {
if (!ReachedNewPt) {
if (firstInBB(Insn, NewPt))
continue;
ReachedNewPt = true;
}
}
if (MemorySSAUtil::defClobbersUseOrDef(Def, MU, *AA))
return true;
}
return false;
}
bool GVNHoist::hasEHhelper(const BasicBlock *BB, const BasicBlock *SrcBB,
int &NBBsOnAllPaths) {
if (NBBsOnAllPaths == 0)
return true;
if (hasEH(BB))
return true;
if ((BB != SrcBB) && HoistBarrier.count(BB))
return true;
return false;
}
bool GVNHoist::hasEHOrLoadsOnPath(const Instruction *NewPt, MemoryDef *Def,
int &NBBsOnAllPaths) {
const BasicBlock *NewBB = NewPt->getParent();
const BasicBlock *OldBB = Def->getBlock();
assert(DT->dominates(NewBB, OldBB) && "invalid path");
assert(DT->dominates(Def->getDefiningAccess()->getBlock(), NewBB) &&
"def does not dominate new hoisting point");
for (auto I = idf_begin(OldBB), E = idf_end(OldBB); I != E;) {
const BasicBlock *BB = *I;
if (BB == NewBB) {
I.skipChildren();
continue;
}
if (hasEHhelper(BB, OldBB, NBBsOnAllPaths))
return true;
if (hasMemoryUse(NewPt, Def, BB))
return true;
if (NBBsOnAllPaths != -1)
--NBBsOnAllPaths;
++I;
}
return false;
}
bool GVNHoist::hasEHOnPath(const BasicBlock *HoistPt, const BasicBlock *SrcBB,
int &NBBsOnAllPaths) {
assert(DT->dominates(HoistPt, SrcBB) && "Invalid path");
for (auto I = idf_begin(SrcBB), E = idf_end(SrcBB); I != E;) {
const BasicBlock *BB = *I;
if (BB == HoistPt) {
I.skipChildren();
continue;
}
if (hasEHhelper(BB, SrcBB, NBBsOnAllPaths))
return true;
if (NBBsOnAllPaths != -1)
--NBBsOnAllPaths;
++I;
}
return false;
}
bool GVNHoist::safeToHoistLdSt(const Instruction *NewPt,
const Instruction *OldPt, MemoryUseOrDef *U,
GVNHoist::InsKind K, int &NBBsOnAllPaths) {
if (NewPt == OldPt)
return true;
const BasicBlock *NewBB = NewPt->getParent();
const BasicBlock *OldBB = OldPt->getParent();
const BasicBlock *UBB = U->getBlock();
MemoryAccess *D = U->getDefiningAccess();
BasicBlock *DBB = D->getBlock();
if (DT->properlyDominates(NewBB, DBB))
return false;
if (NewBB == DBB && !MSSA->isLiveOnEntryDef(D))
if (auto *UD = dyn_cast<MemoryUseOrDef>(D))
if (!firstInBB(UD->getMemoryInst(), NewPt))
return false;
if (K == InsKind::Store) {
if (hasEHOrLoadsOnPath(NewPt, cast<MemoryDef>(U), NBBsOnAllPaths))
return false;
} else if (hasEHOnPath(NewBB, OldBB, NBBsOnAllPaths))
return false;
if (UBB == NewBB) {
if (DT->properlyDominates(DBB, NewBB))
return true;
assert(UBB == DBB);
assert(MSSA->locallyDominates(D, U));
}
return true;
}
bool GVNHoist::valueAnticipable(CHIArgs C, Instruction *TI) const {
if (TI->getNumSuccessors() > (unsigned)size(C))
return false;
for (auto CHI : C) {
if (!llvm::is_contained(successors(TI), CHI.Dest))
return false;
}
return true;
}
void GVNHoist::checkSafety(CHIArgs C, BasicBlock *BB, GVNHoist::InsKind K,
SmallVectorImpl<CHIArg> &Safe) {
int NumBBsOnAllPaths = MaxNumberOfBBSInPath;
for (auto CHI : C) {
Instruction *Insn = CHI.I;
if (!Insn) continue;
if (K == InsKind::Scalar) {
if (safeToHoistScalar(BB, Insn->getParent(), NumBBsOnAllPaths))
Safe.push_back(CHI);
} else {
auto *T = BB->getTerminator();
if (MemoryUseOrDef *UD = MSSA->getMemoryAccess(Insn))
if (safeToHoistLdSt(T, Insn, UD, K, NumBBsOnAllPaths))
Safe.push_back(CHI);
}
}
}
void GVNHoist::fillRenameStack(BasicBlock *BB, InValuesType &ValueBBs,
GVNHoist::RenameStackType &RenameStack) {
auto it1 = ValueBBs.find(BB);
if (it1 != ValueBBs.end()) {
LLVM_DEBUG(dbgs() << "\nVisiting: " << BB->getName()
<< " for pushing instructions on stack";);
for (std::pair<VNType, Instruction *> &VI : reverse(it1->second)) {
LLVM_DEBUG(dbgs() << "\nPushing on stack: " << *VI.second);
RenameStack[VI.first].push_back(VI.second);
}
}
}
void GVNHoist::fillChiArgs(BasicBlock *BB, OutValuesType &CHIBBs,
GVNHoist::RenameStackType &RenameStack) {
for (auto Pred : predecessors(BB)) {
auto P = CHIBBs.find(Pred);
if (P == CHIBBs.end()) {
continue;
}
LLVM_DEBUG(dbgs() << "\nLooking at CHIs in: " << Pred->getName(););
auto &VCHI = P->second;
for (auto It = VCHI.begin(), E = VCHI.end(); It != E;) {
CHIArg &C = *It;
if (!C.Dest) {
auto si = RenameStack.find(C.VN);
if (si != RenameStack.end() && si->second.size() &&
DT->properlyDominates(Pred, si->second.back()->getParent())) {
C.Dest = BB; C.I = si->second.pop_back_val(); LLVM_DEBUG(dbgs()
<< "\nCHI Inserted in BB: " << C.Dest->getName() << *C.I
<< ", VN: " << C.VN.first << ", " << C.VN.second);
}
It = std::find_if(It, VCHI.end(), [It](CHIArg &A) { return A != *It; });
} else
++It;
}
}
}
void GVNHoist::findHoistableCandidates(OutValuesType &CHIBBs,
GVNHoist::InsKind K,
HoistingPointList &HPL) {
auto cmpVN = [](const CHIArg &A, const CHIArg &B) { return A.VN < B.VN; };
for (std::pair<BasicBlock *, SmallVector<CHIArg, 2>> &A : CHIBBs) {
BasicBlock *BB = A.first;
SmallVectorImpl<CHIArg> &CHIs = A.second;
llvm::stable_sort(CHIs, cmpVN);
auto TI = BB->getTerminator();
auto B = CHIs.begin();
auto PHIIt = llvm::find_if(CHIs, [B](CHIArg &A) { return A != *B; });
auto PrevIt = CHIs.begin();
while (PrevIt != PHIIt) {
SmallVector<CHIArg, 2> Safe;
checkSafety(make_range(PrevIt, PHIIt), BB, K, Safe);
if (valueAnticipable(make_range(Safe.begin(), Safe.end()), TI)) {
HPL.push_back({BB, SmallVecInsn()});
SmallVecInsn &V = HPL.back().second;
for (auto B : Safe)
V.push_back(B.I);
}
PrevIt = PHIIt;
PHIIt = std::find_if(PrevIt, CHIs.end(),
[PrevIt](CHIArg &A) { return A != *PrevIt; });
}
}
}
bool GVNHoist::allOperandsAvailable(const Instruction *I,
const BasicBlock *HoistPt) const {
for (const Use &Op : I->operands())
if (const auto *Inst = dyn_cast<Instruction>(&Op))
if (!DT->dominates(Inst->getParent(), HoistPt))
return false;
return true;
}
bool GVNHoist::allGepOperandsAvailable(const Instruction *I,
const BasicBlock *HoistPt) const {
for (const Use &Op : I->operands())
if (const auto *Inst = dyn_cast<Instruction>(&Op))
if (!DT->dominates(Inst->getParent(), HoistPt)) {
if (const GetElementPtrInst *GepOp =
dyn_cast<GetElementPtrInst>(Inst)) {
if (!allGepOperandsAvailable(GepOp, HoistPt))
return false;
} else {
return false;
}
}
return true;
}
void GVNHoist::makeGepsAvailable(Instruction *Repl, BasicBlock *HoistPt,
const SmallVecInsn &InstructionsToHoist,
Instruction *Gep) const {
assert(allGepOperandsAvailable(Gep, HoistPt) && "GEP operands not available");
Instruction *ClonedGep = Gep->clone();
for (unsigned i = 0, e = Gep->getNumOperands(); i != e; ++i)
if (Instruction *Op = dyn_cast<Instruction>(Gep->getOperand(i))) {
if (DT->dominates(Op->getParent(), HoistPt))
continue;
if (GetElementPtrInst *GepOp = dyn_cast<GetElementPtrInst>(Op))
makeGepsAvailable(ClonedGep, HoistPt, InstructionsToHoist, GepOp);
}
ClonedGep->insertBefore(HoistPt->getTerminator());
ClonedGep->dropUnknownNonDebugMetadata();
for (const Instruction *OtherInst : InstructionsToHoist) {
const GetElementPtrInst *OtherGep;
if (auto *OtherLd = dyn_cast<LoadInst>(OtherInst))
OtherGep = cast<GetElementPtrInst>(OtherLd->getPointerOperand());
else
OtherGep = cast<GetElementPtrInst>(
cast<StoreInst>(OtherInst)->getPointerOperand());
ClonedGep->andIRFlags(OtherGep);
}
Repl->replaceUsesOfWith(Gep, ClonedGep);
}
void GVNHoist::updateAlignment(Instruction *I, Instruction *Repl) {
if (auto *ReplacementLoad = dyn_cast<LoadInst>(Repl)) {
ReplacementLoad->setAlignment(
std::min(ReplacementLoad->getAlign(), cast<LoadInst>(I)->getAlign()));
++NumLoadsRemoved;
} else if (auto *ReplacementStore = dyn_cast<StoreInst>(Repl)) {
ReplacementStore->setAlignment(
std::min(ReplacementStore->getAlign(), cast<StoreInst>(I)->getAlign()));
++NumStoresRemoved;
} else if (auto *ReplacementAlloca = dyn_cast<AllocaInst>(Repl)) {
ReplacementAlloca->setAlignment(std::max(ReplacementAlloca->getAlign(),
cast<AllocaInst>(I)->getAlign()));
} else if (isa<CallInst>(Repl)) {
++NumCallsRemoved;
}
}
unsigned GVNHoist::rauw(const SmallVecInsn &Candidates, Instruction *Repl,
MemoryUseOrDef *NewMemAcc) {
unsigned NR = 0;
for (Instruction *I : Candidates) {
if (I != Repl) {
++NR;
updateAlignment(I, Repl);
if (NewMemAcc) {
MemoryAccess *OldMA = MSSA->getMemoryAccess(I);
OldMA->replaceAllUsesWith(NewMemAcc);
MSSAUpdater->removeMemoryAccess(OldMA);
}
Repl->andIRFlags(I);
combineKnownMetadata(Repl, I);
I->replaceAllUsesWith(Repl);
MD->removeInstruction(I);
I->eraseFromParent();
}
}
return NR;
}
void GVNHoist::raMPHIuw(MemoryUseOrDef *NewMemAcc) {
SmallPtrSet<MemoryPhi *, 4> UsePhis;
for (User *U : NewMemAcc->users())
if (MemoryPhi *Phi = dyn_cast<MemoryPhi>(U))
UsePhis.insert(Phi);
for (MemoryPhi *Phi : UsePhis) {
auto In = Phi->incoming_values();
if (llvm::all_of(In, [&](Use &U) { return U == NewMemAcc; })) {
Phi->replaceAllUsesWith(NewMemAcc);
MSSAUpdater->removeMemoryAccess(Phi);
}
}
}
unsigned GVNHoist::removeAndReplace(const SmallVecInsn &Candidates,
Instruction *Repl, BasicBlock *DestBB,
bool MoveAccess) {
MemoryUseOrDef *NewMemAcc = MSSA->getMemoryAccess(Repl);
if (MoveAccess && NewMemAcc) {
MSSAUpdater->moveToPlace(NewMemAcc, DestBB, MemorySSA::BeforeTerminator);
}
unsigned NR = rauw(Candidates, Repl, NewMemAcc);
if (NewMemAcc)
raMPHIuw(NewMemAcc);
return NR;
}
bool GVNHoist::makeGepOperandsAvailable(
Instruction *Repl, BasicBlock *HoistPt,
const SmallVecInsn &InstructionsToHoist) const {
GetElementPtrInst *Gep = nullptr;
Instruction *Val = nullptr;
if (auto *Ld = dyn_cast<LoadInst>(Repl)) {
Gep = dyn_cast<GetElementPtrInst>(Ld->getPointerOperand());
} else if (auto *St = dyn_cast<StoreInst>(Repl)) {
Gep = dyn_cast<GetElementPtrInst>(St->getPointerOperand());
Val = dyn_cast<Instruction>(St->getValueOperand());
if (Val) {
if (isa<GetElementPtrInst>(Val)) {
if (!allGepOperandsAvailable(Val, HoistPt))
return false;
} else if (!DT->dominates(Val->getParent(), HoistPt))
return false;
}
}
if (!Gep || !allGepOperandsAvailable(Gep, HoistPt))
return false;
makeGepsAvailable(Repl, HoistPt, InstructionsToHoist, Gep);
if (Val && isa<GetElementPtrInst>(Val))
makeGepsAvailable(Repl, HoistPt, InstructionsToHoist, Val);
return true;
}
std::pair<unsigned, unsigned> GVNHoist::hoist(HoistingPointList &HPL) {
unsigned NI = 0, NL = 0, NS = 0, NC = 0, NR = 0;
for (const HoistingPointInfo &HP : HPL) {
BasicBlock *DestBB = HP.first;
const SmallVecInsn &InstructionsToHoist = HP.second;
Instruction *Repl = nullptr;
for (Instruction *I : InstructionsToHoist)
if (I->getParent() == DestBB)
if (!Repl || firstInBB(I, Repl))
Repl = I;
bool MoveAccess = true;
if (Repl) {
assert(allOperandsAvailable(Repl, DestBB) &&
"instruction depends on operands that are not available");
MoveAccess = false;
} else {
Repl = InstructionsToHoist.front();
if (!allOperandsAvailable(Repl, DestBB)) {
if (HoistingGeps)
continue;
if (!makeGepOperandsAvailable(Repl, DestBB, InstructionsToHoist))
continue;
}
Instruction *Last = DestBB->getTerminator();
MD->removeInstruction(Repl);
Repl->moveBefore(Last);
DFSNumber[Repl] = DFSNumber[Last]++;
}
Repl->dropLocation();
NR += removeAndReplace(InstructionsToHoist, Repl, DestBB, MoveAccess);
if (isa<LoadInst>(Repl))
++NL;
else if (isa<StoreInst>(Repl))
++NS;
else if (isa<CallInst>(Repl))
++NC;
else ++NI;
}
if (MSSA && VerifyMemorySSA)
MSSA->verifyMemorySSA();
NumHoisted += NL + NS + NC + NI;
NumRemoved += NR;
NumLoadsHoisted += NL;
NumStoresHoisted += NS;
NumCallsHoisted += NC;
return {NI, NL + NC + NS};
}
std::pair<unsigned, unsigned> GVNHoist::hoistExpressions(Function &F) {
InsnInfo II;
LoadInfo LI;
StoreInfo SI;
CallInfo CI;
for (BasicBlock *BB : depth_first(&F.getEntryBlock())) {
int InstructionNb = 0;
for (Instruction &I1 : *BB) {
if (!isGuaranteedToTransferExecutionToSuccessor(&I1)) {
HoistBarrier.insert(BB);
break;
}
if (MaxDepthInBB != -1 && InstructionNb++ >= MaxDepthInBB)
break;
if (I1.isTerminator())
break;
if (auto *Load = dyn_cast<LoadInst>(&I1))
LI.insert(Load, VN);
else if (auto *Store = dyn_cast<StoreInst>(&I1))
SI.insert(Store, VN);
else if (auto *Call = dyn_cast<CallInst>(&I1)) {
if (auto *Intr = dyn_cast<IntrinsicInst>(Call)) {
if (isa<DbgInfoIntrinsic>(Intr) ||
Intr->getIntrinsicID() == Intrinsic::assume ||
Intr->getIntrinsicID() == Intrinsic::sideeffect)
continue;
}
if (Call->mayHaveSideEffects())
break;
if (Call->isConvergent())
break;
CI.insert(Call, VN);
} else if (HoistingGeps || !isa<GetElementPtrInst>(&I1))
II.insert(&I1, VN);
}
}
HoistingPointList HPL;
computeInsertionPoints(II.getVNTable(), HPL, InsKind::Scalar);
computeInsertionPoints(LI.getVNTable(), HPL, InsKind::Load);
computeInsertionPoints(SI.getVNTable(), HPL, InsKind::Store);
computeInsertionPoints(CI.getScalarVNTable(), HPL, InsKind::Scalar);
computeInsertionPoints(CI.getLoadVNTable(), HPL, InsKind::Load);
computeInsertionPoints(CI.getStoreVNTable(), HPL, InsKind::Store);
return hoist(HPL);
}
}
PreservedAnalyses GVNHoistPass::run(Function &F, FunctionAnalysisManager &AM) {
DominatorTree &DT = AM.getResult<DominatorTreeAnalysis>(F);
PostDominatorTree &PDT = AM.getResult<PostDominatorTreeAnalysis>(F);
AliasAnalysis &AA = AM.getResult<AAManager>(F);
MemoryDependenceResults &MD = AM.getResult<MemoryDependenceAnalysis>(F);
MemorySSA &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
GVNHoist G(&DT, &PDT, &AA, &MD, &MSSA);
if (!G.run(F))
return PreservedAnalyses::all();
PreservedAnalyses PA;
PA.preserve<DominatorTreeAnalysis>();
PA.preserve<MemorySSAAnalysis>();
return PA;
}
char GVNHoistLegacyPass::ID = 0;
INITIALIZE_PASS_BEGIN(GVNHoistLegacyPass, "gvn-hoist",
"Early GVN Hoisting of Expressions", false, false)
INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass)
INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
INITIALIZE_PASS_END(GVNHoistLegacyPass, "gvn-hoist",
"Early GVN Hoisting of Expressions", false, false)
FunctionPass *llvm::createGVNHoistPass() { return new GVNHoistLegacyPass(); }