blob: 358253266eb6fc5706660f594824afe4f5ecf8fb [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.
Denis Zobnin15d1e642016-05-10 05:55:16 +000080 if (getPtrStride(PSE, LoadPtr, L) != 1 ||
81 getPtrStride(PSE, StorePtr, L) != 1)
Adam Nemet660748c2016-03-09 20:47:55 +000082 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);
David Majnemer0a16c222016-08-11 21:15:00 +0000116 return all_of(Latches, [&](const BasicBlock *Latch) {
117 return DT->dominates(StoreBlock, Latch);
118 });
Adam Nemete54a4fa2015-11-03 23:50:08 +0000119}
120
Adam Nemetbd861ac2016-06-28 04:02:47 +0000121/// \brief Return true if the load is not executed on all paths in the loop.
122static bool isLoadConditional(LoadInst *Load, Loop *L) {
123 return Load->getParent() != L->getHeader();
124}
125
Adam Nemete54a4fa2015-11-03 23:50:08 +0000126/// \brief The per-loop class that does most of the work.
127class LoadEliminationForLoop {
128public:
129 LoadEliminationForLoop(Loop *L, LoopInfo *LI, const LoopAccessInfo &LAI,
Silviu Baranga86de80d2015-12-10 11:07:18 +0000130 DominatorTree *DT)
Xinliang David Li94734ee2016-07-01 05:59:55 +0000131 : L(L), LI(LI), LAI(LAI), DT(DT), PSE(LAI.getPSE()) {}
Adam Nemete54a4fa2015-11-03 23:50:08 +0000132
133 /// \brief Look through the loop-carried and loop-independent dependences in
134 /// this loop and find store->load dependences.
135 ///
136 /// Note that no candidate is returned if LAA has failed to analyze the loop
137 /// (e.g. if it's not bottom-tested, contains volatile memops, etc.)
138 std::forward_list<StoreToLoadForwardingCandidate>
139 findStoreToLoadDependences(const LoopAccessInfo &LAI) {
140 std::forward_list<StoreToLoadForwardingCandidate> Candidates;
141
142 const auto *Deps = LAI.getDepChecker().getDependences();
143 if (!Deps)
144 return Candidates;
145
146 // Find store->load dependences (consequently true dep). Both lexically
147 // forward and backward dependences qualify. Disqualify loads that have
148 // other unknown dependences.
149
150 SmallSet<Instruction *, 4> LoadsWithUnknownDepedence;
151
152 for (const auto &Dep : *Deps) {
153 Instruction *Source = Dep.getSource(LAI);
154 Instruction *Destination = Dep.getDestination(LAI);
155
156 if (Dep.Type == MemoryDepChecker::Dependence::Unknown) {
157 if (isa<LoadInst>(Source))
158 LoadsWithUnknownDepedence.insert(Source);
159 if (isa<LoadInst>(Destination))
160 LoadsWithUnknownDepedence.insert(Destination);
161 continue;
162 }
163
164 if (Dep.isBackward())
165 // Note that the designations source and destination follow the program
166 // order, i.e. source is always first. (The direction is given by the
167 // DepType.)
168 std::swap(Source, Destination);
169 else
170 assert(Dep.isForward() && "Needs to be a forward dependence");
171
172 auto *Store = dyn_cast<StoreInst>(Source);
173 if (!Store)
174 continue;
175 auto *Load = dyn_cast<LoadInst>(Destination);
176 if (!Load)
177 continue;
Adam Nemet7aba60c2016-03-24 17:59:26 +0000178
179 // Only progagate the value if they are of the same type.
180 if (Store->getPointerOperand()->getType() !=
181 Load->getPointerOperand()->getType())
182 continue;
183
Adam Nemete54a4fa2015-11-03 23:50:08 +0000184 Candidates.emplace_front(Load, Store);
185 }
186
187 if (!LoadsWithUnknownDepedence.empty())
188 Candidates.remove_if([&](const StoreToLoadForwardingCandidate &C) {
189 return LoadsWithUnknownDepedence.count(C.Load);
190 });
191
192 return Candidates;
193 }
194
195 /// \brief 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
202 /// \brief If a load has multiple candidates associated (i.e. different
203 /// stores), it means that it could be forwarding from multiple stores
204 /// depending on control flow. Remove these candidates.
205 ///
206 /// Here, we rely on LAA to include the relevant loop-independent dependences.
207 /// LAA is known to omit these in the very simple case when the read and the
208 /// write within an alias set always takes place using the *same* pointer.
209 ///
210 /// However, we know that this is not the case here, i.e. we can rely on LAA
211 /// to provide us with loop-independent dependences for the cases we're
212 /// interested. Consider the case for example where a loop-independent
213 /// dependece S1->S2 invalidates the forwarding S3->S2.
214 ///
215 /// A[i] = ... (S1)
216 /// ... = A[i] (S2)
217 /// A[i+1] = ... (S3)
218 ///
219 /// LAA will perform dependence analysis here because there are two
220 /// *different* pointers involved in the same alias set (&A[i] and &A[i+1]).
221 void removeDependencesFromMultipleStores(
222 std::forward_list<StoreToLoadForwardingCandidate> &Candidates) {
223 // If Store is nullptr it means that we have multiple stores forwarding to
224 // this store.
225 typedef DenseMap<LoadInst *, const StoreToLoadForwardingCandidate *>
226 LoadToSingleCandT;
227 LoadToSingleCandT LoadToSingleCand;
228
229 for (const auto &Cand : Candidates) {
230 bool NewElt;
231 LoadToSingleCandT::iterator Iter;
232
233 std::tie(Iter, NewElt) =
234 LoadToSingleCand.insert(std::make_pair(Cand.Load, &Cand));
235 if (!NewElt) {
236 const StoreToLoadForwardingCandidate *&OtherCand = Iter->second;
237 // Already multiple stores forward to this load.
238 if (OtherCand == nullptr)
239 continue;
240
Adam Nemetefc091f2016-02-29 23:21:12 +0000241 // Handle the very basic case when the two stores are in the same block
242 // so deciding which one forwards is easy. The later one forwards as
243 // long as they both have a dependence distance of one to the load.
Adam Nemete54a4fa2015-11-03 23:50:08 +0000244 if (Cand.Store->getParent() == OtherCand->Store->getParent() &&
Adam Nemet660748c2016-03-09 20:47:55 +0000245 Cand.isDependenceDistanceOfOne(PSE, L) &&
246 OtherCand->isDependenceDistanceOfOne(PSE, L)) {
Adam Nemete54a4fa2015-11-03 23:50:08 +0000247 // They are in the same block, the later one will forward to the load.
248 if (getInstrIndex(OtherCand->Store) < getInstrIndex(Cand.Store))
249 OtherCand = &Cand;
250 } else
251 OtherCand = nullptr;
252 }
253 }
254
255 Candidates.remove_if([&](const StoreToLoadForwardingCandidate &Cand) {
256 if (LoadToSingleCand[Cand.Load] != &Cand) {
257 DEBUG(dbgs() << "Removing from candidates: \n" << Cand
258 << " The load may have multiple stores forwarding to "
259 << "it\n");
260 return true;
261 }
262 return false;
263 });
264 }
265
266 /// \brief Given two pointers operations by their RuntimePointerChecking
267 /// indices, return true if they require an alias check.
268 ///
269 /// We need a check if one is a pointer for a candidate load and the other is
270 /// a pointer for a possibly intervening store.
271 bool needsChecking(unsigned PtrIdx1, unsigned PtrIdx2,
272 const SmallSet<Value *, 4> &PtrsWrittenOnFwdingPath,
273 const std::set<Value *> &CandLoadPtrs) {
274 Value *Ptr1 =
275 LAI.getRuntimePointerChecking()->getPointerInfo(PtrIdx1).PointerValue;
276 Value *Ptr2 =
277 LAI.getRuntimePointerChecking()->getPointerInfo(PtrIdx2).PointerValue;
278 return ((PtrsWrittenOnFwdingPath.count(Ptr1) && CandLoadPtrs.count(Ptr2)) ||
279 (PtrsWrittenOnFwdingPath.count(Ptr2) && CandLoadPtrs.count(Ptr1)));
280 }
281
282 /// \brief Return pointers that are possibly written to on the path from a
283 /// forwarding store to a load.
284 ///
285 /// These pointers need to be alias-checked against the forwarding candidates.
286 SmallSet<Value *, 4> findPointersWrittenOnForwardingPath(
287 const SmallVectorImpl<StoreToLoadForwardingCandidate> &Candidates) {
288 // From FirstStore to LastLoad neither of the elimination candidate loads
289 // should overlap with any of the stores.
290 //
291 // E.g.:
292 //
293 // st1 C[i]
294 // ld1 B[i] <-------,
295 // ld0 A[i] <----, | * LastLoad
296 // ... | |
297 // st2 E[i] | |
298 // st3 B[i+1] -- | -' * FirstStore
299 // st0 A[i+1] ---'
300 // st4 D[i]
301 //
302 // st0 forwards to ld0 if the accesses in st4 and st1 don't overlap with
303 // ld0.
304
305 LoadInst *LastLoad =
306 std::max_element(Candidates.begin(), Candidates.end(),
307 [&](const StoreToLoadForwardingCandidate &A,
308 const StoreToLoadForwardingCandidate &B) {
309 return getInstrIndex(A.Load) < getInstrIndex(B.Load);
310 })
311 ->Load;
312 StoreInst *FirstStore =
313 std::min_element(Candidates.begin(), Candidates.end(),
314 [&](const StoreToLoadForwardingCandidate &A,
315 const StoreToLoadForwardingCandidate &B) {
316 return getInstrIndex(A.Store) <
317 getInstrIndex(B.Store);
318 })
319 ->Store;
320
321 // We're looking for stores after the first forwarding store until the end
322 // of the loop, then from the beginning of the loop until the last
323 // forwarded-to load. Collect the pointer for the stores.
324 SmallSet<Value *, 4> PtrsWrittenOnFwdingPath;
325
326 auto InsertStorePtr = [&](Instruction *I) {
327 if (auto *S = dyn_cast<StoreInst>(I))
328 PtrsWrittenOnFwdingPath.insert(S->getPointerOperand());
329 };
330 const auto &MemInstrs = LAI.getDepChecker().getMemoryInstructions();
331 std::for_each(MemInstrs.begin() + getInstrIndex(FirstStore) + 1,
332 MemInstrs.end(), InsertStorePtr);
333 std::for_each(MemInstrs.begin(), &MemInstrs[getInstrIndex(LastLoad)],
334 InsertStorePtr);
335
336 return PtrsWrittenOnFwdingPath;
337 }
338
339 /// \brief Determine the pointer alias checks to prove that there are no
340 /// intervening stores.
341 SmallVector<RuntimePointerChecking::PointerCheck, 4> collectMemchecks(
342 const SmallVectorImpl<StoreToLoadForwardingCandidate> &Candidates) {
343
344 SmallSet<Value *, 4> PtrsWrittenOnFwdingPath =
345 findPointersWrittenOnForwardingPath(Candidates);
346
347 // Collect the pointers of the candidate loads.
348 // FIXME: SmallSet does not work with std::inserter.
349 std::set<Value *> CandLoadPtrs;
David Majnemer2d006e72016-08-12 04:32:42 +0000350 transform(Candidates,
Adam Nemete54a4fa2015-11-03 23:50:08 +0000351 std::inserter(CandLoadPtrs, CandLoadPtrs.begin()),
352 std::mem_fn(&StoreToLoadForwardingCandidate::getLoadPtr));
353
354 const auto &AllChecks = LAI.getRuntimePointerChecking()->getChecks();
355 SmallVector<RuntimePointerChecking::PointerCheck, 4> Checks;
356
357 std::copy_if(AllChecks.begin(), AllChecks.end(), std::back_inserter(Checks),
358 [&](const RuntimePointerChecking::PointerCheck &Check) {
359 for (auto PtrIdx1 : Check.first->Members)
360 for (auto PtrIdx2 : Check.second->Members)
361 if (needsChecking(PtrIdx1, PtrIdx2,
362 PtrsWrittenOnFwdingPath, CandLoadPtrs))
363 return true;
364 return false;
365 });
366
367 DEBUG(dbgs() << "\nPointer Checks (count: " << Checks.size() << "):\n");
368 DEBUG(LAI.getRuntimePointerChecking()->printChecks(dbgs(), Checks));
369
370 return Checks;
371 }
372
373 /// \brief Perform the transformation for a candidate.
374 void
375 propagateStoredValueToLoadUsers(const StoreToLoadForwardingCandidate &Cand,
376 SCEVExpander &SEE) {
377 //
378 // loop:
379 // %x = load %gep_i
380 // = ... %x
381 // store %y, %gep_i_plus_1
382 //
383 // =>
384 //
385 // ph:
386 // %x.initial = load %gep_0
387 // loop:
388 // %x.storeforward = phi [%x.initial, %ph] [%y, %loop]
389 // %x = load %gep_i <---- now dead
390 // = ... %x.storeforward
391 // store %y, %gep_i_plus_1
392
393 Value *Ptr = Cand.Load->getPointerOperand();
Silviu Baranga86de80d2015-12-10 11:07:18 +0000394 auto *PtrSCEV = cast<SCEVAddRecExpr>(PSE.getSCEV(Ptr));
Adam Nemete54a4fa2015-11-03 23:50:08 +0000395 auto *PH = L->getLoopPreheader();
396 Value *InitialPtr = SEE.expandCodeFor(PtrSCEV->getStart(), Ptr->getType(),
397 PH->getTerminator());
398 Value *Initial =
399 new LoadInst(InitialPtr, "load_initial", PH->getTerminator());
400 PHINode *PHI = PHINode::Create(Initial->getType(), 2, "store_forwarded",
Duncan P. N. Exon Smith83c4b682015-11-07 00:01:16 +0000401 &L->getHeader()->front());
Adam Nemete54a4fa2015-11-03 23:50:08 +0000402 PHI->addIncoming(Initial, PH);
403 PHI->addIncoming(Cand.Store->getOperand(0), L->getLoopLatch());
404
405 Cand.Load->replaceAllUsesWith(PHI);
406 }
407
408 /// \brief Top-level driver for each loop: find store->load forwarding
409 /// candidates, add run-time checks and perform transformation.
410 bool processLoop() {
411 DEBUG(dbgs() << "\nIn \"" << L->getHeader()->getParent()->getName()
412 << "\" checking " << *L << "\n");
413 // Look for store-to-load forwarding cases across the
414 // backedge. E.g.:
415 //
416 // loop:
417 // %x = load %gep_i
418 // = ... %x
419 // store %y, %gep_i_plus_1
420 //
421 // =>
422 //
423 // ph:
424 // %x.initial = load %gep_0
425 // loop:
426 // %x.storeforward = phi [%x.initial, %ph] [%y, %loop]
427 // %x = load %gep_i <---- now dead
428 // = ... %x.storeforward
429 // store %y, %gep_i_plus_1
430
431 // First start with store->load dependences.
432 auto StoreToLoadDependences = findStoreToLoadDependences(LAI);
433 if (StoreToLoadDependences.empty())
434 return false;
435
436 // Generate an index for each load and store according to the original
437 // program order. This will be used later.
438 InstOrder = LAI.getDepChecker().generateInstructionOrderMap();
439
440 // To keep things simple for now, remove those where the load is potentially
441 // fed by multiple stores.
442 removeDependencesFromMultipleStores(StoreToLoadDependences);
443 if (StoreToLoadDependences.empty())
444 return false;
445
446 // Filter the candidates further.
447 SmallVector<StoreToLoadForwardingCandidate, 4> Candidates;
448 unsigned NumForwarding = 0;
449 for (const StoreToLoadForwardingCandidate Cand : StoreToLoadDependences) {
450 DEBUG(dbgs() << "Candidate " << Cand);
Adam Nemet83be06e2016-02-29 22:53:59 +0000451
Adam Nemete54a4fa2015-11-03 23:50:08 +0000452 // Make sure that the stored values is available everywhere in the loop in
453 // the next iteration.
454 if (!doesStoreDominatesAllLatches(Cand.Store->getParent(), L, DT))
455 continue;
456
Adam Nemetbd861ac2016-06-28 04:02:47 +0000457 // If the load is conditional we can't hoist its 0-iteration instance to
458 // the preheader because that would make it unconditional. Thus we would
459 // access a memory location that the original loop did not access.
460 if (isLoadConditional(Cand.Load, L))
461 continue;
462
Adam Nemete54a4fa2015-11-03 23:50:08 +0000463 // Check whether the SCEV difference is the same as the induction step,
464 // thus we load the value in the next iteration.
Adam Nemet660748c2016-03-09 20:47:55 +0000465 if (!Cand.isDependenceDistanceOfOne(PSE, L))
Adam Nemete54a4fa2015-11-03 23:50:08 +0000466 continue;
467
468 ++NumForwarding;
469 DEBUG(dbgs()
470 << NumForwarding
471 << ". Valid store-to-load forwarding across the loop backedge\n");
472 Candidates.push_back(Cand);
473 }
474 if (Candidates.empty())
475 return false;
476
477 // Check intervening may-alias stores. These need runtime checks for alias
478 // disambiguation.
479 SmallVector<RuntimePointerChecking::PointerCheck, 4> Checks =
480 collectMemchecks(Candidates);
481
482 // Too many checks are likely to outweigh the benefits of forwarding.
483 if (Checks.size() > Candidates.size() * CheckPerElim) {
484 DEBUG(dbgs() << "Too many run-time checks needed.\n");
485 return false;
486 }
487
Xinliang David Li94734ee2016-07-01 05:59:55 +0000488 if (LAI.getPSE().getUnionPredicate().getComplexity() >
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +0000489 LoadElimSCEVCheckThreshold) {
Silviu Baranga2910a4f2015-11-09 13:26:09 +0000490 DEBUG(dbgs() << "Too many SCEV run-time checks needed.\n");
491 return false;
492 }
493
Xinliang David Li94734ee2016-07-01 05:59:55 +0000494 if (!Checks.empty() || !LAI.getPSE().getUnionPredicate().isAlwaysTrue()) {
Adam Nemet9455c1d2016-02-05 01:14:05 +0000495 if (L->getHeader()->getParent()->optForSize()) {
496 DEBUG(dbgs() << "Versioning is needed but not allowed when optimizing "
497 "for size.\n");
498 return false;
499 }
500
501 // Point of no-return, start the transformation. First, version the loop
502 // if necessary.
503
Silviu Baranga86de80d2015-12-10 11:07:18 +0000504 LoopVersioning LV(LAI, L, LI, DT, PSE.getSE(), false);
Silviu Baranga2910a4f2015-11-09 13:26:09 +0000505 LV.setAliasChecks(std::move(Checks));
Xinliang David Li94734ee2016-07-01 05:59:55 +0000506 LV.setSCEVChecks(LAI.getPSE().getUnionPredicate());
Adam Nemete54a4fa2015-11-03 23:50:08 +0000507 LV.versionLoop();
508 }
509
510 // Next, propagate the value stored by the store to the users of the load.
511 // Also for the first iteration, generate the initial value of the load.
Silviu Baranga86de80d2015-12-10 11:07:18 +0000512 SCEVExpander SEE(*PSE.getSE(), L->getHeader()->getModule()->getDataLayout(),
Adam Nemete54a4fa2015-11-03 23:50:08 +0000513 "storeforward");
514 for (const auto &Cand : Candidates)
515 propagateStoredValueToLoadUsers(Cand, SEE);
516 NumLoopLoadEliminted += NumForwarding;
517
518 return true;
519 }
520
521private:
522 Loop *L;
523
524 /// \brief Maps the load/store instructions to their index according to
525 /// program order.
526 DenseMap<Instruction *, unsigned> InstOrder;
527
528 // Analyses used.
529 LoopInfo *LI;
530 const LoopAccessInfo &LAI;
531 DominatorTree *DT;
Silviu Baranga86de80d2015-12-10 11:07:18 +0000532 PredicatedScalarEvolution PSE;
Adam Nemete54a4fa2015-11-03 23:50:08 +0000533};
534
535/// \brief The pass. Most of the work is delegated to the per-loop
536/// LoadEliminationForLoop class.
537class LoopLoadElimination : public FunctionPass {
538public:
539 LoopLoadElimination() : FunctionPass(ID) {
540 initializeLoopLoadEliminationPass(*PassRegistry::getPassRegistry());
541 }
542
543 bool runOnFunction(Function &F) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000544 if (skipFunction(F))
545 return false;
546
Adam Nemete54a4fa2015-11-03 23:50:08 +0000547 auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Xinliang David Li7853c1d2016-07-08 20:55:26 +0000548 auto *LAA = &getAnalysis<LoopAccessLegacyAnalysis>();
Adam Nemete54a4fa2015-11-03 23:50:08 +0000549 auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Adam Nemete54a4fa2015-11-03 23:50:08 +0000550
551 // Build up a worklist of inner-loops to vectorize. This is necessary as the
552 // act of distributing a loop creates new loops and can invalidate iterators
553 // across the loops.
554 SmallVector<Loop *, 8> Worklist;
555
556 for (Loop *TopLevelLoop : *LI)
557 for (Loop *L : depth_first(TopLevelLoop))
558 // We only handle inner-most loops.
559 if (L->empty())
560 Worklist.push_back(L);
561
562 // Now walk the identified inner loops.
563 bool Changed = false;
564 for (Loop *L : Worklist) {
Adam Nemetbdbc5222016-06-16 08:26:56 +0000565 const LoopAccessInfo &LAI = LAA->getInfo(L);
Adam Nemete54a4fa2015-11-03 23:50:08 +0000566 // The actual work is performed by LoadEliminationForLoop.
Silviu Baranga86de80d2015-12-10 11:07:18 +0000567 LoadEliminationForLoop LEL(L, LI, LAI, DT);
Adam Nemete54a4fa2015-11-03 23:50:08 +0000568 Changed |= LEL.processLoop();
569 }
570
571 // Process each loop nest in the function.
572 return Changed;
573 }
574
575 void getAnalysisUsage(AnalysisUsage &AU) const override {
Adam Nemetefb23412016-03-10 23:54:39 +0000576 AU.addRequiredID(LoopSimplifyID);
Adam Nemete54a4fa2015-11-03 23:50:08 +0000577 AU.addRequired<LoopInfoWrapperPass>();
578 AU.addPreserved<LoopInfoWrapperPass>();
Xinliang David Li7853c1d2016-07-08 20:55:26 +0000579 AU.addRequired<LoopAccessLegacyAnalysis>();
Adam Nemete54a4fa2015-11-03 23:50:08 +0000580 AU.addRequired<ScalarEvolutionWrapperPass>();
581 AU.addRequired<DominatorTreeWrapperPass>();
582 AU.addPreserved<DominatorTreeWrapperPass>();
583 }
584
585 static char ID;
586};
587}
588
589char LoopLoadElimination::ID;
590static const char LLE_name[] = "Loop Load Elimination";
591
592INITIALIZE_PASS_BEGIN(LoopLoadElimination, LLE_OPTION, LLE_name, false, false)
593INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Xinliang David Li7853c1d2016-07-08 20:55:26 +0000594INITIALIZE_PASS_DEPENDENCY(LoopAccessLegacyAnalysis)
Adam Nemete54a4fa2015-11-03 23:50:08 +0000595INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
596INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
Adam Nemetefb23412016-03-10 23:54:39 +0000597INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
Adam Nemete54a4fa2015-11-03 23:50:08 +0000598INITIALIZE_PASS_END(LoopLoadElimination, LLE_OPTION, LLE_name, false, false)
599
600namespace llvm {
601FunctionPass *createLoopLoadEliminationPass() {
602 return new LoopLoadElimination();
603}
604}