1 //===- llvm/Analysis/MemoryDependenceAnalysis.h - Memory Deps --*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the MemoryDependenceAnalysis analysis pass.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_ANALYSIS_MEMORY_DEPENDENCE_H
15 #define LLVM_ANALYSIS_MEMORY_DEPENDENCE_H
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"
33 class MemoryDependenceAnalysis;
34 class PredIteratorCache;
38 /// MemDepResult - A memory dependence query can return one of three different
39 /// answers, described below.
42 /// Invalid - Clients of MemDep never see this.
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
52 /// Def - This is a dependence on the specified instruction which
53 /// defines/produces the desired memory location. The pointer member of
54 /// the MemDepResult pair holds the instruction that defines the memory.
55 /// Cases of interest:
56 /// 1. This could be a load or store for dependence queries on
57 /// load/store. The value loaded or stored is the produced value.
58 /// Note that the pointer operand may be different than that of the
59 /// queried pointer due to must aliases and phi translation. Note
60 /// that the def may not be the same type as the query, the pointers
61 /// may just be must aliases.
62 /// 2. For loads and stores, this could be an allocation instruction. In
63 /// this case, the load is loading an undef value or a store is the
64 /// first store to (that part of) the allocation.
65 /// 3. Dependence queries on calls return Def only when they are
66 /// readonly calls or memory use intrinsics with identical callees
67 /// and no intervening clobbers. No validation is done that the
68 /// operands to the calls are the same.
71 /// NonLocal - This marker indicates that the query has no dependency in
72 /// the specified block. To find out more, the client should query other
73 /// predecessor blocks.
76 typedef PointerIntPair<Instruction*, 2, DepType> PairTy;
78 explicit MemDepResult(PairTy V) : Value(V) {}
80 MemDepResult() : Value(0, Invalid) {}
82 /// get methods: These are static ctor methods for creating various
83 /// MemDepResult kinds.
84 static MemDepResult getDef(Instruction *Inst) {
85 return MemDepResult(PairTy(Inst, Def));
87 static MemDepResult getClobber(Instruction *Inst) {
88 return MemDepResult(PairTy(Inst, Clobber));
90 static MemDepResult getNonLocal() {
91 return MemDepResult(PairTy(0, NonLocal));
94 /// isClobber - Return true if this MemDepResult represents a query that is
95 /// a instruction clobber dependency.
96 bool isClobber() const { return Value.getInt() == Clobber; }
98 /// isDef - Return true if this MemDepResult represents a query that is
99 /// a instruction definition dependency.
100 bool isDef() const { return Value.getInt() == Def; }
102 /// isNonLocal - Return true if this MemDepResult represents a query that
103 /// is transparent to the start of the block, but where a non-local hasn't
105 bool isNonLocal() const { return Value.getInt() == NonLocal; }
107 /// getInst() - If this is a normal dependency, return the instruction that
108 /// is depended on. Otherwise, return null.
109 Instruction *getInst() const { return Value.getPointer(); }
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 bool operator>(const MemDepResult &M) const { return Value > M.Value; }
116 friend class MemoryDependenceAnalysis;
117 /// Dirty - Entries with this marker occur in a LocalDeps map or
118 /// NonLocalDeps map when the instruction they previously referenced was
119 /// removed from MemDep. In either case, the entry may include an
120 /// instruction pointer. If so, the pointer is an instruction in the
121 /// block where scanning can start from, saving some work.
123 /// In a default-constructed MemDepResult object, the type will be Dirty
124 /// and the instruction pointer will be null.
127 /// isDirty - Return true if this is a MemDepResult in its dirty/invalid.
129 bool isDirty() const { return Value.getInt() == Invalid; }
131 static MemDepResult getDirty(Instruction *Inst) {
132 return MemDepResult(PairTy(Inst, Invalid));
136 /// NonLocalDepEntry - This is an entry in the NonLocalDepInfo cache. For
137 /// each BasicBlock (the BB entry) it keeps a MemDepResult.
138 class NonLocalDepEntry {
142 NonLocalDepEntry(BasicBlock *bb, MemDepResult result)
143 : BB(bb), Result(result) {}
145 // This is used for searches.
146 NonLocalDepEntry(BasicBlock *bb) : BB(bb) {}
148 // BB is the sort key, it can't be changed.
149 BasicBlock *getBB() const { return BB; }
151 void setResult(const MemDepResult &R) { Result = R; }
153 const MemDepResult &getResult() const { return Result; }
155 bool operator<(const NonLocalDepEntry &RHS) const {
160 /// NonLocalDepResult - This is a result from a NonLocal dependence query.
161 /// For each BasicBlock (the BB entry) it keeps a MemDepResult and the
162 /// (potentially phi translated) address that was live in the block.
163 class NonLocalDepResult {
164 NonLocalDepEntry Entry;
167 NonLocalDepResult(BasicBlock *bb, MemDepResult result, Value *address)
168 : Entry(bb, result), Address(address) {}
170 // BB is the sort key, it can't be changed.
171 BasicBlock *getBB() const { return Entry.getBB(); }
173 void setResult(const MemDepResult &R, Value *Addr) {
178 const MemDepResult &getResult() const { return Entry.getResult(); }
180 /// getAddress - Return the address of this pointer in this block. This can
181 /// be different than the address queried for the non-local result because
182 /// of phi translation. This returns null if the address was not available
183 /// in a block (i.e. because phi translation failed) or if this is a cached
184 /// result and that address was deleted.
186 /// The address is always null for a non-local 'call' dependence.
187 Value *getAddress() const { return Address; }
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.
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.
205 class MemoryDependenceAnalysis : public FunctionPass {
206 // A map from instructions to their dependency.
207 typedef DenseMap<Instruction*, MemDepResult> LocalDepMapType;
208 LocalDepMapType LocalDeps;
211 typedef std::vector<NonLocalDepEntry> NonLocalDepInfo;
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<const Value*, 1, bool> ValueIsLoadPair;
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;
223 /// NonLocalPointerInfo - This record is the information kept for each
224 /// (value, is load) pair.
225 struct NonLocalPointerInfo {
226 /// Pair - The pair of the block and the skip-first-block flag.
227 BBSkipFirstBlockPair Pair;
228 /// NonLocalDeps - The results of the query for each relevant block.
229 NonLocalDepInfo NonLocalDeps;
230 /// Size - The maximum size of the dereferences of the
231 /// pointer. May be UnknownSize if the sizes are unknown.
233 /// TBAATag - The TBAA tag associated with dereferences of the
234 /// pointer. May be null if there are no tags or conflicting tags.
235 const MDNode *TBAATag;
237 NonLocalPointerInfo() : Size(AliasAnalysis::UnknownSize), TBAATag(0) {}
240 /// CachedNonLocalPointerInfo - This map stores the cached results of doing
241 /// a pointer lookup at the bottom of a block. The key of this map is the
242 /// pointer+isload bit, the value is a list of <bb->result> mappings.
243 typedef DenseMap<ValueIsLoadPair,
244 NonLocalPointerInfo> CachedNonLocalPointerInfo;
245 CachedNonLocalPointerInfo NonLocalPointerDeps;
247 // A map from instructions to their non-local pointer dependencies.
248 typedef DenseMap<Instruction*,
249 SmallPtrSet<ValueIsLoadPair, 4> > ReverseNonLocalPtrDepTy;
250 ReverseNonLocalPtrDepTy ReverseNonLocalPtrDeps;
253 /// PerInstNLInfo - This is the instruction we keep for each cached access
254 /// that we have for an instruction. The pointer is an owning pointer and
255 /// the bool indicates whether we have any dirty bits in the set.
256 typedef std::pair<NonLocalDepInfo, bool> PerInstNLInfo;
258 // A map from instructions to their non-local dependencies.
259 typedef DenseMap<Instruction*, PerInstNLInfo> NonLocalDepMapType;
261 NonLocalDepMapType NonLocalDeps;
263 // A reverse mapping from dependencies to the dependees. This is
264 // used when removing instructions to keep the cache coherent.
265 typedef DenseMap<Instruction*,
266 SmallPtrSet<Instruction*, 4> > ReverseDepMapType;
267 ReverseDepMapType ReverseLocalDeps;
269 // A reverse mapping from dependencies to the non-local dependees.
270 ReverseDepMapType ReverseNonLocalDeps;
272 /// Current AA implementation, just a cache.
275 OwningPtr<PredIteratorCache> PredCache;
277 MemoryDependenceAnalysis();
278 ~MemoryDependenceAnalysis();
281 /// Pass Implementation stuff. This doesn't do any analysis eagerly.
282 bool runOnFunction(Function &);
284 /// Clean up memory in between runs
285 void releaseMemory();
287 /// getAnalysisUsage - Does not modify anything. It uses Value Numbering
288 /// and Alias Analysis.
290 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
292 /// getDependency - Return the instruction on which a memory operation
293 /// depends. See the class comment for more details. It is illegal to call
294 /// this on non-memory instructions.
295 MemDepResult getDependency(Instruction *QueryInst);
297 /// getNonLocalCallDependency - Perform a full dependency query for the
298 /// specified call, returning the set of blocks that the value is
299 /// potentially live across. The returned set of results will include a
300 /// "NonLocal" result for all blocks where the value is live across.
302 /// This method assumes the instruction returns a "NonLocal" dependency
303 /// within its own block.
305 /// This returns a reference to an internal data structure that may be
306 /// invalidated on the next non-local query or when an instruction is
307 /// removed. Clients must copy this data if they want it around longer than
309 const NonLocalDepInfo &getNonLocalCallDependency(CallSite QueryCS);
312 /// getNonLocalPointerDependency - Perform a full dependency query for an
313 /// access to the specified (non-volatile) memory location, returning the
314 /// set of instructions that either define or clobber the value.
316 /// This method assumes the pointer has a "NonLocal" dependency within BB.
317 void getNonLocalPointerDependency(const AliasAnalysis::Location &Loc,
318 bool isLoad, BasicBlock *BB,
319 SmallVectorImpl<NonLocalDepResult> &Result);
321 /// removeInstruction - Remove an instruction from the dependence analysis,
322 /// updating the dependence of instructions that previously depended on it.
323 void removeInstruction(Instruction *InstToRemove);
325 /// invalidateCachedPointerInfo - This method is used to invalidate cached
326 /// information about the specified pointer, because it may be too
327 /// conservative in memdep. This is an optional call that can be used when
328 /// the client detects an equivalence between the pointer and some other
329 /// value and replaces the other value with ptr. This can make Ptr available
330 /// in more places that cached info does not necessarily keep.
331 void invalidateCachedPointerInfo(Value *Ptr);
333 /// invalidateCachedPredecessors - Clear the PredIteratorCache info.
334 /// This needs to be done when the CFG changes, e.g., due to splitting
336 void invalidateCachedPredecessors();
339 MemDepResult getPointerDependencyFrom(const AliasAnalysis::Location &Loc,
341 BasicBlock::iterator ScanIt,
343 MemDepResult getCallSiteDependencyFrom(CallSite C, bool isReadOnlyCall,
344 BasicBlock::iterator ScanIt,
346 bool getNonLocalPointerDepFromBB(const PHITransAddr &Pointer,
347 const AliasAnalysis::Location &Loc,
348 bool isLoad, BasicBlock *BB,
349 SmallVectorImpl<NonLocalDepResult> &Result,
350 DenseMap<BasicBlock*, Value*> &Visited,
351 bool SkipFirstBlock = false);
352 MemDepResult GetNonLocalInfoForBlock(const AliasAnalysis::Location &Loc,
353 bool isLoad, BasicBlock *BB,
354 NonLocalDepInfo *Cache,
355 unsigned NumSortedEntries);
357 void RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair P);
359 /// verifyRemoved - Verify that the specified instruction does not occur
360 /// in our internal data structures.
361 void verifyRemoved(Instruction *Inst) const;
365 } // End llvm namespace