1 //===- ModuleSummaryAnalysis.cpp - Module summary index builder -----------===// 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 pass builds a ModuleSummaryIndex object for the module, to be written 10 // to bitcode or LLVM assembly. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/Analysis/ModuleSummaryAnalysis.h" 15 #include "llvm/ADT/ArrayRef.h" 16 #include "llvm/ADT/DenseSet.h" 17 #include "llvm/ADT/MapVector.h" 18 #include "llvm/ADT/STLExtras.h" 19 #include "llvm/ADT/SetVector.h" 20 #include "llvm/ADT/SmallPtrSet.h" 21 #include "llvm/ADT/SmallVector.h" 22 #include "llvm/ADT/StringRef.h" 23 #include "llvm/Analysis/BlockFrequencyInfo.h" 24 #include "llvm/Analysis/BranchProbabilityInfo.h" 25 #include "llvm/Analysis/IndirectCallPromotionAnalysis.h" 26 #include "llvm/Analysis/LoopInfo.h" 27 #include "llvm/Analysis/MemoryProfileInfo.h" 28 #include "llvm/Analysis/ProfileSummaryInfo.h" 29 #include "llvm/Analysis/StackSafetyAnalysis.h" 30 #include "llvm/Analysis/TypeMetadataUtils.h" 31 #include "llvm/IR/Attributes.h" 32 #include "llvm/IR/BasicBlock.h" 33 #include "llvm/IR/Constant.h" 34 #include "llvm/IR/Constants.h" 35 #include "llvm/IR/Dominators.h" 36 #include "llvm/IR/Function.h" 37 #include "llvm/IR/GlobalAlias.h" 38 #include "llvm/IR/GlobalValue.h" 39 #include "llvm/IR/GlobalVariable.h" 40 #include "llvm/IR/Instructions.h" 41 #include "llvm/IR/IntrinsicInst.h" 42 #include "llvm/IR/Metadata.h" 43 #include "llvm/IR/Module.h" 44 #include "llvm/IR/ModuleSummaryIndex.h" 45 #include "llvm/IR/Use.h" 46 #include "llvm/IR/User.h" 47 #include "llvm/InitializePasses.h" 48 #include "llvm/Object/ModuleSymbolTable.h" 49 #include "llvm/Object/SymbolicFile.h" 50 #include "llvm/Pass.h" 51 #include "llvm/Support/Casting.h" 52 #include "llvm/Support/CommandLine.h" 53 #include "llvm/Support/FileSystem.h" 54 #include <algorithm> 55 #include <cassert> 56 #include <cstdint> 57 #include <vector> 58 59 using namespace llvm; 60 using namespace llvm::memprof; 61 62 #define DEBUG_TYPE "module-summary-analysis" 63 64 // Option to force edges cold which will block importing when the 65 // -import-cold-multiplier is set to 0. Useful for debugging. 66 namespace llvm { 67 FunctionSummary::ForceSummaryHotnessType ForceSummaryEdgesCold = 68 FunctionSummary::FSHT_None; 69 } // namespace llvm 70 71 static cl::opt<FunctionSummary::ForceSummaryHotnessType, true> FSEC( 72 "force-summary-edges-cold", cl::Hidden, cl::location(ForceSummaryEdgesCold), 73 cl::desc("Force all edges in the function summary to cold"), 74 cl::values(clEnumValN(FunctionSummary::FSHT_None, "none", "None."), 75 clEnumValN(FunctionSummary::FSHT_AllNonCritical, 76 "all-non-critical", "All non-critical edges."), 77 clEnumValN(FunctionSummary::FSHT_All, "all", "All edges."))); 78 79 static cl::opt<std::string> ModuleSummaryDotFile( 80 "module-summary-dot-file", cl::Hidden, cl::value_desc("filename"), 81 cl::desc("File to emit dot graph of new summary into")); 82 83 extern cl::opt<bool> ScalePartialSampleProfileWorkingSetSize; 84 85 extern cl::opt<unsigned> MaxNumVTableAnnotations; 86 87 // Walk through the operands of a given User via worklist iteration and populate 88 // the set of GlobalValue references encountered. Invoked either on an 89 // Instruction or a GlobalVariable (which walks its initializer). 90 // Return true if any of the operands contains blockaddress. This is important 91 // to know when computing summary for global var, because if global variable 92 // references basic block address we can't import it separately from function 93 // containing that basic block. For simplicity we currently don't import such 94 // global vars at all. When importing function we aren't interested if any 95 // instruction in it takes an address of any basic block, because instruction 96 // can only take an address of basic block located in the same function. 97 static bool findRefEdges(ModuleSummaryIndex &Index, const User *CurUser, 98 SetVector<ValueInfo, std::vector<ValueInfo>> &RefEdges, 99 SmallPtrSet<const User *, 8> &Visited) { 100 bool HasBlockAddress = false; 101 SmallVector<const User *, 32> Worklist; 102 if (Visited.insert(CurUser).second) 103 Worklist.push_back(CurUser); 104 105 while (!Worklist.empty()) { 106 const User *U = Worklist.pop_back_val(); 107 const auto *CB = dyn_cast<CallBase>(U); 108 109 for (const auto &OI : U->operands()) { 110 const User *Operand = dyn_cast<User>(OI); 111 if (!Operand) 112 continue; 113 if (isa<BlockAddress>(Operand)) { 114 HasBlockAddress = true; 115 continue; 116 } 117 if (auto *GV = dyn_cast<GlobalValue>(Operand)) { 118 // We have a reference to a global value. This should be added to 119 // the reference set unless it is a callee. Callees are handled 120 // specially by WriteFunction and are added to a separate list. 121 if (!(CB && CB->isCallee(&OI))) 122 RefEdges.insert(Index.getOrInsertValueInfo(GV)); 123 continue; 124 } 125 if (Visited.insert(Operand).second) 126 Worklist.push_back(Operand); 127 } 128 } 129 130 const Instruction *I = dyn_cast<Instruction>(CurUser); 131 if (I) { 132 uint32_t ActualNumValueData = 0; 133 uint64_t TotalCount = 0; 134 // MaxNumVTableAnnotations is the maximum number of vtables annotated on 135 // the instruction. 136 auto ValueDataArray = 137 getValueProfDataFromInst(*I, IPVK_VTableTarget, MaxNumVTableAnnotations, 138 ActualNumValueData, TotalCount); 139 140 if (ValueDataArray.get()) { 141 for (uint32_t j = 0; j < ActualNumValueData; j++) { 142 RefEdges.insert(Index.getOrInsertValueInfo(/* VTableGUID = */ 143 ValueDataArray[j].Value)); 144 } 145 } 146 } 147 return HasBlockAddress; 148 } 149 150 static CalleeInfo::HotnessType getHotness(uint64_t ProfileCount, 151 ProfileSummaryInfo *PSI) { 152 if (!PSI) 153 return CalleeInfo::HotnessType::Unknown; 154 if (PSI->isHotCount(ProfileCount)) 155 return CalleeInfo::HotnessType::Hot; 156 if (PSI->isColdCount(ProfileCount)) 157 return CalleeInfo::HotnessType::Cold; 158 return CalleeInfo::HotnessType::None; 159 } 160 161 static bool isNonRenamableLocal(const GlobalValue &GV) { 162 return GV.hasSection() && GV.hasLocalLinkage(); 163 } 164 165 /// Determine whether this call has all constant integer arguments (excluding 166 /// "this") and summarize it to VCalls or ConstVCalls as appropriate. 167 static void addVCallToSet( 168 DevirtCallSite Call, GlobalValue::GUID Guid, 169 SetVector<FunctionSummary::VFuncId, std::vector<FunctionSummary::VFuncId>> 170 &VCalls, 171 SetVector<FunctionSummary::ConstVCall, 172 std::vector<FunctionSummary::ConstVCall>> &ConstVCalls) { 173 std::vector<uint64_t> Args; 174 // Start from the second argument to skip the "this" pointer. 175 for (auto &Arg : drop_begin(Call.CB.args())) { 176 auto *CI = dyn_cast<ConstantInt>(Arg); 177 if (!CI || CI->getBitWidth() > 64) { 178 VCalls.insert({Guid, Call.Offset}); 179 return; 180 } 181 Args.push_back(CI->getZExtValue()); 182 } 183 ConstVCalls.insert({{Guid, Call.Offset}, std::move(Args)}); 184 } 185 186 /// If this intrinsic call requires that we add information to the function 187 /// summary, do so via the non-constant reference arguments. 188 static void addIntrinsicToSummary( 189 const CallInst *CI, 190 SetVector<GlobalValue::GUID, std::vector<GlobalValue::GUID>> &TypeTests, 191 SetVector<FunctionSummary::VFuncId, std::vector<FunctionSummary::VFuncId>> 192 &TypeTestAssumeVCalls, 193 SetVector<FunctionSummary::VFuncId, std::vector<FunctionSummary::VFuncId>> 194 &TypeCheckedLoadVCalls, 195 SetVector<FunctionSummary::ConstVCall, 196 std::vector<FunctionSummary::ConstVCall>> 197 &TypeTestAssumeConstVCalls, 198 SetVector<FunctionSummary::ConstVCall, 199 std::vector<FunctionSummary::ConstVCall>> 200 &TypeCheckedLoadConstVCalls, 201 DominatorTree &DT) { 202 switch (CI->getCalledFunction()->getIntrinsicID()) { 203 case Intrinsic::type_test: 204 case Intrinsic::public_type_test: { 205 auto *TypeMDVal = cast<MetadataAsValue>(CI->getArgOperand(1)); 206 auto *TypeId = dyn_cast<MDString>(TypeMDVal->getMetadata()); 207 if (!TypeId) 208 break; 209 GlobalValue::GUID Guid = GlobalValue::getGUID(TypeId->getString()); 210 211 // Produce a summary from type.test intrinsics. We only summarize type.test 212 // intrinsics that are used other than by an llvm.assume intrinsic. 213 // Intrinsics that are assumed are relevant only to the devirtualization 214 // pass, not the type test lowering pass. 215 bool HasNonAssumeUses = llvm::any_of(CI->uses(), [](const Use &CIU) { 216 return !isa<AssumeInst>(CIU.getUser()); 217 }); 218 if (HasNonAssumeUses) 219 TypeTests.insert(Guid); 220 221 SmallVector<DevirtCallSite, 4> DevirtCalls; 222 SmallVector<CallInst *, 4> Assumes; 223 findDevirtualizableCallsForTypeTest(DevirtCalls, Assumes, CI, DT); 224 for (auto &Call : DevirtCalls) 225 addVCallToSet(Call, Guid, TypeTestAssumeVCalls, 226 TypeTestAssumeConstVCalls); 227 228 break; 229 } 230 231 case Intrinsic::type_checked_load_relative: 232 case Intrinsic::type_checked_load: { 233 auto *TypeMDVal = cast<MetadataAsValue>(CI->getArgOperand(2)); 234 auto *TypeId = dyn_cast<MDString>(TypeMDVal->getMetadata()); 235 if (!TypeId) 236 break; 237 GlobalValue::GUID Guid = GlobalValue::getGUID(TypeId->getString()); 238 239 SmallVector<DevirtCallSite, 4> DevirtCalls; 240 SmallVector<Instruction *, 4> LoadedPtrs; 241 SmallVector<Instruction *, 4> Preds; 242 bool HasNonCallUses = false; 243 findDevirtualizableCallsForTypeCheckedLoad(DevirtCalls, LoadedPtrs, Preds, 244 HasNonCallUses, CI, DT); 245 // Any non-call uses of the result of llvm.type.checked.load will 246 // prevent us from optimizing away the llvm.type.test. 247 if (HasNonCallUses) 248 TypeTests.insert(Guid); 249 for (auto &Call : DevirtCalls) 250 addVCallToSet(Call, Guid, TypeCheckedLoadVCalls, 251 TypeCheckedLoadConstVCalls); 252 253 break; 254 } 255 default: 256 break; 257 } 258 } 259 260 static bool isNonVolatileLoad(const Instruction *I) { 261 if (const auto *LI = dyn_cast<LoadInst>(I)) 262 return !LI->isVolatile(); 263 264 return false; 265 } 266 267 static bool isNonVolatileStore(const Instruction *I) { 268 if (const auto *SI = dyn_cast<StoreInst>(I)) 269 return !SI->isVolatile(); 270 271 return false; 272 } 273 274 // Returns true if the function definition must be unreachable. 275 // 276 // Note if this helper function returns true, `F` is guaranteed 277 // to be unreachable; if it returns false, `F` might still 278 // be unreachable but not covered by this helper function. 279 static bool mustBeUnreachableFunction(const Function &F) { 280 // A function must be unreachable if its entry block ends with an 281 // 'unreachable'. 282 assert(!F.isDeclaration()); 283 return isa<UnreachableInst>(F.getEntryBlock().getTerminator()); 284 } 285 286 static void computeFunctionSummary( 287 ModuleSummaryIndex &Index, const Module &M, const Function &F, 288 BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI, DominatorTree &DT, 289 bool HasLocalsInUsedOrAsm, DenseSet<GlobalValue::GUID> &CantBePromoted, 290 bool IsThinLTO, 291 std::function<const StackSafetyInfo *(const Function &F)> GetSSICallback) { 292 // Summary not currently supported for anonymous functions, they should 293 // have been named. 294 assert(F.hasName()); 295 296 unsigned NumInsts = 0; 297 // Map from callee ValueId to profile count. Used to accumulate profile 298 // counts for all static calls to a given callee. 299 MapVector<ValueInfo, CalleeInfo, DenseMap<ValueInfo, unsigned>, 300 std::vector<std::pair<ValueInfo, CalleeInfo>>> 301 CallGraphEdges; 302 SetVector<ValueInfo, std::vector<ValueInfo>> RefEdges, LoadRefEdges, 303 StoreRefEdges; 304 SetVector<GlobalValue::GUID, std::vector<GlobalValue::GUID>> TypeTests; 305 SetVector<FunctionSummary::VFuncId, std::vector<FunctionSummary::VFuncId>> 306 TypeTestAssumeVCalls, TypeCheckedLoadVCalls; 307 SetVector<FunctionSummary::ConstVCall, 308 std::vector<FunctionSummary::ConstVCall>> 309 TypeTestAssumeConstVCalls, TypeCheckedLoadConstVCalls; 310 ICallPromotionAnalysis ICallAnalysis; 311 SmallPtrSet<const User *, 8> Visited; 312 313 // Add personality function, prefix data and prologue data to function's ref 314 // list. 315 findRefEdges(Index, &F, RefEdges, Visited); 316 std::vector<const Instruction *> NonVolatileLoads; 317 std::vector<const Instruction *> NonVolatileStores; 318 319 std::vector<CallsiteInfo> Callsites; 320 std::vector<AllocInfo> Allocs; 321 322 #ifndef NDEBUG 323 DenseSet<const CallBase *> CallsThatMayHaveMemprofSummary; 324 #endif 325 326 bool HasInlineAsmMaybeReferencingInternal = false; 327 bool HasIndirBranchToBlockAddress = false; 328 bool HasIFuncCall = false; 329 bool HasUnknownCall = false; 330 bool MayThrow = false; 331 for (const BasicBlock &BB : F) { 332 // We don't allow inlining of function with indirect branch to blockaddress. 333 // If the blockaddress escapes the function, e.g., via a global variable, 334 // inlining may lead to an invalid cross-function reference. So we shouldn't 335 // import such function either. 336 if (BB.hasAddressTaken()) { 337 for (User *U : BlockAddress::get(const_cast<BasicBlock *>(&BB))->users()) 338 if (!isa<CallBrInst>(*U)) { 339 HasIndirBranchToBlockAddress = true; 340 break; 341 } 342 } 343 344 for (const Instruction &I : BB) { 345 if (I.isDebugOrPseudoInst()) 346 continue; 347 ++NumInsts; 348 349 // Regular LTO module doesn't participate in ThinLTO import, 350 // so no reference from it can be read/writeonly, since this 351 // would require importing variable as local copy 352 if (IsThinLTO) { 353 if (isNonVolatileLoad(&I)) { 354 // Postpone processing of non-volatile load instructions 355 // See comments below 356 Visited.insert(&I); 357 NonVolatileLoads.push_back(&I); 358 continue; 359 } else if (isNonVolatileStore(&I)) { 360 Visited.insert(&I); 361 NonVolatileStores.push_back(&I); 362 // All references from second operand of store (destination address) 363 // can be considered write-only if they're not referenced by any 364 // non-store instruction. References from first operand of store 365 // (stored value) can't be treated either as read- or as write-only 366 // so we add them to RefEdges as we do with all other instructions 367 // except non-volatile load. 368 Value *Stored = I.getOperand(0); 369 if (auto *GV = dyn_cast<GlobalValue>(Stored)) 370 // findRefEdges will try to examine GV operands, so instead 371 // of calling it we should add GV to RefEdges directly. 372 RefEdges.insert(Index.getOrInsertValueInfo(GV)); 373 else if (auto *U = dyn_cast<User>(Stored)) 374 findRefEdges(Index, U, RefEdges, Visited); 375 continue; 376 } 377 } 378 findRefEdges(Index, &I, RefEdges, Visited); 379 const auto *CB = dyn_cast<CallBase>(&I); 380 if (!CB) { 381 if (I.mayThrow()) 382 MayThrow = true; 383 continue; 384 } 385 386 const auto *CI = dyn_cast<CallInst>(&I); 387 // Since we don't know exactly which local values are referenced in inline 388 // assembly, conservatively mark the function as possibly referencing 389 // a local value from inline assembly to ensure we don't export a 390 // reference (which would require renaming and promotion of the 391 // referenced value). 392 if (HasLocalsInUsedOrAsm && CI && CI->isInlineAsm()) 393 HasInlineAsmMaybeReferencingInternal = true; 394 395 auto *CalledValue = CB->getCalledOperand(); 396 auto *CalledFunction = CB->getCalledFunction(); 397 if (CalledValue && !CalledFunction) { 398 CalledValue = CalledValue->stripPointerCasts(); 399 // Stripping pointer casts can reveal a called function. 400 CalledFunction = dyn_cast<Function>(CalledValue); 401 } 402 // Check if this is an alias to a function. If so, get the 403 // called aliasee for the checks below. 404 if (auto *GA = dyn_cast<GlobalAlias>(CalledValue)) { 405 assert(!CalledFunction && "Expected null called function in callsite for alias"); 406 CalledFunction = dyn_cast<Function>(GA->getAliaseeObject()); 407 } 408 // Check if this is a direct call to a known function or a known 409 // intrinsic, or an indirect call with profile data. 410 if (CalledFunction) { 411 if (CI && CalledFunction->isIntrinsic()) { 412 addIntrinsicToSummary( 413 CI, TypeTests, TypeTestAssumeVCalls, TypeCheckedLoadVCalls, 414 TypeTestAssumeConstVCalls, TypeCheckedLoadConstVCalls, DT); 415 continue; 416 } 417 // We should have named any anonymous globals 418 assert(CalledFunction->hasName()); 419 auto ScaledCount = PSI->getProfileCount(*CB, BFI); 420 auto Hotness = ScaledCount ? getHotness(*ScaledCount, PSI) 421 : CalleeInfo::HotnessType::Unknown; 422 if (ForceSummaryEdgesCold != FunctionSummary::FSHT_None) 423 Hotness = CalleeInfo::HotnessType::Cold; 424 425 // Use the original CalledValue, in case it was an alias. We want 426 // to record the call edge to the alias in that case. Eventually 427 // an alias summary will be created to associate the alias and 428 // aliasee. 429 auto &ValueInfo = CallGraphEdges[Index.getOrInsertValueInfo( 430 cast<GlobalValue>(CalledValue))]; 431 ValueInfo.updateHotness(Hotness); 432 if (CB->isTailCall()) 433 ValueInfo.setHasTailCall(true); 434 // Add the relative block frequency to CalleeInfo if there is no profile 435 // information. 436 if (BFI != nullptr && Hotness == CalleeInfo::HotnessType::Unknown) { 437 uint64_t BBFreq = BFI->getBlockFreq(&BB).getFrequency(); 438 uint64_t EntryFreq = BFI->getEntryFreq().getFrequency(); 439 ValueInfo.updateRelBlockFreq(BBFreq, EntryFreq); 440 } 441 } else { 442 HasUnknownCall = true; 443 // If F is imported, a local linkage ifunc (e.g. target_clones on a 444 // static function) called by F will be cloned. Since summaries don't 445 // track ifunc, we do not know implementation functions referenced by 446 // the ifunc resolver need to be promoted in the exporter, and we will 447 // get linker errors due to cloned declarations for implementation 448 // functions. As a simple fix, just mark F as not eligible for import. 449 // Non-local ifunc is not cloned and does not have the issue. 450 if (auto *GI = dyn_cast_if_present<GlobalIFunc>(CalledValue)) 451 if (GI->hasLocalLinkage()) 452 HasIFuncCall = true; 453 // Skip inline assembly calls. 454 if (CI && CI->isInlineAsm()) 455 continue; 456 // Skip direct calls. 457 if (!CalledValue || isa<Constant>(CalledValue)) 458 continue; 459 460 // Check if the instruction has a callees metadata. If so, add callees 461 // to CallGraphEdges to reflect the references from the metadata, and 462 // to enable importing for subsequent indirect call promotion and 463 // inlining. 464 if (auto *MD = I.getMetadata(LLVMContext::MD_callees)) { 465 for (const auto &Op : MD->operands()) { 466 Function *Callee = mdconst::extract_or_null<Function>(Op); 467 if (Callee) 468 CallGraphEdges[Index.getOrInsertValueInfo(Callee)]; 469 } 470 } 471 472 uint32_t NumVals, NumCandidates; 473 uint64_t TotalCount; 474 auto CandidateProfileData = 475 ICallAnalysis.getPromotionCandidatesForInstruction( 476 &I, NumVals, TotalCount, NumCandidates); 477 for (const auto &Candidate : CandidateProfileData) 478 CallGraphEdges[Index.getOrInsertValueInfo(Candidate.Value)] 479 .updateHotness(getHotness(Candidate.Count, PSI)); 480 } 481 482 // Summarize memprof related metadata. This is only needed for ThinLTO. 483 if (!IsThinLTO) 484 continue; 485 486 // TODO: Skip indirect calls for now. Need to handle these better, likely 487 // by creating multiple Callsites, one per target, then speculatively 488 // devirtualize while applying clone info in the ThinLTO backends. This 489 // will also be important because we will have a different set of clone 490 // versions per target. This handling needs to match that in the ThinLTO 491 // backend so we handle things consistently for matching of callsite 492 // summaries to instructions. 493 if (!CalledFunction) 494 continue; 495 496 // Ensure we keep this analysis in sync with the handling in the ThinLTO 497 // backend (see MemProfContextDisambiguation::applyImport). Save this call 498 // so that we can skip it in checking the reverse case later. 499 assert(mayHaveMemprofSummary(CB)); 500 #ifndef NDEBUG 501 CallsThatMayHaveMemprofSummary.insert(CB); 502 #endif 503 504 // Compute the list of stack ids first (so we can trim them from the stack 505 // ids on any MIBs). 506 CallStack<MDNode, MDNode::op_iterator> InstCallsite( 507 I.getMetadata(LLVMContext::MD_callsite)); 508 auto *MemProfMD = I.getMetadata(LLVMContext::MD_memprof); 509 if (MemProfMD) { 510 std::vector<MIBInfo> MIBs; 511 for (auto &MDOp : MemProfMD->operands()) { 512 auto *MIBMD = cast<const MDNode>(MDOp); 513 MDNode *StackNode = getMIBStackNode(MIBMD); 514 assert(StackNode); 515 SmallVector<unsigned> StackIdIndices; 516 CallStack<MDNode, MDNode::op_iterator> StackContext(StackNode); 517 // Collapse out any on the allocation call (inlining). 518 for (auto ContextIter = 519 StackContext.beginAfterSharedPrefix(InstCallsite); 520 ContextIter != StackContext.end(); ++ContextIter) { 521 unsigned StackIdIdx = Index.addOrGetStackIdIndex(*ContextIter); 522 // If this is a direct recursion, simply skip the duplicate 523 // entries. If this is mutual recursion, handling is left to 524 // the LTO link analysis client. 525 if (StackIdIndices.empty() || StackIdIndices.back() != StackIdIdx) 526 StackIdIndices.push_back(StackIdIdx); 527 } 528 MIBs.push_back( 529 MIBInfo(getMIBAllocType(MIBMD), std::move(StackIdIndices))); 530 } 531 Allocs.push_back(AllocInfo(std::move(MIBs))); 532 } else if (!InstCallsite.empty()) { 533 SmallVector<unsigned> StackIdIndices; 534 for (auto StackId : InstCallsite) 535 StackIdIndices.push_back(Index.addOrGetStackIdIndex(StackId)); 536 // Use the original CalledValue, in case it was an alias. We want 537 // to record the call edge to the alias in that case. Eventually 538 // an alias summary will be created to associate the alias and 539 // aliasee. 540 auto CalleeValueInfo = 541 Index.getOrInsertValueInfo(cast<GlobalValue>(CalledValue)); 542 Callsites.push_back({CalleeValueInfo, StackIdIndices}); 543 } 544 } 545 } 546 547 if (PSI->hasPartialSampleProfile() && ScalePartialSampleProfileWorkingSetSize) 548 Index.addBlockCount(F.size()); 549 550 std::vector<ValueInfo> Refs; 551 if (IsThinLTO) { 552 auto AddRefEdges = [&](const std::vector<const Instruction *> &Instrs, 553 SetVector<ValueInfo, std::vector<ValueInfo>> &Edges, 554 SmallPtrSet<const User *, 8> &Cache) { 555 for (const auto *I : Instrs) { 556 Cache.erase(I); 557 findRefEdges(Index, I, Edges, Cache); 558 } 559 }; 560 561 // By now we processed all instructions in a function, except 562 // non-volatile loads and non-volatile value stores. Let's find 563 // ref edges for both of instruction sets 564 AddRefEdges(NonVolatileLoads, LoadRefEdges, Visited); 565 // We can add some values to the Visited set when processing load 566 // instructions which are also used by stores in NonVolatileStores. 567 // For example this can happen if we have following code: 568 // 569 // store %Derived* @foo, %Derived** bitcast (%Base** @bar to %Derived**) 570 // %42 = load %Derived*, %Derived** bitcast (%Base** @bar to %Derived**) 571 // 572 // After processing loads we'll add bitcast to the Visited set, and if 573 // we use the same set while processing stores, we'll never see store 574 // to @bar and @bar will be mistakenly treated as readonly. 575 SmallPtrSet<const llvm::User *, 8> StoreCache; 576 AddRefEdges(NonVolatileStores, StoreRefEdges, StoreCache); 577 578 // If both load and store instruction reference the same variable 579 // we won't be able to optimize it. Add all such reference edges 580 // to RefEdges set. 581 for (const auto &VI : StoreRefEdges) 582 if (LoadRefEdges.remove(VI)) 583 RefEdges.insert(VI); 584 585 unsigned RefCnt = RefEdges.size(); 586 // All new reference edges inserted in two loops below are either 587 // read or write only. They will be grouped in the end of RefEdges 588 // vector, so we can use a single integer value to identify them. 589 for (const auto &VI : LoadRefEdges) 590 RefEdges.insert(VI); 591 592 unsigned FirstWORef = RefEdges.size(); 593 for (const auto &VI : StoreRefEdges) 594 RefEdges.insert(VI); 595 596 Refs = RefEdges.takeVector(); 597 for (; RefCnt < FirstWORef; ++RefCnt) 598 Refs[RefCnt].setReadOnly(); 599 600 for (; RefCnt < Refs.size(); ++RefCnt) 601 Refs[RefCnt].setWriteOnly(); 602 } else { 603 Refs = RefEdges.takeVector(); 604 } 605 // Explicit add hot edges to enforce importing for designated GUIDs for 606 // sample PGO, to enable the same inlines as the profiled optimized binary. 607 for (auto &I : F.getImportGUIDs()) 608 CallGraphEdges[Index.getOrInsertValueInfo(I)].updateHotness( 609 ForceSummaryEdgesCold == FunctionSummary::FSHT_All 610 ? CalleeInfo::HotnessType::Cold 611 : CalleeInfo::HotnessType::Critical); 612 613 #ifndef NDEBUG 614 // Make sure that all calls we decided could not have memprof summaries get a 615 // false value for mayHaveMemprofSummary, to ensure that this handling remains 616 // in sync with the ThinLTO backend handling. 617 if (IsThinLTO) { 618 for (const BasicBlock &BB : F) { 619 for (const Instruction &I : BB) { 620 const auto *CB = dyn_cast<CallBase>(&I); 621 if (!CB) 622 continue; 623 // We already checked these above. 624 if (CallsThatMayHaveMemprofSummary.count(CB)) 625 continue; 626 assert(!mayHaveMemprofSummary(CB)); 627 } 628 } 629 } 630 #endif 631 632 bool NonRenamableLocal = isNonRenamableLocal(F); 633 bool NotEligibleForImport = NonRenamableLocal || 634 HasInlineAsmMaybeReferencingInternal || 635 HasIndirBranchToBlockAddress || HasIFuncCall; 636 GlobalValueSummary::GVFlags Flags( 637 F.getLinkage(), F.getVisibility(), NotEligibleForImport, 638 /* Live = */ false, F.isDSOLocal(), F.canBeOmittedFromSymbolTable(), 639 GlobalValueSummary::ImportKind::Definition); 640 FunctionSummary::FFlags FunFlags{ 641 F.doesNotAccessMemory(), F.onlyReadsMemory() && !F.doesNotAccessMemory(), 642 F.hasFnAttribute(Attribute::NoRecurse), F.returnDoesNotAlias(), 643 // FIXME: refactor this to use the same code that inliner is using. 644 // Don't try to import functions with noinline attribute. 645 F.getAttributes().hasFnAttr(Attribute::NoInline), 646 F.hasFnAttribute(Attribute::AlwaysInline), 647 F.hasFnAttribute(Attribute::NoUnwind), MayThrow, HasUnknownCall, 648 mustBeUnreachableFunction(F)}; 649 std::vector<FunctionSummary::ParamAccess> ParamAccesses; 650 if (auto *SSI = GetSSICallback(F)) 651 ParamAccesses = SSI->getParamAccesses(Index); 652 auto FuncSummary = std::make_unique<FunctionSummary>( 653 Flags, NumInsts, FunFlags, /*EntryCount=*/0, std::move(Refs), 654 CallGraphEdges.takeVector(), TypeTests.takeVector(), 655 TypeTestAssumeVCalls.takeVector(), TypeCheckedLoadVCalls.takeVector(), 656 TypeTestAssumeConstVCalls.takeVector(), 657 TypeCheckedLoadConstVCalls.takeVector(), std::move(ParamAccesses), 658 std::move(Callsites), std::move(Allocs)); 659 if (NonRenamableLocal) 660 CantBePromoted.insert(F.getGUID()); 661 Index.addGlobalValueSummary(F, std::move(FuncSummary)); 662 } 663 664 /// Find function pointers referenced within the given vtable initializer 665 /// (or subset of an initializer) \p I. The starting offset of \p I within 666 /// the vtable initializer is \p StartingOffset. Any discovered function 667 /// pointers are added to \p VTableFuncs along with their cumulative offset 668 /// within the initializer. 669 static void findFuncPointers(const Constant *I, uint64_t StartingOffset, 670 const Module &M, ModuleSummaryIndex &Index, 671 VTableFuncList &VTableFuncs) { 672 // First check if this is a function pointer. 673 if (I->getType()->isPointerTy()) { 674 auto C = I->stripPointerCasts(); 675 auto A = dyn_cast<GlobalAlias>(C); 676 if (isa<Function>(C) || (A && isa<Function>(A->getAliasee()))) { 677 auto GV = dyn_cast<GlobalValue>(C); 678 assert(GV); 679 // We can disregard __cxa_pure_virtual as a possible call target, as 680 // calls to pure virtuals are UB. 681 if (GV && GV->getName() != "__cxa_pure_virtual") 682 VTableFuncs.push_back({Index.getOrInsertValueInfo(GV), StartingOffset}); 683 return; 684 } 685 } 686 687 // Walk through the elements in the constant struct or array and recursively 688 // look for virtual function pointers. 689 const DataLayout &DL = M.getDataLayout(); 690 if (auto *C = dyn_cast<ConstantStruct>(I)) { 691 StructType *STy = dyn_cast<StructType>(C->getType()); 692 assert(STy); 693 const StructLayout *SL = DL.getStructLayout(C->getType()); 694 695 for (auto EI : llvm::enumerate(STy->elements())) { 696 auto Offset = SL->getElementOffset(EI.index()); 697 unsigned Op = SL->getElementContainingOffset(Offset); 698 findFuncPointers(cast<Constant>(I->getOperand(Op)), 699 StartingOffset + Offset, M, Index, VTableFuncs); 700 } 701 } else if (auto *C = dyn_cast<ConstantArray>(I)) { 702 ArrayType *ATy = C->getType(); 703 Type *EltTy = ATy->getElementType(); 704 uint64_t EltSize = DL.getTypeAllocSize(EltTy); 705 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) { 706 findFuncPointers(cast<Constant>(I->getOperand(i)), 707 StartingOffset + i * EltSize, M, Index, VTableFuncs); 708 } 709 } 710 } 711 712 // Identify the function pointers referenced by vtable definition \p V. 713 static void computeVTableFuncs(ModuleSummaryIndex &Index, 714 const GlobalVariable &V, const Module &M, 715 VTableFuncList &VTableFuncs) { 716 if (!V.isConstant()) 717 return; 718 719 findFuncPointers(V.getInitializer(), /*StartingOffset=*/0, M, Index, 720 VTableFuncs); 721 722 #ifndef NDEBUG 723 // Validate that the VTableFuncs list is ordered by offset. 724 uint64_t PrevOffset = 0; 725 for (auto &P : VTableFuncs) { 726 // The findVFuncPointers traversal should have encountered the 727 // functions in offset order. We need to use ">=" since PrevOffset 728 // starts at 0. 729 assert(P.VTableOffset >= PrevOffset); 730 PrevOffset = P.VTableOffset; 731 } 732 #endif 733 } 734 735 /// Record vtable definition \p V for each type metadata it references. 736 static void 737 recordTypeIdCompatibleVtableReferences(ModuleSummaryIndex &Index, 738 const GlobalVariable &V, 739 SmallVectorImpl<MDNode *> &Types) { 740 for (MDNode *Type : Types) { 741 auto TypeID = Type->getOperand(1).get(); 742 743 uint64_t Offset = 744 cast<ConstantInt>( 745 cast<ConstantAsMetadata>(Type->getOperand(0))->getValue()) 746 ->getZExtValue(); 747 748 if (auto *TypeId = dyn_cast<MDString>(TypeID)) 749 Index.getOrInsertTypeIdCompatibleVtableSummary(TypeId->getString()) 750 .push_back({Offset, Index.getOrInsertValueInfo(&V)}); 751 } 752 } 753 754 static void computeVariableSummary(ModuleSummaryIndex &Index, 755 const GlobalVariable &V, 756 DenseSet<GlobalValue::GUID> &CantBePromoted, 757 const Module &M, 758 SmallVectorImpl<MDNode *> &Types) { 759 SetVector<ValueInfo, std::vector<ValueInfo>> RefEdges; 760 SmallPtrSet<const User *, 8> Visited; 761 bool HasBlockAddress = findRefEdges(Index, &V, RefEdges, Visited); 762 bool NonRenamableLocal = isNonRenamableLocal(V); 763 GlobalValueSummary::GVFlags Flags( 764 V.getLinkage(), V.getVisibility(), NonRenamableLocal, 765 /* Live = */ false, V.isDSOLocal(), V.canBeOmittedFromSymbolTable(), 766 GlobalValueSummary::Definition); 767 768 VTableFuncList VTableFuncs; 769 // If splitting is not enabled, then we compute the summary information 770 // necessary for index-based whole program devirtualization. 771 if (!Index.enableSplitLTOUnit()) { 772 Types.clear(); 773 V.getMetadata(LLVMContext::MD_type, Types); 774 if (!Types.empty()) { 775 // Identify the function pointers referenced by this vtable definition. 776 computeVTableFuncs(Index, V, M, VTableFuncs); 777 778 // Record this vtable definition for each type metadata it references. 779 recordTypeIdCompatibleVtableReferences(Index, V, Types); 780 } 781 } 782 783 // Don't mark variables we won't be able to internalize as read/write-only. 784 bool CanBeInternalized = 785 !V.hasComdat() && !V.hasAppendingLinkage() && !V.isInterposable() && 786 !V.hasAvailableExternallyLinkage() && !V.hasDLLExportStorageClass(); 787 bool Constant = V.isConstant(); 788 GlobalVarSummary::GVarFlags VarFlags(CanBeInternalized, 789 Constant ? false : CanBeInternalized, 790 Constant, V.getVCallVisibility()); 791 auto GVarSummary = std::make_unique<GlobalVarSummary>(Flags, VarFlags, 792 RefEdges.takeVector()); 793 if (NonRenamableLocal) 794 CantBePromoted.insert(V.getGUID()); 795 if (HasBlockAddress) 796 GVarSummary->setNotEligibleToImport(); 797 if (!VTableFuncs.empty()) 798 GVarSummary->setVTableFuncs(VTableFuncs); 799 Index.addGlobalValueSummary(V, std::move(GVarSummary)); 800 } 801 802 static void computeAliasSummary(ModuleSummaryIndex &Index, const GlobalAlias &A, 803 DenseSet<GlobalValue::GUID> &CantBePromoted) { 804 // Skip summary for indirect function aliases as summary for aliasee will not 805 // be emitted. 806 const GlobalObject *Aliasee = A.getAliaseeObject(); 807 if (isa<GlobalIFunc>(Aliasee)) 808 return; 809 bool NonRenamableLocal = isNonRenamableLocal(A); 810 GlobalValueSummary::GVFlags Flags( 811 A.getLinkage(), A.getVisibility(), NonRenamableLocal, 812 /* Live = */ false, A.isDSOLocal(), A.canBeOmittedFromSymbolTable(), 813 GlobalValueSummary::Definition); 814 auto AS = std::make_unique<AliasSummary>(Flags); 815 auto AliaseeVI = Index.getValueInfo(Aliasee->getGUID()); 816 assert(AliaseeVI && "Alias expects aliasee summary to be available"); 817 assert(AliaseeVI.getSummaryList().size() == 1 && 818 "Expected a single entry per aliasee in per-module index"); 819 AS->setAliasee(AliaseeVI, AliaseeVI.getSummaryList()[0].get()); 820 if (NonRenamableLocal) 821 CantBePromoted.insert(A.getGUID()); 822 Index.addGlobalValueSummary(A, std::move(AS)); 823 } 824 825 // Set LiveRoot flag on entries matching the given value name. 826 static void setLiveRoot(ModuleSummaryIndex &Index, StringRef Name) { 827 if (ValueInfo VI = Index.getValueInfo(GlobalValue::getGUID(Name))) 828 for (const auto &Summary : VI.getSummaryList()) 829 Summary->setLive(true); 830 } 831 832 ModuleSummaryIndex llvm::buildModuleSummaryIndex( 833 const Module &M, 834 std::function<BlockFrequencyInfo *(const Function &F)> GetBFICallback, 835 ProfileSummaryInfo *PSI, 836 std::function<const StackSafetyInfo *(const Function &F)> GetSSICallback) { 837 assert(PSI); 838 bool EnableSplitLTOUnit = false; 839 bool UnifiedLTO = false; 840 if (auto *MD = mdconst::extract_or_null<ConstantInt>( 841 M.getModuleFlag("EnableSplitLTOUnit"))) 842 EnableSplitLTOUnit = MD->getZExtValue(); 843 if (auto *MD = 844 mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("UnifiedLTO"))) 845 UnifiedLTO = MD->getZExtValue(); 846 ModuleSummaryIndex Index(/*HaveGVs=*/true, EnableSplitLTOUnit, UnifiedLTO); 847 848 // Identify the local values in the llvm.used and llvm.compiler.used sets, 849 // which should not be exported as they would then require renaming and 850 // promotion, but we may have opaque uses e.g. in inline asm. We collect them 851 // here because we use this information to mark functions containing inline 852 // assembly calls as not importable. 853 SmallPtrSet<GlobalValue *, 4> LocalsUsed; 854 SmallVector<GlobalValue *, 4> Used; 855 // First collect those in the llvm.used set. 856 collectUsedGlobalVariables(M, Used, /*CompilerUsed=*/false); 857 // Next collect those in the llvm.compiler.used set. 858 collectUsedGlobalVariables(M, Used, /*CompilerUsed=*/true); 859 DenseSet<GlobalValue::GUID> CantBePromoted; 860 for (auto *V : Used) { 861 if (V->hasLocalLinkage()) { 862 LocalsUsed.insert(V); 863 CantBePromoted.insert(V->getGUID()); 864 } 865 } 866 867 bool HasLocalInlineAsmSymbol = false; 868 if (!M.getModuleInlineAsm().empty()) { 869 // Collect the local values defined by module level asm, and set up 870 // summaries for these symbols so that they can be marked as NoRename, 871 // to prevent export of any use of them in regular IR that would require 872 // renaming within the module level asm. Note we don't need to create a 873 // summary for weak or global defs, as they don't need to be flagged as 874 // NoRename, and defs in module level asm can't be imported anyway. 875 // Also, any values used but not defined within module level asm should 876 // be listed on the llvm.used or llvm.compiler.used global and marked as 877 // referenced from there. 878 ModuleSymbolTable::CollectAsmSymbols( 879 M, [&](StringRef Name, object::BasicSymbolRef::Flags Flags) { 880 // Symbols not marked as Weak or Global are local definitions. 881 if (Flags & (object::BasicSymbolRef::SF_Weak | 882 object::BasicSymbolRef::SF_Global)) 883 return; 884 HasLocalInlineAsmSymbol = true; 885 GlobalValue *GV = M.getNamedValue(Name); 886 if (!GV) 887 return; 888 assert(GV->isDeclaration() && "Def in module asm already has definition"); 889 GlobalValueSummary::GVFlags GVFlags( 890 GlobalValue::InternalLinkage, GlobalValue::DefaultVisibility, 891 /* NotEligibleToImport = */ true, 892 /* Live = */ true, 893 /* Local */ GV->isDSOLocal(), GV->canBeOmittedFromSymbolTable(), 894 GlobalValueSummary::Definition); 895 CantBePromoted.insert(GV->getGUID()); 896 // Create the appropriate summary type. 897 if (Function *F = dyn_cast<Function>(GV)) { 898 std::unique_ptr<FunctionSummary> Summary = 899 std::make_unique<FunctionSummary>( 900 GVFlags, /*InstCount=*/0, 901 FunctionSummary::FFlags{ 902 F->hasFnAttribute(Attribute::ReadNone), 903 F->hasFnAttribute(Attribute::ReadOnly), 904 F->hasFnAttribute(Attribute::NoRecurse), 905 F->returnDoesNotAlias(), 906 /* NoInline = */ false, 907 F->hasFnAttribute(Attribute::AlwaysInline), 908 F->hasFnAttribute(Attribute::NoUnwind), 909 /* MayThrow */ true, 910 /* HasUnknownCall */ true, 911 /* MustBeUnreachable */ false}, 912 /*EntryCount=*/0, ArrayRef<ValueInfo>{}, 913 ArrayRef<FunctionSummary::EdgeTy>{}, 914 ArrayRef<GlobalValue::GUID>{}, 915 ArrayRef<FunctionSummary::VFuncId>{}, 916 ArrayRef<FunctionSummary::VFuncId>{}, 917 ArrayRef<FunctionSummary::ConstVCall>{}, 918 ArrayRef<FunctionSummary::ConstVCall>{}, 919 ArrayRef<FunctionSummary::ParamAccess>{}, 920 ArrayRef<CallsiteInfo>{}, ArrayRef<AllocInfo>{}); 921 Index.addGlobalValueSummary(*GV, std::move(Summary)); 922 } else { 923 std::unique_ptr<GlobalVarSummary> Summary = 924 std::make_unique<GlobalVarSummary>( 925 GVFlags, 926 GlobalVarSummary::GVarFlags( 927 false, false, cast<GlobalVariable>(GV)->isConstant(), 928 GlobalObject::VCallVisibilityPublic), 929 ArrayRef<ValueInfo>{}); 930 Index.addGlobalValueSummary(*GV, std::move(Summary)); 931 } 932 }); 933 } 934 935 bool IsThinLTO = true; 936 if (auto *MD = 937 mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("ThinLTO"))) 938 IsThinLTO = MD->getZExtValue(); 939 940 // Compute summaries for all functions defined in module, and save in the 941 // index. 942 for (const auto &F : M) { 943 if (F.isDeclaration()) 944 continue; 945 946 DominatorTree DT(const_cast<Function &>(F)); 947 BlockFrequencyInfo *BFI = nullptr; 948 std::unique_ptr<BlockFrequencyInfo> BFIPtr; 949 if (GetBFICallback) 950 BFI = GetBFICallback(F); 951 else if (F.hasProfileData()) { 952 LoopInfo LI{DT}; 953 BranchProbabilityInfo BPI{F, LI}; 954 BFIPtr = std::make_unique<BlockFrequencyInfo>(F, BPI, LI); 955 BFI = BFIPtr.get(); 956 } 957 958 computeFunctionSummary(Index, M, F, BFI, PSI, DT, 959 !LocalsUsed.empty() || HasLocalInlineAsmSymbol, 960 CantBePromoted, IsThinLTO, GetSSICallback); 961 } 962 963 // Compute summaries for all variables defined in module, and save in the 964 // index. 965 SmallVector<MDNode *, 2> Types; 966 for (const GlobalVariable &G : M.globals()) { 967 if (G.isDeclaration()) 968 continue; 969 computeVariableSummary(Index, G, CantBePromoted, M, Types); 970 } 971 972 // Compute summaries for all aliases defined in module, and save in the 973 // index. 974 for (const GlobalAlias &A : M.aliases()) 975 computeAliasSummary(Index, A, CantBePromoted); 976 977 // Iterate through ifuncs, set their resolvers all alive. 978 for (const GlobalIFunc &I : M.ifuncs()) { 979 I.applyAlongResolverPath([&Index](const GlobalValue &GV) { 980 Index.getGlobalValueSummary(GV)->setLive(true); 981 }); 982 } 983 984 for (auto *V : LocalsUsed) { 985 auto *Summary = Index.getGlobalValueSummary(*V); 986 assert(Summary && "Missing summary for global value"); 987 Summary->setNotEligibleToImport(); 988 } 989 990 // The linker doesn't know about these LLVM produced values, so we need 991 // to flag them as live in the index to ensure index-based dead value 992 // analysis treats them as live roots of the analysis. 993 setLiveRoot(Index, "llvm.used"); 994 setLiveRoot(Index, "llvm.compiler.used"); 995 setLiveRoot(Index, "llvm.global_ctors"); 996 setLiveRoot(Index, "llvm.global_dtors"); 997 setLiveRoot(Index, "llvm.global.annotations"); 998 999 for (auto &GlobalList : Index) { 1000 // Ignore entries for references that are undefined in the current module. 1001 if (GlobalList.second.SummaryList.empty()) 1002 continue; 1003 1004 assert(GlobalList.second.SummaryList.size() == 1 && 1005 "Expected module's index to have one summary per GUID"); 1006 auto &Summary = GlobalList.second.SummaryList[0]; 1007 if (!IsThinLTO) { 1008 Summary->setNotEligibleToImport(); 1009 continue; 1010 } 1011 1012 bool AllRefsCanBeExternallyReferenced = 1013 llvm::all_of(Summary->refs(), [&](const ValueInfo &VI) { 1014 return !CantBePromoted.count(VI.getGUID()); 1015 }); 1016 if (!AllRefsCanBeExternallyReferenced) { 1017 Summary->setNotEligibleToImport(); 1018 continue; 1019 } 1020 1021 if (auto *FuncSummary = dyn_cast<FunctionSummary>(Summary.get())) { 1022 bool AllCallsCanBeExternallyReferenced = llvm::all_of( 1023 FuncSummary->calls(), [&](const FunctionSummary::EdgeTy &Edge) { 1024 return !CantBePromoted.count(Edge.first.getGUID()); 1025 }); 1026 if (!AllCallsCanBeExternallyReferenced) 1027 Summary->setNotEligibleToImport(); 1028 } 1029 } 1030 1031 if (!ModuleSummaryDotFile.empty()) { 1032 std::error_code EC; 1033 raw_fd_ostream OSDot(ModuleSummaryDotFile, EC, sys::fs::OpenFlags::OF_None); 1034 if (EC) 1035 report_fatal_error(Twine("Failed to open dot file ") + 1036 ModuleSummaryDotFile + ": " + EC.message() + "\n"); 1037 Index.exportToDot(OSDot, {}); 1038 } 1039 1040 return Index; 1041 } 1042 1043 AnalysisKey ModuleSummaryIndexAnalysis::Key; 1044 1045 ModuleSummaryIndex 1046 ModuleSummaryIndexAnalysis::run(Module &M, ModuleAnalysisManager &AM) { 1047 ProfileSummaryInfo &PSI = AM.getResult<ProfileSummaryAnalysis>(M); 1048 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager(); 1049 bool NeedSSI = needsParamAccessSummary(M); 1050 return buildModuleSummaryIndex( 1051 M, 1052 [&FAM](const Function &F) { 1053 return &FAM.getResult<BlockFrequencyAnalysis>( 1054 *const_cast<Function *>(&F)); 1055 }, 1056 &PSI, 1057 [&FAM, NeedSSI](const Function &F) -> const StackSafetyInfo * { 1058 return NeedSSI ? &FAM.getResult<StackSafetyAnalysis>( 1059 const_cast<Function &>(F)) 1060 : nullptr; 1061 }); 1062 } 1063 1064 char ModuleSummaryIndexWrapperPass::ID = 0; 1065 1066 INITIALIZE_PASS_BEGIN(ModuleSummaryIndexWrapperPass, "module-summary-analysis", 1067 "Module Summary Analysis", false, true) 1068 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass) 1069 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass) 1070 INITIALIZE_PASS_DEPENDENCY(StackSafetyInfoWrapperPass) 1071 INITIALIZE_PASS_END(ModuleSummaryIndexWrapperPass, "module-summary-analysis", 1072 "Module Summary Analysis", false, true) 1073 1074 ModulePass *llvm::createModuleSummaryIndexWrapperPass() { 1075 return new ModuleSummaryIndexWrapperPass(); 1076 } 1077 1078 ModuleSummaryIndexWrapperPass::ModuleSummaryIndexWrapperPass() 1079 : ModulePass(ID) { 1080 initializeModuleSummaryIndexWrapperPassPass(*PassRegistry::getPassRegistry()); 1081 } 1082 1083 bool ModuleSummaryIndexWrapperPass::runOnModule(Module &M) { 1084 auto *PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI(); 1085 bool NeedSSI = needsParamAccessSummary(M); 1086 Index.emplace(buildModuleSummaryIndex( 1087 M, 1088 [this](const Function &F) { 1089 return &(this->getAnalysis<BlockFrequencyInfoWrapperPass>( 1090 *const_cast<Function *>(&F)) 1091 .getBFI()); 1092 }, 1093 PSI, 1094 [&](const Function &F) -> const StackSafetyInfo * { 1095 return NeedSSI ? &getAnalysis<StackSafetyInfoWrapperPass>( 1096 const_cast<Function &>(F)) 1097 .getResult() 1098 : nullptr; 1099 })); 1100 return false; 1101 } 1102 1103 bool ModuleSummaryIndexWrapperPass::doFinalization(Module &M) { 1104 Index.reset(); 1105 return false; 1106 } 1107 1108 void ModuleSummaryIndexWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 1109 AU.setPreservesAll(); 1110 AU.addRequired<BlockFrequencyInfoWrapperPass>(); 1111 AU.addRequired<ProfileSummaryInfoWrapperPass>(); 1112 AU.addRequired<StackSafetyInfoWrapperPass>(); 1113 } 1114 1115 char ImmutableModuleSummaryIndexWrapperPass::ID = 0; 1116 1117 ImmutableModuleSummaryIndexWrapperPass::ImmutableModuleSummaryIndexWrapperPass( 1118 const ModuleSummaryIndex *Index) 1119 : ImmutablePass(ID), Index(Index) { 1120 initializeImmutableModuleSummaryIndexWrapperPassPass( 1121 *PassRegistry::getPassRegistry()); 1122 } 1123 1124 void ImmutableModuleSummaryIndexWrapperPass::getAnalysisUsage( 1125 AnalysisUsage &AU) const { 1126 AU.setPreservesAll(); 1127 } 1128 1129 ImmutablePass *llvm::createImmutableModuleSummaryIndexWrapperPass( 1130 const ModuleSummaryIndex *Index) { 1131 return new ImmutableModuleSummaryIndexWrapperPass(Index); 1132 } 1133 1134 INITIALIZE_PASS(ImmutableModuleSummaryIndexWrapperPass, "module-summary-info", 1135 "Module summary info", false, true) 1136 1137 bool llvm::mayHaveMemprofSummary(const CallBase *CB) { 1138 if (!CB) 1139 return false; 1140 if (CB->isDebugOrPseudoInst()) 1141 return false; 1142 auto *CI = dyn_cast<CallInst>(CB); 1143 auto *CalledValue = CB->getCalledOperand(); 1144 auto *CalledFunction = CB->getCalledFunction(); 1145 if (CalledValue && !CalledFunction) { 1146 CalledValue = CalledValue->stripPointerCasts(); 1147 // Stripping pointer casts can reveal a called function. 1148 CalledFunction = dyn_cast<Function>(CalledValue); 1149 } 1150 // Check if this is an alias to a function. If so, get the 1151 // called aliasee for the checks below. 1152 if (auto *GA = dyn_cast<GlobalAlias>(CalledValue)) { 1153 assert(!CalledFunction && 1154 "Expected null called function in callsite for alias"); 1155 CalledFunction = dyn_cast<Function>(GA->getAliaseeObject()); 1156 } 1157 // Check if this is a direct call to a known function or a known 1158 // intrinsic, or an indirect call with profile data. 1159 if (CalledFunction) { 1160 if (CI && CalledFunction->isIntrinsic()) 1161 return false; 1162 } else { 1163 // TODO: For now skip indirect calls. See comments in 1164 // computeFunctionSummary for what is needed to handle this. 1165 return false; 1166 } 1167 return true; 1168 } 1169