60#include <forward_list>
66#define LLE_OPTION "loop-load-elim"
67#define DEBUG_TYPE LLE_OPTION
70 "runtime-check-per-loop-load-elim",
cl::Hidden,
71 cl::desc(
"Max number of memchecks allowed per eliminated load on average"),
76 cl::desc(
"The maximum number of SCEV checks allowed for Loop "
79STATISTIC(NumLoopLoadEliminted,
"Number of loads eliminated by LLE");
84struct StoreToLoadForwardingCandidate {
89 : Load(Load), Store(Store) {}
96 Value *LoadPtr =
Load->getPointerOperand();
99 auto &
DL =
Load->getParent()->getModule()->getDataLayout();
103 DL.getTypeSizeInBits(LoadType) ==
105 "Should be a known dependence");
107 int64_t StrideLoad =
getPtrStride(PSE, LoadType, LoadPtr, L).value_or(0);
108 int64_t StrideStore =
getPtrStride(PSE, LoadType, StorePtr, L).value_or(0);
109 if (!StrideLoad || !StrideStore || StrideLoad != StrideStore)
119 if (std::abs(StrideLoad) != 1)
122 unsigned TypeByteSize =
DL.getTypeAllocSize(
const_cast<Type *
>(LoadType));
124 auto *LoadPtrSCEV = cast<SCEVAddRecExpr>(PSE.
getSCEV(LoadPtr));
125 auto *StorePtrSCEV = cast<SCEVAddRecExpr>(PSE.
getSCEV(StorePtr));
129 auto *Dist = cast<SCEVConstant>(
131 const APInt &Val = Dist->getAPInt();
132 return Val == TypeByteSize * StrideLoad;
135 Value *getLoadPtr()
const {
return Load->getPointerOperand(); }
139 const StoreToLoadForwardingCandidate &Cand) {
140 OS << *Cand.Store <<
" -->\n";
154 L->getLoopLatches(Latches);
162 return Load->getParent() != L->getHeader();
168class LoadEliminationForLoop {
173 :
L(
L), LI(LI), LAI(LAI), DT(DT),
BFI(
BFI), PSI(PSI), PSE(LAI.getPSE()) {}
180 std::forward_list<StoreToLoadForwardingCandidate>
182 std::forward_list<StoreToLoadForwardingCandidate> Candidates;
194 for (
const auto &Dep : *Deps) {
196 Instruction *Destination = Dep.getDestination(LAI);
199 if (isa<LoadInst>(Source))
200 LoadsWithUnknownDepedence.
insert(Source);
201 if (isa<LoadInst>(Destination))
202 LoadsWithUnknownDepedence.
insert(Destination);
206 if (Dep.isBackward())
212 assert(Dep.isForward() &&
"Needs to be a forward dependence");
214 auto *
Store = dyn_cast<StoreInst>(Source);
217 auto *
Load = dyn_cast<LoadInst>(Destination);
224 Store->getParent()->getModule()->getDataLayout()))
227 Candidates.emplace_front(Load, Store);
230 if (!LoadsWithUnknownDepedence.
empty())
231 Candidates.remove_if([&](
const StoreToLoadForwardingCandidate &
C) {
232 return LoadsWithUnknownDepedence.
count(
C.Load);
240 auto I = InstOrder.find(Inst);
241 assert(
I != InstOrder.end() &&
"No index for instruction");
264 void removeDependencesFromMultipleStores(
265 std::forward_list<StoreToLoadForwardingCandidate> &Candidates) {
268 using LoadToSingleCandT =
270 LoadToSingleCandT LoadToSingleCand;
272 for (
const auto &Cand : Candidates) {
274 LoadToSingleCandT::iterator Iter;
276 std::tie(Iter, NewElt) =
277 LoadToSingleCand.
insert(std::make_pair(Cand.Load, &Cand));
279 const StoreToLoadForwardingCandidate *&OtherCand = Iter->second;
281 if (OtherCand ==
nullptr)
287 if (Cand.Store->getParent() == OtherCand->Store->getParent() &&
288 Cand.isDependenceDistanceOfOne(PSE, L) &&
289 OtherCand->isDependenceDistanceOfOne(PSE, L)) {
291 if (getInstrIndex(OtherCand->Store) < getInstrIndex(Cand.Store))
298 Candidates.remove_if([&](
const StoreToLoadForwardingCandidate &Cand) {
299 if (LoadToSingleCand[Cand.Load] != &Cand) {
301 dbgs() <<
"Removing from candidates: \n"
303 <<
" The load may have multiple stores forwarding to "
316 bool needsChecking(
unsigned PtrIdx1,
unsigned PtrIdx2,
323 return ((PtrsWrittenOnFwdingPath.
count(Ptr1) && CandLoadPtrs.
count(Ptr2)) ||
324 (PtrsWrittenOnFwdingPath.
count(Ptr2) && CandLoadPtrs.
count(Ptr1)));
351 std::max_element(Candidates.
begin(), Candidates.
end(),
352 [&](
const StoreToLoadForwardingCandidate &
A,
353 const StoreToLoadForwardingCandidate &
B) {
354 return getInstrIndex(A.Load) < getInstrIndex(B.Load);
358 std::min_element(Candidates.
begin(), Candidates.
end(),
359 [&](
const StoreToLoadForwardingCandidate &
A,
360 const StoreToLoadForwardingCandidate &
B) {
361 return getInstrIndex(A.Store) <
362 getInstrIndex(B.Store);
372 if (
auto *S = dyn_cast<StoreInst>(
I))
373 PtrsWrittenOnFwdingPath.
insert(S->getPointerOperand());
376 std::for_each(MemInstrs.begin() + getInstrIndex(FirstStore) + 1,
377 MemInstrs.end(), InsertStorePtr);
378 std::for_each(MemInstrs.begin(), &MemInstrs[getInstrIndex(LastLoad)],
381 return PtrsWrittenOnFwdingPath;
390 findPointersWrittenOnForwardingPath(Candidates);
394 for (
const auto &Candidate : Candidates)
395 CandLoadPtrs.
insert(Candidate.getLoadPtr());
400 copy_if(AllChecks, std::back_inserter(Checks),
402 for (
auto PtrIdx1 :
Check.first->Members)
403 for (
auto PtrIdx2 :
Check.second->Members)
404 if (needsChecking(PtrIdx1, PtrIdx2, PtrsWrittenOnFwdingPath,
419 propagateStoredValueToLoadUsers(
const StoreToLoadForwardingCandidate &Cand,
436 Value *
Ptr = Cand.Load->getPointerOperand();
437 auto *PtrSCEV = cast<SCEVAddRecExpr>(PSE.
getSCEV(
Ptr));
438 auto *PH =
L->getLoopPreheader();
439 assert(PH &&
"Preheader should exist!");
440 Value *InitialPtr =
SEE.expandCodeFor(PtrSCEV->getStart(),
Ptr->getType(),
441 PH->getTerminator());
443 Cand.Load->getType(), InitialPtr,
"load_initial",
444 false, Cand.Load->getAlign(), PH->getTerminator());
447 PHI->insertBefore(
L->getHeader()->begin());
448 PHI->addIncoming(Initial, PH);
451 Type *StoreType = Cand.Store->getValueOperand()->getType();
455 assert(
DL.getTypeSizeInBits(LoadType) ==
DL.getTypeSizeInBits(StoreType) &&
456 "The type sizes should match!");
458 Value *StoreValue = Cand.Store->getValueOperand();
459 if (LoadType != StoreType)
461 StoreValue, LoadType,
"store_forward_cast", Cand.Store);
463 PHI->addIncoming(StoreValue,
L->getLoopLatch());
465 Cand.Load->replaceAllUsesWith(
PHI);
471 LLVM_DEBUG(
dbgs() <<
"\nIn \"" <<
L->getHeader()->getParent()->getName()
472 <<
"\" checking " << *L <<
"\n");
493 auto StoreToLoadDependences = findStoreToLoadDependences(LAI);
494 if (StoreToLoadDependences.empty())
503 removeDependencesFromMultipleStores(StoreToLoadDependences);
504 if (StoreToLoadDependences.empty())
509 for (
const StoreToLoadForwardingCandidate &Cand : StoreToLoadDependences) {
525 if (!Cand.isDependenceDistanceOfOne(PSE, L))
528 assert(isa<SCEVAddRecExpr>(PSE.
getSCEV(Cand.Load->getPointerOperand())) &&
529 "Loading from something other than indvar?");
531 isa<SCEVAddRecExpr>(PSE.
getSCEV(Cand.Store->getPointerOperand())) &&
532 "Storing to something other than indvar?");
538 <<
". Valid store-to-load forwarding across the loop backedge\n");
540 if (Candidates.
empty())
559 if (!
L->isLoopSimplifyForm()) {
567 "convergent calls\n");
571 auto *HeaderBB =
L->getHeader();
572 auto *
F = HeaderBB->getParent();
573 bool OptForSize =
F->hasOptSize() ||
575 PGSOQueryType::IRPass);
578 dbgs() <<
"Versioning is needed but not allowed when optimizing "
591 auto NoLongerGoodCandidate = [
this](
592 const StoreToLoadForwardingCandidate &Cand) {
593 return !isa<SCEVAddRecExpr>(
594 PSE.
getSCEV(Cand.Load->getPointerOperand())) ||
595 !isa<SCEVAddRecExpr>(
596 PSE.
getSCEV(Cand.Store->getPointerOperand()));
605 for (
const auto &Cand : Candidates)
606 propagateStoredValueToLoadUsers(Cand,
SEE);
607 NumLoopLoadEliminted += Candidates.size();
643 bool Changed =
false;
645 for (
Loop *TopLevelLoop : LI)
647 Changed |=
simplifyLoop(L, &DT, &LI, SE, AC,
nullptr,
false);
649 if (L->isInnermost())
654 for (
Loop *L : Worklist) {
656 if (!L->isRotatedForm() || !L->getExitingBlock())
659 LoadEliminationForLoop LEL(L, &LI, LAIs.
getInfo(*L), &DT, BFI, PSI);
660 Changed |= LEL.processLoop();
679 auto *BFI = (PSI && PSI->hasProfileSummary()) ?
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
This file implements a class to represent arbitrary precision integral constant values and operations...
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
This file defines the DenseMap class.
This file builds on the ADT/GraphTraits.h file to build generic depth first graph iterator.
This is the interface for a simple mod/ref and alias analysis over globals.
This header provides classes for managing per-loop analyses.
static bool eliminateLoadsAcrossLoops(Function &F, LoopInfo &LI, DominatorTree &DT, BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI, ScalarEvolution *SE, AssumptionCache *AC, LoopAccessInfoManager &LAIs)
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"))
static bool isLoadConditional(LoadInst *Load, Loop *L)
Return true if the load is not executed on all paths in the loop.
static bool doesStoreDominatesAllLatches(BasicBlock *StoreBlock, Loop *L, DominatorTree *DT)
Check if the store dominates all latches, so as long as there is no intervening store this value will...
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))
This header defines the LoopLoadEliminationPass object.
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Class for arbitrary precision integers.
A container for analyses that lazily runs them and caches their results.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
A function analysis which provides an AssumptionCache.
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
Analysis pass which computes BlockFrequencyInfo.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
static CastInst * CreateBitOrPointerCast(Value *S, Type *Ty, const Twine &Name="", Instruction *InsertBefore=nullptr)
Create a BitCast, a PtrToInt, or an IntToPTr cast instruction.
static bool isBitOrNoopPointerCastable(Type *SrcTy, Type *DestTy, const DataLayout &DL)
Check whether a bitcast, inttoptr, or ptrtoint cast between these types is valid and a no-op.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Analysis pass which computes a DominatorTree.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
An instruction for reading from memory.
This analysis provides dependence information for the memory accesses of a loop.
const LoopAccessInfo & getInfo(Loop &L)
Drive the analysis of memory accesses in the loop.
const MemoryDepChecker & getDepChecker() const
the Memory Dependence Checker which can determine the loop-independent and loop-carried dependences b...
const RuntimePointerChecking * getRuntimePointerChecking() const
const PredicatedScalarEvolution & getPSE() const
Used to add runtime SCEV checks.
bool hasConvergentOp() const
Return true if there is a convergent operation in the loop.
Analysis pass that exposes the LoopInfo for a function.
This class emits a version of the loop where run-time checks ensure that may-alias pointers can't ove...
Represents a single loop in the control flow graph.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
const DataLayout & getDataLayout() const
Return the DataLayout attached to the Module associated to this MF.
const SmallVectorImpl< Instruction * > & getMemoryInstructions() const
The vector of memory access instructions.
const SmallVectorImpl< Dependence > * getDependences() const
Returns the memory dependences.
DenseMap< Instruction *, unsigned > generateInstructionOrderMap() const
Generate a mapping between the memory instructions and their indices according to program order.
An analysis over an "inner" IR unit that provides access to an analysis manager over a "outer" IR uni...
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
An interface layer with SCEV used to manage how we see SCEV expressions for values in the context of ...
ScalarEvolution * getSE() const
Returns the ScalarEvolution analysis used.
const SCEVPredicate & getPredicate() const
const SCEV * getSCEV(Value *V)
Returns the SCEV expression of V, in the context of the current SCEV predicate.
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
void preserve()
Mark an analysis as preserved.
An analysis pass based on the new PM to deliver ProfileSummaryInfo.
Analysis providing profile information.
void printChecks(raw_ostream &OS, const SmallVectorImpl< RuntimePointerCheck > &Checks, unsigned Depth=0) const
Print Checks.
const SmallVectorImpl< RuntimePointerCheck > & getChecks() const
Returns the checks that generateChecks created.
const PointerInfo & getPointerInfo(unsigned PtrIdx) const
Return PointerInfo for pointer at index PtrIdx.
This class uses information about analyze scalars to rewrite expressions in canonical form.
virtual unsigned getComplexity() const
Returns the estimated complexity of this predicate.
virtual bool isAlwaysTrue() const =0
Returns true if the predicate is always true.
Analysis pass that exposes the ScalarEvolution for a function.
The main scalar evolution driver.
const SCEV * getMinusSCEV(const SCEV *LHS, const SCEV *RHS, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Return LHS-RHS.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
The instances of the Type class are immutable: once they are created, they are never changed.
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
This class implements an extremely fast bulk output stream that can only output to a stream.
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
@ C
The default llvm calling convention, compatible with C.
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
bool simplifyLoop(Loop *L, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE, AssumptionCache *AC, MemorySSAUpdater *MSSAU, bool PreserveLCSSA)
Simplify each loop in a loop nest recursively.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
std::pair< const RuntimeCheckingPtrGroup *, const RuntimeCheckingPtrGroup * > RuntimePointerCheck
A memcheck which made up of a pair of grouped pointers.
bool shouldOptimizeForSize(const MachineFunction *MF, ProfileSummaryInfo *PSI, const MachineBlockFrequencyInfo *BFI, PGSOQueryType QueryType=PGSOQueryType::Other)
Returns true if machine function MF is suggested to be size-optimized based on the profile.
OutputIt copy_if(R &&Range, OutputIt Out, UnaryPredicate P)
Provide wrappers to std::copy_if which take ranges instead of having to pass begin/end explicitly.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
std::optional< int64_t > getPtrStride(PredicatedScalarEvolution &PSE, Type *AccessTy, Value *Ptr, const Loop *Lp, const DenseMap< Value *, const SCEV * > &StridesMap=DenseMap< Value *, const SCEV * >(), bool Assume=false, bool ShouldCheckWrap=true)
If the pointer has a constant stride return it in units of the access type size.
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
iterator_range< df_iterator< T > > depth_first(const T &G)
Type * getLoadStoreType(Value *I)
A helper function that returns the type of a load or store instruction.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
TrackingVH< Value > PointerValue
Holds the pointer value that we need to check.