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