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