1 //==- AliasAnalysis.cpp - Generic Alias Analysis Interface Implementation --==// 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 implements the generic AliasAnalysis interface which is used as the 10 // common interface used by all clients and implementations of alias analysis. 11 // 12 // This file also implements the default version of the AliasAnalysis interface 13 // that is to be used when no other implementation is specified. This does some 14 // simple tests that detect obvious cases: two different global pointers cannot 15 // alias, a global cannot alias a malloc, two different mallocs cannot alias, 16 // etc. 17 // 18 // This alias analysis implementation really isn't very good for anything, but 19 // it is very fast, and makes a nice clean default implementation. Because it 20 // handles lots of little corner cases, other, more complex, alias analysis 21 // implementations may choose to rely on this pass to resolve these simple and 22 // easy cases. 23 // 24 //===----------------------------------------------------------------------===// 25 26 #include "llvm/Analysis/AliasAnalysis.h" 27 #include "llvm/ADT/Statistic.h" 28 #include "llvm/Analysis/BasicAliasAnalysis.h" 29 #include "llvm/Analysis/CaptureTracking.h" 30 #include "llvm/Analysis/GlobalsModRef.h" 31 #include "llvm/Analysis/MemoryLocation.h" 32 #include "llvm/Analysis/ObjCARCAliasAnalysis.h" 33 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h" 34 #include "llvm/Analysis/ScopedNoAliasAA.h" 35 #include "llvm/Analysis/TargetLibraryInfo.h" 36 #include "llvm/Analysis/TypeBasedAliasAnalysis.h" 37 #include "llvm/Analysis/ValueTracking.h" 38 #include "llvm/IR/Argument.h" 39 #include "llvm/IR/Attributes.h" 40 #include "llvm/IR/BasicBlock.h" 41 #include "llvm/IR/Instruction.h" 42 #include "llvm/IR/Instructions.h" 43 #include "llvm/IR/Type.h" 44 #include "llvm/IR/Value.h" 45 #include "llvm/InitializePasses.h" 46 #include "llvm/Pass.h" 47 #include "llvm/Support/AtomicOrdering.h" 48 #include "llvm/Support/Casting.h" 49 #include "llvm/Support/CommandLine.h" 50 #include <algorithm> 51 #include <cassert> 52 #include <functional> 53 #include <iterator> 54 55 #define DEBUG_TYPE "aa" 56 57 using namespace llvm; 58 59 STATISTIC(NumNoAlias, "Number of NoAlias results"); 60 STATISTIC(NumMayAlias, "Number of MayAlias results"); 61 STATISTIC(NumMustAlias, "Number of MustAlias results"); 62 63 namespace llvm { 64 /// Allow disabling BasicAA from the AA results. This is particularly useful 65 /// when testing to isolate a single AA implementation. 66 cl::opt<bool> DisableBasicAA("disable-basic-aa", cl::Hidden, cl::init(false)); 67 } // namespace llvm 68 69 #ifndef NDEBUG 70 /// Print a trace of alias analysis queries and their results. 71 static cl::opt<bool> EnableAATrace("aa-trace", cl::Hidden, cl::init(false)); 72 #else 73 static const bool EnableAATrace = false; 74 #endif 75 76 AAResults::AAResults(const TargetLibraryInfo &TLI) : TLI(TLI) {} 77 78 AAResults::AAResults(AAResults &&Arg) 79 : TLI(Arg.TLI), AAs(std::move(Arg.AAs)), AADeps(std::move(Arg.AADeps)) {} 80 81 AAResults::~AAResults() {} 82 83 bool AAResults::invalidate(Function &F, const PreservedAnalyses &PA, 84 FunctionAnalysisManager::Invalidator &Inv) { 85 // AAResults preserves the AAManager by default, due to the stateless nature 86 // of AliasAnalysis. There is no need to check whether it has been preserved 87 // explicitly. Check if any module dependency was invalidated and caused the 88 // AAManager to be invalidated. Invalidate ourselves in that case. 89 auto PAC = PA.getChecker<AAManager>(); 90 if (!PAC.preservedWhenStateless()) 91 return true; 92 93 // Check if any of the function dependencies were invalidated, and invalidate 94 // ourselves in that case. 95 for (AnalysisKey *ID : AADeps) 96 if (Inv.invalidate(ID, F, PA)) 97 return true; 98 99 // Everything we depend on is still fine, so are we. Nothing to invalidate. 100 return false; 101 } 102 103 //===----------------------------------------------------------------------===// 104 // Default chaining methods 105 //===----------------------------------------------------------------------===// 106 107 AliasResult AAResults::alias(const MemoryLocation &LocA, 108 const MemoryLocation &LocB) { 109 SimpleAAQueryInfo AAQIP(*this); 110 return alias(LocA, LocB, AAQIP, nullptr); 111 } 112 113 AliasResult AAResults::alias(const MemoryLocation &LocA, 114 const MemoryLocation &LocB, AAQueryInfo &AAQI, 115 const Instruction *CtxI) { 116 AliasResult Result = AliasResult::MayAlias; 117 118 if (EnableAATrace) { 119 for (unsigned I = 0; I < AAQI.Depth; ++I) 120 dbgs() << " "; 121 dbgs() << "Start " << *LocA.Ptr << " @ " << LocA.Size << ", " 122 << *LocB.Ptr << " @ " << LocB.Size << "\n"; 123 } 124 125 AAQI.Depth++; 126 for (const auto &AA : AAs) { 127 Result = AA->alias(LocA, LocB, AAQI, CtxI); 128 if (Result != AliasResult::MayAlias) 129 break; 130 } 131 AAQI.Depth--; 132 133 if (EnableAATrace) { 134 for (unsigned I = 0; I < AAQI.Depth; ++I) 135 dbgs() << " "; 136 dbgs() << "End " << *LocA.Ptr << " @ " << LocA.Size << ", " 137 << *LocB.Ptr << " @ " << LocB.Size << " = " << Result << "\n"; 138 } 139 140 if (AAQI.Depth == 0) { 141 if (Result == AliasResult::NoAlias) 142 ++NumNoAlias; 143 else if (Result == AliasResult::MustAlias) 144 ++NumMustAlias; 145 else 146 ++NumMayAlias; 147 } 148 return Result; 149 } 150 151 ModRefInfo AAResults::getModRefInfoMask(const MemoryLocation &Loc, 152 bool IgnoreLocals) { 153 SimpleAAQueryInfo AAQIP(*this); 154 return getModRefInfoMask(Loc, AAQIP, IgnoreLocals); 155 } 156 157 ModRefInfo AAResults::getModRefInfoMask(const MemoryLocation &Loc, 158 AAQueryInfo &AAQI, bool IgnoreLocals) { 159 ModRefInfo Result = ModRefInfo::ModRef; 160 161 for (const auto &AA : AAs) { 162 Result &= AA->getModRefInfoMask(Loc, AAQI, IgnoreLocals); 163 164 // Early-exit the moment we reach the bottom of the lattice. 165 if (isNoModRef(Result)) 166 return ModRefInfo::NoModRef; 167 } 168 169 return Result; 170 } 171 172 ModRefInfo AAResults::getArgModRefInfo(const CallBase *Call, unsigned ArgIdx) { 173 ModRefInfo Result = ModRefInfo::ModRef; 174 175 for (const auto &AA : AAs) { 176 Result &= AA->getArgModRefInfo(Call, ArgIdx); 177 178 // Early-exit the moment we reach the bottom of the lattice. 179 if (isNoModRef(Result)) 180 return ModRefInfo::NoModRef; 181 } 182 183 return Result; 184 } 185 186 ModRefInfo AAResults::getModRefInfo(const Instruction *I, 187 const CallBase *Call2) { 188 SimpleAAQueryInfo AAQIP(*this); 189 return getModRefInfo(I, Call2, AAQIP); 190 } 191 192 ModRefInfo AAResults::getModRefInfo(const Instruction *I, const CallBase *Call2, 193 AAQueryInfo &AAQI) { 194 // We may have two calls. 195 if (const auto *Call1 = dyn_cast<CallBase>(I)) { 196 // Check if the two calls modify the same memory. 197 return getModRefInfo(Call1, Call2, AAQI); 198 } 199 // If this is a fence, just return ModRef. 200 if (I->isFenceLike()) 201 return ModRefInfo::ModRef; 202 // Otherwise, check if the call modifies or references the 203 // location this memory access defines. The best we can say 204 // is that if the call references what this instruction 205 // defines, it must be clobbered by this location. 206 const MemoryLocation DefLoc = MemoryLocation::get(I); 207 ModRefInfo MR = getModRefInfo(Call2, DefLoc, AAQI); 208 if (isModOrRefSet(MR)) 209 return ModRefInfo::ModRef; 210 return ModRefInfo::NoModRef; 211 } 212 213 ModRefInfo AAResults::getModRefInfo(const CallBase *Call, 214 const MemoryLocation &Loc, 215 AAQueryInfo &AAQI) { 216 ModRefInfo Result = ModRefInfo::ModRef; 217 218 for (const auto &AA : AAs) { 219 Result &= AA->getModRefInfo(Call, Loc, AAQI); 220 221 // Early-exit the moment we reach the bottom of the lattice. 222 if (isNoModRef(Result)) 223 return ModRefInfo::NoModRef; 224 } 225 226 // Try to refine the mod-ref info further using other API entry points to the 227 // aggregate set of AA results. 228 229 // We can completely ignore inaccessible memory here, because MemoryLocations 230 // can only reference accessible memory. 231 auto ME = getMemoryEffects(Call, AAQI) 232 .getWithoutLoc(IRMemLocation::InaccessibleMem); 233 if (ME.doesNotAccessMemory()) 234 return ModRefInfo::NoModRef; 235 236 ModRefInfo ArgMR = ME.getModRef(IRMemLocation::ArgMem); 237 ModRefInfo OtherMR = ME.getWithoutLoc(IRMemLocation::ArgMem).getModRef(); 238 if ((ArgMR | OtherMR) != OtherMR) { 239 // Refine the modref info for argument memory. We only bother to do this 240 // if ArgMR is not a subset of OtherMR, otherwise this won't have an impact 241 // on the final result. 242 ModRefInfo AllArgsMask = ModRefInfo::NoModRef; 243 for (const auto &I : llvm::enumerate(Call->args())) { 244 const Value *Arg = I.value(); 245 if (!Arg->getType()->isPointerTy()) 246 continue; 247 unsigned ArgIdx = I.index(); 248 MemoryLocation ArgLoc = MemoryLocation::getForArgument(Call, ArgIdx, TLI); 249 AliasResult ArgAlias = alias(ArgLoc, Loc, AAQI, Call); 250 if (ArgAlias != AliasResult::NoAlias) 251 AllArgsMask |= getArgModRefInfo(Call, ArgIdx); 252 } 253 ArgMR &= AllArgsMask; 254 } 255 256 Result &= ArgMR | OtherMR; 257 258 // Apply the ModRef mask. This ensures that if Loc is a constant memory 259 // location, we take into account the fact that the call definitely could not 260 // modify the memory location. 261 if (!isNoModRef(Result)) 262 Result &= getModRefInfoMask(Loc); 263 264 return Result; 265 } 266 267 ModRefInfo AAResults::getModRefInfo(const CallBase *Call1, 268 const CallBase *Call2, AAQueryInfo &AAQI) { 269 ModRefInfo Result = ModRefInfo::ModRef; 270 271 for (const auto &AA : AAs) { 272 Result &= AA->getModRefInfo(Call1, Call2, AAQI); 273 274 // Early-exit the moment we reach the bottom of the lattice. 275 if (isNoModRef(Result)) 276 return ModRefInfo::NoModRef; 277 } 278 279 // Try to refine the mod-ref info further using other API entry points to the 280 // aggregate set of AA results. 281 282 // If Call1 or Call2 are readnone, they don't interact. 283 auto Call1B = getMemoryEffects(Call1, AAQI); 284 if (Call1B.doesNotAccessMemory()) 285 return ModRefInfo::NoModRef; 286 287 auto Call2B = getMemoryEffects(Call2, AAQI); 288 if (Call2B.doesNotAccessMemory()) 289 return ModRefInfo::NoModRef; 290 291 // If they both only read from memory, there is no dependence. 292 if (Call1B.onlyReadsMemory() && Call2B.onlyReadsMemory()) 293 return ModRefInfo::NoModRef; 294 295 // If Call1 only reads memory, the only dependence on Call2 can be 296 // from Call1 reading memory written by Call2. 297 if (Call1B.onlyReadsMemory()) 298 Result &= ModRefInfo::Ref; 299 else if (Call1B.onlyWritesMemory()) 300 Result &= ModRefInfo::Mod; 301 302 // If Call2 only access memory through arguments, accumulate the mod/ref 303 // information from Call1's references to the memory referenced by 304 // Call2's arguments. 305 if (Call2B.onlyAccessesArgPointees()) { 306 if (!Call2B.doesAccessArgPointees()) 307 return ModRefInfo::NoModRef; 308 ModRefInfo R = ModRefInfo::NoModRef; 309 for (auto I = Call2->arg_begin(), E = Call2->arg_end(); I != E; ++I) { 310 const Value *Arg = *I; 311 if (!Arg->getType()->isPointerTy()) 312 continue; 313 unsigned Call2ArgIdx = std::distance(Call2->arg_begin(), I); 314 auto Call2ArgLoc = 315 MemoryLocation::getForArgument(Call2, Call2ArgIdx, TLI); 316 317 // ArgModRefC2 indicates what Call2 might do to Call2ArgLoc, and the 318 // dependence of Call1 on that location is the inverse: 319 // - If Call2 modifies location, dependence exists if Call1 reads or 320 // writes. 321 // - If Call2 only reads location, dependence exists if Call1 writes. 322 ModRefInfo ArgModRefC2 = getArgModRefInfo(Call2, Call2ArgIdx); 323 ModRefInfo ArgMask = ModRefInfo::NoModRef; 324 if (isModSet(ArgModRefC2)) 325 ArgMask = ModRefInfo::ModRef; 326 else if (isRefSet(ArgModRefC2)) 327 ArgMask = ModRefInfo::Mod; 328 329 // ModRefC1 indicates what Call1 might do to Call2ArgLoc, and we use 330 // above ArgMask to update dependence info. 331 ArgMask &= getModRefInfo(Call1, Call2ArgLoc, AAQI); 332 333 R = (R | ArgMask) & Result; 334 if (R == Result) 335 break; 336 } 337 338 return R; 339 } 340 341 // If Call1 only accesses memory through arguments, check if Call2 references 342 // any of the memory referenced by Call1's arguments. If not, return NoModRef. 343 if (Call1B.onlyAccessesArgPointees()) { 344 if (!Call1B.doesAccessArgPointees()) 345 return ModRefInfo::NoModRef; 346 ModRefInfo R = ModRefInfo::NoModRef; 347 for (auto I = Call1->arg_begin(), E = Call1->arg_end(); I != E; ++I) { 348 const Value *Arg = *I; 349 if (!Arg->getType()->isPointerTy()) 350 continue; 351 unsigned Call1ArgIdx = std::distance(Call1->arg_begin(), I); 352 auto Call1ArgLoc = 353 MemoryLocation::getForArgument(Call1, Call1ArgIdx, TLI); 354 355 // ArgModRefC1 indicates what Call1 might do to Call1ArgLoc; if Call1 356 // might Mod Call1ArgLoc, then we care about either a Mod or a Ref by 357 // Call2. If Call1 might Ref, then we care only about a Mod by Call2. 358 ModRefInfo ArgModRefC1 = getArgModRefInfo(Call1, Call1ArgIdx); 359 ModRefInfo ModRefC2 = getModRefInfo(Call2, Call1ArgLoc, AAQI); 360 if ((isModSet(ArgModRefC1) && isModOrRefSet(ModRefC2)) || 361 (isRefSet(ArgModRefC1) && isModSet(ModRefC2))) 362 R = (R | ArgModRefC1) & Result; 363 364 if (R == Result) 365 break; 366 } 367 368 return R; 369 } 370 371 return Result; 372 } 373 374 MemoryEffects AAResults::getMemoryEffects(const CallBase *Call, 375 AAQueryInfo &AAQI) { 376 MemoryEffects Result = MemoryEffects::unknown(); 377 378 for (const auto &AA : AAs) { 379 Result &= AA->getMemoryEffects(Call, AAQI); 380 381 // Early-exit the moment we reach the bottom of the lattice. 382 if (Result.doesNotAccessMemory()) 383 return Result; 384 } 385 386 return Result; 387 } 388 389 MemoryEffects AAResults::getMemoryEffects(const CallBase *Call) { 390 SimpleAAQueryInfo AAQI(*this); 391 return getMemoryEffects(Call, AAQI); 392 } 393 394 MemoryEffects AAResults::getMemoryEffects(const Function *F) { 395 MemoryEffects Result = MemoryEffects::unknown(); 396 397 for (const auto &AA : AAs) { 398 Result &= AA->getMemoryEffects(F); 399 400 // Early-exit the moment we reach the bottom of the lattice. 401 if (Result.doesNotAccessMemory()) 402 return Result; 403 } 404 405 return Result; 406 } 407 408 raw_ostream &llvm::operator<<(raw_ostream &OS, AliasResult AR) { 409 switch (AR) { 410 case AliasResult::NoAlias: 411 OS << "NoAlias"; 412 break; 413 case AliasResult::MustAlias: 414 OS << "MustAlias"; 415 break; 416 case AliasResult::MayAlias: 417 OS << "MayAlias"; 418 break; 419 case AliasResult::PartialAlias: 420 OS << "PartialAlias"; 421 if (AR.hasOffset()) 422 OS << " (off " << AR.getOffset() << ")"; 423 break; 424 } 425 return OS; 426 } 427 428 //===----------------------------------------------------------------------===// 429 // Helper method implementation 430 //===----------------------------------------------------------------------===// 431 432 ModRefInfo AAResults::getModRefInfo(const LoadInst *L, 433 const MemoryLocation &Loc, 434 AAQueryInfo &AAQI) { 435 // Be conservative in the face of atomic. 436 if (isStrongerThan(L->getOrdering(), AtomicOrdering::Unordered)) 437 return ModRefInfo::ModRef; 438 439 // If the load address doesn't alias the given address, it doesn't read 440 // or write the specified memory. 441 if (Loc.Ptr) { 442 AliasResult AR = alias(MemoryLocation::get(L), Loc, AAQI, L); 443 if (AR == AliasResult::NoAlias) 444 return ModRefInfo::NoModRef; 445 } 446 // Otherwise, a load just reads. 447 return ModRefInfo::Ref; 448 } 449 450 ModRefInfo AAResults::getModRefInfo(const StoreInst *S, 451 const MemoryLocation &Loc, 452 AAQueryInfo &AAQI) { 453 // Be conservative in the face of atomic. 454 if (isStrongerThan(S->getOrdering(), AtomicOrdering::Unordered)) 455 return ModRefInfo::ModRef; 456 457 if (Loc.Ptr) { 458 AliasResult AR = alias(MemoryLocation::get(S), Loc, AAQI, S); 459 // If the store address cannot alias the pointer in question, then the 460 // specified memory cannot be modified by the store. 461 if (AR == AliasResult::NoAlias) 462 return ModRefInfo::NoModRef; 463 464 // Examine the ModRef mask. If Mod isn't present, then return NoModRef. 465 // This ensures that if Loc is a constant memory location, we take into 466 // account the fact that the store definitely could not modify the memory 467 // location. 468 if (!isModSet(getModRefInfoMask(Loc))) 469 return ModRefInfo::NoModRef; 470 } 471 472 // Otherwise, a store just writes. 473 return ModRefInfo::Mod; 474 } 475 476 ModRefInfo AAResults::getModRefInfo(const FenceInst *S, 477 const MemoryLocation &Loc, 478 AAQueryInfo &AAQI) { 479 // All we know about a fence instruction is what we get from the ModRef 480 // mask: if Loc is a constant memory location, the fence definitely could 481 // not modify it. 482 if (Loc.Ptr) 483 return getModRefInfoMask(Loc); 484 return ModRefInfo::ModRef; 485 } 486 487 ModRefInfo AAResults::getModRefInfo(const VAArgInst *V, 488 const MemoryLocation &Loc, 489 AAQueryInfo &AAQI) { 490 if (Loc.Ptr) { 491 AliasResult AR = alias(MemoryLocation::get(V), Loc, AAQI, V); 492 // If the va_arg address cannot alias the pointer in question, then the 493 // specified memory cannot be accessed by the va_arg. 494 if (AR == AliasResult::NoAlias) 495 return ModRefInfo::NoModRef; 496 497 // If the pointer is a pointer to invariant memory, then it could not have 498 // been modified by this va_arg. 499 return getModRefInfoMask(Loc, AAQI); 500 } 501 502 // Otherwise, a va_arg reads and writes. 503 return ModRefInfo::ModRef; 504 } 505 506 ModRefInfo AAResults::getModRefInfo(const CatchPadInst *CatchPad, 507 const MemoryLocation &Loc, 508 AAQueryInfo &AAQI) { 509 if (Loc.Ptr) { 510 // If the pointer is a pointer to invariant memory, 511 // then it could not have been modified by this catchpad. 512 return getModRefInfoMask(Loc, AAQI); 513 } 514 515 // Otherwise, a catchpad reads and writes. 516 return ModRefInfo::ModRef; 517 } 518 519 ModRefInfo AAResults::getModRefInfo(const CatchReturnInst *CatchRet, 520 const MemoryLocation &Loc, 521 AAQueryInfo &AAQI) { 522 if (Loc.Ptr) { 523 // If the pointer is a pointer to invariant memory, 524 // then it could not have been modified by this catchpad. 525 return getModRefInfoMask(Loc, AAQI); 526 } 527 528 // Otherwise, a catchret reads and writes. 529 return ModRefInfo::ModRef; 530 } 531 532 ModRefInfo AAResults::getModRefInfo(const AtomicCmpXchgInst *CX, 533 const MemoryLocation &Loc, 534 AAQueryInfo &AAQI) { 535 // Acquire/Release cmpxchg has properties that matter for arbitrary addresses. 536 if (isStrongerThanMonotonic(CX->getSuccessOrdering())) 537 return ModRefInfo::ModRef; 538 539 if (Loc.Ptr) { 540 AliasResult AR = alias(MemoryLocation::get(CX), Loc, AAQI, CX); 541 // If the cmpxchg address does not alias the location, it does not access 542 // it. 543 if (AR == AliasResult::NoAlias) 544 return ModRefInfo::NoModRef; 545 } 546 547 return ModRefInfo::ModRef; 548 } 549 550 ModRefInfo AAResults::getModRefInfo(const AtomicRMWInst *RMW, 551 const MemoryLocation &Loc, 552 AAQueryInfo &AAQI) { 553 // Acquire/Release atomicrmw has properties that matter for arbitrary addresses. 554 if (isStrongerThanMonotonic(RMW->getOrdering())) 555 return ModRefInfo::ModRef; 556 557 if (Loc.Ptr) { 558 AliasResult AR = alias(MemoryLocation::get(RMW), Loc, AAQI, RMW); 559 // If the atomicrmw address does not alias the location, it does not access 560 // it. 561 if (AR == AliasResult::NoAlias) 562 return ModRefInfo::NoModRef; 563 } 564 565 return ModRefInfo::ModRef; 566 } 567 568 ModRefInfo AAResults::getModRefInfo(const Instruction *I, 569 const std::optional<MemoryLocation> &OptLoc, 570 AAQueryInfo &AAQIP) { 571 if (OptLoc == std::nullopt) { 572 if (const auto *Call = dyn_cast<CallBase>(I)) 573 return getMemoryEffects(Call, AAQIP).getModRef(); 574 } 575 576 const MemoryLocation &Loc = OptLoc.value_or(MemoryLocation()); 577 578 switch (I->getOpcode()) { 579 case Instruction::VAArg: 580 return getModRefInfo((const VAArgInst *)I, Loc, AAQIP); 581 case Instruction::Load: 582 return getModRefInfo((const LoadInst *)I, Loc, AAQIP); 583 case Instruction::Store: 584 return getModRefInfo((const StoreInst *)I, Loc, AAQIP); 585 case Instruction::Fence: 586 return getModRefInfo((const FenceInst *)I, Loc, AAQIP); 587 case Instruction::AtomicCmpXchg: 588 return getModRefInfo((const AtomicCmpXchgInst *)I, Loc, AAQIP); 589 case Instruction::AtomicRMW: 590 return getModRefInfo((const AtomicRMWInst *)I, Loc, AAQIP); 591 case Instruction::Call: 592 case Instruction::CallBr: 593 case Instruction::Invoke: 594 return getModRefInfo((const CallBase *)I, Loc, AAQIP); 595 case Instruction::CatchPad: 596 return getModRefInfo((const CatchPadInst *)I, Loc, AAQIP); 597 case Instruction::CatchRet: 598 return getModRefInfo((const CatchReturnInst *)I, Loc, AAQIP); 599 default: 600 assert(!I->mayReadOrWriteMemory() && 601 "Unhandled memory access instruction!"); 602 return ModRefInfo::NoModRef; 603 } 604 } 605 606 /// Return information about whether a particular call site modifies 607 /// or reads the specified memory location \p MemLoc before instruction \p I 608 /// in a BasicBlock. 609 /// FIXME: this is really just shoring-up a deficiency in alias analysis. 610 /// BasicAA isn't willing to spend linear time determining whether an alloca 611 /// was captured before or after this particular call, while we are. However, 612 /// with a smarter AA in place, this test is just wasting compile time. 613 ModRefInfo AAResults::callCapturesBefore(const Instruction *I, 614 const MemoryLocation &MemLoc, 615 DominatorTree *DT, 616 AAQueryInfo &AAQI) { 617 if (!DT) 618 return ModRefInfo::ModRef; 619 620 const Value *Object = getUnderlyingObject(MemLoc.Ptr); 621 if (!isIdentifiedFunctionLocal(Object)) 622 return ModRefInfo::ModRef; 623 624 const auto *Call = dyn_cast<CallBase>(I); 625 if (!Call || Call == Object) 626 return ModRefInfo::ModRef; 627 628 if (PointerMayBeCapturedBefore(Object, /* ReturnCaptures */ true, 629 /* StoreCaptures */ true, I, DT, 630 /* include Object */ true)) 631 return ModRefInfo::ModRef; 632 633 unsigned ArgNo = 0; 634 ModRefInfo R = ModRefInfo::NoModRef; 635 // Set flag only if no May found and all operands processed. 636 for (auto CI = Call->data_operands_begin(), CE = Call->data_operands_end(); 637 CI != CE; ++CI, ++ArgNo) { 638 // Only look at the no-capture or byval pointer arguments. If this 639 // pointer were passed to arguments that were neither of these, then it 640 // couldn't be no-capture. 641 if (!(*CI)->getType()->isPointerTy() || 642 (!Call->doesNotCapture(ArgNo) && ArgNo < Call->arg_size() && 643 !Call->isByValArgument(ArgNo))) 644 continue; 645 646 AliasResult AR = 647 alias(MemoryLocation::getBeforeOrAfter(*CI), 648 MemoryLocation::getBeforeOrAfter(Object), AAQI, Call); 649 // If this is a no-capture pointer argument, see if we can tell that it 650 // is impossible to alias the pointer we're checking. If not, we have to 651 // assume that the call could touch the pointer, even though it doesn't 652 // escape. 653 if (AR == AliasResult::NoAlias) 654 continue; 655 if (Call->doesNotAccessMemory(ArgNo)) 656 continue; 657 if (Call->onlyReadsMemory(ArgNo)) { 658 R = ModRefInfo::Ref; 659 continue; 660 } 661 return ModRefInfo::ModRef; 662 } 663 return R; 664 } 665 666 /// canBasicBlockModify - Return true if it is possible for execution of the 667 /// specified basic block to modify the location Loc. 668 /// 669 bool AAResults::canBasicBlockModify(const BasicBlock &BB, 670 const MemoryLocation &Loc) { 671 return canInstructionRangeModRef(BB.front(), BB.back(), Loc, ModRefInfo::Mod); 672 } 673 674 /// canInstructionRangeModRef - Return true if it is possible for the 675 /// execution of the specified instructions to mod\ref (according to the 676 /// mode) the location Loc. The instructions to consider are all 677 /// of the instructions in the range of [I1,I2] INCLUSIVE. 678 /// I1 and I2 must be in the same basic block. 679 bool AAResults::canInstructionRangeModRef(const Instruction &I1, 680 const Instruction &I2, 681 const MemoryLocation &Loc, 682 const ModRefInfo Mode) { 683 assert(I1.getParent() == I2.getParent() && 684 "Instructions not in same basic block!"); 685 BasicBlock::const_iterator I = I1.getIterator(); 686 BasicBlock::const_iterator E = I2.getIterator(); 687 ++E; // Convert from inclusive to exclusive range. 688 689 for (; I != E; ++I) // Check every instruction in range 690 if (isModOrRefSet(getModRefInfo(&*I, Loc) & Mode)) 691 return true; 692 return false; 693 } 694 695 // Provide a definition for the root virtual destructor. 696 AAResults::Concept::~Concept() = default; 697 698 // Provide a definition for the static object used to identify passes. 699 AnalysisKey AAManager::Key; 700 701 ExternalAAWrapperPass::ExternalAAWrapperPass() : ImmutablePass(ID) { 702 initializeExternalAAWrapperPassPass(*PassRegistry::getPassRegistry()); 703 } 704 705 ExternalAAWrapperPass::ExternalAAWrapperPass(CallbackT CB) 706 : ImmutablePass(ID), CB(std::move(CB)) { 707 initializeExternalAAWrapperPassPass(*PassRegistry::getPassRegistry()); 708 } 709 710 char ExternalAAWrapperPass::ID = 0; 711 712 INITIALIZE_PASS(ExternalAAWrapperPass, "external-aa", "External Alias Analysis", 713 false, true) 714 715 ImmutablePass * 716 llvm::createExternalAAWrapperPass(ExternalAAWrapperPass::CallbackT Callback) { 717 return new ExternalAAWrapperPass(std::move(Callback)); 718 } 719 720 AAResultsWrapperPass::AAResultsWrapperPass() : FunctionPass(ID) { 721 initializeAAResultsWrapperPassPass(*PassRegistry::getPassRegistry()); 722 } 723 724 char AAResultsWrapperPass::ID = 0; 725 726 INITIALIZE_PASS_BEGIN(AAResultsWrapperPass, "aa", 727 "Function Alias Analysis Results", false, true) 728 INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass) 729 INITIALIZE_PASS_DEPENDENCY(ExternalAAWrapperPass) 730 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass) 731 INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass) 732 INITIALIZE_PASS_DEPENDENCY(ScopedNoAliasAAWrapperPass) 733 INITIALIZE_PASS_DEPENDENCY(TypeBasedAAWrapperPass) 734 INITIALIZE_PASS_END(AAResultsWrapperPass, "aa", 735 "Function Alias Analysis Results", false, true) 736 737 /// Run the wrapper pass to rebuild an aggregation over known AA passes. 738 /// 739 /// This is the legacy pass manager's interface to the new-style AA results 740 /// aggregation object. Because this is somewhat shoe-horned into the legacy 741 /// pass manager, we hard code all the specific alias analyses available into 742 /// it. While the particular set enabled is configured via commandline flags, 743 /// adding a new alias analysis to LLVM will require adding support for it to 744 /// this list. 745 bool AAResultsWrapperPass::runOnFunction(Function &F) { 746 // NB! This *must* be reset before adding new AA results to the new 747 // AAResults object because in the legacy pass manager, each instance 748 // of these will refer to the *same* immutable analyses, registering and 749 // unregistering themselves with them. We need to carefully tear down the 750 // previous object first, in this case replacing it with an empty one, before 751 // registering new results. 752 AAR.reset( 753 new AAResults(getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F))); 754 755 // BasicAA is always available for function analyses. Also, we add it first 756 // so that it can trump TBAA results when it proves MustAlias. 757 // FIXME: TBAA should have an explicit mode to support this and then we 758 // should reconsider the ordering here. 759 if (!DisableBasicAA) 760 AAR->addAAResult(getAnalysis<BasicAAWrapperPass>().getResult()); 761 762 // Populate the results with the currently available AAs. 763 if (auto *WrapperPass = getAnalysisIfAvailable<ScopedNoAliasAAWrapperPass>()) 764 AAR->addAAResult(WrapperPass->getResult()); 765 if (auto *WrapperPass = getAnalysisIfAvailable<TypeBasedAAWrapperPass>()) 766 AAR->addAAResult(WrapperPass->getResult()); 767 if (auto *WrapperPass = getAnalysisIfAvailable<GlobalsAAWrapperPass>()) 768 AAR->addAAResult(WrapperPass->getResult()); 769 if (auto *WrapperPass = getAnalysisIfAvailable<SCEVAAWrapperPass>()) 770 AAR->addAAResult(WrapperPass->getResult()); 771 772 // If available, run an external AA providing callback over the results as 773 // well. 774 if (auto *WrapperPass = getAnalysisIfAvailable<ExternalAAWrapperPass>()) 775 if (WrapperPass->CB) 776 WrapperPass->CB(*this, F, *AAR); 777 778 // Analyses don't mutate the IR, so return false. 779 return false; 780 } 781 782 void AAResultsWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 783 AU.setPreservesAll(); 784 AU.addRequiredTransitive<BasicAAWrapperPass>(); 785 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 786 787 // We also need to mark all the alias analysis passes we will potentially 788 // probe in runOnFunction as used here to ensure the legacy pass manager 789 // preserves them. This hard coding of lists of alias analyses is specific to 790 // the legacy pass manager. 791 AU.addUsedIfAvailable<ScopedNoAliasAAWrapperPass>(); 792 AU.addUsedIfAvailable<TypeBasedAAWrapperPass>(); 793 AU.addUsedIfAvailable<GlobalsAAWrapperPass>(); 794 AU.addUsedIfAvailable<SCEVAAWrapperPass>(); 795 AU.addUsedIfAvailable<ExternalAAWrapperPass>(); 796 } 797 798 AAManager::Result AAManager::run(Function &F, FunctionAnalysisManager &AM) { 799 Result R(AM.getResult<TargetLibraryAnalysis>(F)); 800 for (auto &Getter : ResultGetters) 801 (*Getter)(F, AM, R); 802 return R; 803 } 804 805 bool llvm::isNoAliasCall(const Value *V) { 806 if (const auto *Call = dyn_cast<CallBase>(V)) 807 return Call->hasRetAttr(Attribute::NoAlias); 808 return false; 809 } 810 811 static bool isNoAliasOrByValArgument(const Value *V) { 812 if (const Argument *A = dyn_cast<Argument>(V)) 813 return A->hasNoAliasAttr() || A->hasByValAttr(); 814 return false; 815 } 816 817 bool llvm::isIdentifiedObject(const Value *V) { 818 if (isa<AllocaInst>(V)) 819 return true; 820 if (isa<GlobalValue>(V) && !isa<GlobalAlias>(V)) 821 return true; 822 if (isNoAliasCall(V)) 823 return true; 824 if (isNoAliasOrByValArgument(V)) 825 return true; 826 return false; 827 } 828 829 bool llvm::isIdentifiedFunctionLocal(const Value *V) { 830 return isa<AllocaInst>(V) || isNoAliasCall(V) || isNoAliasOrByValArgument(V); 831 } 832 833 bool llvm::isEscapeSource(const Value *V) { 834 if (auto *CB = dyn_cast<CallBase>(V)) 835 return !isIntrinsicReturningPointerAliasingArgumentWithoutCapturing(CB, 836 true); 837 838 // The load case works because isNonEscapingLocalObject considers all 839 // stores to be escapes (it passes true for the StoreCaptures argument 840 // to PointerMayBeCaptured). 841 if (isa<LoadInst>(V)) 842 return true; 843 844 // The inttoptr case works because isNonEscapingLocalObject considers all 845 // means of converting or equating a pointer to an int (ptrtoint, ptr store 846 // which could be followed by an integer load, ptr<->int compare) as 847 // escaping, and objects located at well-known addresses via platform-specific 848 // means cannot be considered non-escaping local objects. 849 if (isa<IntToPtrInst>(V)) 850 return true; 851 852 // Same for inttoptr constant expressions. 853 if (auto *CE = dyn_cast<ConstantExpr>(V)) 854 if (CE->getOpcode() == Instruction::IntToPtr) 855 return true; 856 857 return false; 858 } 859 860 bool llvm::isNotVisibleOnUnwind(const Value *Object, 861 bool &RequiresNoCaptureBeforeUnwind) { 862 RequiresNoCaptureBeforeUnwind = false; 863 864 // Alloca goes out of scope on unwind. 865 if (isa<AllocaInst>(Object)) 866 return true; 867 868 // Byval goes out of scope on unwind. 869 if (auto *A = dyn_cast<Argument>(Object)) 870 return A->hasByValAttr() || A->hasAttribute(Attribute::DeadOnUnwind); 871 872 // A noalias return is not accessible from any other code. If the pointer 873 // does not escape prior to the unwind, then the caller cannot access the 874 // memory either. 875 if (isNoAliasCall(Object)) { 876 RequiresNoCaptureBeforeUnwind = true; 877 return true; 878 } 879 880 return false; 881 } 882 883 // We don't consider globals as writable: While the physical memory is writable, 884 // we may not have provenance to perform the write. 885 bool llvm::isWritableObject(const Value *Object, 886 bool &ExplicitlyDereferenceableOnly) { 887 ExplicitlyDereferenceableOnly = false; 888 889 // TODO: Alloca might not be writable after its lifetime ends. 890 // See https://github.com/llvm/llvm-project/issues/51838. 891 if (isa<AllocaInst>(Object)) 892 return true; 893 894 if (auto *A = dyn_cast<Argument>(Object)) { 895 if (A->hasAttribute(Attribute::Writable)) { 896 ExplicitlyDereferenceableOnly = true; 897 return true; 898 } 899 900 return A->hasByValAttr(); 901 } 902 903 // TODO: Noalias shouldn't imply writability, this should check for an 904 // allocator function instead. 905 return isNoAliasCall(Object); 906 } 907