1 //===- AliasAnalysis.cpp - Generic Alias Analysis Interface 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 generic AliasAnalysis interface which is used as the
11 // common interface used by all clients and implementations of alias analysis.
12 //
13 // This file also implements the default version of the AliasAnalysis interface
14 // that is to be used when no other implementation is specified.  This does some
15 // simple tests that detect obvious cases: two different global pointers cannot
16 // alias, a global cannot alias a malloc, two different mallocs cannot alias,
17 // etc.
18 //
19 // This alias analysis implementation really isn't very good for anything, but
20 // it is very fast, and makes a nice clean default implementation.  Because it
21 // handles lots of little corner cases, other, more complex, alias analysis
22 // implementations may choose to rely on this pass to resolve these simple and
23 // easy cases.
24 //
25 //===----------------------------------------------------------------------===//
26 
27 #include "llvm/Analysis/AliasAnalysis.h"
28 #include "llvm/Analysis/BasicAliasAnalysis.h"
29 #include "llvm/Analysis/CFG.h"
30 #include "llvm/Analysis/CFLAndersAliasAnalysis.h"
31 #include "llvm/Analysis/CFLSteensAliasAnalysis.h"
32 #include "llvm/Analysis/CaptureTracking.h"
33 #include "llvm/Analysis/GlobalsModRef.h"
34 #include "llvm/Analysis/ObjCARCAliasAnalysis.h"
35 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
36 #include "llvm/Analysis/ScopedNoAliasAA.h"
37 #include "llvm/Analysis/TargetLibraryInfo.h"
38 #include "llvm/Analysis/TypeBasedAliasAnalysis.h"
39 #include "llvm/Analysis/ValueTracking.h"
40 #include "llvm/IR/BasicBlock.h"
41 #include "llvm/IR/DataLayout.h"
42 #include "llvm/IR/Dominators.h"
43 #include "llvm/IR/Function.h"
44 #include "llvm/IR/Instructions.h"
45 #include "llvm/IR/IntrinsicInst.h"
46 #include "llvm/IR/LLVMContext.h"
47 #include "llvm/IR/Type.h"
48 #include "llvm/Pass.h"
49 using namespace llvm;
50 
51 /// Allow disabling BasicAA from the AA results. This is particularly useful
52 /// when testing to isolate a single AA implementation.
53 static cl::opt<bool> DisableBasicAA("disable-basicaa", cl::Hidden,
54                                     cl::init(false));
55 
56 AAResults::AAResults(AAResults &&Arg) : TLI(Arg.TLI), AAs(std::move(Arg.AAs)) {
57   for (auto &AA : AAs)
58     AA->setAAResults(this);
59 }
60 
61 AAResults::~AAResults() {
62 // FIXME; It would be nice to at least clear out the pointers back to this
63 // aggregation here, but we end up with non-nesting lifetimes in the legacy
64 // pass manager that prevent this from working. In the legacy pass manager
65 // we'll end up with dangling references here in some cases.
66 #if 0
67   for (auto &AA : AAs)
68     AA->setAAResults(nullptr);
69 #endif
70 }
71 
72 //===----------------------------------------------------------------------===//
73 // Default chaining methods
74 //===----------------------------------------------------------------------===//
75 
76 AliasResult AAResults::alias(const MemoryLocation &LocA,
77                              const MemoryLocation &LocB) {
78   for (const auto &AA : AAs) {
79     auto Result = AA->alias(LocA, LocB);
80     if (Result != MayAlias)
81       return Result;
82   }
83   return MayAlias;
84 }
85 
86 bool AAResults::pointsToConstantMemory(const MemoryLocation &Loc,
87                                        bool OrLocal) {
88   for (const auto &AA : AAs)
89     if (AA->pointsToConstantMemory(Loc, OrLocal))
90       return true;
91 
92   return false;
93 }
94 
95 ModRefInfo AAResults::getArgModRefInfo(ImmutableCallSite CS, unsigned ArgIdx) {
96   ModRefInfo Result = MRI_ModRef;
97 
98   for (const auto &AA : AAs) {
99     Result = ModRefInfo(Result & AA->getArgModRefInfo(CS, ArgIdx));
100 
101     // Early-exit the moment we reach the bottom of the lattice.
102     if (Result == MRI_NoModRef)
103       return Result;
104   }
105 
106   return Result;
107 }
108 
109 ModRefInfo AAResults::getModRefInfo(Instruction *I, ImmutableCallSite Call) {
110   // We may have two calls
111   if (auto CS = ImmutableCallSite(I)) {
112     // Check if the two calls modify the same memory
113     return getModRefInfo(CS, Call);
114   } else if (I->isFenceLike()) {
115     // If this is a fence, just return MRI_ModRef.
116     return MRI_ModRef;
117   } else {
118     // Otherwise, check if the call modifies or references the
119     // location this memory access defines.  The best we can say
120     // is that if the call references what this instruction
121     // defines, it must be clobbered by this location.
122     const MemoryLocation DefLoc = MemoryLocation::get(I);
123     if (getModRefInfo(Call, DefLoc) != MRI_NoModRef)
124       return MRI_ModRef;
125   }
126   return MRI_NoModRef;
127 }
128 
129 ModRefInfo AAResults::getModRefInfo(ImmutableCallSite CS,
130                                     const MemoryLocation &Loc) {
131   ModRefInfo Result = MRI_ModRef;
132 
133   for (const auto &AA : AAs) {
134     Result = ModRefInfo(Result & AA->getModRefInfo(CS, Loc));
135 
136     // Early-exit the moment we reach the bottom of the lattice.
137     if (Result == MRI_NoModRef)
138       return Result;
139   }
140 
141   // Try to refine the mod-ref info further using other API entry points to the
142   // aggregate set of AA results.
143   auto MRB = getModRefBehavior(CS);
144   if (MRB == FMRB_DoesNotAccessMemory ||
145       MRB == FMRB_OnlyAccessesInaccessibleMem)
146     return MRI_NoModRef;
147 
148   if (onlyReadsMemory(MRB))
149     Result = ModRefInfo(Result & MRI_Ref);
150   else if (doesNotReadMemory(MRB))
151     Result = ModRefInfo(Result & MRI_Mod);
152 
153   if (onlyAccessesArgPointees(MRB) || onlyAccessesInaccessibleOrArgMem(MRB)) {
154     bool DoesAlias = false;
155     ModRefInfo AllArgsMask = MRI_NoModRef;
156     if (doesAccessArgPointees(MRB)) {
157       for (auto AI = CS.arg_begin(), AE = CS.arg_end(); AI != AE; ++AI) {
158         const Value *Arg = *AI;
159         if (!Arg->getType()->isPointerTy())
160           continue;
161         unsigned ArgIdx = std::distance(CS.arg_begin(), AI);
162         MemoryLocation ArgLoc = MemoryLocation::getForArgument(CS, ArgIdx, TLI);
163         AliasResult ArgAlias = alias(ArgLoc, Loc);
164         if (ArgAlias != NoAlias) {
165           ModRefInfo ArgMask = getArgModRefInfo(CS, ArgIdx);
166           DoesAlias = true;
167           AllArgsMask = ModRefInfo(AllArgsMask | ArgMask);
168         }
169       }
170     }
171     if (!DoesAlias)
172       return MRI_NoModRef;
173     Result = ModRefInfo(Result & AllArgsMask);
174   }
175 
176   // If Loc is a constant memory location, the call definitely could not
177   // modify the memory location.
178   if ((Result & MRI_Mod) &&
179       pointsToConstantMemory(Loc, /*OrLocal*/ false))
180     Result = ModRefInfo(Result & ~MRI_Mod);
181 
182   return Result;
183 }
184 
185 ModRefInfo AAResults::getModRefInfo(ImmutableCallSite CS1,
186                                     ImmutableCallSite CS2) {
187   ModRefInfo Result = MRI_ModRef;
188 
189   for (const auto &AA : AAs) {
190     Result = ModRefInfo(Result & AA->getModRefInfo(CS1, CS2));
191 
192     // Early-exit the moment we reach the bottom of the lattice.
193     if (Result == MRI_NoModRef)
194       return Result;
195   }
196 
197   // Try to refine the mod-ref info further using other API entry points to the
198   // aggregate set of AA results.
199 
200   // If CS1 or CS2 are readnone, they don't interact.
201   auto CS1B = getModRefBehavior(CS1);
202   if (CS1B == FMRB_DoesNotAccessMemory)
203     return MRI_NoModRef;
204 
205   auto CS2B = getModRefBehavior(CS2);
206   if (CS2B == FMRB_DoesNotAccessMemory)
207     return MRI_NoModRef;
208 
209   // If they both only read from memory, there is no dependence.
210   if (onlyReadsMemory(CS1B) && onlyReadsMemory(CS2B))
211     return MRI_NoModRef;
212 
213   // If CS1 only reads memory, the only dependence on CS2 can be
214   // from CS1 reading memory written by CS2.
215   if (onlyReadsMemory(CS1B))
216     Result = ModRefInfo(Result & MRI_Ref);
217   else if (doesNotReadMemory(CS1B))
218     Result = ModRefInfo(Result & MRI_Mod);
219 
220   // If CS2 only access memory through arguments, accumulate the mod/ref
221   // information from CS1's references to the memory referenced by
222   // CS2's arguments.
223   if (onlyAccessesArgPointees(CS2B)) {
224     ModRefInfo R = MRI_NoModRef;
225     if (doesAccessArgPointees(CS2B)) {
226       for (auto I = CS2.arg_begin(), E = CS2.arg_end(); I != E; ++I) {
227         const Value *Arg = *I;
228         if (!Arg->getType()->isPointerTy())
229           continue;
230         unsigned CS2ArgIdx = std::distance(CS2.arg_begin(), I);
231         auto CS2ArgLoc = MemoryLocation::getForArgument(CS2, CS2ArgIdx, TLI);
232 
233         // ArgMask indicates what CS2 might do to CS2ArgLoc, and the dependence
234         // of CS1 on that location is the inverse.
235         ModRefInfo ArgMask = getArgModRefInfo(CS2, CS2ArgIdx);
236         if (ArgMask == MRI_Mod)
237           ArgMask = MRI_ModRef;
238         else if (ArgMask == MRI_Ref)
239           ArgMask = MRI_Mod;
240 
241         ArgMask = ModRefInfo(ArgMask & getModRefInfo(CS1, CS2ArgLoc));
242 
243         R = ModRefInfo((R | ArgMask) & Result);
244         if (R == Result)
245           break;
246       }
247     }
248     return R;
249   }
250 
251   // If CS1 only accesses memory through arguments, check if CS2 references
252   // any of the memory referenced by CS1's arguments. If not, return NoModRef.
253   if (onlyAccessesArgPointees(CS1B)) {
254     ModRefInfo R = MRI_NoModRef;
255     if (doesAccessArgPointees(CS1B)) {
256       for (auto I = CS1.arg_begin(), E = CS1.arg_end(); I != E; ++I) {
257         const Value *Arg = *I;
258         if (!Arg->getType()->isPointerTy())
259           continue;
260         unsigned CS1ArgIdx = std::distance(CS1.arg_begin(), I);
261         auto CS1ArgLoc = MemoryLocation::getForArgument(CS1, CS1ArgIdx, TLI);
262 
263         // ArgMask indicates what CS1 might do to CS1ArgLoc; if CS1 might Mod
264         // CS1ArgLoc, then we care about either a Mod or a Ref by CS2. If CS1
265         // might Ref, then we care only about a Mod by CS2.
266         ModRefInfo ArgMask = getArgModRefInfo(CS1, CS1ArgIdx);
267         ModRefInfo ArgR = getModRefInfo(CS2, CS1ArgLoc);
268         if (((ArgMask & MRI_Mod) != MRI_NoModRef &&
269              (ArgR & MRI_ModRef) != MRI_NoModRef) ||
270             ((ArgMask & MRI_Ref) != MRI_NoModRef &&
271              (ArgR & MRI_Mod) != MRI_NoModRef))
272           R = ModRefInfo((R | ArgMask) & Result);
273 
274         if (R == Result)
275           break;
276       }
277     }
278     return R;
279   }
280 
281   return Result;
282 }
283 
284 FunctionModRefBehavior AAResults::getModRefBehavior(ImmutableCallSite CS) {
285   FunctionModRefBehavior Result = FMRB_UnknownModRefBehavior;
286 
287   for (const auto &AA : AAs) {
288     Result = FunctionModRefBehavior(Result & AA->getModRefBehavior(CS));
289 
290     // Early-exit the moment we reach the bottom of the lattice.
291     if (Result == FMRB_DoesNotAccessMemory)
292       return Result;
293   }
294 
295   return Result;
296 }
297 
298 FunctionModRefBehavior AAResults::getModRefBehavior(const Function *F) {
299   FunctionModRefBehavior Result = FMRB_UnknownModRefBehavior;
300 
301   for (const auto &AA : AAs) {
302     Result = FunctionModRefBehavior(Result & AA->getModRefBehavior(F));
303 
304     // Early-exit the moment we reach the bottom of the lattice.
305     if (Result == FMRB_DoesNotAccessMemory)
306       return Result;
307   }
308 
309   return Result;
310 }
311 
312 //===----------------------------------------------------------------------===//
313 // Helper method implementation
314 //===----------------------------------------------------------------------===//
315 
316 ModRefInfo AAResults::getModRefInfo(const LoadInst *L,
317                                     const MemoryLocation &Loc) {
318   // Be conservative in the face of volatile/atomic.
319   if (!L->isUnordered())
320     return MRI_ModRef;
321 
322   // If the load address doesn't alias the given address, it doesn't read
323   // or write the specified memory.
324   if (Loc.Ptr && !alias(MemoryLocation::get(L), Loc))
325     return MRI_NoModRef;
326 
327   // Otherwise, a load just reads.
328   return MRI_Ref;
329 }
330 
331 ModRefInfo AAResults::getModRefInfo(const StoreInst *S,
332                                     const MemoryLocation &Loc) {
333   // Be conservative in the face of volatile/atomic.
334   if (!S->isUnordered())
335     return MRI_ModRef;
336 
337   if (Loc.Ptr) {
338     // If the store address cannot alias the pointer in question, then the
339     // specified memory cannot be modified by the store.
340     if (!alias(MemoryLocation::get(S), Loc))
341       return MRI_NoModRef;
342 
343     // If the pointer is a pointer to constant memory, then it could not have
344     // been modified by this store.
345     if (pointsToConstantMemory(Loc))
346       return MRI_NoModRef;
347   }
348 
349   // Otherwise, a store just writes.
350   return MRI_Mod;
351 }
352 
353 ModRefInfo AAResults::getModRefInfo(const VAArgInst *V,
354                                     const MemoryLocation &Loc) {
355 
356   if (Loc.Ptr) {
357     // If the va_arg address cannot alias the pointer in question, then the
358     // specified memory cannot be accessed by the va_arg.
359     if (!alias(MemoryLocation::get(V), Loc))
360       return MRI_NoModRef;
361 
362     // If the pointer is a pointer to constant memory, then it could not have
363     // been modified by this va_arg.
364     if (pointsToConstantMemory(Loc))
365       return MRI_NoModRef;
366   }
367 
368   // Otherwise, a va_arg reads and writes.
369   return MRI_ModRef;
370 }
371 
372 ModRefInfo AAResults::getModRefInfo(const CatchPadInst *CatchPad,
373                                     const MemoryLocation &Loc) {
374   if (Loc.Ptr) {
375     // If the pointer is a pointer to constant memory,
376     // then it could not have been modified by this catchpad.
377     if (pointsToConstantMemory(Loc))
378       return MRI_NoModRef;
379   }
380 
381   // Otherwise, a catchpad reads and writes.
382   return MRI_ModRef;
383 }
384 
385 ModRefInfo AAResults::getModRefInfo(const CatchReturnInst *CatchRet,
386                                     const MemoryLocation &Loc) {
387   if (Loc.Ptr) {
388     // If the pointer is a pointer to constant memory,
389     // then it could not have been modified by this catchpad.
390     if (pointsToConstantMemory(Loc))
391       return MRI_NoModRef;
392   }
393 
394   // Otherwise, a catchret reads and writes.
395   return MRI_ModRef;
396 }
397 
398 ModRefInfo AAResults::getModRefInfo(const AtomicCmpXchgInst *CX,
399                                     const MemoryLocation &Loc) {
400   // Acquire/Release cmpxchg has properties that matter for arbitrary addresses.
401   if (isStrongerThanMonotonic(CX->getSuccessOrdering()))
402     return MRI_ModRef;
403 
404   // If the cmpxchg address does not alias the location, it does not access it.
405   if (Loc.Ptr && !alias(MemoryLocation::get(CX), Loc))
406     return MRI_NoModRef;
407 
408   return MRI_ModRef;
409 }
410 
411 ModRefInfo AAResults::getModRefInfo(const AtomicRMWInst *RMW,
412                                     const MemoryLocation &Loc) {
413   // Acquire/Release atomicrmw has properties that matter for arbitrary addresses.
414   if (isStrongerThanMonotonic(RMW->getOrdering()))
415     return MRI_ModRef;
416 
417   // If the atomicrmw address does not alias the location, it does not access it.
418   if (Loc.Ptr && !alias(MemoryLocation::get(RMW), Loc))
419     return MRI_NoModRef;
420 
421   return MRI_ModRef;
422 }
423 
424 /// \brief Return information about whether a particular call site modifies
425 /// or reads the specified memory location \p MemLoc before instruction \p I
426 /// in a BasicBlock. A ordered basic block \p OBB can be used to speed up
427 /// instruction-ordering queries inside the BasicBlock containing \p I.
428 /// FIXME: this is really just shoring-up a deficiency in alias analysis.
429 /// BasicAA isn't willing to spend linear time determining whether an alloca
430 /// was captured before or after this particular call, while we are. However,
431 /// with a smarter AA in place, this test is just wasting compile time.
432 ModRefInfo AAResults::callCapturesBefore(const Instruction *I,
433                                          const MemoryLocation &MemLoc,
434                                          DominatorTree *DT,
435                                          OrderedBasicBlock *OBB) {
436   if (!DT)
437     return MRI_ModRef;
438 
439   const Value *Object =
440       GetUnderlyingObject(MemLoc.Ptr, I->getModule()->getDataLayout());
441   if (!isIdentifiedObject(Object) || isa<GlobalValue>(Object) ||
442       isa<Constant>(Object))
443     return MRI_ModRef;
444 
445   ImmutableCallSite CS(I);
446   if (!CS.getInstruction() || CS.getInstruction() == Object)
447     return MRI_ModRef;
448 
449   if (llvm::PointerMayBeCapturedBefore(Object, /* ReturnCaptures */ true,
450                                        /* StoreCaptures */ true, I, DT,
451                                        /* include Object */ true,
452                                        /* OrderedBasicBlock */ OBB))
453     return MRI_ModRef;
454 
455   unsigned ArgNo = 0;
456   ModRefInfo R = MRI_NoModRef;
457   for (auto CI = CS.data_operands_begin(), CE = CS.data_operands_end();
458        CI != CE; ++CI, ++ArgNo) {
459     // Only look at the no-capture or byval pointer arguments.  If this
460     // pointer were passed to arguments that were neither of these, then it
461     // couldn't be no-capture.
462     if (!(*CI)->getType()->isPointerTy() ||
463         (!CS.doesNotCapture(ArgNo) && !CS.isByValArgument(ArgNo)))
464       continue;
465 
466     // If this is a no-capture pointer argument, see if we can tell that it
467     // is impossible to alias the pointer we're checking.  If not, we have to
468     // assume that the call could touch the pointer, even though it doesn't
469     // escape.
470     if (isNoAlias(MemoryLocation(*CI), MemoryLocation(Object)))
471       continue;
472     if (CS.doesNotAccessMemory(ArgNo))
473       continue;
474     if (CS.onlyReadsMemory(ArgNo)) {
475       R = MRI_Ref;
476       continue;
477     }
478     return MRI_ModRef;
479   }
480   return R;
481 }
482 
483 /// canBasicBlockModify - Return true if it is possible for execution of the
484 /// specified basic block to modify the location Loc.
485 ///
486 bool AAResults::canBasicBlockModify(const BasicBlock &BB,
487                                     const MemoryLocation &Loc) {
488   return canInstructionRangeModRef(BB.front(), BB.back(), Loc, MRI_Mod);
489 }
490 
491 /// canInstructionRangeModRef - Return true if it is possible for the
492 /// execution of the specified instructions to mod\ref (according to the
493 /// mode) the location Loc. The instructions to consider are all
494 /// of the instructions in the range of [I1,I2] INCLUSIVE.
495 /// I1 and I2 must be in the same basic block.
496 bool AAResults::canInstructionRangeModRef(const Instruction &I1,
497                                           const Instruction &I2,
498                                           const MemoryLocation &Loc,
499                                           const ModRefInfo Mode) {
500   assert(I1.getParent() == I2.getParent() &&
501          "Instructions not in same basic block!");
502   BasicBlock::const_iterator I = I1.getIterator();
503   BasicBlock::const_iterator E = I2.getIterator();
504   ++E;  // Convert from inclusive to exclusive range.
505 
506   for (; I != E; ++I) // Check every instruction in range
507     if (getModRefInfo(&*I, Loc) & Mode)
508       return true;
509   return false;
510 }
511 
512 // Provide a definition for the root virtual destructor.
513 AAResults::Concept::~Concept() {}
514 
515 // Provide a definition for the static object used to identify passes.
516 AnalysisKey AAManager::Key;
517 
518 namespace {
519 /// A wrapper pass for external alias analyses. This just squirrels away the
520 /// callback used to run any analyses and register their results.
521 struct ExternalAAWrapperPass : ImmutablePass {
522   typedef std::function<void(Pass &, Function &, AAResults &)> CallbackT;
523 
524   CallbackT CB;
525 
526   static char ID;
527 
528   ExternalAAWrapperPass() : ImmutablePass(ID) {
529     initializeExternalAAWrapperPassPass(*PassRegistry::getPassRegistry());
530   }
531   explicit ExternalAAWrapperPass(CallbackT CB)
532       : ImmutablePass(ID), CB(std::move(CB)) {
533     initializeExternalAAWrapperPassPass(*PassRegistry::getPassRegistry());
534   }
535 
536   void getAnalysisUsage(AnalysisUsage &AU) const override {
537     AU.setPreservesAll();
538   }
539 };
540 }
541 
542 char ExternalAAWrapperPass::ID = 0;
543 INITIALIZE_PASS(ExternalAAWrapperPass, "external-aa", "External Alias Analysis",
544                 false, true)
545 
546 ImmutablePass *
547 llvm::createExternalAAWrapperPass(ExternalAAWrapperPass::CallbackT Callback) {
548   return new ExternalAAWrapperPass(std::move(Callback));
549 }
550 
551 AAResultsWrapperPass::AAResultsWrapperPass() : FunctionPass(ID) {
552   initializeAAResultsWrapperPassPass(*PassRegistry::getPassRegistry());
553 }
554 
555 char AAResultsWrapperPass::ID = 0;
556 
557 INITIALIZE_PASS_BEGIN(AAResultsWrapperPass, "aa",
558                       "Function Alias Analysis Results", false, true)
559 INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
560 INITIALIZE_PASS_DEPENDENCY(CFLAndersAAWrapperPass)
561 INITIALIZE_PASS_DEPENDENCY(CFLSteensAAWrapperPass)
562 INITIALIZE_PASS_DEPENDENCY(ExternalAAWrapperPass)
563 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
564 INITIALIZE_PASS_DEPENDENCY(ObjCARCAAWrapperPass)
565 INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass)
566 INITIALIZE_PASS_DEPENDENCY(ScopedNoAliasAAWrapperPass)
567 INITIALIZE_PASS_DEPENDENCY(TypeBasedAAWrapperPass)
568 INITIALIZE_PASS_END(AAResultsWrapperPass, "aa",
569                     "Function Alias Analysis Results", false, true)
570 
571 FunctionPass *llvm::createAAResultsWrapperPass() {
572   return new AAResultsWrapperPass();
573 }
574 
575 /// Run the wrapper pass to rebuild an aggregation over known AA passes.
576 ///
577 /// This is the legacy pass manager's interface to the new-style AA results
578 /// aggregation object. Because this is somewhat shoe-horned into the legacy
579 /// pass manager, we hard code all the specific alias analyses available into
580 /// it. While the particular set enabled is configured via commandline flags,
581 /// adding a new alias analysis to LLVM will require adding support for it to
582 /// this list.
583 bool AAResultsWrapperPass::runOnFunction(Function &F) {
584   // NB! This *must* be reset before adding new AA results to the new
585   // AAResults object because in the legacy pass manager, each instance
586   // of these will refer to the *same* immutable analyses, registering and
587   // unregistering themselves with them. We need to carefully tear down the
588   // previous object first, in this case replacing it with an empty one, before
589   // registering new results.
590   AAR.reset(
591       new AAResults(getAnalysis<TargetLibraryInfoWrapperPass>().getTLI()));
592 
593   // BasicAA is always available for function analyses. Also, we add it first
594   // so that it can trump TBAA results when it proves MustAlias.
595   // FIXME: TBAA should have an explicit mode to support this and then we
596   // should reconsider the ordering here.
597   if (!DisableBasicAA)
598     AAR->addAAResult(getAnalysis<BasicAAWrapperPass>().getResult());
599 
600   // Populate the results with the currently available AAs.
601   if (auto *WrapperPass = getAnalysisIfAvailable<ScopedNoAliasAAWrapperPass>())
602     AAR->addAAResult(WrapperPass->getResult());
603   if (auto *WrapperPass = getAnalysisIfAvailable<TypeBasedAAWrapperPass>())
604     AAR->addAAResult(WrapperPass->getResult());
605   if (auto *WrapperPass =
606           getAnalysisIfAvailable<objcarc::ObjCARCAAWrapperPass>())
607     AAR->addAAResult(WrapperPass->getResult());
608   if (auto *WrapperPass = getAnalysisIfAvailable<GlobalsAAWrapperPass>())
609     AAR->addAAResult(WrapperPass->getResult());
610   if (auto *WrapperPass = getAnalysisIfAvailable<SCEVAAWrapperPass>())
611     AAR->addAAResult(WrapperPass->getResult());
612   if (auto *WrapperPass = getAnalysisIfAvailable<CFLAndersAAWrapperPass>())
613     AAR->addAAResult(WrapperPass->getResult());
614   if (auto *WrapperPass = getAnalysisIfAvailable<CFLSteensAAWrapperPass>())
615     AAR->addAAResult(WrapperPass->getResult());
616 
617   // If available, run an external AA providing callback over the results as
618   // well.
619   if (auto *WrapperPass = getAnalysisIfAvailable<ExternalAAWrapperPass>())
620     if (WrapperPass->CB)
621       WrapperPass->CB(*this, F, *AAR);
622 
623   // Analyses don't mutate the IR, so return false.
624   return false;
625 }
626 
627 void AAResultsWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
628   AU.setPreservesAll();
629   AU.addRequired<BasicAAWrapperPass>();
630   AU.addRequired<TargetLibraryInfoWrapperPass>();
631 
632   // We also need to mark all the alias analysis passes we will potentially
633   // probe in runOnFunction as used here to ensure the legacy pass manager
634   // preserves them. This hard coding of lists of alias analyses is specific to
635   // the legacy pass manager.
636   AU.addUsedIfAvailable<ScopedNoAliasAAWrapperPass>();
637   AU.addUsedIfAvailable<TypeBasedAAWrapperPass>();
638   AU.addUsedIfAvailable<objcarc::ObjCARCAAWrapperPass>();
639   AU.addUsedIfAvailable<GlobalsAAWrapperPass>();
640   AU.addUsedIfAvailable<SCEVAAWrapperPass>();
641   AU.addUsedIfAvailable<CFLAndersAAWrapperPass>();
642   AU.addUsedIfAvailable<CFLSteensAAWrapperPass>();
643 }
644 
645 AAResults llvm::createLegacyPMAAResults(Pass &P, Function &F,
646                                         BasicAAResult &BAR) {
647   AAResults AAR(P.getAnalysis<TargetLibraryInfoWrapperPass>().getTLI());
648 
649   // Add in our explicitly constructed BasicAA results.
650   if (!DisableBasicAA)
651     AAR.addAAResult(BAR);
652 
653   // Populate the results with the other currently available AAs.
654   if (auto *WrapperPass =
655           P.getAnalysisIfAvailable<ScopedNoAliasAAWrapperPass>())
656     AAR.addAAResult(WrapperPass->getResult());
657   if (auto *WrapperPass = P.getAnalysisIfAvailable<TypeBasedAAWrapperPass>())
658     AAR.addAAResult(WrapperPass->getResult());
659   if (auto *WrapperPass =
660           P.getAnalysisIfAvailable<objcarc::ObjCARCAAWrapperPass>())
661     AAR.addAAResult(WrapperPass->getResult());
662   if (auto *WrapperPass = P.getAnalysisIfAvailable<GlobalsAAWrapperPass>())
663     AAR.addAAResult(WrapperPass->getResult());
664   if (auto *WrapperPass = P.getAnalysisIfAvailable<CFLAndersAAWrapperPass>())
665     AAR.addAAResult(WrapperPass->getResult());
666   if (auto *WrapperPass = P.getAnalysisIfAvailable<CFLSteensAAWrapperPass>())
667     AAR.addAAResult(WrapperPass->getResult());
668 
669   return AAR;
670 }
671 
672 bool llvm::isNoAliasCall(const Value *V) {
673   if (auto CS = ImmutableCallSite(V))
674     return CS.paramHasAttr(0, Attribute::NoAlias);
675   return false;
676 }
677 
678 bool llvm::isNoAliasArgument(const Value *V) {
679   if (const Argument *A = dyn_cast<Argument>(V))
680     return A->hasNoAliasAttr();
681   return false;
682 }
683 
684 bool llvm::isIdentifiedObject(const Value *V) {
685   if (isa<AllocaInst>(V))
686     return true;
687   if (isa<GlobalValue>(V) && !isa<GlobalAlias>(V))
688     return true;
689   if (isNoAliasCall(V))
690     return true;
691   if (const Argument *A = dyn_cast<Argument>(V))
692     return A->hasNoAliasAttr() || A->hasByValAttr();
693   return false;
694 }
695 
696 bool llvm::isIdentifiedFunctionLocal(const Value *V) {
697   return isa<AllocaInst>(V) || isNoAliasCall(V) || isNoAliasArgument(V);
698 }
699 
700 void llvm::getAAResultsAnalysisUsage(AnalysisUsage &AU) {
701   // This function needs to be in sync with llvm::createLegacyPMAAResults -- if
702   // more alias analyses are added to llvm::createLegacyPMAAResults, they need
703   // to be added here also.
704   AU.addRequired<TargetLibraryInfoWrapperPass>();
705   AU.addUsedIfAvailable<ScopedNoAliasAAWrapperPass>();
706   AU.addUsedIfAvailable<TypeBasedAAWrapperPass>();
707   AU.addUsedIfAvailable<objcarc::ObjCARCAAWrapperPass>();
708   AU.addUsedIfAvailable<GlobalsAAWrapperPass>();
709   AU.addUsedIfAvailable<CFLAndersAAWrapperPass>();
710   AU.addUsedIfAvailable<CFLSteensAAWrapperPass>();
711 }
712