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