enhance NonLocalDepEntry to keep the per-block phi translated address
[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   /// NonLocalDepEntry - This is an entry in the NonLocalDepInfo cache, and an
136   /// entry in the results set for a non-local query.  For each BasicBlock (the
137   /// BB entry) it keeps a MemDepResult and the (potentially phi translated)
138   /// address that was live in the block.
139   class NonLocalDepEntry {
140     BasicBlock *BB;
141     MemDepResult Result;
142     WeakVH Address;
143   public:
144     NonLocalDepEntry(BasicBlock *bb, MemDepResult result, Value *address)
145       : BB(bb), Result(result), Address(address) {}
146
147     // This is used for searches.
148     NonLocalDepEntry(BasicBlock *bb) : BB(bb) {}
149
150     // BB is the sort key, it can't be changed.
151     BasicBlock *getBB() const { return BB; }
152     
153     void setResult(const MemDepResult &R, Value *Addr) {
154       Result = R;
155       Address = Addr;
156     }
157
158     const MemDepResult &getResult() const { return Result; }
159     
160     /// getAddress - Return the address of this pointer in this block.  This can
161     /// be different than the address queried for the non-local result because
162     /// of phi translation.  This returns null if the address was not available
163     /// in a block (i.e. because phi translation failed) or if this is a cached
164     /// result and that address was deleted.
165     ///
166     /// The address is always null for a non-local 'call' dependence.
167     Value *getAddress() const { return Address; }
168
169     bool operator<(const NonLocalDepEntry &RHS) const {
170       return BB < RHS.BB;
171     }
172   };
173   
174   /// MemoryDependenceAnalysis - This is an analysis that determines, for a
175   /// given memory operation, what preceding memory operations it depends on.
176   /// It builds on alias analysis information, and tries to provide a lazy,
177   /// caching interface to a common kind of alias information query.
178   ///
179   /// The dependency information returned is somewhat unusual, but is pragmatic.
180   /// If queried about a store or call that might modify memory, the analysis
181   /// will return the instruction[s] that may either load from that memory or
182   /// store to it.  If queried with a load or call that can never modify memory,
183   /// the analysis will return calls and stores that might modify the pointer,
184   /// but generally does not return loads unless a) they are volatile, or
185   /// b) they load from *must-aliased* pointers.  Returning a dependence on
186   /// must-alias'd pointers instead of all pointers interacts well with the
187   /// internal caching mechanism.
188   ///
189   class MemoryDependenceAnalysis : public FunctionPass {
190     // A map from instructions to their dependency.
191     typedef DenseMap<Instruction*, MemDepResult> LocalDepMapType;
192     LocalDepMapType LocalDeps;
193
194   public:
195     typedef std::vector<NonLocalDepEntry> NonLocalDepInfo;
196   private:
197     /// ValueIsLoadPair - This is a pair<Value*, bool> where the bool is true if
198     /// the dependence is a read only dependence, false if read/write.
199     typedef PointerIntPair<Value*, 1, bool> ValueIsLoadPair;
200
201     /// BBSkipFirstBlockPair - This pair is used when caching information for a
202     /// block.  If the pointer is null, the cache value is not a full query that
203     /// starts at the specified block.  If non-null, the bool indicates whether
204     /// or not the contents of the block was skipped.
205     typedef PointerIntPair<BasicBlock*, 1, bool> BBSkipFirstBlockPair;
206
207     /// CachedNonLocalPointerInfo - This map stores the cached results of doing
208     /// a pointer lookup at the bottom of a block.  The key of this map is the
209     /// pointer+isload bit, the value is a list of <bb->result> mappings.
210     typedef DenseMap<ValueIsLoadPair, std::pair<BBSkipFirstBlockPair, 
211                   NonLocalDepInfo> > CachedNonLocalPointerInfo;
212     CachedNonLocalPointerInfo NonLocalPointerDeps;
213
214     // A map from instructions to their non-local pointer dependencies.
215     typedef DenseMap<Instruction*, 
216                      SmallPtrSet<ValueIsLoadPair, 4> > ReverseNonLocalPtrDepTy;
217     ReverseNonLocalPtrDepTy ReverseNonLocalPtrDeps;
218
219     
220     /// PerInstNLInfo - This is the instruction we keep for each cached access
221     /// that we have for an instruction.  The pointer is an owning pointer and
222     /// the bool indicates whether we have any dirty bits in the set.
223     typedef std::pair<NonLocalDepInfo, bool> PerInstNLInfo;
224     
225     // A map from instructions to their non-local dependencies.
226     typedef DenseMap<Instruction*, PerInstNLInfo> NonLocalDepMapType;
227       
228     NonLocalDepMapType NonLocalDeps;
229     
230     // A reverse mapping from dependencies to the dependees.  This is
231     // used when removing instructions to keep the cache coherent.
232     typedef DenseMap<Instruction*,
233                      SmallPtrSet<Instruction*, 4> > ReverseDepMapType;
234     ReverseDepMapType ReverseLocalDeps;
235     
236     // A reverse mapping form dependencies to the non-local dependees.
237     ReverseDepMapType ReverseNonLocalDeps;
238     
239     /// Current AA implementation, just a cache.
240     AliasAnalysis *AA;
241     TargetData *TD;
242     OwningPtr<PredIteratorCache> PredCache;
243   public:
244     MemoryDependenceAnalysis();
245     ~MemoryDependenceAnalysis();
246     static char ID;
247
248     /// Pass Implementation stuff.  This doesn't do any analysis eagerly.
249     bool runOnFunction(Function &);
250     
251     /// Clean up memory in between runs
252     void releaseMemory();
253     
254     /// getAnalysisUsage - Does not modify anything.  It uses Value Numbering
255     /// and Alias Analysis.
256     ///
257     virtual void getAnalysisUsage(AnalysisUsage &AU) const;
258     
259     /// getDependency - Return the instruction on which a memory operation
260     /// depends.  See the class comment for more details.  It is illegal to call
261     /// this on non-memory instructions.
262     MemDepResult getDependency(Instruction *QueryInst);
263
264     /// getNonLocalCallDependency - Perform a full dependency query for the
265     /// specified call, returning the set of blocks that the value is
266     /// potentially live across.  The returned set of results will include a
267     /// "NonLocal" result for all blocks where the value is live across.
268     ///
269     /// This method assumes the instruction returns a "NonLocal" dependency
270     /// within its own block.
271     ///
272     /// This returns a reference to an internal data structure that may be
273     /// invalidated on the next non-local query or when an instruction is
274     /// removed.  Clients must copy this data if they want it around longer than
275     /// that.
276     const NonLocalDepInfo &getNonLocalCallDependency(CallSite QueryCS);
277     
278     
279     /// getNonLocalPointerDependency - Perform a full dependency query for an
280     /// access to the specified (non-volatile) memory location, returning the
281     /// set of instructions that either define or clobber the value.
282     ///
283     /// This method assumes the pointer has a "NonLocal" dependency within BB.
284     void getNonLocalPointerDependency(Value *Pointer, bool isLoad,
285                                       BasicBlock *BB,
286                                      SmallVectorImpl<NonLocalDepEntry> &Result);
287     
288     /// removeInstruction - Remove an instruction from the dependence analysis,
289     /// updating the dependence of instructions that previously depended on it.
290     void removeInstruction(Instruction *InstToRemove);
291     
292     /// invalidateCachedPointerInfo - This method is used to invalidate cached
293     /// information about the specified pointer, because it may be too
294     /// conservative in memdep.  This is an optional call that can be used when
295     /// the client detects an equivalence between the pointer and some other
296     /// value and replaces the other value with ptr. This can make Ptr available
297     /// in more places that cached info does not necessarily keep.
298     void invalidateCachedPointerInfo(Value *Ptr);
299     
300   private:
301     MemDepResult getPointerDependencyFrom(Value *Pointer, uint64_t MemSize,
302                                           bool isLoad, 
303                                           BasicBlock::iterator ScanIt,
304                                           BasicBlock *BB);
305     MemDepResult getCallSiteDependencyFrom(CallSite C, bool isReadOnlyCall,
306                                            BasicBlock::iterator ScanIt,
307                                            BasicBlock *BB);
308     bool getNonLocalPointerDepFromBB(const PHITransAddr &Pointer, uint64_t Size,
309                                      bool isLoad, BasicBlock *BB,
310                                      SmallVectorImpl<NonLocalDepEntry> &Result,
311                                      DenseMap<BasicBlock*, Value*> &Visited,
312                                      bool SkipFirstBlock = false);
313     MemDepResult GetNonLocalInfoForBlock(Value *Pointer, uint64_t PointeeSize,
314                                          bool isLoad, BasicBlock *BB,
315                                          NonLocalDepInfo *Cache,
316                                          unsigned NumSortedEntries);
317
318     void RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair P);
319     
320     /// verifyRemoved - Verify that the specified instruction does not occur
321     /// in our internal data structures.
322     void verifyRemoved(Instruction *Inst) const;
323     
324   };
325
326 } // End llvm namespace
327
328 #endif