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