]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/Analysis/LoopAccessAnalysis.cpp
Update compiler-rt to release_39 branch r288513. Since this contains a
[FreeBSD/FreeBSD.git] / contrib / llvm / lib / Analysis / LoopAccessAnalysis.cpp
1 //===- 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"
17 #include "llvm/Analysis/LoopPassManager.h"
18 #include "llvm/Analysis/ScalarEvolutionExpander.h"
19 #include "llvm/Analysis/TargetLibraryInfo.h"
20 #include "llvm/Analysis/ValueTracking.h"
21 #include "llvm/Analysis/VectorUtils.h"
22 #include "llvm/IR/DiagnosticInfo.h"
23 #include "llvm/IR/Dominators.h"
24 #include "llvm/IR/IRBuilder.h"
25 #include "llvm/IR/PassManager.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/raw_ostream.h"
28 using namespace llvm;
29
30 #define DEBUG_TYPE "loop-accesses"
31
32 static cl::opt<unsigned, true>
33 VectorizationFactor("force-vector-width", cl::Hidden,
34                     cl::desc("Sets the SIMD width. Zero is autoselect."),
35                     cl::location(VectorizerParams::VectorizationFactor));
36 unsigned VectorizerParams::VectorizationFactor;
37
38 static cl::opt<unsigned, true>
39 VectorizationInterleave("force-vector-interleave", cl::Hidden,
40                         cl::desc("Sets the vectorization interleave count. "
41                                  "Zero is autoselect."),
42                         cl::location(
43                             VectorizerParams::VectorizationInterleave));
44 unsigned VectorizerParams::VectorizationInterleave;
45
46 static cl::opt<unsigned, true> RuntimeMemoryCheckThreshold(
47     "runtime-memory-check-threshold", cl::Hidden,
48     cl::desc("When performing memory disambiguation checks at runtime do not "
49              "generate more than this number of comparisons (default = 8)."),
50     cl::location(VectorizerParams::RuntimeMemoryCheckThreshold), cl::init(8));
51 unsigned VectorizerParams::RuntimeMemoryCheckThreshold;
52
53 /// \brief The maximum iterations used to merge memory checks
54 static cl::opt<unsigned> MemoryCheckMergeThreshold(
55     "memory-check-merge-threshold", cl::Hidden,
56     cl::desc("Maximum number of comparisons done when trying to merge "
57              "runtime memory checks. (default = 100)"),
58     cl::init(100));
59
60 /// Maximum SIMD width.
61 const unsigned VectorizerParams::MaxVectorWidth = 64;
62
63 /// \brief We collect dependences up to this threshold.
64 static cl::opt<unsigned>
65     MaxDependences("max-dependences", cl::Hidden,
66                    cl::desc("Maximum number of dependences collected by "
67                             "loop-access analysis (default = 100)"),
68                    cl::init(100));
69
70 /// This enables versioning on the strides of symbolically striding memory
71 /// accesses in code like the following.
72 ///   for (i = 0; i < N; ++i)
73 ///     A[i * Stride1] += B[i * Stride2] ...
74 ///
75 /// Will be roughly translated to
76 ///    if (Stride1 == 1 && Stride2 == 1) {
77 ///      for (i = 0; i < N; i+=4)
78 ///       A[i:i+3] += ...
79 ///    } else
80 ///      ...
81 static cl::opt<bool> EnableMemAccessVersioning(
82     "enable-mem-access-versioning", cl::init(true), cl::Hidden,
83     cl::desc("Enable symbolic stride memory access versioning"));
84
85 /// \brief Enable store-to-load forwarding conflict detection. This option can
86 /// be disabled for correctness testing.
87 static cl::opt<bool> EnableForwardingConflictDetection(
88     "store-to-load-forwarding-conflict-detection", cl::Hidden,
89     cl::desc("Enable conflict detection in loop-access analysis"),
90     cl::init(true));
91
92 bool VectorizerParams::isInterleaveForced() {
93   return ::VectorizationInterleave.getNumOccurrences() > 0;
94 }
95
96 void LoopAccessReport::emitAnalysis(const LoopAccessReport &Message,
97                                     const Function *TheFunction,
98                                     const Loop *TheLoop,
99                                     const char *PassName) {
100   DebugLoc DL = TheLoop->getStartLoc();
101   if (const Instruction *I = Message.getInstr())
102     DL = I->getDebugLoc();
103   emitOptimizationRemarkAnalysis(TheFunction->getContext(), PassName,
104                                  *TheFunction, DL, Message.str());
105 }
106
107 Value *llvm::stripIntegerCast(Value *V) {
108   if (auto *CI = dyn_cast<CastInst>(V))
109     if (CI->getOperand(0)->getType()->isIntegerTy())
110       return CI->getOperand(0);
111   return V;
112 }
113
114 const SCEV *llvm::replaceSymbolicStrideSCEV(PredicatedScalarEvolution &PSE,
115                                             const ValueToValueMap &PtrToStride,
116                                             Value *Ptr, Value *OrigPtr) {
117   const SCEV *OrigSCEV = PSE.getSCEV(Ptr);
118
119   // If there is an entry in the map return the SCEV of the pointer with the
120   // symbolic stride replaced by one.
121   ValueToValueMap::const_iterator SI =
122       PtrToStride.find(OrigPtr ? OrigPtr : Ptr);
123   if (SI != PtrToStride.end()) {
124     Value *StrideVal = SI->second;
125
126     // Strip casts.
127     StrideVal = stripIntegerCast(StrideVal);
128
129     // Replace symbolic stride by one.
130     Value *One = ConstantInt::get(StrideVal->getType(), 1);
131     ValueToValueMap RewriteMap;
132     RewriteMap[StrideVal] = One;
133
134     ScalarEvolution *SE = PSE.getSE();
135     const auto *U = cast<SCEVUnknown>(SE->getSCEV(StrideVal));
136     const auto *CT =
137         static_cast<const SCEVConstant *>(SE->getOne(StrideVal->getType()));
138
139     PSE.addPredicate(*SE->getEqualPredicate(U, CT));
140     auto *Expr = PSE.getSCEV(Ptr);
141
142     DEBUG(dbgs() << "LAA: Replacing SCEV: " << *OrigSCEV << " by: " << *Expr
143                  << "\n");
144     return Expr;
145   }
146
147   // Otherwise, just return the SCEV of the original pointer.
148   return OrigSCEV;
149 }
150
151 /// Calculate Start and End points of memory access.
152 /// Let's assume A is the first access and B is a memory access on N-th loop
153 /// iteration. Then B is calculated as:  
154 ///   B = A + Step*N . 
155 /// Step value may be positive or negative.
156 /// N is a calculated back-edge taken count:
157 ///     N = (TripCount > 0) ? RoundDown(TripCount -1 , VF) : 0
158 /// Start and End points are calculated in the following way:
159 /// Start = UMIN(A, B) ; End = UMAX(A, B) + SizeOfElt,
160 /// where SizeOfElt is the size of single memory access in bytes.
161 ///
162 /// There is no conflict when the intervals are disjoint:
163 /// NoConflict = (P2.Start >= P1.End) || (P1.Start >= P2.End)
164 void RuntimePointerChecking::insert(Loop *Lp, Value *Ptr, bool WritePtr,
165                                     unsigned DepSetId, unsigned ASId,
166                                     const ValueToValueMap &Strides,
167                                     PredicatedScalarEvolution &PSE) {
168   // Get the stride replaced scev.
169   const SCEV *Sc = replaceSymbolicStrideSCEV(PSE, Strides, Ptr);
170   ScalarEvolution *SE = PSE.getSE();
171
172   const SCEV *ScStart;
173   const SCEV *ScEnd;
174
175   if (SE->isLoopInvariant(Sc, Lp))
176     ScStart = ScEnd = Sc;
177   else {
178     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
179     assert(AR && "Invalid addrec expression");
180     const SCEV *Ex = PSE.getBackedgeTakenCount();
181
182     ScStart = AR->getStart();
183     ScEnd = AR->evaluateAtIteration(Ex, *SE);
184     const SCEV *Step = AR->getStepRecurrence(*SE);
185
186     // For expressions with negative step, the upper bound is ScStart and the
187     // lower bound is ScEnd.
188     if (const auto *CStep = dyn_cast<SCEVConstant>(Step)) {
189       if (CStep->getValue()->isNegative())
190         std::swap(ScStart, ScEnd);
191     } else {
192       // Fallback case: the step is not constant, but we can still
193       // get the upper and lower bounds of the interval by using min/max
194       // expressions.
195       ScStart = SE->getUMinExpr(ScStart, ScEnd);
196       ScEnd = SE->getUMaxExpr(AR->getStart(), ScEnd);
197     }
198     // Add the size of the pointed element to ScEnd.
199     unsigned EltSize =
200       Ptr->getType()->getPointerElementType()->getScalarSizeInBits() / 8;
201     const SCEV *EltSizeSCEV = SE->getConstant(ScEnd->getType(), EltSize);
202     ScEnd = SE->getAddExpr(ScEnd, EltSizeSCEV);
203   }
204
205   Pointers.emplace_back(Ptr, ScStart, ScEnd, WritePtr, DepSetId, ASId, Sc);
206 }
207
208 SmallVector<RuntimePointerChecking::PointerCheck, 4>
209 RuntimePointerChecking::generateChecks() const {
210   SmallVector<PointerCheck, 4> Checks;
211
212   for (unsigned I = 0; I < CheckingGroups.size(); ++I) {
213     for (unsigned J = I + 1; J < CheckingGroups.size(); ++J) {
214       const RuntimePointerChecking::CheckingPtrGroup &CGI = CheckingGroups[I];
215       const RuntimePointerChecking::CheckingPtrGroup &CGJ = CheckingGroups[J];
216
217       if (needsChecking(CGI, CGJ))
218         Checks.push_back(std::make_pair(&CGI, &CGJ));
219     }
220   }
221   return Checks;
222 }
223
224 void RuntimePointerChecking::generateChecks(
225     MemoryDepChecker::DepCandidates &DepCands, bool UseDependencies) {
226   assert(Checks.empty() && "Checks is not empty");
227   groupChecks(DepCands, UseDependencies);
228   Checks = generateChecks();
229 }
230
231 bool RuntimePointerChecking::needsChecking(const CheckingPtrGroup &M,
232                                            const CheckingPtrGroup &N) const {
233   for (unsigned I = 0, EI = M.Members.size(); EI != I; ++I)
234     for (unsigned J = 0, EJ = N.Members.size(); EJ != J; ++J)
235       if (needsChecking(M.Members[I], N.Members[J]))
236         return true;
237   return false;
238 }
239
240 /// Compare \p I and \p J and return the minimum.
241 /// Return nullptr in case we couldn't find an answer.
242 static const SCEV *getMinFromExprs(const SCEV *I, const SCEV *J,
243                                    ScalarEvolution *SE) {
244   const SCEV *Diff = SE->getMinusSCEV(J, I);
245   const SCEVConstant *C = dyn_cast<const SCEVConstant>(Diff);
246
247   if (!C)
248     return nullptr;
249   if (C->getValue()->isNegative())
250     return J;
251   return I;
252 }
253
254 bool RuntimePointerChecking::CheckingPtrGroup::addPointer(unsigned Index) {
255   const SCEV *Start = RtCheck.Pointers[Index].Start;
256   const SCEV *End = RtCheck.Pointers[Index].End;
257
258   // Compare the starts and ends with the known minimum and maximum
259   // of this set. We need to know how we compare against the min/max
260   // of the set in order to be able to emit memchecks.
261   const SCEV *Min0 = getMinFromExprs(Start, Low, RtCheck.SE);
262   if (!Min0)
263     return false;
264
265   const SCEV *Min1 = getMinFromExprs(End, High, RtCheck.SE);
266   if (!Min1)
267     return false;
268
269   // Update the low bound  expression if we've found a new min value.
270   if (Min0 == Start)
271     Low = Start;
272
273   // Update the high bound expression if we've found a new max value.
274   if (Min1 != End)
275     High = End;
276
277   Members.push_back(Index);
278   return true;
279 }
280
281 void RuntimePointerChecking::groupChecks(
282     MemoryDepChecker::DepCandidates &DepCands, bool UseDependencies) {
283   // We build the groups from dependency candidates equivalence classes
284   // because:
285   //    - We know that pointers in the same equivalence class share
286   //      the same underlying object and therefore there is a chance
287   //      that we can compare pointers
288   //    - We wouldn't be able to merge two pointers for which we need
289   //      to emit a memcheck. The classes in DepCands are already
290   //      conveniently built such that no two pointers in the same
291   //      class need checking against each other.
292
293   // We use the following (greedy) algorithm to construct the groups
294   // For every pointer in the equivalence class:
295   //   For each existing group:
296   //   - if the difference between this pointer and the min/max bounds
297   //     of the group is a constant, then make the pointer part of the
298   //     group and update the min/max bounds of that group as required.
299
300   CheckingGroups.clear();
301
302   // If we need to check two pointers to the same underlying object
303   // with a non-constant difference, we shouldn't perform any pointer
304   // grouping with those pointers. This is because we can easily get
305   // into cases where the resulting check would return false, even when
306   // the accesses are safe.
307   //
308   // The following example shows this:
309   // for (i = 0; i < 1000; ++i)
310   //   a[5000 + i * m] = a[i] + a[i + 9000]
311   //
312   // Here grouping gives a check of (5000, 5000 + 1000 * m) against
313   // (0, 10000) which is always false. However, if m is 1, there is no
314   // dependence. Not grouping the checks for a[i] and a[i + 9000] allows
315   // us to perform an accurate check in this case.
316   //
317   // The above case requires that we have an UnknownDependence between
318   // accesses to the same underlying object. This cannot happen unless
319   // ShouldRetryWithRuntimeCheck is set, and therefore UseDependencies
320   // is also false. In this case we will use the fallback path and create
321   // separate checking groups for all pointers.
322
323   // If we don't have the dependency partitions, construct a new
324   // checking pointer group for each pointer. This is also required
325   // for correctness, because in this case we can have checking between
326   // pointers to the same underlying object.
327   if (!UseDependencies) {
328     for (unsigned I = 0; I < Pointers.size(); ++I)
329       CheckingGroups.push_back(CheckingPtrGroup(I, *this));
330     return;
331   }
332
333   unsigned TotalComparisons = 0;
334
335   DenseMap<Value *, unsigned> PositionMap;
336   for (unsigned Index = 0; Index < Pointers.size(); ++Index)
337     PositionMap[Pointers[Index].PointerValue] = Index;
338
339   // We need to keep track of what pointers we've already seen so we
340   // don't process them twice.
341   SmallSet<unsigned, 2> Seen;
342
343   // Go through all equivalence classes, get the "pointer check groups"
344   // and add them to the overall solution. We use the order in which accesses
345   // appear in 'Pointers' to enforce determinism.
346   for (unsigned I = 0; I < Pointers.size(); ++I) {
347     // We've seen this pointer before, and therefore already processed
348     // its equivalence class.
349     if (Seen.count(I))
350       continue;
351
352     MemoryDepChecker::MemAccessInfo Access(Pointers[I].PointerValue,
353                                            Pointers[I].IsWritePtr);
354
355     SmallVector<CheckingPtrGroup, 2> Groups;
356     auto LeaderI = DepCands.findValue(DepCands.getLeaderValue(Access));
357
358     // Because DepCands is constructed by visiting accesses in the order in
359     // which they appear in alias sets (which is deterministic) and the
360     // iteration order within an equivalence class member is only dependent on
361     // the order in which unions and insertions are performed on the
362     // equivalence class, the iteration order is deterministic.
363     for (auto MI = DepCands.member_begin(LeaderI), ME = DepCands.member_end();
364          MI != ME; ++MI) {
365       unsigned Pointer = PositionMap[MI->getPointer()];
366       bool Merged = false;
367       // Mark this pointer as seen.
368       Seen.insert(Pointer);
369
370       // Go through all the existing sets and see if we can find one
371       // which can include this pointer.
372       for (CheckingPtrGroup &Group : Groups) {
373         // Don't perform more than a certain amount of comparisons.
374         // This should limit the cost of grouping the pointers to something
375         // reasonable.  If we do end up hitting this threshold, the algorithm
376         // will create separate groups for all remaining pointers.
377         if (TotalComparisons > MemoryCheckMergeThreshold)
378           break;
379
380         TotalComparisons++;
381
382         if (Group.addPointer(Pointer)) {
383           Merged = true;
384           break;
385         }
386       }
387
388       if (!Merged)
389         // We couldn't add this pointer to any existing set or the threshold
390         // for the number of comparisons has been reached. Create a new group
391         // to hold the current pointer.
392         Groups.push_back(CheckingPtrGroup(Pointer, *this));
393     }
394
395     // We've computed the grouped checks for this partition.
396     // Save the results and continue with the next one.
397     std::copy(Groups.begin(), Groups.end(), std::back_inserter(CheckingGroups));
398   }
399 }
400
401 bool RuntimePointerChecking::arePointersInSamePartition(
402     const SmallVectorImpl<int> &PtrToPartition, unsigned PtrIdx1,
403     unsigned PtrIdx2) {
404   return (PtrToPartition[PtrIdx1] != -1 &&
405           PtrToPartition[PtrIdx1] == PtrToPartition[PtrIdx2]);
406 }
407
408 bool RuntimePointerChecking::needsChecking(unsigned I, unsigned J) const {
409   const PointerInfo &PointerI = Pointers[I];
410   const PointerInfo &PointerJ = Pointers[J];
411
412   // No need to check if two readonly pointers intersect.
413   if (!PointerI.IsWritePtr && !PointerJ.IsWritePtr)
414     return false;
415
416   // Only need to check pointers between two different dependency sets.
417   if (PointerI.DependencySetId == PointerJ.DependencySetId)
418     return false;
419
420   // Only need to check pointers in the same alias set.
421   if (PointerI.AliasSetId != PointerJ.AliasSetId)
422     return false;
423
424   return true;
425 }
426
427 void RuntimePointerChecking::printChecks(
428     raw_ostream &OS, const SmallVectorImpl<PointerCheck> &Checks,
429     unsigned Depth) const {
430   unsigned N = 0;
431   for (const auto &Check : Checks) {
432     const auto &First = Check.first->Members, &Second = Check.second->Members;
433
434     OS.indent(Depth) << "Check " << N++ << ":\n";
435
436     OS.indent(Depth + 2) << "Comparing group (" << Check.first << "):\n";
437     for (unsigned K = 0; K < First.size(); ++K)
438       OS.indent(Depth + 2) << *Pointers[First[K]].PointerValue << "\n";
439
440     OS.indent(Depth + 2) << "Against group (" << Check.second << "):\n";
441     for (unsigned K = 0; K < Second.size(); ++K)
442       OS.indent(Depth + 2) << *Pointers[Second[K]].PointerValue << "\n";
443   }
444 }
445
446 void RuntimePointerChecking::print(raw_ostream &OS, unsigned Depth) const {
447
448   OS.indent(Depth) << "Run-time memory checks:\n";
449   printChecks(OS, Checks, Depth);
450
451   OS.indent(Depth) << "Grouped accesses:\n";
452   for (unsigned I = 0; I < CheckingGroups.size(); ++I) {
453     const auto &CG = CheckingGroups[I];
454
455     OS.indent(Depth + 2) << "Group " << &CG << ":\n";
456     OS.indent(Depth + 4) << "(Low: " << *CG.Low << " High: " << *CG.High
457                          << ")\n";
458     for (unsigned J = 0; J < CG.Members.size(); ++J) {
459       OS.indent(Depth + 6) << "Member: " << *Pointers[CG.Members[J]].Expr
460                            << "\n";
461     }
462   }
463 }
464
465 namespace {
466 /// \brief Analyses memory accesses in a loop.
467 ///
468 /// Checks whether run time pointer checks are needed and builds sets for data
469 /// dependence checking.
470 class AccessAnalysis {
471 public:
472   /// \brief Read or write access location.
473   typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
474   typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
475
476   AccessAnalysis(const DataLayout &Dl, AliasAnalysis *AA, LoopInfo *LI,
477                  MemoryDepChecker::DepCandidates &DA,
478                  PredicatedScalarEvolution &PSE)
479       : DL(Dl), AST(*AA), LI(LI), DepCands(DA), IsRTCheckAnalysisNeeded(false),
480         PSE(PSE) {}
481
482   /// \brief Register a load  and whether it is only read from.
483   void addLoad(MemoryLocation &Loc, bool IsReadOnly) {
484     Value *Ptr = const_cast<Value*>(Loc.Ptr);
485     AST.add(Ptr, MemoryLocation::UnknownSize, Loc.AATags);
486     Accesses.insert(MemAccessInfo(Ptr, false));
487     if (IsReadOnly)
488       ReadOnlyPtr.insert(Ptr);
489   }
490
491   /// \brief Register a store.
492   void addStore(MemoryLocation &Loc) {
493     Value *Ptr = const_cast<Value*>(Loc.Ptr);
494     AST.add(Ptr, MemoryLocation::UnknownSize, Loc.AATags);
495     Accesses.insert(MemAccessInfo(Ptr, true));
496   }
497
498   /// \brief Check whether we can check the pointers at runtime for
499   /// non-intersection.
500   ///
501   /// Returns true if we need no check or if we do and we can generate them
502   /// (i.e. the pointers have computable bounds).
503   bool canCheckPtrAtRT(RuntimePointerChecking &RtCheck, ScalarEvolution *SE,
504                        Loop *TheLoop, const ValueToValueMap &Strides,
505                        bool ShouldCheckWrap = false);
506
507   /// \brief Goes over all memory accesses, checks whether a RT check is needed
508   /// and builds sets of dependent accesses.
509   void buildDependenceSets() {
510     processMemAccesses();
511   }
512
513   /// \brief Initial processing of memory accesses determined that we need to
514   /// perform dependency checking.
515   ///
516   /// Note that this can later be cleared if we retry memcheck analysis without
517   /// dependency checking (i.e. ShouldRetryWithRuntimeCheck).
518   bool isDependencyCheckNeeded() { return !CheckDeps.empty(); }
519
520   /// We decided that no dependence analysis would be used.  Reset the state.
521   void resetDepChecks(MemoryDepChecker &DepChecker) {
522     CheckDeps.clear();
523     DepChecker.clearDependences();
524   }
525
526   MemAccessInfoSet &getDependenciesToCheck() { return CheckDeps; }
527
528 private:
529   typedef SetVector<MemAccessInfo> PtrAccessSet;
530
531   /// \brief Go over all memory access and check whether runtime pointer checks
532   /// are needed and build sets of dependency check candidates.
533   void processMemAccesses();
534
535   /// Set of all accesses.
536   PtrAccessSet Accesses;
537
538   const DataLayout &DL;
539
540   /// Set of accesses that need a further dependence check.
541   MemAccessInfoSet CheckDeps;
542
543   /// Set of pointers that are read only.
544   SmallPtrSet<Value*, 16> ReadOnlyPtr;
545
546   /// An alias set tracker to partition the access set by underlying object and
547   //intrinsic property (such as TBAA metadata).
548   AliasSetTracker AST;
549
550   LoopInfo *LI;
551
552   /// Sets of potentially dependent accesses - members of one set share an
553   /// underlying pointer. The set "CheckDeps" identfies which sets really need a
554   /// dependence check.
555   MemoryDepChecker::DepCandidates &DepCands;
556
557   /// \brief Initial processing of memory accesses determined that we may need
558   /// to add memchecks.  Perform the analysis to determine the necessary checks.
559   ///
560   /// Note that, this is different from isDependencyCheckNeeded.  When we retry
561   /// memcheck analysis without dependency checking
562   /// (i.e. ShouldRetryWithRuntimeCheck), isDependencyCheckNeeded is cleared
563   /// while this remains set if we have potentially dependent accesses.
564   bool IsRTCheckAnalysisNeeded;
565
566   /// The SCEV predicate containing all the SCEV-related assumptions.
567   PredicatedScalarEvolution &PSE;
568 };
569
570 } // end anonymous namespace
571
572 /// \brief Check whether a pointer can participate in a runtime bounds check.
573 static bool hasComputableBounds(PredicatedScalarEvolution &PSE,
574                                 const ValueToValueMap &Strides, Value *Ptr,
575                                 Loop *L) {
576   const SCEV *PtrScev = replaceSymbolicStrideSCEV(PSE, Strides, Ptr);
577
578   // The bounds for loop-invariant pointer is trivial.
579   if (PSE.getSE()->isLoopInvariant(PtrScev, L))
580     return true;
581
582   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
583   if (!AR)
584     return false;
585
586   return AR->isAffine();
587 }
588
589 /// \brief Check whether a pointer address cannot wrap.
590 static bool isNoWrap(PredicatedScalarEvolution &PSE,
591                      const ValueToValueMap &Strides, Value *Ptr, Loop *L) {
592   const SCEV *PtrScev = PSE.getSCEV(Ptr);
593   if (PSE.getSE()->isLoopInvariant(PtrScev, L))
594     return true;
595
596   int64_t Stride = getPtrStride(PSE, Ptr, L, Strides);
597   return Stride == 1;
598 }
599
600 bool AccessAnalysis::canCheckPtrAtRT(RuntimePointerChecking &RtCheck,
601                                      ScalarEvolution *SE, Loop *TheLoop,
602                                      const ValueToValueMap &StridesMap,
603                                      bool ShouldCheckWrap) {
604   // Find pointers with computable bounds. We are going to use this information
605   // to place a runtime bound check.
606   bool CanDoRT = true;
607
608   bool NeedRTCheck = false;
609   if (!IsRTCheckAnalysisNeeded) return true;
610
611   bool IsDepCheckNeeded = isDependencyCheckNeeded();
612
613   // We assign a consecutive id to access from different alias sets.
614   // Accesses between different groups doesn't need to be checked.
615   unsigned ASId = 1;
616   for (auto &AS : AST) {
617     int NumReadPtrChecks = 0;
618     int NumWritePtrChecks = 0;
619
620     // We assign consecutive id to access from different dependence sets.
621     // Accesses within the same set don't need a runtime check.
622     unsigned RunningDepId = 1;
623     DenseMap<Value *, unsigned> DepSetId;
624
625     for (auto A : AS) {
626       Value *Ptr = A.getValue();
627       bool IsWrite = Accesses.count(MemAccessInfo(Ptr, true));
628       MemAccessInfo Access(Ptr, IsWrite);
629
630       if (IsWrite)
631         ++NumWritePtrChecks;
632       else
633         ++NumReadPtrChecks;
634
635       if (hasComputableBounds(PSE, StridesMap, Ptr, TheLoop) &&
636           // When we run after a failing dependency check we have to make sure
637           // we don't have wrapping pointers.
638           (!ShouldCheckWrap || isNoWrap(PSE, StridesMap, Ptr, TheLoop))) {
639         // The id of the dependence set.
640         unsigned DepId;
641
642         if (IsDepCheckNeeded) {
643           Value *Leader = DepCands.getLeaderValue(Access).getPointer();
644           unsigned &LeaderId = DepSetId[Leader];
645           if (!LeaderId)
646             LeaderId = RunningDepId++;
647           DepId = LeaderId;
648         } else
649           // Each access has its own dependence set.
650           DepId = RunningDepId++;
651
652         RtCheck.insert(TheLoop, Ptr, IsWrite, DepId, ASId, StridesMap, PSE);
653
654         DEBUG(dbgs() << "LAA: Found a runtime check ptr:" << *Ptr << '\n');
655       } else {
656         DEBUG(dbgs() << "LAA: Can't find bounds for ptr:" << *Ptr << '\n');
657         CanDoRT = false;
658       }
659     }
660
661     // If we have at least two writes or one write and a read then we need to
662     // check them.  But there is no need to checks if there is only one
663     // dependence set for this alias set.
664     //
665     // Note that this function computes CanDoRT and NeedRTCheck independently.
666     // For example CanDoRT=false, NeedRTCheck=false means that we have a pointer
667     // for which we couldn't find the bounds but we don't actually need to emit
668     // any checks so it does not matter.
669     if (!(IsDepCheckNeeded && CanDoRT && RunningDepId == 2))
670       NeedRTCheck |= (NumWritePtrChecks >= 2 || (NumReadPtrChecks >= 1 &&
671                                                  NumWritePtrChecks >= 1));
672
673     ++ASId;
674   }
675
676   // If the pointers that we would use for the bounds comparison have different
677   // address spaces, assume the values aren't directly comparable, so we can't
678   // use them for the runtime check. We also have to assume they could
679   // overlap. In the future there should be metadata for whether address spaces
680   // are disjoint.
681   unsigned NumPointers = RtCheck.Pointers.size();
682   for (unsigned i = 0; i < NumPointers; ++i) {
683     for (unsigned j = i + 1; j < NumPointers; ++j) {
684       // Only need to check pointers between two different dependency sets.
685       if (RtCheck.Pointers[i].DependencySetId ==
686           RtCheck.Pointers[j].DependencySetId)
687        continue;
688       // Only need to check pointers in the same alias set.
689       if (RtCheck.Pointers[i].AliasSetId != RtCheck.Pointers[j].AliasSetId)
690         continue;
691
692       Value *PtrI = RtCheck.Pointers[i].PointerValue;
693       Value *PtrJ = RtCheck.Pointers[j].PointerValue;
694
695       unsigned ASi = PtrI->getType()->getPointerAddressSpace();
696       unsigned ASj = PtrJ->getType()->getPointerAddressSpace();
697       if (ASi != ASj) {
698         DEBUG(dbgs() << "LAA: Runtime check would require comparison between"
699                        " different address spaces\n");
700         return false;
701       }
702     }
703   }
704
705   if (NeedRTCheck && CanDoRT)
706     RtCheck.generateChecks(DepCands, IsDepCheckNeeded);
707
708   DEBUG(dbgs() << "LAA: We need to do " << RtCheck.getNumberOfChecks()
709                << " pointer comparisons.\n");
710
711   RtCheck.Need = NeedRTCheck;
712
713   bool CanDoRTIfNeeded = !NeedRTCheck || CanDoRT;
714   if (!CanDoRTIfNeeded)
715     RtCheck.reset();
716   return CanDoRTIfNeeded;
717 }
718
719 void AccessAnalysis::processMemAccesses() {
720   // We process the set twice: first we process read-write pointers, last we
721   // process read-only pointers. This allows us to skip dependence tests for
722   // read-only pointers.
723
724   DEBUG(dbgs() << "LAA: Processing memory accesses...\n");
725   DEBUG(dbgs() << "  AST: "; AST.dump());
726   DEBUG(dbgs() << "LAA:   Accesses(" << Accesses.size() << "):\n");
727   DEBUG({
728     for (auto A : Accesses)
729       dbgs() << "\t" << *A.getPointer() << " (" <<
730                 (A.getInt() ? "write" : (ReadOnlyPtr.count(A.getPointer()) ?
731                                          "read-only" : "read")) << ")\n";
732   });
733
734   // The AliasSetTracker has nicely partitioned our pointers by metadata
735   // compatibility and potential for underlying-object overlap. As a result, we
736   // only need to check for potential pointer dependencies within each alias
737   // set.
738   for (auto &AS : AST) {
739     // Note that both the alias-set tracker and the alias sets themselves used
740     // linked lists internally and so the iteration order here is deterministic
741     // (matching the original instruction order within each set).
742
743     bool SetHasWrite = false;
744
745     // Map of pointers to last access encountered.
746     typedef DenseMap<Value*, MemAccessInfo> UnderlyingObjToAccessMap;
747     UnderlyingObjToAccessMap ObjToLastAccess;
748
749     // Set of access to check after all writes have been processed.
750     PtrAccessSet DeferredAccesses;
751
752     // Iterate over each alias set twice, once to process read/write pointers,
753     // and then to process read-only pointers.
754     for (int SetIteration = 0; SetIteration < 2; ++SetIteration) {
755       bool UseDeferred = SetIteration > 0;
756       PtrAccessSet &S = UseDeferred ? DeferredAccesses : Accesses;
757
758       for (auto AV : AS) {
759         Value *Ptr = AV.getValue();
760
761         // For a single memory access in AliasSetTracker, Accesses may contain
762         // both read and write, and they both need to be handled for CheckDeps.
763         for (auto AC : S) {
764           if (AC.getPointer() != Ptr)
765             continue;
766
767           bool IsWrite = AC.getInt();
768
769           // If we're using the deferred access set, then it contains only
770           // reads.
771           bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite;
772           if (UseDeferred && !IsReadOnlyPtr)
773             continue;
774           // Otherwise, the pointer must be in the PtrAccessSet, either as a
775           // read or a write.
776           assert(((IsReadOnlyPtr && UseDeferred) || IsWrite ||
777                   S.count(MemAccessInfo(Ptr, false))) &&
778                  "Alias-set pointer not in the access set?");
779
780           MemAccessInfo Access(Ptr, IsWrite);
781           DepCands.insert(Access);
782
783           // Memorize read-only pointers for later processing and skip them in
784           // the first round (they need to be checked after we have seen all
785           // write pointers). Note: we also mark pointer that are not
786           // consecutive as "read-only" pointers (so that we check
787           // "a[b[i]] +="). Hence, we need the second check for "!IsWrite".
788           if (!UseDeferred && IsReadOnlyPtr) {
789             DeferredAccesses.insert(Access);
790             continue;
791           }
792
793           // If this is a write - check other reads and writes for conflicts. If
794           // this is a read only check other writes for conflicts (but only if
795           // there is no other write to the ptr - this is an optimization to
796           // catch "a[i] = a[i] + " without having to do a dependence check).
797           if ((IsWrite || IsReadOnlyPtr) && SetHasWrite) {
798             CheckDeps.insert(Access);
799             IsRTCheckAnalysisNeeded = true;
800           }
801
802           if (IsWrite)
803             SetHasWrite = true;
804
805           // Create sets of pointers connected by a shared alias set and
806           // underlying object.
807           typedef SmallVector<Value *, 16> ValueVector;
808           ValueVector TempObjects;
809
810           GetUnderlyingObjects(Ptr, TempObjects, DL, LI);
811           DEBUG(dbgs() << "Underlying objects for pointer " << *Ptr << "\n");
812           for (Value *UnderlyingObj : TempObjects) {
813             // nullptr never alias, don't join sets for pointer that have "null"
814             // in their UnderlyingObjects list.
815             if (isa<ConstantPointerNull>(UnderlyingObj))
816               continue;
817
818             UnderlyingObjToAccessMap::iterator Prev =
819                 ObjToLastAccess.find(UnderlyingObj);
820             if (Prev != ObjToLastAccess.end())
821               DepCands.unionSets(Access, Prev->second);
822
823             ObjToLastAccess[UnderlyingObj] = Access;
824             DEBUG(dbgs() << "  " << *UnderlyingObj << "\n");
825           }
826         }
827       }
828     }
829   }
830 }
831
832 static bool isInBoundsGep(Value *Ptr) {
833   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
834     return GEP->isInBounds();
835   return false;
836 }
837
838 /// \brief Return true if an AddRec pointer \p Ptr is unsigned non-wrapping,
839 /// i.e. monotonically increasing/decreasing.
840 static bool isNoWrapAddRec(Value *Ptr, const SCEVAddRecExpr *AR,
841                            PredicatedScalarEvolution &PSE, const Loop *L) {
842   // FIXME: This should probably only return true for NUW.
843   if (AR->getNoWrapFlags(SCEV::NoWrapMask))
844     return true;
845
846   // Scalar evolution does not propagate the non-wrapping flags to values that
847   // are derived from a non-wrapping induction variable because non-wrapping
848   // could be flow-sensitive.
849   //
850   // Look through the potentially overflowing instruction to try to prove
851   // non-wrapping for the *specific* value of Ptr.
852
853   // The arithmetic implied by an inbounds GEP can't overflow.
854   auto *GEP = dyn_cast<GetElementPtrInst>(Ptr);
855   if (!GEP || !GEP->isInBounds())
856     return false;
857
858   // Make sure there is only one non-const index and analyze that.
859   Value *NonConstIndex = nullptr;
860   for (Value *Index : make_range(GEP->idx_begin(), GEP->idx_end()))
861     if (!isa<ConstantInt>(Index)) {
862       if (NonConstIndex)
863         return false;
864       NonConstIndex = Index;
865     }
866   if (!NonConstIndex)
867     // The recurrence is on the pointer, ignore for now.
868     return false;
869
870   // The index in GEP is signed.  It is non-wrapping if it's derived from a NSW
871   // AddRec using a NSW operation.
872   if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(NonConstIndex))
873     if (OBO->hasNoSignedWrap() &&
874         // Assume constant for other the operand so that the AddRec can be
875         // easily found.
876         isa<ConstantInt>(OBO->getOperand(1))) {
877       auto *OpScev = PSE.getSCEV(OBO->getOperand(0));
878
879       if (auto *OpAR = dyn_cast<SCEVAddRecExpr>(OpScev))
880         return OpAR->getLoop() == L && OpAR->getNoWrapFlags(SCEV::FlagNSW);
881     }
882
883   return false;
884 }
885
886 /// \brief Check whether the access through \p Ptr has a constant stride.
887 int64_t llvm::getPtrStride(PredicatedScalarEvolution &PSE, Value *Ptr,
888                            const Loop *Lp, const ValueToValueMap &StridesMap,
889                            bool Assume) {
890   Type *Ty = Ptr->getType();
891   assert(Ty->isPointerTy() && "Unexpected non-ptr");
892
893   // Make sure that the pointer does not point to aggregate types.
894   auto *PtrTy = cast<PointerType>(Ty);
895   if (PtrTy->getElementType()->isAggregateType()) {
896     DEBUG(dbgs() << "LAA: Bad stride - Not a pointer to a scalar type" << *Ptr
897                  << "\n");
898     return 0;
899   }
900
901   const SCEV *PtrScev = replaceSymbolicStrideSCEV(PSE, StridesMap, Ptr);
902
903   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
904   if (Assume && !AR)
905     AR = PSE.getAsAddRec(Ptr);
906
907   if (!AR) {
908     DEBUG(dbgs() << "LAA: Bad stride - Not an AddRecExpr pointer " << *Ptr
909                  << " SCEV: " << *PtrScev << "\n");
910     return 0;
911   }
912
913   // The accesss function must stride over the innermost loop.
914   if (Lp != AR->getLoop()) {
915     DEBUG(dbgs() << "LAA: Bad stride - Not striding over innermost loop " <<
916           *Ptr << " SCEV: " << *AR << "\n");
917     return 0;
918   }
919
920   // The address calculation must not wrap. Otherwise, a dependence could be
921   // inverted.
922   // An inbounds getelementptr that is a AddRec with a unit stride
923   // cannot wrap per definition. The unit stride requirement is checked later.
924   // An getelementptr without an inbounds attribute and unit stride would have
925   // to access the pointer value "0" which is undefined behavior in address
926   // space 0, therefore we can also vectorize this case.
927   bool IsInBoundsGEP = isInBoundsGep(Ptr);
928   bool IsNoWrapAddRec =
929       PSE.hasNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW) ||
930       isNoWrapAddRec(Ptr, AR, PSE, Lp);
931   bool IsInAddressSpaceZero = PtrTy->getAddressSpace() == 0;
932   if (!IsNoWrapAddRec && !IsInBoundsGEP && !IsInAddressSpaceZero) {
933     if (Assume) {
934       PSE.setNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW);
935       IsNoWrapAddRec = true;
936       DEBUG(dbgs() << "LAA: Pointer may wrap in the address space:\n"
937                    << "LAA:   Pointer: " << *Ptr << "\n"
938                    << "LAA:   SCEV: " << *AR << "\n"
939                    << "LAA:   Added an overflow assumption\n");
940     } else {
941       DEBUG(dbgs() << "LAA: Bad stride - Pointer may wrap in the address space "
942                    << *Ptr << " SCEV: " << *AR << "\n");
943       return 0;
944     }
945   }
946
947   // Check the step is constant.
948   const SCEV *Step = AR->getStepRecurrence(*PSE.getSE());
949
950   // Calculate the pointer stride and check if it is constant.
951   const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
952   if (!C) {
953     DEBUG(dbgs() << "LAA: Bad stride - Not a constant strided " << *Ptr <<
954           " SCEV: " << *AR << "\n");
955     return 0;
956   }
957
958   auto &DL = Lp->getHeader()->getModule()->getDataLayout();
959   int64_t Size = DL.getTypeAllocSize(PtrTy->getElementType());
960   const APInt &APStepVal = C->getAPInt();
961
962   // Huge step value - give up.
963   if (APStepVal.getBitWidth() > 64)
964     return 0;
965
966   int64_t StepVal = APStepVal.getSExtValue();
967
968   // Strided access.
969   int64_t Stride = StepVal / Size;
970   int64_t Rem = StepVal % Size;
971   if (Rem)
972     return 0;
973
974   // If the SCEV could wrap but we have an inbounds gep with a unit stride we
975   // know we can't "wrap around the address space". In case of address space
976   // zero we know that this won't happen without triggering undefined behavior.
977   if (!IsNoWrapAddRec && (IsInBoundsGEP || IsInAddressSpaceZero) &&
978       Stride != 1 && Stride != -1) {
979     if (Assume) {
980       // We can avoid this case by adding a run-time check.
981       DEBUG(dbgs() << "LAA: Non unit strided pointer which is not either "
982                    << "inbouds or in address space 0 may wrap:\n"
983                    << "LAA:   Pointer: " << *Ptr << "\n"
984                    << "LAA:   SCEV: " << *AR << "\n"
985                    << "LAA:   Added an overflow assumption\n");
986       PSE.setNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW);
987     } else
988       return 0;
989   }
990
991   return Stride;
992 }
993
994 /// Take the pointer operand from the Load/Store instruction.
995 /// Returns NULL if this is not a valid Load/Store instruction.
996 static Value *getPointerOperand(Value *I) {
997   if (auto *LI = dyn_cast<LoadInst>(I))
998     return LI->getPointerOperand();
999   if (auto *SI = dyn_cast<StoreInst>(I))
1000     return SI->getPointerOperand();
1001   return nullptr;
1002 }
1003
1004 /// Take the address space operand from the Load/Store instruction.
1005 /// Returns -1 if this is not a valid Load/Store instruction.
1006 static unsigned getAddressSpaceOperand(Value *I) {
1007   if (LoadInst *L = dyn_cast<LoadInst>(I))
1008     return L->getPointerAddressSpace();
1009   if (StoreInst *S = dyn_cast<StoreInst>(I))
1010     return S->getPointerAddressSpace();
1011   return -1;
1012 }
1013
1014 /// Returns true if the memory operations \p A and \p B are consecutive.
1015 bool llvm::isConsecutiveAccess(Value *A, Value *B, const DataLayout &DL,
1016                                ScalarEvolution &SE, bool CheckType) {
1017   Value *PtrA = getPointerOperand(A);
1018   Value *PtrB = getPointerOperand(B);
1019   unsigned ASA = getAddressSpaceOperand(A);
1020   unsigned ASB = getAddressSpaceOperand(B);
1021
1022   // Check that the address spaces match and that the pointers are valid.
1023   if (!PtrA || !PtrB || (ASA != ASB))
1024     return false;
1025
1026   // Make sure that A and B are different pointers.
1027   if (PtrA == PtrB)
1028     return false;
1029
1030   // Make sure that A and B have the same type if required.
1031   if(CheckType && PtrA->getType() != PtrB->getType())
1032       return false;
1033
1034   unsigned PtrBitWidth = DL.getPointerSizeInBits(ASA);
1035   Type *Ty = cast<PointerType>(PtrA->getType())->getElementType();
1036   APInt Size(PtrBitWidth, DL.getTypeStoreSize(Ty));
1037
1038   APInt OffsetA(PtrBitWidth, 0), OffsetB(PtrBitWidth, 0);
1039   PtrA = PtrA->stripAndAccumulateInBoundsConstantOffsets(DL, OffsetA);
1040   PtrB = PtrB->stripAndAccumulateInBoundsConstantOffsets(DL, OffsetB);
1041
1042   //  OffsetDelta = OffsetB - OffsetA;
1043   const SCEV *OffsetSCEVA = SE.getConstant(OffsetA);
1044   const SCEV *OffsetSCEVB = SE.getConstant(OffsetB);
1045   const SCEV *OffsetDeltaSCEV = SE.getMinusSCEV(OffsetSCEVB, OffsetSCEVA);
1046   const SCEVConstant *OffsetDeltaC = dyn_cast<SCEVConstant>(OffsetDeltaSCEV);
1047   const APInt &OffsetDelta = OffsetDeltaC->getAPInt();
1048   // Check if they are based on the same pointer. That makes the offsets
1049   // sufficient.
1050   if (PtrA == PtrB)
1051     return OffsetDelta == Size;
1052
1053   // Compute the necessary base pointer delta to have the necessary final delta
1054   // equal to the size.
1055   // BaseDelta = Size - OffsetDelta;
1056   const SCEV *SizeSCEV = SE.getConstant(Size);
1057   const SCEV *BaseDelta = SE.getMinusSCEV(SizeSCEV, OffsetDeltaSCEV);
1058
1059   // Otherwise compute the distance with SCEV between the base pointers.
1060   const SCEV *PtrSCEVA = SE.getSCEV(PtrA);
1061   const SCEV *PtrSCEVB = SE.getSCEV(PtrB);
1062   const SCEV *X = SE.getAddExpr(PtrSCEVA, BaseDelta);
1063   return X == PtrSCEVB;
1064 }
1065
1066 bool MemoryDepChecker::Dependence::isSafeForVectorization(DepType Type) {
1067   switch (Type) {
1068   case NoDep:
1069   case Forward:
1070   case BackwardVectorizable:
1071     return true;
1072
1073   case Unknown:
1074   case ForwardButPreventsForwarding:
1075   case Backward:
1076   case BackwardVectorizableButPreventsForwarding:
1077     return false;
1078   }
1079   llvm_unreachable("unexpected DepType!");
1080 }
1081
1082 bool MemoryDepChecker::Dependence::isBackward() const {
1083   switch (Type) {
1084   case NoDep:
1085   case Forward:
1086   case ForwardButPreventsForwarding:
1087   case Unknown:
1088     return false;
1089
1090   case BackwardVectorizable:
1091   case Backward:
1092   case BackwardVectorizableButPreventsForwarding:
1093     return true;
1094   }
1095   llvm_unreachable("unexpected DepType!");
1096 }
1097
1098 bool MemoryDepChecker::Dependence::isPossiblyBackward() const {
1099   return isBackward() || Type == Unknown;
1100 }
1101
1102 bool MemoryDepChecker::Dependence::isForward() const {
1103   switch (Type) {
1104   case Forward:
1105   case ForwardButPreventsForwarding:
1106     return true;
1107
1108   case NoDep:
1109   case Unknown:
1110   case BackwardVectorizable:
1111   case Backward:
1112   case BackwardVectorizableButPreventsForwarding:
1113     return false;
1114   }
1115   llvm_unreachable("unexpected DepType!");
1116 }
1117
1118 bool MemoryDepChecker::couldPreventStoreLoadForward(uint64_t Distance,
1119                                                     uint64_t TypeByteSize) {
1120   // If loads occur at a distance that is not a multiple of a feasible vector
1121   // factor store-load forwarding does not take place.
1122   // Positive dependences might cause troubles because vectorizing them might
1123   // prevent store-load forwarding making vectorized code run a lot slower.
1124   //   a[i] = a[i-3] ^ a[i-8];
1125   //   The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
1126   //   hence on your typical architecture store-load forwarding does not take
1127   //   place. Vectorizing in such cases does not make sense.
1128   // Store-load forwarding distance.
1129
1130   // After this many iterations store-to-load forwarding conflicts should not
1131   // cause any slowdowns.
1132   const uint64_t NumItersForStoreLoadThroughMemory = 8 * TypeByteSize;
1133   // Maximum vector factor.
1134   uint64_t MaxVFWithoutSLForwardIssues = std::min(
1135       VectorizerParams::MaxVectorWidth * TypeByteSize, MaxSafeDepDistBytes);
1136
1137   // Compute the smallest VF at which the store and load would be misaligned.
1138   for (uint64_t VF = 2 * TypeByteSize; VF <= MaxVFWithoutSLForwardIssues;
1139        VF *= 2) {
1140     // If the number of vector iteration between the store and the load are
1141     // small we could incur conflicts.
1142     if (Distance % VF && Distance / VF < NumItersForStoreLoadThroughMemory) {
1143       MaxVFWithoutSLForwardIssues = (VF >>= 1);
1144       break;
1145     }
1146   }
1147
1148   if (MaxVFWithoutSLForwardIssues < 2 * TypeByteSize) {
1149     DEBUG(dbgs() << "LAA: Distance " << Distance
1150                  << " that could cause a store-load forwarding conflict\n");
1151     return true;
1152   }
1153
1154   if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes &&
1155       MaxVFWithoutSLForwardIssues !=
1156           VectorizerParams::MaxVectorWidth * TypeByteSize)
1157     MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues;
1158   return false;
1159 }
1160
1161 /// \brief Check the dependence for two accesses with the same stride \p Stride.
1162 /// \p Distance is the positive distance and \p TypeByteSize is type size in
1163 /// bytes.
1164 ///
1165 /// \returns true if they are independent.
1166 static bool areStridedAccessesIndependent(uint64_t Distance, uint64_t Stride,
1167                                           uint64_t TypeByteSize) {
1168   assert(Stride > 1 && "The stride must be greater than 1");
1169   assert(TypeByteSize > 0 && "The type size in byte must be non-zero");
1170   assert(Distance > 0 && "The distance must be non-zero");
1171
1172   // Skip if the distance is not multiple of type byte size.
1173   if (Distance % TypeByteSize)
1174     return false;
1175
1176   uint64_t ScaledDist = Distance / TypeByteSize;
1177
1178   // No dependence if the scaled distance is not multiple of the stride.
1179   // E.g.
1180   //      for (i = 0; i < 1024 ; i += 4)
1181   //        A[i+2] = A[i] + 1;
1182   //
1183   // Two accesses in memory (scaled distance is 2, stride is 4):
1184   //     | A[0] |      |      |      | A[4] |      |      |      |
1185   //     |      |      | A[2] |      |      |      | A[6] |      |
1186   //
1187   // E.g.
1188   //      for (i = 0; i < 1024 ; i += 3)
1189   //        A[i+4] = A[i] + 1;
1190   //
1191   // Two accesses in memory (scaled distance is 4, stride is 3):
1192   //     | A[0] |      |      | A[3] |      |      | A[6] |      |      |
1193   //     |      |      |      |      | A[4] |      |      | A[7] |      |
1194   return ScaledDist % Stride;
1195 }
1196
1197 MemoryDepChecker::Dependence::DepType
1198 MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
1199                               const MemAccessInfo &B, unsigned BIdx,
1200                               const ValueToValueMap &Strides) {
1201   assert (AIdx < BIdx && "Must pass arguments in program order");
1202
1203   Value *APtr = A.getPointer();
1204   Value *BPtr = B.getPointer();
1205   bool AIsWrite = A.getInt();
1206   bool BIsWrite = B.getInt();
1207
1208   // Two reads are independent.
1209   if (!AIsWrite && !BIsWrite)
1210     return Dependence::NoDep;
1211
1212   // We cannot check pointers in different address spaces.
1213   if (APtr->getType()->getPointerAddressSpace() !=
1214       BPtr->getType()->getPointerAddressSpace())
1215     return Dependence::Unknown;
1216
1217   int64_t StrideAPtr = getPtrStride(PSE, APtr, InnermostLoop, Strides, true);
1218   int64_t StrideBPtr = getPtrStride(PSE, BPtr, InnermostLoop, Strides, true);
1219
1220   const SCEV *Src = PSE.getSCEV(APtr);
1221   const SCEV *Sink = PSE.getSCEV(BPtr);
1222
1223   // If the induction step is negative we have to invert source and sink of the
1224   // dependence.
1225   if (StrideAPtr < 0) {
1226     std::swap(APtr, BPtr);
1227     std::swap(Src, Sink);
1228     std::swap(AIsWrite, BIsWrite);
1229     std::swap(AIdx, BIdx);
1230     std::swap(StrideAPtr, StrideBPtr);
1231   }
1232
1233   const SCEV *Dist = PSE.getSE()->getMinusSCEV(Sink, Src);
1234
1235   DEBUG(dbgs() << "LAA: Src Scev: " << *Src << "Sink Scev: " << *Sink
1236                << "(Induction step: " << StrideAPtr << ")\n");
1237   DEBUG(dbgs() << "LAA: Distance for " << *InstMap[AIdx] << " to "
1238                << *InstMap[BIdx] << ": " << *Dist << "\n");
1239
1240   // Need accesses with constant stride. We don't want to vectorize
1241   // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in
1242   // the address space.
1243   if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){
1244     DEBUG(dbgs() << "Pointer access with non-constant stride\n");
1245     return Dependence::Unknown;
1246   }
1247
1248   const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist);
1249   if (!C) {
1250     DEBUG(dbgs() << "LAA: Dependence because of non-constant distance\n");
1251     ShouldRetryWithRuntimeCheck = true;
1252     return Dependence::Unknown;
1253   }
1254
1255   Type *ATy = APtr->getType()->getPointerElementType();
1256   Type *BTy = BPtr->getType()->getPointerElementType();
1257   auto &DL = InnermostLoop->getHeader()->getModule()->getDataLayout();
1258   uint64_t TypeByteSize = DL.getTypeAllocSize(ATy);
1259
1260   const APInt &Val = C->getAPInt();
1261   int64_t Distance = Val.getSExtValue();
1262   uint64_t Stride = std::abs(StrideAPtr);
1263
1264   // Attempt to prove strided accesses independent.
1265   if (std::abs(Distance) > 0 && Stride > 1 && ATy == BTy &&
1266       areStridedAccessesIndependent(std::abs(Distance), Stride, TypeByteSize)) {
1267     DEBUG(dbgs() << "LAA: Strided accesses are independent\n");
1268     return Dependence::NoDep;
1269   }
1270
1271   // Negative distances are not plausible dependencies.
1272   if (Val.isNegative()) {
1273     bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
1274     if (IsTrueDataDependence && EnableForwardingConflictDetection &&
1275         (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) ||
1276          ATy != BTy)) {
1277       DEBUG(dbgs() << "LAA: Forward but may prevent st->ld forwarding\n");
1278       return Dependence::ForwardButPreventsForwarding;
1279     }
1280
1281     DEBUG(dbgs() << "LAA: Dependence is negative\n");
1282     return Dependence::Forward;
1283   }
1284
1285   // Write to the same location with the same size.
1286   // Could be improved to assert type sizes are the same (i32 == float, etc).
1287   if (Val == 0) {
1288     if (ATy == BTy)
1289       return Dependence::Forward;
1290     DEBUG(dbgs() << "LAA: Zero dependence difference but different types\n");
1291     return Dependence::Unknown;
1292   }
1293
1294   assert(Val.isStrictlyPositive() && "Expect a positive value");
1295
1296   if (ATy != BTy) {
1297     DEBUG(dbgs() <<
1298           "LAA: ReadWrite-Write positive dependency with different types\n");
1299     return Dependence::Unknown;
1300   }
1301
1302   // Bail out early if passed-in parameters make vectorization not feasible.
1303   unsigned ForcedFactor = (VectorizerParams::VectorizationFactor ?
1304                            VectorizerParams::VectorizationFactor : 1);
1305   unsigned ForcedUnroll = (VectorizerParams::VectorizationInterleave ?
1306                            VectorizerParams::VectorizationInterleave : 1);
1307   // The minimum number of iterations for a vectorized/unrolled version.
1308   unsigned MinNumIter = std::max(ForcedFactor * ForcedUnroll, 2U);
1309
1310   // It's not vectorizable if the distance is smaller than the minimum distance
1311   // needed for a vectroized/unrolled version. Vectorizing one iteration in
1312   // front needs TypeByteSize * Stride. Vectorizing the last iteration needs
1313   // TypeByteSize (No need to plus the last gap distance).
1314   //
1315   // E.g. Assume one char is 1 byte in memory and one int is 4 bytes.
1316   //      foo(int *A) {
1317   //        int *B = (int *)((char *)A + 14);
1318   //        for (i = 0 ; i < 1024 ; i += 2)
1319   //          B[i] = A[i] + 1;
1320   //      }
1321   //
1322   // Two accesses in memory (stride is 2):
1323   //     | A[0] |      | A[2] |      | A[4] |      | A[6] |      |
1324   //                              | B[0] |      | B[2] |      | B[4] |
1325   //
1326   // Distance needs for vectorizing iterations except the last iteration:
1327   // 4 * 2 * (MinNumIter - 1). Distance needs for the last iteration: 4.
1328   // So the minimum distance needed is: 4 * 2 * (MinNumIter - 1) + 4.
1329   //
1330   // If MinNumIter is 2, it is vectorizable as the minimum distance needed is
1331   // 12, which is less than distance.
1332   //
1333   // If MinNumIter is 4 (Say if a user forces the vectorization factor to be 4),
1334   // the minimum distance needed is 28, which is greater than distance. It is
1335   // not safe to do vectorization.
1336   uint64_t MinDistanceNeeded =
1337       TypeByteSize * Stride * (MinNumIter - 1) + TypeByteSize;
1338   if (MinDistanceNeeded > static_cast<uint64_t>(Distance)) {
1339     DEBUG(dbgs() << "LAA: Failure because of positive distance " << Distance
1340                  << '\n');
1341     return Dependence::Backward;
1342   }
1343
1344   // Unsafe if the minimum distance needed is greater than max safe distance.
1345   if (MinDistanceNeeded > MaxSafeDepDistBytes) {
1346     DEBUG(dbgs() << "LAA: Failure because it needs at least "
1347                  << MinDistanceNeeded << " size in bytes");
1348     return Dependence::Backward;
1349   }
1350
1351   // Positive distance bigger than max vectorization factor.
1352   // FIXME: Should use max factor instead of max distance in bytes, which could
1353   // not handle different types.
1354   // E.g. Assume one char is 1 byte in memory and one int is 4 bytes.
1355   //      void foo (int *A, char *B) {
1356   //        for (unsigned i = 0; i < 1024; i++) {
1357   //          A[i+2] = A[i] + 1;
1358   //          B[i+2] = B[i] + 1;
1359   //        }
1360   //      }
1361   //
1362   // This case is currently unsafe according to the max safe distance. If we
1363   // analyze the two accesses on array B, the max safe dependence distance
1364   // is 2. Then we analyze the accesses on array A, the minimum distance needed
1365   // is 8, which is less than 2 and forbidden vectorization, But actually
1366   // both A and B could be vectorized by 2 iterations.
1367   MaxSafeDepDistBytes =
1368       std::min(static_cast<uint64_t>(Distance), MaxSafeDepDistBytes);
1369
1370   bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
1371   if (IsTrueDataDependence && EnableForwardingConflictDetection &&
1372       couldPreventStoreLoadForward(Distance, TypeByteSize))
1373     return Dependence::BackwardVectorizableButPreventsForwarding;
1374
1375   DEBUG(dbgs() << "LAA: Positive distance " << Val.getSExtValue()
1376                << " with max VF = "
1377                << MaxSafeDepDistBytes / (TypeByteSize * Stride) << '\n');
1378
1379   return Dependence::BackwardVectorizable;
1380 }
1381
1382 bool MemoryDepChecker::areDepsSafe(DepCandidates &AccessSets,
1383                                    MemAccessInfoSet &CheckDeps,
1384                                    const ValueToValueMap &Strides) {
1385
1386   MaxSafeDepDistBytes = -1;
1387   while (!CheckDeps.empty()) {
1388     MemAccessInfo CurAccess = *CheckDeps.begin();
1389
1390     // Get the relevant memory access set.
1391     EquivalenceClasses<MemAccessInfo>::iterator I =
1392       AccessSets.findValue(AccessSets.getLeaderValue(CurAccess));
1393
1394     // Check accesses within this set.
1395     EquivalenceClasses<MemAccessInfo>::member_iterator AI =
1396         AccessSets.member_begin(I);
1397     EquivalenceClasses<MemAccessInfo>::member_iterator AE =
1398         AccessSets.member_end();
1399
1400     // Check every access pair.
1401     while (AI != AE) {
1402       CheckDeps.erase(*AI);
1403       EquivalenceClasses<MemAccessInfo>::member_iterator OI = std::next(AI);
1404       while (OI != AE) {
1405         // Check every accessing instruction pair in program order.
1406         for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(),
1407              I1E = Accesses[*AI].end(); I1 != I1E; ++I1)
1408           for (std::vector<unsigned>::iterator I2 = Accesses[*OI].begin(),
1409                I2E = Accesses[*OI].end(); I2 != I2E; ++I2) {
1410             auto A = std::make_pair(&*AI, *I1);
1411             auto B = std::make_pair(&*OI, *I2);
1412
1413             assert(*I1 != *I2);
1414             if (*I1 > *I2)
1415               std::swap(A, B);
1416
1417             Dependence::DepType Type =
1418                 isDependent(*A.first, A.second, *B.first, B.second, Strides);
1419             SafeForVectorization &= Dependence::isSafeForVectorization(Type);
1420
1421             // Gather dependences unless we accumulated MaxDependences
1422             // dependences.  In that case return as soon as we find the first
1423             // unsafe dependence.  This puts a limit on this quadratic
1424             // algorithm.
1425             if (RecordDependences) {
1426               if (Type != Dependence::NoDep)
1427                 Dependences.push_back(Dependence(A.second, B.second, Type));
1428
1429               if (Dependences.size() >= MaxDependences) {
1430                 RecordDependences = false;
1431                 Dependences.clear();
1432                 DEBUG(dbgs() << "Too many dependences, stopped recording\n");
1433               }
1434             }
1435             if (!RecordDependences && !SafeForVectorization)
1436               return false;
1437           }
1438         ++OI;
1439       }
1440       AI++;
1441     }
1442   }
1443
1444   DEBUG(dbgs() << "Total Dependences: " << Dependences.size() << "\n");
1445   return SafeForVectorization;
1446 }
1447
1448 SmallVector<Instruction *, 4>
1449 MemoryDepChecker::getInstructionsForAccess(Value *Ptr, bool isWrite) const {
1450   MemAccessInfo Access(Ptr, isWrite);
1451   auto &IndexVector = Accesses.find(Access)->second;
1452
1453   SmallVector<Instruction *, 4> Insts;
1454   std::transform(IndexVector.begin(), IndexVector.end(),
1455                  std::back_inserter(Insts),
1456                  [&](unsigned Idx) { return this->InstMap[Idx]; });
1457   return Insts;
1458 }
1459
1460 const char *MemoryDepChecker::Dependence::DepName[] = {
1461     "NoDep", "Unknown", "Forward", "ForwardButPreventsForwarding", "Backward",
1462     "BackwardVectorizable", "BackwardVectorizableButPreventsForwarding"};
1463
1464 void MemoryDepChecker::Dependence::print(
1465     raw_ostream &OS, unsigned Depth,
1466     const SmallVectorImpl<Instruction *> &Instrs) const {
1467   OS.indent(Depth) << DepName[Type] << ":\n";
1468   OS.indent(Depth + 2) << *Instrs[Source] << " -> \n";
1469   OS.indent(Depth + 2) << *Instrs[Destination] << "\n";
1470 }
1471
1472 bool LoopAccessInfo::canAnalyzeLoop() {
1473   // We need to have a loop header.
1474   DEBUG(dbgs() << "LAA: Found a loop in "
1475                << TheLoop->getHeader()->getParent()->getName() << ": "
1476                << TheLoop->getHeader()->getName() << '\n');
1477
1478   // We can only analyze innermost loops.
1479   if (!TheLoop->empty()) {
1480     DEBUG(dbgs() << "LAA: loop is not the innermost loop\n");
1481     emitAnalysis(LoopAccessReport() << "loop is not the innermost loop");
1482     return false;
1483   }
1484
1485   // We must have a single backedge.
1486   if (TheLoop->getNumBackEdges() != 1) {
1487     DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n");
1488     emitAnalysis(
1489         LoopAccessReport() <<
1490         "loop control flow is not understood by analyzer");
1491     return false;
1492   }
1493
1494   // We must have a single exiting block.
1495   if (!TheLoop->getExitingBlock()) {
1496     DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n");
1497     emitAnalysis(
1498         LoopAccessReport() <<
1499         "loop control flow is not understood by analyzer");
1500     return false;
1501   }
1502
1503   // We only handle bottom-tested loops, i.e. loop in which the condition is
1504   // checked at the end of each iteration. With that we can assume that all
1505   // instructions in the loop are executed the same number of times.
1506   if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
1507     DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n");
1508     emitAnalysis(
1509         LoopAccessReport() <<
1510         "loop control flow is not understood by analyzer");
1511     return false;
1512   }
1513
1514   // ScalarEvolution needs to be able to find the exit count.
1515   const SCEV *ExitCount = PSE->getBackedgeTakenCount();
1516   if (ExitCount == PSE->getSE()->getCouldNotCompute()) {
1517     emitAnalysis(LoopAccessReport()
1518                  << "could not determine number of loop iterations");
1519     DEBUG(dbgs() << "LAA: SCEV could not compute the loop exit count.\n");
1520     return false;
1521   }
1522
1523   return true;
1524 }
1525
1526 void LoopAccessInfo::analyzeLoop(AliasAnalysis *AA, LoopInfo *LI,
1527                                  const TargetLibraryInfo *TLI,
1528                                  DominatorTree *DT) {
1529   typedef SmallPtrSet<Value*, 16> ValueSet;
1530
1531   // Holds the Load and Store instructions.
1532   SmallVector<LoadInst *, 16> Loads;
1533   SmallVector<StoreInst *, 16> Stores;
1534
1535   // Holds all the different accesses in the loop.
1536   unsigned NumReads = 0;
1537   unsigned NumReadWrites = 0;
1538
1539   PtrRtChecking->Pointers.clear();
1540   PtrRtChecking->Need = false;
1541
1542   const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
1543
1544   // For each block.
1545   for (BasicBlock *BB : TheLoop->blocks()) {
1546     // Scan the BB and collect legal loads and stores.
1547     for (Instruction &I : *BB) {
1548       // If this is a load, save it. If this instruction can read from memory
1549       // but is not a load, then we quit. Notice that we don't handle function
1550       // calls that read or write.
1551       if (I.mayReadFromMemory()) {
1552         // Many math library functions read the rounding mode. We will only
1553         // vectorize a loop if it contains known function calls that don't set
1554         // the flag. Therefore, it is safe to ignore this read from memory.
1555         auto *Call = dyn_cast<CallInst>(&I);
1556         if (Call && getVectorIntrinsicIDForCall(Call, TLI))
1557           continue;
1558
1559         // If the function has an explicit vectorized counterpart, we can safely
1560         // assume that it can be vectorized.
1561         if (Call && !Call->isNoBuiltin() && Call->getCalledFunction() &&
1562             TLI->isFunctionVectorizable(Call->getCalledFunction()->getName()))
1563           continue;
1564
1565         auto *Ld = dyn_cast<LoadInst>(&I);
1566         if (!Ld || (!Ld->isSimple() && !IsAnnotatedParallel)) {
1567           emitAnalysis(LoopAccessReport(Ld)
1568                        << "read with atomic ordering or volatile read");
1569           DEBUG(dbgs() << "LAA: Found a non-simple load.\n");
1570           CanVecMem = false;
1571           return;
1572         }
1573         NumLoads++;
1574         Loads.push_back(Ld);
1575         DepChecker->addAccess(Ld);
1576         if (EnableMemAccessVersioning)
1577           collectStridedAccess(Ld);
1578         continue;
1579       }
1580
1581       // Save 'store' instructions. Abort if other instructions write to memory.
1582       if (I.mayWriteToMemory()) {
1583         auto *St = dyn_cast<StoreInst>(&I);
1584         if (!St) {
1585           emitAnalysis(LoopAccessReport(St)
1586                        << "instruction cannot be vectorized");
1587           CanVecMem = false;
1588           return;
1589         }
1590         if (!St->isSimple() && !IsAnnotatedParallel) {
1591           emitAnalysis(LoopAccessReport(St)
1592                        << "write with atomic ordering or volatile write");
1593           DEBUG(dbgs() << "LAA: Found a non-simple store.\n");
1594           CanVecMem = false;
1595           return;
1596         }
1597         NumStores++;
1598         Stores.push_back(St);
1599         DepChecker->addAccess(St);
1600         if (EnableMemAccessVersioning)
1601           collectStridedAccess(St);
1602       }
1603     } // Next instr.
1604   } // Next block.
1605
1606   // Now we have two lists that hold the loads and the stores.
1607   // Next, we find the pointers that they use.
1608
1609   // Check if we see any stores. If there are no stores, then we don't
1610   // care if the pointers are *restrict*.
1611   if (!Stores.size()) {
1612     DEBUG(dbgs() << "LAA: Found a read-only loop!\n");
1613     CanVecMem = true;
1614     return;
1615   }
1616
1617   MemoryDepChecker::DepCandidates DependentAccesses;
1618   AccessAnalysis Accesses(TheLoop->getHeader()->getModule()->getDataLayout(),
1619                           AA, LI, DependentAccesses, *PSE);
1620
1621   // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
1622   // multiple times on the same object. If the ptr is accessed twice, once
1623   // for read and once for write, it will only appear once (on the write
1624   // list). This is okay, since we are going to check for conflicts between
1625   // writes and between reads and writes, but not between reads and reads.
1626   ValueSet Seen;
1627
1628   for (StoreInst *ST : Stores) {
1629     Value *Ptr = ST->getPointerOperand();
1630     // Check for store to loop invariant address.
1631     StoreToLoopInvariantAddress |= isUniform(Ptr);
1632     // If we did *not* see this pointer before, insert it to  the read-write
1633     // list. At this phase it is only a 'write' list.
1634     if (Seen.insert(Ptr).second) {
1635       ++NumReadWrites;
1636
1637       MemoryLocation Loc = MemoryLocation::get(ST);
1638       // The TBAA metadata could have a control dependency on the predication
1639       // condition, so we cannot rely on it when determining whether or not we
1640       // need runtime pointer checks.
1641       if (blockNeedsPredication(ST->getParent(), TheLoop, DT))
1642         Loc.AATags.TBAA = nullptr;
1643
1644       Accesses.addStore(Loc);
1645     }
1646   }
1647
1648   if (IsAnnotatedParallel) {
1649     DEBUG(dbgs()
1650           << "LAA: A loop annotated parallel, ignore memory dependency "
1651           << "checks.\n");
1652     CanVecMem = true;
1653     return;
1654   }
1655
1656   for (LoadInst *LD : Loads) {
1657     Value *Ptr = LD->getPointerOperand();
1658     // If we did *not* see this pointer before, insert it to the
1659     // read list. If we *did* see it before, then it is already in
1660     // the read-write list. This allows us to vectorize expressions
1661     // such as A[i] += x;  Because the address of A[i] is a read-write
1662     // pointer. This only works if the index of A[i] is consecutive.
1663     // If the address of i is unknown (for example A[B[i]]) then we may
1664     // read a few words, modify, and write a few words, and some of the
1665     // words may be written to the same address.
1666     bool IsReadOnlyPtr = false;
1667     if (Seen.insert(Ptr).second ||
1668         !getPtrStride(*PSE, Ptr, TheLoop, SymbolicStrides)) {
1669       ++NumReads;
1670       IsReadOnlyPtr = true;
1671     }
1672
1673     MemoryLocation Loc = MemoryLocation::get(LD);
1674     // The TBAA metadata could have a control dependency on the predication
1675     // condition, so we cannot rely on it when determining whether or not we
1676     // need runtime pointer checks.
1677     if (blockNeedsPredication(LD->getParent(), TheLoop, DT))
1678       Loc.AATags.TBAA = nullptr;
1679
1680     Accesses.addLoad(Loc, IsReadOnlyPtr);
1681   }
1682
1683   // If we write (or read-write) to a single destination and there are no
1684   // other reads in this loop then is it safe to vectorize.
1685   if (NumReadWrites == 1 && NumReads == 0) {
1686     DEBUG(dbgs() << "LAA: Found a write-only loop!\n");
1687     CanVecMem = true;
1688     return;
1689   }
1690
1691   // Build dependence sets and check whether we need a runtime pointer bounds
1692   // check.
1693   Accesses.buildDependenceSets();
1694
1695   // Find pointers with computable bounds. We are going to use this information
1696   // to place a runtime bound check.
1697   bool CanDoRTIfNeeded = Accesses.canCheckPtrAtRT(*PtrRtChecking, PSE->getSE(),
1698                                                   TheLoop, SymbolicStrides);
1699   if (!CanDoRTIfNeeded) {
1700     emitAnalysis(LoopAccessReport() << "cannot identify array bounds");
1701     DEBUG(dbgs() << "LAA: We can't vectorize because we can't find "
1702                  << "the array bounds.\n");
1703     CanVecMem = false;
1704     return;
1705   }
1706
1707   DEBUG(dbgs() << "LAA: We can perform a memory runtime check if needed.\n");
1708
1709   CanVecMem = true;
1710   if (Accesses.isDependencyCheckNeeded()) {
1711     DEBUG(dbgs() << "LAA: Checking memory dependencies\n");
1712     CanVecMem = DepChecker->areDepsSafe(
1713         DependentAccesses, Accesses.getDependenciesToCheck(), SymbolicStrides);
1714     MaxSafeDepDistBytes = DepChecker->getMaxSafeDepDistBytes();
1715
1716     if (!CanVecMem && DepChecker->shouldRetryWithRuntimeCheck()) {
1717       DEBUG(dbgs() << "LAA: Retrying with memory checks\n");
1718
1719       // Clear the dependency checks. We assume they are not needed.
1720       Accesses.resetDepChecks(*DepChecker);
1721
1722       PtrRtChecking->reset();
1723       PtrRtChecking->Need = true;
1724
1725       auto *SE = PSE->getSE();
1726       CanDoRTIfNeeded = Accesses.canCheckPtrAtRT(*PtrRtChecking, SE, TheLoop,
1727                                                  SymbolicStrides, true);
1728
1729       // Check that we found the bounds for the pointer.
1730       if (!CanDoRTIfNeeded) {
1731         emitAnalysis(LoopAccessReport()
1732                      << "cannot check memory dependencies at runtime");
1733         DEBUG(dbgs() << "LAA: Can't vectorize with memory checks\n");
1734         CanVecMem = false;
1735         return;
1736       }
1737
1738       CanVecMem = true;
1739     }
1740   }
1741
1742   if (CanVecMem)
1743     DEBUG(dbgs() << "LAA: No unsafe dependent memory operations in loop.  We"
1744                  << (PtrRtChecking->Need ? "" : " don't")
1745                  << " need runtime memory checks.\n");
1746   else {
1747     emitAnalysis(
1748         LoopAccessReport()
1749         << "unsafe dependent memory operations in loop. Use "
1750            "#pragma loop distribute(enable) to allow loop distribution "
1751            "to attempt to isolate the offending operations into a separate "
1752            "loop");
1753     DEBUG(dbgs() << "LAA: unsafe dependent memory operations in loop\n");
1754   }
1755 }
1756
1757 bool LoopAccessInfo::blockNeedsPredication(BasicBlock *BB, Loop *TheLoop,
1758                                            DominatorTree *DT)  {
1759   assert(TheLoop->contains(BB) && "Unknown block used");
1760
1761   // Blocks that do not dominate the latch need predication.
1762   BasicBlock* Latch = TheLoop->getLoopLatch();
1763   return !DT->dominates(BB, Latch);
1764 }
1765
1766 void LoopAccessInfo::emitAnalysis(LoopAccessReport &Message) {
1767   assert(!Report && "Multiple reports generated");
1768   Report = Message;
1769 }
1770
1771 bool LoopAccessInfo::isUniform(Value *V) const {
1772   return (PSE->getSE()->isLoopInvariant(PSE->getSE()->getSCEV(V), TheLoop));
1773 }
1774
1775 // FIXME: this function is currently a duplicate of the one in
1776 // LoopVectorize.cpp.
1777 static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
1778                                  Instruction *Loc) {
1779   if (FirstInst)
1780     return FirstInst;
1781   if (Instruction *I = dyn_cast<Instruction>(V))
1782     return I->getParent() == Loc->getParent() ? I : nullptr;
1783   return nullptr;
1784 }
1785
1786 namespace {
1787 /// \brief IR Values for the lower and upper bounds of a pointer evolution.  We
1788 /// need to use value-handles because SCEV expansion can invalidate previously
1789 /// expanded values.  Thus expansion of a pointer can invalidate the bounds for
1790 /// a previous one.
1791 struct PointerBounds {
1792   TrackingVH<Value> Start;
1793   TrackingVH<Value> End;
1794 };
1795 } // end anonymous namespace
1796
1797 /// \brief Expand code for the lower and upper bound of the pointer group \p CG
1798 /// in \p TheLoop.  \return the values for the bounds.
1799 static PointerBounds
1800 expandBounds(const RuntimePointerChecking::CheckingPtrGroup *CG, Loop *TheLoop,
1801              Instruction *Loc, SCEVExpander &Exp, ScalarEvolution *SE,
1802              const RuntimePointerChecking &PtrRtChecking) {
1803   Value *Ptr = PtrRtChecking.Pointers[CG->Members[0]].PointerValue;
1804   const SCEV *Sc = SE->getSCEV(Ptr);
1805
1806   if (SE->isLoopInvariant(Sc, TheLoop)) {
1807     DEBUG(dbgs() << "LAA: Adding RT check for a loop invariant ptr:" << *Ptr
1808                  << "\n");
1809     return {Ptr, Ptr};
1810   } else {
1811     unsigned AS = Ptr->getType()->getPointerAddressSpace();
1812     LLVMContext &Ctx = Loc->getContext();
1813
1814     // Use this type for pointer arithmetic.
1815     Type *PtrArithTy = Type::getInt8PtrTy(Ctx, AS);
1816     Value *Start = nullptr, *End = nullptr;
1817
1818     DEBUG(dbgs() << "LAA: Adding RT check for range:\n");
1819     Start = Exp.expandCodeFor(CG->Low, PtrArithTy, Loc);
1820     End = Exp.expandCodeFor(CG->High, PtrArithTy, Loc);
1821     DEBUG(dbgs() << "Start: " << *CG->Low << " End: " << *CG->High << "\n");
1822     return {Start, End};
1823   }
1824 }
1825
1826 /// \brief Turns a collection of checks into a collection of expanded upper and
1827 /// lower bounds for both pointers in the check.
1828 static SmallVector<std::pair<PointerBounds, PointerBounds>, 4> expandBounds(
1829     const SmallVectorImpl<RuntimePointerChecking::PointerCheck> &PointerChecks,
1830     Loop *L, Instruction *Loc, ScalarEvolution *SE, SCEVExpander &Exp,
1831     const RuntimePointerChecking &PtrRtChecking) {
1832   SmallVector<std::pair<PointerBounds, PointerBounds>, 4> ChecksWithBounds;
1833
1834   // Here we're relying on the SCEV Expander's cache to only emit code for the
1835   // same bounds once.
1836   std::transform(
1837       PointerChecks.begin(), PointerChecks.end(),
1838       std::back_inserter(ChecksWithBounds),
1839       [&](const RuntimePointerChecking::PointerCheck &Check) {
1840         PointerBounds
1841           First = expandBounds(Check.first, L, Loc, Exp, SE, PtrRtChecking),
1842           Second = expandBounds(Check.second, L, Loc, Exp, SE, PtrRtChecking);
1843         return std::make_pair(First, Second);
1844       });
1845
1846   return ChecksWithBounds;
1847 }
1848
1849 std::pair<Instruction *, Instruction *> LoopAccessInfo::addRuntimeChecks(
1850     Instruction *Loc,
1851     const SmallVectorImpl<RuntimePointerChecking::PointerCheck> &PointerChecks)
1852     const {
1853   const DataLayout &DL = TheLoop->getHeader()->getModule()->getDataLayout();
1854   auto *SE = PSE->getSE();
1855   SCEVExpander Exp(*SE, DL, "induction");
1856   auto ExpandedChecks =
1857       expandBounds(PointerChecks, TheLoop, Loc, SE, Exp, *PtrRtChecking);
1858
1859   LLVMContext &Ctx = Loc->getContext();
1860   Instruction *FirstInst = nullptr;
1861   IRBuilder<> ChkBuilder(Loc);
1862   // Our instructions might fold to a constant.
1863   Value *MemoryRuntimeCheck = nullptr;
1864
1865   for (const auto &Check : ExpandedChecks) {
1866     const PointerBounds &A = Check.first, &B = Check.second;
1867     // Check if two pointers (A and B) conflict where conflict is computed as:
1868     // start(A) <= end(B) && start(B) <= end(A)
1869     unsigned AS0 = A.Start->getType()->getPointerAddressSpace();
1870     unsigned AS1 = B.Start->getType()->getPointerAddressSpace();
1871
1872     assert((AS0 == B.End->getType()->getPointerAddressSpace()) &&
1873            (AS1 == A.End->getType()->getPointerAddressSpace()) &&
1874            "Trying to bounds check pointers with different address spaces");
1875
1876     Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0);
1877     Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1);
1878
1879     Value *Start0 = ChkBuilder.CreateBitCast(A.Start, PtrArithTy0, "bc");
1880     Value *Start1 = ChkBuilder.CreateBitCast(B.Start, PtrArithTy1, "bc");
1881     Value *End0 =   ChkBuilder.CreateBitCast(A.End,   PtrArithTy1, "bc");
1882     Value *End1 =   ChkBuilder.CreateBitCast(B.End,   PtrArithTy0, "bc");
1883
1884     // [A|B].Start points to the first accessed byte under base [A|B].
1885     // [A|B].End points to the last accessed byte, plus one.
1886     // There is no conflict when the intervals are disjoint:
1887     // NoConflict = (B.Start >= A.End) || (A.Start >= B.End)
1888     //
1889     // bound0 = (B.Start < A.End)
1890     // bound1 = (A.Start < B.End)
1891     //  IsConflict = bound0 & bound1
1892     Value *Cmp0 = ChkBuilder.CreateICmpULT(Start0, End1, "bound0");
1893     FirstInst = getFirstInst(FirstInst, Cmp0, Loc);
1894     Value *Cmp1 = ChkBuilder.CreateICmpULT(Start1, End0, "bound1");
1895     FirstInst = getFirstInst(FirstInst, Cmp1, Loc);
1896     Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
1897     FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1898     if (MemoryRuntimeCheck) {
1899       IsConflict =
1900           ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict, "conflict.rdx");
1901       FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1902     }
1903     MemoryRuntimeCheck = IsConflict;
1904   }
1905
1906   if (!MemoryRuntimeCheck)
1907     return std::make_pair(nullptr, nullptr);
1908
1909   // We have to do this trickery because the IRBuilder might fold the check to a
1910   // constant expression in which case there is no Instruction anchored in a
1911   // the block.
1912   Instruction *Check = BinaryOperator::CreateAnd(MemoryRuntimeCheck,
1913                                                  ConstantInt::getTrue(Ctx));
1914   ChkBuilder.Insert(Check, "memcheck.conflict");
1915   FirstInst = getFirstInst(FirstInst, Check, Loc);
1916   return std::make_pair(FirstInst, Check);
1917 }
1918
1919 std::pair<Instruction *, Instruction *>
1920 LoopAccessInfo::addRuntimeChecks(Instruction *Loc) const {
1921   if (!PtrRtChecking->Need)
1922     return std::make_pair(nullptr, nullptr);
1923
1924   return addRuntimeChecks(Loc, PtrRtChecking->getChecks());
1925 }
1926
1927 void LoopAccessInfo::collectStridedAccess(Value *MemAccess) {
1928   Value *Ptr = nullptr;
1929   if (LoadInst *LI = dyn_cast<LoadInst>(MemAccess))
1930     Ptr = LI->getPointerOperand();
1931   else if (StoreInst *SI = dyn_cast<StoreInst>(MemAccess))
1932     Ptr = SI->getPointerOperand();
1933   else
1934     return;
1935
1936   Value *Stride = getStrideFromPointer(Ptr, PSE->getSE(), TheLoop);
1937   if (!Stride)
1938     return;
1939
1940   DEBUG(dbgs() << "LAA: Found a strided access that we can version");
1941   DEBUG(dbgs() << "  Ptr: " << *Ptr << " Stride: " << *Stride << "\n");
1942   SymbolicStrides[Ptr] = Stride;
1943   StrideSet.insert(Stride);
1944 }
1945
1946 LoopAccessInfo::LoopAccessInfo(Loop *L, ScalarEvolution *SE,
1947                                const TargetLibraryInfo *TLI, AliasAnalysis *AA,
1948                                DominatorTree *DT, LoopInfo *LI)
1949     : PSE(llvm::make_unique<PredicatedScalarEvolution>(*SE, *L)),
1950       PtrRtChecking(llvm::make_unique<RuntimePointerChecking>(SE)),
1951       DepChecker(llvm::make_unique<MemoryDepChecker>(*PSE, L)), TheLoop(L),
1952       NumLoads(0), NumStores(0), MaxSafeDepDistBytes(-1), CanVecMem(false),
1953       StoreToLoopInvariantAddress(false) {
1954   if (canAnalyzeLoop())
1955     analyzeLoop(AA, LI, TLI, DT);
1956 }
1957
1958 void LoopAccessInfo::print(raw_ostream &OS, unsigned Depth) const {
1959   if (CanVecMem) {
1960     OS.indent(Depth) << "Memory dependences are safe";
1961     if (MaxSafeDepDistBytes != -1ULL)
1962       OS << " with a maximum dependence distance of " << MaxSafeDepDistBytes
1963          << " bytes";
1964     if (PtrRtChecking->Need)
1965       OS << " with run-time checks";
1966     OS << "\n";
1967   }
1968
1969   if (Report)
1970     OS.indent(Depth) << "Report: " << Report->str() << "\n";
1971
1972   if (auto *Dependences = DepChecker->getDependences()) {
1973     OS.indent(Depth) << "Dependences:\n";
1974     for (auto &Dep : *Dependences) {
1975       Dep.print(OS, Depth + 2, DepChecker->getMemoryInstructions());
1976       OS << "\n";
1977     }
1978   } else
1979     OS.indent(Depth) << "Too many dependences, not recorded\n";
1980
1981   // List the pair of accesses need run-time checks to prove independence.
1982   PtrRtChecking->print(OS, Depth);
1983   OS << "\n";
1984
1985   OS.indent(Depth) << "Store to invariant address was "
1986                    << (StoreToLoopInvariantAddress ? "" : "not ")
1987                    << "found in loop.\n";
1988
1989   OS.indent(Depth) << "SCEV assumptions:\n";
1990   PSE->getUnionPredicate().print(OS, Depth);
1991
1992   OS << "\n";
1993
1994   OS.indent(Depth) << "Expressions re-written:\n";
1995   PSE->print(OS, Depth);
1996 }
1997
1998 const LoopAccessInfo &LoopAccessLegacyAnalysis::getInfo(Loop *L) {
1999   auto &LAI = LoopAccessInfoMap[L];
2000
2001   if (!LAI)
2002     LAI = llvm::make_unique<LoopAccessInfo>(L, SE, TLI, AA, DT, LI);
2003
2004   return *LAI.get();
2005 }
2006
2007 void LoopAccessLegacyAnalysis::print(raw_ostream &OS, const Module *M) const {
2008   LoopAccessLegacyAnalysis &LAA = *const_cast<LoopAccessLegacyAnalysis *>(this);
2009
2010   for (Loop *TopLevelLoop : *LI)
2011     for (Loop *L : depth_first(TopLevelLoop)) {
2012       OS.indent(2) << L->getHeader()->getName() << ":\n";
2013       auto &LAI = LAA.getInfo(L);
2014       LAI.print(OS, 4);
2015     }
2016 }
2017
2018 bool LoopAccessLegacyAnalysis::runOnFunction(Function &F) {
2019   SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
2020   auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
2021   TLI = TLIP ? &TLIP->getTLI() : nullptr;
2022   AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
2023   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2024   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2025
2026   return false;
2027 }
2028
2029 void LoopAccessLegacyAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
2030     AU.addRequired<ScalarEvolutionWrapperPass>();
2031     AU.addRequired<AAResultsWrapperPass>();
2032     AU.addRequired<DominatorTreeWrapperPass>();
2033     AU.addRequired<LoopInfoWrapperPass>();
2034
2035     AU.setPreservesAll();
2036 }
2037
2038 char LoopAccessLegacyAnalysis::ID = 0;
2039 static const char laa_name[] = "Loop Access Analysis";
2040 #define LAA_NAME "loop-accesses"
2041
2042 INITIALIZE_PASS_BEGIN(LoopAccessLegacyAnalysis, LAA_NAME, laa_name, false, true)
2043 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
2044 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
2045 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
2046 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
2047 INITIALIZE_PASS_END(LoopAccessLegacyAnalysis, LAA_NAME, laa_name, false, true)
2048
2049 char LoopAccessAnalysis::PassID;
2050
2051 LoopAccessInfo LoopAccessAnalysis::run(Loop &L, AnalysisManager<Loop> &AM) {
2052   const AnalysisManager<Function> &FAM =
2053       AM.getResult<FunctionAnalysisManagerLoopProxy>(L).getManager();
2054   Function &F = *L.getHeader()->getParent();
2055   auto *SE = FAM.getCachedResult<ScalarEvolutionAnalysis>(F);
2056   auto *TLI = FAM.getCachedResult<TargetLibraryAnalysis>(F);
2057   auto *AA = FAM.getCachedResult<AAManager>(F);
2058   auto *DT = FAM.getCachedResult<DominatorTreeAnalysis>(F);
2059   auto *LI = FAM.getCachedResult<LoopAnalysis>(F);
2060   if (!SE)
2061     report_fatal_error(
2062         "ScalarEvolution must have been cached at a higher level");
2063   if (!AA)
2064     report_fatal_error("AliasAnalysis must have been cached at a higher level");
2065   if (!DT)
2066     report_fatal_error("DominatorTree must have been cached at a higher level");
2067   if (!LI)
2068     report_fatal_error("LoopInfo must have been cached at a higher level");
2069   return LoopAccessInfo(&L, SE, TLI, AA, DT, LI);
2070 }
2071
2072 PreservedAnalyses LoopAccessInfoPrinterPass::run(Loop &L,
2073                                                  AnalysisManager<Loop> &AM) {
2074   Function &F = *L.getHeader()->getParent();
2075   auto &LAI = AM.getResult<LoopAccessAnalysis>(L);
2076   OS << "Loop access info in function '" << F.getName() << "':\n";
2077   OS.indent(2) << L.getHeader()->getName() << ":\n";
2078   LAI.print(OS, 4);
2079   return PreservedAnalyses::all();
2080 }
2081
2082 namespace llvm {
2083   Pass *createLAAPass() {
2084     return new LoopAccessLegacyAnalysis();
2085   }
2086 }