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