MergedLoadStoreMotion.cpp [plain text]
#include "llvm/Transforms/Scalar.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Analysis/CFG.h"
#include "llvm/Analysis/Loads.h"
#include "llvm/Analysis/MemoryBuiltins.h"
#include "llvm/Analysis/MemoryDependenceAnalysis.h"
#include "llvm/IR/Metadata.h"
#include "llvm/IR/PatternMatch.h"
#include "llvm/Support/Allocator.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Target/TargetLibraryInfo.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include "llvm/Transforms/Utils/SSAUpdater.h"
#include <vector>
using namespace llvm;
#define DEBUG_TYPE "mldst-motion"
static cl::opt<bool>
EnableMLSM("mlsm", cl::desc("Enable motion of merged load and store"),
cl::init(true));
namespace {
class MergedLoadStoreMotion : public FunctionPass {
AliasAnalysis *AA;
MemoryDependenceAnalysis *MD;
public:
static char ID; explicit MergedLoadStoreMotion(void)
: FunctionPass(ID), MD(nullptr), MagicCompileTimeControl(250) {
initializeMergedLoadStoreMotionPass(*PassRegistry::getPassRegistry());
}
bool runOnFunction(Function &F) override;
private:
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequired<TargetLibraryInfo>();
AU.addRequired<MemoryDependenceAnalysis>();
AU.addRequired<AliasAnalysis>();
AU.addPreserved<AliasAnalysis>();
}
void removeInstruction(Instruction *Inst);
BasicBlock *getDiamondTail(BasicBlock *BB);
bool isDiamondHead(BasicBlock *BB);
bool isLoadHoistBarrier(Instruction *Inst);
LoadInst *canHoistFromBlock(BasicBlock *BB, LoadInst *LI);
void hoistInstruction(BasicBlock *BB, Instruction *HoistCand,
Instruction *ElseInst);
bool isSafeToHoist(Instruction *I) const;
bool hoistLoad(BasicBlock *BB, LoadInst *HoistCand, LoadInst *ElseInst);
bool mergeLoads(BasicBlock *BB);
StoreInst *canSinkFromBlock(BasicBlock *BB, StoreInst *SI);
PHINode *getPHIOperand(BasicBlock *BB, StoreInst *S0, StoreInst *S1);
bool isStoreSinkBarrier(Instruction *Inst);
bool sinkStore(BasicBlock *BB, StoreInst *SinkCand, StoreInst *ElseInst);
bool mergeStores(BasicBlock *BB);
const int MagicCompileTimeControl;
};
char MergedLoadStoreMotion::ID = 0;
}
FunctionPass *llvm::createMergedLoadStoreMotionPass() {
return new MergedLoadStoreMotion();
}
INITIALIZE_PASS_BEGIN(MergedLoadStoreMotion, "mldst-motion",
"MergedLoadStoreMotion", false, false)
INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
INITIALIZE_PASS_END(MergedLoadStoreMotion, "mldst-motion",
"MergedLoadStoreMotion", false, false)
void MergedLoadStoreMotion::removeInstruction(Instruction *Inst) {
if (MD) {
MD->removeInstruction(Inst);
if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
MD->invalidateCachedPointerInfo(LI->getPointerOperand());
if (Inst->getType()->getScalarType()->isPointerTy()) {
MD->invalidateCachedPointerInfo(Inst);
}
}
Inst->eraseFromParent();
}
BasicBlock *MergedLoadStoreMotion::getDiamondTail(BasicBlock *BB) {
assert(isDiamondHead(BB) && "Basic block is not head of a diamond");
BranchInst *BI = (BranchInst *)(BB->getTerminator());
BasicBlock *Succ0 = BI->getSuccessor(0);
BasicBlock *Tail = Succ0->getTerminator()->getSuccessor(0);
return Tail;
}
bool MergedLoadStoreMotion::isDiamondHead(BasicBlock *BB) {
if (!BB)
return false;
if (!isa<BranchInst>(BB->getTerminator()))
return false;
if (BB->getTerminator()->getNumSuccessors() != 2)
return false;
BranchInst *BI = (BranchInst *)(BB->getTerminator());
BasicBlock *Succ0 = BI->getSuccessor(0);
BasicBlock *Succ1 = BI->getSuccessor(1);
if (!Succ0->getSinglePredecessor() ||
Succ0->getTerminator()->getNumSuccessors() != 1)
return false;
if (!Succ1->getSinglePredecessor() ||
Succ1->getTerminator()->getNumSuccessors() != 1)
return false;
BasicBlock *Tail = Succ0->getTerminator()->getSuccessor(0);
if (Succ1->getTerminator()->getSuccessor(0) != Tail)
return false;
return true;
}
bool MergedLoadStoreMotion::isLoadHoistBarrier(Instruction *Inst) {
if (isa<CallInst>(Inst))
return true;
if (isa<TerminatorInst>(Inst))
return true;
if (isa<StoreInst>(Inst))
return true;
if (Inst->mayHaveSideEffects()) {
return true;
}
DEBUG(dbgs() << "No Hoist Barrier\n");
return false;
}
LoadInst *MergedLoadStoreMotion::canHoistFromBlock(BasicBlock *BB,
LoadInst *LI) {
LoadInst *I = nullptr;
assert(isa<LoadInst>(LI));
if (LI->isUsedOutsideOfBlock(LI->getParent()))
return nullptr;
for (BasicBlock::iterator BBI = BB->begin(), BBE = BB->end(); BBI != BBE;
++BBI) {
Instruction *Inst = BBI;
if (isLoadHoistBarrier(Inst))
break;
if (!isa<LoadInst>(Inst))
continue;
if (Inst->isUsedOutsideOfBlock(Inst->getParent()))
continue;
AliasAnalysis::Location LocLI = AA->getLocation(LI);
AliasAnalysis::Location LocInst = AA->getLocation((LoadInst *)Inst);
if (AA->isMustAlias(LocLI, LocInst) && LI->getType() == Inst->getType()) {
I = (LoadInst *)Inst;
break;
}
}
return I;
}
void MergedLoadStoreMotion::hoistInstruction(BasicBlock *BB,
Instruction *HoistCand,
Instruction *ElseInst) {
DEBUG(dbgs() << " Hoist Instruction into BB \n"; BB->dump();
dbgs() << "Instruction Left\n"; HoistCand->dump(); dbgs() << "\n";
dbgs() << "Instruction Right\n"; ElseInst->dump(); dbgs() << "\n");
assert(HoistCand->getParent() != BB);
HoistCand->intersectOptionalDataWith(ElseInst);
HoistCand->dropUnknownMetadata();
Instruction *HoistPt = BB->getTerminator();
Instruction *HoistedInst = HoistCand->clone();
if (isa<LoadInst>(HoistCand))
AA->copyValue(HoistCand, HoistedInst);
HoistedInst->insertBefore(HoistPt);
HoistCand->replaceAllUsesWith(HoistedInst);
removeInstruction(HoistCand);
ElseInst->replaceAllUsesWith(HoistedInst);
removeInstruction(ElseInst);
}
bool MergedLoadStoreMotion::isSafeToHoist(Instruction *I) const {
BasicBlock *Parent = I->getParent();
for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
Instruction *Instr = dyn_cast<Instruction>(I->getOperand(i));
if (Instr && Instr->getParent() == Parent)
return false;
}
return true;
}
bool MergedLoadStoreMotion::hoistLoad(BasicBlock *BB, LoadInst *L0,
LoadInst *L1) {
Instruction *A0 = dyn_cast<Instruction>(L0->getPointerOperand());
Instruction *A1 = dyn_cast<Instruction>(L1->getPointerOperand());
if (A0 && A1 && A0->isIdenticalTo(A1) && isSafeToHoist(A0) &&
A0->hasOneUse() && (A0->getParent() == L0->getParent()) &&
A1->hasOneUse() && (A1->getParent() == L1->getParent()) &&
isa<GetElementPtrInst>(A0)) {
DEBUG(dbgs() << "Hoist Instruction into BB \n"; BB->dump();
dbgs() << "Instruction Left\n"; L0->dump(); dbgs() << "\n";
dbgs() << "Instruction Right\n"; L1->dump(); dbgs() << "\n");
hoistInstruction(BB, A0, A1);
hoistInstruction(BB, L0, L1);
return true;
} else
return false;
}
bool MergedLoadStoreMotion::mergeLoads(BasicBlock *BB) {
bool MergedLoads = false;
assert(isDiamondHead(BB));
BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
BasicBlock *Succ0 = BI->getSuccessor(0);
BasicBlock *Succ1 = BI->getSuccessor(1);
int Size1 = Succ1->size();
int NLoads = 0;
for (BasicBlock::iterator BBI = Succ0->begin(), BBE = Succ0->end();
BBI != BBE;) {
Instruction *I = BBI;
++BBI;
if (isLoadHoistBarrier(I))
break;
if (!isa<LoadInst>(I))
continue;
LoadInst *L0 = (LoadInst *)I;
if (!L0->isSimple())
continue;
++NLoads;
if (NLoads * Size1 >= MagicCompileTimeControl)
break;
if (LoadInst *L1 = canHoistFromBlock(Succ1, L0)) {
bool Res = hoistLoad(BB, L0, L1);
MergedLoads |= Res;
if (!Res)
break;
}
}
return MergedLoads;
}
bool MergedLoadStoreMotion::isStoreSinkBarrier(Instruction *Inst) {
if (isa<LoadInst>(Inst))
return true;
if (isa<CallInst>(Inst))
return true;
if (isa<TerminatorInst>(Inst) && !isa<BranchInst>(Inst))
return true;
if (!isa<StoreInst>(Inst) && Inst->mayHaveSideEffects()) {
return true;
}
DEBUG(dbgs() << "No Sink Barrier\n");
return false;
}
StoreInst *MergedLoadStoreMotion::canSinkFromBlock(BasicBlock *BB,
StoreInst *SI) {
StoreInst *I = 0;
DEBUG(dbgs() << "can Sink? : "; SI->dump(); dbgs() << "\n");
for (BasicBlock::reverse_iterator RBI = BB->rbegin(), RBE = BB->rend();
RBI != RBE; ++RBI) {
Instruction *Inst = &*RBI;
if (isStoreSinkBarrier(Inst))
break;
if (isa<StoreInst>(Inst)) {
AliasAnalysis::Location LocSI = AA->getLocation(SI);
AliasAnalysis::Location LocInst = AA->getLocation((StoreInst *)Inst);
if (AA->isMustAlias(LocSI, LocInst)) {
I = (StoreInst *)Inst;
break;
}
}
}
return I;
}
PHINode *MergedLoadStoreMotion::getPHIOperand(BasicBlock *BB, StoreInst *S0,
StoreInst *S1) {
PHINode *NewPN = 0;
Value *Opd1 = S0->getValueOperand();
Value *Opd2 = S1->getValueOperand();
if (Opd1 != Opd2) {
NewPN = PHINode::Create(Opd1->getType(), 2, Opd2->getName() + ".sink",
BB->begin());
NewPN->addIncoming(Opd1, S0->getParent());
NewPN->addIncoming(Opd2, S1->getParent());
if (NewPN->getType()->getScalarType()->isPointerTy()) {
AA->copyValue(Opd1, NewPN);
AA->copyValue(Opd2, NewPN);
for (unsigned I = 0, E = NewPN->getNumIncomingValues(); I != E; ++I) {
unsigned J = PHINode::getOperandNumForIncomingValue(I);
AA->addEscapingUse(NewPN->getOperandUse(J));
}
if (MD)
MD->invalidateCachedPointerInfo(NewPN);
}
}
return NewPN;
}
bool MergedLoadStoreMotion::sinkStore(BasicBlock *BB, StoreInst *S0,
StoreInst *S1) {
Instruction *A0 = dyn_cast<Instruction>(S0->getPointerOperand());
Instruction *A1 = dyn_cast<Instruction>(S1->getPointerOperand());
if (A0 && A1 && A0->isIdenticalTo(A1) && A0->hasOneUse() &&
(A0->getParent() == S0->getParent()) && A1->hasOneUse() &&
(A1->getParent() == S1->getParent()) && isa<GetElementPtrInst>(A0)) {
DEBUG(dbgs() << "Sink Instruction into BB \n"; BB->dump();
dbgs() << "Instruction Left\n"; S0->dump(); dbgs() << "\n";
dbgs() << "Instruction Right\n"; S1->dump(); dbgs() << "\n");
BasicBlock::iterator InsertPt = BB->getFirstInsertionPt();
S0->intersectOptionalDataWith(S1);
S0->dropUnknownMetadata();
StoreInst *SNew = (StoreInst *)(S0->clone());
Instruction *ANew = A0->clone();
AA->copyValue(S0, SNew);
SNew->insertBefore(InsertPt);
ANew->insertBefore(SNew);
assert(S0->getParent() == A0->getParent());
assert(S1->getParent() == A1->getParent());
PHINode *NewPN = getPHIOperand(BB, S0, S1);
if (NewPN)
SNew->setOperand(0, NewPN);
removeInstruction(S0);
removeInstruction(S1);
A0->replaceAllUsesWith(ANew);
removeInstruction(A0);
A1->replaceAllUsesWith(ANew);
removeInstruction(A1);
return true;
}
return false;
}
bool MergedLoadStoreMotion::mergeStores(BasicBlock *T) {
bool MergedStores = false;
assert(T && "Footer of a diamond cannot be empty");
pred_iterator PI = pred_begin(T), E = pred_end(T);
assert(PI != E);
BasicBlock *Pred0 = *PI;
++PI;
BasicBlock *Pred1 = *PI;
++PI;
if (Pred0 == Pred1)
return false; if (PI != E)
return false;
int Size1 = Pred1->size();
int NStores = 0;
for (BasicBlock::reverse_iterator RBI = Pred0->rbegin(), RBE = Pred0->rend();
RBI != RBE;) {
Instruction *I = &*RBI;
++RBI;
if (isStoreSinkBarrier(I))
break;
if (!isa<StoreInst>(I))
continue;
StoreInst *S0 = (StoreInst *)I;
if (!S0->isSimple())
continue;
++NStores;
if (NStores * Size1 >= MagicCompileTimeControl)
break;
if (StoreInst *S1 = canSinkFromBlock(Pred1, S0)) {
bool Res = sinkStore(T, S0, S1);
MergedStores |= Res;
if (!Res)
break;
else {
RBI = Pred0->rbegin();
RBE = Pred0->rend();
DEBUG(dbgs() << "Search again\n"; Instruction *I = &*RBI; I->dump());
}
}
}
return MergedStores;
}
bool MergedLoadStoreMotion::runOnFunction(Function &F) {
MD = &getAnalysis<MemoryDependenceAnalysis>();
AA = &getAnalysis<AliasAnalysis>();
bool Changed = false;
if (!EnableMLSM)
return false;
DEBUG(dbgs() << "Instruction Merger\n");
for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
BasicBlock *BB = FI++;
if (isDiamondHead(BB)) {
Changed |= mergeLoads(BB);
Changed |= mergeStores(getDiamondTail(BB));
}
}
return Changed;
}