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/Analysis/GuardUtils.h"
17 #include "llvm/Analysis/MemoryLocation.h"
18 #include "llvm/Config/llvm-config.h"
19 #include "llvm/IR/CallSite.h"
20 #include "llvm/IR/Constants.h"
21 #include "llvm/IR/DataLayout.h"
22 #include "llvm/IR/Function.h"
23 #include "llvm/IR/InstIterator.h"
24 #include "llvm/IR/Instruction.h"
25 #include "llvm/IR/Instructions.h"
26 #include "llvm/IR/IntrinsicInst.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/IR/PatternMatch.h"
29 #include "llvm/IR/Value.h"
30 #include "llvm/Pass.h"
31 #include "llvm/Support/AtomicOrdering.h"
32 #include "llvm/Support/Casting.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Compiler.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include <cassert>
39 #include <cstdint>
40 #include <vector>
41 
42 using namespace llvm;
43 
44 static cl::opt<unsigned>
45     SaturationThreshold("alias-set-saturation-threshold", cl::Hidden,
46                         cl::init(250),
47                         cl::desc("The maximum number of pointers may-alias "
48                                  "sets may contain before degradation"));
49 
50 /// mergeSetIn - Merge the specified alias set into this alias set.
51 ///
52 void AliasSet::mergeSetIn(AliasSet &AS, AliasSetTracker &AST) {
53   assert(!AS.Forward && "Alias set is already forwarding!");
54   assert(!Forward && "This set is a forwarding set!!");
55 
56   bool WasMustAlias = (Alias == SetMustAlias);
57   // Update the alias and access types of this set...
58   Access |= AS.Access;
59   Alias  |= AS.Alias;
60 
61   if (Alias == SetMustAlias) {
62     // Check that these two merged sets really are must aliases.  Since both
63     // used to be must-alias sets, we can just check any pointer from each set
64     // for aliasing.
65     AliasAnalysis &AA = AST.getAliasAnalysis();
66     PointerRec *L = getSomePointer();
67     PointerRec *R = AS.getSomePointer();
68 
69     // If the pointers are not a must-alias pair, this set becomes a may alias.
70     if (AA.alias(MemoryLocation(L->getValue(), L->getSize(), L->getAAInfo()),
71                  MemoryLocation(R->getValue(), R->getSize(), R->getAAInfo())) !=
72         MustAlias)
73       Alias = SetMayAlias;
74   }
75 
76   if (Alias == SetMayAlias) {
77     if (WasMustAlias)
78       AST.TotalMayAliasSetSize += size();
79     if (AS.Alias == SetMustAlias)
80       AST.TotalMayAliasSetSize += AS.size();
81   }
82 
83   bool ASHadUnknownInsts = !AS.UnknownInsts.empty();
84   if (UnknownInsts.empty()) {            // Merge call sites...
85     if (ASHadUnknownInsts) {
86       std::swap(UnknownInsts, AS.UnknownInsts);
87       addRef();
88     }
89   } else if (ASHadUnknownInsts) {
90     UnknownInsts.insert(UnknownInsts.end(), AS.UnknownInsts.begin(), AS.UnknownInsts.end());
91     AS.UnknownInsts.clear();
92   }
93 
94   AS.Forward = this; // Forward across AS now...
95   addRef();          // AS is now pointing to us...
96 
97   // Merge the list of constituent pointers...
98   if (AS.PtrList) {
99     SetSize += AS.size();
100     AS.SetSize = 0;
101     *PtrListEnd = AS.PtrList;
102     AS.PtrList->setPrevInList(PtrListEnd);
103     PtrListEnd = AS.PtrListEnd;
104 
105     AS.PtrList = nullptr;
106     AS.PtrListEnd = &AS.PtrList;
107     assert(*AS.PtrListEnd == nullptr && "End of list is not null?");
108   }
109   if (ASHadUnknownInsts)
110     AS.dropRef(AST);
111 }
112 
113 void AliasSetTracker::removeAliasSet(AliasSet *AS) {
114   if (AliasSet *Fwd = AS->Forward) {
115     Fwd->dropRef(*this);
116     AS->Forward = nullptr;
117   }
118 
119   if (AS->Alias == AliasSet::SetMayAlias)
120     TotalMayAliasSetSize -= AS->size();
121 
122   AliasSets.erase(AS);
123 }
124 
125 void AliasSet::removeFromTracker(AliasSetTracker &AST) {
126   assert(RefCount == 0 && "Cannot remove non-dead alias set from tracker!");
127   AST.removeAliasSet(this);
128 }
129 
130 void AliasSet::addPointer(AliasSetTracker &AST, PointerRec &Entry,
131                           LocationSize Size, const AAMDNodes &AAInfo,
132                           bool KnownMustAlias) {
133   assert(!Entry.hasAliasSet() && "Entry already in set!");
134 
135   // Check to see if we have to downgrade to _may_ alias.
136   if (isMustAlias() && !KnownMustAlias)
137     if (PointerRec *P = getSomePointer()) {
138       AliasAnalysis &AA = AST.getAliasAnalysis();
139       AliasResult Result =
140           AA.alias(MemoryLocation(P->getValue(), P->getSize(), P->getAAInfo()),
141                    MemoryLocation(Entry.getValue(), Size, AAInfo));
142       if (Result != MustAlias) {
143         Alias = SetMayAlias;
144         AST.TotalMayAliasSetSize += size();
145       } else {
146         // First entry of must alias must have maximum size!
147         P->updateSizeAndAAInfo(Size, AAInfo);
148       }
149       assert(Result != NoAlias && "Cannot be part of must set!");
150     }
151 
152   Entry.setAliasSet(this);
153   Entry.updateSizeAndAAInfo(Size, AAInfo);
154 
155   // Add it to the end of the list...
156   ++SetSize;
157   assert(*PtrListEnd == nullptr && "End of list is not null?");
158   *PtrListEnd = &Entry;
159   PtrListEnd = Entry.setPrevInList(PtrListEnd);
160   assert(*PtrListEnd == nullptr && "End of list is not null?");
161   // Entry points to alias set.
162   addRef();
163 
164   if (Alias == SetMayAlias)
165     AST.TotalMayAliasSetSize++;
166 }
167 
168 void AliasSet::addUnknownInst(Instruction *I, AliasAnalysis &AA) {
169   if (UnknownInsts.empty())
170     addRef();
171   UnknownInsts.emplace_back(I);
172 
173   // Guards are marked as modifying memory for control flow modelling purposes,
174   // but don't actually modify any specific memory location.
175   using namespace PatternMatch;
176   bool MayWriteMemory = I->mayWriteToMemory() && !isGuard(I) &&
177     !(I->use_empty() && match(I, m_Intrinsic<Intrinsic::invariant_start>()));
178   if (!MayWriteMemory) {
179     Alias = SetMayAlias;
180     Access |= RefAccess;
181     return;
182   }
183 
184   // FIXME: This should use mod/ref information to make this not suck so bad
185   Alias = SetMayAlias;
186   Access = ModRefAccess;
187 }
188 
189 /// aliasesPointer - Return true if the specified pointer "may" (or must)
190 /// alias one of the members in the set.
191 ///
192 bool AliasSet::aliasesPointer(const Value *Ptr, LocationSize Size,
193                               const AAMDNodes &AAInfo,
194                               AliasAnalysis &AA) const {
195   if (AliasAny)
196     return true;
197 
198   if (Alias == SetMustAlias) {
199     assert(UnknownInsts.empty() && "Illegal must alias set!");
200 
201     // If this is a set of MustAliases, only check to see if the pointer aliases
202     // SOME value in the set.
203     PointerRec *SomePtr = getSomePointer();
204     assert(SomePtr && "Empty must-alias set??");
205     return AA.alias(MemoryLocation(SomePtr->getValue(), SomePtr->getSize(),
206                                    SomePtr->getAAInfo()),
207                     MemoryLocation(Ptr, Size, AAInfo));
208   }
209 
210   // If this is a may-alias set, we have to check all of the pointers in the set
211   // to be sure it doesn't alias the set...
212   for (iterator I = begin(), E = end(); I != E; ++I)
213     if (AA.alias(MemoryLocation(Ptr, Size, AAInfo),
214                  MemoryLocation(I.getPointer(), I.getSize(), I.getAAInfo())))
215       return true;
216 
217   // Check the unknown instructions...
218   if (!UnknownInsts.empty()) {
219     for (unsigned i = 0, e = UnknownInsts.size(); i != e; ++i)
220       if (auto *Inst = getUnknownInst(i))
221         if (isModOrRefSet(
222                 AA.getModRefInfo(Inst, MemoryLocation(Ptr, Size, AAInfo))))
223           return true;
224   }
225 
226   return false;
227 }
228 
229 bool AliasSet::aliasesUnknownInst(const Instruction *Inst,
230                                   AliasAnalysis &AA) const {
231 
232   if (AliasAny)
233     return true;
234 
235   if (!Inst->mayReadOrWriteMemory())
236     return false;
237 
238   for (unsigned i = 0, e = UnknownInsts.size(); i != e; ++i) {
239     if (auto *UnknownInst = getUnknownInst(i)) {
240       ImmutableCallSite C1(UnknownInst), C2(Inst);
241       if (!C1 || !C2 || isModOrRefSet(AA.getModRefInfo(C1, C2)) ||
242           isModOrRefSet(AA.getModRefInfo(C2, C1)))
243         return true;
244     }
245   }
246 
247   for (iterator I = begin(), E = end(); I != E; ++I)
248     if (isModOrRefSet(AA.getModRefInfo(
249             Inst, MemoryLocation(I.getPointer(), I.getSize(), I.getAAInfo()))))
250       return true;
251 
252   return false;
253 }
254 
255 Instruction* AliasSet::getUniqueInstruction() {
256   if (AliasAny)
257     // May have collapses alias set
258     return nullptr;
259   if (begin() != end()) {
260     if (!UnknownInsts.empty())
261       // Another instruction found
262       return nullptr;
263     if (std::next(begin()) != end())
264       // Another instruction found
265       return nullptr;
266     Value *Addr = begin()->getValue();
267     assert(!Addr->user_empty() &&
268            "where's the instruction which added this pointer?");
269     if (std::next(Addr->user_begin()) != Addr->user_end())
270       // Another instruction found -- this is really restrictive
271       // TODO: generalize!
272       return nullptr;
273     return cast<Instruction>(*(Addr->user_begin()));
274   }
275   if (1 != UnknownInsts.size())
276     return nullptr;
277   return cast<Instruction>(UnknownInsts[0]);
278 }
279 
280 void AliasSetTracker::clear() {
281   // Delete all the PointerRec entries.
282   for (PointerMapType::iterator I = PointerMap.begin(), E = PointerMap.end();
283        I != E; ++I)
284     I->second->eraseFromList();
285 
286   PointerMap.clear();
287 
288   // The alias sets should all be clear now.
289   AliasSets.clear();
290 }
291 
292 
293 /// mergeAliasSetsForPointer - Given a pointer, merge all alias sets that may
294 /// alias the pointer. Return the unified set, or nullptr if no set that aliases
295 /// the pointer was found.
296 AliasSet *AliasSetTracker::mergeAliasSetsForPointer(const Value *Ptr,
297                                                     LocationSize Size,
298                                                     const AAMDNodes &AAInfo) {
299   AliasSet *FoundSet = nullptr;
300   for (iterator I = begin(), E = end(); I != E;) {
301     iterator Cur = I++;
302     if (Cur->Forward || !Cur->aliasesPointer(Ptr, Size, AAInfo, AA)) continue;
303 
304     if (!FoundSet) {      // If this is the first alias set ptr can go into.
305       FoundSet = &*Cur;   // Remember it.
306     } else {              // Otherwise, we must merge the sets.
307       FoundSet->mergeSetIn(*Cur, *this);     // Merge in contents.
308     }
309   }
310 
311   return FoundSet;
312 }
313 
314 bool AliasSetTracker::containsUnknown(const Instruction *Inst) const {
315   for (const AliasSet &AS : *this)
316     if (!AS.Forward && AS.aliasesUnknownInst(Inst, AA))
317       return true;
318   return false;
319 }
320 
321 AliasSet *AliasSetTracker::findAliasSetForUnknownInst(Instruction *Inst) {
322   AliasSet *FoundSet = nullptr;
323   for (iterator I = begin(), E = end(); I != E;) {
324     iterator Cur = I++;
325     if (Cur->Forward || !Cur->aliasesUnknownInst(Inst, AA))
326       continue;
327     if (!FoundSet)            // If this is the first alias set ptr can go into.
328       FoundSet = &*Cur;       // Remember it.
329     else if (!Cur->Forward)   // Otherwise, we must merge the sets.
330       FoundSet->mergeSetIn(*Cur, *this);     // Merge in contents.
331   }
332   return FoundSet;
333 }
334 
335 AliasSet &AliasSetTracker::getAliasSetFor(const MemoryLocation &MemLoc) {
336 
337   Value * const Pointer = const_cast<Value*>(MemLoc.Ptr);
338   const LocationSize Size = MemLoc.Size;
339   const AAMDNodes &AAInfo = MemLoc.AATags;
340 
341   AliasSet::PointerRec &Entry = getEntryFor(Pointer);
342 
343   if (AliasAnyAS) {
344     // At this point, the AST is saturated, so we only have one active alias
345     // set. That means we already know which alias set we want to return, and
346     // just need to add the pointer to that set to keep the data structure
347     // consistent.
348     // This, of course, means that we will never need a merge here.
349     if (Entry.hasAliasSet()) {
350       Entry.updateSizeAndAAInfo(Size, AAInfo);
351       assert(Entry.getAliasSet(*this) == AliasAnyAS &&
352              "Entry in saturated AST must belong to only alias set");
353     } else {
354       AliasAnyAS->addPointer(*this, Entry, Size, AAInfo);
355     }
356     return *AliasAnyAS;
357   }
358 
359   // Check to see if the pointer is already known.
360   if (Entry.hasAliasSet()) {
361     // If the size changed, we may need to merge several alias sets.
362     // Note that we can *not* return the result of mergeAliasSetsForPointer
363     // due to a quirk of alias analysis behavior. Since alias(undef, undef)
364     // is NoAlias, mergeAliasSetsForPointer(undef, ...) will not find the
365     // the right set for undef, even if it exists.
366     if (Entry.updateSizeAndAAInfo(Size, AAInfo))
367       mergeAliasSetsForPointer(Pointer, Size, AAInfo);
368     // Return the set!
369     return *Entry.getAliasSet(*this)->getForwardedTarget(*this);
370   }
371 
372   if (AliasSet *AS = mergeAliasSetsForPointer(Pointer, Size, AAInfo)) {
373     // Add it to the alias set it aliases.
374     AS->addPointer(*this, Entry, Size, AAInfo);
375     return *AS;
376   }
377 
378   // Otherwise create a new alias set to hold the loaded pointer.
379   AliasSets.push_back(new AliasSet());
380   AliasSets.back().addPointer(*this, Entry, Size, AAInfo);
381   return AliasSets.back();
382 }
383 
384 void AliasSetTracker::add(Value *Ptr, LocationSize Size,
385                           const AAMDNodes &AAInfo) {
386   addPointer(Ptr, Size, AAInfo, AliasSet::NoAccess);
387 }
388 
389 void AliasSetTracker::add(LoadInst *LI) {
390   if (isStrongerThanMonotonic(LI->getOrdering()))
391     return addUnknown(LI);
392   addPointer(MemoryLocation::get(LI), AliasSet::RefAccess);
393 }
394 
395 void AliasSetTracker::add(StoreInst *SI) {
396   if (isStrongerThanMonotonic(SI->getOrdering()))
397     return addUnknown(SI);
398   addPointer(MemoryLocation::get(SI), AliasSet::ModAccess);
399 }
400 
401 void AliasSetTracker::add(VAArgInst *VAAI) {
402   addPointer(MemoryLocation::get(VAAI), AliasSet::ModRefAccess);
403 }
404 
405 void AliasSetTracker::add(AnyMemSetInst *MSI) {
406   addPointer(MemoryLocation::getForDest(MSI), AliasSet::ModAccess);
407 }
408 
409 void AliasSetTracker::add(AnyMemTransferInst *MTI) {
410   addPointer(MemoryLocation::getForSource(MTI), AliasSet::RefAccess);
411   addPointer(MemoryLocation::getForDest(MTI), AliasSet::ModAccess);
412 }
413 
414 void AliasSetTracker::addUnknown(Instruction *Inst) {
415   if (isa<DbgInfoIntrinsic>(Inst))
416     return; // Ignore DbgInfo Intrinsics.
417 
418   if (auto *II = dyn_cast<IntrinsicInst>(Inst)) {
419     // These intrinsics will show up as affecting memory, but they are just
420     // markers.
421     switch (II->getIntrinsicID()) {
422     default:
423       break;
424       // FIXME: Add lifetime/invariant intrinsics (See: PR30807).
425     case Intrinsic::assume:
426     case Intrinsic::sideeffect:
427       return;
428     }
429   }
430   if (!Inst->mayReadOrWriteMemory())
431     return; // doesn't alias anything
432 
433   AliasSet *AS = findAliasSetForUnknownInst(Inst);
434   if (AS) {
435     AS->addUnknownInst(Inst, AA);
436     return;
437   }
438   AliasSets.push_back(new AliasSet());
439   AS = &AliasSets.back();
440   AS->addUnknownInst(Inst, AA);
441 }
442 
443 void AliasSetTracker::add(Instruction *I) {
444   // Dispatch to one of the other add methods.
445   if (LoadInst *LI = dyn_cast<LoadInst>(I))
446     return add(LI);
447   if (StoreInst *SI = dyn_cast<StoreInst>(I))
448     return add(SI);
449   if (VAArgInst *VAAI = dyn_cast<VAArgInst>(I))
450     return add(VAAI);
451   if (AnyMemSetInst *MSI = dyn_cast<AnyMemSetInst>(I))
452     return add(MSI);
453   if (AnyMemTransferInst *MTI = dyn_cast<AnyMemTransferInst>(I))
454     return add(MTI);
455   return addUnknown(I);
456 }
457 
458 void AliasSetTracker::add(BasicBlock &BB) {
459   for (auto &I : BB)
460     add(&I);
461 }
462 
463 void AliasSetTracker::add(const AliasSetTracker &AST) {
464   assert(&AA == &AST.AA &&
465          "Merging AliasSetTracker objects with different Alias Analyses!");
466 
467   // Loop over all of the alias sets in AST, adding the pointers contained
468   // therein into the current alias sets.  This can cause alias sets to be
469   // merged together in the current AST.
470   for (const AliasSet &AS : AST) {
471     if (AS.Forward)
472       continue; // Ignore forwarding alias sets
473 
474     // If there are any call sites in the alias set, add them to this AST.
475     for (unsigned i = 0, e = AS.UnknownInsts.size(); i != e; ++i)
476       if (auto *Inst = AS.getUnknownInst(i))
477         add(Inst);
478 
479     // Loop over all of the pointers in this alias set.
480     for (AliasSet::iterator ASI = AS.begin(), E = AS.end(); ASI != E; ++ASI)
481       addPointer(ASI.getPointer(), ASI.getSize(), ASI.getAAInfo(),
482                  (AliasSet::AccessLattice)AS.Access);
483   }
484 }
485 
486 // deleteValue method - This method is used to remove a pointer value from the
487 // AliasSetTracker entirely.  It should be used when an instruction is deleted
488 // from the program to update the AST.  If you don't use this, you would have
489 // dangling pointers to deleted instructions.
490 //
491 void AliasSetTracker::deleteValue(Value *PtrVal) {
492   // First, look up the PointerRec for this pointer.
493   PointerMapType::iterator I = PointerMap.find_as(PtrVal);
494   if (I == PointerMap.end()) return;  // Noop
495 
496   // If we found one, remove the pointer from the alias set it is in.
497   AliasSet::PointerRec *PtrValEnt = I->second;
498   AliasSet *AS = PtrValEnt->getAliasSet(*this);
499 
500   // Unlink and delete from the list of values.
501   PtrValEnt->eraseFromList();
502 
503   if (AS->Alias == AliasSet::SetMayAlias) {
504     AS->SetSize--;
505     TotalMayAliasSetSize--;
506   }
507 
508   // Stop using the alias set.
509   AS->dropRef(*this);
510 
511   PointerMap.erase(I);
512 }
513 
514 // copyValue - This method should be used whenever a preexisting value in the
515 // program is copied or cloned, introducing a new value.  Note that it is ok for
516 // clients that use this method to introduce the same value multiple times: if
517 // the tracker already knows about a value, it will ignore the request.
518 //
519 void AliasSetTracker::copyValue(Value *From, Value *To) {
520   // First, look up the PointerRec for this pointer.
521   PointerMapType::iterator I = PointerMap.find_as(From);
522   if (I == PointerMap.end())
523     return;  // Noop
524   assert(I->second->hasAliasSet() && "Dead entry?");
525 
526   AliasSet::PointerRec &Entry = getEntryFor(To);
527   if (Entry.hasAliasSet()) return;    // Already in the tracker!
528 
529   // getEntryFor above may invalidate iterator \c I, so reinitialize it.
530   I = PointerMap.find_as(From);
531   // Add it to the alias set it aliases...
532   AliasSet *AS = I->second->getAliasSet(*this);
533   AS->addPointer(*this, Entry, I->second->getSize(),
534                  I->second->getAAInfo(),
535                  true);
536 }
537 
538 AliasSet &AliasSetTracker::mergeAllAliasSets() {
539   assert(!AliasAnyAS && (TotalMayAliasSetSize > SaturationThreshold) &&
540          "Full merge should happen once, when the saturation threshold is "
541          "reached");
542 
543   // Collect all alias sets, so that we can drop references with impunity
544   // without worrying about iterator invalidation.
545   std::vector<AliasSet *> ASVector;
546   ASVector.reserve(SaturationThreshold);
547   for (iterator I = begin(), E = end(); I != E; I++)
548     ASVector.push_back(&*I);
549 
550   // Copy all instructions and pointers into a new set, and forward all other
551   // sets to it.
552   AliasSets.push_back(new AliasSet());
553   AliasAnyAS = &AliasSets.back();
554   AliasAnyAS->Alias = AliasSet::SetMayAlias;
555   AliasAnyAS->Access = AliasSet::ModRefAccess;
556   AliasAnyAS->AliasAny = true;
557 
558   for (auto Cur : ASVector) {
559     // If Cur was already forwarding, just forward to the new AS instead.
560     AliasSet *FwdTo = Cur->Forward;
561     if (FwdTo) {
562       Cur->Forward = AliasAnyAS;
563       AliasAnyAS->addRef();
564       FwdTo->dropRef(*this);
565       continue;
566     }
567 
568     // Otherwise, perform the actual merge.
569     AliasAnyAS->mergeSetIn(*Cur, *this);
570   }
571 
572   return *AliasAnyAS;
573 }
574 
575 AliasSet &AliasSetTracker::addPointer(Value *P, LocationSize Size,
576                                       const AAMDNodes &AAInfo,
577                                       AliasSet::AccessLattice E) {
578   AliasSet &AS = getAliasSetFor(MemoryLocation(P, Size, AAInfo));
579   AS.Access |= E;
580 
581   if (!AliasAnyAS && (TotalMayAliasSetSize > SaturationThreshold)) {
582     // The AST is now saturated. From here on, we conservatively consider all
583     // pointers to alias each-other.
584     return mergeAllAliasSets();
585   }
586 
587   return AS;
588 }
589 
590 //===----------------------------------------------------------------------===//
591 //               AliasSet/AliasSetTracker Printing Support
592 //===----------------------------------------------------------------------===//
593 
594 void AliasSet::print(raw_ostream &OS) const {
595   OS << "  AliasSet[" << (const void*)this << ", " << RefCount << "] ";
596   OS << (Alias == SetMustAlias ? "must" : "may") << " alias, ";
597   switch (Access) {
598   case NoAccess:     OS << "No access "; break;
599   case RefAccess:    OS << "Ref       "; break;
600   case ModAccess:    OS << "Mod       "; break;
601   case ModRefAccess: OS << "Mod/Ref   "; break;
602   default: llvm_unreachable("Bad value for Access!");
603   }
604   if (Forward)
605     OS << " forwarding to " << (void*)Forward;
606 
607   if (!empty()) {
608     OS << "Pointers: ";
609     for (iterator I = begin(), E = end(); I != E; ++I) {
610       if (I != begin()) OS << ", ";
611       I.getPointer()->printAsOperand(OS << "(");
612       if (I.getSize() == MemoryLocation::UnknownSize)
613         OS << ", unknown)";
614       else
615         OS << ", " << I.getSize() << ")";
616     }
617   }
618   if (!UnknownInsts.empty()) {
619     OS << "\n    " << UnknownInsts.size() << " Unknown instructions: ";
620     for (unsigned i = 0, e = UnknownInsts.size(); i != e; ++i) {
621       if (i) OS << ", ";
622       if (auto *I = getUnknownInst(i)) {
623         if (I->hasName())
624           I->printAsOperand(OS);
625         else
626           I->print(OS);
627       }
628     }
629   }
630   OS << "\n";
631 }
632 
633 void AliasSetTracker::print(raw_ostream &OS) const {
634   OS << "Alias Set Tracker: " << AliasSets.size() << " alias sets for "
635      << PointerMap.size() << " pointer values.\n";
636   for (const AliasSet &AS : *this)
637     AS.print(OS);
638   OS << "\n";
639 }
640 
641 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
642 LLVM_DUMP_METHOD void AliasSet::dump() const { print(dbgs()); }
643 LLVM_DUMP_METHOD void AliasSetTracker::dump() const { print(dbgs()); }
644 #endif
645 
646 //===----------------------------------------------------------------------===//
647 //                     ASTCallbackVH Class Implementation
648 //===----------------------------------------------------------------------===//
649 
650 void AliasSetTracker::ASTCallbackVH::deleted() {
651   assert(AST && "ASTCallbackVH called with a null AliasSetTracker!");
652   AST->deleteValue(getValPtr());
653   // this now dangles!
654 }
655 
656 void AliasSetTracker::ASTCallbackVH::allUsesReplacedWith(Value *V) {
657   AST->copyValue(getValPtr(), V);
658 }
659 
660 AliasSetTracker::ASTCallbackVH::ASTCallbackVH(Value *V, AliasSetTracker *ast)
661   : CallbackVH(V), AST(ast) {}
662 
663 AliasSetTracker::ASTCallbackVH &
664 AliasSetTracker::ASTCallbackVH::operator=(Value *V) {
665   return *this = ASTCallbackVH(V, AST);
666 }
667 
668 //===----------------------------------------------------------------------===//
669 //                            AliasSetPrinter Pass
670 //===----------------------------------------------------------------------===//
671 
672 namespace {
673 
674   class AliasSetPrinter : public FunctionPass {
675     AliasSetTracker *Tracker;
676 
677   public:
678     static char ID; // Pass identification, replacement for typeid
679 
680     AliasSetPrinter() : FunctionPass(ID) {
681       initializeAliasSetPrinterPass(*PassRegistry::getPassRegistry());
682     }
683 
684     void getAnalysisUsage(AnalysisUsage &AU) const override {
685       AU.setPreservesAll();
686       AU.addRequired<AAResultsWrapperPass>();
687     }
688 
689     bool runOnFunction(Function &F) override {
690       auto &AAWP = getAnalysis<AAResultsWrapperPass>();
691       Tracker = new AliasSetTracker(AAWP.getAAResults());
692       errs() << "Alias sets for function '" << F.getName() << "':\n";
693       for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
694         Tracker->add(&*I);
695       Tracker->print(errs());
696       delete Tracker;
697       return false;
698     }
699   };
700 
701 } // end anonymous namespace
702 
703 char AliasSetPrinter::ID = 0;
704 
705 INITIALIZE_PASS_BEGIN(AliasSetPrinter, "print-alias-sets",
706                 "Alias Set Printer", false, true)
707 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
708 INITIALIZE_PASS_END(AliasSetPrinter, "print-alias-sets",
709                 "Alias Set Printer", false, true)
710