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; 108 constexpr AliasResult(const Kind &Alias) 109 : Alias(Alias), HasOffset(false), Offset(0) {} 110 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 122 constexpr bool hasOffset() const { return HasOffset; } 123 constexpr int32_t getOffset() const { 124 assert(HasOffset && "No offset!"); 125 return Offset; 126 } 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 analysis. 148 struct CaptureAnalysis { 149 virtual ~CaptureAnalysis() = 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 CaptureAnalysis 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 SimpleCaptureAnalysis final : public CaptureAnalysis { 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 CaptureAnalysis 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 EarliestEscapeAnalysis final : public CaptureAnalysis { 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 EarliestEscapeAnalysis(DominatorTree &DT, const LoopInfo *LI = nullptr) 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 205 AACacheLoc(PtrTy Ptr, LocationSize Size) : Ptr(Ptr), Size(Size) {} 206 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 CaptureAnalysis *CA; 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, CaptureAnalysis *CA) : AAR(AAR), CA(CA) {} 302 }; 303 304 /// AAQueryInfo that uses SimpleCaptureAnalysis. 305 class SimpleAAQueryInfo : public AAQueryInfo { 306 SimpleCaptureAnalysis CA; 307 308 public: 309 SimpleAAQueryInfo(AAResults &AAR) : AAQueryInfo(AAR, &CA) {} 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); 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 SimpleCaptureAnalysis SimpleCA; 634 635 public: 636 BatchAAResults(AAResults &AAR) : AA(AAR), AAQI(AAR, &SimpleCA) {} 637 BatchAAResults(AAResults &AAR, CaptureAnalysis *CA) 638 : AA(AAR), AAQI(AAR, CA) {} 639 640 AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB) { 641 return AA.alias(LocA, LocB, AAQI); 642 } 643 bool pointsToConstantMemory(const MemoryLocation &Loc, bool OrLocal = false) { 644 return isNoModRef(AA.getModRefInfoMask(Loc, AAQI, OrLocal)); 645 } 646 bool pointsToConstantMemory(const Value *P, bool OrLocal = false) { 647 return pointsToConstantMemory(MemoryLocation::getBeforeOrAfter(P), OrLocal); 648 } 649 ModRefInfo getModRefInfoMask(const MemoryLocation &Loc, 650 bool IgnoreLocals = false) { 651 return AA.getModRefInfoMask(Loc, AAQI, IgnoreLocals); 652 } 653 ModRefInfo getModRefInfo(const Instruction *I, 654 const std::optional<MemoryLocation> &OptLoc) { 655 return AA.getModRefInfo(I, OptLoc, AAQI); 656 } 657 ModRefInfo getModRefInfo(const Instruction *I, const CallBase *Call2) { 658 return AA.getModRefInfo(I, Call2, AAQI); 659 } 660 ModRefInfo getArgModRefInfo(const CallBase *Call, unsigned ArgIdx) { 661 return AA.getArgModRefInfo(Call, ArgIdx); 662 } 663 MemoryEffects getMemoryEffects(const CallBase *Call) { 664 return AA.getMemoryEffects(Call, AAQI); 665 } 666 bool isMustAlias(const MemoryLocation &LocA, const MemoryLocation &LocB) { 667 return alias(LocA, LocB) == AliasResult::MustAlias; 668 } 669 bool isMustAlias(const Value *V1, const Value *V2) { 670 return alias(MemoryLocation(V1, LocationSize::precise(1)), 671 MemoryLocation(V2, LocationSize::precise(1))) == 672 AliasResult::MustAlias; 673 } 674 bool isNoAlias(const MemoryLocation &LocA, const MemoryLocation &LocB) { 675 return alias(LocA, LocB) == AliasResult::NoAlias; 676 } 677 ModRefInfo callCapturesBefore(const Instruction *I, 678 const MemoryLocation &MemLoc, 679 DominatorTree *DT) { 680 return AA.callCapturesBefore(I, MemLoc, DT, AAQI); 681 } 682 683 /// Assume that values may come from different cycle iterations. 684 void enableCrossIterationMode() { 685 AAQI.MayBeCrossIteration = true; 686 } 687 688 /// Disable the use of the dominator tree during alias analysis queries. 689 void disableDominatorTree() { AAQI.UseDominatorTree = false; } 690 }; 691 692 /// Temporary typedef for legacy code that uses a generic \c AliasAnalysis 693 /// pointer or reference. 694 using AliasAnalysis = AAResults; 695 696 /// A private abstract base class describing the concept of an individual alias 697 /// analysis implementation. 698 /// 699 /// This interface is implemented by any \c Model instantiation. It is also the 700 /// interface which a type used to instantiate the model must provide. 701 /// 702 /// All of these methods model methods by the same name in the \c 703 /// AAResults class. Only differences and specifics to how the 704 /// implementations are called are documented here. 705 class AAResults::Concept { 706 public: 707 virtual ~Concept() = 0; 708 709 //===--------------------------------------------------------------------===// 710 /// \name Alias Queries 711 /// @{ 712 713 /// The main low level interface to the alias analysis implementation. 714 /// Returns an AliasResult indicating whether the two pointers are aliased to 715 /// each other. This is the interface that must be implemented by specific 716 /// alias analysis implementations. 717 virtual AliasResult alias(const MemoryLocation &LocA, 718 const MemoryLocation &LocB, AAQueryInfo &AAQI, 719 const Instruction *CtxI) = 0; 720 721 /// @} 722 //===--------------------------------------------------------------------===// 723 /// \name Simple mod/ref information 724 /// @{ 725 726 /// Returns a bitmask that should be unconditionally applied to the ModRef 727 /// info of a memory location. This allows us to eliminate Mod and/or Ref from 728 /// the ModRef info based on the knowledge that the memory location points to 729 /// constant and/or locally-invariant memory. 730 virtual ModRefInfo getModRefInfoMask(const MemoryLocation &Loc, 731 AAQueryInfo &AAQI, 732 bool IgnoreLocals) = 0; 733 734 /// Get the ModRef info associated with a pointer argument of a callsite. The 735 /// result's bits are set to indicate the allowed aliasing ModRef kinds. Note 736 /// that these bits do not necessarily account for the overall behavior of 737 /// the function, but rather only provide additional per-argument 738 /// information. 739 virtual ModRefInfo getArgModRefInfo(const CallBase *Call, 740 unsigned ArgIdx) = 0; 741 742 /// Return the behavior of the given call site. 743 virtual MemoryEffects getMemoryEffects(const CallBase *Call, 744 AAQueryInfo &AAQI) = 0; 745 746 /// Return the behavior when calling the given function. 747 virtual MemoryEffects getMemoryEffects(const Function *F) = 0; 748 749 /// getModRefInfo (for call sites) - Return information about whether 750 /// a particular call site modifies or reads the specified memory location. 751 virtual ModRefInfo getModRefInfo(const CallBase *Call, 752 const MemoryLocation &Loc, 753 AAQueryInfo &AAQI) = 0; 754 755 /// Return information about whether two call sites may refer to the same set 756 /// of memory locations. See the AA documentation for details: 757 /// http://llvm.org/docs/AliasAnalysis.html#ModRefInfo 758 virtual ModRefInfo getModRefInfo(const CallBase *Call1, const CallBase *Call2, 759 AAQueryInfo &AAQI) = 0; 760 761 /// @} 762 }; 763 764 /// A private class template which derives from \c Concept and wraps some other 765 /// type. 766 /// 767 /// This models the concept by directly forwarding each interface point to the 768 /// wrapped type which must implement a compatible interface. This provides 769 /// a type erased binding. 770 template <typename AAResultT> class AAResults::Model final : public Concept { 771 AAResultT &Result; 772 773 public: 774 explicit Model(AAResultT &Result, AAResults &AAR) : Result(Result) {} 775 ~Model() override = default; 776 777 AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB, 778 AAQueryInfo &AAQI, const Instruction *CtxI) override { 779 return Result.alias(LocA, LocB, AAQI, CtxI); 780 } 781 782 ModRefInfo getModRefInfoMask(const MemoryLocation &Loc, AAQueryInfo &AAQI, 783 bool IgnoreLocals) override { 784 return Result.getModRefInfoMask(Loc, AAQI, IgnoreLocals); 785 } 786 787 ModRefInfo getArgModRefInfo(const CallBase *Call, unsigned ArgIdx) override { 788 return Result.getArgModRefInfo(Call, ArgIdx); 789 } 790 791 MemoryEffects getMemoryEffects(const CallBase *Call, 792 AAQueryInfo &AAQI) override { 793 return Result.getMemoryEffects(Call, AAQI); 794 } 795 796 MemoryEffects getMemoryEffects(const Function *F) override { 797 return Result.getMemoryEffects(F); 798 } 799 800 ModRefInfo getModRefInfo(const CallBase *Call, const MemoryLocation &Loc, 801 AAQueryInfo &AAQI) override { 802 return Result.getModRefInfo(Call, Loc, AAQI); 803 } 804 805 ModRefInfo getModRefInfo(const CallBase *Call1, const CallBase *Call2, 806 AAQueryInfo &AAQI) override { 807 return Result.getModRefInfo(Call1, Call2, AAQI); 808 } 809 }; 810 811 /// A base class to help implement the function alias analysis results concept. 812 /// 813 /// Because of the nature of many alias analysis implementations, they often 814 /// only implement a subset of the interface. This base class will attempt to 815 /// implement the remaining portions of the interface in terms of simpler forms 816 /// of the interface where possible, and otherwise provide conservatively 817 /// correct fallback implementations. 818 /// 819 /// Implementors of an alias analysis should derive from this class, and then 820 /// override specific methods that they wish to customize. There is no need to 821 /// use virtual anywhere. 822 class AAResultBase { 823 protected: 824 explicit AAResultBase() = default; 825 826 // Provide all the copy and move constructors so that derived types aren't 827 // constrained. 828 AAResultBase(const AAResultBase &Arg) {} 829 AAResultBase(AAResultBase &&Arg) {} 830 831 public: 832 AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB, 833 AAQueryInfo &AAQI, const Instruction *I) { 834 return AliasResult::MayAlias; 835 } 836 837 ModRefInfo getModRefInfoMask(const MemoryLocation &Loc, AAQueryInfo &AAQI, 838 bool IgnoreLocals) { 839 return ModRefInfo::ModRef; 840 } 841 842 ModRefInfo getArgModRefInfo(const CallBase *Call, unsigned ArgIdx) { 843 return ModRefInfo::ModRef; 844 } 845 846 MemoryEffects getMemoryEffects(const CallBase *Call, AAQueryInfo &AAQI) { 847 return MemoryEffects::unknown(); 848 } 849 850 MemoryEffects getMemoryEffects(const Function *F) { 851 return MemoryEffects::unknown(); 852 } 853 854 ModRefInfo getModRefInfo(const CallBase *Call, const MemoryLocation &Loc, 855 AAQueryInfo &AAQI) { 856 return ModRefInfo::ModRef; 857 } 858 859 ModRefInfo getModRefInfo(const CallBase *Call1, const CallBase *Call2, 860 AAQueryInfo &AAQI) { 861 return ModRefInfo::ModRef; 862 } 863 }; 864 865 /// Return true if this pointer is returned by a noalias function. 866 bool isNoAliasCall(const Value *V); 867 868 /// Return true if this pointer refers to a distinct and identifiable object. 869 /// This returns true for: 870 /// Global Variables and Functions (but not Global Aliases) 871 /// Allocas 872 /// ByVal and NoAlias Arguments 873 /// NoAlias returns (e.g. calls to malloc) 874 /// 875 bool isIdentifiedObject(const Value *V); 876 877 /// Return true if V is umabigously identified at the function-level. 878 /// Different IdentifiedFunctionLocals can't alias. 879 /// Further, an IdentifiedFunctionLocal can not alias with any function 880 /// arguments other than itself, which is not necessarily true for 881 /// IdentifiedObjects. 882 bool isIdentifiedFunctionLocal(const Value *V); 883 884 /// Return true if we know V to the base address of the corresponding memory 885 /// object. This implies that any address less than V must be out of bounds 886 /// for the underlying object. Note that just being isIdentifiedObject() is 887 /// not enough - For example, a negative offset from a noalias argument or call 888 /// can be inbounds w.r.t the actual underlying object. 889 bool isBaseOfObject(const Value *V); 890 891 /// Returns true if the pointer is one which would have been considered an 892 /// escape by isNonEscapingLocalObject. 893 bool isEscapeSource(const Value *V); 894 895 /// Return true if Object memory is not visible after an unwind, in the sense 896 /// that program semantics cannot depend on Object containing any particular 897 /// value on unwind. If the RequiresNoCaptureBeforeUnwind out parameter is set 898 /// to true, then the memory is only not visible if the object has not been 899 /// captured prior to the unwind. Otherwise it is not visible even if captured. 900 bool isNotVisibleOnUnwind(const Value *Object, 901 bool &RequiresNoCaptureBeforeUnwind); 902 903 /// Return true if the Object is writable, in the sense that any location based 904 /// on this pointer that can be loaded can also be stored to without trapping. 905 /// Additionally, at the point Object is declared, stores can be introduced 906 /// without data races. At later points, this is only the case if the pointer 907 /// can not escape to a different thread. 908 /// 909 /// If ExplicitlyDereferenceableOnly is set to true, this property only holds 910 /// for the part of Object that is explicitly marked as dereferenceable, e.g. 911 /// using the dereferenceable(N) attribute. It does not necessarily hold for 912 /// parts that are only known to be dereferenceable due to the presence of 913 /// loads. 914 bool isWritableObject(const Value *Object, bool &ExplicitlyDereferenceableOnly); 915 916 /// A manager for alias analyses. 917 /// 918 /// This class can have analyses registered with it and when run, it will run 919 /// all of them and aggregate their results into single AA results interface 920 /// that dispatches across all of the alias analysis results available. 921 /// 922 /// Note that the order in which analyses are registered is very significant. 923 /// That is the order in which the results will be aggregated and queried. 924 /// 925 /// This manager effectively wraps the AnalysisManager for registering alias 926 /// analyses. When you register your alias analysis with this manager, it will 927 /// ensure the analysis itself is registered with its AnalysisManager. 928 /// 929 /// The result of this analysis is only invalidated if one of the particular 930 /// aggregated AA results end up being invalidated. This removes the need to 931 /// explicitly preserve the results of `AAManager`. Note that analyses should no 932 /// longer be registered once the `AAManager` is run. 933 class AAManager : public AnalysisInfoMixin<AAManager> { 934 public: 935 using Result = AAResults; 936 937 /// Register a specific AA result. 938 template <typename AnalysisT> void registerFunctionAnalysis() { 939 ResultGetters.push_back(&getFunctionAAResultImpl<AnalysisT>); 940 } 941 942 /// Register a specific AA result. 943 template <typename AnalysisT> void registerModuleAnalysis() { 944 ResultGetters.push_back(&getModuleAAResultImpl<AnalysisT>); 945 } 946 947 Result run(Function &F, FunctionAnalysisManager &AM); 948 949 private: 950 friend AnalysisInfoMixin<AAManager>; 951 952 static AnalysisKey Key; 953 954 SmallVector<void (*)(Function &F, FunctionAnalysisManager &AM, 955 AAResults &AAResults), 956 4> ResultGetters; 957 958 template <typename AnalysisT> 959 static void getFunctionAAResultImpl(Function &F, 960 FunctionAnalysisManager &AM, 961 AAResults &AAResults) { 962 AAResults.addAAResult(AM.template getResult<AnalysisT>(F)); 963 AAResults.addAADependencyID(AnalysisT::ID()); 964 } 965 966 template <typename AnalysisT> 967 static void getModuleAAResultImpl(Function &F, FunctionAnalysisManager &AM, 968 AAResults &AAResults) { 969 auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F); 970 if (auto *R = 971 MAMProxy.template getCachedResult<AnalysisT>(*F.getParent())) { 972 AAResults.addAAResult(*R); 973 MAMProxy 974 .template registerOuterAnalysisInvalidation<AnalysisT, AAManager>(); 975 } 976 } 977 }; 978 979 /// A wrapper pass to provide the legacy pass manager access to a suitably 980 /// prepared AAResults object. 981 class AAResultsWrapperPass : public FunctionPass { 982 std::unique_ptr<AAResults> AAR; 983 984 public: 985 static char ID; 986 987 AAResultsWrapperPass(); 988 989 AAResults &getAAResults() { return *AAR; } 990 const AAResults &getAAResults() const { return *AAR; } 991 992 bool runOnFunction(Function &F) override; 993 994 void getAnalysisUsage(AnalysisUsage &AU) const override; 995 }; 996 997 /// A wrapper pass for external alias analyses. This just squirrels away the 998 /// callback used to run any analyses and register their results. 999 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 1028