1 //===- llvm/Analysis/LoopAccessAnalysis.h -----------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interface for the loop memory dependence framework that
11 // was originally developed for the Loop Vectorizer.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_ANALYSIS_LOOPACCESSANALYSIS_H
16 #define LLVM_ANALYSIS_LOOPACCESSANALYSIS_H
18 #include "llvm/ADT/EquivalenceClasses.h"
19 #include "llvm/ADT/Optional.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/Analysis/AliasAnalysis.h"
22 #include "llvm/Analysis/AliasSetTracker.h"
23 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
24 #include "llvm/IR/ValueHandle.h"
25 #include "llvm/Pass.h"
26 #include "llvm/Support/raw_ostream.h"
33 class ScalarEvolution;
37 /// Optimization analysis message produced during vectorization. Messages inform
38 /// the user why vectorization did not occur.
39 class LoopAccessReport {
41 const Instruction *Instr;
44 LoopAccessReport(const Twine &Message, const Instruction *I)
45 : Message(Message.str()), Instr(I) {}
48 LoopAccessReport(const Instruction *I = nullptr) : Instr(I) {}
50 template <typename A> LoopAccessReport &operator<<(const A &Value) {
51 raw_string_ostream Out(Message);
56 const Instruction *getInstr() const { return Instr; }
58 std::string &str() { return Message; }
59 const std::string &str() const { return Message; }
60 operator Twine() { return Message; }
62 /// \brief Emit an analysis note for \p PassName with the debug location from
63 /// the instruction in \p Message if available. Otherwise use the location of
65 static void emitAnalysis(const LoopAccessReport &Message,
66 const Function *TheFunction,
68 const char *PassName);
71 /// \brief Collection of parameters shared beetween the Loop Vectorizer and the
72 /// Loop Access Analysis.
73 struct VectorizerParams {
74 /// \brief Maximum SIMD width.
75 static const unsigned MaxVectorWidth;
77 /// \brief VF as overridden by the user.
78 static unsigned VectorizationFactor;
79 /// \brief Interleave factor as overridden by the user.
80 static unsigned VectorizationInterleave;
81 /// \brief True if force-vector-interleave was specified by the user.
82 static bool isInterleaveForced();
84 /// \\brief When performing memory disambiguation checks at runtime do not
85 /// make more than this number of comparisons.
86 static unsigned RuntimeMemoryCheckThreshold;
89 /// \brief Checks memory dependences among accesses to the same underlying
90 /// object to determine whether there vectorization is legal or not (and at
91 /// which vectorization factor).
93 /// Note: This class will compute a conservative dependence for access to
94 /// different underlying pointers. Clients, such as the loop vectorizer, will
95 /// sometimes deal these potential dependencies by emitting runtime checks.
97 /// We use the ScalarEvolution framework to symbolically evalutate access
98 /// functions pairs. Since we currently don't restructure the loop we can rely
99 /// on the program order of memory accesses to determine their safety.
100 /// At the moment we will only deem accesses as safe for:
101 /// * A negative constant distance assuming program order.
103 /// Safe: tmp = a[i + 1]; OR a[i + 1] = x;
104 /// a[i] = tmp; y = a[i];
106 /// The latter case is safe because later checks guarantuee that there can't
107 /// be a cycle through a phi node (that is, we check that "x" and "y" is not
108 /// the same variable: a header phi can only be an induction or a reduction, a
109 /// reduction can't have a memory sink, an induction can't have a memory
110 /// source). This is important and must not be violated (or we have to
111 /// resort to checking for cycles through memory).
113 /// * A positive constant distance assuming program order that is bigger
114 /// than the biggest memory access.
116 /// tmp = a[i] OR b[i] = x
117 /// a[i+2] = tmp y = b[i+2];
119 /// Safe distance: 2 x sizeof(a[0]), and 2 x sizeof(b[0]), respectively.
121 /// * Zero distances and all accesses have the same size.
123 class MemoryDepChecker {
125 typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
126 typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
127 /// \brief Set of potential dependent memory accesses.
128 typedef EquivalenceClasses<MemAccessInfo> DepCandidates;
130 /// \brief Dependece between memory access instructions.
132 /// \brief The type of the dependence.
136 // We couldn't determine the direction or the distance.
138 // Lexically forward.
140 // Forward, but if vectorized, is likely to prevent store-to-load
142 ForwardButPreventsForwarding,
143 // Lexically backward.
145 // Backward, but the distance allows a vectorization factor of
146 // MaxSafeDepDistBytes.
147 BackwardVectorizable,
148 // Same, but may prevent store-to-load forwarding.
149 BackwardVectorizableButPreventsForwarding
152 /// \brief String version of the types.
153 static const char *DepName[];
155 /// \brief Index of the source of the dependence in the InstMap vector.
157 /// \brief Index of the destination of the dependence in the InstMap vector.
158 unsigned Destination;
159 /// \brief The type of the dependence.
162 Dependence(unsigned Source, unsigned Destination, DepType Type)
163 : Source(Source), Destination(Destination), Type(Type) {}
165 /// \brief Dependence types that don't prevent vectorization.
166 static bool isSafeForVectorization(DepType Type);
168 /// \brief Dependence types that can be queried from the analysis.
169 static bool isInterestingDependence(DepType Type);
171 /// \brief Lexically backward dependence types.
172 bool isPossiblyBackward() const;
174 /// \brief Print the dependence. \p Instr is used to map the instruction
175 /// indices to instructions.
176 void print(raw_ostream &OS, unsigned Depth,
177 const SmallVectorImpl<Instruction *> &Instrs) const;
180 MemoryDepChecker(ScalarEvolution *Se, const Loop *L)
181 : SE(Se), InnermostLoop(L), AccessIdx(0),
182 ShouldRetryWithRuntimeCheck(false), SafeForVectorization(true),
183 RecordInterestingDependences(true) {}
185 /// \brief Register the location (instructions are given increasing numbers)
186 /// of a write access.
187 void addAccess(StoreInst *SI) {
188 Value *Ptr = SI->getPointerOperand();
189 Accesses[MemAccessInfo(Ptr, true)].push_back(AccessIdx);
190 InstMap.push_back(SI);
194 /// \brief Register the location (instructions are given increasing numbers)
195 /// of a write access.
196 void addAccess(LoadInst *LI) {
197 Value *Ptr = LI->getPointerOperand();
198 Accesses[MemAccessInfo(Ptr, false)].push_back(AccessIdx);
199 InstMap.push_back(LI);
203 /// \brief Check whether the dependencies between the accesses are safe.
205 /// Only checks sets with elements in \p CheckDeps.
206 bool areDepsSafe(DepCandidates &AccessSets, MemAccessInfoSet &CheckDeps,
207 const ValueToValueMap &Strides);
209 /// \brief No memory dependence was encountered that would inhibit
211 bool isSafeForVectorization() const { return SafeForVectorization; }
213 /// \brief The maximum number of bytes of a vector register we can vectorize
214 /// the accesses safely with.
215 unsigned getMaxSafeDepDistBytes() { return MaxSafeDepDistBytes; }
217 /// \brief In same cases when the dependency check fails we can still
218 /// vectorize the loop with a dynamic array access check.
219 bool shouldRetryWithRuntimeCheck() { return ShouldRetryWithRuntimeCheck; }
221 /// \brief Returns the interesting dependences. If null is returned we
222 /// exceeded the MaxInterestingDependence threshold and this information is
224 const SmallVectorImpl<Dependence> *getInterestingDependences() const {
225 return RecordInterestingDependences ? &InterestingDependences : nullptr;
228 void clearInterestingDependences() { InterestingDependences.clear(); }
230 /// \brief The vector of memory access instructions. The indices are used as
231 /// instruction identifiers in the Dependence class.
232 const SmallVectorImpl<Instruction *> &getMemoryInstructions() const {
236 /// \brief Find the set of instructions that read or write via \p Ptr.
237 SmallVector<Instruction *, 4> getInstructionsForAccess(Value *Ptr,
242 const Loop *InnermostLoop;
244 /// \brief Maps access locations (ptr, read/write) to program order.
245 DenseMap<MemAccessInfo, std::vector<unsigned> > Accesses;
247 /// \brief Memory access instructions in program order.
248 SmallVector<Instruction *, 16> InstMap;
250 /// \brief The program order index to be used for the next instruction.
253 // We can access this many bytes in parallel safely.
254 unsigned MaxSafeDepDistBytes;
256 /// \brief If we see a non-constant dependence distance we can still try to
257 /// vectorize this loop with runtime checks.
258 bool ShouldRetryWithRuntimeCheck;
260 /// \brief No memory dependence was encountered that would inhibit
262 bool SafeForVectorization;
264 //// \brief True if InterestingDependences reflects the dependences in the
265 //// loop. If false we exceeded MaxInterestingDependence and
266 //// InterestingDependences is invalid.
267 bool RecordInterestingDependences;
269 /// \brief Interesting memory dependences collected during the analysis as
270 /// defined by isInterestingDependence. Only valid if
271 /// RecordInterestingDependences is true.
272 SmallVector<Dependence, 8> InterestingDependences;
274 /// \brief Check whether there is a plausible dependence between the two
277 /// Access \p A must happen before \p B in program order. The two indices
278 /// identify the index into the program order map.
280 /// This function checks whether there is a plausible dependence (or the
281 /// absence of such can't be proved) between the two accesses. If there is a
282 /// plausible dependence but the dependence distance is bigger than one
283 /// element access it records this distance in \p MaxSafeDepDistBytes (if this
284 /// distance is smaller than any other distance encountered so far).
285 /// Otherwise, this function returns true signaling a possible dependence.
286 Dependence::DepType isDependent(const MemAccessInfo &A, unsigned AIdx,
287 const MemAccessInfo &B, unsigned BIdx,
288 const ValueToValueMap &Strides);
290 /// \brief Check whether the data dependence could prevent store-load
292 bool couldPreventStoreLoadForward(unsigned Distance, unsigned TypeByteSize);
295 /// \brief Holds information about the memory runtime legality checks to verify
296 /// that a group of pointers do not overlap.
297 class RuntimePointerChecking {
300 /// Holds the pointer value that we need to check.
301 TrackingVH<Value> PointerValue;
302 /// Holds the pointer value at the beginning of the loop.
304 /// Holds the pointer value at the end of the loop.
306 /// Holds the information if this pointer is used for writing to memory.
308 /// Holds the id of the set of pointers that could be dependent because of a
309 /// shared underlying object.
310 unsigned DependencySetId;
311 /// Holds the id of the disjoint alias set to which this pointer belongs.
313 /// SCEV for the access.
316 PointerInfo(Value *PointerValue, const SCEV *Start, const SCEV *End,
317 bool IsWritePtr, unsigned DependencySetId, unsigned AliasSetId,
319 : PointerValue(PointerValue), Start(Start), End(End),
320 IsWritePtr(IsWritePtr), DependencySetId(DependencySetId),
321 AliasSetId(AliasSetId), Expr(Expr) {}
324 RuntimePointerChecking(ScalarEvolution *SE) : Need(false), SE(SE) {}
326 /// Reset the state of the pointer runtime information.
333 /// Insert a pointer and calculate the start and end SCEVs.
334 void insert(Loop *Lp, Value *Ptr, bool WritePtr, unsigned DepSetId,
335 unsigned ASId, const ValueToValueMap &Strides);
337 /// \brief No run-time memory checking is necessary.
338 bool empty() const { return Pointers.empty(); }
340 /// A grouping of pointers. A single memcheck is required between
342 struct CheckingPtrGroup {
343 /// \brief Create a new pointer checking group containing a single
344 /// pointer, with index \p Index in RtCheck.
345 CheckingPtrGroup(unsigned Index, RuntimePointerChecking &RtCheck)
346 : RtCheck(RtCheck), High(RtCheck.Pointers[Index].End),
347 Low(RtCheck.Pointers[Index].Start) {
348 Members.push_back(Index);
351 /// \brief Tries to add the pointer recorded in RtCheck at index
352 /// \p Index to this pointer checking group. We can only add a pointer
353 /// to a checking group if we will still be able to get
354 /// the upper and lower bounds of the check. Returns true in case
355 /// of success, false otherwise.
356 bool addPointer(unsigned Index);
358 /// Constitutes the context of this pointer checking group. For each
359 /// pointer that is a member of this group we will retain the index
360 /// at which it appears in RtCheck.
361 RuntimePointerChecking &RtCheck;
362 /// The SCEV expression which represents the upper bound of all the
363 /// pointers in this group.
365 /// The SCEV expression which represents the lower bound of all the
366 /// pointers in this group.
368 /// Indices of all the pointers that constitute this grouping.
369 SmallVector<unsigned, 2> Members;
372 /// \brief A memcheck which made up of a pair of grouped pointers.
374 /// These *have* to be const for now, since checks are generated from
375 /// CheckingPtrGroups in LAI::addRuntimeChecks which is a const member
376 /// function. FIXME: once check-generation is moved inside this class (after
377 /// the PtrPartition hack is removed), we could drop const.
378 typedef std::pair<const CheckingPtrGroup *, const CheckingPtrGroup *>
381 /// \brief Generate the checks and store it. This also performs the grouping
382 /// of pointers to reduce the number of memchecks necessary.
383 void generateChecks(MemoryDepChecker::DepCandidates &DepCands,
384 bool UseDependencies);
386 /// \brief Returns the checks that generateChecks created.
387 const SmallVector<PointerCheck, 4> &getChecks() const { return Checks; }
389 /// \brief Decide if we need to add a check between two groups of pointers,
390 /// according to needsChecking.
391 bool needsChecking(const CheckingPtrGroup &M,
392 const CheckingPtrGroup &N) const;
394 /// \brief Returns the number of run-time checks required according to
396 unsigned getNumberOfChecks() const { return Checks.size(); }
398 /// \brief Print the list run-time memory checks necessary.
399 void print(raw_ostream &OS, unsigned Depth = 0) const;
402 void printChecks(raw_ostream &OS, const SmallVectorImpl<PointerCheck> &Checks,
403 unsigned Depth = 0) const;
405 /// This flag indicates if we need to add the runtime check.
408 /// Information about the pointers that may require checking.
409 SmallVector<PointerInfo, 2> Pointers;
411 /// Holds a partitioning of pointers into "check groups".
412 SmallVector<CheckingPtrGroup, 2> CheckingGroups;
414 /// \brief Check if pointers are in the same partition
416 /// \p PtrToPartition contains the partition number for pointers (-1 if the
417 /// pointer belongs to multiple partitions).
419 arePointersInSamePartition(const SmallVectorImpl<int> &PtrToPartition,
420 unsigned PtrIdx1, unsigned PtrIdx2);
422 /// \brief Decide whether we need to issue a run-time check for pointer at
423 /// index \p I and \p J to prove their independence.
424 bool needsChecking(unsigned I, unsigned J) const;
427 /// \brief Groups pointers such that a single memcheck is required
428 /// between two different groups. This will clear the CheckingGroups vector
429 /// and re-compute it. We will only group dependecies if \p UseDependencies
430 /// is true, otherwise we will create a separate group for each pointer.
431 void groupChecks(MemoryDepChecker::DepCandidates &DepCands,
432 bool UseDependencies);
434 /// Generate the checks and return them.
435 SmallVector<PointerCheck, 4>
436 generateChecks() const;
438 /// Holds a pointer to the ScalarEvolution analysis.
441 /// \brief Set of run-time checks required to establish independence of
442 /// otherwise may-aliasing pointers in the loop.
443 SmallVector<PointerCheck, 4> Checks;
446 /// \brief Drive the analysis of memory accesses in the loop
448 /// This class is responsible for analyzing the memory accesses of a loop. It
449 /// collects the accesses and then its main helper the AccessAnalysis class
450 /// finds and categorizes the dependences in buildDependenceSets.
452 /// For memory dependences that can be analyzed at compile time, it determines
453 /// whether the dependence is part of cycle inhibiting vectorization. This work
454 /// is delegated to the MemoryDepChecker class.
456 /// For memory dependences that cannot be determined at compile time, it
457 /// generates run-time checks to prove independence. This is done by
458 /// AccessAnalysis::canCheckPtrAtRT and the checks are maintained by the
459 /// RuntimePointerCheck class.
460 class LoopAccessInfo {
462 LoopAccessInfo(Loop *L, ScalarEvolution *SE, const DataLayout &DL,
463 const TargetLibraryInfo *TLI, AliasAnalysis *AA,
464 DominatorTree *DT, LoopInfo *LI,
465 const ValueToValueMap &Strides);
467 /// Return true we can analyze the memory accesses in the loop and there are
468 /// no memory dependence cycles.
469 bool canVectorizeMemory() const { return CanVecMem; }
471 const RuntimePointerChecking *getRuntimePointerChecking() const {
472 return &PtrRtChecking;
475 /// \brief Number of memchecks required to prove independence of otherwise
476 /// may-alias pointers.
477 unsigned getNumRuntimePointerChecks() const {
478 return PtrRtChecking.getNumberOfChecks();
481 /// Return true if the block BB needs to be predicated in order for the loop
482 /// to be vectorized.
483 static bool blockNeedsPredication(BasicBlock *BB, Loop *TheLoop,
486 /// Returns true if the value V is uniform within the loop.
487 bool isUniform(Value *V) const;
489 unsigned getMaxSafeDepDistBytes() const { return MaxSafeDepDistBytes; }
490 unsigned getNumStores() const { return NumStores; }
491 unsigned getNumLoads() const { return NumLoads;}
493 /// \brief Add code that checks at runtime if the accessed arrays overlap.
495 /// Returns a pair of instructions where the first element is the first
496 /// instruction generated in possibly a sequence of instructions and the
497 /// second value is the final comparator value or NULL if no check is needed.
498 std::pair<Instruction *, Instruction *>
499 addRuntimeChecks(Instruction *Loc) const;
501 /// \brief Generete the instructions for the checks in \p PointerChecks.
503 /// Returns a pair of instructions where the first element is the first
504 /// instruction generated in possibly a sequence of instructions and the
505 /// second value is the final comparator value or NULL if no check is needed.
506 std::pair<Instruction *, Instruction *>
507 addRuntimeChecks(Instruction *Loc,
508 const SmallVectorImpl<RuntimePointerChecking::PointerCheck>
509 &PointerChecks) const;
511 /// \brief The diagnostics report generated for the analysis. E.g. why we
512 /// couldn't analyze the loop.
513 const Optional<LoopAccessReport> &getReport() const { return Report; }
515 /// \brief the Memory Dependence Checker which can determine the
516 /// loop-independent and loop-carried dependences between memory accesses.
517 const MemoryDepChecker &getDepChecker() const { return DepChecker; }
519 /// \brief Return the list of instructions that use \p Ptr to read or write
521 SmallVector<Instruction *, 4> getInstructionsForAccess(Value *Ptr,
522 bool isWrite) const {
523 return DepChecker.getInstructionsForAccess(Ptr, isWrite);
526 /// \brief Print the information about the memory accesses in the loop.
527 void print(raw_ostream &OS, unsigned Depth = 0) const;
529 /// \brief Used to ensure that if the analysis was run with speculating the
530 /// value of symbolic strides, the client queries it with the same assumption.
531 /// Only used in DEBUG build but we don't want NDEBUG-dependent ABI.
532 unsigned NumSymbolicStrides;
534 /// \brief Checks existence of store to invariant address inside loop.
535 /// If the loop has any store to invariant address, then it returns true,
536 /// else returns false.
537 bool hasStoreToLoopInvariantAddress() const {
538 return StoreToLoopInvariantAddress;
542 /// \brief Analyze the loop. Substitute symbolic strides using Strides.
543 void analyzeLoop(const ValueToValueMap &Strides);
545 /// \brief Check if the structure of the loop allows it to be analyzed by this
547 bool canAnalyzeLoop();
549 void emitAnalysis(LoopAccessReport &Message);
551 /// We need to check that all of the pointers in this list are disjoint
553 RuntimePointerChecking PtrRtChecking;
555 /// \brief the Memory Dependence Checker which can determine the
556 /// loop-independent and loop-carried dependences between memory accesses.
557 MemoryDepChecker DepChecker;
561 const DataLayout &DL;
562 const TargetLibraryInfo *TLI;
570 unsigned MaxSafeDepDistBytes;
572 /// \brief Cache the result of analyzeLoop.
575 /// \brief Indicator for storing to uniform addresses.
576 /// If a loop has write to a loop invariant address then it should be true.
577 bool StoreToLoopInvariantAddress;
579 /// \brief The diagnostics report generated for the analysis. E.g. why we
580 /// couldn't analyze the loop.
581 Optional<LoopAccessReport> Report;
584 Value *stripIntegerCast(Value *V);
586 ///\brief Return the SCEV corresponding to a pointer with the symbolic stride
587 ///replaced with constant one.
589 /// If \p OrigPtr is not null, use it to look up the stride value instead of \p
590 /// Ptr. \p PtrToStride provides the mapping between the pointer value and its
591 /// stride as collected by LoopVectorizationLegality::collectStridedAccess.
592 const SCEV *replaceSymbolicStrideSCEV(ScalarEvolution *SE,
593 const ValueToValueMap &PtrToStride,
594 Value *Ptr, Value *OrigPtr = nullptr);
596 /// \brief Check the stride of the pointer and ensure that it does not wrap in
597 /// the address space.
598 int isStridedPtr(ScalarEvolution *SE, Value *Ptr, const Loop *Lp,
599 const ValueToValueMap &StridesMap);
601 /// \brief This analysis provides dependence information for the memory accesses
604 /// It runs the analysis for a loop on demand. This can be initiated by
605 /// querying the loop access info via LAA::getInfo. getInfo return a
606 /// LoopAccessInfo object. See this class for the specifics of what information
608 class LoopAccessAnalysis : public FunctionPass {
612 LoopAccessAnalysis() : FunctionPass(ID) {
613 initializeLoopAccessAnalysisPass(*PassRegistry::getPassRegistry());
616 bool runOnFunction(Function &F) override;
618 void getAnalysisUsage(AnalysisUsage &AU) const override;
620 /// \brief Query the result of the loop access information for the loop \p L.
622 /// If the client speculates (and then issues run-time checks) for the values
623 /// of symbolic strides, \p Strides provides the mapping (see
624 /// replaceSymbolicStrideSCEV). If there is no cached result available run
626 const LoopAccessInfo &getInfo(Loop *L, const ValueToValueMap &Strides);
628 void releaseMemory() override {
629 // Invalidate the cache when the pass is freed.
630 LoopAccessInfoMap.clear();
633 /// \brief Print the result of the analysis when invoked with -analyze.
634 void print(raw_ostream &OS, const Module *M = nullptr) const override;
637 /// \brief The cache.
638 DenseMap<Loop *, std::unique_ptr<LoopAccessInfo>> LoopAccessInfoMap;
640 // The used analysis passes.
642 const TargetLibraryInfo *TLI;
647 } // End llvm namespace