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 Drive the analysis of memory accesses in the loop
91 /// This class is responsible for analyzing the memory accesses of a loop. It
92 /// collects the accesses and then its main helper the AccessAnalysis class
93 /// finds and categorizes the dependences in buildDependenceSets.
95 /// For memory dependences that can be analyzed at compile time, it determines
96 /// whether the dependence is part of cycle inhibiting vectorization. This work
97 /// is delegated to the MemoryDepChecker class.
99 /// For memory dependences that cannot be determined at compile time, it
100 /// generates run-time checks to prove independence. This is done by
101 /// AccessAnalysis::canCheckPtrAtRT and the checks are maintained by the
102 /// RuntimePointerCheck class.
103 class LoopAccessInfo {
105 /// This struct holds information about the memory runtime legality check that
106 /// a group of pointers do not overlap.
107 struct RuntimePointerCheck {
108 RuntimePointerCheck() : Need(false) {}
110 /// Reset the state of the pointer runtime information.
117 DependencySetId.clear();
121 /// Insert a pointer and calculate the start and end SCEVs.
122 void insert(ScalarEvolution *SE, Loop *Lp, Value *Ptr, bool WritePtr,
123 unsigned DepSetId, unsigned ASId,
124 const ValueToValueMap &Strides);
126 /// \brief No run-time memory checking is necessary.
127 bool empty() const { return Pointers.empty(); }
129 /// \brief Decide whether we need to issue a run-time check for pointer at
130 /// index \p I and \p J to prove their independence.
131 bool needsChecking(unsigned I, unsigned J) const;
133 /// \brief Print the list run-time memory checks necessary.
134 void print(raw_ostream &OS, unsigned Depth = 0) const;
136 /// This flag indicates if we need to add the runtime check.
138 /// Holds the pointers that we need to check.
139 SmallVector<TrackingVH<Value>, 2> Pointers;
140 /// Holds the pointer value at the beginning of the loop.
141 SmallVector<const SCEV*, 2> Starts;
142 /// Holds the pointer value at the end of the loop.
143 SmallVector<const SCEV*, 2> Ends;
144 /// Holds the information if this pointer is used for writing to memory.
145 SmallVector<bool, 2> IsWritePtr;
146 /// Holds the id of the set of pointers that could be dependent because of a
147 /// shared underlying object.
148 SmallVector<unsigned, 2> DependencySetId;
149 /// Holds the id of the disjoint alias set to which this pointer belongs.
150 SmallVector<unsigned, 2> AliasSetId;
153 LoopAccessInfo(Loop *L, ScalarEvolution *SE, const DataLayout *DL,
154 const TargetLibraryInfo *TLI, AliasAnalysis *AA,
155 DominatorTree *DT, const ValueToValueMap &Strides);
157 /// Return true we can analyze the memory accesses in the loop and there are
158 /// no memory dependence cycles.
159 bool canVectorizeMemory() const { return CanVecMem; }
161 const RuntimePointerCheck *getRuntimePointerCheck() const {
165 /// Return true if the block BB needs to be predicated in order for the loop
166 /// to be vectorized.
167 static bool blockNeedsPredication(BasicBlock *BB, Loop *TheLoop,
170 /// Returns true if the value V is uniform within the loop.
171 bool isUniform(Value *V) const;
173 unsigned getMaxSafeDepDistBytes() const { return MaxSafeDepDistBytes; }
174 unsigned getNumStores() const { return NumStores; }
175 unsigned getNumLoads() const { return NumLoads;}
177 /// \brief Add code that checks at runtime if the accessed arrays overlap.
179 /// Returns a pair of instructions where the first element is the first
180 /// instruction generated in possibly a sequence of instructions and the
181 /// second value is the final comparator value or NULL if no check is needed.
182 std::pair<Instruction *, Instruction *>
183 addRuntimeCheck(Instruction *Loc) const;
185 /// \brief The diagnostics report generated for the analysis. E.g. why we
186 /// couldn't analyze the loop.
187 const Optional<LoopAccessReport> &getReport() const { return Report; }
189 /// \brief Print the information about the memory accesses in the loop.
190 void print(raw_ostream &OS, unsigned Depth = 0) const;
192 /// \brief Used to ensure that if the analysis was run with speculating the
193 /// value of symbolic strides, the client queries it with the same assumption.
194 /// Only used in DEBUG build but we don't want NDEBUG-dependent ABI.
195 unsigned NumSymbolicStrides;
198 /// \brief Analyze the loop. Substitute symbolic strides using Strides.
199 void analyzeLoop(const ValueToValueMap &Strides);
201 /// \brief Check if the structure of the loop allows it to be analyzed by this
203 bool canAnalyzeLoop();
205 void emitAnalysis(LoopAccessReport &Message);
207 /// We need to check that all of the pointers in this list are disjoint
209 RuntimePointerCheck PtrRtCheck;
212 const DataLayout *DL;
213 const TargetLibraryInfo *TLI;
220 unsigned MaxSafeDepDistBytes;
222 /// \brief Cache the result of analyzeLoop.
225 /// \brief The diagnostics report generated for the analysis. E.g. why we
226 /// couldn't analyze the loop.
227 Optional<LoopAccessReport> Report;
230 Value *stripIntegerCast(Value *V);
232 ///\brief Return the SCEV corresponding to a pointer with the symbolic stride
233 ///replaced with constant one.
235 /// If \p OrigPtr is not null, use it to look up the stride value instead of \p
236 /// Ptr. \p PtrToStride provides the mapping between the pointer value and its
237 /// stride as collected by LoopVectorizationLegality::collectStridedAccess.
238 const SCEV *replaceSymbolicStrideSCEV(ScalarEvolution *SE,
239 const ValueToValueMap &PtrToStride,
240 Value *Ptr, Value *OrigPtr = nullptr);
242 /// \brief This analysis provides dependence information for the memory accesses
245 /// It runs the analysis for a loop on demand. This can be initiated by
246 /// querying the loop access info via LAA::getInfo. getInfo return a
247 /// LoopAccessInfo object. See this class for the specifics of what information
249 class LoopAccessAnalysis : public FunctionPass {
253 LoopAccessAnalysis() : FunctionPass(ID) {
254 initializeLoopAccessAnalysisPass(*PassRegistry::getPassRegistry());
257 bool runOnFunction(Function &F) override;
259 void getAnalysisUsage(AnalysisUsage &AU) const override;
261 /// \brief Query the result of the loop access information for the loop \p L.
263 /// If the client speculates (and then issues run-time checks) for the values
264 /// of symbolic strides, \p Strides provides the mapping (see
265 /// replaceSymbolicStrideSCEV). If there is no cached result available run
267 const LoopAccessInfo &getInfo(Loop *L, const ValueToValueMap &Strides);
269 void releaseMemory() override {
270 // Invalidate the cache when the pass is freed.
271 LoopAccessInfoMap.clear();
274 /// \brief Print the result of the analysis when invoked with -analyze.
275 void print(raw_ostream &OS, const Module *M = nullptr) const override;
278 /// \brief The cache.
279 DenseMap<Loop *, std::unique_ptr<LoopAccessInfo>> LoopAccessInfoMap;
281 // The used analysis passes.
283 const DataLayout *DL;
284 const TargetLibraryInfo *TLI;
288 } // End llvm namespace