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