LoopLoadElimination.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748
  1. //===- LoopLoadElimination.cpp - Loop Load Elimination Pass ---------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implement a loop-aware load elimination pass.
  10. //
  11. // It uses LoopAccessAnalysis to identify loop-carried dependences with a
  12. // distance of one between stores and loads. These form the candidates for the
  13. // transformation. The source value of each store then propagated to the user
  14. // of the corresponding load. This makes the load dead.
  15. //
  16. // The pass can also version the loop and add memchecks in order to prove that
  17. // may-aliasing stores can't change the value in memory before it's read by the
  18. // load.
  19. //
  20. //===----------------------------------------------------------------------===//
  21. #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/InitializePasses.h"
  49. #include "llvm/Pass.h"
  50. #include "llvm/Support/Casting.h"
  51. #include "llvm/Support/CommandLine.h"
  52. #include "llvm/Support/Debug.h"
  53. #include "llvm/Support/raw_ostream.h"
  54. #include "llvm/Transforms/Scalar.h"
  55. #include "llvm/Transforms/Utils.h"
  56. #include "llvm/Transforms/Utils/LoopSimplify.h"
  57. #include "llvm/Transforms/Utils/LoopVersioning.h"
  58. #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
  59. #include "llvm/Transforms/Utils/SizeOpts.h"
  60. #include <algorithm>
  61. #include <cassert>
  62. #include <forward_list>
  63. #include <tuple>
  64. #include <utility>
  65. using namespace llvm;
  66. #define LLE_OPTION "loop-load-elim"
  67. #define DEBUG_TYPE LLE_OPTION
  68. static cl::opt<unsigned> CheckPerElim(
  69. "runtime-check-per-loop-load-elim", cl::Hidden,
  70. cl::desc("Max number of memchecks allowed per eliminated load on average"),
  71. cl::init(1));
  72. static cl::opt<unsigned> LoadElimSCEVCheckThreshold(
  73. "loop-load-elimination-scev-check-threshold", cl::init(8), cl::Hidden,
  74. cl::desc("The maximum number of SCEV checks allowed for Loop "
  75. "Load Elimination"));
  76. STATISTIC(NumLoopLoadEliminted, "Number of loads eliminated by LLE");
  77. namespace {
  78. /// Represent a store-to-forwarding candidate.
  79. struct StoreToLoadForwardingCandidate {
  80. LoadInst *Load;
  81. StoreInst *Store;
  82. StoreToLoadForwardingCandidate(LoadInst *Load, StoreInst *Store)
  83. : Load(Load), Store(Store) {}
  84. /// Return true if the dependence from the store to the load has a
  85. /// distance of one. E.g. A[i+1] = A[i]
  86. bool isDependenceDistanceOfOne(PredicatedScalarEvolution &PSE,
  87. Loop *L) const {
  88. Value *LoadPtr = Load->getPointerOperand();
  89. Value *StorePtr = Store->getPointerOperand();
  90. Type *LoadType = getLoadStoreType(Load);
  91. auto &DL = Load->getParent()->getModule()->getDataLayout();
  92. assert(LoadPtr->getType()->getPointerAddressSpace() ==
  93. StorePtr->getType()->getPointerAddressSpace() &&
  94. DL.getTypeSizeInBits(LoadType) ==
  95. DL.getTypeSizeInBits(getLoadStoreType(Store)) &&
  96. "Should be a known dependence");
  97. // Currently we only support accesses with unit stride. FIXME: we should be
  98. // able to handle non unit stirde as well as long as the stride is equal to
  99. // the dependence distance.
  100. if (getPtrStride(PSE, LoadType, LoadPtr, L).value_or(0) != 1 ||
  101. getPtrStride(PSE, LoadType, StorePtr, L).value_or(0) != 1)
  102. return false;
  103. unsigned TypeByteSize = DL.getTypeAllocSize(const_cast<Type *>(LoadType));
  104. auto *LoadPtrSCEV = cast<SCEVAddRecExpr>(PSE.getSCEV(LoadPtr));
  105. auto *StorePtrSCEV = cast<SCEVAddRecExpr>(PSE.getSCEV(StorePtr));
  106. // We don't need to check non-wrapping here because forward/backward
  107. // dependence wouldn't be valid if these weren't monotonic accesses.
  108. auto *Dist = cast<SCEVConstant>(
  109. PSE.getSE()->getMinusSCEV(StorePtrSCEV, LoadPtrSCEV));
  110. const APInt &Val = Dist->getAPInt();
  111. return Val == TypeByteSize;
  112. }
  113. Value *getLoadPtr() const { return Load->getPointerOperand(); }
  114. #ifndef NDEBUG
  115. friend raw_ostream &operator<<(raw_ostream &OS,
  116. const StoreToLoadForwardingCandidate &Cand) {
  117. OS << *Cand.Store << " -->\n";
  118. OS.indent(2) << *Cand.Load << "\n";
  119. return OS;
  120. }
  121. #endif
  122. };
  123. } // end anonymous namespace
  124. /// Check if the store dominates all latches, so as long as there is no
  125. /// intervening store this value will be loaded in the next iteration.
  126. static bool doesStoreDominatesAllLatches(BasicBlock *StoreBlock, Loop *L,
  127. DominatorTree *DT) {
  128. SmallVector<BasicBlock *, 8> Latches;
  129. L->getLoopLatches(Latches);
  130. return llvm::all_of(Latches, [&](const BasicBlock *Latch) {
  131. return DT->dominates(StoreBlock, Latch);
  132. });
  133. }
  134. /// Return true if the load is not executed on all paths in the loop.
  135. static bool isLoadConditional(LoadInst *Load, Loop *L) {
  136. return Load->getParent() != L->getHeader();
  137. }
  138. namespace {
  139. /// The per-loop class that does most of the work.
  140. class LoadEliminationForLoop {
  141. public:
  142. LoadEliminationForLoop(Loop *L, LoopInfo *LI, const LoopAccessInfo &LAI,
  143. DominatorTree *DT, BlockFrequencyInfo *BFI,
  144. ProfileSummaryInfo* PSI)
  145. : L(L), LI(LI), LAI(LAI), DT(DT), BFI(BFI), PSI(PSI), PSE(LAI.getPSE()) {}
  146. /// Look through the loop-carried and loop-independent dependences in
  147. /// this loop and find store->load dependences.
  148. ///
  149. /// Note that no candidate is returned if LAA has failed to analyze the loop
  150. /// (e.g. if it's not bottom-tested, contains volatile memops, etc.)
  151. std::forward_list<StoreToLoadForwardingCandidate>
  152. findStoreToLoadDependences(const LoopAccessInfo &LAI) {
  153. std::forward_list<StoreToLoadForwardingCandidate> Candidates;
  154. const auto *Deps = LAI.getDepChecker().getDependences();
  155. if (!Deps)
  156. return Candidates;
  157. // Find store->load dependences (consequently true dep). Both lexically
  158. // forward and backward dependences qualify. Disqualify loads that have
  159. // other unknown dependences.
  160. SmallPtrSet<Instruction *, 4> LoadsWithUnknownDepedence;
  161. for (const auto &Dep : *Deps) {
  162. Instruction *Source = Dep.getSource(LAI);
  163. Instruction *Destination = Dep.getDestination(LAI);
  164. if (Dep.Type == MemoryDepChecker::Dependence::Unknown) {
  165. if (isa<LoadInst>(Source))
  166. LoadsWithUnknownDepedence.insert(Source);
  167. if (isa<LoadInst>(Destination))
  168. LoadsWithUnknownDepedence.insert(Destination);
  169. continue;
  170. }
  171. if (Dep.isBackward())
  172. // Note that the designations source and destination follow the program
  173. // order, i.e. source is always first. (The direction is given by the
  174. // DepType.)
  175. std::swap(Source, Destination);
  176. else
  177. assert(Dep.isForward() && "Needs to be a forward dependence");
  178. auto *Store = dyn_cast<StoreInst>(Source);
  179. if (!Store)
  180. continue;
  181. auto *Load = dyn_cast<LoadInst>(Destination);
  182. if (!Load)
  183. continue;
  184. // Only propagate if the stored values are bit/pointer castable.
  185. if (!CastInst::isBitOrNoopPointerCastable(
  186. getLoadStoreType(Store), getLoadStoreType(Load),
  187. Store->getParent()->getModule()->getDataLayout()))
  188. continue;
  189. Candidates.emplace_front(Load, Store);
  190. }
  191. if (!LoadsWithUnknownDepedence.empty())
  192. Candidates.remove_if([&](const StoreToLoadForwardingCandidate &C) {
  193. return LoadsWithUnknownDepedence.count(C.Load);
  194. });
  195. return Candidates;
  196. }
  197. /// Return the index of the instruction according to program order.
  198. unsigned getInstrIndex(Instruction *Inst) {
  199. auto I = InstOrder.find(Inst);
  200. assert(I != InstOrder.end() && "No index for instruction");
  201. return I->second;
  202. }
  203. /// If a load has multiple candidates associated (i.e. different
  204. /// stores), it means that it could be forwarding from multiple stores
  205. /// depending on control flow. Remove these candidates.
  206. ///
  207. /// Here, we rely on LAA to include the relevant loop-independent dependences.
  208. /// LAA is known to omit these in the very simple case when the read and the
  209. /// write within an alias set always takes place using the *same* pointer.
  210. ///
  211. /// However, we know that this is not the case here, i.e. we can rely on LAA
  212. /// to provide us with loop-independent dependences for the cases we're
  213. /// interested. Consider the case for example where a loop-independent
  214. /// dependece S1->S2 invalidates the forwarding S3->S2.
  215. ///
  216. /// A[i] = ... (S1)
  217. /// ... = A[i] (S2)
  218. /// A[i+1] = ... (S3)
  219. ///
  220. /// LAA will perform dependence analysis here because there are two
  221. /// *different* pointers involved in the same alias set (&A[i] and &A[i+1]).
  222. void removeDependencesFromMultipleStores(
  223. std::forward_list<StoreToLoadForwardingCandidate> &Candidates) {
  224. // If Store is nullptr it means that we have multiple stores forwarding to
  225. // this store.
  226. using LoadToSingleCandT =
  227. DenseMap<LoadInst *, const StoreToLoadForwardingCandidate *>;
  228. LoadToSingleCandT LoadToSingleCand;
  229. for (const auto &Cand : Candidates) {
  230. bool NewElt;
  231. LoadToSingleCandT::iterator Iter;
  232. std::tie(Iter, NewElt) =
  233. LoadToSingleCand.insert(std::make_pair(Cand.Load, &Cand));
  234. if (!NewElt) {
  235. const StoreToLoadForwardingCandidate *&OtherCand = Iter->second;
  236. // Already multiple stores forward to this load.
  237. if (OtherCand == nullptr)
  238. continue;
  239. // Handle the very basic case when the two stores are in the same block
  240. // so deciding which one forwards is easy. The later one forwards as
  241. // long as they both have a dependence distance of one to the load.
  242. if (Cand.Store->getParent() == OtherCand->Store->getParent() &&
  243. Cand.isDependenceDistanceOfOne(PSE, L) &&
  244. OtherCand->isDependenceDistanceOfOne(PSE, L)) {
  245. // They are in the same block, the later one will forward to the load.
  246. if (getInstrIndex(OtherCand->Store) < getInstrIndex(Cand.Store))
  247. OtherCand = &Cand;
  248. } else
  249. OtherCand = nullptr;
  250. }
  251. }
  252. Candidates.remove_if([&](const StoreToLoadForwardingCandidate &Cand) {
  253. if (LoadToSingleCand[Cand.Load] != &Cand) {
  254. LLVM_DEBUG(
  255. dbgs() << "Removing from candidates: \n"
  256. << Cand
  257. << " The load may have multiple stores forwarding to "
  258. << "it\n");
  259. return true;
  260. }
  261. return false;
  262. });
  263. }
  264. /// Given two pointers operations by their RuntimePointerChecking
  265. /// indices, return true if they require an alias check.
  266. ///
  267. /// We need a check if one is a pointer for a candidate load and the other is
  268. /// a pointer for a possibly intervening store.
  269. bool needsChecking(unsigned PtrIdx1, unsigned PtrIdx2,
  270. const SmallPtrSetImpl<Value *> &PtrsWrittenOnFwdingPath,
  271. const SmallPtrSetImpl<Value *> &CandLoadPtrs) {
  272. Value *Ptr1 =
  273. LAI.getRuntimePointerChecking()->getPointerInfo(PtrIdx1).PointerValue;
  274. Value *Ptr2 =
  275. LAI.getRuntimePointerChecking()->getPointerInfo(PtrIdx2).PointerValue;
  276. return ((PtrsWrittenOnFwdingPath.count(Ptr1) && CandLoadPtrs.count(Ptr2)) ||
  277. (PtrsWrittenOnFwdingPath.count(Ptr2) && CandLoadPtrs.count(Ptr1)));
  278. }
  279. /// Return pointers that are possibly written to on the path from a
  280. /// forwarding store to a load.
  281. ///
  282. /// These pointers need to be alias-checked against the forwarding candidates.
  283. SmallPtrSet<Value *, 4> findPointersWrittenOnForwardingPath(
  284. const SmallVectorImpl<StoreToLoadForwardingCandidate> &Candidates) {
  285. // From FirstStore to LastLoad neither of the elimination candidate loads
  286. // should overlap with any of the stores.
  287. //
  288. // E.g.:
  289. //
  290. // st1 C[i]
  291. // ld1 B[i] <-------,
  292. // ld0 A[i] <----, | * LastLoad
  293. // ... | |
  294. // st2 E[i] | |
  295. // st3 B[i+1] -- | -' * FirstStore
  296. // st0 A[i+1] ---'
  297. // st4 D[i]
  298. //
  299. // st0 forwards to ld0 if the accesses in st4 and st1 don't overlap with
  300. // ld0.
  301. LoadInst *LastLoad =
  302. std::max_element(Candidates.begin(), Candidates.end(),
  303. [&](const StoreToLoadForwardingCandidate &A,
  304. const StoreToLoadForwardingCandidate &B) {
  305. return getInstrIndex(A.Load) < getInstrIndex(B.Load);
  306. })
  307. ->Load;
  308. StoreInst *FirstStore =
  309. std::min_element(Candidates.begin(), Candidates.end(),
  310. [&](const StoreToLoadForwardingCandidate &A,
  311. const StoreToLoadForwardingCandidate &B) {
  312. return getInstrIndex(A.Store) <
  313. getInstrIndex(B.Store);
  314. })
  315. ->Store;
  316. // We're looking for stores after the first forwarding store until the end
  317. // of the loop, then from the beginning of the loop until the last
  318. // forwarded-to load. Collect the pointer for the stores.
  319. SmallPtrSet<Value *, 4> PtrsWrittenOnFwdingPath;
  320. auto InsertStorePtr = [&](Instruction *I) {
  321. if (auto *S = dyn_cast<StoreInst>(I))
  322. PtrsWrittenOnFwdingPath.insert(S->getPointerOperand());
  323. };
  324. const auto &MemInstrs = LAI.getDepChecker().getMemoryInstructions();
  325. std::for_each(MemInstrs.begin() + getInstrIndex(FirstStore) + 1,
  326. MemInstrs.end(), InsertStorePtr);
  327. std::for_each(MemInstrs.begin(), &MemInstrs[getInstrIndex(LastLoad)],
  328. InsertStorePtr);
  329. return PtrsWrittenOnFwdingPath;
  330. }
  331. /// Determine the pointer alias checks to prove that there are no
  332. /// intervening stores.
  333. SmallVector<RuntimePointerCheck, 4> collectMemchecks(
  334. const SmallVectorImpl<StoreToLoadForwardingCandidate> &Candidates) {
  335. SmallPtrSet<Value *, 4> PtrsWrittenOnFwdingPath =
  336. findPointersWrittenOnForwardingPath(Candidates);
  337. // Collect the pointers of the candidate loads.
  338. SmallPtrSet<Value *, 4> CandLoadPtrs;
  339. for (const auto &Candidate : Candidates)
  340. CandLoadPtrs.insert(Candidate.getLoadPtr());
  341. const auto &AllChecks = LAI.getRuntimePointerChecking()->getChecks();
  342. SmallVector<RuntimePointerCheck, 4> Checks;
  343. copy_if(AllChecks, std::back_inserter(Checks),
  344. [&](const RuntimePointerCheck &Check) {
  345. for (auto PtrIdx1 : Check.first->Members)
  346. for (auto PtrIdx2 : Check.second->Members)
  347. if (needsChecking(PtrIdx1, PtrIdx2, PtrsWrittenOnFwdingPath,
  348. CandLoadPtrs))
  349. return true;
  350. return false;
  351. });
  352. LLVM_DEBUG(dbgs() << "\nPointer Checks (count: " << Checks.size()
  353. << "):\n");
  354. LLVM_DEBUG(LAI.getRuntimePointerChecking()->printChecks(dbgs(), Checks));
  355. return Checks;
  356. }
  357. /// Perform the transformation for a candidate.
  358. void
  359. propagateStoredValueToLoadUsers(const StoreToLoadForwardingCandidate &Cand,
  360. SCEVExpander &SEE) {
  361. // loop:
  362. // %x = load %gep_i
  363. // = ... %x
  364. // store %y, %gep_i_plus_1
  365. //
  366. // =>
  367. //
  368. // ph:
  369. // %x.initial = load %gep_0
  370. // loop:
  371. // %x.storeforward = phi [%x.initial, %ph] [%y, %loop]
  372. // %x = load %gep_i <---- now dead
  373. // = ... %x.storeforward
  374. // store %y, %gep_i_plus_1
  375. Value *Ptr = Cand.Load->getPointerOperand();
  376. auto *PtrSCEV = cast<SCEVAddRecExpr>(PSE.getSCEV(Ptr));
  377. auto *PH = L->getLoopPreheader();
  378. assert(PH && "Preheader should exist!");
  379. Value *InitialPtr = SEE.expandCodeFor(PtrSCEV->getStart(), Ptr->getType(),
  380. PH->getTerminator());
  381. Value *Initial = new LoadInst(
  382. Cand.Load->getType(), InitialPtr, "load_initial",
  383. /* isVolatile */ false, Cand.Load->getAlign(), PH->getTerminator());
  384. PHINode *PHI = PHINode::Create(Initial->getType(), 2, "store_forwarded",
  385. &L->getHeader()->front());
  386. PHI->addIncoming(Initial, PH);
  387. Type *LoadType = Initial->getType();
  388. Type *StoreType = Cand.Store->getValueOperand()->getType();
  389. auto &DL = Cand.Load->getParent()->getModule()->getDataLayout();
  390. (void)DL;
  391. assert(DL.getTypeSizeInBits(LoadType) == DL.getTypeSizeInBits(StoreType) &&
  392. "The type sizes should match!");
  393. Value *StoreValue = Cand.Store->getValueOperand();
  394. if (LoadType != StoreType)
  395. StoreValue = CastInst::CreateBitOrPointerCast(
  396. StoreValue, LoadType, "store_forward_cast", Cand.Store);
  397. PHI->addIncoming(StoreValue, L->getLoopLatch());
  398. Cand.Load->replaceAllUsesWith(PHI);
  399. }
  400. /// Top-level driver for each loop: find store->load forwarding
  401. /// candidates, add run-time checks and perform transformation.
  402. bool processLoop() {
  403. LLVM_DEBUG(dbgs() << "\nIn \"" << L->getHeader()->getParent()->getName()
  404. << "\" checking " << *L << "\n");
  405. // Look for store-to-load forwarding cases across the
  406. // backedge. E.g.:
  407. //
  408. // loop:
  409. // %x = load %gep_i
  410. // = ... %x
  411. // store %y, %gep_i_plus_1
  412. //
  413. // =>
  414. //
  415. // ph:
  416. // %x.initial = load %gep_0
  417. // loop:
  418. // %x.storeforward = phi [%x.initial, %ph] [%y, %loop]
  419. // %x = load %gep_i <---- now dead
  420. // = ... %x.storeforward
  421. // store %y, %gep_i_plus_1
  422. // First start with store->load dependences.
  423. auto StoreToLoadDependences = findStoreToLoadDependences(LAI);
  424. if (StoreToLoadDependences.empty())
  425. return false;
  426. // Generate an index for each load and store according to the original
  427. // program order. This will be used later.
  428. InstOrder = LAI.getDepChecker().generateInstructionOrderMap();
  429. // To keep things simple for now, remove those where the load is potentially
  430. // fed by multiple stores.
  431. removeDependencesFromMultipleStores(StoreToLoadDependences);
  432. if (StoreToLoadDependences.empty())
  433. return false;
  434. // Filter the candidates further.
  435. SmallVector<StoreToLoadForwardingCandidate, 4> Candidates;
  436. for (const StoreToLoadForwardingCandidate &Cand : StoreToLoadDependences) {
  437. LLVM_DEBUG(dbgs() << "Candidate " << Cand);
  438. // Make sure that the stored values is available everywhere in the loop in
  439. // the next iteration.
  440. if (!doesStoreDominatesAllLatches(Cand.Store->getParent(), L, DT))
  441. continue;
  442. // If the load is conditional we can't hoist its 0-iteration instance to
  443. // the preheader because that would make it unconditional. Thus we would
  444. // access a memory location that the original loop did not access.
  445. if (isLoadConditional(Cand.Load, L))
  446. continue;
  447. // Check whether the SCEV difference is the same as the induction step,
  448. // thus we load the value in the next iteration.
  449. if (!Cand.isDependenceDistanceOfOne(PSE, L))
  450. continue;
  451. assert(isa<SCEVAddRecExpr>(PSE.getSCEV(Cand.Load->getPointerOperand())) &&
  452. "Loading from something other than indvar?");
  453. assert(
  454. isa<SCEVAddRecExpr>(PSE.getSCEV(Cand.Store->getPointerOperand())) &&
  455. "Storing to something other than indvar?");
  456. Candidates.push_back(Cand);
  457. LLVM_DEBUG(
  458. dbgs()
  459. << Candidates.size()
  460. << ". Valid store-to-load forwarding across the loop backedge\n");
  461. }
  462. if (Candidates.empty())
  463. return false;
  464. // Check intervening may-alias stores. These need runtime checks for alias
  465. // disambiguation.
  466. SmallVector<RuntimePointerCheck, 4> Checks = collectMemchecks(Candidates);
  467. // Too many checks are likely to outweigh the benefits of forwarding.
  468. if (Checks.size() > Candidates.size() * CheckPerElim) {
  469. LLVM_DEBUG(dbgs() << "Too many run-time checks needed.\n");
  470. return false;
  471. }
  472. if (LAI.getPSE().getPredicate().getComplexity() >
  473. LoadElimSCEVCheckThreshold) {
  474. LLVM_DEBUG(dbgs() << "Too many SCEV run-time checks needed.\n");
  475. return false;
  476. }
  477. if (!L->isLoopSimplifyForm()) {
  478. LLVM_DEBUG(dbgs() << "Loop is not is loop-simplify form");
  479. return false;
  480. }
  481. if (!Checks.empty() || !LAI.getPSE().getPredicate().isAlwaysTrue()) {
  482. if (LAI.hasConvergentOp()) {
  483. LLVM_DEBUG(dbgs() << "Versioning is needed but not allowed with "
  484. "convergent calls\n");
  485. return false;
  486. }
  487. auto *HeaderBB = L->getHeader();
  488. auto *F = HeaderBB->getParent();
  489. bool OptForSize = F->hasOptSize() ||
  490. llvm::shouldOptimizeForSize(HeaderBB, PSI, BFI,
  491. PGSOQueryType::IRPass);
  492. if (OptForSize) {
  493. LLVM_DEBUG(
  494. dbgs() << "Versioning is needed but not allowed when optimizing "
  495. "for size.\n");
  496. return false;
  497. }
  498. // Point of no-return, start the transformation. First, version the loop
  499. // if necessary.
  500. LoopVersioning LV(LAI, Checks, L, LI, DT, PSE.getSE());
  501. LV.versionLoop();
  502. // After versioning, some of the candidates' pointers could stop being
  503. // SCEVAddRecs. We need to filter them out.
  504. auto NoLongerGoodCandidate = [this](
  505. const StoreToLoadForwardingCandidate &Cand) {
  506. return !isa<SCEVAddRecExpr>(
  507. PSE.getSCEV(Cand.Load->getPointerOperand())) ||
  508. !isa<SCEVAddRecExpr>(
  509. PSE.getSCEV(Cand.Store->getPointerOperand()));
  510. };
  511. llvm::erase_if(Candidates, NoLongerGoodCandidate);
  512. }
  513. // Next, propagate the value stored by the store to the users of the load.
  514. // Also for the first iteration, generate the initial value of the load.
  515. SCEVExpander SEE(*PSE.getSE(), L->getHeader()->getModule()->getDataLayout(),
  516. "storeforward");
  517. for (const auto &Cand : Candidates)
  518. propagateStoredValueToLoadUsers(Cand, SEE);
  519. NumLoopLoadEliminted += Candidates.size();
  520. return true;
  521. }
  522. private:
  523. Loop *L;
  524. /// Maps the load/store instructions to their index according to
  525. /// program order.
  526. DenseMap<Instruction *, unsigned> InstOrder;
  527. // Analyses used.
  528. LoopInfo *LI;
  529. const LoopAccessInfo &LAI;
  530. DominatorTree *DT;
  531. BlockFrequencyInfo *BFI;
  532. ProfileSummaryInfo *PSI;
  533. PredicatedScalarEvolution PSE;
  534. };
  535. } // end anonymous namespace
  536. static bool eliminateLoadsAcrossLoops(Function &F, LoopInfo &LI,
  537. DominatorTree &DT,
  538. BlockFrequencyInfo *BFI,
  539. ProfileSummaryInfo *PSI,
  540. ScalarEvolution *SE, AssumptionCache *AC,
  541. LoopAccessInfoManager &LAIs) {
  542. // Build up a worklist of inner-loops to transform to avoid iterator
  543. // invalidation.
  544. // FIXME: This logic comes from other passes that actually change the loop
  545. // nest structure. It isn't clear this is necessary (or useful) for a pass
  546. // which merely optimizes the use of loads in a loop.
  547. SmallVector<Loop *, 8> Worklist;
  548. bool Changed = false;
  549. for (Loop *TopLevelLoop : LI)
  550. for (Loop *L : depth_first(TopLevelLoop)) {
  551. Changed |= simplifyLoop(L, &DT, &LI, SE, AC, /*MSSAU*/ nullptr, false);
  552. // We only handle inner-most loops.
  553. if (L->isInnermost())
  554. Worklist.push_back(L);
  555. }
  556. // Now walk the identified inner loops.
  557. for (Loop *L : Worklist) {
  558. // Match historical behavior
  559. if (!L->isRotatedForm() || !L->getExitingBlock())
  560. continue;
  561. // The actual work is performed by LoadEliminationForLoop.
  562. LoadEliminationForLoop LEL(L, &LI, LAIs.getInfo(*L), &DT, BFI, PSI);
  563. Changed |= LEL.processLoop();
  564. if (Changed)
  565. LAIs.clear();
  566. }
  567. return Changed;
  568. }
  569. namespace {
  570. /// The pass. Most of the work is delegated to the per-loop
  571. /// LoadEliminationForLoop class.
  572. class LoopLoadElimination : public FunctionPass {
  573. public:
  574. static char ID;
  575. LoopLoadElimination() : FunctionPass(ID) {
  576. initializeLoopLoadEliminationPass(*PassRegistry::getPassRegistry());
  577. }
  578. bool runOnFunction(Function &F) override {
  579. if (skipFunction(F))
  580. return false;
  581. auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
  582. auto &LAIs = getAnalysis<LoopAccessLegacyAnalysis>().getLAIs();
  583. auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  584. auto *PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
  585. auto *BFI = (PSI && PSI->hasProfileSummary()) ?
  586. &getAnalysis<LazyBlockFrequencyInfoPass>().getBFI() :
  587. nullptr;
  588. auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
  589. // Process each loop nest in the function.
  590. return eliminateLoadsAcrossLoops(F, LI, DT, BFI, PSI, SE, /*AC*/ nullptr,
  591. LAIs);
  592. }
  593. void getAnalysisUsage(AnalysisUsage &AU) const override {
  594. AU.addRequiredID(LoopSimplifyID);
  595. AU.addRequired<LoopInfoWrapperPass>();
  596. AU.addPreserved<LoopInfoWrapperPass>();
  597. AU.addRequired<LoopAccessLegacyAnalysis>();
  598. AU.addRequired<ScalarEvolutionWrapperPass>();
  599. AU.addRequired<DominatorTreeWrapperPass>();
  600. AU.addPreserved<DominatorTreeWrapperPass>();
  601. AU.addPreserved<GlobalsAAWrapperPass>();
  602. AU.addRequired<ProfileSummaryInfoWrapperPass>();
  603. LazyBlockFrequencyInfoPass::getLazyBFIAnalysisUsage(AU);
  604. }
  605. };
  606. } // end anonymous namespace
  607. char LoopLoadElimination::ID;
  608. static const char LLE_name[] = "Loop Load Elimination";
  609. INITIALIZE_PASS_BEGIN(LoopLoadElimination, LLE_OPTION, LLE_name, false, false)
  610. INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
  611. INITIALIZE_PASS_DEPENDENCY(LoopAccessLegacyAnalysis)
  612. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  613. INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
  614. INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
  615. INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
  616. INITIALIZE_PASS_DEPENDENCY(LazyBlockFrequencyInfoPass)
  617. INITIALIZE_PASS_END(LoopLoadElimination, LLE_OPTION, LLE_name, false, false)
  618. FunctionPass *llvm::createLoopLoadEliminationPass() {
  619. return new LoopLoadElimination();
  620. }
  621. PreservedAnalyses LoopLoadEliminationPass::run(Function &F,
  622. FunctionAnalysisManager &AM) {
  623. auto &LI = AM.getResult<LoopAnalysis>(F);
  624. // There are no loops in the function. Return before computing other expensive
  625. // analyses.
  626. if (LI.empty())
  627. return PreservedAnalyses::all();
  628. auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
  629. auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
  630. auto &AC = AM.getResult<AssumptionAnalysis>(F);
  631. auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
  632. auto *PSI = MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
  633. auto *BFI = (PSI && PSI->hasProfileSummary()) ?
  634. &AM.getResult<BlockFrequencyAnalysis>(F) : nullptr;
  635. LoopAccessInfoManager &LAIs = AM.getResult<LoopAccessAnalysis>(F);
  636. bool Changed = eliminateLoadsAcrossLoops(F, LI, DT, BFI, PSI, &SE, &AC, LAIs);
  637. if (!Changed)
  638. return PreservedAnalyses::all();
  639. PreservedAnalyses PA;
  640. return PA;
  641. }