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