17d523365SDimitry Andric //===- LoopLoadElimination.cpp - Loop Load Elimination Pass ---------------===//
27d523365SDimitry Andric //
37d523365SDimitry Andric //                     The LLVM Compiler Infrastructure
47d523365SDimitry Andric //
57d523365SDimitry Andric // This file is distributed under the University of Illinois Open Source
67d523365SDimitry Andric // License. See LICENSE.TXT for details.
77d523365SDimitry Andric //
87d523365SDimitry Andric //===----------------------------------------------------------------------===//
97d523365SDimitry Andric //
107d523365SDimitry Andric // This file implement a loop-aware load elimination pass.
117d523365SDimitry Andric //
127d523365SDimitry Andric // It uses LoopAccessAnalysis to identify loop-carried dependences with a
137d523365SDimitry Andric // distance of one between stores and loads.  These form the candidates for the
147d523365SDimitry Andric // transformation.  The source value of each store then propagated to the user
157d523365SDimitry Andric // of the corresponding load.  This makes the load dead.
167d523365SDimitry Andric //
177d523365SDimitry Andric // The pass can also version the loop and add memchecks in order to prove that
187d523365SDimitry Andric // may-aliasing stores can't change the value in memory before it's read by the
197d523365SDimitry Andric // load.
207d523365SDimitry Andric //
217d523365SDimitry Andric //===----------------------------------------------------------------------===//
227d523365SDimitry Andric 
237a7e6055SDimitry Andric #include "llvm/Transforms/Scalar/LoopLoadElimination.h"
24d88c1a5aSDimitry Andric #include "llvm/ADT/APInt.h"
25d88c1a5aSDimitry Andric #include "llvm/ADT/DenseMap.h"
26d88c1a5aSDimitry Andric #include "llvm/ADT/DepthFirstIterator.h"
277a7e6055SDimitry Andric #include "llvm/ADT/STLExtras.h"
28*4ba319b5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
29d88c1a5aSDimitry Andric #include "llvm/ADT/SmallVector.h"
307d523365SDimitry Andric #include "llvm/ADT/Statistic.h"
312cab237bSDimitry Andric #include "llvm/Analysis/AliasAnalysis.h"
322cab237bSDimitry Andric #include "llvm/Analysis/AssumptionCache.h"
33d88c1a5aSDimitry Andric #include "llvm/Analysis/GlobalsModRef.h"
347d523365SDimitry Andric #include "llvm/Analysis/LoopAccessAnalysis.h"
352cab237bSDimitry Andric #include "llvm/Analysis/LoopAnalysisManager.h"
367d523365SDimitry Andric #include "llvm/Analysis/LoopInfo.h"
37d88c1a5aSDimitry Andric #include "llvm/Analysis/ScalarEvolution.h"
387d523365SDimitry Andric #include "llvm/Analysis/ScalarEvolutionExpander.h"
39d88c1a5aSDimitry Andric #include "llvm/Analysis/ScalarEvolutionExpressions.h"
402cab237bSDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
412cab237bSDimitry Andric #include "llvm/Analysis/TargetTransformInfo.h"
42d88c1a5aSDimitry Andric #include "llvm/IR/DataLayout.h"
437d523365SDimitry Andric #include "llvm/IR/Dominators.h"
44d88c1a5aSDimitry Andric #include "llvm/IR/Instructions.h"
457d523365SDimitry Andric #include "llvm/IR/Module.h"
462cab237bSDimitry Andric #include "llvm/IR/PassManager.h"
47d88c1a5aSDimitry Andric #include "llvm/IR/Type.h"
48d88c1a5aSDimitry Andric #include "llvm/IR/Value.h"
497d523365SDimitry Andric #include "llvm/Pass.h"
50d88c1a5aSDimitry Andric #include "llvm/Support/Casting.h"
51d88c1a5aSDimitry Andric #include "llvm/Support/CommandLine.h"
527d523365SDimitry Andric #include "llvm/Support/Debug.h"
532cab237bSDimitry Andric #include "llvm/Support/raw_ostream.h"
543ca95b02SDimitry Andric #include "llvm/Transforms/Scalar.h"
55*4ba319b5SDimitry Andric #include "llvm/Transforms/Utils.h"
567d523365SDimitry Andric #include "llvm/Transforms/Utils/LoopVersioning.h"
57d88c1a5aSDimitry Andric #include <algorithm>
587a7e6055SDimitry Andric #include <cassert>
597a7e6055SDimitry Andric #include <forward_list>
60d88c1a5aSDimitry Andric #include <set>
61d88c1a5aSDimitry Andric #include <tuple>
62d88c1a5aSDimitry Andric #include <utility>
637d523365SDimitry Andric 
642cab237bSDimitry Andric using namespace llvm;
652cab237bSDimitry Andric 
667d523365SDimitry Andric #define LLE_OPTION "loop-load-elim"
677d523365SDimitry Andric #define DEBUG_TYPE LLE_OPTION
687d523365SDimitry Andric 
697d523365SDimitry Andric static cl::opt<unsigned> CheckPerElim(
707d523365SDimitry Andric     "runtime-check-per-loop-load-elim", cl::Hidden,
717d523365SDimitry Andric     cl::desc("Max number of memchecks allowed per eliminated load on average"),
727d523365SDimitry Andric     cl::init(1));
737d523365SDimitry Andric 
747d523365SDimitry Andric static cl::opt<unsigned> LoadElimSCEVCheckThreshold(
757d523365SDimitry Andric     "loop-load-elimination-scev-check-threshold", cl::init(8), cl::Hidden,
767d523365SDimitry Andric     cl::desc("The maximum number of SCEV checks allowed for Loop "
777d523365SDimitry Andric              "Load Elimination"));
787d523365SDimitry Andric 
797d523365SDimitry Andric STATISTIC(NumLoopLoadEliminted, "Number of loads eliminated by LLE");
807d523365SDimitry Andric 
817d523365SDimitry Andric namespace {
827d523365SDimitry Andric 
83*4ba319b5SDimitry Andric /// Represent a store-to-forwarding candidate.
847d523365SDimitry Andric struct StoreToLoadForwardingCandidate {
857d523365SDimitry Andric   LoadInst *Load;
867d523365SDimitry Andric   StoreInst *Store;
877d523365SDimitry Andric 
StoreToLoadForwardingCandidate__anonb1751c6b0111::StoreToLoadForwardingCandidate887d523365SDimitry Andric   StoreToLoadForwardingCandidate(LoadInst *Load, StoreInst *Store)
897d523365SDimitry Andric       : Load(Load), Store(Store) {}
907d523365SDimitry Andric 
91*4ba319b5SDimitry Andric   /// Return true if the dependence from the store to the load has a
927d523365SDimitry Andric   /// distance of one.  E.g. A[i+1] = A[i]
isDependenceDistanceOfOne__anonb1751c6b0111::StoreToLoadForwardingCandidate933ca95b02SDimitry Andric   bool isDependenceDistanceOfOne(PredicatedScalarEvolution &PSE,
943ca95b02SDimitry Andric                                  Loop *L) const {
957d523365SDimitry Andric     Value *LoadPtr = Load->getPointerOperand();
967d523365SDimitry Andric     Value *StorePtr = Store->getPointerOperand();
977d523365SDimitry Andric     Type *LoadPtrType = LoadPtr->getType();
987d523365SDimitry Andric     Type *LoadType = LoadPtrType->getPointerElementType();
997d523365SDimitry Andric 
1007d523365SDimitry Andric     assert(LoadPtrType->getPointerAddressSpace() ==
1017d523365SDimitry Andric                StorePtr->getType()->getPointerAddressSpace() &&
1027d523365SDimitry Andric            LoadType == StorePtr->getType()->getPointerElementType() &&
1037d523365SDimitry Andric            "Should be a known dependence");
1047d523365SDimitry Andric 
1053ca95b02SDimitry Andric     // Currently we only support accesses with unit stride.  FIXME: we should be
1063ca95b02SDimitry Andric     // able to handle non unit stirde as well as long as the stride is equal to
1073ca95b02SDimitry Andric     // the dependence distance.
1083ca95b02SDimitry Andric     if (getPtrStride(PSE, LoadPtr, L) != 1 ||
1093ca95b02SDimitry Andric         getPtrStride(PSE, StorePtr, L) != 1)
1103ca95b02SDimitry Andric       return false;
1113ca95b02SDimitry Andric 
1127d523365SDimitry Andric     auto &DL = Load->getParent()->getModule()->getDataLayout();
1137d523365SDimitry Andric     unsigned TypeByteSize = DL.getTypeAllocSize(const_cast<Type *>(LoadType));
1147d523365SDimitry Andric 
1157d523365SDimitry Andric     auto *LoadPtrSCEV = cast<SCEVAddRecExpr>(PSE.getSCEV(LoadPtr));
1167d523365SDimitry Andric     auto *StorePtrSCEV = cast<SCEVAddRecExpr>(PSE.getSCEV(StorePtr));
1177d523365SDimitry Andric 
1187d523365SDimitry Andric     // We don't need to check non-wrapping here because forward/backward
1197d523365SDimitry Andric     // dependence wouldn't be valid if these weren't monotonic accesses.
1207d523365SDimitry Andric     auto *Dist = cast<SCEVConstant>(
1217d523365SDimitry Andric         PSE.getSE()->getMinusSCEV(StorePtrSCEV, LoadPtrSCEV));
1227d523365SDimitry Andric     const APInt &Val = Dist->getAPInt();
1233ca95b02SDimitry Andric     return Val == TypeByteSize;
1247d523365SDimitry Andric   }
1257d523365SDimitry Andric 
getLoadPtr__anonb1751c6b0111::StoreToLoadForwardingCandidate1267d523365SDimitry Andric   Value *getLoadPtr() const { return Load->getPointerOperand(); }
1277d523365SDimitry Andric 
1287d523365SDimitry Andric #ifndef NDEBUG
operator <<(raw_ostream & OS,const StoreToLoadForwardingCandidate & Cand)1297d523365SDimitry Andric   friend raw_ostream &operator<<(raw_ostream &OS,
1307d523365SDimitry Andric                                  const StoreToLoadForwardingCandidate &Cand) {
1317d523365SDimitry Andric     OS << *Cand.Store << " -->\n";
1327d523365SDimitry Andric     OS.indent(2) << *Cand.Load << "\n";
1337d523365SDimitry Andric     return OS;
1347d523365SDimitry Andric   }
1357d523365SDimitry Andric #endif
1367d523365SDimitry Andric };
1377d523365SDimitry Andric 
1382cab237bSDimitry Andric } // end anonymous namespace
1392cab237bSDimitry Andric 
140*4ba319b5SDimitry Andric /// Check if the store dominates all latches, so as long as there is no
1417d523365SDimitry Andric /// intervening store this value will be loaded in the next iteration.
doesStoreDominatesAllLatches(BasicBlock * StoreBlock,Loop * L,DominatorTree * DT)1422cab237bSDimitry Andric static bool doesStoreDominatesAllLatches(BasicBlock *StoreBlock, Loop *L,
1437d523365SDimitry Andric                                          DominatorTree *DT) {
1447d523365SDimitry Andric   SmallVector<BasicBlock *, 8> Latches;
1457d523365SDimitry Andric   L->getLoopLatches(Latches);
146d88c1a5aSDimitry Andric   return llvm::all_of(Latches, [&](const BasicBlock *Latch) {
1477d523365SDimitry Andric     return DT->dominates(StoreBlock, Latch);
1487d523365SDimitry Andric   });
1497d523365SDimitry Andric }
1507d523365SDimitry Andric 
151*4ba319b5SDimitry Andric /// Return true if the load is not executed on all paths in the loop.
isLoadConditional(LoadInst * Load,Loop * L)1523ca95b02SDimitry Andric static bool isLoadConditional(LoadInst *Load, Loop *L) {
1533ca95b02SDimitry Andric   return Load->getParent() != L->getHeader();
1543ca95b02SDimitry Andric }
1553ca95b02SDimitry Andric 
1562cab237bSDimitry Andric namespace {
1572cab237bSDimitry Andric 
158*4ba319b5SDimitry Andric /// The per-loop class that does most of the work.
1597d523365SDimitry Andric class LoadEliminationForLoop {
1607d523365SDimitry Andric public:
LoadEliminationForLoop(Loop * L,LoopInfo * LI,const LoopAccessInfo & LAI,DominatorTree * DT)1617d523365SDimitry Andric   LoadEliminationForLoop(Loop *L, LoopInfo *LI, const LoopAccessInfo &LAI,
1627d523365SDimitry Andric                          DominatorTree *DT)
1633ca95b02SDimitry Andric       : L(L), LI(LI), LAI(LAI), DT(DT), PSE(LAI.getPSE()) {}
1647d523365SDimitry Andric 
165*4ba319b5SDimitry Andric   /// Look through the loop-carried and loop-independent dependences in
1667d523365SDimitry Andric   /// this loop and find store->load dependences.
1677d523365SDimitry Andric   ///
1687d523365SDimitry Andric   /// Note that no candidate is returned if LAA has failed to analyze the loop
1697d523365SDimitry Andric   /// (e.g. if it's not bottom-tested, contains volatile memops, etc.)
1707d523365SDimitry Andric   std::forward_list<StoreToLoadForwardingCandidate>
findStoreToLoadDependences(const LoopAccessInfo & LAI)1717d523365SDimitry Andric   findStoreToLoadDependences(const LoopAccessInfo &LAI) {
1727d523365SDimitry Andric     std::forward_list<StoreToLoadForwardingCandidate> Candidates;
1737d523365SDimitry Andric 
1747d523365SDimitry Andric     const auto *Deps = LAI.getDepChecker().getDependences();
1757d523365SDimitry Andric     if (!Deps)
1767d523365SDimitry Andric       return Candidates;
1777d523365SDimitry Andric 
1787d523365SDimitry Andric     // Find store->load dependences (consequently true dep).  Both lexically
1797d523365SDimitry Andric     // forward and backward dependences qualify.  Disqualify loads that have
1807d523365SDimitry Andric     // other unknown dependences.
1817d523365SDimitry Andric 
182*4ba319b5SDimitry Andric     SmallPtrSet<Instruction *, 4> LoadsWithUnknownDepedence;
1837d523365SDimitry Andric 
1847d523365SDimitry Andric     for (const auto &Dep : *Deps) {
1857d523365SDimitry Andric       Instruction *Source = Dep.getSource(LAI);
1867d523365SDimitry Andric       Instruction *Destination = Dep.getDestination(LAI);
1877d523365SDimitry Andric 
1887d523365SDimitry Andric       if (Dep.Type == MemoryDepChecker::Dependence::Unknown) {
1897d523365SDimitry Andric         if (isa<LoadInst>(Source))
1907d523365SDimitry Andric           LoadsWithUnknownDepedence.insert(Source);
1917d523365SDimitry Andric         if (isa<LoadInst>(Destination))
1927d523365SDimitry Andric           LoadsWithUnknownDepedence.insert(Destination);
1937d523365SDimitry Andric         continue;
1947d523365SDimitry Andric       }
1957d523365SDimitry Andric 
1967d523365SDimitry Andric       if (Dep.isBackward())
1977d523365SDimitry Andric         // Note that the designations source and destination follow the program
1987d523365SDimitry Andric         // order, i.e. source is always first.  (The direction is given by the
1997d523365SDimitry Andric         // DepType.)
2007d523365SDimitry Andric         std::swap(Source, Destination);
2017d523365SDimitry Andric       else
2027d523365SDimitry Andric         assert(Dep.isForward() && "Needs to be a forward dependence");
2037d523365SDimitry Andric 
2047d523365SDimitry Andric       auto *Store = dyn_cast<StoreInst>(Source);
2057d523365SDimitry Andric       if (!Store)
2067d523365SDimitry Andric         continue;
2077d523365SDimitry Andric       auto *Load = dyn_cast<LoadInst>(Destination);
2087d523365SDimitry Andric       if (!Load)
2097d523365SDimitry Andric         continue;
2103ca95b02SDimitry Andric 
2113ca95b02SDimitry Andric       // Only progagate the value if they are of the same type.
2126bc11b14SDimitry Andric       if (Store->getPointerOperandType() != Load->getPointerOperandType())
2133ca95b02SDimitry Andric         continue;
2143ca95b02SDimitry Andric 
2157d523365SDimitry Andric       Candidates.emplace_front(Load, Store);
2167d523365SDimitry Andric     }
2177d523365SDimitry Andric 
2187d523365SDimitry Andric     if (!LoadsWithUnknownDepedence.empty())
2197d523365SDimitry Andric       Candidates.remove_if([&](const StoreToLoadForwardingCandidate &C) {
2207d523365SDimitry Andric         return LoadsWithUnknownDepedence.count(C.Load);
2217d523365SDimitry Andric       });
2227d523365SDimitry Andric 
2237d523365SDimitry Andric     return Candidates;
2247d523365SDimitry Andric   }
2257d523365SDimitry Andric 
226*4ba319b5SDimitry Andric   /// Return the index of the instruction according to program order.
getInstrIndex(Instruction * Inst)2277d523365SDimitry Andric   unsigned getInstrIndex(Instruction *Inst) {
2287d523365SDimitry Andric     auto I = InstOrder.find(Inst);
2297d523365SDimitry Andric     assert(I != InstOrder.end() && "No index for instruction");
2307d523365SDimitry Andric     return I->second;
2317d523365SDimitry Andric   }
2327d523365SDimitry Andric 
233*4ba319b5SDimitry Andric   /// If a load has multiple candidates associated (i.e. different
2347d523365SDimitry Andric   /// stores), it means that it could be forwarding from multiple stores
2357d523365SDimitry Andric   /// depending on control flow.  Remove these candidates.
2367d523365SDimitry Andric   ///
2377d523365SDimitry Andric   /// Here, we rely on LAA to include the relevant loop-independent dependences.
2387d523365SDimitry Andric   /// LAA is known to omit these in the very simple case when the read and the
2397d523365SDimitry Andric   /// write within an alias set always takes place using the *same* pointer.
2407d523365SDimitry Andric   ///
2417d523365SDimitry Andric   /// However, we know that this is not the case here, i.e. we can rely on LAA
2427d523365SDimitry Andric   /// to provide us with loop-independent dependences for the cases we're
2437d523365SDimitry Andric   /// interested.  Consider the case for example where a loop-independent
2447d523365SDimitry Andric   /// dependece S1->S2 invalidates the forwarding S3->S2.
2457d523365SDimitry Andric   ///
2467d523365SDimitry Andric   ///         A[i]   = ...   (S1)
2477d523365SDimitry Andric   ///         ...    = A[i]  (S2)
2487d523365SDimitry Andric   ///         A[i+1] = ...   (S3)
2497d523365SDimitry Andric   ///
2507d523365SDimitry Andric   /// LAA will perform dependence analysis here because there are two
2517d523365SDimitry Andric   /// *different* pointers involved in the same alias set (&A[i] and &A[i+1]).
removeDependencesFromMultipleStores(std::forward_list<StoreToLoadForwardingCandidate> & Candidates)2527d523365SDimitry Andric   void removeDependencesFromMultipleStores(
2537d523365SDimitry Andric       std::forward_list<StoreToLoadForwardingCandidate> &Candidates) {
2547d523365SDimitry Andric     // If Store is nullptr it means that we have multiple stores forwarding to
2557d523365SDimitry Andric     // this store.
2562cab237bSDimitry Andric     using LoadToSingleCandT =
2572cab237bSDimitry Andric         DenseMap<LoadInst *, const StoreToLoadForwardingCandidate *>;
2587d523365SDimitry Andric     LoadToSingleCandT LoadToSingleCand;
2597d523365SDimitry Andric 
2607d523365SDimitry Andric     for (const auto &Cand : Candidates) {
2617d523365SDimitry Andric       bool NewElt;
2627d523365SDimitry Andric       LoadToSingleCandT::iterator Iter;
2637d523365SDimitry Andric 
2647d523365SDimitry Andric       std::tie(Iter, NewElt) =
2657d523365SDimitry Andric           LoadToSingleCand.insert(std::make_pair(Cand.Load, &Cand));
2667d523365SDimitry Andric       if (!NewElt) {
2677d523365SDimitry Andric         const StoreToLoadForwardingCandidate *&OtherCand = Iter->second;
2687d523365SDimitry Andric         // Already multiple stores forward to this load.
2697d523365SDimitry Andric         if (OtherCand == nullptr)
2707d523365SDimitry Andric           continue;
2717d523365SDimitry Andric 
2723ca95b02SDimitry Andric         // Handle the very basic case when the two stores are in the same block
2733ca95b02SDimitry Andric         // so deciding which one forwards is easy.  The later one forwards as
2743ca95b02SDimitry Andric         // long as they both have a dependence distance of one to the load.
2757d523365SDimitry Andric         if (Cand.Store->getParent() == OtherCand->Store->getParent() &&
2763ca95b02SDimitry Andric             Cand.isDependenceDistanceOfOne(PSE, L) &&
2773ca95b02SDimitry Andric             OtherCand->isDependenceDistanceOfOne(PSE, L)) {
2787d523365SDimitry Andric           // They are in the same block, the later one will forward to the load.
2797d523365SDimitry Andric           if (getInstrIndex(OtherCand->Store) < getInstrIndex(Cand.Store))
2807d523365SDimitry Andric             OtherCand = &Cand;
2817d523365SDimitry Andric         } else
2827d523365SDimitry Andric           OtherCand = nullptr;
2837d523365SDimitry Andric       }
2847d523365SDimitry Andric     }
2857d523365SDimitry Andric 
2867d523365SDimitry Andric     Candidates.remove_if([&](const StoreToLoadForwardingCandidate &Cand) {
2877d523365SDimitry Andric       if (LoadToSingleCand[Cand.Load] != &Cand) {
288*4ba319b5SDimitry Andric         LLVM_DEBUG(
289*4ba319b5SDimitry Andric             dbgs() << "Removing from candidates: \n"
290*4ba319b5SDimitry Andric                    << Cand
2917d523365SDimitry Andric                    << "  The load may have multiple stores forwarding to "
2927d523365SDimitry Andric                    << "it\n");
2937d523365SDimitry Andric         return true;
2947d523365SDimitry Andric       }
2957d523365SDimitry Andric       return false;
2967d523365SDimitry Andric     });
2977d523365SDimitry Andric   }
2987d523365SDimitry Andric 
299*4ba319b5SDimitry Andric   /// Given two pointers operations by their RuntimePointerChecking
3007d523365SDimitry Andric   /// indices, return true if they require an alias check.
3017d523365SDimitry Andric   ///
3027d523365SDimitry Andric   /// We need a check if one is a pointer for a candidate load and the other is
3037d523365SDimitry Andric   /// a pointer for a possibly intervening store.
needsChecking(unsigned PtrIdx1,unsigned PtrIdx2,const SmallPtrSet<Value *,4> & PtrsWrittenOnFwdingPath,const std::set<Value * > & CandLoadPtrs)3047d523365SDimitry Andric   bool needsChecking(unsigned PtrIdx1, unsigned PtrIdx2,
305*4ba319b5SDimitry Andric                      const SmallPtrSet<Value *, 4> &PtrsWrittenOnFwdingPath,
3067d523365SDimitry Andric                      const std::set<Value *> &CandLoadPtrs) {
3077d523365SDimitry Andric     Value *Ptr1 =
3087d523365SDimitry Andric         LAI.getRuntimePointerChecking()->getPointerInfo(PtrIdx1).PointerValue;
3097d523365SDimitry Andric     Value *Ptr2 =
3107d523365SDimitry Andric         LAI.getRuntimePointerChecking()->getPointerInfo(PtrIdx2).PointerValue;
3117d523365SDimitry Andric     return ((PtrsWrittenOnFwdingPath.count(Ptr1) && CandLoadPtrs.count(Ptr2)) ||
3127d523365SDimitry Andric             (PtrsWrittenOnFwdingPath.count(Ptr2) && CandLoadPtrs.count(Ptr1)));
3137d523365SDimitry Andric   }
3147d523365SDimitry Andric 
315*4ba319b5SDimitry Andric   /// Return pointers that are possibly written to on the path from a
3167d523365SDimitry Andric   /// forwarding store to a load.
3177d523365SDimitry Andric   ///
3187d523365SDimitry Andric   /// These pointers need to be alias-checked against the forwarding candidates.
findPointersWrittenOnForwardingPath(const SmallVectorImpl<StoreToLoadForwardingCandidate> & Candidates)319*4ba319b5SDimitry Andric   SmallPtrSet<Value *, 4> findPointersWrittenOnForwardingPath(
3207d523365SDimitry Andric       const SmallVectorImpl<StoreToLoadForwardingCandidate> &Candidates) {
3217d523365SDimitry Andric     // From FirstStore to LastLoad neither of the elimination candidate loads
3227d523365SDimitry Andric     // should overlap with any of the stores.
3237d523365SDimitry Andric     //
3247d523365SDimitry Andric     // E.g.:
3257d523365SDimitry Andric     //
3267d523365SDimitry Andric     // st1 C[i]
3277d523365SDimitry Andric     // ld1 B[i] <-------,
3287d523365SDimitry Andric     // ld0 A[i] <----,  |              * LastLoad
3297d523365SDimitry Andric     // ...           |  |
3307d523365SDimitry Andric     // st2 E[i]      |  |
3317d523365SDimitry Andric     // st3 B[i+1] -- | -'              * FirstStore
3327d523365SDimitry Andric     // st0 A[i+1] ---'
3337d523365SDimitry Andric     // st4 D[i]
3347d523365SDimitry Andric     //
3357d523365SDimitry Andric     // st0 forwards to ld0 if the accesses in st4 and st1 don't overlap with
3367d523365SDimitry Andric     // ld0.
3377d523365SDimitry Andric 
3387d523365SDimitry Andric     LoadInst *LastLoad =
3397d523365SDimitry Andric         std::max_element(Candidates.begin(), Candidates.end(),
3407d523365SDimitry Andric                          [&](const StoreToLoadForwardingCandidate &A,
3417d523365SDimitry Andric                              const StoreToLoadForwardingCandidate &B) {
3427d523365SDimitry Andric                            return getInstrIndex(A.Load) < getInstrIndex(B.Load);
3437d523365SDimitry Andric                          })
3447d523365SDimitry Andric             ->Load;
3457d523365SDimitry Andric     StoreInst *FirstStore =
3467d523365SDimitry Andric         std::min_element(Candidates.begin(), Candidates.end(),
3477d523365SDimitry Andric                          [&](const StoreToLoadForwardingCandidate &A,
3487d523365SDimitry Andric                              const StoreToLoadForwardingCandidate &B) {
3497d523365SDimitry Andric                            return getInstrIndex(A.Store) <
3507d523365SDimitry Andric                                   getInstrIndex(B.Store);
3517d523365SDimitry Andric                          })
3527d523365SDimitry Andric             ->Store;
3537d523365SDimitry Andric 
3547d523365SDimitry Andric     // We're looking for stores after the first forwarding store until the end
3557d523365SDimitry Andric     // of the loop, then from the beginning of the loop until the last
3567d523365SDimitry Andric     // forwarded-to load.  Collect the pointer for the stores.
357*4ba319b5SDimitry Andric     SmallPtrSet<Value *, 4> PtrsWrittenOnFwdingPath;
3587d523365SDimitry Andric 
3597d523365SDimitry Andric     auto InsertStorePtr = [&](Instruction *I) {
3607d523365SDimitry Andric       if (auto *S = dyn_cast<StoreInst>(I))
3617d523365SDimitry Andric         PtrsWrittenOnFwdingPath.insert(S->getPointerOperand());
3627d523365SDimitry Andric     };
3637d523365SDimitry Andric     const auto &MemInstrs = LAI.getDepChecker().getMemoryInstructions();
3647d523365SDimitry Andric     std::for_each(MemInstrs.begin() + getInstrIndex(FirstStore) + 1,
3657d523365SDimitry Andric                   MemInstrs.end(), InsertStorePtr);
3667d523365SDimitry Andric     std::for_each(MemInstrs.begin(), &MemInstrs[getInstrIndex(LastLoad)],
3677d523365SDimitry Andric                   InsertStorePtr);
3687d523365SDimitry Andric 
3697d523365SDimitry Andric     return PtrsWrittenOnFwdingPath;
3707d523365SDimitry Andric   }
3717d523365SDimitry Andric 
372*4ba319b5SDimitry Andric   /// Determine the pointer alias checks to prove that there are no
3737d523365SDimitry Andric   /// intervening stores.
collectMemchecks(const SmallVectorImpl<StoreToLoadForwardingCandidate> & Candidates)3747d523365SDimitry Andric   SmallVector<RuntimePointerChecking::PointerCheck, 4> collectMemchecks(
3757d523365SDimitry Andric       const SmallVectorImpl<StoreToLoadForwardingCandidate> &Candidates) {
3767d523365SDimitry Andric 
377*4ba319b5SDimitry Andric     SmallPtrSet<Value *, 4> PtrsWrittenOnFwdingPath =
3787d523365SDimitry Andric         findPointersWrittenOnForwardingPath(Candidates);
3797d523365SDimitry Andric 
3807d523365SDimitry Andric     // Collect the pointers of the candidate loads.
381*4ba319b5SDimitry Andric     // FIXME: SmallPtrSet does not work with std::inserter.
3827d523365SDimitry Andric     std::set<Value *> CandLoadPtrs;
383d88c1a5aSDimitry Andric     transform(Candidates,
3847d523365SDimitry Andric                    std::inserter(CandLoadPtrs, CandLoadPtrs.begin()),
3857d523365SDimitry Andric                    std::mem_fn(&StoreToLoadForwardingCandidate::getLoadPtr));
3867d523365SDimitry Andric 
3877d523365SDimitry Andric     const auto &AllChecks = LAI.getRuntimePointerChecking()->getChecks();
3887d523365SDimitry Andric     SmallVector<RuntimePointerChecking::PointerCheck, 4> Checks;
3897d523365SDimitry Andric 
3907a7e6055SDimitry Andric     copy_if(AllChecks, std::back_inserter(Checks),
3917d523365SDimitry Andric             [&](const RuntimePointerChecking::PointerCheck &Check) {
3927d523365SDimitry Andric               for (auto PtrIdx1 : Check.first->Members)
3937d523365SDimitry Andric                 for (auto PtrIdx2 : Check.second->Members)
3947a7e6055SDimitry Andric                   if (needsChecking(PtrIdx1, PtrIdx2, PtrsWrittenOnFwdingPath,
3957a7e6055SDimitry Andric                                     CandLoadPtrs))
3967d523365SDimitry Andric                     return true;
3977d523365SDimitry Andric               return false;
3987d523365SDimitry Andric             });
3997d523365SDimitry Andric 
400*4ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "\nPointer Checks (count: " << Checks.size()
401*4ba319b5SDimitry Andric                       << "):\n");
402*4ba319b5SDimitry Andric     LLVM_DEBUG(LAI.getRuntimePointerChecking()->printChecks(dbgs(), Checks));
4037d523365SDimitry Andric 
4047d523365SDimitry Andric     return Checks;
4057d523365SDimitry Andric   }
4067d523365SDimitry Andric 
407*4ba319b5SDimitry Andric   /// Perform the transformation for a candidate.
4087d523365SDimitry Andric   void
propagateStoredValueToLoadUsers(const StoreToLoadForwardingCandidate & Cand,SCEVExpander & SEE)4097d523365SDimitry Andric   propagateStoredValueToLoadUsers(const StoreToLoadForwardingCandidate &Cand,
4107d523365SDimitry Andric                                   SCEVExpander &SEE) {
4117d523365SDimitry Andric     // loop:
4127d523365SDimitry Andric     //      %x = load %gep_i
4137d523365SDimitry Andric     //         = ... %x
4147d523365SDimitry Andric     //      store %y, %gep_i_plus_1
4157d523365SDimitry Andric     //
4167d523365SDimitry Andric     // =>
4177d523365SDimitry Andric     //
4187d523365SDimitry Andric     // ph:
4197d523365SDimitry Andric     //      %x.initial = load %gep_0
4207d523365SDimitry Andric     // loop:
4217d523365SDimitry Andric     //      %x.storeforward = phi [%x.initial, %ph] [%y, %loop]
4227d523365SDimitry Andric     //      %x = load %gep_i            <---- now dead
4237d523365SDimitry Andric     //         = ... %x.storeforward
4247d523365SDimitry Andric     //      store %y, %gep_i_plus_1
4257d523365SDimitry Andric 
4267d523365SDimitry Andric     Value *Ptr = Cand.Load->getPointerOperand();
4277d523365SDimitry Andric     auto *PtrSCEV = cast<SCEVAddRecExpr>(PSE.getSCEV(Ptr));
4287d523365SDimitry Andric     auto *PH = L->getLoopPreheader();
4297d523365SDimitry Andric     Value *InitialPtr = SEE.expandCodeFor(PtrSCEV->getStart(), Ptr->getType(),
4307d523365SDimitry Andric                                           PH->getTerminator());
4317d523365SDimitry Andric     Value *Initial =
43224e2fe98SDimitry Andric         new LoadInst(InitialPtr, "load_initial", /* isVolatile */ false,
43324e2fe98SDimitry Andric                      Cand.Load->getAlignment(), PH->getTerminator());
43424e2fe98SDimitry Andric 
4357d523365SDimitry Andric     PHINode *PHI = PHINode::Create(Initial->getType(), 2, "store_forwarded",
4367d523365SDimitry Andric                                    &L->getHeader()->front());
4377d523365SDimitry Andric     PHI->addIncoming(Initial, PH);
4387d523365SDimitry Andric     PHI->addIncoming(Cand.Store->getOperand(0), L->getLoopLatch());
4397d523365SDimitry Andric 
4407d523365SDimitry Andric     Cand.Load->replaceAllUsesWith(PHI);
4417d523365SDimitry Andric   }
4427d523365SDimitry Andric 
443*4ba319b5SDimitry Andric   /// Top-level driver for each loop: find store->load forwarding
4447d523365SDimitry Andric   /// candidates, add run-time checks and perform transformation.
processLoop()4457d523365SDimitry Andric   bool processLoop() {
446*4ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "\nIn \"" << L->getHeader()->getParent()->getName()
4477d523365SDimitry Andric                       << "\" checking " << *L << "\n");
4482cab237bSDimitry Andric 
4497d523365SDimitry Andric     // Look for store-to-load forwarding cases across the
4507d523365SDimitry Andric     // backedge. E.g.:
4517d523365SDimitry Andric     //
4527d523365SDimitry Andric     // loop:
4537d523365SDimitry Andric     //      %x = load %gep_i
4547d523365SDimitry Andric     //         = ... %x
4557d523365SDimitry Andric     //      store %y, %gep_i_plus_1
4567d523365SDimitry Andric     //
4577d523365SDimitry Andric     // =>
4587d523365SDimitry Andric     //
4597d523365SDimitry Andric     // ph:
4607d523365SDimitry Andric     //      %x.initial = load %gep_0
4617d523365SDimitry Andric     // loop:
4627d523365SDimitry Andric     //      %x.storeforward = phi [%x.initial, %ph] [%y, %loop]
4637d523365SDimitry Andric     //      %x = load %gep_i            <---- now dead
4647d523365SDimitry Andric     //         = ... %x.storeforward
4657d523365SDimitry Andric     //      store %y, %gep_i_plus_1
4667d523365SDimitry Andric 
4677d523365SDimitry Andric     // First start with store->load dependences.
4687d523365SDimitry Andric     auto StoreToLoadDependences = findStoreToLoadDependences(LAI);
4697d523365SDimitry Andric     if (StoreToLoadDependences.empty())
4707d523365SDimitry Andric       return false;
4717d523365SDimitry Andric 
4727d523365SDimitry Andric     // Generate an index for each load and store according to the original
4737d523365SDimitry Andric     // program order.  This will be used later.
4747d523365SDimitry Andric     InstOrder = LAI.getDepChecker().generateInstructionOrderMap();
4757d523365SDimitry Andric 
4767d523365SDimitry Andric     // To keep things simple for now, remove those where the load is potentially
4777d523365SDimitry Andric     // fed by multiple stores.
4787d523365SDimitry Andric     removeDependencesFromMultipleStores(StoreToLoadDependences);
4797d523365SDimitry Andric     if (StoreToLoadDependences.empty())
4807d523365SDimitry Andric       return false;
4817d523365SDimitry Andric 
4827d523365SDimitry Andric     // Filter the candidates further.
4837d523365SDimitry Andric     SmallVector<StoreToLoadForwardingCandidate, 4> Candidates;
4847d523365SDimitry Andric     unsigned NumForwarding = 0;
4857d523365SDimitry Andric     for (const StoreToLoadForwardingCandidate Cand : StoreToLoadDependences) {
486*4ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "Candidate " << Cand);
4873ca95b02SDimitry Andric 
4887d523365SDimitry Andric       // Make sure that the stored values is available everywhere in the loop in
4897d523365SDimitry Andric       // the next iteration.
4907d523365SDimitry Andric       if (!doesStoreDominatesAllLatches(Cand.Store->getParent(), L, DT))
4917d523365SDimitry Andric         continue;
4927d523365SDimitry Andric 
4933ca95b02SDimitry Andric       // If the load is conditional we can't hoist its 0-iteration instance to
4943ca95b02SDimitry Andric       // the preheader because that would make it unconditional.  Thus we would
4953ca95b02SDimitry Andric       // access a memory location that the original loop did not access.
4963ca95b02SDimitry Andric       if (isLoadConditional(Cand.Load, L))
4973ca95b02SDimitry Andric         continue;
4983ca95b02SDimitry Andric 
4997d523365SDimitry Andric       // Check whether the SCEV difference is the same as the induction step,
5007d523365SDimitry Andric       // thus we load the value in the next iteration.
5013ca95b02SDimitry Andric       if (!Cand.isDependenceDistanceOfOne(PSE, L))
5027d523365SDimitry Andric         continue;
5037d523365SDimitry Andric 
5047d523365SDimitry Andric       ++NumForwarding;
505*4ba319b5SDimitry Andric       LLVM_DEBUG(
506*4ba319b5SDimitry Andric           dbgs()
5077d523365SDimitry Andric           << NumForwarding
5087d523365SDimitry Andric           << ". Valid store-to-load forwarding across the loop backedge\n");
5097d523365SDimitry Andric       Candidates.push_back(Cand);
5107d523365SDimitry Andric     }
5117d523365SDimitry Andric     if (Candidates.empty())
5127d523365SDimitry Andric       return false;
5137d523365SDimitry Andric 
5147d523365SDimitry Andric     // Check intervening may-alias stores.  These need runtime checks for alias
5157d523365SDimitry Andric     // disambiguation.
5167d523365SDimitry Andric     SmallVector<RuntimePointerChecking::PointerCheck, 4> Checks =
5177d523365SDimitry Andric         collectMemchecks(Candidates);
5187d523365SDimitry Andric 
5197d523365SDimitry Andric     // Too many checks are likely to outweigh the benefits of forwarding.
5207d523365SDimitry Andric     if (Checks.size() > Candidates.size() * CheckPerElim) {
521*4ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "Too many run-time checks needed.\n");
5227d523365SDimitry Andric       return false;
5237d523365SDimitry Andric     }
5247d523365SDimitry Andric 
5253ca95b02SDimitry Andric     if (LAI.getPSE().getUnionPredicate().getComplexity() >
5267d523365SDimitry Andric         LoadElimSCEVCheckThreshold) {
527*4ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "Too many SCEV run-time checks needed.\n");
5287d523365SDimitry Andric       return false;
5297d523365SDimitry Andric     }
5307d523365SDimitry Andric 
5313ca95b02SDimitry Andric     if (!Checks.empty() || !LAI.getPSE().getUnionPredicate().isAlwaysTrue()) {
5323ca95b02SDimitry Andric       if (L->getHeader()->getParent()->optForSize()) {
533*4ba319b5SDimitry Andric         LLVM_DEBUG(
534*4ba319b5SDimitry Andric             dbgs() << "Versioning is needed but not allowed when optimizing "
5353ca95b02SDimitry Andric                       "for size.\n");
5363ca95b02SDimitry Andric         return false;
5373ca95b02SDimitry Andric       }
5383ca95b02SDimitry Andric 
539d88c1a5aSDimitry Andric       if (!L->isLoopSimplifyForm()) {
540*4ba319b5SDimitry Andric         LLVM_DEBUG(dbgs() << "Loop is not is loop-simplify form");
541d88c1a5aSDimitry Andric         return false;
542d88c1a5aSDimitry Andric       }
543d88c1a5aSDimitry Andric 
5443ca95b02SDimitry Andric       // Point of no-return, start the transformation.  First, version the loop
5453ca95b02SDimitry Andric       // if necessary.
5463ca95b02SDimitry Andric 
5477d523365SDimitry Andric       LoopVersioning LV(LAI, L, LI, DT, PSE.getSE(), false);
5487d523365SDimitry Andric       LV.setAliasChecks(std::move(Checks));
5493ca95b02SDimitry Andric       LV.setSCEVChecks(LAI.getPSE().getUnionPredicate());
5507d523365SDimitry Andric       LV.versionLoop();
5517d523365SDimitry Andric     }
5527d523365SDimitry Andric 
5537d523365SDimitry Andric     // Next, propagate the value stored by the store to the users of the load.
5547d523365SDimitry Andric     // Also for the first iteration, generate the initial value of the load.
5557d523365SDimitry Andric     SCEVExpander SEE(*PSE.getSE(), L->getHeader()->getModule()->getDataLayout(),
5567d523365SDimitry Andric                      "storeforward");
5577d523365SDimitry Andric     for (const auto &Cand : Candidates)
5587d523365SDimitry Andric       propagateStoredValueToLoadUsers(Cand, SEE);
5597d523365SDimitry Andric     NumLoopLoadEliminted += NumForwarding;
5607d523365SDimitry Andric 
5617d523365SDimitry Andric     return true;
5627d523365SDimitry Andric   }
5637d523365SDimitry Andric 
5647d523365SDimitry Andric private:
5657d523365SDimitry Andric   Loop *L;
5667d523365SDimitry Andric 
567*4ba319b5SDimitry Andric   /// Maps the load/store instructions to their index according to
5687d523365SDimitry Andric   /// program order.
5697d523365SDimitry Andric   DenseMap<Instruction *, unsigned> InstOrder;
5707d523365SDimitry Andric 
5717d523365SDimitry Andric   // Analyses used.
5727d523365SDimitry Andric   LoopInfo *LI;
5737d523365SDimitry Andric   const LoopAccessInfo &LAI;
5747d523365SDimitry Andric   DominatorTree *DT;
5757d523365SDimitry Andric   PredicatedScalarEvolution PSE;
5767d523365SDimitry Andric };
5777d523365SDimitry Andric 
5782cab237bSDimitry Andric } // end anonymous namespace
5792cab237bSDimitry Andric 
5807a7e6055SDimitry Andric static bool
eliminateLoadsAcrossLoops(Function & F,LoopInfo & LI,DominatorTree & DT,function_ref<const LoopAccessInfo & (Loop &)> GetLAI)5817a7e6055SDimitry Andric eliminateLoadsAcrossLoops(Function &F, LoopInfo &LI, DominatorTree &DT,
5827a7e6055SDimitry Andric                           function_ref<const LoopAccessInfo &(Loop &)> GetLAI) {
5837a7e6055SDimitry Andric   // Build up a worklist of inner-loops to transform to avoid iterator
5847a7e6055SDimitry Andric   // invalidation.
5857a7e6055SDimitry Andric   // FIXME: This logic comes from other passes that actually change the loop
5867a7e6055SDimitry Andric   // nest structure. It isn't clear this is necessary (or useful) for a pass
5877a7e6055SDimitry Andric   // which merely optimizes the use of loads in a loop.
5887a7e6055SDimitry Andric   SmallVector<Loop *, 8> Worklist;
5897a7e6055SDimitry Andric 
5907a7e6055SDimitry Andric   for (Loop *TopLevelLoop : LI)
5917a7e6055SDimitry Andric     for (Loop *L : depth_first(TopLevelLoop))
5927a7e6055SDimitry Andric       // We only handle inner-most loops.
5937a7e6055SDimitry Andric       if (L->empty())
5947a7e6055SDimitry Andric         Worklist.push_back(L);
5957a7e6055SDimitry Andric 
5967a7e6055SDimitry Andric   // Now walk the identified inner loops.
5977a7e6055SDimitry Andric   bool Changed = false;
5987a7e6055SDimitry Andric   for (Loop *L : Worklist) {
5997a7e6055SDimitry Andric     // The actual work is performed by LoadEliminationForLoop.
6007a7e6055SDimitry Andric     LoadEliminationForLoop LEL(L, &LI, GetLAI(*L), &DT);
6017a7e6055SDimitry Andric     Changed |= LEL.processLoop();
6027a7e6055SDimitry Andric   }
6037a7e6055SDimitry Andric   return Changed;
6047a7e6055SDimitry Andric }
6057a7e6055SDimitry Andric 
6062cab237bSDimitry Andric namespace {
6072cab237bSDimitry Andric 
608*4ba319b5SDimitry Andric /// The pass.  Most of the work is delegated to the per-loop
6097d523365SDimitry Andric /// LoadEliminationForLoop class.
6107d523365SDimitry Andric class LoopLoadElimination : public FunctionPass {
6117d523365SDimitry Andric public:
6122cab237bSDimitry Andric   static char ID;
6132cab237bSDimitry Andric 
LoopLoadElimination()6147d523365SDimitry Andric   LoopLoadElimination() : FunctionPass(ID) {
6157d523365SDimitry Andric     initializeLoopLoadEliminationPass(*PassRegistry::getPassRegistry());
6167d523365SDimitry Andric   }
6177d523365SDimitry Andric 
runOnFunction(Function & F)6187d523365SDimitry Andric   bool runOnFunction(Function &F) override {
6193ca95b02SDimitry Andric     if (skipFunction(F))
6203ca95b02SDimitry Andric       return false;
6213ca95b02SDimitry Andric 
6227a7e6055SDimitry Andric     auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
6237a7e6055SDimitry Andric     auto &LAA = getAnalysis<LoopAccessLegacyAnalysis>();
6247a7e6055SDimitry Andric     auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
6257d523365SDimitry Andric 
6267d523365SDimitry Andric     // Process each loop nest in the function.
6277a7e6055SDimitry Andric     return eliminateLoadsAcrossLoops(
6287a7e6055SDimitry Andric         F, LI, DT,
6297a7e6055SDimitry Andric         [&LAA](Loop &L) -> const LoopAccessInfo & { return LAA.getInfo(&L); });
6307d523365SDimitry Andric   }
6317d523365SDimitry Andric 
getAnalysisUsage(AnalysisUsage & AU) const6327d523365SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
6333ca95b02SDimitry Andric     AU.addRequiredID(LoopSimplifyID);
6347d523365SDimitry Andric     AU.addRequired<LoopInfoWrapperPass>();
6357d523365SDimitry Andric     AU.addPreserved<LoopInfoWrapperPass>();
6363ca95b02SDimitry Andric     AU.addRequired<LoopAccessLegacyAnalysis>();
6377d523365SDimitry Andric     AU.addRequired<ScalarEvolutionWrapperPass>();
6387d523365SDimitry Andric     AU.addRequired<DominatorTreeWrapperPass>();
6397d523365SDimitry Andric     AU.addPreserved<DominatorTreeWrapperPass>();
640d88c1a5aSDimitry Andric     AU.addPreserved<GlobalsAAWrapperPass>();
6417d523365SDimitry Andric   }
6427d523365SDimitry Andric };
643d88c1a5aSDimitry Andric 
644d88c1a5aSDimitry Andric } // end anonymous namespace
6457d523365SDimitry Andric 
6467d523365SDimitry Andric char LoopLoadElimination::ID;
6472cab237bSDimitry Andric 
6487d523365SDimitry Andric static const char LLE_name[] = "Loop Load Elimination";
6497d523365SDimitry Andric 
INITIALIZE_PASS_BEGIN(LoopLoadElimination,LLE_OPTION,LLE_name,false,false)6507d523365SDimitry Andric INITIALIZE_PASS_BEGIN(LoopLoadElimination, LLE_OPTION, LLE_name, false, false)
6517d523365SDimitry Andric INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
6523ca95b02SDimitry Andric INITIALIZE_PASS_DEPENDENCY(LoopAccessLegacyAnalysis)
6537d523365SDimitry Andric INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
6547d523365SDimitry Andric INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
6553ca95b02SDimitry Andric INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
6567d523365SDimitry Andric INITIALIZE_PASS_END(LoopLoadElimination, LLE_OPTION, LLE_name, false, false)
6577d523365SDimitry Andric 
6582cab237bSDimitry Andric FunctionPass *llvm::createLoopLoadEliminationPass() {
6597d523365SDimitry Andric   return new LoopLoadElimination();
6607d523365SDimitry Andric }
661d88c1a5aSDimitry Andric 
run(Function & F,FunctionAnalysisManager & AM)6627a7e6055SDimitry Andric PreservedAnalyses LoopLoadEliminationPass::run(Function &F,
6637a7e6055SDimitry Andric                                                FunctionAnalysisManager &AM) {
6647a7e6055SDimitry Andric   auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
6657a7e6055SDimitry Andric   auto &LI = AM.getResult<LoopAnalysis>(F);
6667a7e6055SDimitry Andric   auto &TTI = AM.getResult<TargetIRAnalysis>(F);
6677a7e6055SDimitry Andric   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
6687a7e6055SDimitry Andric   auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
6697a7e6055SDimitry Andric   auto &AA = AM.getResult<AAManager>(F);
6707a7e6055SDimitry Andric   auto &AC = AM.getResult<AssumptionAnalysis>(F);
6717a7e6055SDimitry Andric 
6727a7e6055SDimitry Andric   auto &LAM = AM.getResult<LoopAnalysisManagerFunctionProxy>(F).getManager();
6737a7e6055SDimitry Andric   bool Changed = eliminateLoadsAcrossLoops(
6747a7e6055SDimitry Andric       F, LI, DT, [&](Loop &L) -> const LoopAccessInfo & {
6752cab237bSDimitry Andric         LoopStandardAnalysisResults AR = {AA, AC,  DT,  LI,
6762cab237bSDimitry Andric                                           SE, TLI, TTI, nullptr};
6777a7e6055SDimitry Andric         return LAM.getResult<LoopAccessAnalysis>(L, AR);
6787a7e6055SDimitry Andric       });
6797a7e6055SDimitry Andric 
6807a7e6055SDimitry Andric   if (!Changed)
6817a7e6055SDimitry Andric     return PreservedAnalyses::all();
6827a7e6055SDimitry Andric 
6837a7e6055SDimitry Andric   PreservedAnalyses PA;
6847a7e6055SDimitry Andric   return PA;
6857a7e6055SDimitry Andric }
686