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