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