blob: aafbc5eb1ab5c7252867395625585e9ebdf28203 [file] [log] [blame]
Adam Nemet04563272015-02-01 16:56:15 +00001//===- LoopAccessAnalysis.cpp - Loop Access Analysis Implementation --------==//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// The implementation for the loop memory dependence that was originally
11// developed for the loop vectorizer.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Analysis/LoopAccessAnalysis.h"
16#include "llvm/Analysis/LoopInfo.h"
Adam Nemet7206d7a2015-02-06 18:31:04 +000017#include "llvm/Analysis/ScalarEvolutionExpander.h"
Adam Nemet04563272015-02-01 16:56:15 +000018#include "llvm/Analysis/ValueTracking.h"
19#include "llvm/IR/DiagnosticInfo.h"
20#include "llvm/IR/Dominators.h"
Adam Nemet7206d7a2015-02-06 18:31:04 +000021#include "llvm/IR/IRBuilder.h"
Adam Nemet04563272015-02-01 16:56:15 +000022#include "llvm/Support/Debug.h"
23#include "llvm/Transforms/Utils/VectorUtils.h"
24using namespace llvm;
25
Adam Nemet339f42b2015-02-19 19:15:07 +000026#define DEBUG_TYPE "loop-accesses"
Adam Nemet04563272015-02-01 16:56:15 +000027
Adam Nemetf219c642015-02-19 19:14:52 +000028static cl::opt<unsigned, true>
29VectorizationFactor("force-vector-width", cl::Hidden,
30 cl::desc("Sets the SIMD width. Zero is autoselect."),
31 cl::location(VectorizerParams::VectorizationFactor));
Adam Nemet1d862af2015-02-26 04:39:09 +000032unsigned VectorizerParams::VectorizationFactor;
Adam Nemetf219c642015-02-19 19:14:52 +000033
34static cl::opt<unsigned, true>
35VectorizationInterleave("force-vector-interleave", cl::Hidden,
36 cl::desc("Sets the vectorization interleave count. "
37 "Zero is autoselect."),
38 cl::location(
39 VectorizerParams::VectorizationInterleave));
Adam Nemet1d862af2015-02-26 04:39:09 +000040unsigned VectorizerParams::VectorizationInterleave;
Adam Nemetf219c642015-02-19 19:14:52 +000041
Adam Nemet1d862af2015-02-26 04:39:09 +000042static cl::opt<unsigned, true> RuntimeMemoryCheckThreshold(
43 "runtime-memory-check-threshold", cl::Hidden,
44 cl::desc("When performing memory disambiguation checks at runtime do not "
45 "generate more than this number of comparisons (default = 8)."),
46 cl::location(VectorizerParams::RuntimeMemoryCheckThreshold), cl::init(8));
47unsigned VectorizerParams::RuntimeMemoryCheckThreshold;
Adam Nemetf219c642015-02-19 19:14:52 +000048
49/// Maximum SIMD width.
50const unsigned VectorizerParams::MaxVectorWidth = 64;
51
52bool VectorizerParams::isInterleaveForced() {
53 return ::VectorizationInterleave.getNumOccurrences() > 0;
54}
55
Adam Nemet2bd6e982015-02-19 19:15:15 +000056void LoopAccessReport::emitAnalysis(const LoopAccessReport &Message,
57 const Function *TheFunction,
58 const Loop *TheLoop,
59 const char *PassName) {
Adam Nemet04563272015-02-01 16:56:15 +000060 DebugLoc DL = TheLoop->getStartLoc();
Adam Nemet3e876342015-02-19 19:15:13 +000061 if (const Instruction *I = Message.getInstr())
Adam Nemet04563272015-02-01 16:56:15 +000062 DL = I->getDebugLoc();
Adam Nemet339f42b2015-02-19 19:15:07 +000063 emitOptimizationRemarkAnalysis(TheFunction->getContext(), PassName,
Adam Nemet04563272015-02-01 16:56:15 +000064 *TheFunction, DL, Message.str());
65}
66
67Value *llvm::stripIntegerCast(Value *V) {
68 if (CastInst *CI = dyn_cast<CastInst>(V))
69 if (CI->getOperand(0)->getType()->isIntegerTy())
70 return CI->getOperand(0);
71 return V;
72}
73
74const SCEV *llvm::replaceSymbolicStrideSCEV(ScalarEvolution *SE,
Adam Nemet8bc61df2015-02-24 00:41:59 +000075 const ValueToValueMap &PtrToStride,
Adam Nemet04563272015-02-01 16:56:15 +000076 Value *Ptr, Value *OrigPtr) {
77
78 const SCEV *OrigSCEV = SE->getSCEV(Ptr);
79
80 // If there is an entry in the map return the SCEV of the pointer with the
81 // symbolic stride replaced by one.
Adam Nemet8bc61df2015-02-24 00:41:59 +000082 ValueToValueMap::const_iterator SI =
83 PtrToStride.find(OrigPtr ? OrigPtr : Ptr);
Adam Nemet04563272015-02-01 16:56:15 +000084 if (SI != PtrToStride.end()) {
85 Value *StrideVal = SI->second;
86
87 // Strip casts.
88 StrideVal = stripIntegerCast(StrideVal);
89
90 // Replace symbolic stride by one.
91 Value *One = ConstantInt::get(StrideVal->getType(), 1);
92 ValueToValueMap RewriteMap;
93 RewriteMap[StrideVal] = One;
94
95 const SCEV *ByOne =
96 SCEVParameterRewriter::rewrite(OrigSCEV, *SE, RewriteMap, true);
Adam Nemet339f42b2015-02-19 19:15:07 +000097 DEBUG(dbgs() << "LAA: Replacing SCEV: " << *OrigSCEV << " by: " << *ByOne
Adam Nemet04563272015-02-01 16:56:15 +000098 << "\n");
99 return ByOne;
100 }
101
102 // Otherwise, just return the SCEV of the original pointer.
103 return SE->getSCEV(Ptr);
104}
105
Adam Nemet8bc61df2015-02-24 00:41:59 +0000106void LoopAccessInfo::RuntimePointerCheck::insert(
107 ScalarEvolution *SE, Loop *Lp, Value *Ptr, bool WritePtr, unsigned DepSetId,
108 unsigned ASId, const ValueToValueMap &Strides) {
Adam Nemet04563272015-02-01 16:56:15 +0000109 // Get the stride replaced scev.
110 const SCEV *Sc = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
111 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
112 assert(AR && "Invalid addrec expression");
113 const SCEV *Ex = SE->getBackedgeTakenCount(Lp);
114 const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
115 Pointers.push_back(Ptr);
116 Starts.push_back(AR->getStart());
117 Ends.push_back(ScEnd);
118 IsWritePtr.push_back(WritePtr);
119 DependencySetId.push_back(DepSetId);
120 AliasSetId.push_back(ASId);
121}
122
Adam Nemeta8945b72015-02-18 03:43:58 +0000123bool LoopAccessInfo::RuntimePointerCheck::needsChecking(unsigned I,
124 unsigned J) const {
125 // No need to check if two readonly pointers intersect.
126 if (!IsWritePtr[I] && !IsWritePtr[J])
127 return false;
128
129 // Only need to check pointers between two different dependency sets.
130 if (DependencySetId[I] == DependencySetId[J])
131 return false;
132
133 // Only need to check pointers in the same alias set.
134 if (AliasSetId[I] != AliasSetId[J])
135 return false;
136
137 return true;
138}
139
Adam Nemete91cc6e2015-02-19 19:15:19 +0000140void LoopAccessInfo::RuntimePointerCheck::print(raw_ostream &OS,
141 unsigned Depth) const {
142 unsigned NumPointers = Pointers.size();
143 if (NumPointers == 0)
144 return;
145
146 OS.indent(Depth) << "Run-time memory checks:\n";
147 unsigned N = 0;
148 for (unsigned I = 0; I < NumPointers; ++I)
149 for (unsigned J = I + 1; J < NumPointers; ++J)
150 if (needsChecking(I, J)) {
151 OS.indent(Depth) << N++ << ":\n";
152 OS.indent(Depth + 2) << *Pointers[I] << "\n";
153 OS.indent(Depth + 2) << *Pointers[J] << "\n";
154 }
155}
156
Adam Nemet04563272015-02-01 16:56:15 +0000157namespace {
158/// \brief Analyses memory accesses in a loop.
159///
160/// Checks whether run time pointer checks are needed and builds sets for data
161/// dependence checking.
162class AccessAnalysis {
163public:
164 /// \brief Read or write access location.
165 typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
166 typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
167
Adam Nemetdee666b2015-03-10 17:40:34 +0000168 AccessAnalysis(const DataLayout &Dl, AliasAnalysis *AA,
169 MemoryDepChecker::DepCandidates &DA)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000170 : DL(Dl), AST(*AA), DepCands(DA), IsRTCheckNeeded(false) {}
Adam Nemet04563272015-02-01 16:56:15 +0000171
172 /// \brief Register a load and whether it is only read from.
173 void addLoad(AliasAnalysis::Location &Loc, bool IsReadOnly) {
174 Value *Ptr = const_cast<Value*>(Loc.Ptr);
175 AST.add(Ptr, AliasAnalysis::UnknownSize, Loc.AATags);
176 Accesses.insert(MemAccessInfo(Ptr, false));
177 if (IsReadOnly)
178 ReadOnlyPtr.insert(Ptr);
179 }
180
181 /// \brief Register a store.
182 void addStore(AliasAnalysis::Location &Loc) {
183 Value *Ptr = const_cast<Value*>(Loc.Ptr);
184 AST.add(Ptr, AliasAnalysis::UnknownSize, Loc.AATags);
185 Accesses.insert(MemAccessInfo(Ptr, true));
186 }
187
188 /// \brief Check whether we can check the pointers at runtime for
189 /// non-intersection.
Adam Nemet30f16e12015-02-18 03:42:35 +0000190 bool canCheckPtrAtRT(LoopAccessInfo::RuntimePointerCheck &RtCheck,
Adam Nemet8bc61df2015-02-24 00:41:59 +0000191 unsigned &NumComparisons, ScalarEvolution *SE,
192 Loop *TheLoop, const ValueToValueMap &Strides,
Adam Nemet04563272015-02-01 16:56:15 +0000193 bool ShouldCheckStride = false);
194
195 /// \brief Goes over all memory accesses, checks whether a RT check is needed
196 /// and builds sets of dependent accesses.
197 void buildDependenceSets() {
198 processMemAccesses();
199 }
200
201 bool isRTCheckNeeded() { return IsRTCheckNeeded; }
202
203 bool isDependencyCheckNeeded() { return !CheckDeps.empty(); }
204 void resetDepChecks() { CheckDeps.clear(); }
205
206 MemAccessInfoSet &getDependenciesToCheck() { return CheckDeps; }
207
208private:
209 typedef SetVector<MemAccessInfo> PtrAccessSet;
210
211 /// \brief Go over all memory access and check whether runtime pointer checks
212 /// are needed /// and build sets of dependency check candidates.
213 void processMemAccesses();
214
215 /// Set of all accesses.
216 PtrAccessSet Accesses;
217
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000218 const DataLayout &DL;
219
Adam Nemet04563272015-02-01 16:56:15 +0000220 /// Set of accesses that need a further dependence check.
221 MemAccessInfoSet CheckDeps;
222
223 /// Set of pointers that are read only.
224 SmallPtrSet<Value*, 16> ReadOnlyPtr;
225
Adam Nemet04563272015-02-01 16:56:15 +0000226 /// An alias set tracker to partition the access set by underlying object and
227 //intrinsic property (such as TBAA metadata).
228 AliasSetTracker AST;
229
230 /// Sets of potentially dependent accesses - members of one set share an
231 /// underlying pointer. The set "CheckDeps" identfies which sets really need a
232 /// dependence check.
Adam Nemetdee666b2015-03-10 17:40:34 +0000233 MemoryDepChecker::DepCandidates &DepCands;
Adam Nemet04563272015-02-01 16:56:15 +0000234
235 bool IsRTCheckNeeded;
236};
237
238} // end anonymous namespace
239
240/// \brief Check whether a pointer can participate in a runtime bounds check.
Adam Nemet8bc61df2015-02-24 00:41:59 +0000241static bool hasComputableBounds(ScalarEvolution *SE,
242 const ValueToValueMap &Strides, Value *Ptr) {
Adam Nemet04563272015-02-01 16:56:15 +0000243 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
244 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
245 if (!AR)
246 return false;
247
248 return AR->isAffine();
249}
250
251/// \brief Check the stride of the pointer and ensure that it does not wrap in
252/// the address space.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000253static int isStridedPtr(ScalarEvolution *SE, Value *Ptr, const Loop *Lp,
254 const ValueToValueMap &StridesMap);
Adam Nemet04563272015-02-01 16:56:15 +0000255
256bool AccessAnalysis::canCheckPtrAtRT(
Adam Nemet8bc61df2015-02-24 00:41:59 +0000257 LoopAccessInfo::RuntimePointerCheck &RtCheck, unsigned &NumComparisons,
258 ScalarEvolution *SE, Loop *TheLoop, const ValueToValueMap &StridesMap,
259 bool ShouldCheckStride) {
Adam Nemet04563272015-02-01 16:56:15 +0000260 // Find pointers with computable bounds. We are going to use this information
261 // to place a runtime bound check.
262 bool CanDoRT = true;
263
264 bool IsDepCheckNeeded = isDependencyCheckNeeded();
265 NumComparisons = 0;
266
267 // We assign a consecutive id to access from different alias sets.
268 // Accesses between different groups doesn't need to be checked.
269 unsigned ASId = 1;
270 for (auto &AS : AST) {
271 unsigned NumReadPtrChecks = 0;
272 unsigned NumWritePtrChecks = 0;
273
274 // We assign consecutive id to access from different dependence sets.
275 // Accesses within the same set don't need a runtime check.
276 unsigned RunningDepId = 1;
277 DenseMap<Value *, unsigned> DepSetId;
278
279 for (auto A : AS) {
280 Value *Ptr = A.getValue();
281 bool IsWrite = Accesses.count(MemAccessInfo(Ptr, true));
282 MemAccessInfo Access(Ptr, IsWrite);
283
284 if (IsWrite)
285 ++NumWritePtrChecks;
286 else
287 ++NumReadPtrChecks;
288
289 if (hasComputableBounds(SE, StridesMap, Ptr) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000290 // When we run after a failing dependency check we have to make sure
291 // we don't have wrapping pointers.
Adam Nemet04563272015-02-01 16:56:15 +0000292 (!ShouldCheckStride ||
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000293 isStridedPtr(SE, Ptr, TheLoop, StridesMap) == 1)) {
Adam Nemet04563272015-02-01 16:56:15 +0000294 // The id of the dependence set.
295 unsigned DepId;
296
297 if (IsDepCheckNeeded) {
298 Value *Leader = DepCands.getLeaderValue(Access).getPointer();
299 unsigned &LeaderId = DepSetId[Leader];
300 if (!LeaderId)
301 LeaderId = RunningDepId++;
302 DepId = LeaderId;
303 } else
304 // Each access has its own dependence set.
305 DepId = RunningDepId++;
306
307 RtCheck.insert(SE, TheLoop, Ptr, IsWrite, DepId, ASId, StridesMap);
308
Adam Nemet339f42b2015-02-19 19:15:07 +0000309 DEBUG(dbgs() << "LAA: Found a runtime check ptr:" << *Ptr << '\n');
Adam Nemet04563272015-02-01 16:56:15 +0000310 } else {
311 CanDoRT = false;
312 }
313 }
314
315 if (IsDepCheckNeeded && CanDoRT && RunningDepId == 2)
316 NumComparisons += 0; // Only one dependence set.
317 else {
318 NumComparisons += (NumWritePtrChecks * (NumReadPtrChecks +
319 NumWritePtrChecks - 1));
320 }
321
322 ++ASId;
323 }
324
325 // If the pointers that we would use for the bounds comparison have different
326 // address spaces, assume the values aren't directly comparable, so we can't
327 // use them for the runtime check. We also have to assume they could
328 // overlap. In the future there should be metadata for whether address spaces
329 // are disjoint.
330 unsigned NumPointers = RtCheck.Pointers.size();
331 for (unsigned i = 0; i < NumPointers; ++i) {
332 for (unsigned j = i + 1; j < NumPointers; ++j) {
333 // Only need to check pointers between two different dependency sets.
334 if (RtCheck.DependencySetId[i] == RtCheck.DependencySetId[j])
335 continue;
336 // Only need to check pointers in the same alias set.
337 if (RtCheck.AliasSetId[i] != RtCheck.AliasSetId[j])
338 continue;
339
340 Value *PtrI = RtCheck.Pointers[i];
341 Value *PtrJ = RtCheck.Pointers[j];
342
343 unsigned ASi = PtrI->getType()->getPointerAddressSpace();
344 unsigned ASj = PtrJ->getType()->getPointerAddressSpace();
345 if (ASi != ASj) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000346 DEBUG(dbgs() << "LAA: Runtime check would require comparison between"
Adam Nemet04d41632015-02-19 19:14:34 +0000347 " different address spaces\n");
Adam Nemet04563272015-02-01 16:56:15 +0000348 return false;
349 }
350 }
351 }
352
353 return CanDoRT;
354}
355
356void AccessAnalysis::processMemAccesses() {
357 // We process the set twice: first we process read-write pointers, last we
358 // process read-only pointers. This allows us to skip dependence tests for
359 // read-only pointers.
360
Adam Nemet339f42b2015-02-19 19:15:07 +0000361 DEBUG(dbgs() << "LAA: Processing memory accesses...\n");
Adam Nemet04563272015-02-01 16:56:15 +0000362 DEBUG(dbgs() << " AST: "; AST.dump());
Adam Nemet339f42b2015-02-19 19:15:07 +0000363 DEBUG(dbgs() << "LAA: Accesses:\n");
Adam Nemet04563272015-02-01 16:56:15 +0000364 DEBUG({
365 for (auto A : Accesses)
366 dbgs() << "\t" << *A.getPointer() << " (" <<
367 (A.getInt() ? "write" : (ReadOnlyPtr.count(A.getPointer()) ?
368 "read-only" : "read")) << ")\n";
369 });
370
371 // The AliasSetTracker has nicely partitioned our pointers by metadata
372 // compatibility and potential for underlying-object overlap. As a result, we
373 // only need to check for potential pointer dependencies within each alias
374 // set.
375 for (auto &AS : AST) {
376 // Note that both the alias-set tracker and the alias sets themselves used
377 // linked lists internally and so the iteration order here is deterministic
378 // (matching the original instruction order within each set).
379
380 bool SetHasWrite = false;
381
382 // Map of pointers to last access encountered.
383 typedef DenseMap<Value*, MemAccessInfo> UnderlyingObjToAccessMap;
384 UnderlyingObjToAccessMap ObjToLastAccess;
385
386 // Set of access to check after all writes have been processed.
387 PtrAccessSet DeferredAccesses;
388
389 // Iterate over each alias set twice, once to process read/write pointers,
390 // and then to process read-only pointers.
391 for (int SetIteration = 0; SetIteration < 2; ++SetIteration) {
392 bool UseDeferred = SetIteration > 0;
393 PtrAccessSet &S = UseDeferred ? DeferredAccesses : Accesses;
394
395 for (auto AV : AS) {
396 Value *Ptr = AV.getValue();
397
398 // For a single memory access in AliasSetTracker, Accesses may contain
399 // both read and write, and they both need to be handled for CheckDeps.
400 for (auto AC : S) {
401 if (AC.getPointer() != Ptr)
402 continue;
403
404 bool IsWrite = AC.getInt();
405
406 // If we're using the deferred access set, then it contains only
407 // reads.
408 bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite;
409 if (UseDeferred && !IsReadOnlyPtr)
410 continue;
411 // Otherwise, the pointer must be in the PtrAccessSet, either as a
412 // read or a write.
413 assert(((IsReadOnlyPtr && UseDeferred) || IsWrite ||
414 S.count(MemAccessInfo(Ptr, false))) &&
415 "Alias-set pointer not in the access set?");
416
417 MemAccessInfo Access(Ptr, IsWrite);
418 DepCands.insert(Access);
419
420 // Memorize read-only pointers for later processing and skip them in
421 // the first round (they need to be checked after we have seen all
422 // write pointers). Note: we also mark pointer that are not
423 // consecutive as "read-only" pointers (so that we check
424 // "a[b[i]] +="). Hence, we need the second check for "!IsWrite".
425 if (!UseDeferred && IsReadOnlyPtr) {
426 DeferredAccesses.insert(Access);
427 continue;
428 }
429
430 // If this is a write - check other reads and writes for conflicts. If
431 // this is a read only check other writes for conflicts (but only if
432 // there is no other write to the ptr - this is an optimization to
433 // catch "a[i] = a[i] + " without having to do a dependence check).
434 if ((IsWrite || IsReadOnlyPtr) && SetHasWrite) {
435 CheckDeps.insert(Access);
436 IsRTCheckNeeded = true;
437 }
438
439 if (IsWrite)
440 SetHasWrite = true;
441
442 // Create sets of pointers connected by a shared alias set and
443 // underlying object.
444 typedef SmallVector<Value *, 16> ValueVector;
445 ValueVector TempObjects;
446 GetUnderlyingObjects(Ptr, TempObjects, DL);
447 for (Value *UnderlyingObj : TempObjects) {
448 UnderlyingObjToAccessMap::iterator Prev =
449 ObjToLastAccess.find(UnderlyingObj);
450 if (Prev != ObjToLastAccess.end())
451 DepCands.unionSets(Access, Prev->second);
452
453 ObjToLastAccess[UnderlyingObj] = Access;
454 }
455 }
456 }
457 }
458 }
459}
460
Adam Nemet04563272015-02-01 16:56:15 +0000461static bool isInBoundsGep(Value *Ptr) {
462 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
463 return GEP->isInBounds();
464 return false;
465}
466
467/// \brief Check whether the access through \p Ptr has a constant stride.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000468static int isStridedPtr(ScalarEvolution *SE, Value *Ptr, const Loop *Lp,
469 const ValueToValueMap &StridesMap) {
Adam Nemet04563272015-02-01 16:56:15 +0000470 const Type *Ty = Ptr->getType();
471 assert(Ty->isPointerTy() && "Unexpected non-ptr");
472
473 // Make sure that the pointer does not point to aggregate types.
474 const PointerType *PtrTy = cast<PointerType>(Ty);
475 if (PtrTy->getElementType()->isAggregateType()) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000476 DEBUG(dbgs() << "LAA: Bad stride - Not a pointer to a scalar type"
477 << *Ptr << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000478 return 0;
479 }
480
481 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, StridesMap, Ptr);
482
483 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
484 if (!AR) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000485 DEBUG(dbgs() << "LAA: Bad stride - Not an AddRecExpr pointer "
Adam Nemet04d41632015-02-19 19:14:34 +0000486 << *Ptr << " SCEV: " << *PtrScev << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000487 return 0;
488 }
489
490 // The accesss function must stride over the innermost loop.
491 if (Lp != AR->getLoop()) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000492 DEBUG(dbgs() << "LAA: Bad stride - Not striding over innermost loop " <<
Adam Nemet04d41632015-02-19 19:14:34 +0000493 *Ptr << " SCEV: " << *PtrScev << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000494 }
495
496 // The address calculation must not wrap. Otherwise, a dependence could be
497 // inverted.
498 // An inbounds getelementptr that is a AddRec with a unit stride
499 // cannot wrap per definition. The unit stride requirement is checked later.
500 // An getelementptr without an inbounds attribute and unit stride would have
501 // to access the pointer value "0" which is undefined behavior in address
502 // space 0, therefore we can also vectorize this case.
503 bool IsInBoundsGEP = isInBoundsGep(Ptr);
504 bool IsNoWrapAddRec = AR->getNoWrapFlags(SCEV::NoWrapMask);
505 bool IsInAddressSpaceZero = PtrTy->getAddressSpace() == 0;
506 if (!IsNoWrapAddRec && !IsInBoundsGEP && !IsInAddressSpaceZero) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000507 DEBUG(dbgs() << "LAA: Bad stride - Pointer may wrap in the address space "
Adam Nemet04d41632015-02-19 19:14:34 +0000508 << *Ptr << " SCEV: " << *PtrScev << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000509 return 0;
510 }
511
512 // Check the step is constant.
513 const SCEV *Step = AR->getStepRecurrence(*SE);
514
515 // Calculate the pointer stride and check if it is consecutive.
516 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
517 if (!C) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000518 DEBUG(dbgs() << "LAA: Bad stride - Not a constant strided " << *Ptr <<
Adam Nemet04d41632015-02-19 19:14:34 +0000519 " SCEV: " << *PtrScev << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000520 return 0;
521 }
522
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000523 auto &DL = Lp->getHeader()->getModule()->getDataLayout();
524 int64_t Size = DL.getTypeAllocSize(PtrTy->getElementType());
Adam Nemet04563272015-02-01 16:56:15 +0000525 const APInt &APStepVal = C->getValue()->getValue();
526
527 // Huge step value - give up.
528 if (APStepVal.getBitWidth() > 64)
529 return 0;
530
531 int64_t StepVal = APStepVal.getSExtValue();
532
533 // Strided access.
534 int64_t Stride = StepVal / Size;
535 int64_t Rem = StepVal % Size;
536 if (Rem)
537 return 0;
538
539 // If the SCEV could wrap but we have an inbounds gep with a unit stride we
540 // know we can't "wrap around the address space". In case of address space
541 // zero we know that this won't happen without triggering undefined behavior.
542 if (!IsNoWrapAddRec && (IsInBoundsGEP || IsInAddressSpaceZero) &&
543 Stride != 1 && Stride != -1)
544 return 0;
545
546 return Stride;
547}
548
549bool MemoryDepChecker::couldPreventStoreLoadForward(unsigned Distance,
550 unsigned TypeByteSize) {
551 // If loads occur at a distance that is not a multiple of a feasible vector
552 // factor store-load forwarding does not take place.
553 // Positive dependences might cause troubles because vectorizing them might
554 // prevent store-load forwarding making vectorized code run a lot slower.
555 // a[i] = a[i-3] ^ a[i-8];
556 // The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
557 // hence on your typical architecture store-load forwarding does not take
558 // place. Vectorizing in such cases does not make sense.
559 // Store-load forwarding distance.
560 const unsigned NumCyclesForStoreLoadThroughMemory = 8*TypeByteSize;
561 // Maximum vector factor.
Adam Nemetf219c642015-02-19 19:14:52 +0000562 unsigned MaxVFWithoutSLForwardIssues =
563 VectorizerParams::MaxVectorWidth * TypeByteSize;
Adam Nemet04d41632015-02-19 19:14:34 +0000564 if(MaxSafeDepDistBytes < MaxVFWithoutSLForwardIssues)
Adam Nemet04563272015-02-01 16:56:15 +0000565 MaxVFWithoutSLForwardIssues = MaxSafeDepDistBytes;
566
567 for (unsigned vf = 2*TypeByteSize; vf <= MaxVFWithoutSLForwardIssues;
568 vf *= 2) {
569 if (Distance % vf && Distance / vf < NumCyclesForStoreLoadThroughMemory) {
570 MaxVFWithoutSLForwardIssues = (vf >>=1);
571 break;
572 }
573 }
574
Adam Nemet04d41632015-02-19 19:14:34 +0000575 if (MaxVFWithoutSLForwardIssues< 2*TypeByteSize) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000576 DEBUG(dbgs() << "LAA: Distance " << Distance <<
Adam Nemet04d41632015-02-19 19:14:34 +0000577 " that could cause a store-load forwarding conflict\n");
Adam Nemet04563272015-02-01 16:56:15 +0000578 return true;
579 }
580
581 if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes &&
Adam Nemetf219c642015-02-19 19:14:52 +0000582 MaxVFWithoutSLForwardIssues !=
583 VectorizerParams::MaxVectorWidth * TypeByteSize)
Adam Nemet04563272015-02-01 16:56:15 +0000584 MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues;
585 return false;
586}
587
588bool MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
589 const MemAccessInfo &B, unsigned BIdx,
Adam Nemet8bc61df2015-02-24 00:41:59 +0000590 const ValueToValueMap &Strides) {
Adam Nemet04563272015-02-01 16:56:15 +0000591 assert (AIdx < BIdx && "Must pass arguments in program order");
592
593 Value *APtr = A.getPointer();
594 Value *BPtr = B.getPointer();
595 bool AIsWrite = A.getInt();
596 bool BIsWrite = B.getInt();
597
598 // Two reads are independent.
599 if (!AIsWrite && !BIsWrite)
600 return false;
601
602 // We cannot check pointers in different address spaces.
603 if (APtr->getType()->getPointerAddressSpace() !=
604 BPtr->getType()->getPointerAddressSpace())
605 return true;
606
607 const SCEV *AScev = replaceSymbolicStrideSCEV(SE, Strides, APtr);
608 const SCEV *BScev = replaceSymbolicStrideSCEV(SE, Strides, BPtr);
609
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000610 int StrideAPtr = isStridedPtr(SE, APtr, InnermostLoop, Strides);
611 int StrideBPtr = isStridedPtr(SE, BPtr, InnermostLoop, Strides);
Adam Nemet04563272015-02-01 16:56:15 +0000612
613 const SCEV *Src = AScev;
614 const SCEV *Sink = BScev;
615
616 // If the induction step is negative we have to invert source and sink of the
617 // dependence.
618 if (StrideAPtr < 0) {
619 //Src = BScev;
620 //Sink = AScev;
621 std::swap(APtr, BPtr);
622 std::swap(Src, Sink);
623 std::swap(AIsWrite, BIsWrite);
624 std::swap(AIdx, BIdx);
625 std::swap(StrideAPtr, StrideBPtr);
626 }
627
628 const SCEV *Dist = SE->getMinusSCEV(Sink, Src);
629
Adam Nemet339f42b2015-02-19 19:15:07 +0000630 DEBUG(dbgs() << "LAA: Src Scev: " << *Src << "Sink Scev: " << *Sink
Adam Nemet04d41632015-02-19 19:14:34 +0000631 << "(Induction step: " << StrideAPtr << ")\n");
Adam Nemet339f42b2015-02-19 19:15:07 +0000632 DEBUG(dbgs() << "LAA: Distance for " << *InstMap[AIdx] << " to "
Adam Nemet04d41632015-02-19 19:14:34 +0000633 << *InstMap[BIdx] << ": " << *Dist << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000634
635 // Need consecutive accesses. We don't want to vectorize
636 // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in
637 // the address space.
638 if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){
639 DEBUG(dbgs() << "Non-consecutive pointer access\n");
640 return true;
641 }
642
643 const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist);
644 if (!C) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000645 DEBUG(dbgs() << "LAA: Dependence because of non-constant distance\n");
Adam Nemet04563272015-02-01 16:56:15 +0000646 ShouldRetryWithRuntimeCheck = true;
647 return true;
648 }
649
650 Type *ATy = APtr->getType()->getPointerElementType();
651 Type *BTy = BPtr->getType()->getPointerElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000652 auto &DL = InnermostLoop->getHeader()->getModule()->getDataLayout();
653 unsigned TypeByteSize = DL.getTypeAllocSize(ATy);
Adam Nemet04563272015-02-01 16:56:15 +0000654
655 // Negative distances are not plausible dependencies.
656 const APInt &Val = C->getValue()->getValue();
657 if (Val.isNegative()) {
658 bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
659 if (IsTrueDataDependence &&
660 (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) ||
661 ATy != BTy))
662 return true;
663
Adam Nemet339f42b2015-02-19 19:15:07 +0000664 DEBUG(dbgs() << "LAA: Dependence is negative: NoDep\n");
Adam Nemet04563272015-02-01 16:56:15 +0000665 return false;
666 }
667
668 // Write to the same location with the same size.
669 // Could be improved to assert type sizes are the same (i32 == float, etc).
670 if (Val == 0) {
671 if (ATy == BTy)
672 return false;
Adam Nemet339f42b2015-02-19 19:15:07 +0000673 DEBUG(dbgs() << "LAA: Zero dependence difference but different types\n");
Adam Nemet04563272015-02-01 16:56:15 +0000674 return true;
675 }
676
677 assert(Val.isStrictlyPositive() && "Expect a positive value");
678
Adam Nemet04563272015-02-01 16:56:15 +0000679 if (ATy != BTy) {
Adam Nemet04d41632015-02-19 19:14:34 +0000680 DEBUG(dbgs() <<
Adam Nemet339f42b2015-02-19 19:15:07 +0000681 "LAA: ReadWrite-Write positive dependency with different types\n");
Adam Nemet9cc0c392015-02-26 17:58:48 +0000682 return true;
Adam Nemet04563272015-02-01 16:56:15 +0000683 }
684
685 unsigned Distance = (unsigned) Val.getZExtValue();
686
687 // Bail out early if passed-in parameters make vectorization not feasible.
Adam Nemetf219c642015-02-19 19:14:52 +0000688 unsigned ForcedFactor = (VectorizerParams::VectorizationFactor ?
689 VectorizerParams::VectorizationFactor : 1);
690 unsigned ForcedUnroll = (VectorizerParams::VectorizationInterleave ?
691 VectorizerParams::VectorizationInterleave : 1);
Adam Nemet04563272015-02-01 16:56:15 +0000692
693 // The distance must be bigger than the size needed for a vectorized version
694 // of the operation and the size of the vectorized operation must not be
695 // bigger than the currrent maximum size.
696 if (Distance < 2*TypeByteSize ||
697 2*TypeByteSize > MaxSafeDepDistBytes ||
698 Distance < TypeByteSize * ForcedUnroll * ForcedFactor) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000699 DEBUG(dbgs() << "LAA: Failure because of Positive distance "
Adam Nemet04d41632015-02-19 19:14:34 +0000700 << Val.getSExtValue() << '\n');
Adam Nemet04563272015-02-01 16:56:15 +0000701 return true;
702 }
703
Adam Nemet9cc0c392015-02-26 17:58:48 +0000704 // Positive distance bigger than max vectorization factor.
Adam Nemet04563272015-02-01 16:56:15 +0000705 MaxSafeDepDistBytes = Distance < MaxSafeDepDistBytes ?
706 Distance : MaxSafeDepDistBytes;
707
708 bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
709 if (IsTrueDataDependence &&
710 couldPreventStoreLoadForward(Distance, TypeByteSize))
711 return true;
712
Adam Nemet339f42b2015-02-19 19:15:07 +0000713 DEBUG(dbgs() << "LAA: Positive distance " << Val.getSExtValue() <<
Adam Nemet04d41632015-02-19 19:14:34 +0000714 " with max VF = " << MaxSafeDepDistBytes / TypeByteSize << '\n');
Adam Nemet04563272015-02-01 16:56:15 +0000715
716 return false;
717}
718
Adam Nemetdee666b2015-03-10 17:40:34 +0000719bool MemoryDepChecker::areDepsSafe(DepCandidates &AccessSets,
Adam Nemet04563272015-02-01 16:56:15 +0000720 MemAccessInfoSet &CheckDeps,
Adam Nemet8bc61df2015-02-24 00:41:59 +0000721 const ValueToValueMap &Strides) {
Adam Nemet04563272015-02-01 16:56:15 +0000722
723 MaxSafeDepDistBytes = -1U;
724 while (!CheckDeps.empty()) {
725 MemAccessInfo CurAccess = *CheckDeps.begin();
726
727 // Get the relevant memory access set.
728 EquivalenceClasses<MemAccessInfo>::iterator I =
729 AccessSets.findValue(AccessSets.getLeaderValue(CurAccess));
730
731 // Check accesses within this set.
732 EquivalenceClasses<MemAccessInfo>::member_iterator AI, AE;
733 AI = AccessSets.member_begin(I), AE = AccessSets.member_end();
734
735 // Check every access pair.
736 while (AI != AE) {
737 CheckDeps.erase(*AI);
738 EquivalenceClasses<MemAccessInfo>::member_iterator OI = std::next(AI);
739 while (OI != AE) {
740 // Check every accessing instruction pair in program order.
741 for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(),
742 I1E = Accesses[*AI].end(); I1 != I1E; ++I1)
743 for (std::vector<unsigned>::iterator I2 = Accesses[*OI].begin(),
744 I2E = Accesses[*OI].end(); I2 != I2E; ++I2) {
745 if (*I1 < *I2 && isDependent(*AI, *I1, *OI, *I2, Strides))
746 return false;
747 if (*I2 < *I1 && isDependent(*OI, *I2, *AI, *I1, Strides))
748 return false;
749 }
750 ++OI;
751 }
752 AI++;
753 }
754 }
755 return true;
756}
757
Adam Nemet929c38e2015-02-19 19:15:10 +0000758bool LoopAccessInfo::canAnalyzeLoop() {
759 // We can only analyze innermost loops.
760 if (!TheLoop->empty()) {
Adam Nemet2bd6e982015-02-19 19:15:15 +0000761 emitAnalysis(LoopAccessReport() << "loop is not the innermost loop");
Adam Nemet929c38e2015-02-19 19:15:10 +0000762 return false;
763 }
764
765 // We must have a single backedge.
766 if (TheLoop->getNumBackEdges() != 1) {
767 emitAnalysis(
Adam Nemet2bd6e982015-02-19 19:15:15 +0000768 LoopAccessReport() <<
Adam Nemet929c38e2015-02-19 19:15:10 +0000769 "loop control flow is not understood by analyzer");
770 return false;
771 }
772
773 // We must have a single exiting block.
774 if (!TheLoop->getExitingBlock()) {
775 emitAnalysis(
Adam Nemet2bd6e982015-02-19 19:15:15 +0000776 LoopAccessReport() <<
Adam Nemet929c38e2015-02-19 19:15:10 +0000777 "loop control flow is not understood by analyzer");
778 return false;
779 }
780
781 // We only handle bottom-tested loops, i.e. loop in which the condition is
782 // checked at the end of each iteration. With that we can assume that all
783 // instructions in the loop are executed the same number of times.
784 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
785 emitAnalysis(
Adam Nemet2bd6e982015-02-19 19:15:15 +0000786 LoopAccessReport() <<
Adam Nemet929c38e2015-02-19 19:15:10 +0000787 "loop control flow is not understood by analyzer");
788 return false;
789 }
790
791 // We need to have a loop header.
792 DEBUG(dbgs() << "LAA: Found a loop: " <<
793 TheLoop->getHeader()->getName() << '\n');
794
795 // ScalarEvolution needs to be able to find the exit count.
796 const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop);
797 if (ExitCount == SE->getCouldNotCompute()) {
Adam Nemet2bd6e982015-02-19 19:15:15 +0000798 emitAnalysis(LoopAccessReport() <<
Adam Nemet929c38e2015-02-19 19:15:10 +0000799 "could not determine number of loop iterations");
800 DEBUG(dbgs() << "LAA: SCEV could not compute the loop exit count.\n");
801 return false;
802 }
803
804 return true;
805}
806
Adam Nemet8bc61df2015-02-24 00:41:59 +0000807void LoopAccessInfo::analyzeLoop(const ValueToValueMap &Strides) {
Adam Nemet04563272015-02-01 16:56:15 +0000808
809 typedef SmallVector<Value*, 16> ValueVector;
810 typedef SmallPtrSet<Value*, 16> ValueSet;
811
812 // Holds the Load and Store *instructions*.
813 ValueVector Loads;
814 ValueVector Stores;
815
816 // Holds all the different accesses in the loop.
817 unsigned NumReads = 0;
818 unsigned NumReadWrites = 0;
819
820 PtrRtCheck.Pointers.clear();
821 PtrRtCheck.Need = false;
822
823 const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
Adam Nemet04563272015-02-01 16:56:15 +0000824
825 // For each block.
826 for (Loop::block_iterator bb = TheLoop->block_begin(),
827 be = TheLoop->block_end(); bb != be; ++bb) {
828
829 // Scan the BB and collect legal loads and stores.
830 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
831 ++it) {
832
833 // If this is a load, save it. If this instruction can read from memory
834 // but is not a load, then we quit. Notice that we don't handle function
835 // calls that read or write.
836 if (it->mayReadFromMemory()) {
837 // Many math library functions read the rounding mode. We will only
838 // vectorize a loop if it contains known function calls that don't set
839 // the flag. Therefore, it is safe to ignore this read from memory.
840 CallInst *Call = dyn_cast<CallInst>(it);
841 if (Call && getIntrinsicIDForCall(Call, TLI))
842 continue;
843
844 LoadInst *Ld = dyn_cast<LoadInst>(it);
845 if (!Ld || (!Ld->isSimple() && !IsAnnotatedParallel)) {
Adam Nemet2bd6e982015-02-19 19:15:15 +0000846 emitAnalysis(LoopAccessReport(Ld)
Adam Nemet04563272015-02-01 16:56:15 +0000847 << "read with atomic ordering or volatile read");
Adam Nemet339f42b2015-02-19 19:15:07 +0000848 DEBUG(dbgs() << "LAA: Found a non-simple load.\n");
Adam Nemet436018c2015-02-19 19:15:00 +0000849 CanVecMem = false;
850 return;
Adam Nemet04563272015-02-01 16:56:15 +0000851 }
852 NumLoads++;
853 Loads.push_back(Ld);
854 DepChecker.addAccess(Ld);
855 continue;
856 }
857
858 // Save 'store' instructions. Abort if other instructions write to memory.
859 if (it->mayWriteToMemory()) {
860 StoreInst *St = dyn_cast<StoreInst>(it);
861 if (!St) {
Adam Nemet2bd6e982015-02-19 19:15:15 +0000862 emitAnalysis(LoopAccessReport(it) <<
Adam Nemet04d41632015-02-19 19:14:34 +0000863 "instruction cannot be vectorized");
Adam Nemet436018c2015-02-19 19:15:00 +0000864 CanVecMem = false;
865 return;
Adam Nemet04563272015-02-01 16:56:15 +0000866 }
867 if (!St->isSimple() && !IsAnnotatedParallel) {
Adam Nemet2bd6e982015-02-19 19:15:15 +0000868 emitAnalysis(LoopAccessReport(St)
Adam Nemet04563272015-02-01 16:56:15 +0000869 << "write with atomic ordering or volatile write");
Adam Nemet339f42b2015-02-19 19:15:07 +0000870 DEBUG(dbgs() << "LAA: Found a non-simple store.\n");
Adam Nemet436018c2015-02-19 19:15:00 +0000871 CanVecMem = false;
872 return;
Adam Nemet04563272015-02-01 16:56:15 +0000873 }
874 NumStores++;
875 Stores.push_back(St);
876 DepChecker.addAccess(St);
877 }
878 } // Next instr.
879 } // Next block.
880
881 // Now we have two lists that hold the loads and the stores.
882 // Next, we find the pointers that they use.
883
884 // Check if we see any stores. If there are no stores, then we don't
885 // care if the pointers are *restrict*.
886 if (!Stores.size()) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000887 DEBUG(dbgs() << "LAA: Found a read-only loop!\n");
Adam Nemet436018c2015-02-19 19:15:00 +0000888 CanVecMem = true;
889 return;
Adam Nemet04563272015-02-01 16:56:15 +0000890 }
891
Adam Nemetdee666b2015-03-10 17:40:34 +0000892 MemoryDepChecker::DepCandidates DependentAccesses;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000893 AccessAnalysis Accesses(TheLoop->getHeader()->getModule()->getDataLayout(),
894 AA, DependentAccesses);
Adam Nemet04563272015-02-01 16:56:15 +0000895
896 // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
897 // multiple times on the same object. If the ptr is accessed twice, once
898 // for read and once for write, it will only appear once (on the write
899 // list). This is okay, since we are going to check for conflicts between
900 // writes and between reads and writes, but not between reads and reads.
901 ValueSet Seen;
902
903 ValueVector::iterator I, IE;
904 for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
905 StoreInst *ST = cast<StoreInst>(*I);
906 Value* Ptr = ST->getPointerOperand();
907
908 if (isUniform(Ptr)) {
909 emitAnalysis(
Adam Nemet2bd6e982015-02-19 19:15:15 +0000910 LoopAccessReport(ST)
Adam Nemet04563272015-02-01 16:56:15 +0000911 << "write to a loop invariant address could not be vectorized");
Adam Nemet339f42b2015-02-19 19:15:07 +0000912 DEBUG(dbgs() << "LAA: We don't allow storing to uniform addresses\n");
Adam Nemet436018c2015-02-19 19:15:00 +0000913 CanVecMem = false;
914 return;
Adam Nemet04563272015-02-01 16:56:15 +0000915 }
916
917 // If we did *not* see this pointer before, insert it to the read-write
918 // list. At this phase it is only a 'write' list.
919 if (Seen.insert(Ptr).second) {
920 ++NumReadWrites;
921
922 AliasAnalysis::Location Loc = AA->getLocation(ST);
923 // The TBAA metadata could have a control dependency on the predication
924 // condition, so we cannot rely on it when determining whether or not we
925 // need runtime pointer checks.
Adam Nemet01abb2c2015-02-18 03:43:19 +0000926 if (blockNeedsPredication(ST->getParent(), TheLoop, DT))
Adam Nemet04563272015-02-01 16:56:15 +0000927 Loc.AATags.TBAA = nullptr;
928
929 Accesses.addStore(Loc);
930 }
931 }
932
933 if (IsAnnotatedParallel) {
Adam Nemet04d41632015-02-19 19:14:34 +0000934 DEBUG(dbgs()
Adam Nemet339f42b2015-02-19 19:15:07 +0000935 << "LAA: A loop annotated parallel, ignore memory dependency "
Adam Nemet04d41632015-02-19 19:14:34 +0000936 << "checks.\n");
Adam Nemet436018c2015-02-19 19:15:00 +0000937 CanVecMem = true;
938 return;
Adam Nemet04563272015-02-01 16:56:15 +0000939 }
940
941 for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
942 LoadInst *LD = cast<LoadInst>(*I);
943 Value* Ptr = LD->getPointerOperand();
944 // If we did *not* see this pointer before, insert it to the
945 // read list. If we *did* see it before, then it is already in
946 // the read-write list. This allows us to vectorize expressions
947 // such as A[i] += x; Because the address of A[i] is a read-write
948 // pointer. This only works if the index of A[i] is consecutive.
949 // If the address of i is unknown (for example A[B[i]]) then we may
950 // read a few words, modify, and write a few words, and some of the
951 // words may be written to the same address.
952 bool IsReadOnlyPtr = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000953 if (Seen.insert(Ptr).second || !isStridedPtr(SE, Ptr, TheLoop, Strides)) {
Adam Nemet04563272015-02-01 16:56:15 +0000954 ++NumReads;
955 IsReadOnlyPtr = true;
956 }
957
958 AliasAnalysis::Location Loc = AA->getLocation(LD);
959 // The TBAA metadata could have a control dependency on the predication
960 // condition, so we cannot rely on it when determining whether or not we
961 // need runtime pointer checks.
Adam Nemet01abb2c2015-02-18 03:43:19 +0000962 if (blockNeedsPredication(LD->getParent(), TheLoop, DT))
Adam Nemet04563272015-02-01 16:56:15 +0000963 Loc.AATags.TBAA = nullptr;
964
965 Accesses.addLoad(Loc, IsReadOnlyPtr);
966 }
967
968 // If we write (or read-write) to a single destination and there are no
969 // other reads in this loop then is it safe to vectorize.
970 if (NumReadWrites == 1 && NumReads == 0) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000971 DEBUG(dbgs() << "LAA: Found a write-only loop!\n");
Adam Nemet436018c2015-02-19 19:15:00 +0000972 CanVecMem = true;
973 return;
Adam Nemet04563272015-02-01 16:56:15 +0000974 }
975
976 // Build dependence sets and check whether we need a runtime pointer bounds
977 // check.
978 Accesses.buildDependenceSets();
979 bool NeedRTCheck = Accesses.isRTCheckNeeded();
980
981 // Find pointers with computable bounds. We are going to use this information
982 // to place a runtime bound check.
983 unsigned NumComparisons = 0;
984 bool CanDoRT = false;
985 if (NeedRTCheck)
986 CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE, TheLoop,
987 Strides);
988
Adam Nemet339f42b2015-02-19 19:15:07 +0000989 DEBUG(dbgs() << "LAA: We need to do " << NumComparisons <<
Adam Nemet04d41632015-02-19 19:14:34 +0000990 " pointer comparisons.\n");
Adam Nemet04563272015-02-01 16:56:15 +0000991
992 // If we only have one set of dependences to check pointers among we don't
993 // need a runtime check.
994 if (NumComparisons == 0 && NeedRTCheck)
995 NeedRTCheck = false;
996
997 // Check that we did not collect too many pointers or found an unsizeable
998 // pointer.
Adam Nemet1d862af2015-02-26 04:39:09 +0000999 if (!CanDoRT || NumComparisons > RuntimeMemoryCheckThreshold) {
Adam Nemet04563272015-02-01 16:56:15 +00001000 PtrRtCheck.reset();
1001 CanDoRT = false;
1002 }
1003
1004 if (CanDoRT) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001005 DEBUG(dbgs() << "LAA: We can perform a memory runtime check if needed.\n");
Adam Nemet04563272015-02-01 16:56:15 +00001006 }
1007
1008 if (NeedRTCheck && !CanDoRT) {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001009 emitAnalysis(LoopAccessReport() << "cannot identify array bounds");
Adam Nemet339f42b2015-02-19 19:15:07 +00001010 DEBUG(dbgs() << "LAA: We can't vectorize because we can't find " <<
Adam Nemet04d41632015-02-19 19:14:34 +00001011 "the array bounds.\n");
Adam Nemet04563272015-02-01 16:56:15 +00001012 PtrRtCheck.reset();
Adam Nemet436018c2015-02-19 19:15:00 +00001013 CanVecMem = false;
1014 return;
Adam Nemet04563272015-02-01 16:56:15 +00001015 }
1016
1017 PtrRtCheck.Need = NeedRTCheck;
1018
Adam Nemet436018c2015-02-19 19:15:00 +00001019 CanVecMem = true;
Adam Nemet04563272015-02-01 16:56:15 +00001020 if (Accesses.isDependencyCheckNeeded()) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001021 DEBUG(dbgs() << "LAA: Checking memory dependencies\n");
Adam Nemet04563272015-02-01 16:56:15 +00001022 CanVecMem = DepChecker.areDepsSafe(
1023 DependentAccesses, Accesses.getDependenciesToCheck(), Strides);
1024 MaxSafeDepDistBytes = DepChecker.getMaxSafeDepDistBytes();
1025
1026 if (!CanVecMem && DepChecker.shouldRetryWithRuntimeCheck()) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001027 DEBUG(dbgs() << "LAA: Retrying with memory checks\n");
Adam Nemet04563272015-02-01 16:56:15 +00001028 NeedRTCheck = true;
1029
1030 // Clear the dependency checks. We assume they are not needed.
1031 Accesses.resetDepChecks();
1032
1033 PtrRtCheck.reset();
1034 PtrRtCheck.Need = true;
1035
1036 CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE,
1037 TheLoop, Strides, true);
1038 // Check that we did not collect too many pointers or found an unsizeable
1039 // pointer.
Adam Nemet1d862af2015-02-26 04:39:09 +00001040 if (!CanDoRT || NumComparisons > RuntimeMemoryCheckThreshold) {
Adam Nemet04563272015-02-01 16:56:15 +00001041 if (!CanDoRT && NumComparisons > 0)
Adam Nemet2bd6e982015-02-19 19:15:15 +00001042 emitAnalysis(LoopAccessReport()
Adam Nemet04563272015-02-01 16:56:15 +00001043 << "cannot check memory dependencies at runtime");
1044 else
Adam Nemet2bd6e982015-02-19 19:15:15 +00001045 emitAnalysis(LoopAccessReport()
Adam Nemet04563272015-02-01 16:56:15 +00001046 << NumComparisons << " exceeds limit of "
Adam Nemet1d862af2015-02-26 04:39:09 +00001047 << RuntimeMemoryCheckThreshold
Adam Nemet04563272015-02-01 16:56:15 +00001048 << " dependent memory operations checked at runtime");
Adam Nemet339f42b2015-02-19 19:15:07 +00001049 DEBUG(dbgs() << "LAA: Can't vectorize with memory checks\n");
Adam Nemet04563272015-02-01 16:56:15 +00001050 PtrRtCheck.reset();
Adam Nemet436018c2015-02-19 19:15:00 +00001051 CanVecMem = false;
1052 return;
Adam Nemet04563272015-02-01 16:56:15 +00001053 }
1054
1055 CanVecMem = true;
1056 }
1057 }
1058
1059 if (!CanVecMem)
Adam Nemet2bd6e982015-02-19 19:15:15 +00001060 emitAnalysis(LoopAccessReport() <<
Adam Nemet04d41632015-02-19 19:14:34 +00001061 "unsafe dependent memory operations in loop");
Adam Nemet04563272015-02-01 16:56:15 +00001062
Adam Nemet339f42b2015-02-19 19:15:07 +00001063 DEBUG(dbgs() << "LAA: We" << (NeedRTCheck ? "" : " don't") <<
Adam Nemet04d41632015-02-19 19:14:34 +00001064 " need a runtime memory check.\n");
Adam Nemet04563272015-02-01 16:56:15 +00001065}
1066
Adam Nemet01abb2c2015-02-18 03:43:19 +00001067bool LoopAccessInfo::blockNeedsPredication(BasicBlock *BB, Loop *TheLoop,
1068 DominatorTree *DT) {
Adam Nemet04563272015-02-01 16:56:15 +00001069 assert(TheLoop->contains(BB) && "Unknown block used");
1070
1071 // Blocks that do not dominate the latch need predication.
1072 BasicBlock* Latch = TheLoop->getLoopLatch();
1073 return !DT->dominates(BB, Latch);
1074}
1075
Adam Nemet2bd6e982015-02-19 19:15:15 +00001076void LoopAccessInfo::emitAnalysis(LoopAccessReport &Message) {
Adam Nemetc9228532015-02-19 19:14:56 +00001077 assert(!Report && "Multiple reports generated");
1078 Report = Message;
Adam Nemet04563272015-02-01 16:56:15 +00001079}
1080
Adam Nemet57ac7662015-02-19 19:15:21 +00001081bool LoopAccessInfo::isUniform(Value *V) const {
Adam Nemet04563272015-02-01 16:56:15 +00001082 return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
1083}
Adam Nemet7206d7a2015-02-06 18:31:04 +00001084
1085// FIXME: this function is currently a duplicate of the one in
1086// LoopVectorize.cpp.
1087static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
1088 Instruction *Loc) {
1089 if (FirstInst)
1090 return FirstInst;
1091 if (Instruction *I = dyn_cast<Instruction>(V))
1092 return I->getParent() == Loc->getParent() ? I : nullptr;
1093 return nullptr;
1094}
1095
1096std::pair<Instruction *, Instruction *>
Adam Nemet57ac7662015-02-19 19:15:21 +00001097LoopAccessInfo::addRuntimeCheck(Instruction *Loc) const {
Adam Nemet7206d7a2015-02-06 18:31:04 +00001098 Instruction *tnullptr = nullptr;
1099 if (!PtrRtCheck.Need)
1100 return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr);
1101
1102 unsigned NumPointers = PtrRtCheck.Pointers.size();
1103 SmallVector<TrackingVH<Value> , 2> Starts;
1104 SmallVector<TrackingVH<Value> , 2> Ends;
1105
1106 LLVMContext &Ctx = Loc->getContext();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001107 SCEVExpander Exp(*SE, DL, "induction");
Adam Nemet7206d7a2015-02-06 18:31:04 +00001108 Instruction *FirstInst = nullptr;
1109
1110 for (unsigned i = 0; i < NumPointers; ++i) {
1111 Value *Ptr = PtrRtCheck.Pointers[i];
1112 const SCEV *Sc = SE->getSCEV(Ptr);
1113
1114 if (SE->isLoopInvariant(Sc, TheLoop)) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001115 DEBUG(dbgs() << "LAA: Adding RT check for a loop invariant ptr:" <<
Adam Nemet04d41632015-02-19 19:14:34 +00001116 *Ptr <<"\n");
Adam Nemet7206d7a2015-02-06 18:31:04 +00001117 Starts.push_back(Ptr);
1118 Ends.push_back(Ptr);
1119 } else {
Adam Nemet339f42b2015-02-19 19:15:07 +00001120 DEBUG(dbgs() << "LAA: Adding RT check for range:" << *Ptr << '\n');
Adam Nemet7206d7a2015-02-06 18:31:04 +00001121 unsigned AS = Ptr->getType()->getPointerAddressSpace();
1122
1123 // Use this type for pointer arithmetic.
1124 Type *PtrArithTy = Type::getInt8PtrTy(Ctx, AS);
1125
1126 Value *Start = Exp.expandCodeFor(PtrRtCheck.Starts[i], PtrArithTy, Loc);
1127 Value *End = Exp.expandCodeFor(PtrRtCheck.Ends[i], PtrArithTy, Loc);
1128 Starts.push_back(Start);
1129 Ends.push_back(End);
1130 }
1131 }
1132
1133 IRBuilder<> ChkBuilder(Loc);
1134 // Our instructions might fold to a constant.
1135 Value *MemoryRuntimeCheck = nullptr;
1136 for (unsigned i = 0; i < NumPointers; ++i) {
1137 for (unsigned j = i+1; j < NumPointers; ++j) {
Adam Nemeta8945b72015-02-18 03:43:58 +00001138 if (!PtrRtCheck.needsChecking(i, j))
Adam Nemet7206d7a2015-02-06 18:31:04 +00001139 continue;
1140
1141 unsigned AS0 = Starts[i]->getType()->getPointerAddressSpace();
1142 unsigned AS1 = Starts[j]->getType()->getPointerAddressSpace();
1143
1144 assert((AS0 == Ends[j]->getType()->getPointerAddressSpace()) &&
1145 (AS1 == Ends[i]->getType()->getPointerAddressSpace()) &&
1146 "Trying to bounds check pointers with different address spaces");
1147
1148 Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0);
1149 Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1);
1150
1151 Value *Start0 = ChkBuilder.CreateBitCast(Starts[i], PtrArithTy0, "bc");
1152 Value *Start1 = ChkBuilder.CreateBitCast(Starts[j], PtrArithTy1, "bc");
1153 Value *End0 = ChkBuilder.CreateBitCast(Ends[i], PtrArithTy1, "bc");
1154 Value *End1 = ChkBuilder.CreateBitCast(Ends[j], PtrArithTy0, "bc");
1155
1156 Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0");
1157 FirstInst = getFirstInst(FirstInst, Cmp0, Loc);
1158 Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1");
1159 FirstInst = getFirstInst(FirstInst, Cmp1, Loc);
1160 Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
1161 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1162 if (MemoryRuntimeCheck) {
1163 IsConflict = ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict,
1164 "conflict.rdx");
1165 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1166 }
1167 MemoryRuntimeCheck = IsConflict;
1168 }
1169 }
1170
1171 // We have to do this trickery because the IRBuilder might fold the check to a
1172 // constant expression in which case there is no Instruction anchored in a
1173 // the block.
1174 Instruction *Check = BinaryOperator::CreateAnd(MemoryRuntimeCheck,
1175 ConstantInt::getTrue(Ctx));
1176 ChkBuilder.Insert(Check, "memcheck.conflict");
1177 FirstInst = getFirstInst(FirstInst, Check, Loc);
1178 return std::make_pair(FirstInst, Check);
1179}
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001180
1181LoopAccessInfo::LoopAccessInfo(Loop *L, ScalarEvolution *SE,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001182 const DataLayout &DL,
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001183 const TargetLibraryInfo *TLI, AliasAnalysis *AA,
Adam Nemet8bc61df2015-02-24 00:41:59 +00001184 DominatorTree *DT,
1185 const ValueToValueMap &Strides)
Adam Nemetdee666b2015-03-10 17:40:34 +00001186 : DepChecker(SE, L), TheLoop(L), SE(SE), DL(DL), TLI(TLI), AA(AA),
1187 DT(DT), NumLoads(0), NumStores(0), MaxSafeDepDistBytes(-1U),
1188 CanVecMem(false) {
Adam Nemet929c38e2015-02-19 19:15:10 +00001189 if (canAnalyzeLoop())
1190 analyzeLoop(Strides);
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001191}
1192
Adam Nemete91cc6e2015-02-19 19:15:19 +00001193void LoopAccessInfo::print(raw_ostream &OS, unsigned Depth) const {
1194 if (CanVecMem) {
1195 if (PtrRtCheck.empty())
1196 OS.indent(Depth) << "Memory dependences are safe\n";
1197 else
1198 OS.indent(Depth) << "Memory dependences are safe with run-time checks\n";
1199 }
1200
1201 if (Report)
1202 OS.indent(Depth) << "Report: " << Report->str() << "\n";
1203
1204 // FIXME: Print unsafe dependences
1205
1206 // List the pair of accesses need run-time checks to prove independence.
1207 PtrRtCheck.print(OS, Depth);
1208 OS << "\n";
1209}
1210
Adam Nemet8bc61df2015-02-24 00:41:59 +00001211const LoopAccessInfo &
1212LoopAccessAnalysis::getInfo(Loop *L, const ValueToValueMap &Strides) {
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001213 auto &LAI = LoopAccessInfoMap[L];
1214
1215#ifndef NDEBUG
1216 assert((!LAI || LAI->NumSymbolicStrides == Strides.size()) &&
1217 "Symbolic strides changed for loop");
1218#endif
1219
1220 if (!LAI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001221 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001222 LAI = llvm::make_unique<LoopAccessInfo>(L, SE, DL, TLI, AA, DT, Strides);
1223#ifndef NDEBUG
1224 LAI->NumSymbolicStrides = Strides.size();
1225#endif
1226 }
1227 return *LAI.get();
1228}
1229
Adam Nemete91cc6e2015-02-19 19:15:19 +00001230void LoopAccessAnalysis::print(raw_ostream &OS, const Module *M) const {
1231 LoopAccessAnalysis &LAA = *const_cast<LoopAccessAnalysis *>(this);
1232
1233 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1234 ValueToValueMap NoSymbolicStrides;
1235
1236 for (Loop *TopLevelLoop : *LI)
1237 for (Loop *L : depth_first(TopLevelLoop)) {
1238 OS.indent(2) << L->getHeader()->getName() << ":\n";
1239 auto &LAI = LAA.getInfo(L, NoSymbolicStrides);
1240 LAI.print(OS, 4);
1241 }
1242}
1243
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001244bool LoopAccessAnalysis::runOnFunction(Function &F) {
1245 SE = &getAnalysis<ScalarEvolution>();
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001246 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
1247 TLI = TLIP ? &TLIP->getTLI() : nullptr;
1248 AA = &getAnalysis<AliasAnalysis>();
1249 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1250
1251 return false;
1252}
1253
1254void LoopAccessAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
1255 AU.addRequired<ScalarEvolution>();
1256 AU.addRequired<AliasAnalysis>();
1257 AU.addRequired<DominatorTreeWrapperPass>();
Adam Nemete91cc6e2015-02-19 19:15:19 +00001258 AU.addRequired<LoopInfoWrapperPass>();
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001259
1260 AU.setPreservesAll();
1261}
1262
1263char LoopAccessAnalysis::ID = 0;
1264static const char laa_name[] = "Loop Access Analysis";
1265#define LAA_NAME "loop-accesses"
1266
1267INITIALIZE_PASS_BEGIN(LoopAccessAnalysis, LAA_NAME, laa_name, false, true)
1268INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
1269INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
1270INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Adam Nemete91cc6e2015-02-19 19:15:19 +00001271INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001272INITIALIZE_PASS_END(LoopAccessAnalysis, LAA_NAME, laa_name, false, true)
1273
1274namespace llvm {
1275 Pass *createLAAPass() {
1276 return new LoopAccessAnalysis();
1277 }
1278}