blob: f8fc76e4b8789ddb74271e6ae50e02c9e92e2a8c [file] [log] [blame]
Adam Nemete54a4fa2015-11-03 23:50:08 +00001//===- LoopLoadElimination.cpp - Loop Load Elimination Pass ---------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Adam Nemete54a4fa2015-11-03 23:50:08 +00006//
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
Chandler Carruthbaabda92017-01-27 01:32:26 +000022#include "llvm/Transforms/Scalar/LoopLoadElimination.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000023#include "llvm/ADT/APInt.h"
24#include "llvm/ADT/DenseMap.h"
25#include "llvm/ADT/DepthFirstIterator.h"
Chandler Carruthbaabda92017-01-27 01:32:26 +000026#include "llvm/ADT/STLExtras.h"
Florian Hahna1cc8482018-06-12 11:16:56 +000027#include "llvm/ADT/SmallPtrSet.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000028#include "llvm/ADT/SmallVector.h"
Adam Nemete54a4fa2015-11-03 23:50:08 +000029#include "llvm/ADT/Statistic.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000030#include "llvm/Analysis/AliasAnalysis.h"
31#include "llvm/Analysis/AssumptionCache.h"
Eli Friedman02d48be2016-09-16 17:58:07 +000032#include "llvm/Analysis/GlobalsModRef.h"
Adam Nemete54a4fa2015-11-03 23:50:08 +000033#include "llvm/Analysis/LoopAccessAnalysis.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000034#include "llvm/Analysis/LoopAnalysisManager.h"
Adam Nemete54a4fa2015-11-03 23:50:08 +000035#include "llvm/Analysis/LoopInfo.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000036#include "llvm/Analysis/ScalarEvolution.h"
Adam Nemete54a4fa2015-11-03 23:50:08 +000037#include "llvm/Analysis/ScalarEvolutionExpander.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000038#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000039#include "llvm/Analysis/TargetLibraryInfo.h"
40#include "llvm/Analysis/TargetTransformInfo.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000041#include "llvm/IR/DataLayout.h"
Adam Nemete54a4fa2015-11-03 23:50:08 +000042#include "llvm/IR/Dominators.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000043#include "llvm/IR/Instructions.h"
Adam Nemete54a4fa2015-11-03 23:50:08 +000044#include "llvm/IR/Module.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000045#include "llvm/IR/PassManager.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000046#include "llvm/IR/Type.h"
47#include "llvm/IR/Value.h"
Adam Nemete54a4fa2015-11-03 23:50:08 +000048#include "llvm/Pass.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000049#include "llvm/Support/Casting.h"
50#include "llvm/Support/CommandLine.h"
Adam Nemete54a4fa2015-11-03 23:50:08 +000051#include "llvm/Support/Debug.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000052#include "llvm/Support/raw_ostream.h"
Adam Nemetefb23412016-03-10 23:54:39 +000053#include "llvm/Transforms/Scalar.h"
David Blaikiea373d182018-03-28 17:44:36 +000054#include "llvm/Transforms/Utils.h"
Adam Nemete54a4fa2015-11-03 23:50:08 +000055#include "llvm/Transforms/Utils/LoopVersioning.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000056#include <algorithm>
Chandler Carruthbaabda92017-01-27 01:32:26 +000057#include <cassert>
58#include <forward_list>
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000059#include <set>
60#include <tuple>
61#include <utility>
Adam Nemete54a4fa2015-11-03 23:50:08 +000062
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000063using namespace llvm;
64
Adam Nemete54a4fa2015-11-03 23:50:08 +000065#define LLE_OPTION "loop-load-elim"
66#define DEBUG_TYPE LLE_OPTION
67
Adam Nemete54a4fa2015-11-03 23:50:08 +000068static 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(1));
72
Silviu Baranga2910a4f2015-11-09 13:26:09 +000073static cl::opt<unsigned> LoadElimSCEVCheckThreshold(
74 "loop-load-elimination-scev-check-threshold", cl::init(8), cl::Hidden,
75 cl::desc("The maximum number of SCEV checks allowed for Loop "
76 "Load Elimination"));
77
Adam Nemete54a4fa2015-11-03 23:50:08 +000078STATISTIC(NumLoopLoadEliminted, "Number of loads eliminated by LLE");
79
80namespace {
81
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000082/// Represent a store-to-forwarding candidate.
Adam Nemete54a4fa2015-11-03 23:50:08 +000083struct StoreToLoadForwardingCandidate {
84 LoadInst *Load;
85 StoreInst *Store;
86
87 StoreToLoadForwardingCandidate(LoadInst *Load, StoreInst *Store)
88 : Load(Load), Store(Store) {}
89
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000090 /// Return true if the dependence from the store to the load has a
Adam Nemete54a4fa2015-11-03 23:50:08 +000091 /// distance of one. E.g. A[i+1] = A[i]
Adam Nemet660748c2016-03-09 20:47:55 +000092 bool isDependenceDistanceOfOne(PredicatedScalarEvolution &PSE,
93 Loop *L) const {
Adam Nemete54a4fa2015-11-03 23:50:08 +000094 Value *LoadPtr = Load->getPointerOperand();
95 Value *StorePtr = Store->getPointerOperand();
96 Type *LoadPtrType = LoadPtr->getType();
Adam Nemete54a4fa2015-11-03 23:50:08 +000097 Type *LoadType = LoadPtrType->getPointerElementType();
98
99 assert(LoadPtrType->getPointerAddressSpace() ==
Adam Nemet7c94c9b2015-11-04 00:10:33 +0000100 StorePtr->getType()->getPointerAddressSpace() &&
101 LoadType == StorePtr->getType()->getPointerElementType() &&
Adam Nemete54a4fa2015-11-03 23:50:08 +0000102 "Should be a known dependence");
103
Adam Nemet660748c2016-03-09 20:47:55 +0000104 // Currently we only support accesses with unit stride. FIXME: we should be
105 // able to handle non unit stirde as well as long as the stride is equal to
106 // the dependence distance.
Denis Zobnin15d1e642016-05-10 05:55:16 +0000107 if (getPtrStride(PSE, LoadPtr, L) != 1 ||
108 getPtrStride(PSE, StorePtr, L) != 1)
Adam Nemet660748c2016-03-09 20:47:55 +0000109 return false;
110
Adam Nemete54a4fa2015-11-03 23:50:08 +0000111 auto &DL = Load->getParent()->getModule()->getDataLayout();
112 unsigned TypeByteSize = DL.getTypeAllocSize(const_cast<Type *>(LoadType));
113
Silviu Baranga86de80d2015-12-10 11:07:18 +0000114 auto *LoadPtrSCEV = cast<SCEVAddRecExpr>(PSE.getSCEV(LoadPtr));
115 auto *StorePtrSCEV = cast<SCEVAddRecExpr>(PSE.getSCEV(StorePtr));
Adam Nemete54a4fa2015-11-03 23:50:08 +0000116
117 // We don't need to check non-wrapping here because forward/backward
118 // dependence wouldn't be valid if these weren't monotonic accesses.
Silviu Baranga86de80d2015-12-10 11:07:18 +0000119 auto *Dist = cast<SCEVConstant>(
120 PSE.getSE()->getMinusSCEV(StorePtrSCEV, LoadPtrSCEV));
Sanjoy Das0de2fec2015-12-17 20:28:46 +0000121 const APInt &Val = Dist->getAPInt();
Adam Nemet660748c2016-03-09 20:47:55 +0000122 return Val == TypeByteSize;
Adam Nemete54a4fa2015-11-03 23:50:08 +0000123 }
124
125 Value *getLoadPtr() const { return Load->getPointerOperand(); }
126
127#ifndef NDEBUG
128 friend raw_ostream &operator<<(raw_ostream &OS,
129 const StoreToLoadForwardingCandidate &Cand) {
130 OS << *Cand.Store << " -->\n";
131 OS.indent(2) << *Cand.Load << "\n";
132 return OS;
133 }
134#endif
135};
136
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000137} // end anonymous namespace
138
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000139/// Check if the store dominates all latches, so as long as there is no
Adam Nemete54a4fa2015-11-03 23:50:08 +0000140/// intervening store this value will be loaded in the next iteration.
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000141static bool doesStoreDominatesAllLatches(BasicBlock *StoreBlock, Loop *L,
142 DominatorTree *DT) {
Adam Nemete54a4fa2015-11-03 23:50:08 +0000143 SmallVector<BasicBlock *, 8> Latches;
144 L->getLoopLatches(Latches);
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +0000145 return llvm::all_of(Latches, [&](const BasicBlock *Latch) {
David Majnemer0a16c222016-08-11 21:15:00 +0000146 return DT->dominates(StoreBlock, Latch);
147 });
Adam Nemete54a4fa2015-11-03 23:50:08 +0000148}
149
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000150/// Return true if the load is not executed on all paths in the loop.
Adam Nemetbd861ac2016-06-28 04:02:47 +0000151static bool isLoadConditional(LoadInst *Load, Loop *L) {
152 return Load->getParent() != L->getHeader();
153}
154
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000155namespace {
156
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000157/// The per-loop class that does most of the work.
Adam Nemete54a4fa2015-11-03 23:50:08 +0000158class LoadEliminationForLoop {
159public:
160 LoadEliminationForLoop(Loop *L, LoopInfo *LI, const LoopAccessInfo &LAI,
Silviu Baranga86de80d2015-12-10 11:07:18 +0000161 DominatorTree *DT)
Xinliang David Li94734ee2016-07-01 05:59:55 +0000162 : L(L), LI(LI), LAI(LAI), DT(DT), PSE(LAI.getPSE()) {}
Adam Nemete54a4fa2015-11-03 23:50:08 +0000163
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000164 /// Look through the loop-carried and loop-independent dependences in
Adam Nemete54a4fa2015-11-03 23:50:08 +0000165 /// this loop and find store->load dependences.
166 ///
167 /// Note that no candidate is returned if LAA has failed to analyze the loop
168 /// (e.g. if it's not bottom-tested, contains volatile memops, etc.)
169 std::forward_list<StoreToLoadForwardingCandidate>
170 findStoreToLoadDependences(const LoopAccessInfo &LAI) {
171 std::forward_list<StoreToLoadForwardingCandidate> Candidates;
172
173 const auto *Deps = LAI.getDepChecker().getDependences();
174 if (!Deps)
175 return Candidates;
176
177 // Find store->load dependences (consequently true dep). Both lexically
178 // forward and backward dependences qualify. Disqualify loads that have
179 // other unknown dependences.
180
Florian Hahna1cc8482018-06-12 11:16:56 +0000181 SmallPtrSet<Instruction *, 4> LoadsWithUnknownDepedence;
Adam Nemete54a4fa2015-11-03 23:50:08 +0000182
183 for (const auto &Dep : *Deps) {
184 Instruction *Source = Dep.getSource(LAI);
185 Instruction *Destination = Dep.getDestination(LAI);
186
187 if (Dep.Type == MemoryDepChecker::Dependence::Unknown) {
188 if (isa<LoadInst>(Source))
189 LoadsWithUnknownDepedence.insert(Source);
190 if (isa<LoadInst>(Destination))
191 LoadsWithUnknownDepedence.insert(Destination);
192 continue;
193 }
194
195 if (Dep.isBackward())
196 // Note that the designations source and destination follow the program
197 // order, i.e. source is always first. (The direction is given by the
198 // DepType.)
199 std::swap(Source, Destination);
200 else
201 assert(Dep.isForward() && "Needs to be a forward dependence");
202
203 auto *Store = dyn_cast<StoreInst>(Source);
204 if (!Store)
205 continue;
206 auto *Load = dyn_cast<LoadInst>(Destination);
207 if (!Load)
208 continue;
Adam Nemet7aba60c2016-03-24 17:59:26 +0000209
210 // Only progagate the value if they are of the same type.
Sanjoy Dasf09c1e32017-04-18 22:00:54 +0000211 if (Store->getPointerOperandType() != Load->getPointerOperandType())
Adam Nemet7aba60c2016-03-24 17:59:26 +0000212 continue;
213
Adam Nemete54a4fa2015-11-03 23:50:08 +0000214 Candidates.emplace_front(Load, Store);
215 }
216
217 if (!LoadsWithUnknownDepedence.empty())
218 Candidates.remove_if([&](const StoreToLoadForwardingCandidate &C) {
219 return LoadsWithUnknownDepedence.count(C.Load);
220 });
221
222 return Candidates;
223 }
224
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000225 /// Return the index of the instruction according to program order.
Adam Nemete54a4fa2015-11-03 23:50:08 +0000226 unsigned getInstrIndex(Instruction *Inst) {
227 auto I = InstOrder.find(Inst);
228 assert(I != InstOrder.end() && "No index for instruction");
229 return I->second;
230 }
231
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000232 /// If a load has multiple candidates associated (i.e. different
Adam Nemete54a4fa2015-11-03 23:50:08 +0000233 /// stores), it means that it could be forwarding from multiple stores
234 /// depending on control flow. Remove these candidates.
235 ///
236 /// Here, we rely on LAA to include the relevant loop-independent dependences.
237 /// LAA is known to omit these in the very simple case when the read and the
238 /// write within an alias set always takes place using the *same* pointer.
239 ///
240 /// However, we know that this is not the case here, i.e. we can rely on LAA
241 /// to provide us with loop-independent dependences for the cases we're
242 /// interested. Consider the case for example where a loop-independent
243 /// dependece S1->S2 invalidates the forwarding S3->S2.
244 ///
245 /// A[i] = ... (S1)
246 /// ... = A[i] (S2)
247 /// A[i+1] = ... (S3)
248 ///
249 /// LAA will perform dependence analysis here because there are two
250 /// *different* pointers involved in the same alias set (&A[i] and &A[i+1]).
251 void removeDependencesFromMultipleStores(
252 std::forward_list<StoreToLoadForwardingCandidate> &Candidates) {
253 // If Store is nullptr it means that we have multiple stores forwarding to
254 // this store.
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000255 using LoadToSingleCandT =
256 DenseMap<LoadInst *, const StoreToLoadForwardingCandidate *>;
Adam Nemete54a4fa2015-11-03 23:50:08 +0000257 LoadToSingleCandT LoadToSingleCand;
258
259 for (const auto &Cand : Candidates) {
260 bool NewElt;
261 LoadToSingleCandT::iterator Iter;
262
263 std::tie(Iter, NewElt) =
264 LoadToSingleCand.insert(std::make_pair(Cand.Load, &Cand));
265 if (!NewElt) {
266 const StoreToLoadForwardingCandidate *&OtherCand = Iter->second;
267 // Already multiple stores forward to this load.
268 if (OtherCand == nullptr)
269 continue;
270
Adam Nemetefc091f2016-02-29 23:21:12 +0000271 // Handle the very basic case when the two stores are in the same block
272 // so deciding which one forwards is easy. The later one forwards as
273 // long as they both have a dependence distance of one to the load.
Adam Nemete54a4fa2015-11-03 23:50:08 +0000274 if (Cand.Store->getParent() == OtherCand->Store->getParent() &&
Adam Nemet660748c2016-03-09 20:47:55 +0000275 Cand.isDependenceDistanceOfOne(PSE, L) &&
276 OtherCand->isDependenceDistanceOfOne(PSE, L)) {
Adam Nemete54a4fa2015-11-03 23:50:08 +0000277 // They are in the same block, the later one will forward to the load.
278 if (getInstrIndex(OtherCand->Store) < getInstrIndex(Cand.Store))
279 OtherCand = &Cand;
280 } else
281 OtherCand = nullptr;
282 }
283 }
284
285 Candidates.remove_if([&](const StoreToLoadForwardingCandidate &Cand) {
286 if (LoadToSingleCand[Cand.Load] != &Cand) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000287 LLVM_DEBUG(
288 dbgs() << "Removing from candidates: \n"
289 << Cand
290 << " The load may have multiple stores forwarding to "
291 << "it\n");
Adam Nemete54a4fa2015-11-03 23:50:08 +0000292 return true;
293 }
294 return false;
295 });
296 }
297
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000298 /// Given two pointers operations by their RuntimePointerChecking
Adam Nemete54a4fa2015-11-03 23:50:08 +0000299 /// indices, return true if they require an alias check.
300 ///
301 /// We need a check if one is a pointer for a candidate load and the other is
302 /// a pointer for a possibly intervening store.
303 bool needsChecking(unsigned PtrIdx1, unsigned PtrIdx2,
Florian Hahna1cc8482018-06-12 11:16:56 +0000304 const SmallPtrSet<Value *, 4> &PtrsWrittenOnFwdingPath,
Adam Nemete54a4fa2015-11-03 23:50:08 +0000305 const std::set<Value *> &CandLoadPtrs) {
306 Value *Ptr1 =
307 LAI.getRuntimePointerChecking()->getPointerInfo(PtrIdx1).PointerValue;
308 Value *Ptr2 =
309 LAI.getRuntimePointerChecking()->getPointerInfo(PtrIdx2).PointerValue;
310 return ((PtrsWrittenOnFwdingPath.count(Ptr1) && CandLoadPtrs.count(Ptr2)) ||
311 (PtrsWrittenOnFwdingPath.count(Ptr2) && CandLoadPtrs.count(Ptr1)));
312 }
313
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000314 /// Return pointers that are possibly written to on the path from a
Adam Nemete54a4fa2015-11-03 23:50:08 +0000315 /// forwarding store to a load.
316 ///
317 /// These pointers need to be alias-checked against the forwarding candidates.
Florian Hahna1cc8482018-06-12 11:16:56 +0000318 SmallPtrSet<Value *, 4> findPointersWrittenOnForwardingPath(
Adam Nemete54a4fa2015-11-03 23:50:08 +0000319 const SmallVectorImpl<StoreToLoadForwardingCandidate> &Candidates) {
320 // From FirstStore to LastLoad neither of the elimination candidate loads
321 // should overlap with any of the stores.
322 //
323 // E.g.:
324 //
325 // st1 C[i]
326 // ld1 B[i] <-------,
327 // ld0 A[i] <----, | * LastLoad
328 // ... | |
329 // st2 E[i] | |
330 // st3 B[i+1] -- | -' * FirstStore
331 // st0 A[i+1] ---'
332 // st4 D[i]
333 //
334 // st0 forwards to ld0 if the accesses in st4 and st1 don't overlap with
335 // ld0.
336
337 LoadInst *LastLoad =
338 std::max_element(Candidates.begin(), Candidates.end(),
339 [&](const StoreToLoadForwardingCandidate &A,
340 const StoreToLoadForwardingCandidate &B) {
341 return getInstrIndex(A.Load) < getInstrIndex(B.Load);
342 })
343 ->Load;
344 StoreInst *FirstStore =
345 std::min_element(Candidates.begin(), Candidates.end(),
346 [&](const StoreToLoadForwardingCandidate &A,
347 const StoreToLoadForwardingCandidate &B) {
348 return getInstrIndex(A.Store) <
349 getInstrIndex(B.Store);
350 })
351 ->Store;
352
353 // We're looking for stores after the first forwarding store until the end
354 // of the loop, then from the beginning of the loop until the last
355 // forwarded-to load. Collect the pointer for the stores.
Florian Hahna1cc8482018-06-12 11:16:56 +0000356 SmallPtrSet<Value *, 4> PtrsWrittenOnFwdingPath;
Adam Nemete54a4fa2015-11-03 23:50:08 +0000357
358 auto InsertStorePtr = [&](Instruction *I) {
359 if (auto *S = dyn_cast<StoreInst>(I))
360 PtrsWrittenOnFwdingPath.insert(S->getPointerOperand());
361 };
362 const auto &MemInstrs = LAI.getDepChecker().getMemoryInstructions();
363 std::for_each(MemInstrs.begin() + getInstrIndex(FirstStore) + 1,
364 MemInstrs.end(), InsertStorePtr);
365 std::for_each(MemInstrs.begin(), &MemInstrs[getInstrIndex(LastLoad)],
366 InsertStorePtr);
367
368 return PtrsWrittenOnFwdingPath;
369 }
370
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000371 /// Determine the pointer alias checks to prove that there are no
Adam Nemete54a4fa2015-11-03 23:50:08 +0000372 /// intervening stores.
373 SmallVector<RuntimePointerChecking::PointerCheck, 4> collectMemchecks(
374 const SmallVectorImpl<StoreToLoadForwardingCandidate> &Candidates) {
375
Florian Hahna1cc8482018-06-12 11:16:56 +0000376 SmallPtrSet<Value *, 4> PtrsWrittenOnFwdingPath =
Adam Nemete54a4fa2015-11-03 23:50:08 +0000377 findPointersWrittenOnForwardingPath(Candidates);
378
379 // Collect the pointers of the candidate loads.
Florian Hahna1cc8482018-06-12 11:16:56 +0000380 // FIXME: SmallPtrSet does not work with std::inserter.
Adam Nemete54a4fa2015-11-03 23:50:08 +0000381 std::set<Value *> CandLoadPtrs;
David Majnemer2d006e72016-08-12 04:32:42 +0000382 transform(Candidates,
Adam Nemete54a4fa2015-11-03 23:50:08 +0000383 std::inserter(CandLoadPtrs, CandLoadPtrs.begin()),
384 std::mem_fn(&StoreToLoadForwardingCandidate::getLoadPtr));
385
386 const auto &AllChecks = LAI.getRuntimePointerChecking()->getChecks();
387 SmallVector<RuntimePointerChecking::PointerCheck, 4> Checks;
388
Sanjoy Das90208722017-02-21 00:38:44 +0000389 copy_if(AllChecks, std::back_inserter(Checks),
390 [&](const RuntimePointerChecking::PointerCheck &Check) {
391 for (auto PtrIdx1 : Check.first->Members)
392 for (auto PtrIdx2 : Check.second->Members)
393 if (needsChecking(PtrIdx1, PtrIdx2, PtrsWrittenOnFwdingPath,
394 CandLoadPtrs))
395 return true;
396 return false;
397 });
Adam Nemete54a4fa2015-11-03 23:50:08 +0000398
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000399 LLVM_DEBUG(dbgs() << "\nPointer Checks (count: " << Checks.size()
400 << "):\n");
401 LLVM_DEBUG(LAI.getRuntimePointerChecking()->printChecks(dbgs(), Checks));
Adam Nemete54a4fa2015-11-03 23:50:08 +0000402
403 return Checks;
404 }
405
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000406 /// Perform the transformation for a candidate.
Adam Nemete54a4fa2015-11-03 23:50:08 +0000407 void
408 propagateStoredValueToLoadUsers(const StoreToLoadForwardingCandidate &Cand,
409 SCEVExpander &SEE) {
Adam Nemete54a4fa2015-11-03 23:50:08 +0000410 // loop:
411 // %x = load %gep_i
412 // = ... %x
413 // store %y, %gep_i_plus_1
414 //
415 // =>
416 //
417 // ph:
418 // %x.initial = load %gep_0
419 // loop:
420 // %x.storeforward = phi [%x.initial, %ph] [%y, %loop]
421 // %x = load %gep_i <---- now dead
422 // = ... %x.storeforward
423 // store %y, %gep_i_plus_1
424
425 Value *Ptr = Cand.Load->getPointerOperand();
Silviu Baranga86de80d2015-12-10 11:07:18 +0000426 auto *PtrSCEV = cast<SCEVAddRecExpr>(PSE.getSCEV(Ptr));
Adam Nemete54a4fa2015-11-03 23:50:08 +0000427 auto *PH = L->getLoopPreheader();
428 Value *InitialPtr = SEE.expandCodeFor(PtrSCEV->getStart(), Ptr->getType(),
429 PH->getTerminator());
430 Value *Initial =
Mehdi Amini27d224f2017-01-06 21:06:51 +0000431 new LoadInst(InitialPtr, "load_initial", /* isVolatile */ false,
432 Cand.Load->getAlignment(), PH->getTerminator());
433
Adam Nemete54a4fa2015-11-03 23:50:08 +0000434 PHINode *PHI = PHINode::Create(Initial->getType(), 2, "store_forwarded",
Duncan P. N. Exon Smith83c4b682015-11-07 00:01:16 +0000435 &L->getHeader()->front());
Adam Nemete54a4fa2015-11-03 23:50:08 +0000436 PHI->addIncoming(Initial, PH);
437 PHI->addIncoming(Cand.Store->getOperand(0), L->getLoopLatch());
438
439 Cand.Load->replaceAllUsesWith(PHI);
440 }
441
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000442 /// Top-level driver for each loop: find store->load forwarding
Adam Nemete54a4fa2015-11-03 23:50:08 +0000443 /// candidates, add run-time checks and perform transformation.
444 bool processLoop() {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000445 LLVM_DEBUG(dbgs() << "\nIn \"" << L->getHeader()->getParent()->getName()
446 << "\" checking " << *L << "\n");
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000447
Adam Nemete54a4fa2015-11-03 23:50:08 +0000448 // Look for store-to-load forwarding cases across the
449 // backedge. E.g.:
450 //
451 // loop:
452 // %x = load %gep_i
453 // = ... %x
454 // store %y, %gep_i_plus_1
455 //
456 // =>
457 //
458 // ph:
459 // %x.initial = load %gep_0
460 // loop:
461 // %x.storeforward = phi [%x.initial, %ph] [%y, %loop]
462 // %x = load %gep_i <---- now dead
463 // = ... %x.storeforward
464 // store %y, %gep_i_plus_1
465
466 // First start with store->load dependences.
467 auto StoreToLoadDependences = findStoreToLoadDependences(LAI);
468 if (StoreToLoadDependences.empty())
469 return false;
470
471 // Generate an index for each load and store according to the original
472 // program order. This will be used later.
473 InstOrder = LAI.getDepChecker().generateInstructionOrderMap();
474
475 // To keep things simple for now, remove those where the load is potentially
476 // fed by multiple stores.
477 removeDependencesFromMultipleStores(StoreToLoadDependences);
478 if (StoreToLoadDependences.empty())
479 return false;
480
481 // Filter the candidates further.
482 SmallVector<StoreToLoadForwardingCandidate, 4> Candidates;
483 unsigned NumForwarding = 0;
484 for (const StoreToLoadForwardingCandidate Cand : StoreToLoadDependences) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000485 LLVM_DEBUG(dbgs() << "Candidate " << Cand);
Adam Nemet83be06e2016-02-29 22:53:59 +0000486
Adam Nemete54a4fa2015-11-03 23:50:08 +0000487 // Make sure that the stored values is available everywhere in the loop in
488 // the next iteration.
489 if (!doesStoreDominatesAllLatches(Cand.Store->getParent(), L, DT))
490 continue;
491
Adam Nemetbd861ac2016-06-28 04:02:47 +0000492 // If the load is conditional we can't hoist its 0-iteration instance to
493 // the preheader because that would make it unconditional. Thus we would
494 // access a memory location that the original loop did not access.
495 if (isLoadConditional(Cand.Load, L))
496 continue;
497
Adam Nemete54a4fa2015-11-03 23:50:08 +0000498 // Check whether the SCEV difference is the same as the induction step,
499 // thus we load the value in the next iteration.
Adam Nemet660748c2016-03-09 20:47:55 +0000500 if (!Cand.isDependenceDistanceOfOne(PSE, L))
Adam Nemete54a4fa2015-11-03 23:50:08 +0000501 continue;
502
503 ++NumForwarding;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000504 LLVM_DEBUG(
505 dbgs()
506 << NumForwarding
507 << ". Valid store-to-load forwarding across the loop backedge\n");
Adam Nemete54a4fa2015-11-03 23:50:08 +0000508 Candidates.push_back(Cand);
509 }
510 if (Candidates.empty())
511 return false;
512
513 // Check intervening may-alias stores. These need runtime checks for alias
514 // disambiguation.
515 SmallVector<RuntimePointerChecking::PointerCheck, 4> Checks =
516 collectMemchecks(Candidates);
517
518 // Too many checks are likely to outweigh the benefits of forwarding.
519 if (Checks.size() > Candidates.size() * CheckPerElim) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000520 LLVM_DEBUG(dbgs() << "Too many run-time checks needed.\n");
Adam Nemete54a4fa2015-11-03 23:50:08 +0000521 return false;
522 }
523
Xinliang David Li94734ee2016-07-01 05:59:55 +0000524 if (LAI.getPSE().getUnionPredicate().getComplexity() >
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +0000525 LoadElimSCEVCheckThreshold) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000526 LLVM_DEBUG(dbgs() << "Too many SCEV run-time checks needed.\n");
Silviu Baranga2910a4f2015-11-09 13:26:09 +0000527 return false;
528 }
529
Xinliang David Li94734ee2016-07-01 05:59:55 +0000530 if (!Checks.empty() || !LAI.getPSE().getUnionPredicate().isAlwaysTrue()) {
Adam Nemet9455c1d2016-02-05 01:14:05 +0000531 if (L->getHeader()->getParent()->optForSize()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000532 LLVM_DEBUG(
533 dbgs() << "Versioning is needed but not allowed when optimizing "
534 "for size.\n");
Adam Nemet9455c1d2016-02-05 01:14:05 +0000535 return false;
536 }
537
Florian Hahn2e032132016-12-19 17:13:37 +0000538 if (!L->isLoopSimplifyForm()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000539 LLVM_DEBUG(dbgs() << "Loop is not is loop-simplify form");
Florian Hahn2e032132016-12-19 17:13:37 +0000540 return false;
541 }
542
Adam Nemet9455c1d2016-02-05 01:14:05 +0000543 // Point of no-return, start the transformation. First, version the loop
544 // if necessary.
545
Silviu Baranga86de80d2015-12-10 11:07:18 +0000546 LoopVersioning LV(LAI, L, LI, DT, PSE.getSE(), false);
Silviu Baranga2910a4f2015-11-09 13:26:09 +0000547 LV.setAliasChecks(std::move(Checks));
Xinliang David Li94734ee2016-07-01 05:59:55 +0000548 LV.setSCEVChecks(LAI.getPSE().getUnionPredicate());
Adam Nemete54a4fa2015-11-03 23:50:08 +0000549 LV.versionLoop();
550 }
551
552 // Next, propagate the value stored by the store to the users of the load.
553 // Also for the first iteration, generate the initial value of the load.
Silviu Baranga86de80d2015-12-10 11:07:18 +0000554 SCEVExpander SEE(*PSE.getSE(), L->getHeader()->getModule()->getDataLayout(),
Adam Nemete54a4fa2015-11-03 23:50:08 +0000555 "storeforward");
556 for (const auto &Cand : Candidates)
557 propagateStoredValueToLoadUsers(Cand, SEE);
558 NumLoopLoadEliminted += NumForwarding;
559
560 return true;
561 }
562
563private:
564 Loop *L;
565
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000566 /// Maps the load/store instructions to their index according to
Adam Nemete54a4fa2015-11-03 23:50:08 +0000567 /// program order.
568 DenseMap<Instruction *, unsigned> InstOrder;
569
570 // Analyses used.
571 LoopInfo *LI;
572 const LoopAccessInfo &LAI;
573 DominatorTree *DT;
Silviu Baranga86de80d2015-12-10 11:07:18 +0000574 PredicatedScalarEvolution PSE;
Adam Nemete54a4fa2015-11-03 23:50:08 +0000575};
576
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000577} // end anonymous namespace
578
Chandler Carruthbaabda92017-01-27 01:32:26 +0000579static bool
580eliminateLoadsAcrossLoops(Function &F, LoopInfo &LI, DominatorTree &DT,
581 function_ref<const LoopAccessInfo &(Loop &)> GetLAI) {
582 // Build up a worklist of inner-loops to transform to avoid iterator
583 // invalidation.
584 // FIXME: This logic comes from other passes that actually change the loop
585 // nest structure. It isn't clear this is necessary (or useful) for a pass
586 // which merely optimizes the use of loads in a loop.
587 SmallVector<Loop *, 8> Worklist;
588
589 for (Loop *TopLevelLoop : LI)
590 for (Loop *L : depth_first(TopLevelLoop))
591 // We only handle inner-most loops.
592 if (L->empty())
593 Worklist.push_back(L);
594
595 // Now walk the identified inner loops.
596 bool Changed = false;
597 for (Loop *L : Worklist) {
598 // The actual work is performed by LoadEliminationForLoop.
599 LoadEliminationForLoop LEL(L, &LI, GetLAI(*L), &DT);
600 Changed |= LEL.processLoop();
601 }
602 return Changed;
603}
604
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000605namespace {
606
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000607/// The pass. Most of the work is delegated to the per-loop
Adam Nemete54a4fa2015-11-03 23:50:08 +0000608/// LoadEliminationForLoop class.
609class LoopLoadElimination : public FunctionPass {
610public:
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000611 static char ID;
612
Adam Nemete54a4fa2015-11-03 23:50:08 +0000613 LoopLoadElimination() : FunctionPass(ID) {
614 initializeLoopLoadEliminationPass(*PassRegistry::getPassRegistry());
615 }
616
617 bool runOnFunction(Function &F) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000618 if (skipFunction(F))
619 return false;
620
Chandler Carruthbaabda92017-01-27 01:32:26 +0000621 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
622 auto &LAA = getAnalysis<LoopAccessLegacyAnalysis>();
623 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Adam Nemete54a4fa2015-11-03 23:50:08 +0000624
625 // Process each loop nest in the function.
Chandler Carruthbaabda92017-01-27 01:32:26 +0000626 return eliminateLoadsAcrossLoops(
627 F, LI, DT,
628 [&LAA](Loop &L) -> const LoopAccessInfo & { return LAA.getInfo(&L); });
Adam Nemete54a4fa2015-11-03 23:50:08 +0000629 }
630
631 void getAnalysisUsage(AnalysisUsage &AU) const override {
Adam Nemetefb23412016-03-10 23:54:39 +0000632 AU.addRequiredID(LoopSimplifyID);
Adam Nemete54a4fa2015-11-03 23:50:08 +0000633 AU.addRequired<LoopInfoWrapperPass>();
634 AU.addPreserved<LoopInfoWrapperPass>();
Xinliang David Li7853c1d2016-07-08 20:55:26 +0000635 AU.addRequired<LoopAccessLegacyAnalysis>();
Adam Nemete54a4fa2015-11-03 23:50:08 +0000636 AU.addRequired<ScalarEvolutionWrapperPass>();
637 AU.addRequired<DominatorTreeWrapperPass>();
638 AU.addPreserved<DominatorTreeWrapperPass>();
Eli Friedman02d48be2016-09-16 17:58:07 +0000639 AU.addPreserved<GlobalsAAWrapperPass>();
Adam Nemete54a4fa2015-11-03 23:50:08 +0000640 }
Adam Nemete54a4fa2015-11-03 23:50:08 +0000641};
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +0000642
643} // end anonymous namespace
Adam Nemete54a4fa2015-11-03 23:50:08 +0000644
645char LoopLoadElimination::ID;
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000646
Adam Nemete54a4fa2015-11-03 23:50:08 +0000647static const char LLE_name[] = "Loop Load Elimination";
648
649INITIALIZE_PASS_BEGIN(LoopLoadElimination, LLE_OPTION, LLE_name, false, false)
650INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Xinliang David Li7853c1d2016-07-08 20:55:26 +0000651INITIALIZE_PASS_DEPENDENCY(LoopAccessLegacyAnalysis)
Adam Nemete54a4fa2015-11-03 23:50:08 +0000652INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
653INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
Adam Nemetefb23412016-03-10 23:54:39 +0000654INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
Adam Nemete54a4fa2015-11-03 23:50:08 +0000655INITIALIZE_PASS_END(LoopLoadElimination, LLE_OPTION, LLE_name, false, false)
656
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000657FunctionPass *llvm::createLoopLoadEliminationPass() {
Adam Nemete54a4fa2015-11-03 23:50:08 +0000658 return new LoopLoadElimination();
659}
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +0000660
Chandler Carruthbaabda92017-01-27 01:32:26 +0000661PreservedAnalyses LoopLoadEliminationPass::run(Function &F,
662 FunctionAnalysisManager &AM) {
663 auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
664 auto &LI = AM.getResult<LoopAnalysis>(F);
665 auto &TTI = AM.getResult<TargetIRAnalysis>(F);
666 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
667 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
668 auto &AA = AM.getResult<AAManager>(F);
669 auto &AC = AM.getResult<AssumptionAnalysis>(F);
670
671 auto &LAM = AM.getResult<LoopAnalysisManagerFunctionProxy>(F).getManager();
672 bool Changed = eliminateLoadsAcrossLoops(
673 F, LI, DT, [&](Loop &L) -> const LoopAccessInfo & {
Alina Sbirleaff8b8ae2017-11-21 15:45:46 +0000674 LoopStandardAnalysisResults AR = {AA, AC, DT, LI,
675 SE, TLI, TTI, nullptr};
Chandler Carruthbaabda92017-01-27 01:32:26 +0000676 return LAM.getResult<LoopAccessAnalysis>(L, AR);
677 });
678
679 if (!Changed)
680 return PreservedAnalyses::all();
681
682 PreservedAnalyses PA;
683 return PA;
684}