• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===- llvm/Analysis/AliasAnalysis.h - Alias Analysis Interface -*- C++ -*-===//
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 defines the generic AliasAnalysis interface, which is used as the
10 // common interface used by all clients of alias analysis information, and
11 // implemented by all alias analysis implementations.  Mod/Ref information is
12 // also captured by this interface.
13 //
14 // Implementations of this interface must implement the various virtual methods,
15 // which automatically provides functionality for the entire suite of client
16 // APIs.
17 //
18 // This API identifies memory regions with the MemoryLocation class. The pointer
19 // component specifies the base memory address of the region. The Size specifies
20 // the maximum size (in address units) of the memory region, or
21 // MemoryLocation::UnknownSize if the size is not known. The TBAA tag
22 // identifies the "type" of the memory reference; see the
23 // TypeBasedAliasAnalysis class for details.
24 //
25 // Some non-obvious details include:
26 //  - Pointers that point to two completely different objects in memory never
27 //    alias, regardless of the value of the Size component.
28 //  - NoAlias doesn't imply inequal pointers. The most obvious example of this
29 //    is two pointers to constant memory. Even if they are equal, constant
30 //    memory is never stored to, so there will never be any dependencies.
31 //    In this and other situations, the pointers may be both NoAlias and
32 //    MustAlias at the same time. The current API can only return one result,
33 //    though this is rarely a problem in practice.
34 //
35 //===----------------------------------------------------------------------===//
36 
37 #ifndef LLVM_ANALYSIS_ALIASANALYSIS_H
38 #define LLVM_ANALYSIS_ALIASANALYSIS_H
39 
40 #include "llvm/ADT/DenseMap.h"
41 #include "llvm/ADT/None.h"
42 #include "llvm/ADT/Optional.h"
43 #include "llvm/ADT/SmallVector.h"
44 #include "llvm/Analysis/MemoryLocation.h"
45 #include "llvm/IR/Instruction.h"
46 #include "llvm/IR/Instructions.h"
47 #include "llvm/IR/PassManager.h"
48 #include "llvm/Pass.h"
49 #include <cstdint>
50 #include <functional>
51 #include <memory>
52 #include <vector>
53 
54 namespace llvm {
55 
56 class AnalysisUsage;
57 class BasicAAResult;
58 class BasicBlock;
59 class DominatorTree;
60 class Function;
61 class Value;
62 
63 /// The possible results of an alias query.
64 ///
65 /// These results are always computed between two MemoryLocation objects as
66 /// a query to some alias analysis.
67 ///
68 /// Note that these are unscoped enumerations because we would like to support
69 /// implicitly testing a result for the existence of any possible aliasing with
70 /// a conversion to bool, but an "enum class" doesn't support this. The
71 /// canonical names from the literature are suffixed and unique anyways, and so
72 /// they serve as global constants in LLVM for these results.
73 ///
74 /// See docs/AliasAnalysis.html for more information on the specific meanings
75 /// of these values.
76 enum AliasResult : uint8_t {
77   /// The two locations do not alias at all.
78   ///
79   /// This value is arranged to convert to false, while all other values
80   /// convert to true. This allows a boolean context to convert the result to
81   /// a binary flag indicating whether there is the possibility of aliasing.
82   NoAlias = 0,
83   /// The two locations may or may not alias. This is the least precise result.
84   MayAlias,
85   /// The two locations alias, but only due to a partial overlap.
86   PartialAlias,
87   /// The two locations precisely alias each other.
88   MustAlias,
89 };
90 
91 /// << operator for AliasResult.
92 raw_ostream &operator<<(raw_ostream &OS, AliasResult AR);
93 
94 /// Flags indicating whether a memory access modifies or references memory.
95 ///
96 /// This is no access at all, a modification, a reference, or both
97 /// a modification and a reference. These are specifically structured such that
98 /// they form a three bit matrix and bit-tests for 'mod' or 'ref' or 'must'
99 /// work with any of the possible values.
100 enum class ModRefInfo : uint8_t {
101   /// Must is provided for completeness, but no routines will return only
102   /// Must today. See definition of Must below.
103   Must = 0,
104   /// The access may reference the value stored in memory,
105   /// a mustAlias relation was found, and no mayAlias or partialAlias found.
106   MustRef = 1,
107   /// The access may modify the value stored in memory,
108   /// a mustAlias relation was found, and no mayAlias or partialAlias found.
109   MustMod = 2,
110   /// The access may reference, modify or both the value stored in memory,
111   /// a mustAlias relation was found, and no mayAlias or partialAlias found.
112   MustModRef = MustRef | MustMod,
113   /// The access neither references nor modifies the value stored in memory.
114   NoModRef = 4,
115   /// The access may reference the value stored in memory.
116   Ref = NoModRef | MustRef,
117   /// The access may modify the value stored in memory.
118   Mod = NoModRef | MustMod,
119   /// The access may reference and may modify the value stored in memory.
120   ModRef = Ref | Mod,
121 
122   /// About Must:
123   /// Must is set in a best effort manner.
124   /// We usually do not try our best to infer Must, instead it is merely
125   /// another piece of "free" information that is presented when available.
126   /// Must set means there was certainly a MustAlias found. For calls,
127   /// where multiple arguments are checked (argmemonly), this translates to
128   /// only MustAlias or NoAlias was found.
129   /// Must is not set for RAR accesses, even if the two locations must
130   /// alias. The reason is that two read accesses translate to an early return
131   /// of NoModRef. An additional alias check to set Must may be
132   /// expensive. Other cases may also not set Must(e.g. callCapturesBefore).
133   /// We refer to Must being *set* when the most significant bit is *cleared*.
134   /// Conversely we *clear* Must information by *setting* the Must bit to 1.
135 };
136 
isNoModRef(const ModRefInfo MRI)137 LLVM_NODISCARD inline bool isNoModRef(const ModRefInfo MRI) {
138   return (static_cast<int>(MRI) & static_cast<int>(ModRefInfo::MustModRef)) ==
139          static_cast<int>(ModRefInfo::Must);
140 }
isModOrRefSet(const ModRefInfo MRI)141 LLVM_NODISCARD inline bool isModOrRefSet(const ModRefInfo MRI) {
142   return static_cast<int>(MRI) & static_cast<int>(ModRefInfo::MustModRef);
143 }
isModAndRefSet(const ModRefInfo MRI)144 LLVM_NODISCARD inline bool isModAndRefSet(const ModRefInfo MRI) {
145   return (static_cast<int>(MRI) & static_cast<int>(ModRefInfo::MustModRef)) ==
146          static_cast<int>(ModRefInfo::MustModRef);
147 }
isModSet(const ModRefInfo MRI)148 LLVM_NODISCARD inline bool isModSet(const ModRefInfo MRI) {
149   return static_cast<int>(MRI) & static_cast<int>(ModRefInfo::MustMod);
150 }
isRefSet(const ModRefInfo MRI)151 LLVM_NODISCARD inline bool isRefSet(const ModRefInfo MRI) {
152   return static_cast<int>(MRI) & static_cast<int>(ModRefInfo::MustRef);
153 }
isMustSet(const ModRefInfo MRI)154 LLVM_NODISCARD inline bool isMustSet(const ModRefInfo MRI) {
155   return !(static_cast<int>(MRI) & static_cast<int>(ModRefInfo::NoModRef));
156 }
157 
setMod(const ModRefInfo MRI)158 LLVM_NODISCARD inline ModRefInfo setMod(const ModRefInfo MRI) {
159   return ModRefInfo(static_cast<int>(MRI) |
160                     static_cast<int>(ModRefInfo::MustMod));
161 }
setRef(const ModRefInfo MRI)162 LLVM_NODISCARD inline ModRefInfo setRef(const ModRefInfo MRI) {
163   return ModRefInfo(static_cast<int>(MRI) |
164                     static_cast<int>(ModRefInfo::MustRef));
165 }
setMust(const ModRefInfo MRI)166 LLVM_NODISCARD inline ModRefInfo setMust(const ModRefInfo MRI) {
167   return ModRefInfo(static_cast<int>(MRI) &
168                     static_cast<int>(ModRefInfo::MustModRef));
169 }
setModAndRef(const ModRefInfo MRI)170 LLVM_NODISCARD inline ModRefInfo setModAndRef(const ModRefInfo MRI) {
171   return ModRefInfo(static_cast<int>(MRI) |
172                     static_cast<int>(ModRefInfo::MustModRef));
173 }
clearMod(const ModRefInfo MRI)174 LLVM_NODISCARD inline ModRefInfo clearMod(const ModRefInfo MRI) {
175   return ModRefInfo(static_cast<int>(MRI) & static_cast<int>(ModRefInfo::Ref));
176 }
clearRef(const ModRefInfo MRI)177 LLVM_NODISCARD inline ModRefInfo clearRef(const ModRefInfo MRI) {
178   return ModRefInfo(static_cast<int>(MRI) & static_cast<int>(ModRefInfo::Mod));
179 }
clearMust(const ModRefInfo MRI)180 LLVM_NODISCARD inline ModRefInfo clearMust(const ModRefInfo MRI) {
181   return ModRefInfo(static_cast<int>(MRI) |
182                     static_cast<int>(ModRefInfo::NoModRef));
183 }
unionModRef(const ModRefInfo MRI1,const ModRefInfo MRI2)184 LLVM_NODISCARD inline ModRefInfo unionModRef(const ModRefInfo MRI1,
185                                              const ModRefInfo MRI2) {
186   return ModRefInfo(static_cast<int>(MRI1) | static_cast<int>(MRI2));
187 }
intersectModRef(const ModRefInfo MRI1,const ModRefInfo MRI2)188 LLVM_NODISCARD inline ModRefInfo intersectModRef(const ModRefInfo MRI1,
189                                                  const ModRefInfo MRI2) {
190   return ModRefInfo(static_cast<int>(MRI1) & static_cast<int>(MRI2));
191 }
192 
193 /// The locations at which a function might access memory.
194 ///
195 /// These are primarily used in conjunction with the \c AccessKind bits to
196 /// describe both the nature of access and the locations of access for a
197 /// function call.
198 enum FunctionModRefLocation {
199   /// Base case is no access to memory.
200   FMRL_Nowhere = 0,
201   /// Access to memory via argument pointers.
202   FMRL_ArgumentPointees = 8,
203   /// Memory that is inaccessible via LLVM IR.
204   FMRL_InaccessibleMem = 16,
205   /// Access to any memory.
206   FMRL_Anywhere = 32 | FMRL_InaccessibleMem | FMRL_ArgumentPointees
207 };
208 
209 /// Summary of how a function affects memory in the program.
210 ///
211 /// Loads from constant globals are not considered memory accesses for this
212 /// interface. Also, functions may freely modify stack space local to their
213 /// invocation without having to report it through these interfaces.
214 enum FunctionModRefBehavior {
215   /// This function does not perform any non-local loads or stores to memory.
216   ///
217   /// This property corresponds to the GCC 'const' attribute.
218   /// This property corresponds to the LLVM IR 'readnone' attribute.
219   /// This property corresponds to the IntrNoMem LLVM intrinsic flag.
220   FMRB_DoesNotAccessMemory =
221       FMRL_Nowhere | static_cast<int>(ModRefInfo::NoModRef),
222 
223   /// The only memory references in this function (if it has any) are
224   /// non-volatile loads from objects pointed to by its pointer-typed
225   /// arguments, with arbitrary offsets.
226   ///
227   /// This property corresponds to the combination of the IntrReadMem
228   /// and IntrArgMemOnly LLVM intrinsic flags.
229   FMRB_OnlyReadsArgumentPointees =
230       FMRL_ArgumentPointees | static_cast<int>(ModRefInfo::Ref),
231 
232   /// The only memory references in this function (if it has any) are
233   /// non-volatile stores from objects pointed to by its pointer-typed
234   /// arguments, with arbitrary offsets.
235   ///
236   /// This property corresponds to the combination of the IntrWriteMem
237   /// and IntrArgMemOnly LLVM intrinsic flags.
238   FMRB_OnlyWritesArgumentPointees =
239       FMRL_ArgumentPointees | static_cast<int>(ModRefInfo::Mod),
240 
241   /// The only memory references in this function (if it has any) are
242   /// non-volatile loads and stores from objects pointed to by its
243   /// pointer-typed arguments, with arbitrary offsets.
244   ///
245   /// This property corresponds to the IntrArgMemOnly LLVM intrinsic flag.
246   FMRB_OnlyAccessesArgumentPointees =
247       FMRL_ArgumentPointees | static_cast<int>(ModRefInfo::ModRef),
248 
249   /// The only memory references in this function (if it has any) are
250   /// reads of memory that is otherwise inaccessible via LLVM IR.
251   ///
252   /// This property corresponds to the LLVM IR inaccessiblememonly attribute.
253   FMRB_OnlyReadsInaccessibleMem =
254       FMRL_InaccessibleMem | static_cast<int>(ModRefInfo::Ref),
255 
256   /// The only memory references in this function (if it has any) are
257   /// writes to memory that is otherwise inaccessible via LLVM IR.
258   ///
259   /// This property corresponds to the LLVM IR inaccessiblememonly attribute.
260   FMRB_OnlyWritesInaccessibleMem =
261       FMRL_InaccessibleMem | static_cast<int>(ModRefInfo::Mod),
262 
263   /// The only memory references in this function (if it has any) are
264   /// references of memory that is otherwise inaccessible via LLVM IR.
265   ///
266   /// This property corresponds to the LLVM IR inaccessiblememonly attribute.
267   FMRB_OnlyAccessesInaccessibleMem =
268       FMRL_InaccessibleMem | static_cast<int>(ModRefInfo::ModRef),
269 
270   /// The function may perform non-volatile loads from objects pointed
271   /// to by its pointer-typed arguments, with arbitrary offsets, and
272   /// it may also perform loads of memory that is otherwise
273   /// inaccessible via LLVM IR.
274   ///
275   /// This property corresponds to the LLVM IR
276   /// inaccessiblemem_or_argmemonly attribute.
277   FMRB_OnlyReadsInaccessibleOrArgMem = FMRL_InaccessibleMem |
278                                        FMRL_ArgumentPointees |
279                                        static_cast<int>(ModRefInfo::Ref),
280 
281   /// The function may perform non-volatile stores to objects pointed
282   /// to by its pointer-typed arguments, with arbitrary offsets, and
283   /// it may also perform stores of memory that is otherwise
284   /// inaccessible via LLVM IR.
285   ///
286   /// This property corresponds to the LLVM IR
287   /// inaccessiblemem_or_argmemonly attribute.
288   FMRB_OnlyWritesInaccessibleOrArgMem = FMRL_InaccessibleMem |
289                                         FMRL_ArgumentPointees |
290                                         static_cast<int>(ModRefInfo::Mod),
291 
292   /// The function may perform non-volatile loads and stores of objects
293   /// pointed to by its pointer-typed arguments, with arbitrary offsets, and
294   /// it may also perform loads and stores of memory that is otherwise
295   /// inaccessible via LLVM IR.
296   ///
297   /// This property corresponds to the LLVM IR
298   /// inaccessiblemem_or_argmemonly attribute.
299   FMRB_OnlyAccessesInaccessibleOrArgMem = FMRL_InaccessibleMem |
300                                           FMRL_ArgumentPointees |
301                                           static_cast<int>(ModRefInfo::ModRef),
302 
303   /// This function does not perform any non-local stores or volatile loads,
304   /// but may read from any memory location.
305   ///
306   /// This property corresponds to the GCC 'pure' attribute.
307   /// This property corresponds to the LLVM IR 'readonly' attribute.
308   /// This property corresponds to the IntrReadMem LLVM intrinsic flag.
309   FMRB_OnlyReadsMemory = FMRL_Anywhere | static_cast<int>(ModRefInfo::Ref),
310 
311   // This function does not read from memory anywhere, but may write to any
312   // memory location.
313   //
314   // This property corresponds to the LLVM IR 'writeonly' attribute.
315   // This property corresponds to the IntrWriteMem LLVM intrinsic flag.
316   FMRB_OnlyWritesMemory = FMRL_Anywhere | static_cast<int>(ModRefInfo::Mod),
317 
318   /// This indicates that the function could not be classified into one of the
319   /// behaviors above.
320   FMRB_UnknownModRefBehavior =
321       FMRL_Anywhere | static_cast<int>(ModRefInfo::ModRef)
322 };
323 
324 // Wrapper method strips bits significant only in FunctionModRefBehavior,
325 // to obtain a valid ModRefInfo. The benefit of using the wrapper is that if
326 // ModRefInfo enum changes, the wrapper can be updated to & with the new enum
327 // entry with all bits set to 1.
328 LLVM_NODISCARD inline ModRefInfo
createModRefInfo(const FunctionModRefBehavior FMRB)329 createModRefInfo(const FunctionModRefBehavior FMRB) {
330   return ModRefInfo(FMRB & static_cast<int>(ModRefInfo::ModRef));
331 }
332 
333 /// This class stores info we want to provide to or retain within an alias
334 /// query. By default, the root query is stateless and starts with a freshly
335 /// constructed info object. Specific alias analyses can use this query info to
336 /// store per-query state that is important for recursive or nested queries to
337 /// avoid recomputing. To enable preserving this state across multiple queries
338 /// where safe (due to the IR not changing), use a `BatchAAResults` wrapper.
339 /// The information stored in an `AAQueryInfo` is currently limitted to the
340 /// caches used by BasicAA, but can further be extended to fit other AA needs.
341 class AAQueryInfo {
342 public:
343   using LocPair = std::pair<MemoryLocation, MemoryLocation>;
344   using AliasCacheT = SmallDenseMap<LocPair, AliasResult, 8>;
345   AliasCacheT AliasCache;
346 
347   using IsCapturedCacheT = SmallDenseMap<const Value *, bool, 8>;
348   IsCapturedCacheT IsCapturedCache;
349 
AAQueryInfo()350   AAQueryInfo() : AliasCache(), IsCapturedCache() {}
351 
updateResult(const LocPair & Locs,AliasResult Result)352   AliasResult updateResult(const LocPair &Locs, AliasResult Result) {
353     auto It = AliasCache.find(Locs);
354     assert(It != AliasCache.end() && "Entry must have existed");
355     return It->second = Result;
356   }
357 };
358 
359 class BatchAAResults;
360 
361 class AAResults {
362 public:
363   // Make these results default constructable and movable. We have to spell
364   // these out because MSVC won't synthesize them.
AAResults(const TargetLibraryInfo & TLI)365   AAResults(const TargetLibraryInfo &TLI) : TLI(TLI) {}
366   AAResults(AAResults &&Arg);
367   ~AAResults();
368 
369   /// Register a specific AA result.
addAAResult(AAResultT & AAResult)370   template <typename AAResultT> void addAAResult(AAResultT &AAResult) {
371     // FIXME: We should use a much lighter weight system than the usual
372     // polymorphic pattern because we don't own AAResult. It should
373     // ideally involve two pointers and no separate allocation.
374     AAs.emplace_back(new Model<AAResultT>(AAResult, *this));
375   }
376 
377   /// Register a function analysis ID that the results aggregation depends on.
378   ///
379   /// This is used in the new pass manager to implement the invalidation logic
380   /// where we must invalidate the results aggregation if any of our component
381   /// analyses become invalid.
addAADependencyID(AnalysisKey * ID)382   void addAADependencyID(AnalysisKey *ID) { AADeps.push_back(ID); }
383 
384   /// Handle invalidation events in the new pass manager.
385   ///
386   /// The aggregation is invalidated if any of the underlying analyses is
387   /// invalidated.
388   bool invalidate(Function &F, const PreservedAnalyses &PA,
389                   FunctionAnalysisManager::Invalidator &Inv);
390 
391   //===--------------------------------------------------------------------===//
392   /// \name Alias Queries
393   /// @{
394 
395   /// The main low level interface to the alias analysis implementation.
396   /// Returns an AliasResult indicating whether the two pointers are aliased to
397   /// each other. This is the interface that must be implemented by specific
398   /// alias analysis implementations.
399   AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB);
400 
401   /// A convenience wrapper around the primary \c alias interface.
alias(const Value * V1,LocationSize V1Size,const Value * V2,LocationSize V2Size)402   AliasResult alias(const Value *V1, LocationSize V1Size, const Value *V2,
403                     LocationSize V2Size) {
404     return alias(MemoryLocation(V1, V1Size), MemoryLocation(V2, V2Size));
405   }
406 
407   /// A convenience wrapper around the primary \c alias interface.
alias(const Value * V1,const Value * V2)408   AliasResult alias(const Value *V1, const Value *V2) {
409     return alias(MemoryLocation::getBeforeOrAfter(V1),
410                  MemoryLocation::getBeforeOrAfter(V2));
411   }
412 
413   /// A trivial helper function to check to see if the specified pointers are
414   /// no-alias.
isNoAlias(const MemoryLocation & LocA,const MemoryLocation & LocB)415   bool isNoAlias(const MemoryLocation &LocA, const MemoryLocation &LocB) {
416     return alias(LocA, LocB) == NoAlias;
417   }
418 
419   /// A convenience wrapper around the \c isNoAlias helper interface.
isNoAlias(const Value * V1,LocationSize V1Size,const Value * V2,LocationSize V2Size)420   bool isNoAlias(const Value *V1, LocationSize V1Size, const Value *V2,
421                  LocationSize V2Size) {
422     return isNoAlias(MemoryLocation(V1, V1Size), MemoryLocation(V2, V2Size));
423   }
424 
425   /// A convenience wrapper around the \c isNoAlias helper interface.
isNoAlias(const Value * V1,const Value * V2)426   bool isNoAlias(const Value *V1, const Value *V2) {
427     return isNoAlias(MemoryLocation::getBeforeOrAfter(V1),
428                      MemoryLocation::getBeforeOrAfter(V2));
429   }
430 
431   /// A trivial helper function to check to see if the specified pointers are
432   /// must-alias.
isMustAlias(const MemoryLocation & LocA,const MemoryLocation & LocB)433   bool isMustAlias(const MemoryLocation &LocA, const MemoryLocation &LocB) {
434     return alias(LocA, LocB) == MustAlias;
435   }
436 
437   /// A convenience wrapper around the \c isMustAlias helper interface.
isMustAlias(const Value * V1,const Value * V2)438   bool isMustAlias(const Value *V1, const Value *V2) {
439     return alias(V1, LocationSize::precise(1), V2, LocationSize::precise(1)) ==
440            MustAlias;
441   }
442 
443   /// Checks whether the given location points to constant memory, or if
444   /// \p OrLocal is true whether it points to a local alloca.
445   bool pointsToConstantMemory(const MemoryLocation &Loc, bool OrLocal = false);
446 
447   /// A convenience wrapper around the primary \c pointsToConstantMemory
448   /// interface.
449   bool pointsToConstantMemory(const Value *P, bool OrLocal = false) {
450     return pointsToConstantMemory(MemoryLocation::getBeforeOrAfter(P), OrLocal);
451   }
452 
453   /// @}
454   //===--------------------------------------------------------------------===//
455   /// \name Simple mod/ref information
456   /// @{
457 
458   /// Get the ModRef info associated with a pointer argument of a call. The
459   /// result's bits are set to indicate the allowed aliasing ModRef kinds. Note
460   /// that these bits do not necessarily account for the overall behavior of
461   /// the function, but rather only provide additional per-argument
462   /// information. This never sets ModRefInfo::Must.
463   ModRefInfo getArgModRefInfo(const CallBase *Call, unsigned ArgIdx);
464 
465   /// Return the behavior of the given call site.
466   FunctionModRefBehavior getModRefBehavior(const CallBase *Call);
467 
468   /// Return the behavior when calling the given function.
469   FunctionModRefBehavior getModRefBehavior(const Function *F);
470 
471   /// Checks if the specified call is known to never read or write memory.
472   ///
473   /// Note that if the call only reads from known-constant memory, it is also
474   /// legal to return true. Also, calls that unwind the stack are legal for
475   /// this predicate.
476   ///
477   /// Many optimizations (such as CSE and LICM) can be performed on such calls
478   /// without worrying about aliasing properties, and many calls have this
479   /// property (e.g. calls to 'sin' and 'cos').
480   ///
481   /// This property corresponds to the GCC 'const' attribute.
doesNotAccessMemory(const CallBase * Call)482   bool doesNotAccessMemory(const CallBase *Call) {
483     return getModRefBehavior(Call) == FMRB_DoesNotAccessMemory;
484   }
485 
486   /// Checks if the specified function is known to never read or write memory.
487   ///
488   /// Note that if the function only reads from known-constant memory, it is
489   /// also legal to return true. Also, function that unwind the stack are legal
490   /// for this predicate.
491   ///
492   /// Many optimizations (such as CSE and LICM) can be performed on such calls
493   /// to such functions without worrying about aliasing properties, and many
494   /// functions have this property (e.g. 'sin' and 'cos').
495   ///
496   /// This property corresponds to the GCC 'const' attribute.
doesNotAccessMemory(const Function * F)497   bool doesNotAccessMemory(const Function *F) {
498     return getModRefBehavior(F) == FMRB_DoesNotAccessMemory;
499   }
500 
501   /// Checks if the specified call is known to only read from non-volatile
502   /// memory (or not access memory at all).
503   ///
504   /// Calls that unwind the stack are legal for this predicate.
505   ///
506   /// This property allows many common optimizations to be performed in the
507   /// absence of interfering store instructions, such as CSE of strlen calls.
508   ///
509   /// This property corresponds to the GCC 'pure' attribute.
onlyReadsMemory(const CallBase * Call)510   bool onlyReadsMemory(const CallBase *Call) {
511     return onlyReadsMemory(getModRefBehavior(Call));
512   }
513 
514   /// Checks if the specified function is known to only read from non-volatile
515   /// memory (or not access memory at all).
516   ///
517   /// Functions that unwind the stack are legal for this predicate.
518   ///
519   /// This property allows many common optimizations to be performed in the
520   /// absence of interfering store instructions, such as CSE of strlen calls.
521   ///
522   /// This property corresponds to the GCC 'pure' attribute.
onlyReadsMemory(const Function * F)523   bool onlyReadsMemory(const Function *F) {
524     return onlyReadsMemory(getModRefBehavior(F));
525   }
526 
527   /// Checks if functions with the specified behavior are known to only read
528   /// from non-volatile memory (or not access memory at all).
onlyReadsMemory(FunctionModRefBehavior MRB)529   static bool onlyReadsMemory(FunctionModRefBehavior MRB) {
530     return !isModSet(createModRefInfo(MRB));
531   }
532 
533   /// Checks if functions with the specified behavior are known to only write
534   /// memory (or not access memory at all).
doesNotReadMemory(FunctionModRefBehavior MRB)535   static bool doesNotReadMemory(FunctionModRefBehavior MRB) {
536     return !isRefSet(createModRefInfo(MRB));
537   }
538 
539   /// Checks if functions with the specified behavior are known to read and
540   /// write at most from objects pointed to by their pointer-typed arguments
541   /// (with arbitrary offsets).
onlyAccessesArgPointees(FunctionModRefBehavior MRB)542   static bool onlyAccessesArgPointees(FunctionModRefBehavior MRB) {
543     return !(MRB & FMRL_Anywhere & ~FMRL_ArgumentPointees);
544   }
545 
546   /// Checks if functions with the specified behavior are known to potentially
547   /// read or write from objects pointed to be their pointer-typed arguments
548   /// (with arbitrary offsets).
doesAccessArgPointees(FunctionModRefBehavior MRB)549   static bool doesAccessArgPointees(FunctionModRefBehavior MRB) {
550     return isModOrRefSet(createModRefInfo(MRB)) &&
551            (MRB & FMRL_ArgumentPointees);
552   }
553 
554   /// Checks if functions with the specified behavior are known to read and
555   /// write at most from memory that is inaccessible from LLVM IR.
onlyAccessesInaccessibleMem(FunctionModRefBehavior MRB)556   static bool onlyAccessesInaccessibleMem(FunctionModRefBehavior MRB) {
557     return !(MRB & FMRL_Anywhere & ~FMRL_InaccessibleMem);
558   }
559 
560   /// Checks if functions with the specified behavior are known to potentially
561   /// read or write from memory that is inaccessible from LLVM IR.
doesAccessInaccessibleMem(FunctionModRefBehavior MRB)562   static bool doesAccessInaccessibleMem(FunctionModRefBehavior MRB) {
563     return isModOrRefSet(createModRefInfo(MRB)) && (MRB & FMRL_InaccessibleMem);
564   }
565 
566   /// Checks if functions with the specified behavior are known to read and
567   /// write at most from memory that is inaccessible from LLVM IR or objects
568   /// pointed to by their pointer-typed arguments (with arbitrary offsets).
onlyAccessesInaccessibleOrArgMem(FunctionModRefBehavior MRB)569   static bool onlyAccessesInaccessibleOrArgMem(FunctionModRefBehavior MRB) {
570     return !(MRB & FMRL_Anywhere &
571              ~(FMRL_InaccessibleMem | FMRL_ArgumentPointees));
572   }
573 
574   /// getModRefInfo (for call sites) - Return information about whether
575   /// a particular call site modifies or reads the specified memory location.
576   ModRefInfo getModRefInfo(const CallBase *Call, const MemoryLocation &Loc);
577 
578   /// getModRefInfo (for call sites) - A convenience wrapper.
getModRefInfo(const CallBase * Call,const Value * P,LocationSize Size)579   ModRefInfo getModRefInfo(const CallBase *Call, const Value *P,
580                            LocationSize Size) {
581     return getModRefInfo(Call, MemoryLocation(P, Size));
582   }
583 
584   /// getModRefInfo (for loads) - Return information about whether
585   /// a particular load modifies or reads the specified memory location.
586   ModRefInfo getModRefInfo(const LoadInst *L, const MemoryLocation &Loc);
587 
588   /// getModRefInfo (for loads) - A convenience wrapper.
getModRefInfo(const LoadInst * L,const Value * P,LocationSize Size)589   ModRefInfo getModRefInfo(const LoadInst *L, const Value *P,
590                            LocationSize Size) {
591     return getModRefInfo(L, MemoryLocation(P, Size));
592   }
593 
594   /// getModRefInfo (for stores) - Return information about whether
595   /// a particular store modifies or reads the specified memory location.
596   ModRefInfo getModRefInfo(const StoreInst *S, const MemoryLocation &Loc);
597 
598   /// getModRefInfo (for stores) - A convenience wrapper.
getModRefInfo(const StoreInst * S,const Value * P,LocationSize Size)599   ModRefInfo getModRefInfo(const StoreInst *S, const Value *P,
600                            LocationSize Size) {
601     return getModRefInfo(S, MemoryLocation(P, Size));
602   }
603 
604   /// getModRefInfo (for fences) - Return information about whether
605   /// a particular store modifies or reads the specified memory location.
606   ModRefInfo getModRefInfo(const FenceInst *S, const MemoryLocation &Loc);
607 
608   /// getModRefInfo (for fences) - A convenience wrapper.
getModRefInfo(const FenceInst * S,const Value * P,LocationSize Size)609   ModRefInfo getModRefInfo(const FenceInst *S, const Value *P,
610                            LocationSize Size) {
611     return getModRefInfo(S, MemoryLocation(P, Size));
612   }
613 
614   /// getModRefInfo (for cmpxchges) - Return information about whether
615   /// a particular cmpxchg modifies or reads the specified memory location.
616   ModRefInfo getModRefInfo(const AtomicCmpXchgInst *CX,
617                            const MemoryLocation &Loc);
618 
619   /// getModRefInfo (for cmpxchges) - A convenience wrapper.
getModRefInfo(const AtomicCmpXchgInst * CX,const Value * P,LocationSize Size)620   ModRefInfo getModRefInfo(const AtomicCmpXchgInst *CX, const Value *P,
621                            LocationSize Size) {
622     return getModRefInfo(CX, MemoryLocation(P, Size));
623   }
624 
625   /// getModRefInfo (for atomicrmws) - Return information about whether
626   /// a particular atomicrmw modifies or reads the specified memory location.
627   ModRefInfo getModRefInfo(const AtomicRMWInst *RMW, const MemoryLocation &Loc);
628 
629   /// getModRefInfo (for atomicrmws) - A convenience wrapper.
getModRefInfo(const AtomicRMWInst * RMW,const Value * P,LocationSize Size)630   ModRefInfo getModRefInfo(const AtomicRMWInst *RMW, const Value *P,
631                            LocationSize Size) {
632     return getModRefInfo(RMW, MemoryLocation(P, Size));
633   }
634 
635   /// getModRefInfo (for va_args) - Return information about whether
636   /// a particular va_arg modifies or reads the specified memory location.
637   ModRefInfo getModRefInfo(const VAArgInst *I, const MemoryLocation &Loc);
638 
639   /// getModRefInfo (for va_args) - A convenience wrapper.
getModRefInfo(const VAArgInst * I,const Value * P,LocationSize Size)640   ModRefInfo getModRefInfo(const VAArgInst *I, const Value *P,
641                            LocationSize Size) {
642     return getModRefInfo(I, MemoryLocation(P, Size));
643   }
644 
645   /// getModRefInfo (for catchpads) - Return information about whether
646   /// a particular catchpad modifies or reads the specified memory location.
647   ModRefInfo getModRefInfo(const CatchPadInst *I, const MemoryLocation &Loc);
648 
649   /// getModRefInfo (for catchpads) - A convenience wrapper.
getModRefInfo(const CatchPadInst * I,const Value * P,LocationSize Size)650   ModRefInfo getModRefInfo(const CatchPadInst *I, const Value *P,
651                            LocationSize Size) {
652     return getModRefInfo(I, MemoryLocation(P, Size));
653   }
654 
655   /// getModRefInfo (for catchrets) - Return information about whether
656   /// a particular catchret modifies or reads the specified memory location.
657   ModRefInfo getModRefInfo(const CatchReturnInst *I, const MemoryLocation &Loc);
658 
659   /// getModRefInfo (for catchrets) - A convenience wrapper.
getModRefInfo(const CatchReturnInst * I,const Value * P,LocationSize Size)660   ModRefInfo getModRefInfo(const CatchReturnInst *I, const Value *P,
661                            LocationSize Size) {
662     return getModRefInfo(I, MemoryLocation(P, Size));
663   }
664 
665   /// Check whether or not an instruction may read or write the optionally
666   /// specified memory location.
667   ///
668   ///
669   /// An instruction that doesn't read or write memory may be trivially LICM'd
670   /// for example.
671   ///
672   /// For function calls, this delegates to the alias-analysis specific
673   /// call-site mod-ref behavior queries. Otherwise it delegates to the specific
674   /// helpers above.
getModRefInfo(const Instruction * I,const Optional<MemoryLocation> & OptLoc)675   ModRefInfo getModRefInfo(const Instruction *I,
676                            const Optional<MemoryLocation> &OptLoc) {
677     AAQueryInfo AAQIP;
678     return getModRefInfo(I, OptLoc, AAQIP);
679   }
680 
681   /// A convenience wrapper for constructing the memory location.
getModRefInfo(const Instruction * I,const Value * P,LocationSize Size)682   ModRefInfo getModRefInfo(const Instruction *I, const Value *P,
683                            LocationSize Size) {
684     return getModRefInfo(I, MemoryLocation(P, Size));
685   }
686 
687   /// Return information about whether a call and an instruction may refer to
688   /// the same memory locations.
689   ModRefInfo getModRefInfo(Instruction *I, const CallBase *Call);
690 
691   /// Return information about whether two call sites may refer to the same set
692   /// of memory locations. See the AA documentation for details:
693   ///   http://llvm.org/docs/AliasAnalysis.html#ModRefInfo
694   ModRefInfo getModRefInfo(const CallBase *Call1, const CallBase *Call2);
695 
696   /// Return information about whether a particular call site modifies
697   /// or reads the specified memory location \p MemLoc before instruction \p I
698   /// in a BasicBlock.
699   /// Early exits in callCapturesBefore may lead to ModRefInfo::Must not being
700   /// set.
701   ModRefInfo callCapturesBefore(const Instruction *I,
702                                 const MemoryLocation &MemLoc, DominatorTree *DT);
703 
704   /// A convenience wrapper to synthesize a memory location.
callCapturesBefore(const Instruction * I,const Value * P,LocationSize Size,DominatorTree * DT)705   ModRefInfo callCapturesBefore(const Instruction *I, const Value *P,
706                                 LocationSize Size, DominatorTree *DT) {
707     return callCapturesBefore(I, MemoryLocation(P, Size), DT);
708   }
709 
710   /// @}
711   //===--------------------------------------------------------------------===//
712   /// \name Higher level methods for querying mod/ref information.
713   /// @{
714 
715   /// Check if it is possible for execution of the specified basic block to
716   /// modify the location Loc.
717   bool canBasicBlockModify(const BasicBlock &BB, const MemoryLocation &Loc);
718 
719   /// A convenience wrapper synthesizing a memory location.
canBasicBlockModify(const BasicBlock & BB,const Value * P,LocationSize Size)720   bool canBasicBlockModify(const BasicBlock &BB, const Value *P,
721                            LocationSize Size) {
722     return canBasicBlockModify(BB, MemoryLocation(P, Size));
723   }
724 
725   /// Check if it is possible for the execution of the specified instructions
726   /// to mod\ref (according to the mode) the location Loc.
727   ///
728   /// The instructions to consider are all of the instructions in the range of
729   /// [I1,I2] INCLUSIVE. I1 and I2 must be in the same basic block.
730   bool canInstructionRangeModRef(const Instruction &I1, const Instruction &I2,
731                                  const MemoryLocation &Loc,
732                                  const ModRefInfo Mode);
733 
734   /// A convenience wrapper synthesizing a memory location.
canInstructionRangeModRef(const Instruction & I1,const Instruction & I2,const Value * Ptr,LocationSize Size,const ModRefInfo Mode)735   bool canInstructionRangeModRef(const Instruction &I1, const Instruction &I2,
736                                  const Value *Ptr, LocationSize Size,
737                                  const ModRefInfo Mode) {
738     return canInstructionRangeModRef(I1, I2, MemoryLocation(Ptr, Size), Mode);
739   }
740 
741 private:
742   AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB,
743                     AAQueryInfo &AAQI);
744   bool pointsToConstantMemory(const MemoryLocation &Loc, AAQueryInfo &AAQI,
745                               bool OrLocal = false);
746   ModRefInfo getModRefInfo(Instruction *I, const CallBase *Call2,
747                            AAQueryInfo &AAQIP);
748   ModRefInfo getModRefInfo(const CallBase *Call, const MemoryLocation &Loc,
749                            AAQueryInfo &AAQI);
750   ModRefInfo getModRefInfo(const CallBase *Call1, const CallBase *Call2,
751                            AAQueryInfo &AAQI);
752   ModRefInfo getModRefInfo(const VAArgInst *V, const MemoryLocation &Loc,
753                            AAQueryInfo &AAQI);
754   ModRefInfo getModRefInfo(const LoadInst *L, const MemoryLocation &Loc,
755                            AAQueryInfo &AAQI);
756   ModRefInfo getModRefInfo(const StoreInst *S, const MemoryLocation &Loc,
757                            AAQueryInfo &AAQI);
758   ModRefInfo getModRefInfo(const FenceInst *S, const MemoryLocation &Loc,
759                            AAQueryInfo &AAQI);
760   ModRefInfo getModRefInfo(const AtomicCmpXchgInst *CX,
761                            const MemoryLocation &Loc, AAQueryInfo &AAQI);
762   ModRefInfo getModRefInfo(const AtomicRMWInst *RMW, const MemoryLocation &Loc,
763                            AAQueryInfo &AAQI);
764   ModRefInfo getModRefInfo(const CatchPadInst *I, const MemoryLocation &Loc,
765                            AAQueryInfo &AAQI);
766   ModRefInfo getModRefInfo(const CatchReturnInst *I, const MemoryLocation &Loc,
767                            AAQueryInfo &AAQI);
getModRefInfo(const Instruction * I,const Optional<MemoryLocation> & OptLoc,AAQueryInfo & AAQIP)768   ModRefInfo getModRefInfo(const Instruction *I,
769                            const Optional<MemoryLocation> &OptLoc,
770                            AAQueryInfo &AAQIP) {
771     if (OptLoc == None) {
772       if (const auto *Call = dyn_cast<CallBase>(I)) {
773         return createModRefInfo(getModRefBehavior(Call));
774       }
775     }
776 
777     const MemoryLocation &Loc = OptLoc.getValueOr(MemoryLocation());
778 
779     switch (I->getOpcode()) {
780     case Instruction::VAArg:
781       return getModRefInfo((const VAArgInst *)I, Loc, AAQIP);
782     case Instruction::Load:
783       return getModRefInfo((const LoadInst *)I, Loc, AAQIP);
784     case Instruction::Store:
785       return getModRefInfo((const StoreInst *)I, Loc, AAQIP);
786     case Instruction::Fence:
787       return getModRefInfo((const FenceInst *)I, Loc, AAQIP);
788     case Instruction::AtomicCmpXchg:
789       return getModRefInfo((const AtomicCmpXchgInst *)I, Loc, AAQIP);
790     case Instruction::AtomicRMW:
791       return getModRefInfo((const AtomicRMWInst *)I, Loc, AAQIP);
792     case Instruction::Call:
793       return getModRefInfo((const CallInst *)I, Loc, AAQIP);
794     case Instruction::Invoke:
795       return getModRefInfo((const InvokeInst *)I, Loc, AAQIP);
796     case Instruction::CatchPad:
797       return getModRefInfo((const CatchPadInst *)I, Loc, AAQIP);
798     case Instruction::CatchRet:
799       return getModRefInfo((const CatchReturnInst *)I, Loc, AAQIP);
800     default:
801       return ModRefInfo::NoModRef;
802     }
803   }
804 
805   class Concept;
806 
807   template <typename T> class Model;
808 
809   template <typename T> friend class AAResultBase;
810 
811   const TargetLibraryInfo &TLI;
812 
813   std::vector<std::unique_ptr<Concept>> AAs;
814 
815   std::vector<AnalysisKey *> AADeps;
816 
817   /// Query depth used to distinguish recursive queries.
818   unsigned Depth = 0;
819 
820   friend class BatchAAResults;
821 };
822 
823 /// This class is a wrapper over an AAResults, and it is intended to be used
824 /// only when there are no IR changes inbetween queries. BatchAAResults is
825 /// reusing the same `AAQueryInfo` to preserve the state across queries,
826 /// esentially making AA work in "batch mode". The internal state cannot be
827 /// cleared, so to go "out-of-batch-mode", the user must either use AAResults,
828 /// or create a new BatchAAResults.
829 class BatchAAResults {
830   AAResults &AA;
831   AAQueryInfo AAQI;
832 
833 public:
BatchAAResults(AAResults & AAR)834   BatchAAResults(AAResults &AAR) : AA(AAR), AAQI() {}
alias(const MemoryLocation & LocA,const MemoryLocation & LocB)835   AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB) {
836     return AA.alias(LocA, LocB, AAQI);
837   }
838   bool pointsToConstantMemory(const MemoryLocation &Loc, bool OrLocal = false) {
839     return AA.pointsToConstantMemory(Loc, AAQI, OrLocal);
840   }
getModRefInfo(const CallBase * Call,const MemoryLocation & Loc)841   ModRefInfo getModRefInfo(const CallBase *Call, const MemoryLocation &Loc) {
842     return AA.getModRefInfo(Call, Loc, AAQI);
843   }
getModRefInfo(const CallBase * Call1,const CallBase * Call2)844   ModRefInfo getModRefInfo(const CallBase *Call1, const CallBase *Call2) {
845     return AA.getModRefInfo(Call1, Call2, AAQI);
846   }
getModRefInfo(const Instruction * I,const Optional<MemoryLocation> & OptLoc)847   ModRefInfo getModRefInfo(const Instruction *I,
848                            const Optional<MemoryLocation> &OptLoc) {
849     return AA.getModRefInfo(I, OptLoc, AAQI);
850   }
getModRefInfo(Instruction * I,const CallBase * Call2)851   ModRefInfo getModRefInfo(Instruction *I, const CallBase *Call2) {
852     return AA.getModRefInfo(I, Call2, AAQI);
853   }
getArgModRefInfo(const CallBase * Call,unsigned ArgIdx)854   ModRefInfo getArgModRefInfo(const CallBase *Call, unsigned ArgIdx) {
855     return AA.getArgModRefInfo(Call, ArgIdx);
856   }
getModRefBehavior(const CallBase * Call)857   FunctionModRefBehavior getModRefBehavior(const CallBase *Call) {
858     return AA.getModRefBehavior(Call);
859   }
isMustAlias(const MemoryLocation & LocA,const MemoryLocation & LocB)860   bool isMustAlias(const MemoryLocation &LocA, const MemoryLocation &LocB) {
861     return alias(LocA, LocB) == MustAlias;
862   }
isMustAlias(const Value * V1,const Value * V2)863   bool isMustAlias(const Value *V1, const Value *V2) {
864     return alias(MemoryLocation(V1, LocationSize::precise(1)),
865                  MemoryLocation(V2, LocationSize::precise(1))) == MustAlias;
866   }
867 };
868 
869 /// Temporary typedef for legacy code that uses a generic \c AliasAnalysis
870 /// pointer or reference.
871 using AliasAnalysis = AAResults;
872 
873 /// A private abstract base class describing the concept of an individual alias
874 /// analysis implementation.
875 ///
876 /// This interface is implemented by any \c Model instantiation. It is also the
877 /// interface which a type used to instantiate the model must provide.
878 ///
879 /// All of these methods model methods by the same name in the \c
880 /// AAResults class. Only differences and specifics to how the
881 /// implementations are called are documented here.
882 class AAResults::Concept {
883 public:
884   virtual ~Concept() = 0;
885 
886   /// An update API used internally by the AAResults to provide
887   /// a handle back to the top level aggregation.
888   virtual void setAAResults(AAResults *NewAAR) = 0;
889 
890   //===--------------------------------------------------------------------===//
891   /// \name Alias Queries
892   /// @{
893 
894   /// The main low level interface to the alias analysis implementation.
895   /// Returns an AliasResult indicating whether the two pointers are aliased to
896   /// each other. This is the interface that must be implemented by specific
897   /// alias analysis implementations.
898   virtual AliasResult alias(const MemoryLocation &LocA,
899                             const MemoryLocation &LocB, AAQueryInfo &AAQI) = 0;
900 
901   /// Checks whether the given location points to constant memory, or if
902   /// \p OrLocal is true whether it points to a local alloca.
903   virtual bool pointsToConstantMemory(const MemoryLocation &Loc,
904                                       AAQueryInfo &AAQI, bool OrLocal) = 0;
905 
906   /// @}
907   //===--------------------------------------------------------------------===//
908   /// \name Simple mod/ref information
909   /// @{
910 
911   /// Get the ModRef info associated with a pointer argument of a callsite. The
912   /// result's bits are set to indicate the allowed aliasing ModRef kinds. Note
913   /// that these bits do not necessarily account for the overall behavior of
914   /// the function, but rather only provide additional per-argument
915   /// information.
916   virtual ModRefInfo getArgModRefInfo(const CallBase *Call,
917                                       unsigned ArgIdx) = 0;
918 
919   /// Return the behavior of the given call site.
920   virtual FunctionModRefBehavior getModRefBehavior(const CallBase *Call) = 0;
921 
922   /// Return the behavior when calling the given function.
923   virtual FunctionModRefBehavior getModRefBehavior(const Function *F) = 0;
924 
925   /// getModRefInfo (for call sites) - Return information about whether
926   /// a particular call site modifies or reads the specified memory location.
927   virtual ModRefInfo getModRefInfo(const CallBase *Call,
928                                    const MemoryLocation &Loc,
929                                    AAQueryInfo &AAQI) = 0;
930 
931   /// Return information about whether two call sites may refer to the same set
932   /// of memory locations. See the AA documentation for details:
933   ///   http://llvm.org/docs/AliasAnalysis.html#ModRefInfo
934   virtual ModRefInfo getModRefInfo(const CallBase *Call1, const CallBase *Call2,
935                                    AAQueryInfo &AAQI) = 0;
936 
937   /// @}
938 };
939 
940 /// A private class template which derives from \c Concept and wraps some other
941 /// type.
942 ///
943 /// This models the concept by directly forwarding each interface point to the
944 /// wrapped type which must implement a compatible interface. This provides
945 /// a type erased binding.
946 template <typename AAResultT> class AAResults::Model final : public Concept {
947   AAResultT &Result;
948 
949 public:
Model(AAResultT & Result,AAResults & AAR)950   explicit Model(AAResultT &Result, AAResults &AAR) : Result(Result) {
951     Result.setAAResults(&AAR);
952   }
953   ~Model() override = default;
954 
setAAResults(AAResults * NewAAR)955   void setAAResults(AAResults *NewAAR) override { Result.setAAResults(NewAAR); }
956 
alias(const MemoryLocation & LocA,const MemoryLocation & LocB,AAQueryInfo & AAQI)957   AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB,
958                     AAQueryInfo &AAQI) override {
959     return Result.alias(LocA, LocB, AAQI);
960   }
961 
pointsToConstantMemory(const MemoryLocation & Loc,AAQueryInfo & AAQI,bool OrLocal)962   bool pointsToConstantMemory(const MemoryLocation &Loc, AAQueryInfo &AAQI,
963                               bool OrLocal) override {
964     return Result.pointsToConstantMemory(Loc, AAQI, OrLocal);
965   }
966 
getArgModRefInfo(const CallBase * Call,unsigned ArgIdx)967   ModRefInfo getArgModRefInfo(const CallBase *Call, unsigned ArgIdx) override {
968     return Result.getArgModRefInfo(Call, ArgIdx);
969   }
970 
getModRefBehavior(const CallBase * Call)971   FunctionModRefBehavior getModRefBehavior(const CallBase *Call) override {
972     return Result.getModRefBehavior(Call);
973   }
974 
getModRefBehavior(const Function * F)975   FunctionModRefBehavior getModRefBehavior(const Function *F) override {
976     return Result.getModRefBehavior(F);
977   }
978 
getModRefInfo(const CallBase * Call,const MemoryLocation & Loc,AAQueryInfo & AAQI)979   ModRefInfo getModRefInfo(const CallBase *Call, const MemoryLocation &Loc,
980                            AAQueryInfo &AAQI) override {
981     return Result.getModRefInfo(Call, Loc, AAQI);
982   }
983 
getModRefInfo(const CallBase * Call1,const CallBase * Call2,AAQueryInfo & AAQI)984   ModRefInfo getModRefInfo(const CallBase *Call1, const CallBase *Call2,
985                            AAQueryInfo &AAQI) override {
986     return Result.getModRefInfo(Call1, Call2, AAQI);
987   }
988 };
989 
990 /// A CRTP-driven "mixin" base class to help implement the function alias
991 /// analysis results concept.
992 ///
993 /// Because of the nature of many alias analysis implementations, they often
994 /// only implement a subset of the interface. This base class will attempt to
995 /// implement the remaining portions of the interface in terms of simpler forms
996 /// of the interface where possible, and otherwise provide conservatively
997 /// correct fallback implementations.
998 ///
999 /// Implementors of an alias analysis should derive from this CRTP, and then
1000 /// override specific methods that they wish to customize. There is no need to
1001 /// use virtual anywhere, the CRTP base class does static dispatch to the
1002 /// derived type passed into it.
1003 template <typename DerivedT> class AAResultBase {
1004   // Expose some parts of the interface only to the AAResults::Model
1005   // for wrapping. Specifically, this allows the model to call our
1006   // setAAResults method without exposing it as a fully public API.
1007   friend class AAResults::Model<DerivedT>;
1008 
1009   /// A pointer to the AAResults object that this AAResult is
1010   /// aggregated within. May be null if not aggregated.
1011   AAResults *AAR = nullptr;
1012 
1013   /// Helper to dispatch calls back through the derived type.
derived()1014   DerivedT &derived() { return static_cast<DerivedT &>(*this); }
1015 
1016   /// A setter for the AAResults pointer, which is used to satisfy the
1017   /// AAResults::Model contract.
setAAResults(AAResults * NewAAR)1018   void setAAResults(AAResults *NewAAR) { AAR = NewAAR; }
1019 
1020 protected:
1021   /// This proxy class models a common pattern where we delegate to either the
1022   /// top-level \c AAResults aggregation if one is registered, or to the
1023   /// current result if none are registered.
1024   class AAResultsProxy {
1025     AAResults *AAR;
1026     DerivedT &CurrentResult;
1027 
1028   public:
AAResultsProxy(AAResults * AAR,DerivedT & CurrentResult)1029     AAResultsProxy(AAResults *AAR, DerivedT &CurrentResult)
1030         : AAR(AAR), CurrentResult(CurrentResult) {}
1031 
alias(const MemoryLocation & LocA,const MemoryLocation & LocB,AAQueryInfo & AAQI)1032     AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB,
1033                       AAQueryInfo &AAQI) {
1034       return AAR ? AAR->alias(LocA, LocB, AAQI)
1035                  : CurrentResult.alias(LocA, LocB, AAQI);
1036     }
1037 
pointsToConstantMemory(const MemoryLocation & Loc,AAQueryInfo & AAQI,bool OrLocal)1038     bool pointsToConstantMemory(const MemoryLocation &Loc, AAQueryInfo &AAQI,
1039                                 bool OrLocal) {
1040       return AAR ? AAR->pointsToConstantMemory(Loc, AAQI, OrLocal)
1041                  : CurrentResult.pointsToConstantMemory(Loc, AAQI, OrLocal);
1042     }
1043 
getArgModRefInfo(const CallBase * Call,unsigned ArgIdx)1044     ModRefInfo getArgModRefInfo(const CallBase *Call, unsigned ArgIdx) {
1045       return AAR ? AAR->getArgModRefInfo(Call, ArgIdx)
1046                  : CurrentResult.getArgModRefInfo(Call, ArgIdx);
1047     }
1048 
getModRefBehavior(const CallBase * Call)1049     FunctionModRefBehavior getModRefBehavior(const CallBase *Call) {
1050       return AAR ? AAR->getModRefBehavior(Call)
1051                  : CurrentResult.getModRefBehavior(Call);
1052     }
1053 
getModRefBehavior(const Function * F)1054     FunctionModRefBehavior getModRefBehavior(const Function *F) {
1055       return AAR ? AAR->getModRefBehavior(F) : CurrentResult.getModRefBehavior(F);
1056     }
1057 
getModRefInfo(const CallBase * Call,const MemoryLocation & Loc,AAQueryInfo & AAQI)1058     ModRefInfo getModRefInfo(const CallBase *Call, const MemoryLocation &Loc,
1059                              AAQueryInfo &AAQI) {
1060       return AAR ? AAR->getModRefInfo(Call, Loc, AAQI)
1061                  : CurrentResult.getModRefInfo(Call, Loc, AAQI);
1062     }
1063 
getModRefInfo(const CallBase * Call1,const CallBase * Call2,AAQueryInfo & AAQI)1064     ModRefInfo getModRefInfo(const CallBase *Call1, const CallBase *Call2,
1065                              AAQueryInfo &AAQI) {
1066       return AAR ? AAR->getModRefInfo(Call1, Call2, AAQI)
1067                  : CurrentResult.getModRefInfo(Call1, Call2, AAQI);
1068     }
1069   };
1070 
1071   explicit AAResultBase() = default;
1072 
1073   // Provide all the copy and move constructors so that derived types aren't
1074   // constrained.
AAResultBase(const AAResultBase & Arg)1075   AAResultBase(const AAResultBase &Arg) {}
AAResultBase(AAResultBase && Arg)1076   AAResultBase(AAResultBase &&Arg) {}
1077 
1078   /// Get a proxy for the best AA result set to query at this time.
1079   ///
1080   /// When this result is part of a larger aggregation, this will proxy to that
1081   /// aggregation. When this result is used in isolation, it will just delegate
1082   /// back to the derived class's implementation.
1083   ///
1084   /// Note that callers of this need to take considerable care to not cause
1085   /// performance problems when they use this routine, in the case of a large
1086   /// number of alias analyses being aggregated, it can be expensive to walk
1087   /// back across the chain.
getBestAAResults()1088   AAResultsProxy getBestAAResults() { return AAResultsProxy(AAR, derived()); }
1089 
1090 public:
alias(const MemoryLocation & LocA,const MemoryLocation & LocB,AAQueryInfo & AAQI)1091   AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB,
1092                     AAQueryInfo &AAQI) {
1093     return MayAlias;
1094   }
1095 
pointsToConstantMemory(const MemoryLocation & Loc,AAQueryInfo & AAQI,bool OrLocal)1096   bool pointsToConstantMemory(const MemoryLocation &Loc, AAQueryInfo &AAQI,
1097                               bool OrLocal) {
1098     return false;
1099   }
1100 
getArgModRefInfo(const CallBase * Call,unsigned ArgIdx)1101   ModRefInfo getArgModRefInfo(const CallBase *Call, unsigned ArgIdx) {
1102     return ModRefInfo::ModRef;
1103   }
1104 
getModRefBehavior(const CallBase * Call)1105   FunctionModRefBehavior getModRefBehavior(const CallBase *Call) {
1106     return FMRB_UnknownModRefBehavior;
1107   }
1108 
getModRefBehavior(const Function * F)1109   FunctionModRefBehavior getModRefBehavior(const Function *F) {
1110     return FMRB_UnknownModRefBehavior;
1111   }
1112 
getModRefInfo(const CallBase * Call,const MemoryLocation & Loc,AAQueryInfo & AAQI)1113   ModRefInfo getModRefInfo(const CallBase *Call, const MemoryLocation &Loc,
1114                            AAQueryInfo &AAQI) {
1115     return ModRefInfo::ModRef;
1116   }
1117 
getModRefInfo(const CallBase * Call1,const CallBase * Call2,AAQueryInfo & AAQI)1118   ModRefInfo getModRefInfo(const CallBase *Call1, const CallBase *Call2,
1119                            AAQueryInfo &AAQI) {
1120     return ModRefInfo::ModRef;
1121   }
1122 };
1123 
1124 /// Return true if this pointer is returned by a noalias function.
1125 bool isNoAliasCall(const Value *V);
1126 
1127 /// Return true if this is an argument with the noalias attribute.
1128 bool isNoAliasArgument(const Value *V);
1129 
1130 /// Return true if this pointer refers to a distinct and identifiable object.
1131 /// This returns true for:
1132 ///    Global Variables and Functions (but not Global Aliases)
1133 ///    Allocas
1134 ///    ByVal and NoAlias Arguments
1135 ///    NoAlias returns (e.g. calls to malloc)
1136 ///
1137 bool isIdentifiedObject(const Value *V);
1138 
1139 /// Return true if V is umabigously identified at the function-level.
1140 /// Different IdentifiedFunctionLocals can't alias.
1141 /// Further, an IdentifiedFunctionLocal can not alias with any function
1142 /// arguments other than itself, which is not necessarily true for
1143 /// IdentifiedObjects.
1144 bool isIdentifiedFunctionLocal(const Value *V);
1145 
1146 /// A manager for alias analyses.
1147 ///
1148 /// This class can have analyses registered with it and when run, it will run
1149 /// all of them and aggregate their results into single AA results interface
1150 /// that dispatches across all of the alias analysis results available.
1151 ///
1152 /// Note that the order in which analyses are registered is very significant.
1153 /// That is the order in which the results will be aggregated and queried.
1154 ///
1155 /// This manager effectively wraps the AnalysisManager for registering alias
1156 /// analyses. When you register your alias analysis with this manager, it will
1157 /// ensure the analysis itself is registered with its AnalysisManager.
1158 ///
1159 /// The result of this analysis is only invalidated if one of the particular
1160 /// aggregated AA results end up being invalidated. This removes the need to
1161 /// explicitly preserve the results of `AAManager`. Note that analyses should no
1162 /// longer be registered once the `AAManager` is run.
1163 class AAManager : public AnalysisInfoMixin<AAManager> {
1164 public:
1165   using Result = AAResults;
1166 
1167   /// Register a specific AA result.
registerFunctionAnalysis()1168   template <typename AnalysisT> void registerFunctionAnalysis() {
1169     ResultGetters.push_back(&getFunctionAAResultImpl<AnalysisT>);
1170   }
1171 
1172   /// Register a specific AA result.
registerModuleAnalysis()1173   template <typename AnalysisT> void registerModuleAnalysis() {
1174     ResultGetters.push_back(&getModuleAAResultImpl<AnalysisT>);
1175   }
1176 
1177   Result run(Function &F, FunctionAnalysisManager &AM);
1178 
1179 private:
1180   friend AnalysisInfoMixin<AAManager>;
1181 
1182   static AnalysisKey Key;
1183 
1184   SmallVector<void (*)(Function &F, FunctionAnalysisManager &AM,
1185                        AAResults &AAResults),
1186               4> ResultGetters;
1187 
1188   template <typename AnalysisT>
getFunctionAAResultImpl(Function & F,FunctionAnalysisManager & AM,AAResults & AAResults)1189   static void getFunctionAAResultImpl(Function &F,
1190                                       FunctionAnalysisManager &AM,
1191                                       AAResults &AAResults) {
1192     AAResults.addAAResult(AM.template getResult<AnalysisT>(F));
1193     AAResults.addAADependencyID(AnalysisT::ID());
1194   }
1195 
1196   template <typename AnalysisT>
getModuleAAResultImpl(Function & F,FunctionAnalysisManager & AM,AAResults & AAResults)1197   static void getModuleAAResultImpl(Function &F, FunctionAnalysisManager &AM,
1198                                     AAResults &AAResults) {
1199     auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
1200     if (auto *R =
1201             MAMProxy.template getCachedResult<AnalysisT>(*F.getParent())) {
1202       AAResults.addAAResult(*R);
1203       MAMProxy
1204           .template registerOuterAnalysisInvalidation<AnalysisT, AAManager>();
1205     }
1206   }
1207 };
1208 
1209 /// A wrapper pass to provide the legacy pass manager access to a suitably
1210 /// prepared AAResults object.
1211 class AAResultsWrapperPass : public FunctionPass {
1212   std::unique_ptr<AAResults> AAR;
1213 
1214 public:
1215   static char ID;
1216 
1217   AAResultsWrapperPass();
1218 
getAAResults()1219   AAResults &getAAResults() { return *AAR; }
getAAResults()1220   const AAResults &getAAResults() const { return *AAR; }
1221 
1222   bool runOnFunction(Function &F) override;
1223 
1224   void getAnalysisUsage(AnalysisUsage &AU) const override;
1225 };
1226 
1227 /// A wrapper pass for external alias analyses. This just squirrels away the
1228 /// callback used to run any analyses and register their results.
1229 struct ExternalAAWrapperPass : ImmutablePass {
1230   using CallbackT = std::function<void(Pass &, Function &, AAResults &)>;
1231 
1232   CallbackT CB;
1233 
1234   static char ID;
1235 
1236   ExternalAAWrapperPass();
1237 
1238   explicit ExternalAAWrapperPass(CallbackT CB);
1239 
getAnalysisUsageExternalAAWrapperPass1240   void getAnalysisUsage(AnalysisUsage &AU) const override {
1241     AU.setPreservesAll();
1242   }
1243 };
1244 
1245 FunctionPass *createAAResultsWrapperPass();
1246 
1247 /// A wrapper pass around a callback which can be used to populate the
1248 /// AAResults in the AAResultsWrapperPass from an external AA.
1249 ///
1250 /// The callback provided here will be used each time we prepare an AAResults
1251 /// object, and will receive a reference to the function wrapper pass, the
1252 /// function, and the AAResults object to populate. This should be used when
1253 /// setting up a custom pass pipeline to inject a hook into the AA results.
1254 ImmutablePass *createExternalAAWrapperPass(
1255     std::function<void(Pass &, Function &, AAResults &)> Callback);
1256 
1257 /// A helper for the legacy pass manager to create a \c AAResults
1258 /// object populated to the best of our ability for a particular function when
1259 /// inside of a \c ModulePass or a \c CallGraphSCCPass.
1260 ///
1261 /// If a \c ModulePass or a \c CallGraphSCCPass calls \p
1262 /// createLegacyPMAAResults, it also needs to call \p addUsedAAAnalyses in \p
1263 /// getAnalysisUsage.
1264 AAResults createLegacyPMAAResults(Pass &P, Function &F, BasicAAResult &BAR);
1265 
1266 /// A helper for the legacy pass manager to populate \p AU to add uses to make
1267 /// sure the analyses required by \p createLegacyPMAAResults are available.
1268 void getAAResultsAnalysisUsage(AnalysisUsage &AU);
1269 
1270 } // end namespace llvm
1271 
1272 #endif // LLVM_ANALYSIS_ALIASANALYSIS_H
1273