blob: 8c4ae93a64ffd4ce3d17e28a7df8408c45367d16 [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 Nemet7cdebac2015-07-14 22:32:44 +0000122void RuntimePointerChecking::insert(Loop *Lp, Value *Ptr, bool WritePtr,
123 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);
Silviu Baranga0e5804a2015-07-16 14:02:58 +0000130
131 const SCEV *ScStart = AR->getStart();
Adam Nemet04563272015-02-01 16:56:15 +0000132 const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
Silviu Baranga0e5804a2015-07-16 14:02:58 +0000133 const SCEV *Step = AR->getStepRecurrence(*SE);
134
135 // For expressions with negative step, the upper bound is ScStart and the
136 // lower bound is ScEnd.
137 if (const SCEVConstant *CStep = dyn_cast<const SCEVConstant>(Step)) {
138 if (CStep->getValue()->isNegative())
139 std::swap(ScStart, ScEnd);
140 } else {
141 // Fallback case: the step is not constant, but the we can still
142 // get the upper and lower bounds of the interval by using min/max
143 // expressions.
144 ScStart = SE->getUMinExpr(ScStart, ScEnd);
145 ScEnd = SE->getUMaxExpr(AR->getStart(), ScEnd);
146 }
147
148 Pointers.emplace_back(Ptr, ScStart, ScEnd, WritePtr, DepSetId, ASId, Sc);
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000149}
150
Adam Nemetbbe1f1d2015-07-27 19:38:48 +0000151SmallVector<RuntimePointerChecking::PointerCheck, 4>
152RuntimePointerChecking::generateChecks(
153 const SmallVectorImpl<int> *PtrPartition) const {
154 SmallVector<PointerCheck, 4> Checks;
155
Adam Nemet7c52e052015-07-27 19:38:50 +0000156 for (unsigned I = 0; I < CheckingGroups.size(); ++I) {
157 for (unsigned J = I + 1; J < CheckingGroups.size(); ++J) {
158 const RuntimePointerChecking::CheckingPtrGroup &CGI = CheckingGroups[I];
159 const RuntimePointerChecking::CheckingPtrGroup &CGJ = CheckingGroups[J];
Adam Nemetbbe1f1d2015-07-27 19:38:48 +0000160
161 if (needsChecking(CGI, CGJ, PtrPartition))
162 Checks.push_back(std::make_pair(&CGI, &CGJ));
163 }
164 }
165 return Checks;
166}
167
Adam Nemet7cdebac2015-07-14 22:32:44 +0000168bool RuntimePointerChecking::needsChecking(
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000169 const CheckingPtrGroup &M, const CheckingPtrGroup &N,
170 const SmallVectorImpl<int> *PtrPartition) const {
171 for (unsigned I = 0, EI = M.Members.size(); EI != I; ++I)
172 for (unsigned J = 0, EJ = N.Members.size(); EJ != J; ++J)
173 if (needsChecking(M.Members[I], N.Members[J], PtrPartition))
174 return true;
175 return false;
176}
177
178/// Compare \p I and \p J and return the minimum.
179/// Return nullptr in case we couldn't find an answer.
180static const SCEV *getMinFromExprs(const SCEV *I, const SCEV *J,
181 ScalarEvolution *SE) {
182 const SCEV *Diff = SE->getMinusSCEV(J, I);
183 const SCEVConstant *C = dyn_cast<const SCEVConstant>(Diff);
184
185 if (!C)
186 return nullptr;
187 if (C->getValue()->isNegative())
188 return J;
189 return I;
190}
191
Adam Nemet7cdebac2015-07-14 22:32:44 +0000192bool RuntimePointerChecking::CheckingPtrGroup::addPointer(unsigned Index) {
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000193 const SCEV *Start = RtCheck.Pointers[Index].Start;
194 const SCEV *End = RtCheck.Pointers[Index].End;
195
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000196 // Compare the starts and ends with the known minimum and maximum
197 // of this set. We need to know how we compare against the min/max
198 // of the set in order to be able to emit memchecks.
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000199 const SCEV *Min0 = getMinFromExprs(Start, Low, RtCheck.SE);
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000200 if (!Min0)
201 return false;
202
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000203 const SCEV *Min1 = getMinFromExprs(End, High, RtCheck.SE);
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000204 if (!Min1)
205 return false;
206
207 // Update the low bound expression if we've found a new min value.
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000208 if (Min0 == Start)
209 Low = Start;
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000210
211 // Update the high bound expression if we've found a new max value.
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000212 if (Min1 != End)
213 High = End;
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000214
215 Members.push_back(Index);
216 return true;
217}
218
Adam Nemet7cdebac2015-07-14 22:32:44 +0000219void RuntimePointerChecking::groupChecks(
220 MemoryDepChecker::DepCandidates &DepCands, bool UseDependencies) {
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000221 // We build the groups from dependency candidates equivalence classes
222 // because:
223 // - We know that pointers in the same equivalence class share
224 // the same underlying object and therefore there is a chance
225 // that we can compare pointers
226 // - We wouldn't be able to merge two pointers for which we need
227 // to emit a memcheck. The classes in DepCands are already
228 // conveniently built such that no two pointers in the same
229 // class need checking against each other.
230
231 // We use the following (greedy) algorithm to construct the groups
232 // For every pointer in the equivalence class:
233 // For each existing group:
234 // - if the difference between this pointer and the min/max bounds
235 // of the group is a constant, then make the pointer part of the
236 // group and update the min/max bounds of that group as required.
237
238 CheckingGroups.clear();
239
Silviu Baranga48250602015-07-28 13:44:08 +0000240 // If we need to check two pointers to the same underlying object
241 // with a non-constant difference, we shouldn't perform any pointer
242 // grouping with those pointers. This is because we can easily get
243 // into cases where the resulting check would return false, even when
244 // the accesses are safe.
245 //
246 // The following example shows this:
247 // for (i = 0; i < 1000; ++i)
248 // a[5000 + i * m] = a[i] + a[i + 9000]
249 //
250 // Here grouping gives a check of (5000, 5000 + 1000 * m) against
251 // (0, 10000) which is always false. However, if m is 1, there is no
252 // dependence. Not grouping the checks for a[i] and a[i + 9000] allows
253 // us to perform an accurate check in this case.
254 //
255 // The above case requires that we have an UnknownDependence between
256 // accesses to the same underlying object. This cannot happen unless
257 // ShouldRetryWithRuntimeCheck is set, and therefore UseDependencies
258 // is also false. In this case we will use the fallback path and create
259 // separate checking groups for all pointers.
260
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000261 // If we don't have the dependency partitions, construct a new
Silviu Baranga48250602015-07-28 13:44:08 +0000262 // checking pointer group for each pointer. This is also required
263 // for correctness, because in this case we can have checking between
264 // pointers to the same underlying object.
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000265 if (!UseDependencies) {
266 for (unsigned I = 0; I < Pointers.size(); ++I)
267 CheckingGroups.push_back(CheckingPtrGroup(I, *this));
268 return;
269 }
270
271 unsigned TotalComparisons = 0;
272
273 DenseMap<Value *, unsigned> PositionMap;
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000274 for (unsigned Index = 0; Index < Pointers.size(); ++Index)
275 PositionMap[Pointers[Index].PointerValue] = Index;
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000276
Silviu Barangace3877f2015-07-09 15:18:25 +0000277 // We need to keep track of what pointers we've already seen so we
278 // don't process them twice.
279 SmallSet<unsigned, 2> Seen;
280
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000281 // Go through all equivalence classes, get the the "pointer check groups"
Silviu Barangace3877f2015-07-09 15:18:25 +0000282 // and add them to the overall solution. We use the order in which accesses
283 // appear in 'Pointers' to enforce determinism.
284 for (unsigned I = 0; I < Pointers.size(); ++I) {
285 // We've seen this pointer before, and therefore already processed
286 // its equivalence class.
287 if (Seen.count(I))
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000288 continue;
289
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000290 MemoryDepChecker::MemAccessInfo Access(Pointers[I].PointerValue,
291 Pointers[I].IsWritePtr);
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000292
Silviu Barangace3877f2015-07-09 15:18:25 +0000293 SmallVector<CheckingPtrGroup, 2> Groups;
294 auto LeaderI = DepCands.findValue(DepCands.getLeaderValue(Access));
295
Silviu Barangaa647c302015-07-13 14:48:24 +0000296 // Because DepCands is constructed by visiting accesses in the order in
297 // which they appear in alias sets (which is deterministic) and the
298 // iteration order within an equivalence class member is only dependent on
299 // the order in which unions and insertions are performed on the
300 // equivalence class, the iteration order is deterministic.
Silviu Barangace3877f2015-07-09 15:18:25 +0000301 for (auto MI = DepCands.member_begin(LeaderI), ME = DepCands.member_end();
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000302 MI != ME; ++MI) {
303 unsigned Pointer = PositionMap[MI->getPointer()];
304 bool Merged = false;
Silviu Barangace3877f2015-07-09 15:18:25 +0000305 // Mark this pointer as seen.
306 Seen.insert(Pointer);
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000307
308 // Go through all the existing sets and see if we can find one
309 // which can include this pointer.
310 for (CheckingPtrGroup &Group : Groups) {
311 // Don't perform more than a certain amount of comparisons.
312 // This should limit the cost of grouping the pointers to something
313 // reasonable. If we do end up hitting this threshold, the algorithm
314 // will create separate groups for all remaining pointers.
315 if (TotalComparisons > MemoryCheckMergeThreshold)
316 break;
317
318 TotalComparisons++;
319
320 if (Group.addPointer(Pointer)) {
321 Merged = true;
322 break;
323 }
324 }
325
326 if (!Merged)
327 // We couldn't add this pointer to any existing set or the threshold
328 // for the number of comparisons has been reached. Create a new group
329 // to hold the current pointer.
330 Groups.push_back(CheckingPtrGroup(Pointer, *this));
331 }
332
333 // We've computed the grouped checks for this partition.
334 // Save the results and continue with the next one.
335 std::copy(Groups.begin(), Groups.end(), std::back_inserter(CheckingGroups));
336 }
Adam Nemet04563272015-02-01 16:56:15 +0000337}
338
Adam Nemet041e6de2015-07-16 02:48:05 +0000339bool RuntimePointerChecking::arePointersInSamePartition(
340 const SmallVectorImpl<int> &PtrToPartition, unsigned PtrIdx1,
341 unsigned PtrIdx2) {
342 return (PtrToPartition[PtrIdx1] != -1 &&
343 PtrToPartition[PtrIdx1] == PtrToPartition[PtrIdx2]);
344}
345
Adam Nemet7cdebac2015-07-14 22:32:44 +0000346bool RuntimePointerChecking::needsChecking(
Adam Nemetec1e2bb2015-03-10 18:54:26 +0000347 unsigned I, unsigned J, const SmallVectorImpl<int> *PtrPartition) const {
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000348 const PointerInfo &PointerI = Pointers[I];
349 const PointerInfo &PointerJ = Pointers[J];
350
Adam Nemeta8945b72015-02-18 03:43:58 +0000351 // No need to check if two readonly pointers intersect.
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000352 if (!PointerI.IsWritePtr && !PointerJ.IsWritePtr)
Adam Nemeta8945b72015-02-18 03:43:58 +0000353 return false;
354
355 // Only need to check pointers between two different dependency sets.
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000356 if (PointerI.DependencySetId == PointerJ.DependencySetId)
Adam Nemeta8945b72015-02-18 03:43:58 +0000357 return false;
358
359 // Only need to check pointers in the same alias set.
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000360 if (PointerI.AliasSetId != PointerJ.AliasSetId)
Adam Nemeta8945b72015-02-18 03:43:58 +0000361 return false;
362
Adam Nemetec1e2bb2015-03-10 18:54:26 +0000363 // If PtrPartition is set omit checks between pointers of the same partition.
Adam Nemet041e6de2015-07-16 02:48:05 +0000364 if (PtrPartition && arePointersInSamePartition(*PtrPartition, I, J))
Adam Nemetec1e2bb2015-03-10 18:54:26 +0000365 return false;
366
Adam Nemeta8945b72015-02-18 03:43:58 +0000367 return true;
368}
369
Adam Nemet54f0b832015-07-27 23:54:41 +0000370void RuntimePointerChecking::printChecks(
371 raw_ostream &OS, const SmallVectorImpl<PointerCheck> &Checks,
372 unsigned Depth) const {
373 unsigned N = 0;
374 for (const auto &Check : Checks) {
375 const auto &First = Check.first->Members, &Second = Check.second->Members;
376
377 OS.indent(Depth) << "Check " << N++ << ":\n";
378
379 OS.indent(Depth + 2) << "Comparing group (" << Check.first << "):\n";
380 for (unsigned K = 0; K < First.size(); ++K)
381 OS.indent(Depth + 2) << *Pointers[First[K]].PointerValue << "\n";
382
383 OS.indent(Depth + 2) << "Against group (" << Check.second << "):\n";
384 for (unsigned K = 0; K < Second.size(); ++K)
385 OS.indent(Depth + 2) << *Pointers[Second[K]].PointerValue << "\n";
386 }
387}
388
Adam Nemet7cdebac2015-07-14 22:32:44 +0000389void RuntimePointerChecking::print(
Adam Nemetec1e2bb2015-03-10 18:54:26 +0000390 raw_ostream &OS, unsigned Depth,
391 const SmallVectorImpl<int> *PtrPartition) const {
Adam Nemete91cc6e2015-02-19 19:15:19 +0000392
393 OS.indent(Depth) << "Run-time memory checks:\n";
Adam Nemet54f0b832015-07-27 23:54:41 +0000394 printChecks(OS, generateChecks(PtrPartition), Depth);
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000395
396 OS.indent(Depth) << "Grouped accesses:\n";
397 for (unsigned I = 0; I < CheckingGroups.size(); ++I) {
Adam Nemet54f0b832015-07-27 23:54:41 +0000398 const auto &CG = CheckingGroups[I];
399
400 OS.indent(Depth + 2) << "Group " << &CG << ":\n";
401 OS.indent(Depth + 4) << "(Low: " << *CG.Low << " High: " << *CG.High
402 << ")\n";
403 for (unsigned J = 0; J < CG.Members.size(); ++J) {
404 OS.indent(Depth + 6) << "Member: " << *Pointers[CG.Members[J]].Expr
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000405 << "\n";
406 }
407 }
Adam Nemete91cc6e2015-02-19 19:15:19 +0000408}
409
Adam Nemet7cdebac2015-07-14 22:32:44 +0000410unsigned RuntimePointerChecking::getNumberOfChecks(
Adam Nemet51870d12015-04-07 03:35:26 +0000411 const SmallVectorImpl<int> *PtrPartition) const {
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000412
413 unsigned NumPartitions = CheckingGroups.size();
Silviu Baranga98a13712015-06-08 10:27:06 +0000414 unsigned CheckCount = 0;
Adam Nemet51870d12015-04-07 03:35:26 +0000415
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000416 for (unsigned I = 0; I < NumPartitions; ++I)
417 for (unsigned J = I + 1; J < NumPartitions; ++J)
418 if (needsChecking(CheckingGroups[I], CheckingGroups[J], PtrPartition))
Silviu Baranga98a13712015-06-08 10:27:06 +0000419 CheckCount++;
420 return CheckCount;
421}
422
Adam Nemet04563272015-02-01 16:56:15 +0000423namespace {
424/// \brief Analyses memory accesses in a loop.
425///
426/// Checks whether run time pointer checks are needed and builds sets for data
427/// dependence checking.
428class AccessAnalysis {
429public:
430 /// \brief Read or write access location.
431 typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
432 typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
433
Adam Nemete2b885c2015-04-23 20:09:20 +0000434 AccessAnalysis(const DataLayout &Dl, AliasAnalysis *AA, LoopInfo *LI,
Adam Nemetdee666b2015-03-10 17:40:34 +0000435 MemoryDepChecker::DepCandidates &DA)
Adam Nemet5dc3b2c2015-07-09 06:47:18 +0000436 : DL(Dl), AST(*AA), LI(LI), DepCands(DA),
437 IsRTCheckAnalysisNeeded(false) {}
Adam Nemet04563272015-02-01 16:56:15 +0000438
439 /// \brief Register a load and whether it is only read from.
Chandler Carruthac80dc72015-06-17 07:18:54 +0000440 void addLoad(MemoryLocation &Loc, bool IsReadOnly) {
Adam Nemet04563272015-02-01 16:56:15 +0000441 Value *Ptr = const_cast<Value*>(Loc.Ptr);
Chandler Carruthecbd1682015-06-17 07:21:38 +0000442 AST.add(Ptr, MemoryLocation::UnknownSize, Loc.AATags);
Adam Nemet04563272015-02-01 16:56:15 +0000443 Accesses.insert(MemAccessInfo(Ptr, false));
444 if (IsReadOnly)
445 ReadOnlyPtr.insert(Ptr);
446 }
447
448 /// \brief Register a store.
Chandler Carruthac80dc72015-06-17 07:18:54 +0000449 void addStore(MemoryLocation &Loc) {
Adam Nemet04563272015-02-01 16:56:15 +0000450 Value *Ptr = const_cast<Value*>(Loc.Ptr);
Chandler Carruthecbd1682015-06-17 07:21:38 +0000451 AST.add(Ptr, MemoryLocation::UnknownSize, Loc.AATags);
Adam Nemet04563272015-02-01 16:56:15 +0000452 Accesses.insert(MemAccessInfo(Ptr, true));
453 }
454
455 /// \brief Check whether we can check the pointers at runtime for
Adam Nemetee614742015-07-09 22:17:38 +0000456 /// non-intersection.
457 ///
458 /// Returns true if we need no check or if we do and we can generate them
459 /// (i.e. the pointers have computable bounds).
Adam Nemet7cdebac2015-07-14 22:32:44 +0000460 bool canCheckPtrAtRT(RuntimePointerChecking &RtCheck, ScalarEvolution *SE,
461 Loop *TheLoop, const ValueToValueMap &Strides,
Adam Nemet04563272015-02-01 16:56:15 +0000462 bool ShouldCheckStride = false);
463
464 /// \brief Goes over all memory accesses, checks whether a RT check is needed
465 /// and builds sets of dependent accesses.
466 void buildDependenceSets() {
467 processMemAccesses();
468 }
469
Adam Nemet5dc3b2c2015-07-09 06:47:18 +0000470 /// \brief Initial processing of memory accesses determined that we need to
471 /// perform dependency checking.
472 ///
473 /// Note that this can later be cleared if we retry memcheck analysis without
474 /// dependency checking (i.e. ShouldRetryWithRuntimeCheck).
Adam Nemet04563272015-02-01 16:56:15 +0000475 bool isDependencyCheckNeeded() { return !CheckDeps.empty(); }
Adam Nemetdf3dc5b2015-05-18 15:37:03 +0000476
477 /// We decided that no dependence analysis would be used. Reset the state.
478 void resetDepChecks(MemoryDepChecker &DepChecker) {
479 CheckDeps.clear();
480 DepChecker.clearInterestingDependences();
481 }
Adam Nemet04563272015-02-01 16:56:15 +0000482
483 MemAccessInfoSet &getDependenciesToCheck() { return CheckDeps; }
484
485private:
486 typedef SetVector<MemAccessInfo> PtrAccessSet;
487
488 /// \brief Go over all memory access and check whether runtime pointer checks
Adam Nemetb41d2d32015-07-09 06:47:21 +0000489 /// are needed and build sets of dependency check candidates.
Adam Nemet04563272015-02-01 16:56:15 +0000490 void processMemAccesses();
491
492 /// Set of all accesses.
493 PtrAccessSet Accesses;
494
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000495 const DataLayout &DL;
496
Adam Nemet04563272015-02-01 16:56:15 +0000497 /// Set of accesses that need a further dependence check.
498 MemAccessInfoSet CheckDeps;
499
500 /// Set of pointers that are read only.
501 SmallPtrSet<Value*, 16> ReadOnlyPtr;
502
Adam Nemet04563272015-02-01 16:56:15 +0000503 /// An alias set tracker to partition the access set by underlying object and
504 //intrinsic property (such as TBAA metadata).
505 AliasSetTracker AST;
506
Adam Nemete2b885c2015-04-23 20:09:20 +0000507 LoopInfo *LI;
508
Adam Nemet04563272015-02-01 16:56:15 +0000509 /// Sets of potentially dependent accesses - members of one set share an
510 /// underlying pointer. The set "CheckDeps" identfies which sets really need a
511 /// dependence check.
Adam Nemetdee666b2015-03-10 17:40:34 +0000512 MemoryDepChecker::DepCandidates &DepCands;
Adam Nemet04563272015-02-01 16:56:15 +0000513
Adam Nemet5dc3b2c2015-07-09 06:47:18 +0000514 /// \brief Initial processing of memory accesses determined that we may need
515 /// to add memchecks. Perform the analysis to determine the necessary checks.
516 ///
517 /// Note that, this is different from isDependencyCheckNeeded. When we retry
518 /// memcheck analysis without dependency checking
519 /// (i.e. ShouldRetryWithRuntimeCheck), isDependencyCheckNeeded is cleared
520 /// while this remains set if we have potentially dependent accesses.
521 bool IsRTCheckAnalysisNeeded;
Adam Nemet04563272015-02-01 16:56:15 +0000522};
523
524} // end anonymous namespace
525
526/// \brief Check whether a pointer can participate in a runtime bounds check.
Adam Nemet8bc61df2015-02-24 00:41:59 +0000527static bool hasComputableBounds(ScalarEvolution *SE,
528 const ValueToValueMap &Strides, Value *Ptr) {
Adam Nemet04563272015-02-01 16:56:15 +0000529 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
530 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
531 if (!AR)
532 return false;
533
534 return AR->isAffine();
535}
536
Adam Nemet7cdebac2015-07-14 22:32:44 +0000537bool AccessAnalysis::canCheckPtrAtRT(RuntimePointerChecking &RtCheck,
538 ScalarEvolution *SE, Loop *TheLoop,
539 const ValueToValueMap &StridesMap,
540 bool ShouldCheckStride) {
Adam Nemet04563272015-02-01 16:56:15 +0000541 // Find pointers with computable bounds. We are going to use this information
542 // to place a runtime bound check.
543 bool CanDoRT = true;
544
Adam Nemetee614742015-07-09 22:17:38 +0000545 bool NeedRTCheck = false;
Adam Nemet5dc3b2c2015-07-09 06:47:18 +0000546 if (!IsRTCheckAnalysisNeeded) return true;
Silviu Baranga98a13712015-06-08 10:27:06 +0000547
Adam Nemet04563272015-02-01 16:56:15 +0000548 bool IsDepCheckNeeded = isDependencyCheckNeeded();
Adam Nemet04563272015-02-01 16:56:15 +0000549
550 // We assign a consecutive id to access from different alias sets.
551 // Accesses between different groups doesn't need to be checked.
552 unsigned ASId = 1;
553 for (auto &AS : AST) {
Adam Nemet424edc62015-07-08 22:58:48 +0000554 int NumReadPtrChecks = 0;
555 int NumWritePtrChecks = 0;
556
Adam Nemet04563272015-02-01 16:56:15 +0000557 // We assign consecutive id to access from different dependence sets.
558 // Accesses within the same set don't need a runtime check.
559 unsigned RunningDepId = 1;
560 DenseMap<Value *, unsigned> DepSetId;
561
562 for (auto A : AS) {
563 Value *Ptr = A.getValue();
564 bool IsWrite = Accesses.count(MemAccessInfo(Ptr, true));
565 MemAccessInfo Access(Ptr, IsWrite);
566
Adam Nemet424edc62015-07-08 22:58:48 +0000567 if (IsWrite)
568 ++NumWritePtrChecks;
569 else
570 ++NumReadPtrChecks;
571
Adam Nemet04563272015-02-01 16:56:15 +0000572 if (hasComputableBounds(SE, StridesMap, Ptr) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000573 // When we run after a failing dependency check we have to make sure
574 // we don't have wrapping pointers.
Adam Nemet04563272015-02-01 16:56:15 +0000575 (!ShouldCheckStride ||
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000576 isStridedPtr(SE, Ptr, TheLoop, StridesMap) == 1)) {
Adam Nemet04563272015-02-01 16:56:15 +0000577 // The id of the dependence set.
578 unsigned DepId;
579
580 if (IsDepCheckNeeded) {
581 Value *Leader = DepCands.getLeaderValue(Access).getPointer();
582 unsigned &LeaderId = DepSetId[Leader];
583 if (!LeaderId)
584 LeaderId = RunningDepId++;
585 DepId = LeaderId;
586 } else
587 // Each access has its own dependence set.
588 DepId = RunningDepId++;
589
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000590 RtCheck.insert(TheLoop, Ptr, IsWrite, DepId, ASId, StridesMap);
Adam Nemet04563272015-02-01 16:56:15 +0000591
Adam Nemet339f42b2015-02-19 19:15:07 +0000592 DEBUG(dbgs() << "LAA: Found a runtime check ptr:" << *Ptr << '\n');
Adam Nemet04563272015-02-01 16:56:15 +0000593 } else {
Adam Nemetf10ca272015-05-18 15:36:52 +0000594 DEBUG(dbgs() << "LAA: Can't find bounds for ptr:" << *Ptr << '\n');
Adam Nemet04563272015-02-01 16:56:15 +0000595 CanDoRT = false;
596 }
597 }
598
Adam Nemet424edc62015-07-08 22:58:48 +0000599 // If we have at least two writes or one write and a read then we need to
600 // check them. But there is no need to checks if there is only one
601 // dependence set for this alias set.
602 //
603 // Note that this function computes CanDoRT and NeedRTCheck independently.
604 // For example CanDoRT=false, NeedRTCheck=false means that we have a pointer
605 // for which we couldn't find the bounds but we don't actually need to emit
606 // any checks so it does not matter.
607 if (!(IsDepCheckNeeded && CanDoRT && RunningDepId == 2))
608 NeedRTCheck |= (NumWritePtrChecks >= 2 || (NumReadPtrChecks >= 1 &&
609 NumWritePtrChecks >= 1));
610
Adam Nemet04563272015-02-01 16:56:15 +0000611 ++ASId;
612 }
613
614 // If the pointers that we would use for the bounds comparison have different
615 // address spaces, assume the values aren't directly comparable, so we can't
616 // use them for the runtime check. We also have to assume they could
617 // overlap. In the future there should be metadata for whether address spaces
618 // are disjoint.
619 unsigned NumPointers = RtCheck.Pointers.size();
620 for (unsigned i = 0; i < NumPointers; ++i) {
621 for (unsigned j = i + 1; j < NumPointers; ++j) {
622 // Only need to check pointers between two different dependency sets.
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000623 if (RtCheck.Pointers[i].DependencySetId ==
624 RtCheck.Pointers[j].DependencySetId)
Adam Nemet04563272015-02-01 16:56:15 +0000625 continue;
626 // Only need to check pointers in the same alias set.
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000627 if (RtCheck.Pointers[i].AliasSetId != RtCheck.Pointers[j].AliasSetId)
Adam Nemet04563272015-02-01 16:56:15 +0000628 continue;
629
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000630 Value *PtrI = RtCheck.Pointers[i].PointerValue;
631 Value *PtrJ = RtCheck.Pointers[j].PointerValue;
Adam Nemet04563272015-02-01 16:56:15 +0000632
633 unsigned ASi = PtrI->getType()->getPointerAddressSpace();
634 unsigned ASj = PtrJ->getType()->getPointerAddressSpace();
635 if (ASi != ASj) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000636 DEBUG(dbgs() << "LAA: Runtime check would require comparison between"
Adam Nemet04d41632015-02-19 19:14:34 +0000637 " different address spaces\n");
Adam Nemet04563272015-02-01 16:56:15 +0000638 return false;
639 }
640 }
641 }
642
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000643 if (NeedRTCheck && CanDoRT)
644 RtCheck.groupChecks(DepCands, IsDepCheckNeeded);
645
Adam Nemetee614742015-07-09 22:17:38 +0000646 DEBUG(dbgs() << "LAA: We need to do " << RtCheck.getNumberOfChecks(nullptr)
647 << " pointer comparisons.\n");
648
649 RtCheck.Need = NeedRTCheck;
650
651 bool CanDoRTIfNeeded = !NeedRTCheck || CanDoRT;
652 if (!CanDoRTIfNeeded)
653 RtCheck.reset();
654 return CanDoRTIfNeeded;
Adam Nemet04563272015-02-01 16:56:15 +0000655}
656
657void AccessAnalysis::processMemAccesses() {
658 // We process the set twice: first we process read-write pointers, last we
659 // process read-only pointers. This allows us to skip dependence tests for
660 // read-only pointers.
661
Adam Nemet339f42b2015-02-19 19:15:07 +0000662 DEBUG(dbgs() << "LAA: Processing memory accesses...\n");
Adam Nemet04563272015-02-01 16:56:15 +0000663 DEBUG(dbgs() << " AST: "; AST.dump());
Adam Nemet9c926572015-03-10 17:40:37 +0000664 DEBUG(dbgs() << "LAA: Accesses(" << Accesses.size() << "):\n");
Adam Nemet04563272015-02-01 16:56:15 +0000665 DEBUG({
666 for (auto A : Accesses)
667 dbgs() << "\t" << *A.getPointer() << " (" <<
668 (A.getInt() ? "write" : (ReadOnlyPtr.count(A.getPointer()) ?
669 "read-only" : "read")) << ")\n";
670 });
671
672 // The AliasSetTracker has nicely partitioned our pointers by metadata
673 // compatibility and potential for underlying-object overlap. As a result, we
674 // only need to check for potential pointer dependencies within each alias
675 // set.
676 for (auto &AS : AST) {
677 // Note that both the alias-set tracker and the alias sets themselves used
678 // linked lists internally and so the iteration order here is deterministic
679 // (matching the original instruction order within each set).
680
681 bool SetHasWrite = false;
682
683 // Map of pointers to last access encountered.
684 typedef DenseMap<Value*, MemAccessInfo> UnderlyingObjToAccessMap;
685 UnderlyingObjToAccessMap ObjToLastAccess;
686
687 // Set of access to check after all writes have been processed.
688 PtrAccessSet DeferredAccesses;
689
690 // Iterate over each alias set twice, once to process read/write pointers,
691 // and then to process read-only pointers.
692 for (int SetIteration = 0; SetIteration < 2; ++SetIteration) {
693 bool UseDeferred = SetIteration > 0;
694 PtrAccessSet &S = UseDeferred ? DeferredAccesses : Accesses;
695
696 for (auto AV : AS) {
697 Value *Ptr = AV.getValue();
698
699 // For a single memory access in AliasSetTracker, Accesses may contain
700 // both read and write, and they both need to be handled for CheckDeps.
701 for (auto AC : S) {
702 if (AC.getPointer() != Ptr)
703 continue;
704
705 bool IsWrite = AC.getInt();
706
707 // If we're using the deferred access set, then it contains only
708 // reads.
709 bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite;
710 if (UseDeferred && !IsReadOnlyPtr)
711 continue;
712 // Otherwise, the pointer must be in the PtrAccessSet, either as a
713 // read or a write.
714 assert(((IsReadOnlyPtr && UseDeferred) || IsWrite ||
715 S.count(MemAccessInfo(Ptr, false))) &&
716 "Alias-set pointer not in the access set?");
717
718 MemAccessInfo Access(Ptr, IsWrite);
719 DepCands.insert(Access);
720
721 // Memorize read-only pointers for later processing and skip them in
722 // the first round (they need to be checked after we have seen all
723 // write pointers). Note: we also mark pointer that are not
724 // consecutive as "read-only" pointers (so that we check
725 // "a[b[i]] +="). Hence, we need the second check for "!IsWrite".
726 if (!UseDeferred && IsReadOnlyPtr) {
727 DeferredAccesses.insert(Access);
728 continue;
729 }
730
731 // If this is a write - check other reads and writes for conflicts. If
732 // this is a read only check other writes for conflicts (but only if
733 // there is no other write to the ptr - this is an optimization to
734 // catch "a[i] = a[i] + " without having to do a dependence check).
735 if ((IsWrite || IsReadOnlyPtr) && SetHasWrite) {
736 CheckDeps.insert(Access);
Adam Nemet5dc3b2c2015-07-09 06:47:18 +0000737 IsRTCheckAnalysisNeeded = true;
Adam Nemet04563272015-02-01 16:56:15 +0000738 }
739
740 if (IsWrite)
741 SetHasWrite = true;
742
743 // Create sets of pointers connected by a shared alias set and
744 // underlying object.
745 typedef SmallVector<Value *, 16> ValueVector;
746 ValueVector TempObjects;
Adam Nemete2b885c2015-04-23 20:09:20 +0000747
748 GetUnderlyingObjects(Ptr, TempObjects, DL, LI);
749 DEBUG(dbgs() << "Underlying objects for pointer " << *Ptr << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000750 for (Value *UnderlyingObj : TempObjects) {
751 UnderlyingObjToAccessMap::iterator Prev =
752 ObjToLastAccess.find(UnderlyingObj);
753 if (Prev != ObjToLastAccess.end())
754 DepCands.unionSets(Access, Prev->second);
755
756 ObjToLastAccess[UnderlyingObj] = Access;
Adam Nemete2b885c2015-04-23 20:09:20 +0000757 DEBUG(dbgs() << " " << *UnderlyingObj << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000758 }
759 }
760 }
761 }
762 }
763}
764
Adam Nemet04563272015-02-01 16:56:15 +0000765static bool isInBoundsGep(Value *Ptr) {
766 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
767 return GEP->isInBounds();
768 return false;
769}
770
Adam Nemetc4866d22015-06-26 17:25:43 +0000771/// \brief Return true if an AddRec pointer \p Ptr is unsigned non-wrapping,
772/// i.e. monotonically increasing/decreasing.
773static bool isNoWrapAddRec(Value *Ptr, const SCEVAddRecExpr *AR,
774 ScalarEvolution *SE, const Loop *L) {
775 // FIXME: This should probably only return true for NUW.
776 if (AR->getNoWrapFlags(SCEV::NoWrapMask))
777 return true;
778
779 // Scalar evolution does not propagate the non-wrapping flags to values that
780 // are derived from a non-wrapping induction variable because non-wrapping
781 // could be flow-sensitive.
782 //
783 // Look through the potentially overflowing instruction to try to prove
784 // non-wrapping for the *specific* value of Ptr.
785
786 // The arithmetic implied by an inbounds GEP can't overflow.
787 auto *GEP = dyn_cast<GetElementPtrInst>(Ptr);
788 if (!GEP || !GEP->isInBounds())
789 return false;
790
791 // Make sure there is only one non-const index and analyze that.
792 Value *NonConstIndex = nullptr;
793 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
794 if (!isa<ConstantInt>(*Index)) {
795 if (NonConstIndex)
796 return false;
797 NonConstIndex = *Index;
798 }
799 if (!NonConstIndex)
800 // The recurrence is on the pointer, ignore for now.
801 return false;
802
803 // The index in GEP is signed. It is non-wrapping if it's derived from a NSW
804 // AddRec using a NSW operation.
805 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(NonConstIndex))
806 if (OBO->hasNoSignedWrap() &&
807 // Assume constant for other the operand so that the AddRec can be
808 // easily found.
809 isa<ConstantInt>(OBO->getOperand(1))) {
810 auto *OpScev = SE->getSCEV(OBO->getOperand(0));
811
812 if (auto *OpAR = dyn_cast<SCEVAddRecExpr>(OpScev))
813 return OpAR->getLoop() == L && OpAR->getNoWrapFlags(SCEV::FlagNSW);
814 }
815
816 return false;
817}
818
Adam Nemet04563272015-02-01 16:56:15 +0000819/// \brief Check whether the access through \p Ptr has a constant stride.
Hao Liu32c05392015-06-08 06:39:56 +0000820int llvm::isStridedPtr(ScalarEvolution *SE, Value *Ptr, const Loop *Lp,
821 const ValueToValueMap &StridesMap) {
Craig Toppere3dcce92015-08-01 22:20:21 +0000822 Type *Ty = Ptr->getType();
Adam Nemet04563272015-02-01 16:56:15 +0000823 assert(Ty->isPointerTy() && "Unexpected non-ptr");
824
825 // Make sure that the pointer does not point to aggregate types.
Craig Toppere3dcce92015-08-01 22:20:21 +0000826 auto *PtrTy = cast<PointerType>(Ty);
Adam Nemet04563272015-02-01 16:56:15 +0000827 if (PtrTy->getElementType()->isAggregateType()) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000828 DEBUG(dbgs() << "LAA: Bad stride - Not a pointer to a scalar type"
829 << *Ptr << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000830 return 0;
831 }
832
833 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, StridesMap, Ptr);
834
835 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
836 if (!AR) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000837 DEBUG(dbgs() << "LAA: Bad stride - Not an AddRecExpr pointer "
Adam Nemet04d41632015-02-19 19:14:34 +0000838 << *Ptr << " SCEV: " << *PtrScev << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000839 return 0;
840 }
841
842 // The accesss function must stride over the innermost loop.
843 if (Lp != AR->getLoop()) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000844 DEBUG(dbgs() << "LAA: Bad stride - Not striding over innermost loop " <<
Adam Nemet04d41632015-02-19 19:14:34 +0000845 *Ptr << " SCEV: " << *PtrScev << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000846 }
847
848 // The address calculation must not wrap. Otherwise, a dependence could be
849 // inverted.
850 // An inbounds getelementptr that is a AddRec with a unit stride
851 // cannot wrap per definition. The unit stride requirement is checked later.
852 // An getelementptr without an inbounds attribute and unit stride would have
853 // to access the pointer value "0" which is undefined behavior in address
854 // space 0, therefore we can also vectorize this case.
855 bool IsInBoundsGEP = isInBoundsGep(Ptr);
Adam Nemetc4866d22015-06-26 17:25:43 +0000856 bool IsNoWrapAddRec = isNoWrapAddRec(Ptr, AR, SE, Lp);
Adam Nemet04563272015-02-01 16:56:15 +0000857 bool IsInAddressSpaceZero = PtrTy->getAddressSpace() == 0;
858 if (!IsNoWrapAddRec && !IsInBoundsGEP && !IsInAddressSpaceZero) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000859 DEBUG(dbgs() << "LAA: Bad stride - Pointer may wrap in the address space "
Adam Nemet04d41632015-02-19 19:14:34 +0000860 << *Ptr << " SCEV: " << *PtrScev << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000861 return 0;
862 }
863
864 // Check the step is constant.
865 const SCEV *Step = AR->getStepRecurrence(*SE);
866
Adam Nemet943befe2015-07-09 00:03:22 +0000867 // Calculate the pointer stride and check if it is constant.
Adam Nemet04563272015-02-01 16:56:15 +0000868 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
869 if (!C) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000870 DEBUG(dbgs() << "LAA: Bad stride - Not a constant strided " << *Ptr <<
Adam Nemet04d41632015-02-19 19:14:34 +0000871 " SCEV: " << *PtrScev << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000872 return 0;
873 }
874
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000875 auto &DL = Lp->getHeader()->getModule()->getDataLayout();
876 int64_t Size = DL.getTypeAllocSize(PtrTy->getElementType());
Adam Nemet04563272015-02-01 16:56:15 +0000877 const APInt &APStepVal = C->getValue()->getValue();
878
879 // Huge step value - give up.
880 if (APStepVal.getBitWidth() > 64)
881 return 0;
882
883 int64_t StepVal = APStepVal.getSExtValue();
884
885 // Strided access.
886 int64_t Stride = StepVal / Size;
887 int64_t Rem = StepVal % Size;
888 if (Rem)
889 return 0;
890
891 // If the SCEV could wrap but we have an inbounds gep with a unit stride we
892 // know we can't "wrap around the address space". In case of address space
893 // zero we know that this won't happen without triggering undefined behavior.
894 if (!IsNoWrapAddRec && (IsInBoundsGEP || IsInAddressSpaceZero) &&
895 Stride != 1 && Stride != -1)
896 return 0;
897
898 return Stride;
899}
900
Adam Nemet9c926572015-03-10 17:40:37 +0000901bool MemoryDepChecker::Dependence::isSafeForVectorization(DepType Type) {
902 switch (Type) {
903 case NoDep:
904 case Forward:
905 case BackwardVectorizable:
906 return true;
907
908 case Unknown:
909 case ForwardButPreventsForwarding:
910 case Backward:
911 case BackwardVectorizableButPreventsForwarding:
912 return false;
913 }
David Majnemerd388e932015-03-10 20:23:29 +0000914 llvm_unreachable("unexpected DepType!");
Adam Nemet9c926572015-03-10 17:40:37 +0000915}
916
917bool MemoryDepChecker::Dependence::isInterestingDependence(DepType Type) {
918 switch (Type) {
919 case NoDep:
920 case Forward:
921 return false;
922
923 case BackwardVectorizable:
924 case Unknown:
925 case ForwardButPreventsForwarding:
926 case Backward:
927 case BackwardVectorizableButPreventsForwarding:
928 return true;
929 }
David Majnemerd388e932015-03-10 20:23:29 +0000930 llvm_unreachable("unexpected DepType!");
Adam Nemet9c926572015-03-10 17:40:37 +0000931}
932
933bool MemoryDepChecker::Dependence::isPossiblyBackward() const {
934 switch (Type) {
935 case NoDep:
936 case Forward:
937 case ForwardButPreventsForwarding:
938 return false;
939
940 case Unknown:
941 case BackwardVectorizable:
942 case Backward:
943 case BackwardVectorizableButPreventsForwarding:
944 return true;
945 }
David Majnemerd388e932015-03-10 20:23:29 +0000946 llvm_unreachable("unexpected DepType!");
Adam Nemet9c926572015-03-10 17:40:37 +0000947}
948
Adam Nemet04563272015-02-01 16:56:15 +0000949bool MemoryDepChecker::couldPreventStoreLoadForward(unsigned Distance,
950 unsigned TypeByteSize) {
951 // If loads occur at a distance that is not a multiple of a feasible vector
952 // factor store-load forwarding does not take place.
953 // Positive dependences might cause troubles because vectorizing them might
954 // prevent store-load forwarding making vectorized code run a lot slower.
955 // a[i] = a[i-3] ^ a[i-8];
956 // The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
957 // hence on your typical architecture store-load forwarding does not take
958 // place. Vectorizing in such cases does not make sense.
959 // Store-load forwarding distance.
960 const unsigned NumCyclesForStoreLoadThroughMemory = 8*TypeByteSize;
961 // Maximum vector factor.
Adam Nemetf219c642015-02-19 19:14:52 +0000962 unsigned MaxVFWithoutSLForwardIssues =
963 VectorizerParams::MaxVectorWidth * TypeByteSize;
Adam Nemet04d41632015-02-19 19:14:34 +0000964 if(MaxSafeDepDistBytes < MaxVFWithoutSLForwardIssues)
Adam Nemet04563272015-02-01 16:56:15 +0000965 MaxVFWithoutSLForwardIssues = MaxSafeDepDistBytes;
966
967 for (unsigned vf = 2*TypeByteSize; vf <= MaxVFWithoutSLForwardIssues;
968 vf *= 2) {
969 if (Distance % vf && Distance / vf < NumCyclesForStoreLoadThroughMemory) {
970 MaxVFWithoutSLForwardIssues = (vf >>=1);
971 break;
972 }
973 }
974
Adam Nemet04d41632015-02-19 19:14:34 +0000975 if (MaxVFWithoutSLForwardIssues< 2*TypeByteSize) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000976 DEBUG(dbgs() << "LAA: Distance " << Distance <<
Adam Nemet04d41632015-02-19 19:14:34 +0000977 " that could cause a store-load forwarding conflict\n");
Adam Nemet04563272015-02-01 16:56:15 +0000978 return true;
979 }
980
981 if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes &&
Adam Nemetf219c642015-02-19 19:14:52 +0000982 MaxVFWithoutSLForwardIssues !=
983 VectorizerParams::MaxVectorWidth * TypeByteSize)
Adam Nemet04563272015-02-01 16:56:15 +0000984 MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues;
985 return false;
986}
987
Hao Liu751004a2015-06-08 04:48:37 +0000988/// \brief Check the dependence for two accesses with the same stride \p Stride.
989/// \p Distance is the positive distance and \p TypeByteSize is type size in
990/// bytes.
991///
992/// \returns true if they are independent.
993static bool areStridedAccessesIndependent(unsigned Distance, unsigned Stride,
994 unsigned TypeByteSize) {
995 assert(Stride > 1 && "The stride must be greater than 1");
996 assert(TypeByteSize > 0 && "The type size in byte must be non-zero");
997 assert(Distance > 0 && "The distance must be non-zero");
998
999 // Skip if the distance is not multiple of type byte size.
1000 if (Distance % TypeByteSize)
1001 return false;
1002
1003 unsigned ScaledDist = Distance / TypeByteSize;
1004
1005 // No dependence if the scaled distance is not multiple of the stride.
1006 // E.g.
1007 // for (i = 0; i < 1024 ; i += 4)
1008 // A[i+2] = A[i] + 1;
1009 //
1010 // Two accesses in memory (scaled distance is 2, stride is 4):
1011 // | A[0] | | | | A[4] | | | |
1012 // | | | A[2] | | | | A[6] | |
1013 //
1014 // E.g.
1015 // for (i = 0; i < 1024 ; i += 3)
1016 // A[i+4] = A[i] + 1;
1017 //
1018 // Two accesses in memory (scaled distance is 4, stride is 3):
1019 // | A[0] | | | A[3] | | | A[6] | | |
1020 // | | | | | A[4] | | | A[7] | |
1021 return ScaledDist % Stride;
1022}
1023
Adam Nemet9c926572015-03-10 17:40:37 +00001024MemoryDepChecker::Dependence::DepType
1025MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
1026 const MemAccessInfo &B, unsigned BIdx,
1027 const ValueToValueMap &Strides) {
Adam Nemet04563272015-02-01 16:56:15 +00001028 assert (AIdx < BIdx && "Must pass arguments in program order");
1029
1030 Value *APtr = A.getPointer();
1031 Value *BPtr = B.getPointer();
1032 bool AIsWrite = A.getInt();
1033 bool BIsWrite = B.getInt();
1034
1035 // Two reads are independent.
1036 if (!AIsWrite && !BIsWrite)
Adam Nemet9c926572015-03-10 17:40:37 +00001037 return Dependence::NoDep;
Adam Nemet04563272015-02-01 16:56:15 +00001038
1039 // We cannot check pointers in different address spaces.
1040 if (APtr->getType()->getPointerAddressSpace() !=
1041 BPtr->getType()->getPointerAddressSpace())
Adam Nemet9c926572015-03-10 17:40:37 +00001042 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +00001043
1044 const SCEV *AScev = replaceSymbolicStrideSCEV(SE, Strides, APtr);
1045 const SCEV *BScev = replaceSymbolicStrideSCEV(SE, Strides, BPtr);
1046
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001047 int StrideAPtr = isStridedPtr(SE, APtr, InnermostLoop, Strides);
1048 int StrideBPtr = isStridedPtr(SE, BPtr, InnermostLoop, Strides);
Adam Nemet04563272015-02-01 16:56:15 +00001049
1050 const SCEV *Src = AScev;
1051 const SCEV *Sink = BScev;
1052
1053 // If the induction step is negative we have to invert source and sink of the
1054 // dependence.
1055 if (StrideAPtr < 0) {
1056 //Src = BScev;
1057 //Sink = AScev;
1058 std::swap(APtr, BPtr);
1059 std::swap(Src, Sink);
1060 std::swap(AIsWrite, BIsWrite);
1061 std::swap(AIdx, BIdx);
1062 std::swap(StrideAPtr, StrideBPtr);
1063 }
1064
1065 const SCEV *Dist = SE->getMinusSCEV(Sink, Src);
1066
Adam Nemet339f42b2015-02-19 19:15:07 +00001067 DEBUG(dbgs() << "LAA: Src Scev: " << *Src << "Sink Scev: " << *Sink
Adam Nemet04d41632015-02-19 19:14:34 +00001068 << "(Induction step: " << StrideAPtr << ")\n");
Adam Nemet339f42b2015-02-19 19:15:07 +00001069 DEBUG(dbgs() << "LAA: Distance for " << *InstMap[AIdx] << " to "
Adam Nemet04d41632015-02-19 19:14:34 +00001070 << *InstMap[BIdx] << ": " << *Dist << "\n");
Adam Nemet04563272015-02-01 16:56:15 +00001071
Adam Nemet943befe2015-07-09 00:03:22 +00001072 // Need accesses with constant stride. We don't want to vectorize
Adam Nemet04563272015-02-01 16:56:15 +00001073 // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in
1074 // the address space.
1075 if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){
Adam Nemet943befe2015-07-09 00:03:22 +00001076 DEBUG(dbgs() << "Pointer access with non-constant stride\n");
Adam Nemet9c926572015-03-10 17:40:37 +00001077 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +00001078 }
1079
1080 const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist);
1081 if (!C) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001082 DEBUG(dbgs() << "LAA: Dependence because of non-constant distance\n");
Adam Nemet04563272015-02-01 16:56:15 +00001083 ShouldRetryWithRuntimeCheck = true;
Adam Nemet9c926572015-03-10 17:40:37 +00001084 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +00001085 }
1086
1087 Type *ATy = APtr->getType()->getPointerElementType();
1088 Type *BTy = BPtr->getType()->getPointerElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001089 auto &DL = InnermostLoop->getHeader()->getModule()->getDataLayout();
1090 unsigned TypeByteSize = DL.getTypeAllocSize(ATy);
Adam Nemet04563272015-02-01 16:56:15 +00001091
1092 // Negative distances are not plausible dependencies.
1093 const APInt &Val = C->getValue()->getValue();
1094 if (Val.isNegative()) {
1095 bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
1096 if (IsTrueDataDependence &&
1097 (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) ||
1098 ATy != BTy))
Adam Nemet9c926572015-03-10 17:40:37 +00001099 return Dependence::ForwardButPreventsForwarding;
Adam Nemet04563272015-02-01 16:56:15 +00001100
Adam Nemet339f42b2015-02-19 19:15:07 +00001101 DEBUG(dbgs() << "LAA: Dependence is negative: NoDep\n");
Adam Nemet9c926572015-03-10 17:40:37 +00001102 return Dependence::Forward;
Adam Nemet04563272015-02-01 16:56:15 +00001103 }
1104
1105 // Write to the same location with the same size.
1106 // Could be improved to assert type sizes are the same (i32 == float, etc).
1107 if (Val == 0) {
1108 if (ATy == BTy)
Adam Nemet9c926572015-03-10 17:40:37 +00001109 return Dependence::NoDep;
Adam Nemet339f42b2015-02-19 19:15:07 +00001110 DEBUG(dbgs() << "LAA: Zero dependence difference but different types\n");
Adam Nemet9c926572015-03-10 17:40:37 +00001111 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +00001112 }
1113
1114 assert(Val.isStrictlyPositive() && "Expect a positive value");
1115
Adam Nemet04563272015-02-01 16:56:15 +00001116 if (ATy != BTy) {
Adam Nemet04d41632015-02-19 19:14:34 +00001117 DEBUG(dbgs() <<
Adam Nemet339f42b2015-02-19 19:15:07 +00001118 "LAA: ReadWrite-Write positive dependency with different types\n");
Adam Nemet9c926572015-03-10 17:40:37 +00001119 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +00001120 }
1121
1122 unsigned Distance = (unsigned) Val.getZExtValue();
1123
Hao Liu751004a2015-06-08 04:48:37 +00001124 unsigned Stride = std::abs(StrideAPtr);
1125 if (Stride > 1 &&
Adam Nemet0131a562015-07-08 18:47:38 +00001126 areStridedAccessesIndependent(Distance, Stride, TypeByteSize)) {
1127 DEBUG(dbgs() << "LAA: Strided accesses are independent\n");
Hao Liu751004a2015-06-08 04:48:37 +00001128 return Dependence::NoDep;
Adam Nemet0131a562015-07-08 18:47:38 +00001129 }
Hao Liu751004a2015-06-08 04:48:37 +00001130
Adam Nemet04563272015-02-01 16:56:15 +00001131 // Bail out early if passed-in parameters make vectorization not feasible.
Adam Nemetf219c642015-02-19 19:14:52 +00001132 unsigned ForcedFactor = (VectorizerParams::VectorizationFactor ?
1133 VectorizerParams::VectorizationFactor : 1);
1134 unsigned ForcedUnroll = (VectorizerParams::VectorizationInterleave ?
1135 VectorizerParams::VectorizationInterleave : 1);
Hao Liu751004a2015-06-08 04:48:37 +00001136 // The minimum number of iterations for a vectorized/unrolled version.
1137 unsigned MinNumIter = std::max(ForcedFactor * ForcedUnroll, 2U);
Adam Nemet04563272015-02-01 16:56:15 +00001138
Hao Liu751004a2015-06-08 04:48:37 +00001139 // It's not vectorizable if the distance is smaller than the minimum distance
1140 // needed for a vectroized/unrolled version. Vectorizing one iteration in
1141 // front needs TypeByteSize * Stride. Vectorizing the last iteration needs
1142 // TypeByteSize (No need to plus the last gap distance).
1143 //
1144 // E.g. Assume one char is 1 byte in memory and one int is 4 bytes.
1145 // foo(int *A) {
1146 // int *B = (int *)((char *)A + 14);
1147 // for (i = 0 ; i < 1024 ; i += 2)
1148 // B[i] = A[i] + 1;
1149 // }
1150 //
1151 // Two accesses in memory (stride is 2):
1152 // | A[0] | | A[2] | | A[4] | | A[6] | |
1153 // | B[0] | | B[2] | | B[4] |
1154 //
1155 // Distance needs for vectorizing iterations except the last iteration:
1156 // 4 * 2 * (MinNumIter - 1). Distance needs for the last iteration: 4.
1157 // So the minimum distance needed is: 4 * 2 * (MinNumIter - 1) + 4.
1158 //
1159 // If MinNumIter is 2, it is vectorizable as the minimum distance needed is
1160 // 12, which is less than distance.
1161 //
1162 // If MinNumIter is 4 (Say if a user forces the vectorization factor to be 4),
1163 // the minimum distance needed is 28, which is greater than distance. It is
1164 // not safe to do vectorization.
1165 unsigned MinDistanceNeeded =
1166 TypeByteSize * Stride * (MinNumIter - 1) + TypeByteSize;
1167 if (MinDistanceNeeded > Distance) {
1168 DEBUG(dbgs() << "LAA: Failure because of positive distance " << Distance
1169 << '\n');
1170 return Dependence::Backward;
1171 }
1172
1173 // Unsafe if the minimum distance needed is greater than max safe distance.
1174 if (MinDistanceNeeded > MaxSafeDepDistBytes) {
1175 DEBUG(dbgs() << "LAA: Failure because it needs at least "
1176 << MinDistanceNeeded << " size in bytes");
Adam Nemet9c926572015-03-10 17:40:37 +00001177 return Dependence::Backward;
Adam Nemet04563272015-02-01 16:56:15 +00001178 }
1179
Adam Nemet9cc0c392015-02-26 17:58:48 +00001180 // Positive distance bigger than max vectorization factor.
Hao Liu751004a2015-06-08 04:48:37 +00001181 // FIXME: Should use max factor instead of max distance in bytes, which could
1182 // not handle different types.
1183 // E.g. Assume one char is 1 byte in memory and one int is 4 bytes.
1184 // void foo (int *A, char *B) {
1185 // for (unsigned i = 0; i < 1024; i++) {
1186 // A[i+2] = A[i] + 1;
1187 // B[i+2] = B[i] + 1;
1188 // }
1189 // }
1190 //
1191 // This case is currently unsafe according to the max safe distance. If we
1192 // analyze the two accesses on array B, the max safe dependence distance
1193 // is 2. Then we analyze the accesses on array A, the minimum distance needed
1194 // is 8, which is less than 2 and forbidden vectorization, But actually
1195 // both A and B could be vectorized by 2 iterations.
1196 MaxSafeDepDistBytes =
1197 Distance < MaxSafeDepDistBytes ? Distance : MaxSafeDepDistBytes;
Adam Nemet04563272015-02-01 16:56:15 +00001198
1199 bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
1200 if (IsTrueDataDependence &&
1201 couldPreventStoreLoadForward(Distance, TypeByteSize))
Adam Nemet9c926572015-03-10 17:40:37 +00001202 return Dependence::BackwardVectorizableButPreventsForwarding;
Adam Nemet04563272015-02-01 16:56:15 +00001203
Hao Liu751004a2015-06-08 04:48:37 +00001204 DEBUG(dbgs() << "LAA: Positive distance " << Val.getSExtValue()
1205 << " with max VF = "
1206 << MaxSafeDepDistBytes / (TypeByteSize * Stride) << '\n');
Adam Nemet04563272015-02-01 16:56:15 +00001207
Adam Nemet9c926572015-03-10 17:40:37 +00001208 return Dependence::BackwardVectorizable;
Adam Nemet04563272015-02-01 16:56:15 +00001209}
1210
Adam Nemetdee666b2015-03-10 17:40:34 +00001211bool MemoryDepChecker::areDepsSafe(DepCandidates &AccessSets,
Adam Nemet04563272015-02-01 16:56:15 +00001212 MemAccessInfoSet &CheckDeps,
Adam Nemet8bc61df2015-02-24 00:41:59 +00001213 const ValueToValueMap &Strides) {
Adam Nemet04563272015-02-01 16:56:15 +00001214
1215 MaxSafeDepDistBytes = -1U;
1216 while (!CheckDeps.empty()) {
1217 MemAccessInfo CurAccess = *CheckDeps.begin();
1218
1219 // Get the relevant memory access set.
1220 EquivalenceClasses<MemAccessInfo>::iterator I =
1221 AccessSets.findValue(AccessSets.getLeaderValue(CurAccess));
1222
1223 // Check accesses within this set.
1224 EquivalenceClasses<MemAccessInfo>::member_iterator AI, AE;
1225 AI = AccessSets.member_begin(I), AE = AccessSets.member_end();
1226
1227 // Check every access pair.
1228 while (AI != AE) {
1229 CheckDeps.erase(*AI);
1230 EquivalenceClasses<MemAccessInfo>::member_iterator OI = std::next(AI);
1231 while (OI != AE) {
1232 // Check every accessing instruction pair in program order.
1233 for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(),
1234 I1E = Accesses[*AI].end(); I1 != I1E; ++I1)
1235 for (std::vector<unsigned>::iterator I2 = Accesses[*OI].begin(),
1236 I2E = Accesses[*OI].end(); I2 != I2E; ++I2) {
Adam Nemet9c926572015-03-10 17:40:37 +00001237 auto A = std::make_pair(&*AI, *I1);
1238 auto B = std::make_pair(&*OI, *I2);
1239
1240 assert(*I1 != *I2);
1241 if (*I1 > *I2)
1242 std::swap(A, B);
1243
1244 Dependence::DepType Type =
1245 isDependent(*A.first, A.second, *B.first, B.second, Strides);
1246 SafeForVectorization &= Dependence::isSafeForVectorization(Type);
1247
1248 // Gather dependences unless we accumulated MaxInterestingDependence
1249 // dependences. In that case return as soon as we find the first
1250 // unsafe dependence. This puts a limit on this quadratic
1251 // algorithm.
1252 if (RecordInterestingDependences) {
1253 if (Dependence::isInterestingDependence(Type))
1254 InterestingDependences.push_back(
1255 Dependence(A.second, B.second, Type));
1256
1257 if (InterestingDependences.size() >= MaxInterestingDependence) {
1258 RecordInterestingDependences = false;
1259 InterestingDependences.clear();
1260 DEBUG(dbgs() << "Too many dependences, stopped recording\n");
1261 }
1262 }
1263 if (!RecordInterestingDependences && !SafeForVectorization)
Adam Nemet04563272015-02-01 16:56:15 +00001264 return false;
1265 }
1266 ++OI;
1267 }
1268 AI++;
1269 }
1270 }
Adam Nemet9c926572015-03-10 17:40:37 +00001271
1272 DEBUG(dbgs() << "Total Interesting Dependences: "
1273 << InterestingDependences.size() << "\n");
1274 return SafeForVectorization;
Adam Nemet04563272015-02-01 16:56:15 +00001275}
1276
Adam Nemetec1e2bb2015-03-10 18:54:26 +00001277SmallVector<Instruction *, 4>
1278MemoryDepChecker::getInstructionsForAccess(Value *Ptr, bool isWrite) const {
1279 MemAccessInfo Access(Ptr, isWrite);
1280 auto &IndexVector = Accesses.find(Access)->second;
1281
1282 SmallVector<Instruction *, 4> Insts;
1283 std::transform(IndexVector.begin(), IndexVector.end(),
1284 std::back_inserter(Insts),
1285 [&](unsigned Idx) { return this->InstMap[Idx]; });
1286 return Insts;
1287}
1288
Adam Nemet58913d62015-03-10 17:40:43 +00001289const char *MemoryDepChecker::Dependence::DepName[] = {
1290 "NoDep", "Unknown", "Forward", "ForwardButPreventsForwarding", "Backward",
1291 "BackwardVectorizable", "BackwardVectorizableButPreventsForwarding"};
1292
1293void MemoryDepChecker::Dependence::print(
1294 raw_ostream &OS, unsigned Depth,
1295 const SmallVectorImpl<Instruction *> &Instrs) const {
1296 OS.indent(Depth) << DepName[Type] << ":\n";
1297 OS.indent(Depth + 2) << *Instrs[Source] << " -> \n";
1298 OS.indent(Depth + 2) << *Instrs[Destination] << "\n";
1299}
1300
Adam Nemet929c38e2015-02-19 19:15:10 +00001301bool LoopAccessInfo::canAnalyzeLoop() {
Adam Nemet8dcb3b62015-04-17 22:43:10 +00001302 // We need to have a loop header.
1303 DEBUG(dbgs() << "LAA: Found a loop: " <<
1304 TheLoop->getHeader()->getName() << '\n');
1305
Adam Nemet929c38e2015-02-19 19:15:10 +00001306 // We can only analyze innermost loops.
1307 if (!TheLoop->empty()) {
Adam Nemet8dcb3b62015-04-17 22:43:10 +00001308 DEBUG(dbgs() << "LAA: loop is not the innermost loop\n");
Adam Nemet2bd6e982015-02-19 19:15:15 +00001309 emitAnalysis(LoopAccessReport() << "loop is not the innermost loop");
Adam Nemet929c38e2015-02-19 19:15:10 +00001310 return false;
1311 }
1312
1313 // We must have a single backedge.
1314 if (TheLoop->getNumBackEdges() != 1) {
Adam Nemet8dcb3b62015-04-17 22:43:10 +00001315 DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n");
Adam Nemet929c38e2015-02-19 19:15:10 +00001316 emitAnalysis(
Adam Nemet2bd6e982015-02-19 19:15:15 +00001317 LoopAccessReport() <<
Adam Nemet929c38e2015-02-19 19:15:10 +00001318 "loop control flow is not understood by analyzer");
1319 return false;
1320 }
1321
1322 // We must have a single exiting block.
1323 if (!TheLoop->getExitingBlock()) {
Adam Nemet8dcb3b62015-04-17 22:43:10 +00001324 DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n");
Adam Nemet929c38e2015-02-19 19:15:10 +00001325 emitAnalysis(
Adam Nemet2bd6e982015-02-19 19:15:15 +00001326 LoopAccessReport() <<
Adam Nemet929c38e2015-02-19 19:15:10 +00001327 "loop control flow is not understood by analyzer");
1328 return false;
1329 }
1330
1331 // We only handle bottom-tested loops, i.e. loop in which the condition is
1332 // checked at the end of each iteration. With that we can assume that all
1333 // instructions in the loop are executed the same number of times.
1334 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
Adam Nemet8dcb3b62015-04-17 22:43:10 +00001335 DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n");
Adam Nemet929c38e2015-02-19 19:15:10 +00001336 emitAnalysis(
Adam Nemet2bd6e982015-02-19 19:15:15 +00001337 LoopAccessReport() <<
Adam Nemet929c38e2015-02-19 19:15:10 +00001338 "loop control flow is not understood by analyzer");
1339 return false;
1340 }
1341
Adam Nemet929c38e2015-02-19 19:15:10 +00001342 // ScalarEvolution needs to be able to find the exit count.
1343 const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop);
1344 if (ExitCount == SE->getCouldNotCompute()) {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001345 emitAnalysis(LoopAccessReport() <<
Adam Nemet929c38e2015-02-19 19:15:10 +00001346 "could not determine number of loop iterations");
1347 DEBUG(dbgs() << "LAA: SCEV could not compute the loop exit count.\n");
1348 return false;
1349 }
1350
1351 return true;
1352}
1353
Adam Nemet8bc61df2015-02-24 00:41:59 +00001354void LoopAccessInfo::analyzeLoop(const ValueToValueMap &Strides) {
Adam Nemet04563272015-02-01 16:56:15 +00001355
1356 typedef SmallVector<Value*, 16> ValueVector;
1357 typedef SmallPtrSet<Value*, 16> ValueSet;
1358
1359 // Holds the Load and Store *instructions*.
1360 ValueVector Loads;
1361 ValueVector Stores;
1362
1363 // Holds all the different accesses in the loop.
1364 unsigned NumReads = 0;
1365 unsigned NumReadWrites = 0;
1366
Adam Nemet7cdebac2015-07-14 22:32:44 +00001367 PtrRtChecking.Pointers.clear();
1368 PtrRtChecking.Need = false;
Adam Nemet04563272015-02-01 16:56:15 +00001369
1370 const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
Adam Nemet04563272015-02-01 16:56:15 +00001371
1372 // For each block.
1373 for (Loop::block_iterator bb = TheLoop->block_begin(),
1374 be = TheLoop->block_end(); bb != be; ++bb) {
1375
1376 // Scan the BB and collect legal loads and stores.
1377 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
1378 ++it) {
1379
1380 // If this is a load, save it. If this instruction can read from memory
1381 // but is not a load, then we quit. Notice that we don't handle function
1382 // calls that read or write.
1383 if (it->mayReadFromMemory()) {
1384 // Many math library functions read the rounding mode. We will only
1385 // vectorize a loop if it contains known function calls that don't set
1386 // the flag. Therefore, it is safe to ignore this read from memory.
1387 CallInst *Call = dyn_cast<CallInst>(it);
1388 if (Call && getIntrinsicIDForCall(Call, TLI))
1389 continue;
1390
Michael Zolotukhin9b3cf602015-03-17 19:46:50 +00001391 // If the function has an explicit vectorized counterpart, we can safely
1392 // assume that it can be vectorized.
1393 if (Call && !Call->isNoBuiltin() && Call->getCalledFunction() &&
1394 TLI->isFunctionVectorizable(Call->getCalledFunction()->getName()))
1395 continue;
1396
Adam Nemet04563272015-02-01 16:56:15 +00001397 LoadInst *Ld = dyn_cast<LoadInst>(it);
1398 if (!Ld || (!Ld->isSimple() && !IsAnnotatedParallel)) {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001399 emitAnalysis(LoopAccessReport(Ld)
Adam Nemet04563272015-02-01 16:56:15 +00001400 << "read with atomic ordering or volatile read");
Adam Nemet339f42b2015-02-19 19:15:07 +00001401 DEBUG(dbgs() << "LAA: Found a non-simple load.\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001402 CanVecMem = false;
1403 return;
Adam Nemet04563272015-02-01 16:56:15 +00001404 }
1405 NumLoads++;
1406 Loads.push_back(Ld);
1407 DepChecker.addAccess(Ld);
1408 continue;
1409 }
1410
1411 // Save 'store' instructions. Abort if other instructions write to memory.
1412 if (it->mayWriteToMemory()) {
1413 StoreInst *St = dyn_cast<StoreInst>(it);
1414 if (!St) {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001415 emitAnalysis(LoopAccessReport(it) <<
Adam Nemet04d41632015-02-19 19:14:34 +00001416 "instruction cannot be vectorized");
Adam Nemet436018c2015-02-19 19:15:00 +00001417 CanVecMem = false;
1418 return;
Adam Nemet04563272015-02-01 16:56:15 +00001419 }
1420 if (!St->isSimple() && !IsAnnotatedParallel) {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001421 emitAnalysis(LoopAccessReport(St)
Adam Nemet04563272015-02-01 16:56:15 +00001422 << "write with atomic ordering or volatile write");
Adam Nemet339f42b2015-02-19 19:15:07 +00001423 DEBUG(dbgs() << "LAA: Found a non-simple store.\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001424 CanVecMem = false;
1425 return;
Adam Nemet04563272015-02-01 16:56:15 +00001426 }
1427 NumStores++;
1428 Stores.push_back(St);
1429 DepChecker.addAccess(St);
1430 }
1431 } // Next instr.
1432 } // Next block.
1433
1434 // Now we have two lists that hold the loads and the stores.
1435 // Next, we find the pointers that they use.
1436
1437 // Check if we see any stores. If there are no stores, then we don't
1438 // care if the pointers are *restrict*.
1439 if (!Stores.size()) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001440 DEBUG(dbgs() << "LAA: Found a read-only loop!\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001441 CanVecMem = true;
1442 return;
Adam Nemet04563272015-02-01 16:56:15 +00001443 }
1444
Adam Nemetdee666b2015-03-10 17:40:34 +00001445 MemoryDepChecker::DepCandidates DependentAccesses;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001446 AccessAnalysis Accesses(TheLoop->getHeader()->getModule()->getDataLayout(),
Adam Nemete2b885c2015-04-23 20:09:20 +00001447 AA, LI, DependentAccesses);
Adam Nemet04563272015-02-01 16:56:15 +00001448
1449 // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
1450 // multiple times on the same object. If the ptr is accessed twice, once
1451 // for read and once for write, it will only appear once (on the write
1452 // list). This is okay, since we are going to check for conflicts between
1453 // writes and between reads and writes, but not between reads and reads.
1454 ValueSet Seen;
1455
1456 ValueVector::iterator I, IE;
1457 for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
1458 StoreInst *ST = cast<StoreInst>(*I);
1459 Value* Ptr = ST->getPointerOperand();
Adam Nemetce482502015-04-08 17:48:40 +00001460 // Check for store to loop invariant address.
1461 StoreToLoopInvariantAddress |= isUniform(Ptr);
Adam Nemet04563272015-02-01 16:56:15 +00001462 // If we did *not* see this pointer before, insert it to the read-write
1463 // list. At this phase it is only a 'write' list.
1464 if (Seen.insert(Ptr).second) {
1465 ++NumReadWrites;
1466
Chandler Carruthac80dc72015-06-17 07:18:54 +00001467 MemoryLocation Loc = MemoryLocation::get(ST);
Adam Nemet04563272015-02-01 16:56:15 +00001468 // The TBAA metadata could have a control dependency on the predication
1469 // condition, so we cannot rely on it when determining whether or not we
1470 // need runtime pointer checks.
Adam Nemet01abb2c2015-02-18 03:43:19 +00001471 if (blockNeedsPredication(ST->getParent(), TheLoop, DT))
Adam Nemet04563272015-02-01 16:56:15 +00001472 Loc.AATags.TBAA = nullptr;
1473
1474 Accesses.addStore(Loc);
1475 }
1476 }
1477
1478 if (IsAnnotatedParallel) {
Adam Nemet04d41632015-02-19 19:14:34 +00001479 DEBUG(dbgs()
Adam Nemet339f42b2015-02-19 19:15:07 +00001480 << "LAA: A loop annotated parallel, ignore memory dependency "
Adam Nemet04d41632015-02-19 19:14:34 +00001481 << "checks.\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001482 CanVecMem = true;
1483 return;
Adam Nemet04563272015-02-01 16:56:15 +00001484 }
1485
1486 for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
1487 LoadInst *LD = cast<LoadInst>(*I);
1488 Value* Ptr = LD->getPointerOperand();
1489 // If we did *not* see this pointer before, insert it to the
1490 // read list. If we *did* see it before, then it is already in
1491 // the read-write list. This allows us to vectorize expressions
1492 // such as A[i] += x; Because the address of A[i] is a read-write
1493 // pointer. This only works if the index of A[i] is consecutive.
1494 // If the address of i is unknown (for example A[B[i]]) then we may
1495 // read a few words, modify, and write a few words, and some of the
1496 // words may be written to the same address.
1497 bool IsReadOnlyPtr = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001498 if (Seen.insert(Ptr).second || !isStridedPtr(SE, Ptr, TheLoop, Strides)) {
Adam Nemet04563272015-02-01 16:56:15 +00001499 ++NumReads;
1500 IsReadOnlyPtr = true;
1501 }
1502
Chandler Carruthac80dc72015-06-17 07:18:54 +00001503 MemoryLocation Loc = MemoryLocation::get(LD);
Adam Nemet04563272015-02-01 16:56:15 +00001504 // The TBAA metadata could have a control dependency on the predication
1505 // condition, so we cannot rely on it when determining whether or not we
1506 // need runtime pointer checks.
Adam Nemet01abb2c2015-02-18 03:43:19 +00001507 if (blockNeedsPredication(LD->getParent(), TheLoop, DT))
Adam Nemet04563272015-02-01 16:56:15 +00001508 Loc.AATags.TBAA = nullptr;
1509
1510 Accesses.addLoad(Loc, IsReadOnlyPtr);
1511 }
1512
1513 // If we write (or read-write) to a single destination and there are no
1514 // other reads in this loop then is it safe to vectorize.
1515 if (NumReadWrites == 1 && NumReads == 0) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001516 DEBUG(dbgs() << "LAA: Found a write-only loop!\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001517 CanVecMem = true;
1518 return;
Adam Nemet04563272015-02-01 16:56:15 +00001519 }
1520
1521 // Build dependence sets and check whether we need a runtime pointer bounds
1522 // check.
1523 Accesses.buildDependenceSets();
Adam Nemet04563272015-02-01 16:56:15 +00001524
1525 // Find pointers with computable bounds. We are going to use this information
1526 // to place a runtime bound check.
Adam Nemetee614742015-07-09 22:17:38 +00001527 bool CanDoRTIfNeeded =
Adam Nemet7cdebac2015-07-14 22:32:44 +00001528 Accesses.canCheckPtrAtRT(PtrRtChecking, SE, TheLoop, Strides);
Adam Nemetee614742015-07-09 22:17:38 +00001529 if (!CanDoRTIfNeeded) {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001530 emitAnalysis(LoopAccessReport() << "cannot identify array bounds");
Adam Nemetee614742015-07-09 22:17:38 +00001531 DEBUG(dbgs() << "LAA: We can't vectorize because we can't find "
1532 << "the array bounds.\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001533 CanVecMem = false;
1534 return;
Adam Nemet04563272015-02-01 16:56:15 +00001535 }
1536
Adam Nemetee614742015-07-09 22:17:38 +00001537 DEBUG(dbgs() << "LAA: We can perform a memory runtime check if needed.\n");
Adam Nemet04563272015-02-01 16:56:15 +00001538
Adam Nemet436018c2015-02-19 19:15:00 +00001539 CanVecMem = true;
Adam Nemet04563272015-02-01 16:56:15 +00001540 if (Accesses.isDependencyCheckNeeded()) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001541 DEBUG(dbgs() << "LAA: Checking memory dependencies\n");
Adam Nemet04563272015-02-01 16:56:15 +00001542 CanVecMem = DepChecker.areDepsSafe(
1543 DependentAccesses, Accesses.getDependenciesToCheck(), Strides);
1544 MaxSafeDepDistBytes = DepChecker.getMaxSafeDepDistBytes();
1545
1546 if (!CanVecMem && DepChecker.shouldRetryWithRuntimeCheck()) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001547 DEBUG(dbgs() << "LAA: Retrying with memory checks\n");
Adam Nemet04563272015-02-01 16:56:15 +00001548
1549 // Clear the dependency checks. We assume they are not needed.
Adam Nemetdf3dc5b2015-05-18 15:37:03 +00001550 Accesses.resetDepChecks(DepChecker);
Adam Nemet04563272015-02-01 16:56:15 +00001551
Adam Nemet7cdebac2015-07-14 22:32:44 +00001552 PtrRtChecking.reset();
1553 PtrRtChecking.Need = true;
Adam Nemet04563272015-02-01 16:56:15 +00001554
Adam Nemetee614742015-07-09 22:17:38 +00001555 CanDoRTIfNeeded =
Adam Nemet7cdebac2015-07-14 22:32:44 +00001556 Accesses.canCheckPtrAtRT(PtrRtChecking, SE, TheLoop, Strides, true);
Silviu Baranga98a13712015-06-08 10:27:06 +00001557
Adam Nemet949e91a2015-03-10 19:12:41 +00001558 // Check that we found the bounds for the pointer.
Adam Nemetee614742015-07-09 22:17:38 +00001559 if (!CanDoRTIfNeeded) {
Adam Nemetb6dc76f2015-03-10 18:54:19 +00001560 emitAnalysis(LoopAccessReport()
1561 << "cannot check memory dependencies at runtime");
1562 DEBUG(dbgs() << "LAA: Can't vectorize with memory checks\n");
Adam Nemetb6dc76f2015-03-10 18:54:19 +00001563 CanVecMem = false;
1564 return;
1565 }
1566
Adam Nemet04563272015-02-01 16:56:15 +00001567 CanVecMem = true;
1568 }
1569 }
1570
Adam Nemet4bb90a72015-03-10 21:47:39 +00001571 if (CanVecMem)
1572 DEBUG(dbgs() << "LAA: No unsafe dependent memory operations in loop. We"
Adam Nemet7cdebac2015-07-14 22:32:44 +00001573 << (PtrRtChecking.Need ? "" : " don't")
Adam Nemet0f67c6c2015-07-09 22:17:41 +00001574 << " need runtime memory checks.\n");
Adam Nemet4bb90a72015-03-10 21:47:39 +00001575 else {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001576 emitAnalysis(LoopAccessReport() <<
Adam Nemet04d41632015-02-19 19:14:34 +00001577 "unsafe dependent memory operations in loop");
Adam Nemet4bb90a72015-03-10 21:47:39 +00001578 DEBUG(dbgs() << "LAA: unsafe dependent memory operations in loop\n");
1579 }
Adam Nemet04563272015-02-01 16:56:15 +00001580}
1581
Adam Nemet01abb2c2015-02-18 03:43:19 +00001582bool LoopAccessInfo::blockNeedsPredication(BasicBlock *BB, Loop *TheLoop,
1583 DominatorTree *DT) {
Adam Nemet04563272015-02-01 16:56:15 +00001584 assert(TheLoop->contains(BB) && "Unknown block used");
1585
1586 // Blocks that do not dominate the latch need predication.
1587 BasicBlock* Latch = TheLoop->getLoopLatch();
1588 return !DT->dominates(BB, Latch);
1589}
1590
Adam Nemet2bd6e982015-02-19 19:15:15 +00001591void LoopAccessInfo::emitAnalysis(LoopAccessReport &Message) {
Adam Nemetc9228532015-02-19 19:14:56 +00001592 assert(!Report && "Multiple reports generated");
1593 Report = Message;
Adam Nemet04563272015-02-01 16:56:15 +00001594}
1595
Adam Nemet57ac7662015-02-19 19:15:21 +00001596bool LoopAccessInfo::isUniform(Value *V) const {
Adam Nemet04563272015-02-01 16:56:15 +00001597 return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
1598}
Adam Nemet7206d7a2015-02-06 18:31:04 +00001599
1600// FIXME: this function is currently a duplicate of the one in
1601// LoopVectorize.cpp.
1602static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
1603 Instruction *Loc) {
1604 if (FirstInst)
1605 return FirstInst;
1606 if (Instruction *I = dyn_cast<Instruction>(V))
1607 return I->getParent() == Loc->getParent() ? I : nullptr;
1608 return nullptr;
1609}
1610
Adam Nemet1da7df32015-07-26 05:32:14 +00001611/// \brief IR Values for the lower and upper bounds of a pointer evolution.
1612struct PointerBounds {
1613 Value *Start;
1614 Value *End;
1615};
Adam Nemet7206d7a2015-02-06 18:31:04 +00001616
Adam Nemet1da7df32015-07-26 05:32:14 +00001617/// \brief Expand code for the lower and upper bound of the pointer group \p CG
1618/// in \p TheLoop. \return the values for the bounds.
1619static PointerBounds
1620expandBounds(const RuntimePointerChecking::CheckingPtrGroup *CG, Loop *TheLoop,
1621 Instruction *Loc, SCEVExpander &Exp, ScalarEvolution *SE,
1622 const RuntimePointerChecking &PtrRtChecking) {
1623 Value *Ptr = PtrRtChecking.Pointers[CG->Members[0]].PointerValue;
1624 const SCEV *Sc = SE->getSCEV(Ptr);
1625
1626 if (SE->isLoopInvariant(Sc, TheLoop)) {
1627 DEBUG(dbgs() << "LAA: Adding RT check for a loop invariant ptr:" << *Ptr
1628 << "\n");
1629 return {Ptr, Ptr};
1630 } else {
1631 unsigned AS = Ptr->getType()->getPointerAddressSpace();
1632 LLVMContext &Ctx = Loc->getContext();
1633
1634 // Use this type for pointer arithmetic.
1635 Type *PtrArithTy = Type::getInt8PtrTy(Ctx, AS);
1636 Value *Start = nullptr, *End = nullptr;
1637
1638 DEBUG(dbgs() << "LAA: Adding RT check for range:\n");
1639 Start = Exp.expandCodeFor(CG->Low, PtrArithTy, Loc);
1640 End = Exp.expandCodeFor(CG->High, PtrArithTy, Loc);
1641 DEBUG(dbgs() << "Start: " << *CG->Low << " End: " << *CG->High << "\n");
1642 return {Start, End};
1643 }
1644}
1645
1646/// \brief Turns a collection of checks into a collection of expanded upper and
1647/// lower bounds for both pointers in the check.
1648static SmallVector<std::pair<PointerBounds, PointerBounds>, 4> expandBounds(
1649 const SmallVectorImpl<RuntimePointerChecking::PointerCheck> &PointerChecks,
1650 Loop *L, Instruction *Loc, ScalarEvolution *SE, SCEVExpander &Exp,
1651 const RuntimePointerChecking &PtrRtChecking) {
1652 SmallVector<std::pair<PointerBounds, PointerBounds>, 4> ChecksWithBounds;
1653
1654 // Here we're relying on the SCEV Expander's cache to only emit code for the
1655 // same bounds once.
1656 std::transform(
1657 PointerChecks.begin(), PointerChecks.end(),
1658 std::back_inserter(ChecksWithBounds),
1659 [&](const RuntimePointerChecking::PointerCheck &Check) {
NAKAMURA Takumi94abbbd2015-07-27 01:35:30 +00001660 PointerBounds
1661 First = expandBounds(Check.first, L, Loc, Exp, SE, PtrRtChecking),
1662 Second = expandBounds(Check.second, L, Loc, Exp, SE, PtrRtChecking);
1663 return std::make_pair(First, Second);
Adam Nemet1da7df32015-07-26 05:32:14 +00001664 });
1665
1666 return ChecksWithBounds;
1667}
1668
1669std::pair<Instruction *, Instruction *> LoopAccessInfo::addRuntimeCheck(
1670 Instruction *Loc,
1671 const SmallVectorImpl<RuntimePointerChecking::PointerCheck> &PointerChecks)
1672 const {
1673
1674 SCEVExpander Exp(*SE, DL, "induction");
1675 auto ExpandedChecks =
1676 expandBounds(PointerChecks, TheLoop, Loc, SE, Exp, PtrRtChecking);
Adam Nemet7206d7a2015-02-06 18:31:04 +00001677
1678 LLVMContext &Ctx = Loc->getContext();
Adam Nemet7206d7a2015-02-06 18:31:04 +00001679 Instruction *FirstInst = nullptr;
Adam Nemet7206d7a2015-02-06 18:31:04 +00001680 IRBuilder<> ChkBuilder(Loc);
1681 // Our instructions might fold to a constant.
1682 Value *MemoryRuntimeCheck = nullptr;
Silviu Baranga1b6b50a2015-07-08 09:16:33 +00001683
Adam Nemet1da7df32015-07-26 05:32:14 +00001684 for (const auto &Check : ExpandedChecks) {
1685 const PointerBounds &A = Check.first, &B = Check.second;
1686 unsigned AS0 = A.Start->getType()->getPointerAddressSpace();
1687 unsigned AS1 = B.Start->getType()->getPointerAddressSpace();
Adam Nemet7206d7a2015-02-06 18:31:04 +00001688
Adam Nemet1da7df32015-07-26 05:32:14 +00001689 assert((AS0 == B.End->getType()->getPointerAddressSpace()) &&
1690 (AS1 == A.End->getType()->getPointerAddressSpace()) &&
1691 "Trying to bounds check pointers with different address spaces");
Adam Nemet7206d7a2015-02-06 18:31:04 +00001692
Adam Nemet1da7df32015-07-26 05:32:14 +00001693 Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0);
1694 Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1);
Adam Nemet7206d7a2015-02-06 18:31:04 +00001695
Adam Nemet1da7df32015-07-26 05:32:14 +00001696 Value *Start0 = ChkBuilder.CreateBitCast(A.Start, PtrArithTy0, "bc");
1697 Value *Start1 = ChkBuilder.CreateBitCast(B.Start, PtrArithTy1, "bc");
1698 Value *End0 = ChkBuilder.CreateBitCast(A.End, PtrArithTy1, "bc");
1699 Value *End1 = ChkBuilder.CreateBitCast(B.End, PtrArithTy0, "bc");
Adam Nemet7206d7a2015-02-06 18:31:04 +00001700
Adam Nemet1da7df32015-07-26 05:32:14 +00001701 Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0");
1702 FirstInst = getFirstInst(FirstInst, Cmp0, Loc);
1703 Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1");
1704 FirstInst = getFirstInst(FirstInst, Cmp1, Loc);
1705 Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
1706 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1707 if (MemoryRuntimeCheck) {
1708 IsConflict =
1709 ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict, "conflict.rdx");
Adam Nemet7206d7a2015-02-06 18:31:04 +00001710 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
Adam Nemet7206d7a2015-02-06 18:31:04 +00001711 }
Adam Nemet1da7df32015-07-26 05:32:14 +00001712 MemoryRuntimeCheck = IsConflict;
Adam Nemet7206d7a2015-02-06 18:31:04 +00001713 }
1714
Adam Nemet90fec842015-04-02 17:51:57 +00001715 if (!MemoryRuntimeCheck)
1716 return std::make_pair(nullptr, nullptr);
1717
Adam Nemet7206d7a2015-02-06 18:31:04 +00001718 // We have to do this trickery because the IRBuilder might fold the check to a
1719 // constant expression in which case there is no Instruction anchored in a
1720 // the block.
1721 Instruction *Check = BinaryOperator::CreateAnd(MemoryRuntimeCheck,
1722 ConstantInt::getTrue(Ctx));
1723 ChkBuilder.Insert(Check, "memcheck.conflict");
1724 FirstInst = getFirstInst(FirstInst, Check, Loc);
1725 return std::make_pair(FirstInst, Check);
1726}
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001727
Adam Nemet1da7df32015-07-26 05:32:14 +00001728std::pair<Instruction *, Instruction *> LoopAccessInfo::addRuntimeCheck(
Adam Nemet87011182015-08-04 05:16:20 +00001729 Instruction *Loc) const {
Adam Nemet1da7df32015-07-26 05:32:14 +00001730 if (!PtrRtChecking.Need)
1731 return std::make_pair(nullptr, nullptr);
1732
Adam Nemet87011182015-08-04 05:16:20 +00001733 return addRuntimeCheck(Loc, PtrRtChecking.generateChecks());
Adam Nemet1da7df32015-07-26 05:32:14 +00001734}
1735
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001736LoopAccessInfo::LoopAccessInfo(Loop *L, ScalarEvolution *SE,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001737 const DataLayout &DL,
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001738 const TargetLibraryInfo *TLI, AliasAnalysis *AA,
Adam Nemete2b885c2015-04-23 20:09:20 +00001739 DominatorTree *DT, LoopInfo *LI,
Adam Nemet8bc61df2015-02-24 00:41:59 +00001740 const ValueToValueMap &Strides)
Adam Nemet7cdebac2015-07-14 22:32:44 +00001741 : PtrRtChecking(SE), DepChecker(SE, L), TheLoop(L), SE(SE), DL(DL),
1742 TLI(TLI), AA(AA), DT(DT), LI(LI), NumLoads(0), NumStores(0),
Adam Nemetce482502015-04-08 17:48:40 +00001743 MaxSafeDepDistBytes(-1U), CanVecMem(false),
1744 StoreToLoopInvariantAddress(false) {
Adam Nemet929c38e2015-02-19 19:15:10 +00001745 if (canAnalyzeLoop())
1746 analyzeLoop(Strides);
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001747}
1748
Adam Nemete91cc6e2015-02-19 19:15:19 +00001749void LoopAccessInfo::print(raw_ostream &OS, unsigned Depth) const {
1750 if (CanVecMem) {
Adam Nemet7cdebac2015-07-14 22:32:44 +00001751 if (PtrRtChecking.Need)
Adam Nemete91cc6e2015-02-19 19:15:19 +00001752 OS.indent(Depth) << "Memory dependences are safe with run-time checks\n";
Adam Nemet26da8e92015-04-14 01:12:55 +00001753 else
1754 OS.indent(Depth) << "Memory dependences are safe\n";
Adam Nemete91cc6e2015-02-19 19:15:19 +00001755 }
1756
1757 if (Report)
1758 OS.indent(Depth) << "Report: " << Report->str() << "\n";
1759
Adam Nemet58913d62015-03-10 17:40:43 +00001760 if (auto *InterestingDependences = DepChecker.getInterestingDependences()) {
1761 OS.indent(Depth) << "Interesting Dependences:\n";
1762 for (auto &Dep : *InterestingDependences) {
1763 Dep.print(OS, Depth + 2, DepChecker.getMemoryInstructions());
1764 OS << "\n";
1765 }
1766 } else
1767 OS.indent(Depth) << "Too many interesting dependences, not recorded\n";
Adam Nemete91cc6e2015-02-19 19:15:19 +00001768
1769 // List the pair of accesses need run-time checks to prove independence.
Adam Nemet7cdebac2015-07-14 22:32:44 +00001770 PtrRtChecking.print(OS, Depth);
Adam Nemete91cc6e2015-02-19 19:15:19 +00001771 OS << "\n";
Adam Nemetc3384322015-05-18 15:36:57 +00001772
1773 OS.indent(Depth) << "Store to invariant address was "
1774 << (StoreToLoopInvariantAddress ? "" : "not ")
1775 << "found in loop.\n";
Adam Nemete91cc6e2015-02-19 19:15:19 +00001776}
1777
Adam Nemet8bc61df2015-02-24 00:41:59 +00001778const LoopAccessInfo &
1779LoopAccessAnalysis::getInfo(Loop *L, const ValueToValueMap &Strides) {
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001780 auto &LAI = LoopAccessInfoMap[L];
1781
1782#ifndef NDEBUG
1783 assert((!LAI || LAI->NumSymbolicStrides == Strides.size()) &&
1784 "Symbolic strides changed for loop");
1785#endif
1786
1787 if (!LAI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001788 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
Adam Nemete2b885c2015-04-23 20:09:20 +00001789 LAI = llvm::make_unique<LoopAccessInfo>(L, SE, DL, TLI, AA, DT, LI,
1790 Strides);
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001791#ifndef NDEBUG
1792 LAI->NumSymbolicStrides = Strides.size();
1793#endif
1794 }
1795 return *LAI.get();
1796}
1797
Adam Nemete91cc6e2015-02-19 19:15:19 +00001798void LoopAccessAnalysis::print(raw_ostream &OS, const Module *M) const {
1799 LoopAccessAnalysis &LAA = *const_cast<LoopAccessAnalysis *>(this);
1800
Adam Nemete91cc6e2015-02-19 19:15:19 +00001801 ValueToValueMap NoSymbolicStrides;
1802
1803 for (Loop *TopLevelLoop : *LI)
1804 for (Loop *L : depth_first(TopLevelLoop)) {
1805 OS.indent(2) << L->getHeader()->getName() << ":\n";
1806 auto &LAI = LAA.getInfo(L, NoSymbolicStrides);
1807 LAI.print(OS, 4);
1808 }
1809}
1810
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001811bool LoopAccessAnalysis::runOnFunction(Function &F) {
1812 SE = &getAnalysis<ScalarEvolution>();
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001813 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
1814 TLI = TLIP ? &TLIP->getTLI() : nullptr;
1815 AA = &getAnalysis<AliasAnalysis>();
1816 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Adam Nemete2b885c2015-04-23 20:09:20 +00001817 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001818
1819 return false;
1820}
1821
1822void LoopAccessAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
1823 AU.addRequired<ScalarEvolution>();
1824 AU.addRequired<AliasAnalysis>();
1825 AU.addRequired<DominatorTreeWrapperPass>();
Adam Nemete91cc6e2015-02-19 19:15:19 +00001826 AU.addRequired<LoopInfoWrapperPass>();
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001827
1828 AU.setPreservesAll();
1829}
1830
1831char LoopAccessAnalysis::ID = 0;
1832static const char laa_name[] = "Loop Access Analysis";
1833#define LAA_NAME "loop-accesses"
1834
1835INITIALIZE_PASS_BEGIN(LoopAccessAnalysis, LAA_NAME, laa_name, false, true)
1836INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
1837INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
1838INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Adam Nemete91cc6e2015-02-19 19:15:19 +00001839INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001840INITIALIZE_PASS_END(LoopAccessAnalysis, LAA_NAME, laa_name, false, true)
1841
1842namespace llvm {
1843 Pass *createLAAPass() {
1844 return new LoopAccessAnalysis();
1845 }
1846}