1 //===- GlobalsModRef.cpp - Simple Mod/Ref Analysis for Globals ------------===// 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 simple pass provides alias and mod/ref information for global values 10 // that do not have their address taken, and keeps track of whether functions 11 // read or write memory (are "pure"). For this simple (but very common) case, 12 // we can provide pretty accurate and useful information. 13 // 14 //===----------------------------------------------------------------------===// 15 16 #include "llvm/Analysis/GlobalsModRef.h" 17 #include "llvm/ADT/SCCIterator.h" 18 #include "llvm/ADT/SmallPtrSet.h" 19 #include "llvm/ADT/Statistic.h" 20 #include "llvm/Analysis/CallGraph.h" 21 #include "llvm/Analysis/MemoryBuiltins.h" 22 #include "llvm/Analysis/TargetLibraryInfo.h" 23 #include "llvm/Analysis/ValueTracking.h" 24 #include "llvm/IR/InstIterator.h" 25 #include "llvm/IR/Instructions.h" 26 #include "llvm/IR/IntrinsicInst.h" 27 #include "llvm/IR/Module.h" 28 #include "llvm/InitializePasses.h" 29 #include "llvm/Pass.h" 30 #include "llvm/Support/CommandLine.h" 31 32 using namespace llvm; 33 34 #define DEBUG_TYPE "globalsmodref-aa" 35 36 STATISTIC(NumNonAddrTakenGlobalVars, 37 "Number of global vars without address taken"); 38 STATISTIC(NumNonAddrTakenFunctions,"Number of functions without address taken"); 39 STATISTIC(NumNoMemFunctions, "Number of functions that do not access memory"); 40 STATISTIC(NumReadMemFunctions, "Number of functions that only read memory"); 41 STATISTIC(NumIndirectGlobalVars, "Number of indirect global objects"); 42 43 // An option to enable unsafe alias results from the GlobalsModRef analysis. 44 // When enabled, GlobalsModRef will provide no-alias results which in extremely 45 // rare cases may not be conservatively correct. In particular, in the face of 46 // transforms which cause asymmetry between how effective getUnderlyingObject 47 // is for two pointers, it may produce incorrect results. 48 // 49 // These unsafe results have been returned by GMR for many years without 50 // causing significant issues in the wild and so we provide a mechanism to 51 // re-enable them for users of LLVM that have a particular performance 52 // sensitivity and no known issues. The option also makes it easy to evaluate 53 // the performance impact of these results. 54 static cl::opt<bool> EnableUnsafeGlobalsModRefAliasResults( 55 "enable-unsafe-globalsmodref-alias-results", cl::init(false), cl::Hidden); 56 57 /// The mod/ref information collected for a particular function. 58 /// 59 /// We collect information about mod/ref behavior of a function here, both in 60 /// general and as pertains to specific globals. We only have this detailed 61 /// information when we know *something* useful about the behavior. If we 62 /// saturate to fully general mod/ref, we remove the info for the function. 63 class GlobalsAAResult::FunctionInfo { 64 typedef SmallDenseMap<const GlobalValue *, ModRefInfo, 16> GlobalInfoMapType; 65 66 /// Build a wrapper struct that has 8-byte alignment. All heap allocations 67 /// should provide this much alignment at least, but this makes it clear we 68 /// specifically rely on this amount of alignment. 69 struct alignas(8) AlignedMap { 70 AlignedMap() = default; 71 AlignedMap(const AlignedMap &Arg) = default; 72 GlobalInfoMapType Map; 73 }; 74 75 /// Pointer traits for our aligned map. 76 struct AlignedMapPointerTraits { 77 static inline void *getAsVoidPointer(AlignedMap *P) { return P; } 78 static inline AlignedMap *getFromVoidPointer(void *P) { 79 return (AlignedMap *)P; 80 } 81 static constexpr int NumLowBitsAvailable = 3; 82 static_assert(alignof(AlignedMap) >= (1 << NumLowBitsAvailable), 83 "AlignedMap insufficiently aligned to have enough low bits."); 84 }; 85 86 /// The bit that flags that this function may read any global. This is 87 /// chosen to mix together with ModRefInfo bits. 88 /// FIXME: This assumes ModRefInfo lattice will remain 4 bits! 89 /// It overlaps with ModRefInfo::Must bit! 90 /// FunctionInfo.getModRefInfo() masks out everything except ModRef so 91 /// this remains correct, but the Must info is lost. 92 enum { MayReadAnyGlobal = 4 }; 93 94 /// Checks to document the invariants of the bit packing here. 95 static_assert((MayReadAnyGlobal & static_cast<int>(ModRefInfo::MustModRef)) == 96 0, 97 "ModRef and the MayReadAnyGlobal flag bits overlap."); 98 static_assert(((MayReadAnyGlobal | 99 static_cast<int>(ModRefInfo::MustModRef)) >> 100 AlignedMapPointerTraits::NumLowBitsAvailable) == 0, 101 "Insufficient low bits to store our flag and ModRef info."); 102 103 public: 104 FunctionInfo() = default; 105 ~FunctionInfo() { 106 delete Info.getPointer(); 107 } 108 // Spell out the copy ond move constructors and assignment operators to get 109 // deep copy semantics and correct move semantics in the face of the 110 // pointer-int pair. 111 FunctionInfo(const FunctionInfo &Arg) 112 : Info(nullptr, Arg.Info.getInt()) { 113 if (const auto *ArgPtr = Arg.Info.getPointer()) 114 Info.setPointer(new AlignedMap(*ArgPtr)); 115 } 116 FunctionInfo(FunctionInfo &&Arg) 117 : Info(Arg.Info.getPointer(), Arg.Info.getInt()) { 118 Arg.Info.setPointerAndInt(nullptr, 0); 119 } 120 FunctionInfo &operator=(const FunctionInfo &RHS) { 121 delete Info.getPointer(); 122 Info.setPointerAndInt(nullptr, RHS.Info.getInt()); 123 if (const auto *RHSPtr = RHS.Info.getPointer()) 124 Info.setPointer(new AlignedMap(*RHSPtr)); 125 return *this; 126 } 127 FunctionInfo &operator=(FunctionInfo &&RHS) { 128 delete Info.getPointer(); 129 Info.setPointerAndInt(RHS.Info.getPointer(), RHS.Info.getInt()); 130 RHS.Info.setPointerAndInt(nullptr, 0); 131 return *this; 132 } 133 134 /// This method clears MayReadAnyGlobal bit added by GlobalsAAResult to return 135 /// the corresponding ModRefInfo. It must align in functionality with 136 /// clearMust(). 137 ModRefInfo globalClearMayReadAnyGlobal(int I) const { 138 return ModRefInfo((I & static_cast<int>(ModRefInfo::ModRef)) | 139 static_cast<int>(ModRefInfo::NoModRef)); 140 } 141 142 /// Returns the \c ModRefInfo info for this function. 143 ModRefInfo getModRefInfo() const { 144 return globalClearMayReadAnyGlobal(Info.getInt()); 145 } 146 147 /// Adds new \c ModRefInfo for this function to its state. 148 void addModRefInfo(ModRefInfo NewMRI) { 149 Info.setInt(Info.getInt() | static_cast<int>(setMust(NewMRI))); 150 } 151 152 /// Returns whether this function may read any global variable, and we don't 153 /// know which global. 154 bool mayReadAnyGlobal() const { return Info.getInt() & MayReadAnyGlobal; } 155 156 /// Sets this function as potentially reading from any global. 157 void setMayReadAnyGlobal() { Info.setInt(Info.getInt() | MayReadAnyGlobal); } 158 159 /// Returns the \c ModRefInfo info for this function w.r.t. a particular 160 /// global, which may be more precise than the general information above. 161 ModRefInfo getModRefInfoForGlobal(const GlobalValue &GV) const { 162 ModRefInfo GlobalMRI = 163 mayReadAnyGlobal() ? ModRefInfo::Ref : ModRefInfo::NoModRef; 164 if (AlignedMap *P = Info.getPointer()) { 165 auto I = P->Map.find(&GV); 166 if (I != P->Map.end()) 167 GlobalMRI = unionModRef(GlobalMRI, I->second); 168 } 169 return GlobalMRI; 170 } 171 172 /// Add mod/ref info from another function into ours, saturating towards 173 /// ModRef. 174 void addFunctionInfo(const FunctionInfo &FI) { 175 addModRefInfo(FI.getModRefInfo()); 176 177 if (FI.mayReadAnyGlobal()) 178 setMayReadAnyGlobal(); 179 180 if (AlignedMap *P = FI.Info.getPointer()) 181 for (const auto &G : P->Map) 182 addModRefInfoForGlobal(*G.first, G.second); 183 } 184 185 void addModRefInfoForGlobal(const GlobalValue &GV, ModRefInfo NewMRI) { 186 AlignedMap *P = Info.getPointer(); 187 if (!P) { 188 P = new AlignedMap(); 189 Info.setPointer(P); 190 } 191 auto &GlobalMRI = P->Map[&GV]; 192 GlobalMRI = unionModRef(GlobalMRI, NewMRI); 193 } 194 195 /// Clear a global's ModRef info. Should be used when a global is being 196 /// deleted. 197 void eraseModRefInfoForGlobal(const GlobalValue &GV) { 198 if (AlignedMap *P = Info.getPointer()) 199 P->Map.erase(&GV); 200 } 201 202 private: 203 /// All of the information is encoded into a single pointer, with a three bit 204 /// integer in the low three bits. The high bit provides a flag for when this 205 /// function may read any global. The low two bits are the ModRefInfo. And 206 /// the pointer, when non-null, points to a map from GlobalValue to 207 /// ModRefInfo specific to that GlobalValue. 208 PointerIntPair<AlignedMap *, 3, unsigned, AlignedMapPointerTraits> Info; 209 }; 210 211 void GlobalsAAResult::DeletionCallbackHandle::deleted() { 212 Value *V = getValPtr(); 213 if (auto *F = dyn_cast<Function>(V)) 214 GAR->FunctionInfos.erase(F); 215 216 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) { 217 if (GAR->NonAddressTakenGlobals.erase(GV)) { 218 // This global might be an indirect global. If so, remove it and 219 // remove any AllocRelatedValues for it. 220 if (GAR->IndirectGlobals.erase(GV)) { 221 // Remove any entries in AllocsForIndirectGlobals for this global. 222 for (auto I = GAR->AllocsForIndirectGlobals.begin(), 223 E = GAR->AllocsForIndirectGlobals.end(); 224 I != E; ++I) 225 if (I->second == GV) 226 GAR->AllocsForIndirectGlobals.erase(I); 227 } 228 229 // Scan the function info we have collected and remove this global 230 // from all of them. 231 for (auto &FIPair : GAR->FunctionInfos) 232 FIPair.second.eraseModRefInfoForGlobal(*GV); 233 } 234 } 235 236 // If this is an allocation related to an indirect global, remove it. 237 GAR->AllocsForIndirectGlobals.erase(V); 238 239 // And clear out the handle. 240 setValPtr(nullptr); 241 GAR->Handles.erase(I); 242 // This object is now destroyed! 243 } 244 245 FunctionModRefBehavior GlobalsAAResult::getModRefBehavior(const Function *F) { 246 FunctionModRefBehavior Min = FMRB_UnknownModRefBehavior; 247 248 if (FunctionInfo *FI = getFunctionInfo(F)) { 249 if (!isModOrRefSet(FI->getModRefInfo())) 250 Min = FMRB_DoesNotAccessMemory; 251 else if (!isModSet(FI->getModRefInfo())) 252 Min = FMRB_OnlyReadsMemory; 253 } 254 255 return FunctionModRefBehavior(AAResultBase::getModRefBehavior(F) & Min); 256 } 257 258 FunctionModRefBehavior 259 GlobalsAAResult::getModRefBehavior(const CallBase *Call) { 260 FunctionModRefBehavior Min = FMRB_UnknownModRefBehavior; 261 262 if (!Call->hasOperandBundles()) 263 if (const Function *F = Call->getCalledFunction()) 264 if (FunctionInfo *FI = getFunctionInfo(F)) { 265 if (!isModOrRefSet(FI->getModRefInfo())) 266 Min = FMRB_DoesNotAccessMemory; 267 else if (!isModSet(FI->getModRefInfo())) 268 Min = FMRB_OnlyReadsMemory; 269 } 270 271 return FunctionModRefBehavior(AAResultBase::getModRefBehavior(Call) & Min); 272 } 273 274 /// Returns the function info for the function, or null if we don't have 275 /// anything useful to say about it. 276 GlobalsAAResult::FunctionInfo * 277 GlobalsAAResult::getFunctionInfo(const Function *F) { 278 auto I = FunctionInfos.find(F); 279 if (I != FunctionInfos.end()) 280 return &I->second; 281 return nullptr; 282 } 283 284 /// AnalyzeGlobals - Scan through the users of all of the internal 285 /// GlobalValue's in the program. If none of them have their "address taken" 286 /// (really, their address passed to something nontrivial), record this fact, 287 /// and record the functions that they are used directly in. 288 void GlobalsAAResult::AnalyzeGlobals(Module &M) { 289 SmallPtrSet<Function *, 32> TrackedFunctions; 290 for (Function &F : M) 291 if (F.hasLocalLinkage()) { 292 if (!AnalyzeUsesOfPointer(&F)) { 293 // Remember that we are tracking this global. 294 NonAddressTakenGlobals.insert(&F); 295 TrackedFunctions.insert(&F); 296 Handles.emplace_front(*this, &F); 297 Handles.front().I = Handles.begin(); 298 ++NumNonAddrTakenFunctions; 299 } else 300 UnknownFunctionsWithLocalLinkage = true; 301 } 302 303 SmallPtrSet<Function *, 16> Readers, Writers; 304 for (GlobalVariable &GV : M.globals()) 305 if (GV.hasLocalLinkage()) { 306 if (!AnalyzeUsesOfPointer(&GV, &Readers, 307 GV.isConstant() ? nullptr : &Writers)) { 308 // Remember that we are tracking this global, and the mod/ref fns 309 NonAddressTakenGlobals.insert(&GV); 310 Handles.emplace_front(*this, &GV); 311 Handles.front().I = Handles.begin(); 312 313 for (Function *Reader : Readers) { 314 if (TrackedFunctions.insert(Reader).second) { 315 Handles.emplace_front(*this, Reader); 316 Handles.front().I = Handles.begin(); 317 } 318 FunctionInfos[Reader].addModRefInfoForGlobal(GV, ModRefInfo::Ref); 319 } 320 321 if (!GV.isConstant()) // No need to keep track of writers to constants 322 for (Function *Writer : Writers) { 323 if (TrackedFunctions.insert(Writer).second) { 324 Handles.emplace_front(*this, Writer); 325 Handles.front().I = Handles.begin(); 326 } 327 FunctionInfos[Writer].addModRefInfoForGlobal(GV, ModRefInfo::Mod); 328 } 329 ++NumNonAddrTakenGlobalVars; 330 331 // If this global holds a pointer type, see if it is an indirect global. 332 if (GV.getValueType()->isPointerTy() && 333 AnalyzeIndirectGlobalMemory(&GV)) 334 ++NumIndirectGlobalVars; 335 } 336 Readers.clear(); 337 Writers.clear(); 338 } 339 } 340 341 /// AnalyzeUsesOfPointer - Look at all of the users of the specified pointer. 342 /// If this is used by anything complex (i.e., the address escapes), return 343 /// true. Also, while we are at it, keep track of those functions that read and 344 /// write to the value. 345 /// 346 /// If OkayStoreDest is non-null, stores into this global are allowed. 347 bool GlobalsAAResult::AnalyzeUsesOfPointer(Value *V, 348 SmallPtrSetImpl<Function *> *Readers, 349 SmallPtrSetImpl<Function *> *Writers, 350 GlobalValue *OkayStoreDest) { 351 if (!V->getType()->isPointerTy()) 352 return true; 353 354 for (Use &U : V->uses()) { 355 User *I = U.getUser(); 356 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 357 if (Readers) 358 Readers->insert(LI->getParent()->getParent()); 359 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) { 360 if (V == SI->getOperand(1)) { 361 if (Writers) 362 Writers->insert(SI->getParent()->getParent()); 363 } else if (SI->getOperand(1) != OkayStoreDest) { 364 return true; // Storing the pointer 365 } 366 } else if (Operator::getOpcode(I) == Instruction::GetElementPtr) { 367 if (AnalyzeUsesOfPointer(I, Readers, Writers)) 368 return true; 369 } else if (Operator::getOpcode(I) == Instruction::BitCast || 370 Operator::getOpcode(I) == Instruction::AddrSpaceCast) { 371 if (AnalyzeUsesOfPointer(I, Readers, Writers, OkayStoreDest)) 372 return true; 373 } else if (auto *Call = dyn_cast<CallBase>(I)) { 374 // Make sure that this is just the function being called, not that it is 375 // passing into the function. 376 if (Call->isDataOperand(&U)) { 377 // Detect calls to free. 378 if (Call->isArgOperand(&U) && 379 isFreeCall(I, &GetTLI(*Call->getFunction()))) { 380 if (Writers) 381 Writers->insert(Call->getParent()->getParent()); 382 } else { 383 return true; // Argument of an unknown call. 384 } 385 } 386 } else if (ICmpInst *ICI = dyn_cast<ICmpInst>(I)) { 387 if (!isa<ConstantPointerNull>(ICI->getOperand(1))) 388 return true; // Allow comparison against null. 389 } else if (Constant *C = dyn_cast<Constant>(I)) { 390 // Ignore constants which don't have any live uses. 391 if (isa<GlobalValue>(C) || C->isConstantUsed()) 392 return true; 393 } else { 394 return true; 395 } 396 } 397 398 return false; 399 } 400 401 /// AnalyzeIndirectGlobalMemory - We found an non-address-taken global variable 402 /// which holds a pointer type. See if the global always points to non-aliased 403 /// heap memory: that is, all initializers of the globals store a value known 404 /// to be obtained via a noalias return function call which have no other use. 405 /// Further, all loads out of GV must directly use the memory, not store the 406 /// pointer somewhere. If this is true, we consider the memory pointed to by 407 /// GV to be owned by GV and can disambiguate other pointers from it. 408 bool GlobalsAAResult::AnalyzeIndirectGlobalMemory(GlobalVariable *GV) { 409 // Keep track of values related to the allocation of the memory, f.e. the 410 // value produced by the noalias call and any casts. 411 std::vector<Value *> AllocRelatedValues; 412 413 // If the initializer is a valid pointer, bail. 414 if (Constant *C = GV->getInitializer()) 415 if (!C->isNullValue()) 416 return false; 417 418 // Walk the user list of the global. If we find anything other than a direct 419 // load or store, bail out. 420 for (User *U : GV->users()) { 421 if (LoadInst *LI = dyn_cast<LoadInst>(U)) { 422 // The pointer loaded from the global can only be used in simple ways: 423 // we allow addressing of it and loading storing to it. We do *not* allow 424 // storing the loaded pointer somewhere else or passing to a function. 425 if (AnalyzeUsesOfPointer(LI)) 426 return false; // Loaded pointer escapes. 427 // TODO: Could try some IP mod/ref of the loaded pointer. 428 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) { 429 // Storing the global itself. 430 if (SI->getOperand(0) == GV) 431 return false; 432 433 // If storing the null pointer, ignore it. 434 if (isa<ConstantPointerNull>(SI->getOperand(0))) 435 continue; 436 437 // Check the value being stored. 438 Value *Ptr = getUnderlyingObject(SI->getOperand(0)); 439 440 if (!isNoAliasCall(Ptr)) 441 return false; // Too hard to analyze. 442 443 // Analyze all uses of the allocation. If any of them are used in a 444 // non-simple way (e.g. stored to another global) bail out. 445 if (AnalyzeUsesOfPointer(Ptr, /*Readers*/ nullptr, /*Writers*/ nullptr, 446 GV)) 447 return false; // Loaded pointer escapes. 448 449 // Remember that this allocation is related to the indirect global. 450 AllocRelatedValues.push_back(Ptr); 451 } else { 452 // Something complex, bail out. 453 return false; 454 } 455 } 456 457 // Okay, this is an indirect global. Remember all of the allocations for 458 // this global in AllocsForIndirectGlobals. 459 while (!AllocRelatedValues.empty()) { 460 AllocsForIndirectGlobals[AllocRelatedValues.back()] = GV; 461 Handles.emplace_front(*this, AllocRelatedValues.back()); 462 Handles.front().I = Handles.begin(); 463 AllocRelatedValues.pop_back(); 464 } 465 IndirectGlobals.insert(GV); 466 Handles.emplace_front(*this, GV); 467 Handles.front().I = Handles.begin(); 468 return true; 469 } 470 471 void GlobalsAAResult::CollectSCCMembership(CallGraph &CG) { 472 // We do a bottom-up SCC traversal of the call graph. In other words, we 473 // visit all callees before callers (leaf-first). 474 unsigned SCCID = 0; 475 for (scc_iterator<CallGraph *> I = scc_begin(&CG); !I.isAtEnd(); ++I) { 476 const std::vector<CallGraphNode *> &SCC = *I; 477 assert(!SCC.empty() && "SCC with no functions?"); 478 479 for (auto *CGN : SCC) 480 if (Function *F = CGN->getFunction()) 481 FunctionToSCCMap[F] = SCCID; 482 ++SCCID; 483 } 484 } 485 486 /// AnalyzeCallGraph - At this point, we know the functions where globals are 487 /// immediately stored to and read from. Propagate this information up the call 488 /// graph to all callers and compute the mod/ref info for all memory for each 489 /// function. 490 void GlobalsAAResult::AnalyzeCallGraph(CallGraph &CG, Module &M) { 491 // We do a bottom-up SCC traversal of the call graph. In other words, we 492 // visit all callees before callers (leaf-first). 493 for (scc_iterator<CallGraph *> I = scc_begin(&CG); !I.isAtEnd(); ++I) { 494 const std::vector<CallGraphNode *> &SCC = *I; 495 assert(!SCC.empty() && "SCC with no functions?"); 496 497 Function *F = SCC[0]->getFunction(); 498 499 if (!F || !F->isDefinitionExact()) { 500 // Calls externally or not exact - can't say anything useful. Remove any 501 // existing function records (may have been created when scanning 502 // globals). 503 for (auto *Node : SCC) 504 FunctionInfos.erase(Node->getFunction()); 505 continue; 506 } 507 508 FunctionInfo &FI = FunctionInfos[F]; 509 Handles.emplace_front(*this, F); 510 Handles.front().I = Handles.begin(); 511 bool KnowNothing = false; 512 513 // Collect the mod/ref properties due to called functions. We only compute 514 // one mod-ref set. 515 for (unsigned i = 0, e = SCC.size(); i != e && !KnowNothing; ++i) { 516 if (!F) { 517 KnowNothing = true; 518 break; 519 } 520 521 if (F->isDeclaration() || F->hasOptNone()) { 522 // Try to get mod/ref behaviour from function attributes. 523 if (F->doesNotAccessMemory()) { 524 // Can't do better than that! 525 } else if (F->onlyReadsMemory()) { 526 FI.addModRefInfo(ModRefInfo::Ref); 527 if (!F->isIntrinsic() && !F->onlyAccessesArgMemory()) 528 // This function might call back into the module and read a global - 529 // consider every global as possibly being read by this function. 530 FI.setMayReadAnyGlobal(); 531 } else { 532 FI.addModRefInfo(ModRefInfo::ModRef); 533 if (!F->onlyAccessesArgMemory()) 534 FI.setMayReadAnyGlobal(); 535 if (!F->isIntrinsic()) { 536 KnowNothing = true; 537 break; 538 } 539 } 540 continue; 541 } 542 543 for (CallGraphNode::iterator CI = SCC[i]->begin(), E = SCC[i]->end(); 544 CI != E && !KnowNothing; ++CI) 545 if (Function *Callee = CI->second->getFunction()) { 546 if (FunctionInfo *CalleeFI = getFunctionInfo(Callee)) { 547 // Propagate function effect up. 548 FI.addFunctionInfo(*CalleeFI); 549 } else { 550 // Can't say anything about it. However, if it is inside our SCC, 551 // then nothing needs to be done. 552 CallGraphNode *CalleeNode = CG[Callee]; 553 if (!is_contained(SCC, CalleeNode)) 554 KnowNothing = true; 555 } 556 } else { 557 KnowNothing = true; 558 } 559 } 560 561 // If we can't say anything useful about this SCC, remove all SCC functions 562 // from the FunctionInfos map. 563 if (KnowNothing) { 564 for (auto *Node : SCC) 565 FunctionInfos.erase(Node->getFunction()); 566 continue; 567 } 568 569 // Scan the function bodies for explicit loads or stores. 570 for (auto *Node : SCC) { 571 if (isModAndRefSet(FI.getModRefInfo())) 572 break; // The mod/ref lattice saturates here. 573 574 // Don't prove any properties based on the implementation of an optnone 575 // function. Function attributes were already used as a best approximation 576 // above. 577 if (Node->getFunction()->hasOptNone()) 578 continue; 579 580 for (Instruction &I : instructions(Node->getFunction())) { 581 if (isModAndRefSet(FI.getModRefInfo())) 582 break; // The mod/ref lattice saturates here. 583 584 // We handle calls specially because the graph-relevant aspects are 585 // handled above. 586 if (auto *Call = dyn_cast<CallBase>(&I)) { 587 auto &TLI = GetTLI(*Node->getFunction()); 588 if (isAllocationFn(Call, &TLI) || isFreeCall(Call, &TLI)) { 589 // FIXME: It is completely unclear why this is necessary and not 590 // handled by the above graph code. 591 FI.addModRefInfo(ModRefInfo::ModRef); 592 } else if (Function *Callee = Call->getCalledFunction()) { 593 // The callgraph doesn't include intrinsic calls. 594 if (Callee->isIntrinsic()) { 595 if (isa<DbgInfoIntrinsic>(Call)) 596 // Don't let dbg intrinsics affect alias info. 597 continue; 598 599 FunctionModRefBehavior Behaviour = 600 AAResultBase::getModRefBehavior(Callee); 601 FI.addModRefInfo(createModRefInfo(Behaviour)); 602 } 603 } 604 continue; 605 } 606 607 // All non-call instructions we use the primary predicates for whether 608 // they read or write memory. 609 if (I.mayReadFromMemory()) 610 FI.addModRefInfo(ModRefInfo::Ref); 611 if (I.mayWriteToMemory()) 612 FI.addModRefInfo(ModRefInfo::Mod); 613 } 614 } 615 616 if (!isModSet(FI.getModRefInfo())) 617 ++NumReadMemFunctions; 618 if (!isModOrRefSet(FI.getModRefInfo())) 619 ++NumNoMemFunctions; 620 621 // Finally, now that we know the full effect on this SCC, clone the 622 // information to each function in the SCC. 623 // FI is a reference into FunctionInfos, so copy it now so that it doesn't 624 // get invalidated if DenseMap decides to re-hash. 625 FunctionInfo CachedFI = FI; 626 for (unsigned i = 1, e = SCC.size(); i != e; ++i) 627 FunctionInfos[SCC[i]->getFunction()] = CachedFI; 628 } 629 } 630 631 // GV is a non-escaping global. V is a pointer address that has been loaded from. 632 // If we can prove that V must escape, we can conclude that a load from V cannot 633 // alias GV. 634 static bool isNonEscapingGlobalNoAliasWithLoad(const GlobalValue *GV, 635 const Value *V, 636 int &Depth, 637 const DataLayout &DL) { 638 SmallPtrSet<const Value *, 8> Visited; 639 SmallVector<const Value *, 8> Inputs; 640 Visited.insert(V); 641 Inputs.push_back(V); 642 do { 643 const Value *Input = Inputs.pop_back_val(); 644 645 if (isa<GlobalValue>(Input) || isa<Argument>(Input) || isa<CallInst>(Input) || 646 isa<InvokeInst>(Input)) 647 // Arguments to functions or returns from functions are inherently 648 // escaping, so we can immediately classify those as not aliasing any 649 // non-addr-taken globals. 650 // 651 // (Transitive) loads from a global are also safe - if this aliased 652 // another global, its address would escape, so no alias. 653 continue; 654 655 // Recurse through a limited number of selects, loads and PHIs. This is an 656 // arbitrary depth of 4, lower numbers could be used to fix compile time 657 // issues if needed, but this is generally expected to be only be important 658 // for small depths. 659 if (++Depth > 4) 660 return false; 661 662 if (auto *LI = dyn_cast<LoadInst>(Input)) { 663 Inputs.push_back(getUnderlyingObject(LI->getPointerOperand())); 664 continue; 665 } 666 if (auto *SI = dyn_cast<SelectInst>(Input)) { 667 const Value *LHS = getUnderlyingObject(SI->getTrueValue()); 668 const Value *RHS = getUnderlyingObject(SI->getFalseValue()); 669 if (Visited.insert(LHS).second) 670 Inputs.push_back(LHS); 671 if (Visited.insert(RHS).second) 672 Inputs.push_back(RHS); 673 continue; 674 } 675 if (auto *PN = dyn_cast<PHINode>(Input)) { 676 for (const Value *Op : PN->incoming_values()) { 677 Op = getUnderlyingObject(Op); 678 if (Visited.insert(Op).second) 679 Inputs.push_back(Op); 680 } 681 continue; 682 } 683 684 return false; 685 } while (!Inputs.empty()); 686 687 // All inputs were known to be no-alias. 688 return true; 689 } 690 691 // There are particular cases where we can conclude no-alias between 692 // a non-addr-taken global and some other underlying object. Specifically, 693 // a non-addr-taken global is known to not be escaped from any function. It is 694 // also incorrect for a transformation to introduce an escape of a global in 695 // a way that is observable when it was not there previously. One function 696 // being transformed to introduce an escape which could possibly be observed 697 // (via loading from a global or the return value for example) within another 698 // function is never safe. If the observation is made through non-atomic 699 // operations on different threads, it is a data-race and UB. If the 700 // observation is well defined, by being observed the transformation would have 701 // changed program behavior by introducing the observed escape, making it an 702 // invalid transform. 703 // 704 // This property does require that transformations which *temporarily* escape 705 // a global that was not previously escaped, prior to restoring it, cannot rely 706 // on the results of GMR::alias. This seems a reasonable restriction, although 707 // currently there is no way to enforce it. There is also no realistic 708 // optimization pass that would make this mistake. The closest example is 709 // a transformation pass which does reg2mem of SSA values but stores them into 710 // global variables temporarily before restoring the global variable's value. 711 // This could be useful to expose "benign" races for example. However, it seems 712 // reasonable to require that a pass which introduces escapes of global 713 // variables in this way to either not trust AA results while the escape is 714 // active, or to be forced to operate as a module pass that cannot co-exist 715 // with an alias analysis such as GMR. 716 bool GlobalsAAResult::isNonEscapingGlobalNoAlias(const GlobalValue *GV, 717 const Value *V) { 718 // In order to know that the underlying object cannot alias the 719 // non-addr-taken global, we must know that it would have to be an escape. 720 // Thus if the underlying object is a function argument, a load from 721 // a global, or the return of a function, it cannot alias. We can also 722 // recurse through PHI nodes and select nodes provided all of their inputs 723 // resolve to one of these known-escaping roots. 724 SmallPtrSet<const Value *, 8> Visited; 725 SmallVector<const Value *, 8> Inputs; 726 Visited.insert(V); 727 Inputs.push_back(V); 728 int Depth = 0; 729 do { 730 const Value *Input = Inputs.pop_back_val(); 731 732 if (auto *InputGV = dyn_cast<GlobalValue>(Input)) { 733 // If one input is the very global we're querying against, then we can't 734 // conclude no-alias. 735 if (InputGV == GV) 736 return false; 737 738 // Distinct GlobalVariables never alias, unless overriden or zero-sized. 739 // FIXME: The condition can be refined, but be conservative for now. 740 auto *GVar = dyn_cast<GlobalVariable>(GV); 741 auto *InputGVar = dyn_cast<GlobalVariable>(InputGV); 742 if (GVar && InputGVar && 743 !GVar->isDeclaration() && !InputGVar->isDeclaration() && 744 !GVar->isInterposable() && !InputGVar->isInterposable()) { 745 Type *GVType = GVar->getInitializer()->getType(); 746 Type *InputGVType = InputGVar->getInitializer()->getType(); 747 if (GVType->isSized() && InputGVType->isSized() && 748 (DL.getTypeAllocSize(GVType) > 0) && 749 (DL.getTypeAllocSize(InputGVType) > 0)) 750 continue; 751 } 752 753 // Conservatively return false, even though we could be smarter 754 // (e.g. look through GlobalAliases). 755 return false; 756 } 757 758 if (isa<Argument>(Input) || isa<CallInst>(Input) || 759 isa<InvokeInst>(Input)) { 760 // Arguments to functions or returns from functions are inherently 761 // escaping, so we can immediately classify those as not aliasing any 762 // non-addr-taken globals. 763 continue; 764 } 765 766 // Recurse through a limited number of selects, loads and PHIs. This is an 767 // arbitrary depth of 4, lower numbers could be used to fix compile time 768 // issues if needed, but this is generally expected to be only be important 769 // for small depths. 770 if (++Depth > 4) 771 return false; 772 773 if (auto *LI = dyn_cast<LoadInst>(Input)) { 774 // A pointer loaded from a global would have been captured, and we know 775 // that the global is non-escaping, so no alias. 776 const Value *Ptr = getUnderlyingObject(LI->getPointerOperand()); 777 if (isNonEscapingGlobalNoAliasWithLoad(GV, Ptr, Depth, DL)) 778 // The load does not alias with GV. 779 continue; 780 // Otherwise, a load could come from anywhere, so bail. 781 return false; 782 } 783 if (auto *SI = dyn_cast<SelectInst>(Input)) { 784 const Value *LHS = getUnderlyingObject(SI->getTrueValue()); 785 const Value *RHS = getUnderlyingObject(SI->getFalseValue()); 786 if (Visited.insert(LHS).second) 787 Inputs.push_back(LHS); 788 if (Visited.insert(RHS).second) 789 Inputs.push_back(RHS); 790 continue; 791 } 792 if (auto *PN = dyn_cast<PHINode>(Input)) { 793 for (const Value *Op : PN->incoming_values()) { 794 Op = getUnderlyingObject(Op); 795 if (Visited.insert(Op).second) 796 Inputs.push_back(Op); 797 } 798 continue; 799 } 800 801 // FIXME: It would be good to handle other obvious no-alias cases here, but 802 // it isn't clear how to do so reasonably without building a small version 803 // of BasicAA into this code. We could recurse into AAResultBase::alias 804 // here but that seems likely to go poorly as we're inside the 805 // implementation of such a query. Until then, just conservatively return 806 // false. 807 return false; 808 } while (!Inputs.empty()); 809 810 // If all the inputs to V were definitively no-alias, then V is no-alias. 811 return true; 812 } 813 814 bool GlobalsAAResult::invalidate(Module &, const PreservedAnalyses &PA, 815 ModuleAnalysisManager::Invalidator &) { 816 // Check whether the analysis has been explicitly invalidated. Otherwise, it's 817 // stateless and remains preserved. 818 auto PAC = PA.getChecker<GlobalsAA>(); 819 return !PAC.preservedWhenStateless(); 820 } 821 822 /// alias - If one of the pointers is to a global that we are tracking, and the 823 /// other is some random pointer, we know there cannot be an alias, because the 824 /// address of the global isn't taken. 825 AliasResult GlobalsAAResult::alias(const MemoryLocation &LocA, 826 const MemoryLocation &LocB, 827 AAQueryInfo &AAQI) { 828 // Get the base object these pointers point to. 829 const Value *UV1 = 830 getUnderlyingObject(LocA.Ptr->stripPointerCastsForAliasAnalysis()); 831 const Value *UV2 = 832 getUnderlyingObject(LocB.Ptr->stripPointerCastsForAliasAnalysis()); 833 834 // If either of the underlying values is a global, they may be non-addr-taken 835 // globals, which we can answer queries about. 836 const GlobalValue *GV1 = dyn_cast<GlobalValue>(UV1); 837 const GlobalValue *GV2 = dyn_cast<GlobalValue>(UV2); 838 if (GV1 || GV2) { 839 // If the global's address is taken, pretend we don't know it's a pointer to 840 // the global. 841 if (GV1 && !NonAddressTakenGlobals.count(GV1)) 842 GV1 = nullptr; 843 if (GV2 && !NonAddressTakenGlobals.count(GV2)) 844 GV2 = nullptr; 845 846 // If the two pointers are derived from two different non-addr-taken 847 // globals we know these can't alias. 848 if (GV1 && GV2 && GV1 != GV2) 849 return AliasResult::NoAlias; 850 851 // If one is and the other isn't, it isn't strictly safe but we can fake 852 // this result if necessary for performance. This does not appear to be 853 // a common problem in practice. 854 if (EnableUnsafeGlobalsModRefAliasResults) 855 if ((GV1 || GV2) && GV1 != GV2) 856 return AliasResult::NoAlias; 857 858 // Check for a special case where a non-escaping global can be used to 859 // conclude no-alias. 860 if ((GV1 || GV2) && GV1 != GV2) { 861 const GlobalValue *GV = GV1 ? GV1 : GV2; 862 const Value *UV = GV1 ? UV2 : UV1; 863 if (isNonEscapingGlobalNoAlias(GV, UV)) 864 return AliasResult::NoAlias; 865 } 866 867 // Otherwise if they are both derived from the same addr-taken global, we 868 // can't know the two accesses don't overlap. 869 } 870 871 // These pointers may be based on the memory owned by an indirect global. If 872 // so, we may be able to handle this. First check to see if the base pointer 873 // is a direct load from an indirect global. 874 GV1 = GV2 = nullptr; 875 if (const LoadInst *LI = dyn_cast<LoadInst>(UV1)) 876 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getOperand(0))) 877 if (IndirectGlobals.count(GV)) 878 GV1 = GV; 879 if (const LoadInst *LI = dyn_cast<LoadInst>(UV2)) 880 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getOperand(0))) 881 if (IndirectGlobals.count(GV)) 882 GV2 = GV; 883 884 // These pointers may also be from an allocation for the indirect global. If 885 // so, also handle them. 886 if (!GV1) 887 GV1 = AllocsForIndirectGlobals.lookup(UV1); 888 if (!GV2) 889 GV2 = AllocsForIndirectGlobals.lookup(UV2); 890 891 // Now that we know whether the two pointers are related to indirect globals, 892 // use this to disambiguate the pointers. If the pointers are based on 893 // different indirect globals they cannot alias. 894 if (GV1 && GV2 && GV1 != GV2) 895 return AliasResult::NoAlias; 896 897 // If one is based on an indirect global and the other isn't, it isn't 898 // strictly safe but we can fake this result if necessary for performance. 899 // This does not appear to be a common problem in practice. 900 if (EnableUnsafeGlobalsModRefAliasResults) 901 if ((GV1 || GV2) && GV1 != GV2) 902 return AliasResult::NoAlias; 903 904 return AAResultBase::alias(LocA, LocB, AAQI); 905 } 906 907 ModRefInfo GlobalsAAResult::getModRefInfoForArgument(const CallBase *Call, 908 const GlobalValue *GV, 909 AAQueryInfo &AAQI) { 910 if (Call->doesNotAccessMemory()) 911 return ModRefInfo::NoModRef; 912 ModRefInfo ConservativeResult = 913 Call->onlyReadsMemory() ? ModRefInfo::Ref : ModRefInfo::ModRef; 914 915 // Iterate through all the arguments to the called function. If any argument 916 // is based on GV, return the conservative result. 917 for (auto &A : Call->args()) { 918 SmallVector<const Value*, 4> Objects; 919 getUnderlyingObjects(A, Objects); 920 921 // All objects must be identified. 922 if (!all_of(Objects, isIdentifiedObject) && 923 // Try ::alias to see if all objects are known not to alias GV. 924 !all_of(Objects, [&](const Value *V) { 925 return this->alias(MemoryLocation::getBeforeOrAfter(V), 926 MemoryLocation::getBeforeOrAfter(GV), 927 AAQI) == AliasResult::NoAlias; 928 })) 929 return ConservativeResult; 930 931 if (is_contained(Objects, GV)) 932 return ConservativeResult; 933 } 934 935 // We identified all objects in the argument list, and none of them were GV. 936 return ModRefInfo::NoModRef; 937 } 938 939 ModRefInfo GlobalsAAResult::getModRefInfo(const CallBase *Call, 940 const MemoryLocation &Loc, 941 AAQueryInfo &AAQI) { 942 ModRefInfo Known = ModRefInfo::ModRef; 943 944 // If we are asking for mod/ref info of a direct call with a pointer to a 945 // global we are tracking, return information if we have it. 946 if (const GlobalValue *GV = 947 dyn_cast<GlobalValue>(getUnderlyingObject(Loc.Ptr))) 948 // If GV is internal to this IR and there is no function with local linkage 949 // that has had their address taken, keep looking for a tighter ModRefInfo. 950 if (GV->hasLocalLinkage() && !UnknownFunctionsWithLocalLinkage) 951 if (const Function *F = Call->getCalledFunction()) 952 if (NonAddressTakenGlobals.count(GV)) 953 if (const FunctionInfo *FI = getFunctionInfo(F)) 954 Known = unionModRef(FI->getModRefInfoForGlobal(*GV), 955 getModRefInfoForArgument(Call, GV, AAQI)); 956 957 if (!isModOrRefSet(Known)) 958 return ModRefInfo::NoModRef; // No need to query other mod/ref analyses 959 return intersectModRef(Known, AAResultBase::getModRefInfo(Call, Loc, AAQI)); 960 } 961 962 GlobalsAAResult::GlobalsAAResult( 963 const DataLayout &DL, 964 std::function<const TargetLibraryInfo &(Function &F)> GetTLI) 965 : DL(DL), GetTLI(std::move(GetTLI)) {} 966 967 GlobalsAAResult::GlobalsAAResult(GlobalsAAResult &&Arg) 968 : AAResultBase(std::move(Arg)), DL(Arg.DL), GetTLI(std::move(Arg.GetTLI)), 969 NonAddressTakenGlobals(std::move(Arg.NonAddressTakenGlobals)), 970 IndirectGlobals(std::move(Arg.IndirectGlobals)), 971 AllocsForIndirectGlobals(std::move(Arg.AllocsForIndirectGlobals)), 972 FunctionInfos(std::move(Arg.FunctionInfos)), 973 Handles(std::move(Arg.Handles)) { 974 // Update the parent for each DeletionCallbackHandle. 975 for (auto &H : Handles) { 976 assert(H.GAR == &Arg); 977 H.GAR = this; 978 } 979 } 980 981 GlobalsAAResult::~GlobalsAAResult() = default; 982 983 /*static*/ GlobalsAAResult GlobalsAAResult::analyzeModule( 984 Module &M, std::function<const TargetLibraryInfo &(Function &F)> GetTLI, 985 CallGraph &CG) { 986 GlobalsAAResult Result(M.getDataLayout(), GetTLI); 987 988 // Discover which functions aren't recursive, to feed into AnalyzeGlobals. 989 Result.CollectSCCMembership(CG); 990 991 // Find non-addr taken globals. 992 Result.AnalyzeGlobals(M); 993 994 // Propagate on CG. 995 Result.AnalyzeCallGraph(CG, M); 996 997 return Result; 998 } 999 1000 AnalysisKey GlobalsAA::Key; 1001 1002 GlobalsAAResult GlobalsAA::run(Module &M, ModuleAnalysisManager &AM) { 1003 FunctionAnalysisManager &FAM = 1004 AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager(); 1005 auto GetTLI = [&FAM](Function &F) -> TargetLibraryInfo & { 1006 return FAM.getResult<TargetLibraryAnalysis>(F); 1007 }; 1008 return GlobalsAAResult::analyzeModule(M, GetTLI, 1009 AM.getResult<CallGraphAnalysis>(M)); 1010 } 1011 1012 char GlobalsAAWrapperPass::ID = 0; 1013 INITIALIZE_PASS_BEGIN(GlobalsAAWrapperPass, "globals-aa", 1014 "Globals Alias Analysis", false, true) 1015 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass) 1016 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 1017 INITIALIZE_PASS_END(GlobalsAAWrapperPass, "globals-aa", 1018 "Globals Alias Analysis", false, true) 1019 1020 ModulePass *llvm::createGlobalsAAWrapperPass() { 1021 return new GlobalsAAWrapperPass(); 1022 } 1023 1024 GlobalsAAWrapperPass::GlobalsAAWrapperPass() : ModulePass(ID) { 1025 initializeGlobalsAAWrapperPassPass(*PassRegistry::getPassRegistry()); 1026 } 1027 1028 bool GlobalsAAWrapperPass::runOnModule(Module &M) { 1029 auto GetTLI = [this](Function &F) -> TargetLibraryInfo & { 1030 return this->getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F); 1031 }; 1032 Result.reset(new GlobalsAAResult(GlobalsAAResult::analyzeModule( 1033 M, GetTLI, getAnalysis<CallGraphWrapperPass>().getCallGraph()))); 1034 return false; 1035 } 1036 1037 bool GlobalsAAWrapperPass::doFinalization(Module &M) { 1038 Result.reset(); 1039 return false; 1040 } 1041 1042 void GlobalsAAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 1043 AU.setPreservesAll(); 1044 AU.addRequired<CallGraphWrapperPass>(); 1045 AU.addRequired<TargetLibraryInfoWrapperPass>(); 1046 } 1047