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