#include "llvm/Transforms/Scalar/MergedLoadStoreMotion.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Analysis/GlobalsModRef.h"
#include "llvm/IR/Instructions.h"
#include "llvm/InitializePasses.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
using namespace llvm;
#define DEBUG_TYPE "mldst-motion"
namespace {
class MergedLoadStoreMotion {
AliasAnalysis *AA = nullptr;
const int MagicCompileTimeControl = 250;
const bool SplitFooterBB;
public:
MergedLoadStoreMotion(bool SplitFooterBB) : SplitFooterBB(SplitFooterBB) {}
bool run(Function &F, AliasAnalysis &AA);
private:
BasicBlock *getDiamondTail(BasicBlock *BB);
bool isDiamondHead(BasicBlock *BB);
StoreInst *canSinkFromBlock(BasicBlock *BB, StoreInst *SI);
PHINode *getPHIOperand(BasicBlock *BB, StoreInst *S0, StoreInst *S1);
bool isStoreSinkBarrierInRange(const Instruction &Start,
const Instruction &End, MemoryLocation Loc);
bool canSinkStoresAndGEPs(StoreInst *S0, StoreInst *S1) const;
void sinkStoresAndGEPs(BasicBlock *BB, StoreInst *SinkCand,
StoreInst *ElseInst);
bool mergeStores(BasicBlock *BB);
};
}
BasicBlock *MergedLoadStoreMotion::getDiamondTail(BasicBlock *BB) {
assert(isDiamondHead(BB) && "Basic block is not head of a diamond");
return BB->getTerminator()->getSuccessor(0)->getSingleSuccessor();
}
bool MergedLoadStoreMotion::isDiamondHead(BasicBlock *BB) {
if (!BB)
return false;
auto *BI = dyn_cast<BranchInst>(BB->getTerminator());
if (!BI || !BI->isConditional())
return false;
BasicBlock *Succ0 = BI->getSuccessor(0);
BasicBlock *Succ1 = BI->getSuccessor(1);
if (!Succ0->getSinglePredecessor())
return false;
if (!Succ1->getSinglePredecessor())
return false;
BasicBlock *Succ0Succ = Succ0->getSingleSuccessor();
BasicBlock *Succ1Succ = Succ1->getSingleSuccessor();
if (!Succ0Succ || !Succ1Succ || Succ0Succ != Succ1Succ)
return false;
return true;
}
bool MergedLoadStoreMotion::isStoreSinkBarrierInRange(const Instruction &Start,
const Instruction &End,
MemoryLocation Loc) {
for (const Instruction &Inst :
make_range(Start.getIterator(), End.getIterator()))
if (Inst.mayThrow())
return true;
return AA->canInstructionRangeModRef(Start, End, Loc, ModRefInfo::ModRef);
}
StoreInst *MergedLoadStoreMotion::canSinkFromBlock(BasicBlock *BB1,
StoreInst *Store0) {
LLVM_DEBUG(dbgs() << "can Sink? : "; Store0->dump(); dbgs() << "\n");
BasicBlock *BB0 = Store0->getParent();
for (Instruction &Inst : reverse(*BB1)) {
auto *Store1 = dyn_cast<StoreInst>(&Inst);
if (!Store1)
continue;
MemoryLocation Loc0 = MemoryLocation::get(Store0);
MemoryLocation Loc1 = MemoryLocation::get(Store1);
if (AA->isMustAlias(Loc0, Loc1) && Store0->isSameOperationAs(Store1) &&
!isStoreSinkBarrierInRange(*Store1->getNextNode(), BB1->back(), Loc1) &&
!isStoreSinkBarrierInRange(*Store0->getNextNode(), BB0->back(), Loc0)) {
return Store1;
}
}
return nullptr;
}
PHINode *MergedLoadStoreMotion::getPHIOperand(BasicBlock *BB, StoreInst *S0,
StoreInst *S1) {
Value *Opd1 = S0->getValueOperand();
Value *Opd2 = S1->getValueOperand();
if (Opd1 == Opd2)
return nullptr;
auto *NewPN = PHINode::Create(Opd1->getType(), 2, Opd2->getName() + ".sink",
&BB->front());
NewPN->applyMergedLocation(S0->getDebugLoc(), S1->getDebugLoc());
NewPN->addIncoming(Opd1, S0->getParent());
NewPN->addIncoming(Opd2, S1->getParent());
return NewPN;
}
bool MergedLoadStoreMotion::canSinkStoresAndGEPs(StoreInst *S0,
StoreInst *S1) const {
auto *A0 = dyn_cast<Instruction>(S0->getPointerOperand());
auto *A1 = dyn_cast<Instruction>(S1->getPointerOperand());
return A0 && A1 && A0->isIdenticalTo(A1) && A0->hasOneUse() &&
(A0->getParent() == S0->getParent()) && A1->hasOneUse() &&
(A1->getParent() == S1->getParent()) && isa<GetElementPtrInst>(A0);
}
void MergedLoadStoreMotion::sinkStoresAndGEPs(BasicBlock *BB, StoreInst *S0,
StoreInst *S1) {
auto *A0 = dyn_cast<Instruction>(S0->getPointerOperand());
auto *A1 = dyn_cast<Instruction>(S1->getPointerOperand());
LLVM_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->andIRFlags(S1);
S0->dropUnknownNonDebugMetadata();
StoreInst *SNew = cast<StoreInst>(S0->clone());
Instruction *ANew = A0->clone();
SNew->insertBefore(&*InsertPt);
ANew->insertBefore(SNew);
assert(S0->getParent() == A0->getParent());
assert(S1->getParent() == A1->getParent());
if (PHINode *NewPN = getPHIOperand(BB, S0, S1))
SNew->setOperand(0, NewPN);
S0->eraseFromParent();
S1->eraseFromParent();
A0->replaceAllUsesWith(ANew);
A0->eraseFromParent();
A1->replaceAllUsesWith(ANew);
A1->eraseFromParent();
}
bool MergedLoadStoreMotion::mergeStores(BasicBlock *HeadBB) {
bool MergedStores = false;
BasicBlock *TailBB = getDiamondTail(HeadBB);
BasicBlock *SinkBB = TailBB;
assert(SinkBB && "Footer of a diamond cannot be empty");
succ_iterator SI = succ_begin(HeadBB);
assert(SI != succ_end(HeadBB) && "Diamond head cannot have zero successors");
BasicBlock *Pred0 = *SI;
++SI;
assert(SI != succ_end(HeadBB) && "Diamond head cannot have single successor");
BasicBlock *Pred1 = *SI;
if (Pred0 == Pred1)
return false; if (!SplitFooterBB && TailBB->hasNPredecessorsOrMore(3))
return false;
auto InstsNoDbg = Pred1->instructionsWithoutDebug();
int Size1 = std::distance(InstsNoDbg.begin(), InstsNoDbg.end());
int NStores = 0;
for (BasicBlock::reverse_iterator RBI = Pred0->rbegin(), RBE = Pred0->rend();
RBI != RBE;) {
Instruction *I = &*RBI;
++RBI;
auto *S0 = dyn_cast<StoreInst>(I);
if (!S0 || !S0->isSimple())
continue;
++NStores;
if (NStores * Size1 >= MagicCompileTimeControl)
break;
if (StoreInst *S1 = canSinkFromBlock(Pred1, S0)) {
if (!canSinkStoresAndGEPs(S0, S1))
break;
if (SinkBB == TailBB && TailBB->hasNPredecessorsOrMore(3)) {
SinkBB = SplitBlockPredecessors(TailBB, {Pred0, Pred1}, ".sink.split");
if (!SinkBB)
break;
}
MergedStores = true;
sinkStoresAndGEPs(SinkBB, S0, S1);
RBI = Pred0->rbegin();
RBE = Pred0->rend();
LLVM_DEBUG(dbgs() << "Search again\n"; Instruction *I = &*RBI; I->dump());
}
}
return MergedStores;
}
bool MergedLoadStoreMotion::run(Function &F, AliasAnalysis &AA) {
this->AA = &AA;
bool Changed = false;
LLVM_DEBUG(dbgs() << "Instruction Merger\n");
for (BasicBlock &BB : make_early_inc_range(F))
if (isDiamondHead(&BB))
Changed |= mergeStores(&BB);
return Changed;
}
namespace {
class MergedLoadStoreMotionLegacyPass : public FunctionPass {
const bool SplitFooterBB;
public:
static char ID; MergedLoadStoreMotionLegacyPass(bool SplitFooterBB = false)
: FunctionPass(ID), SplitFooterBB(SplitFooterBB) {
initializeMergedLoadStoreMotionLegacyPassPass(
*PassRegistry::getPassRegistry());
}
bool runOnFunction(Function &F) override {
if (skipFunction(F))
return false;
MergedLoadStoreMotion Impl(SplitFooterBB);
return Impl.run(F, getAnalysis<AAResultsWrapperPass>().getAAResults());
}
private:
void getAnalysisUsage(AnalysisUsage &AU) const override {
if (!SplitFooterBB)
AU.setPreservesCFG();
AU.addRequired<AAResultsWrapperPass>();
AU.addPreserved<GlobalsAAWrapperPass>();
}
};
char MergedLoadStoreMotionLegacyPass::ID = 0;
}
FunctionPass *llvm::createMergedLoadStoreMotionPass(bool SplitFooterBB) {
return new MergedLoadStoreMotionLegacyPass(SplitFooterBB);
}
INITIALIZE_PASS_BEGIN(MergedLoadStoreMotionLegacyPass, "mldst-motion",
"MergedLoadStoreMotion", false, false)
INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
INITIALIZE_PASS_END(MergedLoadStoreMotionLegacyPass, "mldst-motion",
"MergedLoadStoreMotion", false, false)
PreservedAnalyses
MergedLoadStoreMotionPass::run(Function &F, FunctionAnalysisManager &AM) {
MergedLoadStoreMotion Impl(Options.SplitFooterBB);
auto &AA = AM.getResult<AAManager>(F);
if (!Impl.run(F, AA))
return PreservedAnalyses::all();
PreservedAnalyses PA;
if (!Options.SplitFooterBB)
PA.preserveSet<CFGAnalyses>();
return PA;
}
void MergedLoadStoreMotionPass::printPipeline(
raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
static_cast<PassInfoMixin<MergedLoadStoreMotionPass> *>(this)->printPipeline(
OS, MapClassName2PassName);
OS << "<";
OS << (Options.SplitFooterBB ? "" : "no-") << "split-footer-bb";
OS << ">";
}