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