AliasSetTracker.h revision 7ffafe4102ec4b8491a82e700076c85bd692ec84
16d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)//===- llvm/Analysis/AliasSetTracker.h - Build Alias Sets -------*- C++ -*-===//
26d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)//
36d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)//                     The LLVM Compiler Infrastructure
46d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)//
5116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch// This file is distributed under the University of Illinois Open Source
66d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)// License. See LICENSE.TXT for details.
76d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)//
86d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)//===----------------------------------------------------------------------===//
96d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)//
106d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)// This file defines two classes: AliasSetTracker and AliasSet.  These interface
116d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)// are used to classify a collection of pointer references into a maximal number
126d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)// of disjoint sets.  Each AliasSet object constructed by the AliasSetTracker
136d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)// object refers to memory disjoint from the other sets.
146d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)//
156d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)//===----------------------------------------------------------------------===//
166d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)
176d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)#ifndef LLVM_ANALYSIS_ALIASSETTRACKER_H
186d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)#define LLVM_ANALYSIS_ALIASSETTRACKER_H
196d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)
206d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)#include "llvm/Support/CallSite.h"
216d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)#include "llvm/Support/ValueHandle.h"
226d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)#include "llvm/ADT/DenseMap.h"
236d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)#include "llvm/ADT/ilist.h"
246d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)#include "llvm/ADT/ilist_node.h"
256d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)#include <vector>
266d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)
276d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)namespace llvm {
286d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)
296d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)class AliasAnalysis;
306d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)class LoadInst;
316d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)class StoreInst;
326d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)class VAArgInst;
336d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)class AliasSetTracker;
346d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)class AliasSet;
356d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)
366d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)class AliasSet : public ilist_node<AliasSet> {
376d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)  friend class AliasSetTracker;
386d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)
396d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)  class PointerRec {
406d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)    Value *Val;  // The pointer this record corresponds to.
416d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)    PointerRec **PrevInList, *NextInList;
426d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)    AliasSet *AS;
436d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)    uint64_t Size;
44    const MDNode *TBAAInfo;
45  public:
46    PointerRec(Value *V)
47      : Val(V), PrevInList(0), NextInList(0), AS(0), Size(0),
48        TBAAInfo(DenseMapInfo<const MDNode *>::getEmptyKey()) {}
49
50    Value *getValue() const { return Val; }
51
52    PointerRec *getNext() const { return NextInList; }
53    bool hasAliasSet() const { return AS != 0; }
54
55    PointerRec** setPrevInList(PointerRec **PIL) {
56      PrevInList = PIL;
57      return &NextInList;
58    }
59
60    void updateSizeAndTBAAInfo(uint64_t NewSize, const MDNode *NewTBAAInfo) {
61      if (NewSize > Size) Size = NewSize;
62
63      if (TBAAInfo == DenseMapInfo<const MDNode *>::getEmptyKey())
64        // We don't have a TBAAInfo yet. Set it to NewTBAAInfo.
65        TBAAInfo = NewTBAAInfo;
66      else if (TBAAInfo != NewTBAAInfo)
67        // NewTBAAInfo conflicts with TBAAInfo.
68        TBAAInfo = DenseMapInfo<const MDNode *>::getTombstoneKey();
69    }
70
71    uint64_t getSize() const { return Size; }
72
73    /// getTBAAInfo - Return the TBAAInfo, or null if there is no
74    /// information or conflicting information.
75    const MDNode *getTBAAInfo() const {
76      // If we have missing or conflicting TBAAInfo, return null.
77      if (TBAAInfo == DenseMapInfo<const MDNode *>::getEmptyKey() ||
78          TBAAInfo == DenseMapInfo<const MDNode *>::getTombstoneKey())
79        return 0;
80      return TBAAInfo;
81    }
82
83    AliasSet *getAliasSet(AliasSetTracker &AST) {
84      assert(AS && "No AliasSet yet!");
85      if (AS->Forward) {
86        AliasSet *OldAS = AS;
87        AS = OldAS->getForwardedTarget(AST);
88        AS->addRef();
89        OldAS->dropRef(AST);
90      }
91      return AS;
92    }
93
94    void setAliasSet(AliasSet *as) {
95      assert(AS == 0 && "Already have an alias set!");
96      AS = as;
97    }
98
99    void eraseFromList() {
100      if (NextInList) NextInList->PrevInList = PrevInList;
101      *PrevInList = NextInList;
102      if (AS->PtrListEnd == &NextInList) {
103        AS->PtrListEnd = PrevInList;
104        assert(*AS->PtrListEnd == 0 && "List not terminated right!");
105      }
106      delete this;
107    }
108  };
109
110  PointerRec *PtrList, **PtrListEnd;  // Doubly linked list of nodes.
111  AliasSet *Forward;             // Forwarding pointer.
112
113  // All instructions without a specific address in this alias set.
114  std::vector<AssertingVH<Instruction> > UnknownInsts;
115
116  // RefCount - Number of nodes pointing to this AliasSet plus the number of
117  // AliasSets forwarding to it.
118  unsigned RefCount : 28;
119
120  /// AccessType - Keep track of whether this alias set merely refers to the
121  /// locations of memory, whether it modifies the memory, or whether it does
122  /// both.  The lattice goes from "NoModRef" to either Refs or Mods, then to
123  /// ModRef as necessary.
124  ///
125  enum AccessType {
126    NoModRef = 0, Refs = 1,         // Ref = bit 1
127    Mods     = 2, ModRef = 3        // Mod = bit 2
128  };
129  unsigned AccessTy : 2;
130
131  /// AliasType - Keep track the relationships between the pointers in the set.
132  /// Lattice goes from MustAlias to MayAlias.
133  ///
134  enum AliasType {
135    MustAlias = 0, MayAlias = 1
136  };
137  unsigned AliasTy : 1;
138
139  // Volatile - True if this alias set contains volatile loads or stores.
140  bool Volatile : 1;
141
142  void addRef() { ++RefCount; }
143  void dropRef(AliasSetTracker &AST) {
144    assert(RefCount >= 1 && "Invalid reference count detected!");
145    if (--RefCount == 0)
146      removeFromTracker(AST);
147  }
148
149  Instruction *getUnknownInst(unsigned i) const {
150    assert(i < UnknownInsts.size());
151    return UnknownInsts[i];
152  }
153
154public:
155  /// Accessors...
156  bool isRef() const { return AccessTy & Refs; }
157  bool isMod() const { return AccessTy & Mods; }
158  bool isMustAlias() const { return AliasTy == MustAlias; }
159  bool isMayAlias()  const { return AliasTy == MayAlias; }
160
161  // isVolatile - Return true if this alias set contains volatile loads or
162  // stores.
163  bool isVolatile() const { return Volatile; }
164
165  /// isForwardingAliasSet - Return true if this alias set should be ignored as
166  /// part of the AliasSetTracker object.
167  bool isForwardingAliasSet() const { return Forward; }
168
169  /// mergeSetIn - Merge the specified alias set into this alias set...
170  ///
171  void mergeSetIn(AliasSet &AS, AliasSetTracker &AST);
172
173  // Alias Set iteration - Allow access to all of the pointer which are part of
174  // this alias set...
175  class iterator;
176  iterator begin() const { return iterator(PtrList); }
177  iterator end()   const { return iterator(); }
178  bool empty() const { return PtrList == 0; }
179
180  void print(raw_ostream &OS) const;
181  void dump() const;
182
183  /// Define an iterator for alias sets... this is just a forward iterator.
184  class iterator : public std::iterator<std::forward_iterator_tag,
185                                        PointerRec, ptrdiff_t> {
186    PointerRec *CurNode;
187  public:
188    explicit iterator(PointerRec *CN = 0) : CurNode(CN) {}
189
190    bool operator==(const iterator& x) const {
191      return CurNode == x.CurNode;
192    }
193    bool operator!=(const iterator& x) const { return !operator==(x); }
194
195    const iterator &operator=(const iterator &I) {
196      CurNode = I.CurNode;
197      return *this;
198    }
199
200    value_type &operator*() const {
201      assert(CurNode && "Dereferencing AliasSet.end()!");
202      return *CurNode;
203    }
204    value_type *operator->() const { return &operator*(); }
205
206    Value *getPointer() const { return CurNode->getValue(); }
207    uint64_t getSize() const { return CurNode->getSize(); }
208    const MDNode *getTBAAInfo() const { return CurNode->getTBAAInfo(); }
209
210    iterator& operator++() {                // Preincrement
211      assert(CurNode && "Advancing past AliasSet.end()!");
212      CurNode = CurNode->getNext();
213      return *this;
214    }
215    iterator operator++(int) { // Postincrement
216      iterator tmp = *this; ++*this; return tmp;
217    }
218  };
219
220private:
221  // Can only be created by AliasSetTracker. Also, ilist creates one
222  // to serve as a sentinel.
223  friend struct ilist_sentinel_traits<AliasSet>;
224  AliasSet() : PtrList(0), PtrListEnd(&PtrList), Forward(0), RefCount(0),
225               AccessTy(NoModRef), AliasTy(MustAlias), Volatile(false) {
226  }
227
228  AliasSet(const AliasSet &AS);        // do not implement
229  void operator=(const AliasSet &AS);  // do not implement
230
231  PointerRec *getSomePointer() const {
232    return PtrList;
233  }
234
235  /// getForwardedTarget - Return the real alias set this represents.  If this
236  /// has been merged with another set and is forwarding, return the ultimate
237  /// destination set.  This also implements the union-find collapsing as well.
238  AliasSet *getForwardedTarget(AliasSetTracker &AST) {
239    if (!Forward) return this;
240
241    AliasSet *Dest = Forward->getForwardedTarget(AST);
242    if (Dest != Forward) {
243      Dest->addRef();
244      Forward->dropRef(AST);
245      Forward = Dest;
246    }
247    return Dest;
248  }
249
250  void removeFromTracker(AliasSetTracker &AST);
251
252  void addPointer(AliasSetTracker &AST, PointerRec &Entry, uint64_t Size,
253                  const MDNode *TBAAInfo,
254                  bool KnownMustAlias = false);
255  void addUnknownInst(Instruction *I, AliasAnalysis &AA);
256  void removeUnknownInst(Instruction *I) {
257    for (size_t i = 0, e = UnknownInsts.size(); i != e; ++i)
258      if (UnknownInsts[i] == I) {
259        UnknownInsts[i] = UnknownInsts.back();
260        UnknownInsts.pop_back();
261        --i; --e;  // Revisit the moved entry.
262      }
263  }
264  void setVolatile() { Volatile = true; }
265
266public:
267  /// aliasesPointer - Return true if the specified pointer "may" (or must)
268  /// alias one of the members in the set.
269  ///
270  bool aliasesPointer(const Value *Ptr, uint64_t Size, const MDNode *TBAAInfo,
271                      AliasAnalysis &AA) const;
272  bool aliasesUnknownInst(Instruction *Inst, AliasAnalysis &AA) const;
273};
274
275inline raw_ostream& operator<<(raw_ostream &OS, const AliasSet &AS) {
276  AS.print(OS);
277  return OS;
278}
279
280
281class AliasSetTracker {
282  /// CallbackVH - A CallbackVH to arrange for AliasSetTracker to be
283  /// notified whenever a Value is deleted.
284  class ASTCallbackVH : public CallbackVH {
285    AliasSetTracker *AST;
286    virtual void deleted();
287    virtual void allUsesReplacedWith(Value *);
288  public:
289    ASTCallbackVH(Value *V, AliasSetTracker *AST = 0);
290    ASTCallbackVH &operator=(Value *V);
291  };
292  /// ASTCallbackVHDenseMapInfo - Traits to tell DenseMap that tell us how to
293  /// compare and hash the value handle.
294  struct ASTCallbackVHDenseMapInfo : public DenseMapInfo<Value *> {};
295
296  AliasAnalysis &AA;
297  ilist<AliasSet> AliasSets;
298
299  typedef DenseMap<ASTCallbackVH, AliasSet::PointerRec*,
300                   ASTCallbackVHDenseMapInfo>
301    PointerMapType;
302
303  // Map from pointers to their node
304  PointerMapType PointerMap;
305
306public:
307  /// AliasSetTracker ctor - Create an empty collection of AliasSets, and use
308  /// the specified alias analysis object to disambiguate load and store
309  /// addresses.
310  explicit AliasSetTracker(AliasAnalysis &aa) : AA(aa) {}
311  ~AliasSetTracker() { clear(); }
312
313  /// add methods - These methods are used to add different types of
314  /// instructions to the alias sets.  Adding a new instruction can result in
315  /// one of three actions happening:
316  ///
317  ///   1. If the instruction doesn't alias any other sets, create a new set.
318  ///   2. If the instruction aliases exactly one set, add it to the set
319  ///   3. If the instruction aliases multiple sets, merge the sets, and add
320  ///      the instruction to the result.
321  ///
322  /// These methods return true if inserting the instruction resulted in the
323  /// addition of a new alias set (i.e., the pointer did not alias anything).
324  ///
325  bool add(Value *Ptr, uint64_t Size, const MDNode *TBAAInfo); // Add a location
326  bool add(LoadInst *LI);
327  bool add(StoreInst *SI);
328  bool add(VAArgInst *VAAI);
329  bool add(Instruction *I);       // Dispatch to one of the other add methods...
330  void add(BasicBlock &BB);       // Add all instructions in basic block
331  void add(const AliasSetTracker &AST); // Add alias relations from another AST
332  bool addUnknown(Instruction *I);
333
334  /// remove methods - These methods are used to remove all entries that might
335  /// be aliased by the specified instruction.  These methods return true if any
336  /// alias sets were eliminated.
337  // Remove a location
338  bool remove(Value *Ptr, uint64_t Size, const MDNode *TBAAInfo);
339  bool remove(LoadInst *LI);
340  bool remove(StoreInst *SI);
341  bool remove(VAArgInst *VAAI);
342  bool remove(Instruction *I);
343  void remove(AliasSet &AS);
344  bool removeUnknown(Instruction *I);
345
346  void clear();
347
348  /// getAliasSets - Return the alias sets that are active.
349  ///
350  const ilist<AliasSet> &getAliasSets() const { return AliasSets; }
351
352  /// getAliasSetForPointer - Return the alias set that the specified pointer
353  /// lives in.  If the New argument is non-null, this method sets the value to
354  /// true if a new alias set is created to contain the pointer (because the
355  /// pointer didn't alias anything).
356  AliasSet &getAliasSetForPointer(Value *P, uint64_t Size,
357                                  const MDNode *TBAAInfo,
358                                  bool *New = 0);
359
360  /// getAliasSetForPointerIfExists - Return the alias set containing the
361  /// location specified if one exists, otherwise return null.
362  AliasSet *getAliasSetForPointerIfExists(Value *P, uint64_t Size,
363                                          const MDNode *TBAAInfo) {
364    return findAliasSetForPointer(P, Size, TBAAInfo);
365  }
366
367  /// containsPointer - Return true if the specified location is represented by
368  /// this alias set, false otherwise.  This does not modify the AST object or
369  /// alias sets.
370  bool containsPointer(Value *P, uint64_t Size, const MDNode *TBAAInfo) const;
371
372  /// getAliasAnalysis - Return the underlying alias analysis object used by
373  /// this tracker.
374  AliasAnalysis &getAliasAnalysis() const { return AA; }
375
376  /// deleteValue method - This method is used to remove a pointer value from
377  /// the AliasSetTracker entirely.  It should be used when an instruction is
378  /// deleted from the program to update the AST.  If you don't use this, you
379  /// would have dangling pointers to deleted instructions.
380  ///
381  void deleteValue(Value *PtrVal);
382
383  /// copyValue - This method should be used whenever a preexisting value in the
384  /// program is copied or cloned, introducing a new value.  Note that it is ok
385  /// for clients that use this method to introduce the same value multiple
386  /// times: if the tracker already knows about a value, it will ignore the
387  /// request.
388  ///
389  void copyValue(Value *From, Value *To);
390
391
392  typedef ilist<AliasSet>::iterator iterator;
393  typedef ilist<AliasSet>::const_iterator const_iterator;
394
395  const_iterator begin() const { return AliasSets.begin(); }
396  const_iterator end()   const { return AliasSets.end(); }
397
398  iterator begin() { return AliasSets.begin(); }
399  iterator end()   { return AliasSets.end(); }
400
401  void print(raw_ostream &OS) const;
402  void dump() const;
403
404private:
405  friend class AliasSet;
406  void removeAliasSet(AliasSet *AS);
407
408  // getEntryFor - Just like operator[] on the map, except that it creates an
409  // entry for the pointer if it doesn't already exist.
410  AliasSet::PointerRec &getEntryFor(Value *V) {
411    AliasSet::PointerRec *&Entry = PointerMap[ASTCallbackVH(V, this)];
412    if (Entry == 0)
413      Entry = new AliasSet::PointerRec(V);
414    return *Entry;
415  }
416
417  AliasSet &addPointer(Value *P, uint64_t Size, const MDNode *TBAAInfo,
418                       AliasSet::AccessType E,
419                       bool &NewSet) {
420    NewSet = false;
421    AliasSet &AS = getAliasSetForPointer(P, Size, TBAAInfo, &NewSet);
422    AS.AccessTy |= E;
423    return AS;
424  }
425  AliasSet *findAliasSetForPointer(const Value *Ptr, uint64_t Size,
426                                   const MDNode *TBAAInfo);
427
428  AliasSet *findAliasSetForUnknownInst(Instruction *Inst);
429};
430
431inline raw_ostream& operator<<(raw_ostream &OS, const AliasSetTracker &AST) {
432  AST.print(OS);
433  return OS;
434}
435
436} // End llvm namespace
437
438#endif
439