Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-05-10 08:43:11

0001 //===- llvm/Analysis/AliasAnalysis.h - Alias Analysis Interface -*- C++ -*-===//
0002 //
0003 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
0004 // See https://llvm.org/LICENSE.txt for license information.
0005 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
0006 //
0007 //===----------------------------------------------------------------------===//
0008 //
0009 // This file defines the generic AliasAnalysis interface, which is used as the
0010 // common interface used by all clients of alias analysis information, and
0011 // implemented by all alias analysis implementations.  Mod/Ref information is
0012 // also captured by this interface.
0013 //
0014 // Implementations of this interface must implement the various virtual methods,
0015 // which automatically provides functionality for the entire suite of client
0016 // APIs.
0017 //
0018 // This API identifies memory regions with the MemoryLocation class. The pointer
0019 // component specifies the base memory address of the region. The Size specifies
0020 // the maximum size (in address units) of the memory region, or
0021 // MemoryLocation::UnknownSize if the size is not known. The TBAA tag
0022 // identifies the "type" of the memory reference; see the
0023 // TypeBasedAliasAnalysis class for details.
0024 //
0025 // Some non-obvious details include:
0026 //  - Pointers that point to two completely different objects in memory never
0027 //    alias, regardless of the value of the Size component.
0028 //  - NoAlias doesn't imply inequal pointers. The most obvious example of this
0029 //    is two pointers to constant memory. Even if they are equal, constant
0030 //    memory is never stored to, so there will never be any dependencies.
0031 //    In this and other situations, the pointers may be both NoAlias and
0032 //    MustAlias at the same time. The current API can only return one result,
0033 //    though this is rarely a problem in practice.
0034 //
0035 //===----------------------------------------------------------------------===//
0036 
0037 #ifndef LLVM_ANALYSIS_ALIASANALYSIS_H
0038 #define LLVM_ANALYSIS_ALIASANALYSIS_H
0039 
0040 #include "llvm/ADT/DenseMap.h"
0041 #include "llvm/ADT/SmallVector.h"
0042 #include "llvm/Analysis/MemoryLocation.h"
0043 #include "llvm/IR/Function.h"
0044 #include "llvm/IR/PassManager.h"
0045 #include "llvm/Pass.h"
0046 #include "llvm/Support/ModRef.h"
0047 #include <cstdint>
0048 #include <functional>
0049 #include <memory>
0050 #include <optional>
0051 #include <vector>
0052 
0053 namespace llvm {
0054 
0055 class AtomicCmpXchgInst;
0056 class BasicBlock;
0057 class CatchPadInst;
0058 class CatchReturnInst;
0059 class DominatorTree;
0060 class FenceInst;
0061 class LoopInfo;
0062 class TargetLibraryInfo;
0063 
0064 /// The possible results of an alias query.
0065 ///
0066 /// These results are always computed between two MemoryLocation objects as
0067 /// a query to some alias analysis.
0068 ///
0069 /// Note that these are unscoped enumerations because we would like to support
0070 /// implicitly testing a result for the existence of any possible aliasing with
0071 /// a conversion to bool, but an "enum class" doesn't support this. The
0072 /// canonical names from the literature are suffixed and unique anyways, and so
0073 /// they serve as global constants in LLVM for these results.
0074 ///
0075 /// See docs/AliasAnalysis.html for more information on the specific meanings
0076 /// of these values.
0077 class AliasResult {
0078 private:
0079   static const int OffsetBits = 23;
0080   static const int AliasBits = 8;
0081   static_assert(AliasBits + 1 + OffsetBits <= 32,
0082                 "AliasResult size is intended to be 4 bytes!");
0083 
0084   unsigned int Alias : AliasBits;
0085   unsigned int HasOffset : 1;
0086   signed int Offset : OffsetBits;
0087 
0088 public:
0089   enum Kind : uint8_t {
0090     /// The two locations do not alias at all.
0091     ///
0092     /// This value is arranged to convert to false, while all other values
0093     /// convert to true. This allows a boolean context to convert the result to
0094     /// a binary flag indicating whether there is the possibility of aliasing.
0095     NoAlias = 0,
0096     /// The two locations may or may not alias. This is the least precise
0097     /// result.
0098     MayAlias,
0099     /// The two locations alias, but only due to a partial overlap.
0100     PartialAlias,
0101     /// The two locations precisely alias each other.
0102     MustAlias,
0103   };
0104   static_assert(MustAlias < (1 << AliasBits),
0105                 "Not enough bit field size for the enum!");
0106 
0107   explicit AliasResult() = delete;
0108   constexpr AliasResult(const Kind &Alias)
0109       : Alias(Alias), HasOffset(false), Offset(0) {}
0110 
0111   operator Kind() const { return static_cast<Kind>(Alias); }
0112 
0113   bool operator==(const AliasResult &Other) const {
0114     return Alias == Other.Alias && HasOffset == Other.HasOffset &&
0115            Offset == Other.Offset;
0116   }
0117   bool operator!=(const AliasResult &Other) const { return !(*this == Other); }
0118 
0119   bool operator==(Kind K) const { return Alias == K; }
0120   bool operator!=(Kind K) const { return !(*this == K); }
0121 
0122   constexpr bool hasOffset() const { return HasOffset; }
0123   constexpr int32_t getOffset() const {
0124     assert(HasOffset && "No offset!");
0125     return Offset;
0126   }
0127   void setOffset(int32_t NewOffset) {
0128     if (isInt<OffsetBits>(NewOffset)) {
0129       HasOffset = true;
0130       Offset = NewOffset;
0131     }
0132   }
0133 
0134   /// Helper for processing AliasResult for swapped memory location pairs.
0135   void swap(bool DoSwap = true) {
0136     if (DoSwap && hasOffset())
0137       setOffset(-getOffset());
0138   }
0139 };
0140 
0141 static_assert(sizeof(AliasResult) == 4,
0142               "AliasResult size is intended to be 4 bytes!");
0143 
0144 /// << operator for AliasResult.
0145 raw_ostream &operator<<(raw_ostream &OS, AliasResult AR);
0146 
0147 /// Virtual base class for providers of capture analysis.
0148 struct CaptureAnalysis {
0149   virtual ~CaptureAnalysis() = 0;
0150 
0151   /// Check whether Object is not captured before instruction I. If OrAt is
0152   /// true, captures by instruction I itself are also considered.
0153   ///
0154   /// If I is nullptr, then captures at any point will be considered.
0155   virtual bool isNotCapturedBefore(const Value *Object, const Instruction *I,
0156                                    bool OrAt) = 0;
0157 };
0158 
0159 /// Context-free CaptureAnalysis provider, which computes and caches whether an
0160 /// object is captured in the function at all, but does not distinguish whether
0161 /// it was captured before or after the context instruction.
0162 class SimpleCaptureAnalysis final : public CaptureAnalysis {
0163   SmallDenseMap<const Value *, bool, 8> IsCapturedCache;
0164 
0165 public:
0166   bool isNotCapturedBefore(const Value *Object, const Instruction *I,
0167                            bool OrAt) override;
0168 };
0169 
0170 /// Context-sensitive CaptureAnalysis provider, which computes and caches the
0171 /// earliest common dominator closure of all captures. It provides a good
0172 /// approximation to a precise "captures before" analysis.
0173 class EarliestEscapeAnalysis final : public CaptureAnalysis {
0174   DominatorTree &DT;
0175   const LoopInfo *LI;
0176 
0177   /// Map from identified local object to an instruction before which it does
0178   /// not escape, or nullptr if it never escapes. The "earliest" instruction
0179   /// may be a conservative approximation, e.g. the first instruction in the
0180   /// function is always a legal choice.
0181   DenseMap<const Value *, Instruction *> EarliestEscapes;
0182 
0183   /// Reverse map from instruction to the objects it is the earliest escape for.
0184   /// This is used for cache invalidation purposes.
0185   DenseMap<Instruction *, TinyPtrVector<const Value *>> Inst2Obj;
0186 
0187 public:
0188   EarliestEscapeAnalysis(DominatorTree &DT, const LoopInfo *LI = nullptr)
0189       : DT(DT), LI(LI) {}
0190 
0191   bool isNotCapturedBefore(const Value *Object, const Instruction *I,
0192                            bool OrAt) override;
0193 
0194   void removeInstruction(Instruction *I);
0195 };
0196 
0197 /// Cache key for BasicAA results. It only includes the pointer and size from
0198 /// MemoryLocation, as BasicAA is AATags independent. Additionally, it includes
0199 /// the value of MayBeCrossIteration, which may affect BasicAA results.
0200 struct AACacheLoc {
0201   using PtrTy = PointerIntPair<const Value *, 1, bool>;
0202   PtrTy Ptr;
0203   LocationSize Size;
0204 
0205   AACacheLoc(PtrTy Ptr, LocationSize Size) : Ptr(Ptr), Size(Size) {}
0206   AACacheLoc(const Value *Ptr, LocationSize Size, bool MayBeCrossIteration)
0207       : Ptr(Ptr, MayBeCrossIteration), Size(Size) {}
0208 };
0209 
0210 template <> struct DenseMapInfo<AACacheLoc> {
0211   static inline AACacheLoc getEmptyKey() {
0212     return {DenseMapInfo<AACacheLoc::PtrTy>::getEmptyKey(),
0213             DenseMapInfo<LocationSize>::getEmptyKey()};
0214   }
0215   static inline AACacheLoc getTombstoneKey() {
0216     return {DenseMapInfo<AACacheLoc::PtrTy>::getTombstoneKey(),
0217             DenseMapInfo<LocationSize>::getTombstoneKey()};
0218   }
0219   static unsigned getHashValue(const AACacheLoc &Val) {
0220     return DenseMapInfo<AACacheLoc::PtrTy>::getHashValue(Val.Ptr) ^
0221            DenseMapInfo<LocationSize>::getHashValue(Val.Size);
0222   }
0223   static bool isEqual(const AACacheLoc &LHS, const AACacheLoc &RHS) {
0224     return LHS.Ptr == RHS.Ptr && LHS.Size == RHS.Size;
0225   }
0226 };
0227 
0228 class AAResults;
0229 
0230 /// This class stores info we want to provide to or retain within an alias
0231 /// query. By default, the root query is stateless and starts with a freshly
0232 /// constructed info object. Specific alias analyses can use this query info to
0233 /// store per-query state that is important for recursive or nested queries to
0234 /// avoid recomputing. To enable preserving this state across multiple queries
0235 /// where safe (due to the IR not changing), use a `BatchAAResults` wrapper.
0236 /// The information stored in an `AAQueryInfo` is currently limitted to the
0237 /// caches used by BasicAA, but can further be extended to fit other AA needs.
0238 class AAQueryInfo {
0239 public:
0240   using LocPair = std::pair<AACacheLoc, AACacheLoc>;
0241   struct CacheEntry {
0242     /// Cache entry is neither an assumption nor does it use a (non-definitive)
0243     /// assumption.
0244     static constexpr int Definitive = -2;
0245     /// Cache entry is not an assumption itself, but may be using an assumption
0246     /// from higher up the stack.
0247     static constexpr int AssumptionBased = -1;
0248 
0249     AliasResult Result;
0250     /// Number of times a NoAlias assumption has been used, 0 for assumptions
0251     /// that have not been used. Can also take one of the Definitive or
0252     /// AssumptionBased values documented above.
0253     int NumAssumptionUses;
0254 
0255     /// Whether this is a definitive (non-assumption) result.
0256     bool isDefinitive() const { return NumAssumptionUses == Definitive; }
0257     /// Whether this is an assumption that has not been proven yet.
0258     bool isAssumption() const { return NumAssumptionUses >= 0; }
0259   };
0260 
0261   // Alias analysis result aggregration using which this query is performed.
0262   // Can be used to perform recursive queries.
0263   AAResults &AAR;
0264 
0265   using AliasCacheT = SmallDenseMap<LocPair, CacheEntry, 8>;
0266   AliasCacheT AliasCache;
0267 
0268   CaptureAnalysis *CA;
0269 
0270   /// Query depth used to distinguish recursive queries.
0271   unsigned Depth = 0;
0272 
0273   /// How many active NoAlias assumption uses there are.
0274   int NumAssumptionUses = 0;
0275 
0276   /// Location pairs for which an assumption based result is currently stored.
0277   /// Used to remove all potentially incorrect results from the cache if an
0278   /// assumption is disproven.
0279   SmallVector<AAQueryInfo::LocPair, 4> AssumptionBasedResults;
0280 
0281   /// Tracks whether the accesses may be on different cycle iterations.
0282   ///
0283   /// When interpret "Value" pointer equality as value equality we need to make
0284   /// sure that the "Value" is not part of a cycle. Otherwise, two uses could
0285   /// come from different "iterations" of a cycle and see different values for
0286   /// the same "Value" pointer.
0287   ///
0288   /// The following example shows the problem:
0289   ///   %p = phi(%alloca1, %addr2)
0290   ///   %l = load %ptr
0291   ///   %addr1 = gep, %alloca2, 0, %l
0292   ///   %addr2 = gep  %alloca2, 0, (%l + 1)
0293   ///      alias(%p, %addr1) -> MayAlias !
0294   ///   store %l, ...
0295   bool MayBeCrossIteration = false;
0296 
0297   /// Whether alias analysis is allowed to use the dominator tree, for use by
0298   /// passes that lazily update the DT while performing AA queries.
0299   bool UseDominatorTree = true;
0300 
0301   AAQueryInfo(AAResults &AAR, CaptureAnalysis *CA) : AAR(AAR), CA(CA) {}
0302 };
0303 
0304 /// AAQueryInfo that uses SimpleCaptureAnalysis.
0305 class SimpleAAQueryInfo : public AAQueryInfo {
0306   SimpleCaptureAnalysis CA;
0307 
0308 public:
0309   SimpleAAQueryInfo(AAResults &AAR) : AAQueryInfo(AAR, &CA) {}
0310 };
0311 
0312 class BatchAAResults;
0313 
0314 class AAResults {
0315 public:
0316   // Make these results default constructable and movable. We have to spell
0317   // these out because MSVC won't synthesize them.
0318   AAResults(const TargetLibraryInfo &TLI);
0319   AAResults(AAResults &&Arg);
0320   ~AAResults();
0321 
0322   /// Register a specific AA result.
0323   template <typename AAResultT> void addAAResult(AAResultT &AAResult) {
0324     // FIXME: We should use a much lighter weight system than the usual
0325     // polymorphic pattern because we don't own AAResult. It should
0326     // ideally involve two pointers and no separate allocation.
0327     AAs.emplace_back(new Model<AAResultT>(AAResult, *this));
0328   }
0329 
0330   /// Register a function analysis ID that the results aggregation depends on.
0331   ///
0332   /// This is used in the new pass manager to implement the invalidation logic
0333   /// where we must invalidate the results aggregation if any of our component
0334   /// analyses become invalid.
0335   void addAADependencyID(AnalysisKey *ID) { AADeps.push_back(ID); }
0336 
0337   /// Handle invalidation events in the new pass manager.
0338   ///
0339   /// The aggregation is invalidated if any of the underlying analyses is
0340   /// invalidated.
0341   bool invalidate(Function &F, const PreservedAnalyses &PA,
0342                   FunctionAnalysisManager::Invalidator &Inv);
0343 
0344   //===--------------------------------------------------------------------===//
0345   /// \name Alias Queries
0346   /// @{
0347 
0348   /// The main low level interface to the alias analysis implementation.
0349   /// Returns an AliasResult indicating whether the two pointers are aliased to
0350   /// each other. This is the interface that must be implemented by specific
0351   /// alias analysis implementations.
0352   AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB);
0353 
0354   /// A convenience wrapper around the primary \c alias interface.
0355   AliasResult alias(const Value *V1, LocationSize V1Size, const Value *V2,
0356                     LocationSize V2Size) {
0357     return alias(MemoryLocation(V1, V1Size), MemoryLocation(V2, V2Size));
0358   }
0359 
0360   /// A convenience wrapper around the primary \c alias interface.
0361   AliasResult alias(const Value *V1, const Value *V2) {
0362     return alias(MemoryLocation::getBeforeOrAfter(V1),
0363                  MemoryLocation::getBeforeOrAfter(V2));
0364   }
0365 
0366   /// A trivial helper function to check to see if the specified pointers are
0367   /// no-alias.
0368   bool isNoAlias(const MemoryLocation &LocA, const MemoryLocation &LocB) {
0369     return alias(LocA, LocB) == AliasResult::NoAlias;
0370   }
0371 
0372   /// A convenience wrapper around the \c isNoAlias helper interface.
0373   bool isNoAlias(const Value *V1, LocationSize V1Size, const Value *V2,
0374                  LocationSize V2Size) {
0375     return isNoAlias(MemoryLocation(V1, V1Size), MemoryLocation(V2, V2Size));
0376   }
0377 
0378   /// A convenience wrapper around the \c isNoAlias helper interface.
0379   bool isNoAlias(const Value *V1, const Value *V2) {
0380     return isNoAlias(MemoryLocation::getBeforeOrAfter(V1),
0381                      MemoryLocation::getBeforeOrAfter(V2));
0382   }
0383 
0384   /// A trivial helper function to check to see if the specified pointers are
0385   /// must-alias.
0386   bool isMustAlias(const MemoryLocation &LocA, const MemoryLocation &LocB) {
0387     return alias(LocA, LocB) == AliasResult::MustAlias;
0388   }
0389 
0390   /// A convenience wrapper around the \c isMustAlias helper interface.
0391   bool isMustAlias(const Value *V1, const Value *V2) {
0392     return alias(V1, LocationSize::precise(1), V2, LocationSize::precise(1)) ==
0393            AliasResult::MustAlias;
0394   }
0395 
0396   /// Checks whether the given location points to constant memory, or if
0397   /// \p OrLocal is true whether it points to a local alloca.
0398   bool pointsToConstantMemory(const MemoryLocation &Loc, bool OrLocal = false) {
0399     return isNoModRef(getModRefInfoMask(Loc, OrLocal));
0400   }
0401 
0402   /// A convenience wrapper around the primary \c pointsToConstantMemory
0403   /// interface.
0404   bool pointsToConstantMemory(const Value *P, bool OrLocal = false) {
0405     return pointsToConstantMemory(MemoryLocation::getBeforeOrAfter(P), OrLocal);
0406   }
0407 
0408   /// @}
0409   //===--------------------------------------------------------------------===//
0410   /// \name Simple mod/ref information
0411   /// @{
0412 
0413   /// Returns a bitmask that should be unconditionally applied to the ModRef
0414   /// info of a memory location. This allows us to eliminate Mod and/or Ref
0415   /// from the ModRef info based on the knowledge that the memory location
0416   /// points to constant and/or locally-invariant memory.
0417   ///
0418   /// If IgnoreLocals is true, then this method returns NoModRef for memory
0419   /// that points to a local alloca.
0420   ModRefInfo getModRefInfoMask(const MemoryLocation &Loc,
0421                                bool IgnoreLocals = false);
0422 
0423   /// A convenience wrapper around the primary \c getModRefInfoMask
0424   /// interface.
0425   ModRefInfo getModRefInfoMask(const Value *P, bool IgnoreLocals = false) {
0426     return getModRefInfoMask(MemoryLocation::getBeforeOrAfter(P), IgnoreLocals);
0427   }
0428 
0429   /// Get the ModRef info associated with a pointer argument of a call. The
0430   /// result's bits are set to indicate the allowed aliasing ModRef kinds. Note
0431   /// that these bits do not necessarily account for the overall behavior of
0432   /// the function, but rather only provide additional per-argument
0433   /// information.
0434   ModRefInfo getArgModRefInfo(const CallBase *Call, unsigned ArgIdx);
0435 
0436   /// Return the behavior of the given call site.
0437   MemoryEffects getMemoryEffects(const CallBase *Call);
0438 
0439   /// Return the behavior when calling the given function.
0440   MemoryEffects getMemoryEffects(const Function *F);
0441 
0442   /// Checks if the specified call is known to never read or write memory.
0443   ///
0444   /// Note that if the call only reads from known-constant memory, it is also
0445   /// legal to return true. Also, calls that unwind the stack are legal for
0446   /// this predicate.
0447   ///
0448   /// Many optimizations (such as CSE and LICM) can be performed on such calls
0449   /// without worrying about aliasing properties, and many calls have this
0450   /// property (e.g. calls to 'sin' and 'cos').
0451   ///
0452   /// This property corresponds to the GCC 'const' attribute.
0453   bool doesNotAccessMemory(const CallBase *Call) {
0454     return getMemoryEffects(Call).doesNotAccessMemory();
0455   }
0456 
0457   /// Checks if the specified function is known to never read or write memory.
0458   ///
0459   /// Note that if the function only reads from known-constant memory, it is
0460   /// also legal to return true. Also, function that unwind the stack are legal
0461   /// for this predicate.
0462   ///
0463   /// Many optimizations (such as CSE and LICM) can be performed on such calls
0464   /// to such functions without worrying about aliasing properties, and many
0465   /// functions have this property (e.g. 'sin' and 'cos').
0466   ///
0467   /// This property corresponds to the GCC 'const' attribute.
0468   bool doesNotAccessMemory(const Function *F) {
0469     return getMemoryEffects(F).doesNotAccessMemory();
0470   }
0471 
0472   /// Checks if the specified call is known to only read from non-volatile
0473   /// memory (or not access memory at all).
0474   ///
0475   /// Calls that unwind the stack are legal for this predicate.
0476   ///
0477   /// This property allows many common optimizations to be performed in the
0478   /// absence of interfering store instructions, such as CSE of strlen calls.
0479   ///
0480   /// This property corresponds to the GCC 'pure' attribute.
0481   bool onlyReadsMemory(const CallBase *Call) {
0482     return getMemoryEffects(Call).onlyReadsMemory();
0483   }
0484 
0485   /// Checks if the specified function is known to only read from non-volatile
0486   /// memory (or not access memory at all).
0487   ///
0488   /// Functions that unwind the stack are legal for this predicate.
0489   ///
0490   /// This property allows many common optimizations to be performed in the
0491   /// absence of interfering store instructions, such as CSE of strlen calls.
0492   ///
0493   /// This property corresponds to the GCC 'pure' attribute.
0494   bool onlyReadsMemory(const Function *F) {
0495     return getMemoryEffects(F).onlyReadsMemory();
0496   }
0497 
0498   /// Check whether or not an instruction may read or write the optionally
0499   /// specified memory location.
0500   ///
0501   ///
0502   /// An instruction that doesn't read or write memory may be trivially LICM'd
0503   /// for example.
0504   ///
0505   /// For function calls, this delegates to the alias-analysis specific
0506   /// call-site mod-ref behavior queries. Otherwise it delegates to the specific
0507   /// helpers above.
0508   ModRefInfo getModRefInfo(const Instruction *I,
0509                            const std::optional<MemoryLocation> &OptLoc) {
0510     SimpleAAQueryInfo AAQIP(*this);
0511     return getModRefInfo(I, OptLoc, AAQIP);
0512   }
0513 
0514   /// A convenience wrapper for constructing the memory location.
0515   ModRefInfo getModRefInfo(const Instruction *I, const Value *P,
0516                            LocationSize Size) {
0517     return getModRefInfo(I, MemoryLocation(P, Size));
0518   }
0519 
0520   /// Return information about whether a call and an instruction may refer to
0521   /// the same memory locations.
0522   ModRefInfo getModRefInfo(const Instruction *I, const CallBase *Call);
0523 
0524   /// Return information about whether a particular call site modifies
0525   /// or reads the specified memory location \p MemLoc before instruction \p I
0526   /// in a BasicBlock.
0527   ModRefInfo callCapturesBefore(const Instruction *I,
0528                                 const MemoryLocation &MemLoc,
0529                                 DominatorTree *DT) {
0530     SimpleAAQueryInfo AAQIP(*this);
0531     return callCapturesBefore(I, MemLoc, DT, AAQIP);
0532   }
0533 
0534   /// A convenience wrapper to synthesize a memory location.
0535   ModRefInfo callCapturesBefore(const Instruction *I, const Value *P,
0536                                 LocationSize Size, DominatorTree *DT) {
0537     return callCapturesBefore(I, MemoryLocation(P, Size), DT);
0538   }
0539 
0540   /// @}
0541   //===--------------------------------------------------------------------===//
0542   /// \name Higher level methods for querying mod/ref information.
0543   /// @{
0544 
0545   /// Check if it is possible for execution of the specified basic block to
0546   /// modify the location Loc.
0547   bool canBasicBlockModify(const BasicBlock &BB, const MemoryLocation &Loc);
0548 
0549   /// A convenience wrapper synthesizing a memory location.
0550   bool canBasicBlockModify(const BasicBlock &BB, const Value *P,
0551                            LocationSize Size) {
0552     return canBasicBlockModify(BB, MemoryLocation(P, Size));
0553   }
0554 
0555   /// Check if it is possible for the execution of the specified instructions
0556   /// to mod\ref (according to the mode) the location Loc.
0557   ///
0558   /// The instructions to consider are all of the instructions in the range of
0559   /// [I1,I2] INCLUSIVE. I1 and I2 must be in the same basic block.
0560   bool canInstructionRangeModRef(const Instruction &I1, const Instruction &I2,
0561                                  const MemoryLocation &Loc,
0562                                  const ModRefInfo Mode);
0563 
0564   /// A convenience wrapper synthesizing a memory location.
0565   bool canInstructionRangeModRef(const Instruction &I1, const Instruction &I2,
0566                                  const Value *Ptr, LocationSize Size,
0567                                  const ModRefInfo Mode) {
0568     return canInstructionRangeModRef(I1, I2, MemoryLocation(Ptr, Size), Mode);
0569   }
0570 
0571   // CtxI can be nullptr, in which case the query is whether or not the aliasing
0572   // relationship holds through the entire function.
0573   AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB,
0574                     AAQueryInfo &AAQI, const Instruction *CtxI = nullptr);
0575 
0576   ModRefInfo getModRefInfoMask(const MemoryLocation &Loc, AAQueryInfo &AAQI,
0577                                bool IgnoreLocals = false);
0578   ModRefInfo getModRefInfo(const Instruction *I, const CallBase *Call2,
0579                            AAQueryInfo &AAQIP);
0580   ModRefInfo getModRefInfo(const CallBase *Call, const MemoryLocation &Loc,
0581                            AAQueryInfo &AAQI);
0582   ModRefInfo getModRefInfo(const CallBase *Call1, const CallBase *Call2,
0583                            AAQueryInfo &AAQI);
0584   ModRefInfo getModRefInfo(const VAArgInst *V, const MemoryLocation &Loc,
0585                            AAQueryInfo &AAQI);
0586   ModRefInfo getModRefInfo(const LoadInst *L, const MemoryLocation &Loc,
0587                            AAQueryInfo &AAQI);
0588   ModRefInfo getModRefInfo(const StoreInst *S, const MemoryLocation &Loc,
0589                            AAQueryInfo &AAQI);
0590   ModRefInfo getModRefInfo(const FenceInst *S, const MemoryLocation &Loc,
0591                            AAQueryInfo &AAQI);
0592   ModRefInfo getModRefInfo(const AtomicCmpXchgInst *CX,
0593                            const MemoryLocation &Loc, AAQueryInfo &AAQI);
0594   ModRefInfo getModRefInfo(const AtomicRMWInst *RMW, const MemoryLocation &Loc,
0595                            AAQueryInfo &AAQI);
0596   ModRefInfo getModRefInfo(const CatchPadInst *I, const MemoryLocation &Loc,
0597                            AAQueryInfo &AAQI);
0598   ModRefInfo getModRefInfo(const CatchReturnInst *I, const MemoryLocation &Loc,
0599                            AAQueryInfo &AAQI);
0600   ModRefInfo getModRefInfo(const Instruction *I,
0601                            const std::optional<MemoryLocation> &OptLoc,
0602                            AAQueryInfo &AAQIP);
0603   ModRefInfo callCapturesBefore(const Instruction *I,
0604                                 const MemoryLocation &MemLoc, DominatorTree *DT,
0605                                 AAQueryInfo &AAQIP);
0606   MemoryEffects getMemoryEffects(const CallBase *Call, AAQueryInfo &AAQI);
0607 
0608 private:
0609   class Concept;
0610 
0611   template <typename T> class Model;
0612 
0613   friend class AAResultBase;
0614 
0615   const TargetLibraryInfo &TLI;
0616 
0617   std::vector<std::unique_ptr<Concept>> AAs;
0618 
0619   std::vector<AnalysisKey *> AADeps;
0620 
0621   friend class BatchAAResults;
0622 };
0623 
0624 /// This class is a wrapper over an AAResults, and it is intended to be used
0625 /// only when there are no IR changes inbetween queries. BatchAAResults is
0626 /// reusing the same `AAQueryInfo` to preserve the state across queries,
0627 /// esentially making AA work in "batch mode". The internal state cannot be
0628 /// cleared, so to go "out-of-batch-mode", the user must either use AAResults,
0629 /// or create a new BatchAAResults.
0630 class BatchAAResults {
0631   AAResults &AA;
0632   AAQueryInfo AAQI;
0633   SimpleCaptureAnalysis SimpleCA;
0634 
0635 public:
0636   BatchAAResults(AAResults &AAR) : AA(AAR), AAQI(AAR, &SimpleCA) {}
0637   BatchAAResults(AAResults &AAR, CaptureAnalysis *CA)
0638       : AA(AAR), AAQI(AAR, CA) {}
0639 
0640   AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB) {
0641     return AA.alias(LocA, LocB, AAQI);
0642   }
0643   bool pointsToConstantMemory(const MemoryLocation &Loc, bool OrLocal = false) {
0644     return isNoModRef(AA.getModRefInfoMask(Loc, AAQI, OrLocal));
0645   }
0646   bool pointsToConstantMemory(const Value *P, bool OrLocal = false) {
0647     return pointsToConstantMemory(MemoryLocation::getBeforeOrAfter(P), OrLocal);
0648   }
0649   ModRefInfo getModRefInfoMask(const MemoryLocation &Loc,
0650                                bool IgnoreLocals = false) {
0651     return AA.getModRefInfoMask(Loc, AAQI, IgnoreLocals);
0652   }
0653   ModRefInfo getModRefInfo(const Instruction *I,
0654                            const std::optional<MemoryLocation> &OptLoc) {
0655     return AA.getModRefInfo(I, OptLoc, AAQI);
0656   }
0657   ModRefInfo getModRefInfo(const Instruction *I, const CallBase *Call2) {
0658     return AA.getModRefInfo(I, Call2, AAQI);
0659   }
0660   ModRefInfo getArgModRefInfo(const CallBase *Call, unsigned ArgIdx) {
0661     return AA.getArgModRefInfo(Call, ArgIdx);
0662   }
0663   MemoryEffects getMemoryEffects(const CallBase *Call) {
0664     return AA.getMemoryEffects(Call, AAQI);
0665   }
0666   bool isMustAlias(const MemoryLocation &LocA, const MemoryLocation &LocB) {
0667     return alias(LocA, LocB) == AliasResult::MustAlias;
0668   }
0669   bool isMustAlias(const Value *V1, const Value *V2) {
0670     return alias(MemoryLocation(V1, LocationSize::precise(1)),
0671                  MemoryLocation(V2, LocationSize::precise(1))) ==
0672            AliasResult::MustAlias;
0673   }
0674   bool isNoAlias(const MemoryLocation &LocA, const MemoryLocation &LocB) {
0675     return alias(LocA, LocB) == AliasResult::NoAlias;
0676   }
0677   ModRefInfo callCapturesBefore(const Instruction *I,
0678                                 const MemoryLocation &MemLoc,
0679                                 DominatorTree *DT) {
0680     return AA.callCapturesBefore(I, MemLoc, DT, AAQI);
0681   }
0682 
0683   /// Assume that values may come from different cycle iterations.
0684   void enableCrossIterationMode() {
0685     AAQI.MayBeCrossIteration = true;
0686   }
0687 
0688   /// Disable the use of the dominator tree during alias analysis queries.
0689   void disableDominatorTree() { AAQI.UseDominatorTree = false; }
0690 };
0691 
0692 /// Temporary typedef for legacy code that uses a generic \c AliasAnalysis
0693 /// pointer or reference.
0694 using AliasAnalysis = AAResults;
0695 
0696 /// A private abstract base class describing the concept of an individual alias
0697 /// analysis implementation.
0698 ///
0699 /// This interface is implemented by any \c Model instantiation. It is also the
0700 /// interface which a type used to instantiate the model must provide.
0701 ///
0702 /// All of these methods model methods by the same name in the \c
0703 /// AAResults class. Only differences and specifics to how the
0704 /// implementations are called are documented here.
0705 class AAResults::Concept {
0706 public:
0707   virtual ~Concept() = 0;
0708 
0709   //===--------------------------------------------------------------------===//
0710   /// \name Alias Queries
0711   /// @{
0712 
0713   /// The main low level interface to the alias analysis implementation.
0714   /// Returns an AliasResult indicating whether the two pointers are aliased to
0715   /// each other. This is the interface that must be implemented by specific
0716   /// alias analysis implementations.
0717   virtual AliasResult alias(const MemoryLocation &LocA,
0718                             const MemoryLocation &LocB, AAQueryInfo &AAQI,
0719                             const Instruction *CtxI) = 0;
0720 
0721   /// @}
0722   //===--------------------------------------------------------------------===//
0723   /// \name Simple mod/ref information
0724   /// @{
0725 
0726   /// Returns a bitmask that should be unconditionally applied to the ModRef
0727   /// info of a memory location. This allows us to eliminate Mod and/or Ref from
0728   /// the ModRef info based on the knowledge that the memory location points to
0729   /// constant and/or locally-invariant memory.
0730   virtual ModRefInfo getModRefInfoMask(const MemoryLocation &Loc,
0731                                        AAQueryInfo &AAQI,
0732                                        bool IgnoreLocals) = 0;
0733 
0734   /// Get the ModRef info associated with a pointer argument of a callsite. The
0735   /// result's bits are set to indicate the allowed aliasing ModRef kinds. Note
0736   /// that these bits do not necessarily account for the overall behavior of
0737   /// the function, but rather only provide additional per-argument
0738   /// information.
0739   virtual ModRefInfo getArgModRefInfo(const CallBase *Call,
0740                                       unsigned ArgIdx) = 0;
0741 
0742   /// Return the behavior of the given call site.
0743   virtual MemoryEffects getMemoryEffects(const CallBase *Call,
0744                                          AAQueryInfo &AAQI) = 0;
0745 
0746   /// Return the behavior when calling the given function.
0747   virtual MemoryEffects getMemoryEffects(const Function *F) = 0;
0748 
0749   /// getModRefInfo (for call sites) - Return information about whether
0750   /// a particular call site modifies or reads the specified memory location.
0751   virtual ModRefInfo getModRefInfo(const CallBase *Call,
0752                                    const MemoryLocation &Loc,
0753                                    AAQueryInfo &AAQI) = 0;
0754 
0755   /// Return information about whether two call sites may refer to the same set
0756   /// of memory locations. See the AA documentation for details:
0757   ///   http://llvm.org/docs/AliasAnalysis.html#ModRefInfo
0758   virtual ModRefInfo getModRefInfo(const CallBase *Call1, const CallBase *Call2,
0759                                    AAQueryInfo &AAQI) = 0;
0760 
0761   /// @}
0762 };
0763 
0764 /// A private class template which derives from \c Concept and wraps some other
0765 /// type.
0766 ///
0767 /// This models the concept by directly forwarding each interface point to the
0768 /// wrapped type which must implement a compatible interface. This provides
0769 /// a type erased binding.
0770 template <typename AAResultT> class AAResults::Model final : public Concept {
0771   AAResultT &Result;
0772 
0773 public:
0774   explicit Model(AAResultT &Result, AAResults &AAR) : Result(Result) {}
0775   ~Model() override = default;
0776 
0777   AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB,
0778                     AAQueryInfo &AAQI, const Instruction *CtxI) override {
0779     return Result.alias(LocA, LocB, AAQI, CtxI);
0780   }
0781 
0782   ModRefInfo getModRefInfoMask(const MemoryLocation &Loc, AAQueryInfo &AAQI,
0783                                bool IgnoreLocals) override {
0784     return Result.getModRefInfoMask(Loc, AAQI, IgnoreLocals);
0785   }
0786 
0787   ModRefInfo getArgModRefInfo(const CallBase *Call, unsigned ArgIdx) override {
0788     return Result.getArgModRefInfo(Call, ArgIdx);
0789   }
0790 
0791   MemoryEffects getMemoryEffects(const CallBase *Call,
0792                                  AAQueryInfo &AAQI) override {
0793     return Result.getMemoryEffects(Call, AAQI);
0794   }
0795 
0796   MemoryEffects getMemoryEffects(const Function *F) override {
0797     return Result.getMemoryEffects(F);
0798   }
0799 
0800   ModRefInfo getModRefInfo(const CallBase *Call, const MemoryLocation &Loc,
0801                            AAQueryInfo &AAQI) override {
0802     return Result.getModRefInfo(Call, Loc, AAQI);
0803   }
0804 
0805   ModRefInfo getModRefInfo(const CallBase *Call1, const CallBase *Call2,
0806                            AAQueryInfo &AAQI) override {
0807     return Result.getModRefInfo(Call1, Call2, AAQI);
0808   }
0809 };
0810 
0811 /// A base class to help implement the function alias analysis results concept.
0812 ///
0813 /// Because of the nature of many alias analysis implementations, they often
0814 /// only implement a subset of the interface. This base class will attempt to
0815 /// implement the remaining portions of the interface in terms of simpler forms
0816 /// of the interface where possible, and otherwise provide conservatively
0817 /// correct fallback implementations.
0818 ///
0819 /// Implementors of an alias analysis should derive from this class, and then
0820 /// override specific methods that they wish to customize. There is no need to
0821 /// use virtual anywhere.
0822 class AAResultBase {
0823 protected:
0824   explicit AAResultBase() = default;
0825 
0826   // Provide all the copy and move constructors so that derived types aren't
0827   // constrained.
0828   AAResultBase(const AAResultBase &Arg) {}
0829   AAResultBase(AAResultBase &&Arg) {}
0830 
0831 public:
0832   AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB,
0833                     AAQueryInfo &AAQI, const Instruction *I) {
0834     return AliasResult::MayAlias;
0835   }
0836 
0837   ModRefInfo getModRefInfoMask(const MemoryLocation &Loc, AAQueryInfo &AAQI,
0838                                bool IgnoreLocals) {
0839     return ModRefInfo::ModRef;
0840   }
0841 
0842   ModRefInfo getArgModRefInfo(const CallBase *Call, unsigned ArgIdx) {
0843     return ModRefInfo::ModRef;
0844   }
0845 
0846   MemoryEffects getMemoryEffects(const CallBase *Call, AAQueryInfo &AAQI) {
0847     return MemoryEffects::unknown();
0848   }
0849 
0850   MemoryEffects getMemoryEffects(const Function *F) {
0851     return MemoryEffects::unknown();
0852   }
0853 
0854   ModRefInfo getModRefInfo(const CallBase *Call, const MemoryLocation &Loc,
0855                            AAQueryInfo &AAQI) {
0856     return ModRefInfo::ModRef;
0857   }
0858 
0859   ModRefInfo getModRefInfo(const CallBase *Call1, const CallBase *Call2,
0860                            AAQueryInfo &AAQI) {
0861     return ModRefInfo::ModRef;
0862   }
0863 };
0864 
0865 /// Return true if this pointer is returned by a noalias function.
0866 bool isNoAliasCall(const Value *V);
0867 
0868 /// Return true if this pointer refers to a distinct and identifiable object.
0869 /// This returns true for:
0870 ///    Global Variables and Functions (but not Global Aliases)
0871 ///    Allocas
0872 ///    ByVal and NoAlias Arguments
0873 ///    NoAlias returns (e.g. calls to malloc)
0874 ///
0875 bool isIdentifiedObject(const Value *V);
0876 
0877 /// Return true if V is umabigously identified at the function-level.
0878 /// Different IdentifiedFunctionLocals can't alias.
0879 /// Further, an IdentifiedFunctionLocal can not alias with any function
0880 /// arguments other than itself, which is not necessarily true for
0881 /// IdentifiedObjects.
0882 bool isIdentifiedFunctionLocal(const Value *V);
0883 
0884 /// Return true if we know V to the base address of the corresponding memory
0885 /// object.  This implies that any address less than V must be out of bounds
0886 /// for the underlying object.  Note that just being isIdentifiedObject() is
0887 /// not enough - For example, a negative offset from a noalias argument or call
0888 /// can be inbounds w.r.t the actual underlying object.
0889 bool isBaseOfObject(const Value *V);
0890 
0891 /// Returns true if the pointer is one which would have been considered an
0892 /// escape by isNonEscapingLocalObject.
0893 bool isEscapeSource(const Value *V);
0894 
0895 /// Return true if Object memory is not visible after an unwind, in the sense
0896 /// that program semantics cannot depend on Object containing any particular
0897 /// value on unwind. If the RequiresNoCaptureBeforeUnwind out parameter is set
0898 /// to true, then the memory is only not visible if the object has not been
0899 /// captured prior to the unwind. Otherwise it is not visible even if captured.
0900 bool isNotVisibleOnUnwind(const Value *Object,
0901                           bool &RequiresNoCaptureBeforeUnwind);
0902 
0903 /// Return true if the Object is writable, in the sense that any location based
0904 /// on this pointer that can be loaded can also be stored to without trapping.
0905 /// Additionally, at the point Object is declared, stores can be introduced
0906 /// without data races. At later points, this is only the case if the pointer
0907 /// can not escape to a different thread.
0908 ///
0909 /// If ExplicitlyDereferenceableOnly is set to true, this property only holds
0910 /// for the part of Object that is explicitly marked as dereferenceable, e.g.
0911 /// using the dereferenceable(N) attribute. It does not necessarily hold for
0912 /// parts that are only known to be dereferenceable due to the presence of
0913 /// loads.
0914 bool isWritableObject(const Value *Object, bool &ExplicitlyDereferenceableOnly);
0915 
0916 /// A manager for alias analyses.
0917 ///
0918 /// This class can have analyses registered with it and when run, it will run
0919 /// all of them and aggregate their results into single AA results interface
0920 /// that dispatches across all of the alias analysis results available.
0921 ///
0922 /// Note that the order in which analyses are registered is very significant.
0923 /// That is the order in which the results will be aggregated and queried.
0924 ///
0925 /// This manager effectively wraps the AnalysisManager for registering alias
0926 /// analyses. When you register your alias analysis with this manager, it will
0927 /// ensure the analysis itself is registered with its AnalysisManager.
0928 ///
0929 /// The result of this analysis is only invalidated if one of the particular
0930 /// aggregated AA results end up being invalidated. This removes the need to
0931 /// explicitly preserve the results of `AAManager`. Note that analyses should no
0932 /// longer be registered once the `AAManager` is run.
0933 class AAManager : public AnalysisInfoMixin<AAManager> {
0934 public:
0935   using Result = AAResults;
0936 
0937   /// Register a specific AA result.
0938   template <typename AnalysisT> void registerFunctionAnalysis() {
0939     ResultGetters.push_back(&getFunctionAAResultImpl<AnalysisT>);
0940   }
0941 
0942   /// Register a specific AA result.
0943   template <typename AnalysisT> void registerModuleAnalysis() {
0944     ResultGetters.push_back(&getModuleAAResultImpl<AnalysisT>);
0945   }
0946 
0947   Result run(Function &F, FunctionAnalysisManager &AM);
0948 
0949 private:
0950   friend AnalysisInfoMixin<AAManager>;
0951 
0952   static AnalysisKey Key;
0953 
0954   SmallVector<void (*)(Function &F, FunctionAnalysisManager &AM,
0955                        AAResults &AAResults),
0956               4> ResultGetters;
0957 
0958   template <typename AnalysisT>
0959   static void getFunctionAAResultImpl(Function &F,
0960                                       FunctionAnalysisManager &AM,
0961                                       AAResults &AAResults) {
0962     AAResults.addAAResult(AM.template getResult<AnalysisT>(F));
0963     AAResults.addAADependencyID(AnalysisT::ID());
0964   }
0965 
0966   template <typename AnalysisT>
0967   static void getModuleAAResultImpl(Function &F, FunctionAnalysisManager &AM,
0968                                     AAResults &AAResults) {
0969     auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
0970     if (auto *R =
0971             MAMProxy.template getCachedResult<AnalysisT>(*F.getParent())) {
0972       AAResults.addAAResult(*R);
0973       MAMProxy
0974           .template registerOuterAnalysisInvalidation<AnalysisT, AAManager>();
0975     }
0976   }
0977 };
0978 
0979 /// A wrapper pass to provide the legacy pass manager access to a suitably
0980 /// prepared AAResults object.
0981 class AAResultsWrapperPass : public FunctionPass {
0982   std::unique_ptr<AAResults> AAR;
0983 
0984 public:
0985   static char ID;
0986 
0987   AAResultsWrapperPass();
0988 
0989   AAResults &getAAResults() { return *AAR; }
0990   const AAResults &getAAResults() const { return *AAR; }
0991 
0992   bool runOnFunction(Function &F) override;
0993 
0994   void getAnalysisUsage(AnalysisUsage &AU) const override;
0995 };
0996 
0997 /// A wrapper pass for external alias analyses. This just squirrels away the
0998 /// callback used to run any analyses and register their results.
0999 struct ExternalAAWrapperPass : ImmutablePass {
1000   using CallbackT = std::function<void(Pass &, Function &, AAResults &)>;
1001 
1002   CallbackT CB;
1003 
1004   static char ID;
1005 
1006   ExternalAAWrapperPass();
1007 
1008   explicit ExternalAAWrapperPass(CallbackT CB);
1009 
1010   void getAnalysisUsage(AnalysisUsage &AU) const override {
1011     AU.setPreservesAll();
1012   }
1013 };
1014 
1015 /// A wrapper pass around a callback which can be used to populate the
1016 /// AAResults in the AAResultsWrapperPass from an external AA.
1017 ///
1018 /// The callback provided here will be used each time we prepare an AAResults
1019 /// object, and will receive a reference to the function wrapper pass, the
1020 /// function, and the AAResults object to populate. This should be used when
1021 /// setting up a custom pass pipeline to inject a hook into the AA results.
1022 ImmutablePass *createExternalAAWrapperPass(
1023     std::function<void(Pass &, Function &, AAResults &)> Callback);
1024 
1025 } // end namespace llvm
1026 
1027 #endif // LLVM_ANALYSIS_ALIASANALYSIS_H