blob: cd94583c9e2cd78aced5612eb09a7c1f1ec3960d [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"
Benjamin Kramer799003b2015-03-23 19:32:43 +000018#include "llvm/Analysis/TargetLibraryInfo.h"
Adam Nemet04563272015-02-01 16:56:15 +000019#include "llvm/Analysis/ValueTracking.h"
20#include "llvm/IR/DiagnosticInfo.h"
21#include "llvm/IR/Dominators.h"
Adam Nemet7206d7a2015-02-06 18:31:04 +000022#include "llvm/IR/IRBuilder.h"
Adam Nemet04563272015-02-01 16:56:15 +000023#include "llvm/Support/Debug.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000024#include "llvm/Support/raw_ostream.h"
Adam Nemet04563272015-02-01 16:56:15 +000025#include "llvm/Transforms/Utils/VectorUtils.h"
26using namespace llvm;
27
Adam Nemet339f42b2015-02-19 19:15:07 +000028#define DEBUG_TYPE "loop-accesses"
Adam Nemet04563272015-02-01 16:56:15 +000029
Adam Nemetf219c642015-02-19 19:14:52 +000030static cl::opt<unsigned, true>
31VectorizationFactor("force-vector-width", cl::Hidden,
32 cl::desc("Sets the SIMD width. Zero is autoselect."),
33 cl::location(VectorizerParams::VectorizationFactor));
Adam Nemet1d862af2015-02-26 04:39:09 +000034unsigned VectorizerParams::VectorizationFactor;
Adam Nemetf219c642015-02-19 19:14:52 +000035
36static cl::opt<unsigned, true>
37VectorizationInterleave("force-vector-interleave", cl::Hidden,
38 cl::desc("Sets the vectorization interleave count. "
39 "Zero is autoselect."),
40 cl::location(
41 VectorizerParams::VectorizationInterleave));
Adam Nemet1d862af2015-02-26 04:39:09 +000042unsigned VectorizerParams::VectorizationInterleave;
Adam Nemetf219c642015-02-19 19:14:52 +000043
Adam Nemet1d862af2015-02-26 04:39:09 +000044static cl::opt<unsigned, true> RuntimeMemoryCheckThreshold(
45 "runtime-memory-check-threshold", cl::Hidden,
46 cl::desc("When performing memory disambiguation checks at runtime do not "
47 "generate more than this number of comparisons (default = 8)."),
48 cl::location(VectorizerParams::RuntimeMemoryCheckThreshold), cl::init(8));
49unsigned VectorizerParams::RuntimeMemoryCheckThreshold;
Adam Nemetf219c642015-02-19 19:14:52 +000050
51/// Maximum SIMD width.
52const unsigned VectorizerParams::MaxVectorWidth = 64;
53
Adam Nemet9c926572015-03-10 17:40:37 +000054/// \brief We collect interesting dependences up to this threshold.
55static cl::opt<unsigned> MaxInterestingDependence(
56 "max-interesting-dependences", cl::Hidden,
57 cl::desc("Maximum number of interesting dependences collected by "
58 "loop-access analysis (default = 100)"),
59 cl::init(100));
60
Adam Nemetf219c642015-02-19 19:14:52 +000061bool VectorizerParams::isInterleaveForced() {
62 return ::VectorizationInterleave.getNumOccurrences() > 0;
63}
64
Adam Nemet2bd6e982015-02-19 19:15:15 +000065void LoopAccessReport::emitAnalysis(const LoopAccessReport &Message,
66 const Function *TheFunction,
67 const Loop *TheLoop,
68 const char *PassName) {
Adam Nemet04563272015-02-01 16:56:15 +000069 DebugLoc DL = TheLoop->getStartLoc();
Adam Nemet3e876342015-02-19 19:15:13 +000070 if (const Instruction *I = Message.getInstr())
Adam Nemet04563272015-02-01 16:56:15 +000071 DL = I->getDebugLoc();
Adam Nemet339f42b2015-02-19 19:15:07 +000072 emitOptimizationRemarkAnalysis(TheFunction->getContext(), PassName,
Adam Nemet04563272015-02-01 16:56:15 +000073 *TheFunction, DL, Message.str());
74}
75
76Value *llvm::stripIntegerCast(Value *V) {
77 if (CastInst *CI = dyn_cast<CastInst>(V))
78 if (CI->getOperand(0)->getType()->isIntegerTy())
79 return CI->getOperand(0);
80 return V;
81}
82
83const SCEV *llvm::replaceSymbolicStrideSCEV(ScalarEvolution *SE,
Adam Nemet8bc61df2015-02-24 00:41:59 +000084 const ValueToValueMap &PtrToStride,
Adam Nemet04563272015-02-01 16:56:15 +000085 Value *Ptr, Value *OrigPtr) {
86
87 const SCEV *OrigSCEV = SE->getSCEV(Ptr);
88
89 // If there is an entry in the map return the SCEV of the pointer with the
90 // symbolic stride replaced by one.
Adam Nemet8bc61df2015-02-24 00:41:59 +000091 ValueToValueMap::const_iterator SI =
92 PtrToStride.find(OrigPtr ? OrigPtr : Ptr);
Adam Nemet04563272015-02-01 16:56:15 +000093 if (SI != PtrToStride.end()) {
94 Value *StrideVal = SI->second;
95
96 // Strip casts.
97 StrideVal = stripIntegerCast(StrideVal);
98
99 // Replace symbolic stride by one.
100 Value *One = ConstantInt::get(StrideVal->getType(), 1);
101 ValueToValueMap RewriteMap;
102 RewriteMap[StrideVal] = One;
103
104 const SCEV *ByOne =
105 SCEVParameterRewriter::rewrite(OrigSCEV, *SE, RewriteMap, true);
Adam Nemet339f42b2015-02-19 19:15:07 +0000106 DEBUG(dbgs() << "LAA: Replacing SCEV: " << *OrigSCEV << " by: " << *ByOne
Adam Nemet04563272015-02-01 16:56:15 +0000107 << "\n");
108 return ByOne;
109 }
110
111 // Otherwise, just return the SCEV of the original pointer.
112 return SE->getSCEV(Ptr);
113}
114
Adam Nemet8bc61df2015-02-24 00:41:59 +0000115void LoopAccessInfo::RuntimePointerCheck::insert(
116 ScalarEvolution *SE, Loop *Lp, Value *Ptr, bool WritePtr, unsigned DepSetId,
117 unsigned ASId, const ValueToValueMap &Strides) {
Adam Nemet04563272015-02-01 16:56:15 +0000118 // Get the stride replaced scev.
119 const SCEV *Sc = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
120 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
121 assert(AR && "Invalid addrec expression");
122 const SCEV *Ex = SE->getBackedgeTakenCount(Lp);
123 const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
124 Pointers.push_back(Ptr);
125 Starts.push_back(AR->getStart());
126 Ends.push_back(ScEnd);
127 IsWritePtr.push_back(WritePtr);
128 DependencySetId.push_back(DepSetId);
129 AliasSetId.push_back(ASId);
130}
131
Adam Nemetec1e2bb2015-03-10 18:54:26 +0000132bool LoopAccessInfo::RuntimePointerCheck::needsChecking(
133 unsigned I, unsigned J, const SmallVectorImpl<int> *PtrPartition) const {
Adam Nemeta8945b72015-02-18 03:43:58 +0000134 // No need to check if two readonly pointers intersect.
135 if (!IsWritePtr[I] && !IsWritePtr[J])
136 return false;
137
138 // Only need to check pointers between two different dependency sets.
139 if (DependencySetId[I] == DependencySetId[J])
140 return false;
141
142 // Only need to check pointers in the same alias set.
143 if (AliasSetId[I] != AliasSetId[J])
144 return false;
145
Adam Nemetec1e2bb2015-03-10 18:54:26 +0000146 // If PtrPartition is set omit checks between pointers of the same partition.
147 // Partition number -1 means that the pointer is used in multiple partitions.
148 // In this case we can't omit the check.
149 if (PtrPartition && (*PtrPartition)[I] != -1 &&
150 (*PtrPartition)[I] == (*PtrPartition)[J])
151 return false;
152
Adam Nemeta8945b72015-02-18 03:43:58 +0000153 return true;
154}
155
Adam Nemetec1e2bb2015-03-10 18:54:26 +0000156void LoopAccessInfo::RuntimePointerCheck::print(
157 raw_ostream &OS, unsigned Depth,
158 const SmallVectorImpl<int> *PtrPartition) const {
Adam Nemete91cc6e2015-02-19 19:15:19 +0000159 unsigned NumPointers = Pointers.size();
160 if (NumPointers == 0)
161 return;
162
163 OS.indent(Depth) << "Run-time memory checks:\n";
164 unsigned N = 0;
165 for (unsigned I = 0; I < NumPointers; ++I)
166 for (unsigned J = I + 1; J < NumPointers; ++J)
Adam Nemetec1e2bb2015-03-10 18:54:26 +0000167 if (needsChecking(I, J, PtrPartition)) {
Adam Nemete91cc6e2015-02-19 19:15:19 +0000168 OS.indent(Depth) << N++ << ":\n";
Adam Nemetec1e2bb2015-03-10 18:54:26 +0000169 OS.indent(Depth + 2) << *Pointers[I];
170 if (PtrPartition)
171 OS << " (Partition: " << (*PtrPartition)[I] << ")";
172 OS << "\n";
173 OS.indent(Depth + 2) << *Pointers[J];
174 if (PtrPartition)
175 OS << " (Partition: " << (*PtrPartition)[J] << ")";
176 OS << "\n";
Adam Nemete91cc6e2015-02-19 19:15:19 +0000177 }
178}
179
Adam Nemet51870d12015-04-07 03:35:26 +0000180bool LoopAccessInfo::RuntimePointerCheck::needsAnyChecking(
181 const SmallVectorImpl<int> *PtrPartition) const {
182 unsigned NumPointers = Pointers.size();
183
184 for (unsigned I = 0; I < NumPointers; ++I)
185 for (unsigned J = I + 1; J < NumPointers; ++J)
186 if (needsChecking(I, J, PtrPartition))
187 return true;
188 return false;
189}
190
Adam Nemet04563272015-02-01 16:56:15 +0000191namespace {
192/// \brief Analyses memory accesses in a loop.
193///
194/// Checks whether run time pointer checks are needed and builds sets for data
195/// dependence checking.
196class AccessAnalysis {
197public:
198 /// \brief Read or write access location.
199 typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
200 typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
201
Adam Nemetdee666b2015-03-10 17:40:34 +0000202 AccessAnalysis(const DataLayout &Dl, AliasAnalysis *AA,
203 MemoryDepChecker::DepCandidates &DA)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000204 : DL(Dl), AST(*AA), DepCands(DA), IsRTCheckNeeded(false) {}
Adam Nemet04563272015-02-01 16:56:15 +0000205
206 /// \brief Register a load and whether it is only read from.
207 void addLoad(AliasAnalysis::Location &Loc, bool IsReadOnly) {
208 Value *Ptr = const_cast<Value*>(Loc.Ptr);
209 AST.add(Ptr, AliasAnalysis::UnknownSize, Loc.AATags);
210 Accesses.insert(MemAccessInfo(Ptr, false));
211 if (IsReadOnly)
212 ReadOnlyPtr.insert(Ptr);
213 }
214
215 /// \brief Register a store.
216 void addStore(AliasAnalysis::Location &Loc) {
217 Value *Ptr = const_cast<Value*>(Loc.Ptr);
218 AST.add(Ptr, AliasAnalysis::UnknownSize, Loc.AATags);
219 Accesses.insert(MemAccessInfo(Ptr, true));
220 }
221
222 /// \brief Check whether we can check the pointers at runtime for
223 /// non-intersection.
Adam Nemet30f16e12015-02-18 03:42:35 +0000224 bool canCheckPtrAtRT(LoopAccessInfo::RuntimePointerCheck &RtCheck,
Adam Nemet8bc61df2015-02-24 00:41:59 +0000225 unsigned &NumComparisons, ScalarEvolution *SE,
226 Loop *TheLoop, const ValueToValueMap &Strides,
Adam Nemet04563272015-02-01 16:56:15 +0000227 bool ShouldCheckStride = false);
228
229 /// \brief Goes over all memory accesses, checks whether a RT check is needed
230 /// and builds sets of dependent accesses.
231 void buildDependenceSets() {
232 processMemAccesses();
233 }
234
235 bool isRTCheckNeeded() { return IsRTCheckNeeded; }
236
237 bool isDependencyCheckNeeded() { return !CheckDeps.empty(); }
238 void resetDepChecks() { CheckDeps.clear(); }
239
240 MemAccessInfoSet &getDependenciesToCheck() { return CheckDeps; }
241
242private:
243 typedef SetVector<MemAccessInfo> PtrAccessSet;
244
245 /// \brief Go over all memory access and check whether runtime pointer checks
246 /// are needed /// and build sets of dependency check candidates.
247 void processMemAccesses();
248
249 /// Set of all accesses.
250 PtrAccessSet Accesses;
251
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000252 const DataLayout &DL;
253
Adam Nemet04563272015-02-01 16:56:15 +0000254 /// Set of accesses that need a further dependence check.
255 MemAccessInfoSet CheckDeps;
256
257 /// Set of pointers that are read only.
258 SmallPtrSet<Value*, 16> ReadOnlyPtr;
259
Adam Nemet04563272015-02-01 16:56:15 +0000260 /// An alias set tracker to partition the access set by underlying object and
261 //intrinsic property (such as TBAA metadata).
262 AliasSetTracker AST;
263
264 /// Sets of potentially dependent accesses - members of one set share an
265 /// underlying pointer. The set "CheckDeps" identfies which sets really need a
266 /// dependence check.
Adam Nemetdee666b2015-03-10 17:40:34 +0000267 MemoryDepChecker::DepCandidates &DepCands;
Adam Nemet04563272015-02-01 16:56:15 +0000268
269 bool IsRTCheckNeeded;
270};
271
272} // end anonymous namespace
273
274/// \brief Check whether a pointer can participate in a runtime bounds check.
Adam Nemet8bc61df2015-02-24 00:41:59 +0000275static bool hasComputableBounds(ScalarEvolution *SE,
276 const ValueToValueMap &Strides, Value *Ptr) {
Adam Nemet04563272015-02-01 16:56:15 +0000277 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
278 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
279 if (!AR)
280 return false;
281
282 return AR->isAffine();
283}
284
285/// \brief Check the stride of the pointer and ensure that it does not wrap in
286/// the address space.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000287static int isStridedPtr(ScalarEvolution *SE, Value *Ptr, const Loop *Lp,
288 const ValueToValueMap &StridesMap);
Adam Nemet04563272015-02-01 16:56:15 +0000289
290bool AccessAnalysis::canCheckPtrAtRT(
Adam Nemet8bc61df2015-02-24 00:41:59 +0000291 LoopAccessInfo::RuntimePointerCheck &RtCheck, unsigned &NumComparisons,
292 ScalarEvolution *SE, Loop *TheLoop, const ValueToValueMap &StridesMap,
293 bool ShouldCheckStride) {
Adam Nemet04563272015-02-01 16:56:15 +0000294 // Find pointers with computable bounds. We are going to use this information
295 // to place a runtime bound check.
296 bool CanDoRT = true;
297
298 bool IsDepCheckNeeded = isDependencyCheckNeeded();
299 NumComparisons = 0;
300
301 // We assign a consecutive id to access from different alias sets.
302 // Accesses between different groups doesn't need to be checked.
303 unsigned ASId = 1;
304 for (auto &AS : AST) {
305 unsigned NumReadPtrChecks = 0;
306 unsigned NumWritePtrChecks = 0;
307
308 // We assign consecutive id to access from different dependence sets.
309 // Accesses within the same set don't need a runtime check.
310 unsigned RunningDepId = 1;
311 DenseMap<Value *, unsigned> DepSetId;
312
313 for (auto A : AS) {
314 Value *Ptr = A.getValue();
315 bool IsWrite = Accesses.count(MemAccessInfo(Ptr, true));
316 MemAccessInfo Access(Ptr, IsWrite);
317
318 if (IsWrite)
319 ++NumWritePtrChecks;
320 else
321 ++NumReadPtrChecks;
322
323 if (hasComputableBounds(SE, StridesMap, Ptr) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000324 // When we run after a failing dependency check we have to make sure
325 // we don't have wrapping pointers.
Adam Nemet04563272015-02-01 16:56:15 +0000326 (!ShouldCheckStride ||
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000327 isStridedPtr(SE, Ptr, TheLoop, StridesMap) == 1)) {
Adam Nemet04563272015-02-01 16:56:15 +0000328 // The id of the dependence set.
329 unsigned DepId;
330
331 if (IsDepCheckNeeded) {
332 Value *Leader = DepCands.getLeaderValue(Access).getPointer();
333 unsigned &LeaderId = DepSetId[Leader];
334 if (!LeaderId)
335 LeaderId = RunningDepId++;
336 DepId = LeaderId;
337 } else
338 // Each access has its own dependence set.
339 DepId = RunningDepId++;
340
341 RtCheck.insert(SE, TheLoop, Ptr, IsWrite, DepId, ASId, StridesMap);
342
Adam Nemet339f42b2015-02-19 19:15:07 +0000343 DEBUG(dbgs() << "LAA: Found a runtime check ptr:" << *Ptr << '\n');
Adam Nemet04563272015-02-01 16:56:15 +0000344 } else {
345 CanDoRT = false;
346 }
347 }
348
349 if (IsDepCheckNeeded && CanDoRT && RunningDepId == 2)
350 NumComparisons += 0; // Only one dependence set.
351 else {
352 NumComparisons += (NumWritePtrChecks * (NumReadPtrChecks +
353 NumWritePtrChecks - 1));
354 }
355
356 ++ASId;
357 }
358
359 // If the pointers that we would use for the bounds comparison have different
360 // address spaces, assume the values aren't directly comparable, so we can't
361 // use them for the runtime check. We also have to assume they could
362 // overlap. In the future there should be metadata for whether address spaces
363 // are disjoint.
364 unsigned NumPointers = RtCheck.Pointers.size();
365 for (unsigned i = 0; i < NumPointers; ++i) {
366 for (unsigned j = i + 1; j < NumPointers; ++j) {
367 // Only need to check pointers between two different dependency sets.
368 if (RtCheck.DependencySetId[i] == RtCheck.DependencySetId[j])
369 continue;
370 // Only need to check pointers in the same alias set.
371 if (RtCheck.AliasSetId[i] != RtCheck.AliasSetId[j])
372 continue;
373
374 Value *PtrI = RtCheck.Pointers[i];
375 Value *PtrJ = RtCheck.Pointers[j];
376
377 unsigned ASi = PtrI->getType()->getPointerAddressSpace();
378 unsigned ASj = PtrJ->getType()->getPointerAddressSpace();
379 if (ASi != ASj) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000380 DEBUG(dbgs() << "LAA: Runtime check would require comparison between"
Adam Nemet04d41632015-02-19 19:14:34 +0000381 " different address spaces\n");
Adam Nemet04563272015-02-01 16:56:15 +0000382 return false;
383 }
384 }
385 }
386
387 return CanDoRT;
388}
389
390void AccessAnalysis::processMemAccesses() {
391 // We process the set twice: first we process read-write pointers, last we
392 // process read-only pointers. This allows us to skip dependence tests for
393 // read-only pointers.
394
Adam Nemet339f42b2015-02-19 19:15:07 +0000395 DEBUG(dbgs() << "LAA: Processing memory accesses...\n");
Adam Nemet04563272015-02-01 16:56:15 +0000396 DEBUG(dbgs() << " AST: "; AST.dump());
Adam Nemet9c926572015-03-10 17:40:37 +0000397 DEBUG(dbgs() << "LAA: Accesses(" << Accesses.size() << "):\n");
Adam Nemet04563272015-02-01 16:56:15 +0000398 DEBUG({
399 for (auto A : Accesses)
400 dbgs() << "\t" << *A.getPointer() << " (" <<
401 (A.getInt() ? "write" : (ReadOnlyPtr.count(A.getPointer()) ?
402 "read-only" : "read")) << ")\n";
403 });
404
405 // The AliasSetTracker has nicely partitioned our pointers by metadata
406 // compatibility and potential for underlying-object overlap. As a result, we
407 // only need to check for potential pointer dependencies within each alias
408 // set.
409 for (auto &AS : AST) {
410 // Note that both the alias-set tracker and the alias sets themselves used
411 // linked lists internally and so the iteration order here is deterministic
412 // (matching the original instruction order within each set).
413
414 bool SetHasWrite = false;
415
416 // Map of pointers to last access encountered.
417 typedef DenseMap<Value*, MemAccessInfo> UnderlyingObjToAccessMap;
418 UnderlyingObjToAccessMap ObjToLastAccess;
419
420 // Set of access to check after all writes have been processed.
421 PtrAccessSet DeferredAccesses;
422
423 // Iterate over each alias set twice, once to process read/write pointers,
424 // and then to process read-only pointers.
425 for (int SetIteration = 0; SetIteration < 2; ++SetIteration) {
426 bool UseDeferred = SetIteration > 0;
427 PtrAccessSet &S = UseDeferred ? DeferredAccesses : Accesses;
428
429 for (auto AV : AS) {
430 Value *Ptr = AV.getValue();
431
432 // For a single memory access in AliasSetTracker, Accesses may contain
433 // both read and write, and they both need to be handled for CheckDeps.
434 for (auto AC : S) {
435 if (AC.getPointer() != Ptr)
436 continue;
437
438 bool IsWrite = AC.getInt();
439
440 // If we're using the deferred access set, then it contains only
441 // reads.
442 bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite;
443 if (UseDeferred && !IsReadOnlyPtr)
444 continue;
445 // Otherwise, the pointer must be in the PtrAccessSet, either as a
446 // read or a write.
447 assert(((IsReadOnlyPtr && UseDeferred) || IsWrite ||
448 S.count(MemAccessInfo(Ptr, false))) &&
449 "Alias-set pointer not in the access set?");
450
451 MemAccessInfo Access(Ptr, IsWrite);
452 DepCands.insert(Access);
453
454 // Memorize read-only pointers for later processing and skip them in
455 // the first round (they need to be checked after we have seen all
456 // write pointers). Note: we also mark pointer that are not
457 // consecutive as "read-only" pointers (so that we check
458 // "a[b[i]] +="). Hence, we need the second check for "!IsWrite".
459 if (!UseDeferred && IsReadOnlyPtr) {
460 DeferredAccesses.insert(Access);
461 continue;
462 }
463
464 // If this is a write - check other reads and writes for conflicts. If
465 // this is a read only check other writes for conflicts (but only if
466 // there is no other write to the ptr - this is an optimization to
467 // catch "a[i] = a[i] + " without having to do a dependence check).
468 if ((IsWrite || IsReadOnlyPtr) && SetHasWrite) {
469 CheckDeps.insert(Access);
470 IsRTCheckNeeded = true;
471 }
472
473 if (IsWrite)
474 SetHasWrite = true;
475
476 // Create sets of pointers connected by a shared alias set and
477 // underlying object.
478 typedef SmallVector<Value *, 16> ValueVector;
479 ValueVector TempObjects;
480 GetUnderlyingObjects(Ptr, TempObjects, DL);
481 for (Value *UnderlyingObj : TempObjects) {
482 UnderlyingObjToAccessMap::iterator Prev =
483 ObjToLastAccess.find(UnderlyingObj);
484 if (Prev != ObjToLastAccess.end())
485 DepCands.unionSets(Access, Prev->second);
486
487 ObjToLastAccess[UnderlyingObj] = Access;
488 }
489 }
490 }
491 }
492 }
493}
494
Adam Nemet04563272015-02-01 16:56:15 +0000495static bool isInBoundsGep(Value *Ptr) {
496 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
497 return GEP->isInBounds();
498 return false;
499}
500
501/// \brief Check whether the access through \p Ptr has a constant stride.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000502static int isStridedPtr(ScalarEvolution *SE, Value *Ptr, const Loop *Lp,
503 const ValueToValueMap &StridesMap) {
Adam Nemet04563272015-02-01 16:56:15 +0000504 const Type *Ty = Ptr->getType();
505 assert(Ty->isPointerTy() && "Unexpected non-ptr");
506
507 // Make sure that the pointer does not point to aggregate types.
508 const PointerType *PtrTy = cast<PointerType>(Ty);
509 if (PtrTy->getElementType()->isAggregateType()) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000510 DEBUG(dbgs() << "LAA: Bad stride - Not a pointer to a scalar type"
511 << *Ptr << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000512 return 0;
513 }
514
515 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, StridesMap, Ptr);
516
517 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
518 if (!AR) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000519 DEBUG(dbgs() << "LAA: Bad stride - Not an AddRecExpr pointer "
Adam Nemet04d41632015-02-19 19:14:34 +0000520 << *Ptr << " SCEV: " << *PtrScev << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000521 return 0;
522 }
523
524 // The accesss function must stride over the innermost loop.
525 if (Lp != AR->getLoop()) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000526 DEBUG(dbgs() << "LAA: Bad stride - Not striding over innermost loop " <<
Adam Nemet04d41632015-02-19 19:14:34 +0000527 *Ptr << " SCEV: " << *PtrScev << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000528 }
529
530 // The address calculation must not wrap. Otherwise, a dependence could be
531 // inverted.
532 // An inbounds getelementptr that is a AddRec with a unit stride
533 // cannot wrap per definition. The unit stride requirement is checked later.
534 // An getelementptr without an inbounds attribute and unit stride would have
535 // to access the pointer value "0" which is undefined behavior in address
536 // space 0, therefore we can also vectorize this case.
537 bool IsInBoundsGEP = isInBoundsGep(Ptr);
538 bool IsNoWrapAddRec = AR->getNoWrapFlags(SCEV::NoWrapMask);
539 bool IsInAddressSpaceZero = PtrTy->getAddressSpace() == 0;
540 if (!IsNoWrapAddRec && !IsInBoundsGEP && !IsInAddressSpaceZero) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000541 DEBUG(dbgs() << "LAA: Bad stride - Pointer may wrap in the address space "
Adam Nemet04d41632015-02-19 19:14:34 +0000542 << *Ptr << " SCEV: " << *PtrScev << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000543 return 0;
544 }
545
546 // Check the step is constant.
547 const SCEV *Step = AR->getStepRecurrence(*SE);
548
549 // Calculate the pointer stride and check if it is consecutive.
550 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
551 if (!C) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000552 DEBUG(dbgs() << "LAA: Bad stride - Not a constant strided " << *Ptr <<
Adam Nemet04d41632015-02-19 19:14:34 +0000553 " SCEV: " << *PtrScev << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000554 return 0;
555 }
556
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000557 auto &DL = Lp->getHeader()->getModule()->getDataLayout();
558 int64_t Size = DL.getTypeAllocSize(PtrTy->getElementType());
Adam Nemet04563272015-02-01 16:56:15 +0000559 const APInt &APStepVal = C->getValue()->getValue();
560
561 // Huge step value - give up.
562 if (APStepVal.getBitWidth() > 64)
563 return 0;
564
565 int64_t StepVal = APStepVal.getSExtValue();
566
567 // Strided access.
568 int64_t Stride = StepVal / Size;
569 int64_t Rem = StepVal % Size;
570 if (Rem)
571 return 0;
572
573 // If the SCEV could wrap but we have an inbounds gep with a unit stride we
574 // know we can't "wrap around the address space". In case of address space
575 // zero we know that this won't happen without triggering undefined behavior.
576 if (!IsNoWrapAddRec && (IsInBoundsGEP || IsInAddressSpaceZero) &&
577 Stride != 1 && Stride != -1)
578 return 0;
579
580 return Stride;
581}
582
Adam Nemet9c926572015-03-10 17:40:37 +0000583bool MemoryDepChecker::Dependence::isSafeForVectorization(DepType Type) {
584 switch (Type) {
585 case NoDep:
586 case Forward:
587 case BackwardVectorizable:
588 return true;
589
590 case Unknown:
591 case ForwardButPreventsForwarding:
592 case Backward:
593 case BackwardVectorizableButPreventsForwarding:
594 return false;
595 }
David Majnemerd388e932015-03-10 20:23:29 +0000596 llvm_unreachable("unexpected DepType!");
Adam Nemet9c926572015-03-10 17:40:37 +0000597}
598
599bool MemoryDepChecker::Dependence::isInterestingDependence(DepType Type) {
600 switch (Type) {
601 case NoDep:
602 case Forward:
603 return false;
604
605 case BackwardVectorizable:
606 case Unknown:
607 case ForwardButPreventsForwarding:
608 case Backward:
609 case BackwardVectorizableButPreventsForwarding:
610 return true;
611 }
David Majnemerd388e932015-03-10 20:23:29 +0000612 llvm_unreachable("unexpected DepType!");
Adam Nemet9c926572015-03-10 17:40:37 +0000613}
614
615bool MemoryDepChecker::Dependence::isPossiblyBackward() const {
616 switch (Type) {
617 case NoDep:
618 case Forward:
619 case ForwardButPreventsForwarding:
620 return false;
621
622 case Unknown:
623 case BackwardVectorizable:
624 case Backward:
625 case BackwardVectorizableButPreventsForwarding:
626 return true;
627 }
David Majnemerd388e932015-03-10 20:23:29 +0000628 llvm_unreachable("unexpected DepType!");
Adam Nemet9c926572015-03-10 17:40:37 +0000629}
630
Adam Nemet04563272015-02-01 16:56:15 +0000631bool MemoryDepChecker::couldPreventStoreLoadForward(unsigned Distance,
632 unsigned TypeByteSize) {
633 // If loads occur at a distance that is not a multiple of a feasible vector
634 // factor store-load forwarding does not take place.
635 // Positive dependences might cause troubles because vectorizing them might
636 // prevent store-load forwarding making vectorized code run a lot slower.
637 // a[i] = a[i-3] ^ a[i-8];
638 // The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
639 // hence on your typical architecture store-load forwarding does not take
640 // place. Vectorizing in such cases does not make sense.
641 // Store-load forwarding distance.
642 const unsigned NumCyclesForStoreLoadThroughMemory = 8*TypeByteSize;
643 // Maximum vector factor.
Adam Nemetf219c642015-02-19 19:14:52 +0000644 unsigned MaxVFWithoutSLForwardIssues =
645 VectorizerParams::MaxVectorWidth * TypeByteSize;
Adam Nemet04d41632015-02-19 19:14:34 +0000646 if(MaxSafeDepDistBytes < MaxVFWithoutSLForwardIssues)
Adam Nemet04563272015-02-01 16:56:15 +0000647 MaxVFWithoutSLForwardIssues = MaxSafeDepDistBytes;
648
649 for (unsigned vf = 2*TypeByteSize; vf <= MaxVFWithoutSLForwardIssues;
650 vf *= 2) {
651 if (Distance % vf && Distance / vf < NumCyclesForStoreLoadThroughMemory) {
652 MaxVFWithoutSLForwardIssues = (vf >>=1);
653 break;
654 }
655 }
656
Adam Nemet04d41632015-02-19 19:14:34 +0000657 if (MaxVFWithoutSLForwardIssues< 2*TypeByteSize) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000658 DEBUG(dbgs() << "LAA: Distance " << Distance <<
Adam Nemet04d41632015-02-19 19:14:34 +0000659 " that could cause a store-load forwarding conflict\n");
Adam Nemet04563272015-02-01 16:56:15 +0000660 return true;
661 }
662
663 if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes &&
Adam Nemetf219c642015-02-19 19:14:52 +0000664 MaxVFWithoutSLForwardIssues !=
665 VectorizerParams::MaxVectorWidth * TypeByteSize)
Adam Nemet04563272015-02-01 16:56:15 +0000666 MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues;
667 return false;
668}
669
Adam Nemet9c926572015-03-10 17:40:37 +0000670MemoryDepChecker::Dependence::DepType
671MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
672 const MemAccessInfo &B, unsigned BIdx,
673 const ValueToValueMap &Strides) {
Adam Nemet04563272015-02-01 16:56:15 +0000674 assert (AIdx < BIdx && "Must pass arguments in program order");
675
676 Value *APtr = A.getPointer();
677 Value *BPtr = B.getPointer();
678 bool AIsWrite = A.getInt();
679 bool BIsWrite = B.getInt();
680
681 // Two reads are independent.
682 if (!AIsWrite && !BIsWrite)
Adam Nemet9c926572015-03-10 17:40:37 +0000683 return Dependence::NoDep;
Adam Nemet04563272015-02-01 16:56:15 +0000684
685 // We cannot check pointers in different address spaces.
686 if (APtr->getType()->getPointerAddressSpace() !=
687 BPtr->getType()->getPointerAddressSpace())
Adam Nemet9c926572015-03-10 17:40:37 +0000688 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +0000689
690 const SCEV *AScev = replaceSymbolicStrideSCEV(SE, Strides, APtr);
691 const SCEV *BScev = replaceSymbolicStrideSCEV(SE, Strides, BPtr);
692
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000693 int StrideAPtr = isStridedPtr(SE, APtr, InnermostLoop, Strides);
694 int StrideBPtr = isStridedPtr(SE, BPtr, InnermostLoop, Strides);
Adam Nemet04563272015-02-01 16:56:15 +0000695
696 const SCEV *Src = AScev;
697 const SCEV *Sink = BScev;
698
699 // If the induction step is negative we have to invert source and sink of the
700 // dependence.
701 if (StrideAPtr < 0) {
702 //Src = BScev;
703 //Sink = AScev;
704 std::swap(APtr, BPtr);
705 std::swap(Src, Sink);
706 std::swap(AIsWrite, BIsWrite);
707 std::swap(AIdx, BIdx);
708 std::swap(StrideAPtr, StrideBPtr);
709 }
710
711 const SCEV *Dist = SE->getMinusSCEV(Sink, Src);
712
Adam Nemet339f42b2015-02-19 19:15:07 +0000713 DEBUG(dbgs() << "LAA: Src Scev: " << *Src << "Sink Scev: " << *Sink
Adam Nemet04d41632015-02-19 19:14:34 +0000714 << "(Induction step: " << StrideAPtr << ")\n");
Adam Nemet339f42b2015-02-19 19:15:07 +0000715 DEBUG(dbgs() << "LAA: Distance for " << *InstMap[AIdx] << " to "
Adam Nemet04d41632015-02-19 19:14:34 +0000716 << *InstMap[BIdx] << ": " << *Dist << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000717
718 // Need consecutive accesses. We don't want to vectorize
719 // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in
720 // the address space.
721 if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){
722 DEBUG(dbgs() << "Non-consecutive pointer access\n");
Adam Nemet9c926572015-03-10 17:40:37 +0000723 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +0000724 }
725
726 const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist);
727 if (!C) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000728 DEBUG(dbgs() << "LAA: Dependence because of non-constant distance\n");
Adam Nemet04563272015-02-01 16:56:15 +0000729 ShouldRetryWithRuntimeCheck = true;
Adam Nemet9c926572015-03-10 17:40:37 +0000730 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +0000731 }
732
733 Type *ATy = APtr->getType()->getPointerElementType();
734 Type *BTy = BPtr->getType()->getPointerElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000735 auto &DL = InnermostLoop->getHeader()->getModule()->getDataLayout();
736 unsigned TypeByteSize = DL.getTypeAllocSize(ATy);
Adam Nemet04563272015-02-01 16:56:15 +0000737
738 // Negative distances are not plausible dependencies.
739 const APInt &Val = C->getValue()->getValue();
740 if (Val.isNegative()) {
741 bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
742 if (IsTrueDataDependence &&
743 (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) ||
744 ATy != BTy))
Adam Nemet9c926572015-03-10 17:40:37 +0000745 return Dependence::ForwardButPreventsForwarding;
Adam Nemet04563272015-02-01 16:56:15 +0000746
Adam Nemet339f42b2015-02-19 19:15:07 +0000747 DEBUG(dbgs() << "LAA: Dependence is negative: NoDep\n");
Adam Nemet9c926572015-03-10 17:40:37 +0000748 return Dependence::Forward;
Adam Nemet04563272015-02-01 16:56:15 +0000749 }
750
751 // Write to the same location with the same size.
752 // Could be improved to assert type sizes are the same (i32 == float, etc).
753 if (Val == 0) {
754 if (ATy == BTy)
Adam Nemet9c926572015-03-10 17:40:37 +0000755 return Dependence::NoDep;
Adam Nemet339f42b2015-02-19 19:15:07 +0000756 DEBUG(dbgs() << "LAA: Zero dependence difference but different types\n");
Adam Nemet9c926572015-03-10 17:40:37 +0000757 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +0000758 }
759
760 assert(Val.isStrictlyPositive() && "Expect a positive value");
761
Adam Nemet04563272015-02-01 16:56:15 +0000762 if (ATy != BTy) {
Adam Nemet04d41632015-02-19 19:14:34 +0000763 DEBUG(dbgs() <<
Adam Nemet339f42b2015-02-19 19:15:07 +0000764 "LAA: ReadWrite-Write positive dependency with different types\n");
Adam Nemet9c926572015-03-10 17:40:37 +0000765 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +0000766 }
767
768 unsigned Distance = (unsigned) Val.getZExtValue();
769
770 // Bail out early if passed-in parameters make vectorization not feasible.
Adam Nemetf219c642015-02-19 19:14:52 +0000771 unsigned ForcedFactor = (VectorizerParams::VectorizationFactor ?
772 VectorizerParams::VectorizationFactor : 1);
773 unsigned ForcedUnroll = (VectorizerParams::VectorizationInterleave ?
774 VectorizerParams::VectorizationInterleave : 1);
Adam Nemet04563272015-02-01 16:56:15 +0000775
776 // The distance must be bigger than the size needed for a vectorized version
777 // of the operation and the size of the vectorized operation must not be
778 // bigger than the currrent maximum size.
779 if (Distance < 2*TypeByteSize ||
780 2*TypeByteSize > MaxSafeDepDistBytes ||
781 Distance < TypeByteSize * ForcedUnroll * ForcedFactor) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000782 DEBUG(dbgs() << "LAA: Failure because of Positive distance "
Adam Nemet04d41632015-02-19 19:14:34 +0000783 << Val.getSExtValue() << '\n');
Adam Nemet9c926572015-03-10 17:40:37 +0000784 return Dependence::Backward;
Adam Nemet04563272015-02-01 16:56:15 +0000785 }
786
Adam Nemet9cc0c392015-02-26 17:58:48 +0000787 // Positive distance bigger than max vectorization factor.
Adam Nemet04563272015-02-01 16:56:15 +0000788 MaxSafeDepDistBytes = Distance < MaxSafeDepDistBytes ?
789 Distance : MaxSafeDepDistBytes;
790
791 bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
792 if (IsTrueDataDependence &&
793 couldPreventStoreLoadForward(Distance, TypeByteSize))
Adam Nemet9c926572015-03-10 17:40:37 +0000794 return Dependence::BackwardVectorizableButPreventsForwarding;
Adam Nemet04563272015-02-01 16:56:15 +0000795
Adam Nemet339f42b2015-02-19 19:15:07 +0000796 DEBUG(dbgs() << "LAA: Positive distance " << Val.getSExtValue() <<
Adam Nemet04d41632015-02-19 19:14:34 +0000797 " with max VF = " << MaxSafeDepDistBytes / TypeByteSize << '\n');
Adam Nemet04563272015-02-01 16:56:15 +0000798
Adam Nemet9c926572015-03-10 17:40:37 +0000799 return Dependence::BackwardVectorizable;
Adam Nemet04563272015-02-01 16:56:15 +0000800}
801
Adam Nemetdee666b2015-03-10 17:40:34 +0000802bool MemoryDepChecker::areDepsSafe(DepCandidates &AccessSets,
Adam Nemet04563272015-02-01 16:56:15 +0000803 MemAccessInfoSet &CheckDeps,
Adam Nemet8bc61df2015-02-24 00:41:59 +0000804 const ValueToValueMap &Strides) {
Adam Nemet04563272015-02-01 16:56:15 +0000805
806 MaxSafeDepDistBytes = -1U;
807 while (!CheckDeps.empty()) {
808 MemAccessInfo CurAccess = *CheckDeps.begin();
809
810 // Get the relevant memory access set.
811 EquivalenceClasses<MemAccessInfo>::iterator I =
812 AccessSets.findValue(AccessSets.getLeaderValue(CurAccess));
813
814 // Check accesses within this set.
815 EquivalenceClasses<MemAccessInfo>::member_iterator AI, AE;
816 AI = AccessSets.member_begin(I), AE = AccessSets.member_end();
817
818 // Check every access pair.
819 while (AI != AE) {
820 CheckDeps.erase(*AI);
821 EquivalenceClasses<MemAccessInfo>::member_iterator OI = std::next(AI);
822 while (OI != AE) {
823 // Check every accessing instruction pair in program order.
824 for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(),
825 I1E = Accesses[*AI].end(); I1 != I1E; ++I1)
826 for (std::vector<unsigned>::iterator I2 = Accesses[*OI].begin(),
827 I2E = Accesses[*OI].end(); I2 != I2E; ++I2) {
Adam Nemet9c926572015-03-10 17:40:37 +0000828 auto A = std::make_pair(&*AI, *I1);
829 auto B = std::make_pair(&*OI, *I2);
830
831 assert(*I1 != *I2);
832 if (*I1 > *I2)
833 std::swap(A, B);
834
835 Dependence::DepType Type =
836 isDependent(*A.first, A.second, *B.first, B.second, Strides);
837 SafeForVectorization &= Dependence::isSafeForVectorization(Type);
838
839 // Gather dependences unless we accumulated MaxInterestingDependence
840 // dependences. In that case return as soon as we find the first
841 // unsafe dependence. This puts a limit on this quadratic
842 // algorithm.
843 if (RecordInterestingDependences) {
844 if (Dependence::isInterestingDependence(Type))
845 InterestingDependences.push_back(
846 Dependence(A.second, B.second, Type));
847
848 if (InterestingDependences.size() >= MaxInterestingDependence) {
849 RecordInterestingDependences = false;
850 InterestingDependences.clear();
851 DEBUG(dbgs() << "Too many dependences, stopped recording\n");
852 }
853 }
854 if (!RecordInterestingDependences && !SafeForVectorization)
Adam Nemet04563272015-02-01 16:56:15 +0000855 return false;
856 }
857 ++OI;
858 }
859 AI++;
860 }
861 }
Adam Nemet9c926572015-03-10 17:40:37 +0000862
863 DEBUG(dbgs() << "Total Interesting Dependences: "
864 << InterestingDependences.size() << "\n");
865 return SafeForVectorization;
Adam Nemet04563272015-02-01 16:56:15 +0000866}
867
Adam Nemetec1e2bb2015-03-10 18:54:26 +0000868SmallVector<Instruction *, 4>
869MemoryDepChecker::getInstructionsForAccess(Value *Ptr, bool isWrite) const {
870 MemAccessInfo Access(Ptr, isWrite);
871 auto &IndexVector = Accesses.find(Access)->second;
872
873 SmallVector<Instruction *, 4> Insts;
874 std::transform(IndexVector.begin(), IndexVector.end(),
875 std::back_inserter(Insts),
876 [&](unsigned Idx) { return this->InstMap[Idx]; });
877 return Insts;
878}
879
Adam Nemet58913d62015-03-10 17:40:43 +0000880const char *MemoryDepChecker::Dependence::DepName[] = {
881 "NoDep", "Unknown", "Forward", "ForwardButPreventsForwarding", "Backward",
882 "BackwardVectorizable", "BackwardVectorizableButPreventsForwarding"};
883
884void MemoryDepChecker::Dependence::print(
885 raw_ostream &OS, unsigned Depth,
886 const SmallVectorImpl<Instruction *> &Instrs) const {
887 OS.indent(Depth) << DepName[Type] << ":\n";
888 OS.indent(Depth + 2) << *Instrs[Source] << " -> \n";
889 OS.indent(Depth + 2) << *Instrs[Destination] << "\n";
890}
891
Adam Nemet929c38e2015-02-19 19:15:10 +0000892bool LoopAccessInfo::canAnalyzeLoop() {
Adam Nemet8dcb3b62015-04-17 22:43:10 +0000893 // We need to have a loop header.
894 DEBUG(dbgs() << "LAA: Found a loop: " <<
895 TheLoop->getHeader()->getName() << '\n');
896
Adam Nemet929c38e2015-02-19 19:15:10 +0000897 // We can only analyze innermost loops.
898 if (!TheLoop->empty()) {
Adam Nemet8dcb3b62015-04-17 22:43:10 +0000899 DEBUG(dbgs() << "LAA: loop is not the innermost loop\n");
Adam Nemet2bd6e982015-02-19 19:15:15 +0000900 emitAnalysis(LoopAccessReport() << "loop is not the innermost loop");
Adam Nemet929c38e2015-02-19 19:15:10 +0000901 return false;
902 }
903
904 // We must have a single backedge.
905 if (TheLoop->getNumBackEdges() != 1) {
Adam Nemet8dcb3b62015-04-17 22:43:10 +0000906 DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n");
Adam Nemet929c38e2015-02-19 19:15:10 +0000907 emitAnalysis(
Adam Nemet2bd6e982015-02-19 19:15:15 +0000908 LoopAccessReport() <<
Adam Nemet929c38e2015-02-19 19:15:10 +0000909 "loop control flow is not understood by analyzer");
910 return false;
911 }
912
913 // We must have a single exiting block.
914 if (!TheLoop->getExitingBlock()) {
Adam Nemet8dcb3b62015-04-17 22:43:10 +0000915 DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n");
Adam Nemet929c38e2015-02-19 19:15:10 +0000916 emitAnalysis(
Adam Nemet2bd6e982015-02-19 19:15:15 +0000917 LoopAccessReport() <<
Adam Nemet929c38e2015-02-19 19:15:10 +0000918 "loop control flow is not understood by analyzer");
919 return false;
920 }
921
922 // We only handle bottom-tested loops, i.e. loop in which the condition is
923 // checked at the end of each iteration. With that we can assume that all
924 // instructions in the loop are executed the same number of times.
925 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
Adam Nemet8dcb3b62015-04-17 22:43:10 +0000926 DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n");
Adam Nemet929c38e2015-02-19 19:15:10 +0000927 emitAnalysis(
Adam Nemet2bd6e982015-02-19 19:15:15 +0000928 LoopAccessReport() <<
Adam Nemet929c38e2015-02-19 19:15:10 +0000929 "loop control flow is not understood by analyzer");
930 return false;
931 }
932
Adam Nemet929c38e2015-02-19 19:15:10 +0000933 // ScalarEvolution needs to be able to find the exit count.
934 const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop);
935 if (ExitCount == SE->getCouldNotCompute()) {
Adam Nemet2bd6e982015-02-19 19:15:15 +0000936 emitAnalysis(LoopAccessReport() <<
Adam Nemet929c38e2015-02-19 19:15:10 +0000937 "could not determine number of loop iterations");
938 DEBUG(dbgs() << "LAA: SCEV could not compute the loop exit count.\n");
939 return false;
940 }
941
942 return true;
943}
944
Adam Nemet8bc61df2015-02-24 00:41:59 +0000945void LoopAccessInfo::analyzeLoop(const ValueToValueMap &Strides) {
Adam Nemet04563272015-02-01 16:56:15 +0000946
947 typedef SmallVector<Value*, 16> ValueVector;
948 typedef SmallPtrSet<Value*, 16> ValueSet;
949
950 // Holds the Load and Store *instructions*.
951 ValueVector Loads;
952 ValueVector Stores;
953
954 // Holds all the different accesses in the loop.
955 unsigned NumReads = 0;
956 unsigned NumReadWrites = 0;
957
958 PtrRtCheck.Pointers.clear();
959 PtrRtCheck.Need = false;
960
961 const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
Adam Nemet04563272015-02-01 16:56:15 +0000962
963 // For each block.
964 for (Loop::block_iterator bb = TheLoop->block_begin(),
965 be = TheLoop->block_end(); bb != be; ++bb) {
966
967 // Scan the BB and collect legal loads and stores.
968 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
969 ++it) {
970
971 // If this is a load, save it. If this instruction can read from memory
972 // but is not a load, then we quit. Notice that we don't handle function
973 // calls that read or write.
974 if (it->mayReadFromMemory()) {
975 // Many math library functions read the rounding mode. We will only
976 // vectorize a loop if it contains known function calls that don't set
977 // the flag. Therefore, it is safe to ignore this read from memory.
978 CallInst *Call = dyn_cast<CallInst>(it);
979 if (Call && getIntrinsicIDForCall(Call, TLI))
980 continue;
981
Michael Zolotukhin9b3cf602015-03-17 19:46:50 +0000982 // If the function has an explicit vectorized counterpart, we can safely
983 // assume that it can be vectorized.
984 if (Call && !Call->isNoBuiltin() && Call->getCalledFunction() &&
985 TLI->isFunctionVectorizable(Call->getCalledFunction()->getName()))
986 continue;
987
Adam Nemet04563272015-02-01 16:56:15 +0000988 LoadInst *Ld = dyn_cast<LoadInst>(it);
989 if (!Ld || (!Ld->isSimple() && !IsAnnotatedParallel)) {
Adam Nemet2bd6e982015-02-19 19:15:15 +0000990 emitAnalysis(LoopAccessReport(Ld)
Adam Nemet04563272015-02-01 16:56:15 +0000991 << "read with atomic ordering or volatile read");
Adam Nemet339f42b2015-02-19 19:15:07 +0000992 DEBUG(dbgs() << "LAA: Found a non-simple load.\n");
Adam Nemet436018c2015-02-19 19:15:00 +0000993 CanVecMem = false;
994 return;
Adam Nemet04563272015-02-01 16:56:15 +0000995 }
996 NumLoads++;
997 Loads.push_back(Ld);
998 DepChecker.addAccess(Ld);
999 continue;
1000 }
1001
1002 // Save 'store' instructions. Abort if other instructions write to memory.
1003 if (it->mayWriteToMemory()) {
1004 StoreInst *St = dyn_cast<StoreInst>(it);
1005 if (!St) {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001006 emitAnalysis(LoopAccessReport(it) <<
Adam Nemet04d41632015-02-19 19:14:34 +00001007 "instruction cannot be vectorized");
Adam Nemet436018c2015-02-19 19:15:00 +00001008 CanVecMem = false;
1009 return;
Adam Nemet04563272015-02-01 16:56:15 +00001010 }
1011 if (!St->isSimple() && !IsAnnotatedParallel) {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001012 emitAnalysis(LoopAccessReport(St)
Adam Nemet04563272015-02-01 16:56:15 +00001013 << "write with atomic ordering or volatile write");
Adam Nemet339f42b2015-02-19 19:15:07 +00001014 DEBUG(dbgs() << "LAA: Found a non-simple store.\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001015 CanVecMem = false;
1016 return;
Adam Nemet04563272015-02-01 16:56:15 +00001017 }
1018 NumStores++;
1019 Stores.push_back(St);
1020 DepChecker.addAccess(St);
1021 }
1022 } // Next instr.
1023 } // Next block.
1024
1025 // Now we have two lists that hold the loads and the stores.
1026 // Next, we find the pointers that they use.
1027
1028 // Check if we see any stores. If there are no stores, then we don't
1029 // care if the pointers are *restrict*.
1030 if (!Stores.size()) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001031 DEBUG(dbgs() << "LAA: Found a read-only loop!\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001032 CanVecMem = true;
1033 return;
Adam Nemet04563272015-02-01 16:56:15 +00001034 }
1035
Adam Nemetdee666b2015-03-10 17:40:34 +00001036 MemoryDepChecker::DepCandidates DependentAccesses;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001037 AccessAnalysis Accesses(TheLoop->getHeader()->getModule()->getDataLayout(),
1038 AA, DependentAccesses);
Adam Nemet04563272015-02-01 16:56:15 +00001039
1040 // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
1041 // multiple times on the same object. If the ptr is accessed twice, once
1042 // for read and once for write, it will only appear once (on the write
1043 // list). This is okay, since we are going to check for conflicts between
1044 // writes and between reads and writes, but not between reads and reads.
1045 ValueSet Seen;
1046
1047 ValueVector::iterator I, IE;
1048 for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
1049 StoreInst *ST = cast<StoreInst>(*I);
1050 Value* Ptr = ST->getPointerOperand();
Adam Nemetce482502015-04-08 17:48:40 +00001051 // Check for store to loop invariant address.
1052 StoreToLoopInvariantAddress |= isUniform(Ptr);
Adam Nemet04563272015-02-01 16:56:15 +00001053 // If we did *not* see this pointer before, insert it to the read-write
1054 // list. At this phase it is only a 'write' list.
1055 if (Seen.insert(Ptr).second) {
1056 ++NumReadWrites;
1057
1058 AliasAnalysis::Location Loc = AA->getLocation(ST);
1059 // The TBAA metadata could have a control dependency on the predication
1060 // condition, so we cannot rely on it when determining whether or not we
1061 // need runtime pointer checks.
Adam Nemet01abb2c2015-02-18 03:43:19 +00001062 if (blockNeedsPredication(ST->getParent(), TheLoop, DT))
Adam Nemet04563272015-02-01 16:56:15 +00001063 Loc.AATags.TBAA = nullptr;
1064
1065 Accesses.addStore(Loc);
1066 }
1067 }
1068
1069 if (IsAnnotatedParallel) {
Adam Nemet04d41632015-02-19 19:14:34 +00001070 DEBUG(dbgs()
Adam Nemet339f42b2015-02-19 19:15:07 +00001071 << "LAA: A loop annotated parallel, ignore memory dependency "
Adam Nemet04d41632015-02-19 19:14:34 +00001072 << "checks.\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001073 CanVecMem = true;
1074 return;
Adam Nemet04563272015-02-01 16:56:15 +00001075 }
1076
1077 for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
1078 LoadInst *LD = cast<LoadInst>(*I);
1079 Value* Ptr = LD->getPointerOperand();
1080 // If we did *not* see this pointer before, insert it to the
1081 // read list. If we *did* see it before, then it is already in
1082 // the read-write list. This allows us to vectorize expressions
1083 // such as A[i] += x; Because the address of A[i] is a read-write
1084 // pointer. This only works if the index of A[i] is consecutive.
1085 // If the address of i is unknown (for example A[B[i]]) then we may
1086 // read a few words, modify, and write a few words, and some of the
1087 // words may be written to the same address.
1088 bool IsReadOnlyPtr = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001089 if (Seen.insert(Ptr).second || !isStridedPtr(SE, Ptr, TheLoop, Strides)) {
Adam Nemet04563272015-02-01 16:56:15 +00001090 ++NumReads;
1091 IsReadOnlyPtr = true;
1092 }
1093
1094 AliasAnalysis::Location Loc = AA->getLocation(LD);
1095 // The TBAA metadata could have a control dependency on the predication
1096 // condition, so we cannot rely on it when determining whether or not we
1097 // need runtime pointer checks.
Adam Nemet01abb2c2015-02-18 03:43:19 +00001098 if (blockNeedsPredication(LD->getParent(), TheLoop, DT))
Adam Nemet04563272015-02-01 16:56:15 +00001099 Loc.AATags.TBAA = nullptr;
1100
1101 Accesses.addLoad(Loc, IsReadOnlyPtr);
1102 }
1103
1104 // If we write (or read-write) to a single destination and there are no
1105 // other reads in this loop then is it safe to vectorize.
1106 if (NumReadWrites == 1 && NumReads == 0) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001107 DEBUG(dbgs() << "LAA: Found a write-only loop!\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001108 CanVecMem = true;
1109 return;
Adam Nemet04563272015-02-01 16:56:15 +00001110 }
1111
1112 // Build dependence sets and check whether we need a runtime pointer bounds
1113 // check.
1114 Accesses.buildDependenceSets();
1115 bool NeedRTCheck = Accesses.isRTCheckNeeded();
1116
1117 // Find pointers with computable bounds. We are going to use this information
1118 // to place a runtime bound check.
Adam Nemet04563272015-02-01 16:56:15 +00001119 bool CanDoRT = false;
1120 if (NeedRTCheck)
1121 CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE, TheLoop,
1122 Strides);
1123
Adam Nemet339f42b2015-02-19 19:15:07 +00001124 DEBUG(dbgs() << "LAA: We need to do " << NumComparisons <<
Adam Nemet04d41632015-02-19 19:14:34 +00001125 " pointer comparisons.\n");
Adam Nemet04563272015-02-01 16:56:15 +00001126
1127 // If we only have one set of dependences to check pointers among we don't
1128 // need a runtime check.
1129 if (NumComparisons == 0 && NeedRTCheck)
1130 NeedRTCheck = false;
1131
Adam Nemet949e91a2015-03-10 19:12:41 +00001132 // Check that we found the bounds for the pointer.
Adam Nemetb6dc76f2015-03-10 18:54:19 +00001133 if (CanDoRT)
Adam Nemet339f42b2015-02-19 19:15:07 +00001134 DEBUG(dbgs() << "LAA: We can perform a memory runtime check if needed.\n");
Adam Nemetb6dc76f2015-03-10 18:54:19 +00001135 else if (NeedRTCheck) {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001136 emitAnalysis(LoopAccessReport() << "cannot identify array bounds");
Adam Nemet339f42b2015-02-19 19:15:07 +00001137 DEBUG(dbgs() << "LAA: We can't vectorize because we can't find " <<
Adam Nemet04d41632015-02-19 19:14:34 +00001138 "the array bounds.\n");
Adam Nemet04563272015-02-01 16:56:15 +00001139 PtrRtCheck.reset();
Adam Nemet436018c2015-02-19 19:15:00 +00001140 CanVecMem = false;
1141 return;
Adam Nemet04563272015-02-01 16:56:15 +00001142 }
1143
1144 PtrRtCheck.Need = NeedRTCheck;
1145
Adam Nemet436018c2015-02-19 19:15:00 +00001146 CanVecMem = true;
Adam Nemet04563272015-02-01 16:56:15 +00001147 if (Accesses.isDependencyCheckNeeded()) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001148 DEBUG(dbgs() << "LAA: Checking memory dependencies\n");
Adam Nemet04563272015-02-01 16:56:15 +00001149 CanVecMem = DepChecker.areDepsSafe(
1150 DependentAccesses, Accesses.getDependenciesToCheck(), Strides);
1151 MaxSafeDepDistBytes = DepChecker.getMaxSafeDepDistBytes();
1152
1153 if (!CanVecMem && DepChecker.shouldRetryWithRuntimeCheck()) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001154 DEBUG(dbgs() << "LAA: Retrying with memory checks\n");
Adam Nemet04563272015-02-01 16:56:15 +00001155 NeedRTCheck = true;
1156
1157 // Clear the dependency checks. We assume they are not needed.
1158 Accesses.resetDepChecks();
1159
1160 PtrRtCheck.reset();
1161 PtrRtCheck.Need = true;
1162
1163 CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE,
1164 TheLoop, Strides, true);
Adam Nemet949e91a2015-03-10 19:12:41 +00001165 // Check that we found the bounds for the pointer.
Adam Nemetb6dc76f2015-03-10 18:54:19 +00001166 if (!CanDoRT && NumComparisons > 0) {
1167 emitAnalysis(LoopAccessReport()
1168 << "cannot check memory dependencies at runtime");
1169 DEBUG(dbgs() << "LAA: Can't vectorize with memory checks\n");
1170 PtrRtCheck.reset();
1171 CanVecMem = false;
1172 return;
1173 }
1174
Adam Nemet04563272015-02-01 16:56:15 +00001175 CanVecMem = true;
1176 }
1177 }
1178
Adam Nemet4bb90a72015-03-10 21:47:39 +00001179 if (CanVecMem)
1180 DEBUG(dbgs() << "LAA: No unsafe dependent memory operations in loop. We"
1181 << (NeedRTCheck ? "" : " don't")
1182 << " need a runtime memory check.\n");
1183 else {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001184 emitAnalysis(LoopAccessReport() <<
Adam Nemet04d41632015-02-19 19:14:34 +00001185 "unsafe dependent memory operations in loop");
Adam Nemet4bb90a72015-03-10 21:47:39 +00001186 DEBUG(dbgs() << "LAA: unsafe dependent memory operations in loop\n");
1187 }
Adam Nemet04563272015-02-01 16:56:15 +00001188}
1189
Adam Nemet01abb2c2015-02-18 03:43:19 +00001190bool LoopAccessInfo::blockNeedsPredication(BasicBlock *BB, Loop *TheLoop,
1191 DominatorTree *DT) {
Adam Nemet04563272015-02-01 16:56:15 +00001192 assert(TheLoop->contains(BB) && "Unknown block used");
1193
1194 // Blocks that do not dominate the latch need predication.
1195 BasicBlock* Latch = TheLoop->getLoopLatch();
1196 return !DT->dominates(BB, Latch);
1197}
1198
Adam Nemet2bd6e982015-02-19 19:15:15 +00001199void LoopAccessInfo::emitAnalysis(LoopAccessReport &Message) {
Adam Nemetc9228532015-02-19 19:14:56 +00001200 assert(!Report && "Multiple reports generated");
1201 Report = Message;
Adam Nemet04563272015-02-01 16:56:15 +00001202}
1203
Adam Nemet57ac7662015-02-19 19:15:21 +00001204bool LoopAccessInfo::isUniform(Value *V) const {
Adam Nemet04563272015-02-01 16:56:15 +00001205 return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
1206}
Adam Nemet7206d7a2015-02-06 18:31:04 +00001207
1208// FIXME: this function is currently a duplicate of the one in
1209// LoopVectorize.cpp.
1210static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
1211 Instruction *Loc) {
1212 if (FirstInst)
1213 return FirstInst;
1214 if (Instruction *I = dyn_cast<Instruction>(V))
1215 return I->getParent() == Loc->getParent() ? I : nullptr;
1216 return nullptr;
1217}
1218
Adam Nemetec1e2bb2015-03-10 18:54:26 +00001219std::pair<Instruction *, Instruction *> LoopAccessInfo::addRuntimeCheck(
1220 Instruction *Loc, const SmallVectorImpl<int> *PtrPartition) const {
Adam Nemet7206d7a2015-02-06 18:31:04 +00001221 if (!PtrRtCheck.Need)
Adam Nemet90fec842015-04-02 17:51:57 +00001222 return std::make_pair(nullptr, nullptr);
Adam Nemet7206d7a2015-02-06 18:31:04 +00001223
1224 unsigned NumPointers = PtrRtCheck.Pointers.size();
1225 SmallVector<TrackingVH<Value> , 2> Starts;
1226 SmallVector<TrackingVH<Value> , 2> Ends;
1227
1228 LLVMContext &Ctx = Loc->getContext();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001229 SCEVExpander Exp(*SE, DL, "induction");
Adam Nemet7206d7a2015-02-06 18:31:04 +00001230 Instruction *FirstInst = nullptr;
1231
1232 for (unsigned i = 0; i < NumPointers; ++i) {
1233 Value *Ptr = PtrRtCheck.Pointers[i];
1234 const SCEV *Sc = SE->getSCEV(Ptr);
1235
1236 if (SE->isLoopInvariant(Sc, TheLoop)) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001237 DEBUG(dbgs() << "LAA: Adding RT check for a loop invariant ptr:" <<
Adam Nemet04d41632015-02-19 19:14:34 +00001238 *Ptr <<"\n");
Adam Nemet7206d7a2015-02-06 18:31:04 +00001239 Starts.push_back(Ptr);
1240 Ends.push_back(Ptr);
1241 } else {
Adam Nemet339f42b2015-02-19 19:15:07 +00001242 DEBUG(dbgs() << "LAA: Adding RT check for range:" << *Ptr << '\n');
Adam Nemet7206d7a2015-02-06 18:31:04 +00001243 unsigned AS = Ptr->getType()->getPointerAddressSpace();
1244
1245 // Use this type for pointer arithmetic.
1246 Type *PtrArithTy = Type::getInt8PtrTy(Ctx, AS);
1247
1248 Value *Start = Exp.expandCodeFor(PtrRtCheck.Starts[i], PtrArithTy, Loc);
1249 Value *End = Exp.expandCodeFor(PtrRtCheck.Ends[i], PtrArithTy, Loc);
1250 Starts.push_back(Start);
1251 Ends.push_back(End);
1252 }
1253 }
1254
1255 IRBuilder<> ChkBuilder(Loc);
1256 // Our instructions might fold to a constant.
1257 Value *MemoryRuntimeCheck = nullptr;
1258 for (unsigned i = 0; i < NumPointers; ++i) {
1259 for (unsigned j = i+1; j < NumPointers; ++j) {
Adam Nemetec1e2bb2015-03-10 18:54:26 +00001260 if (!PtrRtCheck.needsChecking(i, j, PtrPartition))
Adam Nemet7206d7a2015-02-06 18:31:04 +00001261 continue;
1262
1263 unsigned AS0 = Starts[i]->getType()->getPointerAddressSpace();
1264 unsigned AS1 = Starts[j]->getType()->getPointerAddressSpace();
1265
1266 assert((AS0 == Ends[j]->getType()->getPointerAddressSpace()) &&
1267 (AS1 == Ends[i]->getType()->getPointerAddressSpace()) &&
1268 "Trying to bounds check pointers with different address spaces");
1269
1270 Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0);
1271 Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1);
1272
1273 Value *Start0 = ChkBuilder.CreateBitCast(Starts[i], PtrArithTy0, "bc");
1274 Value *Start1 = ChkBuilder.CreateBitCast(Starts[j], PtrArithTy1, "bc");
1275 Value *End0 = ChkBuilder.CreateBitCast(Ends[i], PtrArithTy1, "bc");
1276 Value *End1 = ChkBuilder.CreateBitCast(Ends[j], PtrArithTy0, "bc");
1277
1278 Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0");
1279 FirstInst = getFirstInst(FirstInst, Cmp0, Loc);
1280 Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1");
1281 FirstInst = getFirstInst(FirstInst, Cmp1, Loc);
1282 Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
1283 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1284 if (MemoryRuntimeCheck) {
1285 IsConflict = ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict,
1286 "conflict.rdx");
1287 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1288 }
1289 MemoryRuntimeCheck = IsConflict;
1290 }
1291 }
1292
Adam Nemet90fec842015-04-02 17:51:57 +00001293 if (!MemoryRuntimeCheck)
1294 return std::make_pair(nullptr, nullptr);
1295
Adam Nemet7206d7a2015-02-06 18:31:04 +00001296 // We have to do this trickery because the IRBuilder might fold the check to a
1297 // constant expression in which case there is no Instruction anchored in a
1298 // the block.
1299 Instruction *Check = BinaryOperator::CreateAnd(MemoryRuntimeCheck,
1300 ConstantInt::getTrue(Ctx));
1301 ChkBuilder.Insert(Check, "memcheck.conflict");
1302 FirstInst = getFirstInst(FirstInst, Check, Loc);
1303 return std::make_pair(FirstInst, Check);
1304}
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001305
1306LoopAccessInfo::LoopAccessInfo(Loop *L, ScalarEvolution *SE,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001307 const DataLayout &DL,
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001308 const TargetLibraryInfo *TLI, AliasAnalysis *AA,
Adam Nemet8bc61df2015-02-24 00:41:59 +00001309 DominatorTree *DT,
1310 const ValueToValueMap &Strides)
Adam Nemet98c4c5d2015-03-10 18:54:23 +00001311 : DepChecker(SE, L), NumComparisons(0), TheLoop(L), SE(SE), DL(DL),
1312 TLI(TLI), AA(AA), DT(DT), NumLoads(0), NumStores(0),
Adam Nemetce482502015-04-08 17:48:40 +00001313 MaxSafeDepDistBytes(-1U), CanVecMem(false),
1314 StoreToLoopInvariantAddress(false) {
Adam Nemet929c38e2015-02-19 19:15:10 +00001315 if (canAnalyzeLoop())
1316 analyzeLoop(Strides);
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001317}
1318
Adam Nemete91cc6e2015-02-19 19:15:19 +00001319void LoopAccessInfo::print(raw_ostream &OS, unsigned Depth) const {
1320 if (CanVecMem) {
Adam Nemet26da8e92015-04-14 01:12:55 +00001321 if (PtrRtCheck.Need)
Adam Nemete91cc6e2015-02-19 19:15:19 +00001322 OS.indent(Depth) << "Memory dependences are safe with run-time checks\n";
Adam Nemet26da8e92015-04-14 01:12:55 +00001323 else
1324 OS.indent(Depth) << "Memory dependences are safe\n";
Adam Nemete91cc6e2015-02-19 19:15:19 +00001325 }
1326
Adam Nemetce482502015-04-08 17:48:40 +00001327 OS.indent(Depth) << "Store to invariant address was "
1328 << (StoreToLoopInvariantAddress ? "" : "not ")
1329 << "found in loop.\n";
1330
Adam Nemete91cc6e2015-02-19 19:15:19 +00001331 if (Report)
1332 OS.indent(Depth) << "Report: " << Report->str() << "\n";
1333
Adam Nemet58913d62015-03-10 17:40:43 +00001334 if (auto *InterestingDependences = DepChecker.getInterestingDependences()) {
1335 OS.indent(Depth) << "Interesting Dependences:\n";
1336 for (auto &Dep : *InterestingDependences) {
1337 Dep.print(OS, Depth + 2, DepChecker.getMemoryInstructions());
1338 OS << "\n";
1339 }
1340 } else
1341 OS.indent(Depth) << "Too many interesting dependences, not recorded\n";
Adam Nemete91cc6e2015-02-19 19:15:19 +00001342
1343 // List the pair of accesses need run-time checks to prove independence.
1344 PtrRtCheck.print(OS, Depth);
1345 OS << "\n";
1346}
1347
Adam Nemet8bc61df2015-02-24 00:41:59 +00001348const LoopAccessInfo &
1349LoopAccessAnalysis::getInfo(Loop *L, const ValueToValueMap &Strides) {
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001350 auto &LAI = LoopAccessInfoMap[L];
1351
1352#ifndef NDEBUG
1353 assert((!LAI || LAI->NumSymbolicStrides == Strides.size()) &&
1354 "Symbolic strides changed for loop");
1355#endif
1356
1357 if (!LAI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001358 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001359 LAI = llvm::make_unique<LoopAccessInfo>(L, SE, DL, TLI, AA, DT, Strides);
1360#ifndef NDEBUG
1361 LAI->NumSymbolicStrides = Strides.size();
1362#endif
1363 }
1364 return *LAI.get();
1365}
1366
Adam Nemete91cc6e2015-02-19 19:15:19 +00001367void LoopAccessAnalysis::print(raw_ostream &OS, const Module *M) const {
1368 LoopAccessAnalysis &LAA = *const_cast<LoopAccessAnalysis *>(this);
1369
1370 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1371 ValueToValueMap NoSymbolicStrides;
1372
1373 for (Loop *TopLevelLoop : *LI)
1374 for (Loop *L : depth_first(TopLevelLoop)) {
1375 OS.indent(2) << L->getHeader()->getName() << ":\n";
1376 auto &LAI = LAA.getInfo(L, NoSymbolicStrides);
1377 LAI.print(OS, 4);
1378 }
1379}
1380
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001381bool LoopAccessAnalysis::runOnFunction(Function &F) {
1382 SE = &getAnalysis<ScalarEvolution>();
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001383 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
1384 TLI = TLIP ? &TLIP->getTLI() : nullptr;
1385 AA = &getAnalysis<AliasAnalysis>();
1386 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1387
1388 return false;
1389}
1390
1391void LoopAccessAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
1392 AU.addRequired<ScalarEvolution>();
1393 AU.addRequired<AliasAnalysis>();
1394 AU.addRequired<DominatorTreeWrapperPass>();
Adam Nemete91cc6e2015-02-19 19:15:19 +00001395 AU.addRequired<LoopInfoWrapperPass>();
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001396
1397 AU.setPreservesAll();
1398}
1399
1400char LoopAccessAnalysis::ID = 0;
1401static const char laa_name[] = "Loop Access Analysis";
1402#define LAA_NAME "loop-accesses"
1403
1404INITIALIZE_PASS_BEGIN(LoopAccessAnalysis, LAA_NAME, laa_name, false, true)
1405INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
1406INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
1407INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Adam Nemete91cc6e2015-02-19 19:15:19 +00001408INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001409INITIALIZE_PASS_END(LoopAccessAnalysis, LAA_NAME, laa_name, false, true)
1410
1411namespace llvm {
1412 Pass *createLAAPass() {
1413 return new LoopAccessAnalysis();
1414 }
1415}