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