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