#include "llvm/Transforms/Scalar/LoopLoadElimination.h"
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/DepthFirstIterator.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Analysis/AssumptionCache.h"
#include "llvm/Analysis/BlockFrequencyInfo.h"
#include "llvm/Analysis/GlobalsModRef.h"
#include "llvm/Analysis/LazyBlockFrequencyInfo.h"
#include "llvm/Analysis/LoopAccessAnalysis.h"
#include "llvm/Analysis/LoopAnalysisManager.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/Analysis/ProfileSummaryInfo.h"
#include "llvm/Analysis/ScalarEvolution.h"
#include "llvm/Analysis/ScalarEvolutionExpressions.h"
#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/PassManager.h"
#include "llvm/IR/Type.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/Utils.h"
#include "llvm/Transforms/Utils/LoopSimplify.h"
#include "llvm/Transforms/Utils/LoopVersioning.h"
#include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
#include "llvm/Transforms/Utils/SizeOpts.h"
#include <algorithm>
#include <cassert>
#include <forward_list>
#include <tuple>
#include <utility>
using namespace llvm;
#define LLE_OPTION "loop-load-elim"
#define DEBUG_TYPE LLE_OPTION
static cl::opt<unsigned> CheckPerElim(
"runtime-check-per-loop-load-elim", cl::Hidden,
cl::desc("Max number of memchecks allowed per eliminated load on average"),
cl::init(1));
static cl::opt<unsigned> LoadElimSCEVCheckThreshold(
"loop-load-elimination-scev-check-threshold", cl::init(8), cl::Hidden,
cl::desc("The maximum number of SCEV checks allowed for Loop "
"Load Elimination"));
STATISTIC(NumLoopLoadEliminted, "Number of loads eliminated by LLE");
namespace {
struct StoreToLoadForwardingCandidate {
LoadInst *Load;
StoreInst *Store;
StoreToLoadForwardingCandidate(LoadInst *Load, StoreInst *Store)
: Load(Load), Store(Store) {}
bool isDependenceDistanceOfOne(PredicatedScalarEvolution &PSE,
Loop *L) const {
Value *LoadPtr = Load->getPointerOperand();
Value *StorePtr = Store->getPointerOperand();
Type *LoadType = getLoadStoreType(Load);
assert(LoadPtr->getType()->getPointerAddressSpace() ==
StorePtr->getType()->getPointerAddressSpace() &&
LoadType == getLoadStoreType(Store) &&
"Should be a known dependence");
if (getPtrStride(PSE, LoadType, LoadPtr, L) != 1 ||
getPtrStride(PSE, LoadType, StorePtr, L) != 1)
return false;
auto &DL = Load->getParent()->getModule()->getDataLayout();
unsigned TypeByteSize = DL.getTypeAllocSize(const_cast<Type *>(LoadType));
auto *LoadPtrSCEV = cast<SCEVAddRecExpr>(PSE.getSCEV(LoadPtr));
auto *StorePtrSCEV = cast<SCEVAddRecExpr>(PSE.getSCEV(StorePtr));
auto *Dist = cast<SCEVConstant>(
PSE.getSE()->getMinusSCEV(StorePtrSCEV, LoadPtrSCEV));
const APInt &Val = Dist->getAPInt();
return Val == TypeByteSize;
}
Value *getLoadPtr() const { return Load->getPointerOperand(); }
#ifndef NDEBUG
friend raw_ostream &operator<<(raw_ostream &OS,
const StoreToLoadForwardingCandidate &Cand) {
OS << *Cand.Store << " -->\n";
OS.indent(2) << *Cand.Load << "\n";
return OS;
}
#endif
};
}
static bool doesStoreDominatesAllLatches(BasicBlock *StoreBlock, Loop *L,
DominatorTree *DT) {
SmallVector<BasicBlock *, 8> Latches;
L->getLoopLatches(Latches);
return llvm::all_of(Latches, [&](const BasicBlock *Latch) {
return DT->dominates(StoreBlock, Latch);
});
}
static bool isLoadConditional(LoadInst *Load, Loop *L) {
return Load->getParent() != L->getHeader();
}
namespace {
class LoadEliminationForLoop {
public:
LoadEliminationForLoop(Loop *L, LoopInfo *LI, const LoopAccessInfo &LAI,
DominatorTree *DT, BlockFrequencyInfo *BFI,
ProfileSummaryInfo* PSI)
: L(L), LI(LI), LAI(LAI), DT(DT), BFI(BFI), PSI(PSI), PSE(LAI.getPSE()) {}
std::forward_list<StoreToLoadForwardingCandidate>
findStoreToLoadDependences(const LoopAccessInfo &LAI) {
std::forward_list<StoreToLoadForwardingCandidate> Candidates;
const auto *Deps = LAI.getDepChecker().getDependences();
if (!Deps)
return Candidates;
SmallPtrSet<Instruction *, 4> LoadsWithUnknownDepedence;
for (const auto &Dep : *Deps) {
Instruction *Source = Dep.getSource(LAI);
Instruction *Destination = Dep.getDestination(LAI);
if (Dep.Type == MemoryDepChecker::Dependence::Unknown) {
if (isa<LoadInst>(Source))
LoadsWithUnknownDepedence.insert(Source);
if (isa<LoadInst>(Destination))
LoadsWithUnknownDepedence.insert(Destination);
continue;
}
if (Dep.isBackward())
std::swap(Source, Destination);
else
assert(Dep.isForward() && "Needs to be a forward dependence");
auto *Store = dyn_cast<StoreInst>(Source);
if (!Store)
continue;
auto *Load = dyn_cast<LoadInst>(Destination);
if (!Load)
continue;
if (Store->getPointerOperandType() != Load->getPointerOperandType() ||
getLoadStoreType(Store) != getLoadStoreType(Load))
continue;
Candidates.emplace_front(Load, Store);
}
if (!LoadsWithUnknownDepedence.empty())
Candidates.remove_if([&](const StoreToLoadForwardingCandidate &C) {
return LoadsWithUnknownDepedence.count(C.Load);
});
return Candidates;
}
unsigned getInstrIndex(Instruction *Inst) {
auto I = InstOrder.find(Inst);
assert(I != InstOrder.end() && "No index for instruction");
return I->second;
}
void removeDependencesFromMultipleStores(
std::forward_list<StoreToLoadForwardingCandidate> &Candidates) {
using LoadToSingleCandT =
DenseMap<LoadInst *, const StoreToLoadForwardingCandidate *>;
LoadToSingleCandT LoadToSingleCand;
for (const auto &Cand : Candidates) {
bool NewElt;
LoadToSingleCandT::iterator Iter;
std::tie(Iter, NewElt) =
LoadToSingleCand.insert(std::make_pair(Cand.Load, &Cand));
if (!NewElt) {
const StoreToLoadForwardingCandidate *&OtherCand = Iter->second;
if (OtherCand == nullptr)
continue;
if (Cand.Store->getParent() == OtherCand->Store->getParent() &&
Cand.isDependenceDistanceOfOne(PSE, L) &&
OtherCand->isDependenceDistanceOfOne(PSE, L)) {
if (getInstrIndex(OtherCand->Store) < getInstrIndex(Cand.Store))
OtherCand = &Cand;
} else
OtherCand = nullptr;
}
}
Candidates.remove_if([&](const StoreToLoadForwardingCandidate &Cand) {
if (LoadToSingleCand[Cand.Load] != &Cand) {
LLVM_DEBUG(
dbgs() << "Removing from candidates: \n"
<< Cand
<< " The load may have multiple stores forwarding to "
<< "it\n");
return true;
}
return false;
});
}
bool needsChecking(unsigned PtrIdx1, unsigned PtrIdx2,
const SmallPtrSetImpl<Value *> &PtrsWrittenOnFwdingPath,
const SmallPtrSetImpl<Value *> &CandLoadPtrs) {
Value *Ptr1 =
LAI.getRuntimePointerChecking()->getPointerInfo(PtrIdx1).PointerValue;
Value *Ptr2 =
LAI.getRuntimePointerChecking()->getPointerInfo(PtrIdx2).PointerValue;
return ((PtrsWrittenOnFwdingPath.count(Ptr1) && CandLoadPtrs.count(Ptr2)) ||
(PtrsWrittenOnFwdingPath.count(Ptr2) && CandLoadPtrs.count(Ptr1)));
}
SmallPtrSet<Value *, 4> findPointersWrittenOnForwardingPath(
const SmallVectorImpl<StoreToLoadForwardingCandidate> &Candidates) {
LoadInst *LastLoad =
std::max_element(Candidates.begin(), Candidates.end(),
[&](const StoreToLoadForwardingCandidate &A,
const StoreToLoadForwardingCandidate &B) {
return getInstrIndex(A.Load) < getInstrIndex(B.Load);
})
->Load;
StoreInst *FirstStore =
std::min_element(Candidates.begin(), Candidates.end(),
[&](const StoreToLoadForwardingCandidate &A,
const StoreToLoadForwardingCandidate &B) {
return getInstrIndex(A.Store) <
getInstrIndex(B.Store);
})
->Store;
SmallPtrSet<Value *, 4> PtrsWrittenOnFwdingPath;
auto InsertStorePtr = [&](Instruction *I) {
if (auto *S = dyn_cast<StoreInst>(I))
PtrsWrittenOnFwdingPath.insert(S->getPointerOperand());
};
const auto &MemInstrs = LAI.getDepChecker().getMemoryInstructions();
std::for_each(MemInstrs.begin() + getInstrIndex(FirstStore) + 1,
MemInstrs.end(), InsertStorePtr);
std::for_each(MemInstrs.begin(), &MemInstrs[getInstrIndex(LastLoad)],
InsertStorePtr);
return PtrsWrittenOnFwdingPath;
}
SmallVector<RuntimePointerCheck, 4> collectMemchecks(
const SmallVectorImpl<StoreToLoadForwardingCandidate> &Candidates) {
SmallPtrSet<Value *, 4> PtrsWrittenOnFwdingPath =
findPointersWrittenOnForwardingPath(Candidates);
SmallPtrSet<Value *, 4> CandLoadPtrs;
for (const auto &Candidate : Candidates)
CandLoadPtrs.insert(Candidate.getLoadPtr());
const auto &AllChecks = LAI.getRuntimePointerChecking()->getChecks();
SmallVector<RuntimePointerCheck, 4> Checks;
copy_if(AllChecks, std::back_inserter(Checks),
[&](const RuntimePointerCheck &Check) {
for (auto PtrIdx1 : Check.first->Members)
for (auto PtrIdx2 : Check.second->Members)
if (needsChecking(PtrIdx1, PtrIdx2, PtrsWrittenOnFwdingPath,
CandLoadPtrs))
return true;
return false;
});
LLVM_DEBUG(dbgs() << "\nPointer Checks (count: " << Checks.size()
<< "):\n");
LLVM_DEBUG(LAI.getRuntimePointerChecking()->printChecks(dbgs(), Checks));
return Checks;
}
void
propagateStoredValueToLoadUsers(const StoreToLoadForwardingCandidate &Cand,
SCEVExpander &SEE) {
Value *Ptr = Cand.Load->getPointerOperand();
auto *PtrSCEV = cast<SCEVAddRecExpr>(PSE.getSCEV(Ptr));
auto *PH = L->getLoopPreheader();
assert(PH && "Preheader should exist!");
Value *InitialPtr = SEE.expandCodeFor(PtrSCEV->getStart(), Ptr->getType(),
PH->getTerminator());
Value *Initial = new LoadInst(
Cand.Load->getType(), InitialPtr, "load_initial",
false, Cand.Load->getAlign(), PH->getTerminator());
PHINode *PHI = PHINode::Create(Initial->getType(), 2, "store_forwarded",
&L->getHeader()->front());
PHI->addIncoming(Initial, PH);
PHI->addIncoming(Cand.Store->getOperand(0), L->getLoopLatch());
Cand.Load->replaceAllUsesWith(PHI);
}
bool processLoop() {
LLVM_DEBUG(dbgs() << "\nIn \"" << L->getHeader()->getParent()->getName()
<< "\" checking " << *L << "\n");
auto StoreToLoadDependences = findStoreToLoadDependences(LAI);
if (StoreToLoadDependences.empty())
return false;
InstOrder = LAI.getDepChecker().generateInstructionOrderMap();
removeDependencesFromMultipleStores(StoreToLoadDependences);
if (StoreToLoadDependences.empty())
return false;
SmallVector<StoreToLoadForwardingCandidate, 4> Candidates;
for (const StoreToLoadForwardingCandidate &Cand : StoreToLoadDependences) {
LLVM_DEBUG(dbgs() << "Candidate " << Cand);
if (!doesStoreDominatesAllLatches(Cand.Store->getParent(), L, DT))
continue;
if (isLoadConditional(Cand.Load, L))
continue;
if (!Cand.isDependenceDistanceOfOne(PSE, L))
continue;
assert(isa<SCEVAddRecExpr>(PSE.getSCEV(Cand.Load->getPointerOperand())) &&
"Loading from something other than indvar?");
assert(
isa<SCEVAddRecExpr>(PSE.getSCEV(Cand.Store->getPointerOperand())) &&
"Storing to something other than indvar?");
Candidates.push_back(Cand);
LLVM_DEBUG(
dbgs()
<< Candidates.size()
<< ". Valid store-to-load forwarding across the loop backedge\n");
}
if (Candidates.empty())
return false;
SmallVector<RuntimePointerCheck, 4> Checks = collectMemchecks(Candidates);
if (Checks.size() > Candidates.size() * CheckPerElim) {
LLVM_DEBUG(dbgs() << "Too many run-time checks needed.\n");
return false;
}
if (LAI.getPSE().getPredicate().getComplexity() >
LoadElimSCEVCheckThreshold) {
LLVM_DEBUG(dbgs() << "Too many SCEV run-time checks needed.\n");
return false;
}
if (!L->isLoopSimplifyForm()) {
LLVM_DEBUG(dbgs() << "Loop is not is loop-simplify form");
return false;
}
if (!Checks.empty() || !LAI.getPSE().getPredicate().isAlwaysTrue()) {
if (LAI.hasConvergentOp()) {
LLVM_DEBUG(dbgs() << "Versioning is needed but not allowed with "
"convergent calls\n");
return false;
}
auto *HeaderBB = L->getHeader();
auto *F = HeaderBB->getParent();
bool OptForSize = F->hasOptSize() ||
llvm::shouldOptimizeForSize(HeaderBB, PSI, BFI,
PGSOQueryType::IRPass);
if (OptForSize) {
LLVM_DEBUG(
dbgs() << "Versioning is needed but not allowed when optimizing "
"for size.\n");
return false;
}
LoopVersioning LV(LAI, Checks, L, LI, DT, PSE.getSE());
LV.versionLoop();
auto NoLongerGoodCandidate = [this](
const StoreToLoadForwardingCandidate &Cand) {
return !isa<SCEVAddRecExpr>(
PSE.getSCEV(Cand.Load->getPointerOperand())) ||
!isa<SCEVAddRecExpr>(
PSE.getSCEV(Cand.Store->getPointerOperand()));
};
llvm::erase_if(Candidates, NoLongerGoodCandidate);
}
SCEVExpander SEE(*PSE.getSE(), L->getHeader()->getModule()->getDataLayout(),
"storeforward");
for (const auto &Cand : Candidates)
propagateStoredValueToLoadUsers(Cand, SEE);
NumLoopLoadEliminted += Candidates.size();
return true;
}
private:
Loop *L;
DenseMap<Instruction *, unsigned> InstOrder;
LoopInfo *LI;
const LoopAccessInfo &LAI;
DominatorTree *DT;
BlockFrequencyInfo *BFI;
ProfileSummaryInfo *PSI;
PredicatedScalarEvolution PSE;
};
}
static bool
eliminateLoadsAcrossLoops(Function &F, LoopInfo &LI, DominatorTree &DT,
BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
ScalarEvolution *SE, AssumptionCache *AC,
function_ref<const LoopAccessInfo &(Loop &)> GetLAI) {
SmallVector<Loop *, 8> Worklist;
bool Changed = false;
for (Loop *TopLevelLoop : LI)
for (Loop *L : depth_first(TopLevelLoop)) {
Changed |= simplifyLoop(L, &DT, &LI, SE, AC, nullptr, false);
if (L->isInnermost())
Worklist.push_back(L);
}
for (Loop *L : Worklist) {
if (!L->isRotatedForm() || !L->getExitingBlock())
continue;
LoadEliminationForLoop LEL(L, &LI, GetLAI(*L), &DT, BFI, PSI);
Changed |= LEL.processLoop();
}
return Changed;
}
namespace {
class LoopLoadElimination : public FunctionPass {
public:
static char ID;
LoopLoadElimination() : FunctionPass(ID) {
initializeLoopLoadEliminationPass(*PassRegistry::getPassRegistry());
}
bool runOnFunction(Function &F) override {
if (skipFunction(F))
return false;
auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
auto &LAA = getAnalysis<LoopAccessLegacyAnalysis>();
auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
auto *PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
auto *BFI = (PSI && PSI->hasProfileSummary()) ?
&getAnalysis<LazyBlockFrequencyInfoPass>().getBFI() :
nullptr;
auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
return eliminateLoadsAcrossLoops(
F, LI, DT, BFI, PSI, SE, nullptr,
[&LAA](Loop &L) -> const LoopAccessInfo & { return LAA.getInfo(&L); });
}
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequiredID(LoopSimplifyID);
AU.addRequired<LoopInfoWrapperPass>();
AU.addPreserved<LoopInfoWrapperPass>();
AU.addRequired<LoopAccessLegacyAnalysis>();
AU.addRequired<ScalarEvolutionWrapperPass>();
AU.addRequired<DominatorTreeWrapperPass>();
AU.addPreserved<DominatorTreeWrapperPass>();
AU.addPreserved<GlobalsAAWrapperPass>();
AU.addRequired<ProfileSummaryInfoWrapperPass>();
LazyBlockFrequencyInfoPass::getLazyBFIAnalysisUsage(AU);
}
};
}
char LoopLoadElimination::ID;
static const char LLE_name[] = "Loop Load Elimination";
INITIALIZE_PASS_BEGIN(LoopLoadElimination, LLE_OPTION, LLE_name, false, false)
INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
INITIALIZE_PASS_DEPENDENCY(LoopAccessLegacyAnalysis)
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
INITIALIZE_PASS_DEPENDENCY(LazyBlockFrequencyInfoPass)
INITIALIZE_PASS_END(LoopLoadElimination, LLE_OPTION, LLE_name, false, false)
FunctionPass *llvm::createLoopLoadEliminationPass() {
return new LoopLoadElimination();
}
PreservedAnalyses LoopLoadEliminationPass::run(Function &F,
FunctionAnalysisManager &AM) {
auto &LI = AM.getResult<LoopAnalysis>(F);
if (LI.empty())
return PreservedAnalyses::all();
auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
auto &TTI = AM.getResult<TargetIRAnalysis>(F);
auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
auto &AA = AM.getResult<AAManager>(F);
auto &AC = AM.getResult<AssumptionAnalysis>(F);
auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
auto *PSI = MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
auto *BFI = (PSI && PSI->hasProfileSummary()) ?
&AM.getResult<BlockFrequencyAnalysis>(F) : nullptr;
auto &LAM = AM.getResult<LoopAnalysisManagerFunctionProxy>(F).getManager();
bool Changed = eliminateLoadsAcrossLoops(
F, LI, DT, BFI, PSI, &SE, &AC, [&](Loop &L) -> const LoopAccessInfo & {
LoopStandardAnalysisResults AR = {AA, AC, DT, LI, SE,
TLI, TTI, nullptr, nullptr, nullptr};
return LAM.getResult<LoopAccessAnalysis>(L, AR);
});
if (!Changed)
return PreservedAnalyses::all();
PreservedAnalyses PA;
return PA;
}