Path: blob/main/contrib/llvm-project/llvm/lib/Transforms/Scalar/LoopLoadElimination.cpp
35266 views
//===- LoopLoadElimination.cpp - Loop Load Elimination Pass ---------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file implement a loop-aware load elimination pass.9//10// It uses LoopAccessAnalysis to identify loop-carried dependences with a11// distance of one between stores and loads. These form the candidates for the12// transformation. The source value of each store then propagated to the user13// of the corresponding load. This makes the load dead.14//15// The pass can also version the loop and add memchecks in order to prove that16// may-aliasing stores can't change the value in memory before it's read by the17// load.18//19//===----------------------------------------------------------------------===//2021#include "llvm/Transforms/Scalar/LoopLoadElimination.h"22#include "llvm/ADT/APInt.h"23#include "llvm/ADT/DenseMap.h"24#include "llvm/ADT/DepthFirstIterator.h"25#include "llvm/ADT/STLExtras.h"26#include "llvm/ADT/SmallPtrSet.h"27#include "llvm/ADT/SmallVector.h"28#include "llvm/ADT/Statistic.h"29#include "llvm/Analysis/AssumptionCache.h"30#include "llvm/Analysis/BlockFrequencyInfo.h"31#include "llvm/Analysis/GlobalsModRef.h"32#include "llvm/Analysis/LazyBlockFrequencyInfo.h"33#include "llvm/Analysis/LoopAccessAnalysis.h"34#include "llvm/Analysis/LoopAnalysisManager.h"35#include "llvm/Analysis/LoopInfo.h"36#include "llvm/Analysis/ProfileSummaryInfo.h"37#include "llvm/Analysis/ScalarEvolution.h"38#include "llvm/Analysis/ScalarEvolutionExpressions.h"39#include "llvm/Analysis/TargetLibraryInfo.h"40#include "llvm/Analysis/TargetTransformInfo.h"41#include "llvm/IR/DataLayout.h"42#include "llvm/IR/Dominators.h"43#include "llvm/IR/Instructions.h"44#include "llvm/IR/Module.h"45#include "llvm/IR/PassManager.h"46#include "llvm/IR/Type.h"47#include "llvm/IR/Value.h"48#include "llvm/Support/Casting.h"49#include "llvm/Support/CommandLine.h"50#include "llvm/Support/Debug.h"51#include "llvm/Support/raw_ostream.h"52#include "llvm/Transforms/Utils.h"53#include "llvm/Transforms/Utils/LoopSimplify.h"54#include "llvm/Transforms/Utils/LoopVersioning.h"55#include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"56#include "llvm/Transforms/Utils/SizeOpts.h"57#include <algorithm>58#include <cassert>59#include <forward_list>60#include <tuple>61#include <utility>6263using namespace llvm;6465#define LLE_OPTION "loop-load-elim"66#define DEBUG_TYPE LLE_OPTION6768static cl::opt<unsigned> CheckPerElim(69"runtime-check-per-loop-load-elim", cl::Hidden,70cl::desc("Max number of memchecks allowed per eliminated load on average"),71cl::init(1));7273static cl::opt<unsigned> LoadElimSCEVCheckThreshold(74"loop-load-elimination-scev-check-threshold", cl::init(8), cl::Hidden,75cl::desc("The maximum number of SCEV checks allowed for Loop "76"Load Elimination"));7778STATISTIC(NumLoopLoadEliminted, "Number of loads eliminated by LLE");7980namespace {8182/// Represent a store-to-forwarding candidate.83struct StoreToLoadForwardingCandidate {84LoadInst *Load;85StoreInst *Store;8687StoreToLoadForwardingCandidate(LoadInst *Load, StoreInst *Store)88: Load(Load), Store(Store) {}8990/// Return true if the dependence from the store to the load has an91/// absolute distance of one.92/// E.g. A[i+1] = A[i] (or A[i-1] = A[i] for descending loop)93bool isDependenceDistanceOfOne(PredicatedScalarEvolution &PSE,94Loop *L) const {95Value *LoadPtr = Load->getPointerOperand();96Value *StorePtr = Store->getPointerOperand();97Type *LoadType = getLoadStoreType(Load);98auto &DL = Load->getDataLayout();99100assert(LoadPtr->getType()->getPointerAddressSpace() ==101StorePtr->getType()->getPointerAddressSpace() &&102DL.getTypeSizeInBits(LoadType) ==103DL.getTypeSizeInBits(getLoadStoreType(Store)) &&104"Should be a known dependence");105106int64_t StrideLoad = getPtrStride(PSE, LoadType, LoadPtr, L).value_or(0);107int64_t StrideStore = getPtrStride(PSE, LoadType, StorePtr, L).value_or(0);108if (!StrideLoad || !StrideStore || StrideLoad != StrideStore)109return false;110111// TODO: This check for stride values other than 1 and -1 can be eliminated.112// However, doing so may cause the LoopAccessAnalysis to overcompensate,113// generating numerous non-wrap runtime checks that may undermine the114// benefits of load elimination. To safely implement support for non-unit115// strides, we would need to ensure either that the processed case does not116// require these additional checks, or improve the LAA to handle them more117// efficiently, or potentially both.118if (std::abs(StrideLoad) != 1)119return false;120121unsigned TypeByteSize = DL.getTypeAllocSize(const_cast<Type *>(LoadType));122123auto *LoadPtrSCEV = cast<SCEVAddRecExpr>(PSE.getSCEV(LoadPtr));124auto *StorePtrSCEV = cast<SCEVAddRecExpr>(PSE.getSCEV(StorePtr));125126// We don't need to check non-wrapping here because forward/backward127// dependence wouldn't be valid if these weren't monotonic accesses.128auto *Dist = dyn_cast<SCEVConstant>(129PSE.getSE()->getMinusSCEV(StorePtrSCEV, LoadPtrSCEV));130if (!Dist)131return false;132const APInt &Val = Dist->getAPInt();133return Val == TypeByteSize * StrideLoad;134}135136Value *getLoadPtr() const { return Load->getPointerOperand(); }137138#ifndef NDEBUG139friend raw_ostream &operator<<(raw_ostream &OS,140const StoreToLoadForwardingCandidate &Cand) {141OS << *Cand.Store << " -->\n";142OS.indent(2) << *Cand.Load << "\n";143return OS;144}145#endif146};147148} // end anonymous namespace149150/// Check if the store dominates all latches, so as long as there is no151/// intervening store this value will be loaded in the next iteration.152static bool doesStoreDominatesAllLatches(BasicBlock *StoreBlock, Loop *L,153DominatorTree *DT) {154SmallVector<BasicBlock *, 8> Latches;155L->getLoopLatches(Latches);156return llvm::all_of(Latches, [&](const BasicBlock *Latch) {157return DT->dominates(StoreBlock, Latch);158});159}160161/// Return true if the load is not executed on all paths in the loop.162static bool isLoadConditional(LoadInst *Load, Loop *L) {163return Load->getParent() != L->getHeader();164}165166namespace {167168/// The per-loop class that does most of the work.169class LoadEliminationForLoop {170public:171LoadEliminationForLoop(Loop *L, LoopInfo *LI, const LoopAccessInfo &LAI,172DominatorTree *DT, BlockFrequencyInfo *BFI,173ProfileSummaryInfo* PSI)174: L(L), LI(LI), LAI(LAI), DT(DT), BFI(BFI), PSI(PSI), PSE(LAI.getPSE()) {}175176/// Look through the loop-carried and loop-independent dependences in177/// this loop and find store->load dependences.178///179/// Note that no candidate is returned if LAA has failed to analyze the loop180/// (e.g. if it's not bottom-tested, contains volatile memops, etc.)181std::forward_list<StoreToLoadForwardingCandidate>182findStoreToLoadDependences(const LoopAccessInfo &LAI) {183std::forward_list<StoreToLoadForwardingCandidate> Candidates;184185const auto &DepChecker = LAI.getDepChecker();186const auto *Deps = DepChecker.getDependences();187if (!Deps)188return Candidates;189190// Find store->load dependences (consequently true dep). Both lexically191// forward and backward dependences qualify. Disqualify loads that have192// other unknown dependences.193194SmallPtrSet<Instruction *, 4> LoadsWithUnknownDepedence;195196for (const auto &Dep : *Deps) {197Instruction *Source = Dep.getSource(DepChecker);198Instruction *Destination = Dep.getDestination(DepChecker);199200if (Dep.Type == MemoryDepChecker::Dependence::Unknown ||201Dep.Type == MemoryDepChecker::Dependence::IndirectUnsafe) {202if (isa<LoadInst>(Source))203LoadsWithUnknownDepedence.insert(Source);204if (isa<LoadInst>(Destination))205LoadsWithUnknownDepedence.insert(Destination);206continue;207}208209if (Dep.isBackward())210// Note that the designations source and destination follow the program211// order, i.e. source is always first. (The direction is given by the212// DepType.)213std::swap(Source, Destination);214else215assert(Dep.isForward() && "Needs to be a forward dependence");216217auto *Store = dyn_cast<StoreInst>(Source);218if (!Store)219continue;220auto *Load = dyn_cast<LoadInst>(Destination);221if (!Load)222continue;223224// Only propagate if the stored values are bit/pointer castable.225if (!CastInst::isBitOrNoopPointerCastable(226getLoadStoreType(Store), getLoadStoreType(Load),227Store->getDataLayout()))228continue;229230Candidates.emplace_front(Load, Store);231}232233if (!LoadsWithUnknownDepedence.empty())234Candidates.remove_if([&](const StoreToLoadForwardingCandidate &C) {235return LoadsWithUnknownDepedence.count(C.Load);236});237238return Candidates;239}240241/// Return the index of the instruction according to program order.242unsigned getInstrIndex(Instruction *Inst) {243auto I = InstOrder.find(Inst);244assert(I != InstOrder.end() && "No index for instruction");245return I->second;246}247248/// If a load has multiple candidates associated (i.e. different249/// stores), it means that it could be forwarding from multiple stores250/// depending on control flow. Remove these candidates.251///252/// Here, we rely on LAA to include the relevant loop-independent dependences.253/// LAA is known to omit these in the very simple case when the read and the254/// write within an alias set always takes place using the *same* pointer.255///256/// However, we know that this is not the case here, i.e. we can rely on LAA257/// to provide us with loop-independent dependences for the cases we're258/// interested. Consider the case for example where a loop-independent259/// dependece S1->S2 invalidates the forwarding S3->S2.260///261/// A[i] = ... (S1)262/// ... = A[i] (S2)263/// A[i+1] = ... (S3)264///265/// LAA will perform dependence analysis here because there are two266/// *different* pointers involved in the same alias set (&A[i] and &A[i+1]).267void removeDependencesFromMultipleStores(268std::forward_list<StoreToLoadForwardingCandidate> &Candidates) {269// If Store is nullptr it means that we have multiple stores forwarding to270// this store.271using LoadToSingleCandT =272DenseMap<LoadInst *, const StoreToLoadForwardingCandidate *>;273LoadToSingleCandT LoadToSingleCand;274275for (const auto &Cand : Candidates) {276bool NewElt;277LoadToSingleCandT::iterator Iter;278279std::tie(Iter, NewElt) =280LoadToSingleCand.insert(std::make_pair(Cand.Load, &Cand));281if (!NewElt) {282const StoreToLoadForwardingCandidate *&OtherCand = Iter->second;283// Already multiple stores forward to this load.284if (OtherCand == nullptr)285continue;286287// Handle the very basic case when the two stores are in the same block288// so deciding which one forwards is easy. The later one forwards as289// long as they both have a dependence distance of one to the load.290if (Cand.Store->getParent() == OtherCand->Store->getParent() &&291Cand.isDependenceDistanceOfOne(PSE, L) &&292OtherCand->isDependenceDistanceOfOne(PSE, L)) {293// They are in the same block, the later one will forward to the load.294if (getInstrIndex(OtherCand->Store) < getInstrIndex(Cand.Store))295OtherCand = &Cand;296} else297OtherCand = nullptr;298}299}300301Candidates.remove_if([&](const StoreToLoadForwardingCandidate &Cand) {302if (LoadToSingleCand[Cand.Load] != &Cand) {303LLVM_DEBUG(304dbgs() << "Removing from candidates: \n"305<< Cand306<< " The load may have multiple stores forwarding to "307<< "it\n");308return true;309}310return false;311});312}313314/// Given two pointers operations by their RuntimePointerChecking315/// indices, return true if they require an alias check.316///317/// We need a check if one is a pointer for a candidate load and the other is318/// a pointer for a possibly intervening store.319bool needsChecking(unsigned PtrIdx1, unsigned PtrIdx2,320const SmallPtrSetImpl<Value *> &PtrsWrittenOnFwdingPath,321const SmallPtrSetImpl<Value *> &CandLoadPtrs) {322Value *Ptr1 =323LAI.getRuntimePointerChecking()->getPointerInfo(PtrIdx1).PointerValue;324Value *Ptr2 =325LAI.getRuntimePointerChecking()->getPointerInfo(PtrIdx2).PointerValue;326return ((PtrsWrittenOnFwdingPath.count(Ptr1) && CandLoadPtrs.count(Ptr2)) ||327(PtrsWrittenOnFwdingPath.count(Ptr2) && CandLoadPtrs.count(Ptr1)));328}329330/// Return pointers that are possibly written to on the path from a331/// forwarding store to a load.332///333/// These pointers need to be alias-checked against the forwarding candidates.334SmallPtrSet<Value *, 4> findPointersWrittenOnForwardingPath(335const SmallVectorImpl<StoreToLoadForwardingCandidate> &Candidates) {336// From FirstStore to LastLoad neither of the elimination candidate loads337// should overlap with any of the stores.338//339// E.g.:340//341// st1 C[i]342// ld1 B[i] <-------,343// ld0 A[i] <----, | * LastLoad344// ... | |345// st2 E[i] | |346// st3 B[i+1] -- | -' * FirstStore347// st0 A[i+1] ---'348// st4 D[i]349//350// st0 forwards to ld0 if the accesses in st4 and st1 don't overlap with351// ld0.352353LoadInst *LastLoad =354llvm::max_element(Candidates,355[&](const StoreToLoadForwardingCandidate &A,356const StoreToLoadForwardingCandidate &B) {357return getInstrIndex(A.Load) <358getInstrIndex(B.Load);359})360->Load;361StoreInst *FirstStore =362llvm::min_element(Candidates,363[&](const StoreToLoadForwardingCandidate &A,364const StoreToLoadForwardingCandidate &B) {365return getInstrIndex(A.Store) <366getInstrIndex(B.Store);367})368->Store;369370// We're looking for stores after the first forwarding store until the end371// of the loop, then from the beginning of the loop until the last372// forwarded-to load. Collect the pointer for the stores.373SmallPtrSet<Value *, 4> PtrsWrittenOnFwdingPath;374375auto InsertStorePtr = [&](Instruction *I) {376if (auto *S = dyn_cast<StoreInst>(I))377PtrsWrittenOnFwdingPath.insert(S->getPointerOperand());378};379const auto &MemInstrs = LAI.getDepChecker().getMemoryInstructions();380std::for_each(MemInstrs.begin() + getInstrIndex(FirstStore) + 1,381MemInstrs.end(), InsertStorePtr);382std::for_each(MemInstrs.begin(), &MemInstrs[getInstrIndex(LastLoad)],383InsertStorePtr);384385return PtrsWrittenOnFwdingPath;386}387388/// Determine the pointer alias checks to prove that there are no389/// intervening stores.390SmallVector<RuntimePointerCheck, 4> collectMemchecks(391const SmallVectorImpl<StoreToLoadForwardingCandidate> &Candidates) {392393SmallPtrSet<Value *, 4> PtrsWrittenOnFwdingPath =394findPointersWrittenOnForwardingPath(Candidates);395396// Collect the pointers of the candidate loads.397SmallPtrSet<Value *, 4> CandLoadPtrs;398for (const auto &Candidate : Candidates)399CandLoadPtrs.insert(Candidate.getLoadPtr());400401const auto &AllChecks = LAI.getRuntimePointerChecking()->getChecks();402SmallVector<RuntimePointerCheck, 4> Checks;403404copy_if(AllChecks, std::back_inserter(Checks),405[&](const RuntimePointerCheck &Check) {406for (auto PtrIdx1 : Check.first->Members)407for (auto PtrIdx2 : Check.second->Members)408if (needsChecking(PtrIdx1, PtrIdx2, PtrsWrittenOnFwdingPath,409CandLoadPtrs))410return true;411return false;412});413414LLVM_DEBUG(dbgs() << "\nPointer Checks (count: " << Checks.size()415<< "):\n");416LLVM_DEBUG(LAI.getRuntimePointerChecking()->printChecks(dbgs(), Checks));417418return Checks;419}420421/// Perform the transformation for a candidate.422void423propagateStoredValueToLoadUsers(const StoreToLoadForwardingCandidate &Cand,424SCEVExpander &SEE) {425// loop:426// %x = load %gep_i427// = ... %x428// store %y, %gep_i_plus_1429//430// =>431//432// ph:433// %x.initial = load %gep_0434// loop:435// %x.storeforward = phi [%x.initial, %ph] [%y, %loop]436// %x = load %gep_i <---- now dead437// = ... %x.storeforward438// store %y, %gep_i_plus_1439440Value *Ptr = Cand.Load->getPointerOperand();441auto *PtrSCEV = cast<SCEVAddRecExpr>(PSE.getSCEV(Ptr));442auto *PH = L->getLoopPreheader();443assert(PH && "Preheader should exist!");444Value *InitialPtr = SEE.expandCodeFor(PtrSCEV->getStart(), Ptr->getType(),445PH->getTerminator());446Value *Initial =447new LoadInst(Cand.Load->getType(), InitialPtr, "load_initial",448/* isVolatile */ false, Cand.Load->getAlign(),449PH->getTerminator()->getIterator());450// We don't give any debug location to Initial, because it is inserted451// into the loop's preheader. A debug location inside the loop will cause452// a misleading stepping when debugging. The test update-debugloc-store453// -forwarded.ll checks this.454455PHINode *PHI = PHINode::Create(Initial->getType(), 2, "store_forwarded");456PHI->insertBefore(L->getHeader()->begin());457PHI->addIncoming(Initial, PH);458459Type *LoadType = Initial->getType();460Type *StoreType = Cand.Store->getValueOperand()->getType();461auto &DL = Cand.Load->getDataLayout();462(void)DL;463464assert(DL.getTypeSizeInBits(LoadType) == DL.getTypeSizeInBits(StoreType) &&465"The type sizes should match!");466467Value *StoreValue = Cand.Store->getValueOperand();468if (LoadType != StoreType) {469StoreValue = CastInst::CreateBitOrPointerCast(StoreValue, LoadType,470"store_forward_cast",471Cand.Store->getIterator());472// Because it casts the old `load` value and is used by the new `phi`473// which replaces the old `load`, we give the `load`'s debug location474// to it.475cast<Instruction>(StoreValue)->setDebugLoc(Cand.Load->getDebugLoc());476}477478PHI->addIncoming(StoreValue, L->getLoopLatch());479480Cand.Load->replaceAllUsesWith(PHI);481PHI->setDebugLoc(Cand.Load->getDebugLoc());482}483484/// Top-level driver for each loop: find store->load forwarding485/// candidates, add run-time checks and perform transformation.486bool processLoop() {487LLVM_DEBUG(dbgs() << "\nIn \"" << L->getHeader()->getParent()->getName()488<< "\" checking " << *L << "\n");489490// Look for store-to-load forwarding cases across the491// backedge. E.g.:492//493// loop:494// %x = load %gep_i495// = ... %x496// store %y, %gep_i_plus_1497//498// =>499//500// ph:501// %x.initial = load %gep_0502// loop:503// %x.storeforward = phi [%x.initial, %ph] [%y, %loop]504// %x = load %gep_i <---- now dead505// = ... %x.storeforward506// store %y, %gep_i_plus_1507508// First start with store->load dependences.509auto StoreToLoadDependences = findStoreToLoadDependences(LAI);510if (StoreToLoadDependences.empty())511return false;512513// Generate an index for each load and store according to the original514// program order. This will be used later.515InstOrder = LAI.getDepChecker().generateInstructionOrderMap();516517// To keep things simple for now, remove those where the load is potentially518// fed by multiple stores.519removeDependencesFromMultipleStores(StoreToLoadDependences);520if (StoreToLoadDependences.empty())521return false;522523// Filter the candidates further.524SmallVector<StoreToLoadForwardingCandidate, 4> Candidates;525for (const StoreToLoadForwardingCandidate &Cand : StoreToLoadDependences) {526LLVM_DEBUG(dbgs() << "Candidate " << Cand);527528// Make sure that the stored values is available everywhere in the loop in529// the next iteration.530if (!doesStoreDominatesAllLatches(Cand.Store->getParent(), L, DT))531continue;532533// If the load is conditional we can't hoist its 0-iteration instance to534// the preheader because that would make it unconditional. Thus we would535// access a memory location that the original loop did not access.536if (isLoadConditional(Cand.Load, L))537continue;538539// Check whether the SCEV difference is the same as the induction step,540// thus we load the value in the next iteration.541if (!Cand.isDependenceDistanceOfOne(PSE, L))542continue;543544assert(isa<SCEVAddRecExpr>(PSE.getSCEV(Cand.Load->getPointerOperand())) &&545"Loading from something other than indvar?");546assert(547isa<SCEVAddRecExpr>(PSE.getSCEV(Cand.Store->getPointerOperand())) &&548"Storing to something other than indvar?");549550Candidates.push_back(Cand);551LLVM_DEBUG(552dbgs()553<< Candidates.size()554<< ". Valid store-to-load forwarding across the loop backedge\n");555}556if (Candidates.empty())557return false;558559// Check intervening may-alias stores. These need runtime checks for alias560// disambiguation.561SmallVector<RuntimePointerCheck, 4> Checks = collectMemchecks(Candidates);562563// Too many checks are likely to outweigh the benefits of forwarding.564if (Checks.size() > Candidates.size() * CheckPerElim) {565LLVM_DEBUG(dbgs() << "Too many run-time checks needed.\n");566return false;567}568569if (LAI.getPSE().getPredicate().getComplexity() >570LoadElimSCEVCheckThreshold) {571LLVM_DEBUG(dbgs() << "Too many SCEV run-time checks needed.\n");572return false;573}574575if (!L->isLoopSimplifyForm()) {576LLVM_DEBUG(dbgs() << "Loop is not is loop-simplify form");577return false;578}579580if (!Checks.empty() || !LAI.getPSE().getPredicate().isAlwaysTrue()) {581if (LAI.hasConvergentOp()) {582LLVM_DEBUG(dbgs() << "Versioning is needed but not allowed with "583"convergent calls\n");584return false;585}586587auto *HeaderBB = L->getHeader();588auto *F = HeaderBB->getParent();589bool OptForSize = F->hasOptSize() ||590llvm::shouldOptimizeForSize(HeaderBB, PSI, BFI,591PGSOQueryType::IRPass);592if (OptForSize) {593LLVM_DEBUG(594dbgs() << "Versioning is needed but not allowed when optimizing "595"for size.\n");596return false;597}598599// Point of no-return, start the transformation. First, version the loop600// if necessary.601602LoopVersioning LV(LAI, Checks, L, LI, DT, PSE.getSE());603LV.versionLoop();604605// After versioning, some of the candidates' pointers could stop being606// SCEVAddRecs. We need to filter them out.607auto NoLongerGoodCandidate = [this](608const StoreToLoadForwardingCandidate &Cand) {609return !isa<SCEVAddRecExpr>(610PSE.getSCEV(Cand.Load->getPointerOperand())) ||611!isa<SCEVAddRecExpr>(612PSE.getSCEV(Cand.Store->getPointerOperand()));613};614llvm::erase_if(Candidates, NoLongerGoodCandidate);615}616617// Next, propagate the value stored by the store to the users of the load.618// Also for the first iteration, generate the initial value of the load.619SCEVExpander SEE(*PSE.getSE(), L->getHeader()->getDataLayout(),620"storeforward");621for (const auto &Cand : Candidates)622propagateStoredValueToLoadUsers(Cand, SEE);623NumLoopLoadEliminted += Candidates.size();624625return true;626}627628private:629Loop *L;630631/// Maps the load/store instructions to their index according to632/// program order.633DenseMap<Instruction *, unsigned> InstOrder;634635// Analyses used.636LoopInfo *LI;637const LoopAccessInfo &LAI;638DominatorTree *DT;639BlockFrequencyInfo *BFI;640ProfileSummaryInfo *PSI;641PredicatedScalarEvolution PSE;642};643644} // end anonymous namespace645646static bool eliminateLoadsAcrossLoops(Function &F, LoopInfo &LI,647DominatorTree &DT,648BlockFrequencyInfo *BFI,649ProfileSummaryInfo *PSI,650ScalarEvolution *SE, AssumptionCache *AC,651LoopAccessInfoManager &LAIs) {652// Build up a worklist of inner-loops to transform to avoid iterator653// invalidation.654// FIXME: This logic comes from other passes that actually change the loop655// nest structure. It isn't clear this is necessary (or useful) for a pass656// which merely optimizes the use of loads in a loop.657SmallVector<Loop *, 8> Worklist;658659bool Changed = false;660661for (Loop *TopLevelLoop : LI)662for (Loop *L : depth_first(TopLevelLoop)) {663Changed |= simplifyLoop(L, &DT, &LI, SE, AC, /*MSSAU*/ nullptr, false);664// We only handle inner-most loops.665if (L->isInnermost())666Worklist.push_back(L);667}668669// Now walk the identified inner loops.670for (Loop *L : Worklist) {671// Match historical behavior672if (!L->isRotatedForm() || !L->getExitingBlock())673continue;674// The actual work is performed by LoadEliminationForLoop.675LoadEliminationForLoop LEL(L, &LI, LAIs.getInfo(*L), &DT, BFI, PSI);676Changed |= LEL.processLoop();677if (Changed)678LAIs.clear();679}680return Changed;681}682683PreservedAnalyses LoopLoadEliminationPass::run(Function &F,684FunctionAnalysisManager &AM) {685auto &LI = AM.getResult<LoopAnalysis>(F);686// There are no loops in the function. Return before computing other expensive687// analyses.688if (LI.empty())689return PreservedAnalyses::all();690auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);691auto &DT = AM.getResult<DominatorTreeAnalysis>(F);692auto &AC = AM.getResult<AssumptionAnalysis>(F);693auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);694auto *PSI = MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());695auto *BFI = (PSI && PSI->hasProfileSummary()) ?696&AM.getResult<BlockFrequencyAnalysis>(F) : nullptr;697LoopAccessInfoManager &LAIs = AM.getResult<LoopAccessAnalysis>(F);698699bool Changed = eliminateLoadsAcrossLoops(F, LI, DT, BFI, PSI, &SE, &AC, LAIs);700701if (!Changed)702return PreservedAnalyses::all();703704PreservedAnalyses PA;705PA.preserve<DominatorTreeAnalysis>();706PA.preserve<LoopAnalysis>();707return PA;708}709710711