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