blob: 46b81355c074420ba65c07e4cb995718e2ad1e2e [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
Chandler Carruthbaabda92017-01-27 01:32:26 +000023#include "llvm/Transforms/Scalar/LoopLoadElimination.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000024#include "llvm/ADT/APInt.h"
25#include "llvm/ADT/DenseMap.h"
26#include "llvm/ADT/DepthFirstIterator.h"
Chandler Carruthbaabda92017-01-27 01:32:26 +000027#include "llvm/ADT/STLExtras.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000028#include "llvm/ADT/SmallSet.h"
29#include "llvm/ADT/SmallVector.h"
Adam Nemete54a4fa2015-11-03 23:50:08 +000030#include "llvm/ADT/Statistic.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000031#include "llvm/Analysis/AliasAnalysis.h"
32#include "llvm/Analysis/AssumptionCache.h"
Eli Friedman02d48be2016-09-16 17:58:07 +000033#include "llvm/Analysis/GlobalsModRef.h"
Adam Nemete54a4fa2015-11-03 23:50:08 +000034#include "llvm/Analysis/LoopAccessAnalysis.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000035#include "llvm/Analysis/LoopAnalysisManager.h"
Adam Nemete54a4fa2015-11-03 23:50:08 +000036#include "llvm/Analysis/LoopInfo.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000037#include "llvm/Analysis/ScalarEvolution.h"
Adam Nemete54a4fa2015-11-03 23:50:08 +000038#include "llvm/Analysis/ScalarEvolutionExpander.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000039#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000040#include "llvm/Analysis/TargetLibraryInfo.h"
41#include "llvm/Analysis/TargetTransformInfo.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000042#include "llvm/IR/DataLayout.h"
Adam Nemete54a4fa2015-11-03 23:50:08 +000043#include "llvm/IR/Dominators.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000044#include "llvm/IR/Instructions.h"
Adam Nemete54a4fa2015-11-03 23:50:08 +000045#include "llvm/IR/Module.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000046#include "llvm/IR/PassManager.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000047#include "llvm/IR/Type.h"
48#include "llvm/IR/Value.h"
Adam Nemete54a4fa2015-11-03 23:50:08 +000049#include "llvm/Pass.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000050#include "llvm/Support/Casting.h"
51#include "llvm/Support/CommandLine.h"
Adam Nemete54a4fa2015-11-03 23:50:08 +000052#include "llvm/Support/Debug.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000053#include "llvm/Support/raw_ostream.h"
Adam Nemetefb23412016-03-10 23:54:39 +000054#include "llvm/Transforms/Scalar.h"
David Blaikiea373d182018-03-28 17:44:36 +000055#include "llvm/Transforms/Utils.h"
Adam Nemete54a4fa2015-11-03 23:50:08 +000056#include "llvm/Transforms/Utils/LoopVersioning.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000057#include <algorithm>
Chandler Carruthbaabda92017-01-27 01:32:26 +000058#include <cassert>
59#include <forward_list>
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000060#include <set>
61#include <tuple>
62#include <utility>
Adam Nemete54a4fa2015-11-03 23:50:08 +000063
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000064using namespace llvm;
65
Adam Nemete54a4fa2015-11-03 23:50:08 +000066#define LLE_OPTION "loop-load-elim"
67#define DEBUG_TYPE LLE_OPTION
68
Adam Nemete54a4fa2015-11-03 23:50:08 +000069static 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
Silviu Baranga2910a4f2015-11-09 13:26:09 +000074static cl::opt<unsigned> LoadElimSCEVCheckThreshold(
75 "loop-load-elimination-scev-check-threshold", cl::init(8), cl::Hidden,
76 cl::desc("The maximum number of SCEV checks allowed for Loop "
77 "Load Elimination"));
78
Adam Nemete54a4fa2015-11-03 23:50:08 +000079STATISTIC(NumLoopLoadEliminted, "Number of loads eliminated by LLE");
80
81namespace {
82
83/// \brief Represent a store-to-forwarding candidate.
84struct StoreToLoadForwardingCandidate {
85 LoadInst *Load;
86 StoreInst *Store;
87
88 StoreToLoadForwardingCandidate(LoadInst *Load, StoreInst *Store)
89 : Load(Load), Store(Store) {}
90
91 /// \brief Return true if the dependence from the store to the load has a
92 /// distance of one. E.g. A[i+1] = A[i]
Adam Nemet660748c2016-03-09 20:47:55 +000093 bool isDependenceDistanceOfOne(PredicatedScalarEvolution &PSE,
94 Loop *L) const {
Adam Nemete54a4fa2015-11-03 23:50:08 +000095 Value *LoadPtr = Load->getPointerOperand();
96 Value *StorePtr = Store->getPointerOperand();
97 Type *LoadPtrType = LoadPtr->getType();
Adam Nemete54a4fa2015-11-03 23:50:08 +000098 Type *LoadType = LoadPtrType->getPointerElementType();
99
100 assert(LoadPtrType->getPointerAddressSpace() ==
Adam Nemet7c94c9b2015-11-04 00:10:33 +0000101 StorePtr->getType()->getPointerAddressSpace() &&
102 LoadType == StorePtr->getType()->getPointerElementType() &&
Adam Nemete54a4fa2015-11-03 23:50:08 +0000103 "Should be a known dependence");
104
Adam Nemet660748c2016-03-09 20:47:55 +0000105 // Currently we only support accesses with unit stride. FIXME: we should be
106 // able to handle non unit stirde as well as long as the stride is equal to
107 // the dependence distance.
Denis Zobnin15d1e642016-05-10 05:55:16 +0000108 if (getPtrStride(PSE, LoadPtr, L) != 1 ||
109 getPtrStride(PSE, StorePtr, L) != 1)
Adam Nemet660748c2016-03-09 20:47:55 +0000110 return false;
111
Adam Nemete54a4fa2015-11-03 23:50:08 +0000112 auto &DL = Load->getParent()->getModule()->getDataLayout();
113 unsigned TypeByteSize = DL.getTypeAllocSize(const_cast<Type *>(LoadType));
114
Silviu Baranga86de80d2015-12-10 11:07:18 +0000115 auto *LoadPtrSCEV = cast<SCEVAddRecExpr>(PSE.getSCEV(LoadPtr));
116 auto *StorePtrSCEV = cast<SCEVAddRecExpr>(PSE.getSCEV(StorePtr));
Adam Nemete54a4fa2015-11-03 23:50:08 +0000117
118 // We don't need to check non-wrapping here because forward/backward
119 // dependence wouldn't be valid if these weren't monotonic accesses.
Silviu Baranga86de80d2015-12-10 11:07:18 +0000120 auto *Dist = cast<SCEVConstant>(
121 PSE.getSE()->getMinusSCEV(StorePtrSCEV, LoadPtrSCEV));
Sanjoy Das0de2fec2015-12-17 20:28:46 +0000122 const APInt &Val = Dist->getAPInt();
Adam Nemet660748c2016-03-09 20:47:55 +0000123 return Val == TypeByteSize;
Adam Nemete54a4fa2015-11-03 23:50:08 +0000124 }
125
126 Value *getLoadPtr() const { return Load->getPointerOperand(); }
127
128#ifndef NDEBUG
129 friend raw_ostream &operator<<(raw_ostream &OS,
130 const StoreToLoadForwardingCandidate &Cand) {
131 OS << *Cand.Store << " -->\n";
132 OS.indent(2) << *Cand.Load << "\n";
133 return OS;
134 }
135#endif
136};
137
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000138} // end anonymous namespace
139
Adam Nemete54a4fa2015-11-03 23:50:08 +0000140/// \brief Check if the store dominates all latches, so as long as there is no
141/// intervening store this value will be loaded in the next iteration.
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000142static bool doesStoreDominatesAllLatches(BasicBlock *StoreBlock, Loop *L,
143 DominatorTree *DT) {
Adam Nemete54a4fa2015-11-03 23:50:08 +0000144 SmallVector<BasicBlock *, 8> Latches;
145 L->getLoopLatches(Latches);
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +0000146 return llvm::all_of(Latches, [&](const BasicBlock *Latch) {
David Majnemer0a16c222016-08-11 21:15:00 +0000147 return DT->dominates(StoreBlock, Latch);
148 });
Adam Nemete54a4fa2015-11-03 23:50:08 +0000149}
150
Adam Nemetbd861ac2016-06-28 04:02:47 +0000151/// \brief Return true if the load is not executed on all paths in the loop.
152static bool isLoadConditional(LoadInst *Load, Loop *L) {
153 return Load->getParent() != L->getHeader();
154}
155
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000156namespace {
157
Adam Nemete54a4fa2015-11-03 23:50:08 +0000158/// \brief The per-loop class that does most of the work.
159class LoadEliminationForLoop {
160public:
161 LoadEliminationForLoop(Loop *L, LoopInfo *LI, const LoopAccessInfo &LAI,
Silviu Baranga86de80d2015-12-10 11:07:18 +0000162 DominatorTree *DT)
Xinliang David Li94734ee2016-07-01 05:59:55 +0000163 : L(L), LI(LI), LAI(LAI), DT(DT), PSE(LAI.getPSE()) {}
Adam Nemete54a4fa2015-11-03 23:50:08 +0000164
165 /// \brief Look through the loop-carried and loop-independent dependences in
166 /// this loop and find store->load dependences.
167 ///
168 /// Note that no candidate is returned if LAA has failed to analyze the loop
169 /// (e.g. if it's not bottom-tested, contains volatile memops, etc.)
170 std::forward_list<StoreToLoadForwardingCandidate>
171 findStoreToLoadDependences(const LoopAccessInfo &LAI) {
172 std::forward_list<StoreToLoadForwardingCandidate> Candidates;
173
174 const auto *Deps = LAI.getDepChecker().getDependences();
175 if (!Deps)
176 return Candidates;
177
178 // Find store->load dependences (consequently true dep). Both lexically
179 // forward and backward dependences qualify. Disqualify loads that have
180 // other unknown dependences.
181
182 SmallSet<Instruction *, 4> LoadsWithUnknownDepedence;
183
184 for (const auto &Dep : *Deps) {
185 Instruction *Source = Dep.getSource(LAI);
186 Instruction *Destination = Dep.getDestination(LAI);
187
188 if (Dep.Type == MemoryDepChecker::Dependence::Unknown) {
189 if (isa<LoadInst>(Source))
190 LoadsWithUnknownDepedence.insert(Source);
191 if (isa<LoadInst>(Destination))
192 LoadsWithUnknownDepedence.insert(Destination);
193 continue;
194 }
195
196 if (Dep.isBackward())
197 // Note that the designations source and destination follow the program
198 // order, i.e. source is always first. (The direction is given by the
199 // DepType.)
200 std::swap(Source, Destination);
201 else
202 assert(Dep.isForward() && "Needs to be a forward dependence");
203
204 auto *Store = dyn_cast<StoreInst>(Source);
205 if (!Store)
206 continue;
207 auto *Load = dyn_cast<LoadInst>(Destination);
208 if (!Load)
209 continue;
Adam Nemet7aba60c2016-03-24 17:59:26 +0000210
211 // Only progagate the value if they are of the same type.
Sanjoy Dasf09c1e32017-04-18 22:00:54 +0000212 if (Store->getPointerOperandType() != Load->getPointerOperandType())
Adam Nemet7aba60c2016-03-24 17:59:26 +0000213 continue;
214
Adam Nemete54a4fa2015-11-03 23:50:08 +0000215 Candidates.emplace_front(Load, Store);
216 }
217
218 if (!LoadsWithUnknownDepedence.empty())
219 Candidates.remove_if([&](const StoreToLoadForwardingCandidate &C) {
220 return LoadsWithUnknownDepedence.count(C.Load);
221 });
222
223 return Candidates;
224 }
225
226 /// \brief Return the index of the instruction according to program order.
227 unsigned getInstrIndex(Instruction *Inst) {
228 auto I = InstOrder.find(Inst);
229 assert(I != InstOrder.end() && "No index for instruction");
230 return I->second;
231 }
232
233 /// \brief If a load has multiple candidates associated (i.e. different
234 /// stores), it means that it could be forwarding from multiple stores
235 /// depending on control flow. Remove these candidates.
236 ///
237 /// Here, we rely on LAA to include the relevant loop-independent dependences.
238 /// LAA is known to omit these in the very simple case when the read and the
239 /// write within an alias set always takes place using the *same* pointer.
240 ///
241 /// However, we know that this is not the case here, i.e. we can rely on LAA
242 /// to provide us with loop-independent dependences for the cases we're
243 /// interested. Consider the case for example where a loop-independent
244 /// dependece S1->S2 invalidates the forwarding S3->S2.
245 ///
246 /// A[i] = ... (S1)
247 /// ... = A[i] (S2)
248 /// A[i+1] = ... (S3)
249 ///
250 /// LAA will perform dependence analysis here because there are two
251 /// *different* pointers involved in the same alias set (&A[i] and &A[i+1]).
252 void removeDependencesFromMultipleStores(
253 std::forward_list<StoreToLoadForwardingCandidate> &Candidates) {
254 // If Store is nullptr it means that we have multiple stores forwarding to
255 // this store.
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000256 using LoadToSingleCandT =
257 DenseMap<LoadInst *, const StoreToLoadForwardingCandidate *>;
Adam Nemete54a4fa2015-11-03 23:50:08 +0000258 LoadToSingleCandT LoadToSingleCand;
259
260 for (const auto &Cand : Candidates) {
261 bool NewElt;
262 LoadToSingleCandT::iterator Iter;
263
264 std::tie(Iter, NewElt) =
265 LoadToSingleCand.insert(std::make_pair(Cand.Load, &Cand));
266 if (!NewElt) {
267 const StoreToLoadForwardingCandidate *&OtherCand = Iter->second;
268 // Already multiple stores forward to this load.
269 if (OtherCand == nullptr)
270 continue;
271
Adam Nemetefc091f2016-02-29 23:21:12 +0000272 // Handle the very basic case when the two stores are in the same block
273 // so deciding which one forwards is easy. The later one forwards as
274 // long as they both have a dependence distance of one to the load.
Adam Nemete54a4fa2015-11-03 23:50:08 +0000275 if (Cand.Store->getParent() == OtherCand->Store->getParent() &&
Adam Nemet660748c2016-03-09 20:47:55 +0000276 Cand.isDependenceDistanceOfOne(PSE, L) &&
277 OtherCand->isDependenceDistanceOfOne(PSE, L)) {
Adam Nemete54a4fa2015-11-03 23:50:08 +0000278 // They are in the same block, the later one will forward to the load.
279 if (getInstrIndex(OtherCand->Store) < getInstrIndex(Cand.Store))
280 OtherCand = &Cand;
281 } else
282 OtherCand = nullptr;
283 }
284 }
285
286 Candidates.remove_if([&](const StoreToLoadForwardingCandidate &Cand) {
287 if (LoadToSingleCand[Cand.Load] != &Cand) {
288 DEBUG(dbgs() << "Removing from candidates: \n" << Cand
289 << " The load may have multiple stores forwarding to "
290 << "it\n");
291 return true;
292 }
293 return false;
294 });
295 }
296
297 /// \brief Given two pointers operations by their RuntimePointerChecking
298 /// indices, return true if they require an alias check.
299 ///
300 /// We need a check if one is a pointer for a candidate load and the other is
301 /// a pointer for a possibly intervening store.
302 bool needsChecking(unsigned PtrIdx1, unsigned PtrIdx2,
303 const SmallSet<Value *, 4> &PtrsWrittenOnFwdingPath,
304 const std::set<Value *> &CandLoadPtrs) {
305 Value *Ptr1 =
306 LAI.getRuntimePointerChecking()->getPointerInfo(PtrIdx1).PointerValue;
307 Value *Ptr2 =
308 LAI.getRuntimePointerChecking()->getPointerInfo(PtrIdx2).PointerValue;
309 return ((PtrsWrittenOnFwdingPath.count(Ptr1) && CandLoadPtrs.count(Ptr2)) ||
310 (PtrsWrittenOnFwdingPath.count(Ptr2) && CandLoadPtrs.count(Ptr1)));
311 }
312
313 /// \brief Return pointers that are possibly written to on the path from a
314 /// forwarding store to a load.
315 ///
316 /// These pointers need to be alias-checked against the forwarding candidates.
317 SmallSet<Value *, 4> findPointersWrittenOnForwardingPath(
318 const SmallVectorImpl<StoreToLoadForwardingCandidate> &Candidates) {
319 // From FirstStore to LastLoad neither of the elimination candidate loads
320 // should overlap with any of the stores.
321 //
322 // E.g.:
323 //
324 // st1 C[i]
325 // ld1 B[i] <-------,
326 // ld0 A[i] <----, | * LastLoad
327 // ... | |
328 // st2 E[i] | |
329 // st3 B[i+1] -- | -' * FirstStore
330 // st0 A[i+1] ---'
331 // st4 D[i]
332 //
333 // st0 forwards to ld0 if the accesses in st4 and st1 don't overlap with
334 // ld0.
335
336 LoadInst *LastLoad =
337 std::max_element(Candidates.begin(), Candidates.end(),
338 [&](const StoreToLoadForwardingCandidate &A,
339 const StoreToLoadForwardingCandidate &B) {
340 return getInstrIndex(A.Load) < getInstrIndex(B.Load);
341 })
342 ->Load;
343 StoreInst *FirstStore =
344 std::min_element(Candidates.begin(), Candidates.end(),
345 [&](const StoreToLoadForwardingCandidate &A,
346 const StoreToLoadForwardingCandidate &B) {
347 return getInstrIndex(A.Store) <
348 getInstrIndex(B.Store);
349 })
350 ->Store;
351
352 // We're looking for stores after the first forwarding store until the end
353 // of the loop, then from the beginning of the loop until the last
354 // forwarded-to load. Collect the pointer for the stores.
355 SmallSet<Value *, 4> PtrsWrittenOnFwdingPath;
356
357 auto InsertStorePtr = [&](Instruction *I) {
358 if (auto *S = dyn_cast<StoreInst>(I))
359 PtrsWrittenOnFwdingPath.insert(S->getPointerOperand());
360 };
361 const auto &MemInstrs = LAI.getDepChecker().getMemoryInstructions();
362 std::for_each(MemInstrs.begin() + getInstrIndex(FirstStore) + 1,
363 MemInstrs.end(), InsertStorePtr);
364 std::for_each(MemInstrs.begin(), &MemInstrs[getInstrIndex(LastLoad)],
365 InsertStorePtr);
366
367 return PtrsWrittenOnFwdingPath;
368 }
369
370 /// \brief Determine the pointer alias checks to prove that there are no
371 /// intervening stores.
372 SmallVector<RuntimePointerChecking::PointerCheck, 4> collectMemchecks(
373 const SmallVectorImpl<StoreToLoadForwardingCandidate> &Candidates) {
374
375 SmallSet<Value *, 4> PtrsWrittenOnFwdingPath =
376 findPointersWrittenOnForwardingPath(Candidates);
377
378 // Collect the pointers of the candidate loads.
379 // FIXME: SmallSet does not work with std::inserter.
380 std::set<Value *> CandLoadPtrs;
David Majnemer2d006e72016-08-12 04:32:42 +0000381 transform(Candidates,
Adam Nemete54a4fa2015-11-03 23:50:08 +0000382 std::inserter(CandLoadPtrs, CandLoadPtrs.begin()),
383 std::mem_fn(&StoreToLoadForwardingCandidate::getLoadPtr));
384
385 const auto &AllChecks = LAI.getRuntimePointerChecking()->getChecks();
386 SmallVector<RuntimePointerChecking::PointerCheck, 4> Checks;
387
Sanjoy Das90208722017-02-21 00:38:44 +0000388 copy_if(AllChecks, std::back_inserter(Checks),
389 [&](const RuntimePointerChecking::PointerCheck &Check) {
390 for (auto PtrIdx1 : Check.first->Members)
391 for (auto PtrIdx2 : Check.second->Members)
392 if (needsChecking(PtrIdx1, PtrIdx2, PtrsWrittenOnFwdingPath,
393 CandLoadPtrs))
394 return true;
395 return false;
396 });
Adam Nemete54a4fa2015-11-03 23:50:08 +0000397
398 DEBUG(dbgs() << "\nPointer Checks (count: " << Checks.size() << "):\n");
399 DEBUG(LAI.getRuntimePointerChecking()->printChecks(dbgs(), Checks));
400
401 return Checks;
402 }
403
404 /// \brief Perform the transformation for a candidate.
405 void
406 propagateStoredValueToLoadUsers(const StoreToLoadForwardingCandidate &Cand,
407 SCEVExpander &SEE) {
Adam Nemete54a4fa2015-11-03 23:50:08 +0000408 // loop:
409 // %x = load %gep_i
410 // = ... %x
411 // store %y, %gep_i_plus_1
412 //
413 // =>
414 //
415 // ph:
416 // %x.initial = load %gep_0
417 // loop:
418 // %x.storeforward = phi [%x.initial, %ph] [%y, %loop]
419 // %x = load %gep_i <---- now dead
420 // = ... %x.storeforward
421 // store %y, %gep_i_plus_1
422
423 Value *Ptr = Cand.Load->getPointerOperand();
Silviu Baranga86de80d2015-12-10 11:07:18 +0000424 auto *PtrSCEV = cast<SCEVAddRecExpr>(PSE.getSCEV(Ptr));
Adam Nemete54a4fa2015-11-03 23:50:08 +0000425 auto *PH = L->getLoopPreheader();
426 Value *InitialPtr = SEE.expandCodeFor(PtrSCEV->getStart(), Ptr->getType(),
427 PH->getTerminator());
428 Value *Initial =
Mehdi Amini27d224f2017-01-06 21:06:51 +0000429 new LoadInst(InitialPtr, "load_initial", /* isVolatile */ false,
430 Cand.Load->getAlignment(), PH->getTerminator());
431
Adam Nemete54a4fa2015-11-03 23:50:08 +0000432 PHINode *PHI = PHINode::Create(Initial->getType(), 2, "store_forwarded",
Duncan P. N. Exon Smith83c4b682015-11-07 00:01:16 +0000433 &L->getHeader()->front());
Adam Nemete54a4fa2015-11-03 23:50:08 +0000434 PHI->addIncoming(Initial, PH);
435 PHI->addIncoming(Cand.Store->getOperand(0), L->getLoopLatch());
436
437 Cand.Load->replaceAllUsesWith(PHI);
438 }
439
440 /// \brief Top-level driver for each loop: find store->load forwarding
441 /// candidates, add run-time checks and perform transformation.
442 bool processLoop() {
443 DEBUG(dbgs() << "\nIn \"" << L->getHeader()->getParent()->getName()
444 << "\" checking " << *L << "\n");
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000445
Adam Nemete54a4fa2015-11-03 23:50:08 +0000446 // Look for store-to-load forwarding cases across the
447 // backedge. E.g.:
448 //
449 // loop:
450 // %x = load %gep_i
451 // = ... %x
452 // store %y, %gep_i_plus_1
453 //
454 // =>
455 //
456 // ph:
457 // %x.initial = load %gep_0
458 // loop:
459 // %x.storeforward = phi [%x.initial, %ph] [%y, %loop]
460 // %x = load %gep_i <---- now dead
461 // = ... %x.storeforward
462 // store %y, %gep_i_plus_1
463
464 // First start with store->load dependences.
465 auto StoreToLoadDependences = findStoreToLoadDependences(LAI);
466 if (StoreToLoadDependences.empty())
467 return false;
468
469 // Generate an index for each load and store according to the original
470 // program order. This will be used later.
471 InstOrder = LAI.getDepChecker().generateInstructionOrderMap();
472
473 // To keep things simple for now, remove those where the load is potentially
474 // fed by multiple stores.
475 removeDependencesFromMultipleStores(StoreToLoadDependences);
476 if (StoreToLoadDependences.empty())
477 return false;
478
479 // Filter the candidates further.
480 SmallVector<StoreToLoadForwardingCandidate, 4> Candidates;
481 unsigned NumForwarding = 0;
482 for (const StoreToLoadForwardingCandidate Cand : StoreToLoadDependences) {
483 DEBUG(dbgs() << "Candidate " << Cand);
Adam Nemet83be06e2016-02-29 22:53:59 +0000484
Adam Nemete54a4fa2015-11-03 23:50:08 +0000485 // Make sure that the stored values is available everywhere in the loop in
486 // the next iteration.
487 if (!doesStoreDominatesAllLatches(Cand.Store->getParent(), L, DT))
488 continue;
489
Adam Nemetbd861ac2016-06-28 04:02:47 +0000490 // If the load is conditional we can't hoist its 0-iteration instance to
491 // the preheader because that would make it unconditional. Thus we would
492 // access a memory location that the original loop did not access.
493 if (isLoadConditional(Cand.Load, L))
494 continue;
495
Adam Nemete54a4fa2015-11-03 23:50:08 +0000496 // Check whether the SCEV difference is the same as the induction step,
497 // thus we load the value in the next iteration.
Adam Nemet660748c2016-03-09 20:47:55 +0000498 if (!Cand.isDependenceDistanceOfOne(PSE, L))
Adam Nemete54a4fa2015-11-03 23:50:08 +0000499 continue;
500
501 ++NumForwarding;
502 DEBUG(dbgs()
503 << NumForwarding
504 << ". Valid store-to-load forwarding across the loop backedge\n");
505 Candidates.push_back(Cand);
506 }
507 if (Candidates.empty())
508 return false;
509
510 // Check intervening may-alias stores. These need runtime checks for alias
511 // disambiguation.
512 SmallVector<RuntimePointerChecking::PointerCheck, 4> Checks =
513 collectMemchecks(Candidates);
514
515 // Too many checks are likely to outweigh the benefits of forwarding.
516 if (Checks.size() > Candidates.size() * CheckPerElim) {
517 DEBUG(dbgs() << "Too many run-time checks needed.\n");
518 return false;
519 }
520
Xinliang David Li94734ee2016-07-01 05:59:55 +0000521 if (LAI.getPSE().getUnionPredicate().getComplexity() >
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +0000522 LoadElimSCEVCheckThreshold) {
Silviu Baranga2910a4f2015-11-09 13:26:09 +0000523 DEBUG(dbgs() << "Too many SCEV run-time checks needed.\n");
524 return false;
525 }
526
Xinliang David Li94734ee2016-07-01 05:59:55 +0000527 if (!Checks.empty() || !LAI.getPSE().getUnionPredicate().isAlwaysTrue()) {
Adam Nemet9455c1d2016-02-05 01:14:05 +0000528 if (L->getHeader()->getParent()->optForSize()) {
529 DEBUG(dbgs() << "Versioning is needed but not allowed when optimizing "
530 "for size.\n");
531 return false;
532 }
533
Florian Hahn2e032132016-12-19 17:13:37 +0000534 if (!L->isLoopSimplifyForm()) {
535 DEBUG(dbgs() << "Loop is not is loop-simplify form");
536 return false;
537 }
538
Adam Nemet9455c1d2016-02-05 01:14:05 +0000539 // Point of no-return, start the transformation. First, version the loop
540 // if necessary.
541
Silviu Baranga86de80d2015-12-10 11:07:18 +0000542 LoopVersioning LV(LAI, L, LI, DT, PSE.getSE(), false);
Silviu Baranga2910a4f2015-11-09 13:26:09 +0000543 LV.setAliasChecks(std::move(Checks));
Xinliang David Li94734ee2016-07-01 05:59:55 +0000544 LV.setSCEVChecks(LAI.getPSE().getUnionPredicate());
Adam Nemete54a4fa2015-11-03 23:50:08 +0000545 LV.versionLoop();
546 }
547
548 // Next, propagate the value stored by the store to the users of the load.
549 // Also for the first iteration, generate the initial value of the load.
Silviu Baranga86de80d2015-12-10 11:07:18 +0000550 SCEVExpander SEE(*PSE.getSE(), L->getHeader()->getModule()->getDataLayout(),
Adam Nemete54a4fa2015-11-03 23:50:08 +0000551 "storeforward");
552 for (const auto &Cand : Candidates)
553 propagateStoredValueToLoadUsers(Cand, SEE);
554 NumLoopLoadEliminted += NumForwarding;
555
556 return true;
557 }
558
559private:
560 Loop *L;
561
562 /// \brief Maps the load/store instructions to their index according to
563 /// program order.
564 DenseMap<Instruction *, unsigned> InstOrder;
565
566 // Analyses used.
567 LoopInfo *LI;
568 const LoopAccessInfo &LAI;
569 DominatorTree *DT;
Silviu Baranga86de80d2015-12-10 11:07:18 +0000570 PredicatedScalarEvolution PSE;
Adam Nemete54a4fa2015-11-03 23:50:08 +0000571};
572
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000573} // end anonymous namespace
574
Chandler Carruthbaabda92017-01-27 01:32:26 +0000575static bool
576eliminateLoadsAcrossLoops(Function &F, LoopInfo &LI, DominatorTree &DT,
577 function_ref<const LoopAccessInfo &(Loop &)> GetLAI) {
578 // Build up a worklist of inner-loops to transform to avoid iterator
579 // invalidation.
580 // FIXME: This logic comes from other passes that actually change the loop
581 // nest structure. It isn't clear this is necessary (or useful) for a pass
582 // which merely optimizes the use of loads in a loop.
583 SmallVector<Loop *, 8> Worklist;
584
585 for (Loop *TopLevelLoop : LI)
586 for (Loop *L : depth_first(TopLevelLoop))
587 // We only handle inner-most loops.
588 if (L->empty())
589 Worklist.push_back(L);
590
591 // Now walk the identified inner loops.
592 bool Changed = false;
593 for (Loop *L : Worklist) {
594 // The actual work is performed by LoadEliminationForLoop.
595 LoadEliminationForLoop LEL(L, &LI, GetLAI(*L), &DT);
596 Changed |= LEL.processLoop();
597 }
598 return Changed;
599}
600
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000601namespace {
602
Adam Nemete54a4fa2015-11-03 23:50:08 +0000603/// \brief The pass. Most of the work is delegated to the per-loop
604/// LoadEliminationForLoop class.
605class LoopLoadElimination : public FunctionPass {
606public:
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000607 static char ID;
608
Adam Nemete54a4fa2015-11-03 23:50:08 +0000609 LoopLoadElimination() : FunctionPass(ID) {
610 initializeLoopLoadEliminationPass(*PassRegistry::getPassRegistry());
611 }
612
613 bool runOnFunction(Function &F) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000614 if (skipFunction(F))
615 return false;
616
Chandler Carruthbaabda92017-01-27 01:32:26 +0000617 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
618 auto &LAA = getAnalysis<LoopAccessLegacyAnalysis>();
619 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Adam Nemete54a4fa2015-11-03 23:50:08 +0000620
621 // Process each loop nest in the function.
Chandler Carruthbaabda92017-01-27 01:32:26 +0000622 return eliminateLoadsAcrossLoops(
623 F, LI, DT,
624 [&LAA](Loop &L) -> const LoopAccessInfo & { return LAA.getInfo(&L); });
Adam Nemete54a4fa2015-11-03 23:50:08 +0000625 }
626
627 void getAnalysisUsage(AnalysisUsage &AU) const override {
Adam Nemetefb23412016-03-10 23:54:39 +0000628 AU.addRequiredID(LoopSimplifyID);
Adam Nemete54a4fa2015-11-03 23:50:08 +0000629 AU.addRequired<LoopInfoWrapperPass>();
630 AU.addPreserved<LoopInfoWrapperPass>();
Xinliang David Li7853c1d2016-07-08 20:55:26 +0000631 AU.addRequired<LoopAccessLegacyAnalysis>();
Adam Nemete54a4fa2015-11-03 23:50:08 +0000632 AU.addRequired<ScalarEvolutionWrapperPass>();
633 AU.addRequired<DominatorTreeWrapperPass>();
634 AU.addPreserved<DominatorTreeWrapperPass>();
Eli Friedman02d48be2016-09-16 17:58:07 +0000635 AU.addPreserved<GlobalsAAWrapperPass>();
Adam Nemete54a4fa2015-11-03 23:50:08 +0000636 }
Adam Nemete54a4fa2015-11-03 23:50:08 +0000637};
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +0000638
639} // end anonymous namespace
Adam Nemete54a4fa2015-11-03 23:50:08 +0000640
641char LoopLoadElimination::ID;
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000642
Adam Nemete54a4fa2015-11-03 23:50:08 +0000643static const char LLE_name[] = "Loop Load Elimination";
644
645INITIALIZE_PASS_BEGIN(LoopLoadElimination, LLE_OPTION, LLE_name, false, false)
646INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Xinliang David Li7853c1d2016-07-08 20:55:26 +0000647INITIALIZE_PASS_DEPENDENCY(LoopAccessLegacyAnalysis)
Adam Nemete54a4fa2015-11-03 23:50:08 +0000648INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
649INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
Adam Nemetefb23412016-03-10 23:54:39 +0000650INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
Adam Nemete54a4fa2015-11-03 23:50:08 +0000651INITIALIZE_PASS_END(LoopLoadElimination, LLE_OPTION, LLE_name, false, false)
652
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000653FunctionPass *llvm::createLoopLoadEliminationPass() {
Adam Nemete54a4fa2015-11-03 23:50:08 +0000654 return new LoopLoadElimination();
655}
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +0000656
Chandler Carruthbaabda92017-01-27 01:32:26 +0000657PreservedAnalyses LoopLoadEliminationPass::run(Function &F,
658 FunctionAnalysisManager &AM) {
659 auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
660 auto &LI = AM.getResult<LoopAnalysis>(F);
661 auto &TTI = AM.getResult<TargetIRAnalysis>(F);
662 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
663 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
664 auto &AA = AM.getResult<AAManager>(F);
665 auto &AC = AM.getResult<AssumptionAnalysis>(F);
666
667 auto &LAM = AM.getResult<LoopAnalysisManagerFunctionProxy>(F).getManager();
668 bool Changed = eliminateLoadsAcrossLoops(
669 F, LI, DT, [&](Loop &L) -> const LoopAccessInfo & {
Alina Sbirleaff8b8ae2017-11-21 15:45:46 +0000670 LoopStandardAnalysisResults AR = {AA, AC, DT, LI,
671 SE, TLI, TTI, nullptr};
Chandler Carruthbaabda92017-01-27 01:32:26 +0000672 return LAM.getResult<LoopAccessAnalysis>(L, AR);
673 });
674
675 if (!Changed)
676 return PreservedAnalyses::all();
677
678 PreservedAnalyses PA;
679 return PA;
680}