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