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 VectorizationReport {
41 const Instruction *Instr;
44 VectorizationReport(const Instruction *I = nullptr)
45 : Message("loop not vectorized: "), Instr(I) {}
47 template <typename A> VectorizationReport &operator<<(const A &Value) {
48 raw_string_ostream Out(Message);
53 const Instruction *getInstr() const { return Instr; }
55 std::string &str() { return Message; }
56 const std::string &str() const { return Message; }
57 operator Twine() { return Message; }
59 /// \brief Emit an analysis note for \p PassName with the debug location from
60 /// the instruction in \p Message if available. Otherwise use the location of
62 static void emitAnalysis(const VectorizationReport &Message,
63 const Function *TheFunction,
65 const char *PassName);
68 /// \brief Collection of parameters shared beetween the Loop Vectorizer and the
69 /// Loop Access Analysis.
70 struct VectorizerParams {
71 /// \brief Maximum SIMD width.
72 static const unsigned MaxVectorWidth;
74 /// \brief VF as overridden by the user.
75 static unsigned VectorizationFactor;
76 /// \brief Interleave factor as overridden by the user.
77 static unsigned VectorizationInterleave;
79 /// \\brief When performing memory disambiguation checks at runtime do not
80 /// make more than this number of comparisons.
81 static const unsigned RuntimeMemoryCheckThreshold;
84 /// \brief Drive the analysis of memory accesses in the loop
86 /// This class is responsible for analyzing the memory accesses of a loop. It
87 /// collects the accesses and then its main helper the AccessAnalysis class
88 /// finds and categorizes the dependences in buildDependenceSets.
90 /// For memory dependences that can be analyzed at compile time, it determines
91 /// whether the dependence is part of cycle inhibiting vectorization. This work
92 /// is delegated to the MemoryDepChecker class.
94 /// For memory dependences that cannot be determined at compile time, it
95 /// generates run-time checks to prove independence. This is done by
96 /// AccessAnalysis::canCheckPtrAtRT and the checks are maintained by the
97 /// RuntimePointerCheck class.
98 class LoopAccessInfo {
100 /// This struct holds information about the memory runtime legality check that
101 /// a group of pointers do not overlap.
102 struct RuntimePointerCheck {
103 RuntimePointerCheck() : Need(false) {}
105 /// Reset the state of the pointer runtime information.
112 DependencySetId.clear();
116 /// Insert a pointer and calculate the start and end SCEVs.
117 void insert(ScalarEvolution *SE, Loop *Lp, Value *Ptr, bool WritePtr,
118 unsigned DepSetId, unsigned ASId, ValueToValueMap &Strides);
120 /// \brief Decide whether we need to issue a run-time check for pointer at
121 /// index \p I and \p J to prove their independence.
122 bool needsChecking(unsigned I, unsigned J) const;
124 /// This flag indicates if we need to add the runtime check.
126 /// Holds the pointers that we need to check.
127 SmallVector<TrackingVH<Value>, 2> Pointers;
128 /// Holds the pointer value at the beginning of the loop.
129 SmallVector<const SCEV*, 2> Starts;
130 /// Holds the pointer value at the end of the loop.
131 SmallVector<const SCEV*, 2> Ends;
132 /// Holds the information if this pointer is used for writing to memory.
133 SmallVector<bool, 2> IsWritePtr;
134 /// Holds the id of the set of pointers that could be dependent because of a
135 /// shared underlying object.
136 SmallVector<unsigned, 2> DependencySetId;
137 /// Holds the id of the disjoint alias set to which this pointer belongs.
138 SmallVector<unsigned, 2> AliasSetId;
141 LoopAccessInfo(Loop *L, ScalarEvolution *SE, const DataLayout *DL,
142 const TargetLibraryInfo *TLI, AliasAnalysis *AA,
143 DominatorTree *DT, ValueToValueMap &Strides);
145 /// Return true we can analyze the memory accesses in the loop and there are
146 /// no memory dependence cycles.
147 bool canVectorizeMemory() { return CanVecMem; }
149 RuntimePointerCheck *getRuntimePointerCheck() { return &PtrRtCheck; }
151 /// Return true if the block BB needs to be predicated in order for the loop
152 /// to be vectorized.
153 static bool blockNeedsPredication(BasicBlock *BB, Loop *TheLoop,
156 /// Returns true if the value V is uniform within the loop.
157 bool isUniform(Value *V);
159 unsigned getMaxSafeDepDistBytes() const { return MaxSafeDepDistBytes; }
160 unsigned getNumStores() const { return NumStores; }
161 unsigned getNumLoads() const { return NumLoads;}
163 /// \brief Add code that checks at runtime if the accessed arrays overlap.
165 /// Returns a pair of instructions where the first element is the first
166 /// instruction generated in possibly a sequence of instructions and the
167 /// second value is the final comparator value or NULL if no check is needed.
168 std::pair<Instruction *, Instruction *> addRuntimeCheck(Instruction *Loc);
170 /// \brief The diagnostics report generated for the analysis. E.g. why we
171 /// couldn't analyze the loop.
172 Optional<VectorizationReport> &getReport() { return Report; }
174 /// \brief Used to ensure that if the analysis was run with speculating the
175 /// value of symbolic strides, the client queries it with the same assumption.
176 /// Only used in DEBUG build but we don't want NDEBUG-depedent ABI.
177 unsigned NumSymbolicStrides;
180 /// \brief Analyze the loop. Substitute symbolic strides using Strides.
181 void analyzeLoop(ValueToValueMap &Strides);
183 /// \brief Check if the structure of the loop allows it to be analyzed by this
185 bool canAnalyzeLoop();
187 void emitAnalysis(VectorizationReport &Message);
189 /// We need to check that all of the pointers in this list are disjoint
191 RuntimePointerCheck PtrRtCheck;
194 const DataLayout *DL;
195 const TargetLibraryInfo *TLI;
202 unsigned MaxSafeDepDistBytes;
204 /// \brief Cache the result of analyzeLoop.
207 /// \brief The diagnostics report generated for the analysis. E.g. why we
208 /// couldn't analyze the loop.
209 Optional<VectorizationReport> Report;
212 Value *stripIntegerCast(Value *V);
214 ///\brief Return the SCEV corresponding to a pointer with the symbolic stride
215 ///replaced with constant one.
217 /// If \p OrigPtr is not null, use it to look up the stride value instead of \p
218 /// Ptr. \p PtrToStride provides the mapping between the pointer value and its
219 /// stride as collected by LoopVectorizationLegality::collectStridedAccess.
220 const SCEV *replaceSymbolicStrideSCEV(ScalarEvolution *SE,
221 ValueToValueMap &PtrToStride,
222 Value *Ptr, Value *OrigPtr = nullptr);
224 /// \brief This analysis provides dependence information for the memory accesses
227 /// It runs the analysis for a loop on demand. This can be initiated by
228 /// querying the loop access info via LAA::getInfo. getInfo return a
229 /// LoopAccessInfo object. See this class for the specifics of what information
231 class LoopAccessAnalysis : public FunctionPass {
235 LoopAccessAnalysis() : FunctionPass(ID) {
236 initializeLoopAccessAnalysisPass(*PassRegistry::getPassRegistry());
239 bool runOnFunction(Function &F) override;
241 void getAnalysisUsage(AnalysisUsage &AU) const override;
243 /// \brief Query the result of the loop access information for the loop \p L.
245 /// If the client speculates (and then issues run-time checks) for the values
246 /// of symbolic strides, \p Strides provides the mapping (see
247 /// replaceSymbolicStrideSCEV). If there is no cached result available run
249 LoopAccessInfo &getInfo(Loop *L, ValueToValueMap &Strides);
251 void releaseMemory() override {
252 // Invalidate the cache when the pass is freed.
253 LoopAccessInfoMap.clear();
257 /// \brief The cache.
258 DenseMap<Loop *, std::unique_ptr<LoopAccessInfo>> LoopAccessInfoMap;
260 // The used analysis passes.
262 const DataLayout *DL;
263 const TargetLibraryInfo *TLI;
267 } // End llvm namespace