Add some new methods
[oota-llvm.git] / lib / Analysis / AliasSetTracker.cpp
1 //===- AliasSetTracker.cpp - Alias Sets Tracker implementation-------------===//
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 implements the AliasSetTracker and AliasSet classes.
11 // 
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Analysis/AliasSetTracker.h"
15 #include "llvm/Analysis/AliasAnalysis.h"
16 #include "llvm/iMemory.h"
17 #include "llvm/iOther.h"
18 #include "llvm/iTerminators.h"
19 #include "llvm/Pass.h"
20 #include "llvm/Target/TargetData.h"
21 #include "llvm/Assembly/Writer.h"
22 #include "llvm/Support/InstIterator.h"
23 #include <iostream>
24 using namespace llvm;
25
26 /// mergeSetIn - Merge the specified alias set into this alias set...
27 ///
28 void AliasSet::mergeSetIn(AliasSet &AS) {
29   assert(!AS.Forward && "Alias set is already forwarding!");
30   assert(!Forward && "This set is a forwarding set!!");
31
32   // Update the alias and access types of this set...
33   AccessTy |= AS.AccessTy;
34   AliasTy  |= AS.AliasTy;
35
36   if (CallSites.empty()) {            // Merge call sites...
37     if (!AS.CallSites.empty())
38       std::swap(CallSites, AS.CallSites);
39   } else if (!AS.CallSites.empty()) {
40     CallSites.insert(CallSites.end(), AS.CallSites.begin(), AS.CallSites.end());
41     AS.CallSites.clear();
42   }
43   
44   // FIXME: If AS's refcount is zero, nuke it now...
45   assert(RefCount != 0);
46
47   AS.Forward = this;  // Forward across AS now...
48   addRef();           // AS is now pointing to us...
49
50   // Merge the list of constituent pointers...
51   if (AS.PtrList) {
52     *PtrListEnd = AS.PtrList;
53     AS.PtrList->second.setPrevInList(PtrListEnd);
54     PtrListEnd = AS.PtrListEnd;
55
56     AS.PtrList = 0;
57     AS.PtrListEnd = &AS.PtrList;
58   }
59 }
60
61 void AliasSetTracker::removeAliasSet(AliasSet *AS) {
62   if (AliasSet *Fwd = AS->Forward) {
63     Fwd->dropRef(*this);
64     AS->Forward = 0;
65   }
66   AliasSets.erase(AS);
67 }
68
69 void AliasSet::removeFromTracker(AliasSetTracker &AST) {
70   assert(RefCount == 0 && "Cannot remove non-dead alias set from tracker!");
71   AST.removeAliasSet(this);
72 }
73
74 void AliasSet::addPointer(AliasSetTracker &AST, HashNodePair &Entry,
75                           unsigned Size) {
76   assert(!Entry.second.hasAliasSet() && "Entry already in set!");
77
78   AliasAnalysis &AA = AST.getAliasAnalysis();
79
80   if (isMustAlias())    // Check to see if we have to downgrade to _may_ alias
81     if (HashNodePair *P = getSomePointer()) {
82       AliasAnalysis::AliasResult Result =
83         AA.alias(P->first, P->second.getSize(), Entry.first, Size);
84       if (Result == AliasAnalysis::MayAlias)
85         AliasTy = MayAlias;
86       else                  // First entry of must alias must have maximum size!
87         P->second.updateSize(Size);
88       assert(Result != AliasAnalysis::NoAlias && "Cannot be part of must set!");
89     }
90
91   Entry.second.setAliasSet(this);
92   Entry.second.updateSize(Size);
93
94   // Add it to the end of the list...
95   assert(*PtrListEnd == 0 && "End of list is not null?");
96   *PtrListEnd = &Entry;
97   PtrListEnd = Entry.second.setPrevInList(PtrListEnd);
98   addRef();               // Entry points to alias set...
99 }
100
101 void AliasSet::addCallSite(CallSite CS, AliasAnalysis &AA) {
102   CallSites.push_back(CS);
103
104   if (Function *F = CS.getCalledFunction()) {
105     if (AA.doesNotAccessMemory(F))
106       return;
107     else if (AA.onlyReadsMemory(F)) {
108       AliasTy = MayAlias;
109       AccessTy |= Refs;
110       return;
111     }
112   }
113
114   // FIXME: This should use mod/ref information to make this not suck so bad
115   AliasTy = MayAlias;
116   AccessTy = ModRef;
117 }
118
119 /// aliasesPointer - Return true if the specified pointer "may" (or must)
120 /// alias one of the members in the set.
121 ///
122 bool AliasSet::aliasesPointer(const Value *Ptr, unsigned Size,
123                               AliasAnalysis &AA) const {
124   if (AliasTy == MustAlias) {
125     assert(CallSites.empty() && "Illegal must alias set!");
126
127     // If this is a set of MustAliases, only check to see if the pointer aliases
128     // SOME value in the set...
129     HashNodePair *SomePtr = getSomePointer();
130     assert(SomePtr && "Empty must-alias set??");
131     return AA.alias(SomePtr->first, SomePtr->second.getSize(), Ptr, Size);
132   }
133
134   // If this is a may-alias set, we have to check all of the pointers in the set
135   // to be sure it doesn't alias the set...
136   for (iterator I = begin(), E = end(); I != E; ++I)
137     if (AA.alias(Ptr, Size, I.getPointer(), I.getSize()))
138       return true;
139
140   // Check the call sites list and invoke list...
141   if (!CallSites.empty())
142     // FIXME: this is pessimistic!
143     return true;
144
145   return false;
146 }
147
148 bool AliasSet::aliasesCallSite(CallSite CS, AliasAnalysis &AA) const {
149   // FIXME: Use mod/ref information to prune this better!
150   if (Function *F = CS.getCalledFunction())
151     if (AA.doesNotAccessMemory(F))
152       return false;
153
154   return true;
155 }
156
157
158 /// findAliasSetForPointer - Given a pointer, find the one alias set to put the
159 /// instruction referring to the pointer into.  If there are multiple alias sets
160 /// that may alias the pointer, merge them together and return the unified set.
161 ///
162 AliasSet *AliasSetTracker::findAliasSetForPointer(const Value *Ptr,
163                                                   unsigned Size) {
164   AliasSet *FoundSet = 0;
165   for (iterator I = begin(), E = end(); I != E; ++I)
166     if (!I->Forward && I->aliasesPointer(Ptr, Size, AA)) {
167       if (FoundSet == 0) {  // If this is the first alias set ptr can go into...
168         FoundSet = I;       // Remember it.
169       } else {              // Otherwise, we must merge the sets...
170         FoundSet->mergeSetIn(*I);     // Merge in contents...
171       }
172     }
173
174   return FoundSet;
175 }
176
177 AliasSet *AliasSetTracker::findAliasSetForCallSite(CallSite CS) {
178   AliasSet *FoundSet = 0;
179   for (iterator I = begin(), E = end(); I != E; ++I)
180     if (!I->Forward && I->aliasesCallSite(CS, AA)) {
181       if (FoundSet == 0) {  // If this is the first alias set ptr can go into...
182         FoundSet = I;       // Remember it.
183       } else if (!I->Forward) {     // Otherwise, we must merge the sets...
184         FoundSet->mergeSetIn(*I);     // Merge in contents...
185       }
186     }
187
188   return FoundSet;
189 }
190
191
192
193
194 /// getAliasSetForPointer - Return the alias set that the specified pointer
195 /// lives in...
196 AliasSet &AliasSetTracker::getAliasSetForPointer(Value *Pointer, unsigned Size,
197                                                  bool *New) {
198   AliasSet::HashNodePair &Entry = getEntryFor(Pointer);
199
200   // Check to see if the pointer is already known...
201   if (Entry.second.hasAliasSet()) {
202     Entry.second.updateSize(Size);
203     // Return the set!
204     return *Entry.second.getAliasSet(*this)->getForwardedTarget(*this);
205   } else if (AliasSet *AS = findAliasSetForPointer(Pointer, Size)) {
206     // Add it to the alias set it aliases...
207     AS->addPointer(*this, Entry, Size);
208     return *AS;
209   } else {
210     if (New) *New = true;
211     // Otherwise create a new alias set to hold the loaded pointer...
212     AliasSets.push_back(new AliasSet());
213     AliasSets.back().addPointer(*this, Entry, Size);
214     return AliasSets.back();
215   }
216 }
217
218 bool AliasSetTracker::add(Value *Ptr, unsigned Size) {
219   bool NewPtr;
220   addPointer(Ptr, Size, AliasSet::NoModRef, NewPtr);
221   return NewPtr;
222 }
223
224
225 bool AliasSetTracker::add(LoadInst *LI) {
226   bool NewPtr;
227   AliasSet &AS = addPointer(LI->getOperand(0),
228                             AA.getTargetData().getTypeSize(LI->getType()),
229                             AliasSet::Refs, NewPtr);
230   if (LI->isVolatile()) AS.setVolatile();
231   return NewPtr;
232 }
233
234 bool AliasSetTracker::add(StoreInst *SI) {
235   bool NewPtr;
236   Value *Val = SI->getOperand(0);
237   AliasSet &AS = addPointer(SI->getOperand(1),
238                             AA.getTargetData().getTypeSize(Val->getType()),
239                             AliasSet::Mods, NewPtr);
240   if (SI->isVolatile()) AS.setVolatile();
241   return NewPtr;
242 }
243
244 bool AliasSetTracker::add(FreeInst *FI) {
245   bool NewPtr;
246   AliasSet &AS = addPointer(FI->getOperand(0), ~0,
247                             AliasSet::Mods, NewPtr);
248   return NewPtr;
249 }
250
251
252 bool AliasSetTracker::add(CallSite CS) {
253   bool NewPtr;
254   if (Function *F = CS.getCalledFunction())
255     if (AA.doesNotAccessMemory(F))
256       return true; // doesn't alias anything
257
258   AliasSet *AS = findAliasSetForCallSite(CS);
259   if (!AS) {
260     AliasSets.push_back(new AliasSet());
261     AS = &AliasSets.back();
262     AS->addCallSite(CS, AA);
263     return true;
264   } else {
265     AS->addCallSite(CS, AA);
266     return false;
267   }
268 }
269
270 bool AliasSetTracker::add(Instruction *I) {
271   // Dispatch to one of the other add methods...
272   if (LoadInst *LI = dyn_cast<LoadInst>(I))
273     return add(LI);
274   else if (StoreInst *SI = dyn_cast<StoreInst>(I))
275     return add(SI);
276   else if (CallInst *CI = dyn_cast<CallInst>(I))
277     return add(CI);
278   else if (InvokeInst *II = dyn_cast<InvokeInst>(I))
279     return add(II);
280   else if (FreeInst *FI = dyn_cast<FreeInst>(I))
281     return add(FI);
282   return true;
283 }
284
285 void AliasSetTracker::add(BasicBlock &BB) {
286   for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
287     add(I);
288 }
289
290 void AliasSetTracker::add(const AliasSetTracker &AST) {
291   assert(&AA == &AST.AA &&
292          "Merging AliasSetTracker objects with different Alias Analyses!");
293
294   // Loop over all of the alias sets in AST, adding the pointers contained
295   // therein into the current alias sets.  This can cause alias sets to be
296   // merged together in the current AST.
297   for (const_iterator I = AST.begin(), E = AST.end(); I != E; ++I)
298     if (!I->Forward) {   // Ignore forwarding alias sets
299       AliasSet &AS = const_cast<AliasSet&>(*I);
300
301       // If there are any call sites in the alias set, add them to this AST.
302       for (unsigned i = 0, e = AS.CallSites.size(); i != e; ++i)
303         add(AS.CallSites[i]);
304
305       // Loop over all of the pointers in this alias set...
306       AliasSet::iterator I = AS.begin(), E = AS.end();
307       bool X;
308       for (; I != E; ++I)
309         addPointer(I.getPointer(), I.getSize(),
310                    (AliasSet::AccessType)AS.AccessTy, X);
311     }
312 }
313
314 /// remove - Remove the specified (potentially non-empty) alias set from the
315 /// tracker.
316 void AliasSetTracker::remove(AliasSet &AS) {
317   bool SetDead;
318   do {
319     AliasSet::iterator I = AS.begin();
320     Value *Ptr = I.getPointer(); ++I;
321
322     // deleteValue will delete the set automatically when the last pointer
323     // reference is destroyed.  "Predict" when this will happen.
324     SetDead = I == AS.end();
325     deleteValue(Ptr);  // Delete all of the pointers from the set
326   } while (!SetDead);
327 }
328
329 bool AliasSetTracker::remove(Value *Ptr, unsigned Size) {
330   AliasSet *AS = findAliasSetForPointer(Ptr, Size);
331   if (!AS) return false;
332   remove(*AS);
333   return true;
334 }
335
336 bool AliasSetTracker::remove(LoadInst *LI) {
337   unsigned Size = AA.getTargetData().getTypeSize(LI->getType());
338   AliasSet *AS = findAliasSetForPointer(LI->getOperand(0), Size);
339   if (!AS) return false;
340   remove(*AS);
341   return true;
342 }
343
344 bool AliasSetTracker::remove(StoreInst *SI) {
345   unsigned Size = AA.getTargetData().getTypeSize(SI->getOperand(0)->getType());
346   AliasSet *AS = findAliasSetForPointer(SI->getOperand(1), Size);
347   if (!AS) return false;
348   remove(*AS);
349   return true;
350 }
351
352 bool AliasSetTracker::remove(FreeInst *FI) {
353   AliasSet *AS = findAliasSetForPointer(FI->getOperand(0), ~0);
354   if (!AS) return false;
355   remove(*AS);
356   return true;
357 }
358
359 bool AliasSetTracker::remove(CallSite CS) {
360   if (Function *F = CS.getCalledFunction())
361     if (AA.doesNotAccessMemory(F))
362       return false; // doesn't alias anything
363
364   AliasSet *AS = findAliasSetForCallSite(CS);
365   if (!AS) return false;
366   remove(*AS);
367   return true;
368 }
369
370 bool AliasSetTracker::remove(Instruction *I) {
371   // Dispatch to one of the other remove methods...
372   if (LoadInst *LI = dyn_cast<LoadInst>(I))
373     return remove(LI);
374   else if (StoreInst *SI = dyn_cast<StoreInst>(I))
375     return remove(SI);
376   else if (CallInst *CI = dyn_cast<CallInst>(I))
377     return remove(CI);
378   else if (FreeInst *FI = dyn_cast<FreeInst>(I))
379     return remove(FI);
380   return true;
381 }
382
383
384 // deleteValue method - This method is used to remove a pointer value from the
385 // AliasSetTracker entirely.  It should be used when an instruction is deleted
386 // from the program to update the AST.  If you don't use this, you would have
387 // dangling pointers to deleted instructions.
388 //
389 void AliasSetTracker::deleteValue(Value *PtrVal) {
390   // First, look up the PointerRec for this pointer...
391   hash_map<Value*, AliasSet::PointerRec>::iterator I = PointerMap.find(PtrVal);
392   if (I == PointerMap.end()) return;  // Noop
393
394   // If we found one, remove the pointer from the alias set it is in.
395   AliasSet::HashNodePair &PtrValEnt = *I;
396   AliasSet *AS = PtrValEnt.second.getAliasSet(*this);
397
398   // Unlink from the list of values...
399   PtrValEnt.second.removeFromList();
400   // Stop using the alias set
401   AS->dropRef(*this);
402   PointerMap.erase(I);
403 }
404
405
406 //===----------------------------------------------------------------------===//
407 //               AliasSet/AliasSetTracker Printing Support
408 //===----------------------------------------------------------------------===//
409
410 void AliasSet::print(std::ostream &OS) const {
411   OS << "  AliasSet[" << (void*)this << "," << RefCount << "] ";
412   OS << (AliasTy == MustAlias ? "must" : "may ") << " alias, ";
413   switch (AccessTy) {
414   case NoModRef: OS << "No access "; break;
415   case Refs    : OS << "Ref       "; break;
416   case Mods    : OS << "Mod       "; break;
417   case ModRef  : OS << "Mod/Ref   "; break;
418   default: assert(0 && "Bad value for AccessTy!");
419   }
420   if (isVolatile()) OS << "[volatile] ";
421   if (Forward)
422     OS << " forwarding to " << (void*)Forward;
423
424
425   if (begin() != end()) {
426     OS << "Pointers: ";
427     for (iterator I = begin(), E = end(); I != E; ++I) {
428       if (I != begin()) OS << ", ";
429       WriteAsOperand(OS << "(", I.getPointer());
430       OS << ", " << I.getSize() << ")";
431     }
432   }
433   if (!CallSites.empty()) {
434     OS << "\n    " << CallSites.size() << " Call Sites: ";
435     for (unsigned i = 0, e = CallSites.size(); i != e; ++i) {
436       if (i) OS << ", ";
437       WriteAsOperand(OS, CallSites[i].getCalledValue());
438     }      
439   }
440   OS << "\n";
441 }
442
443 void AliasSetTracker::print(std::ostream &OS) const {
444   OS << "Alias Set Tracker: " << AliasSets.size() << " alias sets for "
445      << PointerMap.size() << " pointer values.\n";
446   for (const_iterator I = begin(), E = end(); I != E; ++I)
447     I->print(OS);
448   OS << "\n";
449 }
450
451 void AliasSet::dump() const { print (std::cerr); }
452 void AliasSetTracker::dump() const { print(std::cerr); }
453
454 //===----------------------------------------------------------------------===//
455 //                            AliasSetPrinter Pass
456 //===----------------------------------------------------------------------===//
457
458 namespace {
459   class AliasSetPrinter : public FunctionPass {
460     AliasSetTracker *Tracker;
461   public:
462     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
463       AU.setPreservesAll();
464       AU.addRequired<AliasAnalysis>();
465     }
466
467     virtual bool runOnFunction(Function &F) {
468       Tracker = new AliasSetTracker(getAnalysis<AliasAnalysis>());
469
470       for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
471         Tracker->add(&*I);
472       return false;
473     }
474
475     /// print - Convert to human readable form
476     virtual void print(std::ostream &OS) const {
477       Tracker->print(OS);
478     }
479
480     virtual void releaseMemory() {
481       delete Tracker;
482     }
483   };
484   RegisterPass<AliasSetPrinter> X("print-alias-sets", "Alias Set Printer",
485                                   PassInfo::Analysis | PassInfo::Optimization);
486 }