blob: a04869011903979347f6384ead5515992818299c [file] [log] [blame]
Adam Nemete54a4fa2015-11-03 23:50:08 +00001//===- LoopLoadElimination.cpp - Loop Load Elimination Pass ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implement a loop-aware load elimination pass.
11//
12// It uses LoopAccessAnalysis to identify loop-carried dependences with a
13// distance of one between stores and loads. These form the candidates for the
14// transformation. The source value of each store then propagated to the user
15// of the corresponding load. This makes the load dead.
16//
17// The pass can also version the loop and add memchecks in order to prove that
18// may-aliasing stores can't change the value in memory before it's read by the
19// load.
20//
21//===----------------------------------------------------------------------===//
22
23#include "llvm/ADT/Statistic.h"
24#include "llvm/Analysis/LoopAccessAnalysis.h"
25#include "llvm/Analysis/LoopInfo.h"
26#include "llvm/Analysis/ScalarEvolutionExpander.h"
27#include "llvm/IR/Dominators.h"
28#include "llvm/IR/Module.h"
29#include "llvm/Pass.h"
30#include "llvm/Support/Debug.h"
Adam Nemetefb23412016-03-10 23:54:39 +000031#include "llvm/Transforms/Scalar.h"
Adam Nemete54a4fa2015-11-03 23:50:08 +000032#include "llvm/Transforms/Utils/LoopVersioning.h"
33#include <forward_list>
34
35#define LLE_OPTION "loop-load-elim"
36#define DEBUG_TYPE LLE_OPTION
37
38using namespace llvm;
39
40static cl::opt<unsigned> CheckPerElim(
41 "runtime-check-per-loop-load-elim", cl::Hidden,
42 cl::desc("Max number of memchecks allowed per eliminated load on average"),
43 cl::init(1));
44
Silviu Baranga2910a4f2015-11-09 13:26:09 +000045static cl::opt<unsigned> LoadElimSCEVCheckThreshold(
46 "loop-load-elimination-scev-check-threshold", cl::init(8), cl::Hidden,
47 cl::desc("The maximum number of SCEV checks allowed for Loop "
48 "Load Elimination"));
49
50
Adam Nemete54a4fa2015-11-03 23:50:08 +000051STATISTIC(NumLoopLoadEliminted, "Number of loads eliminated by LLE");
52
53namespace {
54
55/// \brief Represent a store-to-forwarding candidate.
56struct StoreToLoadForwardingCandidate {
57 LoadInst *Load;
58 StoreInst *Store;
59
60 StoreToLoadForwardingCandidate(LoadInst *Load, StoreInst *Store)
61 : Load(Load), Store(Store) {}
62
63 /// \brief Return true if the dependence from the store to the load has a
64 /// distance of one. E.g. A[i+1] = A[i]
Adam Nemet660748c2016-03-09 20:47:55 +000065 bool isDependenceDistanceOfOne(PredicatedScalarEvolution &PSE,
66 Loop *L) const {
Adam Nemete54a4fa2015-11-03 23:50:08 +000067 Value *LoadPtr = Load->getPointerOperand();
68 Value *StorePtr = Store->getPointerOperand();
69 Type *LoadPtrType = LoadPtr->getType();
Adam Nemete54a4fa2015-11-03 23:50:08 +000070 Type *LoadType = LoadPtrType->getPointerElementType();
71
72 assert(LoadPtrType->getPointerAddressSpace() ==
Adam Nemet7c94c9b2015-11-04 00:10:33 +000073 StorePtr->getType()->getPointerAddressSpace() &&
74 LoadType == StorePtr->getType()->getPointerElementType() &&
Adam Nemete54a4fa2015-11-03 23:50:08 +000075 "Should be a known dependence");
76
Adam Nemet660748c2016-03-09 20:47:55 +000077 // Currently we only support accesses with unit stride. FIXME: we should be
78 // able to handle non unit stirde as well as long as the stride is equal to
79 // the dependence distance.
80 if (isStridedPtr(PSE, LoadPtr, L) != 1 ||
81 isStridedPtr(PSE, LoadPtr, L) != 1)
82 return false;
83
Adam Nemete54a4fa2015-11-03 23:50:08 +000084 auto &DL = Load->getParent()->getModule()->getDataLayout();
85 unsigned TypeByteSize = DL.getTypeAllocSize(const_cast<Type *>(LoadType));
86
Silviu Baranga86de80d2015-12-10 11:07:18 +000087 auto *LoadPtrSCEV = cast<SCEVAddRecExpr>(PSE.getSCEV(LoadPtr));
88 auto *StorePtrSCEV = cast<SCEVAddRecExpr>(PSE.getSCEV(StorePtr));
Adam Nemete54a4fa2015-11-03 23:50:08 +000089
90 // We don't need to check non-wrapping here because forward/backward
91 // dependence wouldn't be valid if these weren't monotonic accesses.
Silviu Baranga86de80d2015-12-10 11:07:18 +000092 auto *Dist = cast<SCEVConstant>(
93 PSE.getSE()->getMinusSCEV(StorePtrSCEV, LoadPtrSCEV));
Sanjoy Das0de2fec2015-12-17 20:28:46 +000094 const APInt &Val = Dist->getAPInt();
Adam Nemet660748c2016-03-09 20:47:55 +000095 return Val == TypeByteSize;
Adam Nemete54a4fa2015-11-03 23:50:08 +000096 }
97
98 Value *getLoadPtr() const { return Load->getPointerOperand(); }
99
100#ifndef NDEBUG
101 friend raw_ostream &operator<<(raw_ostream &OS,
102 const StoreToLoadForwardingCandidate &Cand) {
103 OS << *Cand.Store << " -->\n";
104 OS.indent(2) << *Cand.Load << "\n";
105 return OS;
106 }
107#endif
108};
109
110/// \brief Check if the store dominates all latches, so as long as there is no
111/// intervening store this value will be loaded in the next iteration.
112bool doesStoreDominatesAllLatches(BasicBlock *StoreBlock, Loop *L,
113 DominatorTree *DT) {
114 SmallVector<BasicBlock *, 8> Latches;
115 L->getLoopLatches(Latches);
116 return std::all_of(Latches.begin(), Latches.end(),
117 [&](const BasicBlock *Latch) {
118 return DT->dominates(StoreBlock, Latch);
119 });
120}
121
122/// \brief The per-loop class that does most of the work.
123class LoadEliminationForLoop {
124public:
125 LoadEliminationForLoop(Loop *L, LoopInfo *LI, const LoopAccessInfo &LAI,
Silviu Baranga86de80d2015-12-10 11:07:18 +0000126 DominatorTree *DT)
127 : L(L), LI(LI), LAI(LAI), DT(DT), PSE(LAI.PSE) {}
Adam Nemete54a4fa2015-11-03 23:50:08 +0000128
129 /// \brief Look through the loop-carried and loop-independent dependences in
130 /// this loop and find store->load dependences.
131 ///
132 /// Note that no candidate is returned if LAA has failed to analyze the loop
133 /// (e.g. if it's not bottom-tested, contains volatile memops, etc.)
134 std::forward_list<StoreToLoadForwardingCandidate>
135 findStoreToLoadDependences(const LoopAccessInfo &LAI) {
136 std::forward_list<StoreToLoadForwardingCandidate> Candidates;
137
138 const auto *Deps = LAI.getDepChecker().getDependences();
139 if (!Deps)
140 return Candidates;
141
142 // Find store->load dependences (consequently true dep). Both lexically
143 // forward and backward dependences qualify. Disqualify loads that have
144 // other unknown dependences.
145
146 SmallSet<Instruction *, 4> LoadsWithUnknownDepedence;
147
148 for (const auto &Dep : *Deps) {
149 Instruction *Source = Dep.getSource(LAI);
150 Instruction *Destination = Dep.getDestination(LAI);
151
152 if (Dep.Type == MemoryDepChecker::Dependence::Unknown) {
153 if (isa<LoadInst>(Source))
154 LoadsWithUnknownDepedence.insert(Source);
155 if (isa<LoadInst>(Destination))
156 LoadsWithUnknownDepedence.insert(Destination);
157 continue;
158 }
159
160 if (Dep.isBackward())
161 // Note that the designations source and destination follow the program
162 // order, i.e. source is always first. (The direction is given by the
163 // DepType.)
164 std::swap(Source, Destination);
165 else
166 assert(Dep.isForward() && "Needs to be a forward dependence");
167
168 auto *Store = dyn_cast<StoreInst>(Source);
169 if (!Store)
170 continue;
171 auto *Load = dyn_cast<LoadInst>(Destination);
172 if (!Load)
173 continue;
174 Candidates.emplace_front(Load, Store);
175 }
176
177 if (!LoadsWithUnknownDepedence.empty())
178 Candidates.remove_if([&](const StoreToLoadForwardingCandidate &C) {
179 return LoadsWithUnknownDepedence.count(C.Load);
180 });
181
182 return Candidates;
183 }
184
185 /// \brief Return the index of the instruction according to program order.
186 unsigned getInstrIndex(Instruction *Inst) {
187 auto I = InstOrder.find(Inst);
188 assert(I != InstOrder.end() && "No index for instruction");
189 return I->second;
190 }
191
192 /// \brief If a load has multiple candidates associated (i.e. different
193 /// stores), it means that it could be forwarding from multiple stores
194 /// depending on control flow. Remove these candidates.
195 ///
196 /// Here, we rely on LAA to include the relevant loop-independent dependences.
197 /// LAA is known to omit these in the very simple case when the read and the
198 /// write within an alias set always takes place using the *same* pointer.
199 ///
200 /// However, we know that this is not the case here, i.e. we can rely on LAA
201 /// to provide us with loop-independent dependences for the cases we're
202 /// interested. Consider the case for example where a loop-independent
203 /// dependece S1->S2 invalidates the forwarding S3->S2.
204 ///
205 /// A[i] = ... (S1)
206 /// ... = A[i] (S2)
207 /// A[i+1] = ... (S3)
208 ///
209 /// LAA will perform dependence analysis here because there are two
210 /// *different* pointers involved in the same alias set (&A[i] and &A[i+1]).
211 void removeDependencesFromMultipleStores(
212 std::forward_list<StoreToLoadForwardingCandidate> &Candidates) {
213 // If Store is nullptr it means that we have multiple stores forwarding to
214 // this store.
215 typedef DenseMap<LoadInst *, const StoreToLoadForwardingCandidate *>
216 LoadToSingleCandT;
217 LoadToSingleCandT LoadToSingleCand;
218
219 for (const auto &Cand : Candidates) {
220 bool NewElt;
221 LoadToSingleCandT::iterator Iter;
222
223 std::tie(Iter, NewElt) =
224 LoadToSingleCand.insert(std::make_pair(Cand.Load, &Cand));
225 if (!NewElt) {
226 const StoreToLoadForwardingCandidate *&OtherCand = Iter->second;
227 // Already multiple stores forward to this load.
228 if (OtherCand == nullptr)
229 continue;
230
Adam Nemetefc091f2016-02-29 23:21:12 +0000231 // Handle the very basic case when the two stores are in the same block
232 // so deciding which one forwards is easy. The later one forwards as
233 // long as they both have a dependence distance of one to the load.
Adam Nemete54a4fa2015-11-03 23:50:08 +0000234 if (Cand.Store->getParent() == OtherCand->Store->getParent() &&
Adam Nemet660748c2016-03-09 20:47:55 +0000235 Cand.isDependenceDistanceOfOne(PSE, L) &&
236 OtherCand->isDependenceDistanceOfOne(PSE, L)) {
Adam Nemete54a4fa2015-11-03 23:50:08 +0000237 // They are in the same block, the later one will forward to the load.
238 if (getInstrIndex(OtherCand->Store) < getInstrIndex(Cand.Store))
239 OtherCand = &Cand;
240 } else
241 OtherCand = nullptr;
242 }
243 }
244
245 Candidates.remove_if([&](const StoreToLoadForwardingCandidate &Cand) {
246 if (LoadToSingleCand[Cand.Load] != &Cand) {
247 DEBUG(dbgs() << "Removing from candidates: \n" << Cand
248 << " The load may have multiple stores forwarding to "
249 << "it\n");
250 return true;
251 }
252 return false;
253 });
254 }
255
256 /// \brief Given two pointers operations by their RuntimePointerChecking
257 /// indices, return true if they require an alias check.
258 ///
259 /// We need a check if one is a pointer for a candidate load and the other is
260 /// a pointer for a possibly intervening store.
261 bool needsChecking(unsigned PtrIdx1, unsigned PtrIdx2,
262 const SmallSet<Value *, 4> &PtrsWrittenOnFwdingPath,
263 const std::set<Value *> &CandLoadPtrs) {
264 Value *Ptr1 =
265 LAI.getRuntimePointerChecking()->getPointerInfo(PtrIdx1).PointerValue;
266 Value *Ptr2 =
267 LAI.getRuntimePointerChecking()->getPointerInfo(PtrIdx2).PointerValue;
268 return ((PtrsWrittenOnFwdingPath.count(Ptr1) && CandLoadPtrs.count(Ptr2)) ||
269 (PtrsWrittenOnFwdingPath.count(Ptr2) && CandLoadPtrs.count(Ptr1)));
270 }
271
272 /// \brief Return pointers that are possibly written to on the path from a
273 /// forwarding store to a load.
274 ///
275 /// These pointers need to be alias-checked against the forwarding candidates.
276 SmallSet<Value *, 4> findPointersWrittenOnForwardingPath(
277 const SmallVectorImpl<StoreToLoadForwardingCandidate> &Candidates) {
278 // From FirstStore to LastLoad neither of the elimination candidate loads
279 // should overlap with any of the stores.
280 //
281 // E.g.:
282 //
283 // st1 C[i]
284 // ld1 B[i] <-------,
285 // ld0 A[i] <----, | * LastLoad
286 // ... | |
287 // st2 E[i] | |
288 // st3 B[i+1] -- | -' * FirstStore
289 // st0 A[i+1] ---'
290 // st4 D[i]
291 //
292 // st0 forwards to ld0 if the accesses in st4 and st1 don't overlap with
293 // ld0.
294
295 LoadInst *LastLoad =
296 std::max_element(Candidates.begin(), Candidates.end(),
297 [&](const StoreToLoadForwardingCandidate &A,
298 const StoreToLoadForwardingCandidate &B) {
299 return getInstrIndex(A.Load) < getInstrIndex(B.Load);
300 })
301 ->Load;
302 StoreInst *FirstStore =
303 std::min_element(Candidates.begin(), Candidates.end(),
304 [&](const StoreToLoadForwardingCandidate &A,
305 const StoreToLoadForwardingCandidate &B) {
306 return getInstrIndex(A.Store) <
307 getInstrIndex(B.Store);
308 })
309 ->Store;
310
311 // We're looking for stores after the first forwarding store until the end
312 // of the loop, then from the beginning of the loop until the last
313 // forwarded-to load. Collect the pointer for the stores.
314 SmallSet<Value *, 4> PtrsWrittenOnFwdingPath;
315
316 auto InsertStorePtr = [&](Instruction *I) {
317 if (auto *S = dyn_cast<StoreInst>(I))
318 PtrsWrittenOnFwdingPath.insert(S->getPointerOperand());
319 };
320 const auto &MemInstrs = LAI.getDepChecker().getMemoryInstructions();
321 std::for_each(MemInstrs.begin() + getInstrIndex(FirstStore) + 1,
322 MemInstrs.end(), InsertStorePtr);
323 std::for_each(MemInstrs.begin(), &MemInstrs[getInstrIndex(LastLoad)],
324 InsertStorePtr);
325
326 return PtrsWrittenOnFwdingPath;
327 }
328
329 /// \brief Determine the pointer alias checks to prove that there are no
330 /// intervening stores.
331 SmallVector<RuntimePointerChecking::PointerCheck, 4> collectMemchecks(
332 const SmallVectorImpl<StoreToLoadForwardingCandidate> &Candidates) {
333
334 SmallSet<Value *, 4> PtrsWrittenOnFwdingPath =
335 findPointersWrittenOnForwardingPath(Candidates);
336
337 // Collect the pointers of the candidate loads.
338 // FIXME: SmallSet does not work with std::inserter.
339 std::set<Value *> CandLoadPtrs;
340 std::transform(Candidates.begin(), Candidates.end(),
341 std::inserter(CandLoadPtrs, CandLoadPtrs.begin()),
342 std::mem_fn(&StoreToLoadForwardingCandidate::getLoadPtr));
343
344 const auto &AllChecks = LAI.getRuntimePointerChecking()->getChecks();
345 SmallVector<RuntimePointerChecking::PointerCheck, 4> Checks;
346
347 std::copy_if(AllChecks.begin(), AllChecks.end(), std::back_inserter(Checks),
348 [&](const RuntimePointerChecking::PointerCheck &Check) {
349 for (auto PtrIdx1 : Check.first->Members)
350 for (auto PtrIdx2 : Check.second->Members)
351 if (needsChecking(PtrIdx1, PtrIdx2,
352 PtrsWrittenOnFwdingPath, CandLoadPtrs))
353 return true;
354 return false;
355 });
356
357 DEBUG(dbgs() << "\nPointer Checks (count: " << Checks.size() << "):\n");
358 DEBUG(LAI.getRuntimePointerChecking()->printChecks(dbgs(), Checks));
359
360 return Checks;
361 }
362
363 /// \brief Perform the transformation for a candidate.
364 void
365 propagateStoredValueToLoadUsers(const StoreToLoadForwardingCandidate &Cand,
366 SCEVExpander &SEE) {
367 //
368 // loop:
369 // %x = load %gep_i
370 // = ... %x
371 // store %y, %gep_i_plus_1
372 //
373 // =>
374 //
375 // ph:
376 // %x.initial = load %gep_0
377 // loop:
378 // %x.storeforward = phi [%x.initial, %ph] [%y, %loop]
379 // %x = load %gep_i <---- now dead
380 // = ... %x.storeforward
381 // store %y, %gep_i_plus_1
382
383 Value *Ptr = Cand.Load->getPointerOperand();
Silviu Baranga86de80d2015-12-10 11:07:18 +0000384 auto *PtrSCEV = cast<SCEVAddRecExpr>(PSE.getSCEV(Ptr));
Adam Nemete54a4fa2015-11-03 23:50:08 +0000385 auto *PH = L->getLoopPreheader();
386 Value *InitialPtr = SEE.expandCodeFor(PtrSCEV->getStart(), Ptr->getType(),
387 PH->getTerminator());
388 Value *Initial =
389 new LoadInst(InitialPtr, "load_initial", PH->getTerminator());
390 PHINode *PHI = PHINode::Create(Initial->getType(), 2, "store_forwarded",
Duncan P. N. Exon Smith83c4b682015-11-07 00:01:16 +0000391 &L->getHeader()->front());
Adam Nemete54a4fa2015-11-03 23:50:08 +0000392 PHI->addIncoming(Initial, PH);
393 PHI->addIncoming(Cand.Store->getOperand(0), L->getLoopLatch());
394
395 Cand.Load->replaceAllUsesWith(PHI);
396 }
397
398 /// \brief Top-level driver for each loop: find store->load forwarding
399 /// candidates, add run-time checks and perform transformation.
400 bool processLoop() {
401 DEBUG(dbgs() << "\nIn \"" << L->getHeader()->getParent()->getName()
402 << "\" checking " << *L << "\n");
403 // Look for store-to-load forwarding cases across the
404 // backedge. E.g.:
405 //
406 // loop:
407 // %x = load %gep_i
408 // = ... %x
409 // store %y, %gep_i_plus_1
410 //
411 // =>
412 //
413 // ph:
414 // %x.initial = load %gep_0
415 // loop:
416 // %x.storeforward = phi [%x.initial, %ph] [%y, %loop]
417 // %x = load %gep_i <---- now dead
418 // = ... %x.storeforward
419 // store %y, %gep_i_plus_1
420
421 // First start with store->load dependences.
422 auto StoreToLoadDependences = findStoreToLoadDependences(LAI);
423 if (StoreToLoadDependences.empty())
424 return false;
425
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
430 // To keep things simple for now, remove those where the load is potentially
431 // fed by multiple stores.
432 removeDependencesFromMultipleStores(StoreToLoadDependences);
433 if (StoreToLoadDependences.empty())
434 return false;
435
436 // Filter the candidates further.
437 SmallVector<StoreToLoadForwardingCandidate, 4> Candidates;
438 unsigned NumForwarding = 0;
439 for (const StoreToLoadForwardingCandidate Cand : StoreToLoadDependences) {
440 DEBUG(dbgs() << "Candidate " << Cand);
Adam Nemet83be06e2016-02-29 22:53:59 +0000441 // Only progagate value if they are of the same type.
442 if (Cand.Store->getPointerOperand()->getType() !=
443 Cand.Load->getPointerOperand()->getType())
444 continue;
445
Adam Nemete54a4fa2015-11-03 23:50:08 +0000446 // Make sure that the stored values is available everywhere in the loop in
447 // the next iteration.
448 if (!doesStoreDominatesAllLatches(Cand.Store->getParent(), L, DT))
449 continue;
450
451 // Check whether the SCEV difference is the same as the induction step,
452 // thus we load the value in the next iteration.
Adam Nemet660748c2016-03-09 20:47:55 +0000453 if (!Cand.isDependenceDistanceOfOne(PSE, L))
Adam Nemete54a4fa2015-11-03 23:50:08 +0000454 continue;
455
456 ++NumForwarding;
457 DEBUG(dbgs()
458 << NumForwarding
459 << ". Valid store-to-load forwarding across the loop backedge\n");
460 Candidates.push_back(Cand);
461 }
462 if (Candidates.empty())
463 return false;
464
465 // Check intervening may-alias stores. These need runtime checks for alias
466 // disambiguation.
467 SmallVector<RuntimePointerChecking::PointerCheck, 4> Checks =
468 collectMemchecks(Candidates);
469
470 // Too many checks are likely to outweigh the benefits of forwarding.
471 if (Checks.size() > Candidates.size() * CheckPerElim) {
472 DEBUG(dbgs() << "Too many run-time checks needed.\n");
473 return false;
474 }
475
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +0000476 if (LAI.PSE.getUnionPredicate().getComplexity() >
477 LoadElimSCEVCheckThreshold) {
Silviu Baranga2910a4f2015-11-09 13:26:09 +0000478 DEBUG(dbgs() << "Too many SCEV run-time checks needed.\n");
479 return false;
480 }
481
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +0000482 if (!Checks.empty() || !LAI.PSE.getUnionPredicate().isAlwaysTrue()) {
Adam Nemet9455c1d2016-02-05 01:14:05 +0000483 if (L->getHeader()->getParent()->optForSize()) {
484 DEBUG(dbgs() << "Versioning is needed but not allowed when optimizing "
485 "for size.\n");
486 return false;
487 }
488
489 // Point of no-return, start the transformation. First, version the loop
490 // if necessary.
491
Silviu Baranga86de80d2015-12-10 11:07:18 +0000492 LoopVersioning LV(LAI, L, LI, DT, PSE.getSE(), false);
Silviu Baranga2910a4f2015-11-09 13:26:09 +0000493 LV.setAliasChecks(std::move(Checks));
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +0000494 LV.setSCEVChecks(LAI.PSE.getUnionPredicate());
Adam Nemete54a4fa2015-11-03 23:50:08 +0000495 LV.versionLoop();
496 }
497
498 // Next, propagate the value stored by the store to the users of the load.
499 // Also for the first iteration, generate the initial value of the load.
Silviu Baranga86de80d2015-12-10 11:07:18 +0000500 SCEVExpander SEE(*PSE.getSE(), L->getHeader()->getModule()->getDataLayout(),
Adam Nemete54a4fa2015-11-03 23:50:08 +0000501 "storeforward");
502 for (const auto &Cand : Candidates)
503 propagateStoredValueToLoadUsers(Cand, SEE);
504 NumLoopLoadEliminted += NumForwarding;
505
506 return true;
507 }
508
509private:
510 Loop *L;
511
512 /// \brief Maps the load/store instructions to their index according to
513 /// program order.
514 DenseMap<Instruction *, unsigned> InstOrder;
515
516 // Analyses used.
517 LoopInfo *LI;
518 const LoopAccessInfo &LAI;
519 DominatorTree *DT;
Silviu Baranga86de80d2015-12-10 11:07:18 +0000520 PredicatedScalarEvolution PSE;
Adam Nemete54a4fa2015-11-03 23:50:08 +0000521};
522
523/// \brief The pass. Most of the work is delegated to the per-loop
524/// LoadEliminationForLoop class.
525class LoopLoadElimination : public FunctionPass {
526public:
527 LoopLoadElimination() : FunctionPass(ID) {
528 initializeLoopLoadEliminationPass(*PassRegistry::getPassRegistry());
529 }
530
531 bool runOnFunction(Function &F) override {
532 auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
533 auto *LAA = &getAnalysis<LoopAccessAnalysis>();
534 auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Adam Nemete54a4fa2015-11-03 23:50:08 +0000535
536 // Build up a worklist of inner-loops to vectorize. This is necessary as the
537 // act of distributing a loop creates new loops and can invalidate iterators
538 // across the loops.
539 SmallVector<Loop *, 8> Worklist;
540
541 for (Loop *TopLevelLoop : *LI)
542 for (Loop *L : depth_first(TopLevelLoop))
543 // We only handle inner-most loops.
544 if (L->empty())
545 Worklist.push_back(L);
546
547 // Now walk the identified inner loops.
548 bool Changed = false;
549 for (Loop *L : Worklist) {
550 const LoopAccessInfo &LAI = LAA->getInfo(L, ValueToValueMap());
551 // The actual work is performed by LoadEliminationForLoop.
Silviu Baranga86de80d2015-12-10 11:07:18 +0000552 LoadEliminationForLoop LEL(L, LI, LAI, DT);
Adam Nemete54a4fa2015-11-03 23:50:08 +0000553 Changed |= LEL.processLoop();
554 }
555
556 // Process each loop nest in the function.
557 return Changed;
558 }
559
560 void getAnalysisUsage(AnalysisUsage &AU) const override {
Adam Nemetefb23412016-03-10 23:54:39 +0000561 AU.addRequiredID(LoopSimplifyID);
Adam Nemete54a4fa2015-11-03 23:50:08 +0000562 AU.addRequired<LoopInfoWrapperPass>();
563 AU.addPreserved<LoopInfoWrapperPass>();
564 AU.addRequired<LoopAccessAnalysis>();
565 AU.addRequired<ScalarEvolutionWrapperPass>();
566 AU.addRequired<DominatorTreeWrapperPass>();
567 AU.addPreserved<DominatorTreeWrapperPass>();
568 }
569
570 static char ID;
571};
572}
573
574char LoopLoadElimination::ID;
575static const char LLE_name[] = "Loop Load Elimination";
576
577INITIALIZE_PASS_BEGIN(LoopLoadElimination, LLE_OPTION, LLE_name, false, false)
578INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
579INITIALIZE_PASS_DEPENDENCY(LoopAccessAnalysis)
580INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
581INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
Adam Nemetefb23412016-03-10 23:54:39 +0000582INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
Adam Nemete54a4fa2015-11-03 23:50:08 +0000583INITIALIZE_PASS_END(LoopLoadElimination, LLE_OPTION, LLE_name, false, false)
584
585namespace llvm {
586FunctionPass *createLoopLoadEliminationPass() {
587 return new LoopLoadElimination();
588}
589}