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