Add a new method.
[oota-llvm.git] / include / llvm / Analysis / AliasSetTracker.h
1 //===- llvm/Analysis/AliasSetTracker.h - Build Alias Sets -------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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/iterator"
22 #include "llvm/ADT/hash_map"
23 #include "llvm/ADT/ilist"
24
25 namespace llvm {
26
27 class AliasAnalysis;
28 class LoadInst;
29 class StoreInst;
30 class FreeInst;
31 class AliasSetTracker;
32 class AliasSet;
33
34 class AliasSet {
35   friend class AliasSetTracker;
36
37   class PointerRec;
38   typedef std::pair<Value* const, PointerRec> HashNodePair;
39
40   class PointerRec {
41     HashNodePair **PrevInList, *NextInList;
42     AliasSet *AS;
43     unsigned Size;
44   public:
45     PointerRec() : PrevInList(0), NextInList(0), AS(0), Size(0) {}
46
47     HashNodePair *getNext() const { return NextInList; }
48     bool hasAliasSet() const { return AS != 0; }
49
50     HashNodePair** setPrevInList(HashNodePair **PIL) {
51       PrevInList = PIL;
52       return &NextInList;
53     }
54
55     void updateSize(unsigned NewSize) {
56       if (NewSize > Size) Size = NewSize;
57     }
58
59     unsigned getSize() const { return Size; }
60
61     AliasSet *getAliasSet(AliasSetTracker &AST) {
62       assert(AS && "No AliasSet yet!");
63       if (AS->Forward) {
64         AliasSet *OldAS = AS;
65         AS = OldAS->getForwardedTarget(AST);
66         AS->addRef();
67         OldAS->dropRef(AST);
68       }
69       return AS;
70     }
71
72     void setAliasSet(AliasSet *as) {
73       assert(AS == 0 && "Already have an alias set!");
74       AS = as;
75     }
76
77     void removeFromList() {
78       if (NextInList) NextInList->second.PrevInList = PrevInList;
79       *PrevInList = NextInList;
80       if (AS->PtrListEnd == &NextInList) {
81         AS->PtrListEnd = PrevInList;
82         assert(*AS->PtrListEnd == 0 && "List not terminated right!");
83       }
84     }
85   };
86
87   HashNodePair *PtrList, **PtrListEnd;  // Doubly linked list of nodes
88   AliasSet *Forward;             // Forwarding pointer
89   AliasSet *Next, *Prev;         // Doubly linked list of AliasSets
90
91   std::vector<CallSite> CallSites; // All calls & invokes in this node
92
93   // RefCount - Number of nodes pointing to this AliasSet plus the number of
94   // AliasSets forwarding to it.
95   unsigned RefCount : 28;
96
97   /// AccessType - Keep track of whether this alias set merely refers to the
98   /// locations of memory, whether it modifies the memory, or whether it does
99   /// both.  The lattice goes from "NoModRef" to either Refs or Mods, then to
100   /// ModRef as necessary.
101   ///
102   enum AccessType {
103     NoModRef = 0, Refs = 1,         // Ref = bit 1
104     Mods     = 2, ModRef = 3        // Mod = bit 2
105   };
106   unsigned AccessTy : 2;
107
108   /// AliasType - Keep track the relationships between the pointers in the set.
109   /// Lattice goes from MustAlias to MayAlias.
110   ///
111   enum AliasType {
112     MustAlias = 0, MayAlias = 1
113   };
114   unsigned AliasTy : 1;
115
116   // Volatile - True if this alias set contains volatile loads or stores.
117   bool Volatile : 1;
118
119   friend struct ilist_traits<AliasSet>;
120   AliasSet *getPrev() const { return Prev; }
121   AliasSet *getNext() const { return Next; }
122   void setPrev(AliasSet *P) { Prev = P; }
123   void setNext(AliasSet *N) { Next = N; }
124
125   void addRef() { ++RefCount; }
126   void dropRef(AliasSetTracker &AST) {
127     assert(RefCount >= 1 && "Invalid reference count detected!");
128     if (--RefCount == 0)
129       removeFromTracker(AST);
130   }
131
132 public:
133   /// Accessors...
134   bool isRef() const { return AccessTy & Refs; }
135   bool isMod() const { return AccessTy & Mods; }
136   bool isMustAlias() const { return AliasTy == MustAlias; }
137   bool isMayAlias()  const { return AliasTy == MayAlias; }
138
139   // isVolatile - Return true if this alias set contains volatile loads or
140   // stores.
141   bool isVolatile() const { return Volatile; }
142
143   /// isForwardingAliasSet - Return true if this alias set should be ignored as
144   /// part of the AliasSetTracker object.
145   bool isForwardingAliasSet() const { return Forward; }
146
147   /// mergeSetIn - Merge the specified alias set into this alias set...
148   ///
149   void mergeSetIn(AliasSet &AS, AliasSetTracker &AST);
150
151   // Alias Set iteration - Allow access to all of the pointer which are part of
152   // this alias set...
153   class iterator;
154   iterator begin() const { return iterator(PtrList); }
155   iterator end()   const { return iterator(); }
156   bool empty() const { return PtrList == 0; }
157
158   void print(std::ostream &OS) const;
159   void dump() const;
160
161   /// Define an iterator for alias sets... this is just a forward iterator.
162   class iterator : public forward_iterator<HashNodePair, ptrdiff_t> {
163     HashNodePair *CurNode;
164   public:
165     iterator(HashNodePair *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->first; }
184     unsigned getSize() const { return CurNode->second.getSize(); }
185
186     iterator& operator++() {                // Preincrement
187       assert(CurNode && "Advancing past AliasSet.end()!");
188       CurNode = CurNode->second.getNext();
189       return *this;
190     }
191     iterator operator++(int) { // Postincrement
192       iterator tmp = *this; ++*this; return tmp;
193     }
194   };
195
196 private:
197   // Can only be created by AliasSetTracker
198   AliasSet() : PtrList(0), PtrListEnd(&PtrList), Forward(0), RefCount(0),
199                AccessTy(NoModRef), AliasTy(MustAlias), Volatile(false) {
200   }
201
202   AliasSet(const AliasSet &AS) {
203     assert(0 && "Copy ctor called!?!?!");
204     abort();
205   }
206
207   HashNodePair *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, HashNodePair &Entry, unsigned Size,
229                   bool KnownMustAlias = false);
230   void addCallSite(CallSite CS, AliasAnalysis &AA);
231   void removeCallSite(CallSite CS) {
232     for (unsigned 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
247 inline std::ostream& operator<<(std::ostream &OS, const AliasSet &AS) {
248   AS.print(OS);
249   return OS;
250 }
251
252
253 class AliasSetTracker {
254   AliasAnalysis &AA;
255   ilist<AliasSet> AliasSets;
256
257   // Map from pointers to their node
258   hash_map<Value*, AliasSet::PointerRec> PointerMap;
259 public:
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   AliasSetTracker(AliasAnalysis &aa) : AA(aa) {}
264
265   /// add methods - These methods are used to add different types of
266   /// instructions to the alias sets.  Adding a new instruction can result in
267   /// one of three actions happening:
268   ///
269   ///   1. If the instruction doesn't alias any other sets, create a new set.
270   ///   2. If the instruction aliases exactly one set, add it to the set
271   ///   3. If the instruction aliases multiple sets, merge the sets, and add
272   ///      the instruction to the result.
273   ///
274   /// These methods return true if inserting the instruction resulted in the
275   /// addition of a new alias set (i.e., the pointer did not alias anything).
276   ///
277   bool add(Value *Ptr, unsigned Size);  // Add a location
278   bool add(LoadInst *LI);
279   bool add(StoreInst *SI);
280   bool add(FreeInst *FI);
281   bool add(CallSite CS);          // Call/Invoke instructions
282   bool add(CallInst *CI)   { return add(CallSite(CI)); }
283   bool add(InvokeInst *II) { return add(CallSite(II)); }
284   bool add(Instruction *I);       // Dispatch to one of the other add methods...
285   void add(BasicBlock &BB);       // Add all instructions in basic block
286   void add(const AliasSetTracker &AST); // Add alias relations from another AST
287
288   /// remove methods - These methods are used to remove all entries that might
289   /// be aliased by the specified instruction.  These methods return true if any
290   /// alias sets were eliminated.
291   bool remove(Value *Ptr, unsigned Size);  // Remove a location
292   bool remove(LoadInst *LI);
293   bool remove(StoreInst *SI);
294   bool remove(FreeInst *FI);
295   bool remove(CallSite CS);
296   bool remove(CallInst *CI)   { return remove(CallSite(CI)); }
297   bool remove(InvokeInst *II) { return remove(CallSite(II)); }
298   bool remove(Instruction *I);
299   void remove(AliasSet &AS);
300   
301   void clear() {
302     PointerMap.clear();
303     AliasSets.clear();
304   }
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 dump() const;
358
359 private:
360   friend class AliasSet;
361   void removeAliasSet(AliasSet *AS);
362
363   AliasSet::HashNodePair &getEntryFor(Value *V) {
364     // Standard operator[], except that it returns the whole pair, not just
365     // ->second.
366     return *PointerMap.insert(AliasSet::HashNodePair(V,
367                                             AliasSet::PointerRec())).first;
368   }
369
370   AliasSet &addPointer(Value *P, unsigned Size, AliasSet::AccessType E,
371                        bool &NewSet) {
372     NewSet = false;
373     AliasSet &AS = getAliasSetForPointer(P, Size, &NewSet);
374     AS.AccessTy |= E;
375     return AS;
376   }
377   AliasSet *findAliasSetForPointer(const Value *Ptr, unsigned Size);
378
379   AliasSet *findAliasSetForCallSite(CallSite CS);
380 };
381
382 inline std::ostream& operator<<(std::ostream &OS, const AliasSetTracker &AST) {
383   AST.print(OS);
384   return OS;
385 }
386
387 } // End llvm namespace
388
389 #endif