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/Module.h" 46 #include "llvm/IR/Type.h" 47 #include "llvm/IR/Value.h" 48 #include "llvm/InitializePasses.h" 49 #include "llvm/Pass.h" 50 #include "llvm/Support/AtomicOrdering.h" 51 #include "llvm/Support/Casting.h" 52 #include "llvm/Support/CommandLine.h" 53 #include <algorithm> 54 #include <cassert> 55 #include <functional> 56 #include <iterator> 57 58 #define DEBUG_TYPE "aa" 59 60 using namespace llvm; 61 62 STATISTIC(NumNoAlias, "Number of NoAlias results"); 63 STATISTIC(NumMayAlias, "Number of MayAlias results"); 64 STATISTIC(NumMustAlias, "Number of MustAlias results"); 65 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 70 #ifndef NDEBUG 71 /// Print a trace of alias analysis queries and their results. 72 static cl::opt<bool> EnableAATrace("aa-trace", cl::Hidden, cl::init(false)); 73 #else 74 static const bool EnableAATrace = false; 75 #endif 76 77 AAResults::AAResults(AAResults &&Arg) 78 : TLI(Arg.TLI), AAs(std::move(Arg.AAs)), AADeps(std::move(Arg.AADeps)) { 79 for (auto &AA : AAs) 80 AA->setAAResults(this); 81 } 82 83 AAResults::~AAResults() { 84 // FIXME; It would be nice to at least clear out the pointers back to this 85 // aggregation here, but we end up with non-nesting lifetimes in the legacy 86 // pass manager that prevent this from working. In the legacy pass manager 87 // we'll end up with dangling references here in some cases. 88 #if 0 89 for (auto &AA : AAs) 90 AA->setAAResults(nullptr); 91 #endif 92 } 93 94 bool AAResults::invalidate(Function &F, const PreservedAnalyses &PA, 95 FunctionAnalysisManager::Invalidator &Inv) { 96 // AAResults preserves the AAManager by default, due to the stateless nature 97 // of AliasAnalysis. There is no need to check whether it has been preserved 98 // explicitly. Check if any module dependency was invalidated and caused the 99 // AAManager to be invalidated. Invalidate ourselves in that case. 100 auto PAC = PA.getChecker<AAManager>(); 101 if (!PAC.preservedWhenStateless()) 102 return true; 103 104 // Check if any of the function dependencies were invalidated, and invalidate 105 // ourselves in that case. 106 for (AnalysisKey *ID : AADeps) 107 if (Inv.invalidate(ID, F, PA)) 108 return true; 109 110 // Everything we depend on is still fine, so are we. Nothing to invalidate. 111 return false; 112 } 113 114 //===----------------------------------------------------------------------===// 115 // Default chaining methods 116 //===----------------------------------------------------------------------===// 117 118 AliasResult AAResults::alias(const MemoryLocation &LocA, 119 const MemoryLocation &LocB) { 120 AAQueryInfo AAQIP; 121 return alias(LocA, LocB, AAQIP); 122 } 123 124 AliasResult AAResults::alias(const MemoryLocation &LocA, 125 const MemoryLocation &LocB, AAQueryInfo &AAQI) { 126 AliasResult Result = AliasResult::MayAlias; 127 128 if (EnableAATrace) { 129 for (unsigned I = 0; I < AAQI.Depth; ++I) 130 dbgs() << " "; 131 dbgs() << "Start " << *LocA.Ptr << " @ " << LocA.Size << ", " 132 << *LocB.Ptr << " @ " << LocB.Size << "\n"; 133 } 134 135 AAQI.Depth++; 136 for (const auto &AA : AAs) { 137 Result = AA->alias(LocA, LocB, AAQI); 138 if (Result != AliasResult::MayAlias) 139 break; 140 } 141 AAQI.Depth--; 142 143 if (EnableAATrace) { 144 for (unsigned I = 0; I < AAQI.Depth; ++I) 145 dbgs() << " "; 146 dbgs() << "End " << *LocA.Ptr << " @ " << LocA.Size << ", " 147 << *LocB.Ptr << " @ " << LocB.Size << " = " << Result << "\n"; 148 } 149 150 if (AAQI.Depth == 0) { 151 if (Result == AliasResult::NoAlias) 152 ++NumNoAlias; 153 else if (Result == AliasResult::MustAlias) 154 ++NumMustAlias; 155 else 156 ++NumMayAlias; 157 } 158 return Result; 159 } 160 161 bool AAResults::pointsToConstantMemory(const MemoryLocation &Loc, 162 bool OrLocal) { 163 AAQueryInfo AAQIP; 164 return pointsToConstantMemory(Loc, AAQIP, OrLocal); 165 } 166 167 bool AAResults::pointsToConstantMemory(const MemoryLocation &Loc, 168 AAQueryInfo &AAQI, bool OrLocal) { 169 for (const auto &AA : AAs) 170 if (AA->pointsToConstantMemory(Loc, AAQI, OrLocal)) 171 return true; 172 173 return false; 174 } 175 176 ModRefInfo AAResults::getArgModRefInfo(const CallBase *Call, unsigned ArgIdx) { 177 ModRefInfo Result = ModRefInfo::ModRef; 178 179 for (const auto &AA : AAs) { 180 Result = intersectModRef(Result, AA->getArgModRefInfo(Call, ArgIdx)); 181 182 // Early-exit the moment we reach the bottom of the lattice. 183 if (isNoModRef(Result)) 184 return ModRefInfo::NoModRef; 185 } 186 187 return Result; 188 } 189 190 ModRefInfo AAResults::getModRefInfo(Instruction *I, const CallBase *Call2) { 191 AAQueryInfo AAQIP; 192 return getModRefInfo(I, Call2, AAQIP); 193 } 194 195 ModRefInfo AAResults::getModRefInfo(Instruction *I, const CallBase *Call2, 196 AAQueryInfo &AAQI) { 197 // We may have two calls. 198 if (const auto *Call1 = dyn_cast<CallBase>(I)) { 199 // Check if the two calls modify the same memory. 200 return getModRefInfo(Call1, Call2, AAQI); 201 } else if (I->isFenceLike()) { 202 // If this is a fence, just return ModRef. 203 return ModRefInfo::ModRef; 204 } else { 205 // Otherwise, check if the call modifies or references the 206 // location this memory access defines. The best we can say 207 // is that if the call references what this instruction 208 // defines, it must be clobbered by this location. 209 const MemoryLocation DefLoc = MemoryLocation::get(I); 210 ModRefInfo MR = getModRefInfo(Call2, DefLoc, AAQI); 211 if (isModOrRefSet(MR)) 212 return setModAndRef(MR); 213 } 214 return ModRefInfo::NoModRef; 215 } 216 217 ModRefInfo AAResults::getModRefInfo(const CallBase *Call, 218 const MemoryLocation &Loc) { 219 AAQueryInfo 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 (doesNotReadMemory(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 (auto AI = Call->arg_begin(), AE = Call->arg_end(); AI != AE; ++AI) { 252 const Value *Arg = *AI; 253 if (!Arg->getType()->isPointerTy()) 254 continue; 255 unsigned ArgIdx = std::distance(Call->arg_begin(), AI); 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 AAQueryInfo 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 (doesNotReadMemory(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 break; 464 } 465 return OS; 466 } 467 468 //===----------------------------------------------------------------------===// 469 // Helper method implementation 470 //===----------------------------------------------------------------------===// 471 472 ModRefInfo AAResults::getModRefInfo(const LoadInst *L, 473 const MemoryLocation &Loc) { 474 AAQueryInfo AAQIP; 475 return getModRefInfo(L, Loc, AAQIP); 476 } 477 ModRefInfo AAResults::getModRefInfo(const LoadInst *L, 478 const MemoryLocation &Loc, 479 AAQueryInfo &AAQI) { 480 // Be conservative in the face of atomic. 481 if (isStrongerThan(L->getOrdering(), AtomicOrdering::Unordered)) 482 return ModRefInfo::ModRef; 483 484 // If the load address doesn't alias the given address, it doesn't read 485 // or write the specified memory. 486 if (Loc.Ptr) { 487 AliasResult AR = alias(MemoryLocation::get(L), Loc, AAQI); 488 if (AR == AliasResult::NoAlias) 489 return ModRefInfo::NoModRef; 490 if (AR == AliasResult::MustAlias) 491 return ModRefInfo::MustRef; 492 } 493 // Otherwise, a load just reads. 494 return ModRefInfo::Ref; 495 } 496 497 ModRefInfo AAResults::getModRefInfo(const StoreInst *S, 498 const MemoryLocation &Loc) { 499 AAQueryInfo AAQIP; 500 return getModRefInfo(S, Loc, AAQIP); 501 } 502 ModRefInfo AAResults::getModRefInfo(const StoreInst *S, 503 const MemoryLocation &Loc, 504 AAQueryInfo &AAQI) { 505 // Be conservative in the face of atomic. 506 if (isStrongerThan(S->getOrdering(), AtomicOrdering::Unordered)) 507 return ModRefInfo::ModRef; 508 509 if (Loc.Ptr) { 510 AliasResult AR = alias(MemoryLocation::get(S), Loc, AAQI); 511 // If the store address cannot alias the pointer in question, then the 512 // specified memory cannot be modified by the store. 513 if (AR == AliasResult::NoAlias) 514 return ModRefInfo::NoModRef; 515 516 // If the pointer is a pointer to constant memory, then it could not have 517 // been modified by this store. 518 if (pointsToConstantMemory(Loc, AAQI)) 519 return ModRefInfo::NoModRef; 520 521 // If the store address aliases the pointer as must alias, set Must. 522 if (AR == AliasResult::MustAlias) 523 return ModRefInfo::MustMod; 524 } 525 526 // Otherwise, a store just writes. 527 return ModRefInfo::Mod; 528 } 529 530 ModRefInfo AAResults::getModRefInfo(const FenceInst *S, const MemoryLocation &Loc) { 531 AAQueryInfo AAQIP; 532 return getModRefInfo(S, Loc, AAQIP); 533 } 534 535 ModRefInfo AAResults::getModRefInfo(const FenceInst *S, 536 const MemoryLocation &Loc, 537 AAQueryInfo &AAQI) { 538 // If we know that the location is a constant memory location, the fence 539 // cannot modify this location. 540 if (Loc.Ptr && pointsToConstantMemory(Loc, AAQI)) 541 return ModRefInfo::Ref; 542 return ModRefInfo::ModRef; 543 } 544 545 ModRefInfo AAResults::getModRefInfo(const VAArgInst *V, 546 const MemoryLocation &Loc) { 547 AAQueryInfo AAQIP; 548 return getModRefInfo(V, Loc, AAQIP); 549 } 550 551 ModRefInfo AAResults::getModRefInfo(const VAArgInst *V, 552 const MemoryLocation &Loc, 553 AAQueryInfo &AAQI) { 554 if (Loc.Ptr) { 555 AliasResult AR = alias(MemoryLocation::get(V), Loc, AAQI); 556 // If the va_arg address cannot alias the pointer in question, then the 557 // specified memory cannot be accessed by the va_arg. 558 if (AR == AliasResult::NoAlias) 559 return ModRefInfo::NoModRef; 560 561 // If the pointer is a pointer to constant memory, then it could not have 562 // been modified by this va_arg. 563 if (pointsToConstantMemory(Loc, AAQI)) 564 return ModRefInfo::NoModRef; 565 566 // If the va_arg aliases the pointer as must alias, set Must. 567 if (AR == AliasResult::MustAlias) 568 return ModRefInfo::MustModRef; 569 } 570 571 // Otherwise, a va_arg reads and writes. 572 return ModRefInfo::ModRef; 573 } 574 575 ModRefInfo AAResults::getModRefInfo(const CatchPadInst *CatchPad, 576 const MemoryLocation &Loc) { 577 AAQueryInfo AAQIP; 578 return getModRefInfo(CatchPad, Loc, AAQIP); 579 } 580 581 ModRefInfo AAResults::getModRefInfo(const CatchPadInst *CatchPad, 582 const MemoryLocation &Loc, 583 AAQueryInfo &AAQI) { 584 if (Loc.Ptr) { 585 // If the pointer is a pointer to constant memory, 586 // then it could not have been modified by this catchpad. 587 if (pointsToConstantMemory(Loc, AAQI)) 588 return ModRefInfo::NoModRef; 589 } 590 591 // Otherwise, a catchpad reads and writes. 592 return ModRefInfo::ModRef; 593 } 594 595 ModRefInfo AAResults::getModRefInfo(const CatchReturnInst *CatchRet, 596 const MemoryLocation &Loc) { 597 AAQueryInfo AAQIP; 598 return getModRefInfo(CatchRet, Loc, AAQIP); 599 } 600 601 ModRefInfo AAResults::getModRefInfo(const CatchReturnInst *CatchRet, 602 const MemoryLocation &Loc, 603 AAQueryInfo &AAQI) { 604 if (Loc.Ptr) { 605 // If the pointer is a pointer to constant memory, 606 // then it could not have been modified by this catchpad. 607 if (pointsToConstantMemory(Loc, AAQI)) 608 return ModRefInfo::NoModRef; 609 } 610 611 // Otherwise, a catchret reads and writes. 612 return ModRefInfo::ModRef; 613 } 614 615 ModRefInfo AAResults::getModRefInfo(const AtomicCmpXchgInst *CX, 616 const MemoryLocation &Loc) { 617 AAQueryInfo AAQIP; 618 return getModRefInfo(CX, Loc, AAQIP); 619 } 620 621 ModRefInfo AAResults::getModRefInfo(const AtomicCmpXchgInst *CX, 622 const MemoryLocation &Loc, 623 AAQueryInfo &AAQI) { 624 // Acquire/Release cmpxchg has properties that matter for arbitrary addresses. 625 if (isStrongerThanMonotonic(CX->getSuccessOrdering())) 626 return ModRefInfo::ModRef; 627 628 if (Loc.Ptr) { 629 AliasResult AR = alias(MemoryLocation::get(CX), Loc, AAQI); 630 // If the cmpxchg address does not alias the location, it does not access 631 // it. 632 if (AR == AliasResult::NoAlias) 633 return ModRefInfo::NoModRef; 634 635 // If the cmpxchg address aliases the pointer as must alias, set Must. 636 if (AR == AliasResult::MustAlias) 637 return ModRefInfo::MustModRef; 638 } 639 640 return ModRefInfo::ModRef; 641 } 642 643 ModRefInfo AAResults::getModRefInfo(const AtomicRMWInst *RMW, 644 const MemoryLocation &Loc) { 645 AAQueryInfo AAQIP; 646 return getModRefInfo(RMW, Loc, AAQIP); 647 } 648 649 ModRefInfo AAResults::getModRefInfo(const AtomicRMWInst *RMW, 650 const MemoryLocation &Loc, 651 AAQueryInfo &AAQI) { 652 // Acquire/Release atomicrmw has properties that matter for arbitrary addresses. 653 if (isStrongerThanMonotonic(RMW->getOrdering())) 654 return ModRefInfo::ModRef; 655 656 if (Loc.Ptr) { 657 AliasResult AR = alias(MemoryLocation::get(RMW), Loc, AAQI); 658 // If the atomicrmw address does not alias the location, it does not access 659 // it. 660 if (AR == AliasResult::NoAlias) 661 return ModRefInfo::NoModRef; 662 663 // If the atomicrmw address aliases the pointer as must alias, set Must. 664 if (AR == AliasResult::MustAlias) 665 return ModRefInfo::MustModRef; 666 } 667 668 return ModRefInfo::ModRef; 669 } 670 671 ModRefInfo AAResults::getModRefInfo(const Instruction *I, 672 const Optional<MemoryLocation> &OptLoc, 673 AAQueryInfo &AAQIP) { 674 if (OptLoc == None) { 675 if (const auto *Call = dyn_cast<CallBase>(I)) { 676 return createModRefInfo(getModRefBehavior(Call)); 677 } 678 } 679 680 const MemoryLocation &Loc = OptLoc.getValueOr(MemoryLocation()); 681 682 switch (I->getOpcode()) { 683 case Instruction::VAArg: 684 return getModRefInfo((const VAArgInst *)I, Loc, AAQIP); 685 case Instruction::Load: 686 return getModRefInfo((const LoadInst *)I, Loc, AAQIP); 687 case Instruction::Store: 688 return getModRefInfo((const StoreInst *)I, Loc, AAQIP); 689 case Instruction::Fence: 690 return getModRefInfo((const FenceInst *)I, Loc, AAQIP); 691 case Instruction::AtomicCmpXchg: 692 return getModRefInfo((const AtomicCmpXchgInst *)I, Loc, AAQIP); 693 case Instruction::AtomicRMW: 694 return getModRefInfo((const AtomicRMWInst *)I, Loc, AAQIP); 695 case Instruction::Call: 696 return getModRefInfo((const CallInst *)I, Loc, AAQIP); 697 case Instruction::Invoke: 698 return getModRefInfo((const InvokeInst *)I, Loc, AAQIP); 699 case Instruction::CatchPad: 700 return getModRefInfo((const CatchPadInst *)I, Loc, AAQIP); 701 case Instruction::CatchRet: 702 return getModRefInfo((const CatchReturnInst *)I, Loc, AAQIP); 703 default: 704 return ModRefInfo::NoModRef; 705 } 706 } 707 708 /// Return information about whether a particular call site modifies 709 /// or reads the specified memory location \p MemLoc before instruction \p I 710 /// in a BasicBlock. 711 /// FIXME: this is really just shoring-up a deficiency in alias analysis. 712 /// BasicAA isn't willing to spend linear time determining whether an alloca 713 /// was captured before or after this particular call, while we are. However, 714 /// with a smarter AA in place, this test is just wasting compile time. 715 ModRefInfo AAResults::callCapturesBefore(const Instruction *I, 716 const MemoryLocation &MemLoc, 717 DominatorTree *DT) { 718 if (!DT) 719 return ModRefInfo::ModRef; 720 721 const Value *Object = getUnderlyingObject(MemLoc.Ptr); 722 if (!isIdentifiedObject(Object) || isa<GlobalValue>(Object) || 723 isa<Constant>(Object)) 724 return ModRefInfo::ModRef; 725 726 const auto *Call = dyn_cast<CallBase>(I); 727 if (!Call || Call == Object) 728 return ModRefInfo::ModRef; 729 730 if (PointerMayBeCapturedBefore(Object, /* ReturnCaptures */ true, 731 /* StoreCaptures */ true, I, DT, 732 /* include Object */ true)) 733 return ModRefInfo::ModRef; 734 735 unsigned ArgNo = 0; 736 ModRefInfo R = ModRefInfo::NoModRef; 737 bool IsMustAlias = true; 738 // Set flag only if no May found and all operands processed. 739 for (auto CI = Call->data_operands_begin(), CE = Call->data_operands_end(); 740 CI != CE; ++CI, ++ArgNo) { 741 // Only look at the no-capture or byval pointer arguments. If this 742 // pointer were passed to arguments that were neither of these, then it 743 // couldn't be no-capture. 744 if (!(*CI)->getType()->isPointerTy() || 745 (!Call->doesNotCapture(ArgNo) && ArgNo < Call->getNumArgOperands() && 746 !Call->isByValArgument(ArgNo))) 747 continue; 748 749 AliasResult AR = alias(*CI, Object); 750 // If this is a no-capture pointer argument, see if we can tell that it 751 // is impossible to alias the pointer we're checking. If not, we have to 752 // assume that the call could touch the pointer, even though it doesn't 753 // escape. 754 if (AR != AliasResult::MustAlias) 755 IsMustAlias = false; 756 if (AR == AliasResult::NoAlias) 757 continue; 758 if (Call->doesNotAccessMemory(ArgNo)) 759 continue; 760 if (Call->onlyReadsMemory(ArgNo)) { 761 R = ModRefInfo::Ref; 762 continue; 763 } 764 // Not returning MustModRef since we have not seen all the arguments. 765 return ModRefInfo::ModRef; 766 } 767 return IsMustAlias ? setMust(R) : clearMust(R); 768 } 769 770 /// canBasicBlockModify - Return true if it is possible for execution of the 771 /// specified basic block to modify the location Loc. 772 /// 773 bool AAResults::canBasicBlockModify(const BasicBlock &BB, 774 const MemoryLocation &Loc) { 775 return canInstructionRangeModRef(BB.front(), BB.back(), Loc, ModRefInfo::Mod); 776 } 777 778 /// canInstructionRangeModRef - Return true if it is possible for the 779 /// execution of the specified instructions to mod\ref (according to the 780 /// mode) the location Loc. The instructions to consider are all 781 /// of the instructions in the range of [I1,I2] INCLUSIVE. 782 /// I1 and I2 must be in the same basic block. 783 bool AAResults::canInstructionRangeModRef(const Instruction &I1, 784 const Instruction &I2, 785 const MemoryLocation &Loc, 786 const ModRefInfo Mode) { 787 assert(I1.getParent() == I2.getParent() && 788 "Instructions not in same basic block!"); 789 BasicBlock::const_iterator I = I1.getIterator(); 790 BasicBlock::const_iterator E = I2.getIterator(); 791 ++E; // Convert from inclusive to exclusive range. 792 793 for (; I != E; ++I) // Check every instruction in range 794 if (isModOrRefSet(intersectModRef(getModRefInfo(&*I, Loc), Mode))) 795 return true; 796 return false; 797 } 798 799 // Provide a definition for the root virtual destructor. 800 AAResults::Concept::~Concept() = default; 801 802 // Provide a definition for the static object used to identify passes. 803 AnalysisKey AAManager::Key; 804 805 namespace { 806 807 808 } // end anonymous namespace 809 810 ExternalAAWrapperPass::ExternalAAWrapperPass() : ImmutablePass(ID) { 811 initializeExternalAAWrapperPassPass(*PassRegistry::getPassRegistry()); 812 } 813 814 ExternalAAWrapperPass::ExternalAAWrapperPass(CallbackT CB) 815 : ImmutablePass(ID), CB(std::move(CB)) { 816 initializeExternalAAWrapperPassPass(*PassRegistry::getPassRegistry()); 817 } 818 819 char ExternalAAWrapperPass::ID = 0; 820 821 INITIALIZE_PASS(ExternalAAWrapperPass, "external-aa", "External Alias Analysis", 822 false, true) 823 824 ImmutablePass * 825 llvm::createExternalAAWrapperPass(ExternalAAWrapperPass::CallbackT Callback) { 826 return new ExternalAAWrapperPass(std::move(Callback)); 827 } 828 829 AAResultsWrapperPass::AAResultsWrapperPass() : FunctionPass(ID) { 830 initializeAAResultsWrapperPassPass(*PassRegistry::getPassRegistry()); 831 } 832 833 char AAResultsWrapperPass::ID = 0; 834 835 INITIALIZE_PASS_BEGIN(AAResultsWrapperPass, "aa", 836 "Function Alias Analysis Results", false, true) 837 INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass) 838 INITIALIZE_PASS_DEPENDENCY(CFLAndersAAWrapperPass) 839 INITIALIZE_PASS_DEPENDENCY(CFLSteensAAWrapperPass) 840 INITIALIZE_PASS_DEPENDENCY(ExternalAAWrapperPass) 841 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass) 842 INITIALIZE_PASS_DEPENDENCY(ObjCARCAAWrapperPass) 843 INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass) 844 INITIALIZE_PASS_DEPENDENCY(ScopedNoAliasAAWrapperPass) 845 INITIALIZE_PASS_DEPENDENCY(TypeBasedAAWrapperPass) 846 INITIALIZE_PASS_END(AAResultsWrapperPass, "aa", 847 "Function Alias Analysis Results", false, true) 848 849 FunctionPass *llvm::createAAResultsWrapperPass() { 850 return new AAResultsWrapperPass(); 851 } 852 853 /// Run the wrapper pass to rebuild an aggregation over known AA passes. 854 /// 855 /// This is the legacy pass manager's interface to the new-style AA results 856 /// aggregation object. Because this is somewhat shoe-horned into the legacy 857 /// pass manager, we hard code all the specific alias analyses available into 858 /// it. While the particular set enabled is configured via commandline flags, 859 /// adding a new alias analysis to LLVM will require adding support for it to 860 /// this list. 861 bool AAResultsWrapperPass::runOnFunction(Function &F) { 862 // NB! This *must* be reset before adding new AA results to the new 863 // AAResults object because in the legacy pass manager, each instance 864 // of these will refer to the *same* immutable analyses, registering and 865 // unregistering themselves with them. We need to carefully tear down the 866 // previous object first, in this case replacing it with an empty one, before 867 // registering new results. 868 AAR.reset( 869 new AAResults(getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F))); 870 871 // BasicAA is always available for function analyses. Also, we add it first 872 // so that it can trump TBAA results when it proves MustAlias. 873 // FIXME: TBAA should have an explicit mode to support this and then we 874 // should reconsider the ordering here. 875 if (!DisableBasicAA) 876 AAR->addAAResult(getAnalysis<BasicAAWrapperPass>().getResult()); 877 878 // Populate the results with the currently available AAs. 879 if (auto *WrapperPass = getAnalysisIfAvailable<ScopedNoAliasAAWrapperPass>()) 880 AAR->addAAResult(WrapperPass->getResult()); 881 if (auto *WrapperPass = getAnalysisIfAvailable<TypeBasedAAWrapperPass>()) 882 AAR->addAAResult(WrapperPass->getResult()); 883 if (auto *WrapperPass = 884 getAnalysisIfAvailable<objcarc::ObjCARCAAWrapperPass>()) 885 AAR->addAAResult(WrapperPass->getResult()); 886 if (auto *WrapperPass = getAnalysisIfAvailable<GlobalsAAWrapperPass>()) 887 AAR->addAAResult(WrapperPass->getResult()); 888 if (auto *WrapperPass = getAnalysisIfAvailable<SCEVAAWrapperPass>()) 889 AAR->addAAResult(WrapperPass->getResult()); 890 if (auto *WrapperPass = getAnalysisIfAvailable<CFLAndersAAWrapperPass>()) 891 AAR->addAAResult(WrapperPass->getResult()); 892 if (auto *WrapperPass = getAnalysisIfAvailable<CFLSteensAAWrapperPass>()) 893 AAR->addAAResult(WrapperPass->getResult()); 894 895 // If available, run an external AA providing callback over the results as 896 // well. 897 if (auto *WrapperPass = getAnalysisIfAvailable<ExternalAAWrapperPass>()) 898 if (WrapperPass->CB) 899 WrapperPass->CB(*this, F, *AAR); 900 901 // Analyses don't mutate the IR, so return false. 902 return false; 903 } 904 905 void AAResultsWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 906 AU.setPreservesAll(); 907 AU.addRequiredTransitive<BasicAAWrapperPass>(); 908 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 909 910 // We also need to mark all the alias analysis passes we will potentially 911 // probe in runOnFunction as used here to ensure the legacy pass manager 912 // preserves them. This hard coding of lists of alias analyses is specific to 913 // the legacy pass manager. 914 AU.addUsedIfAvailable<ScopedNoAliasAAWrapperPass>(); 915 AU.addUsedIfAvailable<TypeBasedAAWrapperPass>(); 916 AU.addUsedIfAvailable<objcarc::ObjCARCAAWrapperPass>(); 917 AU.addUsedIfAvailable<GlobalsAAWrapperPass>(); 918 AU.addUsedIfAvailable<SCEVAAWrapperPass>(); 919 AU.addUsedIfAvailable<CFLAndersAAWrapperPass>(); 920 AU.addUsedIfAvailable<CFLSteensAAWrapperPass>(); 921 AU.addUsedIfAvailable<ExternalAAWrapperPass>(); 922 } 923 924 AAManager::Result AAManager::run(Function &F, FunctionAnalysisManager &AM) { 925 Result R(AM.getResult<TargetLibraryAnalysis>(F)); 926 for (auto &Getter : ResultGetters) 927 (*Getter)(F, AM, R); 928 return R; 929 } 930 931 AAResults llvm::createLegacyPMAAResults(Pass &P, Function &F, 932 BasicAAResult &BAR) { 933 AAResults AAR(P.getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F)); 934 935 // Add in our explicitly constructed BasicAA results. 936 if (!DisableBasicAA) 937 AAR.addAAResult(BAR); 938 939 // Populate the results with the other currently available AAs. 940 if (auto *WrapperPass = 941 P.getAnalysisIfAvailable<ScopedNoAliasAAWrapperPass>()) 942 AAR.addAAResult(WrapperPass->getResult()); 943 if (auto *WrapperPass = P.getAnalysisIfAvailable<TypeBasedAAWrapperPass>()) 944 AAR.addAAResult(WrapperPass->getResult()); 945 if (auto *WrapperPass = 946 P.getAnalysisIfAvailable<objcarc::ObjCARCAAWrapperPass>()) 947 AAR.addAAResult(WrapperPass->getResult()); 948 if (auto *WrapperPass = P.getAnalysisIfAvailable<GlobalsAAWrapperPass>()) 949 AAR.addAAResult(WrapperPass->getResult()); 950 if (auto *WrapperPass = P.getAnalysisIfAvailable<CFLAndersAAWrapperPass>()) 951 AAR.addAAResult(WrapperPass->getResult()); 952 if (auto *WrapperPass = P.getAnalysisIfAvailable<CFLSteensAAWrapperPass>()) 953 AAR.addAAResult(WrapperPass->getResult()); 954 if (auto *WrapperPass = P.getAnalysisIfAvailable<ExternalAAWrapperPass>()) 955 if (WrapperPass->CB) 956 WrapperPass->CB(P, F, AAR); 957 958 return AAR; 959 } 960 961 bool llvm::isNoAliasCall(const Value *V) { 962 if (const auto *Call = dyn_cast<CallBase>(V)) 963 return Call->hasRetAttr(Attribute::NoAlias); 964 return false; 965 } 966 967 static bool isNoAliasOrByValArgument(const Value *V) { 968 if (const Argument *A = dyn_cast<Argument>(V)) 969 return A->hasNoAliasAttr() || A->hasByValAttr(); 970 return false; 971 } 972 973 bool llvm::isIdentifiedObject(const Value *V) { 974 if (isa<AllocaInst>(V)) 975 return true; 976 if (isa<GlobalValue>(V) && !isa<GlobalAlias>(V)) 977 return true; 978 if (isNoAliasCall(V)) 979 return true; 980 if (isNoAliasOrByValArgument(V)) 981 return true; 982 return false; 983 } 984 985 bool llvm::isIdentifiedFunctionLocal(const Value *V) { 986 return isa<AllocaInst>(V) || isNoAliasCall(V) || isNoAliasOrByValArgument(V); 987 } 988 989 void llvm::getAAResultsAnalysisUsage(AnalysisUsage &AU) { 990 // This function needs to be in sync with llvm::createLegacyPMAAResults -- if 991 // more alias analyses are added to llvm::createLegacyPMAAResults, they need 992 // to be added here also. 993 AU.addRequired<TargetLibraryInfoWrapperPass>(); 994 AU.addUsedIfAvailable<ScopedNoAliasAAWrapperPass>(); 995 AU.addUsedIfAvailable<TypeBasedAAWrapperPass>(); 996 AU.addUsedIfAvailable<objcarc::ObjCARCAAWrapperPass>(); 997 AU.addUsedIfAvailable<GlobalsAAWrapperPass>(); 998 AU.addUsedIfAvailable<CFLAndersAAWrapperPass>(); 999 AU.addUsedIfAvailable<CFLSteensAAWrapperPass>(); 1000 AU.addUsedIfAvailable<ExternalAAWrapperPass>(); 1001 } 1002