1 //===- llvm/Analysis/AliasAnalysis.h - Alias Analysis Interface -*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file defines the generic AliasAnalysis interface, which is used as the 10 // common interface used by all clients of alias analysis information, and 11 // implemented by all alias analysis implementations. Mod/Ref information is 12 // also captured by this interface. 13 // 14 // Implementations of this interface must implement the various virtual methods, 15 // which automatically provides functionality for the entire suite of client 16 // APIs. 17 // 18 // This API identifies memory regions with the MemoryLocation class. The pointer 19 // component specifies the base memory address of the region. The Size specifies 20 // the maximum size (in address units) of the memory region, or 21 // MemoryLocation::UnknownSize if the size is not known. The TBAA tag 22 // identifies the "type" of the memory reference; see the 23 // TypeBasedAliasAnalysis class for details. 24 // 25 // Some non-obvious details include: 26 // - Pointers that point to two completely different objects in memory never 27 // alias, regardless of the value of the Size component. 28 // - NoAlias doesn't imply inequal pointers. The most obvious example of this 29 // is two pointers to constant memory. Even if they are equal, constant 30 // memory is never stored to, so there will never be any dependencies. 31 // In this and other situations, the pointers may be both NoAlias and 32 // MustAlias at the same time. The current API can only return one result, 33 // though this is rarely a problem in practice. 34 // 35 //===----------------------------------------------------------------------===// 36 37 #ifndef LLVM_ANALYSIS_ALIASANALYSIS_H 38 #define LLVM_ANALYSIS_ALIASANALYSIS_H 39 40 #include "llvm/ADT/DenseMap.h" 41 #include "llvm/ADT/SmallVector.h" 42 #include "llvm/Analysis/MemoryLocation.h" 43 #include "llvm/IR/Function.h" 44 #include "llvm/IR/PassManager.h" 45 #include "llvm/Pass.h" 46 #include "llvm/Support/ModRef.h" 47 #include <cstdint> 48 #include <functional> 49 #include <memory> 50 #include <optional> 51 #include <vector> 52 53 namespace llvm { 54 55 class AtomicCmpXchgInst; 56 class BasicBlock; 57 class CatchPadInst; 58 class CatchReturnInst; 59 class DominatorTree; 60 class FenceInst; 61 class LoopInfo; 62 class TargetLibraryInfo; 63 64 /// The possible results of an alias query. 65 /// 66 /// These results are always computed between two MemoryLocation objects as 67 /// a query to some alias analysis. 68 /// 69 /// Note that these are unscoped enumerations because we would like to support 70 /// implicitly testing a result for the existence of any possible aliasing with 71 /// a conversion to bool, but an "enum class" doesn't support this. The 72 /// canonical names from the literature are suffixed and unique anyways, and so 73 /// they serve as global constants in LLVM for these results. 74 /// 75 /// See docs/AliasAnalysis.html for more information on the specific meanings 76 /// of these values. 77 class AliasResult { 78 private: 79 static const int OffsetBits = 23; 80 static const int AliasBits = 8; 81 static_assert(AliasBits + 1 + OffsetBits <= 32, 82 "AliasResult size is intended to be 4 bytes!"); 83 84 unsigned int Alias : AliasBits; 85 unsigned int HasOffset : 1; 86 signed int Offset : OffsetBits; 87 88 public: 89 enum Kind : uint8_t { 90 /// The two locations do not alias at all. 91 /// 92 /// This value is arranged to convert to false, while all other values 93 /// convert to true. This allows a boolean context to convert the result to 94 /// a binary flag indicating whether there is the possibility of aliasing. 95 NoAlias = 0, 96 /// The two locations may or may not alias. This is the least precise 97 /// result. 98 MayAlias, 99 /// The two locations alias, but only due to a partial overlap. 100 PartialAlias, 101 /// The two locations precisely alias each other. 102 MustAlias, 103 }; 104 static_assert(MustAlias < (1 << AliasBits), 105 "Not enough bit field size for the enum!"); 106 107 explicit AliasResult() = delete; AliasResult(const Kind & Alias)108 constexpr AliasResult(const Kind &Alias) 109 : Alias(Alias), HasOffset(false), Offset(0) {} 110 Kind()111 operator Kind() const { return static_cast<Kind>(Alias); } 112 113 bool operator==(const AliasResult &Other) const { 114 return Alias == Other.Alias && HasOffset == Other.HasOffset && 115 Offset == Other.Offset; 116 } 117 bool operator!=(const AliasResult &Other) const { return !(*this == Other); } 118 119 bool operator==(Kind K) const { return Alias == K; } 120 bool operator!=(Kind K) const { return !(*this == K); } 121 hasOffset()122 constexpr bool hasOffset() const { return HasOffset; } getOffset()123 constexpr int32_t getOffset() const { 124 assert(HasOffset && "No offset!"); 125 return Offset; 126 } setOffset(int32_t NewOffset)127 void setOffset(int32_t NewOffset) { 128 if (isInt<OffsetBits>(NewOffset)) { 129 HasOffset = true; 130 Offset = NewOffset; 131 } 132 } 133 134 /// Helper for processing AliasResult for swapped memory location pairs. 135 void swap(bool DoSwap = true) { 136 if (DoSwap && hasOffset()) 137 setOffset(-getOffset()); 138 } 139 }; 140 141 static_assert(sizeof(AliasResult) == 4, 142 "AliasResult size is intended to be 4 bytes!"); 143 144 /// << operator for AliasResult. 145 raw_ostream &operator<<(raw_ostream &OS, AliasResult AR); 146 147 /// Virtual base class for providers of capture information. 148 struct CaptureInfo { 149 virtual ~CaptureInfo() = 0; 150 151 /// Check whether Object is not captured before instruction I. If OrAt is 152 /// true, captures by instruction I itself are also considered. 153 /// 154 /// If I is nullptr, then captures at any point will be considered. 155 virtual bool isNotCapturedBefore(const Value *Object, const Instruction *I, 156 bool OrAt) = 0; 157 }; 158 159 /// Context-free CaptureInfo provider, which computes and caches whether an 160 /// object is captured in the function at all, but does not distinguish whether 161 /// it was captured before or after the context instruction. 162 class SimpleCaptureInfo final : public CaptureInfo { 163 SmallDenseMap<const Value *, bool, 8> IsCapturedCache; 164 165 public: 166 bool isNotCapturedBefore(const Value *Object, const Instruction *I, 167 bool OrAt) override; 168 }; 169 170 /// Context-sensitive CaptureInfo provider, which computes and caches the 171 /// earliest common dominator closure of all captures. It provides a good 172 /// approximation to a precise "captures before" analysis. 173 class EarliestEscapeInfo final : public CaptureInfo { 174 DominatorTree &DT; 175 const LoopInfo *LI; 176 177 /// Map from identified local object to an instruction before which it does 178 /// not escape, or nullptr if it never escapes. The "earliest" instruction 179 /// may be a conservative approximation, e.g. the first instruction in the 180 /// function is always a legal choice. 181 DenseMap<const Value *, Instruction *> EarliestEscapes; 182 183 /// Reverse map from instruction to the objects it is the earliest escape for. 184 /// This is used for cache invalidation purposes. 185 DenseMap<Instruction *, TinyPtrVector<const Value *>> Inst2Obj; 186 187 public: 188 EarliestEscapeInfo(DominatorTree &DT, const LoopInfo *LI = nullptr) DT(DT)189 : DT(DT), LI(LI) {} 190 191 bool isNotCapturedBefore(const Value *Object, const Instruction *I, 192 bool OrAt) override; 193 194 void removeInstruction(Instruction *I); 195 }; 196 197 /// Cache key for BasicAA results. It only includes the pointer and size from 198 /// MemoryLocation, as BasicAA is AATags independent. Additionally, it includes 199 /// the value of MayBeCrossIteration, which may affect BasicAA results. 200 struct AACacheLoc { 201 using PtrTy = PointerIntPair<const Value *, 1, bool>; 202 PtrTy Ptr; 203 LocationSize Size; 204 AACacheLocAACacheLoc205 AACacheLoc(PtrTy Ptr, LocationSize Size) : Ptr(Ptr), Size(Size) {} AACacheLocAACacheLoc206 AACacheLoc(const Value *Ptr, LocationSize Size, bool MayBeCrossIteration) 207 : Ptr(Ptr, MayBeCrossIteration), Size(Size) {} 208 }; 209 210 template <> struct DenseMapInfo<AACacheLoc> { 211 static inline AACacheLoc getEmptyKey() { 212 return {DenseMapInfo<AACacheLoc::PtrTy>::getEmptyKey(), 213 DenseMapInfo<LocationSize>::getEmptyKey()}; 214 } 215 static inline AACacheLoc getTombstoneKey() { 216 return {DenseMapInfo<AACacheLoc::PtrTy>::getTombstoneKey(), 217 DenseMapInfo<LocationSize>::getTombstoneKey()}; 218 } 219 static unsigned getHashValue(const AACacheLoc &Val) { 220 return DenseMapInfo<AACacheLoc::PtrTy>::getHashValue(Val.Ptr) ^ 221 DenseMapInfo<LocationSize>::getHashValue(Val.Size); 222 } 223 static bool isEqual(const AACacheLoc &LHS, const AACacheLoc &RHS) { 224 return LHS.Ptr == RHS.Ptr && LHS.Size == RHS.Size; 225 } 226 }; 227 228 class AAResults; 229 230 /// This class stores info we want to provide to or retain within an alias 231 /// query. By default, the root query is stateless and starts with a freshly 232 /// constructed info object. Specific alias analyses can use this query info to 233 /// store per-query state that is important for recursive or nested queries to 234 /// avoid recomputing. To enable preserving this state across multiple queries 235 /// where safe (due to the IR not changing), use a `BatchAAResults` wrapper. 236 /// The information stored in an `AAQueryInfo` is currently limitted to the 237 /// caches used by BasicAA, but can further be extended to fit other AA needs. 238 class AAQueryInfo { 239 public: 240 using LocPair = std::pair<AACacheLoc, AACacheLoc>; 241 struct CacheEntry { 242 /// Cache entry is neither an assumption nor does it use a (non-definitive) 243 /// assumption. 244 static constexpr int Definitive = -2; 245 /// Cache entry is not an assumption itself, but may be using an assumption 246 /// from higher up the stack. 247 static constexpr int AssumptionBased = -1; 248 249 AliasResult Result; 250 /// Number of times a NoAlias assumption has been used, 0 for assumptions 251 /// that have not been used. Can also take one of the Definitive or 252 /// AssumptionBased values documented above. 253 int NumAssumptionUses; 254 255 /// Whether this is a definitive (non-assumption) result. 256 bool isDefinitive() const { return NumAssumptionUses == Definitive; } 257 /// Whether this is an assumption that has not been proven yet. 258 bool isAssumption() const { return NumAssumptionUses >= 0; } 259 }; 260 261 // Alias analysis result aggregration using which this query is performed. 262 // Can be used to perform recursive queries. 263 AAResults &AAR; 264 265 using AliasCacheT = SmallDenseMap<LocPair, CacheEntry, 8>; 266 AliasCacheT AliasCache; 267 268 CaptureInfo *CI; 269 270 /// Query depth used to distinguish recursive queries. 271 unsigned Depth = 0; 272 273 /// How many active NoAlias assumption uses there are. 274 int NumAssumptionUses = 0; 275 276 /// Location pairs for which an assumption based result is currently stored. 277 /// Used to remove all potentially incorrect results from the cache if an 278 /// assumption is disproven. 279 SmallVector<AAQueryInfo::LocPair, 4> AssumptionBasedResults; 280 281 /// Tracks whether the accesses may be on different cycle iterations. 282 /// 283 /// When interpret "Value" pointer equality as value equality we need to make 284 /// sure that the "Value" is not part of a cycle. Otherwise, two uses could 285 /// come from different "iterations" of a cycle and see different values for 286 /// the same "Value" pointer. 287 /// 288 /// The following example shows the problem: 289 /// %p = phi(%alloca1, %addr2) 290 /// %l = load %ptr 291 /// %addr1 = gep, %alloca2, 0, %l 292 /// %addr2 = gep %alloca2, 0, (%l + 1) 293 /// alias(%p, %addr1) -> MayAlias ! 294 /// store %l, ... 295 bool MayBeCrossIteration = false; 296 297 /// Whether alias analysis is allowed to use the dominator tree, for use by 298 /// passes that lazily update the DT while performing AA queries. 299 bool UseDominatorTree = true; 300 301 AAQueryInfo(AAResults &AAR, CaptureInfo *CI) : AAR(AAR), CI(CI) {} 302 }; 303 304 /// AAQueryInfo that uses SimpleCaptureInfo. 305 class SimpleAAQueryInfo : public AAQueryInfo { 306 SimpleCaptureInfo CI; 307 308 public: 309 SimpleAAQueryInfo(AAResults &AAR) : AAQueryInfo(AAR, &CI) {} 310 }; 311 312 class BatchAAResults; 313 314 class AAResults { 315 public: 316 // Make these results default constructable and movable. We have to spell 317 // these out because MSVC won't synthesize them. 318 AAResults(const TargetLibraryInfo &TLI) : TLI(TLI) {} 319 AAResults(AAResults &&Arg); 320 ~AAResults(); 321 322 /// Register a specific AA result. 323 template <typename AAResultT> void addAAResult(AAResultT &AAResult) { 324 // FIXME: We should use a much lighter weight system than the usual 325 // polymorphic pattern because we don't own AAResult. It should 326 // ideally involve two pointers and no separate allocation. 327 AAs.emplace_back(new Model<AAResultT>(AAResult, *this)); 328 } 329 330 /// Register a function analysis ID that the results aggregation depends on. 331 /// 332 /// This is used in the new pass manager to implement the invalidation logic 333 /// where we must invalidate the results aggregation if any of our component 334 /// analyses become invalid. 335 void addAADependencyID(AnalysisKey *ID) { AADeps.push_back(ID); } 336 337 /// Handle invalidation events in the new pass manager. 338 /// 339 /// The aggregation is invalidated if any of the underlying analyses is 340 /// invalidated. 341 bool invalidate(Function &F, const PreservedAnalyses &PA, 342 FunctionAnalysisManager::Invalidator &Inv); 343 344 //===--------------------------------------------------------------------===// 345 /// \name Alias Queries 346 /// @{ 347 348 /// The main low level interface to the alias analysis implementation. 349 /// Returns an AliasResult indicating whether the two pointers are aliased to 350 /// each other. This is the interface that must be implemented by specific 351 /// alias analysis implementations. 352 AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB); 353 354 /// A convenience wrapper around the primary \c alias interface. 355 AliasResult alias(const Value *V1, LocationSize V1Size, const Value *V2, 356 LocationSize V2Size) { 357 return alias(MemoryLocation(V1, V1Size), MemoryLocation(V2, V2Size)); 358 } 359 360 /// A convenience wrapper around the primary \c alias interface. 361 AliasResult alias(const Value *V1, const Value *V2) { 362 return alias(MemoryLocation::getBeforeOrAfter(V1), 363 MemoryLocation::getBeforeOrAfter(V2)); 364 } 365 366 /// A trivial helper function to check to see if the specified pointers are 367 /// no-alias. 368 bool isNoAlias(const MemoryLocation &LocA, const MemoryLocation &LocB) { 369 return alias(LocA, LocB) == AliasResult::NoAlias; 370 } 371 372 /// A convenience wrapper around the \c isNoAlias helper interface. 373 bool isNoAlias(const Value *V1, LocationSize V1Size, const Value *V2, 374 LocationSize V2Size) { 375 return isNoAlias(MemoryLocation(V1, V1Size), MemoryLocation(V2, V2Size)); 376 } 377 378 /// A convenience wrapper around the \c isNoAlias helper interface. 379 bool isNoAlias(const Value *V1, const Value *V2) { 380 return isNoAlias(MemoryLocation::getBeforeOrAfter(V1), 381 MemoryLocation::getBeforeOrAfter(V2)); 382 } 383 384 /// A trivial helper function to check to see if the specified pointers are 385 /// must-alias. 386 bool isMustAlias(const MemoryLocation &LocA, const MemoryLocation &LocB) { 387 return alias(LocA, LocB) == AliasResult::MustAlias; 388 } 389 390 /// A convenience wrapper around the \c isMustAlias helper interface. 391 bool isMustAlias(const Value *V1, const Value *V2) { 392 return alias(V1, LocationSize::precise(1), V2, LocationSize::precise(1)) == 393 AliasResult::MustAlias; 394 } 395 396 /// Checks whether the given location points to constant memory, or if 397 /// \p OrLocal is true whether it points to a local alloca. 398 bool pointsToConstantMemory(const MemoryLocation &Loc, bool OrLocal = false) { 399 return isNoModRef(getModRefInfoMask(Loc, OrLocal)); 400 } 401 402 /// A convenience wrapper around the primary \c pointsToConstantMemory 403 /// interface. 404 bool pointsToConstantMemory(const Value *P, bool OrLocal = false) { 405 return pointsToConstantMemory(MemoryLocation::getBeforeOrAfter(P), OrLocal); 406 } 407 408 /// @} 409 //===--------------------------------------------------------------------===// 410 /// \name Simple mod/ref information 411 /// @{ 412 413 /// Returns a bitmask that should be unconditionally applied to the ModRef 414 /// info of a memory location. This allows us to eliminate Mod and/or Ref 415 /// from the ModRef info based on the knowledge that the memory location 416 /// points to constant and/or locally-invariant memory. 417 /// 418 /// If IgnoreLocals is true, then this method returns NoModRef for memory 419 /// that points to a local alloca. 420 ModRefInfo getModRefInfoMask(const MemoryLocation &Loc, 421 bool IgnoreLocals = false); 422 423 /// A convenience wrapper around the primary \c getModRefInfoMask 424 /// interface. 425 ModRefInfo getModRefInfoMask(const Value *P, bool IgnoreLocals = false) { 426 return getModRefInfoMask(MemoryLocation::getBeforeOrAfter(P), IgnoreLocals); 427 } 428 429 /// Get the ModRef info associated with a pointer argument of a call. The 430 /// result's bits are set to indicate the allowed aliasing ModRef kinds. Note 431 /// that these bits do not necessarily account for the overall behavior of 432 /// the function, but rather only provide additional per-argument 433 /// information. 434 ModRefInfo getArgModRefInfo(const CallBase *Call, unsigned ArgIdx); 435 436 /// Return the behavior of the given call site. 437 MemoryEffects getMemoryEffects(const CallBase *Call); 438 439 /// Return the behavior when calling the given function. 440 MemoryEffects getMemoryEffects(const Function *F); 441 442 /// Checks if the specified call is known to never read or write memory. 443 /// 444 /// Note that if the call only reads from known-constant memory, it is also 445 /// legal to return true. Also, calls that unwind the stack are legal for 446 /// this predicate. 447 /// 448 /// Many optimizations (such as CSE and LICM) can be performed on such calls 449 /// without worrying about aliasing properties, and many calls have this 450 /// property (e.g. calls to 'sin' and 'cos'). 451 /// 452 /// This property corresponds to the GCC 'const' attribute. 453 bool doesNotAccessMemory(const CallBase *Call) { 454 return getMemoryEffects(Call).doesNotAccessMemory(); 455 } 456 457 /// Checks if the specified function is known to never read or write memory. 458 /// 459 /// Note that if the function only reads from known-constant memory, it is 460 /// also legal to return true. Also, function that unwind the stack are legal 461 /// for this predicate. 462 /// 463 /// Many optimizations (such as CSE and LICM) can be performed on such calls 464 /// to such functions without worrying about aliasing properties, and many 465 /// functions have this property (e.g. 'sin' and 'cos'). 466 /// 467 /// This property corresponds to the GCC 'const' attribute. 468 bool doesNotAccessMemory(const Function *F) { 469 return getMemoryEffects(F).doesNotAccessMemory(); 470 } 471 472 /// Checks if the specified call is known to only read from non-volatile 473 /// memory (or not access memory at all). 474 /// 475 /// Calls that unwind the stack are legal for this predicate. 476 /// 477 /// This property allows many common optimizations to be performed in the 478 /// absence of interfering store instructions, such as CSE of strlen calls. 479 /// 480 /// This property corresponds to the GCC 'pure' attribute. 481 bool onlyReadsMemory(const CallBase *Call) { 482 return getMemoryEffects(Call).onlyReadsMemory(); 483 } 484 485 /// Checks if the specified function is known to only read from non-volatile 486 /// memory (or not access memory at all). 487 /// 488 /// Functions that unwind the stack are legal for this predicate. 489 /// 490 /// This property allows many common optimizations to be performed in the 491 /// absence of interfering store instructions, such as CSE of strlen calls. 492 /// 493 /// This property corresponds to the GCC 'pure' attribute. 494 bool onlyReadsMemory(const Function *F) { 495 return getMemoryEffects(F).onlyReadsMemory(); 496 } 497 498 /// Check whether or not an instruction may read or write the optionally 499 /// specified memory location. 500 /// 501 /// 502 /// An instruction that doesn't read or write memory may be trivially LICM'd 503 /// for example. 504 /// 505 /// For function calls, this delegates to the alias-analysis specific 506 /// call-site mod-ref behavior queries. Otherwise it delegates to the specific 507 /// helpers above. 508 ModRefInfo getModRefInfo(const Instruction *I, 509 const std::optional<MemoryLocation> &OptLoc) { 510 SimpleAAQueryInfo AAQIP(*this); 511 return getModRefInfo(I, OptLoc, AAQIP); 512 } 513 514 /// A convenience wrapper for constructing the memory location. 515 ModRefInfo getModRefInfo(const Instruction *I, const Value *P, 516 LocationSize Size) { 517 return getModRefInfo(I, MemoryLocation(P, Size)); 518 } 519 520 /// Return information about whether a call and an instruction may refer to 521 /// the same memory locations. 522 ModRefInfo getModRefInfo(const Instruction *I, const CallBase *Call); 523 524 /// Return information about whether a particular call site modifies 525 /// or reads the specified memory location \p MemLoc before instruction \p I 526 /// in a BasicBlock. 527 ModRefInfo callCapturesBefore(const Instruction *I, 528 const MemoryLocation &MemLoc, 529 DominatorTree *DT) { 530 SimpleAAQueryInfo AAQIP(*this); 531 return callCapturesBefore(I, MemLoc, DT, AAQIP); 532 } 533 534 /// A convenience wrapper to synthesize a memory location. 535 ModRefInfo callCapturesBefore(const Instruction *I, const Value *P, 536 LocationSize Size, DominatorTree *DT) { 537 return callCapturesBefore(I, MemoryLocation(P, Size), DT); 538 } 539 540 /// @} 541 //===--------------------------------------------------------------------===// 542 /// \name Higher level methods for querying mod/ref information. 543 /// @{ 544 545 /// Check if it is possible for execution of the specified basic block to 546 /// modify the location Loc. 547 bool canBasicBlockModify(const BasicBlock &BB, const MemoryLocation &Loc); 548 549 /// A convenience wrapper synthesizing a memory location. 550 bool canBasicBlockModify(const BasicBlock &BB, const Value *P, 551 LocationSize Size) { 552 return canBasicBlockModify(BB, MemoryLocation(P, Size)); 553 } 554 555 /// Check if it is possible for the execution of the specified instructions 556 /// to mod\ref (according to the mode) the location Loc. 557 /// 558 /// The instructions to consider are all of the instructions in the range of 559 /// [I1,I2] INCLUSIVE. I1 and I2 must be in the same basic block. 560 bool canInstructionRangeModRef(const Instruction &I1, const Instruction &I2, 561 const MemoryLocation &Loc, 562 const ModRefInfo Mode); 563 564 /// A convenience wrapper synthesizing a memory location. 565 bool canInstructionRangeModRef(const Instruction &I1, const Instruction &I2, 566 const Value *Ptr, LocationSize Size, 567 const ModRefInfo Mode) { 568 return canInstructionRangeModRef(I1, I2, MemoryLocation(Ptr, Size), Mode); 569 } 570 571 // CtxI can be nullptr, in which case the query is whether or not the aliasing 572 // relationship holds through the entire function. 573 AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB, 574 AAQueryInfo &AAQI, const Instruction *CtxI = nullptr); 575 576 ModRefInfo getModRefInfoMask(const MemoryLocation &Loc, AAQueryInfo &AAQI, 577 bool IgnoreLocals = false); 578 ModRefInfo getModRefInfo(const Instruction *I, const CallBase *Call2, 579 AAQueryInfo &AAQIP); 580 ModRefInfo getModRefInfo(const CallBase *Call, const MemoryLocation &Loc, 581 AAQueryInfo &AAQI); 582 ModRefInfo getModRefInfo(const CallBase *Call1, const CallBase *Call2, 583 AAQueryInfo &AAQI); 584 ModRefInfo getModRefInfo(const VAArgInst *V, const MemoryLocation &Loc, 585 AAQueryInfo &AAQI); 586 ModRefInfo getModRefInfo(const LoadInst *L, const MemoryLocation &Loc, 587 AAQueryInfo &AAQI); 588 ModRefInfo getModRefInfo(const StoreInst *S, const MemoryLocation &Loc, 589 AAQueryInfo &AAQI); 590 ModRefInfo getModRefInfo(const FenceInst *S, const MemoryLocation &Loc, 591 AAQueryInfo &AAQI); 592 ModRefInfo getModRefInfo(const AtomicCmpXchgInst *CX, 593 const MemoryLocation &Loc, AAQueryInfo &AAQI); 594 ModRefInfo getModRefInfo(const AtomicRMWInst *RMW, const MemoryLocation &Loc, 595 AAQueryInfo &AAQI); 596 ModRefInfo getModRefInfo(const CatchPadInst *I, const MemoryLocation &Loc, 597 AAQueryInfo &AAQI); 598 ModRefInfo getModRefInfo(const CatchReturnInst *I, const MemoryLocation &Loc, 599 AAQueryInfo &AAQI); 600 ModRefInfo getModRefInfo(const Instruction *I, 601 const std::optional<MemoryLocation> &OptLoc, 602 AAQueryInfo &AAQIP); 603 ModRefInfo callCapturesBefore(const Instruction *I, 604 const MemoryLocation &MemLoc, DominatorTree *DT, 605 AAQueryInfo &AAQIP); 606 MemoryEffects getMemoryEffects(const CallBase *Call, AAQueryInfo &AAQI); 607 608 private: 609 class Concept; 610 611 template <typename T> class Model; 612 613 friend class AAResultBase; 614 615 const TargetLibraryInfo &TLI; 616 617 std::vector<std::unique_ptr<Concept>> AAs; 618 619 std::vector<AnalysisKey *> AADeps; 620 621 friend class BatchAAResults; 622 }; 623 624 /// This class is a wrapper over an AAResults, and it is intended to be used 625 /// only when there are no IR changes inbetween queries. BatchAAResults is 626 /// reusing the same `AAQueryInfo` to preserve the state across queries, 627 /// esentially making AA work in "batch mode". The internal state cannot be 628 /// cleared, so to go "out-of-batch-mode", the user must either use AAResults, 629 /// or create a new BatchAAResults. 630 class BatchAAResults { 631 AAResults &AA; 632 AAQueryInfo AAQI; 633 SimpleCaptureInfo SimpleCI; 634 635 public: 636 BatchAAResults(AAResults &AAR) : AA(AAR), AAQI(AAR, &SimpleCI) {} 637 BatchAAResults(AAResults &AAR, CaptureInfo *CI) : AA(AAR), AAQI(AAR, CI) {} 638 639 AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB) { 640 return AA.alias(LocA, LocB, AAQI); 641 } 642 bool pointsToConstantMemory(const MemoryLocation &Loc, bool OrLocal = false) { 643 return isNoModRef(AA.getModRefInfoMask(Loc, AAQI, OrLocal)); 644 } 645 ModRefInfo getModRefInfoMask(const MemoryLocation &Loc, 646 bool IgnoreLocals = false) { 647 return AA.getModRefInfoMask(Loc, AAQI, IgnoreLocals); 648 } 649 ModRefInfo getModRefInfo(const Instruction *I, 650 const std::optional<MemoryLocation> &OptLoc) { 651 return AA.getModRefInfo(I, OptLoc, AAQI); 652 } 653 ModRefInfo getModRefInfo(const Instruction *I, const CallBase *Call2) { 654 return AA.getModRefInfo(I, Call2, AAQI); 655 } 656 ModRefInfo getArgModRefInfo(const CallBase *Call, unsigned ArgIdx) { 657 return AA.getArgModRefInfo(Call, ArgIdx); 658 } 659 MemoryEffects getMemoryEffects(const CallBase *Call) { 660 return AA.getMemoryEffects(Call, AAQI); 661 } 662 bool isMustAlias(const MemoryLocation &LocA, const MemoryLocation &LocB) { 663 return alias(LocA, LocB) == AliasResult::MustAlias; 664 } 665 bool isMustAlias(const Value *V1, const Value *V2) { 666 return alias(MemoryLocation(V1, LocationSize::precise(1)), 667 MemoryLocation(V2, LocationSize::precise(1))) == 668 AliasResult::MustAlias; 669 } 670 ModRefInfo callCapturesBefore(const Instruction *I, 671 const MemoryLocation &MemLoc, 672 DominatorTree *DT) { 673 return AA.callCapturesBefore(I, MemLoc, DT, AAQI); 674 } 675 676 /// Assume that values may come from different cycle iterations. 677 void enableCrossIterationMode() { 678 AAQI.MayBeCrossIteration = true; 679 } 680 681 /// Disable the use of the dominator tree during alias analysis queries. 682 void disableDominatorTree() { AAQI.UseDominatorTree = false; } 683 }; 684 685 /// Temporary typedef for legacy code that uses a generic \c AliasAnalysis 686 /// pointer or reference. 687 using AliasAnalysis = AAResults; 688 689 /// A private abstract base class describing the concept of an individual alias 690 /// analysis implementation. 691 /// 692 /// This interface is implemented by any \c Model instantiation. It is also the 693 /// interface which a type used to instantiate the model must provide. 694 /// 695 /// All of these methods model methods by the same name in the \c 696 /// AAResults class. Only differences and specifics to how the 697 /// implementations are called are documented here. 698 class AAResults::Concept { 699 public: 700 virtual ~Concept() = 0; 701 702 //===--------------------------------------------------------------------===// 703 /// \name Alias Queries 704 /// @{ 705 706 /// The main low level interface to the alias analysis implementation. 707 /// Returns an AliasResult indicating whether the two pointers are aliased to 708 /// each other. This is the interface that must be implemented by specific 709 /// alias analysis implementations. 710 virtual AliasResult alias(const MemoryLocation &LocA, 711 const MemoryLocation &LocB, AAQueryInfo &AAQI, 712 const Instruction *CtxI) = 0; 713 714 /// @} 715 //===--------------------------------------------------------------------===// 716 /// \name Simple mod/ref information 717 /// @{ 718 719 /// Returns a bitmask that should be unconditionally applied to the ModRef 720 /// info of a memory location. This allows us to eliminate Mod and/or Ref from 721 /// the ModRef info based on the knowledge that the memory location points to 722 /// constant and/or locally-invariant memory. 723 virtual ModRefInfo getModRefInfoMask(const MemoryLocation &Loc, 724 AAQueryInfo &AAQI, 725 bool IgnoreLocals) = 0; 726 727 /// Get the ModRef info associated with a pointer argument of a callsite. The 728 /// result's bits are set to indicate the allowed aliasing ModRef kinds. Note 729 /// that these bits do not necessarily account for the overall behavior of 730 /// the function, but rather only provide additional per-argument 731 /// information. 732 virtual ModRefInfo getArgModRefInfo(const CallBase *Call, 733 unsigned ArgIdx) = 0; 734 735 /// Return the behavior of the given call site. 736 virtual MemoryEffects getMemoryEffects(const CallBase *Call, 737 AAQueryInfo &AAQI) = 0; 738 739 /// Return the behavior when calling the given function. 740 virtual MemoryEffects getMemoryEffects(const Function *F) = 0; 741 742 /// getModRefInfo (for call sites) - Return information about whether 743 /// a particular call site modifies or reads the specified memory location. 744 virtual ModRefInfo getModRefInfo(const CallBase *Call, 745 const MemoryLocation &Loc, 746 AAQueryInfo &AAQI) = 0; 747 748 /// Return information about whether two call sites may refer to the same set 749 /// of memory locations. See the AA documentation for details: 750 /// http://llvm.org/docs/AliasAnalysis.html#ModRefInfo 751 virtual ModRefInfo getModRefInfo(const CallBase *Call1, const CallBase *Call2, 752 AAQueryInfo &AAQI) = 0; 753 754 /// @} 755 }; 756 757 /// A private class template which derives from \c Concept and wraps some other 758 /// type. 759 /// 760 /// This models the concept by directly forwarding each interface point to the 761 /// wrapped type which must implement a compatible interface. This provides 762 /// a type erased binding. 763 template <typename AAResultT> class AAResults::Model final : public Concept { 764 AAResultT &Result; 765 766 public: 767 explicit Model(AAResultT &Result, AAResults &AAR) : Result(Result) {} 768 ~Model() override = default; 769 770 AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB, 771 AAQueryInfo &AAQI, const Instruction *CtxI) override { 772 return Result.alias(LocA, LocB, AAQI, CtxI); 773 } 774 775 ModRefInfo getModRefInfoMask(const MemoryLocation &Loc, AAQueryInfo &AAQI, 776 bool IgnoreLocals) override { 777 return Result.getModRefInfoMask(Loc, AAQI, IgnoreLocals); 778 } 779 780 ModRefInfo getArgModRefInfo(const CallBase *Call, unsigned ArgIdx) override { 781 return Result.getArgModRefInfo(Call, ArgIdx); 782 } 783 784 MemoryEffects getMemoryEffects(const CallBase *Call, 785 AAQueryInfo &AAQI) override { 786 return Result.getMemoryEffects(Call, AAQI); 787 } 788 789 MemoryEffects getMemoryEffects(const Function *F) override { 790 return Result.getMemoryEffects(F); 791 } 792 793 ModRefInfo getModRefInfo(const CallBase *Call, const MemoryLocation &Loc, 794 AAQueryInfo &AAQI) override { 795 return Result.getModRefInfo(Call, Loc, AAQI); 796 } 797 798 ModRefInfo getModRefInfo(const CallBase *Call1, const CallBase *Call2, 799 AAQueryInfo &AAQI) override { 800 return Result.getModRefInfo(Call1, Call2, AAQI); 801 } 802 }; 803 804 /// A base class to help implement the function alias analysis results concept. 805 /// 806 /// Because of the nature of many alias analysis implementations, they often 807 /// only implement a subset of the interface. This base class will attempt to 808 /// implement the remaining portions of the interface in terms of simpler forms 809 /// of the interface where possible, and otherwise provide conservatively 810 /// correct fallback implementations. 811 /// 812 /// Implementors of an alias analysis should derive from this class, and then 813 /// override specific methods that they wish to customize. There is no need to 814 /// use virtual anywhere. 815 class AAResultBase { 816 protected: 817 explicit AAResultBase() = default; 818 819 // Provide all the copy and move constructors so that derived types aren't 820 // constrained. 821 AAResultBase(const AAResultBase &Arg) {} 822 AAResultBase(AAResultBase &&Arg) {} 823 824 public: 825 AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB, 826 AAQueryInfo &AAQI, const Instruction *I) { 827 return AliasResult::MayAlias; 828 } 829 830 ModRefInfo getModRefInfoMask(const MemoryLocation &Loc, AAQueryInfo &AAQI, 831 bool IgnoreLocals) { 832 return ModRefInfo::ModRef; 833 } 834 835 ModRefInfo getArgModRefInfo(const CallBase *Call, unsigned ArgIdx) { 836 return ModRefInfo::ModRef; 837 } 838 839 MemoryEffects getMemoryEffects(const CallBase *Call, AAQueryInfo &AAQI) { 840 return MemoryEffects::unknown(); 841 } 842 843 MemoryEffects getMemoryEffects(const Function *F) { 844 return MemoryEffects::unknown(); 845 } 846 847 ModRefInfo getModRefInfo(const CallBase *Call, const MemoryLocation &Loc, 848 AAQueryInfo &AAQI) { 849 return ModRefInfo::ModRef; 850 } 851 852 ModRefInfo getModRefInfo(const CallBase *Call1, const CallBase *Call2, 853 AAQueryInfo &AAQI) { 854 return ModRefInfo::ModRef; 855 } 856 }; 857 858 /// Return true if this pointer is returned by a noalias function. 859 bool isNoAliasCall(const Value *V); 860 861 /// Return true if this pointer refers to a distinct and identifiable object. 862 /// This returns true for: 863 /// Global Variables and Functions (but not Global Aliases) 864 /// Allocas 865 /// ByVal and NoAlias Arguments 866 /// NoAlias returns (e.g. calls to malloc) 867 /// 868 bool isIdentifiedObject(const Value *V); 869 870 /// Return true if V is umabigously identified at the function-level. 871 /// Different IdentifiedFunctionLocals can't alias. 872 /// Further, an IdentifiedFunctionLocal can not alias with any function 873 /// arguments other than itself, which is not necessarily true for 874 /// IdentifiedObjects. 875 bool isIdentifiedFunctionLocal(const Value *V); 876 877 /// Returns true if the pointer is one which would have been considered an 878 /// escape by isNonEscapingLocalObject. 879 bool isEscapeSource(const Value *V); 880 881 /// Return true if Object memory is not visible after an unwind, in the sense 882 /// that program semantics cannot depend on Object containing any particular 883 /// value on unwind. If the RequiresNoCaptureBeforeUnwind out parameter is set 884 /// to true, then the memory is only not visible if the object has not been 885 /// captured prior to the unwind. Otherwise it is not visible even if captured. 886 bool isNotVisibleOnUnwind(const Value *Object, 887 bool &RequiresNoCaptureBeforeUnwind); 888 889 /// Return true if the Object is writable, in the sense that any location based 890 /// on this pointer that can be loaded can also be stored to without trapping. 891 /// Additionally, at the point Object is declared, stores can be introduced 892 /// without data races. At later points, this is only the case if the pointer 893 /// can not escape to a different thread. 894 /// 895 /// If ExplicitlyDereferenceableOnly is set to true, this property only holds 896 /// for the part of Object that is explicitly marked as dereferenceable, e.g. 897 /// using the dereferenceable(N) attribute. It does not necessarily hold for 898 /// parts that are only known to be dereferenceable due to the presence of 899 /// loads. 900 bool isWritableObject(const Value *Object, bool &ExplicitlyDereferenceableOnly); 901 902 /// A manager for alias analyses. 903 /// 904 /// This class can have analyses registered with it and when run, it will run 905 /// all of them and aggregate their results into single AA results interface 906 /// that dispatches across all of the alias analysis results available. 907 /// 908 /// Note that the order in which analyses are registered is very significant. 909 /// That is the order in which the results will be aggregated and queried. 910 /// 911 /// This manager effectively wraps the AnalysisManager for registering alias 912 /// analyses. When you register your alias analysis with this manager, it will 913 /// ensure the analysis itself is registered with its AnalysisManager. 914 /// 915 /// The result of this analysis is only invalidated if one of the particular 916 /// aggregated AA results end up being invalidated. This removes the need to 917 /// explicitly preserve the results of `AAManager`. Note that analyses should no 918 /// longer be registered once the `AAManager` is run. 919 class AAManager : public AnalysisInfoMixin<AAManager> { 920 public: 921 using Result = AAResults; 922 923 /// Register a specific AA result. 924 template <typename AnalysisT> void registerFunctionAnalysis() { 925 ResultGetters.push_back(&getFunctionAAResultImpl<AnalysisT>); 926 } 927 928 /// Register a specific AA result. 929 template <typename AnalysisT> void registerModuleAnalysis() { 930 ResultGetters.push_back(&getModuleAAResultImpl<AnalysisT>); 931 } 932 933 Result run(Function &F, FunctionAnalysisManager &AM); 934 935 private: 936 friend AnalysisInfoMixin<AAManager>; 937 938 static AnalysisKey Key; 939 940 SmallVector<void (*)(Function &F, FunctionAnalysisManager &AM, 941 AAResults &AAResults), 942 4> ResultGetters; 943 944 template <typename AnalysisT> 945 static void getFunctionAAResultImpl(Function &F, 946 FunctionAnalysisManager &AM, 947 AAResults &AAResults) { 948 AAResults.addAAResult(AM.template getResult<AnalysisT>(F)); 949 AAResults.addAADependencyID(AnalysisT::ID()); 950 } 951 952 template <typename AnalysisT> 953 static void getModuleAAResultImpl(Function &F, FunctionAnalysisManager &AM, 954 AAResults &AAResults) { 955 auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F); 956 if (auto *R = 957 MAMProxy.template getCachedResult<AnalysisT>(*F.getParent())) { 958 AAResults.addAAResult(*R); 959 MAMProxy 960 .template registerOuterAnalysisInvalidation<AnalysisT, AAManager>(); 961 } 962 } 963 }; 964 965 /// A wrapper pass to provide the legacy pass manager access to a suitably 966 /// prepared AAResults object. 967 class AAResultsWrapperPass : public FunctionPass { 968 std::unique_ptr<AAResults> AAR; 969 970 public: 971 static char ID; 972 973 AAResultsWrapperPass(); 974 975 AAResults &getAAResults() { return *AAR; } 976 const AAResults &getAAResults() const { return *AAR; } 977 978 bool runOnFunction(Function &F) override; 979 980 void getAnalysisUsage(AnalysisUsage &AU) const override; 981 }; 982 983 /// A wrapper pass for external alias analyses. This just squirrels away the 984 /// callback used to run any analyses and register their results. 985 struct ExternalAAWrapperPass : ImmutablePass { 986 using CallbackT = std::function<void(Pass &, Function &, AAResults &)>; 987 988 CallbackT CB; 989 990 static char ID; 991 992 ExternalAAWrapperPass(); 993 994 explicit ExternalAAWrapperPass(CallbackT CB); 995 996 void getAnalysisUsage(AnalysisUsage &AU) const override { 997 AU.setPreservesAll(); 998 } 999 }; 1000 1001 /// A wrapper pass around a callback which can be used to populate the 1002 /// AAResults in the AAResultsWrapperPass from an external AA. 1003 /// 1004 /// The callback provided here will be used each time we prepare an AAResults 1005 /// object, and will receive a reference to the function wrapper pass, the 1006 /// function, and the AAResults object to populate. This should be used when 1007 /// setting up a custom pass pipeline to inject a hook into the AA results. 1008 ImmutablePass *createExternalAAWrapperPass( 1009 std::function<void(Pass &, Function &, AAResults &)> Callback); 1010 1011 } // end namespace llvm 1012 1013 #endif // LLVM_ANALYSIS_ALIASANALYSIS_H 1014