Home | History | Annotate | Download | only in Analysis
      1 //===- llvm/Analysis/AliasAnalysis.h - Alias Analysis Interface -*- C++ -*-===//
      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 defines the generic AliasAnalysis interface, which is used as the
     11 // common interface used by all clients of alias analysis information, and
     12 // implemented by all alias analysis implementations.  Mod/Ref information is
     13 // also captured by this interface.
     14 //
     15 // Implementations of this interface must implement the various virtual methods,
     16 // which automatically provides functionality for the entire suite of client
     17 // APIs.
     18 //
     19 // This API identifies memory regions with the MemoryLocation class. The pointer
     20 // component specifies the base memory address of the region. The Size specifies
     21 // the maximum size (in address units) of the memory region, or
     22 // MemoryLocation::UnknownSize if the size is not known. The TBAA tag
     23 // identifies the "type" of the memory reference; see the
     24 // TypeBasedAliasAnalysis class for details.
     25 //
     26 // Some non-obvious details include:
     27 //  - Pointers that point to two completely different objects in memory never
     28 //    alias, regardless of the value of the Size component.
     29 //  - NoAlias doesn't imply inequal pointers. The most obvious example of this
     30 //    is two pointers to constant memory. Even if they are equal, constant
     31 //    memory is never stored to, so there will never be any dependencies.
     32 //    In this and other situations, the pointers may be both NoAlias and
     33 //    MustAlias at the same time. The current API can only return one result,
     34 //    though this is rarely a problem in practice.
     35 //
     36 //===----------------------------------------------------------------------===//
     37 
     38 #ifndef LLVM_ANALYSIS_ALIASANALYSIS_H
     39 #define LLVM_ANALYSIS_ALIASANALYSIS_H
     40 
     41 #include "llvm/IR/CallSite.h"
     42 #include "llvm/IR/Metadata.h"
     43 #include "llvm/IR/PassManager.h"
     44 #include "llvm/Analysis/MemoryLocation.h"
     45 #include "llvm/Analysis/TargetLibraryInfo.h"
     46 
     47 namespace llvm {
     48 class BasicAAResult;
     49 class LoadInst;
     50 class StoreInst;
     51 class VAArgInst;
     52 class DataLayout;
     53 class Pass;
     54 class AnalysisUsage;
     55 class MemTransferInst;
     56 class MemIntrinsic;
     57 class DominatorTree;
     58 class OrderedBasicBlock;
     59 
     60 /// The possible results of an alias query.
     61 ///
     62 /// These results are always computed between two MemoryLocation objects as
     63 /// a query to some alias analysis.
     64 ///
     65 /// Note that these are unscoped enumerations because we would like to support
     66 /// implicitly testing a result for the existence of any possible aliasing with
     67 /// a conversion to bool, but an "enum class" doesn't support this. The
     68 /// canonical names from the literature are suffixed and unique anyways, and so
     69 /// they serve as global constants in LLVM for these results.
     70 ///
     71 /// See docs/AliasAnalysis.html for more information on the specific meanings
     72 /// of these values.
     73 enum AliasResult {
     74   /// The two locations do not alias at all.
     75   ///
     76   /// This value is arranged to convert to false, while all other values
     77   /// convert to true. This allows a boolean context to convert the result to
     78   /// a binary flag indicating whether there is the possibility of aliasing.
     79   NoAlias = 0,
     80   /// The two locations may or may not alias. This is the least precise result.
     81   MayAlias,
     82   /// The two locations alias, but only due to a partial overlap.
     83   PartialAlias,
     84   /// The two locations precisely alias each other.
     85   MustAlias,
     86 };
     87 
     88 /// Flags indicating whether a memory access modifies or references memory.
     89 ///
     90 /// This is no access at all, a modification, a reference, or both
     91 /// a modification and a reference. These are specifically structured such that
     92 /// they form a two bit matrix and bit-tests for 'mod' or 'ref' work with any
     93 /// of the possible values.
     94 enum ModRefInfo {
     95   /// The access neither references nor modifies the value stored in memory.
     96   MRI_NoModRef = 0,
     97   /// The access references the value stored in memory.
     98   MRI_Ref = 1,
     99   /// The access modifies the value stored in memory.
    100   MRI_Mod = 2,
    101   /// The access both references and modifies the value stored in memory.
    102   MRI_ModRef = MRI_Ref | MRI_Mod
    103 };
    104 
    105 /// The locations at which a function might access memory.
    106 ///
    107 /// These are primarily used in conjunction with the \c AccessKind bits to
    108 /// describe both the nature of access and the locations of access for a
    109 /// function call.
    110 enum FunctionModRefLocation {
    111   /// Base case is no access to memory.
    112   FMRL_Nowhere = 0,
    113   /// Access to memory via argument pointers.
    114   FMRL_ArgumentPointees = 4,
    115   /// Access to any memory.
    116   FMRL_Anywhere = 8 | FMRL_ArgumentPointees
    117 };
    118 
    119 /// Summary of how a function affects memory in the program.
    120 ///
    121 /// Loads from constant globals are not considered memory accesses for this
    122 /// interface. Also, functions may freely modify stack space local to their
    123 /// invocation without having to report it through these interfaces.
    124 enum FunctionModRefBehavior {
    125   /// This function does not perform any non-local loads or stores to memory.
    126   ///
    127   /// This property corresponds to the GCC 'const' attribute.
    128   /// This property corresponds to the LLVM IR 'readnone' attribute.
    129   /// This property corresponds to the IntrNoMem LLVM intrinsic flag.
    130   FMRB_DoesNotAccessMemory = FMRL_Nowhere | MRI_NoModRef,
    131 
    132   /// The only memory references in this function (if it has any) are
    133   /// non-volatile loads from objects pointed to by its pointer-typed
    134   /// arguments, with arbitrary offsets.
    135   ///
    136   /// This property corresponds to the IntrReadArgMem LLVM intrinsic flag.
    137   FMRB_OnlyReadsArgumentPointees = FMRL_ArgumentPointees | MRI_Ref,
    138 
    139   /// The only memory references in this function (if it has any) are
    140   /// non-volatile loads and stores from objects pointed to by its
    141   /// pointer-typed arguments, with arbitrary offsets.
    142   ///
    143   /// This property corresponds to the IntrArgMemOnly LLVM intrinsic flag.
    144   FMRB_OnlyAccessesArgumentPointees = FMRL_ArgumentPointees | MRI_ModRef,
    145 
    146   /// This function does not perform any non-local stores or volatile loads,
    147   /// but may read from any memory location.
    148   ///
    149   /// This property corresponds to the GCC 'pure' attribute.
    150   /// This property corresponds to the LLVM IR 'readonly' attribute.
    151   /// This property corresponds to the IntrReadMem LLVM intrinsic flag.
    152   FMRB_OnlyReadsMemory = FMRL_Anywhere | MRI_Ref,
    153 
    154   // This function does not read from memory anywhere, but may write to any
    155   // memory location.
    156   //
    157   // This property corresponds to the LLVM IR 'writeonly' attribute.
    158   // This property corresponds to the IntrWriteMem LLVM intrinsic flag.
    159   FMRB_DoesNotReadMemory = FMRL_Anywhere | MRI_Mod,
    160 
    161   /// This indicates that the function could not be classified into one of the
    162   /// behaviors above.
    163   FMRB_UnknownModRefBehavior = FMRL_Anywhere | MRI_ModRef
    164 };
    165 
    166 class AAResults {
    167 public:
    168   // Make these results default constructable and movable. We have to spell
    169   // these out because MSVC won't synthesize them.
    170   AAResults(const TargetLibraryInfo &TLI) : TLI(TLI) {}
    171   AAResults(AAResults &&Arg);
    172   ~AAResults();
    173 
    174   /// Register a specific AA result.
    175   template <typename AAResultT> void addAAResult(AAResultT &AAResult) {
    176     // FIXME: We should use a much lighter weight system than the usual
    177     // polymorphic pattern because we don't own AAResult. It should
    178     // ideally involve two pointers and no separate allocation.
    179     AAs.emplace_back(new Model<AAResultT>(AAResult, *this));
    180   }
    181 
    182   //===--------------------------------------------------------------------===//
    183   /// \name Alias Queries
    184   /// @{
    185 
    186   /// The main low level interface to the alias analysis implementation.
    187   /// Returns an AliasResult indicating whether the two pointers are aliased to
    188   /// each other. This is the interface that must be implemented by specific
    189   /// alias analysis implementations.
    190   AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB);
    191 
    192   /// A convenience wrapper around the primary \c alias interface.
    193   AliasResult alias(const Value *V1, uint64_t V1Size, const Value *V2,
    194                     uint64_t V2Size) {
    195     return alias(MemoryLocation(V1, V1Size), MemoryLocation(V2, V2Size));
    196   }
    197 
    198   /// A convenience wrapper around the primary \c alias interface.
    199   AliasResult alias(const Value *V1, const Value *V2) {
    200     return alias(V1, MemoryLocation::UnknownSize, V2,
    201                  MemoryLocation::UnknownSize);
    202   }
    203 
    204   /// A trivial helper function to check to see if the specified pointers are
    205   /// no-alias.
    206   bool isNoAlias(const MemoryLocation &LocA, const MemoryLocation &LocB) {
    207     return alias(LocA, LocB) == NoAlias;
    208   }
    209 
    210   /// A convenience wrapper around the \c isNoAlias helper interface.
    211   bool isNoAlias(const Value *V1, uint64_t V1Size, const Value *V2,
    212                  uint64_t V2Size) {
    213     return isNoAlias(MemoryLocation(V1, V1Size), MemoryLocation(V2, V2Size));
    214   }
    215 
    216   /// A convenience wrapper around the \c isNoAlias helper interface.
    217   bool isNoAlias(const Value *V1, const Value *V2) {
    218     return isNoAlias(MemoryLocation(V1), MemoryLocation(V2));
    219   }
    220 
    221   /// A trivial helper function to check to see if the specified pointers are
    222   /// must-alias.
    223   bool isMustAlias(const MemoryLocation &LocA, const MemoryLocation &LocB) {
    224     return alias(LocA, LocB) == MustAlias;
    225   }
    226 
    227   /// A convenience wrapper around the \c isMustAlias helper interface.
    228   bool isMustAlias(const Value *V1, const Value *V2) {
    229     return alias(V1, 1, V2, 1) == MustAlias;
    230   }
    231 
    232   /// Checks whether the given location points to constant memory, or if
    233   /// \p OrLocal is true whether it points to a local alloca.
    234   bool pointsToConstantMemory(const MemoryLocation &Loc, bool OrLocal = false);
    235 
    236   /// A convenience wrapper around the primary \c pointsToConstantMemory
    237   /// interface.
    238   bool pointsToConstantMemory(const Value *P, bool OrLocal = false) {
    239     return pointsToConstantMemory(MemoryLocation(P), OrLocal);
    240   }
    241 
    242   /// @}
    243   //===--------------------------------------------------------------------===//
    244   /// \name Simple mod/ref information
    245   /// @{
    246 
    247   /// Get the ModRef info associated with a pointer argument of a callsite. The
    248   /// result's bits are set to indicate the allowed aliasing ModRef kinds. Note
    249   /// that these bits do not necessarily account for the overall behavior of
    250   /// the function, but rather only provide additional per-argument
    251   /// information.
    252   ModRefInfo getArgModRefInfo(ImmutableCallSite CS, unsigned ArgIdx);
    253 
    254   /// Return the behavior of the given call site.
    255   FunctionModRefBehavior getModRefBehavior(ImmutableCallSite CS);
    256 
    257   /// Return the behavior when calling the given function.
    258   FunctionModRefBehavior getModRefBehavior(const Function *F);
    259 
    260   /// Checks if the specified call is known to never read or write memory.
    261   ///
    262   /// Note that if the call only reads from known-constant memory, it is also
    263   /// legal to return true. Also, calls that unwind the stack are legal for
    264   /// this predicate.
    265   ///
    266   /// Many optimizations (such as CSE and LICM) can be performed on such calls
    267   /// without worrying about aliasing properties, and many calls have this
    268   /// property (e.g. calls to 'sin' and 'cos').
    269   ///
    270   /// This property corresponds to the GCC 'const' attribute.
    271   bool doesNotAccessMemory(ImmutableCallSite CS) {
    272     return getModRefBehavior(CS) == FMRB_DoesNotAccessMemory;
    273   }
    274 
    275   /// Checks if the specified function is known to never read or write memory.
    276   ///
    277   /// Note that if the function only reads from known-constant memory, it is
    278   /// also legal to return true. Also, function that unwind the stack are legal
    279   /// for this predicate.
    280   ///
    281   /// Many optimizations (such as CSE and LICM) can be performed on such calls
    282   /// to such functions without worrying about aliasing properties, and many
    283   /// functions have this property (e.g. 'sin' and 'cos').
    284   ///
    285   /// This property corresponds to the GCC 'const' attribute.
    286   bool doesNotAccessMemory(const Function *F) {
    287     return getModRefBehavior(F) == FMRB_DoesNotAccessMemory;
    288   }
    289 
    290   /// Checks if the specified call is known to only read from non-volatile
    291   /// memory (or not access memory at all).
    292   ///
    293   /// Calls that unwind the stack are legal for this predicate.
    294   ///
    295   /// This property allows many common optimizations to be performed in the
    296   /// absence of interfering store instructions, such as CSE of strlen calls.
    297   ///
    298   /// This property corresponds to the GCC 'pure' attribute.
    299   bool onlyReadsMemory(ImmutableCallSite CS) {
    300     return onlyReadsMemory(getModRefBehavior(CS));
    301   }
    302 
    303   /// Checks if the specified function is known to only read from non-volatile
    304   /// memory (or not access memory at all).
    305   ///
    306   /// Functions that unwind the stack are legal for this predicate.
    307   ///
    308   /// This property allows many common optimizations to be performed in the
    309   /// absence of interfering store instructions, such as CSE of strlen calls.
    310   ///
    311   /// This property corresponds to the GCC 'pure' attribute.
    312   bool onlyReadsMemory(const Function *F) {
    313     return onlyReadsMemory(getModRefBehavior(F));
    314   }
    315 
    316   /// Checks if functions with the specified behavior are known to only read
    317   /// from non-volatile memory (or not access memory at all).
    318   static bool onlyReadsMemory(FunctionModRefBehavior MRB) {
    319     return !(MRB & MRI_Mod);
    320   }
    321 
    322   /// Checks if functions with the specified behavior are known to only write
    323   /// memory (or not access memory at all).
    324   static bool doesNotReadMemory(FunctionModRefBehavior MRB) {
    325     return !(MRB & MRI_Ref);
    326   }
    327 
    328   /// Checks if functions with the specified behavior are known to read and
    329   /// write at most from objects pointed to by their pointer-typed arguments
    330   /// (with arbitrary offsets).
    331   static bool onlyAccessesArgPointees(FunctionModRefBehavior MRB) {
    332     return !(MRB & FMRL_Anywhere & ~FMRL_ArgumentPointees);
    333   }
    334 
    335   /// Checks if functions with the specified behavior are known to potentially
    336   /// read or write from objects pointed to be their pointer-typed arguments
    337   /// (with arbitrary offsets).
    338   static bool doesAccessArgPointees(FunctionModRefBehavior MRB) {
    339     return (MRB & MRI_ModRef) && (MRB & FMRL_ArgumentPointees);
    340   }
    341 
    342   /// getModRefInfo (for call sites) - Return information about whether
    343   /// a particular call site modifies or reads the specified memory location.
    344   ModRefInfo getModRefInfo(ImmutableCallSite CS, const MemoryLocation &Loc);
    345 
    346   /// getModRefInfo (for call sites) - A convenience wrapper.
    347   ModRefInfo getModRefInfo(ImmutableCallSite CS, const Value *P,
    348                            uint64_t Size) {
    349     return getModRefInfo(CS, MemoryLocation(P, Size));
    350   }
    351 
    352   /// getModRefInfo (for calls) - Return information about whether
    353   /// a particular call modifies or reads the specified memory location.
    354   ModRefInfo getModRefInfo(const CallInst *C, const MemoryLocation &Loc) {
    355     return getModRefInfo(ImmutableCallSite(C), Loc);
    356   }
    357 
    358   /// getModRefInfo (for calls) - A convenience wrapper.
    359   ModRefInfo getModRefInfo(const CallInst *C, const Value *P, uint64_t Size) {
    360     return getModRefInfo(C, MemoryLocation(P, Size));
    361   }
    362 
    363   /// getModRefInfo (for invokes) - Return information about whether
    364   /// a particular invoke modifies or reads the specified memory location.
    365   ModRefInfo getModRefInfo(const InvokeInst *I, const MemoryLocation &Loc) {
    366     return getModRefInfo(ImmutableCallSite(I), Loc);
    367   }
    368 
    369   /// getModRefInfo (for invokes) - A convenience wrapper.
    370   ModRefInfo getModRefInfo(const InvokeInst *I, const Value *P, uint64_t Size) {
    371     return getModRefInfo(I, MemoryLocation(P, Size));
    372   }
    373 
    374   /// getModRefInfo (for loads) - Return information about whether
    375   /// a particular load modifies or reads the specified memory location.
    376   ModRefInfo getModRefInfo(const LoadInst *L, const MemoryLocation &Loc);
    377 
    378   /// getModRefInfo (for loads) - A convenience wrapper.
    379   ModRefInfo getModRefInfo(const LoadInst *L, const Value *P, uint64_t Size) {
    380     return getModRefInfo(L, MemoryLocation(P, Size));
    381   }
    382 
    383   /// getModRefInfo (for stores) - Return information about whether
    384   /// a particular store modifies or reads the specified memory location.
    385   ModRefInfo getModRefInfo(const StoreInst *S, const MemoryLocation &Loc);
    386 
    387   /// getModRefInfo (for stores) - A convenience wrapper.
    388   ModRefInfo getModRefInfo(const StoreInst *S, const Value *P, uint64_t Size) {
    389     return getModRefInfo(S, MemoryLocation(P, Size));
    390   }
    391 
    392   /// getModRefInfo (for fences) - Return information about whether
    393   /// a particular store modifies or reads the specified memory location.
    394   ModRefInfo getModRefInfo(const FenceInst *S, const MemoryLocation &Loc) {
    395     // Conservatively correct.  (We could possibly be a bit smarter if
    396     // Loc is a alloca that doesn't escape.)
    397     return MRI_ModRef;
    398   }
    399 
    400   /// getModRefInfo (for fences) - A convenience wrapper.
    401   ModRefInfo getModRefInfo(const FenceInst *S, const Value *P, uint64_t Size) {
    402     return getModRefInfo(S, MemoryLocation(P, Size));
    403   }
    404 
    405   /// getModRefInfo (for cmpxchges) - Return information about whether
    406   /// a particular cmpxchg modifies or reads the specified memory location.
    407   ModRefInfo getModRefInfo(const AtomicCmpXchgInst *CX,
    408                            const MemoryLocation &Loc);
    409 
    410   /// getModRefInfo (for cmpxchges) - A convenience wrapper.
    411   ModRefInfo getModRefInfo(const AtomicCmpXchgInst *CX, const Value *P,
    412                            unsigned Size) {
    413     return getModRefInfo(CX, MemoryLocation(P, Size));
    414   }
    415 
    416   /// getModRefInfo (for atomicrmws) - Return information about whether
    417   /// a particular atomicrmw modifies or reads the specified memory location.
    418   ModRefInfo getModRefInfo(const AtomicRMWInst *RMW, const MemoryLocation &Loc);
    419 
    420   /// getModRefInfo (for atomicrmws) - A convenience wrapper.
    421   ModRefInfo getModRefInfo(const AtomicRMWInst *RMW, const Value *P,
    422                            unsigned Size) {
    423     return getModRefInfo(RMW, MemoryLocation(P, Size));
    424   }
    425 
    426   /// getModRefInfo (for va_args) - Return information about whether
    427   /// a particular va_arg modifies or reads the specified memory location.
    428   ModRefInfo getModRefInfo(const VAArgInst *I, const MemoryLocation &Loc);
    429 
    430   /// getModRefInfo (for va_args) - A convenience wrapper.
    431   ModRefInfo getModRefInfo(const VAArgInst *I, const Value *P, uint64_t Size) {
    432     return getModRefInfo(I, MemoryLocation(P, Size));
    433   }
    434 
    435   /// getModRefInfo (for catchpads) - Return information about whether
    436   /// a particular catchpad modifies or reads the specified memory location.
    437   ModRefInfo getModRefInfo(const CatchPadInst *I, const MemoryLocation &Loc);
    438 
    439   /// getModRefInfo (for catchpads) - A convenience wrapper.
    440   ModRefInfo getModRefInfo(const CatchPadInst *I, const Value *P,
    441                            uint64_t Size) {
    442     return getModRefInfo(I, MemoryLocation(P, Size));
    443   }
    444 
    445   /// getModRefInfo (for catchrets) - Return information about whether
    446   /// a particular catchret modifies or reads the specified memory location.
    447   ModRefInfo getModRefInfo(const CatchReturnInst *I, const MemoryLocation &Loc);
    448 
    449   /// getModRefInfo (for catchrets) - A convenience wrapper.
    450   ModRefInfo getModRefInfo(const CatchReturnInst *I, const Value *P,
    451                            uint64_t Size) {
    452     return getModRefInfo(I, MemoryLocation(P, Size));
    453   }
    454 
    455   /// Check whether or not an instruction may read or write memory (without
    456   /// regard to a specific location).
    457   ///
    458   /// For function calls, this delegates to the alias-analysis specific
    459   /// call-site mod-ref behavior queries. Otherwise it delegates to the generic
    460   /// mod ref information query without a location.
    461   ModRefInfo getModRefInfo(const Instruction *I) {
    462     if (auto CS = ImmutableCallSite(I)) {
    463       auto MRB = getModRefBehavior(CS);
    464       if ((MRB & MRI_ModRef) == MRI_ModRef)
    465         return MRI_ModRef;
    466       if (MRB & MRI_Ref)
    467         return MRI_Ref;
    468       if (MRB & MRI_Mod)
    469         return MRI_Mod;
    470       return MRI_NoModRef;
    471     }
    472 
    473     return getModRefInfo(I, MemoryLocation());
    474   }
    475 
    476   /// Check whether or not an instruction may read or write the specified
    477   /// memory location.
    478   ///
    479   /// An instruction that doesn't read or write memory may be trivially LICM'd
    480   /// for example.
    481   ///
    482   /// This primarily delegates to specific helpers above.
    483   ModRefInfo getModRefInfo(const Instruction *I, const MemoryLocation &Loc) {
    484     switch (I->getOpcode()) {
    485     case Instruction::VAArg:  return getModRefInfo((const VAArgInst*)I, Loc);
    486     case Instruction::Load:   return getModRefInfo((const LoadInst*)I,  Loc);
    487     case Instruction::Store:  return getModRefInfo((const StoreInst*)I, Loc);
    488     case Instruction::Fence:  return getModRefInfo((const FenceInst*)I, Loc);
    489     case Instruction::AtomicCmpXchg:
    490       return getModRefInfo((const AtomicCmpXchgInst*)I, Loc);
    491     case Instruction::AtomicRMW:
    492       return getModRefInfo((const AtomicRMWInst*)I, Loc);
    493     case Instruction::Call:   return getModRefInfo((const CallInst*)I,  Loc);
    494     case Instruction::Invoke: return getModRefInfo((const InvokeInst*)I,Loc);
    495     case Instruction::CatchPad:
    496       return getModRefInfo((const CatchPadInst *)I, Loc);
    497     case Instruction::CatchRet:
    498       return getModRefInfo((const CatchReturnInst *)I, Loc);
    499     default:
    500       return MRI_NoModRef;
    501     }
    502   }
    503 
    504   /// A convenience wrapper for constructing the memory location.
    505   ModRefInfo getModRefInfo(const Instruction *I, const Value *P,
    506                            uint64_t Size) {
    507     return getModRefInfo(I, MemoryLocation(P, Size));
    508   }
    509 
    510   /// Return information about whether a call and an instruction may refer to
    511   /// the same memory locations.
    512   ModRefInfo getModRefInfo(Instruction *I, ImmutableCallSite Call);
    513 
    514   /// Return information about whether two call sites may refer to the same set
    515   /// of memory locations. See the AA documentation for details:
    516   ///   http://llvm.org/docs/AliasAnalysis.html#ModRefInfo
    517   ModRefInfo getModRefInfo(ImmutableCallSite CS1, ImmutableCallSite CS2);
    518 
    519   /// \brief Return information about whether a particular call site modifies
    520   /// or reads the specified memory location \p MemLoc before instruction \p I
    521   /// in a BasicBlock. A ordered basic block \p OBB can be used to speed up
    522   /// instruction ordering queries inside the BasicBlock containing \p I.
    523   ModRefInfo callCapturesBefore(const Instruction *I,
    524                                 const MemoryLocation &MemLoc, DominatorTree *DT,
    525                                 OrderedBasicBlock *OBB = nullptr);
    526 
    527   /// \brief A convenience wrapper to synthesize a memory location.
    528   ModRefInfo callCapturesBefore(const Instruction *I, const Value *P,
    529                                 uint64_t Size, DominatorTree *DT,
    530                                 OrderedBasicBlock *OBB = nullptr) {
    531     return callCapturesBefore(I, MemoryLocation(P, Size), DT, OBB);
    532   }
    533 
    534   /// @}
    535   //===--------------------------------------------------------------------===//
    536   /// \name Higher level methods for querying mod/ref information.
    537   /// @{
    538 
    539   /// Check if it is possible for execution of the specified basic block to
    540   /// modify the location Loc.
    541   bool canBasicBlockModify(const BasicBlock &BB, const MemoryLocation &Loc);
    542 
    543   /// A convenience wrapper synthesizing a memory location.
    544   bool canBasicBlockModify(const BasicBlock &BB, const Value *P,
    545                            uint64_t Size) {
    546     return canBasicBlockModify(BB, MemoryLocation(P, Size));
    547   }
    548 
    549   /// Check if it is possible for the execution of the specified instructions
    550   /// to mod\ref (according to the mode) the location Loc.
    551   ///
    552   /// The instructions to consider are all of the instructions in the range of
    553   /// [I1,I2] INCLUSIVE. I1 and I2 must be in the same basic block.
    554   bool canInstructionRangeModRef(const Instruction &I1, const Instruction &I2,
    555                                  const MemoryLocation &Loc,
    556                                  const ModRefInfo Mode);
    557 
    558   /// A convenience wrapper synthesizing a memory location.
    559   bool canInstructionRangeModRef(const Instruction &I1, const Instruction &I2,
    560                                  const Value *Ptr, uint64_t Size,
    561                                  const ModRefInfo Mode) {
    562     return canInstructionRangeModRef(I1, I2, MemoryLocation(Ptr, Size), Mode);
    563   }
    564 
    565 private:
    566   class Concept;
    567   template <typename T> class Model;
    568 
    569   template <typename T> friend class AAResultBase;
    570 
    571   const TargetLibraryInfo &TLI;
    572 
    573   std::vector<std::unique_ptr<Concept>> AAs;
    574 };
    575 
    576 /// Temporary typedef for legacy code that uses a generic \c AliasAnalysis
    577 /// pointer or reference.
    578 typedef AAResults AliasAnalysis;
    579 
    580 /// A private abstract base class describing the concept of an individual alias
    581 /// analysis implementation.
    582 ///
    583 /// This interface is implemented by any \c Model instantiation. It is also the
    584 /// interface which a type used to instantiate the model must provide.
    585 ///
    586 /// All of these methods model methods by the same name in the \c
    587 /// AAResults class. Only differences and specifics to how the
    588 /// implementations are called are documented here.
    589 class AAResults::Concept {
    590 public:
    591   virtual ~Concept() = 0;
    592 
    593   /// An update API used internally by the AAResults to provide
    594   /// a handle back to the top level aggregation.
    595   virtual void setAAResults(AAResults *NewAAR) = 0;
    596 
    597   //===--------------------------------------------------------------------===//
    598   /// \name Alias Queries
    599   /// @{
    600 
    601   /// The main low level interface to the alias analysis implementation.
    602   /// Returns an AliasResult indicating whether the two pointers are aliased to
    603   /// each other. This is the interface that must be implemented by specific
    604   /// alias analysis implementations.
    605   virtual AliasResult alias(const MemoryLocation &LocA,
    606                             const MemoryLocation &LocB) = 0;
    607 
    608   /// Checks whether the given location points to constant memory, or if
    609   /// \p OrLocal is true whether it points to a local alloca.
    610   virtual bool pointsToConstantMemory(const MemoryLocation &Loc,
    611                                       bool OrLocal) = 0;
    612 
    613   /// @}
    614   //===--------------------------------------------------------------------===//
    615   /// \name Simple mod/ref information
    616   /// @{
    617 
    618   /// Get the ModRef info associated with a pointer argument of a callsite. The
    619   /// result's bits are set to indicate the allowed aliasing ModRef kinds. Note
    620   /// that these bits do not necessarily account for the overall behavior of
    621   /// the function, but rather only provide additional per-argument
    622   /// information.
    623   virtual ModRefInfo getArgModRefInfo(ImmutableCallSite CS,
    624                                       unsigned ArgIdx) = 0;
    625 
    626   /// Return the behavior of the given call site.
    627   virtual FunctionModRefBehavior getModRefBehavior(ImmutableCallSite CS) = 0;
    628 
    629   /// Return the behavior when calling the given function.
    630   virtual FunctionModRefBehavior getModRefBehavior(const Function *F) = 0;
    631 
    632   /// getModRefInfo (for call sites) - Return information about whether
    633   /// a particular call site modifies or reads the specified memory location.
    634   virtual ModRefInfo getModRefInfo(ImmutableCallSite CS,
    635                                    const MemoryLocation &Loc) = 0;
    636 
    637   /// Return information about whether two call sites may refer to the same set
    638   /// of memory locations. See the AA documentation for details:
    639   ///   http://llvm.org/docs/AliasAnalysis.html#ModRefInfo
    640   virtual ModRefInfo getModRefInfo(ImmutableCallSite CS1,
    641                                    ImmutableCallSite CS2) = 0;
    642 
    643   /// @}
    644 };
    645 
    646 /// A private class template which derives from \c Concept and wraps some other
    647 /// type.
    648 ///
    649 /// This models the concept by directly forwarding each interface point to the
    650 /// wrapped type which must implement a compatible interface. This provides
    651 /// a type erased binding.
    652 template <typename AAResultT> class AAResults::Model final : public Concept {
    653   AAResultT &Result;
    654 
    655 public:
    656   explicit Model(AAResultT &Result, AAResults &AAR) : Result(Result) {
    657     Result.setAAResults(&AAR);
    658   }
    659   ~Model() override {}
    660 
    661   void setAAResults(AAResults *NewAAR) override { Result.setAAResults(NewAAR); }
    662 
    663   AliasResult alias(const MemoryLocation &LocA,
    664                     const MemoryLocation &LocB) override {
    665     return Result.alias(LocA, LocB);
    666   }
    667 
    668   bool pointsToConstantMemory(const MemoryLocation &Loc,
    669                               bool OrLocal) override {
    670     return Result.pointsToConstantMemory(Loc, OrLocal);
    671   }
    672 
    673   ModRefInfo getArgModRefInfo(ImmutableCallSite CS, unsigned ArgIdx) override {
    674     return Result.getArgModRefInfo(CS, ArgIdx);
    675   }
    676 
    677   FunctionModRefBehavior getModRefBehavior(ImmutableCallSite CS) override {
    678     return Result.getModRefBehavior(CS);
    679   }
    680 
    681   FunctionModRefBehavior getModRefBehavior(const Function *F) override {
    682     return Result.getModRefBehavior(F);
    683   }
    684 
    685   ModRefInfo getModRefInfo(ImmutableCallSite CS,
    686                            const MemoryLocation &Loc) override {
    687     return Result.getModRefInfo(CS, Loc);
    688   }
    689 
    690   ModRefInfo getModRefInfo(ImmutableCallSite CS1,
    691                            ImmutableCallSite CS2) override {
    692     return Result.getModRefInfo(CS1, CS2);
    693   }
    694 };
    695 
    696 /// A CRTP-driven "mixin" base class to help implement the function alias
    697 /// analysis results concept.
    698 ///
    699 /// Because of the nature of many alias analysis implementations, they often
    700 /// only implement a subset of the interface. This base class will attempt to
    701 /// implement the remaining portions of the interface in terms of simpler forms
    702 /// of the interface where possible, and otherwise provide conservatively
    703 /// correct fallback implementations.
    704 ///
    705 /// Implementors of an alias analysis should derive from this CRTP, and then
    706 /// override specific methods that they wish to customize. There is no need to
    707 /// use virtual anywhere, the CRTP base class does static dispatch to the
    708 /// derived type passed into it.
    709 template <typename DerivedT> class AAResultBase {
    710   // Expose some parts of the interface only to the AAResults::Model
    711   // for wrapping. Specifically, this allows the model to call our
    712   // setAAResults method without exposing it as a fully public API.
    713   friend class AAResults::Model<DerivedT>;
    714 
    715   /// A pointer to the AAResults object that this AAResult is
    716   /// aggregated within. May be null if not aggregated.
    717   AAResults *AAR;
    718 
    719   /// Helper to dispatch calls back through the derived type.
    720   DerivedT &derived() { return static_cast<DerivedT &>(*this); }
    721 
    722   /// A setter for the AAResults pointer, which is used to satisfy the
    723   /// AAResults::Model contract.
    724   void setAAResults(AAResults *NewAAR) { AAR = NewAAR; }
    725 
    726 protected:
    727   /// This proxy class models a common pattern where we delegate to either the
    728   /// top-level \c AAResults aggregation if one is registered, or to the
    729   /// current result if none are registered.
    730   class AAResultsProxy {
    731     AAResults *AAR;
    732     DerivedT &CurrentResult;
    733 
    734   public:
    735     AAResultsProxy(AAResults *AAR, DerivedT &CurrentResult)
    736         : AAR(AAR), CurrentResult(CurrentResult) {}
    737 
    738     AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB) {
    739       return AAR ? AAR->alias(LocA, LocB) : CurrentResult.alias(LocA, LocB);
    740     }
    741 
    742     bool pointsToConstantMemory(const MemoryLocation &Loc, bool OrLocal) {
    743       return AAR ? AAR->pointsToConstantMemory(Loc, OrLocal)
    744                  : CurrentResult.pointsToConstantMemory(Loc, OrLocal);
    745     }
    746 
    747     ModRefInfo getArgModRefInfo(ImmutableCallSite CS, unsigned ArgIdx) {
    748       return AAR ? AAR->getArgModRefInfo(CS, ArgIdx) : CurrentResult.getArgModRefInfo(CS, ArgIdx);
    749     }
    750 
    751     FunctionModRefBehavior getModRefBehavior(ImmutableCallSite CS) {
    752       return AAR ? AAR->getModRefBehavior(CS) : CurrentResult.getModRefBehavior(CS);
    753     }
    754 
    755     FunctionModRefBehavior getModRefBehavior(const Function *F) {
    756       return AAR ? AAR->getModRefBehavior(F) : CurrentResult.getModRefBehavior(F);
    757     }
    758 
    759     ModRefInfo getModRefInfo(ImmutableCallSite CS, const MemoryLocation &Loc) {
    760       return AAR ? AAR->getModRefInfo(CS, Loc)
    761                  : CurrentResult.getModRefInfo(CS, Loc);
    762     }
    763 
    764     ModRefInfo getModRefInfo(ImmutableCallSite CS1, ImmutableCallSite CS2) {
    765       return AAR ? AAR->getModRefInfo(CS1, CS2) : CurrentResult.getModRefInfo(CS1, CS2);
    766     }
    767   };
    768 
    769   explicit AAResultBase() {}
    770 
    771   // Provide all the copy and move constructors so that derived types aren't
    772   // constrained.
    773   AAResultBase(const AAResultBase &Arg) {}
    774   AAResultBase(AAResultBase &&Arg) {}
    775 
    776   /// Get a proxy for the best AA result set to query at this time.
    777   ///
    778   /// When this result is part of a larger aggregation, this will proxy to that
    779   /// aggregation. When this result is used in isolation, it will just delegate
    780   /// back to the derived class's implementation.
    781   ///
    782   /// Note that callers of this need to take considerable care to not cause
    783   /// performance problems when they use this routine, in the case of a large
    784   /// number of alias analyses being aggregated, it can be expensive to walk
    785   /// back across the chain.
    786   AAResultsProxy getBestAAResults() { return AAResultsProxy(AAR, derived()); }
    787 
    788 public:
    789   AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB) {
    790     return MayAlias;
    791   }
    792 
    793   bool pointsToConstantMemory(const MemoryLocation &Loc, bool OrLocal) {
    794     return false;
    795   }
    796 
    797   ModRefInfo getArgModRefInfo(ImmutableCallSite CS, unsigned ArgIdx) {
    798     return MRI_ModRef;
    799   }
    800 
    801   FunctionModRefBehavior getModRefBehavior(ImmutableCallSite CS) {
    802     return FMRB_UnknownModRefBehavior;
    803   }
    804 
    805   FunctionModRefBehavior getModRefBehavior(const Function *F) {
    806     return FMRB_UnknownModRefBehavior;
    807   }
    808 
    809   ModRefInfo getModRefInfo(ImmutableCallSite CS, const MemoryLocation &Loc) {
    810     return MRI_ModRef;
    811   }
    812 
    813   ModRefInfo getModRefInfo(ImmutableCallSite CS1, ImmutableCallSite CS2) {
    814     return MRI_ModRef;
    815   }
    816 };
    817 
    818 
    819 /// Return true if this pointer is returned by a noalias function.
    820 bool isNoAliasCall(const Value *V);
    821 
    822 /// Return true if this is an argument with the noalias attribute.
    823 bool isNoAliasArgument(const Value *V);
    824 
    825 /// Return true if this pointer refers to a distinct and identifiable object.
    826 /// This returns true for:
    827 ///    Global Variables and Functions (but not Global Aliases)
    828 ///    Allocas
    829 ///    ByVal and NoAlias Arguments
    830 ///    NoAlias returns (e.g. calls to malloc)
    831 ///
    832 bool isIdentifiedObject(const Value *V);
    833 
    834 /// Return true if V is umabigously identified at the function-level.
    835 /// Different IdentifiedFunctionLocals can't alias.
    836 /// Further, an IdentifiedFunctionLocal can not alias with any function
    837 /// arguments other than itself, which is not necessarily true for
    838 /// IdentifiedObjects.
    839 bool isIdentifiedFunctionLocal(const Value *V);
    840 
    841 /// A manager for alias analyses.
    842 ///
    843 /// This class can have analyses registered with it and when run, it will run
    844 /// all of them and aggregate their results into single AA results interface
    845 /// that dispatches across all of the alias analysis results available.
    846 ///
    847 /// Note that the order in which analyses are registered is very significant.
    848 /// That is the order in which the results will be aggregated and queried.
    849 ///
    850 /// This manager effectively wraps the AnalysisManager for registering alias
    851 /// analyses. When you register your alias analysis with this manager, it will
    852 /// ensure the analysis itself is registered with its AnalysisManager.
    853 class AAManager : public AnalysisInfoMixin<AAManager> {
    854 public:
    855   typedef AAResults Result;
    856 
    857   // This type hase value semantics. We have to spell these out because MSVC
    858   // won't synthesize them.
    859   AAManager() {}
    860   AAManager(AAManager &&Arg) : ResultGetters(std::move(Arg.ResultGetters)) {}
    861   AAManager(const AAManager &Arg) : ResultGetters(Arg.ResultGetters) {}
    862   AAManager &operator=(AAManager &&RHS) {
    863     ResultGetters = std::move(RHS.ResultGetters);
    864     return *this;
    865   }
    866   AAManager &operator=(const AAManager &RHS) {
    867     ResultGetters = RHS.ResultGetters;
    868     return *this;
    869   }
    870 
    871   /// Register a specific AA result.
    872   template <typename AnalysisT> void registerFunctionAnalysis() {
    873     ResultGetters.push_back(&getFunctionAAResultImpl<AnalysisT>);
    874   }
    875 
    876   /// Register a specific AA result.
    877   template <typename AnalysisT> void registerModuleAnalysis() {
    878     ResultGetters.push_back(&getModuleAAResultImpl<AnalysisT>);
    879   }
    880 
    881   Result run(Function &F, AnalysisManager<Function> &AM) {
    882     Result R(AM.getResult<TargetLibraryAnalysis>(F));
    883     for (auto &Getter : ResultGetters)
    884       (*Getter)(F, AM, R);
    885     return R;
    886   }
    887 
    888 private:
    889   friend AnalysisInfoMixin<AAManager>;
    890   static char PassID;
    891 
    892   SmallVector<void (*)(Function &F, AnalysisManager<Function> &AM,
    893                        AAResults &AAResults),
    894               4> ResultGetters;
    895 
    896   template <typename AnalysisT>
    897   static void getFunctionAAResultImpl(Function &F,
    898                                       AnalysisManager<Function> &AM,
    899                                       AAResults &AAResults) {
    900     AAResults.addAAResult(AM.template getResult<AnalysisT>(F));
    901   }
    902 
    903   template <typename AnalysisT>
    904   static void getModuleAAResultImpl(Function &F, AnalysisManager<Function> &AM,
    905                                     AAResults &AAResults) {
    906     auto &MAM =
    907         AM.getResult<ModuleAnalysisManagerFunctionProxy>(F).getManager();
    908     if (auto *R = MAM.template getCachedResult<AnalysisT>(*F.getParent()))
    909       AAResults.addAAResult(*R);
    910   }
    911 };
    912 
    913 /// A wrapper pass to provide the legacy pass manager access to a suitably
    914 /// prepared AAResults object.
    915 class AAResultsWrapperPass : public FunctionPass {
    916   std::unique_ptr<AAResults> AAR;
    917 
    918 public:
    919   static char ID;
    920 
    921   AAResultsWrapperPass();
    922 
    923   AAResults &getAAResults() { return *AAR; }
    924   const AAResults &getAAResults() const { return *AAR; }
    925 
    926   bool runOnFunction(Function &F) override;
    927 
    928   void getAnalysisUsage(AnalysisUsage &AU) const override;
    929 };
    930 
    931 FunctionPass *createAAResultsWrapperPass();
    932 
    933 /// A wrapper pass around a callback which can be used to populate the
    934 /// AAResults in the AAResultsWrapperPass from an external AA.
    935 ///
    936 /// The callback provided here will be used each time we prepare an AAResults
    937 /// object, and will receive a reference to the function wrapper pass, the
    938 /// function, and the AAResults object to populate. This should be used when
    939 /// setting up a custom pass pipeline to inject a hook into the AA results.
    940 ImmutablePass *createExternalAAWrapperPass(
    941     std::function<void(Pass &, Function &, AAResults &)> Callback);
    942 
    943 /// A helper for the legacy pass manager to create a \c AAResults
    944 /// object populated to the best of our ability for a particular function when
    945 /// inside of a \c ModulePass or a \c CallGraphSCCPass.
    946 ///
    947 /// If a \c ModulePass or a \c CallGraphSCCPass calls \p
    948 /// createLegacyPMAAResults, it also needs to call \p addUsedAAAnalyses in \p
    949 /// getAnalysisUsage.
    950 AAResults createLegacyPMAAResults(Pass &P, Function &F, BasicAAResult &BAR);
    951 
    952 /// A helper for the legacy pass manager to populate \p AU to add uses to make
    953 /// sure the analyses required by \p createLegacyPMAAResults are available.
    954 void getAAResultsAnalysisUsage(AnalysisUsage &AU);
    955 
    956 } // End llvm namespace
    957 
    958 #endif
    959