Split critical edges as needed for load PRE.
[oota-llvm.git] / include / llvm / Analysis / MemoryDependenceAnalysis.h
1 //===- llvm/Analysis/MemoryDependenceAnalysis.h - Memory Deps  --*- 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 MemoryDependenceAnalysis analysis pass.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_ANALYSIS_MEMORY_DEPENDENCE_H
15 #define LLVM_ANALYSIS_MEMORY_DEPENDENCE_H
16
17 #include "llvm/BasicBlock.h"
18 #include "llvm/Pass.h"
19 #include "llvm/Support/ValueHandle.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/OwningPtr.h"
23 #include "llvm/ADT/PointerIntPair.h"
24
25 namespace llvm {
26   class Function;
27   class FunctionPass;
28   class Instruction;
29   class CallSite;
30   class AliasAnalysis;
31   class TargetData;
32   class MemoryDependenceAnalysis;
33   class PredIteratorCache;
34   class DominatorTree;
35   class PHITransAddr;
36   
37   /// MemDepResult - A memory dependence query can return one of three different
38   /// answers, described below.
39   class MemDepResult {
40     enum DepType {
41       /// Invalid - Clients of MemDep never see this.
42       Invalid = 0,
43       
44       /// Clobber - This is a dependence on the specified instruction which
45       /// clobbers the desired value.  The pointer member of the MemDepResult
46       /// pair holds the instruction that clobbers the memory.  For example,
47       /// this occurs when we see a may-aliased store to the memory location we
48       /// care about.
49       Clobber,
50
51       /// Def - This is a dependence on the specified instruction which
52       /// defines/produces the desired memory location.  The pointer member of
53       /// the MemDepResult pair holds the instruction that defines the memory.
54       /// Cases of interest:
55       ///   1. This could be a load or store for dependence queries on
56       ///      load/store.  The value loaded or stored is the produced value.
57       ///      Note that the pointer operand may be different than that of the
58       ///      queried pointer due to must aliases and phi translation.  Note
59       ///      that the def may not be the same type as the query, the pointers
60       ///      may just be must aliases.
61       ///   2. For loads and stores, this could be an allocation instruction. In
62       ///      this case, the load is loading an undef value or a store is the
63       ///      first store to (that part of) the allocation.
64       ///   3. Dependence queries on calls return Def only when they are
65       ///      readonly calls or memory use intrinsics with identical callees
66       ///      and no intervening clobbers.  No validation is done that the
67       ///      operands to the calls are the same.
68       Def,
69       
70       /// NonLocal - This marker indicates that the query has no dependency in
71       /// the specified block.  To find out more, the client should query other
72       /// predecessor blocks.
73       NonLocal
74     };
75     typedef PointerIntPair<Instruction*, 2, DepType> PairTy;
76     PairTy Value;
77     explicit MemDepResult(PairTy V) : Value(V) {}
78   public:
79     MemDepResult() : Value(0, Invalid) {}
80     
81     /// get methods: These are static ctor methods for creating various
82     /// MemDepResult kinds.
83     static MemDepResult getDef(Instruction *Inst) {
84       return MemDepResult(PairTy(Inst, Def));
85     }
86     static MemDepResult getClobber(Instruction *Inst) {
87       return MemDepResult(PairTy(Inst, Clobber));
88     }
89     static MemDepResult getNonLocal() {
90       return MemDepResult(PairTy(0, NonLocal));
91     }
92
93     /// isClobber - Return true if this MemDepResult represents a query that is
94     /// a instruction clobber dependency.
95     bool isClobber() const { return Value.getInt() == Clobber; }
96
97     /// isDef - Return true if this MemDepResult represents a query that is
98     /// a instruction definition dependency.
99     bool isDef() const { return Value.getInt() == Def; }
100     
101     /// isNonLocal - Return true if this MemDepResult represents a query that
102     /// is transparent to the start of the block, but where a non-local hasn't
103     /// been done.
104     bool isNonLocal() const { return Value.getInt() == NonLocal; }
105     
106     /// getInst() - If this is a normal dependency, return the instruction that
107     /// is depended on.  Otherwise, return null.
108     Instruction *getInst() const { return Value.getPointer(); }
109     
110     bool operator==(const MemDepResult &M) const { return Value == M.Value; }
111     bool operator!=(const MemDepResult &M) const { return Value != M.Value; }
112     bool operator<(const MemDepResult &M) const { return Value < M.Value; }
113     bool operator>(const MemDepResult &M) const { return Value > M.Value; }
114   private:
115     friend class MemoryDependenceAnalysis;
116     /// Dirty - Entries with this marker occur in a LocalDeps map or
117     /// NonLocalDeps map when the instruction they previously referenced was
118     /// removed from MemDep.  In either case, the entry may include an
119     /// instruction pointer.  If so, the pointer is an instruction in the
120     /// block where scanning can start from, saving some work.
121     ///
122     /// In a default-constructed MemDepResult object, the type will be Dirty
123     /// and the instruction pointer will be null.
124     ///
125          
126     /// isDirty - Return true if this is a MemDepResult in its dirty/invalid.
127     /// state.
128     bool isDirty() const { return Value.getInt() == Invalid; }
129     
130     static MemDepResult getDirty(Instruction *Inst) {
131       return MemDepResult(PairTy(Inst, Invalid));
132     }
133   };
134
135   /// NonLocalDepResult - This is a result from a NonLocal dependence query.
136   /// For each BasicBlock (the BB entry) it keeps a MemDepResult and the
137   /// (potentially phi translated) address that was live in the block.
138   class NonLocalDepResult {
139     BasicBlock *BB;
140     MemDepResult Result;
141     Value *Address;
142   public:
143     NonLocalDepResult(BasicBlock *bb, MemDepResult result, Value *address)
144       : BB(bb), Result(result), Address(address) {}
145     
146     // BB is the sort key, it can't be changed.
147     BasicBlock *getBB() const { return BB; }
148     
149     void setResult(const MemDepResult &R, Value *Addr) {
150       Result = R;
151       Address = Addr;
152     }
153     
154     const MemDepResult &getResult() const { return Result; }
155     
156     /// getAddress - Return the address of this pointer in this block.  This can
157     /// be different than the address queried for the non-local result because
158     /// of phi translation.  This returns null if the address was not available
159     /// in a block (i.e. because phi translation failed) or if this is a cached
160     /// result and that address was deleted.
161     ///
162     /// The address is always null for a non-local 'call' dependence.
163     Value *getAddress() const { return Address; }
164   };
165   
166   /// NonLocalDepEntry - This is an entry in the NonLocalDepInfo cache.  For
167   /// each BasicBlock (the BB entry) it keeps a MemDepResult.
168   class NonLocalDepEntry {
169     BasicBlock *BB;
170     MemDepResult Result;
171   public:
172     NonLocalDepEntry(BasicBlock *bb, MemDepResult result)
173       : BB(bb), Result(result) {}
174
175     // This is used for searches.
176     NonLocalDepEntry(BasicBlock *bb) : BB(bb) {}
177
178     // BB is the sort key, it can't be changed.
179     BasicBlock *getBB() const { return BB; }
180     
181     void setResult(const MemDepResult &R) { Result = R; }
182
183     const MemDepResult &getResult() const { return Result; }
184     
185     bool operator<(const NonLocalDepEntry &RHS) const {
186       return BB < RHS.BB;
187     }
188   };
189   
190   /// MemoryDependenceAnalysis - This is an analysis that determines, for a
191   /// given memory operation, what preceding memory operations it depends on.
192   /// It builds on alias analysis information, and tries to provide a lazy,
193   /// caching interface to a common kind of alias information query.
194   ///
195   /// The dependency information returned is somewhat unusual, but is pragmatic.
196   /// If queried about a store or call that might modify memory, the analysis
197   /// will return the instruction[s] that may either load from that memory or
198   /// store to it.  If queried with a load or call that can never modify memory,
199   /// the analysis will return calls and stores that might modify the pointer,
200   /// but generally does not return loads unless a) they are volatile, or
201   /// b) they load from *must-aliased* pointers.  Returning a dependence on
202   /// must-alias'd pointers instead of all pointers interacts well with the
203   /// internal caching mechanism.
204   ///
205   class MemoryDependenceAnalysis : public FunctionPass {
206     // A map from instructions to their dependency.
207     typedef DenseMap<Instruction*, MemDepResult> LocalDepMapType;
208     LocalDepMapType LocalDeps;
209
210   public:
211     typedef std::vector<NonLocalDepEntry> NonLocalDepInfo;
212   private:
213     /// ValueIsLoadPair - This is a pair<Value*, bool> where the bool is true if
214     /// the dependence is a read only dependence, false if read/write.
215     typedef PointerIntPair<Value*, 1, bool> ValueIsLoadPair;
216
217     /// BBSkipFirstBlockPair - This pair is used when caching information for a
218     /// block.  If the pointer is null, the cache value is not a full query that
219     /// starts at the specified block.  If non-null, the bool indicates whether
220     /// or not the contents of the block was skipped.
221     typedef PointerIntPair<BasicBlock*, 1, bool> BBSkipFirstBlockPair;
222
223     /// CachedNonLocalPointerInfo - This map stores the cached results of doing
224     /// a pointer lookup at the bottom of a block.  The key of this map is the
225     /// pointer+isload bit, the value is a list of <bb->result> mappings.
226     typedef DenseMap<ValueIsLoadPair, std::pair<BBSkipFirstBlockPair, 
227                   NonLocalDepInfo> > CachedNonLocalPointerInfo;
228     CachedNonLocalPointerInfo NonLocalPointerDeps;
229
230     // A map from instructions to their non-local pointer dependencies.
231     typedef DenseMap<Instruction*, 
232                      SmallPtrSet<ValueIsLoadPair, 4> > ReverseNonLocalPtrDepTy;
233     ReverseNonLocalPtrDepTy ReverseNonLocalPtrDeps;
234
235     
236     /// PerInstNLInfo - This is the instruction we keep for each cached access
237     /// that we have for an instruction.  The pointer is an owning pointer and
238     /// the bool indicates whether we have any dirty bits in the set.
239     typedef std::pair<NonLocalDepInfo, bool> PerInstNLInfo;
240     
241     // A map from instructions to their non-local dependencies.
242     typedef DenseMap<Instruction*, PerInstNLInfo> NonLocalDepMapType;
243       
244     NonLocalDepMapType NonLocalDeps;
245     
246     // A reverse mapping from dependencies to the dependees.  This is
247     // used when removing instructions to keep the cache coherent.
248     typedef DenseMap<Instruction*,
249                      SmallPtrSet<Instruction*, 4> > ReverseDepMapType;
250     ReverseDepMapType ReverseLocalDeps;
251     
252     // A reverse mapping from dependencies to the non-local dependees.
253     ReverseDepMapType ReverseNonLocalDeps;
254     
255     /// Current AA implementation, just a cache.
256     AliasAnalysis *AA;
257     TargetData *TD;
258     OwningPtr<PredIteratorCache> PredCache;
259   public:
260     MemoryDependenceAnalysis();
261     ~MemoryDependenceAnalysis();
262     static char ID;
263
264     /// Pass Implementation stuff.  This doesn't do any analysis eagerly.
265     bool runOnFunction(Function &);
266     
267     /// Clean up memory in between runs
268     void releaseMemory();
269     
270     /// getAnalysisUsage - Does not modify anything.  It uses Value Numbering
271     /// and Alias Analysis.
272     ///
273     virtual void getAnalysisUsage(AnalysisUsage &AU) const;
274     
275     /// getDependency - Return the instruction on which a memory operation
276     /// depends.  See the class comment for more details.  It is illegal to call
277     /// this on non-memory instructions.
278     MemDepResult getDependency(Instruction *QueryInst);
279
280     /// getNonLocalCallDependency - Perform a full dependency query for the
281     /// specified call, returning the set of blocks that the value is
282     /// potentially live across.  The returned set of results will include a
283     /// "NonLocal" result for all blocks where the value is live across.
284     ///
285     /// This method assumes the instruction returns a "NonLocal" dependency
286     /// within its own block.
287     ///
288     /// This returns a reference to an internal data structure that may be
289     /// invalidated on the next non-local query or when an instruction is
290     /// removed.  Clients must copy this data if they want it around longer than
291     /// that.
292     const NonLocalDepInfo &getNonLocalCallDependency(CallSite QueryCS);
293     
294     
295     /// getNonLocalPointerDependency - Perform a full dependency query for an
296     /// access to the specified (non-volatile) memory location, returning the
297     /// set of instructions that either define or clobber the value.
298     ///
299     /// This method assumes the pointer has a "NonLocal" dependency within BB.
300     void getNonLocalPointerDependency(Value *Pointer, bool isLoad,
301                                       BasicBlock *BB,
302                                     SmallVectorImpl<NonLocalDepResult> &Result);
303     
304     /// removeInstruction - Remove an instruction from the dependence analysis,
305     /// updating the dependence of instructions that previously depended on it.
306     void removeInstruction(Instruction *InstToRemove);
307     
308     /// invalidateCachedPointerInfo - This method is used to invalidate cached
309     /// information about the specified pointer, because it may be too
310     /// conservative in memdep.  This is an optional call that can be used when
311     /// the client detects an equivalence between the pointer and some other
312     /// value and replaces the other value with ptr. This can make Ptr available
313     /// in more places that cached info does not necessarily keep.
314     void invalidateCachedPointerInfo(Value *Ptr);
315
316     /// invalidateCachedPredecessors - Clear the PredIteratorCache info.
317     /// This needs to be done when the CFG changes, e.g., due to splitting
318     /// critical edges.
319     void invalidateCachedPredecessors();
320     
321   private:
322     MemDepResult getPointerDependencyFrom(Value *Pointer, uint64_t MemSize,
323                                           bool isLoad, 
324                                           BasicBlock::iterator ScanIt,
325                                           BasicBlock *BB);
326     MemDepResult getCallSiteDependencyFrom(CallSite C, bool isReadOnlyCall,
327                                            BasicBlock::iterator ScanIt,
328                                            BasicBlock *BB);
329     bool getNonLocalPointerDepFromBB(const PHITransAddr &Pointer, uint64_t Size,
330                                      bool isLoad, BasicBlock *BB,
331                                      SmallVectorImpl<NonLocalDepResult> &Result,
332                                      DenseMap<BasicBlock*, Value*> &Visited,
333                                      bool SkipFirstBlock = false);
334     MemDepResult GetNonLocalInfoForBlock(Value *Pointer, uint64_t PointeeSize,
335                                          bool isLoad, BasicBlock *BB,
336                                          NonLocalDepInfo *Cache,
337                                          unsigned NumSortedEntries);
338
339     void RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair P);
340     
341     /// verifyRemoved - Verify that the specified instruction does not occur
342     /// in our internal data structures.
343     void verifyRemoved(Instruction *Inst) const;
344     
345   };
346
347 } // End llvm namespace
348
349 #endif