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