[LoopAccesses] Add missing const to APIs in VectorizationReport
[oota-llvm.git] / include / llvm / Analysis / LoopAccessAnalysis.h
1 //===- llvm/Analysis/LoopAccessAnalysis.h -----------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interface for the loop memory dependence framework that
11 // was originally developed for the Loop Vectorizer.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_ANALYSIS_LOOPACCESSANALYSIS_H
16 #define LLVM_ANALYSIS_LOOPACCESSANALYSIS_H
17
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"
27
28 namespace llvm {
29
30 class Value;
31 class DataLayout;
32 class AliasAnalysis;
33 class ScalarEvolution;
34 class Loop;
35 class SCEV;
36
37 /// Optimization analysis message produced during vectorization. Messages inform
38 /// the user why vectorization did not occur.
39 class VectorizationReport {
40   std::string Message;
41   const Instruction *Instr;
42
43 public:
44   VectorizationReport(const Instruction *I = nullptr)
45       : Message("loop not vectorized: "), Instr(I) {}
46
47   template <typename A> VectorizationReport &operator<<(const A &Value) {
48     raw_string_ostream Out(Message);
49     Out << Value;
50     return *this;
51   }
52
53   const Instruction *getInstr() const { return Instr; }
54
55   std::string &str() { return Message; }
56   const std::string &str() const { return Message; }
57   operator Twine() { return Message; }
58
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
61   /// \p TheLoop.
62   static void emitAnalysis(const VectorizationReport &Message,
63                            const Function *TheFunction,
64                            const Loop *TheLoop,
65                            const char *PassName);
66 };
67
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;
73
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;
78
79   /// \\brief When performing memory disambiguation checks at runtime do not
80   /// make more than this number of comparisons.
81   static const unsigned RuntimeMemoryCheckThreshold;
82 };
83
84 /// \brief Drive the analysis of memory accesses in the loop
85 ///
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.
89 ///
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.
93 ///
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 {
99 public:
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) {}
104
105     /// Reset the state of the pointer runtime information.
106     void reset() {
107       Need = false;
108       Pointers.clear();
109       Starts.clear();
110       Ends.clear();
111       IsWritePtr.clear();
112       DependencySetId.clear();
113       AliasSetId.clear();
114     }
115
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);
119
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;
123
124     /// This flag indicates if we need to add the runtime check.
125     bool Need;
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;
139   };
140
141   LoopAccessInfo(Loop *L, ScalarEvolution *SE, const DataLayout *DL,
142                  const TargetLibraryInfo *TLI, AliasAnalysis *AA,
143                  DominatorTree *DT, ValueToValueMap &Strides);
144
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; }
148
149   RuntimePointerCheck *getRuntimePointerCheck() { return &PtrRtCheck; }
150
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,
154                                     DominatorTree *DT);
155
156   /// Returns true if the value V is uniform within the loop.
157   bool isUniform(Value *V);
158
159   unsigned getMaxSafeDepDistBytes() const { return MaxSafeDepDistBytes; }
160   unsigned getNumStores() const { return NumStores; }
161   unsigned getNumLoads() const { return NumLoads;}
162
163   /// \brief Add code that checks at runtime if the accessed arrays overlap.
164   ///
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);
169
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; }
173
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;
178
179 private:
180   /// \brief Analyze the loop.  Substitute symbolic strides using Strides.
181   void analyzeLoop(ValueToValueMap &Strides);
182
183   /// \brief Check if the structure of the loop allows it to be analyzed by this
184   /// pass.
185   bool canAnalyzeLoop();
186
187   void emitAnalysis(VectorizationReport &Message);
188
189   /// We need to check that all of the pointers in this list are disjoint
190   /// at runtime.
191   RuntimePointerCheck PtrRtCheck;
192   Loop *TheLoop;
193   ScalarEvolution *SE;
194   const DataLayout *DL;
195   const TargetLibraryInfo *TLI;
196   AliasAnalysis *AA;
197   DominatorTree *DT;
198
199   unsigned NumLoads;
200   unsigned NumStores;
201
202   unsigned MaxSafeDepDistBytes;
203
204   /// \brief Cache the result of analyzeLoop.
205   bool CanVecMem;
206
207   /// \brief The diagnostics report generated for the analysis.  E.g. why we
208   /// couldn't analyze the loop.
209   Optional<VectorizationReport> Report;
210 };
211
212 Value *stripIntegerCast(Value *V);
213
214 ///\brief Return the SCEV corresponding to a pointer with the symbolic stride
215 ///replaced with constant one.
216 ///
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);
223
224 /// \brief This analysis provides dependence information for the memory accesses
225 /// of a loop.
226 ///
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
230 /// is provided.
231 class LoopAccessAnalysis : public FunctionPass {
232 public:
233   static char ID;
234
235   LoopAccessAnalysis() : FunctionPass(ID) {
236     initializeLoopAccessAnalysisPass(*PassRegistry::getPassRegistry());
237   }
238
239   bool runOnFunction(Function &F) override;
240
241   void getAnalysisUsage(AnalysisUsage &AU) const override;
242
243   /// \brief Query the result of the loop access information for the loop \p L.
244   ///
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
248   /// the analysis.
249   LoopAccessInfo &getInfo(Loop *L, ValueToValueMap &Strides);
250
251   void releaseMemory() override {
252     // Invalidate the cache when the pass is freed.
253     LoopAccessInfoMap.clear();
254   }
255
256 private:
257   /// \brief The cache.
258   DenseMap<Loop *, std::unique_ptr<LoopAccessInfo>> LoopAccessInfoMap;
259
260   // The used analysis passes.
261   ScalarEvolution *SE;
262   const DataLayout *DL;
263   const TargetLibraryInfo *TLI;
264   AliasAnalysis *AA;
265   DominatorTree *DT;
266 };
267 } // End llvm namespace
268
269 #endif