blob: b1dd51dc617d3524e114317b4c3d97ab86337ff6 [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
Silviu Baranga98a13712015-06-08 10:27:06 +0000180unsigned LoopAccessInfo::RuntimePointerCheck::getNumberOfChecks(
Adam Nemet51870d12015-04-07 03:35:26 +0000181 const SmallVectorImpl<int> *PtrPartition) const {
182 unsigned NumPointers = Pointers.size();
Silviu Baranga98a13712015-06-08 10:27:06 +0000183 unsigned CheckCount = 0;
Adam Nemet51870d12015-04-07 03:35:26 +0000184
185 for (unsigned I = 0; I < NumPointers; ++I)
186 for (unsigned J = I + 1; J < NumPointers; ++J)
187 if (needsChecking(I, J, PtrPartition))
Silviu Baranga98a13712015-06-08 10:27:06 +0000188 CheckCount++;
189 return CheckCount;
190}
191
192bool LoopAccessInfo::RuntimePointerCheck::needsAnyChecking(
193 const SmallVectorImpl<int> *PtrPartition) const {
194 return getNumberOfChecks(PtrPartition) != 0;
Adam Nemet51870d12015-04-07 03:35:26 +0000195}
196
Adam Nemet04563272015-02-01 16:56:15 +0000197namespace {
198/// \brief Analyses memory accesses in a loop.
199///
200/// Checks whether run time pointer checks are needed and builds sets for data
201/// dependence checking.
202class AccessAnalysis {
203public:
204 /// \brief Read or write access location.
205 typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
206 typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
207
Adam Nemete2b885c2015-04-23 20:09:20 +0000208 AccessAnalysis(const DataLayout &Dl, AliasAnalysis *AA, LoopInfo *LI,
Adam Nemetdee666b2015-03-10 17:40:34 +0000209 MemoryDepChecker::DepCandidates &DA)
Adam Nemete2b885c2015-04-23 20:09:20 +0000210 : DL(Dl), AST(*AA), LI(LI), DepCands(DA), IsRTCheckNeeded(false) {}
Adam Nemet04563272015-02-01 16:56:15 +0000211
212 /// \brief Register a load and whether it is only read from.
Chandler Carruthac80dc72015-06-17 07:18:54 +0000213 void addLoad(MemoryLocation &Loc, bool IsReadOnly) {
Adam Nemet04563272015-02-01 16:56:15 +0000214 Value *Ptr = const_cast<Value*>(Loc.Ptr);
Chandler Carruthecbd1682015-06-17 07:21:38 +0000215 AST.add(Ptr, MemoryLocation::UnknownSize, Loc.AATags);
Adam Nemet04563272015-02-01 16:56:15 +0000216 Accesses.insert(MemAccessInfo(Ptr, false));
217 if (IsReadOnly)
218 ReadOnlyPtr.insert(Ptr);
219 }
220
221 /// \brief Register a store.
Chandler Carruthac80dc72015-06-17 07:18:54 +0000222 void addStore(MemoryLocation &Loc) {
Adam Nemet04563272015-02-01 16:56:15 +0000223 Value *Ptr = const_cast<Value*>(Loc.Ptr);
Chandler Carruthecbd1682015-06-17 07:21:38 +0000224 AST.add(Ptr, MemoryLocation::UnknownSize, Loc.AATags);
Adam Nemet04563272015-02-01 16:56:15 +0000225 Accesses.insert(MemAccessInfo(Ptr, true));
226 }
227
228 /// \brief Check whether we can check the pointers at runtime for
Silviu Baranga98a13712015-06-08 10:27:06 +0000229 /// non-intersection. Returns true when we have 0 pointers
230 /// (a check on 0 pointers for non-intersection will always return true).
Adam Nemet30f16e12015-02-18 03:42:35 +0000231 bool canCheckPtrAtRT(LoopAccessInfo::RuntimePointerCheck &RtCheck,
Silviu Baranga98a13712015-06-08 10:27:06 +0000232 bool &NeedRTCheck, ScalarEvolution *SE, Loop *TheLoop,
233 const ValueToValueMap &Strides,
Adam Nemet04563272015-02-01 16:56:15 +0000234 bool ShouldCheckStride = false);
235
236 /// \brief Goes over all memory accesses, checks whether a RT check is needed
237 /// and builds sets of dependent accesses.
238 void buildDependenceSets() {
239 processMemAccesses();
240 }
241
242 bool isRTCheckNeeded() { return IsRTCheckNeeded; }
243
244 bool isDependencyCheckNeeded() { return !CheckDeps.empty(); }
Adam Nemetdf3dc5b2015-05-18 15:37:03 +0000245
246 /// We decided that no dependence analysis would be used. Reset the state.
247 void resetDepChecks(MemoryDepChecker &DepChecker) {
248 CheckDeps.clear();
249 DepChecker.clearInterestingDependences();
250 }
Adam Nemet04563272015-02-01 16:56:15 +0000251
252 MemAccessInfoSet &getDependenciesToCheck() { return CheckDeps; }
253
254private:
255 typedef SetVector<MemAccessInfo> PtrAccessSet;
256
257 /// \brief Go over all memory access and check whether runtime pointer checks
258 /// are needed /// and build sets of dependency check candidates.
259 void processMemAccesses();
260
261 /// Set of all accesses.
262 PtrAccessSet Accesses;
263
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000264 const DataLayout &DL;
265
Adam Nemet04563272015-02-01 16:56:15 +0000266 /// Set of accesses that need a further dependence check.
267 MemAccessInfoSet CheckDeps;
268
269 /// Set of pointers that are read only.
270 SmallPtrSet<Value*, 16> ReadOnlyPtr;
271
Adam Nemet04563272015-02-01 16:56:15 +0000272 /// An alias set tracker to partition the access set by underlying object and
273 //intrinsic property (such as TBAA metadata).
274 AliasSetTracker AST;
275
Adam Nemete2b885c2015-04-23 20:09:20 +0000276 LoopInfo *LI;
277
Adam Nemet04563272015-02-01 16:56:15 +0000278 /// Sets of potentially dependent accesses - members of one set share an
279 /// underlying pointer. The set "CheckDeps" identfies which sets really need a
280 /// dependence check.
Adam Nemetdee666b2015-03-10 17:40:34 +0000281 MemoryDepChecker::DepCandidates &DepCands;
Adam Nemet04563272015-02-01 16:56:15 +0000282
283 bool IsRTCheckNeeded;
284};
285
286} // end anonymous namespace
287
288/// \brief Check whether a pointer can participate in a runtime bounds check.
Adam Nemet8bc61df2015-02-24 00:41:59 +0000289static bool hasComputableBounds(ScalarEvolution *SE,
290 const ValueToValueMap &Strides, Value *Ptr) {
Adam Nemet04563272015-02-01 16:56:15 +0000291 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
292 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
293 if (!AR)
294 return false;
295
296 return AR->isAffine();
297}
298
Adam Nemet04563272015-02-01 16:56:15 +0000299bool AccessAnalysis::canCheckPtrAtRT(
Silviu Baranga98a13712015-06-08 10:27:06 +0000300 LoopAccessInfo::RuntimePointerCheck &RtCheck, bool &NeedRTCheck,
Adam Nemet8bc61df2015-02-24 00:41:59 +0000301 ScalarEvolution *SE, Loop *TheLoop, const ValueToValueMap &StridesMap,
302 bool ShouldCheckStride) {
Adam Nemet04563272015-02-01 16:56:15 +0000303 // Find pointers with computable bounds. We are going to use this information
304 // to place a runtime bound check.
305 bool CanDoRT = true;
306
Silviu Baranga98a13712015-06-08 10:27:06 +0000307 NeedRTCheck = false;
308 if (!IsRTCheckNeeded) return true;
309
Adam Nemet04563272015-02-01 16:56:15 +0000310 bool IsDepCheckNeeded = isDependencyCheckNeeded();
Adam Nemet04563272015-02-01 16:56:15 +0000311
312 // We assign a consecutive id to access from different alias sets.
313 // Accesses between different groups doesn't need to be checked.
314 unsigned ASId = 1;
315 for (auto &AS : AST) {
Adam Nemet04563272015-02-01 16:56:15 +0000316 // We assign consecutive id to access from different dependence sets.
317 // Accesses within the same set don't need a runtime check.
318 unsigned RunningDepId = 1;
319 DenseMap<Value *, unsigned> DepSetId;
320
321 for (auto A : AS) {
322 Value *Ptr = A.getValue();
323 bool IsWrite = Accesses.count(MemAccessInfo(Ptr, true));
324 MemAccessInfo Access(Ptr, IsWrite);
325
Adam Nemet04563272015-02-01 16:56:15 +0000326 if (hasComputableBounds(SE, StridesMap, Ptr) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000327 // When we run after a failing dependency check we have to make sure
328 // we don't have wrapping pointers.
Adam Nemet04563272015-02-01 16:56:15 +0000329 (!ShouldCheckStride ||
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000330 isStridedPtr(SE, Ptr, TheLoop, StridesMap) == 1)) {
Adam Nemet04563272015-02-01 16:56:15 +0000331 // The id of the dependence set.
332 unsigned DepId;
333
334 if (IsDepCheckNeeded) {
335 Value *Leader = DepCands.getLeaderValue(Access).getPointer();
336 unsigned &LeaderId = DepSetId[Leader];
337 if (!LeaderId)
338 LeaderId = RunningDepId++;
339 DepId = LeaderId;
340 } else
341 // Each access has its own dependence set.
342 DepId = RunningDepId++;
343
344 RtCheck.insert(SE, TheLoop, Ptr, IsWrite, DepId, ASId, StridesMap);
345
Adam Nemet339f42b2015-02-19 19:15:07 +0000346 DEBUG(dbgs() << "LAA: Found a runtime check ptr:" << *Ptr << '\n');
Adam Nemet04563272015-02-01 16:56:15 +0000347 } else {
Adam Nemetf10ca272015-05-18 15:36:52 +0000348 DEBUG(dbgs() << "LAA: Can't find bounds for ptr:" << *Ptr << '\n');
Adam Nemet04563272015-02-01 16:56:15 +0000349 CanDoRT = false;
350 }
351 }
352
Adam Nemet04563272015-02-01 16:56:15 +0000353 ++ASId;
354 }
355
Silviu Baranga98a13712015-06-08 10:27:06 +0000356 // We need a runtime check if there are any accesses that need checking.
357 // However, some accesses cannot be checked (for example because we
358 // can't determine their bounds). In these cases we would need a check
359 // but wouldn't be able to add it.
360 NeedRTCheck = !CanDoRT || RtCheck.needsAnyChecking(nullptr);
361
Adam Nemet04563272015-02-01 16:56:15 +0000362 // If the pointers that we would use for the bounds comparison have different
363 // address spaces, assume the values aren't directly comparable, so we can't
364 // use them for the runtime check. We also have to assume they could
365 // overlap. In the future there should be metadata for whether address spaces
366 // are disjoint.
367 unsigned NumPointers = RtCheck.Pointers.size();
368 for (unsigned i = 0; i < NumPointers; ++i) {
369 for (unsigned j = i + 1; j < NumPointers; ++j) {
370 // Only need to check pointers between two different dependency sets.
371 if (RtCheck.DependencySetId[i] == RtCheck.DependencySetId[j])
372 continue;
373 // Only need to check pointers in the same alias set.
374 if (RtCheck.AliasSetId[i] != RtCheck.AliasSetId[j])
375 continue;
376
377 Value *PtrI = RtCheck.Pointers[i];
378 Value *PtrJ = RtCheck.Pointers[j];
379
380 unsigned ASi = PtrI->getType()->getPointerAddressSpace();
381 unsigned ASj = PtrJ->getType()->getPointerAddressSpace();
382 if (ASi != ASj) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000383 DEBUG(dbgs() << "LAA: Runtime check would require comparison between"
Adam Nemet04d41632015-02-19 19:14:34 +0000384 " different address spaces\n");
Adam Nemet04563272015-02-01 16:56:15 +0000385 return false;
386 }
387 }
388 }
389
390 return CanDoRT;
391}
392
393void AccessAnalysis::processMemAccesses() {
394 // We process the set twice: first we process read-write pointers, last we
395 // process read-only pointers. This allows us to skip dependence tests for
396 // read-only pointers.
397
Adam Nemet339f42b2015-02-19 19:15:07 +0000398 DEBUG(dbgs() << "LAA: Processing memory accesses...\n");
Adam Nemet04563272015-02-01 16:56:15 +0000399 DEBUG(dbgs() << " AST: "; AST.dump());
Adam Nemet9c926572015-03-10 17:40:37 +0000400 DEBUG(dbgs() << "LAA: Accesses(" << Accesses.size() << "):\n");
Adam Nemet04563272015-02-01 16:56:15 +0000401 DEBUG({
402 for (auto A : Accesses)
403 dbgs() << "\t" << *A.getPointer() << " (" <<
404 (A.getInt() ? "write" : (ReadOnlyPtr.count(A.getPointer()) ?
405 "read-only" : "read")) << ")\n";
406 });
407
408 // The AliasSetTracker has nicely partitioned our pointers by metadata
409 // compatibility and potential for underlying-object overlap. As a result, we
410 // only need to check for potential pointer dependencies within each alias
411 // set.
412 for (auto &AS : AST) {
413 // Note that both the alias-set tracker and the alias sets themselves used
414 // linked lists internally and so the iteration order here is deterministic
415 // (matching the original instruction order within each set).
416
417 bool SetHasWrite = false;
418
419 // Map of pointers to last access encountered.
420 typedef DenseMap<Value*, MemAccessInfo> UnderlyingObjToAccessMap;
421 UnderlyingObjToAccessMap ObjToLastAccess;
422
423 // Set of access to check after all writes have been processed.
424 PtrAccessSet DeferredAccesses;
425
426 // Iterate over each alias set twice, once to process read/write pointers,
427 // and then to process read-only pointers.
428 for (int SetIteration = 0; SetIteration < 2; ++SetIteration) {
429 bool UseDeferred = SetIteration > 0;
430 PtrAccessSet &S = UseDeferred ? DeferredAccesses : Accesses;
431
432 for (auto AV : AS) {
433 Value *Ptr = AV.getValue();
434
435 // For a single memory access in AliasSetTracker, Accesses may contain
436 // both read and write, and they both need to be handled for CheckDeps.
437 for (auto AC : S) {
438 if (AC.getPointer() != Ptr)
439 continue;
440
441 bool IsWrite = AC.getInt();
442
443 // If we're using the deferred access set, then it contains only
444 // reads.
445 bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite;
446 if (UseDeferred && !IsReadOnlyPtr)
447 continue;
448 // Otherwise, the pointer must be in the PtrAccessSet, either as a
449 // read or a write.
450 assert(((IsReadOnlyPtr && UseDeferred) || IsWrite ||
451 S.count(MemAccessInfo(Ptr, false))) &&
452 "Alias-set pointer not in the access set?");
453
454 MemAccessInfo Access(Ptr, IsWrite);
455 DepCands.insert(Access);
456
457 // Memorize read-only pointers for later processing and skip them in
458 // the first round (they need to be checked after we have seen all
459 // write pointers). Note: we also mark pointer that are not
460 // consecutive as "read-only" pointers (so that we check
461 // "a[b[i]] +="). Hence, we need the second check for "!IsWrite".
462 if (!UseDeferred && IsReadOnlyPtr) {
463 DeferredAccesses.insert(Access);
464 continue;
465 }
466
467 // If this is a write - check other reads and writes for conflicts. If
468 // this is a read only check other writes for conflicts (but only if
469 // there is no other write to the ptr - this is an optimization to
470 // catch "a[i] = a[i] + " without having to do a dependence check).
471 if ((IsWrite || IsReadOnlyPtr) && SetHasWrite) {
472 CheckDeps.insert(Access);
473 IsRTCheckNeeded = true;
474 }
475
476 if (IsWrite)
477 SetHasWrite = true;
478
479 // Create sets of pointers connected by a shared alias set and
480 // underlying object.
481 typedef SmallVector<Value *, 16> ValueVector;
482 ValueVector TempObjects;
Adam Nemete2b885c2015-04-23 20:09:20 +0000483
484 GetUnderlyingObjects(Ptr, TempObjects, DL, LI);
485 DEBUG(dbgs() << "Underlying objects for pointer " << *Ptr << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000486 for (Value *UnderlyingObj : TempObjects) {
487 UnderlyingObjToAccessMap::iterator Prev =
488 ObjToLastAccess.find(UnderlyingObj);
489 if (Prev != ObjToLastAccess.end())
490 DepCands.unionSets(Access, Prev->second);
491
492 ObjToLastAccess[UnderlyingObj] = Access;
Adam Nemete2b885c2015-04-23 20:09:20 +0000493 DEBUG(dbgs() << " " << *UnderlyingObj << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000494 }
495 }
496 }
497 }
498 }
499}
500
Adam Nemet04563272015-02-01 16:56:15 +0000501static bool isInBoundsGep(Value *Ptr) {
502 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
503 return GEP->isInBounds();
504 return false;
505}
506
Adam Nemetc4866d22015-06-26 17:25:43 +0000507/// \brief Return true if an AddRec pointer \p Ptr is unsigned non-wrapping,
508/// i.e. monotonically increasing/decreasing.
509static bool isNoWrapAddRec(Value *Ptr, const SCEVAddRecExpr *AR,
510 ScalarEvolution *SE, const Loop *L) {
511 // FIXME: This should probably only return true for NUW.
512 if (AR->getNoWrapFlags(SCEV::NoWrapMask))
513 return true;
514
515 // Scalar evolution does not propagate the non-wrapping flags to values that
516 // are derived from a non-wrapping induction variable because non-wrapping
517 // could be flow-sensitive.
518 //
519 // Look through the potentially overflowing instruction to try to prove
520 // non-wrapping for the *specific* value of Ptr.
521
522 // The arithmetic implied by an inbounds GEP can't overflow.
523 auto *GEP = dyn_cast<GetElementPtrInst>(Ptr);
524 if (!GEP || !GEP->isInBounds())
525 return false;
526
527 // Make sure there is only one non-const index and analyze that.
528 Value *NonConstIndex = nullptr;
529 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
530 if (!isa<ConstantInt>(*Index)) {
531 if (NonConstIndex)
532 return false;
533 NonConstIndex = *Index;
534 }
535 if (!NonConstIndex)
536 // The recurrence is on the pointer, ignore for now.
537 return false;
538
539 // The index in GEP is signed. It is non-wrapping if it's derived from a NSW
540 // AddRec using a NSW operation.
541 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(NonConstIndex))
542 if (OBO->hasNoSignedWrap() &&
543 // Assume constant for other the operand so that the AddRec can be
544 // easily found.
545 isa<ConstantInt>(OBO->getOperand(1))) {
546 auto *OpScev = SE->getSCEV(OBO->getOperand(0));
547
548 if (auto *OpAR = dyn_cast<SCEVAddRecExpr>(OpScev))
549 return OpAR->getLoop() == L && OpAR->getNoWrapFlags(SCEV::FlagNSW);
550 }
551
552 return false;
553}
554
Adam Nemet04563272015-02-01 16:56:15 +0000555/// \brief Check whether the access through \p Ptr has a constant stride.
Hao Liu32c05392015-06-08 06:39:56 +0000556int llvm::isStridedPtr(ScalarEvolution *SE, Value *Ptr, const Loop *Lp,
557 const ValueToValueMap &StridesMap) {
Adam Nemet04563272015-02-01 16:56:15 +0000558 const Type *Ty = Ptr->getType();
559 assert(Ty->isPointerTy() && "Unexpected non-ptr");
560
561 // Make sure that the pointer does not point to aggregate types.
562 const PointerType *PtrTy = cast<PointerType>(Ty);
563 if (PtrTy->getElementType()->isAggregateType()) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000564 DEBUG(dbgs() << "LAA: Bad stride - Not a pointer to a scalar type"
565 << *Ptr << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000566 return 0;
567 }
568
569 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, StridesMap, Ptr);
570
571 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
572 if (!AR) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000573 DEBUG(dbgs() << "LAA: Bad stride - Not an AddRecExpr pointer "
Adam Nemet04d41632015-02-19 19:14:34 +0000574 << *Ptr << " SCEV: " << *PtrScev << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000575 return 0;
576 }
577
578 // The accesss function must stride over the innermost loop.
579 if (Lp != AR->getLoop()) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000580 DEBUG(dbgs() << "LAA: Bad stride - Not striding over innermost loop " <<
Adam Nemet04d41632015-02-19 19:14:34 +0000581 *Ptr << " SCEV: " << *PtrScev << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000582 }
583
584 // The address calculation must not wrap. Otherwise, a dependence could be
585 // inverted.
586 // An inbounds getelementptr that is a AddRec with a unit stride
587 // cannot wrap per definition. The unit stride requirement is checked later.
588 // An getelementptr without an inbounds attribute and unit stride would have
589 // to access the pointer value "0" which is undefined behavior in address
590 // space 0, therefore we can also vectorize this case.
591 bool IsInBoundsGEP = isInBoundsGep(Ptr);
Adam Nemetc4866d22015-06-26 17:25:43 +0000592 bool IsNoWrapAddRec = isNoWrapAddRec(Ptr, AR, SE, Lp);
Adam Nemet04563272015-02-01 16:56:15 +0000593 bool IsInAddressSpaceZero = PtrTy->getAddressSpace() == 0;
594 if (!IsNoWrapAddRec && !IsInBoundsGEP && !IsInAddressSpaceZero) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000595 DEBUG(dbgs() << "LAA: Bad stride - Pointer may wrap in the address space "
Adam Nemet04d41632015-02-19 19:14:34 +0000596 << *Ptr << " SCEV: " << *PtrScev << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000597 return 0;
598 }
599
600 // Check the step is constant.
601 const SCEV *Step = AR->getStepRecurrence(*SE);
602
603 // Calculate the pointer stride and check if it is consecutive.
604 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
605 if (!C) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000606 DEBUG(dbgs() << "LAA: Bad stride - Not a constant strided " << *Ptr <<
Adam Nemet04d41632015-02-19 19:14:34 +0000607 " SCEV: " << *PtrScev << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000608 return 0;
609 }
610
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000611 auto &DL = Lp->getHeader()->getModule()->getDataLayout();
612 int64_t Size = DL.getTypeAllocSize(PtrTy->getElementType());
Adam Nemet04563272015-02-01 16:56:15 +0000613 const APInt &APStepVal = C->getValue()->getValue();
614
615 // Huge step value - give up.
616 if (APStepVal.getBitWidth() > 64)
617 return 0;
618
619 int64_t StepVal = APStepVal.getSExtValue();
620
621 // Strided access.
622 int64_t Stride = StepVal / Size;
623 int64_t Rem = StepVal % Size;
624 if (Rem)
625 return 0;
626
627 // If the SCEV could wrap but we have an inbounds gep with a unit stride we
628 // know we can't "wrap around the address space". In case of address space
629 // zero we know that this won't happen without triggering undefined behavior.
630 if (!IsNoWrapAddRec && (IsInBoundsGEP || IsInAddressSpaceZero) &&
631 Stride != 1 && Stride != -1)
632 return 0;
633
634 return Stride;
635}
636
Adam Nemet9c926572015-03-10 17:40:37 +0000637bool MemoryDepChecker::Dependence::isSafeForVectorization(DepType Type) {
638 switch (Type) {
639 case NoDep:
640 case Forward:
641 case BackwardVectorizable:
642 return true;
643
644 case Unknown:
645 case ForwardButPreventsForwarding:
646 case Backward:
647 case BackwardVectorizableButPreventsForwarding:
648 return false;
649 }
David Majnemerd388e932015-03-10 20:23:29 +0000650 llvm_unreachable("unexpected DepType!");
Adam Nemet9c926572015-03-10 17:40:37 +0000651}
652
653bool MemoryDepChecker::Dependence::isInterestingDependence(DepType Type) {
654 switch (Type) {
655 case NoDep:
656 case Forward:
657 return false;
658
659 case BackwardVectorizable:
660 case Unknown:
661 case ForwardButPreventsForwarding:
662 case Backward:
663 case BackwardVectorizableButPreventsForwarding:
664 return true;
665 }
David Majnemerd388e932015-03-10 20:23:29 +0000666 llvm_unreachable("unexpected DepType!");
Adam Nemet9c926572015-03-10 17:40:37 +0000667}
668
669bool MemoryDepChecker::Dependence::isPossiblyBackward() const {
670 switch (Type) {
671 case NoDep:
672 case Forward:
673 case ForwardButPreventsForwarding:
674 return false;
675
676 case Unknown:
677 case BackwardVectorizable:
678 case Backward:
679 case BackwardVectorizableButPreventsForwarding:
680 return true;
681 }
David Majnemerd388e932015-03-10 20:23:29 +0000682 llvm_unreachable("unexpected DepType!");
Adam Nemet9c926572015-03-10 17:40:37 +0000683}
684
Adam Nemet04563272015-02-01 16:56:15 +0000685bool MemoryDepChecker::couldPreventStoreLoadForward(unsigned Distance,
686 unsigned TypeByteSize) {
687 // If loads occur at a distance that is not a multiple of a feasible vector
688 // factor store-load forwarding does not take place.
689 // Positive dependences might cause troubles because vectorizing them might
690 // prevent store-load forwarding making vectorized code run a lot slower.
691 // a[i] = a[i-3] ^ a[i-8];
692 // The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
693 // hence on your typical architecture store-load forwarding does not take
694 // place. Vectorizing in such cases does not make sense.
695 // Store-load forwarding distance.
696 const unsigned NumCyclesForStoreLoadThroughMemory = 8*TypeByteSize;
697 // Maximum vector factor.
Adam Nemetf219c642015-02-19 19:14:52 +0000698 unsigned MaxVFWithoutSLForwardIssues =
699 VectorizerParams::MaxVectorWidth * TypeByteSize;
Adam Nemet04d41632015-02-19 19:14:34 +0000700 if(MaxSafeDepDistBytes < MaxVFWithoutSLForwardIssues)
Adam Nemet04563272015-02-01 16:56:15 +0000701 MaxVFWithoutSLForwardIssues = MaxSafeDepDistBytes;
702
703 for (unsigned vf = 2*TypeByteSize; vf <= MaxVFWithoutSLForwardIssues;
704 vf *= 2) {
705 if (Distance % vf && Distance / vf < NumCyclesForStoreLoadThroughMemory) {
706 MaxVFWithoutSLForwardIssues = (vf >>=1);
707 break;
708 }
709 }
710
Adam Nemet04d41632015-02-19 19:14:34 +0000711 if (MaxVFWithoutSLForwardIssues< 2*TypeByteSize) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000712 DEBUG(dbgs() << "LAA: Distance " << Distance <<
Adam Nemet04d41632015-02-19 19:14:34 +0000713 " that could cause a store-load forwarding conflict\n");
Adam Nemet04563272015-02-01 16:56:15 +0000714 return true;
715 }
716
717 if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes &&
Adam Nemetf219c642015-02-19 19:14:52 +0000718 MaxVFWithoutSLForwardIssues !=
719 VectorizerParams::MaxVectorWidth * TypeByteSize)
Adam Nemet04563272015-02-01 16:56:15 +0000720 MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues;
721 return false;
722}
723
Hao Liu751004a2015-06-08 04:48:37 +0000724/// \brief Check the dependence for two accesses with the same stride \p Stride.
725/// \p Distance is the positive distance and \p TypeByteSize is type size in
726/// bytes.
727///
728/// \returns true if they are independent.
729static bool areStridedAccessesIndependent(unsigned Distance, unsigned Stride,
730 unsigned TypeByteSize) {
731 assert(Stride > 1 && "The stride must be greater than 1");
732 assert(TypeByteSize > 0 && "The type size in byte must be non-zero");
733 assert(Distance > 0 && "The distance must be non-zero");
734
735 // Skip if the distance is not multiple of type byte size.
736 if (Distance % TypeByteSize)
737 return false;
738
739 unsigned ScaledDist = Distance / TypeByteSize;
740
741 // No dependence if the scaled distance is not multiple of the stride.
742 // E.g.
743 // for (i = 0; i < 1024 ; i += 4)
744 // A[i+2] = A[i] + 1;
745 //
746 // Two accesses in memory (scaled distance is 2, stride is 4):
747 // | A[0] | | | | A[4] | | | |
748 // | | | A[2] | | | | A[6] | |
749 //
750 // E.g.
751 // for (i = 0; i < 1024 ; i += 3)
752 // A[i+4] = A[i] + 1;
753 //
754 // Two accesses in memory (scaled distance is 4, stride is 3):
755 // | A[0] | | | A[3] | | | A[6] | | |
756 // | | | | | A[4] | | | A[7] | |
757 return ScaledDist % Stride;
758}
759
Adam Nemet9c926572015-03-10 17:40:37 +0000760MemoryDepChecker::Dependence::DepType
761MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
762 const MemAccessInfo &B, unsigned BIdx,
763 const ValueToValueMap &Strides) {
Adam Nemet04563272015-02-01 16:56:15 +0000764 assert (AIdx < BIdx && "Must pass arguments in program order");
765
766 Value *APtr = A.getPointer();
767 Value *BPtr = B.getPointer();
768 bool AIsWrite = A.getInt();
769 bool BIsWrite = B.getInt();
770
771 // Two reads are independent.
772 if (!AIsWrite && !BIsWrite)
Adam Nemet9c926572015-03-10 17:40:37 +0000773 return Dependence::NoDep;
Adam Nemet04563272015-02-01 16:56:15 +0000774
775 // We cannot check pointers in different address spaces.
776 if (APtr->getType()->getPointerAddressSpace() !=
777 BPtr->getType()->getPointerAddressSpace())
Adam Nemet9c926572015-03-10 17:40:37 +0000778 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +0000779
780 const SCEV *AScev = replaceSymbolicStrideSCEV(SE, Strides, APtr);
781 const SCEV *BScev = replaceSymbolicStrideSCEV(SE, Strides, BPtr);
782
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000783 int StrideAPtr = isStridedPtr(SE, APtr, InnermostLoop, Strides);
784 int StrideBPtr = isStridedPtr(SE, BPtr, InnermostLoop, Strides);
Adam Nemet04563272015-02-01 16:56:15 +0000785
786 const SCEV *Src = AScev;
787 const SCEV *Sink = BScev;
788
789 // If the induction step is negative we have to invert source and sink of the
790 // dependence.
791 if (StrideAPtr < 0) {
792 //Src = BScev;
793 //Sink = AScev;
794 std::swap(APtr, BPtr);
795 std::swap(Src, Sink);
796 std::swap(AIsWrite, BIsWrite);
797 std::swap(AIdx, BIdx);
798 std::swap(StrideAPtr, StrideBPtr);
799 }
800
801 const SCEV *Dist = SE->getMinusSCEV(Sink, Src);
802
Adam Nemet339f42b2015-02-19 19:15:07 +0000803 DEBUG(dbgs() << "LAA: Src Scev: " << *Src << "Sink Scev: " << *Sink
Adam Nemet04d41632015-02-19 19:14:34 +0000804 << "(Induction step: " << StrideAPtr << ")\n");
Adam Nemet339f42b2015-02-19 19:15:07 +0000805 DEBUG(dbgs() << "LAA: Distance for " << *InstMap[AIdx] << " to "
Adam Nemet04d41632015-02-19 19:14:34 +0000806 << *InstMap[BIdx] << ": " << *Dist << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000807
808 // Need consecutive accesses. We don't want to vectorize
809 // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in
810 // the address space.
811 if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){
812 DEBUG(dbgs() << "Non-consecutive pointer access\n");
Adam Nemet9c926572015-03-10 17:40:37 +0000813 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +0000814 }
815
816 const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist);
817 if (!C) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000818 DEBUG(dbgs() << "LAA: Dependence because of non-constant distance\n");
Adam Nemet04563272015-02-01 16:56:15 +0000819 ShouldRetryWithRuntimeCheck = true;
Adam Nemet9c926572015-03-10 17:40:37 +0000820 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +0000821 }
822
823 Type *ATy = APtr->getType()->getPointerElementType();
824 Type *BTy = BPtr->getType()->getPointerElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000825 auto &DL = InnermostLoop->getHeader()->getModule()->getDataLayout();
826 unsigned TypeByteSize = DL.getTypeAllocSize(ATy);
Adam Nemet04563272015-02-01 16:56:15 +0000827
828 // Negative distances are not plausible dependencies.
829 const APInt &Val = C->getValue()->getValue();
830 if (Val.isNegative()) {
831 bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
832 if (IsTrueDataDependence &&
833 (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) ||
834 ATy != BTy))
Adam Nemet9c926572015-03-10 17:40:37 +0000835 return Dependence::ForwardButPreventsForwarding;
Adam Nemet04563272015-02-01 16:56:15 +0000836
Adam Nemet339f42b2015-02-19 19:15:07 +0000837 DEBUG(dbgs() << "LAA: Dependence is negative: NoDep\n");
Adam Nemet9c926572015-03-10 17:40:37 +0000838 return Dependence::Forward;
Adam Nemet04563272015-02-01 16:56:15 +0000839 }
840
841 // Write to the same location with the same size.
842 // Could be improved to assert type sizes are the same (i32 == float, etc).
843 if (Val == 0) {
844 if (ATy == BTy)
Adam Nemet9c926572015-03-10 17:40:37 +0000845 return Dependence::NoDep;
Adam Nemet339f42b2015-02-19 19:15:07 +0000846 DEBUG(dbgs() << "LAA: Zero dependence difference but different types\n");
Adam Nemet9c926572015-03-10 17:40:37 +0000847 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +0000848 }
849
850 assert(Val.isStrictlyPositive() && "Expect a positive value");
851
Adam Nemet04563272015-02-01 16:56:15 +0000852 if (ATy != BTy) {
Adam Nemet04d41632015-02-19 19:14:34 +0000853 DEBUG(dbgs() <<
Adam Nemet339f42b2015-02-19 19:15:07 +0000854 "LAA: ReadWrite-Write positive dependency with different types\n");
Adam Nemet9c926572015-03-10 17:40:37 +0000855 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +0000856 }
857
858 unsigned Distance = (unsigned) Val.getZExtValue();
859
Hao Liu751004a2015-06-08 04:48:37 +0000860 unsigned Stride = std::abs(StrideAPtr);
861 if (Stride > 1 &&
862 areStridedAccessesIndependent(Distance, Stride, TypeByteSize))
863 return Dependence::NoDep;
864
Adam Nemet04563272015-02-01 16:56:15 +0000865 // Bail out early if passed-in parameters make vectorization not feasible.
Adam Nemetf219c642015-02-19 19:14:52 +0000866 unsigned ForcedFactor = (VectorizerParams::VectorizationFactor ?
867 VectorizerParams::VectorizationFactor : 1);
868 unsigned ForcedUnroll = (VectorizerParams::VectorizationInterleave ?
869 VectorizerParams::VectorizationInterleave : 1);
Hao Liu751004a2015-06-08 04:48:37 +0000870 // The minimum number of iterations for a vectorized/unrolled version.
871 unsigned MinNumIter = std::max(ForcedFactor * ForcedUnroll, 2U);
Adam Nemet04563272015-02-01 16:56:15 +0000872
Hao Liu751004a2015-06-08 04:48:37 +0000873 // It's not vectorizable if the distance is smaller than the minimum distance
874 // needed for a vectroized/unrolled version. Vectorizing one iteration in
875 // front needs TypeByteSize * Stride. Vectorizing the last iteration needs
876 // TypeByteSize (No need to plus the last gap distance).
877 //
878 // E.g. Assume one char is 1 byte in memory and one int is 4 bytes.
879 // foo(int *A) {
880 // int *B = (int *)((char *)A + 14);
881 // for (i = 0 ; i < 1024 ; i += 2)
882 // B[i] = A[i] + 1;
883 // }
884 //
885 // Two accesses in memory (stride is 2):
886 // | A[0] | | A[2] | | A[4] | | A[6] | |
887 // | B[0] | | B[2] | | B[4] |
888 //
889 // Distance needs for vectorizing iterations except the last iteration:
890 // 4 * 2 * (MinNumIter - 1). Distance needs for the last iteration: 4.
891 // So the minimum distance needed is: 4 * 2 * (MinNumIter - 1) + 4.
892 //
893 // If MinNumIter is 2, it is vectorizable as the minimum distance needed is
894 // 12, which is less than distance.
895 //
896 // If MinNumIter is 4 (Say if a user forces the vectorization factor to be 4),
897 // the minimum distance needed is 28, which is greater than distance. It is
898 // not safe to do vectorization.
899 unsigned MinDistanceNeeded =
900 TypeByteSize * Stride * (MinNumIter - 1) + TypeByteSize;
901 if (MinDistanceNeeded > Distance) {
902 DEBUG(dbgs() << "LAA: Failure because of positive distance " << Distance
903 << '\n');
904 return Dependence::Backward;
905 }
906
907 // Unsafe if the minimum distance needed is greater than max safe distance.
908 if (MinDistanceNeeded > MaxSafeDepDistBytes) {
909 DEBUG(dbgs() << "LAA: Failure because it needs at least "
910 << MinDistanceNeeded << " size in bytes");
Adam Nemet9c926572015-03-10 17:40:37 +0000911 return Dependence::Backward;
Adam Nemet04563272015-02-01 16:56:15 +0000912 }
913
Adam Nemet9cc0c392015-02-26 17:58:48 +0000914 // Positive distance bigger than max vectorization factor.
Hao Liu751004a2015-06-08 04:48:37 +0000915 // FIXME: Should use max factor instead of max distance in bytes, which could
916 // not handle different types.
917 // E.g. Assume one char is 1 byte in memory and one int is 4 bytes.
918 // void foo (int *A, char *B) {
919 // for (unsigned i = 0; i < 1024; i++) {
920 // A[i+2] = A[i] + 1;
921 // B[i+2] = B[i] + 1;
922 // }
923 // }
924 //
925 // This case is currently unsafe according to the max safe distance. If we
926 // analyze the two accesses on array B, the max safe dependence distance
927 // is 2. Then we analyze the accesses on array A, the minimum distance needed
928 // is 8, which is less than 2 and forbidden vectorization, But actually
929 // both A and B could be vectorized by 2 iterations.
930 MaxSafeDepDistBytes =
931 Distance < MaxSafeDepDistBytes ? Distance : MaxSafeDepDistBytes;
Adam Nemet04563272015-02-01 16:56:15 +0000932
933 bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
934 if (IsTrueDataDependence &&
935 couldPreventStoreLoadForward(Distance, TypeByteSize))
Adam Nemet9c926572015-03-10 17:40:37 +0000936 return Dependence::BackwardVectorizableButPreventsForwarding;
Adam Nemet04563272015-02-01 16:56:15 +0000937
Hao Liu751004a2015-06-08 04:48:37 +0000938 DEBUG(dbgs() << "LAA: Positive distance " << Val.getSExtValue()
939 << " with max VF = "
940 << MaxSafeDepDistBytes / (TypeByteSize * Stride) << '\n');
Adam Nemet04563272015-02-01 16:56:15 +0000941
Adam Nemet9c926572015-03-10 17:40:37 +0000942 return Dependence::BackwardVectorizable;
Adam Nemet04563272015-02-01 16:56:15 +0000943}
944
Adam Nemetdee666b2015-03-10 17:40:34 +0000945bool MemoryDepChecker::areDepsSafe(DepCandidates &AccessSets,
Adam Nemet04563272015-02-01 16:56:15 +0000946 MemAccessInfoSet &CheckDeps,
Adam Nemet8bc61df2015-02-24 00:41:59 +0000947 const ValueToValueMap &Strides) {
Adam Nemet04563272015-02-01 16:56:15 +0000948
949 MaxSafeDepDistBytes = -1U;
950 while (!CheckDeps.empty()) {
951 MemAccessInfo CurAccess = *CheckDeps.begin();
952
953 // Get the relevant memory access set.
954 EquivalenceClasses<MemAccessInfo>::iterator I =
955 AccessSets.findValue(AccessSets.getLeaderValue(CurAccess));
956
957 // Check accesses within this set.
958 EquivalenceClasses<MemAccessInfo>::member_iterator AI, AE;
959 AI = AccessSets.member_begin(I), AE = AccessSets.member_end();
960
961 // Check every access pair.
962 while (AI != AE) {
963 CheckDeps.erase(*AI);
964 EquivalenceClasses<MemAccessInfo>::member_iterator OI = std::next(AI);
965 while (OI != AE) {
966 // Check every accessing instruction pair in program order.
967 for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(),
968 I1E = Accesses[*AI].end(); I1 != I1E; ++I1)
969 for (std::vector<unsigned>::iterator I2 = Accesses[*OI].begin(),
970 I2E = Accesses[*OI].end(); I2 != I2E; ++I2) {
Adam Nemet9c926572015-03-10 17:40:37 +0000971 auto A = std::make_pair(&*AI, *I1);
972 auto B = std::make_pair(&*OI, *I2);
973
974 assert(*I1 != *I2);
975 if (*I1 > *I2)
976 std::swap(A, B);
977
978 Dependence::DepType Type =
979 isDependent(*A.first, A.second, *B.first, B.second, Strides);
980 SafeForVectorization &= Dependence::isSafeForVectorization(Type);
981
982 // Gather dependences unless we accumulated MaxInterestingDependence
983 // dependences. In that case return as soon as we find the first
984 // unsafe dependence. This puts a limit on this quadratic
985 // algorithm.
986 if (RecordInterestingDependences) {
987 if (Dependence::isInterestingDependence(Type))
988 InterestingDependences.push_back(
989 Dependence(A.second, B.second, Type));
990
991 if (InterestingDependences.size() >= MaxInterestingDependence) {
992 RecordInterestingDependences = false;
993 InterestingDependences.clear();
994 DEBUG(dbgs() << "Too many dependences, stopped recording\n");
995 }
996 }
997 if (!RecordInterestingDependences && !SafeForVectorization)
Adam Nemet04563272015-02-01 16:56:15 +0000998 return false;
999 }
1000 ++OI;
1001 }
1002 AI++;
1003 }
1004 }
Adam Nemet9c926572015-03-10 17:40:37 +00001005
1006 DEBUG(dbgs() << "Total Interesting Dependences: "
1007 << InterestingDependences.size() << "\n");
1008 return SafeForVectorization;
Adam Nemet04563272015-02-01 16:56:15 +00001009}
1010
Adam Nemetec1e2bb2015-03-10 18:54:26 +00001011SmallVector<Instruction *, 4>
1012MemoryDepChecker::getInstructionsForAccess(Value *Ptr, bool isWrite) const {
1013 MemAccessInfo Access(Ptr, isWrite);
1014 auto &IndexVector = Accesses.find(Access)->second;
1015
1016 SmallVector<Instruction *, 4> Insts;
1017 std::transform(IndexVector.begin(), IndexVector.end(),
1018 std::back_inserter(Insts),
1019 [&](unsigned Idx) { return this->InstMap[Idx]; });
1020 return Insts;
1021}
1022
Adam Nemet58913d62015-03-10 17:40:43 +00001023const char *MemoryDepChecker::Dependence::DepName[] = {
1024 "NoDep", "Unknown", "Forward", "ForwardButPreventsForwarding", "Backward",
1025 "BackwardVectorizable", "BackwardVectorizableButPreventsForwarding"};
1026
1027void MemoryDepChecker::Dependence::print(
1028 raw_ostream &OS, unsigned Depth,
1029 const SmallVectorImpl<Instruction *> &Instrs) const {
1030 OS.indent(Depth) << DepName[Type] << ":\n";
1031 OS.indent(Depth + 2) << *Instrs[Source] << " -> \n";
1032 OS.indent(Depth + 2) << *Instrs[Destination] << "\n";
1033}
1034
Adam Nemet929c38e2015-02-19 19:15:10 +00001035bool LoopAccessInfo::canAnalyzeLoop() {
Adam Nemet8dcb3b62015-04-17 22:43:10 +00001036 // We need to have a loop header.
1037 DEBUG(dbgs() << "LAA: Found a loop: " <<
1038 TheLoop->getHeader()->getName() << '\n');
1039
Adam Nemet929c38e2015-02-19 19:15:10 +00001040 // We can only analyze innermost loops.
1041 if (!TheLoop->empty()) {
Adam Nemet8dcb3b62015-04-17 22:43:10 +00001042 DEBUG(dbgs() << "LAA: loop is not the innermost loop\n");
Adam Nemet2bd6e982015-02-19 19:15:15 +00001043 emitAnalysis(LoopAccessReport() << "loop is not the innermost loop");
Adam Nemet929c38e2015-02-19 19:15:10 +00001044 return false;
1045 }
1046
1047 // We must have a single backedge.
1048 if (TheLoop->getNumBackEdges() != 1) {
Adam Nemet8dcb3b62015-04-17 22:43:10 +00001049 DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n");
Adam Nemet929c38e2015-02-19 19:15:10 +00001050 emitAnalysis(
Adam Nemet2bd6e982015-02-19 19:15:15 +00001051 LoopAccessReport() <<
Adam Nemet929c38e2015-02-19 19:15:10 +00001052 "loop control flow is not understood by analyzer");
1053 return false;
1054 }
1055
1056 // We must have a single exiting block.
1057 if (!TheLoop->getExitingBlock()) {
Adam Nemet8dcb3b62015-04-17 22:43:10 +00001058 DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n");
Adam Nemet929c38e2015-02-19 19:15:10 +00001059 emitAnalysis(
Adam Nemet2bd6e982015-02-19 19:15:15 +00001060 LoopAccessReport() <<
Adam Nemet929c38e2015-02-19 19:15:10 +00001061 "loop control flow is not understood by analyzer");
1062 return false;
1063 }
1064
1065 // We only handle bottom-tested loops, i.e. loop in which the condition is
1066 // checked at the end of each iteration. With that we can assume that all
1067 // instructions in the loop are executed the same number of times.
1068 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
Adam Nemet8dcb3b62015-04-17 22:43:10 +00001069 DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n");
Adam Nemet929c38e2015-02-19 19:15:10 +00001070 emitAnalysis(
Adam Nemet2bd6e982015-02-19 19:15:15 +00001071 LoopAccessReport() <<
Adam Nemet929c38e2015-02-19 19:15:10 +00001072 "loop control flow is not understood by analyzer");
1073 return false;
1074 }
1075
Adam Nemet929c38e2015-02-19 19:15:10 +00001076 // ScalarEvolution needs to be able to find the exit count.
1077 const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop);
1078 if (ExitCount == SE->getCouldNotCompute()) {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001079 emitAnalysis(LoopAccessReport() <<
Adam Nemet929c38e2015-02-19 19:15:10 +00001080 "could not determine number of loop iterations");
1081 DEBUG(dbgs() << "LAA: SCEV could not compute the loop exit count.\n");
1082 return false;
1083 }
1084
1085 return true;
1086}
1087
Adam Nemet8bc61df2015-02-24 00:41:59 +00001088void LoopAccessInfo::analyzeLoop(const ValueToValueMap &Strides) {
Adam Nemet04563272015-02-01 16:56:15 +00001089
1090 typedef SmallVector<Value*, 16> ValueVector;
1091 typedef SmallPtrSet<Value*, 16> ValueSet;
1092
1093 // Holds the Load and Store *instructions*.
1094 ValueVector Loads;
1095 ValueVector Stores;
1096
1097 // Holds all the different accesses in the loop.
1098 unsigned NumReads = 0;
1099 unsigned NumReadWrites = 0;
1100
1101 PtrRtCheck.Pointers.clear();
1102 PtrRtCheck.Need = false;
1103
1104 const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
Adam Nemet04563272015-02-01 16:56:15 +00001105
1106 // For each block.
1107 for (Loop::block_iterator bb = TheLoop->block_begin(),
1108 be = TheLoop->block_end(); bb != be; ++bb) {
1109
1110 // Scan the BB and collect legal loads and stores.
1111 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
1112 ++it) {
1113
1114 // If this is a load, save it. If this instruction can read from memory
1115 // but is not a load, then we quit. Notice that we don't handle function
1116 // calls that read or write.
1117 if (it->mayReadFromMemory()) {
1118 // Many math library functions read the rounding mode. We will only
1119 // vectorize a loop if it contains known function calls that don't set
1120 // the flag. Therefore, it is safe to ignore this read from memory.
1121 CallInst *Call = dyn_cast<CallInst>(it);
1122 if (Call && getIntrinsicIDForCall(Call, TLI))
1123 continue;
1124
Michael Zolotukhin9b3cf602015-03-17 19:46:50 +00001125 // If the function has an explicit vectorized counterpart, we can safely
1126 // assume that it can be vectorized.
1127 if (Call && !Call->isNoBuiltin() && Call->getCalledFunction() &&
1128 TLI->isFunctionVectorizable(Call->getCalledFunction()->getName()))
1129 continue;
1130
Adam Nemet04563272015-02-01 16:56:15 +00001131 LoadInst *Ld = dyn_cast<LoadInst>(it);
1132 if (!Ld || (!Ld->isSimple() && !IsAnnotatedParallel)) {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001133 emitAnalysis(LoopAccessReport(Ld)
Adam Nemet04563272015-02-01 16:56:15 +00001134 << "read with atomic ordering or volatile read");
Adam Nemet339f42b2015-02-19 19:15:07 +00001135 DEBUG(dbgs() << "LAA: Found a non-simple load.\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001136 CanVecMem = false;
1137 return;
Adam Nemet04563272015-02-01 16:56:15 +00001138 }
1139 NumLoads++;
1140 Loads.push_back(Ld);
1141 DepChecker.addAccess(Ld);
1142 continue;
1143 }
1144
1145 // Save 'store' instructions. Abort if other instructions write to memory.
1146 if (it->mayWriteToMemory()) {
1147 StoreInst *St = dyn_cast<StoreInst>(it);
1148 if (!St) {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001149 emitAnalysis(LoopAccessReport(it) <<
Adam Nemet04d41632015-02-19 19:14:34 +00001150 "instruction cannot be vectorized");
Adam Nemet436018c2015-02-19 19:15:00 +00001151 CanVecMem = false;
1152 return;
Adam Nemet04563272015-02-01 16:56:15 +00001153 }
1154 if (!St->isSimple() && !IsAnnotatedParallel) {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001155 emitAnalysis(LoopAccessReport(St)
Adam Nemet04563272015-02-01 16:56:15 +00001156 << "write with atomic ordering or volatile write");
Adam Nemet339f42b2015-02-19 19:15:07 +00001157 DEBUG(dbgs() << "LAA: Found a non-simple store.\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001158 CanVecMem = false;
1159 return;
Adam Nemet04563272015-02-01 16:56:15 +00001160 }
1161 NumStores++;
1162 Stores.push_back(St);
1163 DepChecker.addAccess(St);
1164 }
1165 } // Next instr.
1166 } // Next block.
1167
1168 // Now we have two lists that hold the loads and the stores.
1169 // Next, we find the pointers that they use.
1170
1171 // Check if we see any stores. If there are no stores, then we don't
1172 // care if the pointers are *restrict*.
1173 if (!Stores.size()) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001174 DEBUG(dbgs() << "LAA: Found a read-only loop!\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001175 CanVecMem = true;
1176 return;
Adam Nemet04563272015-02-01 16:56:15 +00001177 }
1178
Adam Nemetdee666b2015-03-10 17:40:34 +00001179 MemoryDepChecker::DepCandidates DependentAccesses;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001180 AccessAnalysis Accesses(TheLoop->getHeader()->getModule()->getDataLayout(),
Adam Nemete2b885c2015-04-23 20:09:20 +00001181 AA, LI, DependentAccesses);
Adam Nemet04563272015-02-01 16:56:15 +00001182
1183 // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
1184 // multiple times on the same object. If the ptr is accessed twice, once
1185 // for read and once for write, it will only appear once (on the write
1186 // list). This is okay, since we are going to check for conflicts between
1187 // writes and between reads and writes, but not between reads and reads.
1188 ValueSet Seen;
1189
1190 ValueVector::iterator I, IE;
1191 for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
1192 StoreInst *ST = cast<StoreInst>(*I);
1193 Value* Ptr = ST->getPointerOperand();
Adam Nemetce482502015-04-08 17:48:40 +00001194 // Check for store to loop invariant address.
1195 StoreToLoopInvariantAddress |= isUniform(Ptr);
Adam Nemet04563272015-02-01 16:56:15 +00001196 // If we did *not* see this pointer before, insert it to the read-write
1197 // list. At this phase it is only a 'write' list.
1198 if (Seen.insert(Ptr).second) {
1199 ++NumReadWrites;
1200
Chandler Carruthac80dc72015-06-17 07:18:54 +00001201 MemoryLocation Loc = MemoryLocation::get(ST);
Adam Nemet04563272015-02-01 16:56:15 +00001202 // The TBAA metadata could have a control dependency on the predication
1203 // condition, so we cannot rely on it when determining whether or not we
1204 // need runtime pointer checks.
Adam Nemet01abb2c2015-02-18 03:43:19 +00001205 if (blockNeedsPredication(ST->getParent(), TheLoop, DT))
Adam Nemet04563272015-02-01 16:56:15 +00001206 Loc.AATags.TBAA = nullptr;
1207
1208 Accesses.addStore(Loc);
1209 }
1210 }
1211
1212 if (IsAnnotatedParallel) {
Adam Nemet04d41632015-02-19 19:14:34 +00001213 DEBUG(dbgs()
Adam Nemet339f42b2015-02-19 19:15:07 +00001214 << "LAA: A loop annotated parallel, ignore memory dependency "
Adam Nemet04d41632015-02-19 19:14:34 +00001215 << "checks.\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001216 CanVecMem = true;
1217 return;
Adam Nemet04563272015-02-01 16:56:15 +00001218 }
1219
1220 for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
1221 LoadInst *LD = cast<LoadInst>(*I);
1222 Value* Ptr = LD->getPointerOperand();
1223 // If we did *not* see this pointer before, insert it to the
1224 // read list. If we *did* see it before, then it is already in
1225 // the read-write list. This allows us to vectorize expressions
1226 // such as A[i] += x; Because the address of A[i] is a read-write
1227 // pointer. This only works if the index of A[i] is consecutive.
1228 // If the address of i is unknown (for example A[B[i]]) then we may
1229 // read a few words, modify, and write a few words, and some of the
1230 // words may be written to the same address.
1231 bool IsReadOnlyPtr = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001232 if (Seen.insert(Ptr).second || !isStridedPtr(SE, Ptr, TheLoop, Strides)) {
Adam Nemet04563272015-02-01 16:56:15 +00001233 ++NumReads;
1234 IsReadOnlyPtr = true;
1235 }
1236
Chandler Carruthac80dc72015-06-17 07:18:54 +00001237 MemoryLocation Loc = MemoryLocation::get(LD);
Adam Nemet04563272015-02-01 16:56:15 +00001238 // The TBAA metadata could have a control dependency on the predication
1239 // condition, so we cannot rely on it when determining whether or not we
1240 // need runtime pointer checks.
Adam Nemet01abb2c2015-02-18 03:43:19 +00001241 if (blockNeedsPredication(LD->getParent(), TheLoop, DT))
Adam Nemet04563272015-02-01 16:56:15 +00001242 Loc.AATags.TBAA = nullptr;
1243
1244 Accesses.addLoad(Loc, IsReadOnlyPtr);
1245 }
1246
1247 // If we write (or read-write) to a single destination and there are no
1248 // other reads in this loop then is it safe to vectorize.
1249 if (NumReadWrites == 1 && NumReads == 0) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001250 DEBUG(dbgs() << "LAA: Found a write-only loop!\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001251 CanVecMem = true;
1252 return;
Adam Nemet04563272015-02-01 16:56:15 +00001253 }
1254
1255 // Build dependence sets and check whether we need a runtime pointer bounds
1256 // check.
1257 Accesses.buildDependenceSets();
Adam Nemet04563272015-02-01 16:56:15 +00001258
1259 // Find pointers with computable bounds. We are going to use this information
1260 // to place a runtime bound check.
Silviu Baranga98a13712015-06-08 10:27:06 +00001261 bool NeedRTCheck;
1262 bool CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck,
1263 NeedRTCheck, SE,
1264 TheLoop, Strides);
Adam Nemet04563272015-02-01 16:56:15 +00001265
Silviu Baranga98a13712015-06-08 10:27:06 +00001266 DEBUG(dbgs() << "LAA: We need to do "
1267 << PtrRtCheck.getNumberOfChecks(nullptr)
1268 << " pointer comparisons.\n");
Adam Nemet04563272015-02-01 16:56:15 +00001269
Adam Nemet949e91a2015-03-10 19:12:41 +00001270 // Check that we found the bounds for the pointer.
Adam Nemetb6dc76f2015-03-10 18:54:19 +00001271 if (CanDoRT)
Adam Nemet339f42b2015-02-19 19:15:07 +00001272 DEBUG(dbgs() << "LAA: We can perform a memory runtime check if needed.\n");
Adam Nemetb6dc76f2015-03-10 18:54:19 +00001273 else if (NeedRTCheck) {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001274 emitAnalysis(LoopAccessReport() << "cannot identify array bounds");
Adam Nemet339f42b2015-02-19 19:15:07 +00001275 DEBUG(dbgs() << "LAA: We can't vectorize because we can't find " <<
Adam Nemet04d41632015-02-19 19:14:34 +00001276 "the array bounds.\n");
Adam Nemet04563272015-02-01 16:56:15 +00001277 PtrRtCheck.reset();
Adam Nemet436018c2015-02-19 19:15:00 +00001278 CanVecMem = false;
1279 return;
Adam Nemet04563272015-02-01 16:56:15 +00001280 }
1281
1282 PtrRtCheck.Need = NeedRTCheck;
1283
Adam Nemet436018c2015-02-19 19:15:00 +00001284 CanVecMem = true;
Adam Nemet04563272015-02-01 16:56:15 +00001285 if (Accesses.isDependencyCheckNeeded()) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001286 DEBUG(dbgs() << "LAA: Checking memory dependencies\n");
Adam Nemet04563272015-02-01 16:56:15 +00001287 CanVecMem = DepChecker.areDepsSafe(
1288 DependentAccesses, Accesses.getDependenciesToCheck(), Strides);
1289 MaxSafeDepDistBytes = DepChecker.getMaxSafeDepDistBytes();
1290
1291 if (!CanVecMem && DepChecker.shouldRetryWithRuntimeCheck()) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001292 DEBUG(dbgs() << "LAA: Retrying with memory checks\n");
Adam Nemet04563272015-02-01 16:56:15 +00001293 NeedRTCheck = true;
1294
1295 // Clear the dependency checks. We assume they are not needed.
Adam Nemetdf3dc5b2015-05-18 15:37:03 +00001296 Accesses.resetDepChecks(DepChecker);
Adam Nemet04563272015-02-01 16:56:15 +00001297
1298 PtrRtCheck.reset();
1299 PtrRtCheck.Need = true;
1300
Silviu Baranga98a13712015-06-08 10:27:06 +00001301 CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NeedRTCheck, SE,
Adam Nemet04563272015-02-01 16:56:15 +00001302 TheLoop, Strides, true);
Silviu Baranga98a13712015-06-08 10:27:06 +00001303
Adam Nemet949e91a2015-03-10 19:12:41 +00001304 // Check that we found the bounds for the pointer.
Silviu Baranga98a13712015-06-08 10:27:06 +00001305 if (NeedRTCheck && !CanDoRT) {
Adam Nemetb6dc76f2015-03-10 18:54:19 +00001306 emitAnalysis(LoopAccessReport()
1307 << "cannot check memory dependencies at runtime");
1308 DEBUG(dbgs() << "LAA: Can't vectorize with memory checks\n");
1309 PtrRtCheck.reset();
1310 CanVecMem = false;
1311 return;
1312 }
1313
Adam Nemet04563272015-02-01 16:56:15 +00001314 CanVecMem = true;
1315 }
1316 }
1317
Adam Nemet4bb90a72015-03-10 21:47:39 +00001318 if (CanVecMem)
1319 DEBUG(dbgs() << "LAA: No unsafe dependent memory operations in loop. We"
1320 << (NeedRTCheck ? "" : " don't")
1321 << " need a runtime memory check.\n");
1322 else {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001323 emitAnalysis(LoopAccessReport() <<
Adam Nemet04d41632015-02-19 19:14:34 +00001324 "unsafe dependent memory operations in loop");
Adam Nemet4bb90a72015-03-10 21:47:39 +00001325 DEBUG(dbgs() << "LAA: unsafe dependent memory operations in loop\n");
1326 }
Adam Nemet04563272015-02-01 16:56:15 +00001327}
1328
Adam Nemet01abb2c2015-02-18 03:43:19 +00001329bool LoopAccessInfo::blockNeedsPredication(BasicBlock *BB, Loop *TheLoop,
1330 DominatorTree *DT) {
Adam Nemet04563272015-02-01 16:56:15 +00001331 assert(TheLoop->contains(BB) && "Unknown block used");
1332
1333 // Blocks that do not dominate the latch need predication.
1334 BasicBlock* Latch = TheLoop->getLoopLatch();
1335 return !DT->dominates(BB, Latch);
1336}
1337
Adam Nemet2bd6e982015-02-19 19:15:15 +00001338void LoopAccessInfo::emitAnalysis(LoopAccessReport &Message) {
Adam Nemetc9228532015-02-19 19:14:56 +00001339 assert(!Report && "Multiple reports generated");
1340 Report = Message;
Adam Nemet04563272015-02-01 16:56:15 +00001341}
1342
Adam Nemet57ac7662015-02-19 19:15:21 +00001343bool LoopAccessInfo::isUniform(Value *V) const {
Adam Nemet04563272015-02-01 16:56:15 +00001344 return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
1345}
Adam Nemet7206d7a2015-02-06 18:31:04 +00001346
1347// FIXME: this function is currently a duplicate of the one in
1348// LoopVectorize.cpp.
1349static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
1350 Instruction *Loc) {
1351 if (FirstInst)
1352 return FirstInst;
1353 if (Instruction *I = dyn_cast<Instruction>(V))
1354 return I->getParent() == Loc->getParent() ? I : nullptr;
1355 return nullptr;
1356}
1357
Adam Nemetec1e2bb2015-03-10 18:54:26 +00001358std::pair<Instruction *, Instruction *> LoopAccessInfo::addRuntimeCheck(
1359 Instruction *Loc, const SmallVectorImpl<int> *PtrPartition) const {
Adam Nemet7206d7a2015-02-06 18:31:04 +00001360 if (!PtrRtCheck.Need)
Adam Nemet90fec842015-04-02 17:51:57 +00001361 return std::make_pair(nullptr, nullptr);
Adam Nemet7206d7a2015-02-06 18:31:04 +00001362
1363 unsigned NumPointers = PtrRtCheck.Pointers.size();
1364 SmallVector<TrackingVH<Value> , 2> Starts;
1365 SmallVector<TrackingVH<Value> , 2> Ends;
1366
1367 LLVMContext &Ctx = Loc->getContext();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001368 SCEVExpander Exp(*SE, DL, "induction");
Adam Nemet7206d7a2015-02-06 18:31:04 +00001369 Instruction *FirstInst = nullptr;
1370
1371 for (unsigned i = 0; i < NumPointers; ++i) {
1372 Value *Ptr = PtrRtCheck.Pointers[i];
1373 const SCEV *Sc = SE->getSCEV(Ptr);
1374
1375 if (SE->isLoopInvariant(Sc, TheLoop)) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001376 DEBUG(dbgs() << "LAA: Adding RT check for a loop invariant ptr:" <<
Adam Nemet04d41632015-02-19 19:14:34 +00001377 *Ptr <<"\n");
Adam Nemet7206d7a2015-02-06 18:31:04 +00001378 Starts.push_back(Ptr);
1379 Ends.push_back(Ptr);
1380 } else {
Adam Nemet339f42b2015-02-19 19:15:07 +00001381 DEBUG(dbgs() << "LAA: Adding RT check for range:" << *Ptr << '\n');
Adam Nemet7206d7a2015-02-06 18:31:04 +00001382 unsigned AS = Ptr->getType()->getPointerAddressSpace();
1383
1384 // Use this type for pointer arithmetic.
1385 Type *PtrArithTy = Type::getInt8PtrTy(Ctx, AS);
1386
1387 Value *Start = Exp.expandCodeFor(PtrRtCheck.Starts[i], PtrArithTy, Loc);
1388 Value *End = Exp.expandCodeFor(PtrRtCheck.Ends[i], PtrArithTy, Loc);
1389 Starts.push_back(Start);
1390 Ends.push_back(End);
1391 }
1392 }
1393
1394 IRBuilder<> ChkBuilder(Loc);
1395 // Our instructions might fold to a constant.
1396 Value *MemoryRuntimeCheck = nullptr;
1397 for (unsigned i = 0; i < NumPointers; ++i) {
1398 for (unsigned j = i+1; j < NumPointers; ++j) {
Adam Nemetec1e2bb2015-03-10 18:54:26 +00001399 if (!PtrRtCheck.needsChecking(i, j, PtrPartition))
Adam Nemet7206d7a2015-02-06 18:31:04 +00001400 continue;
1401
1402 unsigned AS0 = Starts[i]->getType()->getPointerAddressSpace();
1403 unsigned AS1 = Starts[j]->getType()->getPointerAddressSpace();
1404
1405 assert((AS0 == Ends[j]->getType()->getPointerAddressSpace()) &&
1406 (AS1 == Ends[i]->getType()->getPointerAddressSpace()) &&
1407 "Trying to bounds check pointers with different address spaces");
1408
1409 Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0);
1410 Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1);
1411
1412 Value *Start0 = ChkBuilder.CreateBitCast(Starts[i], PtrArithTy0, "bc");
1413 Value *Start1 = ChkBuilder.CreateBitCast(Starts[j], PtrArithTy1, "bc");
1414 Value *End0 = ChkBuilder.CreateBitCast(Ends[i], PtrArithTy1, "bc");
1415 Value *End1 = ChkBuilder.CreateBitCast(Ends[j], PtrArithTy0, "bc");
1416
1417 Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0");
1418 FirstInst = getFirstInst(FirstInst, Cmp0, Loc);
1419 Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1");
1420 FirstInst = getFirstInst(FirstInst, Cmp1, Loc);
1421 Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
1422 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1423 if (MemoryRuntimeCheck) {
1424 IsConflict = ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict,
1425 "conflict.rdx");
1426 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1427 }
1428 MemoryRuntimeCheck = IsConflict;
1429 }
1430 }
1431
Adam Nemet90fec842015-04-02 17:51:57 +00001432 if (!MemoryRuntimeCheck)
1433 return std::make_pair(nullptr, nullptr);
1434
Adam Nemet7206d7a2015-02-06 18:31:04 +00001435 // We have to do this trickery because the IRBuilder might fold the check to a
1436 // constant expression in which case there is no Instruction anchored in a
1437 // the block.
1438 Instruction *Check = BinaryOperator::CreateAnd(MemoryRuntimeCheck,
1439 ConstantInt::getTrue(Ctx));
1440 ChkBuilder.Insert(Check, "memcheck.conflict");
1441 FirstInst = getFirstInst(FirstInst, Check, Loc);
1442 return std::make_pair(FirstInst, Check);
1443}
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001444
1445LoopAccessInfo::LoopAccessInfo(Loop *L, ScalarEvolution *SE,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001446 const DataLayout &DL,
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001447 const TargetLibraryInfo *TLI, AliasAnalysis *AA,
Adam Nemete2b885c2015-04-23 20:09:20 +00001448 DominatorTree *DT, LoopInfo *LI,
Adam Nemet8bc61df2015-02-24 00:41:59 +00001449 const ValueToValueMap &Strides)
Silviu Baranga98a13712015-06-08 10:27:06 +00001450 : DepChecker(SE, L), TheLoop(L), SE(SE), DL(DL),
Adam Nemete2b885c2015-04-23 20:09:20 +00001451 TLI(TLI), AA(AA), DT(DT), LI(LI), NumLoads(0), NumStores(0),
Adam Nemetce482502015-04-08 17:48:40 +00001452 MaxSafeDepDistBytes(-1U), CanVecMem(false),
1453 StoreToLoopInvariantAddress(false) {
Adam Nemet929c38e2015-02-19 19:15:10 +00001454 if (canAnalyzeLoop())
1455 analyzeLoop(Strides);
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001456}
1457
Adam Nemete91cc6e2015-02-19 19:15:19 +00001458void LoopAccessInfo::print(raw_ostream &OS, unsigned Depth) const {
1459 if (CanVecMem) {
Adam Nemet26da8e92015-04-14 01:12:55 +00001460 if (PtrRtCheck.Need)
Adam Nemete91cc6e2015-02-19 19:15:19 +00001461 OS.indent(Depth) << "Memory dependences are safe with run-time checks\n";
Adam Nemet26da8e92015-04-14 01:12:55 +00001462 else
1463 OS.indent(Depth) << "Memory dependences are safe\n";
Adam Nemete91cc6e2015-02-19 19:15:19 +00001464 }
1465
1466 if (Report)
1467 OS.indent(Depth) << "Report: " << Report->str() << "\n";
1468
Adam Nemet58913d62015-03-10 17:40:43 +00001469 if (auto *InterestingDependences = DepChecker.getInterestingDependences()) {
1470 OS.indent(Depth) << "Interesting Dependences:\n";
1471 for (auto &Dep : *InterestingDependences) {
1472 Dep.print(OS, Depth + 2, DepChecker.getMemoryInstructions());
1473 OS << "\n";
1474 }
1475 } else
1476 OS.indent(Depth) << "Too many interesting dependences, not recorded\n";
Adam Nemete91cc6e2015-02-19 19:15:19 +00001477
1478 // List the pair of accesses need run-time checks to prove independence.
1479 PtrRtCheck.print(OS, Depth);
1480 OS << "\n";
Adam Nemetc3384322015-05-18 15:36:57 +00001481
1482 OS.indent(Depth) << "Store to invariant address was "
1483 << (StoreToLoopInvariantAddress ? "" : "not ")
1484 << "found in loop.\n";
Adam Nemete91cc6e2015-02-19 19:15:19 +00001485}
1486
Adam Nemet8bc61df2015-02-24 00:41:59 +00001487const LoopAccessInfo &
1488LoopAccessAnalysis::getInfo(Loop *L, const ValueToValueMap &Strides) {
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001489 auto &LAI = LoopAccessInfoMap[L];
1490
1491#ifndef NDEBUG
1492 assert((!LAI || LAI->NumSymbolicStrides == Strides.size()) &&
1493 "Symbolic strides changed for loop");
1494#endif
1495
1496 if (!LAI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001497 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
Adam Nemete2b885c2015-04-23 20:09:20 +00001498 LAI = llvm::make_unique<LoopAccessInfo>(L, SE, DL, TLI, AA, DT, LI,
1499 Strides);
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001500#ifndef NDEBUG
1501 LAI->NumSymbolicStrides = Strides.size();
1502#endif
1503 }
1504 return *LAI.get();
1505}
1506
Adam Nemete91cc6e2015-02-19 19:15:19 +00001507void LoopAccessAnalysis::print(raw_ostream &OS, const Module *M) const {
1508 LoopAccessAnalysis &LAA = *const_cast<LoopAccessAnalysis *>(this);
1509
Adam Nemete91cc6e2015-02-19 19:15:19 +00001510 ValueToValueMap NoSymbolicStrides;
1511
1512 for (Loop *TopLevelLoop : *LI)
1513 for (Loop *L : depth_first(TopLevelLoop)) {
1514 OS.indent(2) << L->getHeader()->getName() << ":\n";
1515 auto &LAI = LAA.getInfo(L, NoSymbolicStrides);
1516 LAI.print(OS, 4);
1517 }
1518}
1519
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001520bool LoopAccessAnalysis::runOnFunction(Function &F) {
1521 SE = &getAnalysis<ScalarEvolution>();
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001522 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
1523 TLI = TLIP ? &TLIP->getTLI() : nullptr;
1524 AA = &getAnalysis<AliasAnalysis>();
1525 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Adam Nemete2b885c2015-04-23 20:09:20 +00001526 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001527
1528 return false;
1529}
1530
1531void LoopAccessAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
1532 AU.addRequired<ScalarEvolution>();
1533 AU.addRequired<AliasAnalysis>();
1534 AU.addRequired<DominatorTreeWrapperPass>();
Adam Nemete91cc6e2015-02-19 19:15:19 +00001535 AU.addRequired<LoopInfoWrapperPass>();
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001536
1537 AU.setPreservesAll();
1538}
1539
1540char LoopAccessAnalysis::ID = 0;
1541static const char laa_name[] = "Loop Access Analysis";
1542#define LAA_NAME "loop-accesses"
1543
1544INITIALIZE_PASS_BEGIN(LoopAccessAnalysis, LAA_NAME, laa_name, false, true)
1545INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
1546INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
1547INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Adam Nemete91cc6e2015-02-19 19:15:19 +00001548INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001549INITIALIZE_PASS_END(LoopAccessAnalysis, LAA_NAME, laa_name, false, true)
1550
1551namespace llvm {
1552 Pass *createLAAPass() {
1553 return new LoopAccessAnalysis();
1554 }
1555}