a2f938ca67c07812b59c07077527ca1ccb3e78f3
[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 LoopAccessReport {
40   std::string Message;
41   const Instruction *Instr;
42
43 protected:
44   LoopAccessReport(const Twine &Message, const Instruction *I)
45       : Message(Message.str()), Instr(I) {}
46
47 public:
48   LoopAccessReport(const Instruction *I = nullptr) : Instr(I) {}
49
50   template <typename A> LoopAccessReport &operator<<(const A &Value) {
51     raw_string_ostream Out(Message);
52     Out << Value;
53     return *this;
54   }
55
56   const Instruction *getInstr() const { return Instr; }
57
58   std::string &str() { return Message; }
59   const std::string &str() const { return Message; }
60   operator Twine() { return Message; }
61
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
64   /// \p TheLoop.
65   static void emitAnalysis(const LoopAccessReport &Message,
66                            const Function *TheFunction,
67                            const Loop *TheLoop,
68                            const char *PassName);
69 };
70
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;
76
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();
83
84   /// \\brief When performing memory disambiguation checks at runtime do not
85   /// make more than this number of comparisons.
86   static const unsigned RuntimeMemoryCheckThreshold;
87 };
88
89 /// \brief Drive the analysis of memory accesses in the loop
90 ///
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.
94 ///
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.
98 ///
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 {
104 public:
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) {}
109
110     /// Reset the state of the pointer runtime information.
111     void reset() {
112       Need = false;
113       Pointers.clear();
114       Starts.clear();
115       Ends.clear();
116       IsWritePtr.clear();
117       DependencySetId.clear();
118       AliasSetId.clear();
119     }
120
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, ValueToValueMap &Strides);
124
125     /// \brief Decide whether we need to issue a run-time check for pointer at
126     /// index \p I and \p J to prove their independence.
127     bool needsChecking(unsigned I, unsigned J) const;
128
129     /// This flag indicates if we need to add the runtime check.
130     bool Need;
131     /// Holds the pointers that we need to check.
132     SmallVector<TrackingVH<Value>, 2> Pointers;
133     /// Holds the pointer value at the beginning of the loop.
134     SmallVector<const SCEV*, 2> Starts;
135     /// Holds the pointer value at the end of the loop.
136     SmallVector<const SCEV*, 2> Ends;
137     /// Holds the information if this pointer is used for writing to memory.
138     SmallVector<bool, 2> IsWritePtr;
139     /// Holds the id of the set of pointers that could be dependent because of a
140     /// shared underlying object.
141     SmallVector<unsigned, 2> DependencySetId;
142     /// Holds the id of the disjoint alias set to which this pointer belongs.
143     SmallVector<unsigned, 2> AliasSetId;
144   };
145
146   LoopAccessInfo(Loop *L, ScalarEvolution *SE, const DataLayout *DL,
147                  const TargetLibraryInfo *TLI, AliasAnalysis *AA,
148                  DominatorTree *DT, ValueToValueMap &Strides);
149
150   /// Return true we can analyze the memory accesses in the loop and there are
151   /// no memory dependence cycles.
152   bool canVectorizeMemory() { return CanVecMem; }
153
154   RuntimePointerCheck *getRuntimePointerCheck() { return &PtrRtCheck; }
155
156   /// Return true if the block BB needs to be predicated in order for the loop
157   /// to be vectorized.
158   static bool blockNeedsPredication(BasicBlock *BB, Loop *TheLoop,
159                                     DominatorTree *DT);
160
161   /// Returns true if the value V is uniform within the loop.
162   bool isUniform(Value *V);
163
164   unsigned getMaxSafeDepDistBytes() const { return MaxSafeDepDistBytes; }
165   unsigned getNumStores() const { return NumStores; }
166   unsigned getNumLoads() const { return NumLoads;}
167
168   /// \brief Add code that checks at runtime if the accessed arrays overlap.
169   ///
170   /// Returns a pair of instructions where the first element is the first
171   /// instruction generated in possibly a sequence of instructions and the
172   /// second value is the final comparator value or NULL if no check is needed.
173   std::pair<Instruction *, Instruction *> addRuntimeCheck(Instruction *Loc);
174
175   /// \brief The diagnostics report generated for the analysis.  E.g. why we
176   /// couldn't analyze the loop.
177   Optional<LoopAccessReport> &getReport() { return Report; }
178
179   /// \brief Used to ensure that if the analysis was run with speculating the
180   /// value of symbolic strides, the client queries it with the same assumption.
181   /// Only used in DEBUG build but we don't want NDEBUG-depedent ABI.
182   unsigned NumSymbolicStrides;
183
184 private:
185   /// \brief Analyze the loop.  Substitute symbolic strides using Strides.
186   void analyzeLoop(ValueToValueMap &Strides);
187
188   /// \brief Check if the structure of the loop allows it to be analyzed by this
189   /// pass.
190   bool canAnalyzeLoop();
191
192   void emitAnalysis(LoopAccessReport &Message);
193
194   /// We need to check that all of the pointers in this list are disjoint
195   /// at runtime.
196   RuntimePointerCheck PtrRtCheck;
197   Loop *TheLoop;
198   ScalarEvolution *SE;
199   const DataLayout *DL;
200   const TargetLibraryInfo *TLI;
201   AliasAnalysis *AA;
202   DominatorTree *DT;
203
204   unsigned NumLoads;
205   unsigned NumStores;
206
207   unsigned MaxSafeDepDistBytes;
208
209   /// \brief Cache the result of analyzeLoop.
210   bool CanVecMem;
211
212   /// \brief The diagnostics report generated for the analysis.  E.g. why we
213   /// couldn't analyze the loop.
214   Optional<LoopAccessReport> Report;
215 };
216
217 Value *stripIntegerCast(Value *V);
218
219 ///\brief Return the SCEV corresponding to a pointer with the symbolic stride
220 ///replaced with constant one.
221 ///
222 /// If \p OrigPtr is not null, use it to look up the stride value instead of \p
223 /// Ptr.  \p PtrToStride provides the mapping between the pointer value and its
224 /// stride as collected by LoopVectorizationLegality::collectStridedAccess.
225 const SCEV *replaceSymbolicStrideSCEV(ScalarEvolution *SE,
226                                       ValueToValueMap &PtrToStride,
227                                       Value *Ptr, Value *OrigPtr = nullptr);
228
229 /// \brief This analysis provides dependence information for the memory accesses
230 /// of a loop.
231 ///
232 /// It runs the analysis for a loop on demand.  This can be initiated by
233 /// querying the loop access info via LAA::getInfo.  getInfo return a
234 /// LoopAccessInfo object.  See this class for the specifics of what information
235 /// is provided.
236 class LoopAccessAnalysis : public FunctionPass {
237 public:
238   static char ID;
239
240   LoopAccessAnalysis() : FunctionPass(ID) {
241     initializeLoopAccessAnalysisPass(*PassRegistry::getPassRegistry());
242   }
243
244   bool runOnFunction(Function &F) override;
245
246   void getAnalysisUsage(AnalysisUsage &AU) const override;
247
248   /// \brief Query the result of the loop access information for the loop \p L.
249   ///
250   /// If the client speculates (and then issues run-time checks) for the values
251   /// of symbolic strides, \p Strides provides the mapping (see
252   /// replaceSymbolicStrideSCEV).  If there is no cached result available run
253   /// the analysis.
254   LoopAccessInfo &getInfo(Loop *L, ValueToValueMap &Strides);
255
256   void releaseMemory() override {
257     // Invalidate the cache when the pass is freed.
258     LoopAccessInfoMap.clear();
259   }
260
261 private:
262   /// \brief The cache.
263   DenseMap<Loop *, std::unique_ptr<LoopAccessInfo>> LoopAccessInfoMap;
264
265   // The used analysis passes.
266   ScalarEvolution *SE;
267   const DataLayout *DL;
268   const TargetLibraryInfo *TLI;
269   AliasAnalysis *AA;
270   DominatorTree *DT;
271 };
272 } // End llvm namespace
273
274 #endif