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