xref: /llvm-project/llvm/include/llvm/Analysis/LoopAccessAnalysis.h (revision b7286dbef9dc1986860d29e390b092599e1d7db5)
1 //===- llvm/Analysis/LoopAccessAnalysis.h -----------------------*- C++ -*-===//
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 // This file defines the interface for the loop memory dependence framework that
10 // was originally developed for the Loop Vectorizer.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_ANALYSIS_LOOPACCESSANALYSIS_H
15 #define LLVM_ANALYSIS_LOOPACCESSANALYSIS_H
16 
17 #include "llvm/ADT/EquivalenceClasses.h"
18 #include "llvm/Analysis/ScalarEvolution.h"
19 #include "llvm/IR/DiagnosticInfo.h"
20 #include <optional>
21 #include <variant>
22 
23 namespace llvm {
24 
25 class AAResults;
26 class DataLayout;
27 class Loop;
28 class raw_ostream;
29 class TargetTransformInfo;
30 
31 /// Collection of parameters shared beetween the Loop Vectorizer and the
32 /// Loop Access Analysis.
33 struct VectorizerParams {
34   /// Maximum SIMD width.
35   static const unsigned MaxVectorWidth;
36 
37   /// VF as overridden by the user.
38   static unsigned VectorizationFactor;
39   /// Interleave factor as overridden by the user.
40   static unsigned VectorizationInterleave;
41   /// True if force-vector-interleave was specified by the user.
42   static bool isInterleaveForced();
43 
44   /// \When performing memory disambiguation checks at runtime do not
45   /// make more than this number of comparisons.
46   static unsigned RuntimeMemoryCheckThreshold;
47 
48   // When creating runtime checks for nested loops, where possible try to
49   // write the checks in a form that allows them to be easily hoisted out of
50   // the outermost loop. For example, we can do this by expanding the range of
51   // addresses considered to include the entire nested loop so that they are
52   // loop invariant.
53   static bool HoistRuntimeChecks;
54 };
55 
56 /// Checks memory dependences among accesses to the same underlying
57 /// object to determine whether there vectorization is legal or not (and at
58 /// which vectorization factor).
59 ///
60 /// Note: This class will compute a conservative dependence for access to
61 /// different underlying pointers. Clients, such as the loop vectorizer, will
62 /// sometimes deal these potential dependencies by emitting runtime checks.
63 ///
64 /// We use the ScalarEvolution framework to symbolically evalutate access
65 /// functions pairs. Since we currently don't restructure the loop we can rely
66 /// on the program order of memory accesses to determine their safety.
67 /// At the moment we will only deem accesses as safe for:
68 ///  * A negative constant distance assuming program order.
69 ///
70 ///      Safe: tmp = a[i + 1];     OR     a[i + 1] = x;
71 ///            a[i] = tmp;                y = a[i];
72 ///
73 ///   The latter case is safe because later checks guarantuee that there can't
74 ///   be a cycle through a phi node (that is, we check that "x" and "y" is not
75 ///   the same variable: a header phi can only be an induction or a reduction, a
76 ///   reduction can't have a memory sink, an induction can't have a memory
77 ///   source). This is important and must not be violated (or we have to
78 ///   resort to checking for cycles through memory).
79 ///
80 ///  * A positive constant distance assuming program order that is bigger
81 ///    than the biggest memory access.
82 ///
83 ///     tmp = a[i]        OR              b[i] = x
84 ///     a[i+2] = tmp                      y = b[i+2];
85 ///
86 ///     Safe distance: 2 x sizeof(a[0]), and 2 x sizeof(b[0]), respectively.
87 ///
88 ///  * Zero distances and all accesses have the same size.
89 ///
90 class MemoryDepChecker {
91 public:
92   typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
93   typedef SmallVector<MemAccessInfo, 8> MemAccessInfoList;
94   /// Set of potential dependent memory accesses.
95   typedef EquivalenceClasses<MemAccessInfo> DepCandidates;
96 
97   /// Type to keep track of the status of the dependence check. The order of
98   /// the elements is important and has to be from most permissive to least
99   /// permissive.
100   enum class VectorizationSafetyStatus {
101     // Can vectorize safely without RT checks. All dependences are known to be
102     // safe.
103     Safe,
104     // Can possibly vectorize with RT checks to overcome unknown dependencies.
105     PossiblySafeWithRtChecks,
106     // Cannot vectorize due to known unsafe dependencies.
107     Unsafe,
108   };
109 
110   /// Dependece between memory access instructions.
111   struct Dependence {
112     /// The type of the dependence.
113     enum DepType {
114       // No dependence.
115       NoDep,
116       // We couldn't determine the direction or the distance.
117       Unknown,
118       // At least one of the memory access instructions may access a loop
119       // varying object, e.g. the address of underlying object is loaded inside
120       // the loop, like A[B[i]]. We cannot determine direction or distance in
121       // those cases, and also are unable to generate any runtime checks.
122       IndirectUnsafe,
123 
124       // Lexically forward.
125       //
126       // FIXME: If we only have loop-independent forward dependences (e.g. a
127       // read and write of A[i]), LAA will locally deem the dependence "safe"
128       // without querying the MemoryDepChecker.  Therefore we can miss
129       // enumerating loop-independent forward dependences in
130       // getDependences.  Note that as soon as there are different
131       // indices used to access the same array, the MemoryDepChecker *is*
132       // queried and the dependence list is complete.
133       Forward,
134       // Forward, but if vectorized, is likely to prevent store-to-load
135       // forwarding.
136       ForwardButPreventsForwarding,
137       // Lexically backward.
138       Backward,
139       // Backward, but the distance allows a vectorization factor of dependent
140       // on MinDepDistBytes.
141       BackwardVectorizable,
142       // Same, but may prevent store-to-load forwarding.
143       BackwardVectorizableButPreventsForwarding
144     };
145 
146     /// String version of the types.
147     static const char *DepName[];
148 
149     /// Index of the source of the dependence in the InstMap vector.
150     unsigned Source;
151     /// Index of the destination of the dependence in the InstMap vector.
152     unsigned Destination;
153     /// The type of the dependence.
154     DepType Type;
155 
156     Dependence(unsigned Source, unsigned Destination, DepType Type)
157         : Source(Source), Destination(Destination), Type(Type) {}
158 
159     /// Return the source instruction of the dependence.
160     Instruction *getSource(const MemoryDepChecker &DepChecker) const;
161     /// Return the destination instruction of the dependence.
162     Instruction *getDestination(const MemoryDepChecker &DepChecker) const;
163 
164     /// Dependence types that don't prevent vectorization.
165     static VectorizationSafetyStatus isSafeForVectorization(DepType Type);
166 
167     /// Lexically forward dependence.
168     bool isForward() const;
169     /// Lexically backward dependence.
170     bool isBackward() const;
171 
172     /// May be a lexically backward dependence type (includes Unknown).
173     bool isPossiblyBackward() const;
174 
175     /// Print the dependence.  \p Instr is used to map the instruction
176     /// indices to instructions.
177     void print(raw_ostream &OS, unsigned Depth,
178                const SmallVectorImpl<Instruction *> &Instrs) const;
179   };
180 
181   MemoryDepChecker(PredicatedScalarEvolution &PSE, const Loop *L,
182                    const DenseMap<Value *, const SCEV *> &SymbolicStrides,
183                    unsigned MaxTargetVectorWidthInBits)
184       : PSE(PSE), InnermostLoop(L), SymbolicStrides(SymbolicStrides),
185         MaxTargetVectorWidthInBits(MaxTargetVectorWidthInBits) {}
186 
187   /// Register the location (instructions are given increasing numbers)
188   /// of a write access.
189   void addAccess(StoreInst *SI);
190 
191   /// Register the location (instructions are given increasing numbers)
192   /// of a write access.
193   void addAccess(LoadInst *LI);
194 
195   /// Check whether the dependencies between the accesses are safe.
196   ///
197   /// Only checks sets with elements in \p CheckDeps.
198   bool areDepsSafe(const DepCandidates &AccessSets,
199                    const MemAccessInfoList &CheckDeps);
200 
201   /// No memory dependence was encountered that would inhibit
202   /// vectorization.
203   bool isSafeForVectorization() const {
204     return Status == VectorizationSafetyStatus::Safe;
205   }
206 
207   /// Return true if the number of elements that are safe to operate on
208   /// simultaneously is not bounded.
209   bool isSafeForAnyVectorWidth() const {
210     return MaxSafeVectorWidthInBits == UINT_MAX;
211   }
212 
213   /// Return the number of elements that are safe to operate on
214   /// simultaneously, multiplied by the size of the element in bits.
215   uint64_t getMaxSafeVectorWidthInBits() const {
216     return MaxSafeVectorWidthInBits;
217   }
218 
219   /// In same cases when the dependency check fails we can still
220   /// vectorize the loop with a dynamic array access check.
221   bool shouldRetryWithRuntimeCheck() const {
222     return FoundNonConstantDistanceDependence &&
223            Status == VectorizationSafetyStatus::PossiblySafeWithRtChecks;
224   }
225 
226   /// Returns the memory dependences.  If null is returned we exceeded
227   /// the MaxDependences threshold and this information is not
228   /// available.
229   const SmallVectorImpl<Dependence> *getDependences() const {
230     return RecordDependences ? &Dependences : nullptr;
231   }
232 
233   void clearDependences() { Dependences.clear(); }
234 
235   /// The vector of memory access instructions.  The indices are used as
236   /// instruction identifiers in the Dependence class.
237   const SmallVectorImpl<Instruction *> &getMemoryInstructions() const {
238     return InstMap;
239   }
240 
241   /// Generate a mapping between the memory instructions and their
242   /// indices according to program order.
243   DenseMap<Instruction *, unsigned> generateInstructionOrderMap() const {
244     DenseMap<Instruction *, unsigned> OrderMap;
245 
246     for (unsigned I = 0; I < InstMap.size(); ++I)
247       OrderMap[InstMap[I]] = I;
248 
249     return OrderMap;
250   }
251 
252   /// Find the set of instructions that read or write via \p Ptr.
253   SmallVector<Instruction *, 4> getInstructionsForAccess(Value *Ptr,
254                                                          bool isWrite) const;
255 
256   /// Return the program order indices for the access location (Ptr, IsWrite).
257   /// Returns an empty ArrayRef if there are no accesses for the location.
258   ArrayRef<unsigned> getOrderForAccess(Value *Ptr, bool IsWrite) const {
259     auto I = Accesses.find({Ptr, IsWrite});
260     if (I != Accesses.end())
261       return I->second;
262     return {};
263   }
264 
265   const Loop *getInnermostLoop() const { return InnermostLoop; }
266 
267   DenseMap<std::pair<const SCEV *, Type *>,
268            std::pair<const SCEV *, const SCEV *>> &
269   getPointerBounds() {
270     return PointerBounds;
271   }
272 
273 private:
274   /// A wrapper around ScalarEvolution, used to add runtime SCEV checks, and
275   /// applies dynamic knowledge to simplify SCEV expressions and convert them
276   /// to a more usable form. We need this in case assumptions about SCEV
277   /// expressions need to be made in order to avoid unknown dependences. For
278   /// example we might assume a unit stride for a pointer in order to prove
279   /// that a memory access is strided and doesn't wrap.
280   PredicatedScalarEvolution &PSE;
281   const Loop *InnermostLoop;
282 
283   /// Reference to map of pointer values to
284   /// their stride symbols, if they have a symbolic stride.
285   const DenseMap<Value *, const SCEV *> &SymbolicStrides;
286 
287   /// Maps access locations (ptr, read/write) to program order.
288   DenseMap<MemAccessInfo, std::vector<unsigned> > Accesses;
289 
290   /// Memory access instructions in program order.
291   SmallVector<Instruction *, 16> InstMap;
292 
293   /// The program order index to be used for the next instruction.
294   unsigned AccessIdx = 0;
295 
296   /// The smallest dependence distance in bytes in the loop. This may not be
297   /// the same as the maximum number of bytes that are safe to operate on
298   /// simultaneously.
299   uint64_t MinDepDistBytes = 0;
300 
301   /// Number of elements (from consecutive iterations) that are safe to
302   /// operate on simultaneously, multiplied by the size of the element in bits.
303   /// The size of the element is taken from the memory access that is most
304   /// restrictive.
305   uint64_t MaxSafeVectorWidthInBits = -1U;
306 
307   /// If we see a non-constant dependence distance we can still try to
308   /// vectorize this loop with runtime checks.
309   bool FoundNonConstantDistanceDependence = false;
310 
311   /// Result of the dependence checks, indicating whether the checked
312   /// dependences are safe for vectorization, require RT checks or are known to
313   /// be unsafe.
314   VectorizationSafetyStatus Status = VectorizationSafetyStatus::Safe;
315 
316   //// True if Dependences reflects the dependences in the
317   //// loop.  If false we exceeded MaxDependences and
318   //// Dependences is invalid.
319   bool RecordDependences = true;
320 
321   /// Memory dependences collected during the analysis.  Only valid if
322   /// RecordDependences is true.
323   SmallVector<Dependence, 8> Dependences;
324 
325   /// The maximum width of a target's vector registers multiplied by 2 to also
326   /// roughly account for additional interleaving. Is used to decide if a
327   /// backwards dependence with non-constant stride should be classified as
328   /// backwards-vectorizable or unknown (triggering a runtime check).
329   unsigned MaxTargetVectorWidthInBits = 0;
330 
331   /// Mapping of SCEV expressions to their expanded pointer bounds (pair of
332   /// start and end pointer expressions).
333   DenseMap<std::pair<const SCEV *, Type *>,
334            std::pair<const SCEV *, const SCEV *>>
335       PointerBounds;
336 
337   /// Cache for the loop guards of InnermostLoop.
338   std::optional<ScalarEvolution::LoopGuards> LoopGuards;
339 
340   /// Check whether there is a plausible dependence between the two
341   /// accesses.
342   ///
343   /// Access \p A must happen before \p B in program order. The two indices
344   /// identify the index into the program order map.
345   ///
346   /// This function checks  whether there is a plausible dependence (or the
347   /// absence of such can't be proved) between the two accesses. If there is a
348   /// plausible dependence but the dependence distance is bigger than one
349   /// element access it records this distance in \p MinDepDistBytes (if this
350   /// distance is smaller than any other distance encountered so far).
351   /// Otherwise, this function returns true signaling a possible dependence.
352   Dependence::DepType isDependent(const MemAccessInfo &A, unsigned AIdx,
353                                   const MemAccessInfo &B, unsigned BIdx);
354 
355   /// Check whether the data dependence could prevent store-load
356   /// forwarding.
357   ///
358   /// \return false if we shouldn't vectorize at all or avoid larger
359   /// vectorization factors by limiting MinDepDistBytes.
360   bool couldPreventStoreLoadForward(uint64_t Distance, uint64_t TypeByteSize);
361 
362   /// Updates the current safety status with \p S. We can go from Safe to
363   /// either PossiblySafeWithRtChecks or Unsafe and from
364   /// PossiblySafeWithRtChecks to Unsafe.
365   void mergeInStatus(VectorizationSafetyStatus S);
366 
367   struct DepDistanceStrideAndSizeInfo {
368     const SCEV *Dist;
369 
370     /// Strides could either be scaled (in bytes, taking the size of the
371     /// underlying type into account), or unscaled (in indexing units; unscaled
372     /// stride = scaled stride / size of underlying type). Here, strides are
373     /// unscaled.
374     uint64_t MaxStride;
375     std::optional<uint64_t> CommonStride;
376 
377     bool ShouldRetryWithRuntimeCheck;
378     uint64_t TypeByteSize;
379     bool AIsWrite;
380     bool BIsWrite;
381 
382     DepDistanceStrideAndSizeInfo(const SCEV *Dist, uint64_t MaxStride,
383                                  std::optional<uint64_t> CommonStride,
384                                  bool ShouldRetryWithRuntimeCheck,
385                                  uint64_t TypeByteSize, bool AIsWrite,
386                                  bool BIsWrite)
387         : Dist(Dist), MaxStride(MaxStride), CommonStride(CommonStride),
388           ShouldRetryWithRuntimeCheck(ShouldRetryWithRuntimeCheck),
389           TypeByteSize(TypeByteSize), AIsWrite(AIsWrite), BIsWrite(BIsWrite) {}
390   };
391 
392   /// Get the dependence distance, strides, type size and whether it is a write
393   /// for the dependence between A and B. Returns a DepType, if we can prove
394   /// there's no dependence or the analysis fails. Outlined to lambda to limit
395   /// he scope of various temporary variables, like A/BPtr, StrideA/BPtr and
396   /// others. Returns either the dependence result, if it could already be
397   /// determined, or a struct containing (Distance, Stride, TypeSize, AIsWrite,
398   /// BIsWrite).
399   std::variant<Dependence::DepType, DepDistanceStrideAndSizeInfo>
400   getDependenceDistanceStrideAndSize(const MemAccessInfo &A, Instruction *AInst,
401                                      const MemAccessInfo &B,
402                                      Instruction *BInst);
403 };
404 
405 class RuntimePointerChecking;
406 /// A grouping of pointers. A single memcheck is required between
407 /// two groups.
408 struct RuntimeCheckingPtrGroup {
409   /// Create a new pointer checking group containing a single
410   /// pointer, with index \p Index in RtCheck.
411   RuntimeCheckingPtrGroup(unsigned Index,
412                           const RuntimePointerChecking &RtCheck);
413 
414   /// Tries to add the pointer recorded in RtCheck at index
415   /// \p Index to this pointer checking group. We can only add a pointer
416   /// to a checking group if we will still be able to get
417   /// the upper and lower bounds of the check. Returns true in case
418   /// of success, false otherwise.
419   bool addPointer(unsigned Index, const RuntimePointerChecking &RtCheck);
420   bool addPointer(unsigned Index, const SCEV *Start, const SCEV *End,
421                   unsigned AS, bool NeedsFreeze, ScalarEvolution &SE);
422 
423   /// The SCEV expression which represents the upper bound of all the
424   /// pointers in this group.
425   const SCEV *High;
426   /// The SCEV expression which represents the lower bound of all the
427   /// pointers in this group.
428   const SCEV *Low;
429   /// Indices of all the pointers that constitute this grouping.
430   SmallVector<unsigned, 2> Members;
431   /// Address space of the involved pointers.
432   unsigned AddressSpace;
433   /// Whether the pointer needs to be frozen after expansion, e.g. because it
434   /// may be poison outside the loop.
435   bool NeedsFreeze = false;
436 };
437 
438 /// A memcheck which made up of a pair of grouped pointers.
439 typedef std::pair<const RuntimeCheckingPtrGroup *,
440                   const RuntimeCheckingPtrGroup *>
441     RuntimePointerCheck;
442 
443 struct PointerDiffInfo {
444   const SCEV *SrcStart;
445   const SCEV *SinkStart;
446   unsigned AccessSize;
447   bool NeedsFreeze;
448 
449   PointerDiffInfo(const SCEV *SrcStart, const SCEV *SinkStart,
450                   unsigned AccessSize, bool NeedsFreeze)
451       : SrcStart(SrcStart), SinkStart(SinkStart), AccessSize(AccessSize),
452         NeedsFreeze(NeedsFreeze) {}
453 };
454 
455 /// Holds information about the memory runtime legality checks to verify
456 /// that a group of pointers do not overlap.
457 class RuntimePointerChecking {
458   friend struct RuntimeCheckingPtrGroup;
459 
460 public:
461   struct PointerInfo {
462     /// Holds the pointer value that we need to check.
463     TrackingVH<Value> PointerValue;
464     /// Holds the smallest byte address accessed by the pointer throughout all
465     /// iterations of the loop.
466     const SCEV *Start;
467     /// Holds the largest byte address accessed by the pointer throughout all
468     /// iterations of the loop, plus 1.
469     const SCEV *End;
470     /// Holds the information if this pointer is used for writing to memory.
471     bool IsWritePtr;
472     /// Holds the id of the set of pointers that could be dependent because of a
473     /// shared underlying object.
474     unsigned DependencySetId;
475     /// Holds the id of the disjoint alias set to which this pointer belongs.
476     unsigned AliasSetId;
477     /// SCEV for the access.
478     const SCEV *Expr;
479     /// True if the pointer expressions needs to be frozen after expansion.
480     bool NeedsFreeze;
481 
482     PointerInfo(Value *PointerValue, const SCEV *Start, const SCEV *End,
483                 bool IsWritePtr, unsigned DependencySetId, unsigned AliasSetId,
484                 const SCEV *Expr, bool NeedsFreeze)
485         : PointerValue(PointerValue), Start(Start), End(End),
486           IsWritePtr(IsWritePtr), DependencySetId(DependencySetId),
487           AliasSetId(AliasSetId), Expr(Expr), NeedsFreeze(NeedsFreeze) {}
488   };
489 
490   RuntimePointerChecking(MemoryDepChecker &DC, ScalarEvolution *SE)
491       : DC(DC), SE(SE) {}
492 
493   /// Reset the state of the pointer runtime information.
494   void reset() {
495     Need = false;
496     CanUseDiffCheck = true;
497     Pointers.clear();
498     Checks.clear();
499     DiffChecks.clear();
500   }
501 
502   /// Insert a pointer and calculate the start and end SCEVs.
503   /// We need \p PSE in order to compute the SCEV expression of the pointer
504   /// according to the assumptions that we've made during the analysis.
505   /// The method might also version the pointer stride according to \p Strides,
506   /// and add new predicates to \p PSE.
507   void insert(Loop *Lp, Value *Ptr, const SCEV *PtrExpr, Type *AccessTy,
508               bool WritePtr, unsigned DepSetId, unsigned ASId,
509               PredicatedScalarEvolution &PSE, bool NeedsFreeze);
510 
511   /// No run-time memory checking is necessary.
512   bool empty() const { return Pointers.empty(); }
513 
514   /// Generate the checks and store it.  This also performs the grouping
515   /// of pointers to reduce the number of memchecks necessary.
516   void generateChecks(MemoryDepChecker::DepCandidates &DepCands,
517                       bool UseDependencies);
518 
519   /// Returns the checks that generateChecks created. They can be used to ensure
520   /// no read/write accesses overlap across all loop iterations.
521   const SmallVectorImpl<RuntimePointerCheck> &getChecks() const {
522     return Checks;
523   }
524 
525   // Returns an optional list of (pointer-difference expressions, access size)
526   // pairs that can be used to prove that there are no vectorization-preventing
527   // dependencies at runtime. There are is a vectorization-preventing dependency
528   // if any pointer-difference is <u VF * InterleaveCount * access size. Returns
529   // std::nullopt if pointer-difference checks cannot be used.
530   std::optional<ArrayRef<PointerDiffInfo>> getDiffChecks() const {
531     if (!CanUseDiffCheck)
532       return std::nullopt;
533     return {DiffChecks};
534   }
535 
536   /// Decide if we need to add a check between two groups of pointers,
537   /// according to needsChecking.
538   bool needsChecking(const RuntimeCheckingPtrGroup &M,
539                      const RuntimeCheckingPtrGroup &N) const;
540 
541   /// Returns the number of run-time checks required according to
542   /// needsChecking.
543   unsigned getNumberOfChecks() const { return Checks.size(); }
544 
545   /// Print the list run-time memory checks necessary.
546   void print(raw_ostream &OS, unsigned Depth = 0) const;
547 
548   /// Print \p Checks.
549   void printChecks(raw_ostream &OS,
550                    const SmallVectorImpl<RuntimePointerCheck> &Checks,
551                    unsigned Depth = 0) const;
552 
553   /// This flag indicates if we need to add the runtime check.
554   bool Need = false;
555 
556   /// Information about the pointers that may require checking.
557   SmallVector<PointerInfo, 2> Pointers;
558 
559   /// Holds a partitioning of pointers into "check groups".
560   SmallVector<RuntimeCheckingPtrGroup, 2> CheckingGroups;
561 
562   /// Check if pointers are in the same partition
563   ///
564   /// \p PtrToPartition contains the partition number for pointers (-1 if the
565   /// pointer belongs to multiple partitions).
566   static bool
567   arePointersInSamePartition(const SmallVectorImpl<int> &PtrToPartition,
568                              unsigned PtrIdx1, unsigned PtrIdx2);
569 
570   /// Decide whether we need to issue a run-time check for pointer at
571   /// index \p I and \p J to prove their independence.
572   bool needsChecking(unsigned I, unsigned J) const;
573 
574   /// Return PointerInfo for pointer at index \p PtrIdx.
575   const PointerInfo &getPointerInfo(unsigned PtrIdx) const {
576     return Pointers[PtrIdx];
577   }
578 
579   ScalarEvolution *getSE() const { return SE; }
580 
581 private:
582   /// Groups pointers such that a single memcheck is required
583   /// between two different groups. This will clear the CheckingGroups vector
584   /// and re-compute it. We will only group dependecies if \p UseDependencies
585   /// is true, otherwise we will create a separate group for each pointer.
586   void groupChecks(MemoryDepChecker::DepCandidates &DepCands,
587                    bool UseDependencies);
588 
589   /// Generate the checks and return them.
590   SmallVector<RuntimePointerCheck, 4> generateChecks();
591 
592   /// Try to create add a new (pointer-difference, access size) pair to
593   /// DiffCheck for checking groups \p CGI and \p CGJ. If pointer-difference
594   /// checks cannot be used for the groups, set CanUseDiffCheck to false.
595   bool tryToCreateDiffCheck(const RuntimeCheckingPtrGroup &CGI,
596                             const RuntimeCheckingPtrGroup &CGJ);
597 
598   MemoryDepChecker &DC;
599 
600   /// Holds a pointer to the ScalarEvolution analysis.
601   ScalarEvolution *SE;
602 
603   /// Set of run-time checks required to establish independence of
604   /// otherwise may-aliasing pointers in the loop.
605   SmallVector<RuntimePointerCheck, 4> Checks;
606 
607   /// Flag indicating if pointer-difference checks can be used
608   bool CanUseDiffCheck = true;
609 
610   /// A list of (pointer-difference, access size) pairs that can be used to
611   /// prove that there are no vectorization-preventing dependencies.
612   SmallVector<PointerDiffInfo> DiffChecks;
613 };
614 
615 /// Drive the analysis of memory accesses in the loop
616 ///
617 /// This class is responsible for analyzing the memory accesses of a loop.  It
618 /// collects the accesses and then its main helper the AccessAnalysis class
619 /// finds and categorizes the dependences in buildDependenceSets.
620 ///
621 /// For memory dependences that can be analyzed at compile time, it determines
622 /// whether the dependence is part of cycle inhibiting vectorization.  This work
623 /// is delegated to the MemoryDepChecker class.
624 ///
625 /// For memory dependences that cannot be determined at compile time, it
626 /// generates run-time checks to prove independence.  This is done by
627 /// AccessAnalysis::canCheckPtrAtRT and the checks are maintained by the
628 /// RuntimePointerCheck class.
629 ///
630 /// If pointers can wrap or can't be expressed as affine AddRec expressions by
631 /// ScalarEvolution, we will generate run-time checks by emitting a
632 /// SCEVUnionPredicate.
633 ///
634 /// Checks for both memory dependences and the SCEV predicates contained in the
635 /// PSE must be emitted in order for the results of this analysis to be valid.
636 class LoopAccessInfo {
637 public:
638   LoopAccessInfo(Loop *L, ScalarEvolution *SE, const TargetTransformInfo *TTI,
639                  const TargetLibraryInfo *TLI, AAResults *AA, DominatorTree *DT,
640                  LoopInfo *LI);
641 
642   /// Return true we can analyze the memory accesses in the loop and there are
643   /// no memory dependence cycles. Note that for dependences between loads &
644   /// stores with uniform addresses,
645   /// hasStoreStoreDependenceInvolvingLoopInvariantAddress and
646   /// hasLoadStoreDependenceInvolvingLoopInvariantAddress also need to be
647   /// checked.
648   bool canVectorizeMemory() const { return CanVecMem; }
649 
650   /// Return true if there is a convergent operation in the loop. There may
651   /// still be reported runtime pointer checks that would be required, but it is
652   /// not legal to insert them.
653   bool hasConvergentOp() const { return HasConvergentOp; }
654 
655   const RuntimePointerChecking *getRuntimePointerChecking() const {
656     return PtrRtChecking.get();
657   }
658 
659   /// Number of memchecks required to prove independence of otherwise
660   /// may-alias pointers.
661   unsigned getNumRuntimePointerChecks() const {
662     return PtrRtChecking->getNumberOfChecks();
663   }
664 
665   /// Return true if the block BB needs to be predicated in order for the loop
666   /// to be vectorized.
667   static bool blockNeedsPredication(BasicBlock *BB, Loop *TheLoop,
668                                     DominatorTree *DT);
669 
670   /// Returns true if value \p V is loop invariant.
671   bool isInvariant(Value *V) const;
672 
673   unsigned getNumStores() const { return NumStores; }
674   unsigned getNumLoads() const { return NumLoads;}
675 
676   /// The diagnostics report generated for the analysis.  E.g. why we
677   /// couldn't analyze the loop.
678   const OptimizationRemarkAnalysis *getReport() const { return Report.get(); }
679 
680   /// the Memory Dependence Checker which can determine the
681   /// loop-independent and loop-carried dependences between memory accesses.
682   const MemoryDepChecker &getDepChecker() const { return *DepChecker; }
683 
684   /// Return the list of instructions that use \p Ptr to read or write
685   /// memory.
686   SmallVector<Instruction *, 4> getInstructionsForAccess(Value *Ptr,
687                                                          bool isWrite) const {
688     return DepChecker->getInstructionsForAccess(Ptr, isWrite);
689   }
690 
691   /// If an access has a symbolic strides, this maps the pointer value to
692   /// the stride symbol.
693   const DenseMap<Value *, const SCEV *> &getSymbolicStrides() const {
694     return SymbolicStrides;
695   }
696 
697   /// Print the information about the memory accesses in the loop.
698   void print(raw_ostream &OS, unsigned Depth = 0) const;
699 
700   /// Return true if the loop has memory dependence involving two stores to an
701   /// invariant address, else return false.
702   bool hasStoreStoreDependenceInvolvingLoopInvariantAddress() const {
703     return HasStoreStoreDependenceInvolvingLoopInvariantAddress;
704   }
705 
706   /// Return true if the loop has memory dependence involving a load and a store
707   /// to an invariant address, else return false.
708   bool hasLoadStoreDependenceInvolvingLoopInvariantAddress() const {
709     return HasLoadStoreDependenceInvolvingLoopInvariantAddress;
710   }
711 
712   /// Return the list of stores to invariant addresses.
713   ArrayRef<StoreInst *> getStoresToInvariantAddresses() const {
714     return StoresToInvariantAddresses;
715   }
716 
717   /// Used to add runtime SCEV checks. Simplifies SCEV expressions and converts
718   /// them to a more usable form.  All SCEV expressions during the analysis
719   /// should be re-written (and therefore simplified) according to PSE.
720   /// A user of LoopAccessAnalysis will need to emit the runtime checks
721   /// associated with this predicate.
722   const PredicatedScalarEvolution &getPSE() const { return *PSE; }
723 
724 private:
725   /// Analyze the loop. Returns true if all memory access in the loop can be
726   /// vectorized.
727   bool analyzeLoop(AAResults *AA, const LoopInfo *LI,
728                    const TargetLibraryInfo *TLI, DominatorTree *DT);
729 
730   /// Check if the structure of the loop allows it to be analyzed by this
731   /// pass.
732   bool canAnalyzeLoop();
733 
734   /// Save the analysis remark.
735   ///
736   /// LAA does not directly emits the remarks.  Instead it stores it which the
737   /// client can retrieve and presents as its own analysis
738   /// (e.g. -Rpass-analysis=loop-vectorize).
739   OptimizationRemarkAnalysis &
740   recordAnalysis(StringRef RemarkName, const Instruction *Instr = nullptr);
741 
742   /// Collect memory access with loop invariant strides.
743   ///
744   /// Looks for accesses like "a[i * StrideA]" where "StrideA" is loop
745   /// invariant.
746   void collectStridedAccess(Value *LoadOrStoreInst);
747 
748   // Emits the first unsafe memory dependence in a loop.
749   // Emits nothing if there are no unsafe dependences
750   // or if the dependences were not recorded.
751   void emitUnsafeDependenceRemark();
752 
753   std::unique_ptr<PredicatedScalarEvolution> PSE;
754 
755   /// We need to check that all of the pointers in this list are disjoint
756   /// at runtime. Using std::unique_ptr to make using move ctor simpler.
757   std::unique_ptr<RuntimePointerChecking> PtrRtChecking;
758 
759   /// the Memory Dependence Checker which can determine the
760   /// loop-independent and loop-carried dependences between memory accesses.
761   std::unique_ptr<MemoryDepChecker> DepChecker;
762 
763   Loop *TheLoop;
764 
765   unsigned NumLoads = 0;
766   unsigned NumStores = 0;
767 
768   /// Cache the result of analyzeLoop.
769   bool CanVecMem = false;
770   bool HasConvergentOp = false;
771 
772   /// Indicator that there are two non vectorizable stores to the same uniform
773   /// address.
774   bool HasStoreStoreDependenceInvolvingLoopInvariantAddress = false;
775   /// Indicator that there is non vectorizable load and store to the same
776   /// uniform address.
777   bool HasLoadStoreDependenceInvolvingLoopInvariantAddress = false;
778 
779   /// List of stores to invariant addresses.
780   SmallVector<StoreInst *> StoresToInvariantAddresses;
781 
782   /// The diagnostics report generated for the analysis.  E.g. why we
783   /// couldn't analyze the loop.
784   std::unique_ptr<OptimizationRemarkAnalysis> Report;
785 
786   /// If an access has a symbolic strides, this maps the pointer value to
787   /// the stride symbol.
788   DenseMap<Value *, const SCEV *> SymbolicStrides;
789 };
790 
791 /// Return the SCEV corresponding to a pointer with the symbolic stride
792 /// replaced with constant one, assuming the SCEV predicate associated with
793 /// \p PSE is true.
794 ///
795 /// If necessary this method will version the stride of the pointer according
796 /// to \p PtrToStride and therefore add further predicates to \p PSE.
797 ///
798 /// \p PtrToStride provides the mapping between the pointer value and its
799 /// stride as collected by LoopVectorizationLegality::collectStridedAccess.
800 const SCEV *
801 replaceSymbolicStrideSCEV(PredicatedScalarEvolution &PSE,
802                           const DenseMap<Value *, const SCEV *> &PtrToStride,
803                           Value *Ptr);
804 
805 /// If the pointer has a constant stride return it in units of the access type
806 /// size. If the pointer is loop-invariant, return 0. Otherwise return
807 /// std::nullopt.
808 ///
809 /// Ensure that it does not wrap in the address space, assuming the predicate
810 /// associated with \p PSE is true.
811 ///
812 /// If necessary this method will version the stride of the pointer according
813 /// to \p PtrToStride and therefore add further predicates to \p PSE.
814 /// The \p Assume parameter indicates if we are allowed to make additional
815 /// run-time assumptions.
816 ///
817 /// Note that the analysis results are defined if-and-only-if the original
818 /// memory access was defined.  If that access was dead, or UB, then the
819 /// result of this function is undefined.
820 std::optional<int64_t>
821 getPtrStride(PredicatedScalarEvolution &PSE, Type *AccessTy, Value *Ptr,
822              const Loop *Lp,
823              const DenseMap<Value *, const SCEV *> &StridesMap = DenseMap<Value *, const SCEV *>(),
824              bool Assume = false, bool ShouldCheckWrap = true);
825 
826 /// Returns the distance between the pointers \p PtrA and \p PtrB iff they are
827 /// compatible and it is possible to calculate the distance between them. This
828 /// is a simple API that does not depend on the analysis pass.
829 /// \param StrictCheck Ensure that the calculated distance matches the
830 /// type-based one after all the bitcasts removal in the provided pointers.
831 std::optional<int> getPointersDiff(Type *ElemTyA, Value *PtrA, Type *ElemTyB,
832                                    Value *PtrB, const DataLayout &DL,
833                                    ScalarEvolution &SE,
834                                    bool StrictCheck = false,
835                                    bool CheckType = true);
836 
837 /// Attempt to sort the pointers in \p VL and return the sorted indices
838 /// in \p SortedIndices, if reordering is required.
839 ///
840 /// Returns 'true' if sorting is legal, otherwise returns 'false'.
841 ///
842 /// For example, for a given \p VL of memory accesses in program order, a[i+4],
843 /// a[i+0], a[i+1] and a[i+7], this function will sort the \p VL and save the
844 /// sorted indices in \p SortedIndices as a[i+0], a[i+1], a[i+4], a[i+7] and
845 /// saves the mask for actual memory accesses in program order in
846 /// \p SortedIndices as <1,2,0,3>
847 bool sortPtrAccesses(ArrayRef<Value *> VL, Type *ElemTy, const DataLayout &DL,
848                      ScalarEvolution &SE,
849                      SmallVectorImpl<unsigned> &SortedIndices);
850 
851 /// Returns true if the memory operations \p A and \p B are consecutive.
852 /// This is a simple API that does not depend on the analysis pass.
853 bool isConsecutiveAccess(Value *A, Value *B, const DataLayout &DL,
854                          ScalarEvolution &SE, bool CheckType = true);
855 
856 /// Calculate Start and End points of memory access.
857 /// Let's assume A is the first access and B is a memory access on N-th loop
858 /// iteration. Then B is calculated as:
859 ///   B = A + Step*N .
860 /// Step value may be positive or negative.
861 /// N is a calculated back-edge taken count:
862 ///     N = (TripCount > 0) ? RoundDown(TripCount -1 , VF) : 0
863 /// Start and End points are calculated in the following way:
864 /// Start = UMIN(A, B) ; End = UMAX(A, B) + SizeOfElt,
865 /// where SizeOfElt is the size of single memory access in bytes.
866 ///
867 /// There is no conflict when the intervals are disjoint:
868 /// NoConflict = (P2.Start >= P1.End) || (P1.Start >= P2.End)
869 std::pair<const SCEV *, const SCEV *> getStartAndEndForAccess(
870     const Loop *Lp, const SCEV *PtrExpr, Type *AccessTy, const SCEV *MaxBECount,
871     ScalarEvolution *SE,
872     DenseMap<std::pair<const SCEV *, Type *>,
873              std::pair<const SCEV *, const SCEV *>> *PointerBounds);
874 
875 class LoopAccessInfoManager {
876   /// The cache.
877   DenseMap<Loop *, std::unique_ptr<LoopAccessInfo>> LoopAccessInfoMap;
878 
879   // The used analysis passes.
880   ScalarEvolution &SE;
881   AAResults &AA;
882   DominatorTree &DT;
883   LoopInfo &LI;
884   TargetTransformInfo *TTI;
885   const TargetLibraryInfo *TLI = nullptr;
886 
887 public:
888   LoopAccessInfoManager(ScalarEvolution &SE, AAResults &AA, DominatorTree &DT,
889                         LoopInfo &LI, TargetTransformInfo *TTI,
890                         const TargetLibraryInfo *TLI)
891       : SE(SE), AA(AA), DT(DT), LI(LI), TTI(TTI), TLI(TLI) {}
892 
893   const LoopAccessInfo &getInfo(Loop &L);
894 
895   void clear();
896 
897   bool invalidate(Function &F, const PreservedAnalyses &PA,
898                   FunctionAnalysisManager::Invalidator &Inv);
899 };
900 
901 /// This analysis provides dependence information for the memory
902 /// accesses of a loop.
903 ///
904 /// It runs the analysis for a loop on demand.  This can be initiated by
905 /// querying the loop access info via AM.getResult<LoopAccessAnalysis>.
906 /// getResult return a LoopAccessInfo object.  See this class for the
907 /// specifics of what information is provided.
908 class LoopAccessAnalysis
909     : public AnalysisInfoMixin<LoopAccessAnalysis> {
910   friend AnalysisInfoMixin<LoopAccessAnalysis>;
911   static AnalysisKey Key;
912 
913 public:
914   typedef LoopAccessInfoManager Result;
915 
916   Result run(Function &F, FunctionAnalysisManager &AM);
917 };
918 
919 inline Instruction *MemoryDepChecker::Dependence::getSource(
920     const MemoryDepChecker &DepChecker) const {
921   return DepChecker.getMemoryInstructions()[Source];
922 }
923 
924 inline Instruction *MemoryDepChecker::Dependence::getDestination(
925     const MemoryDepChecker &DepChecker) const {
926   return DepChecker.getMemoryInstructions()[Destination];
927 }
928 
929 } // End llvm namespace
930 
931 #endif
932