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