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