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