blob: cd30915ac0ab87e8921be5290aff03485c7c8fe1 [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 Nemet9c926572015-03-10 17:40:37 +000061/// \brief We collect interesting dependences up to this threshold.
62static cl::opt<unsigned> MaxInterestingDependence(
63 "max-interesting-dependences", cl::Hidden,
64 cl::desc("Maximum number of interesting dependences collected by "
65 "loop-access analysis (default = 100)"),
66 cl::init(100));
67
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
90const SCEV *llvm::replaceSymbolicStrideSCEV(ScalarEvolution *SE,
Adam Nemet8bc61df2015-02-24 00:41:59 +000091 const ValueToValueMap &PtrToStride,
Adam Nemet04563272015-02-01 16:56:15 +000092 Value *Ptr, Value *OrigPtr) {
93
94 const SCEV *OrigSCEV = SE->getSCEV(Ptr);
95
96 // If there is an entry in the map return the SCEV of the pointer with the
97 // symbolic stride replaced by one.
Adam Nemet8bc61df2015-02-24 00:41:59 +000098 ValueToValueMap::const_iterator SI =
99 PtrToStride.find(OrigPtr ? OrigPtr : Ptr);
Adam Nemet04563272015-02-01 16:56:15 +0000100 if (SI != PtrToStride.end()) {
101 Value *StrideVal = SI->second;
102
103 // Strip casts.
104 StrideVal = stripIntegerCast(StrideVal);
105
106 // Replace symbolic stride by one.
107 Value *One = ConstantInt::get(StrideVal->getType(), 1);
108 ValueToValueMap RewriteMap;
109 RewriteMap[StrideVal] = One;
110
111 const SCEV *ByOne =
112 SCEVParameterRewriter::rewrite(OrigSCEV, *SE, RewriteMap, true);
Adam Nemet339f42b2015-02-19 19:15:07 +0000113 DEBUG(dbgs() << "LAA: Replacing SCEV: " << *OrigSCEV << " by: " << *ByOne
Adam Nemet04563272015-02-01 16:56:15 +0000114 << "\n");
115 return ByOne;
116 }
117
118 // Otherwise, just return the SCEV of the original pointer.
119 return SE->getSCEV(Ptr);
120}
121
Adam Nemet8bc61df2015-02-24 00:41:59 +0000122void LoopAccessInfo::RuntimePointerCheck::insert(
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000123 Loop *Lp, Value *Ptr, bool WritePtr, unsigned DepSetId, unsigned ASId,
124 const ValueToValueMap &Strides) {
Adam Nemet04563272015-02-01 16:56:15 +0000125 // Get the stride replaced scev.
126 const SCEV *Sc = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
127 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
128 assert(AR && "Invalid addrec expression");
129 const SCEV *Ex = SE->getBackedgeTakenCount(Lp);
130 const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
131 Pointers.push_back(Ptr);
132 Starts.push_back(AR->getStart());
133 Ends.push_back(ScEnd);
134 IsWritePtr.push_back(WritePtr);
135 DependencySetId.push_back(DepSetId);
136 AliasSetId.push_back(ASId);
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000137 Exprs.push_back(Sc);
138}
139
140bool LoopAccessInfo::RuntimePointerCheck::needsChecking(
141 const CheckingPtrGroup &M, const CheckingPtrGroup &N,
142 const SmallVectorImpl<int> *PtrPartition) const {
143 for (unsigned I = 0, EI = M.Members.size(); EI != I; ++I)
144 for (unsigned J = 0, EJ = N.Members.size(); EJ != J; ++J)
145 if (needsChecking(M.Members[I], N.Members[J], PtrPartition))
146 return true;
147 return false;
148}
149
150/// Compare \p I and \p J and return the minimum.
151/// Return nullptr in case we couldn't find an answer.
152static const SCEV *getMinFromExprs(const SCEV *I, const SCEV *J,
153 ScalarEvolution *SE) {
154 const SCEV *Diff = SE->getMinusSCEV(J, I);
155 const SCEVConstant *C = dyn_cast<const SCEVConstant>(Diff);
156
157 if (!C)
158 return nullptr;
159 if (C->getValue()->isNegative())
160 return J;
161 return I;
162}
163
164bool LoopAccessInfo::RuntimePointerCheck::CheckingPtrGroup::addPointer(
165 unsigned Index) {
166 // Compare the starts and ends with the known minimum and maximum
167 // of this set. We need to know how we compare against the min/max
168 // of the set in order to be able to emit memchecks.
169 const SCEV *Min0 = getMinFromExprs(RtCheck.Starts[Index], Low, RtCheck.SE);
170 if (!Min0)
171 return false;
172
173 const SCEV *Min1 = getMinFromExprs(RtCheck.Ends[Index], High, RtCheck.SE);
174 if (!Min1)
175 return false;
176
177 // Update the low bound expression if we've found a new min value.
178 if (Min0 == RtCheck.Starts[Index])
179 Low = RtCheck.Starts[Index];
180
181 // Update the high bound expression if we've found a new max value.
182 if (Min1 != RtCheck.Ends[Index])
183 High = RtCheck.Ends[Index];
184
185 Members.push_back(Index);
186 return true;
187}
188
189void LoopAccessInfo::RuntimePointerCheck::groupChecks(
190 MemoryDepChecker::DepCandidates &DepCands,
191 bool UseDependencies) {
192 // We build the groups from dependency candidates equivalence classes
193 // because:
194 // - We know that pointers in the same equivalence class share
195 // the same underlying object and therefore there is a chance
196 // that we can compare pointers
197 // - We wouldn't be able to merge two pointers for which we need
198 // to emit a memcheck. The classes in DepCands are already
199 // conveniently built such that no two pointers in the same
200 // class need checking against each other.
201
202 // We use the following (greedy) algorithm to construct the groups
203 // For every pointer in the equivalence class:
204 // For each existing group:
205 // - if the difference between this pointer and the min/max bounds
206 // of the group is a constant, then make the pointer part of the
207 // group and update the min/max bounds of that group as required.
208
209 CheckingGroups.clear();
210
211 // If we don't have the dependency partitions, construct a new
212 // checking pointer group for each pointer.
213 if (!UseDependencies) {
214 for (unsigned I = 0; I < Pointers.size(); ++I)
215 CheckingGroups.push_back(CheckingPtrGroup(I, *this));
216 return;
217 }
218
219 unsigned TotalComparisons = 0;
220
221 DenseMap<Value *, unsigned> PositionMap;
222 for (unsigned Pointer = 0; Pointer < Pointers.size(); ++Pointer)
223 PositionMap[Pointers[Pointer]] = Pointer;
224
Silviu Barangace3877f2015-07-09 15:18:25 +0000225 // We need to keep track of what pointers we've already seen so we
226 // don't process them twice.
227 SmallSet<unsigned, 2> Seen;
228
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000229 // Go through all equivalence classes, get the the "pointer check groups"
Silviu Barangace3877f2015-07-09 15:18:25 +0000230 // and add them to the overall solution. We use the order in which accesses
231 // appear in 'Pointers' to enforce determinism.
232 for (unsigned I = 0; I < Pointers.size(); ++I) {
233 // We've seen this pointer before, and therefore already processed
234 // its equivalence class.
235 if (Seen.count(I))
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000236 continue;
237
Silviu Barangace3877f2015-07-09 15:18:25 +0000238 MemoryDepChecker::MemAccessInfo Access(Pointers[I], IsWritePtr[I]);
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000239
Silviu Barangace3877f2015-07-09 15:18:25 +0000240 SmallVector<CheckingPtrGroup, 2> Groups;
241 auto LeaderI = DepCands.findValue(DepCands.getLeaderValue(Access));
242
243 SmallVector<unsigned, 2> MemberIndices;
244
245 // Get all indeces of the members of this equivalence class and sort them.
246 // This will allow us to process all accesses in the order in which they
247 // were added to the RuntimePointerCheck.
248 for (auto MI = DepCands.member_begin(LeaderI), ME = DepCands.member_end();
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000249 MI != ME; ++MI) {
250 unsigned Pointer = PositionMap[MI->getPointer()];
Silviu Barangace3877f2015-07-09 15:18:25 +0000251 MemberIndices.push_back(Pointer);
252 }
253 std::sort(MemberIndices.begin(), MemberIndices.end());
254
255 for (unsigned Pointer : MemberIndices) {
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000256 bool Merged = false;
Silviu Barangace3877f2015-07-09 15:18:25 +0000257 // Mark this pointer as seen.
258 Seen.insert(Pointer);
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000259
260 // Go through all the existing sets and see if we can find one
261 // which can include this pointer.
262 for (CheckingPtrGroup &Group : Groups) {
263 // Don't perform more than a certain amount of comparisons.
264 // This should limit the cost of grouping the pointers to something
265 // reasonable. If we do end up hitting this threshold, the algorithm
266 // will create separate groups for all remaining pointers.
267 if (TotalComparisons > MemoryCheckMergeThreshold)
268 break;
269
270 TotalComparisons++;
271
272 if (Group.addPointer(Pointer)) {
273 Merged = true;
274 break;
275 }
276 }
277
278 if (!Merged)
279 // We couldn't add this pointer to any existing set or the threshold
280 // for the number of comparisons has been reached. Create a new group
281 // to hold the current pointer.
282 Groups.push_back(CheckingPtrGroup(Pointer, *this));
283 }
284
285 // We've computed the grouped checks for this partition.
286 // Save the results and continue with the next one.
287 std::copy(Groups.begin(), Groups.end(), std::back_inserter(CheckingGroups));
288 }
Adam Nemet04563272015-02-01 16:56:15 +0000289}
290
Adam Nemetec1e2bb2015-03-10 18:54:26 +0000291bool LoopAccessInfo::RuntimePointerCheck::needsChecking(
292 unsigned I, unsigned J, const SmallVectorImpl<int> *PtrPartition) const {
Adam Nemeta8945b72015-02-18 03:43:58 +0000293 // No need to check if two readonly pointers intersect.
294 if (!IsWritePtr[I] && !IsWritePtr[J])
295 return false;
296
297 // Only need to check pointers between two different dependency sets.
298 if (DependencySetId[I] == DependencySetId[J])
299 return false;
300
301 // Only need to check pointers in the same alias set.
302 if (AliasSetId[I] != AliasSetId[J])
303 return false;
304
Adam Nemetec1e2bb2015-03-10 18:54:26 +0000305 // If PtrPartition is set omit checks between pointers of the same partition.
306 // Partition number -1 means that the pointer is used in multiple partitions.
307 // In this case we can't omit the check.
308 if (PtrPartition && (*PtrPartition)[I] != -1 &&
309 (*PtrPartition)[I] == (*PtrPartition)[J])
310 return false;
311
Adam Nemeta8945b72015-02-18 03:43:58 +0000312 return true;
313}
314
Adam Nemetec1e2bb2015-03-10 18:54:26 +0000315void LoopAccessInfo::RuntimePointerCheck::print(
316 raw_ostream &OS, unsigned Depth,
317 const SmallVectorImpl<int> *PtrPartition) const {
Adam Nemete91cc6e2015-02-19 19:15:19 +0000318
319 OS.indent(Depth) << "Run-time memory checks:\n";
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000320
Adam Nemete91cc6e2015-02-19 19:15:19 +0000321 unsigned N = 0;
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000322 for (unsigned I = 0; I < CheckingGroups.size(); ++I)
323 for (unsigned J = I + 1; J < CheckingGroups.size(); ++J)
324 if (needsChecking(CheckingGroups[I], CheckingGroups[J], PtrPartition)) {
325 OS.indent(Depth) << "Check " << N++ << ":\n";
326 OS.indent(Depth + 2) << "Comparing group " << I << ":\n";
327
328 for (unsigned K = 0; K < CheckingGroups[I].Members.size(); ++K) {
329 OS.indent(Depth + 2) << *Pointers[CheckingGroups[I].Members[K]]
330 << "\n";
331 if (PtrPartition)
332 OS << " (Partition: "
333 << (*PtrPartition)[CheckingGroups[I].Members[K]] << ")"
334 << "\n";
335 }
336
337 OS.indent(Depth + 2) << "Against group " << J << ":\n";
338
339 for (unsigned K = 0; K < CheckingGroups[J].Members.size(); ++K) {
340 OS.indent(Depth + 2) << *Pointers[CheckingGroups[J].Members[K]]
341 << "\n";
342 if (PtrPartition)
343 OS << " (Partition: "
344 << (*PtrPartition)[CheckingGroups[J].Members[K]] << ")"
345 << "\n";
346 }
Adam Nemete91cc6e2015-02-19 19:15:19 +0000347 }
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000348
349 OS.indent(Depth) << "Grouped accesses:\n";
350 for (unsigned I = 0; I < CheckingGroups.size(); ++I) {
351 OS.indent(Depth + 2) << "Group " << I << ":\n";
352 OS.indent(Depth + 4) << "(Low: " << *CheckingGroups[I].Low
353 << " High: " << *CheckingGroups[I].High << ")\n";
354 for (unsigned J = 0; J < CheckingGroups[I].Members.size(); ++J) {
355 OS.indent(Depth + 6) << "Member: " << *Exprs[CheckingGroups[I].Members[J]]
356 << "\n";
357 }
358 }
Adam Nemete91cc6e2015-02-19 19:15:19 +0000359}
360
Silviu Baranga98a13712015-06-08 10:27:06 +0000361unsigned LoopAccessInfo::RuntimePointerCheck::getNumberOfChecks(
Adam Nemet51870d12015-04-07 03:35:26 +0000362 const SmallVectorImpl<int> *PtrPartition) const {
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000363
364 unsigned NumPartitions = CheckingGroups.size();
Silviu Baranga98a13712015-06-08 10:27:06 +0000365 unsigned CheckCount = 0;
Adam Nemet51870d12015-04-07 03:35:26 +0000366
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000367 for (unsigned I = 0; I < NumPartitions; ++I)
368 for (unsigned J = I + 1; J < NumPartitions; ++J)
369 if (needsChecking(CheckingGroups[I], CheckingGroups[J], PtrPartition))
Silviu Baranga98a13712015-06-08 10:27:06 +0000370 CheckCount++;
371 return CheckCount;
372}
373
374bool LoopAccessInfo::RuntimePointerCheck::needsAnyChecking(
375 const SmallVectorImpl<int> *PtrPartition) const {
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000376 unsigned NumPointers = Pointers.size();
377
378 for (unsigned I = 0; I < NumPointers; ++I)
379 for (unsigned J = I + 1; J < NumPointers; ++J)
380 if (needsChecking(I, J, PtrPartition))
381 return true;
382 return false;
Adam Nemet51870d12015-04-07 03:35:26 +0000383}
384
Adam Nemet04563272015-02-01 16:56:15 +0000385namespace {
386/// \brief Analyses memory accesses in a loop.
387///
388/// Checks whether run time pointer checks are needed and builds sets for data
389/// dependence checking.
390class AccessAnalysis {
391public:
392 /// \brief Read or write access location.
393 typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
394 typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
395
Adam Nemete2b885c2015-04-23 20:09:20 +0000396 AccessAnalysis(const DataLayout &Dl, AliasAnalysis *AA, LoopInfo *LI,
Adam Nemetdee666b2015-03-10 17:40:34 +0000397 MemoryDepChecker::DepCandidates &DA)
Adam Nemet5dc3b2c2015-07-09 06:47:18 +0000398 : DL(Dl), AST(*AA), LI(LI), DepCands(DA),
399 IsRTCheckAnalysisNeeded(false) {}
Adam Nemet04563272015-02-01 16:56:15 +0000400
401 /// \brief Register a load and whether it is only read from.
Chandler Carruthac80dc72015-06-17 07:18:54 +0000402 void addLoad(MemoryLocation &Loc, bool IsReadOnly) {
Adam Nemet04563272015-02-01 16:56:15 +0000403 Value *Ptr = const_cast<Value*>(Loc.Ptr);
Chandler Carruthecbd1682015-06-17 07:21:38 +0000404 AST.add(Ptr, MemoryLocation::UnknownSize, Loc.AATags);
Adam Nemet04563272015-02-01 16:56:15 +0000405 Accesses.insert(MemAccessInfo(Ptr, false));
406 if (IsReadOnly)
407 ReadOnlyPtr.insert(Ptr);
408 }
409
410 /// \brief Register a store.
Chandler Carruthac80dc72015-06-17 07:18:54 +0000411 void addStore(MemoryLocation &Loc) {
Adam Nemet04563272015-02-01 16:56:15 +0000412 Value *Ptr = const_cast<Value*>(Loc.Ptr);
Chandler Carruthecbd1682015-06-17 07:21:38 +0000413 AST.add(Ptr, MemoryLocation::UnknownSize, Loc.AATags);
Adam Nemet04563272015-02-01 16:56:15 +0000414 Accesses.insert(MemAccessInfo(Ptr, true));
415 }
416
417 /// \brief Check whether we can check the pointers at runtime for
Silviu Baranga98a13712015-06-08 10:27:06 +0000418 /// non-intersection. Returns true when we have 0 pointers
419 /// (a check on 0 pointers for non-intersection will always return true).
Adam Nemet30f16e12015-02-18 03:42:35 +0000420 bool canCheckPtrAtRT(LoopAccessInfo::RuntimePointerCheck &RtCheck,
Silviu Baranga98a13712015-06-08 10:27:06 +0000421 bool &NeedRTCheck, ScalarEvolution *SE, Loop *TheLoop,
422 const ValueToValueMap &Strides,
Adam Nemet04563272015-02-01 16:56:15 +0000423 bool ShouldCheckStride = false);
424
425 /// \brief Goes over all memory accesses, checks whether a RT check is needed
426 /// and builds sets of dependent accesses.
427 void buildDependenceSets() {
428 processMemAccesses();
429 }
430
Adam Nemet5dc3b2c2015-07-09 06:47:18 +0000431 /// \brief Initial processing of memory accesses determined that we need to
432 /// perform dependency checking.
433 ///
434 /// Note that this can later be cleared if we retry memcheck analysis without
435 /// dependency checking (i.e. ShouldRetryWithRuntimeCheck).
Adam Nemet04563272015-02-01 16:56:15 +0000436 bool isDependencyCheckNeeded() { return !CheckDeps.empty(); }
Adam Nemetdf3dc5b2015-05-18 15:37:03 +0000437
438 /// We decided that no dependence analysis would be used. Reset the state.
439 void resetDepChecks(MemoryDepChecker &DepChecker) {
440 CheckDeps.clear();
441 DepChecker.clearInterestingDependences();
442 }
Adam Nemet04563272015-02-01 16:56:15 +0000443
444 MemAccessInfoSet &getDependenciesToCheck() { return CheckDeps; }
445
446private:
447 typedef SetVector<MemAccessInfo> PtrAccessSet;
448
449 /// \brief Go over all memory access and check whether runtime pointer checks
Adam Nemetb41d2d32015-07-09 06:47:21 +0000450 /// are needed and build sets of dependency check candidates.
Adam Nemet04563272015-02-01 16:56:15 +0000451 void processMemAccesses();
452
453 /// Set of all accesses.
454 PtrAccessSet Accesses;
455
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000456 const DataLayout &DL;
457
Adam Nemet04563272015-02-01 16:56:15 +0000458 /// Set of accesses that need a further dependence check.
459 MemAccessInfoSet CheckDeps;
460
461 /// Set of pointers that are read only.
462 SmallPtrSet<Value*, 16> ReadOnlyPtr;
463
Adam Nemet04563272015-02-01 16:56:15 +0000464 /// An alias set tracker to partition the access set by underlying object and
465 //intrinsic property (such as TBAA metadata).
466 AliasSetTracker AST;
467
Adam Nemete2b885c2015-04-23 20:09:20 +0000468 LoopInfo *LI;
469
Adam Nemet04563272015-02-01 16:56:15 +0000470 /// Sets of potentially dependent accesses - members of one set share an
471 /// underlying pointer. The set "CheckDeps" identfies which sets really need a
472 /// dependence check.
Adam Nemetdee666b2015-03-10 17:40:34 +0000473 MemoryDepChecker::DepCandidates &DepCands;
Adam Nemet04563272015-02-01 16:56:15 +0000474
Adam Nemet5dc3b2c2015-07-09 06:47:18 +0000475 /// \brief Initial processing of memory accesses determined that we may need
476 /// to add memchecks. Perform the analysis to determine the necessary checks.
477 ///
478 /// Note that, this is different from isDependencyCheckNeeded. When we retry
479 /// memcheck analysis without dependency checking
480 /// (i.e. ShouldRetryWithRuntimeCheck), isDependencyCheckNeeded is cleared
481 /// while this remains set if we have potentially dependent accesses.
482 bool IsRTCheckAnalysisNeeded;
Adam Nemet04563272015-02-01 16:56:15 +0000483};
484
485} // end anonymous namespace
486
487/// \brief Check whether a pointer can participate in a runtime bounds check.
Adam Nemet8bc61df2015-02-24 00:41:59 +0000488static bool hasComputableBounds(ScalarEvolution *SE,
489 const ValueToValueMap &Strides, Value *Ptr) {
Adam Nemet04563272015-02-01 16:56:15 +0000490 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
491 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
492 if (!AR)
493 return false;
494
495 return AR->isAffine();
496}
497
Adam Nemet04563272015-02-01 16:56:15 +0000498bool AccessAnalysis::canCheckPtrAtRT(
Silviu Baranga98a13712015-06-08 10:27:06 +0000499 LoopAccessInfo::RuntimePointerCheck &RtCheck, bool &NeedRTCheck,
Adam Nemet8bc61df2015-02-24 00:41:59 +0000500 ScalarEvolution *SE, Loop *TheLoop, const ValueToValueMap &StridesMap,
501 bool ShouldCheckStride) {
Adam Nemet04563272015-02-01 16:56:15 +0000502 // Find pointers with computable bounds. We are going to use this information
503 // to place a runtime bound check.
504 bool CanDoRT = true;
505
Silviu Baranga98a13712015-06-08 10:27:06 +0000506 NeedRTCheck = false;
Adam Nemet5dc3b2c2015-07-09 06:47:18 +0000507 if (!IsRTCheckAnalysisNeeded) return true;
Silviu Baranga98a13712015-06-08 10:27:06 +0000508
Adam Nemet04563272015-02-01 16:56:15 +0000509 bool IsDepCheckNeeded = isDependencyCheckNeeded();
Adam Nemet04563272015-02-01 16:56:15 +0000510
511 // We assign a consecutive id to access from different alias sets.
512 // Accesses between different groups doesn't need to be checked.
513 unsigned ASId = 1;
514 for (auto &AS : AST) {
Adam Nemet424edc62015-07-08 22:58:48 +0000515 int NumReadPtrChecks = 0;
516 int NumWritePtrChecks = 0;
517
Adam Nemet04563272015-02-01 16:56:15 +0000518 // We assign consecutive id to access from different dependence sets.
519 // Accesses within the same set don't need a runtime check.
520 unsigned RunningDepId = 1;
521 DenseMap<Value *, unsigned> DepSetId;
522
523 for (auto A : AS) {
524 Value *Ptr = A.getValue();
525 bool IsWrite = Accesses.count(MemAccessInfo(Ptr, true));
526 MemAccessInfo Access(Ptr, IsWrite);
527
Adam Nemet424edc62015-07-08 22:58:48 +0000528 if (IsWrite)
529 ++NumWritePtrChecks;
530 else
531 ++NumReadPtrChecks;
532
Adam Nemet04563272015-02-01 16:56:15 +0000533 if (hasComputableBounds(SE, StridesMap, Ptr) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000534 // When we run after a failing dependency check we have to make sure
535 // we don't have wrapping pointers.
Adam Nemet04563272015-02-01 16:56:15 +0000536 (!ShouldCheckStride ||
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000537 isStridedPtr(SE, Ptr, TheLoop, StridesMap) == 1)) {
Adam Nemet04563272015-02-01 16:56:15 +0000538 // The id of the dependence set.
539 unsigned DepId;
540
541 if (IsDepCheckNeeded) {
542 Value *Leader = DepCands.getLeaderValue(Access).getPointer();
543 unsigned &LeaderId = DepSetId[Leader];
544 if (!LeaderId)
545 LeaderId = RunningDepId++;
546 DepId = LeaderId;
547 } else
548 // Each access has its own dependence set.
549 DepId = RunningDepId++;
550
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000551 RtCheck.insert(TheLoop, Ptr, IsWrite, DepId, ASId, StridesMap);
Adam Nemet04563272015-02-01 16:56:15 +0000552
Adam Nemet339f42b2015-02-19 19:15:07 +0000553 DEBUG(dbgs() << "LAA: Found a runtime check ptr:" << *Ptr << '\n');
Adam Nemet04563272015-02-01 16:56:15 +0000554 } else {
Adam Nemetf10ca272015-05-18 15:36:52 +0000555 DEBUG(dbgs() << "LAA: Can't find bounds for ptr:" << *Ptr << '\n');
Adam Nemet04563272015-02-01 16:56:15 +0000556 CanDoRT = false;
557 }
558 }
559
Adam Nemet424edc62015-07-08 22:58:48 +0000560 // If we have at least two writes or one write and a read then we need to
561 // check them. But there is no need to checks if there is only one
562 // dependence set for this alias set.
563 //
564 // Note that this function computes CanDoRT and NeedRTCheck independently.
565 // For example CanDoRT=false, NeedRTCheck=false means that we have a pointer
566 // for which we couldn't find the bounds but we don't actually need to emit
567 // any checks so it does not matter.
568 if (!(IsDepCheckNeeded && CanDoRT && RunningDepId == 2))
569 NeedRTCheck |= (NumWritePtrChecks >= 2 || (NumReadPtrChecks >= 1 &&
570 NumWritePtrChecks >= 1));
571
Adam Nemet04563272015-02-01 16:56:15 +0000572 ++ASId;
573 }
574
575 // If the pointers that we would use for the bounds comparison have different
576 // address spaces, assume the values aren't directly comparable, so we can't
577 // use them for the runtime check. We also have to assume they could
578 // overlap. In the future there should be metadata for whether address spaces
579 // are disjoint.
580 unsigned NumPointers = RtCheck.Pointers.size();
581 for (unsigned i = 0; i < NumPointers; ++i) {
582 for (unsigned j = i + 1; j < NumPointers; ++j) {
583 // Only need to check pointers between two different dependency sets.
584 if (RtCheck.DependencySetId[i] == RtCheck.DependencySetId[j])
585 continue;
586 // Only need to check pointers in the same alias set.
587 if (RtCheck.AliasSetId[i] != RtCheck.AliasSetId[j])
588 continue;
589
590 Value *PtrI = RtCheck.Pointers[i];
591 Value *PtrJ = RtCheck.Pointers[j];
592
593 unsigned ASi = PtrI->getType()->getPointerAddressSpace();
594 unsigned ASj = PtrJ->getType()->getPointerAddressSpace();
595 if (ASi != ASj) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000596 DEBUG(dbgs() << "LAA: Runtime check would require comparison between"
Adam Nemet04d41632015-02-19 19:14:34 +0000597 " different address spaces\n");
Adam Nemet04563272015-02-01 16:56:15 +0000598 return false;
599 }
600 }
601 }
602
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000603 if (NeedRTCheck && CanDoRT)
604 RtCheck.groupChecks(DepCands, IsDepCheckNeeded);
605
Adam Nemet04563272015-02-01 16:56:15 +0000606 return CanDoRT;
607}
608
609void AccessAnalysis::processMemAccesses() {
610 // We process the set twice: first we process read-write pointers, last we
611 // process read-only pointers. This allows us to skip dependence tests for
612 // read-only pointers.
613
Adam Nemet339f42b2015-02-19 19:15:07 +0000614 DEBUG(dbgs() << "LAA: Processing memory accesses...\n");
Adam Nemet04563272015-02-01 16:56:15 +0000615 DEBUG(dbgs() << " AST: "; AST.dump());
Adam Nemet9c926572015-03-10 17:40:37 +0000616 DEBUG(dbgs() << "LAA: Accesses(" << Accesses.size() << "):\n");
Adam Nemet04563272015-02-01 16:56:15 +0000617 DEBUG({
618 for (auto A : Accesses)
619 dbgs() << "\t" << *A.getPointer() << " (" <<
620 (A.getInt() ? "write" : (ReadOnlyPtr.count(A.getPointer()) ?
621 "read-only" : "read")) << ")\n";
622 });
623
624 // The AliasSetTracker has nicely partitioned our pointers by metadata
625 // compatibility and potential for underlying-object overlap. As a result, we
626 // only need to check for potential pointer dependencies within each alias
627 // set.
628 for (auto &AS : AST) {
629 // Note that both the alias-set tracker and the alias sets themselves used
630 // linked lists internally and so the iteration order here is deterministic
631 // (matching the original instruction order within each set).
632
633 bool SetHasWrite = false;
634
635 // Map of pointers to last access encountered.
636 typedef DenseMap<Value*, MemAccessInfo> UnderlyingObjToAccessMap;
637 UnderlyingObjToAccessMap ObjToLastAccess;
638
639 // Set of access to check after all writes have been processed.
640 PtrAccessSet DeferredAccesses;
641
642 // Iterate over each alias set twice, once to process read/write pointers,
643 // and then to process read-only pointers.
644 for (int SetIteration = 0; SetIteration < 2; ++SetIteration) {
645 bool UseDeferred = SetIteration > 0;
646 PtrAccessSet &S = UseDeferred ? DeferredAccesses : Accesses;
647
648 for (auto AV : AS) {
649 Value *Ptr = AV.getValue();
650
651 // For a single memory access in AliasSetTracker, Accesses may contain
652 // both read and write, and they both need to be handled for CheckDeps.
653 for (auto AC : S) {
654 if (AC.getPointer() != Ptr)
655 continue;
656
657 bool IsWrite = AC.getInt();
658
659 // If we're using the deferred access set, then it contains only
660 // reads.
661 bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite;
662 if (UseDeferred && !IsReadOnlyPtr)
663 continue;
664 // Otherwise, the pointer must be in the PtrAccessSet, either as a
665 // read or a write.
666 assert(((IsReadOnlyPtr && UseDeferred) || IsWrite ||
667 S.count(MemAccessInfo(Ptr, false))) &&
668 "Alias-set pointer not in the access set?");
669
670 MemAccessInfo Access(Ptr, IsWrite);
671 DepCands.insert(Access);
672
673 // Memorize read-only pointers for later processing and skip them in
674 // the first round (they need to be checked after we have seen all
675 // write pointers). Note: we also mark pointer that are not
676 // consecutive as "read-only" pointers (so that we check
677 // "a[b[i]] +="). Hence, we need the second check for "!IsWrite".
678 if (!UseDeferred && IsReadOnlyPtr) {
679 DeferredAccesses.insert(Access);
680 continue;
681 }
682
683 // If this is a write - check other reads and writes for conflicts. If
684 // this is a read only check other writes for conflicts (but only if
685 // there is no other write to the ptr - this is an optimization to
686 // catch "a[i] = a[i] + " without having to do a dependence check).
687 if ((IsWrite || IsReadOnlyPtr) && SetHasWrite) {
688 CheckDeps.insert(Access);
Adam Nemet5dc3b2c2015-07-09 06:47:18 +0000689 IsRTCheckAnalysisNeeded = true;
Adam Nemet04563272015-02-01 16:56:15 +0000690 }
691
692 if (IsWrite)
693 SetHasWrite = true;
694
695 // Create sets of pointers connected by a shared alias set and
696 // underlying object.
697 typedef SmallVector<Value *, 16> ValueVector;
698 ValueVector TempObjects;
Adam Nemete2b885c2015-04-23 20:09:20 +0000699
700 GetUnderlyingObjects(Ptr, TempObjects, DL, LI);
701 DEBUG(dbgs() << "Underlying objects for pointer " << *Ptr << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000702 for (Value *UnderlyingObj : TempObjects) {
703 UnderlyingObjToAccessMap::iterator Prev =
704 ObjToLastAccess.find(UnderlyingObj);
705 if (Prev != ObjToLastAccess.end())
706 DepCands.unionSets(Access, Prev->second);
707
708 ObjToLastAccess[UnderlyingObj] = Access;
Adam Nemete2b885c2015-04-23 20:09:20 +0000709 DEBUG(dbgs() << " " << *UnderlyingObj << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000710 }
711 }
712 }
713 }
714 }
715}
716
Adam Nemet04563272015-02-01 16:56:15 +0000717static bool isInBoundsGep(Value *Ptr) {
718 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
719 return GEP->isInBounds();
720 return false;
721}
722
Adam Nemetc4866d22015-06-26 17:25:43 +0000723/// \brief Return true if an AddRec pointer \p Ptr is unsigned non-wrapping,
724/// i.e. monotonically increasing/decreasing.
725static bool isNoWrapAddRec(Value *Ptr, const SCEVAddRecExpr *AR,
726 ScalarEvolution *SE, const Loop *L) {
727 // FIXME: This should probably only return true for NUW.
728 if (AR->getNoWrapFlags(SCEV::NoWrapMask))
729 return true;
730
731 // Scalar evolution does not propagate the non-wrapping flags to values that
732 // are derived from a non-wrapping induction variable because non-wrapping
733 // could be flow-sensitive.
734 //
735 // Look through the potentially overflowing instruction to try to prove
736 // non-wrapping for the *specific* value of Ptr.
737
738 // The arithmetic implied by an inbounds GEP can't overflow.
739 auto *GEP = dyn_cast<GetElementPtrInst>(Ptr);
740 if (!GEP || !GEP->isInBounds())
741 return false;
742
743 // Make sure there is only one non-const index and analyze that.
744 Value *NonConstIndex = nullptr;
745 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
746 if (!isa<ConstantInt>(*Index)) {
747 if (NonConstIndex)
748 return false;
749 NonConstIndex = *Index;
750 }
751 if (!NonConstIndex)
752 // The recurrence is on the pointer, ignore for now.
753 return false;
754
755 // The index in GEP is signed. It is non-wrapping if it's derived from a NSW
756 // AddRec using a NSW operation.
757 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(NonConstIndex))
758 if (OBO->hasNoSignedWrap() &&
759 // Assume constant for other the operand so that the AddRec can be
760 // easily found.
761 isa<ConstantInt>(OBO->getOperand(1))) {
762 auto *OpScev = SE->getSCEV(OBO->getOperand(0));
763
764 if (auto *OpAR = dyn_cast<SCEVAddRecExpr>(OpScev))
765 return OpAR->getLoop() == L && OpAR->getNoWrapFlags(SCEV::FlagNSW);
766 }
767
768 return false;
769}
770
Adam Nemet04563272015-02-01 16:56:15 +0000771/// \brief Check whether the access through \p Ptr has a constant stride.
Hao Liu32c05392015-06-08 06:39:56 +0000772int llvm::isStridedPtr(ScalarEvolution *SE, Value *Ptr, const Loop *Lp,
773 const ValueToValueMap &StridesMap) {
Adam Nemet04563272015-02-01 16:56:15 +0000774 const Type *Ty = Ptr->getType();
775 assert(Ty->isPointerTy() && "Unexpected non-ptr");
776
777 // Make sure that the pointer does not point to aggregate types.
778 const PointerType *PtrTy = cast<PointerType>(Ty);
779 if (PtrTy->getElementType()->isAggregateType()) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000780 DEBUG(dbgs() << "LAA: Bad stride - Not a pointer to a scalar type"
781 << *Ptr << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000782 return 0;
783 }
784
785 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, StridesMap, Ptr);
786
787 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
788 if (!AR) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000789 DEBUG(dbgs() << "LAA: Bad stride - Not an AddRecExpr pointer "
Adam Nemet04d41632015-02-19 19:14:34 +0000790 << *Ptr << " SCEV: " << *PtrScev << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000791 return 0;
792 }
793
794 // The accesss function must stride over the innermost loop.
795 if (Lp != AR->getLoop()) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000796 DEBUG(dbgs() << "LAA: Bad stride - Not striding over innermost loop " <<
Adam Nemet04d41632015-02-19 19:14:34 +0000797 *Ptr << " SCEV: " << *PtrScev << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000798 }
799
800 // The address calculation must not wrap. Otherwise, a dependence could be
801 // inverted.
802 // An inbounds getelementptr that is a AddRec with a unit stride
803 // cannot wrap per definition. The unit stride requirement is checked later.
804 // An getelementptr without an inbounds attribute and unit stride would have
805 // to access the pointer value "0" which is undefined behavior in address
806 // space 0, therefore we can also vectorize this case.
807 bool IsInBoundsGEP = isInBoundsGep(Ptr);
Adam Nemetc4866d22015-06-26 17:25:43 +0000808 bool IsNoWrapAddRec = isNoWrapAddRec(Ptr, AR, SE, Lp);
Adam Nemet04563272015-02-01 16:56:15 +0000809 bool IsInAddressSpaceZero = PtrTy->getAddressSpace() == 0;
810 if (!IsNoWrapAddRec && !IsInBoundsGEP && !IsInAddressSpaceZero) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000811 DEBUG(dbgs() << "LAA: Bad stride - Pointer may wrap in the address space "
Adam Nemet04d41632015-02-19 19:14:34 +0000812 << *Ptr << " SCEV: " << *PtrScev << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000813 return 0;
814 }
815
816 // Check the step is constant.
817 const SCEV *Step = AR->getStepRecurrence(*SE);
818
Adam Nemet943befe2015-07-09 00:03:22 +0000819 // Calculate the pointer stride and check if it is constant.
Adam Nemet04563272015-02-01 16:56:15 +0000820 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
821 if (!C) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000822 DEBUG(dbgs() << "LAA: Bad stride - Not a constant strided " << *Ptr <<
Adam Nemet04d41632015-02-19 19:14:34 +0000823 " SCEV: " << *PtrScev << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000824 return 0;
825 }
826
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000827 auto &DL = Lp->getHeader()->getModule()->getDataLayout();
828 int64_t Size = DL.getTypeAllocSize(PtrTy->getElementType());
Adam Nemet04563272015-02-01 16:56:15 +0000829 const APInt &APStepVal = C->getValue()->getValue();
830
831 // Huge step value - give up.
832 if (APStepVal.getBitWidth() > 64)
833 return 0;
834
835 int64_t StepVal = APStepVal.getSExtValue();
836
837 // Strided access.
838 int64_t Stride = StepVal / Size;
839 int64_t Rem = StepVal % Size;
840 if (Rem)
841 return 0;
842
843 // If the SCEV could wrap but we have an inbounds gep with a unit stride we
844 // know we can't "wrap around the address space". In case of address space
845 // zero we know that this won't happen without triggering undefined behavior.
846 if (!IsNoWrapAddRec && (IsInBoundsGEP || IsInAddressSpaceZero) &&
847 Stride != 1 && Stride != -1)
848 return 0;
849
850 return Stride;
851}
852
Adam Nemet9c926572015-03-10 17:40:37 +0000853bool MemoryDepChecker::Dependence::isSafeForVectorization(DepType Type) {
854 switch (Type) {
855 case NoDep:
856 case Forward:
857 case BackwardVectorizable:
858 return true;
859
860 case Unknown:
861 case ForwardButPreventsForwarding:
862 case Backward:
863 case BackwardVectorizableButPreventsForwarding:
864 return false;
865 }
David Majnemerd388e932015-03-10 20:23:29 +0000866 llvm_unreachable("unexpected DepType!");
Adam Nemet9c926572015-03-10 17:40:37 +0000867}
868
869bool MemoryDepChecker::Dependence::isInterestingDependence(DepType Type) {
870 switch (Type) {
871 case NoDep:
872 case Forward:
873 return false;
874
875 case BackwardVectorizable:
876 case Unknown:
877 case ForwardButPreventsForwarding:
878 case Backward:
879 case BackwardVectorizableButPreventsForwarding:
880 return true;
881 }
David Majnemerd388e932015-03-10 20:23:29 +0000882 llvm_unreachable("unexpected DepType!");
Adam Nemet9c926572015-03-10 17:40:37 +0000883}
884
885bool MemoryDepChecker::Dependence::isPossiblyBackward() const {
886 switch (Type) {
887 case NoDep:
888 case Forward:
889 case ForwardButPreventsForwarding:
890 return false;
891
892 case Unknown:
893 case BackwardVectorizable:
894 case Backward:
895 case BackwardVectorizableButPreventsForwarding:
896 return true;
897 }
David Majnemerd388e932015-03-10 20:23:29 +0000898 llvm_unreachable("unexpected DepType!");
Adam Nemet9c926572015-03-10 17:40:37 +0000899}
900
Adam Nemet04563272015-02-01 16:56:15 +0000901bool MemoryDepChecker::couldPreventStoreLoadForward(unsigned Distance,
902 unsigned TypeByteSize) {
903 // If loads occur at a distance that is not a multiple of a feasible vector
904 // factor store-load forwarding does not take place.
905 // Positive dependences might cause troubles because vectorizing them might
906 // prevent store-load forwarding making vectorized code run a lot slower.
907 // a[i] = a[i-3] ^ a[i-8];
908 // The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
909 // hence on your typical architecture store-load forwarding does not take
910 // place. Vectorizing in such cases does not make sense.
911 // Store-load forwarding distance.
912 const unsigned NumCyclesForStoreLoadThroughMemory = 8*TypeByteSize;
913 // Maximum vector factor.
Adam Nemetf219c642015-02-19 19:14:52 +0000914 unsigned MaxVFWithoutSLForwardIssues =
915 VectorizerParams::MaxVectorWidth * TypeByteSize;
Adam Nemet04d41632015-02-19 19:14:34 +0000916 if(MaxSafeDepDistBytes < MaxVFWithoutSLForwardIssues)
Adam Nemet04563272015-02-01 16:56:15 +0000917 MaxVFWithoutSLForwardIssues = MaxSafeDepDistBytes;
918
919 for (unsigned vf = 2*TypeByteSize; vf <= MaxVFWithoutSLForwardIssues;
920 vf *= 2) {
921 if (Distance % vf && Distance / vf < NumCyclesForStoreLoadThroughMemory) {
922 MaxVFWithoutSLForwardIssues = (vf >>=1);
923 break;
924 }
925 }
926
Adam Nemet04d41632015-02-19 19:14:34 +0000927 if (MaxVFWithoutSLForwardIssues< 2*TypeByteSize) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000928 DEBUG(dbgs() << "LAA: Distance " << Distance <<
Adam Nemet04d41632015-02-19 19:14:34 +0000929 " that could cause a store-load forwarding conflict\n");
Adam Nemet04563272015-02-01 16:56:15 +0000930 return true;
931 }
932
933 if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes &&
Adam Nemetf219c642015-02-19 19:14:52 +0000934 MaxVFWithoutSLForwardIssues !=
935 VectorizerParams::MaxVectorWidth * TypeByteSize)
Adam Nemet04563272015-02-01 16:56:15 +0000936 MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues;
937 return false;
938}
939
Hao Liu751004a2015-06-08 04:48:37 +0000940/// \brief Check the dependence for two accesses with the same stride \p Stride.
941/// \p Distance is the positive distance and \p TypeByteSize is type size in
942/// bytes.
943///
944/// \returns true if they are independent.
945static bool areStridedAccessesIndependent(unsigned Distance, unsigned Stride,
946 unsigned TypeByteSize) {
947 assert(Stride > 1 && "The stride must be greater than 1");
948 assert(TypeByteSize > 0 && "The type size in byte must be non-zero");
949 assert(Distance > 0 && "The distance must be non-zero");
950
951 // Skip if the distance is not multiple of type byte size.
952 if (Distance % TypeByteSize)
953 return false;
954
955 unsigned ScaledDist = Distance / TypeByteSize;
956
957 // No dependence if the scaled distance is not multiple of the stride.
958 // E.g.
959 // for (i = 0; i < 1024 ; i += 4)
960 // A[i+2] = A[i] + 1;
961 //
962 // Two accesses in memory (scaled distance is 2, stride is 4):
963 // | A[0] | | | | A[4] | | | |
964 // | | | A[2] | | | | A[6] | |
965 //
966 // E.g.
967 // for (i = 0; i < 1024 ; i += 3)
968 // A[i+4] = A[i] + 1;
969 //
970 // Two accesses in memory (scaled distance is 4, stride is 3):
971 // | A[0] | | | A[3] | | | A[6] | | |
972 // | | | | | A[4] | | | A[7] | |
973 return ScaledDist % Stride;
974}
975
Adam Nemet9c926572015-03-10 17:40:37 +0000976MemoryDepChecker::Dependence::DepType
977MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
978 const MemAccessInfo &B, unsigned BIdx,
979 const ValueToValueMap &Strides) {
Adam Nemet04563272015-02-01 16:56:15 +0000980 assert (AIdx < BIdx && "Must pass arguments in program order");
981
982 Value *APtr = A.getPointer();
983 Value *BPtr = B.getPointer();
984 bool AIsWrite = A.getInt();
985 bool BIsWrite = B.getInt();
986
987 // Two reads are independent.
988 if (!AIsWrite && !BIsWrite)
Adam Nemet9c926572015-03-10 17:40:37 +0000989 return Dependence::NoDep;
Adam Nemet04563272015-02-01 16:56:15 +0000990
991 // We cannot check pointers in different address spaces.
992 if (APtr->getType()->getPointerAddressSpace() !=
993 BPtr->getType()->getPointerAddressSpace())
Adam Nemet9c926572015-03-10 17:40:37 +0000994 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +0000995
996 const SCEV *AScev = replaceSymbolicStrideSCEV(SE, Strides, APtr);
997 const SCEV *BScev = replaceSymbolicStrideSCEV(SE, Strides, BPtr);
998
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000999 int StrideAPtr = isStridedPtr(SE, APtr, InnermostLoop, Strides);
1000 int StrideBPtr = isStridedPtr(SE, BPtr, InnermostLoop, Strides);
Adam Nemet04563272015-02-01 16:56:15 +00001001
1002 const SCEV *Src = AScev;
1003 const SCEV *Sink = BScev;
1004
1005 // If the induction step is negative we have to invert source and sink of the
1006 // dependence.
1007 if (StrideAPtr < 0) {
1008 //Src = BScev;
1009 //Sink = AScev;
1010 std::swap(APtr, BPtr);
1011 std::swap(Src, Sink);
1012 std::swap(AIsWrite, BIsWrite);
1013 std::swap(AIdx, BIdx);
1014 std::swap(StrideAPtr, StrideBPtr);
1015 }
1016
1017 const SCEV *Dist = SE->getMinusSCEV(Sink, Src);
1018
Adam Nemet339f42b2015-02-19 19:15:07 +00001019 DEBUG(dbgs() << "LAA: Src Scev: " << *Src << "Sink Scev: " << *Sink
Adam Nemet04d41632015-02-19 19:14:34 +00001020 << "(Induction step: " << StrideAPtr << ")\n");
Adam Nemet339f42b2015-02-19 19:15:07 +00001021 DEBUG(dbgs() << "LAA: Distance for " << *InstMap[AIdx] << " to "
Adam Nemet04d41632015-02-19 19:14:34 +00001022 << *InstMap[BIdx] << ": " << *Dist << "\n");
Adam Nemet04563272015-02-01 16:56:15 +00001023
Adam Nemet943befe2015-07-09 00:03:22 +00001024 // Need accesses with constant stride. We don't want to vectorize
Adam Nemet04563272015-02-01 16:56:15 +00001025 // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in
1026 // the address space.
1027 if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){
Adam Nemet943befe2015-07-09 00:03:22 +00001028 DEBUG(dbgs() << "Pointer access with non-constant stride\n");
Adam Nemet9c926572015-03-10 17:40:37 +00001029 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +00001030 }
1031
1032 const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist);
1033 if (!C) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001034 DEBUG(dbgs() << "LAA: Dependence because of non-constant distance\n");
Adam Nemet04563272015-02-01 16:56:15 +00001035 ShouldRetryWithRuntimeCheck = true;
Adam Nemet9c926572015-03-10 17:40:37 +00001036 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +00001037 }
1038
1039 Type *ATy = APtr->getType()->getPointerElementType();
1040 Type *BTy = BPtr->getType()->getPointerElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001041 auto &DL = InnermostLoop->getHeader()->getModule()->getDataLayout();
1042 unsigned TypeByteSize = DL.getTypeAllocSize(ATy);
Adam Nemet04563272015-02-01 16:56:15 +00001043
1044 // Negative distances are not plausible dependencies.
1045 const APInt &Val = C->getValue()->getValue();
1046 if (Val.isNegative()) {
1047 bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
1048 if (IsTrueDataDependence &&
1049 (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) ||
1050 ATy != BTy))
Adam Nemet9c926572015-03-10 17:40:37 +00001051 return Dependence::ForwardButPreventsForwarding;
Adam Nemet04563272015-02-01 16:56:15 +00001052
Adam Nemet339f42b2015-02-19 19:15:07 +00001053 DEBUG(dbgs() << "LAA: Dependence is negative: NoDep\n");
Adam Nemet9c926572015-03-10 17:40:37 +00001054 return Dependence::Forward;
Adam Nemet04563272015-02-01 16:56:15 +00001055 }
1056
1057 // Write to the same location with the same size.
1058 // Could be improved to assert type sizes are the same (i32 == float, etc).
1059 if (Val == 0) {
1060 if (ATy == BTy)
Adam Nemet9c926572015-03-10 17:40:37 +00001061 return Dependence::NoDep;
Adam Nemet339f42b2015-02-19 19:15:07 +00001062 DEBUG(dbgs() << "LAA: Zero dependence difference but different types\n");
Adam Nemet9c926572015-03-10 17:40:37 +00001063 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +00001064 }
1065
1066 assert(Val.isStrictlyPositive() && "Expect a positive value");
1067
Adam Nemet04563272015-02-01 16:56:15 +00001068 if (ATy != BTy) {
Adam Nemet04d41632015-02-19 19:14:34 +00001069 DEBUG(dbgs() <<
Adam Nemet339f42b2015-02-19 19:15:07 +00001070 "LAA: ReadWrite-Write positive dependency with different types\n");
Adam Nemet9c926572015-03-10 17:40:37 +00001071 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +00001072 }
1073
1074 unsigned Distance = (unsigned) Val.getZExtValue();
1075
Hao Liu751004a2015-06-08 04:48:37 +00001076 unsigned Stride = std::abs(StrideAPtr);
1077 if (Stride > 1 &&
Adam Nemet0131a562015-07-08 18:47:38 +00001078 areStridedAccessesIndependent(Distance, Stride, TypeByteSize)) {
1079 DEBUG(dbgs() << "LAA: Strided accesses are independent\n");
Hao Liu751004a2015-06-08 04:48:37 +00001080 return Dependence::NoDep;
Adam Nemet0131a562015-07-08 18:47:38 +00001081 }
Hao Liu751004a2015-06-08 04:48:37 +00001082
Adam Nemet04563272015-02-01 16:56:15 +00001083 // Bail out early if passed-in parameters make vectorization not feasible.
Adam Nemetf219c642015-02-19 19:14:52 +00001084 unsigned ForcedFactor = (VectorizerParams::VectorizationFactor ?
1085 VectorizerParams::VectorizationFactor : 1);
1086 unsigned ForcedUnroll = (VectorizerParams::VectorizationInterleave ?
1087 VectorizerParams::VectorizationInterleave : 1);
Hao Liu751004a2015-06-08 04:48:37 +00001088 // The minimum number of iterations for a vectorized/unrolled version.
1089 unsigned MinNumIter = std::max(ForcedFactor * ForcedUnroll, 2U);
Adam Nemet04563272015-02-01 16:56:15 +00001090
Hao Liu751004a2015-06-08 04:48:37 +00001091 // It's not vectorizable if the distance is smaller than the minimum distance
1092 // needed for a vectroized/unrolled version. Vectorizing one iteration in
1093 // front needs TypeByteSize * Stride. Vectorizing the last iteration needs
1094 // TypeByteSize (No need to plus the last gap distance).
1095 //
1096 // E.g. Assume one char is 1 byte in memory and one int is 4 bytes.
1097 // foo(int *A) {
1098 // int *B = (int *)((char *)A + 14);
1099 // for (i = 0 ; i < 1024 ; i += 2)
1100 // B[i] = A[i] + 1;
1101 // }
1102 //
1103 // Two accesses in memory (stride is 2):
1104 // | A[0] | | A[2] | | A[4] | | A[6] | |
1105 // | B[0] | | B[2] | | B[4] |
1106 //
1107 // Distance needs for vectorizing iterations except the last iteration:
1108 // 4 * 2 * (MinNumIter - 1). Distance needs for the last iteration: 4.
1109 // So the minimum distance needed is: 4 * 2 * (MinNumIter - 1) + 4.
1110 //
1111 // If MinNumIter is 2, it is vectorizable as the minimum distance needed is
1112 // 12, which is less than distance.
1113 //
1114 // If MinNumIter is 4 (Say if a user forces the vectorization factor to be 4),
1115 // the minimum distance needed is 28, which is greater than distance. It is
1116 // not safe to do vectorization.
1117 unsigned MinDistanceNeeded =
1118 TypeByteSize * Stride * (MinNumIter - 1) + TypeByteSize;
1119 if (MinDistanceNeeded > Distance) {
1120 DEBUG(dbgs() << "LAA: Failure because of positive distance " << Distance
1121 << '\n');
1122 return Dependence::Backward;
1123 }
1124
1125 // Unsafe if the minimum distance needed is greater than max safe distance.
1126 if (MinDistanceNeeded > MaxSafeDepDistBytes) {
1127 DEBUG(dbgs() << "LAA: Failure because it needs at least "
1128 << MinDistanceNeeded << " size in bytes");
Adam Nemet9c926572015-03-10 17:40:37 +00001129 return Dependence::Backward;
Adam Nemet04563272015-02-01 16:56:15 +00001130 }
1131
Adam Nemet9cc0c392015-02-26 17:58:48 +00001132 // Positive distance bigger than max vectorization factor.
Hao Liu751004a2015-06-08 04:48:37 +00001133 // FIXME: Should use max factor instead of max distance in bytes, which could
1134 // not handle different types.
1135 // E.g. Assume one char is 1 byte in memory and one int is 4 bytes.
1136 // void foo (int *A, char *B) {
1137 // for (unsigned i = 0; i < 1024; i++) {
1138 // A[i+2] = A[i] + 1;
1139 // B[i+2] = B[i] + 1;
1140 // }
1141 // }
1142 //
1143 // This case is currently unsafe according to the max safe distance. If we
1144 // analyze the two accesses on array B, the max safe dependence distance
1145 // is 2. Then we analyze the accesses on array A, the minimum distance needed
1146 // is 8, which is less than 2 and forbidden vectorization, But actually
1147 // both A and B could be vectorized by 2 iterations.
1148 MaxSafeDepDistBytes =
1149 Distance < MaxSafeDepDistBytes ? Distance : MaxSafeDepDistBytes;
Adam Nemet04563272015-02-01 16:56:15 +00001150
1151 bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
1152 if (IsTrueDataDependence &&
1153 couldPreventStoreLoadForward(Distance, TypeByteSize))
Adam Nemet9c926572015-03-10 17:40:37 +00001154 return Dependence::BackwardVectorizableButPreventsForwarding;
Adam Nemet04563272015-02-01 16:56:15 +00001155
Hao Liu751004a2015-06-08 04:48:37 +00001156 DEBUG(dbgs() << "LAA: Positive distance " << Val.getSExtValue()
1157 << " with max VF = "
1158 << MaxSafeDepDistBytes / (TypeByteSize * Stride) << '\n');
Adam Nemet04563272015-02-01 16:56:15 +00001159
Adam Nemet9c926572015-03-10 17:40:37 +00001160 return Dependence::BackwardVectorizable;
Adam Nemet04563272015-02-01 16:56:15 +00001161}
1162
Adam Nemetdee666b2015-03-10 17:40:34 +00001163bool MemoryDepChecker::areDepsSafe(DepCandidates &AccessSets,
Adam Nemet04563272015-02-01 16:56:15 +00001164 MemAccessInfoSet &CheckDeps,
Adam Nemet8bc61df2015-02-24 00:41:59 +00001165 const ValueToValueMap &Strides) {
Adam Nemet04563272015-02-01 16:56:15 +00001166
1167 MaxSafeDepDistBytes = -1U;
1168 while (!CheckDeps.empty()) {
1169 MemAccessInfo CurAccess = *CheckDeps.begin();
1170
1171 // Get the relevant memory access set.
1172 EquivalenceClasses<MemAccessInfo>::iterator I =
1173 AccessSets.findValue(AccessSets.getLeaderValue(CurAccess));
1174
1175 // Check accesses within this set.
1176 EquivalenceClasses<MemAccessInfo>::member_iterator AI, AE;
1177 AI = AccessSets.member_begin(I), AE = AccessSets.member_end();
1178
1179 // Check every access pair.
1180 while (AI != AE) {
1181 CheckDeps.erase(*AI);
1182 EquivalenceClasses<MemAccessInfo>::member_iterator OI = std::next(AI);
1183 while (OI != AE) {
1184 // Check every accessing instruction pair in program order.
1185 for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(),
1186 I1E = Accesses[*AI].end(); I1 != I1E; ++I1)
1187 for (std::vector<unsigned>::iterator I2 = Accesses[*OI].begin(),
1188 I2E = Accesses[*OI].end(); I2 != I2E; ++I2) {
Adam Nemet9c926572015-03-10 17:40:37 +00001189 auto A = std::make_pair(&*AI, *I1);
1190 auto B = std::make_pair(&*OI, *I2);
1191
1192 assert(*I1 != *I2);
1193 if (*I1 > *I2)
1194 std::swap(A, B);
1195
1196 Dependence::DepType Type =
1197 isDependent(*A.first, A.second, *B.first, B.second, Strides);
1198 SafeForVectorization &= Dependence::isSafeForVectorization(Type);
1199
1200 // Gather dependences unless we accumulated MaxInterestingDependence
1201 // dependences. In that case return as soon as we find the first
1202 // unsafe dependence. This puts a limit on this quadratic
1203 // algorithm.
1204 if (RecordInterestingDependences) {
1205 if (Dependence::isInterestingDependence(Type))
1206 InterestingDependences.push_back(
1207 Dependence(A.second, B.second, Type));
1208
1209 if (InterestingDependences.size() >= MaxInterestingDependence) {
1210 RecordInterestingDependences = false;
1211 InterestingDependences.clear();
1212 DEBUG(dbgs() << "Too many dependences, stopped recording\n");
1213 }
1214 }
1215 if (!RecordInterestingDependences && !SafeForVectorization)
Adam Nemet04563272015-02-01 16:56:15 +00001216 return false;
1217 }
1218 ++OI;
1219 }
1220 AI++;
1221 }
1222 }
Adam Nemet9c926572015-03-10 17:40:37 +00001223
1224 DEBUG(dbgs() << "Total Interesting Dependences: "
1225 << InterestingDependences.size() << "\n");
1226 return SafeForVectorization;
Adam Nemet04563272015-02-01 16:56:15 +00001227}
1228
Adam Nemetec1e2bb2015-03-10 18:54:26 +00001229SmallVector<Instruction *, 4>
1230MemoryDepChecker::getInstructionsForAccess(Value *Ptr, bool isWrite) const {
1231 MemAccessInfo Access(Ptr, isWrite);
1232 auto &IndexVector = Accesses.find(Access)->second;
1233
1234 SmallVector<Instruction *, 4> Insts;
1235 std::transform(IndexVector.begin(), IndexVector.end(),
1236 std::back_inserter(Insts),
1237 [&](unsigned Idx) { return this->InstMap[Idx]; });
1238 return Insts;
1239}
1240
Adam Nemet58913d62015-03-10 17:40:43 +00001241const char *MemoryDepChecker::Dependence::DepName[] = {
1242 "NoDep", "Unknown", "Forward", "ForwardButPreventsForwarding", "Backward",
1243 "BackwardVectorizable", "BackwardVectorizableButPreventsForwarding"};
1244
1245void MemoryDepChecker::Dependence::print(
1246 raw_ostream &OS, unsigned Depth,
1247 const SmallVectorImpl<Instruction *> &Instrs) const {
1248 OS.indent(Depth) << DepName[Type] << ":\n";
1249 OS.indent(Depth + 2) << *Instrs[Source] << " -> \n";
1250 OS.indent(Depth + 2) << *Instrs[Destination] << "\n";
1251}
1252
Adam Nemet929c38e2015-02-19 19:15:10 +00001253bool LoopAccessInfo::canAnalyzeLoop() {
Adam Nemet8dcb3b62015-04-17 22:43:10 +00001254 // We need to have a loop header.
1255 DEBUG(dbgs() << "LAA: Found a loop: " <<
1256 TheLoop->getHeader()->getName() << '\n');
1257
Adam Nemet929c38e2015-02-19 19:15:10 +00001258 // We can only analyze innermost loops.
1259 if (!TheLoop->empty()) {
Adam Nemet8dcb3b62015-04-17 22:43:10 +00001260 DEBUG(dbgs() << "LAA: loop is not the innermost loop\n");
Adam Nemet2bd6e982015-02-19 19:15:15 +00001261 emitAnalysis(LoopAccessReport() << "loop is not the innermost loop");
Adam Nemet929c38e2015-02-19 19:15:10 +00001262 return false;
1263 }
1264
1265 // We must have a single backedge.
1266 if (TheLoop->getNumBackEdges() != 1) {
Adam Nemet8dcb3b62015-04-17 22:43:10 +00001267 DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n");
Adam Nemet929c38e2015-02-19 19:15:10 +00001268 emitAnalysis(
Adam Nemet2bd6e982015-02-19 19:15:15 +00001269 LoopAccessReport() <<
Adam Nemet929c38e2015-02-19 19:15:10 +00001270 "loop control flow is not understood by analyzer");
1271 return false;
1272 }
1273
1274 // We must have a single exiting block.
1275 if (!TheLoop->getExitingBlock()) {
Adam Nemet8dcb3b62015-04-17 22:43:10 +00001276 DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n");
Adam Nemet929c38e2015-02-19 19:15:10 +00001277 emitAnalysis(
Adam Nemet2bd6e982015-02-19 19:15:15 +00001278 LoopAccessReport() <<
Adam Nemet929c38e2015-02-19 19:15:10 +00001279 "loop control flow is not understood by analyzer");
1280 return false;
1281 }
1282
1283 // We only handle bottom-tested loops, i.e. loop in which the condition is
1284 // checked at the end of each iteration. With that we can assume that all
1285 // instructions in the loop are executed the same number of times.
1286 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
Adam Nemet8dcb3b62015-04-17 22:43:10 +00001287 DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n");
Adam Nemet929c38e2015-02-19 19:15:10 +00001288 emitAnalysis(
Adam Nemet2bd6e982015-02-19 19:15:15 +00001289 LoopAccessReport() <<
Adam Nemet929c38e2015-02-19 19:15:10 +00001290 "loop control flow is not understood by analyzer");
1291 return false;
1292 }
1293
Adam Nemet929c38e2015-02-19 19:15:10 +00001294 // ScalarEvolution needs to be able to find the exit count.
1295 const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop);
1296 if (ExitCount == SE->getCouldNotCompute()) {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001297 emitAnalysis(LoopAccessReport() <<
Adam Nemet929c38e2015-02-19 19:15:10 +00001298 "could not determine number of loop iterations");
1299 DEBUG(dbgs() << "LAA: SCEV could not compute the loop exit count.\n");
1300 return false;
1301 }
1302
1303 return true;
1304}
1305
Adam Nemet8bc61df2015-02-24 00:41:59 +00001306void LoopAccessInfo::analyzeLoop(const ValueToValueMap &Strides) {
Adam Nemet04563272015-02-01 16:56:15 +00001307
1308 typedef SmallVector<Value*, 16> ValueVector;
1309 typedef SmallPtrSet<Value*, 16> ValueSet;
1310
1311 // Holds the Load and Store *instructions*.
1312 ValueVector Loads;
1313 ValueVector Stores;
1314
1315 // Holds all the different accesses in the loop.
1316 unsigned NumReads = 0;
1317 unsigned NumReadWrites = 0;
1318
1319 PtrRtCheck.Pointers.clear();
1320 PtrRtCheck.Need = false;
1321
1322 const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
Adam Nemet04563272015-02-01 16:56:15 +00001323
1324 // For each block.
1325 for (Loop::block_iterator bb = TheLoop->block_begin(),
1326 be = TheLoop->block_end(); bb != be; ++bb) {
1327
1328 // Scan the BB and collect legal loads and stores.
1329 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
1330 ++it) {
1331
1332 // If this is a load, save it. If this instruction can read from memory
1333 // but is not a load, then we quit. Notice that we don't handle function
1334 // calls that read or write.
1335 if (it->mayReadFromMemory()) {
1336 // Many math library functions read the rounding mode. We will only
1337 // vectorize a loop if it contains known function calls that don't set
1338 // the flag. Therefore, it is safe to ignore this read from memory.
1339 CallInst *Call = dyn_cast<CallInst>(it);
1340 if (Call && getIntrinsicIDForCall(Call, TLI))
1341 continue;
1342
Michael Zolotukhin9b3cf602015-03-17 19:46:50 +00001343 // If the function has an explicit vectorized counterpart, we can safely
1344 // assume that it can be vectorized.
1345 if (Call && !Call->isNoBuiltin() && Call->getCalledFunction() &&
1346 TLI->isFunctionVectorizable(Call->getCalledFunction()->getName()))
1347 continue;
1348
Adam Nemet04563272015-02-01 16:56:15 +00001349 LoadInst *Ld = dyn_cast<LoadInst>(it);
1350 if (!Ld || (!Ld->isSimple() && !IsAnnotatedParallel)) {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001351 emitAnalysis(LoopAccessReport(Ld)
Adam Nemet04563272015-02-01 16:56:15 +00001352 << "read with atomic ordering or volatile read");
Adam Nemet339f42b2015-02-19 19:15:07 +00001353 DEBUG(dbgs() << "LAA: Found a non-simple load.\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001354 CanVecMem = false;
1355 return;
Adam Nemet04563272015-02-01 16:56:15 +00001356 }
1357 NumLoads++;
1358 Loads.push_back(Ld);
1359 DepChecker.addAccess(Ld);
1360 continue;
1361 }
1362
1363 // Save 'store' instructions. Abort if other instructions write to memory.
1364 if (it->mayWriteToMemory()) {
1365 StoreInst *St = dyn_cast<StoreInst>(it);
1366 if (!St) {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001367 emitAnalysis(LoopAccessReport(it) <<
Adam Nemet04d41632015-02-19 19:14:34 +00001368 "instruction cannot be vectorized");
Adam Nemet436018c2015-02-19 19:15:00 +00001369 CanVecMem = false;
1370 return;
Adam Nemet04563272015-02-01 16:56:15 +00001371 }
1372 if (!St->isSimple() && !IsAnnotatedParallel) {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001373 emitAnalysis(LoopAccessReport(St)
Adam Nemet04563272015-02-01 16:56:15 +00001374 << "write with atomic ordering or volatile write");
Adam Nemet339f42b2015-02-19 19:15:07 +00001375 DEBUG(dbgs() << "LAA: Found a non-simple store.\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001376 CanVecMem = false;
1377 return;
Adam Nemet04563272015-02-01 16:56:15 +00001378 }
1379 NumStores++;
1380 Stores.push_back(St);
1381 DepChecker.addAccess(St);
1382 }
1383 } // Next instr.
1384 } // Next block.
1385
1386 // Now we have two lists that hold the loads and the stores.
1387 // Next, we find the pointers that they use.
1388
1389 // Check if we see any stores. If there are no stores, then we don't
1390 // care if the pointers are *restrict*.
1391 if (!Stores.size()) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001392 DEBUG(dbgs() << "LAA: Found a read-only loop!\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001393 CanVecMem = true;
1394 return;
Adam Nemet04563272015-02-01 16:56:15 +00001395 }
1396
Adam Nemetdee666b2015-03-10 17:40:34 +00001397 MemoryDepChecker::DepCandidates DependentAccesses;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001398 AccessAnalysis Accesses(TheLoop->getHeader()->getModule()->getDataLayout(),
Adam Nemete2b885c2015-04-23 20:09:20 +00001399 AA, LI, DependentAccesses);
Adam Nemet04563272015-02-01 16:56:15 +00001400
1401 // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
1402 // multiple times on the same object. If the ptr is accessed twice, once
1403 // for read and once for write, it will only appear once (on the write
1404 // list). This is okay, since we are going to check for conflicts between
1405 // writes and between reads and writes, but not between reads and reads.
1406 ValueSet Seen;
1407
1408 ValueVector::iterator I, IE;
1409 for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
1410 StoreInst *ST = cast<StoreInst>(*I);
1411 Value* Ptr = ST->getPointerOperand();
Adam Nemetce482502015-04-08 17:48:40 +00001412 // Check for store to loop invariant address.
1413 StoreToLoopInvariantAddress |= isUniform(Ptr);
Adam Nemet04563272015-02-01 16:56:15 +00001414 // If we did *not* see this pointer before, insert it to the read-write
1415 // list. At this phase it is only a 'write' list.
1416 if (Seen.insert(Ptr).second) {
1417 ++NumReadWrites;
1418
Chandler Carruthac80dc72015-06-17 07:18:54 +00001419 MemoryLocation Loc = MemoryLocation::get(ST);
Adam Nemet04563272015-02-01 16:56:15 +00001420 // The TBAA metadata could have a control dependency on the predication
1421 // condition, so we cannot rely on it when determining whether or not we
1422 // need runtime pointer checks.
Adam Nemet01abb2c2015-02-18 03:43:19 +00001423 if (blockNeedsPredication(ST->getParent(), TheLoop, DT))
Adam Nemet04563272015-02-01 16:56:15 +00001424 Loc.AATags.TBAA = nullptr;
1425
1426 Accesses.addStore(Loc);
1427 }
1428 }
1429
1430 if (IsAnnotatedParallel) {
Adam Nemet04d41632015-02-19 19:14:34 +00001431 DEBUG(dbgs()
Adam Nemet339f42b2015-02-19 19:15:07 +00001432 << "LAA: A loop annotated parallel, ignore memory dependency "
Adam Nemet04d41632015-02-19 19:14:34 +00001433 << "checks.\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001434 CanVecMem = true;
1435 return;
Adam Nemet04563272015-02-01 16:56:15 +00001436 }
1437
1438 for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
1439 LoadInst *LD = cast<LoadInst>(*I);
1440 Value* Ptr = LD->getPointerOperand();
1441 // If we did *not* see this pointer before, insert it to the
1442 // read list. If we *did* see it before, then it is already in
1443 // the read-write list. This allows us to vectorize expressions
1444 // such as A[i] += x; Because the address of A[i] is a read-write
1445 // pointer. This only works if the index of A[i] is consecutive.
1446 // If the address of i is unknown (for example A[B[i]]) then we may
1447 // read a few words, modify, and write a few words, and some of the
1448 // words may be written to the same address.
1449 bool IsReadOnlyPtr = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001450 if (Seen.insert(Ptr).second || !isStridedPtr(SE, Ptr, TheLoop, Strides)) {
Adam Nemet04563272015-02-01 16:56:15 +00001451 ++NumReads;
1452 IsReadOnlyPtr = true;
1453 }
1454
Chandler Carruthac80dc72015-06-17 07:18:54 +00001455 MemoryLocation Loc = MemoryLocation::get(LD);
Adam Nemet04563272015-02-01 16:56:15 +00001456 // The TBAA metadata could have a control dependency on the predication
1457 // condition, so we cannot rely on it when determining whether or not we
1458 // need runtime pointer checks.
Adam Nemet01abb2c2015-02-18 03:43:19 +00001459 if (blockNeedsPredication(LD->getParent(), TheLoop, DT))
Adam Nemet04563272015-02-01 16:56:15 +00001460 Loc.AATags.TBAA = nullptr;
1461
1462 Accesses.addLoad(Loc, IsReadOnlyPtr);
1463 }
1464
1465 // If we write (or read-write) to a single destination and there are no
1466 // other reads in this loop then is it safe to vectorize.
1467 if (NumReadWrites == 1 && NumReads == 0) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001468 DEBUG(dbgs() << "LAA: Found a write-only loop!\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001469 CanVecMem = true;
1470 return;
Adam Nemet04563272015-02-01 16:56:15 +00001471 }
1472
1473 // Build dependence sets and check whether we need a runtime pointer bounds
1474 // check.
1475 Accesses.buildDependenceSets();
Adam Nemet04563272015-02-01 16:56:15 +00001476
1477 // Find pointers with computable bounds. We are going to use this information
1478 // to place a runtime bound check.
Silviu Baranga98a13712015-06-08 10:27:06 +00001479 bool NeedRTCheck;
1480 bool CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck,
1481 NeedRTCheck, SE,
1482 TheLoop, Strides);
Adam Nemet04563272015-02-01 16:56:15 +00001483
Silviu Baranga98a13712015-06-08 10:27:06 +00001484 DEBUG(dbgs() << "LAA: We need to do "
1485 << PtrRtCheck.getNumberOfChecks(nullptr)
1486 << " pointer comparisons.\n");
Adam Nemet04563272015-02-01 16:56:15 +00001487
Adam Nemet949e91a2015-03-10 19:12:41 +00001488 // Check that we found the bounds for the pointer.
Adam Nemetb6dc76f2015-03-10 18:54:19 +00001489 if (CanDoRT)
Adam Nemet339f42b2015-02-19 19:15:07 +00001490 DEBUG(dbgs() << "LAA: We can perform a memory runtime check if needed.\n");
Adam Nemetb6dc76f2015-03-10 18:54:19 +00001491 else if (NeedRTCheck) {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001492 emitAnalysis(LoopAccessReport() << "cannot identify array bounds");
Adam Nemet339f42b2015-02-19 19:15:07 +00001493 DEBUG(dbgs() << "LAA: We can't vectorize because we can't find " <<
Adam Nemet04d41632015-02-19 19:14:34 +00001494 "the array bounds.\n");
Adam Nemet04563272015-02-01 16:56:15 +00001495 PtrRtCheck.reset();
Adam Nemet436018c2015-02-19 19:15:00 +00001496 CanVecMem = false;
1497 return;
Adam Nemet04563272015-02-01 16:56:15 +00001498 }
1499
1500 PtrRtCheck.Need = NeedRTCheck;
1501
Adam Nemet436018c2015-02-19 19:15:00 +00001502 CanVecMem = true;
Adam Nemet04563272015-02-01 16:56:15 +00001503 if (Accesses.isDependencyCheckNeeded()) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001504 DEBUG(dbgs() << "LAA: Checking memory dependencies\n");
Adam Nemet04563272015-02-01 16:56:15 +00001505 CanVecMem = DepChecker.areDepsSafe(
1506 DependentAccesses, Accesses.getDependenciesToCheck(), Strides);
1507 MaxSafeDepDistBytes = DepChecker.getMaxSafeDepDistBytes();
1508
1509 if (!CanVecMem && DepChecker.shouldRetryWithRuntimeCheck()) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001510 DEBUG(dbgs() << "LAA: Retrying with memory checks\n");
Adam Nemet04563272015-02-01 16:56:15 +00001511 NeedRTCheck = true;
1512
1513 // Clear the dependency checks. We assume they are not needed.
Adam Nemetdf3dc5b2015-05-18 15:37:03 +00001514 Accesses.resetDepChecks(DepChecker);
Adam Nemet04563272015-02-01 16:56:15 +00001515
1516 PtrRtCheck.reset();
1517 PtrRtCheck.Need = true;
1518
Silviu Baranga98a13712015-06-08 10:27:06 +00001519 CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NeedRTCheck, SE,
Adam Nemet04563272015-02-01 16:56:15 +00001520 TheLoop, Strides, true);
Silviu Baranga98a13712015-06-08 10:27:06 +00001521
Adam Nemet949e91a2015-03-10 19:12:41 +00001522 // Check that we found the bounds for the pointer.
Silviu Baranga98a13712015-06-08 10:27:06 +00001523 if (NeedRTCheck && !CanDoRT) {
Adam Nemetb6dc76f2015-03-10 18:54:19 +00001524 emitAnalysis(LoopAccessReport()
1525 << "cannot check memory dependencies at runtime");
1526 DEBUG(dbgs() << "LAA: Can't vectorize with memory checks\n");
1527 PtrRtCheck.reset();
1528 CanVecMem = false;
1529 return;
1530 }
1531
Adam Nemet04563272015-02-01 16:56:15 +00001532 CanVecMem = true;
1533 }
1534 }
1535
Adam Nemet4bb90a72015-03-10 21:47:39 +00001536 if (CanVecMem)
1537 DEBUG(dbgs() << "LAA: No unsafe dependent memory operations in loop. We"
1538 << (NeedRTCheck ? "" : " don't")
1539 << " need a runtime memory check.\n");
1540 else {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001541 emitAnalysis(LoopAccessReport() <<
Adam Nemet04d41632015-02-19 19:14:34 +00001542 "unsafe dependent memory operations in loop");
Adam Nemet4bb90a72015-03-10 21:47:39 +00001543 DEBUG(dbgs() << "LAA: unsafe dependent memory operations in loop\n");
1544 }
Adam Nemet04563272015-02-01 16:56:15 +00001545}
1546
Adam Nemet01abb2c2015-02-18 03:43:19 +00001547bool LoopAccessInfo::blockNeedsPredication(BasicBlock *BB, Loop *TheLoop,
1548 DominatorTree *DT) {
Adam Nemet04563272015-02-01 16:56:15 +00001549 assert(TheLoop->contains(BB) && "Unknown block used");
1550
1551 // Blocks that do not dominate the latch need predication.
1552 BasicBlock* Latch = TheLoop->getLoopLatch();
1553 return !DT->dominates(BB, Latch);
1554}
1555
Adam Nemet2bd6e982015-02-19 19:15:15 +00001556void LoopAccessInfo::emitAnalysis(LoopAccessReport &Message) {
Adam Nemetc9228532015-02-19 19:14:56 +00001557 assert(!Report && "Multiple reports generated");
1558 Report = Message;
Adam Nemet04563272015-02-01 16:56:15 +00001559}
1560
Adam Nemet57ac7662015-02-19 19:15:21 +00001561bool LoopAccessInfo::isUniform(Value *V) const {
Adam Nemet04563272015-02-01 16:56:15 +00001562 return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
1563}
Adam Nemet7206d7a2015-02-06 18:31:04 +00001564
1565// FIXME: this function is currently a duplicate of the one in
1566// LoopVectorize.cpp.
1567static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
1568 Instruction *Loc) {
1569 if (FirstInst)
1570 return FirstInst;
1571 if (Instruction *I = dyn_cast<Instruction>(V))
1572 return I->getParent() == Loc->getParent() ? I : nullptr;
1573 return nullptr;
1574}
1575
Adam Nemetec1e2bb2015-03-10 18:54:26 +00001576std::pair<Instruction *, Instruction *> LoopAccessInfo::addRuntimeCheck(
1577 Instruction *Loc, const SmallVectorImpl<int> *PtrPartition) const {
Adam Nemet7206d7a2015-02-06 18:31:04 +00001578 if (!PtrRtCheck.Need)
Adam Nemet90fec842015-04-02 17:51:57 +00001579 return std::make_pair(nullptr, nullptr);
Adam Nemet7206d7a2015-02-06 18:31:04 +00001580
Silviu Baranga1b6b50a2015-07-08 09:16:33 +00001581 SmallVector<TrackingVH<Value>, 2> Starts;
1582 SmallVector<TrackingVH<Value>, 2> Ends;
Adam Nemet7206d7a2015-02-06 18:31:04 +00001583
1584 LLVMContext &Ctx = Loc->getContext();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001585 SCEVExpander Exp(*SE, DL, "induction");
Adam Nemet7206d7a2015-02-06 18:31:04 +00001586 Instruction *FirstInst = nullptr;
1587
Silviu Baranga1b6b50a2015-07-08 09:16:33 +00001588 for (unsigned i = 0; i < PtrRtCheck.CheckingGroups.size(); ++i) {
1589 const RuntimePointerCheck::CheckingPtrGroup &CG =
1590 PtrRtCheck.CheckingGroups[i];
1591 Value *Ptr = PtrRtCheck.Pointers[CG.Members[0]];
Adam Nemet7206d7a2015-02-06 18:31:04 +00001592 const SCEV *Sc = SE->getSCEV(Ptr);
1593
1594 if (SE->isLoopInvariant(Sc, TheLoop)) {
Silviu Baranga1b6b50a2015-07-08 09:16:33 +00001595 DEBUG(dbgs() << "LAA: Adding RT check for a loop invariant ptr:" << *Ptr
1596 << "\n");
Adam Nemet7206d7a2015-02-06 18:31:04 +00001597 Starts.push_back(Ptr);
1598 Ends.push_back(Ptr);
1599 } else {
Adam Nemet7206d7a2015-02-06 18:31:04 +00001600 unsigned AS = Ptr->getType()->getPointerAddressSpace();
1601
1602 // Use this type for pointer arithmetic.
1603 Type *PtrArithTy = Type::getInt8PtrTy(Ctx, AS);
Silviu Baranga1b6b50a2015-07-08 09:16:33 +00001604 Value *Start = nullptr, *End = nullptr;
Adam Nemet7206d7a2015-02-06 18:31:04 +00001605
Silviu Baranga1b6b50a2015-07-08 09:16:33 +00001606 DEBUG(dbgs() << "LAA: Adding RT check for range:\n");
1607 Start = Exp.expandCodeFor(CG.Low, PtrArithTy, Loc);
1608 End = Exp.expandCodeFor(CG.High, PtrArithTy, Loc);
1609 DEBUG(dbgs() << "Start: " << *CG.Low << " End: " << *CG.High << "\n");
Adam Nemet7206d7a2015-02-06 18:31:04 +00001610 Starts.push_back(Start);
1611 Ends.push_back(End);
1612 }
1613 }
1614
1615 IRBuilder<> ChkBuilder(Loc);
1616 // Our instructions might fold to a constant.
1617 Value *MemoryRuntimeCheck = nullptr;
Silviu Baranga1b6b50a2015-07-08 09:16:33 +00001618 for (unsigned i = 0; i < PtrRtCheck.CheckingGroups.size(); ++i) {
1619 for (unsigned j = i + 1; j < PtrRtCheck.CheckingGroups.size(); ++j) {
1620 const RuntimePointerCheck::CheckingPtrGroup &CGI =
1621 PtrRtCheck.CheckingGroups[i];
1622 const RuntimePointerCheck::CheckingPtrGroup &CGJ =
1623 PtrRtCheck.CheckingGroups[j];
1624
1625 if (!PtrRtCheck.needsChecking(CGI, CGJ, PtrPartition))
Adam Nemet7206d7a2015-02-06 18:31:04 +00001626 continue;
1627
1628 unsigned AS0 = Starts[i]->getType()->getPointerAddressSpace();
1629 unsigned AS1 = Starts[j]->getType()->getPointerAddressSpace();
1630
1631 assert((AS0 == Ends[j]->getType()->getPointerAddressSpace()) &&
1632 (AS1 == Ends[i]->getType()->getPointerAddressSpace()) &&
1633 "Trying to bounds check pointers with different address spaces");
1634
1635 Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0);
1636 Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1);
1637
1638 Value *Start0 = ChkBuilder.CreateBitCast(Starts[i], PtrArithTy0, "bc");
1639 Value *Start1 = ChkBuilder.CreateBitCast(Starts[j], PtrArithTy1, "bc");
1640 Value *End0 = ChkBuilder.CreateBitCast(Ends[i], PtrArithTy1, "bc");
1641 Value *End1 = ChkBuilder.CreateBitCast(Ends[j], PtrArithTy0, "bc");
1642
1643 Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0");
1644 FirstInst = getFirstInst(FirstInst, Cmp0, Loc);
1645 Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1");
1646 FirstInst = getFirstInst(FirstInst, Cmp1, Loc);
1647 Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
1648 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1649 if (MemoryRuntimeCheck) {
1650 IsConflict = ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict,
1651 "conflict.rdx");
1652 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1653 }
1654 MemoryRuntimeCheck = IsConflict;
1655 }
1656 }
1657
Adam Nemet90fec842015-04-02 17:51:57 +00001658 if (!MemoryRuntimeCheck)
1659 return std::make_pair(nullptr, nullptr);
1660
Adam Nemet7206d7a2015-02-06 18:31:04 +00001661 // We have to do this trickery because the IRBuilder might fold the check to a
1662 // constant expression in which case there is no Instruction anchored in a
1663 // the block.
1664 Instruction *Check = BinaryOperator::CreateAnd(MemoryRuntimeCheck,
1665 ConstantInt::getTrue(Ctx));
1666 ChkBuilder.Insert(Check, "memcheck.conflict");
1667 FirstInst = getFirstInst(FirstInst, Check, Loc);
1668 return std::make_pair(FirstInst, Check);
1669}
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001670
1671LoopAccessInfo::LoopAccessInfo(Loop *L, ScalarEvolution *SE,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001672 const DataLayout &DL,
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001673 const TargetLibraryInfo *TLI, AliasAnalysis *AA,
Adam Nemete2b885c2015-04-23 20:09:20 +00001674 DominatorTree *DT, LoopInfo *LI,
Adam Nemet8bc61df2015-02-24 00:41:59 +00001675 const ValueToValueMap &Strides)
Silviu Baranga1b6b50a2015-07-08 09:16:33 +00001676 : PtrRtCheck(SE), DepChecker(SE, L), TheLoop(L), SE(SE), DL(DL), TLI(TLI),
1677 AA(AA), DT(DT), LI(LI), NumLoads(0), NumStores(0),
Adam Nemetce482502015-04-08 17:48:40 +00001678 MaxSafeDepDistBytes(-1U), CanVecMem(false),
1679 StoreToLoopInvariantAddress(false) {
Adam Nemet929c38e2015-02-19 19:15:10 +00001680 if (canAnalyzeLoop())
1681 analyzeLoop(Strides);
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001682}
1683
Adam Nemete91cc6e2015-02-19 19:15:19 +00001684void LoopAccessInfo::print(raw_ostream &OS, unsigned Depth) const {
1685 if (CanVecMem) {
Adam Nemet26da8e92015-04-14 01:12:55 +00001686 if (PtrRtCheck.Need)
Adam Nemete91cc6e2015-02-19 19:15:19 +00001687 OS.indent(Depth) << "Memory dependences are safe with run-time checks\n";
Adam Nemet26da8e92015-04-14 01:12:55 +00001688 else
1689 OS.indent(Depth) << "Memory dependences are safe\n";
Adam Nemete91cc6e2015-02-19 19:15:19 +00001690 }
1691
1692 if (Report)
1693 OS.indent(Depth) << "Report: " << Report->str() << "\n";
1694
Adam Nemet58913d62015-03-10 17:40:43 +00001695 if (auto *InterestingDependences = DepChecker.getInterestingDependences()) {
1696 OS.indent(Depth) << "Interesting Dependences:\n";
1697 for (auto &Dep : *InterestingDependences) {
1698 Dep.print(OS, Depth + 2, DepChecker.getMemoryInstructions());
1699 OS << "\n";
1700 }
1701 } else
1702 OS.indent(Depth) << "Too many interesting dependences, not recorded\n";
Adam Nemete91cc6e2015-02-19 19:15:19 +00001703
1704 // List the pair of accesses need run-time checks to prove independence.
1705 PtrRtCheck.print(OS, Depth);
1706 OS << "\n";
Adam Nemetc3384322015-05-18 15:36:57 +00001707
1708 OS.indent(Depth) << "Store to invariant address was "
1709 << (StoreToLoopInvariantAddress ? "" : "not ")
1710 << "found in loop.\n";
Adam Nemete91cc6e2015-02-19 19:15:19 +00001711}
1712
Adam Nemet8bc61df2015-02-24 00:41:59 +00001713const LoopAccessInfo &
1714LoopAccessAnalysis::getInfo(Loop *L, const ValueToValueMap &Strides) {
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001715 auto &LAI = LoopAccessInfoMap[L];
1716
1717#ifndef NDEBUG
1718 assert((!LAI || LAI->NumSymbolicStrides == Strides.size()) &&
1719 "Symbolic strides changed for loop");
1720#endif
1721
1722 if (!LAI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001723 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
Adam Nemete2b885c2015-04-23 20:09:20 +00001724 LAI = llvm::make_unique<LoopAccessInfo>(L, SE, DL, TLI, AA, DT, LI,
1725 Strides);
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001726#ifndef NDEBUG
1727 LAI->NumSymbolicStrides = Strides.size();
1728#endif
1729 }
1730 return *LAI.get();
1731}
1732
Adam Nemete91cc6e2015-02-19 19:15:19 +00001733void LoopAccessAnalysis::print(raw_ostream &OS, const Module *M) const {
1734 LoopAccessAnalysis &LAA = *const_cast<LoopAccessAnalysis *>(this);
1735
Adam Nemete91cc6e2015-02-19 19:15:19 +00001736 ValueToValueMap NoSymbolicStrides;
1737
1738 for (Loop *TopLevelLoop : *LI)
1739 for (Loop *L : depth_first(TopLevelLoop)) {
1740 OS.indent(2) << L->getHeader()->getName() << ":\n";
1741 auto &LAI = LAA.getInfo(L, NoSymbolicStrides);
1742 LAI.print(OS, 4);
1743 }
1744}
1745
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001746bool LoopAccessAnalysis::runOnFunction(Function &F) {
1747 SE = &getAnalysis<ScalarEvolution>();
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001748 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
1749 TLI = TLIP ? &TLIP->getTLI() : nullptr;
1750 AA = &getAnalysis<AliasAnalysis>();
1751 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Adam Nemete2b885c2015-04-23 20:09:20 +00001752 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001753
1754 return false;
1755}
1756
1757void LoopAccessAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
1758 AU.addRequired<ScalarEvolution>();
1759 AU.addRequired<AliasAnalysis>();
1760 AU.addRequired<DominatorTreeWrapperPass>();
Adam Nemete91cc6e2015-02-19 19:15:19 +00001761 AU.addRequired<LoopInfoWrapperPass>();
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001762
1763 AU.setPreservesAll();
1764}
1765
1766char LoopAccessAnalysis::ID = 0;
1767static const char laa_name[] = "Loop Access Analysis";
1768#define LAA_NAME "loop-accesses"
1769
1770INITIALIZE_PASS_BEGIN(LoopAccessAnalysis, LAA_NAME, laa_name, false, true)
1771INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
1772INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
1773INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Adam Nemete91cc6e2015-02-19 19:15:19 +00001774INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001775INITIALIZE_PASS_END(LoopAccessAnalysis, LAA_NAME, laa_name, false, true)
1776
1777namespace llvm {
1778 Pass *createLAAPass() {
1779 return new LoopAccessAnalysis();
1780 }
1781}