1 //===- Inliner.cpp - Code common to all inliners --------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the mechanics required to implement inlining without 10 // missing any calls and updating the call graph. The decisions of which calls 11 // are profitable to inline are implemented elsewhere. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "llvm/Transforms/IPO/Inliner.h" 16 #include "llvm/ADT/DenseMap.h" 17 #include "llvm/ADT/Optional.h" 18 #include "llvm/ADT/PriorityWorklist.h" 19 #include "llvm/ADT/STLExtras.h" 20 #include "llvm/ADT/ScopeExit.h" 21 #include "llvm/ADT/SetVector.h" 22 #include "llvm/ADT/SmallPtrSet.h" 23 #include "llvm/ADT/SmallVector.h" 24 #include "llvm/ADT/Statistic.h" 25 #include "llvm/ADT/StringExtras.h" 26 #include "llvm/ADT/StringRef.h" 27 #include "llvm/Analysis/AssumptionCache.h" 28 #include "llvm/Analysis/BasicAliasAnalysis.h" 29 #include "llvm/Analysis/BlockFrequencyInfo.h" 30 #include "llvm/Analysis/CGSCCPassManager.h" 31 #include "llvm/Analysis/CallGraph.h" 32 #include "llvm/Analysis/InlineAdvisor.h" 33 #include "llvm/Analysis/InlineCost.h" 34 #include "llvm/Analysis/InlineOrder.h" 35 #include "llvm/Analysis/LazyCallGraph.h" 36 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 37 #include "llvm/Analysis/ProfileSummaryInfo.h" 38 #include "llvm/Analysis/ReplayInlineAdvisor.h" 39 #include "llvm/Analysis/TargetLibraryInfo.h" 40 #include "llvm/Analysis/Utils/ImportedFunctionsInliningStatistics.h" 41 #include "llvm/IR/Attributes.h" 42 #include "llvm/IR/BasicBlock.h" 43 #include "llvm/IR/DebugLoc.h" 44 #include "llvm/IR/DerivedTypes.h" 45 #include "llvm/IR/DiagnosticInfo.h" 46 #include "llvm/IR/Function.h" 47 #include "llvm/IR/InstIterator.h" 48 #include "llvm/IR/Instruction.h" 49 #include "llvm/IR/Instructions.h" 50 #include "llvm/IR/IntrinsicInst.h" 51 #include "llvm/IR/Metadata.h" 52 #include "llvm/IR/Module.h" 53 #include "llvm/IR/PassManager.h" 54 #include "llvm/IR/User.h" 55 #include "llvm/IR/Value.h" 56 #include "llvm/Pass.h" 57 #include "llvm/Support/Casting.h" 58 #include "llvm/Support/CommandLine.h" 59 #include "llvm/Support/Debug.h" 60 #include "llvm/Support/raw_ostream.h" 61 #include "llvm/Transforms/Utils/CallPromotionUtils.h" 62 #include "llvm/Transforms/Utils/Cloning.h" 63 #include "llvm/Transforms/Utils/Local.h" 64 #include "llvm/Transforms/Utils/ModuleUtils.h" 65 #include <algorithm> 66 #include <cassert> 67 #include <functional> 68 #include <utility> 69 #include <vector> 70 71 using namespace llvm; 72 73 #define DEBUG_TYPE "inline" 74 75 STATISTIC(NumInlined, "Number of functions inlined"); 76 STATISTIC(NumCallsDeleted, "Number of call sites deleted, not inlined"); 77 STATISTIC(NumDeleted, "Number of functions deleted because all callers found"); 78 STATISTIC(NumMergedAllocas, "Number of allocas merged together"); 79 80 /// Flag to disable manual alloca merging. 81 /// 82 /// Merging of allocas was originally done as a stack-size saving technique 83 /// prior to LLVM's code generator having support for stack coloring based on 84 /// lifetime markers. It is now in the process of being removed. To experiment 85 /// with disabling it and relying fully on lifetime marker based stack 86 /// coloring, you can pass this flag to LLVM. 87 static cl::opt<bool> 88 DisableInlinedAllocaMerging("disable-inlined-alloca-merging", 89 cl::init(false), cl::Hidden); 90 91 static cl::opt<int> IntraSCCCostMultiplier( 92 "intra-scc-cost-multiplier", cl::init(2), cl::Hidden, 93 cl::desc( 94 "Cost multiplier to multiply onto inlined call sites where the " 95 "new call was previously an intra-SCC call (not relevant when the " 96 "original call was already intra-SCC). This can accumulate over " 97 "multiple inlinings (e.g. if a call site already had a cost " 98 "multiplier and one of its inlined calls was also subject to " 99 "this, the inlined call would have the original multiplier " 100 "multiplied by intra-scc-cost-multiplier). This is to prevent tons of " 101 "inlining through a child SCC which can cause terrible compile times")); 102 103 /// A flag for test, so we can print the content of the advisor when running it 104 /// as part of the default (e.g. -O3) pipeline. 105 static cl::opt<bool> KeepAdvisorForPrinting("keep-inline-advisor-for-printing", 106 cl::init(false), cl::Hidden); 107 108 extern cl::opt<InlinerFunctionImportStatsOpts> InlinerFunctionImportStats; 109 110 static cl::opt<std::string> CGSCCInlineReplayFile( 111 "cgscc-inline-replay", cl::init(""), cl::value_desc("filename"), 112 cl::desc( 113 "Optimization remarks file containing inline remarks to be replayed " 114 "by cgscc inlining."), 115 cl::Hidden); 116 117 static cl::opt<ReplayInlinerSettings::Scope> CGSCCInlineReplayScope( 118 "cgscc-inline-replay-scope", 119 cl::init(ReplayInlinerSettings::Scope::Function), 120 cl::values(clEnumValN(ReplayInlinerSettings::Scope::Function, "Function", 121 "Replay on functions that have remarks associated " 122 "with them (default)"), 123 clEnumValN(ReplayInlinerSettings::Scope::Module, "Module", 124 "Replay on the entire module")), 125 cl::desc("Whether inline replay should be applied to the entire " 126 "Module or just the Functions (default) that are present as " 127 "callers in remarks during cgscc inlining."), 128 cl::Hidden); 129 130 static cl::opt<ReplayInlinerSettings::Fallback> CGSCCInlineReplayFallback( 131 "cgscc-inline-replay-fallback", 132 cl::init(ReplayInlinerSettings::Fallback::Original), 133 cl::values( 134 clEnumValN( 135 ReplayInlinerSettings::Fallback::Original, "Original", 136 "All decisions not in replay send to original advisor (default)"), 137 clEnumValN(ReplayInlinerSettings::Fallback::AlwaysInline, 138 "AlwaysInline", "All decisions not in replay are inlined"), 139 clEnumValN(ReplayInlinerSettings::Fallback::NeverInline, "NeverInline", 140 "All decisions not in replay are not inlined")), 141 cl::desc( 142 "How cgscc inline replay treats sites that don't come from the replay. " 143 "Original: defers to original advisor, AlwaysInline: inline all sites " 144 "not in replay, NeverInline: inline no sites not in replay"), 145 cl::Hidden); 146 147 static cl::opt<CallSiteFormat::Format> CGSCCInlineReplayFormat( 148 "cgscc-inline-replay-format", 149 cl::init(CallSiteFormat::Format::LineColumnDiscriminator), 150 cl::values( 151 clEnumValN(CallSiteFormat::Format::Line, "Line", "<Line Number>"), 152 clEnumValN(CallSiteFormat::Format::LineColumn, "LineColumn", 153 "<Line Number>:<Column Number>"), 154 clEnumValN(CallSiteFormat::Format::LineDiscriminator, 155 "LineDiscriminator", "<Line Number>.<Discriminator>"), 156 clEnumValN(CallSiteFormat::Format::LineColumnDiscriminator, 157 "LineColumnDiscriminator", 158 "<Line Number>:<Column Number>.<Discriminator> (default)")), 159 cl::desc("How cgscc inline replay file is formatted"), cl::Hidden); 160 161 static cl::opt<bool> InlineEnablePriorityOrder( 162 "inline-enable-priority-order", cl::Hidden, cl::init(false), 163 cl::desc("Enable the priority inline order for the inliner")); 164 165 LegacyInlinerBase::LegacyInlinerBase(char &ID) : CallGraphSCCPass(ID) {} 166 167 LegacyInlinerBase::LegacyInlinerBase(char &ID, bool InsertLifetime) 168 : CallGraphSCCPass(ID), InsertLifetime(InsertLifetime) {} 169 170 /// For this class, we declare that we require and preserve the call graph. 171 /// If the derived class implements this method, it should 172 /// always explicitly call the implementation here. 173 void LegacyInlinerBase::getAnalysisUsage(AnalysisUsage &AU) const { 174 AU.addRequired<AssumptionCacheTracker>(); 175 AU.addRequired<ProfileSummaryInfoWrapperPass>(); 176 AU.addRequired<TargetLibraryInfoWrapperPass>(); 177 getAAResultsAnalysisUsage(AU); 178 CallGraphSCCPass::getAnalysisUsage(AU); 179 } 180 181 using InlinedArrayAllocasTy = DenseMap<ArrayType *, std::vector<AllocaInst *>>; 182 183 /// Look at all of the allocas that we inlined through this call site. If we 184 /// have already inlined other allocas through other calls into this function, 185 /// then we know that they have disjoint lifetimes and that we can merge them. 186 /// 187 /// There are many heuristics possible for merging these allocas, and the 188 /// different options have different tradeoffs. One thing that we *really* 189 /// don't want to hurt is SRoA: once inlining happens, often allocas are no 190 /// longer address taken and so they can be promoted. 191 /// 192 /// Our "solution" for that is to only merge allocas whose outermost type is an 193 /// array type. These are usually not promoted because someone is using a 194 /// variable index into them. These are also often the most important ones to 195 /// merge. 196 /// 197 /// A better solution would be to have real memory lifetime markers in the IR 198 /// and not have the inliner do any merging of allocas at all. This would 199 /// allow the backend to do proper stack slot coloring of all allocas that 200 /// *actually make it to the backend*, which is really what we want. 201 /// 202 /// Because we don't have this information, we do this simple and useful hack. 203 static void mergeInlinedArrayAllocas(Function *Caller, InlineFunctionInfo &IFI, 204 InlinedArrayAllocasTy &InlinedArrayAllocas, 205 int InlineHistory) { 206 SmallPtrSet<AllocaInst *, 16> UsedAllocas; 207 208 // When processing our SCC, check to see if the call site was inlined from 209 // some other call site. For example, if we're processing "A" in this code: 210 // A() { B() } 211 // B() { x = alloca ... C() } 212 // C() { y = alloca ... } 213 // Assume that C was not inlined into B initially, and so we're processing A 214 // and decide to inline B into A. Doing this makes an alloca available for 215 // reuse and makes a callsite (C) available for inlining. When we process 216 // the C call site we don't want to do any alloca merging between X and Y 217 // because their scopes are not disjoint. We could make this smarter by 218 // keeping track of the inline history for each alloca in the 219 // InlinedArrayAllocas but this isn't likely to be a significant win. 220 if (InlineHistory != -1) // Only do merging for top-level call sites in SCC. 221 return; 222 223 // Loop over all the allocas we have so far and see if they can be merged with 224 // a previously inlined alloca. If not, remember that we had it. 225 for (unsigned AllocaNo = 0, E = IFI.StaticAllocas.size(); AllocaNo != E; 226 ++AllocaNo) { 227 AllocaInst *AI = IFI.StaticAllocas[AllocaNo]; 228 229 // Don't bother trying to merge array allocations (they will usually be 230 // canonicalized to be an allocation *of* an array), or allocations whose 231 // type is not itself an array (because we're afraid of pessimizing SRoA). 232 ArrayType *ATy = dyn_cast<ArrayType>(AI->getAllocatedType()); 233 if (!ATy || AI->isArrayAllocation()) 234 continue; 235 236 // Get the list of all available allocas for this array type. 237 std::vector<AllocaInst *> &AllocasForType = InlinedArrayAllocas[ATy]; 238 239 // Loop over the allocas in AllocasForType to see if we can reuse one. Note 240 // that we have to be careful not to reuse the same "available" alloca for 241 // multiple different allocas that we just inlined, we use the 'UsedAllocas' 242 // set to keep track of which "available" allocas are being used by this 243 // function. Also, AllocasForType can be empty of course! 244 bool MergedAwayAlloca = false; 245 for (AllocaInst *AvailableAlloca : AllocasForType) { 246 Align Align1 = AI->getAlign(); 247 Align Align2 = AvailableAlloca->getAlign(); 248 249 // The available alloca has to be in the right function, not in some other 250 // function in this SCC. 251 if (AvailableAlloca->getParent() != AI->getParent()) 252 continue; 253 254 // If the inlined function already uses this alloca then we can't reuse 255 // it. 256 if (!UsedAllocas.insert(AvailableAlloca).second) 257 continue; 258 259 // Otherwise, we *can* reuse it, RAUW AI into AvailableAlloca and declare 260 // success! 261 LLVM_DEBUG(dbgs() << " ***MERGED ALLOCA: " << *AI 262 << "\n\t\tINTO: " << *AvailableAlloca << '\n'); 263 264 // Move affected dbg.declare calls immediately after the new alloca to 265 // avoid the situation when a dbg.declare precedes its alloca. 266 if (auto *L = LocalAsMetadata::getIfExists(AI)) 267 if (auto *MDV = MetadataAsValue::getIfExists(AI->getContext(), L)) 268 for (User *U : MDV->users()) 269 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(U)) 270 DDI->moveBefore(AvailableAlloca->getNextNode()); 271 272 AI->replaceAllUsesWith(AvailableAlloca); 273 274 if (Align1 > Align2) 275 AvailableAlloca->setAlignment(AI->getAlign()); 276 277 AI->eraseFromParent(); 278 MergedAwayAlloca = true; 279 ++NumMergedAllocas; 280 IFI.StaticAllocas[AllocaNo] = nullptr; 281 break; 282 } 283 284 // If we already nuked the alloca, we're done with it. 285 if (MergedAwayAlloca) 286 continue; 287 288 // If we were unable to merge away the alloca either because there are no 289 // allocas of the right type available or because we reused them all 290 // already, remember that this alloca came from an inlined function and mark 291 // it used so we don't reuse it for other allocas from this inline 292 // operation. 293 AllocasForType.push_back(AI); 294 UsedAllocas.insert(AI); 295 } 296 } 297 298 /// If it is possible to inline the specified call site, 299 /// do so and update the CallGraph for this operation. 300 /// 301 /// This function also does some basic book-keeping to update the IR. The 302 /// InlinedArrayAllocas map keeps track of any allocas that are already 303 /// available from other functions inlined into the caller. If we are able to 304 /// inline this call site we attempt to reuse already available allocas or add 305 /// any new allocas to the set if not possible. 306 static InlineResult inlineCallIfPossible( 307 CallBase &CB, InlineFunctionInfo &IFI, 308 InlinedArrayAllocasTy &InlinedArrayAllocas, int InlineHistory, 309 bool InsertLifetime, function_ref<AAResults &(Function &)> &AARGetter, 310 ImportedFunctionsInliningStatistics &ImportedFunctionsStats) { 311 Function *Callee = CB.getCalledFunction(); 312 Function *Caller = CB.getCaller(); 313 314 AAResults &AAR = AARGetter(*Callee); 315 316 // Try to inline the function. Get the list of static allocas that were 317 // inlined. 318 InlineResult IR = InlineFunction(CB, IFI, &AAR, InsertLifetime); 319 if (!IR.isSuccess()) 320 return IR; 321 322 if (InlinerFunctionImportStats != InlinerFunctionImportStatsOpts::No) 323 ImportedFunctionsStats.recordInline(*Caller, *Callee); 324 325 AttributeFuncs::mergeAttributesForInlining(*Caller, *Callee); 326 327 if (!DisableInlinedAllocaMerging) 328 mergeInlinedArrayAllocas(Caller, IFI, InlinedArrayAllocas, InlineHistory); 329 330 return IR; // success 331 } 332 333 /// Return true if the specified inline history ID 334 /// indicates an inline history that includes the specified function. 335 static bool inlineHistoryIncludes( 336 Function *F, int InlineHistoryID, 337 const SmallVectorImpl<std::pair<Function *, int>> &InlineHistory) { 338 while (InlineHistoryID != -1) { 339 assert(unsigned(InlineHistoryID) < InlineHistory.size() && 340 "Invalid inline history ID"); 341 if (InlineHistory[InlineHistoryID].first == F) 342 return true; 343 InlineHistoryID = InlineHistory[InlineHistoryID].second; 344 } 345 return false; 346 } 347 348 bool LegacyInlinerBase::doInitialization(CallGraph &CG) { 349 if (InlinerFunctionImportStats != InlinerFunctionImportStatsOpts::No) 350 ImportedFunctionsStats.setModuleInfo(CG.getModule()); 351 return false; // No changes to CallGraph. 352 } 353 354 bool LegacyInlinerBase::runOnSCC(CallGraphSCC &SCC) { 355 if (skipSCC(SCC)) 356 return false; 357 return inlineCalls(SCC); 358 } 359 360 static bool 361 inlineCallsImpl(CallGraphSCC &SCC, CallGraph &CG, 362 std::function<AssumptionCache &(Function &)> GetAssumptionCache, 363 ProfileSummaryInfo *PSI, 364 std::function<const TargetLibraryInfo &(Function &)> GetTLI, 365 bool InsertLifetime, 366 function_ref<InlineCost(CallBase &CB)> GetInlineCost, 367 function_ref<AAResults &(Function &)> AARGetter, 368 ImportedFunctionsInliningStatistics &ImportedFunctionsStats) { 369 SmallPtrSet<Function *, 8> SCCFunctions; 370 LLVM_DEBUG(dbgs() << "Inliner visiting SCC:"); 371 for (CallGraphNode *Node : SCC) { 372 Function *F = Node->getFunction(); 373 if (F) 374 SCCFunctions.insert(F); 375 LLVM_DEBUG(dbgs() << " " << (F ? F->getName() : "INDIRECTNODE")); 376 } 377 378 // Scan through and identify all call sites ahead of time so that we only 379 // inline call sites in the original functions, not call sites that result 380 // from inlining other functions. 381 SmallVector<std::pair<CallBase *, int>, 16> CallSites; 382 383 // When inlining a callee produces new call sites, we want to keep track of 384 // the fact that they were inlined from the callee. This allows us to avoid 385 // infinite inlining in some obscure cases. To represent this, we use an 386 // index into the InlineHistory vector. 387 SmallVector<std::pair<Function *, int>, 8> InlineHistory; 388 389 for (CallGraphNode *Node : SCC) { 390 Function *F = Node->getFunction(); 391 if (!F || F->isDeclaration()) 392 continue; 393 394 OptimizationRemarkEmitter ORE(F); 395 for (BasicBlock &BB : *F) 396 for (Instruction &I : BB) { 397 auto *CB = dyn_cast<CallBase>(&I); 398 // If this isn't a call, or it is a call to an intrinsic, it can 399 // never be inlined. 400 if (!CB || isa<IntrinsicInst>(I)) 401 continue; 402 403 // If this is a direct call to an external function, we can never inline 404 // it. If it is an indirect call, inlining may resolve it to be a 405 // direct call, so we keep it. 406 if (Function *Callee = CB->getCalledFunction()) 407 if (Callee->isDeclaration()) { 408 using namespace ore; 409 410 setInlineRemark(*CB, "unavailable definition"); 411 ORE.emit([&]() { 412 return OptimizationRemarkMissed(DEBUG_TYPE, "NoDefinition", &I) 413 << NV("Callee", Callee) << " will not be inlined into " 414 << NV("Caller", CB->getCaller()) 415 << " because its definition is unavailable" 416 << setIsVerbose(); 417 }); 418 continue; 419 } 420 421 CallSites.push_back(std::make_pair(CB, -1)); 422 } 423 } 424 425 LLVM_DEBUG(dbgs() << ": " << CallSites.size() << " call sites.\n"); 426 427 // If there are no calls in this function, exit early. 428 if (CallSites.empty()) 429 return false; 430 431 // Now that we have all of the call sites, move the ones to functions in the 432 // current SCC to the end of the list. 433 unsigned FirstCallInSCC = CallSites.size(); 434 for (unsigned I = 0; I < FirstCallInSCC; ++I) 435 if (Function *F = CallSites[I].first->getCalledFunction()) 436 if (SCCFunctions.count(F)) 437 std::swap(CallSites[I--], CallSites[--FirstCallInSCC]); 438 439 InlinedArrayAllocasTy InlinedArrayAllocas; 440 InlineFunctionInfo InlineInfo(&CG, GetAssumptionCache, PSI); 441 442 // Now that we have all of the call sites, loop over them and inline them if 443 // it looks profitable to do so. 444 bool Changed = false; 445 bool LocalChange; 446 do { 447 LocalChange = false; 448 // Iterate over the outer loop because inlining functions can cause indirect 449 // calls to become direct calls. 450 // CallSites may be modified inside so ranged for loop can not be used. 451 for (unsigned CSi = 0; CSi != CallSites.size(); ++CSi) { 452 auto &P = CallSites[CSi]; 453 CallBase &CB = *P.first; 454 const int InlineHistoryID = P.second; 455 456 Function *Caller = CB.getCaller(); 457 Function *Callee = CB.getCalledFunction(); 458 459 // We can only inline direct calls to non-declarations. 460 if (!Callee || Callee->isDeclaration()) 461 continue; 462 463 bool IsTriviallyDead = isInstructionTriviallyDead(&CB, &GetTLI(*Caller)); 464 465 if (!IsTriviallyDead) { 466 // If this call site was obtained by inlining another function, verify 467 // that the include path for the function did not include the callee 468 // itself. If so, we'd be recursively inlining the same function, 469 // which would provide the same callsites, which would cause us to 470 // infinitely inline. 471 if (InlineHistoryID != -1 && 472 inlineHistoryIncludes(Callee, InlineHistoryID, InlineHistory)) { 473 setInlineRemark(CB, "recursive"); 474 continue; 475 } 476 } 477 478 // FIXME for new PM: because of the old PM we currently generate ORE and 479 // in turn BFI on demand. With the new PM, the ORE dependency should 480 // just become a regular analysis dependency. 481 OptimizationRemarkEmitter ORE(Caller); 482 483 auto OIC = shouldInline(CB, GetInlineCost, ORE); 484 // If the policy determines that we should inline this function, 485 // delete the call instead. 486 if (!OIC) 487 continue; 488 489 // If this call site is dead and it is to a readonly function, we should 490 // just delete the call instead of trying to inline it, regardless of 491 // size. This happens because IPSCCP propagates the result out of the 492 // call and then we're left with the dead call. 493 if (IsTriviallyDead) { 494 LLVM_DEBUG(dbgs() << " -> Deleting dead call: " << CB << "\n"); 495 // Update the call graph by deleting the edge from Callee to Caller. 496 setInlineRemark(CB, "trivially dead"); 497 CG[Caller]->removeCallEdgeFor(CB); 498 CB.eraseFromParent(); 499 ++NumCallsDeleted; 500 } else { 501 // Get DebugLoc to report. CB will be invalid after Inliner. 502 DebugLoc DLoc = CB.getDebugLoc(); 503 BasicBlock *Block = CB.getParent(); 504 505 // Attempt to inline the function. 506 using namespace ore; 507 508 InlineResult IR = inlineCallIfPossible( 509 CB, InlineInfo, InlinedArrayAllocas, InlineHistoryID, 510 InsertLifetime, AARGetter, ImportedFunctionsStats); 511 if (!IR.isSuccess()) { 512 setInlineRemark(CB, std::string(IR.getFailureReason()) + "; " + 513 inlineCostStr(*OIC)); 514 ORE.emit([&]() { 515 return OptimizationRemarkMissed(DEBUG_TYPE, "NotInlined", DLoc, 516 Block) 517 << NV("Callee", Callee) << " will not be inlined into " 518 << NV("Caller", Caller) << ": " 519 << NV("Reason", IR.getFailureReason()); 520 }); 521 continue; 522 } 523 ++NumInlined; 524 525 emitInlinedIntoBasedOnCost(ORE, DLoc, Block, *Callee, *Caller, *OIC); 526 527 // If inlining this function gave us any new call sites, throw them 528 // onto our worklist to process. They are useful inline candidates. 529 if (!InlineInfo.InlinedCalls.empty()) { 530 // Create a new inline history entry for this, so that we remember 531 // that these new callsites came about due to inlining Callee. 532 int NewHistoryID = InlineHistory.size(); 533 InlineHistory.push_back(std::make_pair(Callee, InlineHistoryID)); 534 535 #ifndef NDEBUG 536 // Make sure no dupplicates in the inline candidates. This could 537 // happen when a callsite is simpilfied to reusing the return value 538 // of another callsite during function cloning, thus the other 539 // callsite will be reconsidered here. 540 DenseSet<CallBase *> DbgCallSites; 541 for (auto &II : CallSites) 542 DbgCallSites.insert(II.first); 543 #endif 544 545 for (Value *Ptr : InlineInfo.InlinedCalls) { 546 #ifndef NDEBUG 547 assert(DbgCallSites.count(dyn_cast<CallBase>(Ptr)) == 0); 548 #endif 549 CallSites.push_back( 550 std::make_pair(dyn_cast<CallBase>(Ptr), NewHistoryID)); 551 } 552 } 553 } 554 555 // If we inlined or deleted the last possible call site to the function, 556 // delete the function body now. 557 if (Callee && Callee->use_empty() && Callee->hasLocalLinkage() && 558 // TODO: Can remove if in SCC now. 559 !SCCFunctions.count(Callee) && 560 // The function may be apparently dead, but if there are indirect 561 // callgraph references to the node, we cannot delete it yet, this 562 // could invalidate the CGSCC iterator. 563 CG[Callee]->getNumReferences() == 0) { 564 LLVM_DEBUG(dbgs() << " -> Deleting dead function: " 565 << Callee->getName() << "\n"); 566 CallGraphNode *CalleeNode = CG[Callee]; 567 568 // Remove any call graph edges from the callee to its callees. 569 CalleeNode->removeAllCalledFunctions(); 570 571 // Removing the node for callee from the call graph and delete it. 572 delete CG.removeFunctionFromModule(CalleeNode); 573 ++NumDeleted; 574 } 575 576 // Remove this call site from the list. If possible, use 577 // swap/pop_back for efficiency, but do not use it if doing so would 578 // move a call site to a function in this SCC before the 579 // 'FirstCallInSCC' barrier. 580 if (SCC.isSingular()) { 581 CallSites[CSi] = CallSites.back(); 582 CallSites.pop_back(); 583 } else { 584 CallSites.erase(CallSites.begin() + CSi); 585 } 586 --CSi; 587 588 Changed = true; 589 LocalChange = true; 590 } 591 } while (LocalChange); 592 593 return Changed; 594 } 595 596 bool LegacyInlinerBase::inlineCalls(CallGraphSCC &SCC) { 597 CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph(); 598 ACT = &getAnalysis<AssumptionCacheTracker>(); 599 PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI(); 600 GetTLI = [&](Function &F) -> const TargetLibraryInfo & { 601 return getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F); 602 }; 603 auto GetAssumptionCache = [&](Function &F) -> AssumptionCache & { 604 return ACT->getAssumptionCache(F); 605 }; 606 return inlineCallsImpl( 607 SCC, CG, GetAssumptionCache, PSI, GetTLI, InsertLifetime, 608 [&](CallBase &CB) { return getInlineCost(CB); }, LegacyAARGetter(*this), 609 ImportedFunctionsStats); 610 } 611 612 /// Remove now-dead linkonce functions at the end of 613 /// processing to avoid breaking the SCC traversal. 614 bool LegacyInlinerBase::doFinalization(CallGraph &CG) { 615 if (InlinerFunctionImportStats != InlinerFunctionImportStatsOpts::No) 616 ImportedFunctionsStats.dump(InlinerFunctionImportStats == 617 InlinerFunctionImportStatsOpts::Verbose); 618 return removeDeadFunctions(CG); 619 } 620 621 /// Remove dead functions that are not included in DNR (Do Not Remove) list. 622 bool LegacyInlinerBase::removeDeadFunctions(CallGraph &CG, 623 bool AlwaysInlineOnly) { 624 SmallVector<CallGraphNode *, 16> FunctionsToRemove; 625 SmallVector<Function *, 16> DeadFunctionsInComdats; 626 627 auto RemoveCGN = [&](CallGraphNode *CGN) { 628 // Remove any call graph edges from the function to its callees. 629 CGN->removeAllCalledFunctions(); 630 631 // Remove any edges from the external node to the function's call graph 632 // node. These edges might have been made irrelegant due to 633 // optimization of the program. 634 CG.getExternalCallingNode()->removeAnyCallEdgeTo(CGN); 635 636 // Removing the node for callee from the call graph and delete it. 637 FunctionsToRemove.push_back(CGN); 638 }; 639 640 // Scan for all of the functions, looking for ones that should now be removed 641 // from the program. Insert the dead ones in the FunctionsToRemove set. 642 for (const auto &I : CG) { 643 CallGraphNode *CGN = I.second.get(); 644 Function *F = CGN->getFunction(); 645 if (!F || F->isDeclaration()) 646 continue; 647 648 // Handle the case when this function is called and we only want to care 649 // about always-inline functions. This is a bit of a hack to share code 650 // between here and the InlineAlways pass. 651 if (AlwaysInlineOnly && !F->hasFnAttribute(Attribute::AlwaysInline)) 652 continue; 653 654 // If the only remaining users of the function are dead constants, remove 655 // them. 656 F->removeDeadConstantUsers(); 657 658 if (!F->isDefTriviallyDead()) 659 continue; 660 661 // It is unsafe to drop a function with discardable linkage from a COMDAT 662 // without also dropping the other members of the COMDAT. 663 // The inliner doesn't visit non-function entities which are in COMDAT 664 // groups so it is unsafe to do so *unless* the linkage is local. 665 if (!F->hasLocalLinkage()) { 666 if (F->hasComdat()) { 667 DeadFunctionsInComdats.push_back(F); 668 continue; 669 } 670 } 671 672 RemoveCGN(CGN); 673 } 674 if (!DeadFunctionsInComdats.empty()) { 675 // Filter out the functions whose comdats remain alive. 676 filterDeadComdatFunctions(DeadFunctionsInComdats); 677 // Remove the rest. 678 for (Function *F : DeadFunctionsInComdats) 679 RemoveCGN(CG[F]); 680 } 681 682 if (FunctionsToRemove.empty()) 683 return false; 684 685 // Now that we know which functions to delete, do so. We didn't want to do 686 // this inline, because that would invalidate our CallGraph::iterator 687 // objects. :( 688 // 689 // Note that it doesn't matter that we are iterating over a non-stable order 690 // here to do this, it doesn't matter which order the functions are deleted 691 // in. 692 array_pod_sort(FunctionsToRemove.begin(), FunctionsToRemove.end()); 693 FunctionsToRemove.erase( 694 std::unique(FunctionsToRemove.begin(), FunctionsToRemove.end()), 695 FunctionsToRemove.end()); 696 for (CallGraphNode *CGN : FunctionsToRemove) { 697 delete CG.removeFunctionFromModule(CGN); 698 ++NumDeleted; 699 } 700 return true; 701 } 702 703 InlineAdvisor & 704 InlinerPass::getAdvisor(const ModuleAnalysisManagerCGSCCProxy::Result &MAM, 705 FunctionAnalysisManager &FAM, Module &M) { 706 if (OwnedAdvisor) 707 return *OwnedAdvisor; 708 709 auto *IAA = MAM.getCachedResult<InlineAdvisorAnalysis>(M); 710 if (!IAA) { 711 // It should still be possible to run the inliner as a stand-alone SCC pass, 712 // for test scenarios. In that case, we default to the 713 // DefaultInlineAdvisor, which doesn't need to keep state between SCC pass 714 // runs. It also uses just the default InlineParams. 715 // In this case, we need to use the provided FAM, which is valid for the 716 // duration of the inliner pass, and thus the lifetime of the owned advisor. 717 // The one we would get from the MAM can be invalidated as a result of the 718 // inliner's activity. 719 OwnedAdvisor = 720 std::make_unique<DefaultInlineAdvisor>(M, FAM, getInlineParams()); 721 722 if (!CGSCCInlineReplayFile.empty()) 723 OwnedAdvisor = getReplayInlineAdvisor( 724 M, FAM, M.getContext(), std::move(OwnedAdvisor), 725 ReplayInlinerSettings{CGSCCInlineReplayFile, 726 CGSCCInlineReplayScope, 727 CGSCCInlineReplayFallback, 728 {CGSCCInlineReplayFormat}}, 729 /*EmitRemarks=*/true); 730 731 return *OwnedAdvisor; 732 } 733 assert(IAA->getAdvisor() && 734 "Expected a present InlineAdvisorAnalysis also have an " 735 "InlineAdvisor initialized"); 736 return *IAA->getAdvisor(); 737 } 738 739 PreservedAnalyses InlinerPass::run(LazyCallGraph::SCC &InitialC, 740 CGSCCAnalysisManager &AM, LazyCallGraph &CG, 741 CGSCCUpdateResult &UR) { 742 const auto &MAMProxy = 743 AM.getResult<ModuleAnalysisManagerCGSCCProxy>(InitialC, CG); 744 bool Changed = false; 745 746 assert(InitialC.size() > 0 && "Cannot handle an empty SCC!"); 747 Module &M = *InitialC.begin()->getFunction().getParent(); 748 ProfileSummaryInfo *PSI = MAMProxy.getCachedResult<ProfileSummaryAnalysis>(M); 749 750 FunctionAnalysisManager &FAM = 751 AM.getResult<FunctionAnalysisManagerCGSCCProxy>(InitialC, CG) 752 .getManager(); 753 754 InlineAdvisor &Advisor = getAdvisor(MAMProxy, FAM, M); 755 Advisor.onPassEntry(); 756 757 auto AdvisorOnExit = make_scope_exit([&] { Advisor.onPassExit(&InitialC); }); 758 759 // We use a single common worklist for calls across the entire SCC. We 760 // process these in-order and append new calls introduced during inlining to 761 // the end. The PriorityInlineOrder is optional here, in which the smaller 762 // callee would have a higher priority to inline. 763 // 764 // Note that this particular order of processing is actually critical to 765 // avoid very bad behaviors. Consider *highly connected* call graphs where 766 // each function contains a small amount of code and a couple of calls to 767 // other functions. Because the LLVM inliner is fundamentally a bottom-up 768 // inliner, it can handle gracefully the fact that these all appear to be 769 // reasonable inlining candidates as it will flatten things until they become 770 // too big to inline, and then move on and flatten another batch. 771 // 772 // However, when processing call edges *within* an SCC we cannot rely on this 773 // bottom-up behavior. As a consequence, with heavily connected *SCCs* of 774 // functions we can end up incrementally inlining N calls into each of 775 // N functions because each incremental inlining decision looks good and we 776 // don't have a topological ordering to prevent explosions. 777 // 778 // To compensate for this, we don't process transitive edges made immediate 779 // by inlining until we've done one pass of inlining across the entire SCC. 780 // Large, highly connected SCCs still lead to some amount of code bloat in 781 // this model, but it is uniformly spread across all the functions in the SCC 782 // and eventually they all become too large to inline, rather than 783 // incrementally maknig a single function grow in a super linear fashion. 784 std::unique_ptr<InlineOrder<std::pair<CallBase *, int>>> Calls; 785 if (InlineEnablePriorityOrder) 786 Calls = std::make_unique<PriorityInlineOrder<InlineSizePriority>>(); 787 else 788 Calls = std::make_unique<DefaultInlineOrder<std::pair<CallBase *, int>>>(); 789 assert(Calls != nullptr && "Expected an initialized InlineOrder"); 790 791 // Populate the initial list of calls in this SCC. 792 for (auto &N : InitialC) { 793 auto &ORE = 794 FAM.getResult<OptimizationRemarkEmitterAnalysis>(N.getFunction()); 795 // We want to generally process call sites top-down in order for 796 // simplifications stemming from replacing the call with the returned value 797 // after inlining to be visible to subsequent inlining decisions. 798 // FIXME: Using instructions sequence is a really bad way to do this. 799 // Instead we should do an actual RPO walk of the function body. 800 for (Instruction &I : instructions(N.getFunction())) 801 if (auto *CB = dyn_cast<CallBase>(&I)) 802 if (Function *Callee = CB->getCalledFunction()) { 803 if (!Callee->isDeclaration()) 804 Calls->push({CB, -1}); 805 else if (!isa<IntrinsicInst>(I)) { 806 using namespace ore; 807 setInlineRemark(*CB, "unavailable definition"); 808 ORE.emit([&]() { 809 return OptimizationRemarkMissed(DEBUG_TYPE, "NoDefinition", &I) 810 << NV("Callee", Callee) << " will not be inlined into " 811 << NV("Caller", CB->getCaller()) 812 << " because its definition is unavailable" 813 << setIsVerbose(); 814 }); 815 } 816 } 817 } 818 if (Calls->empty()) 819 return PreservedAnalyses::all(); 820 821 // Capture updatable variable for the current SCC. 822 auto *C = &InitialC; 823 824 // When inlining a callee produces new call sites, we want to keep track of 825 // the fact that they were inlined from the callee. This allows us to avoid 826 // infinite inlining in some obscure cases. To represent this, we use an 827 // index into the InlineHistory vector. 828 SmallVector<std::pair<Function *, int>, 16> InlineHistory; 829 830 // Track a set vector of inlined callees so that we can augment the caller 831 // with all of their edges in the call graph before pruning out the ones that 832 // got simplified away. 833 SmallSetVector<Function *, 4> InlinedCallees; 834 835 // Track the dead functions to delete once finished with inlining calls. We 836 // defer deleting these to make it easier to handle the call graph updates. 837 SmallVector<Function *, 4> DeadFunctions; 838 839 // Track potentially dead non-local functions with comdats to see if they can 840 // be deleted as a batch after inlining. 841 SmallVector<Function *, 4> DeadFunctionsInComdats; 842 843 // Loop forward over all of the calls. 844 while (!Calls->empty()) { 845 // We expect the calls to typically be batched with sequences of calls that 846 // have the same caller, so we first set up some shared infrastructure for 847 // this caller. We also do any pruning we can at this layer on the caller 848 // alone. 849 Function &F = *Calls->front().first->getCaller(); 850 LazyCallGraph::Node &N = *CG.lookup(F); 851 if (CG.lookupSCC(N) != C) { 852 Calls->pop(); 853 continue; 854 } 855 856 LLVM_DEBUG(dbgs() << "Inlining calls in: " << F.getName() << "\n" 857 << " Function size: " << F.getInstructionCount() 858 << "\n"); 859 860 auto GetAssumptionCache = [&](Function &F) -> AssumptionCache & { 861 return FAM.getResult<AssumptionAnalysis>(F); 862 }; 863 864 // Now process as many calls as we have within this caller in the sequence. 865 // We bail out as soon as the caller has to change so we can update the 866 // call graph and prepare the context of that new caller. 867 bool DidInline = false; 868 while (!Calls->empty() && Calls->front().first->getCaller() == &F) { 869 auto P = Calls->pop(); 870 CallBase *CB = P.first; 871 const int InlineHistoryID = P.second; 872 Function &Callee = *CB->getCalledFunction(); 873 874 if (InlineHistoryID != -1 && 875 inlineHistoryIncludes(&Callee, InlineHistoryID, InlineHistory)) { 876 LLVM_DEBUG(dbgs() << "Skipping inlining due to history: " 877 << F.getName() << " -> " << Callee.getName() << "\n"); 878 setInlineRemark(*CB, "recursive"); 879 continue; 880 } 881 882 // Check if this inlining may repeat breaking an SCC apart that has 883 // already been split once before. In that case, inlining here may 884 // trigger infinite inlining, much like is prevented within the inliner 885 // itself by the InlineHistory above, but spread across CGSCC iterations 886 // and thus hidden from the full inline history. 887 LazyCallGraph::SCC *CalleeSCC = CG.lookupSCC(*CG.lookup(Callee)); 888 if (CalleeSCC == C && UR.InlinedInternalEdges.count({&N, C})) { 889 LLVM_DEBUG(dbgs() << "Skipping inlining internal SCC edge from a node " 890 "previously split out of this SCC by inlining: " 891 << F.getName() << " -> " << Callee.getName() << "\n"); 892 setInlineRemark(*CB, "recursive SCC split"); 893 continue; 894 } 895 896 std::unique_ptr<InlineAdvice> Advice = 897 Advisor.getAdvice(*CB, OnlyMandatory); 898 899 // Check whether we want to inline this callsite. 900 if (!Advice) 901 continue; 902 903 if (!Advice->isInliningRecommended()) { 904 Advice->recordUnattemptedInlining(); 905 continue; 906 } 907 908 int CBCostMult = 909 getStringFnAttrAsInt( 910 *CB, InlineConstants::FunctionInlineCostMultiplierAttributeName) 911 .getValueOr(1); 912 913 // Setup the data structure used to plumb customization into the 914 // `InlineFunction` routine. 915 InlineFunctionInfo IFI( 916 /*cg=*/nullptr, GetAssumptionCache, PSI, 917 &FAM.getResult<BlockFrequencyAnalysis>(*(CB->getCaller())), 918 &FAM.getResult<BlockFrequencyAnalysis>(Callee)); 919 920 InlineResult IR = 921 InlineFunction(*CB, IFI, &FAM.getResult<AAManager>(*CB->getCaller())); 922 if (!IR.isSuccess()) { 923 Advice->recordUnsuccessfulInlining(IR); 924 continue; 925 } 926 927 DidInline = true; 928 InlinedCallees.insert(&Callee); 929 ++NumInlined; 930 931 LLVM_DEBUG(dbgs() << " Size after inlining: " 932 << F.getInstructionCount() << "\n"); 933 934 // Add any new callsites to defined functions to the worklist. 935 if (!IFI.InlinedCallSites.empty()) { 936 int NewHistoryID = InlineHistory.size(); 937 InlineHistory.push_back({&Callee, InlineHistoryID}); 938 939 for (CallBase *ICB : reverse(IFI.InlinedCallSites)) { 940 Function *NewCallee = ICB->getCalledFunction(); 941 assert(!(NewCallee && NewCallee->isIntrinsic()) && 942 "Intrinsic calls should not be tracked."); 943 if (!NewCallee) { 944 // Try to promote an indirect (virtual) call without waiting for 945 // the post-inline cleanup and the next DevirtSCCRepeatedPass 946 // iteration because the next iteration may not happen and we may 947 // miss inlining it. 948 if (tryPromoteCall(*ICB)) 949 NewCallee = ICB->getCalledFunction(); 950 } 951 if (NewCallee) { 952 if (!NewCallee->isDeclaration()) { 953 Calls->push({ICB, NewHistoryID}); 954 // Continually inlining through an SCC can result in huge compile 955 // times and bloated code since we arbitrarily stop at some point 956 // when the inliner decides it's not profitable to inline anymore. 957 // We attempt to mitigate this by making these calls exponentially 958 // more expensive. 959 // This doesn't apply to calls in the same SCC since if we do 960 // inline through the SCC the function will end up being 961 // self-recursive which the inliner bails out on, and inlining 962 // within an SCC is necessary for performance. 963 if (CalleeSCC != C && 964 CalleeSCC == CG.lookupSCC(CG.get(*NewCallee))) { 965 Attribute NewCBCostMult = Attribute::get( 966 M.getContext(), 967 InlineConstants::FunctionInlineCostMultiplierAttributeName, 968 itostr(CBCostMult * IntraSCCCostMultiplier)); 969 ICB->addFnAttr(NewCBCostMult); 970 } 971 } 972 } 973 } 974 } 975 976 // Merge the attributes based on the inlining. 977 AttributeFuncs::mergeAttributesForInlining(F, Callee); 978 979 // For local functions or discardable functions without comdats, check 980 // whether this makes the callee trivially dead. In that case, we can drop 981 // the body of the function eagerly which may reduce the number of callers 982 // of other functions to one, changing inline cost thresholds. Non-local 983 // discardable functions with comdats are checked later on. 984 bool CalleeWasDeleted = false; 985 if (Callee.isDiscardableIfUnused() && Callee.hasZeroLiveUses() && 986 !CG.isLibFunction(Callee)) { 987 if (Callee.hasLocalLinkage() || !Callee.hasComdat()) { 988 Calls->erase_if([&](const std::pair<CallBase *, int> &Call) { 989 return Call.first->getCaller() == &Callee; 990 }); 991 // Clear the body and queue the function itself for deletion when we 992 // finish inlining and call graph updates. 993 // Note that after this point, it is an error to do anything other 994 // than use the callee's address or delete it. 995 Callee.dropAllReferences(); 996 assert(!is_contained(DeadFunctions, &Callee) && 997 "Cannot put cause a function to become dead twice!"); 998 DeadFunctions.push_back(&Callee); 999 CalleeWasDeleted = true; 1000 } else { 1001 DeadFunctionsInComdats.push_back(&Callee); 1002 } 1003 } 1004 if (CalleeWasDeleted) 1005 Advice->recordInliningWithCalleeDeleted(); 1006 else 1007 Advice->recordInlining(); 1008 } 1009 1010 if (!DidInline) 1011 continue; 1012 Changed = true; 1013 1014 // At this point, since we have made changes we have at least removed 1015 // a call instruction. However, in the process we do some incremental 1016 // simplification of the surrounding code. This simplification can 1017 // essentially do all of the same things as a function pass and we can 1018 // re-use the exact same logic for updating the call graph to reflect the 1019 // change. 1020 1021 // Inside the update, we also update the FunctionAnalysisManager in the 1022 // proxy for this particular SCC. We do this as the SCC may have changed and 1023 // as we're going to mutate this particular function we want to make sure 1024 // the proxy is in place to forward any invalidation events. 1025 LazyCallGraph::SCC *OldC = C; 1026 C = &updateCGAndAnalysisManagerForCGSCCPass(CG, *C, N, AM, UR, FAM); 1027 LLVM_DEBUG(dbgs() << "Updated inlining SCC: " << *C << "\n"); 1028 1029 // If this causes an SCC to split apart into multiple smaller SCCs, there 1030 // is a subtle risk we need to prepare for. Other transformations may 1031 // expose an "infinite inlining" opportunity later, and because of the SCC 1032 // mutation, we will revisit this function and potentially re-inline. If we 1033 // do, and that re-inlining also has the potentially to mutate the SCC 1034 // structure, the infinite inlining problem can manifest through infinite 1035 // SCC splits and merges. To avoid this, we capture the originating caller 1036 // node and the SCC containing the call edge. This is a slight over 1037 // approximation of the possible inlining decisions that must be avoided, 1038 // but is relatively efficient to store. We use C != OldC to know when 1039 // a new SCC is generated and the original SCC may be generated via merge 1040 // in later iterations. 1041 // 1042 // It is also possible that even if no new SCC is generated 1043 // (i.e., C == OldC), the original SCC could be split and then merged 1044 // into the same one as itself. and the original SCC will be added into 1045 // UR.CWorklist again, we want to catch such cases too. 1046 // 1047 // FIXME: This seems like a very heavyweight way of retaining the inline 1048 // history, we should look for a more efficient way of tracking it. 1049 if ((C != OldC || UR.CWorklist.count(OldC)) && 1050 llvm::any_of(InlinedCallees, [&](Function *Callee) { 1051 return CG.lookupSCC(*CG.lookup(*Callee)) == OldC; 1052 })) { 1053 LLVM_DEBUG(dbgs() << "Inlined an internal call edge and split an SCC, " 1054 "retaining this to avoid infinite inlining.\n"); 1055 UR.InlinedInternalEdges.insert({&N, OldC}); 1056 } 1057 InlinedCallees.clear(); 1058 1059 // Invalidate analyses for this function now so that we don't have to 1060 // invalidate analyses for all functions in this SCC later. 1061 FAM.invalidate(F, PreservedAnalyses::none()); 1062 } 1063 1064 // We must ensure that we only delete functions with comdats if every function 1065 // in the comdat is going to be deleted. 1066 if (!DeadFunctionsInComdats.empty()) { 1067 filterDeadComdatFunctions(DeadFunctionsInComdats); 1068 for (auto *Callee : DeadFunctionsInComdats) 1069 Callee->dropAllReferences(); 1070 DeadFunctions.append(DeadFunctionsInComdats); 1071 } 1072 1073 // Now that we've finished inlining all of the calls across this SCC, delete 1074 // all of the trivially dead functions, updating the call graph and the CGSCC 1075 // pass manager in the process. 1076 // 1077 // Note that this walks a pointer set which has non-deterministic order but 1078 // that is OK as all we do is delete things and add pointers to unordered 1079 // sets. 1080 for (Function *DeadF : DeadFunctions) { 1081 // Get the necessary information out of the call graph and nuke the 1082 // function there. Also, clear out any cached analyses. 1083 auto &DeadC = *CG.lookupSCC(*CG.lookup(*DeadF)); 1084 FAM.clear(*DeadF, DeadF->getName()); 1085 AM.clear(DeadC, DeadC.getName()); 1086 auto &DeadRC = DeadC.getOuterRefSCC(); 1087 CG.removeDeadFunction(*DeadF); 1088 1089 // Mark the relevant parts of the call graph as invalid so we don't visit 1090 // them. 1091 UR.InvalidatedSCCs.insert(&DeadC); 1092 UR.InvalidatedRefSCCs.insert(&DeadRC); 1093 1094 // If the updated SCC was the one containing the deleted function, clear it. 1095 if (&DeadC == UR.UpdatedC) 1096 UR.UpdatedC = nullptr; 1097 1098 // And delete the actual function from the module. 1099 M.getFunctionList().erase(DeadF); 1100 1101 ++NumDeleted; 1102 } 1103 1104 if (!Changed) 1105 return PreservedAnalyses::all(); 1106 1107 PreservedAnalyses PA; 1108 // Even if we change the IR, we update the core CGSCC data structures and so 1109 // can preserve the proxy to the function analysis manager. 1110 PA.preserve<FunctionAnalysisManagerCGSCCProxy>(); 1111 // We have already invalidated all analyses on modified functions. 1112 PA.preserveSet<AllAnalysesOn<Function>>(); 1113 return PA; 1114 } 1115 1116 ModuleInlinerWrapperPass::ModuleInlinerWrapperPass(InlineParams Params, 1117 bool MandatoryFirst, 1118 InliningAdvisorMode Mode, 1119 unsigned MaxDevirtIterations) 1120 : Params(Params), Mode(Mode), MaxDevirtIterations(MaxDevirtIterations) { 1121 // Run the inliner first. The theory is that we are walking bottom-up and so 1122 // the callees have already been fully optimized, and we want to inline them 1123 // into the callers so that our optimizations can reflect that. 1124 // For PreLinkThinLTO pass, we disable hot-caller heuristic for sample PGO 1125 // because it makes profile annotation in the backend inaccurate. 1126 if (MandatoryFirst) 1127 PM.addPass(InlinerPass(/*OnlyMandatory*/ true)); 1128 PM.addPass(InlinerPass()); 1129 } 1130 1131 PreservedAnalyses ModuleInlinerWrapperPass::run(Module &M, 1132 ModuleAnalysisManager &MAM) { 1133 auto &IAA = MAM.getResult<InlineAdvisorAnalysis>(M); 1134 if (!IAA.tryCreate(Params, Mode, 1135 {CGSCCInlineReplayFile, 1136 CGSCCInlineReplayScope, 1137 CGSCCInlineReplayFallback, 1138 {CGSCCInlineReplayFormat}})) { 1139 M.getContext().emitError( 1140 "Could not setup Inlining Advisor for the requested " 1141 "mode and/or options"); 1142 return PreservedAnalyses::all(); 1143 } 1144 1145 // We wrap the CGSCC pipeline in a devirtualization repeater. This will try 1146 // to detect when we devirtualize indirect calls and iterate the SCC passes 1147 // in that case to try and catch knock-on inlining or function attrs 1148 // opportunities. Then we add it to the module pipeline by walking the SCCs 1149 // in postorder (or bottom-up). 1150 // If MaxDevirtIterations is 0, we just don't use the devirtualization 1151 // wrapper. 1152 if (MaxDevirtIterations == 0) 1153 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(PM))); 1154 else 1155 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor( 1156 createDevirtSCCRepeatedPass(std::move(PM), MaxDevirtIterations))); 1157 1158 MPM.addPass(std::move(AfterCGMPM)); 1159 MPM.run(M, MAM); 1160 1161 // Discard the InlineAdvisor, a subsequent inlining session should construct 1162 // its own. 1163 auto PA = PreservedAnalyses::all(); 1164 if (!KeepAdvisorForPrinting) 1165 PA.abandon<InlineAdvisorAnalysis>(); 1166 return PA; 1167 } 1168 1169 void InlinerPass::printPipeline( 1170 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) { 1171 static_cast<PassInfoMixin<InlinerPass> *>(this)->printPipeline( 1172 OS, MapClassName2PassName); 1173 if (OnlyMandatory) 1174 OS << "<only-mandatory>"; 1175 } 1176 1177 void ModuleInlinerWrapperPass::printPipeline( 1178 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) { 1179 // Print some info about passes added to the wrapper. This is however 1180 // incomplete as InlineAdvisorAnalysis part isn't included (which also depends 1181 // on Params and Mode). 1182 if (!MPM.isEmpty()) { 1183 MPM.printPipeline(OS, MapClassName2PassName); 1184 OS << ","; 1185 } 1186 OS << "cgscc("; 1187 if (MaxDevirtIterations != 0) 1188 OS << "devirt<" << MaxDevirtIterations << ">("; 1189 PM.printPipeline(OS, MapClassName2PassName); 1190 if (MaxDevirtIterations != 0) 1191 OS << ")"; 1192 OS << ")"; 1193 } 1194