LoopLoadElimination.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734
  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 <set>
  64. #include <tuple>
  65. #include <utility>
  66. using namespace llvm;
  67. #define LLE_OPTION "loop-load-elim"
  68. #define DEBUG_TYPE LLE_OPTION
  69. static cl::opt<unsigned> CheckPerElim(
  70. "runtime-check-per-loop-load-elim", cl::Hidden,
  71. cl::desc("Max number of memchecks allowed per eliminated load on average"),
  72. cl::init(1));
  73. static cl::opt<unsigned> LoadElimSCEVCheckThreshold(
  74. "loop-load-elimination-scev-check-threshold", cl::init(8), cl::Hidden,
  75. cl::desc("The maximum number of SCEV checks allowed for Loop "
  76. "Load Elimination"));
  77. STATISTIC(NumLoopLoadEliminted, "Number of loads eliminated by LLE");
  78. namespace {
  79. /// Represent a store-to-forwarding candidate.
  80. struct StoreToLoadForwardingCandidate {
  81. LoadInst *Load;
  82. StoreInst *Store;
  83. StoreToLoadForwardingCandidate(LoadInst *Load, StoreInst *Store)
  84. : Load(Load), Store(Store) {}
  85. /// Return true if the dependence from the store to the load has a
  86. /// distance of one. E.g. A[i+1] = A[i]
  87. bool isDependenceDistanceOfOne(PredicatedScalarEvolution &PSE,
  88. Loop *L) const {
  89. Value *LoadPtr = Load->getPointerOperand();
  90. Value *StorePtr = Store->getPointerOperand();
  91. Type *LoadType = getLoadStoreType(Load);
  92. assert(LoadPtr->getType()->getPointerAddressSpace() ==
  93. StorePtr->getType()->getPointerAddressSpace() &&
  94. LoadType == getLoadStoreType(Store) &&
  95. "Should be a known dependence");
  96. // Currently we only support accesses with unit stride. FIXME: we should be
  97. // able to handle non unit stirde as well as long as the stride is equal to
  98. // the dependence distance.
  99. if (getPtrStride(PSE, LoadType, LoadPtr, L) != 1 ||
  100. getPtrStride(PSE, LoadType, StorePtr, L) != 1)
  101. return false;
  102. auto &DL = Load->getParent()->getModule()->getDataLayout();
  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 progagate the value if they are of the same type.
  185. if (Store->getPointerOperandType() != Load->getPointerOperandType())
  186. continue;
  187. Candidates.emplace_front(Load, Store);
  188. }
  189. if (!LoadsWithUnknownDepedence.empty())
  190. Candidates.remove_if([&](const StoreToLoadForwardingCandidate &C) {
  191. return LoadsWithUnknownDepedence.count(C.Load);
  192. });
  193. return Candidates;
  194. }
  195. /// Return the index of the instruction according to program order.
  196. unsigned getInstrIndex(Instruction *Inst) {
  197. auto I = InstOrder.find(Inst);
  198. assert(I != InstOrder.end() && "No index for instruction");
  199. return I->second;
  200. }
  201. /// If a load has multiple candidates associated (i.e. different
  202. /// stores), it means that it could be forwarding from multiple stores
  203. /// depending on control flow. Remove these candidates.
  204. ///
  205. /// Here, we rely on LAA to include the relevant loop-independent dependences.
  206. /// LAA is known to omit these in the very simple case when the read and the
  207. /// write within an alias set always takes place using the *same* pointer.
  208. ///
  209. /// However, we know that this is not the case here, i.e. we can rely on LAA
  210. /// to provide us with loop-independent dependences for the cases we're
  211. /// interested. Consider the case for example where a loop-independent
  212. /// dependece S1->S2 invalidates the forwarding S3->S2.
  213. ///
  214. /// A[i] = ... (S1)
  215. /// ... = A[i] (S2)
  216. /// A[i+1] = ... (S3)
  217. ///
  218. /// LAA will perform dependence analysis here because there are two
  219. /// *different* pointers involved in the same alias set (&A[i] and &A[i+1]).
  220. void removeDependencesFromMultipleStores(
  221. std::forward_list<StoreToLoadForwardingCandidate> &Candidates) {
  222. // If Store is nullptr it means that we have multiple stores forwarding to
  223. // this store.
  224. using LoadToSingleCandT =
  225. DenseMap<LoadInst *, const StoreToLoadForwardingCandidate *>;
  226. LoadToSingleCandT LoadToSingleCand;
  227. for (const auto &Cand : Candidates) {
  228. bool NewElt;
  229. LoadToSingleCandT::iterator Iter;
  230. std::tie(Iter, NewElt) =
  231. LoadToSingleCand.insert(std::make_pair(Cand.Load, &Cand));
  232. if (!NewElt) {
  233. const StoreToLoadForwardingCandidate *&OtherCand = Iter->second;
  234. // Already multiple stores forward to this load.
  235. if (OtherCand == nullptr)
  236. continue;
  237. // Handle the very basic case when the two stores are in the same block
  238. // so deciding which one forwards is easy. The later one forwards as
  239. // long as they both have a dependence distance of one to the load.
  240. if (Cand.Store->getParent() == OtherCand->Store->getParent() &&
  241. Cand.isDependenceDistanceOfOne(PSE, L) &&
  242. OtherCand->isDependenceDistanceOfOne(PSE, L)) {
  243. // They are in the same block, the later one will forward to the load.
  244. if (getInstrIndex(OtherCand->Store) < getInstrIndex(Cand.Store))
  245. OtherCand = &Cand;
  246. } else
  247. OtherCand = nullptr;
  248. }
  249. }
  250. Candidates.remove_if([&](const StoreToLoadForwardingCandidate &Cand) {
  251. if (LoadToSingleCand[Cand.Load] != &Cand) {
  252. LLVM_DEBUG(
  253. dbgs() << "Removing from candidates: \n"
  254. << Cand
  255. << " The load may have multiple stores forwarding to "
  256. << "it\n");
  257. return true;
  258. }
  259. return false;
  260. });
  261. }
  262. /// Given two pointers operations by their RuntimePointerChecking
  263. /// indices, return true if they require an alias check.
  264. ///
  265. /// We need a check if one is a pointer for a candidate load and the other is
  266. /// a pointer for a possibly intervening store.
  267. bool needsChecking(unsigned PtrIdx1, unsigned PtrIdx2,
  268. const SmallPtrSetImpl<Value *> &PtrsWrittenOnFwdingPath,
  269. const SmallPtrSetImpl<Value *> &CandLoadPtrs) {
  270. Value *Ptr1 =
  271. LAI.getRuntimePointerChecking()->getPointerInfo(PtrIdx1).PointerValue;
  272. Value *Ptr2 =
  273. LAI.getRuntimePointerChecking()->getPointerInfo(PtrIdx2).PointerValue;
  274. return ((PtrsWrittenOnFwdingPath.count(Ptr1) && CandLoadPtrs.count(Ptr2)) ||
  275. (PtrsWrittenOnFwdingPath.count(Ptr2) && CandLoadPtrs.count(Ptr1)));
  276. }
  277. /// Return pointers that are possibly written to on the path from a
  278. /// forwarding store to a load.
  279. ///
  280. /// These pointers need to be alias-checked against the forwarding candidates.
  281. SmallPtrSet<Value *, 4> findPointersWrittenOnForwardingPath(
  282. const SmallVectorImpl<StoreToLoadForwardingCandidate> &Candidates) {
  283. // From FirstStore to LastLoad neither of the elimination candidate loads
  284. // should overlap with any of the stores.
  285. //
  286. // E.g.:
  287. //
  288. // st1 C[i]
  289. // ld1 B[i] <-------,
  290. // ld0 A[i] <----, | * LastLoad
  291. // ... | |
  292. // st2 E[i] | |
  293. // st3 B[i+1] -- | -' * FirstStore
  294. // st0 A[i+1] ---'
  295. // st4 D[i]
  296. //
  297. // st0 forwards to ld0 if the accesses in st4 and st1 don't overlap with
  298. // ld0.
  299. LoadInst *LastLoad =
  300. std::max_element(Candidates.begin(), Candidates.end(),
  301. [&](const StoreToLoadForwardingCandidate &A,
  302. const StoreToLoadForwardingCandidate &B) {
  303. return getInstrIndex(A.Load) < getInstrIndex(B.Load);
  304. })
  305. ->Load;
  306. StoreInst *FirstStore =
  307. std::min_element(Candidates.begin(), Candidates.end(),
  308. [&](const StoreToLoadForwardingCandidate &A,
  309. const StoreToLoadForwardingCandidate &B) {
  310. return getInstrIndex(A.Store) <
  311. getInstrIndex(B.Store);
  312. })
  313. ->Store;
  314. // We're looking for stores after the first forwarding store until the end
  315. // of the loop, then from the beginning of the loop until the last
  316. // forwarded-to load. Collect the pointer for the stores.
  317. SmallPtrSet<Value *, 4> PtrsWrittenOnFwdingPath;
  318. auto InsertStorePtr = [&](Instruction *I) {
  319. if (auto *S = dyn_cast<StoreInst>(I))
  320. PtrsWrittenOnFwdingPath.insert(S->getPointerOperand());
  321. };
  322. const auto &MemInstrs = LAI.getDepChecker().getMemoryInstructions();
  323. std::for_each(MemInstrs.begin() + getInstrIndex(FirstStore) + 1,
  324. MemInstrs.end(), InsertStorePtr);
  325. std::for_each(MemInstrs.begin(), &MemInstrs[getInstrIndex(LastLoad)],
  326. InsertStorePtr);
  327. return PtrsWrittenOnFwdingPath;
  328. }
  329. /// Determine the pointer alias checks to prove that there are no
  330. /// intervening stores.
  331. SmallVector<RuntimePointerCheck, 4> collectMemchecks(
  332. const SmallVectorImpl<StoreToLoadForwardingCandidate> &Candidates) {
  333. SmallPtrSet<Value *, 4> PtrsWrittenOnFwdingPath =
  334. findPointersWrittenOnForwardingPath(Candidates);
  335. // Collect the pointers of the candidate loads.
  336. SmallPtrSet<Value *, 4> CandLoadPtrs;
  337. for (const auto &Candidate : Candidates)
  338. CandLoadPtrs.insert(Candidate.getLoadPtr());
  339. const auto &AllChecks = LAI.getRuntimePointerChecking()->getChecks();
  340. SmallVector<RuntimePointerCheck, 4> Checks;
  341. copy_if(AllChecks, std::back_inserter(Checks),
  342. [&](const RuntimePointerCheck &Check) {
  343. for (auto PtrIdx1 : Check.first->Members)
  344. for (auto PtrIdx2 : Check.second->Members)
  345. if (needsChecking(PtrIdx1, PtrIdx2, PtrsWrittenOnFwdingPath,
  346. CandLoadPtrs))
  347. return true;
  348. return false;
  349. });
  350. LLVM_DEBUG(dbgs() << "\nPointer Checks (count: " << Checks.size()
  351. << "):\n");
  352. LLVM_DEBUG(LAI.getRuntimePointerChecking()->printChecks(dbgs(), Checks));
  353. return Checks;
  354. }
  355. /// Perform the transformation for a candidate.
  356. void
  357. propagateStoredValueToLoadUsers(const StoreToLoadForwardingCandidate &Cand,
  358. SCEVExpander &SEE) {
  359. // loop:
  360. // %x = load %gep_i
  361. // = ... %x
  362. // store %y, %gep_i_plus_1
  363. //
  364. // =>
  365. //
  366. // ph:
  367. // %x.initial = load %gep_0
  368. // loop:
  369. // %x.storeforward = phi [%x.initial, %ph] [%y, %loop]
  370. // %x = load %gep_i <---- now dead
  371. // = ... %x.storeforward
  372. // store %y, %gep_i_plus_1
  373. Value *Ptr = Cand.Load->getPointerOperand();
  374. auto *PtrSCEV = cast<SCEVAddRecExpr>(PSE.getSCEV(Ptr));
  375. auto *PH = L->getLoopPreheader();
  376. assert(PH && "Preheader should exist!");
  377. Value *InitialPtr = SEE.expandCodeFor(PtrSCEV->getStart(), Ptr->getType(),
  378. PH->getTerminator());
  379. Value *Initial = new LoadInst(
  380. Cand.Load->getType(), InitialPtr, "load_initial",
  381. /* isVolatile */ false, Cand.Load->getAlign(), PH->getTerminator());
  382. PHINode *PHI = PHINode::Create(Initial->getType(), 2, "store_forwarded",
  383. &L->getHeader()->front());
  384. PHI->addIncoming(Initial, PH);
  385. PHI->addIncoming(Cand.Store->getOperand(0), L->getLoopLatch());
  386. Cand.Load->replaceAllUsesWith(PHI);
  387. }
  388. /// Top-level driver for each loop: find store->load forwarding
  389. /// candidates, add run-time checks and perform transformation.
  390. bool processLoop() {
  391. LLVM_DEBUG(dbgs() << "\nIn \"" << L->getHeader()->getParent()->getName()
  392. << "\" checking " << *L << "\n");
  393. // Look for store-to-load forwarding cases across the
  394. // backedge. E.g.:
  395. //
  396. // loop:
  397. // %x = load %gep_i
  398. // = ... %x
  399. // store %y, %gep_i_plus_1
  400. //
  401. // =>
  402. //
  403. // ph:
  404. // %x.initial = load %gep_0
  405. // loop:
  406. // %x.storeforward = phi [%x.initial, %ph] [%y, %loop]
  407. // %x = load %gep_i <---- now dead
  408. // = ... %x.storeforward
  409. // store %y, %gep_i_plus_1
  410. // First start with store->load dependences.
  411. auto StoreToLoadDependences = findStoreToLoadDependences(LAI);
  412. if (StoreToLoadDependences.empty())
  413. return false;
  414. // Generate an index for each load and store according to the original
  415. // program order. This will be used later.
  416. InstOrder = LAI.getDepChecker().generateInstructionOrderMap();
  417. // To keep things simple for now, remove those where the load is potentially
  418. // fed by multiple stores.
  419. removeDependencesFromMultipleStores(StoreToLoadDependences);
  420. if (StoreToLoadDependences.empty())
  421. return false;
  422. // Filter the candidates further.
  423. SmallVector<StoreToLoadForwardingCandidate, 4> Candidates;
  424. for (const StoreToLoadForwardingCandidate &Cand : StoreToLoadDependences) {
  425. LLVM_DEBUG(dbgs() << "Candidate " << Cand);
  426. // Make sure that the stored values is available everywhere in the loop in
  427. // the next iteration.
  428. if (!doesStoreDominatesAllLatches(Cand.Store->getParent(), L, DT))
  429. continue;
  430. // If the load is conditional we can't hoist its 0-iteration instance to
  431. // the preheader because that would make it unconditional. Thus we would
  432. // access a memory location that the original loop did not access.
  433. if (isLoadConditional(Cand.Load, L))
  434. continue;
  435. // Check whether the SCEV difference is the same as the induction step,
  436. // thus we load the value in the next iteration.
  437. if (!Cand.isDependenceDistanceOfOne(PSE, L))
  438. continue;
  439. assert(isa<SCEVAddRecExpr>(PSE.getSCEV(Cand.Load->getPointerOperand())) &&
  440. "Loading from something other than indvar?");
  441. assert(
  442. isa<SCEVAddRecExpr>(PSE.getSCEV(Cand.Store->getPointerOperand())) &&
  443. "Storing to something other than indvar?");
  444. Candidates.push_back(Cand);
  445. LLVM_DEBUG(
  446. dbgs()
  447. << Candidates.size()
  448. << ". Valid store-to-load forwarding across the loop backedge\n");
  449. }
  450. if (Candidates.empty())
  451. return false;
  452. // Check intervening may-alias stores. These need runtime checks for alias
  453. // disambiguation.
  454. SmallVector<RuntimePointerCheck, 4> Checks = collectMemchecks(Candidates);
  455. // Too many checks are likely to outweigh the benefits of forwarding.
  456. if (Checks.size() > Candidates.size() * CheckPerElim) {
  457. LLVM_DEBUG(dbgs() << "Too many run-time checks needed.\n");
  458. return false;
  459. }
  460. if (LAI.getPSE().getUnionPredicate().getComplexity() >
  461. LoadElimSCEVCheckThreshold) {
  462. LLVM_DEBUG(dbgs() << "Too many SCEV run-time checks needed.\n");
  463. return false;
  464. }
  465. if (!L->isLoopSimplifyForm()) {
  466. LLVM_DEBUG(dbgs() << "Loop is not is loop-simplify form");
  467. return false;
  468. }
  469. if (!Checks.empty() || !LAI.getPSE().getUnionPredicate().isAlwaysTrue()) {
  470. if (LAI.hasConvergentOp()) {
  471. LLVM_DEBUG(dbgs() << "Versioning is needed but not allowed with "
  472. "convergent calls\n");
  473. return false;
  474. }
  475. auto *HeaderBB = L->getHeader();
  476. auto *F = HeaderBB->getParent();
  477. bool OptForSize = F->hasOptSize() ||
  478. llvm::shouldOptimizeForSize(HeaderBB, PSI, BFI,
  479. PGSOQueryType::IRPass);
  480. if (OptForSize) {
  481. LLVM_DEBUG(
  482. dbgs() << "Versioning is needed but not allowed when optimizing "
  483. "for size.\n");
  484. return false;
  485. }
  486. // Point of no-return, start the transformation. First, version the loop
  487. // if necessary.
  488. LoopVersioning LV(LAI, Checks, L, LI, DT, PSE.getSE());
  489. LV.versionLoop();
  490. // After versioning, some of the candidates' pointers could stop being
  491. // SCEVAddRecs. We need to filter them out.
  492. auto NoLongerGoodCandidate = [this](
  493. const StoreToLoadForwardingCandidate &Cand) {
  494. return !isa<SCEVAddRecExpr>(
  495. PSE.getSCEV(Cand.Load->getPointerOperand())) ||
  496. !isa<SCEVAddRecExpr>(
  497. PSE.getSCEV(Cand.Store->getPointerOperand()));
  498. };
  499. llvm::erase_if(Candidates, NoLongerGoodCandidate);
  500. }
  501. // Next, propagate the value stored by the store to the users of the load.
  502. // Also for the first iteration, generate the initial value of the load.
  503. SCEVExpander SEE(*PSE.getSE(), L->getHeader()->getModule()->getDataLayout(),
  504. "storeforward");
  505. for (const auto &Cand : Candidates)
  506. propagateStoredValueToLoadUsers(Cand, SEE);
  507. NumLoopLoadEliminted += Candidates.size();
  508. return true;
  509. }
  510. private:
  511. Loop *L;
  512. /// Maps the load/store instructions to their index according to
  513. /// program order.
  514. DenseMap<Instruction *, unsigned> InstOrder;
  515. // Analyses used.
  516. LoopInfo *LI;
  517. const LoopAccessInfo &LAI;
  518. DominatorTree *DT;
  519. BlockFrequencyInfo *BFI;
  520. ProfileSummaryInfo *PSI;
  521. PredicatedScalarEvolution PSE;
  522. };
  523. } // end anonymous namespace
  524. static bool
  525. eliminateLoadsAcrossLoops(Function &F, LoopInfo &LI, DominatorTree &DT,
  526. BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
  527. ScalarEvolution *SE, AssumptionCache *AC,
  528. function_ref<const LoopAccessInfo &(Loop &)> GetLAI) {
  529. // Build up a worklist of inner-loops to transform to avoid iterator
  530. // invalidation.
  531. // FIXME: This logic comes from other passes that actually change the loop
  532. // nest structure. It isn't clear this is necessary (or useful) for a pass
  533. // which merely optimizes the use of loads in a loop.
  534. SmallVector<Loop *, 8> Worklist;
  535. bool Changed = false;
  536. for (Loop *TopLevelLoop : LI)
  537. for (Loop *L : depth_first(TopLevelLoop)) {
  538. Changed |= simplifyLoop(L, &DT, &LI, SE, AC, /*MSSAU*/ nullptr, false);
  539. // We only handle inner-most loops.
  540. if (L->isInnermost())
  541. Worklist.push_back(L);
  542. }
  543. // Now walk the identified inner loops.
  544. for (Loop *L : Worklist) {
  545. // Match historical behavior
  546. if (!L->isRotatedForm() || !L->getExitingBlock())
  547. continue;
  548. // The actual work is performed by LoadEliminationForLoop.
  549. LoadEliminationForLoop LEL(L, &LI, GetLAI(*L), &DT, BFI, PSI);
  550. Changed |= LEL.processLoop();
  551. }
  552. return Changed;
  553. }
  554. namespace {
  555. /// The pass. Most of the work is delegated to the per-loop
  556. /// LoadEliminationForLoop class.
  557. class LoopLoadElimination : public FunctionPass {
  558. public:
  559. static char ID;
  560. LoopLoadElimination() : FunctionPass(ID) {
  561. initializeLoopLoadEliminationPass(*PassRegistry::getPassRegistry());
  562. }
  563. bool runOnFunction(Function &F) override {
  564. if (skipFunction(F))
  565. return false;
  566. auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
  567. auto &LAA = getAnalysis<LoopAccessLegacyAnalysis>();
  568. auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  569. auto *PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
  570. auto *BFI = (PSI && PSI->hasProfileSummary()) ?
  571. &getAnalysis<LazyBlockFrequencyInfoPass>().getBFI() :
  572. nullptr;
  573. auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
  574. // Process each loop nest in the function.
  575. return eliminateLoadsAcrossLoops(
  576. F, LI, DT, BFI, PSI, SE, /*AC*/ nullptr,
  577. [&LAA](Loop &L) -> const LoopAccessInfo & { return LAA.getInfo(&L); });
  578. }
  579. void getAnalysisUsage(AnalysisUsage &AU) const override {
  580. AU.addRequiredID(LoopSimplifyID);
  581. AU.addRequired<LoopInfoWrapperPass>();
  582. AU.addPreserved<LoopInfoWrapperPass>();
  583. AU.addRequired<LoopAccessLegacyAnalysis>();
  584. AU.addRequired<ScalarEvolutionWrapperPass>();
  585. AU.addRequired<DominatorTreeWrapperPass>();
  586. AU.addPreserved<DominatorTreeWrapperPass>();
  587. AU.addPreserved<GlobalsAAWrapperPass>();
  588. AU.addRequired<ProfileSummaryInfoWrapperPass>();
  589. LazyBlockFrequencyInfoPass::getLazyBFIAnalysisUsage(AU);
  590. }
  591. };
  592. } // end anonymous namespace
  593. char LoopLoadElimination::ID;
  594. static const char LLE_name[] = "Loop Load Elimination";
  595. INITIALIZE_PASS_BEGIN(LoopLoadElimination, LLE_OPTION, LLE_name, false, false)
  596. INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
  597. INITIALIZE_PASS_DEPENDENCY(LoopAccessLegacyAnalysis)
  598. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  599. INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
  600. INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
  601. INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
  602. INITIALIZE_PASS_DEPENDENCY(LazyBlockFrequencyInfoPass)
  603. INITIALIZE_PASS_END(LoopLoadElimination, LLE_OPTION, LLE_name, false, false)
  604. FunctionPass *llvm::createLoopLoadEliminationPass() {
  605. return new LoopLoadElimination();
  606. }
  607. PreservedAnalyses LoopLoadEliminationPass::run(Function &F,
  608. FunctionAnalysisManager &AM) {
  609. auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
  610. auto &LI = AM.getResult<LoopAnalysis>(F);
  611. auto &TTI = AM.getResult<TargetIRAnalysis>(F);
  612. auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
  613. auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
  614. auto &AA = AM.getResult<AAManager>(F);
  615. auto &AC = AM.getResult<AssumptionAnalysis>(F);
  616. auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
  617. auto *PSI = MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
  618. auto *BFI = (PSI && PSI->hasProfileSummary()) ?
  619. &AM.getResult<BlockFrequencyAnalysis>(F) : nullptr;
  620. auto &LAM = AM.getResult<LoopAnalysisManagerFunctionProxy>(F).getManager();
  621. bool Changed = eliminateLoadsAcrossLoops(
  622. F, LI, DT, BFI, PSI, &SE, &AC, [&](Loop &L) -> const LoopAccessInfo & {
  623. LoopStandardAnalysisResults AR = {AA, AC, DT, LI, SE,
  624. TLI, TTI, nullptr, nullptr, nullptr};
  625. return LAM.getResult<LoopAccessAnalysis>(L, AR);
  626. });
  627. if (!Changed)
  628. return PreservedAnalyses::all();
  629. PreservedAnalyses PA;
  630. return PA;
  631. }