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