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