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
51 /// There are several cases that may be interesting here:
52 /// 1. Loads are clobbered by may-alias stores.
53 /// 2. Loads are considered clobbered by partially-aliased loads. The
54 /// client may choose to analyze deeper into these cases.
56 /// A dependence query on the first instruction of the entry block will
57 /// return a clobber(self) result.
60 /// Def - This is a dependence on the specified instruction which
61 /// defines/produces the desired memory location. The pointer member of
62 /// the MemDepResult pair holds the instruction that defines the memory.
63 /// Cases of interest:
64 /// 1. This could be a load or store for dependence queries on
65 /// load/store. The value loaded or stored is the produced value.
66 /// Note that the pointer operand may be different than that of the
67 /// queried pointer due to must aliases and phi translation. Note
68 /// that the def may not be the same type as the query, the pointers
69 /// may just be must aliases.
70 /// 2. For loads and stores, this could be an allocation instruction. In
71 /// this case, the load is loading an undef value or a store is the
72 /// first store to (that part of) the allocation.
73 /// 3. Dependence queries on calls return Def only when they are
74 /// readonly calls or memory use intrinsics with identical callees
75 /// and no intervening clobbers. No validation is done that the
76 /// operands to the calls are the same.
79 /// NonLocal - This marker indicates that the query has no dependency in
80 /// the specified block. To find out more, the client should query other
81 /// predecessor blocks.
84 typedef PointerIntPair<Instruction*, 2, DepType> PairTy;
86 explicit MemDepResult(PairTy V) : Value(V) {}
88 MemDepResult() : Value(0, Invalid) {}
90 /// get methods: These are static ctor methods for creating various
91 /// MemDepResult kinds.
92 static MemDepResult getDef(Instruction *Inst) {
93 assert(Inst && "Def requires inst");
94 return MemDepResult(PairTy(Inst, Def));
96 static MemDepResult getClobber(Instruction *Inst) {
97 assert(Inst && "Clobber requires inst");
98 return MemDepResult(PairTy(Inst, Clobber));
100 static MemDepResult getNonLocal() {
101 return MemDepResult(PairTy(0, NonLocal));
103 static MemDepResult getUnknown() {
104 return MemDepResult(PairTy(0, Clobber));
107 /// isClobber - Return true if this MemDepResult represents a query that is
108 /// a instruction clobber dependency.
109 bool isClobber() const { return Value.getInt() == Clobber && getInst(); }
111 /// isUnknown - Return true if this MemDepResult represents a query which
112 /// cannot and/or will not be computed.
113 bool isUnknown() const { return Value.getInt() == Clobber && !getInst(); }
115 /// isDef - Return true if this MemDepResult represents a query that is
116 /// a instruction definition dependency.
117 bool isDef() const { return Value.getInt() == Def; }
119 /// isNonLocal - Return true if this MemDepResult represents a query that
120 /// is transparent to the start of the block, but where a non-local hasn't
122 bool isNonLocal() const { return Value.getInt() == NonLocal; }
124 /// getInst() - If this is a normal dependency, return the instruction that
125 /// is depended on. Otherwise, return null.
126 Instruction *getInst() const { return Value.getPointer(); }
128 bool operator==(const MemDepResult &M) const { return Value == M.Value; }
129 bool operator!=(const MemDepResult &M) const { return Value != M.Value; }
130 bool operator<(const MemDepResult &M) const { return Value < M.Value; }
131 bool operator>(const MemDepResult &M) const { return Value > M.Value; }
133 friend class MemoryDependenceAnalysis;
134 /// Dirty - Entries with this marker occur in a LocalDeps map or
135 /// NonLocalDeps map when the instruction they previously referenced was
136 /// removed from MemDep. In either case, the entry may include an
137 /// instruction pointer. If so, the pointer is an instruction in the
138 /// block where scanning can start from, saving some work.
140 /// In a default-constructed MemDepResult object, the type will be Dirty
141 /// and the instruction pointer will be null.
144 /// isDirty - Return true if this is a MemDepResult in its dirty/invalid.
146 bool isDirty() const { return Value.getInt() == Invalid; }
148 static MemDepResult getDirty(Instruction *Inst) {
149 return MemDepResult(PairTy(Inst, Invalid));
153 /// NonLocalDepEntry - This is an entry in the NonLocalDepInfo cache. For
154 /// each BasicBlock (the BB entry) it keeps a MemDepResult.
155 class NonLocalDepEntry {
159 NonLocalDepEntry(BasicBlock *bb, MemDepResult result)
160 : BB(bb), Result(result) {}
162 // This is used for searches.
163 NonLocalDepEntry(BasicBlock *bb) : BB(bb) {}
165 // BB is the sort key, it can't be changed.
166 BasicBlock *getBB() const { return BB; }
168 void setResult(const MemDepResult &R) { Result = R; }
170 const MemDepResult &getResult() const { return Result; }
172 bool operator<(const NonLocalDepEntry &RHS) const {
177 /// NonLocalDepResult - This is a result from a NonLocal dependence query.
178 /// For each BasicBlock (the BB entry) it keeps a MemDepResult and the
179 /// (potentially phi translated) address that was live in the block.
180 class NonLocalDepResult {
181 NonLocalDepEntry Entry;
184 NonLocalDepResult(BasicBlock *bb, MemDepResult result, Value *address)
185 : Entry(bb, result), Address(address) {}
187 // BB is the sort key, it can't be changed.
188 BasicBlock *getBB() const { return Entry.getBB(); }
190 void setResult(const MemDepResult &R, Value *Addr) {
195 const MemDepResult &getResult() const { return Entry.getResult(); }
197 /// getAddress - Return the address of this pointer in this block. This can
198 /// be different than the address queried for the non-local result because
199 /// of phi translation. This returns null if the address was not available
200 /// in a block (i.e. because phi translation failed) or if this is a cached
201 /// result and that address was deleted.
203 /// The address is always null for a non-local 'call' dependence.
204 Value *getAddress() const { return Address; }
207 /// MemoryDependenceAnalysis - This is an analysis that determines, for a
208 /// given memory operation, what preceding memory operations it depends on.
209 /// It builds on alias analysis information, and tries to provide a lazy,
210 /// caching interface to a common kind of alias information query.
212 /// The dependency information returned is somewhat unusual, but is pragmatic.
213 /// If queried about a store or call that might modify memory, the analysis
214 /// will return the instruction[s] that may either load from that memory or
215 /// store to it. If queried with a load or call that can never modify memory,
216 /// the analysis will return calls and stores that might modify the pointer,
217 /// but generally does not return loads unless a) they are volatile, or
218 /// b) they load from *must-aliased* pointers. Returning a dependence on
219 /// must-alias'd pointers instead of all pointers interacts well with the
220 /// internal caching mechanism.
222 class MemoryDependenceAnalysis : public FunctionPass {
223 // A map from instructions to their dependency.
224 typedef DenseMap<Instruction*, MemDepResult> LocalDepMapType;
225 LocalDepMapType LocalDeps;
228 typedef std::vector<NonLocalDepEntry> NonLocalDepInfo;
230 /// ValueIsLoadPair - This is a pair<Value*, bool> where the bool is true if
231 /// the dependence is a read only dependence, false if read/write.
232 typedef PointerIntPair<const Value*, 1, bool> ValueIsLoadPair;
234 /// BBSkipFirstBlockPair - This pair is used when caching information for a
235 /// block. If the pointer is null, the cache value is not a full query that
236 /// starts at the specified block. If non-null, the bool indicates whether
237 /// or not the contents of the block was skipped.
238 typedef PointerIntPair<BasicBlock*, 1, bool> BBSkipFirstBlockPair;
240 /// NonLocalPointerInfo - This record is the information kept for each
241 /// (value, is load) pair.
242 struct NonLocalPointerInfo {
243 /// Pair - The pair of the block and the skip-first-block flag.
244 BBSkipFirstBlockPair Pair;
245 /// NonLocalDeps - The results of the query for each relevant block.
246 NonLocalDepInfo NonLocalDeps;
247 /// Size - The maximum size of the dereferences of the
248 /// pointer. May be UnknownSize if the sizes are unknown.
250 /// TBAATag - The TBAA tag associated with dereferences of the
251 /// pointer. May be null if there are no tags or conflicting tags.
252 const MDNode *TBAATag;
254 NonLocalPointerInfo() : Size(AliasAnalysis::UnknownSize), TBAATag(0) {}
257 /// CachedNonLocalPointerInfo - This map stores the cached results of doing
258 /// a pointer lookup at the bottom of a block. The key of this map is the
259 /// pointer+isload bit, the value is a list of <bb->result> mappings.
260 typedef DenseMap<ValueIsLoadPair,
261 NonLocalPointerInfo> CachedNonLocalPointerInfo;
262 CachedNonLocalPointerInfo NonLocalPointerDeps;
264 // A map from instructions to their non-local pointer dependencies.
265 typedef DenseMap<Instruction*,
266 SmallPtrSet<ValueIsLoadPair, 4> > ReverseNonLocalPtrDepTy;
267 ReverseNonLocalPtrDepTy ReverseNonLocalPtrDeps;
270 /// PerInstNLInfo - This is the instruction we keep for each cached access
271 /// that we have for an instruction. The pointer is an owning pointer and
272 /// the bool indicates whether we have any dirty bits in the set.
273 typedef std::pair<NonLocalDepInfo, bool> PerInstNLInfo;
275 // A map from instructions to their non-local dependencies.
276 typedef DenseMap<Instruction*, PerInstNLInfo> NonLocalDepMapType;
278 NonLocalDepMapType NonLocalDeps;
280 // A reverse mapping from dependencies to the dependees. This is
281 // used when removing instructions to keep the cache coherent.
282 typedef DenseMap<Instruction*,
283 SmallPtrSet<Instruction*, 4> > ReverseDepMapType;
284 ReverseDepMapType ReverseLocalDeps;
286 // A reverse mapping from dependencies to the non-local dependees.
287 ReverseDepMapType ReverseNonLocalDeps;
289 /// Current AA implementation, just a cache.
292 OwningPtr<PredIteratorCache> PredCache;
294 MemoryDependenceAnalysis();
295 ~MemoryDependenceAnalysis();
298 /// Pass Implementation stuff. This doesn't do any analysis eagerly.
299 bool runOnFunction(Function &);
301 /// Clean up memory in between runs
302 void releaseMemory();
304 /// getAnalysisUsage - Does not modify anything. It uses Value Numbering
305 /// and Alias Analysis.
307 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
309 /// getDependency - Return the instruction on which a memory operation
310 /// depends. See the class comment for more details. It is illegal to call
311 /// this on non-memory instructions.
312 MemDepResult getDependency(Instruction *QueryInst);
314 /// getNonLocalCallDependency - Perform a full dependency query for the
315 /// specified call, returning the set of blocks that the value is
316 /// potentially live across. The returned set of results will include a
317 /// "NonLocal" result for all blocks where the value is live across.
319 /// This method assumes the instruction returns a "NonLocal" dependency
320 /// within its own block.
322 /// This returns a reference to an internal data structure that may be
323 /// invalidated on the next non-local query or when an instruction is
324 /// removed. Clients must copy this data if they want it around longer than
326 const NonLocalDepInfo &getNonLocalCallDependency(CallSite QueryCS);
329 /// getNonLocalPointerDependency - Perform a full dependency query for an
330 /// access to the specified (non-volatile) memory location, returning the
331 /// set of instructions that either define or clobber the value.
333 /// This method assumes the pointer has a "NonLocal" dependency within BB.
334 void getNonLocalPointerDependency(const AliasAnalysis::Location &Loc,
335 bool isLoad, BasicBlock *BB,
336 SmallVectorImpl<NonLocalDepResult> &Result);
338 /// removeInstruction - Remove an instruction from the dependence analysis,
339 /// updating the dependence of instructions that previously depended on it.
340 void removeInstruction(Instruction *InstToRemove);
342 /// invalidateCachedPointerInfo - This method is used to invalidate cached
343 /// information about the specified pointer, because it may be too
344 /// conservative in memdep. This is an optional call that can be used when
345 /// the client detects an equivalence between the pointer and some other
346 /// value and replaces the other value with ptr. This can make Ptr available
347 /// in more places that cached info does not necessarily keep.
348 void invalidateCachedPointerInfo(Value *Ptr);
350 /// invalidateCachedPredecessors - Clear the PredIteratorCache info.
351 /// This needs to be done when the CFG changes, e.g., due to splitting
353 void invalidateCachedPredecessors();
355 /// getPointerDependencyFrom - Return the instruction on which a memory
356 /// location depends. If isLoad is true, this routine ignores may-aliases
357 /// with read-only operations. If isLoad is false, this routine ignores
358 /// may-aliases with reads from read-only locations.
360 /// Note that this is an uncached query, and thus may be inefficient.
362 MemDepResult getPointerDependencyFrom(const AliasAnalysis::Location &Loc,
364 BasicBlock::iterator ScanIt,
368 /// getLoadLoadClobberFullWidthSize - This is a little bit of analysis that
369 /// looks at a memory location for a load (specified by MemLocBase, Offs,
370 /// and Size) and compares it against a load. If the specified load could
371 /// be safely widened to a larger integer load that is 1) still efficient,
372 /// 2) safe for the target, and 3) would provide the specified memory
373 /// location value, then this function returns the size in bytes of the
374 /// load width to use. If not, this returns zero.
375 static unsigned getLoadLoadClobberFullWidthSize(const Value *MemLocBase,
379 const TargetData &TD);
382 MemDepResult getCallSiteDependencyFrom(CallSite C, bool isReadOnlyCall,
383 BasicBlock::iterator ScanIt,
385 bool getNonLocalPointerDepFromBB(const PHITransAddr &Pointer,
386 const AliasAnalysis::Location &Loc,
387 bool isLoad, BasicBlock *BB,
388 SmallVectorImpl<NonLocalDepResult> &Result,
389 DenseMap<BasicBlock*, Value*> &Visited,
390 bool SkipFirstBlock = false);
391 MemDepResult GetNonLocalInfoForBlock(const AliasAnalysis::Location &Loc,
392 bool isLoad, BasicBlock *BB,
393 NonLocalDepInfo *Cache,
394 unsigned NumSortedEntries);
396 void RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair P);
398 /// verifyRemoved - Verify that the specified instruction does not occur
399 /// in our internal data structures.
400 void verifyRemoved(Instruction *Inst) const;
404 } // End llvm namespace