AliasSetTracker.cpp revision fedac7d9b0c83c94f0f8cc2aaa6b4cce4a6e9a55
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"
27using namespace llvm;
28
29/// mergeSetIn - Merge the specified alias set into this alias set.
30///
31void 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
77void 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
85void AliasSet::removeFromTracker(AliasSetTracker &AST) {
86  assert(RefCount == 0 && "Cannot remove non-dead alias set from tracker!");
87  AST.removeAliasSet(this);
88}
89
90void 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
118void AliasSet::addCallSite(CallSite CS, AliasAnalysis &AA) {
119  CallSites.push_back(CS);
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///
138bool 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
166bool 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(CallSites[i], CS) != AliasAnalysis::NoModRef ||
172        AA.getModRefInfo(CS, CallSites[i]) != AliasAnalysis::NoModRef)
173      return true;
174
175  for (iterator I = begin(), E = end(); I != E; ++I)
176    if (AA.getModRefInfo(CS, I.getPointer(), I.getSize()) !=
177           AliasAnalysis::NoModRef)
178      return true;
179
180  return false;
181}
182
183void AliasSetTracker::clear() {
184  // Delete all the PointerRec entries.
185  for (PointerMapType::iterator I = PointerMap.begin(), E = PointerMap.end();
186       I != E; ++I)
187    I->second->eraseFromList();
188
189  PointerMap.clear();
190
191  // The alias sets should all be clear now.
192  AliasSets.clear();
193}
194
195
196/// findAliasSetForPointer - Given a pointer, find the one alias set to put the
197/// instruction referring to the pointer into.  If there are multiple alias sets
198/// that may alias the pointer, merge them together and return the unified set.
199///
200AliasSet *AliasSetTracker::findAliasSetForPointer(const Value *Ptr,
201                                                  unsigned Size) {
202  AliasSet *FoundSet = 0;
203  for (iterator I = begin(), E = end(); I != E; ++I) {
204    if (I->Forward || !I->aliasesPointer(Ptr, Size, AA)) continue;
205
206    if (FoundSet == 0) {  // If this is the first alias set ptr can go into.
207      FoundSet = I;       // Remember it.
208    } else {              // Otherwise, we must merge the sets.
209      FoundSet->mergeSetIn(*I, *this);     // Merge in contents.
210    }
211  }
212
213  return FoundSet;
214}
215
216/// containsPointer - Return true if the specified location is represented by
217/// this alias set, false otherwise.  This does not modify the AST object or
218/// alias sets.
219bool AliasSetTracker::containsPointer(Value *Ptr, unsigned Size) const {
220  for (const_iterator I = begin(), E = end(); I != E; ++I)
221    if (!I->Forward && I->aliasesPointer(Ptr, Size, AA))
222      return true;
223  return false;
224}
225
226
227
228AliasSet *AliasSetTracker::findAliasSetForCallSite(CallSite CS) {
229  AliasSet *FoundSet = 0;
230  for (iterator I = begin(), E = end(); I != E; ++I) {
231    if (I->Forward || !I->aliasesCallSite(CS, AA))
232      continue;
233
234    if (FoundSet == 0) {  // If this is the first alias set ptr can go into.
235      FoundSet = I;       // Remember it.
236    } else if (!I->Forward) {     // Otherwise, we must merge the sets.
237      FoundSet->mergeSetIn(*I, *this);     // Merge in contents.
238    }
239  }
240  return FoundSet;
241}
242
243
244
245
246/// getAliasSetForPointer - Return the alias set that the specified pointer
247/// lives in.
248AliasSet &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
272bool AliasSetTracker::add(Value *Ptr, unsigned Size) {
273  bool NewPtr;
274  addPointer(Ptr, Size, AliasSet::NoModRef, NewPtr);
275  return NewPtr;
276}
277
278
279bool 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
288bool 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
298bool AliasSetTracker::add(VAArgInst *VAAI) {
299  bool NewPtr;
300  addPointer(VAAI->getOperand(0), ~0, AliasSet::ModRef, NewPtr);
301  return NewPtr;
302}
303
304
305bool 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
322bool 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
337void AliasSetTracker::add(BasicBlock &BB) {
338  for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
339    add(I);
340}
341
342void 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.
370void 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
397bool 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
404bool 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
412bool 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
420bool 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
427bool 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
437bool 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//
456void 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.
462  if (CallSite CS = PtrVal)
463    if (!AA.doesNotAccessMemory(CS))
464      if (AliasSet *AS = findAliasSetForCallSite(CS))
465        AS->removeCallSite(CS);
466
467  // First, look up the PointerRec for this pointer.
468  PointerMapType::iterator I = PointerMap.find(PtrVal);
469  if (I == PointerMap.end()) return;  // Noop
470
471  // If we found one, remove the pointer from the alias set it is in.
472  AliasSet::PointerRec *PtrValEnt = I->second;
473  AliasSet *AS = PtrValEnt->getAliasSet(*this);
474
475  // Unlink and delete from the list of values.
476  PtrValEnt->eraseFromList();
477
478  // Stop using the alias set.
479  AS->dropRef(*this);
480
481  PointerMap.erase(I);
482}
483
484// copyValue - This method should be used whenever a preexisting value in the
485// program is copied or cloned, introducing a new value.  Note that it is ok for
486// clients that use this method to introduce the same value multiple times: if
487// the tracker already knows about a value, it will ignore the request.
488//
489void AliasSetTracker::copyValue(Value *From, Value *To) {
490  // Notify the alias analysis implementation that this value is copied.
491  AA.copyValue(From, To);
492
493  // First, look up the PointerRec for this pointer.
494  PointerMapType::iterator I = PointerMap.find(From);
495  if (I == PointerMap.end())
496    return;  // Noop
497  assert(I->second->hasAliasSet() && "Dead entry?");
498
499  AliasSet::PointerRec &Entry = getEntryFor(To);
500  if (Entry.hasAliasSet()) return;    // Already in the tracker!
501
502  // Add it to the alias set it aliases...
503  I = PointerMap.find(From);
504  AliasSet *AS = I->second->getAliasSet(*this);
505  AS->addPointer(*this, Entry, I->second->getSize(), true);
506}
507
508
509
510//===----------------------------------------------------------------------===//
511//               AliasSet/AliasSetTracker Printing Support
512//===----------------------------------------------------------------------===//
513
514void AliasSet::print(raw_ostream &OS) const {
515  OS << "  AliasSet[" << format("0x%p", (void*)this) << "," << RefCount << "] ";
516  OS << (AliasTy == MustAlias ? "must" : "may") << " alias, ";
517  switch (AccessTy) {
518  case NoModRef: OS << "No access "; break;
519  case Refs    : OS << "Ref       "; break;
520  case Mods    : OS << "Mod       "; break;
521  case ModRef  : OS << "Mod/Ref   "; break;
522  default: llvm_unreachable("Bad value for AccessTy!");
523  }
524  if (isVolatile()) OS << "[volatile] ";
525  if (Forward)
526    OS << " forwarding to " << (void*)Forward;
527
528
529  if (!empty()) {
530    OS << "Pointers: ";
531    for (iterator I = begin(), E = end(); I != E; ++I) {
532      if (I != begin()) OS << ", ";
533      WriteAsOperand(OS << "(", I.getPointer());
534      OS << ", " << I.getSize() << ")";
535    }
536  }
537  if (!CallSites.empty()) {
538    OS << "\n    " << CallSites.size() << " Call Sites: ";
539    for (unsigned i = 0, e = CallSites.size(); i != e; ++i) {
540      if (i) OS << ", ";
541      WriteAsOperand(OS, CallSites[i].getCalledValue());
542    }
543  }
544  OS << "\n";
545}
546
547void AliasSetTracker::print(raw_ostream &OS) const {
548  OS << "Alias Set Tracker: " << AliasSets.size() << " alias sets for "
549     << PointerMap.size() << " pointer values.\n";
550  for (const_iterator I = begin(), E = end(); I != E; ++I)
551    I->print(OS);
552  OS << "\n";
553}
554
555void AliasSet::dump() const { print(dbgs()); }
556void AliasSetTracker::dump() const { print(dbgs()); }
557
558//===----------------------------------------------------------------------===//
559//                     ASTCallbackVH Class Implementation
560//===----------------------------------------------------------------------===//
561
562void AliasSetTracker::ASTCallbackVH::deleted() {
563  assert(AST && "ASTCallbackVH called with a null AliasSetTracker!");
564  AST->deleteValue(getValPtr());
565  // this now dangles!
566}
567
568AliasSetTracker::ASTCallbackVH::ASTCallbackVH(Value *V, AliasSetTracker *ast)
569  : CallbackVH(V), AST(ast) {}
570
571AliasSetTracker::ASTCallbackVH &
572AliasSetTracker::ASTCallbackVH::operator=(Value *V) {
573  return *this = ASTCallbackVH(V, AST);
574}
575
576//===----------------------------------------------------------------------===//
577//                            AliasSetPrinter Pass
578//===----------------------------------------------------------------------===//
579
580namespace {
581  class AliasSetPrinter : public FunctionPass {
582    AliasSetTracker *Tracker;
583  public:
584    static char ID; // Pass identification, replacement for typeid
585    AliasSetPrinter() : FunctionPass(ID) {}
586
587    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
588      AU.setPreservesAll();
589      AU.addRequired<AliasAnalysis>();
590    }
591
592    virtual bool runOnFunction(Function &F) {
593      Tracker = new AliasSetTracker(getAnalysis<AliasAnalysis>());
594
595      for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
596        Tracker->add(&*I);
597      Tracker->print(errs());
598      delete Tracker;
599      return false;
600    }
601  };
602}
603
604char AliasSetPrinter::ID = 0;
605INITIALIZE_PASS(AliasSetPrinter, "print-alias-sets",
606                "Alias Set Printer", false, true);
607