#include "llvm/Transforms/Scalar/Sink.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/IR/Dominators.h"
#include "llvm/InitializePasses.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Scalar.h"
using namespace llvm;
#define DEBUG_TYPE "sink"
STATISTIC(NumSunk, "Number of instructions sunk");
STATISTIC(NumSinkIter, "Number of sinking iterations");
static bool isSafeToMove(Instruction *Inst, AliasAnalysis &AA,
SmallPtrSetImpl<Instruction *> &Stores) {
if (Inst->mayWriteToMemory()) {
Stores.insert(Inst);
return false;
}
if (LoadInst *L = dyn_cast<LoadInst>(Inst)) {
MemoryLocation Loc = MemoryLocation::get(L);
for (Instruction *S : Stores)
if (isModSet(AA.getModRefInfo(S, Loc)))
return false;
}
if (Inst->isTerminator() || isa<PHINode>(Inst) || Inst->isEHPad() ||
Inst->mayThrow() || !Inst->willReturn())
return false;
if (auto *Call = dyn_cast<CallBase>(Inst)) {
if (Call->isConvergent())
return false;
for (Instruction *S : Stores)
if (isModSet(AA.getModRefInfo(S, Call)))
return false;
}
return true;
}
static bool IsAcceptableTarget(Instruction *Inst, BasicBlock *SuccToSinkTo,
DominatorTree &DT, LoopInfo &LI) {
assert(Inst && "Instruction to be sunk is null");
assert(SuccToSinkTo && "Candidate sink target is null");
if (SuccToSinkTo->getTerminator()->isExceptionalTerminator())
return false;
if (SuccToSinkTo->getUniquePredecessor() != Inst->getParent()) {
if (Inst->mayReadFromMemory())
return false;
if (!DT.dominates(Inst->getParent(), SuccToSinkTo))
return false;
Loop *succ = LI.getLoopFor(SuccToSinkTo);
Loop *cur = LI.getLoopFor(Inst->getParent());
if (succ != nullptr && succ != cur)
return false;
}
return true;
}
static bool SinkInstruction(Instruction *Inst,
SmallPtrSetImpl<Instruction *> &Stores,
DominatorTree &DT, LoopInfo &LI, AAResults &AA) {
if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
if (AI->isStaticAlloca())
return false;
if (!isSafeToMove(Inst, AA, Stores))
return false;
BasicBlock *SuccToSinkTo = nullptr;
BasicBlock *BB = Inst->getParent();
for (Use &U : Inst->uses()) {
Instruction *UseInst = cast<Instruction>(U.getUser());
BasicBlock *UseBlock = UseInst->getParent();
if (!DT.isReachableFromEntry(UseBlock))
continue;
if (PHINode *PN = dyn_cast<PHINode>(UseInst)) {
unsigned Num = PHINode::getIncomingValueNumForOperand(U.getOperandNo());
UseBlock = PN->getIncomingBlock(Num);
}
if (SuccToSinkTo)
SuccToSinkTo = DT.findNearestCommonDominator(SuccToSinkTo, UseBlock);
else
SuccToSinkTo = UseBlock;
if (!DT.dominates(BB, SuccToSinkTo))
return false;
}
if (SuccToSinkTo) {
while (SuccToSinkTo != BB &&
!IsAcceptableTarget(Inst, SuccToSinkTo, DT, LI))
SuccToSinkTo = DT.getNode(SuccToSinkTo)->getIDom()->getBlock();
if (SuccToSinkTo == BB)
SuccToSinkTo = nullptr;
}
if (!SuccToSinkTo)
return false;
LLVM_DEBUG(dbgs() << "Sink" << *Inst << " (";
Inst->getParent()->printAsOperand(dbgs(), false); dbgs() << " -> ";
SuccToSinkTo->printAsOperand(dbgs(), false); dbgs() << ")\n");
Inst->moveBefore(&*SuccToSinkTo->getFirstInsertionPt());
return true;
}
static bool ProcessBlock(BasicBlock &BB, DominatorTree &DT, LoopInfo &LI,
AAResults &AA) {
if (BB.getTerminator()->getNumSuccessors() <= 1) return false;
if (!DT.isReachableFromEntry(&BB)) return false;
bool MadeChange = false;
BasicBlock::iterator I = BB.end();
--I;
bool ProcessedBegin = false;
SmallPtrSet<Instruction *, 8> Stores;
do {
Instruction *Inst = &*I;
ProcessedBegin = I == BB.begin();
if (!ProcessedBegin)
--I;
if (Inst->isDebugOrPseudoInst())
continue;
if (SinkInstruction(Inst, Stores, DT, LI, AA)) {
++NumSunk;
MadeChange = true;
}
} while (!ProcessedBegin);
return MadeChange;
}
static bool iterativelySinkInstructions(Function &F, DominatorTree &DT,
LoopInfo &LI, AAResults &AA) {
bool MadeChange, EverMadeChange = false;
do {
MadeChange = false;
LLVM_DEBUG(dbgs() << "Sinking iteration " << NumSinkIter << "\n");
for (BasicBlock &I : F)
MadeChange |= ProcessBlock(I, DT, LI, AA);
EverMadeChange |= MadeChange;
NumSinkIter++;
} while (MadeChange);
return EverMadeChange;
}
PreservedAnalyses SinkingPass::run(Function &F, FunctionAnalysisManager &AM) {
auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
auto &LI = AM.getResult<LoopAnalysis>(F);
auto &AA = AM.getResult<AAManager>(F);
if (!iterativelySinkInstructions(F, DT, LI, AA))
return PreservedAnalyses::all();
PreservedAnalyses PA;
PA.preserveSet<CFGAnalyses>();
return PA;
}
namespace {
class SinkingLegacyPass : public FunctionPass {
public:
static char ID; SinkingLegacyPass() : FunctionPass(ID) {
initializeSinkingLegacyPassPass(*PassRegistry::getPassRegistry());
}
bool runOnFunction(Function &F) override {
auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
return iterativelySinkInstructions(F, DT, LI, AA);
}
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.setPreservesCFG();
FunctionPass::getAnalysisUsage(AU);
AU.addRequired<AAResultsWrapperPass>();
AU.addRequired<DominatorTreeWrapperPass>();
AU.addRequired<LoopInfoWrapperPass>();
AU.addPreserved<DominatorTreeWrapperPass>();
AU.addPreserved<LoopInfoWrapperPass>();
}
};
}
char SinkingLegacyPass::ID = 0;
INITIALIZE_PASS_BEGIN(SinkingLegacyPass, "sink", "Code sinking", false, false)
INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
INITIALIZE_PASS_END(SinkingLegacyPass, "sink", "Code sinking", false, false)
FunctionPass *llvm::createSinkingPass() { return new SinkingLegacyPass(); }