blob: 0ed9f295f4d47fb8a1ce325ec11ff995da312896 [file] [log] [blame]
Adam Nemet04563272015-02-01 16:56:15 +00001//===- LoopAccessAnalysis.cpp - Loop Access Analysis Implementation --------==//
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// The implementation for the loop memory dependence that was originally
11// developed for the loop vectorizer.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Analysis/LoopAccessAnalysis.h"
16#include "llvm/Analysis/LoopInfo.h"
Adam Nemet7206d7a2015-02-06 18:31:04 +000017#include "llvm/Analysis/ScalarEvolutionExpander.h"
Adam Nemet04563272015-02-01 16:56:15 +000018#include "llvm/Analysis/ValueTracking.h"
19#include "llvm/IR/DiagnosticInfo.h"
20#include "llvm/IR/Dominators.h"
Adam Nemet7206d7a2015-02-06 18:31:04 +000021#include "llvm/IR/IRBuilder.h"
Adam Nemet04563272015-02-01 16:56:15 +000022#include "llvm/Support/Debug.h"
23#include "llvm/Transforms/Utils/VectorUtils.h"
24using namespace llvm;
25
Adam Nemet339f42b2015-02-19 19:15:07 +000026#define DEBUG_TYPE "loop-accesses"
Adam Nemet04563272015-02-01 16:56:15 +000027
Adam Nemetf219c642015-02-19 19:14:52 +000028static cl::opt<unsigned, true>
29VectorizationFactor("force-vector-width", cl::Hidden,
30 cl::desc("Sets the SIMD width. Zero is autoselect."),
31 cl::location(VectorizerParams::VectorizationFactor));
Adam Nemet1d862af2015-02-26 04:39:09 +000032unsigned VectorizerParams::VectorizationFactor;
Adam Nemetf219c642015-02-19 19:14:52 +000033
34static cl::opt<unsigned, true>
35VectorizationInterleave("force-vector-interleave", cl::Hidden,
36 cl::desc("Sets the vectorization interleave count. "
37 "Zero is autoselect."),
38 cl::location(
39 VectorizerParams::VectorizationInterleave));
Adam Nemet1d862af2015-02-26 04:39:09 +000040unsigned VectorizerParams::VectorizationInterleave;
Adam Nemetf219c642015-02-19 19:14:52 +000041
Adam Nemet1d862af2015-02-26 04:39:09 +000042static cl::opt<unsigned, true> RuntimeMemoryCheckThreshold(
43 "runtime-memory-check-threshold", cl::Hidden,
44 cl::desc("When performing memory disambiguation checks at runtime do not "
45 "generate more than this number of comparisons (default = 8)."),
46 cl::location(VectorizerParams::RuntimeMemoryCheckThreshold), cl::init(8));
47unsigned VectorizerParams::RuntimeMemoryCheckThreshold;
Adam Nemetf219c642015-02-19 19:14:52 +000048
49/// Maximum SIMD width.
50const unsigned VectorizerParams::MaxVectorWidth = 64;
51
52bool VectorizerParams::isInterleaveForced() {
53 return ::VectorizationInterleave.getNumOccurrences() > 0;
54}
55
Adam Nemet2bd6e982015-02-19 19:15:15 +000056void LoopAccessReport::emitAnalysis(const LoopAccessReport &Message,
57 const Function *TheFunction,
58 const Loop *TheLoop,
59 const char *PassName) {
Adam Nemet04563272015-02-01 16:56:15 +000060 DebugLoc DL = TheLoop->getStartLoc();
Adam Nemet3e876342015-02-19 19:15:13 +000061 if (const Instruction *I = Message.getInstr())
Adam Nemet04563272015-02-01 16:56:15 +000062 DL = I->getDebugLoc();
Adam Nemet339f42b2015-02-19 19:15:07 +000063 emitOptimizationRemarkAnalysis(TheFunction->getContext(), PassName,
Adam Nemet04563272015-02-01 16:56:15 +000064 *TheFunction, DL, Message.str());
65}
66
67Value *llvm::stripIntegerCast(Value *V) {
68 if (CastInst *CI = dyn_cast<CastInst>(V))
69 if (CI->getOperand(0)->getType()->isIntegerTy())
70 return CI->getOperand(0);
71 return V;
72}
73
74const SCEV *llvm::replaceSymbolicStrideSCEV(ScalarEvolution *SE,
Adam Nemet8bc61df2015-02-24 00:41:59 +000075 const ValueToValueMap &PtrToStride,
Adam Nemet04563272015-02-01 16:56:15 +000076 Value *Ptr, Value *OrigPtr) {
77
78 const SCEV *OrigSCEV = SE->getSCEV(Ptr);
79
80 // If there is an entry in the map return the SCEV of the pointer with the
81 // symbolic stride replaced by one.
Adam Nemet8bc61df2015-02-24 00:41:59 +000082 ValueToValueMap::const_iterator SI =
83 PtrToStride.find(OrigPtr ? OrigPtr : Ptr);
Adam Nemet04563272015-02-01 16:56:15 +000084 if (SI != PtrToStride.end()) {
85 Value *StrideVal = SI->second;
86
87 // Strip casts.
88 StrideVal = stripIntegerCast(StrideVal);
89
90 // Replace symbolic stride by one.
91 Value *One = ConstantInt::get(StrideVal->getType(), 1);
92 ValueToValueMap RewriteMap;
93 RewriteMap[StrideVal] = One;
94
95 const SCEV *ByOne =
96 SCEVParameterRewriter::rewrite(OrigSCEV, *SE, RewriteMap, true);
Adam Nemet339f42b2015-02-19 19:15:07 +000097 DEBUG(dbgs() << "LAA: Replacing SCEV: " << *OrigSCEV << " by: " << *ByOne
Adam Nemet04563272015-02-01 16:56:15 +000098 << "\n");
99 return ByOne;
100 }
101
102 // Otherwise, just return the SCEV of the original pointer.
103 return SE->getSCEV(Ptr);
104}
105
Adam Nemet8bc61df2015-02-24 00:41:59 +0000106void LoopAccessInfo::RuntimePointerCheck::insert(
107 ScalarEvolution *SE, Loop *Lp, Value *Ptr, bool WritePtr, unsigned DepSetId,
108 unsigned ASId, const ValueToValueMap &Strides) {
Adam Nemet04563272015-02-01 16:56:15 +0000109 // Get the stride replaced scev.
110 const SCEV *Sc = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
111 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
112 assert(AR && "Invalid addrec expression");
113 const SCEV *Ex = SE->getBackedgeTakenCount(Lp);
114 const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
115 Pointers.push_back(Ptr);
116 Starts.push_back(AR->getStart());
117 Ends.push_back(ScEnd);
118 IsWritePtr.push_back(WritePtr);
119 DependencySetId.push_back(DepSetId);
120 AliasSetId.push_back(ASId);
121}
122
Adam Nemeta8945b72015-02-18 03:43:58 +0000123bool LoopAccessInfo::RuntimePointerCheck::needsChecking(unsigned I,
124 unsigned J) const {
125 // No need to check if two readonly pointers intersect.
126 if (!IsWritePtr[I] && !IsWritePtr[J])
127 return false;
128
129 // Only need to check pointers between two different dependency sets.
130 if (DependencySetId[I] == DependencySetId[J])
131 return false;
132
133 // Only need to check pointers in the same alias set.
134 if (AliasSetId[I] != AliasSetId[J])
135 return false;
136
137 return true;
138}
139
Adam Nemete91cc6e2015-02-19 19:15:19 +0000140void LoopAccessInfo::RuntimePointerCheck::print(raw_ostream &OS,
141 unsigned Depth) const {
142 unsigned NumPointers = Pointers.size();
143 if (NumPointers == 0)
144 return;
145
146 OS.indent(Depth) << "Run-time memory checks:\n";
147 unsigned N = 0;
148 for (unsigned I = 0; I < NumPointers; ++I)
149 for (unsigned J = I + 1; J < NumPointers; ++J)
150 if (needsChecking(I, J)) {
151 OS.indent(Depth) << N++ << ":\n";
152 OS.indent(Depth + 2) << *Pointers[I] << "\n";
153 OS.indent(Depth + 2) << *Pointers[J] << "\n";
154 }
155}
156
Adam Nemet04563272015-02-01 16:56:15 +0000157namespace {
158/// \brief Analyses memory accesses in a loop.
159///
160/// Checks whether run time pointer checks are needed and builds sets for data
161/// dependence checking.
162class AccessAnalysis {
163public:
164 /// \brief Read or write access location.
165 typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
166 typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
167
168 /// \brief Set of potential dependent memory accesses.
169 typedef EquivalenceClasses<MemAccessInfo> DepCandidates;
170
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000171 AccessAnalysis(const DataLayout &Dl, AliasAnalysis *AA, DepCandidates &DA)
172 : DL(Dl), AST(*AA), DepCands(DA), IsRTCheckNeeded(false) {}
Adam Nemet04563272015-02-01 16:56:15 +0000173
174 /// \brief Register a load and whether it is only read from.
175 void addLoad(AliasAnalysis::Location &Loc, bool IsReadOnly) {
176 Value *Ptr = const_cast<Value*>(Loc.Ptr);
177 AST.add(Ptr, AliasAnalysis::UnknownSize, Loc.AATags);
178 Accesses.insert(MemAccessInfo(Ptr, false));
179 if (IsReadOnly)
180 ReadOnlyPtr.insert(Ptr);
181 }
182
183 /// \brief Register a store.
184 void addStore(AliasAnalysis::Location &Loc) {
185 Value *Ptr = const_cast<Value*>(Loc.Ptr);
186 AST.add(Ptr, AliasAnalysis::UnknownSize, Loc.AATags);
187 Accesses.insert(MemAccessInfo(Ptr, true));
188 }
189
190 /// \brief Check whether we can check the pointers at runtime for
191 /// non-intersection.
Adam Nemet30f16e12015-02-18 03:42:35 +0000192 bool canCheckPtrAtRT(LoopAccessInfo::RuntimePointerCheck &RtCheck,
Adam Nemet8bc61df2015-02-24 00:41:59 +0000193 unsigned &NumComparisons, ScalarEvolution *SE,
194 Loop *TheLoop, const ValueToValueMap &Strides,
Adam Nemet04563272015-02-01 16:56:15 +0000195 bool ShouldCheckStride = false);
196
197 /// \brief Goes over all memory accesses, checks whether a RT check is needed
198 /// and builds sets of dependent accesses.
199 void buildDependenceSets() {
200 processMemAccesses();
201 }
202
203 bool isRTCheckNeeded() { return IsRTCheckNeeded; }
204
205 bool isDependencyCheckNeeded() { return !CheckDeps.empty(); }
206 void resetDepChecks() { CheckDeps.clear(); }
207
208 MemAccessInfoSet &getDependenciesToCheck() { return CheckDeps; }
209
210private:
211 typedef SetVector<MemAccessInfo> PtrAccessSet;
212
213 /// \brief Go over all memory access and check whether runtime pointer checks
214 /// are needed /// and build sets of dependency check candidates.
215 void processMemAccesses();
216
217 /// Set of all accesses.
218 PtrAccessSet Accesses;
219
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000220 const DataLayout &DL;
221
Adam Nemet04563272015-02-01 16:56:15 +0000222 /// Set of accesses that need a further dependence check.
223 MemAccessInfoSet CheckDeps;
224
225 /// Set of pointers that are read only.
226 SmallPtrSet<Value*, 16> ReadOnlyPtr;
227
Adam Nemet04563272015-02-01 16:56:15 +0000228 /// An alias set tracker to partition the access set by underlying object and
229 //intrinsic property (such as TBAA metadata).
230 AliasSetTracker AST;
231
232 /// Sets of potentially dependent accesses - members of one set share an
233 /// underlying pointer. The set "CheckDeps" identfies which sets really need a
234 /// dependence check.
235 DepCandidates &DepCands;
236
237 bool IsRTCheckNeeded;
238};
239
240} // end anonymous namespace
241
242/// \brief Check whether a pointer can participate in a runtime bounds check.
Adam Nemet8bc61df2015-02-24 00:41:59 +0000243static bool hasComputableBounds(ScalarEvolution *SE,
244 const ValueToValueMap &Strides, Value *Ptr) {
Adam Nemet04563272015-02-01 16:56:15 +0000245 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
246 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
247 if (!AR)
248 return false;
249
250 return AR->isAffine();
251}
252
253/// \brief Check the stride of the pointer and ensure that it does not wrap in
254/// the address space.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000255static int isStridedPtr(ScalarEvolution *SE, Value *Ptr, const Loop *Lp,
256 const ValueToValueMap &StridesMap);
Adam Nemet04563272015-02-01 16:56:15 +0000257
258bool AccessAnalysis::canCheckPtrAtRT(
Adam Nemet8bc61df2015-02-24 00:41:59 +0000259 LoopAccessInfo::RuntimePointerCheck &RtCheck, unsigned &NumComparisons,
260 ScalarEvolution *SE, Loop *TheLoop, const ValueToValueMap &StridesMap,
261 bool ShouldCheckStride) {
Adam Nemet04563272015-02-01 16:56:15 +0000262 // Find pointers with computable bounds. We are going to use this information
263 // to place a runtime bound check.
264 bool CanDoRT = true;
265
266 bool IsDepCheckNeeded = isDependencyCheckNeeded();
267 NumComparisons = 0;
268
269 // We assign a consecutive id to access from different alias sets.
270 // Accesses between different groups doesn't need to be checked.
271 unsigned ASId = 1;
272 for (auto &AS : AST) {
273 unsigned NumReadPtrChecks = 0;
274 unsigned NumWritePtrChecks = 0;
275
276 // We assign consecutive id to access from different dependence sets.
277 // Accesses within the same set don't need a runtime check.
278 unsigned RunningDepId = 1;
279 DenseMap<Value *, unsigned> DepSetId;
280
281 for (auto A : AS) {
282 Value *Ptr = A.getValue();
283 bool IsWrite = Accesses.count(MemAccessInfo(Ptr, true));
284 MemAccessInfo Access(Ptr, IsWrite);
285
286 if (IsWrite)
287 ++NumWritePtrChecks;
288 else
289 ++NumReadPtrChecks;
290
291 if (hasComputableBounds(SE, StridesMap, Ptr) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000292 // When we run after a failing dependency check we have to make sure
293 // we don't have wrapping pointers.
Adam Nemet04563272015-02-01 16:56:15 +0000294 (!ShouldCheckStride ||
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000295 isStridedPtr(SE, Ptr, TheLoop, StridesMap) == 1)) {
Adam Nemet04563272015-02-01 16:56:15 +0000296 // The id of the dependence set.
297 unsigned DepId;
298
299 if (IsDepCheckNeeded) {
300 Value *Leader = DepCands.getLeaderValue(Access).getPointer();
301 unsigned &LeaderId = DepSetId[Leader];
302 if (!LeaderId)
303 LeaderId = RunningDepId++;
304 DepId = LeaderId;
305 } else
306 // Each access has its own dependence set.
307 DepId = RunningDepId++;
308
309 RtCheck.insert(SE, TheLoop, Ptr, IsWrite, DepId, ASId, StridesMap);
310
Adam Nemet339f42b2015-02-19 19:15:07 +0000311 DEBUG(dbgs() << "LAA: Found a runtime check ptr:" << *Ptr << '\n');
Adam Nemet04563272015-02-01 16:56:15 +0000312 } else {
313 CanDoRT = false;
314 }
315 }
316
317 if (IsDepCheckNeeded && CanDoRT && RunningDepId == 2)
318 NumComparisons += 0; // Only one dependence set.
319 else {
320 NumComparisons += (NumWritePtrChecks * (NumReadPtrChecks +
321 NumWritePtrChecks - 1));
322 }
323
324 ++ASId;
325 }
326
327 // If the pointers that we would use for the bounds comparison have different
328 // address spaces, assume the values aren't directly comparable, so we can't
329 // use them for the runtime check. We also have to assume they could
330 // overlap. In the future there should be metadata for whether address spaces
331 // are disjoint.
332 unsigned NumPointers = RtCheck.Pointers.size();
333 for (unsigned i = 0; i < NumPointers; ++i) {
334 for (unsigned j = i + 1; j < NumPointers; ++j) {
335 // Only need to check pointers between two different dependency sets.
336 if (RtCheck.DependencySetId[i] == RtCheck.DependencySetId[j])
337 continue;
338 // Only need to check pointers in the same alias set.
339 if (RtCheck.AliasSetId[i] != RtCheck.AliasSetId[j])
340 continue;
341
342 Value *PtrI = RtCheck.Pointers[i];
343 Value *PtrJ = RtCheck.Pointers[j];
344
345 unsigned ASi = PtrI->getType()->getPointerAddressSpace();
346 unsigned ASj = PtrJ->getType()->getPointerAddressSpace();
347 if (ASi != ASj) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000348 DEBUG(dbgs() << "LAA: Runtime check would require comparison between"
Adam Nemet04d41632015-02-19 19:14:34 +0000349 " different address spaces\n");
Adam Nemet04563272015-02-01 16:56:15 +0000350 return false;
351 }
352 }
353 }
354
355 return CanDoRT;
356}
357
358void AccessAnalysis::processMemAccesses() {
359 // We process the set twice: first we process read-write pointers, last we
360 // process read-only pointers. This allows us to skip dependence tests for
361 // read-only pointers.
362
Adam Nemet339f42b2015-02-19 19:15:07 +0000363 DEBUG(dbgs() << "LAA: Processing memory accesses...\n");
Adam Nemet04563272015-02-01 16:56:15 +0000364 DEBUG(dbgs() << " AST: "; AST.dump());
Adam Nemet339f42b2015-02-19 19:15:07 +0000365 DEBUG(dbgs() << "LAA: Accesses:\n");
Adam Nemet04563272015-02-01 16:56:15 +0000366 DEBUG({
367 for (auto A : Accesses)
368 dbgs() << "\t" << *A.getPointer() << " (" <<
369 (A.getInt() ? "write" : (ReadOnlyPtr.count(A.getPointer()) ?
370 "read-only" : "read")) << ")\n";
371 });
372
373 // The AliasSetTracker has nicely partitioned our pointers by metadata
374 // compatibility and potential for underlying-object overlap. As a result, we
375 // only need to check for potential pointer dependencies within each alias
376 // set.
377 for (auto &AS : AST) {
378 // Note that both the alias-set tracker and the alias sets themselves used
379 // linked lists internally and so the iteration order here is deterministic
380 // (matching the original instruction order within each set).
381
382 bool SetHasWrite = false;
383
384 // Map of pointers to last access encountered.
385 typedef DenseMap<Value*, MemAccessInfo> UnderlyingObjToAccessMap;
386 UnderlyingObjToAccessMap ObjToLastAccess;
387
388 // Set of access to check after all writes have been processed.
389 PtrAccessSet DeferredAccesses;
390
391 // Iterate over each alias set twice, once to process read/write pointers,
392 // and then to process read-only pointers.
393 for (int SetIteration = 0; SetIteration < 2; ++SetIteration) {
394 bool UseDeferred = SetIteration > 0;
395 PtrAccessSet &S = UseDeferred ? DeferredAccesses : Accesses;
396
397 for (auto AV : AS) {
398 Value *Ptr = AV.getValue();
399
400 // For a single memory access in AliasSetTracker, Accesses may contain
401 // both read and write, and they both need to be handled for CheckDeps.
402 for (auto AC : S) {
403 if (AC.getPointer() != Ptr)
404 continue;
405
406 bool IsWrite = AC.getInt();
407
408 // If we're using the deferred access set, then it contains only
409 // reads.
410 bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite;
411 if (UseDeferred && !IsReadOnlyPtr)
412 continue;
413 // Otherwise, the pointer must be in the PtrAccessSet, either as a
414 // read or a write.
415 assert(((IsReadOnlyPtr && UseDeferred) || IsWrite ||
416 S.count(MemAccessInfo(Ptr, false))) &&
417 "Alias-set pointer not in the access set?");
418
419 MemAccessInfo Access(Ptr, IsWrite);
420 DepCands.insert(Access);
421
422 // Memorize read-only pointers for later processing and skip them in
423 // the first round (they need to be checked after we have seen all
424 // write pointers). Note: we also mark pointer that are not
425 // consecutive as "read-only" pointers (so that we check
426 // "a[b[i]] +="). Hence, we need the second check for "!IsWrite".
427 if (!UseDeferred && IsReadOnlyPtr) {
428 DeferredAccesses.insert(Access);
429 continue;
430 }
431
432 // If this is a write - check other reads and writes for conflicts. If
433 // this is a read only check other writes for conflicts (but only if
434 // there is no other write to the ptr - this is an optimization to
435 // catch "a[i] = a[i] + " without having to do a dependence check).
436 if ((IsWrite || IsReadOnlyPtr) && SetHasWrite) {
437 CheckDeps.insert(Access);
438 IsRTCheckNeeded = true;
439 }
440
441 if (IsWrite)
442 SetHasWrite = true;
443
444 // Create sets of pointers connected by a shared alias set and
445 // underlying object.
446 typedef SmallVector<Value *, 16> ValueVector;
447 ValueVector TempObjects;
448 GetUnderlyingObjects(Ptr, TempObjects, DL);
449 for (Value *UnderlyingObj : TempObjects) {
450 UnderlyingObjToAccessMap::iterator Prev =
451 ObjToLastAccess.find(UnderlyingObj);
452 if (Prev != ObjToLastAccess.end())
453 DepCands.unionSets(Access, Prev->second);
454
455 ObjToLastAccess[UnderlyingObj] = Access;
456 }
457 }
458 }
459 }
460 }
461}
462
463namespace {
464/// \brief Checks memory dependences among accesses to the same underlying
465/// object to determine whether there vectorization is legal or not (and at
466/// which vectorization factor).
467///
468/// This class works under the assumption that we already checked that memory
469/// locations with different underlying pointers are "must-not alias".
470/// We use the ScalarEvolution framework to symbolically evalutate access
471/// functions pairs. Since we currently don't restructure the loop we can rely
472/// on the program order of memory accesses to determine their safety.
473/// At the moment we will only deem accesses as safe for:
474/// * A negative constant distance assuming program order.
475///
476/// Safe: tmp = a[i + 1]; OR a[i + 1] = x;
477/// a[i] = tmp; y = a[i];
478///
479/// The latter case is safe because later checks guarantuee that there can't
480/// be a cycle through a phi node (that is, we check that "x" and "y" is not
481/// the same variable: a header phi can only be an induction or a reduction, a
482/// reduction can't have a memory sink, an induction can't have a memory
483/// source). This is important and must not be violated (or we have to
484/// resort to checking for cycles through memory).
485///
486/// * A positive constant distance assuming program order that is bigger
487/// than the biggest memory access.
488///
489/// tmp = a[i] OR b[i] = x
490/// a[i+2] = tmp y = b[i+2];
491///
492/// Safe distance: 2 x sizeof(a[0]), and 2 x sizeof(b[0]), respectively.
493///
494/// * Zero distances and all accesses have the same size.
495///
496class MemoryDepChecker {
497public:
498 typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
499 typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
500
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000501 MemoryDepChecker(ScalarEvolution *Se, const Loop *L)
502 : SE(Se), InnermostLoop(L), AccessIdx(0),
Adam Nemetf219c642015-02-19 19:14:52 +0000503 ShouldRetryWithRuntimeCheck(false) {}
Adam Nemet04563272015-02-01 16:56:15 +0000504
505 /// \brief Register the location (instructions are given increasing numbers)
506 /// of a write access.
507 void addAccess(StoreInst *SI) {
508 Value *Ptr = SI->getPointerOperand();
509 Accesses[MemAccessInfo(Ptr, true)].push_back(AccessIdx);
510 InstMap.push_back(SI);
511 ++AccessIdx;
512 }
513
514 /// \brief Register the location (instructions are given increasing numbers)
515 /// of a write access.
516 void addAccess(LoadInst *LI) {
517 Value *Ptr = LI->getPointerOperand();
518 Accesses[MemAccessInfo(Ptr, false)].push_back(AccessIdx);
519 InstMap.push_back(LI);
520 ++AccessIdx;
521 }
522
523 /// \brief Check whether the dependencies between the accesses are safe.
524 ///
525 /// Only checks sets with elements in \p CheckDeps.
526 bool areDepsSafe(AccessAnalysis::DepCandidates &AccessSets,
Adam Nemet8bc61df2015-02-24 00:41:59 +0000527 MemAccessInfoSet &CheckDeps, const ValueToValueMap &Strides);
Adam Nemet04563272015-02-01 16:56:15 +0000528
529 /// \brief The maximum number of bytes of a vector register we can vectorize
530 /// the accesses safely with.
531 unsigned getMaxSafeDepDistBytes() { return MaxSafeDepDistBytes; }
532
533 /// \brief In same cases when the dependency check fails we can still
534 /// vectorize the loop with a dynamic array access check.
535 bool shouldRetryWithRuntimeCheck() { return ShouldRetryWithRuntimeCheck; }
536
537private:
538 ScalarEvolution *SE;
Adam Nemet04563272015-02-01 16:56:15 +0000539 const Loop *InnermostLoop;
540
541 /// \brief Maps access locations (ptr, read/write) to program order.
542 DenseMap<MemAccessInfo, std::vector<unsigned> > Accesses;
543
544 /// \brief Memory access instructions in program order.
545 SmallVector<Instruction *, 16> InstMap;
546
547 /// \brief The program order index to be used for the next instruction.
548 unsigned AccessIdx;
549
550 // We can access this many bytes in parallel safely.
551 unsigned MaxSafeDepDistBytes;
552
553 /// \brief If we see a non-constant dependence distance we can still try to
554 /// vectorize this loop with runtime checks.
555 bool ShouldRetryWithRuntimeCheck;
556
Adam Nemet04563272015-02-01 16:56:15 +0000557 /// \brief Check whether there is a plausible dependence between the two
558 /// accesses.
559 ///
560 /// Access \p A must happen before \p B in program order. The two indices
561 /// identify the index into the program order map.
562 ///
563 /// This function checks whether there is a plausible dependence (or the
564 /// absence of such can't be proved) between the two accesses. If there is a
565 /// plausible dependence but the dependence distance is bigger than one
566 /// element access it records this distance in \p MaxSafeDepDistBytes (if this
567 /// distance is smaller than any other distance encountered so far).
568 /// Otherwise, this function returns true signaling a possible dependence.
569 bool isDependent(const MemAccessInfo &A, unsigned AIdx,
570 const MemAccessInfo &B, unsigned BIdx,
Adam Nemet8bc61df2015-02-24 00:41:59 +0000571 const ValueToValueMap &Strides);
Adam Nemet04563272015-02-01 16:56:15 +0000572
573 /// \brief Check whether the data dependence could prevent store-load
574 /// forwarding.
575 bool couldPreventStoreLoadForward(unsigned Distance, unsigned TypeByteSize);
576};
577
578} // end anonymous namespace
579
580static bool isInBoundsGep(Value *Ptr) {
581 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
582 return GEP->isInBounds();
583 return false;
584}
585
586/// \brief Check whether the access through \p Ptr has a constant stride.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000587static int isStridedPtr(ScalarEvolution *SE, Value *Ptr, const Loop *Lp,
588 const ValueToValueMap &StridesMap) {
Adam Nemet04563272015-02-01 16:56:15 +0000589 const Type *Ty = Ptr->getType();
590 assert(Ty->isPointerTy() && "Unexpected non-ptr");
591
592 // Make sure that the pointer does not point to aggregate types.
593 const PointerType *PtrTy = cast<PointerType>(Ty);
594 if (PtrTy->getElementType()->isAggregateType()) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000595 DEBUG(dbgs() << "LAA: Bad stride - Not a pointer to a scalar type"
596 << *Ptr << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000597 return 0;
598 }
599
600 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, StridesMap, Ptr);
601
602 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
603 if (!AR) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000604 DEBUG(dbgs() << "LAA: Bad stride - Not an AddRecExpr pointer "
Adam Nemet04d41632015-02-19 19:14:34 +0000605 << *Ptr << " SCEV: " << *PtrScev << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000606 return 0;
607 }
608
609 // The accesss function must stride over the innermost loop.
610 if (Lp != AR->getLoop()) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000611 DEBUG(dbgs() << "LAA: Bad stride - Not striding over innermost loop " <<
Adam Nemet04d41632015-02-19 19:14:34 +0000612 *Ptr << " SCEV: " << *PtrScev << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000613 }
614
615 // The address calculation must not wrap. Otherwise, a dependence could be
616 // inverted.
617 // An inbounds getelementptr that is a AddRec with a unit stride
618 // cannot wrap per definition. The unit stride requirement is checked later.
619 // An getelementptr without an inbounds attribute and unit stride would have
620 // to access the pointer value "0" which is undefined behavior in address
621 // space 0, therefore we can also vectorize this case.
622 bool IsInBoundsGEP = isInBoundsGep(Ptr);
623 bool IsNoWrapAddRec = AR->getNoWrapFlags(SCEV::NoWrapMask);
624 bool IsInAddressSpaceZero = PtrTy->getAddressSpace() == 0;
625 if (!IsNoWrapAddRec && !IsInBoundsGEP && !IsInAddressSpaceZero) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000626 DEBUG(dbgs() << "LAA: Bad stride - Pointer may wrap in the address space "
Adam Nemet04d41632015-02-19 19:14:34 +0000627 << *Ptr << " SCEV: " << *PtrScev << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000628 return 0;
629 }
630
631 // Check the step is constant.
632 const SCEV *Step = AR->getStepRecurrence(*SE);
633
634 // Calculate the pointer stride and check if it is consecutive.
635 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
636 if (!C) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000637 DEBUG(dbgs() << "LAA: Bad stride - Not a constant strided " << *Ptr <<
Adam Nemet04d41632015-02-19 19:14:34 +0000638 " SCEV: " << *PtrScev << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000639 return 0;
640 }
641
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000642 auto &DL = Lp->getHeader()->getModule()->getDataLayout();
643 int64_t Size = DL.getTypeAllocSize(PtrTy->getElementType());
Adam Nemet04563272015-02-01 16:56:15 +0000644 const APInt &APStepVal = C->getValue()->getValue();
645
646 // Huge step value - give up.
647 if (APStepVal.getBitWidth() > 64)
648 return 0;
649
650 int64_t StepVal = APStepVal.getSExtValue();
651
652 // Strided access.
653 int64_t Stride = StepVal / Size;
654 int64_t Rem = StepVal % Size;
655 if (Rem)
656 return 0;
657
658 // If the SCEV could wrap but we have an inbounds gep with a unit stride we
659 // know we can't "wrap around the address space". In case of address space
660 // zero we know that this won't happen without triggering undefined behavior.
661 if (!IsNoWrapAddRec && (IsInBoundsGEP || IsInAddressSpaceZero) &&
662 Stride != 1 && Stride != -1)
663 return 0;
664
665 return Stride;
666}
667
668bool MemoryDepChecker::couldPreventStoreLoadForward(unsigned Distance,
669 unsigned TypeByteSize) {
670 // If loads occur at a distance that is not a multiple of a feasible vector
671 // factor store-load forwarding does not take place.
672 // Positive dependences might cause troubles because vectorizing them might
673 // prevent store-load forwarding making vectorized code run a lot slower.
674 // a[i] = a[i-3] ^ a[i-8];
675 // The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
676 // hence on your typical architecture store-load forwarding does not take
677 // place. Vectorizing in such cases does not make sense.
678 // Store-load forwarding distance.
679 const unsigned NumCyclesForStoreLoadThroughMemory = 8*TypeByteSize;
680 // Maximum vector factor.
Adam Nemetf219c642015-02-19 19:14:52 +0000681 unsigned MaxVFWithoutSLForwardIssues =
682 VectorizerParams::MaxVectorWidth * TypeByteSize;
Adam Nemet04d41632015-02-19 19:14:34 +0000683 if(MaxSafeDepDistBytes < MaxVFWithoutSLForwardIssues)
Adam Nemet04563272015-02-01 16:56:15 +0000684 MaxVFWithoutSLForwardIssues = MaxSafeDepDistBytes;
685
686 for (unsigned vf = 2*TypeByteSize; vf <= MaxVFWithoutSLForwardIssues;
687 vf *= 2) {
688 if (Distance % vf && Distance / vf < NumCyclesForStoreLoadThroughMemory) {
689 MaxVFWithoutSLForwardIssues = (vf >>=1);
690 break;
691 }
692 }
693
Adam Nemet04d41632015-02-19 19:14:34 +0000694 if (MaxVFWithoutSLForwardIssues< 2*TypeByteSize) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000695 DEBUG(dbgs() << "LAA: Distance " << Distance <<
Adam Nemet04d41632015-02-19 19:14:34 +0000696 " that could cause a store-load forwarding conflict\n");
Adam Nemet04563272015-02-01 16:56:15 +0000697 return true;
698 }
699
700 if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes &&
Adam Nemetf219c642015-02-19 19:14:52 +0000701 MaxVFWithoutSLForwardIssues !=
702 VectorizerParams::MaxVectorWidth * TypeByteSize)
Adam Nemet04563272015-02-01 16:56:15 +0000703 MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues;
704 return false;
705}
706
707bool MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
708 const MemAccessInfo &B, unsigned BIdx,
Adam Nemet8bc61df2015-02-24 00:41:59 +0000709 const ValueToValueMap &Strides) {
Adam Nemet04563272015-02-01 16:56:15 +0000710 assert (AIdx < BIdx && "Must pass arguments in program order");
711
712 Value *APtr = A.getPointer();
713 Value *BPtr = B.getPointer();
714 bool AIsWrite = A.getInt();
715 bool BIsWrite = B.getInt();
716
717 // Two reads are independent.
718 if (!AIsWrite && !BIsWrite)
719 return false;
720
721 // We cannot check pointers in different address spaces.
722 if (APtr->getType()->getPointerAddressSpace() !=
723 BPtr->getType()->getPointerAddressSpace())
724 return true;
725
726 const SCEV *AScev = replaceSymbolicStrideSCEV(SE, Strides, APtr);
727 const SCEV *BScev = replaceSymbolicStrideSCEV(SE, Strides, BPtr);
728
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000729 int StrideAPtr = isStridedPtr(SE, APtr, InnermostLoop, Strides);
730 int StrideBPtr = isStridedPtr(SE, BPtr, InnermostLoop, Strides);
Adam Nemet04563272015-02-01 16:56:15 +0000731
732 const SCEV *Src = AScev;
733 const SCEV *Sink = BScev;
734
735 // If the induction step is negative we have to invert source and sink of the
736 // dependence.
737 if (StrideAPtr < 0) {
738 //Src = BScev;
739 //Sink = AScev;
740 std::swap(APtr, BPtr);
741 std::swap(Src, Sink);
742 std::swap(AIsWrite, BIsWrite);
743 std::swap(AIdx, BIdx);
744 std::swap(StrideAPtr, StrideBPtr);
745 }
746
747 const SCEV *Dist = SE->getMinusSCEV(Sink, Src);
748
Adam Nemet339f42b2015-02-19 19:15:07 +0000749 DEBUG(dbgs() << "LAA: Src Scev: " << *Src << "Sink Scev: " << *Sink
Adam Nemet04d41632015-02-19 19:14:34 +0000750 << "(Induction step: " << StrideAPtr << ")\n");
Adam Nemet339f42b2015-02-19 19:15:07 +0000751 DEBUG(dbgs() << "LAA: Distance for " << *InstMap[AIdx] << " to "
Adam Nemet04d41632015-02-19 19:14:34 +0000752 << *InstMap[BIdx] << ": " << *Dist << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000753
754 // Need consecutive accesses. We don't want to vectorize
755 // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in
756 // the address space.
757 if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){
758 DEBUG(dbgs() << "Non-consecutive pointer access\n");
759 return true;
760 }
761
762 const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist);
763 if (!C) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000764 DEBUG(dbgs() << "LAA: Dependence because of non-constant distance\n");
Adam Nemet04563272015-02-01 16:56:15 +0000765 ShouldRetryWithRuntimeCheck = true;
766 return true;
767 }
768
769 Type *ATy = APtr->getType()->getPointerElementType();
770 Type *BTy = BPtr->getType()->getPointerElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000771 auto &DL = InnermostLoop->getHeader()->getModule()->getDataLayout();
772 unsigned TypeByteSize = DL.getTypeAllocSize(ATy);
Adam Nemet04563272015-02-01 16:56:15 +0000773
774 // Negative distances are not plausible dependencies.
775 const APInt &Val = C->getValue()->getValue();
776 if (Val.isNegative()) {
777 bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
778 if (IsTrueDataDependence &&
779 (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) ||
780 ATy != BTy))
781 return true;
782
Adam Nemet339f42b2015-02-19 19:15:07 +0000783 DEBUG(dbgs() << "LAA: Dependence is negative: NoDep\n");
Adam Nemet04563272015-02-01 16:56:15 +0000784 return false;
785 }
786
787 // Write to the same location with the same size.
788 // Could be improved to assert type sizes are the same (i32 == float, etc).
789 if (Val == 0) {
790 if (ATy == BTy)
791 return false;
Adam Nemet339f42b2015-02-19 19:15:07 +0000792 DEBUG(dbgs() << "LAA: Zero dependence difference but different types\n");
Adam Nemet04563272015-02-01 16:56:15 +0000793 return true;
794 }
795
796 assert(Val.isStrictlyPositive() && "Expect a positive value");
797
Adam Nemet04563272015-02-01 16:56:15 +0000798 if (ATy != BTy) {
Adam Nemet04d41632015-02-19 19:14:34 +0000799 DEBUG(dbgs() <<
Adam Nemet339f42b2015-02-19 19:15:07 +0000800 "LAA: ReadWrite-Write positive dependency with different types\n");
Adam Nemet9cc0c392015-02-26 17:58:48 +0000801 return true;
Adam Nemet04563272015-02-01 16:56:15 +0000802 }
803
804 unsigned Distance = (unsigned) Val.getZExtValue();
805
806 // Bail out early if passed-in parameters make vectorization not feasible.
Adam Nemetf219c642015-02-19 19:14:52 +0000807 unsigned ForcedFactor = (VectorizerParams::VectorizationFactor ?
808 VectorizerParams::VectorizationFactor : 1);
809 unsigned ForcedUnroll = (VectorizerParams::VectorizationInterleave ?
810 VectorizerParams::VectorizationInterleave : 1);
Adam Nemet04563272015-02-01 16:56:15 +0000811
812 // The distance must be bigger than the size needed for a vectorized version
813 // of the operation and the size of the vectorized operation must not be
814 // bigger than the currrent maximum size.
815 if (Distance < 2*TypeByteSize ||
816 2*TypeByteSize > MaxSafeDepDistBytes ||
817 Distance < TypeByteSize * ForcedUnroll * ForcedFactor) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000818 DEBUG(dbgs() << "LAA: Failure because of Positive distance "
Adam Nemet04d41632015-02-19 19:14:34 +0000819 << Val.getSExtValue() << '\n');
Adam Nemet04563272015-02-01 16:56:15 +0000820 return true;
821 }
822
Adam Nemet9cc0c392015-02-26 17:58:48 +0000823 // Positive distance bigger than max vectorization factor.
Adam Nemet04563272015-02-01 16:56:15 +0000824 MaxSafeDepDistBytes = Distance < MaxSafeDepDistBytes ?
825 Distance : MaxSafeDepDistBytes;
826
827 bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
828 if (IsTrueDataDependence &&
829 couldPreventStoreLoadForward(Distance, TypeByteSize))
830 return true;
831
Adam Nemet339f42b2015-02-19 19:15:07 +0000832 DEBUG(dbgs() << "LAA: Positive distance " << Val.getSExtValue() <<
Adam Nemet04d41632015-02-19 19:14:34 +0000833 " with max VF = " << MaxSafeDepDistBytes / TypeByteSize << '\n');
Adam Nemet04563272015-02-01 16:56:15 +0000834
835 return false;
836}
837
838bool MemoryDepChecker::areDepsSafe(AccessAnalysis::DepCandidates &AccessSets,
839 MemAccessInfoSet &CheckDeps,
Adam Nemet8bc61df2015-02-24 00:41:59 +0000840 const ValueToValueMap &Strides) {
Adam Nemet04563272015-02-01 16:56:15 +0000841
842 MaxSafeDepDistBytes = -1U;
843 while (!CheckDeps.empty()) {
844 MemAccessInfo CurAccess = *CheckDeps.begin();
845
846 // Get the relevant memory access set.
847 EquivalenceClasses<MemAccessInfo>::iterator I =
848 AccessSets.findValue(AccessSets.getLeaderValue(CurAccess));
849
850 // Check accesses within this set.
851 EquivalenceClasses<MemAccessInfo>::member_iterator AI, AE;
852 AI = AccessSets.member_begin(I), AE = AccessSets.member_end();
853
854 // Check every access pair.
855 while (AI != AE) {
856 CheckDeps.erase(*AI);
857 EquivalenceClasses<MemAccessInfo>::member_iterator OI = std::next(AI);
858 while (OI != AE) {
859 // Check every accessing instruction pair in program order.
860 for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(),
861 I1E = Accesses[*AI].end(); I1 != I1E; ++I1)
862 for (std::vector<unsigned>::iterator I2 = Accesses[*OI].begin(),
863 I2E = Accesses[*OI].end(); I2 != I2E; ++I2) {
864 if (*I1 < *I2 && isDependent(*AI, *I1, *OI, *I2, Strides))
865 return false;
866 if (*I2 < *I1 && isDependent(*OI, *I2, *AI, *I1, Strides))
867 return false;
868 }
869 ++OI;
870 }
871 AI++;
872 }
873 }
874 return true;
875}
876
Adam Nemet929c38e2015-02-19 19:15:10 +0000877bool LoopAccessInfo::canAnalyzeLoop() {
878 // We can only analyze innermost loops.
879 if (!TheLoop->empty()) {
Adam Nemet2bd6e982015-02-19 19:15:15 +0000880 emitAnalysis(LoopAccessReport() << "loop is not the innermost loop");
Adam Nemet929c38e2015-02-19 19:15:10 +0000881 return false;
882 }
883
884 // We must have a single backedge.
885 if (TheLoop->getNumBackEdges() != 1) {
886 emitAnalysis(
Adam Nemet2bd6e982015-02-19 19:15:15 +0000887 LoopAccessReport() <<
Adam Nemet929c38e2015-02-19 19:15:10 +0000888 "loop control flow is not understood by analyzer");
889 return false;
890 }
891
892 // We must have a single exiting block.
893 if (!TheLoop->getExitingBlock()) {
894 emitAnalysis(
Adam Nemet2bd6e982015-02-19 19:15:15 +0000895 LoopAccessReport() <<
Adam Nemet929c38e2015-02-19 19:15:10 +0000896 "loop control flow is not understood by analyzer");
897 return false;
898 }
899
900 // We only handle bottom-tested loops, i.e. loop in which the condition is
901 // checked at the end of each iteration. With that we can assume that all
902 // instructions in the loop are executed the same number of times.
903 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
904 emitAnalysis(
Adam Nemet2bd6e982015-02-19 19:15:15 +0000905 LoopAccessReport() <<
Adam Nemet929c38e2015-02-19 19:15:10 +0000906 "loop control flow is not understood by analyzer");
907 return false;
908 }
909
910 // We need to have a loop header.
911 DEBUG(dbgs() << "LAA: Found a loop: " <<
912 TheLoop->getHeader()->getName() << '\n');
913
914 // ScalarEvolution needs to be able to find the exit count.
915 const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop);
916 if (ExitCount == SE->getCouldNotCompute()) {
Adam Nemet2bd6e982015-02-19 19:15:15 +0000917 emitAnalysis(LoopAccessReport() <<
Adam Nemet929c38e2015-02-19 19:15:10 +0000918 "could not determine number of loop iterations");
919 DEBUG(dbgs() << "LAA: SCEV could not compute the loop exit count.\n");
920 return false;
921 }
922
923 return true;
924}
925
Adam Nemet8bc61df2015-02-24 00:41:59 +0000926void LoopAccessInfo::analyzeLoop(const ValueToValueMap &Strides) {
Adam Nemet04563272015-02-01 16:56:15 +0000927
928 typedef SmallVector<Value*, 16> ValueVector;
929 typedef SmallPtrSet<Value*, 16> ValueSet;
930
931 // Holds the Load and Store *instructions*.
932 ValueVector Loads;
933 ValueVector Stores;
934
935 // Holds all the different accesses in the loop.
936 unsigned NumReads = 0;
937 unsigned NumReadWrites = 0;
938
939 PtrRtCheck.Pointers.clear();
940 PtrRtCheck.Need = false;
941
942 const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000943 MemoryDepChecker DepChecker(SE, TheLoop);
Adam Nemet04563272015-02-01 16:56:15 +0000944
945 // For each block.
946 for (Loop::block_iterator bb = TheLoop->block_begin(),
947 be = TheLoop->block_end(); bb != be; ++bb) {
948
949 // Scan the BB and collect legal loads and stores.
950 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
951 ++it) {
952
953 // If this is a load, save it. If this instruction can read from memory
954 // but is not a load, then we quit. Notice that we don't handle function
955 // calls that read or write.
956 if (it->mayReadFromMemory()) {
957 // Many math library functions read the rounding mode. We will only
958 // vectorize a loop if it contains known function calls that don't set
959 // the flag. Therefore, it is safe to ignore this read from memory.
960 CallInst *Call = dyn_cast<CallInst>(it);
961 if (Call && getIntrinsicIDForCall(Call, TLI))
962 continue;
963
964 LoadInst *Ld = dyn_cast<LoadInst>(it);
965 if (!Ld || (!Ld->isSimple() && !IsAnnotatedParallel)) {
Adam Nemet2bd6e982015-02-19 19:15:15 +0000966 emitAnalysis(LoopAccessReport(Ld)
Adam Nemet04563272015-02-01 16:56:15 +0000967 << "read with atomic ordering or volatile read");
Adam Nemet339f42b2015-02-19 19:15:07 +0000968 DEBUG(dbgs() << "LAA: Found a non-simple load.\n");
Adam Nemet436018c2015-02-19 19:15:00 +0000969 CanVecMem = false;
970 return;
Adam Nemet04563272015-02-01 16:56:15 +0000971 }
972 NumLoads++;
973 Loads.push_back(Ld);
974 DepChecker.addAccess(Ld);
975 continue;
976 }
977
978 // Save 'store' instructions. Abort if other instructions write to memory.
979 if (it->mayWriteToMemory()) {
980 StoreInst *St = dyn_cast<StoreInst>(it);
981 if (!St) {
Adam Nemet2bd6e982015-02-19 19:15:15 +0000982 emitAnalysis(LoopAccessReport(it) <<
Adam Nemet04d41632015-02-19 19:14:34 +0000983 "instruction cannot be vectorized");
Adam Nemet436018c2015-02-19 19:15:00 +0000984 CanVecMem = false;
985 return;
Adam Nemet04563272015-02-01 16:56:15 +0000986 }
987 if (!St->isSimple() && !IsAnnotatedParallel) {
Adam Nemet2bd6e982015-02-19 19:15:15 +0000988 emitAnalysis(LoopAccessReport(St)
Adam Nemet04563272015-02-01 16:56:15 +0000989 << "write with atomic ordering or volatile write");
Adam Nemet339f42b2015-02-19 19:15:07 +0000990 DEBUG(dbgs() << "LAA: Found a non-simple store.\n");
Adam Nemet436018c2015-02-19 19:15:00 +0000991 CanVecMem = false;
992 return;
Adam Nemet04563272015-02-01 16:56:15 +0000993 }
994 NumStores++;
995 Stores.push_back(St);
996 DepChecker.addAccess(St);
997 }
998 } // Next instr.
999 } // Next block.
1000
1001 // Now we have two lists that hold the loads and the stores.
1002 // Next, we find the pointers that they use.
1003
1004 // Check if we see any stores. If there are no stores, then we don't
1005 // care if the pointers are *restrict*.
1006 if (!Stores.size()) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001007 DEBUG(dbgs() << "LAA: Found a read-only loop!\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001008 CanVecMem = true;
1009 return;
Adam Nemet04563272015-02-01 16:56:15 +00001010 }
1011
1012 AccessAnalysis::DepCandidates DependentAccesses;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001013 AccessAnalysis Accesses(TheLoop->getHeader()->getModule()->getDataLayout(),
1014 AA, DependentAccesses);
Adam Nemet04563272015-02-01 16:56:15 +00001015
1016 // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
1017 // multiple times on the same object. If the ptr is accessed twice, once
1018 // for read and once for write, it will only appear once (on the write
1019 // list). This is okay, since we are going to check for conflicts between
1020 // writes and between reads and writes, but not between reads and reads.
1021 ValueSet Seen;
1022
1023 ValueVector::iterator I, IE;
1024 for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
1025 StoreInst *ST = cast<StoreInst>(*I);
1026 Value* Ptr = ST->getPointerOperand();
1027
1028 if (isUniform(Ptr)) {
1029 emitAnalysis(
Adam Nemet2bd6e982015-02-19 19:15:15 +00001030 LoopAccessReport(ST)
Adam Nemet04563272015-02-01 16:56:15 +00001031 << "write to a loop invariant address could not be vectorized");
Adam Nemet339f42b2015-02-19 19:15:07 +00001032 DEBUG(dbgs() << "LAA: We don't allow storing to uniform addresses\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001033 CanVecMem = false;
1034 return;
Adam Nemet04563272015-02-01 16:56:15 +00001035 }
1036
1037 // If we did *not* see this pointer before, insert it to the read-write
1038 // list. At this phase it is only a 'write' list.
1039 if (Seen.insert(Ptr).second) {
1040 ++NumReadWrites;
1041
1042 AliasAnalysis::Location Loc = AA->getLocation(ST);
1043 // The TBAA metadata could have a control dependency on the predication
1044 // condition, so we cannot rely on it when determining whether or not we
1045 // need runtime pointer checks.
Adam Nemet01abb2c2015-02-18 03:43:19 +00001046 if (blockNeedsPredication(ST->getParent(), TheLoop, DT))
Adam Nemet04563272015-02-01 16:56:15 +00001047 Loc.AATags.TBAA = nullptr;
1048
1049 Accesses.addStore(Loc);
1050 }
1051 }
1052
1053 if (IsAnnotatedParallel) {
Adam Nemet04d41632015-02-19 19:14:34 +00001054 DEBUG(dbgs()
Adam Nemet339f42b2015-02-19 19:15:07 +00001055 << "LAA: A loop annotated parallel, ignore memory dependency "
Adam Nemet04d41632015-02-19 19:14:34 +00001056 << "checks.\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001057 CanVecMem = true;
1058 return;
Adam Nemet04563272015-02-01 16:56:15 +00001059 }
1060
1061 for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
1062 LoadInst *LD = cast<LoadInst>(*I);
1063 Value* Ptr = LD->getPointerOperand();
1064 // If we did *not* see this pointer before, insert it to the
1065 // read list. If we *did* see it before, then it is already in
1066 // the read-write list. This allows us to vectorize expressions
1067 // such as A[i] += x; Because the address of A[i] is a read-write
1068 // pointer. This only works if the index of A[i] is consecutive.
1069 // If the address of i is unknown (for example A[B[i]]) then we may
1070 // read a few words, modify, and write a few words, and some of the
1071 // words may be written to the same address.
1072 bool IsReadOnlyPtr = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001073 if (Seen.insert(Ptr).second || !isStridedPtr(SE, Ptr, TheLoop, Strides)) {
Adam Nemet04563272015-02-01 16:56:15 +00001074 ++NumReads;
1075 IsReadOnlyPtr = true;
1076 }
1077
1078 AliasAnalysis::Location Loc = AA->getLocation(LD);
1079 // The TBAA metadata could have a control dependency on the predication
1080 // condition, so we cannot rely on it when determining whether or not we
1081 // need runtime pointer checks.
Adam Nemet01abb2c2015-02-18 03:43:19 +00001082 if (blockNeedsPredication(LD->getParent(), TheLoop, DT))
Adam Nemet04563272015-02-01 16:56:15 +00001083 Loc.AATags.TBAA = nullptr;
1084
1085 Accesses.addLoad(Loc, IsReadOnlyPtr);
1086 }
1087
1088 // If we write (or read-write) to a single destination and there are no
1089 // other reads in this loop then is it safe to vectorize.
1090 if (NumReadWrites == 1 && NumReads == 0) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001091 DEBUG(dbgs() << "LAA: Found a write-only loop!\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001092 CanVecMem = true;
1093 return;
Adam Nemet04563272015-02-01 16:56:15 +00001094 }
1095
1096 // Build dependence sets and check whether we need a runtime pointer bounds
1097 // check.
1098 Accesses.buildDependenceSets();
1099 bool NeedRTCheck = Accesses.isRTCheckNeeded();
1100
1101 // Find pointers with computable bounds. We are going to use this information
1102 // to place a runtime bound check.
1103 unsigned NumComparisons = 0;
1104 bool CanDoRT = false;
1105 if (NeedRTCheck)
1106 CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE, TheLoop,
1107 Strides);
1108
Adam Nemet339f42b2015-02-19 19:15:07 +00001109 DEBUG(dbgs() << "LAA: We need to do " << NumComparisons <<
Adam Nemet04d41632015-02-19 19:14:34 +00001110 " pointer comparisons.\n");
Adam Nemet04563272015-02-01 16:56:15 +00001111
1112 // If we only have one set of dependences to check pointers among we don't
1113 // need a runtime check.
1114 if (NumComparisons == 0 && NeedRTCheck)
1115 NeedRTCheck = false;
1116
1117 // Check that we did not collect too many pointers or found an unsizeable
1118 // pointer.
Adam Nemet1d862af2015-02-26 04:39:09 +00001119 if (!CanDoRT || NumComparisons > RuntimeMemoryCheckThreshold) {
Adam Nemet04563272015-02-01 16:56:15 +00001120 PtrRtCheck.reset();
1121 CanDoRT = false;
1122 }
1123
1124 if (CanDoRT) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001125 DEBUG(dbgs() << "LAA: We can perform a memory runtime check if needed.\n");
Adam Nemet04563272015-02-01 16:56:15 +00001126 }
1127
1128 if (NeedRTCheck && !CanDoRT) {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001129 emitAnalysis(LoopAccessReport() << "cannot identify array bounds");
Adam Nemet339f42b2015-02-19 19:15:07 +00001130 DEBUG(dbgs() << "LAA: We can't vectorize because we can't find " <<
Adam Nemet04d41632015-02-19 19:14:34 +00001131 "the array bounds.\n");
Adam Nemet04563272015-02-01 16:56:15 +00001132 PtrRtCheck.reset();
Adam Nemet436018c2015-02-19 19:15:00 +00001133 CanVecMem = false;
1134 return;
Adam Nemet04563272015-02-01 16:56:15 +00001135 }
1136
1137 PtrRtCheck.Need = NeedRTCheck;
1138
Adam Nemet436018c2015-02-19 19:15:00 +00001139 CanVecMem = true;
Adam Nemet04563272015-02-01 16:56:15 +00001140 if (Accesses.isDependencyCheckNeeded()) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001141 DEBUG(dbgs() << "LAA: Checking memory dependencies\n");
Adam Nemet04563272015-02-01 16:56:15 +00001142 CanVecMem = DepChecker.areDepsSafe(
1143 DependentAccesses, Accesses.getDependenciesToCheck(), Strides);
1144 MaxSafeDepDistBytes = DepChecker.getMaxSafeDepDistBytes();
1145
1146 if (!CanVecMem && DepChecker.shouldRetryWithRuntimeCheck()) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001147 DEBUG(dbgs() << "LAA: Retrying with memory checks\n");
Adam Nemet04563272015-02-01 16:56:15 +00001148 NeedRTCheck = true;
1149
1150 // Clear the dependency checks. We assume they are not needed.
1151 Accesses.resetDepChecks();
1152
1153 PtrRtCheck.reset();
1154 PtrRtCheck.Need = true;
1155
1156 CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE,
1157 TheLoop, Strides, true);
1158 // Check that we did not collect too many pointers or found an unsizeable
1159 // pointer.
Adam Nemet1d862af2015-02-26 04:39:09 +00001160 if (!CanDoRT || NumComparisons > RuntimeMemoryCheckThreshold) {
Adam Nemet04563272015-02-01 16:56:15 +00001161 if (!CanDoRT && NumComparisons > 0)
Adam Nemet2bd6e982015-02-19 19:15:15 +00001162 emitAnalysis(LoopAccessReport()
Adam Nemet04563272015-02-01 16:56:15 +00001163 << "cannot check memory dependencies at runtime");
1164 else
Adam Nemet2bd6e982015-02-19 19:15:15 +00001165 emitAnalysis(LoopAccessReport()
Adam Nemet04563272015-02-01 16:56:15 +00001166 << NumComparisons << " exceeds limit of "
Adam Nemet1d862af2015-02-26 04:39:09 +00001167 << RuntimeMemoryCheckThreshold
Adam Nemet04563272015-02-01 16:56:15 +00001168 << " dependent memory operations checked at runtime");
Adam Nemet339f42b2015-02-19 19:15:07 +00001169 DEBUG(dbgs() << "LAA: Can't vectorize with memory checks\n");
Adam Nemet04563272015-02-01 16:56:15 +00001170 PtrRtCheck.reset();
Adam Nemet436018c2015-02-19 19:15:00 +00001171 CanVecMem = false;
1172 return;
Adam Nemet04563272015-02-01 16:56:15 +00001173 }
1174
1175 CanVecMem = true;
1176 }
1177 }
1178
1179 if (!CanVecMem)
Adam Nemet2bd6e982015-02-19 19:15:15 +00001180 emitAnalysis(LoopAccessReport() <<
Adam Nemet04d41632015-02-19 19:14:34 +00001181 "unsafe dependent memory operations in loop");
Adam Nemet04563272015-02-01 16:56:15 +00001182
Adam Nemet339f42b2015-02-19 19:15:07 +00001183 DEBUG(dbgs() << "LAA: We" << (NeedRTCheck ? "" : " don't") <<
Adam Nemet04d41632015-02-19 19:14:34 +00001184 " need a runtime memory check.\n");
Adam Nemet04563272015-02-01 16:56:15 +00001185}
1186
Adam Nemet01abb2c2015-02-18 03:43:19 +00001187bool LoopAccessInfo::blockNeedsPredication(BasicBlock *BB, Loop *TheLoop,
1188 DominatorTree *DT) {
Adam Nemet04563272015-02-01 16:56:15 +00001189 assert(TheLoop->contains(BB) && "Unknown block used");
1190
1191 // Blocks that do not dominate the latch need predication.
1192 BasicBlock* Latch = TheLoop->getLoopLatch();
1193 return !DT->dominates(BB, Latch);
1194}
1195
Adam Nemet2bd6e982015-02-19 19:15:15 +00001196void LoopAccessInfo::emitAnalysis(LoopAccessReport &Message) {
Adam Nemetc9228532015-02-19 19:14:56 +00001197 assert(!Report && "Multiple reports generated");
1198 Report = Message;
Adam Nemet04563272015-02-01 16:56:15 +00001199}
1200
Adam Nemet57ac7662015-02-19 19:15:21 +00001201bool LoopAccessInfo::isUniform(Value *V) const {
Adam Nemet04563272015-02-01 16:56:15 +00001202 return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
1203}
Adam Nemet7206d7a2015-02-06 18:31:04 +00001204
1205// FIXME: this function is currently a duplicate of the one in
1206// LoopVectorize.cpp.
1207static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
1208 Instruction *Loc) {
1209 if (FirstInst)
1210 return FirstInst;
1211 if (Instruction *I = dyn_cast<Instruction>(V))
1212 return I->getParent() == Loc->getParent() ? I : nullptr;
1213 return nullptr;
1214}
1215
1216std::pair<Instruction *, Instruction *>
Adam Nemet57ac7662015-02-19 19:15:21 +00001217LoopAccessInfo::addRuntimeCheck(Instruction *Loc) const {
Adam Nemet7206d7a2015-02-06 18:31:04 +00001218 Instruction *tnullptr = nullptr;
1219 if (!PtrRtCheck.Need)
1220 return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr);
1221
1222 unsigned NumPointers = PtrRtCheck.Pointers.size();
1223 SmallVector<TrackingVH<Value> , 2> Starts;
1224 SmallVector<TrackingVH<Value> , 2> Ends;
1225
1226 LLVMContext &Ctx = Loc->getContext();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001227 SCEVExpander Exp(*SE, DL, "induction");
Adam Nemet7206d7a2015-02-06 18:31:04 +00001228 Instruction *FirstInst = nullptr;
1229
1230 for (unsigned i = 0; i < NumPointers; ++i) {
1231 Value *Ptr = PtrRtCheck.Pointers[i];
1232 const SCEV *Sc = SE->getSCEV(Ptr);
1233
1234 if (SE->isLoopInvariant(Sc, TheLoop)) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001235 DEBUG(dbgs() << "LAA: Adding RT check for a loop invariant ptr:" <<
Adam Nemet04d41632015-02-19 19:14:34 +00001236 *Ptr <<"\n");
Adam Nemet7206d7a2015-02-06 18:31:04 +00001237 Starts.push_back(Ptr);
1238 Ends.push_back(Ptr);
1239 } else {
Adam Nemet339f42b2015-02-19 19:15:07 +00001240 DEBUG(dbgs() << "LAA: Adding RT check for range:" << *Ptr << '\n');
Adam Nemet7206d7a2015-02-06 18:31:04 +00001241 unsigned AS = Ptr->getType()->getPointerAddressSpace();
1242
1243 // Use this type for pointer arithmetic.
1244 Type *PtrArithTy = Type::getInt8PtrTy(Ctx, AS);
1245
1246 Value *Start = Exp.expandCodeFor(PtrRtCheck.Starts[i], PtrArithTy, Loc);
1247 Value *End = Exp.expandCodeFor(PtrRtCheck.Ends[i], PtrArithTy, Loc);
1248 Starts.push_back(Start);
1249 Ends.push_back(End);
1250 }
1251 }
1252
1253 IRBuilder<> ChkBuilder(Loc);
1254 // Our instructions might fold to a constant.
1255 Value *MemoryRuntimeCheck = nullptr;
1256 for (unsigned i = 0; i < NumPointers; ++i) {
1257 for (unsigned j = i+1; j < NumPointers; ++j) {
Adam Nemeta8945b72015-02-18 03:43:58 +00001258 if (!PtrRtCheck.needsChecking(i, j))
Adam Nemet7206d7a2015-02-06 18:31:04 +00001259 continue;
1260
1261 unsigned AS0 = Starts[i]->getType()->getPointerAddressSpace();
1262 unsigned AS1 = Starts[j]->getType()->getPointerAddressSpace();
1263
1264 assert((AS0 == Ends[j]->getType()->getPointerAddressSpace()) &&
1265 (AS1 == Ends[i]->getType()->getPointerAddressSpace()) &&
1266 "Trying to bounds check pointers with different address spaces");
1267
1268 Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0);
1269 Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1);
1270
1271 Value *Start0 = ChkBuilder.CreateBitCast(Starts[i], PtrArithTy0, "bc");
1272 Value *Start1 = ChkBuilder.CreateBitCast(Starts[j], PtrArithTy1, "bc");
1273 Value *End0 = ChkBuilder.CreateBitCast(Ends[i], PtrArithTy1, "bc");
1274 Value *End1 = ChkBuilder.CreateBitCast(Ends[j], PtrArithTy0, "bc");
1275
1276 Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0");
1277 FirstInst = getFirstInst(FirstInst, Cmp0, Loc);
1278 Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1");
1279 FirstInst = getFirstInst(FirstInst, Cmp1, Loc);
1280 Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
1281 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1282 if (MemoryRuntimeCheck) {
1283 IsConflict = ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict,
1284 "conflict.rdx");
1285 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1286 }
1287 MemoryRuntimeCheck = IsConflict;
1288 }
1289 }
1290
1291 // We have to do this trickery because the IRBuilder might fold the check to a
1292 // constant expression in which case there is no Instruction anchored in a
1293 // the block.
1294 Instruction *Check = BinaryOperator::CreateAnd(MemoryRuntimeCheck,
1295 ConstantInt::getTrue(Ctx));
1296 ChkBuilder.Insert(Check, "memcheck.conflict");
1297 FirstInst = getFirstInst(FirstInst, Check, Loc);
1298 return std::make_pair(FirstInst, Check);
1299}
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001300
1301LoopAccessInfo::LoopAccessInfo(Loop *L, ScalarEvolution *SE,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001302 const DataLayout &DL,
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001303 const TargetLibraryInfo *TLI, AliasAnalysis *AA,
Adam Nemet8bc61df2015-02-24 00:41:59 +00001304 DominatorTree *DT,
1305 const ValueToValueMap &Strides)
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001306 : TheLoop(L), SE(SE), DL(DL), TLI(TLI), AA(AA), DT(DT), NumLoads(0),
1307 NumStores(0), MaxSafeDepDistBytes(-1U), CanVecMem(false) {
Adam Nemet929c38e2015-02-19 19:15:10 +00001308 if (canAnalyzeLoop())
1309 analyzeLoop(Strides);
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001310}
1311
Adam Nemete91cc6e2015-02-19 19:15:19 +00001312void LoopAccessInfo::print(raw_ostream &OS, unsigned Depth) const {
1313 if (CanVecMem) {
1314 if (PtrRtCheck.empty())
1315 OS.indent(Depth) << "Memory dependences are safe\n";
1316 else
1317 OS.indent(Depth) << "Memory dependences are safe with run-time checks\n";
1318 }
1319
1320 if (Report)
1321 OS.indent(Depth) << "Report: " << Report->str() << "\n";
1322
1323 // FIXME: Print unsafe dependences
1324
1325 // List the pair of accesses need run-time checks to prove independence.
1326 PtrRtCheck.print(OS, Depth);
1327 OS << "\n";
1328}
1329
Adam Nemet8bc61df2015-02-24 00:41:59 +00001330const LoopAccessInfo &
1331LoopAccessAnalysis::getInfo(Loop *L, const ValueToValueMap &Strides) {
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001332 auto &LAI = LoopAccessInfoMap[L];
1333
1334#ifndef NDEBUG
1335 assert((!LAI || LAI->NumSymbolicStrides == Strides.size()) &&
1336 "Symbolic strides changed for loop");
1337#endif
1338
1339 if (!LAI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001340 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001341 LAI = llvm::make_unique<LoopAccessInfo>(L, SE, DL, TLI, AA, DT, Strides);
1342#ifndef NDEBUG
1343 LAI->NumSymbolicStrides = Strides.size();
1344#endif
1345 }
1346 return *LAI.get();
1347}
1348
Adam Nemete91cc6e2015-02-19 19:15:19 +00001349void LoopAccessAnalysis::print(raw_ostream &OS, const Module *M) const {
1350 LoopAccessAnalysis &LAA = *const_cast<LoopAccessAnalysis *>(this);
1351
1352 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1353 ValueToValueMap NoSymbolicStrides;
1354
1355 for (Loop *TopLevelLoop : *LI)
1356 for (Loop *L : depth_first(TopLevelLoop)) {
1357 OS.indent(2) << L->getHeader()->getName() << ":\n";
1358 auto &LAI = LAA.getInfo(L, NoSymbolicStrides);
1359 LAI.print(OS, 4);
1360 }
1361}
1362
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001363bool LoopAccessAnalysis::runOnFunction(Function &F) {
1364 SE = &getAnalysis<ScalarEvolution>();
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001365 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
1366 TLI = TLIP ? &TLIP->getTLI() : nullptr;
1367 AA = &getAnalysis<AliasAnalysis>();
1368 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1369
1370 return false;
1371}
1372
1373void LoopAccessAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
1374 AU.addRequired<ScalarEvolution>();
1375 AU.addRequired<AliasAnalysis>();
1376 AU.addRequired<DominatorTreeWrapperPass>();
Adam Nemete91cc6e2015-02-19 19:15:19 +00001377 AU.addRequired<LoopInfoWrapperPass>();
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001378
1379 AU.setPreservesAll();
1380}
1381
1382char LoopAccessAnalysis::ID = 0;
1383static const char laa_name[] = "Loop Access Analysis";
1384#define LAA_NAME "loop-accesses"
1385
1386INITIALIZE_PASS_BEGIN(LoopAccessAnalysis, LAA_NAME, laa_name, false, true)
1387INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
1388INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
1389INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Adam Nemete91cc6e2015-02-19 19:15:19 +00001390INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001391INITIALIZE_PASS_END(LoopAccessAnalysis, LAA_NAME, laa_name, false, true)
1392
1393namespace llvm {
1394 Pass *createLAAPass() {
1395 return new LoopAccessAnalysis();
1396 }
1397}