blob: e3d0d25411b583c3a2aaf929eeb1fe62c99aa805 [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"
David Blaikieb447ac62015-06-26 18:02:52 +000025#include "llvm/Analysis/VectorUtils.h"
Adam Nemet04563272015-02-01 16:56:15 +000026using 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
Silviu Baranga1b6b50a2015-07-08 09:16:33 +000051/// \brief The maximum iterations used to merge memory checks
52static cl::opt<unsigned> MemoryCheckMergeThreshold(
53 "memory-check-merge-threshold", cl::Hidden,
54 cl::desc("Maximum number of comparisons done when trying to merge "
55 "runtime memory checks. (default = 100)"),
56 cl::init(100));
57
Adam Nemetf219c642015-02-19 19:14:52 +000058/// Maximum SIMD width.
59const unsigned VectorizerParams::MaxVectorWidth = 64;
60
Adam Nemeta2df7502015-11-03 21:39:52 +000061/// \brief We collect dependences up to this threshold.
62static cl::opt<unsigned>
63 MaxDependences("max-dependences", cl::Hidden,
64 cl::desc("Maximum number of dependences collected by "
65 "loop-access analysis (default = 100)"),
66 cl::init(100));
Adam Nemet9c926572015-03-10 17:40:37 +000067
Adam Nemetf219c642015-02-19 19:14:52 +000068bool VectorizerParams::isInterleaveForced() {
69 return ::VectorizationInterleave.getNumOccurrences() > 0;
70}
71
Adam Nemet2bd6e982015-02-19 19:15:15 +000072void LoopAccessReport::emitAnalysis(const LoopAccessReport &Message,
73 const Function *TheFunction,
74 const Loop *TheLoop,
75 const char *PassName) {
Adam Nemet04563272015-02-01 16:56:15 +000076 DebugLoc DL = TheLoop->getStartLoc();
Adam Nemet3e876342015-02-19 19:15:13 +000077 if (const Instruction *I = Message.getInstr())
Adam Nemet04563272015-02-01 16:56:15 +000078 DL = I->getDebugLoc();
Adam Nemet339f42b2015-02-19 19:15:07 +000079 emitOptimizationRemarkAnalysis(TheFunction->getContext(), PassName,
Adam Nemet04563272015-02-01 16:56:15 +000080 *TheFunction, DL, Message.str());
81}
82
83Value *llvm::stripIntegerCast(Value *V) {
84 if (CastInst *CI = dyn_cast<CastInst>(V))
85 if (CI->getOperand(0)->getType()->isIntegerTy())
86 return CI->getOperand(0);
87 return V;
88}
89
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000090const SCEV *llvm::replaceSymbolicStrideSCEV(PredicatedScalarEvolution &PSE,
Adam Nemet8bc61df2015-02-24 00:41:59 +000091 const ValueToValueMap &PtrToStride,
Adam Nemet04563272015-02-01 16:56:15 +000092 Value *Ptr, Value *OrigPtr) {
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000093 const SCEV *OrigSCEV = PSE.getSCEV(Ptr);
Adam Nemet04563272015-02-01 16:56:15 +000094
95 // If there is an entry in the map return the SCEV of the pointer with the
96 // symbolic stride replaced by one.
Adam Nemet8bc61df2015-02-24 00:41:59 +000097 ValueToValueMap::const_iterator SI =
98 PtrToStride.find(OrigPtr ? OrigPtr : Ptr);
Adam Nemet04563272015-02-01 16:56:15 +000099 if (SI != PtrToStride.end()) {
100 Value *StrideVal = SI->second;
101
102 // Strip casts.
103 StrideVal = stripIntegerCast(StrideVal);
104
105 // Replace symbolic stride by one.
106 Value *One = ConstantInt::get(StrideVal->getType(), 1);
107 ValueToValueMap RewriteMap;
108 RewriteMap[StrideVal] = One;
109
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +0000110 ScalarEvolution *SE = PSE.getSE();
Silviu Barangae3c05342015-11-02 14:41:02 +0000111 const auto *U = cast<SCEVUnknown>(SE->getSCEV(StrideVal));
112 const auto *CT =
113 static_cast<const SCEVConstant *>(SE->getOne(StrideVal->getType()));
114
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +0000115 PSE.addPredicate(*SE->getEqualPredicate(U, CT));
116 auto *Expr = PSE.getSCEV(Ptr);
Silviu Barangae3c05342015-11-02 14:41:02 +0000117
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +0000118 DEBUG(dbgs() << "LAA: Replacing SCEV: " << *OrigSCEV << " by: " << *Expr
Adam Nemet04563272015-02-01 16:56:15 +0000119 << "\n");
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +0000120 return Expr;
Adam Nemet04563272015-02-01 16:56:15 +0000121 }
122
123 // Otherwise, just return the SCEV of the original pointer.
Silviu Barangae3c05342015-11-02 14:41:02 +0000124 return OrigSCEV;
Adam Nemet04563272015-02-01 16:56:15 +0000125}
126
Adam Nemet7cdebac2015-07-14 22:32:44 +0000127void RuntimePointerChecking::insert(Loop *Lp, Value *Ptr, bool WritePtr,
128 unsigned DepSetId, unsigned ASId,
Silviu Barangae3c05342015-11-02 14:41:02 +0000129 const ValueToValueMap &Strides,
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +0000130 PredicatedScalarEvolution &PSE) {
Adam Nemet04563272015-02-01 16:56:15 +0000131 // Get the stride replaced scev.
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +0000132 const SCEV *Sc = replaceSymbolicStrideSCEV(PSE, Strides, Ptr);
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +0000133 ScalarEvolution *SE = PSE.getSE();
Silviu Baranga0e5804a2015-07-16 14:02:58 +0000134
Adam Nemet279784f2016-03-24 04:28:47 +0000135 const SCEV *ScStart;
136 const SCEV *ScEnd;
Silviu Baranga0e5804a2015-07-16 14:02:58 +0000137
Adam Nemet279784f2016-03-24 04:28:47 +0000138 if (SE->isLoopInvariant(Sc, Lp)) {
139 ScStart = ScEnd = Sc;
140 }
141 else {
142 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
143 assert(AR && "Invalid addrec expression");
144 const SCEV *Ex = SE->getBackedgeTakenCount(Lp);
145
146 ScStart = AR->getStart();
147 ScEnd = AR->evaluateAtIteration(Ex, *SE);
148 const SCEV *Step = AR->getStepRecurrence(*SE);
149
150 // For expressions with negative step, the upper bound is ScStart and the
151 // lower bound is ScEnd.
152 if (const SCEVConstant *CStep = dyn_cast<const SCEVConstant>(Step)) {
153 if (CStep->getValue()->isNegative())
154 std::swap(ScStart, ScEnd);
155 } else {
156 // Fallback case: the step is not constant, but the we can still
157 // get the upper and lower bounds of the interval by using min/max
158 // expressions.
159 ScStart = SE->getUMinExpr(ScStart, ScEnd);
160 ScEnd = SE->getUMaxExpr(AR->getStart(), ScEnd);
161 }
Silviu Baranga0e5804a2015-07-16 14:02:58 +0000162 }
163
164 Pointers.emplace_back(Ptr, ScStart, ScEnd, WritePtr, DepSetId, ASId, Sc);
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000165}
166
Adam Nemetbbe1f1d2015-07-27 19:38:48 +0000167SmallVector<RuntimePointerChecking::PointerCheck, 4>
Adam Nemet38530882015-08-09 20:06:06 +0000168RuntimePointerChecking::generateChecks() const {
Adam Nemetbbe1f1d2015-07-27 19:38:48 +0000169 SmallVector<PointerCheck, 4> Checks;
170
Adam Nemet7c52e052015-07-27 19:38:50 +0000171 for (unsigned I = 0; I < CheckingGroups.size(); ++I) {
172 for (unsigned J = I + 1; J < CheckingGroups.size(); ++J) {
173 const RuntimePointerChecking::CheckingPtrGroup &CGI = CheckingGroups[I];
174 const RuntimePointerChecking::CheckingPtrGroup &CGJ = CheckingGroups[J];
Adam Nemetbbe1f1d2015-07-27 19:38:48 +0000175
Adam Nemet38530882015-08-09 20:06:06 +0000176 if (needsChecking(CGI, CGJ))
Adam Nemetbbe1f1d2015-07-27 19:38:48 +0000177 Checks.push_back(std::make_pair(&CGI, &CGJ));
178 }
179 }
180 return Checks;
181}
182
Adam Nemet15840392015-08-07 22:44:15 +0000183void RuntimePointerChecking::generateChecks(
184 MemoryDepChecker::DepCandidates &DepCands, bool UseDependencies) {
185 assert(Checks.empty() && "Checks is not empty");
186 groupChecks(DepCands, UseDependencies);
187 Checks = generateChecks();
188}
189
Adam Nemet651a5a22015-08-09 20:06:08 +0000190bool RuntimePointerChecking::needsChecking(const CheckingPtrGroup &M,
191 const CheckingPtrGroup &N) const {
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000192 for (unsigned I = 0, EI = M.Members.size(); EI != I; ++I)
193 for (unsigned J = 0, EJ = N.Members.size(); EJ != J; ++J)
Adam Nemet651a5a22015-08-09 20:06:08 +0000194 if (needsChecking(M.Members[I], N.Members[J]))
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000195 return true;
196 return false;
197}
198
199/// Compare \p I and \p J and return the minimum.
200/// Return nullptr in case we couldn't find an answer.
201static const SCEV *getMinFromExprs(const SCEV *I, const SCEV *J,
202 ScalarEvolution *SE) {
203 const SCEV *Diff = SE->getMinusSCEV(J, I);
204 const SCEVConstant *C = dyn_cast<const SCEVConstant>(Diff);
205
206 if (!C)
207 return nullptr;
208 if (C->getValue()->isNegative())
209 return J;
210 return I;
211}
212
Adam Nemet7cdebac2015-07-14 22:32:44 +0000213bool RuntimePointerChecking::CheckingPtrGroup::addPointer(unsigned Index) {
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000214 const SCEV *Start = RtCheck.Pointers[Index].Start;
215 const SCEV *End = RtCheck.Pointers[Index].End;
216
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000217 // Compare the starts and ends with the known minimum and maximum
218 // of this set. We need to know how we compare against the min/max
219 // of the set in order to be able to emit memchecks.
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000220 const SCEV *Min0 = getMinFromExprs(Start, Low, RtCheck.SE);
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000221 if (!Min0)
222 return false;
223
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000224 const SCEV *Min1 = getMinFromExprs(End, High, RtCheck.SE);
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000225 if (!Min1)
226 return false;
227
228 // Update the low bound expression if we've found a new min value.
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000229 if (Min0 == Start)
230 Low = Start;
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000231
232 // Update the high bound expression if we've found a new max value.
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000233 if (Min1 != End)
234 High = End;
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000235
236 Members.push_back(Index);
237 return true;
238}
239
Adam Nemet7cdebac2015-07-14 22:32:44 +0000240void RuntimePointerChecking::groupChecks(
241 MemoryDepChecker::DepCandidates &DepCands, bool UseDependencies) {
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000242 // We build the groups from dependency candidates equivalence classes
243 // because:
244 // - We know that pointers in the same equivalence class share
245 // the same underlying object and therefore there is a chance
246 // that we can compare pointers
247 // - We wouldn't be able to merge two pointers for which we need
248 // to emit a memcheck. The classes in DepCands are already
249 // conveniently built such that no two pointers in the same
250 // class need checking against each other.
251
252 // We use the following (greedy) algorithm to construct the groups
253 // For every pointer in the equivalence class:
254 // For each existing group:
255 // - if the difference between this pointer and the min/max bounds
256 // of the group is a constant, then make the pointer part of the
257 // group and update the min/max bounds of that group as required.
258
259 CheckingGroups.clear();
260
Silviu Baranga48250602015-07-28 13:44:08 +0000261 // If we need to check two pointers to the same underlying object
262 // with a non-constant difference, we shouldn't perform any pointer
263 // grouping with those pointers. This is because we can easily get
264 // into cases where the resulting check would return false, even when
265 // the accesses are safe.
266 //
267 // The following example shows this:
268 // for (i = 0; i < 1000; ++i)
269 // a[5000 + i * m] = a[i] + a[i + 9000]
270 //
271 // Here grouping gives a check of (5000, 5000 + 1000 * m) against
272 // (0, 10000) which is always false. However, if m is 1, there is no
273 // dependence. Not grouping the checks for a[i] and a[i + 9000] allows
274 // us to perform an accurate check in this case.
275 //
276 // The above case requires that we have an UnknownDependence between
277 // accesses to the same underlying object. This cannot happen unless
278 // ShouldRetryWithRuntimeCheck is set, and therefore UseDependencies
279 // is also false. In this case we will use the fallback path and create
280 // separate checking groups for all pointers.
Mehdi Aminiafd13512015-11-05 05:49:43 +0000281
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000282 // If we don't have the dependency partitions, construct a new
Silviu Baranga48250602015-07-28 13:44:08 +0000283 // checking pointer group for each pointer. This is also required
284 // for correctness, because in this case we can have checking between
285 // pointers to the same underlying object.
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000286 if (!UseDependencies) {
287 for (unsigned I = 0; I < Pointers.size(); ++I)
288 CheckingGroups.push_back(CheckingPtrGroup(I, *this));
289 return;
290 }
291
292 unsigned TotalComparisons = 0;
293
294 DenseMap<Value *, unsigned> PositionMap;
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000295 for (unsigned Index = 0; Index < Pointers.size(); ++Index)
296 PositionMap[Pointers[Index].PointerValue] = Index;
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000297
Silviu Barangace3877f2015-07-09 15:18:25 +0000298 // We need to keep track of what pointers we've already seen so we
299 // don't process them twice.
300 SmallSet<unsigned, 2> Seen;
301
Sanjay Patele4b9f502015-12-07 19:21:39 +0000302 // Go through all equivalence classes, get the "pointer check groups"
Silviu Barangace3877f2015-07-09 15:18:25 +0000303 // and add them to the overall solution. We use the order in which accesses
304 // appear in 'Pointers' to enforce determinism.
305 for (unsigned I = 0; I < Pointers.size(); ++I) {
306 // We've seen this pointer before, and therefore already processed
307 // its equivalence class.
308 if (Seen.count(I))
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000309 continue;
310
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000311 MemoryDepChecker::MemAccessInfo Access(Pointers[I].PointerValue,
312 Pointers[I].IsWritePtr);
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000313
Silviu Barangace3877f2015-07-09 15:18:25 +0000314 SmallVector<CheckingPtrGroup, 2> Groups;
315 auto LeaderI = DepCands.findValue(DepCands.getLeaderValue(Access));
316
Silviu Barangaa647c302015-07-13 14:48:24 +0000317 // Because DepCands is constructed by visiting accesses in the order in
318 // which they appear in alias sets (which is deterministic) and the
319 // iteration order within an equivalence class member is only dependent on
320 // the order in which unions and insertions are performed on the
321 // equivalence class, the iteration order is deterministic.
Silviu Barangace3877f2015-07-09 15:18:25 +0000322 for (auto MI = DepCands.member_begin(LeaderI), ME = DepCands.member_end();
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000323 MI != ME; ++MI) {
324 unsigned Pointer = PositionMap[MI->getPointer()];
325 bool Merged = false;
Silviu Barangace3877f2015-07-09 15:18:25 +0000326 // Mark this pointer as seen.
327 Seen.insert(Pointer);
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000328
329 // Go through all the existing sets and see if we can find one
330 // which can include this pointer.
331 for (CheckingPtrGroup &Group : Groups) {
332 // Don't perform more than a certain amount of comparisons.
333 // This should limit the cost of grouping the pointers to something
334 // reasonable. If we do end up hitting this threshold, the algorithm
335 // will create separate groups for all remaining pointers.
336 if (TotalComparisons > MemoryCheckMergeThreshold)
337 break;
338
339 TotalComparisons++;
340
341 if (Group.addPointer(Pointer)) {
342 Merged = true;
343 break;
344 }
345 }
346
347 if (!Merged)
348 // We couldn't add this pointer to any existing set or the threshold
349 // for the number of comparisons has been reached. Create a new group
350 // to hold the current pointer.
351 Groups.push_back(CheckingPtrGroup(Pointer, *this));
352 }
353
354 // We've computed the grouped checks for this partition.
355 // Save the results and continue with the next one.
356 std::copy(Groups.begin(), Groups.end(), std::back_inserter(CheckingGroups));
357 }
Adam Nemet04563272015-02-01 16:56:15 +0000358}
359
Adam Nemet041e6de2015-07-16 02:48:05 +0000360bool RuntimePointerChecking::arePointersInSamePartition(
361 const SmallVectorImpl<int> &PtrToPartition, unsigned PtrIdx1,
362 unsigned PtrIdx2) {
363 return (PtrToPartition[PtrIdx1] != -1 &&
364 PtrToPartition[PtrIdx1] == PtrToPartition[PtrIdx2]);
365}
366
Adam Nemet651a5a22015-08-09 20:06:08 +0000367bool RuntimePointerChecking::needsChecking(unsigned I, unsigned J) const {
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000368 const PointerInfo &PointerI = Pointers[I];
369 const PointerInfo &PointerJ = Pointers[J];
370
Adam Nemeta8945b72015-02-18 03:43:58 +0000371 // No need to check if two readonly pointers intersect.
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000372 if (!PointerI.IsWritePtr && !PointerJ.IsWritePtr)
Adam Nemeta8945b72015-02-18 03:43:58 +0000373 return false;
374
375 // Only need to check pointers between two different dependency sets.
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000376 if (PointerI.DependencySetId == PointerJ.DependencySetId)
Adam Nemeta8945b72015-02-18 03:43:58 +0000377 return false;
378
379 // Only need to check pointers in the same alias set.
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000380 if (PointerI.AliasSetId != PointerJ.AliasSetId)
Adam Nemeta8945b72015-02-18 03:43:58 +0000381 return false;
382
383 return true;
384}
385
Adam Nemet54f0b832015-07-27 23:54:41 +0000386void RuntimePointerChecking::printChecks(
387 raw_ostream &OS, const SmallVectorImpl<PointerCheck> &Checks,
388 unsigned Depth) const {
389 unsigned N = 0;
390 for (const auto &Check : Checks) {
391 const auto &First = Check.first->Members, &Second = Check.second->Members;
392
393 OS.indent(Depth) << "Check " << N++ << ":\n";
394
395 OS.indent(Depth + 2) << "Comparing group (" << Check.first << "):\n";
396 for (unsigned K = 0; K < First.size(); ++K)
397 OS.indent(Depth + 2) << *Pointers[First[K]].PointerValue << "\n";
398
399 OS.indent(Depth + 2) << "Against group (" << Check.second << "):\n";
400 for (unsigned K = 0; K < Second.size(); ++K)
401 OS.indent(Depth + 2) << *Pointers[Second[K]].PointerValue << "\n";
402 }
403}
404
Adam Nemet3a91e942015-08-07 19:44:48 +0000405void RuntimePointerChecking::print(raw_ostream &OS, unsigned Depth) const {
Adam Nemete91cc6e2015-02-19 19:15:19 +0000406
407 OS.indent(Depth) << "Run-time memory checks:\n";
Adam Nemet15840392015-08-07 22:44:15 +0000408 printChecks(OS, Checks, Depth);
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000409
410 OS.indent(Depth) << "Grouped accesses:\n";
411 for (unsigned I = 0; I < CheckingGroups.size(); ++I) {
Adam Nemet54f0b832015-07-27 23:54:41 +0000412 const auto &CG = CheckingGroups[I];
413
414 OS.indent(Depth + 2) << "Group " << &CG << ":\n";
415 OS.indent(Depth + 4) << "(Low: " << *CG.Low << " High: " << *CG.High
416 << ")\n";
417 for (unsigned J = 0; J < CG.Members.size(); ++J) {
418 OS.indent(Depth + 6) << "Member: " << *Pointers[CG.Members[J]].Expr
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000419 << "\n";
420 }
421 }
Adam Nemete91cc6e2015-02-19 19:15:19 +0000422}
423
Adam Nemet04563272015-02-01 16:56:15 +0000424namespace {
425/// \brief Analyses memory accesses in a loop.
426///
427/// Checks whether run time pointer checks are needed and builds sets for data
428/// dependence checking.
429class AccessAnalysis {
430public:
431 /// \brief Read or write access location.
432 typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
433 typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
434
Adam Nemete2b885c2015-04-23 20:09:20 +0000435 AccessAnalysis(const DataLayout &Dl, AliasAnalysis *AA, LoopInfo *LI,
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +0000436 MemoryDepChecker::DepCandidates &DA,
437 PredicatedScalarEvolution &PSE)
Silviu Barangae3c05342015-11-02 14:41:02 +0000438 : DL(Dl), AST(*AA), LI(LI), DepCands(DA), IsRTCheckAnalysisNeeded(false),
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +0000439 PSE(PSE) {}
Adam Nemet04563272015-02-01 16:56:15 +0000440
441 /// \brief Register a load and whether it is only read from.
Chandler Carruthac80dc72015-06-17 07:18:54 +0000442 void addLoad(MemoryLocation &Loc, bool IsReadOnly) {
Adam Nemet04563272015-02-01 16:56:15 +0000443 Value *Ptr = const_cast<Value*>(Loc.Ptr);
Chandler Carruthecbd1682015-06-17 07:21:38 +0000444 AST.add(Ptr, MemoryLocation::UnknownSize, Loc.AATags);
Adam Nemet04563272015-02-01 16:56:15 +0000445 Accesses.insert(MemAccessInfo(Ptr, false));
446 if (IsReadOnly)
447 ReadOnlyPtr.insert(Ptr);
448 }
449
450 /// \brief Register a store.
Chandler Carruthac80dc72015-06-17 07:18:54 +0000451 void addStore(MemoryLocation &Loc) {
Adam Nemet04563272015-02-01 16:56:15 +0000452 Value *Ptr = const_cast<Value*>(Loc.Ptr);
Chandler Carruthecbd1682015-06-17 07:21:38 +0000453 AST.add(Ptr, MemoryLocation::UnknownSize, Loc.AATags);
Adam Nemet04563272015-02-01 16:56:15 +0000454 Accesses.insert(MemAccessInfo(Ptr, true));
455 }
456
457 /// \brief Check whether we can check the pointers at runtime for
Adam Nemetee614742015-07-09 22:17:38 +0000458 /// non-intersection.
459 ///
460 /// Returns true if we need no check or if we do and we can generate them
461 /// (i.e. the pointers have computable bounds).
Adam Nemet7cdebac2015-07-14 22:32:44 +0000462 bool canCheckPtrAtRT(RuntimePointerChecking &RtCheck, ScalarEvolution *SE,
463 Loop *TheLoop, const ValueToValueMap &Strides,
Adam Nemet04563272015-02-01 16:56:15 +0000464 bool ShouldCheckStride = false);
465
466 /// \brief Goes over all memory accesses, checks whether a RT check is needed
467 /// and builds sets of dependent accesses.
468 void buildDependenceSets() {
469 processMemAccesses();
470 }
471
Adam Nemet5dc3b2c2015-07-09 06:47:18 +0000472 /// \brief Initial processing of memory accesses determined that we need to
473 /// perform dependency checking.
474 ///
475 /// Note that this can later be cleared if we retry memcheck analysis without
476 /// dependency checking (i.e. ShouldRetryWithRuntimeCheck).
Adam Nemet04563272015-02-01 16:56:15 +0000477 bool isDependencyCheckNeeded() { return !CheckDeps.empty(); }
Adam Nemetdf3dc5b2015-05-18 15:37:03 +0000478
479 /// We decided that no dependence analysis would be used. Reset the state.
480 void resetDepChecks(MemoryDepChecker &DepChecker) {
481 CheckDeps.clear();
Adam Nemeta2df7502015-11-03 21:39:52 +0000482 DepChecker.clearDependences();
Adam Nemetdf3dc5b2015-05-18 15:37:03 +0000483 }
Adam Nemet04563272015-02-01 16:56:15 +0000484
485 MemAccessInfoSet &getDependenciesToCheck() { return CheckDeps; }
486
487private:
488 typedef SetVector<MemAccessInfo> PtrAccessSet;
489
490 /// \brief Go over all memory access and check whether runtime pointer checks
Adam Nemetb41d2d32015-07-09 06:47:21 +0000491 /// are needed and build sets of dependency check candidates.
Adam Nemet04563272015-02-01 16:56:15 +0000492 void processMemAccesses();
493
494 /// Set of all accesses.
495 PtrAccessSet Accesses;
496
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000497 const DataLayout &DL;
498
Adam Nemet04563272015-02-01 16:56:15 +0000499 /// Set of accesses that need a further dependence check.
500 MemAccessInfoSet CheckDeps;
501
502 /// Set of pointers that are read only.
503 SmallPtrSet<Value*, 16> ReadOnlyPtr;
504
Adam Nemet04563272015-02-01 16:56:15 +0000505 /// An alias set tracker to partition the access set by underlying object and
506 //intrinsic property (such as TBAA metadata).
507 AliasSetTracker AST;
508
Adam Nemete2b885c2015-04-23 20:09:20 +0000509 LoopInfo *LI;
510
Adam Nemet04563272015-02-01 16:56:15 +0000511 /// Sets of potentially dependent accesses - members of one set share an
512 /// underlying pointer. The set "CheckDeps" identfies which sets really need a
513 /// dependence check.
Adam Nemetdee666b2015-03-10 17:40:34 +0000514 MemoryDepChecker::DepCandidates &DepCands;
Adam Nemet04563272015-02-01 16:56:15 +0000515
Adam Nemet5dc3b2c2015-07-09 06:47:18 +0000516 /// \brief Initial processing of memory accesses determined that we may need
517 /// to add memchecks. Perform the analysis to determine the necessary checks.
518 ///
519 /// Note that, this is different from isDependencyCheckNeeded. When we retry
520 /// memcheck analysis without dependency checking
521 /// (i.e. ShouldRetryWithRuntimeCheck), isDependencyCheckNeeded is cleared
522 /// while this remains set if we have potentially dependent accesses.
523 bool IsRTCheckAnalysisNeeded;
Silviu Barangae3c05342015-11-02 14:41:02 +0000524
525 /// The SCEV predicate containing all the SCEV-related assumptions.
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +0000526 PredicatedScalarEvolution &PSE;
Adam Nemet04563272015-02-01 16:56:15 +0000527};
528
529} // end anonymous namespace
530
531/// \brief Check whether a pointer can participate in a runtime bounds check.
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +0000532static bool hasComputableBounds(PredicatedScalarEvolution &PSE,
Silviu Barangae3c05342015-11-02 14:41:02 +0000533 const ValueToValueMap &Strides, Value *Ptr,
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +0000534 Loop *L) {
535 const SCEV *PtrScev = replaceSymbolicStrideSCEV(PSE, Strides, Ptr);
Adam Nemet279784f2016-03-24 04:28:47 +0000536
537 // The bounds for loop-invariant pointer is trivial.
538 if (PSE.getSE()->isLoopInvariant(PtrScev, L))
539 return true;
540
Adam Nemet04563272015-02-01 16:56:15 +0000541 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
542 if (!AR)
543 return false;
544
545 return AR->isAffine();
546}
547
Adam Nemet7cdebac2015-07-14 22:32:44 +0000548bool AccessAnalysis::canCheckPtrAtRT(RuntimePointerChecking &RtCheck,
549 ScalarEvolution *SE, Loop *TheLoop,
550 const ValueToValueMap &StridesMap,
551 bool ShouldCheckStride) {
Adam Nemet04563272015-02-01 16:56:15 +0000552 // Find pointers with computable bounds. We are going to use this information
553 // to place a runtime bound check.
554 bool CanDoRT = true;
555
Adam Nemetee614742015-07-09 22:17:38 +0000556 bool NeedRTCheck = false;
Adam Nemet5dc3b2c2015-07-09 06:47:18 +0000557 if (!IsRTCheckAnalysisNeeded) return true;
Silviu Baranga98a13712015-06-08 10:27:06 +0000558
Adam Nemet04563272015-02-01 16:56:15 +0000559 bool IsDepCheckNeeded = isDependencyCheckNeeded();
Adam Nemet04563272015-02-01 16:56:15 +0000560
561 // We assign a consecutive id to access from different alias sets.
562 // Accesses between different groups doesn't need to be checked.
563 unsigned ASId = 1;
564 for (auto &AS : AST) {
Adam Nemet424edc62015-07-08 22:58:48 +0000565 int NumReadPtrChecks = 0;
566 int NumWritePtrChecks = 0;
567
Adam Nemet04563272015-02-01 16:56:15 +0000568 // We assign consecutive id to access from different dependence sets.
569 // Accesses within the same set don't need a runtime check.
570 unsigned RunningDepId = 1;
571 DenseMap<Value *, unsigned> DepSetId;
572
573 for (auto A : AS) {
574 Value *Ptr = A.getValue();
575 bool IsWrite = Accesses.count(MemAccessInfo(Ptr, true));
576 MemAccessInfo Access(Ptr, IsWrite);
577
Adam Nemet424edc62015-07-08 22:58:48 +0000578 if (IsWrite)
579 ++NumWritePtrChecks;
580 else
581 ++NumReadPtrChecks;
582
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +0000583 if (hasComputableBounds(PSE, StridesMap, Ptr, TheLoop) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000584 // When we run after a failing dependency check we have to make sure
585 // we don't have wrapping pointers.
Adam Nemet04563272015-02-01 16:56:15 +0000586 (!ShouldCheckStride ||
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +0000587 isStridedPtr(PSE, Ptr, TheLoop, StridesMap) == 1)) {
Adam Nemet04563272015-02-01 16:56:15 +0000588 // The id of the dependence set.
589 unsigned DepId;
590
591 if (IsDepCheckNeeded) {
592 Value *Leader = DepCands.getLeaderValue(Access).getPointer();
593 unsigned &LeaderId = DepSetId[Leader];
594 if (!LeaderId)
595 LeaderId = RunningDepId++;
596 DepId = LeaderId;
597 } else
598 // Each access has its own dependence set.
599 DepId = RunningDepId++;
600
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +0000601 RtCheck.insert(TheLoop, Ptr, IsWrite, DepId, ASId, StridesMap, PSE);
Adam Nemet04563272015-02-01 16:56:15 +0000602
Adam Nemet339f42b2015-02-19 19:15:07 +0000603 DEBUG(dbgs() << "LAA: Found a runtime check ptr:" << *Ptr << '\n');
Adam Nemet04563272015-02-01 16:56:15 +0000604 } else {
Adam Nemetf10ca272015-05-18 15:36:52 +0000605 DEBUG(dbgs() << "LAA: Can't find bounds for ptr:" << *Ptr << '\n');
Adam Nemet04563272015-02-01 16:56:15 +0000606 CanDoRT = false;
607 }
608 }
609
Adam Nemet424edc62015-07-08 22:58:48 +0000610 // If we have at least two writes or one write and a read then we need to
611 // check them. But there is no need to checks if there is only one
612 // dependence set for this alias set.
613 //
614 // Note that this function computes CanDoRT and NeedRTCheck independently.
615 // For example CanDoRT=false, NeedRTCheck=false means that we have a pointer
616 // for which we couldn't find the bounds but we don't actually need to emit
617 // any checks so it does not matter.
618 if (!(IsDepCheckNeeded && CanDoRT && RunningDepId == 2))
619 NeedRTCheck |= (NumWritePtrChecks >= 2 || (NumReadPtrChecks >= 1 &&
620 NumWritePtrChecks >= 1));
621
Adam Nemet04563272015-02-01 16:56:15 +0000622 ++ASId;
623 }
624
625 // If the pointers that we would use for the bounds comparison have different
626 // address spaces, assume the values aren't directly comparable, so we can't
627 // use them for the runtime check. We also have to assume they could
628 // overlap. In the future there should be metadata for whether address spaces
629 // are disjoint.
630 unsigned NumPointers = RtCheck.Pointers.size();
631 for (unsigned i = 0; i < NumPointers; ++i) {
632 for (unsigned j = i + 1; j < NumPointers; ++j) {
633 // Only need to check pointers between two different dependency sets.
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000634 if (RtCheck.Pointers[i].DependencySetId ==
635 RtCheck.Pointers[j].DependencySetId)
Adam Nemet04563272015-02-01 16:56:15 +0000636 continue;
637 // Only need to check pointers in the same alias set.
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000638 if (RtCheck.Pointers[i].AliasSetId != RtCheck.Pointers[j].AliasSetId)
Adam Nemet04563272015-02-01 16:56:15 +0000639 continue;
640
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000641 Value *PtrI = RtCheck.Pointers[i].PointerValue;
642 Value *PtrJ = RtCheck.Pointers[j].PointerValue;
Adam Nemet04563272015-02-01 16:56:15 +0000643
644 unsigned ASi = PtrI->getType()->getPointerAddressSpace();
645 unsigned ASj = PtrJ->getType()->getPointerAddressSpace();
646 if (ASi != ASj) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000647 DEBUG(dbgs() << "LAA: Runtime check would require comparison between"
Adam Nemet04d41632015-02-19 19:14:34 +0000648 " different address spaces\n");
Adam Nemet04563272015-02-01 16:56:15 +0000649 return false;
650 }
651 }
652 }
653
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000654 if (NeedRTCheck && CanDoRT)
Adam Nemet15840392015-08-07 22:44:15 +0000655 RtCheck.generateChecks(DepCands, IsDepCheckNeeded);
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000656
Adam Nemet155e8742015-08-07 22:44:21 +0000657 DEBUG(dbgs() << "LAA: We need to do " << RtCheck.getNumberOfChecks()
Adam Nemetee614742015-07-09 22:17:38 +0000658 << " pointer comparisons.\n");
659
660 RtCheck.Need = NeedRTCheck;
661
662 bool CanDoRTIfNeeded = !NeedRTCheck || CanDoRT;
663 if (!CanDoRTIfNeeded)
664 RtCheck.reset();
665 return CanDoRTIfNeeded;
Adam Nemet04563272015-02-01 16:56:15 +0000666}
667
668void AccessAnalysis::processMemAccesses() {
669 // We process the set twice: first we process read-write pointers, last we
670 // process read-only pointers. This allows us to skip dependence tests for
671 // read-only pointers.
672
Adam Nemet339f42b2015-02-19 19:15:07 +0000673 DEBUG(dbgs() << "LAA: Processing memory accesses...\n");
Adam Nemet04563272015-02-01 16:56:15 +0000674 DEBUG(dbgs() << " AST: "; AST.dump());
Adam Nemet9c926572015-03-10 17:40:37 +0000675 DEBUG(dbgs() << "LAA: Accesses(" << Accesses.size() << "):\n");
Adam Nemet04563272015-02-01 16:56:15 +0000676 DEBUG({
677 for (auto A : Accesses)
678 dbgs() << "\t" << *A.getPointer() << " (" <<
679 (A.getInt() ? "write" : (ReadOnlyPtr.count(A.getPointer()) ?
680 "read-only" : "read")) << ")\n";
681 });
682
683 // The AliasSetTracker has nicely partitioned our pointers by metadata
684 // compatibility and potential for underlying-object overlap. As a result, we
685 // only need to check for potential pointer dependencies within each alias
686 // set.
687 for (auto &AS : AST) {
688 // Note that both the alias-set tracker and the alias sets themselves used
689 // linked lists internally and so the iteration order here is deterministic
690 // (matching the original instruction order within each set).
691
692 bool SetHasWrite = false;
693
694 // Map of pointers to last access encountered.
695 typedef DenseMap<Value*, MemAccessInfo> UnderlyingObjToAccessMap;
696 UnderlyingObjToAccessMap ObjToLastAccess;
697
698 // Set of access to check after all writes have been processed.
699 PtrAccessSet DeferredAccesses;
700
701 // Iterate over each alias set twice, once to process read/write pointers,
702 // and then to process read-only pointers.
703 for (int SetIteration = 0; SetIteration < 2; ++SetIteration) {
704 bool UseDeferred = SetIteration > 0;
705 PtrAccessSet &S = UseDeferred ? DeferredAccesses : Accesses;
706
707 for (auto AV : AS) {
708 Value *Ptr = AV.getValue();
709
710 // For a single memory access in AliasSetTracker, Accesses may contain
711 // both read and write, and they both need to be handled for CheckDeps.
712 for (auto AC : S) {
713 if (AC.getPointer() != Ptr)
714 continue;
715
716 bool IsWrite = AC.getInt();
717
718 // If we're using the deferred access set, then it contains only
719 // reads.
720 bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite;
721 if (UseDeferred && !IsReadOnlyPtr)
722 continue;
723 // Otherwise, the pointer must be in the PtrAccessSet, either as a
724 // read or a write.
725 assert(((IsReadOnlyPtr && UseDeferred) || IsWrite ||
726 S.count(MemAccessInfo(Ptr, false))) &&
727 "Alias-set pointer not in the access set?");
728
729 MemAccessInfo Access(Ptr, IsWrite);
730 DepCands.insert(Access);
731
732 // Memorize read-only pointers for later processing and skip them in
733 // the first round (they need to be checked after we have seen all
734 // write pointers). Note: we also mark pointer that are not
735 // consecutive as "read-only" pointers (so that we check
736 // "a[b[i]] +="). Hence, we need the second check for "!IsWrite".
737 if (!UseDeferred && IsReadOnlyPtr) {
738 DeferredAccesses.insert(Access);
739 continue;
740 }
741
742 // If this is a write - check other reads and writes for conflicts. If
743 // this is a read only check other writes for conflicts (but only if
744 // there is no other write to the ptr - this is an optimization to
745 // catch "a[i] = a[i] + " without having to do a dependence check).
746 if ((IsWrite || IsReadOnlyPtr) && SetHasWrite) {
747 CheckDeps.insert(Access);
Adam Nemet5dc3b2c2015-07-09 06:47:18 +0000748 IsRTCheckAnalysisNeeded = true;
Adam Nemet04563272015-02-01 16:56:15 +0000749 }
750
751 if (IsWrite)
752 SetHasWrite = true;
753
754 // Create sets of pointers connected by a shared alias set and
755 // underlying object.
756 typedef SmallVector<Value *, 16> ValueVector;
757 ValueVector TempObjects;
Adam Nemete2b885c2015-04-23 20:09:20 +0000758
759 GetUnderlyingObjects(Ptr, TempObjects, DL, LI);
760 DEBUG(dbgs() << "Underlying objects for pointer " << *Ptr << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000761 for (Value *UnderlyingObj : TempObjects) {
Mehdi Aminiafd13512015-11-05 05:49:43 +0000762 // nullptr never alias, don't join sets for pointer that have "null"
763 // in their UnderlyingObjects list.
764 if (isa<ConstantPointerNull>(UnderlyingObj))
765 continue;
766
Adam Nemet04563272015-02-01 16:56:15 +0000767 UnderlyingObjToAccessMap::iterator Prev =
768 ObjToLastAccess.find(UnderlyingObj);
769 if (Prev != ObjToLastAccess.end())
770 DepCands.unionSets(Access, Prev->second);
771
772 ObjToLastAccess[UnderlyingObj] = Access;
Adam Nemete2b885c2015-04-23 20:09:20 +0000773 DEBUG(dbgs() << " " << *UnderlyingObj << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000774 }
775 }
776 }
777 }
778 }
779}
780
Adam Nemet04563272015-02-01 16:56:15 +0000781static bool isInBoundsGep(Value *Ptr) {
782 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
783 return GEP->isInBounds();
784 return false;
785}
786
Adam Nemetc4866d22015-06-26 17:25:43 +0000787/// \brief Return true if an AddRec pointer \p Ptr is unsigned non-wrapping,
788/// i.e. monotonically increasing/decreasing.
789static bool isNoWrapAddRec(Value *Ptr, const SCEVAddRecExpr *AR,
Silviu Barangaea63a7f2016-02-08 17:02:45 +0000790 PredicatedScalarEvolution &PSE, const Loop *L) {
Adam Nemetc4866d22015-06-26 17:25:43 +0000791 // FIXME: This should probably only return true for NUW.
792 if (AR->getNoWrapFlags(SCEV::NoWrapMask))
793 return true;
794
795 // Scalar evolution does not propagate the non-wrapping flags to values that
796 // are derived from a non-wrapping induction variable because non-wrapping
797 // could be flow-sensitive.
798 //
799 // Look through the potentially overflowing instruction to try to prove
800 // non-wrapping for the *specific* value of Ptr.
801
802 // The arithmetic implied by an inbounds GEP can't overflow.
803 auto *GEP = dyn_cast<GetElementPtrInst>(Ptr);
804 if (!GEP || !GEP->isInBounds())
805 return false;
806
807 // Make sure there is only one non-const index and analyze that.
808 Value *NonConstIndex = nullptr;
809 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
810 if (!isa<ConstantInt>(*Index)) {
811 if (NonConstIndex)
812 return false;
813 NonConstIndex = *Index;
814 }
815 if (!NonConstIndex)
816 // The recurrence is on the pointer, ignore for now.
817 return false;
818
819 // The index in GEP is signed. It is non-wrapping if it's derived from a NSW
820 // AddRec using a NSW operation.
821 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(NonConstIndex))
822 if (OBO->hasNoSignedWrap() &&
823 // Assume constant for other the operand so that the AddRec can be
824 // easily found.
825 isa<ConstantInt>(OBO->getOperand(1))) {
Silviu Barangaea63a7f2016-02-08 17:02:45 +0000826 auto *OpScev = PSE.getSCEV(OBO->getOperand(0));
Adam Nemetc4866d22015-06-26 17:25:43 +0000827
828 if (auto *OpAR = dyn_cast<SCEVAddRecExpr>(OpScev))
829 return OpAR->getLoop() == L && OpAR->getNoWrapFlags(SCEV::FlagNSW);
830 }
831
832 return false;
833}
834
Adam Nemet04563272015-02-01 16:56:15 +0000835/// \brief Check whether the access through \p Ptr has a constant stride.
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +0000836int llvm::isStridedPtr(PredicatedScalarEvolution &PSE, Value *Ptr,
Silviu Barangaea63a7f2016-02-08 17:02:45 +0000837 const Loop *Lp, const ValueToValueMap &StridesMap,
838 bool Assume) {
Craig Toppere3dcce92015-08-01 22:20:21 +0000839 Type *Ty = Ptr->getType();
Adam Nemet04563272015-02-01 16:56:15 +0000840 assert(Ty->isPointerTy() && "Unexpected non-ptr");
841
842 // Make sure that the pointer does not point to aggregate types.
Craig Toppere3dcce92015-08-01 22:20:21 +0000843 auto *PtrTy = cast<PointerType>(Ty);
Adam Nemet04563272015-02-01 16:56:15 +0000844 if (PtrTy->getElementType()->isAggregateType()) {
Silviu Barangaea63a7f2016-02-08 17:02:45 +0000845 DEBUG(dbgs() << "LAA: Bad stride - Not a pointer to a scalar type" << *Ptr
846 << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000847 return 0;
848 }
849
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +0000850 const SCEV *PtrScev = replaceSymbolicStrideSCEV(PSE, StridesMap, Ptr);
Adam Nemet04563272015-02-01 16:56:15 +0000851
852 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
Silviu Barangaea63a7f2016-02-08 17:02:45 +0000853 if (Assume && !AR)
Silviu Barangad68ed852016-03-23 15:29:30 +0000854 AR = PSE.getAsAddRec(Ptr);
Silviu Barangaea63a7f2016-02-08 17:02:45 +0000855
Adam Nemet04563272015-02-01 16:56:15 +0000856 if (!AR) {
Silviu Barangaea63a7f2016-02-08 17:02:45 +0000857 DEBUG(dbgs() << "LAA: Bad stride - Not an AddRecExpr pointer " << *Ptr
858 << " SCEV: " << *PtrScev << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000859 return 0;
860 }
861
862 // The accesss function must stride over the innermost loop.
863 if (Lp != AR->getLoop()) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000864 DEBUG(dbgs() << "LAA: Bad stride - Not striding over innermost loop " <<
Silviu Barangaea63a7f2016-02-08 17:02:45 +0000865 *Ptr << " SCEV: " << *AR << "\n");
Kyle Butta02ce982016-01-08 01:55:13 +0000866 return 0;
Adam Nemet04563272015-02-01 16:56:15 +0000867 }
868
869 // The address calculation must not wrap. Otherwise, a dependence could be
870 // inverted.
871 // An inbounds getelementptr that is a AddRec with a unit stride
872 // cannot wrap per definition. The unit stride requirement is checked later.
873 // An getelementptr without an inbounds attribute and unit stride would have
874 // to access the pointer value "0" which is undefined behavior in address
875 // space 0, therefore we can also vectorize this case.
876 bool IsInBoundsGEP = isInBoundsGep(Ptr);
Silviu Barangaea63a7f2016-02-08 17:02:45 +0000877 bool IsNoWrapAddRec =
878 PSE.hasNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW) ||
879 isNoWrapAddRec(Ptr, AR, PSE, Lp);
Adam Nemet04563272015-02-01 16:56:15 +0000880 bool IsInAddressSpaceZero = PtrTy->getAddressSpace() == 0;
881 if (!IsNoWrapAddRec && !IsInBoundsGEP && !IsInAddressSpaceZero) {
Silviu Barangaea63a7f2016-02-08 17:02:45 +0000882 if (Assume) {
883 PSE.setNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW);
884 IsNoWrapAddRec = true;
885 DEBUG(dbgs() << "LAA: Pointer may wrap in the address space:\n"
886 << "LAA: Pointer: " << *Ptr << "\n"
887 << "LAA: SCEV: " << *AR << "\n"
888 << "LAA: Added an overflow assumption\n");
889 } else {
890 DEBUG(dbgs() << "LAA: Bad stride - Pointer may wrap in the address space "
891 << *Ptr << " SCEV: " << *AR << "\n");
892 return 0;
893 }
Adam Nemet04563272015-02-01 16:56:15 +0000894 }
895
896 // Check the step is constant.
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +0000897 const SCEV *Step = AR->getStepRecurrence(*PSE.getSE());
Adam Nemet04563272015-02-01 16:56:15 +0000898
Adam Nemet943befe2015-07-09 00:03:22 +0000899 // Calculate the pointer stride and check if it is constant.
Adam Nemet04563272015-02-01 16:56:15 +0000900 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
901 if (!C) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000902 DEBUG(dbgs() << "LAA: Bad stride - Not a constant strided " << *Ptr <<
Silviu Barangaea63a7f2016-02-08 17:02:45 +0000903 " SCEV: " << *AR << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000904 return 0;
905 }
906
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000907 auto &DL = Lp->getHeader()->getModule()->getDataLayout();
908 int64_t Size = DL.getTypeAllocSize(PtrTy->getElementType());
Sanjoy Das0de2fec2015-12-17 20:28:46 +0000909 const APInt &APStepVal = C->getAPInt();
Adam Nemet04563272015-02-01 16:56:15 +0000910
911 // Huge step value - give up.
912 if (APStepVal.getBitWidth() > 64)
913 return 0;
914
915 int64_t StepVal = APStepVal.getSExtValue();
916
917 // Strided access.
918 int64_t Stride = StepVal / Size;
919 int64_t Rem = StepVal % Size;
920 if (Rem)
921 return 0;
922
923 // If the SCEV could wrap but we have an inbounds gep with a unit stride we
924 // know we can't "wrap around the address space". In case of address space
925 // zero we know that this won't happen without triggering undefined behavior.
926 if (!IsNoWrapAddRec && (IsInBoundsGEP || IsInAddressSpaceZero) &&
Silviu Barangaea63a7f2016-02-08 17:02:45 +0000927 Stride != 1 && Stride != -1) {
928 if (Assume) {
929 // We can avoid this case by adding a run-time check.
930 DEBUG(dbgs() << "LAA: Non unit strided pointer which is not either "
931 << "inbouds or in address space 0 may wrap:\n"
932 << "LAA: Pointer: " << *Ptr << "\n"
933 << "LAA: SCEV: " << *AR << "\n"
934 << "LAA: Added an overflow assumption\n");
935 PSE.setNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW);
936 } else
937 return 0;
938 }
Adam Nemet04563272015-02-01 16:56:15 +0000939
940 return Stride;
941}
942
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000943/// Take the pointer operand from the Load/Store instruction.
944/// Returns NULL if this is not a valid Load/Store instruction.
945static Value *getPointerOperand(Value *I) {
946 if (LoadInst *LI = dyn_cast<LoadInst>(I))
947 return LI->getPointerOperand();
948 if (StoreInst *SI = dyn_cast<StoreInst>(I))
949 return SI->getPointerOperand();
950 return nullptr;
951}
952
953/// Take the address space operand from the Load/Store instruction.
954/// Returns -1 if this is not a valid Load/Store instruction.
955static unsigned getAddressSpaceOperand(Value *I) {
956 if (LoadInst *L = dyn_cast<LoadInst>(I))
957 return L->getPointerAddressSpace();
958 if (StoreInst *S = dyn_cast<StoreInst>(I))
959 return S->getPointerAddressSpace();
960 return -1;
961}
962
963/// Returns true if the memory operations \p A and \p B are consecutive.
964bool llvm::isConsecutiveAccess(Value *A, Value *B, const DataLayout &DL,
965 ScalarEvolution &SE, bool CheckType) {
966 Value *PtrA = getPointerOperand(A);
967 Value *PtrB = getPointerOperand(B);
968 unsigned ASA = getAddressSpaceOperand(A);
969 unsigned ASB = getAddressSpaceOperand(B);
970
971 // Check that the address spaces match and that the pointers are valid.
972 if (!PtrA || !PtrB || (ASA != ASB))
973 return false;
974
975 // Make sure that A and B are different pointers.
976 if (PtrA == PtrB)
977 return false;
978
979 // Make sure that A and B have the same type if required.
980 if(CheckType && PtrA->getType() != PtrB->getType())
981 return false;
982
983 unsigned PtrBitWidth = DL.getPointerSizeInBits(ASA);
984 Type *Ty = cast<PointerType>(PtrA->getType())->getElementType();
985 APInt Size(PtrBitWidth, DL.getTypeStoreSize(Ty));
986
987 APInt OffsetA(PtrBitWidth, 0), OffsetB(PtrBitWidth, 0);
988 PtrA = PtrA->stripAndAccumulateInBoundsConstantOffsets(DL, OffsetA);
989 PtrB = PtrB->stripAndAccumulateInBoundsConstantOffsets(DL, OffsetB);
990
991 // OffsetDelta = OffsetB - OffsetA;
992 const SCEV *OffsetSCEVA = SE.getConstant(OffsetA);
993 const SCEV *OffsetSCEVB = SE.getConstant(OffsetB);
994 const SCEV *OffsetDeltaSCEV = SE.getMinusSCEV(OffsetSCEVB, OffsetSCEVA);
995 const SCEVConstant *OffsetDeltaC = dyn_cast<SCEVConstant>(OffsetDeltaSCEV);
996 const APInt &OffsetDelta = OffsetDeltaC->getAPInt();
997 // Check if they are based on the same pointer. That makes the offsets
998 // sufficient.
999 if (PtrA == PtrB)
1000 return OffsetDelta == Size;
1001
1002 // Compute the necessary base pointer delta to have the necessary final delta
1003 // equal to the size.
1004 // BaseDelta = Size - OffsetDelta;
1005 const SCEV *SizeSCEV = SE.getConstant(Size);
1006 const SCEV *BaseDelta = SE.getMinusSCEV(SizeSCEV, OffsetDeltaSCEV);
1007
1008 // Otherwise compute the distance with SCEV between the base pointers.
1009 const SCEV *PtrSCEVA = SE.getSCEV(PtrA);
1010 const SCEV *PtrSCEVB = SE.getSCEV(PtrB);
1011 const SCEV *X = SE.getAddExpr(PtrSCEVA, BaseDelta);
1012 return X == PtrSCEVB;
1013}
1014
Adam Nemet9c926572015-03-10 17:40:37 +00001015bool MemoryDepChecker::Dependence::isSafeForVectorization(DepType Type) {
1016 switch (Type) {
1017 case NoDep:
1018 case Forward:
1019 case BackwardVectorizable:
1020 return true;
1021
1022 case Unknown:
1023 case ForwardButPreventsForwarding:
1024 case Backward:
1025 case BackwardVectorizableButPreventsForwarding:
1026 return false;
1027 }
David Majnemerd388e932015-03-10 20:23:29 +00001028 llvm_unreachable("unexpected DepType!");
Adam Nemet9c926572015-03-10 17:40:37 +00001029}
1030
Adam Nemet397f5822015-11-03 23:50:03 +00001031bool MemoryDepChecker::Dependence::isBackward() const {
Adam Nemet9c926572015-03-10 17:40:37 +00001032 switch (Type) {
1033 case NoDep:
1034 case Forward:
1035 case ForwardButPreventsForwarding:
Adam Nemet397f5822015-11-03 23:50:03 +00001036 case Unknown:
Adam Nemet9c926572015-03-10 17:40:37 +00001037 return false;
1038
Adam Nemet9c926572015-03-10 17:40:37 +00001039 case BackwardVectorizable:
1040 case Backward:
1041 case BackwardVectorizableButPreventsForwarding:
1042 return true;
1043 }
David Majnemerd388e932015-03-10 20:23:29 +00001044 llvm_unreachable("unexpected DepType!");
Adam Nemet9c926572015-03-10 17:40:37 +00001045}
1046
Adam Nemet397f5822015-11-03 23:50:03 +00001047bool MemoryDepChecker::Dependence::isPossiblyBackward() const {
1048 return isBackward() || Type == Unknown;
1049}
1050
1051bool MemoryDepChecker::Dependence::isForward() const {
1052 switch (Type) {
1053 case Forward:
1054 case ForwardButPreventsForwarding:
1055 return true;
1056
1057 case NoDep:
1058 case Unknown:
1059 case BackwardVectorizable:
1060 case Backward:
1061 case BackwardVectorizableButPreventsForwarding:
1062 return false;
1063 }
1064 llvm_unreachable("unexpected DepType!");
1065}
1066
Adam Nemet04563272015-02-01 16:56:15 +00001067bool MemoryDepChecker::couldPreventStoreLoadForward(unsigned Distance,
1068 unsigned TypeByteSize) {
1069 // If loads occur at a distance that is not a multiple of a feasible vector
1070 // factor store-load forwarding does not take place.
1071 // Positive dependences might cause troubles because vectorizing them might
1072 // prevent store-load forwarding making vectorized code run a lot slower.
1073 // a[i] = a[i-3] ^ a[i-8];
1074 // The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
1075 // hence on your typical architecture store-load forwarding does not take
1076 // place. Vectorizing in such cases does not make sense.
1077 // Store-load forwarding distance.
1078 const unsigned NumCyclesForStoreLoadThroughMemory = 8*TypeByteSize;
1079 // Maximum vector factor.
Adam Nemetf219c642015-02-19 19:14:52 +00001080 unsigned MaxVFWithoutSLForwardIssues =
1081 VectorizerParams::MaxVectorWidth * TypeByteSize;
Adam Nemet04d41632015-02-19 19:14:34 +00001082 if(MaxSafeDepDistBytes < MaxVFWithoutSLForwardIssues)
Adam Nemet04563272015-02-01 16:56:15 +00001083 MaxVFWithoutSLForwardIssues = MaxSafeDepDistBytes;
1084
1085 for (unsigned vf = 2*TypeByteSize; vf <= MaxVFWithoutSLForwardIssues;
1086 vf *= 2) {
1087 if (Distance % vf && Distance / vf < NumCyclesForStoreLoadThroughMemory) {
1088 MaxVFWithoutSLForwardIssues = (vf >>=1);
1089 break;
1090 }
1091 }
1092
Adam Nemet04d41632015-02-19 19:14:34 +00001093 if (MaxVFWithoutSLForwardIssues< 2*TypeByteSize) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001094 DEBUG(dbgs() << "LAA: Distance " << Distance <<
Adam Nemet04d41632015-02-19 19:14:34 +00001095 " that could cause a store-load forwarding conflict\n");
Adam Nemet04563272015-02-01 16:56:15 +00001096 return true;
1097 }
1098
1099 if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes &&
Adam Nemetf219c642015-02-19 19:14:52 +00001100 MaxVFWithoutSLForwardIssues !=
1101 VectorizerParams::MaxVectorWidth * TypeByteSize)
Adam Nemet04563272015-02-01 16:56:15 +00001102 MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues;
1103 return false;
1104}
1105
Hao Liu751004a2015-06-08 04:48:37 +00001106/// \brief Check the dependence for two accesses with the same stride \p Stride.
1107/// \p Distance is the positive distance and \p TypeByteSize is type size in
1108/// bytes.
1109///
1110/// \returns true if they are independent.
1111static bool areStridedAccessesIndependent(unsigned Distance, unsigned Stride,
1112 unsigned TypeByteSize) {
1113 assert(Stride > 1 && "The stride must be greater than 1");
1114 assert(TypeByteSize > 0 && "The type size in byte must be non-zero");
1115 assert(Distance > 0 && "The distance must be non-zero");
1116
1117 // Skip if the distance is not multiple of type byte size.
1118 if (Distance % TypeByteSize)
1119 return false;
1120
1121 unsigned ScaledDist = Distance / TypeByteSize;
1122
1123 // No dependence if the scaled distance is not multiple of the stride.
1124 // E.g.
1125 // for (i = 0; i < 1024 ; i += 4)
1126 // A[i+2] = A[i] + 1;
1127 //
1128 // Two accesses in memory (scaled distance is 2, stride is 4):
1129 // | A[0] | | | | A[4] | | | |
1130 // | | | A[2] | | | | A[6] | |
1131 //
1132 // E.g.
1133 // for (i = 0; i < 1024 ; i += 3)
1134 // A[i+4] = A[i] + 1;
1135 //
1136 // Two accesses in memory (scaled distance is 4, stride is 3):
1137 // | A[0] | | | A[3] | | | A[6] | | |
1138 // | | | | | A[4] | | | A[7] | |
1139 return ScaledDist % Stride;
1140}
1141
Adam Nemet9c926572015-03-10 17:40:37 +00001142MemoryDepChecker::Dependence::DepType
1143MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
1144 const MemAccessInfo &B, unsigned BIdx,
1145 const ValueToValueMap &Strides) {
Adam Nemet04563272015-02-01 16:56:15 +00001146 assert (AIdx < BIdx && "Must pass arguments in program order");
1147
1148 Value *APtr = A.getPointer();
1149 Value *BPtr = B.getPointer();
1150 bool AIsWrite = A.getInt();
1151 bool BIsWrite = B.getInt();
1152
1153 // Two reads are independent.
1154 if (!AIsWrite && !BIsWrite)
Adam Nemet9c926572015-03-10 17:40:37 +00001155 return Dependence::NoDep;
Adam Nemet04563272015-02-01 16:56:15 +00001156
1157 // We cannot check pointers in different address spaces.
1158 if (APtr->getType()->getPointerAddressSpace() !=
1159 BPtr->getType()->getPointerAddressSpace())
Adam Nemet9c926572015-03-10 17:40:37 +00001160 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +00001161
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +00001162 const SCEV *AScev = replaceSymbolicStrideSCEV(PSE, Strides, APtr);
1163 const SCEV *BScev = replaceSymbolicStrideSCEV(PSE, Strides, BPtr);
Adam Nemet04563272015-02-01 16:56:15 +00001164
Silviu Barangaea63a7f2016-02-08 17:02:45 +00001165 int StrideAPtr = isStridedPtr(PSE, APtr, InnermostLoop, Strides, true);
1166 int StrideBPtr = isStridedPtr(PSE, BPtr, InnermostLoop, Strides, true);
Adam Nemet04563272015-02-01 16:56:15 +00001167
1168 const SCEV *Src = AScev;
1169 const SCEV *Sink = BScev;
1170
1171 // If the induction step is negative we have to invert source and sink of the
1172 // dependence.
1173 if (StrideAPtr < 0) {
1174 //Src = BScev;
1175 //Sink = AScev;
1176 std::swap(APtr, BPtr);
1177 std::swap(Src, Sink);
1178 std::swap(AIsWrite, BIsWrite);
1179 std::swap(AIdx, BIdx);
1180 std::swap(StrideAPtr, StrideBPtr);
1181 }
1182
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +00001183 const SCEV *Dist = PSE.getSE()->getMinusSCEV(Sink, Src);
Adam Nemet04563272015-02-01 16:56:15 +00001184
Adam Nemet339f42b2015-02-19 19:15:07 +00001185 DEBUG(dbgs() << "LAA: Src Scev: " << *Src << "Sink Scev: " << *Sink
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +00001186 << "(Induction step: " << StrideAPtr << ")\n");
Adam Nemet339f42b2015-02-19 19:15:07 +00001187 DEBUG(dbgs() << "LAA: Distance for " << *InstMap[AIdx] << " to "
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +00001188 << *InstMap[BIdx] << ": " << *Dist << "\n");
Adam Nemet04563272015-02-01 16:56:15 +00001189
Adam Nemet943befe2015-07-09 00:03:22 +00001190 // Need accesses with constant stride. We don't want to vectorize
Adam Nemet04563272015-02-01 16:56:15 +00001191 // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in
1192 // the address space.
1193 if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){
Adam Nemet943befe2015-07-09 00:03:22 +00001194 DEBUG(dbgs() << "Pointer access with non-constant stride\n");
Adam Nemet9c926572015-03-10 17:40:37 +00001195 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +00001196 }
1197
1198 const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist);
1199 if (!C) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001200 DEBUG(dbgs() << "LAA: Dependence because of non-constant distance\n");
Adam Nemet04563272015-02-01 16:56:15 +00001201 ShouldRetryWithRuntimeCheck = true;
Adam Nemet9c926572015-03-10 17:40:37 +00001202 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +00001203 }
1204
1205 Type *ATy = APtr->getType()->getPointerElementType();
1206 Type *BTy = BPtr->getType()->getPointerElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001207 auto &DL = InnermostLoop->getHeader()->getModule()->getDataLayout();
1208 unsigned TypeByteSize = DL.getTypeAllocSize(ATy);
Adam Nemet04563272015-02-01 16:56:15 +00001209
1210 // Negative distances are not plausible dependencies.
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001211 const APInt &Val = C->getAPInt();
Adam Nemet04563272015-02-01 16:56:15 +00001212 if (Val.isNegative()) {
1213 bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
1214 if (IsTrueDataDependence &&
1215 (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) ||
Adam Nemetb8486e52016-03-01 00:50:08 +00001216 ATy != BTy)) {
1217 DEBUG(dbgs() << "LAA: Forward but may prevent st->ld forwarding\n");
Adam Nemet9c926572015-03-10 17:40:37 +00001218 return Dependence::ForwardButPreventsForwarding;
Adam Nemetb8486e52016-03-01 00:50:08 +00001219 }
Adam Nemet04563272015-02-01 16:56:15 +00001220
Adam Nemet339f42b2015-02-19 19:15:07 +00001221 DEBUG(dbgs() << "LAA: Dependence is negative: NoDep\n");
Adam Nemet9c926572015-03-10 17:40:37 +00001222 return Dependence::Forward;
Adam Nemet04563272015-02-01 16:56:15 +00001223 }
1224
1225 // Write to the same location with the same size.
1226 // Could be improved to assert type sizes are the same (i32 == float, etc).
1227 if (Val == 0) {
1228 if (ATy == BTy)
Adam Nemetd7037c52015-11-03 20:13:43 +00001229 return Dependence::Forward;
Adam Nemet339f42b2015-02-19 19:15:07 +00001230 DEBUG(dbgs() << "LAA: Zero dependence difference but different types\n");
Adam Nemet9c926572015-03-10 17:40:37 +00001231 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +00001232 }
1233
1234 assert(Val.isStrictlyPositive() && "Expect a positive value");
1235
Adam Nemet04563272015-02-01 16:56:15 +00001236 if (ATy != BTy) {
Adam Nemet04d41632015-02-19 19:14:34 +00001237 DEBUG(dbgs() <<
Adam Nemet339f42b2015-02-19 19:15:07 +00001238 "LAA: ReadWrite-Write positive dependency with different types\n");
Adam Nemet9c926572015-03-10 17:40:37 +00001239 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +00001240 }
1241
1242 unsigned Distance = (unsigned) Val.getZExtValue();
1243
Hao Liu751004a2015-06-08 04:48:37 +00001244 unsigned Stride = std::abs(StrideAPtr);
1245 if (Stride > 1 &&
Adam Nemet0131a562015-07-08 18:47:38 +00001246 areStridedAccessesIndependent(Distance, Stride, TypeByteSize)) {
1247 DEBUG(dbgs() << "LAA: Strided accesses are independent\n");
Hao Liu751004a2015-06-08 04:48:37 +00001248 return Dependence::NoDep;
Adam Nemet0131a562015-07-08 18:47:38 +00001249 }
Hao Liu751004a2015-06-08 04:48:37 +00001250
Adam Nemet04563272015-02-01 16:56:15 +00001251 // Bail out early if passed-in parameters make vectorization not feasible.
Adam Nemetf219c642015-02-19 19:14:52 +00001252 unsigned ForcedFactor = (VectorizerParams::VectorizationFactor ?
1253 VectorizerParams::VectorizationFactor : 1);
1254 unsigned ForcedUnroll = (VectorizerParams::VectorizationInterleave ?
1255 VectorizerParams::VectorizationInterleave : 1);
Hao Liu751004a2015-06-08 04:48:37 +00001256 // The minimum number of iterations for a vectorized/unrolled version.
1257 unsigned MinNumIter = std::max(ForcedFactor * ForcedUnroll, 2U);
Adam Nemet04563272015-02-01 16:56:15 +00001258
Hao Liu751004a2015-06-08 04:48:37 +00001259 // It's not vectorizable if the distance is smaller than the minimum distance
1260 // needed for a vectroized/unrolled version. Vectorizing one iteration in
1261 // front needs TypeByteSize * Stride. Vectorizing the last iteration needs
1262 // TypeByteSize (No need to plus the last gap distance).
1263 //
1264 // E.g. Assume one char is 1 byte in memory and one int is 4 bytes.
1265 // foo(int *A) {
1266 // int *B = (int *)((char *)A + 14);
1267 // for (i = 0 ; i < 1024 ; i += 2)
1268 // B[i] = A[i] + 1;
1269 // }
1270 //
1271 // Two accesses in memory (stride is 2):
1272 // | A[0] | | A[2] | | A[4] | | A[6] | |
1273 // | B[0] | | B[2] | | B[4] |
1274 //
1275 // Distance needs for vectorizing iterations except the last iteration:
1276 // 4 * 2 * (MinNumIter - 1). Distance needs for the last iteration: 4.
1277 // So the minimum distance needed is: 4 * 2 * (MinNumIter - 1) + 4.
1278 //
1279 // If MinNumIter is 2, it is vectorizable as the minimum distance needed is
1280 // 12, which is less than distance.
1281 //
1282 // If MinNumIter is 4 (Say if a user forces the vectorization factor to be 4),
1283 // the minimum distance needed is 28, which is greater than distance. It is
1284 // not safe to do vectorization.
1285 unsigned MinDistanceNeeded =
1286 TypeByteSize * Stride * (MinNumIter - 1) + TypeByteSize;
1287 if (MinDistanceNeeded > Distance) {
1288 DEBUG(dbgs() << "LAA: Failure because of positive distance " << Distance
1289 << '\n');
1290 return Dependence::Backward;
1291 }
1292
1293 // Unsafe if the minimum distance needed is greater than max safe distance.
1294 if (MinDistanceNeeded > MaxSafeDepDistBytes) {
1295 DEBUG(dbgs() << "LAA: Failure because it needs at least "
1296 << MinDistanceNeeded << " size in bytes");
Adam Nemet9c926572015-03-10 17:40:37 +00001297 return Dependence::Backward;
Adam Nemet04563272015-02-01 16:56:15 +00001298 }
1299
Adam Nemet9cc0c392015-02-26 17:58:48 +00001300 // Positive distance bigger than max vectorization factor.
Hao Liu751004a2015-06-08 04:48:37 +00001301 // FIXME: Should use max factor instead of max distance in bytes, which could
1302 // not handle different types.
1303 // E.g. Assume one char is 1 byte in memory and one int is 4 bytes.
1304 // void foo (int *A, char *B) {
1305 // for (unsigned i = 0; i < 1024; i++) {
1306 // A[i+2] = A[i] + 1;
1307 // B[i+2] = B[i] + 1;
1308 // }
1309 // }
1310 //
1311 // This case is currently unsafe according to the max safe distance. If we
1312 // analyze the two accesses on array B, the max safe dependence distance
1313 // is 2. Then we analyze the accesses on array A, the minimum distance needed
1314 // is 8, which is less than 2 and forbidden vectorization, But actually
1315 // both A and B could be vectorized by 2 iterations.
1316 MaxSafeDepDistBytes =
1317 Distance < MaxSafeDepDistBytes ? Distance : MaxSafeDepDistBytes;
Adam Nemet04563272015-02-01 16:56:15 +00001318
1319 bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
1320 if (IsTrueDataDependence &&
1321 couldPreventStoreLoadForward(Distance, TypeByteSize))
Adam Nemet9c926572015-03-10 17:40:37 +00001322 return Dependence::BackwardVectorizableButPreventsForwarding;
Adam Nemet04563272015-02-01 16:56:15 +00001323
Hao Liu751004a2015-06-08 04:48:37 +00001324 DEBUG(dbgs() << "LAA: Positive distance " << Val.getSExtValue()
1325 << " with max VF = "
1326 << MaxSafeDepDistBytes / (TypeByteSize * Stride) << '\n');
Adam Nemet04563272015-02-01 16:56:15 +00001327
Adam Nemet9c926572015-03-10 17:40:37 +00001328 return Dependence::BackwardVectorizable;
Adam Nemet04563272015-02-01 16:56:15 +00001329}
1330
Adam Nemetdee666b2015-03-10 17:40:34 +00001331bool MemoryDepChecker::areDepsSafe(DepCandidates &AccessSets,
Adam Nemet04563272015-02-01 16:56:15 +00001332 MemAccessInfoSet &CheckDeps,
Adam Nemet8bc61df2015-02-24 00:41:59 +00001333 const ValueToValueMap &Strides) {
Adam Nemet04563272015-02-01 16:56:15 +00001334
1335 MaxSafeDepDistBytes = -1U;
1336 while (!CheckDeps.empty()) {
1337 MemAccessInfo CurAccess = *CheckDeps.begin();
1338
1339 // Get the relevant memory access set.
1340 EquivalenceClasses<MemAccessInfo>::iterator I =
1341 AccessSets.findValue(AccessSets.getLeaderValue(CurAccess));
1342
1343 // Check accesses within this set.
Richard Trieu7a083812016-02-18 22:09:30 +00001344 EquivalenceClasses<MemAccessInfo>::member_iterator AI =
1345 AccessSets.member_begin(I);
1346 EquivalenceClasses<MemAccessInfo>::member_iterator AE =
1347 AccessSets.member_end();
Adam Nemet04563272015-02-01 16:56:15 +00001348
1349 // Check every access pair.
1350 while (AI != AE) {
1351 CheckDeps.erase(*AI);
1352 EquivalenceClasses<MemAccessInfo>::member_iterator OI = std::next(AI);
1353 while (OI != AE) {
1354 // Check every accessing instruction pair in program order.
1355 for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(),
1356 I1E = Accesses[*AI].end(); I1 != I1E; ++I1)
1357 for (std::vector<unsigned>::iterator I2 = Accesses[*OI].begin(),
1358 I2E = Accesses[*OI].end(); I2 != I2E; ++I2) {
Adam Nemet9c926572015-03-10 17:40:37 +00001359 auto A = std::make_pair(&*AI, *I1);
1360 auto B = std::make_pair(&*OI, *I2);
1361
1362 assert(*I1 != *I2);
1363 if (*I1 > *I2)
1364 std::swap(A, B);
1365
1366 Dependence::DepType Type =
1367 isDependent(*A.first, A.second, *B.first, B.second, Strides);
1368 SafeForVectorization &= Dependence::isSafeForVectorization(Type);
1369
Adam Nemeta2df7502015-11-03 21:39:52 +00001370 // Gather dependences unless we accumulated MaxDependences
Adam Nemet9c926572015-03-10 17:40:37 +00001371 // dependences. In that case return as soon as we find the first
1372 // unsafe dependence. This puts a limit on this quadratic
1373 // algorithm.
Adam Nemeta2df7502015-11-03 21:39:52 +00001374 if (RecordDependences) {
1375 if (Type != Dependence::NoDep)
1376 Dependences.push_back(Dependence(A.second, B.second, Type));
Adam Nemet9c926572015-03-10 17:40:37 +00001377
Adam Nemeta2df7502015-11-03 21:39:52 +00001378 if (Dependences.size() >= MaxDependences) {
1379 RecordDependences = false;
1380 Dependences.clear();
Adam Nemet9c926572015-03-10 17:40:37 +00001381 DEBUG(dbgs() << "Too many dependences, stopped recording\n");
1382 }
1383 }
Adam Nemeta2df7502015-11-03 21:39:52 +00001384 if (!RecordDependences && !SafeForVectorization)
Adam Nemet04563272015-02-01 16:56:15 +00001385 return false;
1386 }
1387 ++OI;
1388 }
1389 AI++;
1390 }
1391 }
Adam Nemet9c926572015-03-10 17:40:37 +00001392
Adam Nemeta2df7502015-11-03 21:39:52 +00001393 DEBUG(dbgs() << "Total Dependences: " << Dependences.size() << "\n");
Adam Nemet9c926572015-03-10 17:40:37 +00001394 return SafeForVectorization;
Adam Nemet04563272015-02-01 16:56:15 +00001395}
1396
Adam Nemetec1e2bb2015-03-10 18:54:26 +00001397SmallVector<Instruction *, 4>
1398MemoryDepChecker::getInstructionsForAccess(Value *Ptr, bool isWrite) const {
1399 MemAccessInfo Access(Ptr, isWrite);
1400 auto &IndexVector = Accesses.find(Access)->second;
1401
1402 SmallVector<Instruction *, 4> Insts;
1403 std::transform(IndexVector.begin(), IndexVector.end(),
1404 std::back_inserter(Insts),
1405 [&](unsigned Idx) { return this->InstMap[Idx]; });
1406 return Insts;
1407}
1408
Adam Nemet58913d62015-03-10 17:40:43 +00001409const char *MemoryDepChecker::Dependence::DepName[] = {
1410 "NoDep", "Unknown", "Forward", "ForwardButPreventsForwarding", "Backward",
1411 "BackwardVectorizable", "BackwardVectorizableButPreventsForwarding"};
1412
1413void MemoryDepChecker::Dependence::print(
1414 raw_ostream &OS, unsigned Depth,
1415 const SmallVectorImpl<Instruction *> &Instrs) const {
1416 OS.indent(Depth) << DepName[Type] << ":\n";
1417 OS.indent(Depth + 2) << *Instrs[Source] << " -> \n";
1418 OS.indent(Depth + 2) << *Instrs[Destination] << "\n";
1419}
1420
Adam Nemet929c38e2015-02-19 19:15:10 +00001421bool LoopAccessInfo::canAnalyzeLoop() {
Adam Nemet8dcb3b62015-04-17 22:43:10 +00001422 // We need to have a loop header.
Adam Nemetd8968f02016-01-18 21:16:33 +00001423 DEBUG(dbgs() << "LAA: Found a loop in "
1424 << TheLoop->getHeader()->getParent()->getName() << ": "
1425 << TheLoop->getHeader()->getName() << '\n');
Adam Nemet8dcb3b62015-04-17 22:43:10 +00001426
Adam Nemetd8968f02016-01-18 21:16:33 +00001427 // We can only analyze innermost loops.
Adam Nemet929c38e2015-02-19 19:15:10 +00001428 if (!TheLoop->empty()) {
Adam Nemet8dcb3b62015-04-17 22:43:10 +00001429 DEBUG(dbgs() << "LAA: loop is not the innermost loop\n");
Adam Nemet2bd6e982015-02-19 19:15:15 +00001430 emitAnalysis(LoopAccessReport() << "loop is not the innermost loop");
Adam Nemet929c38e2015-02-19 19:15:10 +00001431 return false;
1432 }
1433
1434 // We must have a single backedge.
1435 if (TheLoop->getNumBackEdges() != 1) {
Adam Nemet8dcb3b62015-04-17 22:43:10 +00001436 DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n");
Adam Nemet929c38e2015-02-19 19:15:10 +00001437 emitAnalysis(
Adam Nemet2bd6e982015-02-19 19:15:15 +00001438 LoopAccessReport() <<
Adam Nemet929c38e2015-02-19 19:15:10 +00001439 "loop control flow is not understood by analyzer");
1440 return false;
1441 }
1442
1443 // We must have a single exiting block.
1444 if (!TheLoop->getExitingBlock()) {
Adam Nemet8dcb3b62015-04-17 22:43:10 +00001445 DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n");
Adam Nemet929c38e2015-02-19 19:15:10 +00001446 emitAnalysis(
Adam Nemet2bd6e982015-02-19 19:15:15 +00001447 LoopAccessReport() <<
Adam Nemet929c38e2015-02-19 19:15:10 +00001448 "loop control flow is not understood by analyzer");
1449 return false;
1450 }
1451
1452 // We only handle bottom-tested loops, i.e. loop in which the condition is
1453 // checked at the end of each iteration. With that we can assume that all
1454 // instructions in the loop are executed the same number of times.
1455 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
Adam Nemet8dcb3b62015-04-17 22:43:10 +00001456 DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n");
Adam Nemet929c38e2015-02-19 19:15:10 +00001457 emitAnalysis(
Adam Nemet2bd6e982015-02-19 19:15:15 +00001458 LoopAccessReport() <<
Adam Nemet929c38e2015-02-19 19:15:10 +00001459 "loop control flow is not understood by analyzer");
1460 return false;
1461 }
1462
Adam Nemet929c38e2015-02-19 19:15:10 +00001463 // ScalarEvolution needs to be able to find the exit count.
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +00001464 const SCEV *ExitCount = PSE.getSE()->getBackedgeTakenCount(TheLoop);
1465 if (ExitCount == PSE.getSE()->getCouldNotCompute()) {
1466 emitAnalysis(LoopAccessReport()
1467 << "could not determine number of loop iterations");
Adam Nemet929c38e2015-02-19 19:15:10 +00001468 DEBUG(dbgs() << "LAA: SCEV could not compute the loop exit count.\n");
1469 return false;
1470 }
1471
1472 return true;
1473}
1474
Adam Nemet8bc61df2015-02-24 00:41:59 +00001475void LoopAccessInfo::analyzeLoop(const ValueToValueMap &Strides) {
Adam Nemet04563272015-02-01 16:56:15 +00001476
1477 typedef SmallVector<Value*, 16> ValueVector;
1478 typedef SmallPtrSet<Value*, 16> ValueSet;
1479
1480 // Holds the Load and Store *instructions*.
1481 ValueVector Loads;
1482 ValueVector Stores;
1483
1484 // Holds all the different accesses in the loop.
1485 unsigned NumReads = 0;
1486 unsigned NumReadWrites = 0;
1487
Adam Nemet7cdebac2015-07-14 22:32:44 +00001488 PtrRtChecking.Pointers.clear();
1489 PtrRtChecking.Need = false;
Adam Nemet04563272015-02-01 16:56:15 +00001490
1491 const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
Adam Nemet04563272015-02-01 16:56:15 +00001492
1493 // For each block.
1494 for (Loop::block_iterator bb = TheLoop->block_begin(),
1495 be = TheLoop->block_end(); bb != be; ++bb) {
1496
1497 // Scan the BB and collect legal loads and stores.
1498 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
1499 ++it) {
1500
1501 // If this is a load, save it. If this instruction can read from memory
1502 // but is not a load, then we quit. Notice that we don't handle function
1503 // calls that read or write.
1504 if (it->mayReadFromMemory()) {
1505 // Many math library functions read the rounding mode. We will only
1506 // vectorize a loop if it contains known function calls that don't set
1507 // the flag. Therefore, it is safe to ignore this read from memory.
1508 CallInst *Call = dyn_cast<CallInst>(it);
1509 if (Call && getIntrinsicIDForCall(Call, TLI))
1510 continue;
1511
Michael Zolotukhin9b3cf602015-03-17 19:46:50 +00001512 // If the function has an explicit vectorized counterpart, we can safely
1513 // assume that it can be vectorized.
1514 if (Call && !Call->isNoBuiltin() && Call->getCalledFunction() &&
1515 TLI->isFunctionVectorizable(Call->getCalledFunction()->getName()))
1516 continue;
1517
Adam Nemet04563272015-02-01 16:56:15 +00001518 LoadInst *Ld = dyn_cast<LoadInst>(it);
1519 if (!Ld || (!Ld->isSimple() && !IsAnnotatedParallel)) {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001520 emitAnalysis(LoopAccessReport(Ld)
Adam Nemet04563272015-02-01 16:56:15 +00001521 << "read with atomic ordering or volatile read");
Adam Nemet339f42b2015-02-19 19:15:07 +00001522 DEBUG(dbgs() << "LAA: Found a non-simple load.\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001523 CanVecMem = false;
1524 return;
Adam Nemet04563272015-02-01 16:56:15 +00001525 }
1526 NumLoads++;
1527 Loads.push_back(Ld);
1528 DepChecker.addAccess(Ld);
1529 continue;
1530 }
1531
1532 // Save 'store' instructions. Abort if other instructions write to memory.
1533 if (it->mayWriteToMemory()) {
1534 StoreInst *St = dyn_cast<StoreInst>(it);
1535 if (!St) {
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +00001536 emitAnalysis(LoopAccessReport(&*it) <<
Adam Nemet04d41632015-02-19 19:14:34 +00001537 "instruction cannot be vectorized");
Adam Nemet436018c2015-02-19 19:15:00 +00001538 CanVecMem = false;
1539 return;
Adam Nemet04563272015-02-01 16:56:15 +00001540 }
1541 if (!St->isSimple() && !IsAnnotatedParallel) {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001542 emitAnalysis(LoopAccessReport(St)
Adam Nemet04563272015-02-01 16:56:15 +00001543 << "write with atomic ordering or volatile write");
Adam Nemet339f42b2015-02-19 19:15:07 +00001544 DEBUG(dbgs() << "LAA: Found a non-simple store.\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001545 CanVecMem = false;
1546 return;
Adam Nemet04563272015-02-01 16:56:15 +00001547 }
1548 NumStores++;
1549 Stores.push_back(St);
1550 DepChecker.addAccess(St);
1551 }
1552 } // Next instr.
1553 } // Next block.
1554
1555 // Now we have two lists that hold the loads and the stores.
1556 // Next, we find the pointers that they use.
1557
1558 // Check if we see any stores. If there are no stores, then we don't
1559 // care if the pointers are *restrict*.
1560 if (!Stores.size()) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001561 DEBUG(dbgs() << "LAA: Found a read-only loop!\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001562 CanVecMem = true;
1563 return;
Adam Nemet04563272015-02-01 16:56:15 +00001564 }
1565
Adam Nemetdee666b2015-03-10 17:40:34 +00001566 MemoryDepChecker::DepCandidates DependentAccesses;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001567 AccessAnalysis Accesses(TheLoop->getHeader()->getModule()->getDataLayout(),
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +00001568 AA, LI, DependentAccesses, PSE);
Adam Nemet04563272015-02-01 16:56:15 +00001569
1570 // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
1571 // multiple times on the same object. If the ptr is accessed twice, once
1572 // for read and once for write, it will only appear once (on the write
1573 // list). This is okay, since we are going to check for conflicts between
1574 // writes and between reads and writes, but not between reads and reads.
1575 ValueSet Seen;
1576
1577 ValueVector::iterator I, IE;
1578 for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
1579 StoreInst *ST = cast<StoreInst>(*I);
1580 Value* Ptr = ST->getPointerOperand();
Adam Nemetce482502015-04-08 17:48:40 +00001581 // Check for store to loop invariant address.
1582 StoreToLoopInvariantAddress |= isUniform(Ptr);
Adam Nemet04563272015-02-01 16:56:15 +00001583 // If we did *not* see this pointer before, insert it to the read-write
1584 // list. At this phase it is only a 'write' list.
1585 if (Seen.insert(Ptr).second) {
1586 ++NumReadWrites;
1587
Chandler Carruthac80dc72015-06-17 07:18:54 +00001588 MemoryLocation Loc = MemoryLocation::get(ST);
Adam Nemet04563272015-02-01 16:56:15 +00001589 // The TBAA metadata could have a control dependency on the predication
1590 // condition, so we cannot rely on it when determining whether or not we
1591 // need runtime pointer checks.
Adam Nemet01abb2c2015-02-18 03:43:19 +00001592 if (blockNeedsPredication(ST->getParent(), TheLoop, DT))
Adam Nemet04563272015-02-01 16:56:15 +00001593 Loc.AATags.TBAA = nullptr;
1594
1595 Accesses.addStore(Loc);
1596 }
1597 }
1598
1599 if (IsAnnotatedParallel) {
Adam Nemet04d41632015-02-19 19:14:34 +00001600 DEBUG(dbgs()
Adam Nemet339f42b2015-02-19 19:15:07 +00001601 << "LAA: A loop annotated parallel, ignore memory dependency "
Adam Nemet04d41632015-02-19 19:14:34 +00001602 << "checks.\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001603 CanVecMem = true;
1604 return;
Adam Nemet04563272015-02-01 16:56:15 +00001605 }
1606
1607 for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
1608 LoadInst *LD = cast<LoadInst>(*I);
1609 Value* Ptr = LD->getPointerOperand();
1610 // If we did *not* see this pointer before, insert it to the
1611 // read list. If we *did* see it before, then it is already in
1612 // the read-write list. This allows us to vectorize expressions
1613 // such as A[i] += x; Because the address of A[i] is a read-write
1614 // pointer. This only works if the index of A[i] is consecutive.
1615 // If the address of i is unknown (for example A[B[i]]) then we may
1616 // read a few words, modify, and write a few words, and some of the
1617 // words may be written to the same address.
1618 bool IsReadOnlyPtr = false;
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +00001619 if (Seen.insert(Ptr).second || !isStridedPtr(PSE, Ptr, TheLoop, Strides)) {
Adam Nemet04563272015-02-01 16:56:15 +00001620 ++NumReads;
1621 IsReadOnlyPtr = true;
1622 }
1623
Chandler Carruthac80dc72015-06-17 07:18:54 +00001624 MemoryLocation Loc = MemoryLocation::get(LD);
Adam Nemet04563272015-02-01 16:56:15 +00001625 // The TBAA metadata could have a control dependency on the predication
1626 // condition, so we cannot rely on it when determining whether or not we
1627 // need runtime pointer checks.
Adam Nemet01abb2c2015-02-18 03:43:19 +00001628 if (blockNeedsPredication(LD->getParent(), TheLoop, DT))
Adam Nemet04563272015-02-01 16:56:15 +00001629 Loc.AATags.TBAA = nullptr;
1630
1631 Accesses.addLoad(Loc, IsReadOnlyPtr);
1632 }
1633
1634 // If we write (or read-write) to a single destination and there are no
1635 // other reads in this loop then is it safe to vectorize.
1636 if (NumReadWrites == 1 && NumReads == 0) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001637 DEBUG(dbgs() << "LAA: Found a write-only loop!\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001638 CanVecMem = true;
1639 return;
Adam Nemet04563272015-02-01 16:56:15 +00001640 }
1641
1642 // Build dependence sets and check whether we need a runtime pointer bounds
1643 // check.
1644 Accesses.buildDependenceSets();
Adam Nemet04563272015-02-01 16:56:15 +00001645
1646 // Find pointers with computable bounds. We are going to use this information
1647 // to place a runtime bound check.
Adam Nemetee614742015-07-09 22:17:38 +00001648 bool CanDoRTIfNeeded =
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +00001649 Accesses.canCheckPtrAtRT(PtrRtChecking, PSE.getSE(), TheLoop, Strides);
Adam Nemetee614742015-07-09 22:17:38 +00001650 if (!CanDoRTIfNeeded) {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001651 emitAnalysis(LoopAccessReport() << "cannot identify array bounds");
Adam Nemetee614742015-07-09 22:17:38 +00001652 DEBUG(dbgs() << "LAA: We can't vectorize because we can't find "
1653 << "the array bounds.\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001654 CanVecMem = false;
1655 return;
Adam Nemet04563272015-02-01 16:56:15 +00001656 }
1657
Adam Nemetee614742015-07-09 22:17:38 +00001658 DEBUG(dbgs() << "LAA: We can perform a memory runtime check if needed.\n");
Adam Nemet04563272015-02-01 16:56:15 +00001659
Adam Nemet436018c2015-02-19 19:15:00 +00001660 CanVecMem = true;
Adam Nemet04563272015-02-01 16:56:15 +00001661 if (Accesses.isDependencyCheckNeeded()) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001662 DEBUG(dbgs() << "LAA: Checking memory dependencies\n");
Adam Nemet04563272015-02-01 16:56:15 +00001663 CanVecMem = DepChecker.areDepsSafe(
1664 DependentAccesses, Accesses.getDependenciesToCheck(), Strides);
1665 MaxSafeDepDistBytes = DepChecker.getMaxSafeDepDistBytes();
1666
1667 if (!CanVecMem && DepChecker.shouldRetryWithRuntimeCheck()) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001668 DEBUG(dbgs() << "LAA: Retrying with memory checks\n");
Adam Nemet04563272015-02-01 16:56:15 +00001669
1670 // Clear the dependency checks. We assume they are not needed.
Adam Nemetdf3dc5b2015-05-18 15:37:03 +00001671 Accesses.resetDepChecks(DepChecker);
Adam Nemet04563272015-02-01 16:56:15 +00001672
Adam Nemet7cdebac2015-07-14 22:32:44 +00001673 PtrRtChecking.reset();
1674 PtrRtChecking.Need = true;
Adam Nemet04563272015-02-01 16:56:15 +00001675
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +00001676 auto *SE = PSE.getSE();
Adam Nemetee614742015-07-09 22:17:38 +00001677 CanDoRTIfNeeded =
Adam Nemet7cdebac2015-07-14 22:32:44 +00001678 Accesses.canCheckPtrAtRT(PtrRtChecking, SE, TheLoop, Strides, true);
Silviu Baranga98a13712015-06-08 10:27:06 +00001679
Adam Nemet949e91a2015-03-10 19:12:41 +00001680 // Check that we found the bounds for the pointer.
Adam Nemetee614742015-07-09 22:17:38 +00001681 if (!CanDoRTIfNeeded) {
Adam Nemetb6dc76f2015-03-10 18:54:19 +00001682 emitAnalysis(LoopAccessReport()
1683 << "cannot check memory dependencies at runtime");
1684 DEBUG(dbgs() << "LAA: Can't vectorize with memory checks\n");
Adam Nemetb6dc76f2015-03-10 18:54:19 +00001685 CanVecMem = false;
1686 return;
1687 }
1688
Adam Nemet04563272015-02-01 16:56:15 +00001689 CanVecMem = true;
1690 }
1691 }
1692
Adam Nemet4bb90a72015-03-10 21:47:39 +00001693 if (CanVecMem)
1694 DEBUG(dbgs() << "LAA: No unsafe dependent memory operations in loop. We"
Adam Nemet7cdebac2015-07-14 22:32:44 +00001695 << (PtrRtChecking.Need ? "" : " don't")
Adam Nemet0f67c6c2015-07-09 22:17:41 +00001696 << " need runtime memory checks.\n");
Adam Nemet4bb90a72015-03-10 21:47:39 +00001697 else {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001698 emitAnalysis(LoopAccessReport() <<
Adam Nemet04d41632015-02-19 19:14:34 +00001699 "unsafe dependent memory operations in loop");
Adam Nemet4bb90a72015-03-10 21:47:39 +00001700 DEBUG(dbgs() << "LAA: unsafe dependent memory operations in loop\n");
1701 }
Adam Nemet04563272015-02-01 16:56:15 +00001702}
1703
Adam Nemet01abb2c2015-02-18 03:43:19 +00001704bool LoopAccessInfo::blockNeedsPredication(BasicBlock *BB, Loop *TheLoop,
1705 DominatorTree *DT) {
Adam Nemet04563272015-02-01 16:56:15 +00001706 assert(TheLoop->contains(BB) && "Unknown block used");
1707
1708 // Blocks that do not dominate the latch need predication.
1709 BasicBlock* Latch = TheLoop->getLoopLatch();
1710 return !DT->dominates(BB, Latch);
1711}
1712
Adam Nemet2bd6e982015-02-19 19:15:15 +00001713void LoopAccessInfo::emitAnalysis(LoopAccessReport &Message) {
Adam Nemetc9228532015-02-19 19:14:56 +00001714 assert(!Report && "Multiple reports generated");
1715 Report = Message;
Adam Nemet04563272015-02-01 16:56:15 +00001716}
1717
Adam Nemet57ac7662015-02-19 19:15:21 +00001718bool LoopAccessInfo::isUniform(Value *V) const {
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +00001719 return (PSE.getSE()->isLoopInvariant(PSE.getSE()->getSCEV(V), TheLoop));
Adam Nemet04563272015-02-01 16:56:15 +00001720}
Adam Nemet7206d7a2015-02-06 18:31:04 +00001721
1722// FIXME: this function is currently a duplicate of the one in
1723// LoopVectorize.cpp.
1724static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
1725 Instruction *Loc) {
1726 if (FirstInst)
1727 return FirstInst;
1728 if (Instruction *I = dyn_cast<Instruction>(V))
1729 return I->getParent() == Loc->getParent() ? I : nullptr;
1730 return nullptr;
1731}
1732
Benjamin Kramer039b1042015-10-28 13:54:36 +00001733namespace {
Adam Nemet4e533ef2015-08-21 23:19:57 +00001734/// \brief IR Values for the lower and upper bounds of a pointer evolution. We
1735/// need to use value-handles because SCEV expansion can invalidate previously
1736/// expanded values. Thus expansion of a pointer can invalidate the bounds for
1737/// a previous one.
Adam Nemet1da7df32015-07-26 05:32:14 +00001738struct PointerBounds {
Adam Nemet4e533ef2015-08-21 23:19:57 +00001739 TrackingVH<Value> Start;
1740 TrackingVH<Value> End;
Adam Nemet1da7df32015-07-26 05:32:14 +00001741};
Benjamin Kramer039b1042015-10-28 13:54:36 +00001742} // end anonymous namespace
Adam Nemet7206d7a2015-02-06 18:31:04 +00001743
Adam Nemet1da7df32015-07-26 05:32:14 +00001744/// \brief Expand code for the lower and upper bound of the pointer group \p CG
1745/// in \p TheLoop. \return the values for the bounds.
1746static PointerBounds
1747expandBounds(const RuntimePointerChecking::CheckingPtrGroup *CG, Loop *TheLoop,
1748 Instruction *Loc, SCEVExpander &Exp, ScalarEvolution *SE,
1749 const RuntimePointerChecking &PtrRtChecking) {
1750 Value *Ptr = PtrRtChecking.Pointers[CG->Members[0]].PointerValue;
1751 const SCEV *Sc = SE->getSCEV(Ptr);
1752
1753 if (SE->isLoopInvariant(Sc, TheLoop)) {
1754 DEBUG(dbgs() << "LAA: Adding RT check for a loop invariant ptr:" << *Ptr
1755 << "\n");
1756 return {Ptr, Ptr};
1757 } else {
1758 unsigned AS = Ptr->getType()->getPointerAddressSpace();
1759 LLVMContext &Ctx = Loc->getContext();
1760
1761 // Use this type for pointer arithmetic.
1762 Type *PtrArithTy = Type::getInt8PtrTy(Ctx, AS);
1763 Value *Start = nullptr, *End = nullptr;
1764
1765 DEBUG(dbgs() << "LAA: Adding RT check for range:\n");
1766 Start = Exp.expandCodeFor(CG->Low, PtrArithTy, Loc);
1767 End = Exp.expandCodeFor(CG->High, PtrArithTy, Loc);
1768 DEBUG(dbgs() << "Start: " << *CG->Low << " End: " << *CG->High << "\n");
1769 return {Start, End};
1770 }
1771}
1772
1773/// \brief Turns a collection of checks into a collection of expanded upper and
1774/// lower bounds for both pointers in the check.
1775static SmallVector<std::pair<PointerBounds, PointerBounds>, 4> expandBounds(
1776 const SmallVectorImpl<RuntimePointerChecking::PointerCheck> &PointerChecks,
1777 Loop *L, Instruction *Loc, ScalarEvolution *SE, SCEVExpander &Exp,
1778 const RuntimePointerChecking &PtrRtChecking) {
1779 SmallVector<std::pair<PointerBounds, PointerBounds>, 4> ChecksWithBounds;
1780
1781 // Here we're relying on the SCEV Expander's cache to only emit code for the
1782 // same bounds once.
1783 std::transform(
1784 PointerChecks.begin(), PointerChecks.end(),
1785 std::back_inserter(ChecksWithBounds),
1786 [&](const RuntimePointerChecking::PointerCheck &Check) {
NAKAMURA Takumi94abbbd2015-07-27 01:35:30 +00001787 PointerBounds
1788 First = expandBounds(Check.first, L, Loc, Exp, SE, PtrRtChecking),
1789 Second = expandBounds(Check.second, L, Loc, Exp, SE, PtrRtChecking);
1790 return std::make_pair(First, Second);
Adam Nemet1da7df32015-07-26 05:32:14 +00001791 });
1792
1793 return ChecksWithBounds;
1794}
1795
Adam Nemet5b0a4792015-08-11 00:09:37 +00001796std::pair<Instruction *, Instruction *> LoopAccessInfo::addRuntimeChecks(
Adam Nemet1da7df32015-07-26 05:32:14 +00001797 Instruction *Loc,
1798 const SmallVectorImpl<RuntimePointerChecking::PointerCheck> &PointerChecks)
1799 const {
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +00001800 auto *SE = PSE.getSE();
Adam Nemet1da7df32015-07-26 05:32:14 +00001801 SCEVExpander Exp(*SE, DL, "induction");
1802 auto ExpandedChecks =
1803 expandBounds(PointerChecks, TheLoop, Loc, SE, Exp, PtrRtChecking);
Adam Nemet7206d7a2015-02-06 18:31:04 +00001804
1805 LLVMContext &Ctx = Loc->getContext();
Adam Nemet7206d7a2015-02-06 18:31:04 +00001806 Instruction *FirstInst = nullptr;
Adam Nemet7206d7a2015-02-06 18:31:04 +00001807 IRBuilder<> ChkBuilder(Loc);
1808 // Our instructions might fold to a constant.
1809 Value *MemoryRuntimeCheck = nullptr;
Silviu Baranga1b6b50a2015-07-08 09:16:33 +00001810
Adam Nemet1da7df32015-07-26 05:32:14 +00001811 for (const auto &Check : ExpandedChecks) {
1812 const PointerBounds &A = Check.first, &B = Check.second;
Adam Nemetcdb791c2015-08-19 17:24:36 +00001813 // Check if two pointers (A and B) conflict where conflict is computed as:
1814 // start(A) <= end(B) && start(B) <= end(A)
Adam Nemet1da7df32015-07-26 05:32:14 +00001815 unsigned AS0 = A.Start->getType()->getPointerAddressSpace();
1816 unsigned AS1 = B.Start->getType()->getPointerAddressSpace();
Adam Nemet7206d7a2015-02-06 18:31:04 +00001817
Adam Nemet1da7df32015-07-26 05:32:14 +00001818 assert((AS0 == B.End->getType()->getPointerAddressSpace()) &&
1819 (AS1 == A.End->getType()->getPointerAddressSpace()) &&
1820 "Trying to bounds check pointers with different address spaces");
Adam Nemet7206d7a2015-02-06 18:31:04 +00001821
Adam Nemet1da7df32015-07-26 05:32:14 +00001822 Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0);
1823 Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1);
Adam Nemet7206d7a2015-02-06 18:31:04 +00001824
Adam Nemet1da7df32015-07-26 05:32:14 +00001825 Value *Start0 = ChkBuilder.CreateBitCast(A.Start, PtrArithTy0, "bc");
1826 Value *Start1 = ChkBuilder.CreateBitCast(B.Start, PtrArithTy1, "bc");
1827 Value *End0 = ChkBuilder.CreateBitCast(A.End, PtrArithTy1, "bc");
1828 Value *End1 = ChkBuilder.CreateBitCast(B.End, PtrArithTy0, "bc");
Adam Nemet7206d7a2015-02-06 18:31:04 +00001829
Adam Nemet1da7df32015-07-26 05:32:14 +00001830 Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0");
1831 FirstInst = getFirstInst(FirstInst, Cmp0, Loc);
1832 Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1");
1833 FirstInst = getFirstInst(FirstInst, Cmp1, Loc);
1834 Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
1835 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1836 if (MemoryRuntimeCheck) {
1837 IsConflict =
1838 ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict, "conflict.rdx");
Adam Nemet7206d7a2015-02-06 18:31:04 +00001839 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
Adam Nemet7206d7a2015-02-06 18:31:04 +00001840 }
Adam Nemet1da7df32015-07-26 05:32:14 +00001841 MemoryRuntimeCheck = IsConflict;
Adam Nemet7206d7a2015-02-06 18:31:04 +00001842 }
1843
Adam Nemet90fec842015-04-02 17:51:57 +00001844 if (!MemoryRuntimeCheck)
1845 return std::make_pair(nullptr, nullptr);
1846
Adam Nemet7206d7a2015-02-06 18:31:04 +00001847 // We have to do this trickery because the IRBuilder might fold the check to a
1848 // constant expression in which case there is no Instruction anchored in a
1849 // the block.
1850 Instruction *Check = BinaryOperator::CreateAnd(MemoryRuntimeCheck,
1851 ConstantInt::getTrue(Ctx));
1852 ChkBuilder.Insert(Check, "memcheck.conflict");
1853 FirstInst = getFirstInst(FirstInst, Check, Loc);
1854 return std::make_pair(FirstInst, Check);
1855}
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001856
Adam Nemet5b0a4792015-08-11 00:09:37 +00001857std::pair<Instruction *, Instruction *>
1858LoopAccessInfo::addRuntimeChecks(Instruction *Loc) const {
Adam Nemet1da7df32015-07-26 05:32:14 +00001859 if (!PtrRtChecking.Need)
1860 return std::make_pair(nullptr, nullptr);
1861
Adam Nemet5b0a4792015-08-11 00:09:37 +00001862 return addRuntimeChecks(Loc, PtrRtChecking.getChecks());
Adam Nemet1da7df32015-07-26 05:32:14 +00001863}
1864
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001865LoopAccessInfo::LoopAccessInfo(Loop *L, ScalarEvolution *SE,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001866 const DataLayout &DL,
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001867 const TargetLibraryInfo *TLI, AliasAnalysis *AA,
Adam Nemete2b885c2015-04-23 20:09:20 +00001868 DominatorTree *DT, LoopInfo *LI,
Adam Nemet8bc61df2015-02-24 00:41:59 +00001869 const ValueToValueMap &Strides)
Silviu Barangaea63a7f2016-02-08 17:02:45 +00001870 : PSE(*SE, *L), PtrRtChecking(SE), DepChecker(PSE, L), TheLoop(L), DL(DL),
Adam Nemet7cdebac2015-07-14 22:32:44 +00001871 TLI(TLI), AA(AA), DT(DT), LI(LI), NumLoads(0), NumStores(0),
Adam Nemetce482502015-04-08 17:48:40 +00001872 MaxSafeDepDistBytes(-1U), CanVecMem(false),
1873 StoreToLoopInvariantAddress(false) {
Adam Nemet929c38e2015-02-19 19:15:10 +00001874 if (canAnalyzeLoop())
1875 analyzeLoop(Strides);
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001876}
1877
Adam Nemete91cc6e2015-02-19 19:15:19 +00001878void LoopAccessInfo::print(raw_ostream &OS, unsigned Depth) const {
1879 if (CanVecMem) {
Adam Nemet7cdebac2015-07-14 22:32:44 +00001880 if (PtrRtChecking.Need)
Adam Nemete91cc6e2015-02-19 19:15:19 +00001881 OS.indent(Depth) << "Memory dependences are safe with run-time checks\n";
Adam Nemet26da8e92015-04-14 01:12:55 +00001882 else
1883 OS.indent(Depth) << "Memory dependences are safe\n";
Adam Nemete91cc6e2015-02-19 19:15:19 +00001884 }
1885
1886 if (Report)
1887 OS.indent(Depth) << "Report: " << Report->str() << "\n";
1888
Adam Nemeta2df7502015-11-03 21:39:52 +00001889 if (auto *Dependences = DepChecker.getDependences()) {
1890 OS.indent(Depth) << "Dependences:\n";
1891 for (auto &Dep : *Dependences) {
Adam Nemet58913d62015-03-10 17:40:43 +00001892 Dep.print(OS, Depth + 2, DepChecker.getMemoryInstructions());
1893 OS << "\n";
1894 }
1895 } else
Adam Nemeta2df7502015-11-03 21:39:52 +00001896 OS.indent(Depth) << "Too many dependences, not recorded\n";
Adam Nemete91cc6e2015-02-19 19:15:19 +00001897
1898 // List the pair of accesses need run-time checks to prove independence.
Adam Nemet7cdebac2015-07-14 22:32:44 +00001899 PtrRtChecking.print(OS, Depth);
Adam Nemete91cc6e2015-02-19 19:15:19 +00001900 OS << "\n";
Adam Nemetc3384322015-05-18 15:36:57 +00001901
1902 OS.indent(Depth) << "Store to invariant address was "
1903 << (StoreToLoopInvariantAddress ? "" : "not ")
1904 << "found in loop.\n";
Silviu Barangae3c05342015-11-02 14:41:02 +00001905
1906 OS.indent(Depth) << "SCEV assumptions:\n";
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +00001907 PSE.getUnionPredicate().print(OS, Depth);
Adam Nemete91cc6e2015-02-19 19:15:19 +00001908}
1909
Adam Nemet8bc61df2015-02-24 00:41:59 +00001910const LoopAccessInfo &
1911LoopAccessAnalysis::getInfo(Loop *L, const ValueToValueMap &Strides) {
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001912 auto &LAI = LoopAccessInfoMap[L];
1913
1914#ifndef NDEBUG
1915 assert((!LAI || LAI->NumSymbolicStrides == Strides.size()) &&
1916 "Symbolic strides changed for loop");
1917#endif
1918
1919 if (!LAI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001920 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
Silviu Barangae3c05342015-11-02 14:41:02 +00001921 LAI =
1922 llvm::make_unique<LoopAccessInfo>(L, SE, DL, TLI, AA, DT, LI, Strides);
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001923#ifndef NDEBUG
1924 LAI->NumSymbolicStrides = Strides.size();
1925#endif
1926 }
1927 return *LAI.get();
1928}
1929
Adam Nemete91cc6e2015-02-19 19:15:19 +00001930void LoopAccessAnalysis::print(raw_ostream &OS, const Module *M) const {
1931 LoopAccessAnalysis &LAA = *const_cast<LoopAccessAnalysis *>(this);
1932
Adam Nemete91cc6e2015-02-19 19:15:19 +00001933 ValueToValueMap NoSymbolicStrides;
1934
1935 for (Loop *TopLevelLoop : *LI)
1936 for (Loop *L : depth_first(TopLevelLoop)) {
1937 OS.indent(2) << L->getHeader()->getName() << ":\n";
1938 auto &LAI = LAA.getInfo(L, NoSymbolicStrides);
1939 LAI.print(OS, 4);
1940 }
1941}
1942
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001943bool LoopAccessAnalysis::runOnFunction(Function &F) {
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001944 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001945 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
1946 TLI = TLIP ? &TLIP->getTLI() : nullptr;
Chandler Carruth7b560d42015-09-09 17:55:00 +00001947 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001948 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Adam Nemete2b885c2015-04-23 20:09:20 +00001949 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001950
1951 return false;
1952}
1953
1954void LoopAccessAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001955 AU.addRequired<ScalarEvolutionWrapperPass>();
Chandler Carruth7b560d42015-09-09 17:55:00 +00001956 AU.addRequired<AAResultsWrapperPass>();
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001957 AU.addRequired<DominatorTreeWrapperPass>();
Adam Nemete91cc6e2015-02-19 19:15:19 +00001958 AU.addRequired<LoopInfoWrapperPass>();
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001959
1960 AU.setPreservesAll();
1961}
1962
1963char LoopAccessAnalysis::ID = 0;
1964static const char laa_name[] = "Loop Access Analysis";
1965#define LAA_NAME "loop-accesses"
1966
1967INITIALIZE_PASS_BEGIN(LoopAccessAnalysis, LAA_NAME, laa_name, false, true)
Chandler Carruth7b560d42015-09-09 17:55:00 +00001968INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001969INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001970INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Adam Nemete91cc6e2015-02-19 19:15:19 +00001971INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001972INITIALIZE_PASS_END(LoopAccessAnalysis, LAA_NAME, laa_name, false, true)
1973
1974namespace llvm {
1975 Pass *createLAAPass() {
1976 return new LoopAccessAnalysis();
1977 }
1978}