blob: f21afd3ebbb3b733e015e8f16d3a4503cf059d75 [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 Nemete2b885c2015-04-23 20:09:20 +0000202 AccessAnalysis(const DataLayout &Dl, AliasAnalysis *AA, LoopInfo *LI,
Adam Nemetdee666b2015-03-10 17:40:34 +0000203 MemoryDepChecker::DepCandidates &DA)
Adam Nemete2b885c2015-04-23 20:09:20 +0000204 : DL(Dl), AST(*AA), LI(LI), 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(); }
Adam Nemetdf3dc5b2015-05-18 15:37:03 +0000238
239 /// We decided that no dependence analysis would be used. Reset the state.
240 void resetDepChecks(MemoryDepChecker &DepChecker) {
241 CheckDeps.clear();
242 DepChecker.clearInterestingDependences();
243 }
Adam Nemet04563272015-02-01 16:56:15 +0000244
245 MemAccessInfoSet &getDependenciesToCheck() { return CheckDeps; }
246
247private:
248 typedef SetVector<MemAccessInfo> PtrAccessSet;
249
250 /// \brief Go over all memory access and check whether runtime pointer checks
251 /// are needed /// and build sets of dependency check candidates.
252 void processMemAccesses();
253
254 /// Set of all accesses.
255 PtrAccessSet Accesses;
256
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000257 const DataLayout &DL;
258
Adam Nemet04563272015-02-01 16:56:15 +0000259 /// Set of accesses that need a further dependence check.
260 MemAccessInfoSet CheckDeps;
261
262 /// Set of pointers that are read only.
263 SmallPtrSet<Value*, 16> ReadOnlyPtr;
264
Adam Nemet04563272015-02-01 16:56:15 +0000265 /// An alias set tracker to partition the access set by underlying object and
266 //intrinsic property (such as TBAA metadata).
267 AliasSetTracker AST;
268
Adam Nemete2b885c2015-04-23 20:09:20 +0000269 LoopInfo *LI;
270
Adam Nemet04563272015-02-01 16:56:15 +0000271 /// Sets of potentially dependent accesses - members of one set share an
272 /// underlying pointer. The set "CheckDeps" identfies which sets really need a
273 /// dependence check.
Adam Nemetdee666b2015-03-10 17:40:34 +0000274 MemoryDepChecker::DepCandidates &DepCands;
Adam Nemet04563272015-02-01 16:56:15 +0000275
276 bool IsRTCheckNeeded;
277};
278
279} // end anonymous namespace
280
281/// \brief Check whether a pointer can participate in a runtime bounds check.
Adam Nemet8bc61df2015-02-24 00:41:59 +0000282static bool hasComputableBounds(ScalarEvolution *SE,
283 const ValueToValueMap &Strides, Value *Ptr) {
Adam Nemet04563272015-02-01 16:56:15 +0000284 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
285 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
286 if (!AR)
287 return false;
288
289 return AR->isAffine();
290}
291
292/// \brief Check the stride of the pointer and ensure that it does not wrap in
293/// the address space.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000294static int isStridedPtr(ScalarEvolution *SE, Value *Ptr, const Loop *Lp,
295 const ValueToValueMap &StridesMap);
Adam Nemet04563272015-02-01 16:56:15 +0000296
297bool AccessAnalysis::canCheckPtrAtRT(
Adam Nemet8bc61df2015-02-24 00:41:59 +0000298 LoopAccessInfo::RuntimePointerCheck &RtCheck, unsigned &NumComparisons,
299 ScalarEvolution *SE, Loop *TheLoop, const ValueToValueMap &StridesMap,
300 bool ShouldCheckStride) {
Adam Nemet04563272015-02-01 16:56:15 +0000301 // Find pointers with computable bounds. We are going to use this information
302 // to place a runtime bound check.
303 bool CanDoRT = true;
304
305 bool IsDepCheckNeeded = isDependencyCheckNeeded();
306 NumComparisons = 0;
307
308 // We assign a consecutive id to access from different alias sets.
309 // Accesses between different groups doesn't need to be checked.
310 unsigned ASId = 1;
311 for (auto &AS : AST) {
312 unsigned NumReadPtrChecks = 0;
313 unsigned NumWritePtrChecks = 0;
314
315 // We assign consecutive id to access from different dependence sets.
316 // Accesses within the same set don't need a runtime check.
317 unsigned RunningDepId = 1;
318 DenseMap<Value *, unsigned> DepSetId;
319
320 for (auto A : AS) {
321 Value *Ptr = A.getValue();
322 bool IsWrite = Accesses.count(MemAccessInfo(Ptr, true));
323 MemAccessInfo Access(Ptr, IsWrite);
324
325 if (IsWrite)
326 ++NumWritePtrChecks;
327 else
328 ++NumReadPtrChecks;
329
330 if (hasComputableBounds(SE, StridesMap, Ptr) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000331 // When we run after a failing dependency check we have to make sure
332 // we don't have wrapping pointers.
Adam Nemet04563272015-02-01 16:56:15 +0000333 (!ShouldCheckStride ||
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000334 isStridedPtr(SE, Ptr, TheLoop, StridesMap) == 1)) {
Adam Nemet04563272015-02-01 16:56:15 +0000335 // The id of the dependence set.
336 unsigned DepId;
337
338 if (IsDepCheckNeeded) {
339 Value *Leader = DepCands.getLeaderValue(Access).getPointer();
340 unsigned &LeaderId = DepSetId[Leader];
341 if (!LeaderId)
342 LeaderId = RunningDepId++;
343 DepId = LeaderId;
344 } else
345 // Each access has its own dependence set.
346 DepId = RunningDepId++;
347
348 RtCheck.insert(SE, TheLoop, Ptr, IsWrite, DepId, ASId, StridesMap);
349
Adam Nemet339f42b2015-02-19 19:15:07 +0000350 DEBUG(dbgs() << "LAA: Found a runtime check ptr:" << *Ptr << '\n');
Adam Nemet04563272015-02-01 16:56:15 +0000351 } else {
Adam Nemetf10ca272015-05-18 15:36:52 +0000352 DEBUG(dbgs() << "LAA: Can't find bounds for ptr:" << *Ptr << '\n');
Adam Nemet04563272015-02-01 16:56:15 +0000353 CanDoRT = false;
354 }
355 }
356
357 if (IsDepCheckNeeded && CanDoRT && RunningDepId == 2)
358 NumComparisons += 0; // Only one dependence set.
359 else {
360 NumComparisons += (NumWritePtrChecks * (NumReadPtrChecks +
361 NumWritePtrChecks - 1));
362 }
363
364 ++ASId;
365 }
366
367 // If the pointers that we would use for the bounds comparison have different
368 // address spaces, assume the values aren't directly comparable, so we can't
369 // use them for the runtime check. We also have to assume they could
370 // overlap. In the future there should be metadata for whether address spaces
371 // are disjoint.
372 unsigned NumPointers = RtCheck.Pointers.size();
373 for (unsigned i = 0; i < NumPointers; ++i) {
374 for (unsigned j = i + 1; j < NumPointers; ++j) {
375 // Only need to check pointers between two different dependency sets.
376 if (RtCheck.DependencySetId[i] == RtCheck.DependencySetId[j])
377 continue;
378 // Only need to check pointers in the same alias set.
379 if (RtCheck.AliasSetId[i] != RtCheck.AliasSetId[j])
380 continue;
381
382 Value *PtrI = RtCheck.Pointers[i];
383 Value *PtrJ = RtCheck.Pointers[j];
384
385 unsigned ASi = PtrI->getType()->getPointerAddressSpace();
386 unsigned ASj = PtrJ->getType()->getPointerAddressSpace();
387 if (ASi != ASj) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000388 DEBUG(dbgs() << "LAA: Runtime check would require comparison between"
Adam Nemet04d41632015-02-19 19:14:34 +0000389 " different address spaces\n");
Adam Nemet04563272015-02-01 16:56:15 +0000390 return false;
391 }
392 }
393 }
394
395 return CanDoRT;
396}
397
398void AccessAnalysis::processMemAccesses() {
399 // We process the set twice: first we process read-write pointers, last we
400 // process read-only pointers. This allows us to skip dependence tests for
401 // read-only pointers.
402
Adam Nemet339f42b2015-02-19 19:15:07 +0000403 DEBUG(dbgs() << "LAA: Processing memory accesses...\n");
Adam Nemet04563272015-02-01 16:56:15 +0000404 DEBUG(dbgs() << " AST: "; AST.dump());
Adam Nemet9c926572015-03-10 17:40:37 +0000405 DEBUG(dbgs() << "LAA: Accesses(" << Accesses.size() << "):\n");
Adam Nemet04563272015-02-01 16:56:15 +0000406 DEBUG({
407 for (auto A : Accesses)
408 dbgs() << "\t" << *A.getPointer() << " (" <<
409 (A.getInt() ? "write" : (ReadOnlyPtr.count(A.getPointer()) ?
410 "read-only" : "read")) << ")\n";
411 });
412
413 // The AliasSetTracker has nicely partitioned our pointers by metadata
414 // compatibility and potential for underlying-object overlap. As a result, we
415 // only need to check for potential pointer dependencies within each alias
416 // set.
417 for (auto &AS : AST) {
418 // Note that both the alias-set tracker and the alias sets themselves used
419 // linked lists internally and so the iteration order here is deterministic
420 // (matching the original instruction order within each set).
421
422 bool SetHasWrite = false;
423
424 // Map of pointers to last access encountered.
425 typedef DenseMap<Value*, MemAccessInfo> UnderlyingObjToAccessMap;
426 UnderlyingObjToAccessMap ObjToLastAccess;
427
428 // Set of access to check after all writes have been processed.
429 PtrAccessSet DeferredAccesses;
430
431 // Iterate over each alias set twice, once to process read/write pointers,
432 // and then to process read-only pointers.
433 for (int SetIteration = 0; SetIteration < 2; ++SetIteration) {
434 bool UseDeferred = SetIteration > 0;
435 PtrAccessSet &S = UseDeferred ? DeferredAccesses : Accesses;
436
437 for (auto AV : AS) {
438 Value *Ptr = AV.getValue();
439
440 // For a single memory access in AliasSetTracker, Accesses may contain
441 // both read and write, and they both need to be handled for CheckDeps.
442 for (auto AC : S) {
443 if (AC.getPointer() != Ptr)
444 continue;
445
446 bool IsWrite = AC.getInt();
447
448 // If we're using the deferred access set, then it contains only
449 // reads.
450 bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite;
451 if (UseDeferred && !IsReadOnlyPtr)
452 continue;
453 // Otherwise, the pointer must be in the PtrAccessSet, either as a
454 // read or a write.
455 assert(((IsReadOnlyPtr && UseDeferred) || IsWrite ||
456 S.count(MemAccessInfo(Ptr, false))) &&
457 "Alias-set pointer not in the access set?");
458
459 MemAccessInfo Access(Ptr, IsWrite);
460 DepCands.insert(Access);
461
462 // Memorize read-only pointers for later processing and skip them in
463 // the first round (they need to be checked after we have seen all
464 // write pointers). Note: we also mark pointer that are not
465 // consecutive as "read-only" pointers (so that we check
466 // "a[b[i]] +="). Hence, we need the second check for "!IsWrite".
467 if (!UseDeferred && IsReadOnlyPtr) {
468 DeferredAccesses.insert(Access);
469 continue;
470 }
471
472 // If this is a write - check other reads and writes for conflicts. If
473 // this is a read only check other writes for conflicts (but only if
474 // there is no other write to the ptr - this is an optimization to
475 // catch "a[i] = a[i] + " without having to do a dependence check).
476 if ((IsWrite || IsReadOnlyPtr) && SetHasWrite) {
477 CheckDeps.insert(Access);
478 IsRTCheckNeeded = true;
479 }
480
481 if (IsWrite)
482 SetHasWrite = true;
483
484 // Create sets of pointers connected by a shared alias set and
485 // underlying object.
486 typedef SmallVector<Value *, 16> ValueVector;
487 ValueVector TempObjects;
Adam Nemete2b885c2015-04-23 20:09:20 +0000488
489 GetUnderlyingObjects(Ptr, TempObjects, DL, LI);
490 DEBUG(dbgs() << "Underlying objects for pointer " << *Ptr << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000491 for (Value *UnderlyingObj : TempObjects) {
492 UnderlyingObjToAccessMap::iterator Prev =
493 ObjToLastAccess.find(UnderlyingObj);
494 if (Prev != ObjToLastAccess.end())
495 DepCands.unionSets(Access, Prev->second);
496
497 ObjToLastAccess[UnderlyingObj] = Access;
Adam Nemete2b885c2015-04-23 20:09:20 +0000498 DEBUG(dbgs() << " " << *UnderlyingObj << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000499 }
500 }
501 }
502 }
503 }
504}
505
Adam Nemet04563272015-02-01 16:56:15 +0000506static bool isInBoundsGep(Value *Ptr) {
507 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
508 return GEP->isInBounds();
509 return false;
510}
511
512/// \brief Check whether the access through \p Ptr has a constant stride.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000513static int isStridedPtr(ScalarEvolution *SE, Value *Ptr, const Loop *Lp,
514 const ValueToValueMap &StridesMap) {
Adam Nemet04563272015-02-01 16:56:15 +0000515 const Type *Ty = Ptr->getType();
516 assert(Ty->isPointerTy() && "Unexpected non-ptr");
517
518 // Make sure that the pointer does not point to aggregate types.
519 const PointerType *PtrTy = cast<PointerType>(Ty);
520 if (PtrTy->getElementType()->isAggregateType()) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000521 DEBUG(dbgs() << "LAA: Bad stride - Not a pointer to a scalar type"
522 << *Ptr << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000523 return 0;
524 }
525
526 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, StridesMap, Ptr);
527
528 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
529 if (!AR) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000530 DEBUG(dbgs() << "LAA: Bad stride - Not an AddRecExpr pointer "
Adam Nemet04d41632015-02-19 19:14:34 +0000531 << *Ptr << " SCEV: " << *PtrScev << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000532 return 0;
533 }
534
535 // The accesss function must stride over the innermost loop.
536 if (Lp != AR->getLoop()) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000537 DEBUG(dbgs() << "LAA: Bad stride - Not striding over innermost loop " <<
Adam Nemet04d41632015-02-19 19:14:34 +0000538 *Ptr << " SCEV: " << *PtrScev << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000539 }
540
541 // The address calculation must not wrap. Otherwise, a dependence could be
542 // inverted.
543 // An inbounds getelementptr that is a AddRec with a unit stride
544 // cannot wrap per definition. The unit stride requirement is checked later.
545 // An getelementptr without an inbounds attribute and unit stride would have
546 // to access the pointer value "0" which is undefined behavior in address
547 // space 0, therefore we can also vectorize this case.
548 bool IsInBoundsGEP = isInBoundsGep(Ptr);
549 bool IsNoWrapAddRec = AR->getNoWrapFlags(SCEV::NoWrapMask);
550 bool IsInAddressSpaceZero = PtrTy->getAddressSpace() == 0;
551 if (!IsNoWrapAddRec && !IsInBoundsGEP && !IsInAddressSpaceZero) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000552 DEBUG(dbgs() << "LAA: Bad stride - Pointer may wrap in the address space "
Adam Nemet04d41632015-02-19 19:14:34 +0000553 << *Ptr << " SCEV: " << *PtrScev << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000554 return 0;
555 }
556
557 // Check the step is constant.
558 const SCEV *Step = AR->getStepRecurrence(*SE);
559
560 // Calculate the pointer stride and check if it is consecutive.
561 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
562 if (!C) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000563 DEBUG(dbgs() << "LAA: Bad stride - Not a constant strided " << *Ptr <<
Adam Nemet04d41632015-02-19 19:14:34 +0000564 " SCEV: " << *PtrScev << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000565 return 0;
566 }
567
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000568 auto &DL = Lp->getHeader()->getModule()->getDataLayout();
569 int64_t Size = DL.getTypeAllocSize(PtrTy->getElementType());
Adam Nemet04563272015-02-01 16:56:15 +0000570 const APInt &APStepVal = C->getValue()->getValue();
571
572 // Huge step value - give up.
573 if (APStepVal.getBitWidth() > 64)
574 return 0;
575
576 int64_t StepVal = APStepVal.getSExtValue();
577
578 // Strided access.
579 int64_t Stride = StepVal / Size;
580 int64_t Rem = StepVal % Size;
581 if (Rem)
582 return 0;
583
584 // If the SCEV could wrap but we have an inbounds gep with a unit stride we
585 // know we can't "wrap around the address space". In case of address space
586 // zero we know that this won't happen without triggering undefined behavior.
587 if (!IsNoWrapAddRec && (IsInBoundsGEP || IsInAddressSpaceZero) &&
588 Stride != 1 && Stride != -1)
589 return 0;
590
591 return Stride;
592}
593
Adam Nemet9c926572015-03-10 17:40:37 +0000594bool MemoryDepChecker::Dependence::isSafeForVectorization(DepType Type) {
595 switch (Type) {
596 case NoDep:
597 case Forward:
598 case BackwardVectorizable:
599 return true;
600
601 case Unknown:
602 case ForwardButPreventsForwarding:
603 case Backward:
604 case BackwardVectorizableButPreventsForwarding:
605 return false;
606 }
David Majnemerd388e932015-03-10 20:23:29 +0000607 llvm_unreachable("unexpected DepType!");
Adam Nemet9c926572015-03-10 17:40:37 +0000608}
609
610bool MemoryDepChecker::Dependence::isInterestingDependence(DepType Type) {
611 switch (Type) {
612 case NoDep:
613 case Forward:
614 return false;
615
616 case BackwardVectorizable:
617 case Unknown:
618 case ForwardButPreventsForwarding:
619 case Backward:
620 case BackwardVectorizableButPreventsForwarding:
621 return true;
622 }
David Majnemerd388e932015-03-10 20:23:29 +0000623 llvm_unreachable("unexpected DepType!");
Adam Nemet9c926572015-03-10 17:40:37 +0000624}
625
626bool MemoryDepChecker::Dependence::isPossiblyBackward() const {
627 switch (Type) {
628 case NoDep:
629 case Forward:
630 case ForwardButPreventsForwarding:
631 return false;
632
633 case Unknown:
634 case BackwardVectorizable:
635 case Backward:
636 case BackwardVectorizableButPreventsForwarding:
637 return true;
638 }
David Majnemerd388e932015-03-10 20:23:29 +0000639 llvm_unreachable("unexpected DepType!");
Adam Nemet9c926572015-03-10 17:40:37 +0000640}
641
Adam Nemet04563272015-02-01 16:56:15 +0000642bool MemoryDepChecker::couldPreventStoreLoadForward(unsigned Distance,
643 unsigned TypeByteSize) {
644 // If loads occur at a distance that is not a multiple of a feasible vector
645 // factor store-load forwarding does not take place.
646 // Positive dependences might cause troubles because vectorizing them might
647 // prevent store-load forwarding making vectorized code run a lot slower.
648 // a[i] = a[i-3] ^ a[i-8];
649 // The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
650 // hence on your typical architecture store-load forwarding does not take
651 // place. Vectorizing in such cases does not make sense.
652 // Store-load forwarding distance.
653 const unsigned NumCyclesForStoreLoadThroughMemory = 8*TypeByteSize;
654 // Maximum vector factor.
Adam Nemetf219c642015-02-19 19:14:52 +0000655 unsigned MaxVFWithoutSLForwardIssues =
656 VectorizerParams::MaxVectorWidth * TypeByteSize;
Adam Nemet04d41632015-02-19 19:14:34 +0000657 if(MaxSafeDepDistBytes < MaxVFWithoutSLForwardIssues)
Adam Nemet04563272015-02-01 16:56:15 +0000658 MaxVFWithoutSLForwardIssues = MaxSafeDepDistBytes;
659
660 for (unsigned vf = 2*TypeByteSize; vf <= MaxVFWithoutSLForwardIssues;
661 vf *= 2) {
662 if (Distance % vf && Distance / vf < NumCyclesForStoreLoadThroughMemory) {
663 MaxVFWithoutSLForwardIssues = (vf >>=1);
664 break;
665 }
666 }
667
Adam Nemet04d41632015-02-19 19:14:34 +0000668 if (MaxVFWithoutSLForwardIssues< 2*TypeByteSize) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000669 DEBUG(dbgs() << "LAA: Distance " << Distance <<
Adam Nemet04d41632015-02-19 19:14:34 +0000670 " that could cause a store-load forwarding conflict\n");
Adam Nemet04563272015-02-01 16:56:15 +0000671 return true;
672 }
673
674 if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes &&
Adam Nemetf219c642015-02-19 19:14:52 +0000675 MaxVFWithoutSLForwardIssues !=
676 VectorizerParams::MaxVectorWidth * TypeByteSize)
Adam Nemet04563272015-02-01 16:56:15 +0000677 MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues;
678 return false;
679}
680
Adam Nemet9c926572015-03-10 17:40:37 +0000681MemoryDepChecker::Dependence::DepType
682MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
683 const MemAccessInfo &B, unsigned BIdx,
684 const ValueToValueMap &Strides) {
Adam Nemet04563272015-02-01 16:56:15 +0000685 assert (AIdx < BIdx && "Must pass arguments in program order");
686
687 Value *APtr = A.getPointer();
688 Value *BPtr = B.getPointer();
689 bool AIsWrite = A.getInt();
690 bool BIsWrite = B.getInt();
691
692 // Two reads are independent.
693 if (!AIsWrite && !BIsWrite)
Adam Nemet9c926572015-03-10 17:40:37 +0000694 return Dependence::NoDep;
Adam Nemet04563272015-02-01 16:56:15 +0000695
696 // We cannot check pointers in different address spaces.
697 if (APtr->getType()->getPointerAddressSpace() !=
698 BPtr->getType()->getPointerAddressSpace())
Adam Nemet9c926572015-03-10 17:40:37 +0000699 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +0000700
701 const SCEV *AScev = replaceSymbolicStrideSCEV(SE, Strides, APtr);
702 const SCEV *BScev = replaceSymbolicStrideSCEV(SE, Strides, BPtr);
703
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000704 int StrideAPtr = isStridedPtr(SE, APtr, InnermostLoop, Strides);
705 int StrideBPtr = isStridedPtr(SE, BPtr, InnermostLoop, Strides);
Adam Nemet04563272015-02-01 16:56:15 +0000706
707 const SCEV *Src = AScev;
708 const SCEV *Sink = BScev;
709
710 // If the induction step is negative we have to invert source and sink of the
711 // dependence.
712 if (StrideAPtr < 0) {
713 //Src = BScev;
714 //Sink = AScev;
715 std::swap(APtr, BPtr);
716 std::swap(Src, Sink);
717 std::swap(AIsWrite, BIsWrite);
718 std::swap(AIdx, BIdx);
719 std::swap(StrideAPtr, StrideBPtr);
720 }
721
722 const SCEV *Dist = SE->getMinusSCEV(Sink, Src);
723
Adam Nemet339f42b2015-02-19 19:15:07 +0000724 DEBUG(dbgs() << "LAA: Src Scev: " << *Src << "Sink Scev: " << *Sink
Adam Nemet04d41632015-02-19 19:14:34 +0000725 << "(Induction step: " << StrideAPtr << ")\n");
Adam Nemet339f42b2015-02-19 19:15:07 +0000726 DEBUG(dbgs() << "LAA: Distance for " << *InstMap[AIdx] << " to "
Adam Nemet04d41632015-02-19 19:14:34 +0000727 << *InstMap[BIdx] << ": " << *Dist << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000728
729 // Need consecutive accesses. We don't want to vectorize
730 // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in
731 // the address space.
732 if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){
733 DEBUG(dbgs() << "Non-consecutive pointer access\n");
Adam Nemet9c926572015-03-10 17:40:37 +0000734 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +0000735 }
736
737 const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist);
738 if (!C) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000739 DEBUG(dbgs() << "LAA: Dependence because of non-constant distance\n");
Adam Nemet04563272015-02-01 16:56:15 +0000740 ShouldRetryWithRuntimeCheck = true;
Adam Nemet9c926572015-03-10 17:40:37 +0000741 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +0000742 }
743
744 Type *ATy = APtr->getType()->getPointerElementType();
745 Type *BTy = BPtr->getType()->getPointerElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000746 auto &DL = InnermostLoop->getHeader()->getModule()->getDataLayout();
747 unsigned TypeByteSize = DL.getTypeAllocSize(ATy);
Adam Nemet04563272015-02-01 16:56:15 +0000748
749 // Negative distances are not plausible dependencies.
750 const APInt &Val = C->getValue()->getValue();
751 if (Val.isNegative()) {
752 bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
753 if (IsTrueDataDependence &&
754 (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) ||
755 ATy != BTy))
Adam Nemet9c926572015-03-10 17:40:37 +0000756 return Dependence::ForwardButPreventsForwarding;
Adam Nemet04563272015-02-01 16:56:15 +0000757
Adam Nemet339f42b2015-02-19 19:15:07 +0000758 DEBUG(dbgs() << "LAA: Dependence is negative: NoDep\n");
Adam Nemet9c926572015-03-10 17:40:37 +0000759 return Dependence::Forward;
Adam Nemet04563272015-02-01 16:56:15 +0000760 }
761
762 // Write to the same location with the same size.
763 // Could be improved to assert type sizes are the same (i32 == float, etc).
764 if (Val == 0) {
765 if (ATy == BTy)
Adam Nemet9c926572015-03-10 17:40:37 +0000766 return Dependence::NoDep;
Adam Nemet339f42b2015-02-19 19:15:07 +0000767 DEBUG(dbgs() << "LAA: Zero dependence difference but different types\n");
Adam Nemet9c926572015-03-10 17:40:37 +0000768 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +0000769 }
770
771 assert(Val.isStrictlyPositive() && "Expect a positive value");
772
Adam Nemet04563272015-02-01 16:56:15 +0000773 if (ATy != BTy) {
Adam Nemet04d41632015-02-19 19:14:34 +0000774 DEBUG(dbgs() <<
Adam Nemet339f42b2015-02-19 19:15:07 +0000775 "LAA: ReadWrite-Write positive dependency with different types\n");
Adam Nemet9c926572015-03-10 17:40:37 +0000776 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +0000777 }
778
779 unsigned Distance = (unsigned) Val.getZExtValue();
780
781 // Bail out early if passed-in parameters make vectorization not feasible.
Adam Nemetf219c642015-02-19 19:14:52 +0000782 unsigned ForcedFactor = (VectorizerParams::VectorizationFactor ?
783 VectorizerParams::VectorizationFactor : 1);
784 unsigned ForcedUnroll = (VectorizerParams::VectorizationInterleave ?
785 VectorizerParams::VectorizationInterleave : 1);
Adam Nemet04563272015-02-01 16:56:15 +0000786
787 // The distance must be bigger than the size needed for a vectorized version
788 // of the operation and the size of the vectorized operation must not be
789 // bigger than the currrent maximum size.
790 if (Distance < 2*TypeByteSize ||
791 2*TypeByteSize > MaxSafeDepDistBytes ||
792 Distance < TypeByteSize * ForcedUnroll * ForcedFactor) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000793 DEBUG(dbgs() << "LAA: Failure because of Positive distance "
Adam Nemet04d41632015-02-19 19:14:34 +0000794 << Val.getSExtValue() << '\n');
Adam Nemet9c926572015-03-10 17:40:37 +0000795 return Dependence::Backward;
Adam Nemet04563272015-02-01 16:56:15 +0000796 }
797
Adam Nemet9cc0c392015-02-26 17:58:48 +0000798 // Positive distance bigger than max vectorization factor.
Adam Nemet04563272015-02-01 16:56:15 +0000799 MaxSafeDepDistBytes = Distance < MaxSafeDepDistBytes ?
800 Distance : MaxSafeDepDistBytes;
801
802 bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
803 if (IsTrueDataDependence &&
804 couldPreventStoreLoadForward(Distance, TypeByteSize))
Adam Nemet9c926572015-03-10 17:40:37 +0000805 return Dependence::BackwardVectorizableButPreventsForwarding;
Adam Nemet04563272015-02-01 16:56:15 +0000806
Adam Nemet339f42b2015-02-19 19:15:07 +0000807 DEBUG(dbgs() << "LAA: Positive distance " << Val.getSExtValue() <<
Adam Nemet04d41632015-02-19 19:14:34 +0000808 " with max VF = " << MaxSafeDepDistBytes / TypeByteSize << '\n');
Adam Nemet04563272015-02-01 16:56:15 +0000809
Adam Nemet9c926572015-03-10 17:40:37 +0000810 return Dependence::BackwardVectorizable;
Adam Nemet04563272015-02-01 16:56:15 +0000811}
812
Adam Nemetdee666b2015-03-10 17:40:34 +0000813bool MemoryDepChecker::areDepsSafe(DepCandidates &AccessSets,
Adam Nemet04563272015-02-01 16:56:15 +0000814 MemAccessInfoSet &CheckDeps,
Adam Nemet8bc61df2015-02-24 00:41:59 +0000815 const ValueToValueMap &Strides) {
Adam Nemet04563272015-02-01 16:56:15 +0000816
817 MaxSafeDepDistBytes = -1U;
818 while (!CheckDeps.empty()) {
819 MemAccessInfo CurAccess = *CheckDeps.begin();
820
821 // Get the relevant memory access set.
822 EquivalenceClasses<MemAccessInfo>::iterator I =
823 AccessSets.findValue(AccessSets.getLeaderValue(CurAccess));
824
825 // Check accesses within this set.
826 EquivalenceClasses<MemAccessInfo>::member_iterator AI, AE;
827 AI = AccessSets.member_begin(I), AE = AccessSets.member_end();
828
829 // Check every access pair.
830 while (AI != AE) {
831 CheckDeps.erase(*AI);
832 EquivalenceClasses<MemAccessInfo>::member_iterator OI = std::next(AI);
833 while (OI != AE) {
834 // Check every accessing instruction pair in program order.
835 for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(),
836 I1E = Accesses[*AI].end(); I1 != I1E; ++I1)
837 for (std::vector<unsigned>::iterator I2 = Accesses[*OI].begin(),
838 I2E = Accesses[*OI].end(); I2 != I2E; ++I2) {
Adam Nemet9c926572015-03-10 17:40:37 +0000839 auto A = std::make_pair(&*AI, *I1);
840 auto B = std::make_pair(&*OI, *I2);
841
842 assert(*I1 != *I2);
843 if (*I1 > *I2)
844 std::swap(A, B);
845
846 Dependence::DepType Type =
847 isDependent(*A.first, A.second, *B.first, B.second, Strides);
848 SafeForVectorization &= Dependence::isSafeForVectorization(Type);
849
850 // Gather dependences unless we accumulated MaxInterestingDependence
851 // dependences. In that case return as soon as we find the first
852 // unsafe dependence. This puts a limit on this quadratic
853 // algorithm.
854 if (RecordInterestingDependences) {
855 if (Dependence::isInterestingDependence(Type))
856 InterestingDependences.push_back(
857 Dependence(A.second, B.second, Type));
858
859 if (InterestingDependences.size() >= MaxInterestingDependence) {
860 RecordInterestingDependences = false;
861 InterestingDependences.clear();
862 DEBUG(dbgs() << "Too many dependences, stopped recording\n");
863 }
864 }
865 if (!RecordInterestingDependences && !SafeForVectorization)
Adam Nemet04563272015-02-01 16:56:15 +0000866 return false;
867 }
868 ++OI;
869 }
870 AI++;
871 }
872 }
Adam Nemet9c926572015-03-10 17:40:37 +0000873
874 DEBUG(dbgs() << "Total Interesting Dependences: "
875 << InterestingDependences.size() << "\n");
876 return SafeForVectorization;
Adam Nemet04563272015-02-01 16:56:15 +0000877}
878
Adam Nemetec1e2bb2015-03-10 18:54:26 +0000879SmallVector<Instruction *, 4>
880MemoryDepChecker::getInstructionsForAccess(Value *Ptr, bool isWrite) const {
881 MemAccessInfo Access(Ptr, isWrite);
882 auto &IndexVector = Accesses.find(Access)->second;
883
884 SmallVector<Instruction *, 4> Insts;
885 std::transform(IndexVector.begin(), IndexVector.end(),
886 std::back_inserter(Insts),
887 [&](unsigned Idx) { return this->InstMap[Idx]; });
888 return Insts;
889}
890
Adam Nemet58913d62015-03-10 17:40:43 +0000891const char *MemoryDepChecker::Dependence::DepName[] = {
892 "NoDep", "Unknown", "Forward", "ForwardButPreventsForwarding", "Backward",
893 "BackwardVectorizable", "BackwardVectorizableButPreventsForwarding"};
894
895void MemoryDepChecker::Dependence::print(
896 raw_ostream &OS, unsigned Depth,
897 const SmallVectorImpl<Instruction *> &Instrs) const {
898 OS.indent(Depth) << DepName[Type] << ":\n";
899 OS.indent(Depth + 2) << *Instrs[Source] << " -> \n";
900 OS.indent(Depth + 2) << *Instrs[Destination] << "\n";
901}
902
Adam Nemet929c38e2015-02-19 19:15:10 +0000903bool LoopAccessInfo::canAnalyzeLoop() {
Adam Nemet8dcb3b62015-04-17 22:43:10 +0000904 // We need to have a loop header.
905 DEBUG(dbgs() << "LAA: Found a loop: " <<
906 TheLoop->getHeader()->getName() << '\n');
907
Adam Nemet929c38e2015-02-19 19:15:10 +0000908 // We can only analyze innermost loops.
909 if (!TheLoop->empty()) {
Adam Nemet8dcb3b62015-04-17 22:43:10 +0000910 DEBUG(dbgs() << "LAA: loop is not the innermost loop\n");
Adam Nemet2bd6e982015-02-19 19:15:15 +0000911 emitAnalysis(LoopAccessReport() << "loop is not the innermost loop");
Adam Nemet929c38e2015-02-19 19:15:10 +0000912 return false;
913 }
914
915 // We must have a single backedge.
916 if (TheLoop->getNumBackEdges() != 1) {
Adam Nemet8dcb3b62015-04-17 22:43:10 +0000917 DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n");
Adam Nemet929c38e2015-02-19 19:15:10 +0000918 emitAnalysis(
Adam Nemet2bd6e982015-02-19 19:15:15 +0000919 LoopAccessReport() <<
Adam Nemet929c38e2015-02-19 19:15:10 +0000920 "loop control flow is not understood by analyzer");
921 return false;
922 }
923
924 // We must have a single exiting block.
925 if (!TheLoop->getExitingBlock()) {
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
933 // We only handle bottom-tested loops, i.e. loop in which the condition is
934 // checked at the end of each iteration. With that we can assume that all
935 // instructions in the loop are executed the same number of times.
936 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
Adam Nemet8dcb3b62015-04-17 22:43:10 +0000937 DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n");
Adam Nemet929c38e2015-02-19 19:15:10 +0000938 emitAnalysis(
Adam Nemet2bd6e982015-02-19 19:15:15 +0000939 LoopAccessReport() <<
Adam Nemet929c38e2015-02-19 19:15:10 +0000940 "loop control flow is not understood by analyzer");
941 return false;
942 }
943
Adam Nemet929c38e2015-02-19 19:15:10 +0000944 // ScalarEvolution needs to be able to find the exit count.
945 const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop);
946 if (ExitCount == SE->getCouldNotCompute()) {
Adam Nemet2bd6e982015-02-19 19:15:15 +0000947 emitAnalysis(LoopAccessReport() <<
Adam Nemet929c38e2015-02-19 19:15:10 +0000948 "could not determine number of loop iterations");
949 DEBUG(dbgs() << "LAA: SCEV could not compute the loop exit count.\n");
950 return false;
951 }
952
953 return true;
954}
955
Adam Nemet8bc61df2015-02-24 00:41:59 +0000956void LoopAccessInfo::analyzeLoop(const ValueToValueMap &Strides) {
Adam Nemet04563272015-02-01 16:56:15 +0000957
958 typedef SmallVector<Value*, 16> ValueVector;
959 typedef SmallPtrSet<Value*, 16> ValueSet;
960
961 // Holds the Load and Store *instructions*.
962 ValueVector Loads;
963 ValueVector Stores;
964
965 // Holds all the different accesses in the loop.
966 unsigned NumReads = 0;
967 unsigned NumReadWrites = 0;
968
969 PtrRtCheck.Pointers.clear();
970 PtrRtCheck.Need = false;
971
972 const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
Adam Nemet04563272015-02-01 16:56:15 +0000973
974 // For each block.
975 for (Loop::block_iterator bb = TheLoop->block_begin(),
976 be = TheLoop->block_end(); bb != be; ++bb) {
977
978 // Scan the BB and collect legal loads and stores.
979 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
980 ++it) {
981
982 // If this is a load, save it. If this instruction can read from memory
983 // but is not a load, then we quit. Notice that we don't handle function
984 // calls that read or write.
985 if (it->mayReadFromMemory()) {
986 // Many math library functions read the rounding mode. We will only
987 // vectorize a loop if it contains known function calls that don't set
988 // the flag. Therefore, it is safe to ignore this read from memory.
989 CallInst *Call = dyn_cast<CallInst>(it);
990 if (Call && getIntrinsicIDForCall(Call, TLI))
991 continue;
992
Michael Zolotukhin9b3cf602015-03-17 19:46:50 +0000993 // If the function has an explicit vectorized counterpart, we can safely
994 // assume that it can be vectorized.
995 if (Call && !Call->isNoBuiltin() && Call->getCalledFunction() &&
996 TLI->isFunctionVectorizable(Call->getCalledFunction()->getName()))
997 continue;
998
Adam Nemet04563272015-02-01 16:56:15 +0000999 LoadInst *Ld = dyn_cast<LoadInst>(it);
1000 if (!Ld || (!Ld->isSimple() && !IsAnnotatedParallel)) {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001001 emitAnalysis(LoopAccessReport(Ld)
Adam Nemet04563272015-02-01 16:56:15 +00001002 << "read with atomic ordering or volatile read");
Adam Nemet339f42b2015-02-19 19:15:07 +00001003 DEBUG(dbgs() << "LAA: Found a non-simple load.\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001004 CanVecMem = false;
1005 return;
Adam Nemet04563272015-02-01 16:56:15 +00001006 }
1007 NumLoads++;
1008 Loads.push_back(Ld);
1009 DepChecker.addAccess(Ld);
1010 continue;
1011 }
1012
1013 // Save 'store' instructions. Abort if other instructions write to memory.
1014 if (it->mayWriteToMemory()) {
1015 StoreInst *St = dyn_cast<StoreInst>(it);
1016 if (!St) {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001017 emitAnalysis(LoopAccessReport(it) <<
Adam Nemet04d41632015-02-19 19:14:34 +00001018 "instruction cannot be vectorized");
Adam Nemet436018c2015-02-19 19:15:00 +00001019 CanVecMem = false;
1020 return;
Adam Nemet04563272015-02-01 16:56:15 +00001021 }
1022 if (!St->isSimple() && !IsAnnotatedParallel) {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001023 emitAnalysis(LoopAccessReport(St)
Adam Nemet04563272015-02-01 16:56:15 +00001024 << "write with atomic ordering or volatile write");
Adam Nemet339f42b2015-02-19 19:15:07 +00001025 DEBUG(dbgs() << "LAA: Found a non-simple store.\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001026 CanVecMem = false;
1027 return;
Adam Nemet04563272015-02-01 16:56:15 +00001028 }
1029 NumStores++;
1030 Stores.push_back(St);
1031 DepChecker.addAccess(St);
1032 }
1033 } // Next instr.
1034 } // Next block.
1035
1036 // Now we have two lists that hold the loads and the stores.
1037 // Next, we find the pointers that they use.
1038
1039 // Check if we see any stores. If there are no stores, then we don't
1040 // care if the pointers are *restrict*.
1041 if (!Stores.size()) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001042 DEBUG(dbgs() << "LAA: Found a read-only loop!\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001043 CanVecMem = true;
1044 return;
Adam Nemet04563272015-02-01 16:56:15 +00001045 }
1046
Adam Nemetdee666b2015-03-10 17:40:34 +00001047 MemoryDepChecker::DepCandidates DependentAccesses;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001048 AccessAnalysis Accesses(TheLoop->getHeader()->getModule()->getDataLayout(),
Adam Nemete2b885c2015-04-23 20:09:20 +00001049 AA, LI, DependentAccesses);
Adam Nemet04563272015-02-01 16:56:15 +00001050
1051 // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
1052 // multiple times on the same object. If the ptr is accessed twice, once
1053 // for read and once for write, it will only appear once (on the write
1054 // list). This is okay, since we are going to check for conflicts between
1055 // writes and between reads and writes, but not between reads and reads.
1056 ValueSet Seen;
1057
1058 ValueVector::iterator I, IE;
1059 for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
1060 StoreInst *ST = cast<StoreInst>(*I);
1061 Value* Ptr = ST->getPointerOperand();
Adam Nemetce482502015-04-08 17:48:40 +00001062 // Check for store to loop invariant address.
1063 StoreToLoopInvariantAddress |= isUniform(Ptr);
Adam Nemet04563272015-02-01 16:56:15 +00001064 // If we did *not* see this pointer before, insert it to the read-write
1065 // list. At this phase it is only a 'write' list.
1066 if (Seen.insert(Ptr).second) {
1067 ++NumReadWrites;
1068
Chandler Carruth70c61c12015-06-04 02:03:15 +00001069 AliasAnalysis::Location Loc = MemoryLocation::get(ST);
Adam Nemet04563272015-02-01 16:56:15 +00001070 // The TBAA metadata could have a control dependency on the predication
1071 // condition, so we cannot rely on it when determining whether or not we
1072 // need runtime pointer checks.
Adam Nemet01abb2c2015-02-18 03:43:19 +00001073 if (blockNeedsPredication(ST->getParent(), TheLoop, DT))
Adam Nemet04563272015-02-01 16:56:15 +00001074 Loc.AATags.TBAA = nullptr;
1075
1076 Accesses.addStore(Loc);
1077 }
1078 }
1079
1080 if (IsAnnotatedParallel) {
Adam Nemet04d41632015-02-19 19:14:34 +00001081 DEBUG(dbgs()
Adam Nemet339f42b2015-02-19 19:15:07 +00001082 << "LAA: A loop annotated parallel, ignore memory dependency "
Adam Nemet04d41632015-02-19 19:14:34 +00001083 << "checks.\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001084 CanVecMem = true;
1085 return;
Adam Nemet04563272015-02-01 16:56:15 +00001086 }
1087
1088 for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
1089 LoadInst *LD = cast<LoadInst>(*I);
1090 Value* Ptr = LD->getPointerOperand();
1091 // If we did *not* see this pointer before, insert it to the
1092 // read list. If we *did* see it before, then it is already in
1093 // the read-write list. This allows us to vectorize expressions
1094 // such as A[i] += x; Because the address of A[i] is a read-write
1095 // pointer. This only works if the index of A[i] is consecutive.
1096 // If the address of i is unknown (for example A[B[i]]) then we may
1097 // read a few words, modify, and write a few words, and some of the
1098 // words may be written to the same address.
1099 bool IsReadOnlyPtr = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001100 if (Seen.insert(Ptr).second || !isStridedPtr(SE, Ptr, TheLoop, Strides)) {
Adam Nemet04563272015-02-01 16:56:15 +00001101 ++NumReads;
1102 IsReadOnlyPtr = true;
1103 }
1104
Chandler Carruth70c61c12015-06-04 02:03:15 +00001105 AliasAnalysis::Location Loc = MemoryLocation::get(LD);
Adam Nemet04563272015-02-01 16:56:15 +00001106 // The TBAA metadata could have a control dependency on the predication
1107 // condition, so we cannot rely on it when determining whether or not we
1108 // need runtime pointer checks.
Adam Nemet01abb2c2015-02-18 03:43:19 +00001109 if (blockNeedsPredication(LD->getParent(), TheLoop, DT))
Adam Nemet04563272015-02-01 16:56:15 +00001110 Loc.AATags.TBAA = nullptr;
1111
1112 Accesses.addLoad(Loc, IsReadOnlyPtr);
1113 }
1114
1115 // If we write (or read-write) to a single destination and there are no
1116 // other reads in this loop then is it safe to vectorize.
1117 if (NumReadWrites == 1 && NumReads == 0) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001118 DEBUG(dbgs() << "LAA: Found a write-only loop!\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001119 CanVecMem = true;
1120 return;
Adam Nemet04563272015-02-01 16:56:15 +00001121 }
1122
1123 // Build dependence sets and check whether we need a runtime pointer bounds
1124 // check.
1125 Accesses.buildDependenceSets();
1126 bool NeedRTCheck = Accesses.isRTCheckNeeded();
1127
1128 // Find pointers with computable bounds. We are going to use this information
1129 // to place a runtime bound check.
Adam Nemet04563272015-02-01 16:56:15 +00001130 bool CanDoRT = false;
1131 if (NeedRTCheck)
1132 CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE, TheLoop,
1133 Strides);
1134
Adam Nemet339f42b2015-02-19 19:15:07 +00001135 DEBUG(dbgs() << "LAA: We need to do " << NumComparisons <<
Adam Nemet04d41632015-02-19 19:14:34 +00001136 " pointer comparisons.\n");
Adam Nemet04563272015-02-01 16:56:15 +00001137
1138 // If we only have one set of dependences to check pointers among we don't
1139 // need a runtime check.
1140 if (NumComparisons == 0 && NeedRTCheck)
1141 NeedRTCheck = false;
1142
Adam Nemet949e91a2015-03-10 19:12:41 +00001143 // Check that we found the bounds for the pointer.
Adam Nemetb6dc76f2015-03-10 18:54:19 +00001144 if (CanDoRT)
Adam Nemet339f42b2015-02-19 19:15:07 +00001145 DEBUG(dbgs() << "LAA: We can perform a memory runtime check if needed.\n");
Adam Nemetb6dc76f2015-03-10 18:54:19 +00001146 else if (NeedRTCheck) {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001147 emitAnalysis(LoopAccessReport() << "cannot identify array bounds");
Adam Nemet339f42b2015-02-19 19:15:07 +00001148 DEBUG(dbgs() << "LAA: We can't vectorize because we can't find " <<
Adam Nemet04d41632015-02-19 19:14:34 +00001149 "the array bounds.\n");
Adam Nemet04563272015-02-01 16:56:15 +00001150 PtrRtCheck.reset();
Adam Nemet436018c2015-02-19 19:15:00 +00001151 CanVecMem = false;
1152 return;
Adam Nemet04563272015-02-01 16:56:15 +00001153 }
1154
1155 PtrRtCheck.Need = NeedRTCheck;
1156
Adam Nemet436018c2015-02-19 19:15:00 +00001157 CanVecMem = true;
Adam Nemet04563272015-02-01 16:56:15 +00001158 if (Accesses.isDependencyCheckNeeded()) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001159 DEBUG(dbgs() << "LAA: Checking memory dependencies\n");
Adam Nemet04563272015-02-01 16:56:15 +00001160 CanVecMem = DepChecker.areDepsSafe(
1161 DependentAccesses, Accesses.getDependenciesToCheck(), Strides);
1162 MaxSafeDepDistBytes = DepChecker.getMaxSafeDepDistBytes();
1163
1164 if (!CanVecMem && DepChecker.shouldRetryWithRuntimeCheck()) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001165 DEBUG(dbgs() << "LAA: Retrying with memory checks\n");
Adam Nemet04563272015-02-01 16:56:15 +00001166 NeedRTCheck = true;
1167
1168 // Clear the dependency checks. We assume they are not needed.
Adam Nemetdf3dc5b2015-05-18 15:37:03 +00001169 Accesses.resetDepChecks(DepChecker);
Adam Nemet04563272015-02-01 16:56:15 +00001170
1171 PtrRtCheck.reset();
1172 PtrRtCheck.Need = true;
1173
1174 CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE,
1175 TheLoop, Strides, true);
Adam Nemet949e91a2015-03-10 19:12:41 +00001176 // Check that we found the bounds for the pointer.
Adam Nemetb6dc76f2015-03-10 18:54:19 +00001177 if (!CanDoRT && NumComparisons > 0) {
1178 emitAnalysis(LoopAccessReport()
1179 << "cannot check memory dependencies at runtime");
1180 DEBUG(dbgs() << "LAA: Can't vectorize with memory checks\n");
1181 PtrRtCheck.reset();
1182 CanVecMem = false;
1183 return;
1184 }
1185
Adam Nemet04563272015-02-01 16:56:15 +00001186 CanVecMem = true;
1187 }
1188 }
1189
Adam Nemet4bb90a72015-03-10 21:47:39 +00001190 if (CanVecMem)
1191 DEBUG(dbgs() << "LAA: No unsafe dependent memory operations in loop. We"
1192 << (NeedRTCheck ? "" : " don't")
1193 << " need a runtime memory check.\n");
1194 else {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001195 emitAnalysis(LoopAccessReport() <<
Adam Nemet04d41632015-02-19 19:14:34 +00001196 "unsafe dependent memory operations in loop");
Adam Nemet4bb90a72015-03-10 21:47:39 +00001197 DEBUG(dbgs() << "LAA: unsafe dependent memory operations in loop\n");
1198 }
Adam Nemet04563272015-02-01 16:56:15 +00001199}
1200
Adam Nemet01abb2c2015-02-18 03:43:19 +00001201bool LoopAccessInfo::blockNeedsPredication(BasicBlock *BB, Loop *TheLoop,
1202 DominatorTree *DT) {
Adam Nemet04563272015-02-01 16:56:15 +00001203 assert(TheLoop->contains(BB) && "Unknown block used");
1204
1205 // Blocks that do not dominate the latch need predication.
1206 BasicBlock* Latch = TheLoop->getLoopLatch();
1207 return !DT->dominates(BB, Latch);
1208}
1209
Adam Nemet2bd6e982015-02-19 19:15:15 +00001210void LoopAccessInfo::emitAnalysis(LoopAccessReport &Message) {
Adam Nemetc9228532015-02-19 19:14:56 +00001211 assert(!Report && "Multiple reports generated");
1212 Report = Message;
Adam Nemet04563272015-02-01 16:56:15 +00001213}
1214
Adam Nemet57ac7662015-02-19 19:15:21 +00001215bool LoopAccessInfo::isUniform(Value *V) const {
Adam Nemet04563272015-02-01 16:56:15 +00001216 return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
1217}
Adam Nemet7206d7a2015-02-06 18:31:04 +00001218
1219// FIXME: this function is currently a duplicate of the one in
1220// LoopVectorize.cpp.
1221static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
1222 Instruction *Loc) {
1223 if (FirstInst)
1224 return FirstInst;
1225 if (Instruction *I = dyn_cast<Instruction>(V))
1226 return I->getParent() == Loc->getParent() ? I : nullptr;
1227 return nullptr;
1228}
1229
Adam Nemetec1e2bb2015-03-10 18:54:26 +00001230std::pair<Instruction *, Instruction *> LoopAccessInfo::addRuntimeCheck(
1231 Instruction *Loc, const SmallVectorImpl<int> *PtrPartition) const {
Adam Nemet7206d7a2015-02-06 18:31:04 +00001232 if (!PtrRtCheck.Need)
Adam Nemet90fec842015-04-02 17:51:57 +00001233 return std::make_pair(nullptr, nullptr);
Adam Nemet7206d7a2015-02-06 18:31:04 +00001234
1235 unsigned NumPointers = PtrRtCheck.Pointers.size();
1236 SmallVector<TrackingVH<Value> , 2> Starts;
1237 SmallVector<TrackingVH<Value> , 2> Ends;
1238
1239 LLVMContext &Ctx = Loc->getContext();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001240 SCEVExpander Exp(*SE, DL, "induction");
Adam Nemet7206d7a2015-02-06 18:31:04 +00001241 Instruction *FirstInst = nullptr;
1242
1243 for (unsigned i = 0; i < NumPointers; ++i) {
1244 Value *Ptr = PtrRtCheck.Pointers[i];
1245 const SCEV *Sc = SE->getSCEV(Ptr);
1246
1247 if (SE->isLoopInvariant(Sc, TheLoop)) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001248 DEBUG(dbgs() << "LAA: Adding RT check for a loop invariant ptr:" <<
Adam Nemet04d41632015-02-19 19:14:34 +00001249 *Ptr <<"\n");
Adam Nemet7206d7a2015-02-06 18:31:04 +00001250 Starts.push_back(Ptr);
1251 Ends.push_back(Ptr);
1252 } else {
Adam Nemet339f42b2015-02-19 19:15:07 +00001253 DEBUG(dbgs() << "LAA: Adding RT check for range:" << *Ptr << '\n');
Adam Nemet7206d7a2015-02-06 18:31:04 +00001254 unsigned AS = Ptr->getType()->getPointerAddressSpace();
1255
1256 // Use this type for pointer arithmetic.
1257 Type *PtrArithTy = Type::getInt8PtrTy(Ctx, AS);
1258
1259 Value *Start = Exp.expandCodeFor(PtrRtCheck.Starts[i], PtrArithTy, Loc);
1260 Value *End = Exp.expandCodeFor(PtrRtCheck.Ends[i], PtrArithTy, Loc);
1261 Starts.push_back(Start);
1262 Ends.push_back(End);
1263 }
1264 }
1265
1266 IRBuilder<> ChkBuilder(Loc);
1267 // Our instructions might fold to a constant.
1268 Value *MemoryRuntimeCheck = nullptr;
1269 for (unsigned i = 0; i < NumPointers; ++i) {
1270 for (unsigned j = i+1; j < NumPointers; ++j) {
Adam Nemetec1e2bb2015-03-10 18:54:26 +00001271 if (!PtrRtCheck.needsChecking(i, j, PtrPartition))
Adam Nemet7206d7a2015-02-06 18:31:04 +00001272 continue;
1273
1274 unsigned AS0 = Starts[i]->getType()->getPointerAddressSpace();
1275 unsigned AS1 = Starts[j]->getType()->getPointerAddressSpace();
1276
1277 assert((AS0 == Ends[j]->getType()->getPointerAddressSpace()) &&
1278 (AS1 == Ends[i]->getType()->getPointerAddressSpace()) &&
1279 "Trying to bounds check pointers with different address spaces");
1280
1281 Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0);
1282 Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1);
1283
1284 Value *Start0 = ChkBuilder.CreateBitCast(Starts[i], PtrArithTy0, "bc");
1285 Value *Start1 = ChkBuilder.CreateBitCast(Starts[j], PtrArithTy1, "bc");
1286 Value *End0 = ChkBuilder.CreateBitCast(Ends[i], PtrArithTy1, "bc");
1287 Value *End1 = ChkBuilder.CreateBitCast(Ends[j], PtrArithTy0, "bc");
1288
1289 Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0");
1290 FirstInst = getFirstInst(FirstInst, Cmp0, Loc);
1291 Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1");
1292 FirstInst = getFirstInst(FirstInst, Cmp1, Loc);
1293 Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
1294 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1295 if (MemoryRuntimeCheck) {
1296 IsConflict = ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict,
1297 "conflict.rdx");
1298 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1299 }
1300 MemoryRuntimeCheck = IsConflict;
1301 }
1302 }
1303
Adam Nemet90fec842015-04-02 17:51:57 +00001304 if (!MemoryRuntimeCheck)
1305 return std::make_pair(nullptr, nullptr);
1306
Adam Nemet7206d7a2015-02-06 18:31:04 +00001307 // We have to do this trickery because the IRBuilder might fold the check to a
1308 // constant expression in which case there is no Instruction anchored in a
1309 // the block.
1310 Instruction *Check = BinaryOperator::CreateAnd(MemoryRuntimeCheck,
1311 ConstantInt::getTrue(Ctx));
1312 ChkBuilder.Insert(Check, "memcheck.conflict");
1313 FirstInst = getFirstInst(FirstInst, Check, Loc);
1314 return std::make_pair(FirstInst, Check);
1315}
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001316
1317LoopAccessInfo::LoopAccessInfo(Loop *L, ScalarEvolution *SE,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001318 const DataLayout &DL,
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001319 const TargetLibraryInfo *TLI, AliasAnalysis *AA,
Adam Nemete2b885c2015-04-23 20:09:20 +00001320 DominatorTree *DT, LoopInfo *LI,
Adam Nemet8bc61df2015-02-24 00:41:59 +00001321 const ValueToValueMap &Strides)
Adam Nemet98c4c5d2015-03-10 18:54:23 +00001322 : DepChecker(SE, L), NumComparisons(0), TheLoop(L), SE(SE), DL(DL),
Adam Nemete2b885c2015-04-23 20:09:20 +00001323 TLI(TLI), AA(AA), DT(DT), LI(LI), NumLoads(0), NumStores(0),
Adam Nemetce482502015-04-08 17:48:40 +00001324 MaxSafeDepDistBytes(-1U), CanVecMem(false),
1325 StoreToLoopInvariantAddress(false) {
Adam Nemet929c38e2015-02-19 19:15:10 +00001326 if (canAnalyzeLoop())
1327 analyzeLoop(Strides);
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001328}
1329
Adam Nemete91cc6e2015-02-19 19:15:19 +00001330void LoopAccessInfo::print(raw_ostream &OS, unsigned Depth) const {
1331 if (CanVecMem) {
Adam Nemet26da8e92015-04-14 01:12:55 +00001332 if (PtrRtCheck.Need)
Adam Nemete91cc6e2015-02-19 19:15:19 +00001333 OS.indent(Depth) << "Memory dependences are safe with run-time checks\n";
Adam Nemet26da8e92015-04-14 01:12:55 +00001334 else
1335 OS.indent(Depth) << "Memory dependences are safe\n";
Adam Nemete91cc6e2015-02-19 19:15:19 +00001336 }
1337
1338 if (Report)
1339 OS.indent(Depth) << "Report: " << Report->str() << "\n";
1340
Adam Nemet58913d62015-03-10 17:40:43 +00001341 if (auto *InterestingDependences = DepChecker.getInterestingDependences()) {
1342 OS.indent(Depth) << "Interesting Dependences:\n";
1343 for (auto &Dep : *InterestingDependences) {
1344 Dep.print(OS, Depth + 2, DepChecker.getMemoryInstructions());
1345 OS << "\n";
1346 }
1347 } else
1348 OS.indent(Depth) << "Too many interesting dependences, not recorded\n";
Adam Nemete91cc6e2015-02-19 19:15:19 +00001349
1350 // List the pair of accesses need run-time checks to prove independence.
1351 PtrRtCheck.print(OS, Depth);
1352 OS << "\n";
Adam Nemetc3384322015-05-18 15:36:57 +00001353
1354 OS.indent(Depth) << "Store to invariant address was "
1355 << (StoreToLoopInvariantAddress ? "" : "not ")
1356 << "found in loop.\n";
Adam Nemete91cc6e2015-02-19 19:15:19 +00001357}
1358
Adam Nemet8bc61df2015-02-24 00:41:59 +00001359const LoopAccessInfo &
1360LoopAccessAnalysis::getInfo(Loop *L, const ValueToValueMap &Strides) {
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001361 auto &LAI = LoopAccessInfoMap[L];
1362
1363#ifndef NDEBUG
1364 assert((!LAI || LAI->NumSymbolicStrides == Strides.size()) &&
1365 "Symbolic strides changed for loop");
1366#endif
1367
1368 if (!LAI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001369 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
Adam Nemete2b885c2015-04-23 20:09:20 +00001370 LAI = llvm::make_unique<LoopAccessInfo>(L, SE, DL, TLI, AA, DT, LI,
1371 Strides);
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001372#ifndef NDEBUG
1373 LAI->NumSymbolicStrides = Strides.size();
1374#endif
1375 }
1376 return *LAI.get();
1377}
1378
Adam Nemete91cc6e2015-02-19 19:15:19 +00001379void LoopAccessAnalysis::print(raw_ostream &OS, const Module *M) const {
1380 LoopAccessAnalysis &LAA = *const_cast<LoopAccessAnalysis *>(this);
1381
Adam Nemete91cc6e2015-02-19 19:15:19 +00001382 ValueToValueMap NoSymbolicStrides;
1383
1384 for (Loop *TopLevelLoop : *LI)
1385 for (Loop *L : depth_first(TopLevelLoop)) {
1386 OS.indent(2) << L->getHeader()->getName() << ":\n";
1387 auto &LAI = LAA.getInfo(L, NoSymbolicStrides);
1388 LAI.print(OS, 4);
1389 }
1390}
1391
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001392bool LoopAccessAnalysis::runOnFunction(Function &F) {
1393 SE = &getAnalysis<ScalarEvolution>();
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001394 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
1395 TLI = TLIP ? &TLIP->getTLI() : nullptr;
1396 AA = &getAnalysis<AliasAnalysis>();
1397 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Adam Nemete2b885c2015-04-23 20:09:20 +00001398 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001399
1400 return false;
1401}
1402
1403void LoopAccessAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
1404 AU.addRequired<ScalarEvolution>();
1405 AU.addRequired<AliasAnalysis>();
1406 AU.addRequired<DominatorTreeWrapperPass>();
Adam Nemete91cc6e2015-02-19 19:15:19 +00001407 AU.addRequired<LoopInfoWrapperPass>();
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001408
1409 AU.setPreservesAll();
1410}
1411
1412char LoopAccessAnalysis::ID = 0;
1413static const char laa_name[] = "Loop Access Analysis";
1414#define LAA_NAME "loop-accesses"
1415
1416INITIALIZE_PASS_BEGIN(LoopAccessAnalysis, LAA_NAME, laa_name, false, true)
1417INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
1418INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
1419INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Adam Nemete91cc6e2015-02-19 19:15:19 +00001420INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001421INITIALIZE_PASS_END(LoopAccessAnalysis, LAA_NAME, laa_name, false, true)
1422
1423namespace llvm {
1424 Pass *createLAAPass() {
1425 return new LoopAccessAnalysis();
1426 }
1427}