blob: 7227d4870027f6a48ad20e11f9ca439f1a08ef9f [file] [log] [blame]
Adam Nemet04563272015-02-01 16:56:15 +00001//===- LoopAccessAnalysis.cpp - Loop Access Analysis Implementation --------==//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// The implementation for the loop memory dependence that was originally
11// developed for the loop vectorizer.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Analysis/LoopAccessAnalysis.h"
16#include "llvm/Analysis/LoopInfo.h"
Adam Nemet7206d7a2015-02-06 18:31:04 +000017#include "llvm/Analysis/ScalarEvolutionExpander.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000018#include "llvm/Analysis/TargetLibraryInfo.h"
Adam Nemet04563272015-02-01 16:56:15 +000019#include "llvm/Analysis/ValueTracking.h"
20#include "llvm/IR/DiagnosticInfo.h"
21#include "llvm/IR/Dominators.h"
Adam Nemet7206d7a2015-02-06 18:31:04 +000022#include "llvm/IR/IRBuilder.h"
Adam Nemet04563272015-02-01 16:56:15 +000023#include "llvm/Support/Debug.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000024#include "llvm/Support/raw_ostream.h"
David Blaikieb447ac62015-06-26 18:02:52 +000025#include "llvm/Analysis/VectorUtils.h"
Adam Nemet04563272015-02-01 16:56:15 +000026using namespace llvm;
27
Adam Nemet339f42b2015-02-19 19:15:07 +000028#define DEBUG_TYPE "loop-accesses"
Adam Nemet04563272015-02-01 16:56:15 +000029
Adam Nemetf219c642015-02-19 19:14:52 +000030static cl::opt<unsigned, true>
31VectorizationFactor("force-vector-width", cl::Hidden,
32 cl::desc("Sets the SIMD width. Zero is autoselect."),
33 cl::location(VectorizerParams::VectorizationFactor));
Adam Nemet1d862af2015-02-26 04:39:09 +000034unsigned VectorizerParams::VectorizationFactor;
Adam Nemetf219c642015-02-19 19:14:52 +000035
36static cl::opt<unsigned, true>
37VectorizationInterleave("force-vector-interleave", cl::Hidden,
38 cl::desc("Sets the vectorization interleave count. "
39 "Zero is autoselect."),
40 cl::location(
41 VectorizerParams::VectorizationInterleave));
Adam Nemet1d862af2015-02-26 04:39:09 +000042unsigned VectorizerParams::VectorizationInterleave;
Adam Nemetf219c642015-02-19 19:14:52 +000043
Adam Nemet1d862af2015-02-26 04:39:09 +000044static cl::opt<unsigned, true> RuntimeMemoryCheckThreshold(
45 "runtime-memory-check-threshold", cl::Hidden,
46 cl::desc("When performing memory disambiguation checks at runtime do not "
47 "generate more than this number of comparisons (default = 8)."),
48 cl::location(VectorizerParams::RuntimeMemoryCheckThreshold), cl::init(8));
49unsigned VectorizerParams::RuntimeMemoryCheckThreshold;
Adam Nemetf219c642015-02-19 19:14:52 +000050
Silviu Baranga1b6b50a2015-07-08 09:16:33 +000051/// \brief The maximum iterations used to merge memory checks
52static cl::opt<unsigned> MemoryCheckMergeThreshold(
53 "memory-check-merge-threshold", cl::Hidden,
54 cl::desc("Maximum number of comparisons done when trying to merge "
55 "runtime memory checks. (default = 100)"),
56 cl::init(100));
57
Adam Nemetf219c642015-02-19 19:14:52 +000058/// Maximum SIMD width.
59const unsigned VectorizerParams::MaxVectorWidth = 64;
60
Adam Nemeta2df7502015-11-03 21:39:52 +000061/// \brief We collect dependences up to this threshold.
62static cl::opt<unsigned>
63 MaxDependences("max-dependences", cl::Hidden,
64 cl::desc("Maximum number of dependences collected by "
65 "loop-access analysis (default = 100)"),
66 cl::init(100));
Adam Nemet9c926572015-03-10 17:40:37 +000067
Adam Nemetf219c642015-02-19 19:14:52 +000068bool VectorizerParams::isInterleaveForced() {
69 return ::VectorizationInterleave.getNumOccurrences() > 0;
70}
71
Adam Nemet2bd6e982015-02-19 19:15:15 +000072void LoopAccessReport::emitAnalysis(const LoopAccessReport &Message,
73 const Function *TheFunction,
74 const Loop *TheLoop,
75 const char *PassName) {
Adam Nemet04563272015-02-01 16:56:15 +000076 DebugLoc DL = TheLoop->getStartLoc();
Adam Nemet3e876342015-02-19 19:15:13 +000077 if (const Instruction *I = Message.getInstr())
Adam Nemet04563272015-02-01 16:56:15 +000078 DL = I->getDebugLoc();
Adam Nemet339f42b2015-02-19 19:15:07 +000079 emitOptimizationRemarkAnalysis(TheFunction->getContext(), PassName,
Adam Nemet04563272015-02-01 16:56:15 +000080 *TheFunction, DL, Message.str());
81}
82
83Value *llvm::stripIntegerCast(Value *V) {
84 if (CastInst *CI = dyn_cast<CastInst>(V))
85 if (CI->getOperand(0)->getType()->isIntegerTy())
86 return CI->getOperand(0);
87 return V;
88}
89
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000090const SCEV *llvm::replaceSymbolicStrideSCEV(PredicatedScalarEvolution &PSE,
Adam Nemet8bc61df2015-02-24 00:41:59 +000091 const ValueToValueMap &PtrToStride,
Adam Nemet04563272015-02-01 16:56:15 +000092 Value *Ptr, Value *OrigPtr) {
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000093 const SCEV *OrigSCEV = PSE.getSCEV(Ptr);
Adam Nemet04563272015-02-01 16:56:15 +000094
95 // If there is an entry in the map return the SCEV of the pointer with the
96 // symbolic stride replaced by one.
Adam Nemet8bc61df2015-02-24 00:41:59 +000097 ValueToValueMap::const_iterator SI =
98 PtrToStride.find(OrigPtr ? OrigPtr : Ptr);
Adam Nemet04563272015-02-01 16:56:15 +000099 if (SI != PtrToStride.end()) {
100 Value *StrideVal = SI->second;
101
102 // Strip casts.
103 StrideVal = stripIntegerCast(StrideVal);
104
105 // Replace symbolic stride by one.
106 Value *One = ConstantInt::get(StrideVal->getType(), 1);
107 ValueToValueMap RewriteMap;
108 RewriteMap[StrideVal] = One;
109
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +0000110 ScalarEvolution *SE = PSE.getSE();
Silviu Barangae3c05342015-11-02 14:41:02 +0000111 const auto *U = cast<SCEVUnknown>(SE->getSCEV(StrideVal));
112 const auto *CT =
113 static_cast<const SCEVConstant *>(SE->getOne(StrideVal->getType()));
114
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +0000115 PSE.addPredicate(*SE->getEqualPredicate(U, CT));
116 auto *Expr = PSE.getSCEV(Ptr);
Silviu Barangae3c05342015-11-02 14:41:02 +0000117
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +0000118 DEBUG(dbgs() << "LAA: Replacing SCEV: " << *OrigSCEV << " by: " << *Expr
Adam Nemet04563272015-02-01 16:56:15 +0000119 << "\n");
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +0000120 return Expr;
Adam Nemet04563272015-02-01 16:56:15 +0000121 }
122
123 // Otherwise, just return the SCEV of the original pointer.
Silviu Barangae3c05342015-11-02 14:41:02 +0000124 return OrigSCEV;
Adam Nemet04563272015-02-01 16:56:15 +0000125}
126
Adam Nemet7cdebac2015-07-14 22:32:44 +0000127void RuntimePointerChecking::insert(Loop *Lp, Value *Ptr, bool WritePtr,
128 unsigned DepSetId, unsigned ASId,
Silviu Barangae3c05342015-11-02 14:41:02 +0000129 const ValueToValueMap &Strides,
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +0000130 PredicatedScalarEvolution &PSE) {
Adam Nemet04563272015-02-01 16:56:15 +0000131 // Get the stride replaced scev.
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +0000132 const SCEV *Sc = replaceSymbolicStrideSCEV(PSE, Strides, Ptr);
Adam Nemet04563272015-02-01 16:56:15 +0000133 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
134 assert(AR && "Invalid addrec expression");
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +0000135 ScalarEvolution *SE = PSE.getSE();
Adam Nemet04563272015-02-01 16:56:15 +0000136 const SCEV *Ex = SE->getBackedgeTakenCount(Lp);
Silviu Baranga0e5804a2015-07-16 14:02:58 +0000137
138 const SCEV *ScStart = AR->getStart();
Adam Nemet04563272015-02-01 16:56:15 +0000139 const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
Silviu Baranga0e5804a2015-07-16 14:02:58 +0000140 const SCEV *Step = AR->getStepRecurrence(*SE);
141
142 // For expressions with negative step, the upper bound is ScStart and the
143 // lower bound is ScEnd.
144 if (const SCEVConstant *CStep = dyn_cast<const SCEVConstant>(Step)) {
145 if (CStep->getValue()->isNegative())
146 std::swap(ScStart, ScEnd);
147 } else {
148 // Fallback case: the step is not constant, but the we can still
149 // get the upper and lower bounds of the interval by using min/max
150 // expressions.
151 ScStart = SE->getUMinExpr(ScStart, ScEnd);
152 ScEnd = SE->getUMaxExpr(AR->getStart(), ScEnd);
153 }
154
155 Pointers.emplace_back(Ptr, ScStart, ScEnd, WritePtr, DepSetId, ASId, Sc);
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000156}
157
Adam Nemetbbe1f1d2015-07-27 19:38:48 +0000158SmallVector<RuntimePointerChecking::PointerCheck, 4>
Adam Nemet38530882015-08-09 20:06:06 +0000159RuntimePointerChecking::generateChecks() const {
Adam Nemetbbe1f1d2015-07-27 19:38:48 +0000160 SmallVector<PointerCheck, 4> Checks;
161
Adam Nemet7c52e052015-07-27 19:38:50 +0000162 for (unsigned I = 0; I < CheckingGroups.size(); ++I) {
163 for (unsigned J = I + 1; J < CheckingGroups.size(); ++J) {
164 const RuntimePointerChecking::CheckingPtrGroup &CGI = CheckingGroups[I];
165 const RuntimePointerChecking::CheckingPtrGroup &CGJ = CheckingGroups[J];
Adam Nemetbbe1f1d2015-07-27 19:38:48 +0000166
Adam Nemet38530882015-08-09 20:06:06 +0000167 if (needsChecking(CGI, CGJ))
Adam Nemetbbe1f1d2015-07-27 19:38:48 +0000168 Checks.push_back(std::make_pair(&CGI, &CGJ));
169 }
170 }
171 return Checks;
172}
173
Adam Nemet15840392015-08-07 22:44:15 +0000174void RuntimePointerChecking::generateChecks(
175 MemoryDepChecker::DepCandidates &DepCands, bool UseDependencies) {
176 assert(Checks.empty() && "Checks is not empty");
177 groupChecks(DepCands, UseDependencies);
178 Checks = generateChecks();
179}
180
Adam Nemet651a5a22015-08-09 20:06:08 +0000181bool RuntimePointerChecking::needsChecking(const CheckingPtrGroup &M,
182 const CheckingPtrGroup &N) const {
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000183 for (unsigned I = 0, EI = M.Members.size(); EI != I; ++I)
184 for (unsigned J = 0, EJ = N.Members.size(); EJ != J; ++J)
Adam Nemet651a5a22015-08-09 20:06:08 +0000185 if (needsChecking(M.Members[I], N.Members[J]))
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000186 return true;
187 return false;
188}
189
190/// Compare \p I and \p J and return the minimum.
191/// Return nullptr in case we couldn't find an answer.
192static const SCEV *getMinFromExprs(const SCEV *I, const SCEV *J,
193 ScalarEvolution *SE) {
194 const SCEV *Diff = SE->getMinusSCEV(J, I);
195 const SCEVConstant *C = dyn_cast<const SCEVConstant>(Diff);
196
197 if (!C)
198 return nullptr;
199 if (C->getValue()->isNegative())
200 return J;
201 return I;
202}
203
Adam Nemet7cdebac2015-07-14 22:32:44 +0000204bool RuntimePointerChecking::CheckingPtrGroup::addPointer(unsigned Index) {
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000205 const SCEV *Start = RtCheck.Pointers[Index].Start;
206 const SCEV *End = RtCheck.Pointers[Index].End;
207
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000208 // Compare the starts and ends with the known minimum and maximum
209 // of this set. We need to know how we compare against the min/max
210 // of the set in order to be able to emit memchecks.
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000211 const SCEV *Min0 = getMinFromExprs(Start, Low, RtCheck.SE);
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000212 if (!Min0)
213 return false;
214
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000215 const SCEV *Min1 = getMinFromExprs(End, High, RtCheck.SE);
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000216 if (!Min1)
217 return false;
218
219 // Update the low bound expression if we've found a new min value.
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000220 if (Min0 == Start)
221 Low = Start;
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000222
223 // Update the high bound expression if we've found a new max value.
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000224 if (Min1 != End)
225 High = End;
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000226
227 Members.push_back(Index);
228 return true;
229}
230
Adam Nemet7cdebac2015-07-14 22:32:44 +0000231void RuntimePointerChecking::groupChecks(
232 MemoryDepChecker::DepCandidates &DepCands, bool UseDependencies) {
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000233 // We build the groups from dependency candidates equivalence classes
234 // because:
235 // - We know that pointers in the same equivalence class share
236 // the same underlying object and therefore there is a chance
237 // that we can compare pointers
238 // - We wouldn't be able to merge two pointers for which we need
239 // to emit a memcheck. The classes in DepCands are already
240 // conveniently built such that no two pointers in the same
241 // class need checking against each other.
242
243 // We use the following (greedy) algorithm to construct the groups
244 // For every pointer in the equivalence class:
245 // For each existing group:
246 // - if the difference between this pointer and the min/max bounds
247 // of the group is a constant, then make the pointer part of the
248 // group and update the min/max bounds of that group as required.
249
250 CheckingGroups.clear();
251
Silviu Baranga48250602015-07-28 13:44:08 +0000252 // If we need to check two pointers to the same underlying object
253 // with a non-constant difference, we shouldn't perform any pointer
254 // grouping with those pointers. This is because we can easily get
255 // into cases where the resulting check would return false, even when
256 // the accesses are safe.
257 //
258 // The following example shows this:
259 // for (i = 0; i < 1000; ++i)
260 // a[5000 + i * m] = a[i] + a[i + 9000]
261 //
262 // Here grouping gives a check of (5000, 5000 + 1000 * m) against
263 // (0, 10000) which is always false. However, if m is 1, there is no
264 // dependence. Not grouping the checks for a[i] and a[i + 9000] allows
265 // us to perform an accurate check in this case.
266 //
267 // The above case requires that we have an UnknownDependence between
268 // accesses to the same underlying object. This cannot happen unless
269 // ShouldRetryWithRuntimeCheck is set, and therefore UseDependencies
270 // is also false. In this case we will use the fallback path and create
271 // separate checking groups for all pointers.
Mehdi Aminiafd13512015-11-05 05:49:43 +0000272
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000273 // If we don't have the dependency partitions, construct a new
Silviu Baranga48250602015-07-28 13:44:08 +0000274 // checking pointer group for each pointer. This is also required
275 // for correctness, because in this case we can have checking between
276 // pointers to the same underlying object.
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000277 if (!UseDependencies) {
278 for (unsigned I = 0; I < Pointers.size(); ++I)
279 CheckingGroups.push_back(CheckingPtrGroup(I, *this));
280 return;
281 }
282
283 unsigned TotalComparisons = 0;
284
285 DenseMap<Value *, unsigned> PositionMap;
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000286 for (unsigned Index = 0; Index < Pointers.size(); ++Index)
287 PositionMap[Pointers[Index].PointerValue] = Index;
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000288
Silviu Barangace3877f2015-07-09 15:18:25 +0000289 // We need to keep track of what pointers we've already seen so we
290 // don't process them twice.
291 SmallSet<unsigned, 2> Seen;
292
Sanjay Patele4b9f502015-12-07 19:21:39 +0000293 // Go through all equivalence classes, get the "pointer check groups"
Silviu Barangace3877f2015-07-09 15:18:25 +0000294 // and add them to the overall solution. We use the order in which accesses
295 // appear in 'Pointers' to enforce determinism.
296 for (unsigned I = 0; I < Pointers.size(); ++I) {
297 // We've seen this pointer before, and therefore already processed
298 // its equivalence class.
299 if (Seen.count(I))
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000300 continue;
301
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000302 MemoryDepChecker::MemAccessInfo Access(Pointers[I].PointerValue,
303 Pointers[I].IsWritePtr);
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000304
Silviu Barangace3877f2015-07-09 15:18:25 +0000305 SmallVector<CheckingPtrGroup, 2> Groups;
306 auto LeaderI = DepCands.findValue(DepCands.getLeaderValue(Access));
307
Silviu Barangaa647c302015-07-13 14:48:24 +0000308 // Because DepCands is constructed by visiting accesses in the order in
309 // which they appear in alias sets (which is deterministic) and the
310 // iteration order within an equivalence class member is only dependent on
311 // the order in which unions and insertions are performed on the
312 // equivalence class, the iteration order is deterministic.
Silviu Barangace3877f2015-07-09 15:18:25 +0000313 for (auto MI = DepCands.member_begin(LeaderI), ME = DepCands.member_end();
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000314 MI != ME; ++MI) {
315 unsigned Pointer = PositionMap[MI->getPointer()];
316 bool Merged = false;
Silviu Barangace3877f2015-07-09 15:18:25 +0000317 // Mark this pointer as seen.
318 Seen.insert(Pointer);
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000319
320 // Go through all the existing sets and see if we can find one
321 // which can include this pointer.
322 for (CheckingPtrGroup &Group : Groups) {
323 // Don't perform more than a certain amount of comparisons.
324 // This should limit the cost of grouping the pointers to something
325 // reasonable. If we do end up hitting this threshold, the algorithm
326 // will create separate groups for all remaining pointers.
327 if (TotalComparisons > MemoryCheckMergeThreshold)
328 break;
329
330 TotalComparisons++;
331
332 if (Group.addPointer(Pointer)) {
333 Merged = true;
334 break;
335 }
336 }
337
338 if (!Merged)
339 // We couldn't add this pointer to any existing set or the threshold
340 // for the number of comparisons has been reached. Create a new group
341 // to hold the current pointer.
342 Groups.push_back(CheckingPtrGroup(Pointer, *this));
343 }
344
345 // We've computed the grouped checks for this partition.
346 // Save the results and continue with the next one.
347 std::copy(Groups.begin(), Groups.end(), std::back_inserter(CheckingGroups));
348 }
Adam Nemet04563272015-02-01 16:56:15 +0000349}
350
Adam Nemet041e6de2015-07-16 02:48:05 +0000351bool RuntimePointerChecking::arePointersInSamePartition(
352 const SmallVectorImpl<int> &PtrToPartition, unsigned PtrIdx1,
353 unsigned PtrIdx2) {
354 return (PtrToPartition[PtrIdx1] != -1 &&
355 PtrToPartition[PtrIdx1] == PtrToPartition[PtrIdx2]);
356}
357
Adam Nemet651a5a22015-08-09 20:06:08 +0000358bool RuntimePointerChecking::needsChecking(unsigned I, unsigned J) const {
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000359 const PointerInfo &PointerI = Pointers[I];
360 const PointerInfo &PointerJ = Pointers[J];
361
Adam Nemeta8945b72015-02-18 03:43:58 +0000362 // No need to check if two readonly pointers intersect.
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000363 if (!PointerI.IsWritePtr && !PointerJ.IsWritePtr)
Adam Nemeta8945b72015-02-18 03:43:58 +0000364 return false;
365
366 // Only need to check pointers between two different dependency sets.
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000367 if (PointerI.DependencySetId == PointerJ.DependencySetId)
Adam Nemeta8945b72015-02-18 03:43:58 +0000368 return false;
369
370 // Only need to check pointers in the same alias set.
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000371 if (PointerI.AliasSetId != PointerJ.AliasSetId)
Adam Nemeta8945b72015-02-18 03:43:58 +0000372 return false;
373
374 return true;
375}
376
Adam Nemet54f0b832015-07-27 23:54:41 +0000377void RuntimePointerChecking::printChecks(
378 raw_ostream &OS, const SmallVectorImpl<PointerCheck> &Checks,
379 unsigned Depth) const {
380 unsigned N = 0;
381 for (const auto &Check : Checks) {
382 const auto &First = Check.first->Members, &Second = Check.second->Members;
383
384 OS.indent(Depth) << "Check " << N++ << ":\n";
385
386 OS.indent(Depth + 2) << "Comparing group (" << Check.first << "):\n";
387 for (unsigned K = 0; K < First.size(); ++K)
388 OS.indent(Depth + 2) << *Pointers[First[K]].PointerValue << "\n";
389
390 OS.indent(Depth + 2) << "Against group (" << Check.second << "):\n";
391 for (unsigned K = 0; K < Second.size(); ++K)
392 OS.indent(Depth + 2) << *Pointers[Second[K]].PointerValue << "\n";
393 }
394}
395
Adam Nemet3a91e942015-08-07 19:44:48 +0000396void RuntimePointerChecking::print(raw_ostream &OS, unsigned Depth) const {
Adam Nemete91cc6e2015-02-19 19:15:19 +0000397
398 OS.indent(Depth) << "Run-time memory checks:\n";
Adam Nemet15840392015-08-07 22:44:15 +0000399 printChecks(OS, Checks, Depth);
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000400
401 OS.indent(Depth) << "Grouped accesses:\n";
402 for (unsigned I = 0; I < CheckingGroups.size(); ++I) {
Adam Nemet54f0b832015-07-27 23:54:41 +0000403 const auto &CG = CheckingGroups[I];
404
405 OS.indent(Depth + 2) << "Group " << &CG << ":\n";
406 OS.indent(Depth + 4) << "(Low: " << *CG.Low << " High: " << *CG.High
407 << ")\n";
408 for (unsigned J = 0; J < CG.Members.size(); ++J) {
409 OS.indent(Depth + 6) << "Member: " << *Pointers[CG.Members[J]].Expr
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000410 << "\n";
411 }
412 }
Adam Nemete91cc6e2015-02-19 19:15:19 +0000413}
414
Adam Nemet04563272015-02-01 16:56:15 +0000415namespace {
416/// \brief Analyses memory accesses in a loop.
417///
418/// Checks whether run time pointer checks are needed and builds sets for data
419/// dependence checking.
420class AccessAnalysis {
421public:
422 /// \brief Read or write access location.
423 typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
424 typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
425
Adam Nemete2b885c2015-04-23 20:09:20 +0000426 AccessAnalysis(const DataLayout &Dl, AliasAnalysis *AA, LoopInfo *LI,
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +0000427 MemoryDepChecker::DepCandidates &DA,
428 PredicatedScalarEvolution &PSE)
Silviu Barangae3c05342015-11-02 14:41:02 +0000429 : DL(Dl), AST(*AA), LI(LI), DepCands(DA), IsRTCheckAnalysisNeeded(false),
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +0000430 PSE(PSE) {}
Adam Nemet04563272015-02-01 16:56:15 +0000431
432 /// \brief Register a load and whether it is only read from.
Chandler Carruthac80dc72015-06-17 07:18:54 +0000433 void addLoad(MemoryLocation &Loc, bool IsReadOnly) {
Adam Nemet04563272015-02-01 16:56:15 +0000434 Value *Ptr = const_cast<Value*>(Loc.Ptr);
Chandler Carruthecbd1682015-06-17 07:21:38 +0000435 AST.add(Ptr, MemoryLocation::UnknownSize, Loc.AATags);
Adam Nemet04563272015-02-01 16:56:15 +0000436 Accesses.insert(MemAccessInfo(Ptr, false));
437 if (IsReadOnly)
438 ReadOnlyPtr.insert(Ptr);
439 }
440
441 /// \brief Register a store.
Chandler Carruthac80dc72015-06-17 07:18:54 +0000442 void addStore(MemoryLocation &Loc) {
Adam Nemet04563272015-02-01 16:56:15 +0000443 Value *Ptr = const_cast<Value*>(Loc.Ptr);
Chandler Carruthecbd1682015-06-17 07:21:38 +0000444 AST.add(Ptr, MemoryLocation::UnknownSize, Loc.AATags);
Adam Nemet04563272015-02-01 16:56:15 +0000445 Accesses.insert(MemAccessInfo(Ptr, true));
446 }
447
448 /// \brief Check whether we can check the pointers at runtime for
Adam Nemetee614742015-07-09 22:17:38 +0000449 /// non-intersection.
450 ///
451 /// Returns true if we need no check or if we do and we can generate them
452 /// (i.e. the pointers have computable bounds).
Adam Nemet7cdebac2015-07-14 22:32:44 +0000453 bool canCheckPtrAtRT(RuntimePointerChecking &RtCheck, ScalarEvolution *SE,
454 Loop *TheLoop, const ValueToValueMap &Strides,
Adam Nemet04563272015-02-01 16:56:15 +0000455 bool ShouldCheckStride = false);
456
457 /// \brief Goes over all memory accesses, checks whether a RT check is needed
458 /// and builds sets of dependent accesses.
459 void buildDependenceSets() {
460 processMemAccesses();
461 }
462
Adam Nemet5dc3b2c2015-07-09 06:47:18 +0000463 /// \brief Initial processing of memory accesses determined that we need to
464 /// perform dependency checking.
465 ///
466 /// Note that this can later be cleared if we retry memcheck analysis without
467 /// dependency checking (i.e. ShouldRetryWithRuntimeCheck).
Adam Nemet04563272015-02-01 16:56:15 +0000468 bool isDependencyCheckNeeded() { return !CheckDeps.empty(); }
Adam Nemetdf3dc5b2015-05-18 15:37:03 +0000469
470 /// We decided that no dependence analysis would be used. Reset the state.
471 void resetDepChecks(MemoryDepChecker &DepChecker) {
472 CheckDeps.clear();
Adam Nemeta2df7502015-11-03 21:39:52 +0000473 DepChecker.clearDependences();
Adam Nemetdf3dc5b2015-05-18 15:37:03 +0000474 }
Adam Nemet04563272015-02-01 16:56:15 +0000475
476 MemAccessInfoSet &getDependenciesToCheck() { return CheckDeps; }
477
478private:
479 typedef SetVector<MemAccessInfo> PtrAccessSet;
480
481 /// \brief Go over all memory access and check whether runtime pointer checks
Adam Nemetb41d2d32015-07-09 06:47:21 +0000482 /// are needed and build sets of dependency check candidates.
Adam Nemet04563272015-02-01 16:56:15 +0000483 void processMemAccesses();
484
485 /// Set of all accesses.
486 PtrAccessSet Accesses;
487
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000488 const DataLayout &DL;
489
Adam Nemet04563272015-02-01 16:56:15 +0000490 /// Set of accesses that need a further dependence check.
491 MemAccessInfoSet CheckDeps;
492
493 /// Set of pointers that are read only.
494 SmallPtrSet<Value*, 16> ReadOnlyPtr;
495
Adam Nemet04563272015-02-01 16:56:15 +0000496 /// An alias set tracker to partition the access set by underlying object and
497 //intrinsic property (such as TBAA metadata).
498 AliasSetTracker AST;
499
Adam Nemete2b885c2015-04-23 20:09:20 +0000500 LoopInfo *LI;
501
Adam Nemet04563272015-02-01 16:56:15 +0000502 /// Sets of potentially dependent accesses - members of one set share an
503 /// underlying pointer. The set "CheckDeps" identfies which sets really need a
504 /// dependence check.
Adam Nemetdee666b2015-03-10 17:40:34 +0000505 MemoryDepChecker::DepCandidates &DepCands;
Adam Nemet04563272015-02-01 16:56:15 +0000506
Adam Nemet5dc3b2c2015-07-09 06:47:18 +0000507 /// \brief Initial processing of memory accesses determined that we may need
508 /// to add memchecks. Perform the analysis to determine the necessary checks.
509 ///
510 /// Note that, this is different from isDependencyCheckNeeded. When we retry
511 /// memcheck analysis without dependency checking
512 /// (i.e. ShouldRetryWithRuntimeCheck), isDependencyCheckNeeded is cleared
513 /// while this remains set if we have potentially dependent accesses.
514 bool IsRTCheckAnalysisNeeded;
Silviu Barangae3c05342015-11-02 14:41:02 +0000515
516 /// The SCEV predicate containing all the SCEV-related assumptions.
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +0000517 PredicatedScalarEvolution &PSE;
Adam Nemet04563272015-02-01 16:56:15 +0000518};
519
520} // end anonymous namespace
521
522/// \brief Check whether a pointer can participate in a runtime bounds check.
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +0000523static bool hasComputableBounds(PredicatedScalarEvolution &PSE,
Silviu Barangae3c05342015-11-02 14:41:02 +0000524 const ValueToValueMap &Strides, Value *Ptr,
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +0000525 Loop *L) {
526 const SCEV *PtrScev = replaceSymbolicStrideSCEV(PSE, Strides, Ptr);
Adam Nemet04563272015-02-01 16:56:15 +0000527 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
528 if (!AR)
529 return false;
530
531 return AR->isAffine();
532}
533
Adam Nemet7cdebac2015-07-14 22:32:44 +0000534bool AccessAnalysis::canCheckPtrAtRT(RuntimePointerChecking &RtCheck,
535 ScalarEvolution *SE, Loop *TheLoop,
536 const ValueToValueMap &StridesMap,
537 bool ShouldCheckStride) {
Adam Nemet04563272015-02-01 16:56:15 +0000538 // Find pointers with computable bounds. We are going to use this information
539 // to place a runtime bound check.
540 bool CanDoRT = true;
541
Adam Nemetee614742015-07-09 22:17:38 +0000542 bool NeedRTCheck = false;
Adam Nemet5dc3b2c2015-07-09 06:47:18 +0000543 if (!IsRTCheckAnalysisNeeded) return true;
Silviu Baranga98a13712015-06-08 10:27:06 +0000544
Adam Nemet04563272015-02-01 16:56:15 +0000545 bool IsDepCheckNeeded = isDependencyCheckNeeded();
Adam Nemet04563272015-02-01 16:56:15 +0000546
547 // We assign a consecutive id to access from different alias sets.
548 // Accesses between different groups doesn't need to be checked.
549 unsigned ASId = 1;
550 for (auto &AS : AST) {
Adam Nemet424edc62015-07-08 22:58:48 +0000551 int NumReadPtrChecks = 0;
552 int NumWritePtrChecks = 0;
553
Adam Nemet04563272015-02-01 16:56:15 +0000554 // We assign consecutive id to access from different dependence sets.
555 // Accesses within the same set don't need a runtime check.
556 unsigned RunningDepId = 1;
557 DenseMap<Value *, unsigned> DepSetId;
558
559 for (auto A : AS) {
560 Value *Ptr = A.getValue();
561 bool IsWrite = Accesses.count(MemAccessInfo(Ptr, true));
562 MemAccessInfo Access(Ptr, IsWrite);
563
Adam Nemet424edc62015-07-08 22:58:48 +0000564 if (IsWrite)
565 ++NumWritePtrChecks;
566 else
567 ++NumReadPtrChecks;
568
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +0000569 if (hasComputableBounds(PSE, StridesMap, Ptr, TheLoop) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000570 // When we run after a failing dependency check we have to make sure
571 // we don't have wrapping pointers.
Adam Nemet04563272015-02-01 16:56:15 +0000572 (!ShouldCheckStride ||
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +0000573 isStridedPtr(PSE, Ptr, TheLoop, StridesMap) == 1)) {
Adam Nemet04563272015-02-01 16:56:15 +0000574 // The id of the dependence set.
575 unsigned DepId;
576
577 if (IsDepCheckNeeded) {
578 Value *Leader = DepCands.getLeaderValue(Access).getPointer();
579 unsigned &LeaderId = DepSetId[Leader];
580 if (!LeaderId)
581 LeaderId = RunningDepId++;
582 DepId = LeaderId;
583 } else
584 // Each access has its own dependence set.
585 DepId = RunningDepId++;
586
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +0000587 RtCheck.insert(TheLoop, Ptr, IsWrite, DepId, ASId, StridesMap, PSE);
Adam Nemet04563272015-02-01 16:56:15 +0000588
Adam Nemet339f42b2015-02-19 19:15:07 +0000589 DEBUG(dbgs() << "LAA: Found a runtime check ptr:" << *Ptr << '\n');
Adam Nemet04563272015-02-01 16:56:15 +0000590 } else {
Adam Nemetf10ca272015-05-18 15:36:52 +0000591 DEBUG(dbgs() << "LAA: Can't find bounds for ptr:" << *Ptr << '\n');
Adam Nemet04563272015-02-01 16:56:15 +0000592 CanDoRT = false;
593 }
594 }
595
Adam Nemet424edc62015-07-08 22:58:48 +0000596 // If we have at least two writes or one write and a read then we need to
597 // check them. But there is no need to checks if there is only one
598 // dependence set for this alias set.
599 //
600 // Note that this function computes CanDoRT and NeedRTCheck independently.
601 // For example CanDoRT=false, NeedRTCheck=false means that we have a pointer
602 // for which we couldn't find the bounds but we don't actually need to emit
603 // any checks so it does not matter.
604 if (!(IsDepCheckNeeded && CanDoRT && RunningDepId == 2))
605 NeedRTCheck |= (NumWritePtrChecks >= 2 || (NumReadPtrChecks >= 1 &&
606 NumWritePtrChecks >= 1));
607
Adam Nemet04563272015-02-01 16:56:15 +0000608 ++ASId;
609 }
610
611 // If the pointers that we would use for the bounds comparison have different
612 // address spaces, assume the values aren't directly comparable, so we can't
613 // use them for the runtime check. We also have to assume they could
614 // overlap. In the future there should be metadata for whether address spaces
615 // are disjoint.
616 unsigned NumPointers = RtCheck.Pointers.size();
617 for (unsigned i = 0; i < NumPointers; ++i) {
618 for (unsigned j = i + 1; j < NumPointers; ++j) {
619 // Only need to check pointers between two different dependency sets.
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000620 if (RtCheck.Pointers[i].DependencySetId ==
621 RtCheck.Pointers[j].DependencySetId)
Adam Nemet04563272015-02-01 16:56:15 +0000622 continue;
623 // Only need to check pointers in the same alias set.
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000624 if (RtCheck.Pointers[i].AliasSetId != RtCheck.Pointers[j].AliasSetId)
Adam Nemet04563272015-02-01 16:56:15 +0000625 continue;
626
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000627 Value *PtrI = RtCheck.Pointers[i].PointerValue;
628 Value *PtrJ = RtCheck.Pointers[j].PointerValue;
Adam Nemet04563272015-02-01 16:56:15 +0000629
630 unsigned ASi = PtrI->getType()->getPointerAddressSpace();
631 unsigned ASj = PtrJ->getType()->getPointerAddressSpace();
632 if (ASi != ASj) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000633 DEBUG(dbgs() << "LAA: Runtime check would require comparison between"
Adam Nemet04d41632015-02-19 19:14:34 +0000634 " different address spaces\n");
Adam Nemet04563272015-02-01 16:56:15 +0000635 return false;
636 }
637 }
638 }
639
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000640 if (NeedRTCheck && CanDoRT)
Adam Nemet15840392015-08-07 22:44:15 +0000641 RtCheck.generateChecks(DepCands, IsDepCheckNeeded);
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000642
Adam Nemet155e8742015-08-07 22:44:21 +0000643 DEBUG(dbgs() << "LAA: We need to do " << RtCheck.getNumberOfChecks()
Adam Nemetee614742015-07-09 22:17:38 +0000644 << " pointer comparisons.\n");
645
646 RtCheck.Need = NeedRTCheck;
647
648 bool CanDoRTIfNeeded = !NeedRTCheck || CanDoRT;
649 if (!CanDoRTIfNeeded)
650 RtCheck.reset();
651 return CanDoRTIfNeeded;
Adam Nemet04563272015-02-01 16:56:15 +0000652}
653
654void AccessAnalysis::processMemAccesses() {
655 // We process the set twice: first we process read-write pointers, last we
656 // process read-only pointers. This allows us to skip dependence tests for
657 // read-only pointers.
658
Adam Nemet339f42b2015-02-19 19:15:07 +0000659 DEBUG(dbgs() << "LAA: Processing memory accesses...\n");
Adam Nemet04563272015-02-01 16:56:15 +0000660 DEBUG(dbgs() << " AST: "; AST.dump());
Adam Nemet9c926572015-03-10 17:40:37 +0000661 DEBUG(dbgs() << "LAA: Accesses(" << Accesses.size() << "):\n");
Adam Nemet04563272015-02-01 16:56:15 +0000662 DEBUG({
663 for (auto A : Accesses)
664 dbgs() << "\t" << *A.getPointer() << " (" <<
665 (A.getInt() ? "write" : (ReadOnlyPtr.count(A.getPointer()) ?
666 "read-only" : "read")) << ")\n";
667 });
668
669 // The AliasSetTracker has nicely partitioned our pointers by metadata
670 // compatibility and potential for underlying-object overlap. As a result, we
671 // only need to check for potential pointer dependencies within each alias
672 // set.
673 for (auto &AS : AST) {
674 // Note that both the alias-set tracker and the alias sets themselves used
675 // linked lists internally and so the iteration order here is deterministic
676 // (matching the original instruction order within each set).
677
678 bool SetHasWrite = false;
679
680 // Map of pointers to last access encountered.
681 typedef DenseMap<Value*, MemAccessInfo> UnderlyingObjToAccessMap;
682 UnderlyingObjToAccessMap ObjToLastAccess;
683
684 // Set of access to check after all writes have been processed.
685 PtrAccessSet DeferredAccesses;
686
687 // Iterate over each alias set twice, once to process read/write pointers,
688 // and then to process read-only pointers.
689 for (int SetIteration = 0; SetIteration < 2; ++SetIteration) {
690 bool UseDeferred = SetIteration > 0;
691 PtrAccessSet &S = UseDeferred ? DeferredAccesses : Accesses;
692
693 for (auto AV : AS) {
694 Value *Ptr = AV.getValue();
695
696 // For a single memory access in AliasSetTracker, Accesses may contain
697 // both read and write, and they both need to be handled for CheckDeps.
698 for (auto AC : S) {
699 if (AC.getPointer() != Ptr)
700 continue;
701
702 bool IsWrite = AC.getInt();
703
704 // If we're using the deferred access set, then it contains only
705 // reads.
706 bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite;
707 if (UseDeferred && !IsReadOnlyPtr)
708 continue;
709 // Otherwise, the pointer must be in the PtrAccessSet, either as a
710 // read or a write.
711 assert(((IsReadOnlyPtr && UseDeferred) || IsWrite ||
712 S.count(MemAccessInfo(Ptr, false))) &&
713 "Alias-set pointer not in the access set?");
714
715 MemAccessInfo Access(Ptr, IsWrite);
716 DepCands.insert(Access);
717
718 // Memorize read-only pointers for later processing and skip them in
719 // the first round (they need to be checked after we have seen all
720 // write pointers). Note: we also mark pointer that are not
721 // consecutive as "read-only" pointers (so that we check
722 // "a[b[i]] +="). Hence, we need the second check for "!IsWrite".
723 if (!UseDeferred && IsReadOnlyPtr) {
724 DeferredAccesses.insert(Access);
725 continue;
726 }
727
728 // If this is a write - check other reads and writes for conflicts. If
729 // this is a read only check other writes for conflicts (but only if
730 // there is no other write to the ptr - this is an optimization to
731 // catch "a[i] = a[i] + " without having to do a dependence check).
732 if ((IsWrite || IsReadOnlyPtr) && SetHasWrite) {
733 CheckDeps.insert(Access);
Adam Nemet5dc3b2c2015-07-09 06:47:18 +0000734 IsRTCheckAnalysisNeeded = true;
Adam Nemet04563272015-02-01 16:56:15 +0000735 }
736
737 if (IsWrite)
738 SetHasWrite = true;
739
740 // Create sets of pointers connected by a shared alias set and
741 // underlying object.
742 typedef SmallVector<Value *, 16> ValueVector;
743 ValueVector TempObjects;
Adam Nemete2b885c2015-04-23 20:09:20 +0000744
745 GetUnderlyingObjects(Ptr, TempObjects, DL, LI);
746 DEBUG(dbgs() << "Underlying objects for pointer " << *Ptr << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000747 for (Value *UnderlyingObj : TempObjects) {
Mehdi Aminiafd13512015-11-05 05:49:43 +0000748 // nullptr never alias, don't join sets for pointer that have "null"
749 // in their UnderlyingObjects list.
750 if (isa<ConstantPointerNull>(UnderlyingObj))
751 continue;
752
Adam Nemet04563272015-02-01 16:56:15 +0000753 UnderlyingObjToAccessMap::iterator Prev =
754 ObjToLastAccess.find(UnderlyingObj);
755 if (Prev != ObjToLastAccess.end())
756 DepCands.unionSets(Access, Prev->second);
757
758 ObjToLastAccess[UnderlyingObj] = Access;
Adam Nemete2b885c2015-04-23 20:09:20 +0000759 DEBUG(dbgs() << " " << *UnderlyingObj << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000760 }
761 }
762 }
763 }
764 }
765}
766
Adam Nemet04563272015-02-01 16:56:15 +0000767static bool isInBoundsGep(Value *Ptr) {
768 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
769 return GEP->isInBounds();
770 return false;
771}
772
Adam Nemetc4866d22015-06-26 17:25:43 +0000773/// \brief Return true if an AddRec pointer \p Ptr is unsigned non-wrapping,
774/// i.e. monotonically increasing/decreasing.
775static bool isNoWrapAddRec(Value *Ptr, const SCEVAddRecExpr *AR,
Silviu Barangaea63a7f2016-02-08 17:02:45 +0000776 PredicatedScalarEvolution &PSE, const Loop *L) {
Adam Nemetc4866d22015-06-26 17:25:43 +0000777 // FIXME: This should probably only return true for NUW.
778 if (AR->getNoWrapFlags(SCEV::NoWrapMask))
779 return true;
780
781 // Scalar evolution does not propagate the non-wrapping flags to values that
782 // are derived from a non-wrapping induction variable because non-wrapping
783 // could be flow-sensitive.
784 //
785 // Look through the potentially overflowing instruction to try to prove
786 // non-wrapping for the *specific* value of Ptr.
787
788 // The arithmetic implied by an inbounds GEP can't overflow.
789 auto *GEP = dyn_cast<GetElementPtrInst>(Ptr);
790 if (!GEP || !GEP->isInBounds())
791 return false;
792
793 // Make sure there is only one non-const index and analyze that.
794 Value *NonConstIndex = nullptr;
795 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
796 if (!isa<ConstantInt>(*Index)) {
797 if (NonConstIndex)
798 return false;
799 NonConstIndex = *Index;
800 }
801 if (!NonConstIndex)
802 // The recurrence is on the pointer, ignore for now.
803 return false;
804
805 // The index in GEP is signed. It is non-wrapping if it's derived from a NSW
806 // AddRec using a NSW operation.
807 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(NonConstIndex))
808 if (OBO->hasNoSignedWrap() &&
809 // Assume constant for other the operand so that the AddRec can be
810 // easily found.
811 isa<ConstantInt>(OBO->getOperand(1))) {
Silviu Barangaea63a7f2016-02-08 17:02:45 +0000812 auto *OpScev = PSE.getSCEV(OBO->getOperand(0));
Adam Nemetc4866d22015-06-26 17:25:43 +0000813
814 if (auto *OpAR = dyn_cast<SCEVAddRecExpr>(OpScev))
815 return OpAR->getLoop() == L && OpAR->getNoWrapFlags(SCEV::FlagNSW);
816 }
817
818 return false;
819}
820
Adam Nemet04563272015-02-01 16:56:15 +0000821/// \brief Check whether the access through \p Ptr has a constant stride.
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +0000822int llvm::isStridedPtr(PredicatedScalarEvolution &PSE, Value *Ptr,
Silviu Barangaea63a7f2016-02-08 17:02:45 +0000823 const Loop *Lp, const ValueToValueMap &StridesMap,
824 bool Assume) {
Craig Toppere3dcce92015-08-01 22:20:21 +0000825 Type *Ty = Ptr->getType();
Adam Nemet04563272015-02-01 16:56:15 +0000826 assert(Ty->isPointerTy() && "Unexpected non-ptr");
827
828 // Make sure that the pointer does not point to aggregate types.
Craig Toppere3dcce92015-08-01 22:20:21 +0000829 auto *PtrTy = cast<PointerType>(Ty);
Adam Nemet04563272015-02-01 16:56:15 +0000830 if (PtrTy->getElementType()->isAggregateType()) {
Silviu Barangaea63a7f2016-02-08 17:02:45 +0000831 DEBUG(dbgs() << "LAA: Bad stride - Not a pointer to a scalar type" << *Ptr
832 << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000833 return 0;
834 }
835
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +0000836 const SCEV *PtrScev = replaceSymbolicStrideSCEV(PSE, StridesMap, Ptr);
Adam Nemet04563272015-02-01 16:56:15 +0000837
838 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
Silviu Barangaea63a7f2016-02-08 17:02:45 +0000839 if (Assume && !AR)
840 AR = dyn_cast<SCEVAddRecExpr>(PSE.getAsAddRec(Ptr));
841
Adam Nemet04563272015-02-01 16:56:15 +0000842 if (!AR) {
Silviu Barangaea63a7f2016-02-08 17:02:45 +0000843 DEBUG(dbgs() << "LAA: Bad stride - Not an AddRecExpr pointer " << *Ptr
844 << " SCEV: " << *PtrScev << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000845 return 0;
846 }
847
848 // The accesss function must stride over the innermost loop.
849 if (Lp != AR->getLoop()) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000850 DEBUG(dbgs() << "LAA: Bad stride - Not striding over innermost loop " <<
Silviu Barangaea63a7f2016-02-08 17:02:45 +0000851 *Ptr << " SCEV: " << *AR << "\n");
Kyle Butta02ce982016-01-08 01:55:13 +0000852 return 0;
Adam Nemet04563272015-02-01 16:56:15 +0000853 }
854
855 // The address calculation must not wrap. Otherwise, a dependence could be
856 // inverted.
857 // An inbounds getelementptr that is a AddRec with a unit stride
858 // cannot wrap per definition. The unit stride requirement is checked later.
859 // An getelementptr without an inbounds attribute and unit stride would have
860 // to access the pointer value "0" which is undefined behavior in address
861 // space 0, therefore we can also vectorize this case.
862 bool IsInBoundsGEP = isInBoundsGep(Ptr);
Silviu Barangaea63a7f2016-02-08 17:02:45 +0000863 bool IsNoWrapAddRec =
864 PSE.hasNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW) ||
865 isNoWrapAddRec(Ptr, AR, PSE, Lp);
Adam Nemet04563272015-02-01 16:56:15 +0000866 bool IsInAddressSpaceZero = PtrTy->getAddressSpace() == 0;
867 if (!IsNoWrapAddRec && !IsInBoundsGEP && !IsInAddressSpaceZero) {
Silviu Barangaea63a7f2016-02-08 17:02:45 +0000868 if (Assume) {
869 PSE.setNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW);
870 IsNoWrapAddRec = true;
871 DEBUG(dbgs() << "LAA: Pointer may wrap in the address space:\n"
872 << "LAA: Pointer: " << *Ptr << "\n"
873 << "LAA: SCEV: " << *AR << "\n"
874 << "LAA: Added an overflow assumption\n");
875 } else {
876 DEBUG(dbgs() << "LAA: Bad stride - Pointer may wrap in the address space "
877 << *Ptr << " SCEV: " << *AR << "\n");
878 return 0;
879 }
Adam Nemet04563272015-02-01 16:56:15 +0000880 }
881
882 // Check the step is constant.
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +0000883 const SCEV *Step = AR->getStepRecurrence(*PSE.getSE());
Adam Nemet04563272015-02-01 16:56:15 +0000884
Adam Nemet943befe2015-07-09 00:03:22 +0000885 // Calculate the pointer stride and check if it is constant.
Adam Nemet04563272015-02-01 16:56:15 +0000886 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
887 if (!C) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000888 DEBUG(dbgs() << "LAA: Bad stride - Not a constant strided " << *Ptr <<
Silviu Barangaea63a7f2016-02-08 17:02:45 +0000889 " SCEV: " << *AR << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000890 return 0;
891 }
892
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000893 auto &DL = Lp->getHeader()->getModule()->getDataLayout();
894 int64_t Size = DL.getTypeAllocSize(PtrTy->getElementType());
Sanjoy Das0de2fec2015-12-17 20:28:46 +0000895 const APInt &APStepVal = C->getAPInt();
Adam Nemet04563272015-02-01 16:56:15 +0000896
897 // Huge step value - give up.
898 if (APStepVal.getBitWidth() > 64)
899 return 0;
900
901 int64_t StepVal = APStepVal.getSExtValue();
902
903 // Strided access.
904 int64_t Stride = StepVal / Size;
905 int64_t Rem = StepVal % Size;
906 if (Rem)
907 return 0;
908
909 // If the SCEV could wrap but we have an inbounds gep with a unit stride we
910 // know we can't "wrap around the address space". In case of address space
911 // zero we know that this won't happen without triggering undefined behavior.
912 if (!IsNoWrapAddRec && (IsInBoundsGEP || IsInAddressSpaceZero) &&
Silviu Barangaea63a7f2016-02-08 17:02:45 +0000913 Stride != 1 && Stride != -1) {
914 if (Assume) {
915 // We can avoid this case by adding a run-time check.
916 DEBUG(dbgs() << "LAA: Non unit strided pointer which is not either "
917 << "inbouds or in address space 0 may wrap:\n"
918 << "LAA: Pointer: " << *Ptr << "\n"
919 << "LAA: SCEV: " << *AR << "\n"
920 << "LAA: Added an overflow assumption\n");
921 PSE.setNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW);
922 } else
923 return 0;
924 }
Adam Nemet04563272015-02-01 16:56:15 +0000925
926 return Stride;
927}
928
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000929/// Take the pointer operand from the Load/Store instruction.
930/// Returns NULL if this is not a valid Load/Store instruction.
931static Value *getPointerOperand(Value *I) {
932 if (LoadInst *LI = dyn_cast<LoadInst>(I))
933 return LI->getPointerOperand();
934 if (StoreInst *SI = dyn_cast<StoreInst>(I))
935 return SI->getPointerOperand();
936 return nullptr;
937}
938
939/// Take the address space operand from the Load/Store instruction.
940/// Returns -1 if this is not a valid Load/Store instruction.
941static unsigned getAddressSpaceOperand(Value *I) {
942 if (LoadInst *L = dyn_cast<LoadInst>(I))
943 return L->getPointerAddressSpace();
944 if (StoreInst *S = dyn_cast<StoreInst>(I))
945 return S->getPointerAddressSpace();
946 return -1;
947}
948
949/// Returns true if the memory operations \p A and \p B are consecutive.
950bool llvm::isConsecutiveAccess(Value *A, Value *B, const DataLayout &DL,
951 ScalarEvolution &SE, bool CheckType) {
952 Value *PtrA = getPointerOperand(A);
953 Value *PtrB = getPointerOperand(B);
954 unsigned ASA = getAddressSpaceOperand(A);
955 unsigned ASB = getAddressSpaceOperand(B);
956
957 // Check that the address spaces match and that the pointers are valid.
958 if (!PtrA || !PtrB || (ASA != ASB))
959 return false;
960
961 // Make sure that A and B are different pointers.
962 if (PtrA == PtrB)
963 return false;
964
965 // Make sure that A and B have the same type if required.
966 if(CheckType && PtrA->getType() != PtrB->getType())
967 return false;
968
969 unsigned PtrBitWidth = DL.getPointerSizeInBits(ASA);
970 Type *Ty = cast<PointerType>(PtrA->getType())->getElementType();
971 APInt Size(PtrBitWidth, DL.getTypeStoreSize(Ty));
972
973 APInt OffsetA(PtrBitWidth, 0), OffsetB(PtrBitWidth, 0);
974 PtrA = PtrA->stripAndAccumulateInBoundsConstantOffsets(DL, OffsetA);
975 PtrB = PtrB->stripAndAccumulateInBoundsConstantOffsets(DL, OffsetB);
976
977 // OffsetDelta = OffsetB - OffsetA;
978 const SCEV *OffsetSCEVA = SE.getConstant(OffsetA);
979 const SCEV *OffsetSCEVB = SE.getConstant(OffsetB);
980 const SCEV *OffsetDeltaSCEV = SE.getMinusSCEV(OffsetSCEVB, OffsetSCEVA);
981 const SCEVConstant *OffsetDeltaC = dyn_cast<SCEVConstant>(OffsetDeltaSCEV);
982 const APInt &OffsetDelta = OffsetDeltaC->getAPInt();
983 // Check if they are based on the same pointer. That makes the offsets
984 // sufficient.
985 if (PtrA == PtrB)
986 return OffsetDelta == Size;
987
988 // Compute the necessary base pointer delta to have the necessary final delta
989 // equal to the size.
990 // BaseDelta = Size - OffsetDelta;
991 const SCEV *SizeSCEV = SE.getConstant(Size);
992 const SCEV *BaseDelta = SE.getMinusSCEV(SizeSCEV, OffsetDeltaSCEV);
993
994 // Otherwise compute the distance with SCEV between the base pointers.
995 const SCEV *PtrSCEVA = SE.getSCEV(PtrA);
996 const SCEV *PtrSCEVB = SE.getSCEV(PtrB);
997 const SCEV *X = SE.getAddExpr(PtrSCEVA, BaseDelta);
998 return X == PtrSCEVB;
999}
1000
Adam Nemet9c926572015-03-10 17:40:37 +00001001bool MemoryDepChecker::Dependence::isSafeForVectorization(DepType Type) {
1002 switch (Type) {
1003 case NoDep:
1004 case Forward:
1005 case BackwardVectorizable:
1006 return true;
1007
1008 case Unknown:
1009 case ForwardButPreventsForwarding:
1010 case Backward:
1011 case BackwardVectorizableButPreventsForwarding:
1012 return false;
1013 }
David Majnemerd388e932015-03-10 20:23:29 +00001014 llvm_unreachable("unexpected DepType!");
Adam Nemet9c926572015-03-10 17:40:37 +00001015}
1016
Adam Nemet397f5822015-11-03 23:50:03 +00001017bool MemoryDepChecker::Dependence::isBackward() const {
Adam Nemet9c926572015-03-10 17:40:37 +00001018 switch (Type) {
1019 case NoDep:
1020 case Forward:
1021 case ForwardButPreventsForwarding:
Adam Nemet397f5822015-11-03 23:50:03 +00001022 case Unknown:
Adam Nemet9c926572015-03-10 17:40:37 +00001023 return false;
1024
Adam Nemet9c926572015-03-10 17:40:37 +00001025 case BackwardVectorizable:
1026 case Backward:
1027 case BackwardVectorizableButPreventsForwarding:
1028 return true;
1029 }
David Majnemerd388e932015-03-10 20:23:29 +00001030 llvm_unreachable("unexpected DepType!");
Adam Nemet9c926572015-03-10 17:40:37 +00001031}
1032
Adam Nemet397f5822015-11-03 23:50:03 +00001033bool MemoryDepChecker::Dependence::isPossiblyBackward() const {
1034 return isBackward() || Type == Unknown;
1035}
1036
1037bool MemoryDepChecker::Dependence::isForward() const {
1038 switch (Type) {
1039 case Forward:
1040 case ForwardButPreventsForwarding:
1041 return true;
1042
1043 case NoDep:
1044 case Unknown:
1045 case BackwardVectorizable:
1046 case Backward:
1047 case BackwardVectorizableButPreventsForwarding:
1048 return false;
1049 }
1050 llvm_unreachable("unexpected DepType!");
1051}
1052
Adam Nemet04563272015-02-01 16:56:15 +00001053bool MemoryDepChecker::couldPreventStoreLoadForward(unsigned Distance,
1054 unsigned TypeByteSize) {
1055 // If loads occur at a distance that is not a multiple of a feasible vector
1056 // factor store-load forwarding does not take place.
1057 // Positive dependences might cause troubles because vectorizing them might
1058 // prevent store-load forwarding making vectorized code run a lot slower.
1059 // a[i] = a[i-3] ^ a[i-8];
1060 // The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
1061 // hence on your typical architecture store-load forwarding does not take
1062 // place. Vectorizing in such cases does not make sense.
1063 // Store-load forwarding distance.
1064 const unsigned NumCyclesForStoreLoadThroughMemory = 8*TypeByteSize;
1065 // Maximum vector factor.
Adam Nemetf219c642015-02-19 19:14:52 +00001066 unsigned MaxVFWithoutSLForwardIssues =
1067 VectorizerParams::MaxVectorWidth * TypeByteSize;
Adam Nemet04d41632015-02-19 19:14:34 +00001068 if(MaxSafeDepDistBytes < MaxVFWithoutSLForwardIssues)
Adam Nemet04563272015-02-01 16:56:15 +00001069 MaxVFWithoutSLForwardIssues = MaxSafeDepDistBytes;
1070
1071 for (unsigned vf = 2*TypeByteSize; vf <= MaxVFWithoutSLForwardIssues;
1072 vf *= 2) {
1073 if (Distance % vf && Distance / vf < NumCyclesForStoreLoadThroughMemory) {
1074 MaxVFWithoutSLForwardIssues = (vf >>=1);
1075 break;
1076 }
1077 }
1078
Adam Nemet04d41632015-02-19 19:14:34 +00001079 if (MaxVFWithoutSLForwardIssues< 2*TypeByteSize) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001080 DEBUG(dbgs() << "LAA: Distance " << Distance <<
Adam Nemet04d41632015-02-19 19:14:34 +00001081 " that could cause a store-load forwarding conflict\n");
Adam Nemet04563272015-02-01 16:56:15 +00001082 return true;
1083 }
1084
1085 if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes &&
Adam Nemetf219c642015-02-19 19:14:52 +00001086 MaxVFWithoutSLForwardIssues !=
1087 VectorizerParams::MaxVectorWidth * TypeByteSize)
Adam Nemet04563272015-02-01 16:56:15 +00001088 MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues;
1089 return false;
1090}
1091
Hao Liu751004a2015-06-08 04:48:37 +00001092/// \brief Check the dependence for two accesses with the same stride \p Stride.
1093/// \p Distance is the positive distance and \p TypeByteSize is type size in
1094/// bytes.
1095///
1096/// \returns true if they are independent.
1097static bool areStridedAccessesIndependent(unsigned Distance, unsigned Stride,
1098 unsigned TypeByteSize) {
1099 assert(Stride > 1 && "The stride must be greater than 1");
1100 assert(TypeByteSize > 0 && "The type size in byte must be non-zero");
1101 assert(Distance > 0 && "The distance must be non-zero");
1102
1103 // Skip if the distance is not multiple of type byte size.
1104 if (Distance % TypeByteSize)
1105 return false;
1106
1107 unsigned ScaledDist = Distance / TypeByteSize;
1108
1109 // No dependence if the scaled distance is not multiple of the stride.
1110 // E.g.
1111 // for (i = 0; i < 1024 ; i += 4)
1112 // A[i+2] = A[i] + 1;
1113 //
1114 // Two accesses in memory (scaled distance is 2, stride is 4):
1115 // | A[0] | | | | A[4] | | | |
1116 // | | | A[2] | | | | A[6] | |
1117 //
1118 // E.g.
1119 // for (i = 0; i < 1024 ; i += 3)
1120 // A[i+4] = A[i] + 1;
1121 //
1122 // Two accesses in memory (scaled distance is 4, stride is 3):
1123 // | A[0] | | | A[3] | | | A[6] | | |
1124 // | | | | | A[4] | | | A[7] | |
1125 return ScaledDist % Stride;
1126}
1127
Adam Nemet9c926572015-03-10 17:40:37 +00001128MemoryDepChecker::Dependence::DepType
1129MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
1130 const MemAccessInfo &B, unsigned BIdx,
1131 const ValueToValueMap &Strides) {
Adam Nemet04563272015-02-01 16:56:15 +00001132 assert (AIdx < BIdx && "Must pass arguments in program order");
1133
1134 Value *APtr = A.getPointer();
1135 Value *BPtr = B.getPointer();
1136 bool AIsWrite = A.getInt();
1137 bool BIsWrite = B.getInt();
1138
1139 // Two reads are independent.
1140 if (!AIsWrite && !BIsWrite)
Adam Nemet9c926572015-03-10 17:40:37 +00001141 return Dependence::NoDep;
Adam Nemet04563272015-02-01 16:56:15 +00001142
1143 // We cannot check pointers in different address spaces.
1144 if (APtr->getType()->getPointerAddressSpace() !=
1145 BPtr->getType()->getPointerAddressSpace())
Adam Nemet9c926572015-03-10 17:40:37 +00001146 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +00001147
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +00001148 const SCEV *AScev = replaceSymbolicStrideSCEV(PSE, Strides, APtr);
1149 const SCEV *BScev = replaceSymbolicStrideSCEV(PSE, Strides, BPtr);
Adam Nemet04563272015-02-01 16:56:15 +00001150
Silviu Barangaea63a7f2016-02-08 17:02:45 +00001151 int StrideAPtr = isStridedPtr(PSE, APtr, InnermostLoop, Strides, true);
1152 int StrideBPtr = isStridedPtr(PSE, BPtr, InnermostLoop, Strides, true);
Adam Nemet04563272015-02-01 16:56:15 +00001153
1154 const SCEV *Src = AScev;
1155 const SCEV *Sink = BScev;
1156
1157 // If the induction step is negative we have to invert source and sink of the
1158 // dependence.
1159 if (StrideAPtr < 0) {
1160 //Src = BScev;
1161 //Sink = AScev;
1162 std::swap(APtr, BPtr);
1163 std::swap(Src, Sink);
1164 std::swap(AIsWrite, BIsWrite);
1165 std::swap(AIdx, BIdx);
1166 std::swap(StrideAPtr, StrideBPtr);
1167 }
1168
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +00001169 const SCEV *Dist = PSE.getSE()->getMinusSCEV(Sink, Src);
Adam Nemet04563272015-02-01 16:56:15 +00001170
Adam Nemet339f42b2015-02-19 19:15:07 +00001171 DEBUG(dbgs() << "LAA: Src Scev: " << *Src << "Sink Scev: " << *Sink
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +00001172 << "(Induction step: " << StrideAPtr << ")\n");
Adam Nemet339f42b2015-02-19 19:15:07 +00001173 DEBUG(dbgs() << "LAA: Distance for " << *InstMap[AIdx] << " to "
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +00001174 << *InstMap[BIdx] << ": " << *Dist << "\n");
Adam Nemet04563272015-02-01 16:56:15 +00001175
Adam Nemet943befe2015-07-09 00:03:22 +00001176 // Need accesses with constant stride. We don't want to vectorize
Adam Nemet04563272015-02-01 16:56:15 +00001177 // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in
1178 // the address space.
1179 if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){
Adam Nemet943befe2015-07-09 00:03:22 +00001180 DEBUG(dbgs() << "Pointer access with non-constant stride\n");
Adam Nemet9c926572015-03-10 17:40:37 +00001181 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +00001182 }
1183
1184 const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist);
1185 if (!C) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001186 DEBUG(dbgs() << "LAA: Dependence because of non-constant distance\n");
Adam Nemet04563272015-02-01 16:56:15 +00001187 ShouldRetryWithRuntimeCheck = true;
Adam Nemet9c926572015-03-10 17:40:37 +00001188 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +00001189 }
1190
1191 Type *ATy = APtr->getType()->getPointerElementType();
1192 Type *BTy = BPtr->getType()->getPointerElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001193 auto &DL = InnermostLoop->getHeader()->getModule()->getDataLayout();
1194 unsigned TypeByteSize = DL.getTypeAllocSize(ATy);
Adam Nemet04563272015-02-01 16:56:15 +00001195
1196 // Negative distances are not plausible dependencies.
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001197 const APInt &Val = C->getAPInt();
Adam Nemet04563272015-02-01 16:56:15 +00001198 if (Val.isNegative()) {
1199 bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
1200 if (IsTrueDataDependence &&
1201 (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) ||
1202 ATy != BTy))
Adam Nemet9c926572015-03-10 17:40:37 +00001203 return Dependence::ForwardButPreventsForwarding;
Adam Nemet04563272015-02-01 16:56:15 +00001204
Adam Nemet339f42b2015-02-19 19:15:07 +00001205 DEBUG(dbgs() << "LAA: Dependence is negative: NoDep\n");
Adam Nemet9c926572015-03-10 17:40:37 +00001206 return Dependence::Forward;
Adam Nemet04563272015-02-01 16:56:15 +00001207 }
1208
1209 // Write to the same location with the same size.
1210 // Could be improved to assert type sizes are the same (i32 == float, etc).
1211 if (Val == 0) {
1212 if (ATy == BTy)
Adam Nemetd7037c52015-11-03 20:13:43 +00001213 return Dependence::Forward;
Adam Nemet339f42b2015-02-19 19:15:07 +00001214 DEBUG(dbgs() << "LAA: Zero dependence difference but different types\n");
Adam Nemet9c926572015-03-10 17:40:37 +00001215 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +00001216 }
1217
1218 assert(Val.isStrictlyPositive() && "Expect a positive value");
1219
Adam Nemet04563272015-02-01 16:56:15 +00001220 if (ATy != BTy) {
Adam Nemet04d41632015-02-19 19:14:34 +00001221 DEBUG(dbgs() <<
Adam Nemet339f42b2015-02-19 19:15:07 +00001222 "LAA: ReadWrite-Write positive dependency with different types\n");
Adam Nemet9c926572015-03-10 17:40:37 +00001223 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +00001224 }
1225
1226 unsigned Distance = (unsigned) Val.getZExtValue();
1227
Hao Liu751004a2015-06-08 04:48:37 +00001228 unsigned Stride = std::abs(StrideAPtr);
1229 if (Stride > 1 &&
Adam Nemet0131a562015-07-08 18:47:38 +00001230 areStridedAccessesIndependent(Distance, Stride, TypeByteSize)) {
1231 DEBUG(dbgs() << "LAA: Strided accesses are independent\n");
Hao Liu751004a2015-06-08 04:48:37 +00001232 return Dependence::NoDep;
Adam Nemet0131a562015-07-08 18:47:38 +00001233 }
Hao Liu751004a2015-06-08 04:48:37 +00001234
Adam Nemet04563272015-02-01 16:56:15 +00001235 // Bail out early if passed-in parameters make vectorization not feasible.
Adam Nemetf219c642015-02-19 19:14:52 +00001236 unsigned ForcedFactor = (VectorizerParams::VectorizationFactor ?
1237 VectorizerParams::VectorizationFactor : 1);
1238 unsigned ForcedUnroll = (VectorizerParams::VectorizationInterleave ?
1239 VectorizerParams::VectorizationInterleave : 1);
Hao Liu751004a2015-06-08 04:48:37 +00001240 // The minimum number of iterations for a vectorized/unrolled version.
1241 unsigned MinNumIter = std::max(ForcedFactor * ForcedUnroll, 2U);
Adam Nemet04563272015-02-01 16:56:15 +00001242
Hao Liu751004a2015-06-08 04:48:37 +00001243 // It's not vectorizable if the distance is smaller than the minimum distance
1244 // needed for a vectroized/unrolled version. Vectorizing one iteration in
1245 // front needs TypeByteSize * Stride. Vectorizing the last iteration needs
1246 // TypeByteSize (No need to plus the last gap distance).
1247 //
1248 // E.g. Assume one char is 1 byte in memory and one int is 4 bytes.
1249 // foo(int *A) {
1250 // int *B = (int *)((char *)A + 14);
1251 // for (i = 0 ; i < 1024 ; i += 2)
1252 // B[i] = A[i] + 1;
1253 // }
1254 //
1255 // Two accesses in memory (stride is 2):
1256 // | A[0] | | A[2] | | A[4] | | A[6] | |
1257 // | B[0] | | B[2] | | B[4] |
1258 //
1259 // Distance needs for vectorizing iterations except the last iteration:
1260 // 4 * 2 * (MinNumIter - 1). Distance needs for the last iteration: 4.
1261 // So the minimum distance needed is: 4 * 2 * (MinNumIter - 1) + 4.
1262 //
1263 // If MinNumIter is 2, it is vectorizable as the minimum distance needed is
1264 // 12, which is less than distance.
1265 //
1266 // If MinNumIter is 4 (Say if a user forces the vectorization factor to be 4),
1267 // the minimum distance needed is 28, which is greater than distance. It is
1268 // not safe to do vectorization.
1269 unsigned MinDistanceNeeded =
1270 TypeByteSize * Stride * (MinNumIter - 1) + TypeByteSize;
1271 if (MinDistanceNeeded > Distance) {
1272 DEBUG(dbgs() << "LAA: Failure because of positive distance " << Distance
1273 << '\n');
1274 return Dependence::Backward;
1275 }
1276
1277 // Unsafe if the minimum distance needed is greater than max safe distance.
1278 if (MinDistanceNeeded > MaxSafeDepDistBytes) {
1279 DEBUG(dbgs() << "LAA: Failure because it needs at least "
1280 << MinDistanceNeeded << " size in bytes");
Adam Nemet9c926572015-03-10 17:40:37 +00001281 return Dependence::Backward;
Adam Nemet04563272015-02-01 16:56:15 +00001282 }
1283
Adam Nemet9cc0c392015-02-26 17:58:48 +00001284 // Positive distance bigger than max vectorization factor.
Hao Liu751004a2015-06-08 04:48:37 +00001285 // FIXME: Should use max factor instead of max distance in bytes, which could
1286 // not handle different types.
1287 // E.g. Assume one char is 1 byte in memory and one int is 4 bytes.
1288 // void foo (int *A, char *B) {
1289 // for (unsigned i = 0; i < 1024; i++) {
1290 // A[i+2] = A[i] + 1;
1291 // B[i+2] = B[i] + 1;
1292 // }
1293 // }
1294 //
1295 // This case is currently unsafe according to the max safe distance. If we
1296 // analyze the two accesses on array B, the max safe dependence distance
1297 // is 2. Then we analyze the accesses on array A, the minimum distance needed
1298 // is 8, which is less than 2 and forbidden vectorization, But actually
1299 // both A and B could be vectorized by 2 iterations.
1300 MaxSafeDepDistBytes =
1301 Distance < MaxSafeDepDistBytes ? Distance : MaxSafeDepDistBytes;
Adam Nemet04563272015-02-01 16:56:15 +00001302
1303 bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
1304 if (IsTrueDataDependence &&
1305 couldPreventStoreLoadForward(Distance, TypeByteSize))
Adam Nemet9c926572015-03-10 17:40:37 +00001306 return Dependence::BackwardVectorizableButPreventsForwarding;
Adam Nemet04563272015-02-01 16:56:15 +00001307
Hao Liu751004a2015-06-08 04:48:37 +00001308 DEBUG(dbgs() << "LAA: Positive distance " << Val.getSExtValue()
1309 << " with max VF = "
1310 << MaxSafeDepDistBytes / (TypeByteSize * Stride) << '\n');
Adam Nemet04563272015-02-01 16:56:15 +00001311
Adam Nemet9c926572015-03-10 17:40:37 +00001312 return Dependence::BackwardVectorizable;
Adam Nemet04563272015-02-01 16:56:15 +00001313}
1314
Adam Nemetdee666b2015-03-10 17:40:34 +00001315bool MemoryDepChecker::areDepsSafe(DepCandidates &AccessSets,
Adam Nemet04563272015-02-01 16:56:15 +00001316 MemAccessInfoSet &CheckDeps,
Adam Nemet8bc61df2015-02-24 00:41:59 +00001317 const ValueToValueMap &Strides) {
Adam Nemet04563272015-02-01 16:56:15 +00001318
1319 MaxSafeDepDistBytes = -1U;
1320 while (!CheckDeps.empty()) {
1321 MemAccessInfo CurAccess = *CheckDeps.begin();
1322
1323 // Get the relevant memory access set.
1324 EquivalenceClasses<MemAccessInfo>::iterator I =
1325 AccessSets.findValue(AccessSets.getLeaderValue(CurAccess));
1326
1327 // Check accesses within this set.
Richard Trieu7a083812016-02-18 22:09:30 +00001328 EquivalenceClasses<MemAccessInfo>::member_iterator AI =
1329 AccessSets.member_begin(I);
1330 EquivalenceClasses<MemAccessInfo>::member_iterator AE =
1331 AccessSets.member_end();
Adam Nemet04563272015-02-01 16:56:15 +00001332
1333 // Check every access pair.
1334 while (AI != AE) {
1335 CheckDeps.erase(*AI);
1336 EquivalenceClasses<MemAccessInfo>::member_iterator OI = std::next(AI);
1337 while (OI != AE) {
1338 // Check every accessing instruction pair in program order.
1339 for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(),
1340 I1E = Accesses[*AI].end(); I1 != I1E; ++I1)
1341 for (std::vector<unsigned>::iterator I2 = Accesses[*OI].begin(),
1342 I2E = Accesses[*OI].end(); I2 != I2E; ++I2) {
Adam Nemet9c926572015-03-10 17:40:37 +00001343 auto A = std::make_pair(&*AI, *I1);
1344 auto B = std::make_pair(&*OI, *I2);
1345
1346 assert(*I1 != *I2);
1347 if (*I1 > *I2)
1348 std::swap(A, B);
1349
1350 Dependence::DepType Type =
1351 isDependent(*A.first, A.second, *B.first, B.second, Strides);
1352 SafeForVectorization &= Dependence::isSafeForVectorization(Type);
1353
Adam Nemeta2df7502015-11-03 21:39:52 +00001354 // Gather dependences unless we accumulated MaxDependences
Adam Nemet9c926572015-03-10 17:40:37 +00001355 // dependences. In that case return as soon as we find the first
1356 // unsafe dependence. This puts a limit on this quadratic
1357 // algorithm.
Adam Nemeta2df7502015-11-03 21:39:52 +00001358 if (RecordDependences) {
1359 if (Type != Dependence::NoDep)
1360 Dependences.push_back(Dependence(A.second, B.second, Type));
Adam Nemet9c926572015-03-10 17:40:37 +00001361
Adam Nemeta2df7502015-11-03 21:39:52 +00001362 if (Dependences.size() >= MaxDependences) {
1363 RecordDependences = false;
1364 Dependences.clear();
Adam Nemet9c926572015-03-10 17:40:37 +00001365 DEBUG(dbgs() << "Too many dependences, stopped recording\n");
1366 }
1367 }
Adam Nemeta2df7502015-11-03 21:39:52 +00001368 if (!RecordDependences && !SafeForVectorization)
Adam Nemet04563272015-02-01 16:56:15 +00001369 return false;
1370 }
1371 ++OI;
1372 }
1373 AI++;
1374 }
1375 }
Adam Nemet9c926572015-03-10 17:40:37 +00001376
Adam Nemeta2df7502015-11-03 21:39:52 +00001377 DEBUG(dbgs() << "Total Dependences: " << Dependences.size() << "\n");
Adam Nemet9c926572015-03-10 17:40:37 +00001378 return SafeForVectorization;
Adam Nemet04563272015-02-01 16:56:15 +00001379}
1380
Adam Nemetec1e2bb2015-03-10 18:54:26 +00001381SmallVector<Instruction *, 4>
1382MemoryDepChecker::getInstructionsForAccess(Value *Ptr, bool isWrite) const {
1383 MemAccessInfo Access(Ptr, isWrite);
1384 auto &IndexVector = Accesses.find(Access)->second;
1385
1386 SmallVector<Instruction *, 4> Insts;
1387 std::transform(IndexVector.begin(), IndexVector.end(),
1388 std::back_inserter(Insts),
1389 [&](unsigned Idx) { return this->InstMap[Idx]; });
1390 return Insts;
1391}
1392
Adam Nemet58913d62015-03-10 17:40:43 +00001393const char *MemoryDepChecker::Dependence::DepName[] = {
1394 "NoDep", "Unknown", "Forward", "ForwardButPreventsForwarding", "Backward",
1395 "BackwardVectorizable", "BackwardVectorizableButPreventsForwarding"};
1396
1397void MemoryDepChecker::Dependence::print(
1398 raw_ostream &OS, unsigned Depth,
1399 const SmallVectorImpl<Instruction *> &Instrs) const {
1400 OS.indent(Depth) << DepName[Type] << ":\n";
1401 OS.indent(Depth + 2) << *Instrs[Source] << " -> \n";
1402 OS.indent(Depth + 2) << *Instrs[Destination] << "\n";
1403}
1404
Adam Nemet929c38e2015-02-19 19:15:10 +00001405bool LoopAccessInfo::canAnalyzeLoop() {
Adam Nemet8dcb3b62015-04-17 22:43:10 +00001406 // We need to have a loop header.
Adam Nemetd8968f02016-01-18 21:16:33 +00001407 DEBUG(dbgs() << "LAA: Found a loop in "
1408 << TheLoop->getHeader()->getParent()->getName() << ": "
1409 << TheLoop->getHeader()->getName() << '\n');
Adam Nemet8dcb3b62015-04-17 22:43:10 +00001410
Adam Nemetd8968f02016-01-18 21:16:33 +00001411 // We can only analyze innermost loops.
Adam Nemet929c38e2015-02-19 19:15:10 +00001412 if (!TheLoop->empty()) {
Adam Nemet8dcb3b62015-04-17 22:43:10 +00001413 DEBUG(dbgs() << "LAA: loop is not the innermost loop\n");
Adam Nemet2bd6e982015-02-19 19:15:15 +00001414 emitAnalysis(LoopAccessReport() << "loop is not the innermost loop");
Adam Nemet929c38e2015-02-19 19:15:10 +00001415 return false;
1416 }
1417
1418 // We must have a single backedge.
1419 if (TheLoop->getNumBackEdges() != 1) {
Adam Nemet8dcb3b62015-04-17 22:43:10 +00001420 DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n");
Adam Nemet929c38e2015-02-19 19:15:10 +00001421 emitAnalysis(
Adam Nemet2bd6e982015-02-19 19:15:15 +00001422 LoopAccessReport() <<
Adam Nemet929c38e2015-02-19 19:15:10 +00001423 "loop control flow is not understood by analyzer");
1424 return false;
1425 }
1426
1427 // We must have a single exiting block.
1428 if (!TheLoop->getExitingBlock()) {
Adam Nemet8dcb3b62015-04-17 22:43:10 +00001429 DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n");
Adam Nemet929c38e2015-02-19 19:15:10 +00001430 emitAnalysis(
Adam Nemet2bd6e982015-02-19 19:15:15 +00001431 LoopAccessReport() <<
Adam Nemet929c38e2015-02-19 19:15:10 +00001432 "loop control flow is not understood by analyzer");
1433 return false;
1434 }
1435
1436 // We only handle bottom-tested loops, i.e. loop in which the condition is
1437 // checked at the end of each iteration. With that we can assume that all
1438 // instructions in the loop are executed the same number of times.
1439 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
Adam Nemet8dcb3b62015-04-17 22:43:10 +00001440 DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n");
Adam Nemet929c38e2015-02-19 19:15:10 +00001441 emitAnalysis(
Adam Nemet2bd6e982015-02-19 19:15:15 +00001442 LoopAccessReport() <<
Adam Nemet929c38e2015-02-19 19:15:10 +00001443 "loop control flow is not understood by analyzer");
1444 return false;
1445 }
1446
Adam Nemet929c38e2015-02-19 19:15:10 +00001447 // ScalarEvolution needs to be able to find the exit count.
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +00001448 const SCEV *ExitCount = PSE.getSE()->getBackedgeTakenCount(TheLoop);
1449 if (ExitCount == PSE.getSE()->getCouldNotCompute()) {
1450 emitAnalysis(LoopAccessReport()
1451 << "could not determine number of loop iterations");
Adam Nemet929c38e2015-02-19 19:15:10 +00001452 DEBUG(dbgs() << "LAA: SCEV could not compute the loop exit count.\n");
1453 return false;
1454 }
1455
1456 return true;
1457}
1458
Adam Nemet8bc61df2015-02-24 00:41:59 +00001459void LoopAccessInfo::analyzeLoop(const ValueToValueMap &Strides) {
Adam Nemet04563272015-02-01 16:56:15 +00001460
1461 typedef SmallVector<Value*, 16> ValueVector;
1462 typedef SmallPtrSet<Value*, 16> ValueSet;
1463
1464 // Holds the Load and Store *instructions*.
1465 ValueVector Loads;
1466 ValueVector Stores;
1467
1468 // Holds all the different accesses in the loop.
1469 unsigned NumReads = 0;
1470 unsigned NumReadWrites = 0;
1471
Adam Nemet7cdebac2015-07-14 22:32:44 +00001472 PtrRtChecking.Pointers.clear();
1473 PtrRtChecking.Need = false;
Adam Nemet04563272015-02-01 16:56:15 +00001474
1475 const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
Adam Nemet04563272015-02-01 16:56:15 +00001476
1477 // For each block.
1478 for (Loop::block_iterator bb = TheLoop->block_begin(),
1479 be = TheLoop->block_end(); bb != be; ++bb) {
1480
1481 // Scan the BB and collect legal loads and stores.
1482 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
1483 ++it) {
1484
1485 // If this is a load, save it. If this instruction can read from memory
1486 // but is not a load, then we quit. Notice that we don't handle function
1487 // calls that read or write.
1488 if (it->mayReadFromMemory()) {
1489 // Many math library functions read the rounding mode. We will only
1490 // vectorize a loop if it contains known function calls that don't set
1491 // the flag. Therefore, it is safe to ignore this read from memory.
1492 CallInst *Call = dyn_cast<CallInst>(it);
1493 if (Call && getIntrinsicIDForCall(Call, TLI))
1494 continue;
1495
Michael Zolotukhin9b3cf602015-03-17 19:46:50 +00001496 // If the function has an explicit vectorized counterpart, we can safely
1497 // assume that it can be vectorized.
1498 if (Call && !Call->isNoBuiltin() && Call->getCalledFunction() &&
1499 TLI->isFunctionVectorizable(Call->getCalledFunction()->getName()))
1500 continue;
1501
Adam Nemet04563272015-02-01 16:56:15 +00001502 LoadInst *Ld = dyn_cast<LoadInst>(it);
1503 if (!Ld || (!Ld->isSimple() && !IsAnnotatedParallel)) {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001504 emitAnalysis(LoopAccessReport(Ld)
Adam Nemet04563272015-02-01 16:56:15 +00001505 << "read with atomic ordering or volatile read");
Adam Nemet339f42b2015-02-19 19:15:07 +00001506 DEBUG(dbgs() << "LAA: Found a non-simple load.\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001507 CanVecMem = false;
1508 return;
Adam Nemet04563272015-02-01 16:56:15 +00001509 }
1510 NumLoads++;
1511 Loads.push_back(Ld);
1512 DepChecker.addAccess(Ld);
1513 continue;
1514 }
1515
1516 // Save 'store' instructions. Abort if other instructions write to memory.
1517 if (it->mayWriteToMemory()) {
1518 StoreInst *St = dyn_cast<StoreInst>(it);
1519 if (!St) {
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +00001520 emitAnalysis(LoopAccessReport(&*it) <<
Adam Nemet04d41632015-02-19 19:14:34 +00001521 "instruction cannot be vectorized");
Adam Nemet436018c2015-02-19 19:15:00 +00001522 CanVecMem = false;
1523 return;
Adam Nemet04563272015-02-01 16:56:15 +00001524 }
1525 if (!St->isSimple() && !IsAnnotatedParallel) {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001526 emitAnalysis(LoopAccessReport(St)
Adam Nemet04563272015-02-01 16:56:15 +00001527 << "write with atomic ordering or volatile write");
Adam Nemet339f42b2015-02-19 19:15:07 +00001528 DEBUG(dbgs() << "LAA: Found a non-simple store.\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001529 CanVecMem = false;
1530 return;
Adam Nemet04563272015-02-01 16:56:15 +00001531 }
1532 NumStores++;
1533 Stores.push_back(St);
1534 DepChecker.addAccess(St);
1535 }
1536 } // Next instr.
1537 } // Next block.
1538
1539 // Now we have two lists that hold the loads and the stores.
1540 // Next, we find the pointers that they use.
1541
1542 // Check if we see any stores. If there are no stores, then we don't
1543 // care if the pointers are *restrict*.
1544 if (!Stores.size()) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001545 DEBUG(dbgs() << "LAA: Found a read-only loop!\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001546 CanVecMem = true;
1547 return;
Adam Nemet04563272015-02-01 16:56:15 +00001548 }
1549
Adam Nemetdee666b2015-03-10 17:40:34 +00001550 MemoryDepChecker::DepCandidates DependentAccesses;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001551 AccessAnalysis Accesses(TheLoop->getHeader()->getModule()->getDataLayout(),
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +00001552 AA, LI, DependentAccesses, PSE);
Adam Nemet04563272015-02-01 16:56:15 +00001553
1554 // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
1555 // multiple times on the same object. If the ptr is accessed twice, once
1556 // for read and once for write, it will only appear once (on the write
1557 // list). This is okay, since we are going to check for conflicts between
1558 // writes and between reads and writes, but not between reads and reads.
1559 ValueSet Seen;
1560
1561 ValueVector::iterator I, IE;
1562 for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
1563 StoreInst *ST = cast<StoreInst>(*I);
1564 Value* Ptr = ST->getPointerOperand();
Adam Nemetce482502015-04-08 17:48:40 +00001565 // Check for store to loop invariant address.
1566 StoreToLoopInvariantAddress |= isUniform(Ptr);
Adam Nemet04563272015-02-01 16:56:15 +00001567 // If we did *not* see this pointer before, insert it to the read-write
1568 // list. At this phase it is only a 'write' list.
1569 if (Seen.insert(Ptr).second) {
1570 ++NumReadWrites;
1571
Chandler Carruthac80dc72015-06-17 07:18:54 +00001572 MemoryLocation Loc = MemoryLocation::get(ST);
Adam Nemet04563272015-02-01 16:56:15 +00001573 // The TBAA metadata could have a control dependency on the predication
1574 // condition, so we cannot rely on it when determining whether or not we
1575 // need runtime pointer checks.
Adam Nemet01abb2c2015-02-18 03:43:19 +00001576 if (blockNeedsPredication(ST->getParent(), TheLoop, DT))
Adam Nemet04563272015-02-01 16:56:15 +00001577 Loc.AATags.TBAA = nullptr;
1578
1579 Accesses.addStore(Loc);
1580 }
1581 }
1582
1583 if (IsAnnotatedParallel) {
Adam Nemet04d41632015-02-19 19:14:34 +00001584 DEBUG(dbgs()
Adam Nemet339f42b2015-02-19 19:15:07 +00001585 << "LAA: A loop annotated parallel, ignore memory dependency "
Adam Nemet04d41632015-02-19 19:14:34 +00001586 << "checks.\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001587 CanVecMem = true;
1588 return;
Adam Nemet04563272015-02-01 16:56:15 +00001589 }
1590
1591 for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
1592 LoadInst *LD = cast<LoadInst>(*I);
1593 Value* Ptr = LD->getPointerOperand();
1594 // If we did *not* see this pointer before, insert it to the
1595 // read list. If we *did* see it before, then it is already in
1596 // the read-write list. This allows us to vectorize expressions
1597 // such as A[i] += x; Because the address of A[i] is a read-write
1598 // pointer. This only works if the index of A[i] is consecutive.
1599 // If the address of i is unknown (for example A[B[i]]) then we may
1600 // read a few words, modify, and write a few words, and some of the
1601 // words may be written to the same address.
1602 bool IsReadOnlyPtr = false;
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +00001603 if (Seen.insert(Ptr).second || !isStridedPtr(PSE, Ptr, TheLoop, Strides)) {
Adam Nemet04563272015-02-01 16:56:15 +00001604 ++NumReads;
1605 IsReadOnlyPtr = true;
1606 }
1607
Chandler Carruthac80dc72015-06-17 07:18:54 +00001608 MemoryLocation Loc = MemoryLocation::get(LD);
Adam Nemet04563272015-02-01 16:56:15 +00001609 // The TBAA metadata could have a control dependency on the predication
1610 // condition, so we cannot rely on it when determining whether or not we
1611 // need runtime pointer checks.
Adam Nemet01abb2c2015-02-18 03:43:19 +00001612 if (blockNeedsPredication(LD->getParent(), TheLoop, DT))
Adam Nemet04563272015-02-01 16:56:15 +00001613 Loc.AATags.TBAA = nullptr;
1614
1615 Accesses.addLoad(Loc, IsReadOnlyPtr);
1616 }
1617
1618 // If we write (or read-write) to a single destination and there are no
1619 // other reads in this loop then is it safe to vectorize.
1620 if (NumReadWrites == 1 && NumReads == 0) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001621 DEBUG(dbgs() << "LAA: Found a write-only loop!\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001622 CanVecMem = true;
1623 return;
Adam Nemet04563272015-02-01 16:56:15 +00001624 }
1625
1626 // Build dependence sets and check whether we need a runtime pointer bounds
1627 // check.
1628 Accesses.buildDependenceSets();
Adam Nemet04563272015-02-01 16:56:15 +00001629
1630 // Find pointers with computable bounds. We are going to use this information
1631 // to place a runtime bound check.
Adam Nemetee614742015-07-09 22:17:38 +00001632 bool CanDoRTIfNeeded =
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +00001633 Accesses.canCheckPtrAtRT(PtrRtChecking, PSE.getSE(), TheLoop, Strides);
Adam Nemetee614742015-07-09 22:17:38 +00001634 if (!CanDoRTIfNeeded) {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001635 emitAnalysis(LoopAccessReport() << "cannot identify array bounds");
Adam Nemetee614742015-07-09 22:17:38 +00001636 DEBUG(dbgs() << "LAA: We can't vectorize because we can't find "
1637 << "the array bounds.\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001638 CanVecMem = false;
1639 return;
Adam Nemet04563272015-02-01 16:56:15 +00001640 }
1641
Adam Nemetee614742015-07-09 22:17:38 +00001642 DEBUG(dbgs() << "LAA: We can perform a memory runtime check if needed.\n");
Adam Nemet04563272015-02-01 16:56:15 +00001643
Adam Nemet436018c2015-02-19 19:15:00 +00001644 CanVecMem = true;
Adam Nemet04563272015-02-01 16:56:15 +00001645 if (Accesses.isDependencyCheckNeeded()) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001646 DEBUG(dbgs() << "LAA: Checking memory dependencies\n");
Adam Nemet04563272015-02-01 16:56:15 +00001647 CanVecMem = DepChecker.areDepsSafe(
1648 DependentAccesses, Accesses.getDependenciesToCheck(), Strides);
1649 MaxSafeDepDistBytes = DepChecker.getMaxSafeDepDistBytes();
1650
1651 if (!CanVecMem && DepChecker.shouldRetryWithRuntimeCheck()) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001652 DEBUG(dbgs() << "LAA: Retrying with memory checks\n");
Adam Nemet04563272015-02-01 16:56:15 +00001653
1654 // Clear the dependency checks. We assume they are not needed.
Adam Nemetdf3dc5b2015-05-18 15:37:03 +00001655 Accesses.resetDepChecks(DepChecker);
Adam Nemet04563272015-02-01 16:56:15 +00001656
Adam Nemet7cdebac2015-07-14 22:32:44 +00001657 PtrRtChecking.reset();
1658 PtrRtChecking.Need = true;
Adam Nemet04563272015-02-01 16:56:15 +00001659
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +00001660 auto *SE = PSE.getSE();
Adam Nemetee614742015-07-09 22:17:38 +00001661 CanDoRTIfNeeded =
Adam Nemet7cdebac2015-07-14 22:32:44 +00001662 Accesses.canCheckPtrAtRT(PtrRtChecking, SE, TheLoop, Strides, true);
Silviu Baranga98a13712015-06-08 10:27:06 +00001663
Adam Nemet949e91a2015-03-10 19:12:41 +00001664 // Check that we found the bounds for the pointer.
Adam Nemetee614742015-07-09 22:17:38 +00001665 if (!CanDoRTIfNeeded) {
Adam Nemetb6dc76f2015-03-10 18:54:19 +00001666 emitAnalysis(LoopAccessReport()
1667 << "cannot check memory dependencies at runtime");
1668 DEBUG(dbgs() << "LAA: Can't vectorize with memory checks\n");
Adam Nemetb6dc76f2015-03-10 18:54:19 +00001669 CanVecMem = false;
1670 return;
1671 }
1672
Adam Nemet04563272015-02-01 16:56:15 +00001673 CanVecMem = true;
1674 }
1675 }
1676
Adam Nemet4bb90a72015-03-10 21:47:39 +00001677 if (CanVecMem)
1678 DEBUG(dbgs() << "LAA: No unsafe dependent memory operations in loop. We"
Adam Nemet7cdebac2015-07-14 22:32:44 +00001679 << (PtrRtChecking.Need ? "" : " don't")
Adam Nemet0f67c6c2015-07-09 22:17:41 +00001680 << " need runtime memory checks.\n");
Adam Nemet4bb90a72015-03-10 21:47:39 +00001681 else {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001682 emitAnalysis(LoopAccessReport() <<
Adam Nemet04d41632015-02-19 19:14:34 +00001683 "unsafe dependent memory operations in loop");
Adam Nemet4bb90a72015-03-10 21:47:39 +00001684 DEBUG(dbgs() << "LAA: unsafe dependent memory operations in loop\n");
1685 }
Adam Nemet04563272015-02-01 16:56:15 +00001686}
1687
Adam Nemet01abb2c2015-02-18 03:43:19 +00001688bool LoopAccessInfo::blockNeedsPredication(BasicBlock *BB, Loop *TheLoop,
1689 DominatorTree *DT) {
Adam Nemet04563272015-02-01 16:56:15 +00001690 assert(TheLoop->contains(BB) && "Unknown block used");
1691
1692 // Blocks that do not dominate the latch need predication.
1693 BasicBlock* Latch = TheLoop->getLoopLatch();
1694 return !DT->dominates(BB, Latch);
1695}
1696
Adam Nemet2bd6e982015-02-19 19:15:15 +00001697void LoopAccessInfo::emitAnalysis(LoopAccessReport &Message) {
Adam Nemetc9228532015-02-19 19:14:56 +00001698 assert(!Report && "Multiple reports generated");
1699 Report = Message;
Adam Nemet04563272015-02-01 16:56:15 +00001700}
1701
Adam Nemet57ac7662015-02-19 19:15:21 +00001702bool LoopAccessInfo::isUniform(Value *V) const {
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +00001703 return (PSE.getSE()->isLoopInvariant(PSE.getSE()->getSCEV(V), TheLoop));
Adam Nemet04563272015-02-01 16:56:15 +00001704}
Adam Nemet7206d7a2015-02-06 18:31:04 +00001705
1706// FIXME: this function is currently a duplicate of the one in
1707// LoopVectorize.cpp.
1708static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
1709 Instruction *Loc) {
1710 if (FirstInst)
1711 return FirstInst;
1712 if (Instruction *I = dyn_cast<Instruction>(V))
1713 return I->getParent() == Loc->getParent() ? I : nullptr;
1714 return nullptr;
1715}
1716
Benjamin Kramer039b1042015-10-28 13:54:36 +00001717namespace {
Adam Nemet4e533ef2015-08-21 23:19:57 +00001718/// \brief IR Values for the lower and upper bounds of a pointer evolution. We
1719/// need to use value-handles because SCEV expansion can invalidate previously
1720/// expanded values. Thus expansion of a pointer can invalidate the bounds for
1721/// a previous one.
Adam Nemet1da7df32015-07-26 05:32:14 +00001722struct PointerBounds {
Adam Nemet4e533ef2015-08-21 23:19:57 +00001723 TrackingVH<Value> Start;
1724 TrackingVH<Value> End;
Adam Nemet1da7df32015-07-26 05:32:14 +00001725};
Benjamin Kramer039b1042015-10-28 13:54:36 +00001726} // end anonymous namespace
Adam Nemet7206d7a2015-02-06 18:31:04 +00001727
Adam Nemet1da7df32015-07-26 05:32:14 +00001728/// \brief Expand code for the lower and upper bound of the pointer group \p CG
1729/// in \p TheLoop. \return the values for the bounds.
1730static PointerBounds
1731expandBounds(const RuntimePointerChecking::CheckingPtrGroup *CG, Loop *TheLoop,
1732 Instruction *Loc, SCEVExpander &Exp, ScalarEvolution *SE,
1733 const RuntimePointerChecking &PtrRtChecking) {
1734 Value *Ptr = PtrRtChecking.Pointers[CG->Members[0]].PointerValue;
1735 const SCEV *Sc = SE->getSCEV(Ptr);
1736
1737 if (SE->isLoopInvariant(Sc, TheLoop)) {
1738 DEBUG(dbgs() << "LAA: Adding RT check for a loop invariant ptr:" << *Ptr
1739 << "\n");
1740 return {Ptr, Ptr};
1741 } else {
1742 unsigned AS = Ptr->getType()->getPointerAddressSpace();
1743 LLVMContext &Ctx = Loc->getContext();
1744
1745 // Use this type for pointer arithmetic.
1746 Type *PtrArithTy = Type::getInt8PtrTy(Ctx, AS);
1747 Value *Start = nullptr, *End = nullptr;
1748
1749 DEBUG(dbgs() << "LAA: Adding RT check for range:\n");
1750 Start = Exp.expandCodeFor(CG->Low, PtrArithTy, Loc);
1751 End = Exp.expandCodeFor(CG->High, PtrArithTy, Loc);
1752 DEBUG(dbgs() << "Start: " << *CG->Low << " End: " << *CG->High << "\n");
1753 return {Start, End};
1754 }
1755}
1756
1757/// \brief Turns a collection of checks into a collection of expanded upper and
1758/// lower bounds for both pointers in the check.
1759static SmallVector<std::pair<PointerBounds, PointerBounds>, 4> expandBounds(
1760 const SmallVectorImpl<RuntimePointerChecking::PointerCheck> &PointerChecks,
1761 Loop *L, Instruction *Loc, ScalarEvolution *SE, SCEVExpander &Exp,
1762 const RuntimePointerChecking &PtrRtChecking) {
1763 SmallVector<std::pair<PointerBounds, PointerBounds>, 4> ChecksWithBounds;
1764
1765 // Here we're relying on the SCEV Expander's cache to only emit code for the
1766 // same bounds once.
1767 std::transform(
1768 PointerChecks.begin(), PointerChecks.end(),
1769 std::back_inserter(ChecksWithBounds),
1770 [&](const RuntimePointerChecking::PointerCheck &Check) {
NAKAMURA Takumi94abbbd2015-07-27 01:35:30 +00001771 PointerBounds
1772 First = expandBounds(Check.first, L, Loc, Exp, SE, PtrRtChecking),
1773 Second = expandBounds(Check.second, L, Loc, Exp, SE, PtrRtChecking);
1774 return std::make_pair(First, Second);
Adam Nemet1da7df32015-07-26 05:32:14 +00001775 });
1776
1777 return ChecksWithBounds;
1778}
1779
Adam Nemet5b0a4792015-08-11 00:09:37 +00001780std::pair<Instruction *, Instruction *> LoopAccessInfo::addRuntimeChecks(
Adam Nemet1da7df32015-07-26 05:32:14 +00001781 Instruction *Loc,
1782 const SmallVectorImpl<RuntimePointerChecking::PointerCheck> &PointerChecks)
1783 const {
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +00001784 auto *SE = PSE.getSE();
Adam Nemet1da7df32015-07-26 05:32:14 +00001785 SCEVExpander Exp(*SE, DL, "induction");
1786 auto ExpandedChecks =
1787 expandBounds(PointerChecks, TheLoop, Loc, SE, Exp, PtrRtChecking);
Adam Nemet7206d7a2015-02-06 18:31:04 +00001788
1789 LLVMContext &Ctx = Loc->getContext();
Adam Nemet7206d7a2015-02-06 18:31:04 +00001790 Instruction *FirstInst = nullptr;
Adam Nemet7206d7a2015-02-06 18:31:04 +00001791 IRBuilder<> ChkBuilder(Loc);
1792 // Our instructions might fold to a constant.
1793 Value *MemoryRuntimeCheck = nullptr;
Silviu Baranga1b6b50a2015-07-08 09:16:33 +00001794
Adam Nemet1da7df32015-07-26 05:32:14 +00001795 for (const auto &Check : ExpandedChecks) {
1796 const PointerBounds &A = Check.first, &B = Check.second;
Adam Nemetcdb791c2015-08-19 17:24:36 +00001797 // Check if two pointers (A and B) conflict where conflict is computed as:
1798 // start(A) <= end(B) && start(B) <= end(A)
Adam Nemet1da7df32015-07-26 05:32:14 +00001799 unsigned AS0 = A.Start->getType()->getPointerAddressSpace();
1800 unsigned AS1 = B.Start->getType()->getPointerAddressSpace();
Adam Nemet7206d7a2015-02-06 18:31:04 +00001801
Adam Nemet1da7df32015-07-26 05:32:14 +00001802 assert((AS0 == B.End->getType()->getPointerAddressSpace()) &&
1803 (AS1 == A.End->getType()->getPointerAddressSpace()) &&
1804 "Trying to bounds check pointers with different address spaces");
Adam Nemet7206d7a2015-02-06 18:31:04 +00001805
Adam Nemet1da7df32015-07-26 05:32:14 +00001806 Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0);
1807 Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1);
Adam Nemet7206d7a2015-02-06 18:31:04 +00001808
Adam Nemet1da7df32015-07-26 05:32:14 +00001809 Value *Start0 = ChkBuilder.CreateBitCast(A.Start, PtrArithTy0, "bc");
1810 Value *Start1 = ChkBuilder.CreateBitCast(B.Start, PtrArithTy1, "bc");
1811 Value *End0 = ChkBuilder.CreateBitCast(A.End, PtrArithTy1, "bc");
1812 Value *End1 = ChkBuilder.CreateBitCast(B.End, PtrArithTy0, "bc");
Adam Nemet7206d7a2015-02-06 18:31:04 +00001813
Adam Nemet1da7df32015-07-26 05:32:14 +00001814 Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0");
1815 FirstInst = getFirstInst(FirstInst, Cmp0, Loc);
1816 Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1");
1817 FirstInst = getFirstInst(FirstInst, Cmp1, Loc);
1818 Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
1819 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1820 if (MemoryRuntimeCheck) {
1821 IsConflict =
1822 ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict, "conflict.rdx");
Adam Nemet7206d7a2015-02-06 18:31:04 +00001823 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
Adam Nemet7206d7a2015-02-06 18:31:04 +00001824 }
Adam Nemet1da7df32015-07-26 05:32:14 +00001825 MemoryRuntimeCheck = IsConflict;
Adam Nemet7206d7a2015-02-06 18:31:04 +00001826 }
1827
Adam Nemet90fec842015-04-02 17:51:57 +00001828 if (!MemoryRuntimeCheck)
1829 return std::make_pair(nullptr, nullptr);
1830
Adam Nemet7206d7a2015-02-06 18:31:04 +00001831 // We have to do this trickery because the IRBuilder might fold the check to a
1832 // constant expression in which case there is no Instruction anchored in a
1833 // the block.
1834 Instruction *Check = BinaryOperator::CreateAnd(MemoryRuntimeCheck,
1835 ConstantInt::getTrue(Ctx));
1836 ChkBuilder.Insert(Check, "memcheck.conflict");
1837 FirstInst = getFirstInst(FirstInst, Check, Loc);
1838 return std::make_pair(FirstInst, Check);
1839}
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001840
Adam Nemet5b0a4792015-08-11 00:09:37 +00001841std::pair<Instruction *, Instruction *>
1842LoopAccessInfo::addRuntimeChecks(Instruction *Loc) const {
Adam Nemet1da7df32015-07-26 05:32:14 +00001843 if (!PtrRtChecking.Need)
1844 return std::make_pair(nullptr, nullptr);
1845
Adam Nemet5b0a4792015-08-11 00:09:37 +00001846 return addRuntimeChecks(Loc, PtrRtChecking.getChecks());
Adam Nemet1da7df32015-07-26 05:32:14 +00001847}
1848
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001849LoopAccessInfo::LoopAccessInfo(Loop *L, ScalarEvolution *SE,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001850 const DataLayout &DL,
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001851 const TargetLibraryInfo *TLI, AliasAnalysis *AA,
Adam Nemete2b885c2015-04-23 20:09:20 +00001852 DominatorTree *DT, LoopInfo *LI,
Adam Nemet8bc61df2015-02-24 00:41:59 +00001853 const ValueToValueMap &Strides)
Silviu Barangaea63a7f2016-02-08 17:02:45 +00001854 : PSE(*SE, *L), PtrRtChecking(SE), DepChecker(PSE, L), TheLoop(L), DL(DL),
Adam Nemet7cdebac2015-07-14 22:32:44 +00001855 TLI(TLI), AA(AA), DT(DT), LI(LI), NumLoads(0), NumStores(0),
Adam Nemetce482502015-04-08 17:48:40 +00001856 MaxSafeDepDistBytes(-1U), CanVecMem(false),
1857 StoreToLoopInvariantAddress(false) {
Adam Nemet929c38e2015-02-19 19:15:10 +00001858 if (canAnalyzeLoop())
1859 analyzeLoop(Strides);
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001860}
1861
Adam Nemete91cc6e2015-02-19 19:15:19 +00001862void LoopAccessInfo::print(raw_ostream &OS, unsigned Depth) const {
1863 if (CanVecMem) {
Adam Nemet7cdebac2015-07-14 22:32:44 +00001864 if (PtrRtChecking.Need)
Adam Nemete91cc6e2015-02-19 19:15:19 +00001865 OS.indent(Depth) << "Memory dependences are safe with run-time checks\n";
Adam Nemet26da8e92015-04-14 01:12:55 +00001866 else
1867 OS.indent(Depth) << "Memory dependences are safe\n";
Adam Nemete91cc6e2015-02-19 19:15:19 +00001868 }
1869
1870 if (Report)
1871 OS.indent(Depth) << "Report: " << Report->str() << "\n";
1872
Adam Nemeta2df7502015-11-03 21:39:52 +00001873 if (auto *Dependences = DepChecker.getDependences()) {
1874 OS.indent(Depth) << "Dependences:\n";
1875 for (auto &Dep : *Dependences) {
Adam Nemet58913d62015-03-10 17:40:43 +00001876 Dep.print(OS, Depth + 2, DepChecker.getMemoryInstructions());
1877 OS << "\n";
1878 }
1879 } else
Adam Nemeta2df7502015-11-03 21:39:52 +00001880 OS.indent(Depth) << "Too many dependences, not recorded\n";
Adam Nemete91cc6e2015-02-19 19:15:19 +00001881
1882 // List the pair of accesses need run-time checks to prove independence.
Adam Nemet7cdebac2015-07-14 22:32:44 +00001883 PtrRtChecking.print(OS, Depth);
Adam Nemete91cc6e2015-02-19 19:15:19 +00001884 OS << "\n";
Adam Nemetc3384322015-05-18 15:36:57 +00001885
1886 OS.indent(Depth) << "Store to invariant address was "
1887 << (StoreToLoopInvariantAddress ? "" : "not ")
1888 << "found in loop.\n";
Silviu Barangae3c05342015-11-02 14:41:02 +00001889
1890 OS.indent(Depth) << "SCEV assumptions:\n";
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +00001891 PSE.getUnionPredicate().print(OS, Depth);
Adam Nemete91cc6e2015-02-19 19:15:19 +00001892}
1893
Adam Nemet8bc61df2015-02-24 00:41:59 +00001894const LoopAccessInfo &
1895LoopAccessAnalysis::getInfo(Loop *L, const ValueToValueMap &Strides) {
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001896 auto &LAI = LoopAccessInfoMap[L];
1897
1898#ifndef NDEBUG
1899 assert((!LAI || LAI->NumSymbolicStrides == Strides.size()) &&
1900 "Symbolic strides changed for loop");
1901#endif
1902
1903 if (!LAI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001904 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
Silviu Barangae3c05342015-11-02 14:41:02 +00001905 LAI =
1906 llvm::make_unique<LoopAccessInfo>(L, SE, DL, TLI, AA, DT, LI, Strides);
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001907#ifndef NDEBUG
1908 LAI->NumSymbolicStrides = Strides.size();
1909#endif
1910 }
1911 return *LAI.get();
1912}
1913
Adam Nemete91cc6e2015-02-19 19:15:19 +00001914void LoopAccessAnalysis::print(raw_ostream &OS, const Module *M) const {
1915 LoopAccessAnalysis &LAA = *const_cast<LoopAccessAnalysis *>(this);
1916
Adam Nemete91cc6e2015-02-19 19:15:19 +00001917 ValueToValueMap NoSymbolicStrides;
1918
1919 for (Loop *TopLevelLoop : *LI)
1920 for (Loop *L : depth_first(TopLevelLoop)) {
1921 OS.indent(2) << L->getHeader()->getName() << ":\n";
1922 auto &LAI = LAA.getInfo(L, NoSymbolicStrides);
1923 LAI.print(OS, 4);
1924 }
1925}
1926
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001927bool LoopAccessAnalysis::runOnFunction(Function &F) {
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001928 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001929 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
1930 TLI = TLIP ? &TLIP->getTLI() : nullptr;
Chandler Carruth7b560d42015-09-09 17:55:00 +00001931 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001932 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Adam Nemete2b885c2015-04-23 20:09:20 +00001933 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001934
1935 return false;
1936}
1937
1938void LoopAccessAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001939 AU.addRequired<ScalarEvolutionWrapperPass>();
Chandler Carruth7b560d42015-09-09 17:55:00 +00001940 AU.addRequired<AAResultsWrapperPass>();
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001941 AU.addRequired<DominatorTreeWrapperPass>();
Adam Nemete91cc6e2015-02-19 19:15:19 +00001942 AU.addRequired<LoopInfoWrapperPass>();
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001943
1944 AU.setPreservesAll();
1945}
1946
1947char LoopAccessAnalysis::ID = 0;
1948static const char laa_name[] = "Loop Access Analysis";
1949#define LAA_NAME "loop-accesses"
1950
1951INITIALIZE_PASS_BEGIN(LoopAccessAnalysis, LAA_NAME, laa_name, false, true)
Chandler Carruth7b560d42015-09-09 17:55:00 +00001952INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001953INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001954INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Adam Nemete91cc6e2015-02-19 19:15:19 +00001955INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001956INITIALIZE_PASS_END(LoopAccessAnalysis, LAA_NAME, laa_name, false, true)
1957
1958namespace llvm {
1959 Pass *createLAAPass() {
1960 return new LoopAccessAnalysis();
1961 }
1962}