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/SetVector.h" 21 #include "llvm/ADT/SmallPtrSet.h" 22 #include "llvm/ADT/SmallVector.h" 23 #include "llvm/ADT/Statistic.h" 24 #include "llvm/ADT/StringRef.h" 25 #include "llvm/Analysis/AliasAnalysis.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/InlineCost.h" 32 #include "llvm/Analysis/LazyCallGraph.h" 33 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 34 #include "llvm/Analysis/ProfileSummaryInfo.h" 35 #include "llvm/Analysis/TargetLibraryInfo.h" 36 #include "llvm/Analysis/TargetTransformInfo.h" 37 #include "llvm/Transforms/Utils/Local.h" 38 #include "llvm/IR/Attributes.h" 39 #include "llvm/IR/BasicBlock.h" 40 #include "llvm/IR/CallSite.h" 41 #include "llvm/IR/DataLayout.h" 42 #include "llvm/IR/DebugLoc.h" 43 #include "llvm/IR/DerivedTypes.h" 44 #include "llvm/IR/DiagnosticInfo.h" 45 #include "llvm/IR/Function.h" 46 #include "llvm/IR/InstIterator.h" 47 #include "llvm/IR/Instruction.h" 48 #include "llvm/IR/Instructions.h" 49 #include "llvm/IR/IntrinsicInst.h" 50 #include "llvm/IR/Metadata.h" 51 #include "llvm/IR/Module.h" 52 #include "llvm/IR/PassManager.h" 53 #include "llvm/IR/User.h" 54 #include "llvm/IR/Value.h" 55 #include "llvm/Pass.h" 56 #include "llvm/Support/Casting.h" 57 #include "llvm/Support/CommandLine.h" 58 #include "llvm/Support/Debug.h" 59 #include "llvm/Support/raw_ostream.h" 60 #include "llvm/Transforms/Utils/Cloning.h" 61 #include "llvm/Transforms/Utils/ImportedFunctionsInliningStatistics.h" 62 #include "llvm/Transforms/Utils/ModuleUtils.h" 63 #include <algorithm> 64 #include <cassert> 65 #include <functional> 66 #include <sstream> 67 #include <tuple> 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 // This weirdly named statistic tracks the number of times that, when attempting 81 // to inline a function A into B, we analyze the callers of B in order to see 82 // if those would be more profitable and blocked inline steps. 83 STATISTIC(NumCallerCallersAnalyzed, "Number of caller-callers analyzed"); 84 85 /// Flag to disable manual alloca merging. 86 /// 87 /// Merging of allocas was originally done as a stack-size saving technique 88 /// prior to LLVM's code generator having support for stack coloring based on 89 /// lifetime markers. It is now in the process of being removed. To experiment 90 /// with disabling it and relying fully on lifetime marker based stack 91 /// coloring, you can pass this flag to LLVM. 92 static cl::opt<bool> 93 DisableInlinedAllocaMerging("disable-inlined-alloca-merging", 94 cl::init(false), cl::Hidden); 95 96 namespace { 97 98 enum class InlinerFunctionImportStatsOpts { 99 No = 0, 100 Basic = 1, 101 Verbose = 2, 102 }; 103 104 } // end anonymous namespace 105 106 static cl::opt<InlinerFunctionImportStatsOpts> InlinerFunctionImportStats( 107 "inliner-function-import-stats", 108 cl::init(InlinerFunctionImportStatsOpts::No), 109 cl::values(clEnumValN(InlinerFunctionImportStatsOpts::Basic, "basic", 110 "basic statistics"), 111 clEnumValN(InlinerFunctionImportStatsOpts::Verbose, "verbose", 112 "printing of statistics for each inlined function")), 113 cl::Hidden, cl::desc("Enable inliner stats for imported functions")); 114 115 /// Flag to add inline messages as callsite attributes 'inline-remark'. 116 static cl::opt<bool> 117 InlineRemarkAttribute("inline-remark-attribute", cl::init(false), 118 cl::Hidden, 119 cl::desc("Enable adding inline-remark attribute to" 120 " callsites processed by inliner but decided" 121 " to be not inlined")); 122 123 LegacyInlinerBase::LegacyInlinerBase(char &ID) : CallGraphSCCPass(ID) {} 124 125 LegacyInlinerBase::LegacyInlinerBase(char &ID, bool InsertLifetime) 126 : CallGraphSCCPass(ID), InsertLifetime(InsertLifetime) {} 127 128 /// For this class, we declare that we require and preserve the call graph. 129 /// If the derived class implements this method, it should 130 /// always explicitly call the implementation here. 131 void LegacyInlinerBase::getAnalysisUsage(AnalysisUsage &AU) const { 132 AU.addRequired<AssumptionCacheTracker>(); 133 AU.addRequired<ProfileSummaryInfoWrapperPass>(); 134 AU.addRequired<TargetLibraryInfoWrapperPass>(); 135 getAAResultsAnalysisUsage(AU); 136 CallGraphSCCPass::getAnalysisUsage(AU); 137 } 138 139 using InlinedArrayAllocasTy = DenseMap<ArrayType *, std::vector<AllocaInst *>>; 140 141 /// Look at all of the allocas that we inlined through this call site. If we 142 /// have already inlined other allocas through other calls into this function, 143 /// then we know that they have disjoint lifetimes and that we can merge them. 144 /// 145 /// There are many heuristics possible for merging these allocas, and the 146 /// different options have different tradeoffs. One thing that we *really* 147 /// don't want to hurt is SRoA: once inlining happens, often allocas are no 148 /// longer address taken and so they can be promoted. 149 /// 150 /// Our "solution" for that is to only merge allocas whose outermost type is an 151 /// array type. These are usually not promoted because someone is using a 152 /// variable index into them. These are also often the most important ones to 153 /// merge. 154 /// 155 /// A better solution would be to have real memory lifetime markers in the IR 156 /// and not have the inliner do any merging of allocas at all. This would 157 /// allow the backend to do proper stack slot coloring of all allocas that 158 /// *actually make it to the backend*, which is really what we want. 159 /// 160 /// Because we don't have this information, we do this simple and useful hack. 161 static void mergeInlinedArrayAllocas( 162 Function *Caller, InlineFunctionInfo &IFI, 163 InlinedArrayAllocasTy &InlinedArrayAllocas, int InlineHistory) { 164 SmallPtrSet<AllocaInst *, 16> UsedAllocas; 165 166 // When processing our SCC, check to see if CS was inlined from some other 167 // call site. For example, if we're processing "A" in this code: 168 // A() { B() } 169 // B() { x = alloca ... C() } 170 // C() { y = alloca ... } 171 // Assume that C was not inlined into B initially, and so we're processing A 172 // and decide to inline B into A. Doing this makes an alloca available for 173 // reuse and makes a callsite (C) available for inlining. When we process 174 // the C call site we don't want to do any alloca merging between X and Y 175 // because their scopes are not disjoint. We could make this smarter by 176 // keeping track of the inline history for each alloca in the 177 // InlinedArrayAllocas but this isn't likely to be a significant win. 178 if (InlineHistory != -1) // Only do merging for top-level call sites in SCC. 179 return; 180 181 // Loop over all the allocas we have so far and see if they can be merged with 182 // a previously inlined alloca. If not, remember that we had it. 183 for (unsigned AllocaNo = 0, e = IFI.StaticAllocas.size(); AllocaNo != e; 184 ++AllocaNo) { 185 AllocaInst *AI = IFI.StaticAllocas[AllocaNo]; 186 187 // Don't bother trying to merge array allocations (they will usually be 188 // canonicalized to be an allocation *of* an array), or allocations whose 189 // type is not itself an array (because we're afraid of pessimizing SRoA). 190 ArrayType *ATy = dyn_cast<ArrayType>(AI->getAllocatedType()); 191 if (!ATy || AI->isArrayAllocation()) 192 continue; 193 194 // Get the list of all available allocas for this array type. 195 std::vector<AllocaInst *> &AllocasForType = InlinedArrayAllocas[ATy]; 196 197 // Loop over the allocas in AllocasForType to see if we can reuse one. Note 198 // that we have to be careful not to reuse the same "available" alloca for 199 // multiple different allocas that we just inlined, we use the 'UsedAllocas' 200 // set to keep track of which "available" allocas are being used by this 201 // function. Also, AllocasForType can be empty of course! 202 bool MergedAwayAlloca = false; 203 for (AllocaInst *AvailableAlloca : AllocasForType) { 204 unsigned Align1 = AI->getAlignment(), 205 Align2 = AvailableAlloca->getAlignment(); 206 207 // The available alloca has to be in the right function, not in some other 208 // function in this SCC. 209 if (AvailableAlloca->getParent() != AI->getParent()) 210 continue; 211 212 // If the inlined function already uses this alloca then we can't reuse 213 // it. 214 if (!UsedAllocas.insert(AvailableAlloca).second) 215 continue; 216 217 // Otherwise, we *can* reuse it, RAUW AI into AvailableAlloca and declare 218 // success! 219 LLVM_DEBUG(dbgs() << " ***MERGED ALLOCA: " << *AI 220 << "\n\t\tINTO: " << *AvailableAlloca << '\n'); 221 222 // Move affected dbg.declare calls immediately after the new alloca to 223 // avoid the situation when a dbg.declare precedes its alloca. 224 if (auto *L = LocalAsMetadata::getIfExists(AI)) 225 if (auto *MDV = MetadataAsValue::getIfExists(AI->getContext(), L)) 226 for (User *U : MDV->users()) 227 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(U)) 228 DDI->moveBefore(AvailableAlloca->getNextNode()); 229 230 AI->replaceAllUsesWith(AvailableAlloca); 231 232 if (Align1 != Align2) { 233 if (!Align1 || !Align2) { 234 const DataLayout &DL = Caller->getParent()->getDataLayout(); 235 unsigned TypeAlign = DL.getABITypeAlignment(AI->getAllocatedType()); 236 237 Align1 = Align1 ? Align1 : TypeAlign; 238 Align2 = Align2 ? Align2 : TypeAlign; 239 } 240 241 if (Align1 > Align2) 242 AvailableAlloca->setAlignment(MaybeAlign(AI->getAlignment())); 243 } 244 245 AI->eraseFromParent(); 246 MergedAwayAlloca = true; 247 ++NumMergedAllocas; 248 IFI.StaticAllocas[AllocaNo] = nullptr; 249 break; 250 } 251 252 // If we already nuked the alloca, we're done with it. 253 if (MergedAwayAlloca) 254 continue; 255 256 // If we were unable to merge away the alloca either because there are no 257 // allocas of the right type available or because we reused them all 258 // already, remember that this alloca came from an inlined function and mark 259 // it used so we don't reuse it for other allocas from this inline 260 // operation. 261 AllocasForType.push_back(AI); 262 UsedAllocas.insert(AI); 263 } 264 } 265 266 /// If it is possible to inline the specified call site, 267 /// do so and update the CallGraph for this operation. 268 /// 269 /// This function also does some basic book-keeping to update the IR. The 270 /// InlinedArrayAllocas map keeps track of any allocas that are already 271 /// available from other functions inlined into the caller. If we are able to 272 /// inline this call site we attempt to reuse already available allocas or add 273 /// any new allocas to the set if not possible. 274 static InlineResult InlineCallIfPossible( 275 CallSite CS, InlineFunctionInfo &IFI, 276 InlinedArrayAllocasTy &InlinedArrayAllocas, int InlineHistory, 277 bool InsertLifetime, function_ref<AAResults &(Function &)> &AARGetter, 278 ImportedFunctionsInliningStatistics &ImportedFunctionsStats) { 279 Function *Callee = CS.getCalledFunction(); 280 Function *Caller = CS.getCaller(); 281 282 AAResults &AAR = AARGetter(*Callee); 283 284 // Try to inline the function. Get the list of static allocas that were 285 // inlined. 286 InlineResult IR = InlineFunction(CS, IFI, &AAR, InsertLifetime); 287 if (!IR.isSuccess()) 288 return IR; 289 290 if (InlinerFunctionImportStats != InlinerFunctionImportStatsOpts::No) 291 ImportedFunctionsStats.recordInline(*Caller, *Callee); 292 293 AttributeFuncs::mergeAttributesForInlining(*Caller, *Callee); 294 295 if (!DisableInlinedAllocaMerging) 296 mergeInlinedArrayAllocas(Caller, IFI, InlinedArrayAllocas, InlineHistory); 297 298 return IR; // success 299 } 300 301 /// Return true if inlining of CS can block the caller from being 302 /// inlined which is proved to be more beneficial. \p IC is the 303 /// estimated inline cost associated with callsite \p CS. 304 /// \p TotalSecondaryCost will be set to the estimated cost of inlining the 305 /// caller if \p CS is suppressed for inlining. 306 static bool 307 shouldBeDeferred(Function *Caller, CallSite CS, InlineCost IC, 308 int &TotalSecondaryCost, 309 function_ref<InlineCost(CallSite CS)> GetInlineCost) { 310 // For now we only handle local or inline functions. 311 if (!Caller->hasLocalLinkage() && !Caller->hasLinkOnceODRLinkage()) 312 return false; 313 // If the cost of inlining CS is non-positive, it is not going to prevent the 314 // caller from being inlined into its callers and hence we don't need to 315 // defer. 316 if (IC.getCost() <= 0) 317 return false; 318 // Try to detect the case where the current inlining candidate caller (call 319 // it B) is a static or linkonce-ODR function and is an inlining candidate 320 // elsewhere, and the current candidate callee (call it C) is large enough 321 // that inlining it into B would make B too big to inline later. In these 322 // circumstances it may be best not to inline C into B, but to inline B into 323 // its callers. 324 // 325 // This only applies to static and linkonce-ODR functions because those are 326 // expected to be available for inlining in the translation units where they 327 // are used. Thus we will always have the opportunity to make local inlining 328 // decisions. Importantly the linkonce-ODR linkage covers inline functions 329 // and templates in C++. 330 // 331 // FIXME: All of this logic should be sunk into getInlineCost. It relies on 332 // the internal implementation of the inline cost metrics rather than 333 // treating them as truly abstract units etc. 334 TotalSecondaryCost = 0; 335 // The candidate cost to be imposed upon the current function. 336 int CandidateCost = IC.getCost() - 1; 337 // If the caller has local linkage and can be inlined to all its callers, we 338 // can apply a huge negative bonus to TotalSecondaryCost. 339 bool ApplyLastCallBonus = Caller->hasLocalLinkage() && !Caller->hasOneUse(); 340 // This bool tracks what happens if we DO inline C into B. 341 bool inliningPreventsSomeOuterInline = false; 342 for (User *U : Caller->users()) { 343 // If the caller will not be removed (either because it does not have a 344 // local linkage or because the LastCallToStaticBonus has been already 345 // applied), then we can exit the loop early. 346 if (!ApplyLastCallBonus && TotalSecondaryCost >= IC.getCost()) 347 return false; 348 CallSite CS2(U); 349 350 // If this isn't a call to Caller (it could be some other sort 351 // of reference) skip it. Such references will prevent the caller 352 // from being removed. 353 if (!CS2 || CS2.getCalledFunction() != Caller) { 354 ApplyLastCallBonus = false; 355 continue; 356 } 357 358 InlineCost IC2 = GetInlineCost(CS2); 359 ++NumCallerCallersAnalyzed; 360 if (!IC2) { 361 ApplyLastCallBonus = false; 362 continue; 363 } 364 if (IC2.isAlways()) 365 continue; 366 367 // See if inlining of the original callsite would erase the cost delta of 368 // this callsite. We subtract off the penalty for the call instruction, 369 // which we would be deleting. 370 if (IC2.getCostDelta() <= CandidateCost) { 371 inliningPreventsSomeOuterInline = true; 372 TotalSecondaryCost += IC2.getCost(); 373 } 374 } 375 // If all outer calls to Caller would get inlined, the cost for the last 376 // one is set very low by getInlineCost, in anticipation that Caller will 377 // be removed entirely. We did not account for this above unless there 378 // is only one caller of Caller. 379 if (ApplyLastCallBonus) 380 TotalSecondaryCost -= InlineConstants::LastCallToStaticBonus; 381 382 if (inliningPreventsSomeOuterInline && TotalSecondaryCost < IC.getCost()) 383 return true; 384 385 return false; 386 } 387 388 static std::basic_ostream<char> &operator<<(std::basic_ostream<char> &R, 389 const ore::NV &Arg) { 390 return R << Arg.Val; 391 } 392 393 template <class RemarkT> 394 RemarkT &operator<<(RemarkT &&R, const InlineCost &IC) { 395 using namespace ore; 396 if (IC.isAlways()) { 397 R << "(cost=always)"; 398 } else if (IC.isNever()) { 399 R << "(cost=never)"; 400 } else { 401 R << "(cost=" << ore::NV("Cost", IC.getCost()) 402 << ", threshold=" << ore::NV("Threshold", IC.getThreshold()) << ")"; 403 } 404 if (const char *Reason = IC.getReason()) 405 R << ": " << ore::NV("Reason", Reason); 406 return R; 407 } 408 409 static std::string inlineCostStr(const InlineCost &IC) { 410 std::stringstream Remark; 411 Remark << IC; 412 return Remark.str(); 413 } 414 415 /// Return the cost only if the inliner should attempt to inline at the given 416 /// CallSite. If we return the cost, we will emit an optimisation remark later 417 /// using that cost, so we won't do so from this function. 418 static Optional<InlineCost> 419 shouldInline(CallSite CS, function_ref<InlineCost(CallSite CS)> GetInlineCost, 420 OptimizationRemarkEmitter &ORE) { 421 using namespace ore; 422 423 InlineCost IC = GetInlineCost(CS); 424 Instruction *Call = CS.getInstruction(); 425 Function *Callee = CS.getCalledFunction(); 426 Function *Caller = CS.getCaller(); 427 428 if (IC.isAlways()) { 429 LLVM_DEBUG(dbgs() << " Inlining " << inlineCostStr(IC) 430 << ", Call: " << *CS.getInstruction() << "\n"); 431 return IC; 432 } 433 434 if (IC.isNever()) { 435 LLVM_DEBUG(dbgs() << " NOT Inlining " << inlineCostStr(IC) 436 << ", Call: " << *CS.getInstruction() << "\n"); 437 ORE.emit([&]() { 438 return OptimizationRemarkMissed(DEBUG_TYPE, "NeverInline", Call) 439 << NV("Callee", Callee) << " not inlined into " 440 << NV("Caller", Caller) << " because it should never be inlined " 441 << IC; 442 }); 443 return IC; 444 } 445 446 if (!IC) { 447 LLVM_DEBUG(dbgs() << " NOT Inlining " << inlineCostStr(IC) 448 << ", Call: " << *CS.getInstruction() << "\n"); 449 ORE.emit([&]() { 450 return OptimizationRemarkMissed(DEBUG_TYPE, "TooCostly", Call) 451 << NV("Callee", Callee) << " not inlined into " 452 << NV("Caller", Caller) << " because too costly to inline " << IC; 453 }); 454 return IC; 455 } 456 457 int TotalSecondaryCost = 0; 458 if (shouldBeDeferred(Caller, CS, IC, TotalSecondaryCost, GetInlineCost)) { 459 LLVM_DEBUG(dbgs() << " NOT Inlining: " << *CS.getInstruction() 460 << " Cost = " << IC.getCost() 461 << ", outer Cost = " << TotalSecondaryCost << '\n'); 462 ORE.emit([&]() { 463 return OptimizationRemarkMissed(DEBUG_TYPE, "IncreaseCostInOtherContexts", 464 Call) 465 << "Not inlining. Cost of inlining " << NV("Callee", Callee) 466 << " increases the cost of inlining " << NV("Caller", Caller) 467 << " in other contexts"; 468 }); 469 470 // IC does not bool() to false, so get an InlineCost that will. 471 // This will not be inspected to make an error message. 472 return None; 473 } 474 475 LLVM_DEBUG(dbgs() << " Inlining " << inlineCostStr(IC) 476 << ", Call: " << *CS.getInstruction() << '\n'); 477 return IC; 478 } 479 480 /// Return true if the specified inline history ID 481 /// indicates an inline history that includes the specified function. 482 static bool InlineHistoryIncludes( 483 Function *F, int InlineHistoryID, 484 const SmallVectorImpl<std::pair<Function *, int>> &InlineHistory) { 485 while (InlineHistoryID != -1) { 486 assert(unsigned(InlineHistoryID) < InlineHistory.size() && 487 "Invalid inline history ID"); 488 if (InlineHistory[InlineHistoryID].first == F) 489 return true; 490 InlineHistoryID = InlineHistory[InlineHistoryID].second; 491 } 492 return false; 493 } 494 495 bool LegacyInlinerBase::doInitialization(CallGraph &CG) { 496 if (InlinerFunctionImportStats != InlinerFunctionImportStatsOpts::No) 497 ImportedFunctionsStats.setModuleInfo(CG.getModule()); 498 return false; // No changes to CallGraph. 499 } 500 501 bool LegacyInlinerBase::runOnSCC(CallGraphSCC &SCC) { 502 if (skipSCC(SCC)) 503 return false; 504 return inlineCalls(SCC); 505 } 506 507 static void emit_inlined_into(OptimizationRemarkEmitter &ORE, DebugLoc &DLoc, 508 const BasicBlock *Block, const Function &Callee, 509 const Function &Caller, const InlineCost &IC) { 510 ORE.emit([&]() { 511 bool AlwaysInline = IC.isAlways(); 512 StringRef RemarkName = AlwaysInline ? "AlwaysInline" : "Inlined"; 513 return OptimizationRemark(DEBUG_TYPE, RemarkName, DLoc, Block) 514 << ore::NV("Callee", &Callee) << " inlined into " 515 << ore::NV("Caller", &Caller) << " with " << IC; 516 }); 517 } 518 519 static void setInlineRemark(CallSite &CS, StringRef message) { 520 if (!InlineRemarkAttribute) 521 return; 522 523 Attribute attr = Attribute::get(CS->getContext(), "inline-remark", message); 524 CS.addAttribute(AttributeList::FunctionIndex, attr); 525 } 526 527 static bool 528 inlineCallsImpl(CallGraphSCC &SCC, CallGraph &CG, 529 std::function<AssumptionCache &(Function &)> GetAssumptionCache, 530 ProfileSummaryInfo *PSI, 531 std::function<TargetLibraryInfo &(Function &)> GetTLI, 532 bool InsertLifetime, 533 function_ref<InlineCost(CallSite CS)> GetInlineCost, 534 function_ref<AAResults &(Function &)> AARGetter, 535 ImportedFunctionsInliningStatistics &ImportedFunctionsStats) { 536 SmallPtrSet<Function *, 8> SCCFunctions; 537 LLVM_DEBUG(dbgs() << "Inliner visiting SCC:"); 538 for (CallGraphNode *Node : SCC) { 539 Function *F = Node->getFunction(); 540 if (F) 541 SCCFunctions.insert(F); 542 LLVM_DEBUG(dbgs() << " " << (F ? F->getName() : "INDIRECTNODE")); 543 } 544 545 // Scan through and identify all call sites ahead of time so that we only 546 // inline call sites in the original functions, not call sites that result 547 // from inlining other functions. 548 SmallVector<std::pair<CallSite, int>, 16> CallSites; 549 550 // When inlining a callee produces new call sites, we want to keep track of 551 // the fact that they were inlined from the callee. This allows us to avoid 552 // infinite inlining in some obscure cases. To represent this, we use an 553 // index into the InlineHistory vector. 554 SmallVector<std::pair<Function *, int>, 8> InlineHistory; 555 556 for (CallGraphNode *Node : SCC) { 557 Function *F = Node->getFunction(); 558 if (!F || F->isDeclaration()) 559 continue; 560 561 OptimizationRemarkEmitter ORE(F); 562 for (BasicBlock &BB : *F) 563 for (Instruction &I : BB) { 564 CallSite CS(cast<Value>(&I)); 565 // If this isn't a call, or it is a call to an intrinsic, it can 566 // never be inlined. 567 if (!CS || isa<IntrinsicInst>(I)) 568 continue; 569 570 // If this is a direct call to an external function, we can never inline 571 // it. If it is an indirect call, inlining may resolve it to be a 572 // direct call, so we keep it. 573 if (Function *Callee = CS.getCalledFunction()) 574 if (Callee->isDeclaration()) { 575 using namespace ore; 576 577 setInlineRemark(CS, "unavailable definition"); 578 ORE.emit([&]() { 579 return OptimizationRemarkMissed(DEBUG_TYPE, "NoDefinition", &I) 580 << NV("Callee", Callee) << " will not be inlined into " 581 << NV("Caller", CS.getCaller()) 582 << " because its definition is unavailable" 583 << setIsVerbose(); 584 }); 585 continue; 586 } 587 588 CallSites.push_back(std::make_pair(CS, -1)); 589 } 590 } 591 592 LLVM_DEBUG(dbgs() << ": " << CallSites.size() << " call sites.\n"); 593 594 // If there are no calls in this function, exit early. 595 if (CallSites.empty()) 596 return false; 597 598 // Now that we have all of the call sites, move the ones to functions in the 599 // current SCC to the end of the list. 600 unsigned FirstCallInSCC = CallSites.size(); 601 for (unsigned i = 0; i < FirstCallInSCC; ++i) 602 if (Function *F = CallSites[i].first.getCalledFunction()) 603 if (SCCFunctions.count(F)) 604 std::swap(CallSites[i--], CallSites[--FirstCallInSCC]); 605 606 InlinedArrayAllocasTy InlinedArrayAllocas; 607 InlineFunctionInfo InlineInfo(&CG, &GetAssumptionCache, PSI); 608 609 // Now that we have all of the call sites, loop over them and inline them if 610 // it looks profitable to do so. 611 bool Changed = false; 612 bool LocalChange; 613 do { 614 LocalChange = false; 615 // Iterate over the outer loop because inlining functions can cause indirect 616 // calls to become direct calls. 617 // CallSites may be modified inside so ranged for loop can not be used. 618 for (unsigned CSi = 0; CSi != CallSites.size(); ++CSi) { 619 CallSite CS = CallSites[CSi].first; 620 621 Function *Caller = CS.getCaller(); 622 Function *Callee = CS.getCalledFunction(); 623 624 // We can only inline direct calls to non-declarations. 625 if (!Callee || Callee->isDeclaration()) 626 continue; 627 628 Instruction *Instr = CS.getInstruction(); 629 630 bool IsTriviallyDead = 631 isInstructionTriviallyDead(Instr, &GetTLI(*Caller)); 632 633 int InlineHistoryID; 634 if (!IsTriviallyDead) { 635 // If this call site was obtained by inlining another function, verify 636 // that the include path for the function did not include the callee 637 // itself. If so, we'd be recursively inlining the same function, 638 // which would provide the same callsites, which would cause us to 639 // infinitely inline. 640 InlineHistoryID = CallSites[CSi].second; 641 if (InlineHistoryID != -1 && 642 InlineHistoryIncludes(Callee, InlineHistoryID, InlineHistory)) { 643 setInlineRemark(CS, "recursive"); 644 continue; 645 } 646 } 647 648 // FIXME for new PM: because of the old PM we currently generate ORE and 649 // in turn BFI on demand. With the new PM, the ORE dependency should 650 // just become a regular analysis dependency. 651 OptimizationRemarkEmitter ORE(Caller); 652 653 Optional<InlineCost> OIC = shouldInline(CS, GetInlineCost, ORE); 654 // If the policy determines that we should inline this function, 655 // delete the call instead. 656 if (!OIC.hasValue()) { 657 setInlineRemark(CS, "deferred"); 658 continue; 659 } 660 661 if (!OIC.getValue()) { 662 // shouldInline() call returned a negative inline cost that explains 663 // why this callsite should not be inlined. 664 setInlineRemark(CS, inlineCostStr(*OIC)); 665 continue; 666 } 667 668 // If this call site is dead and it is to a readonly function, we should 669 // just delete the call instead of trying to inline it, regardless of 670 // size. This happens because IPSCCP propagates the result out of the 671 // call and then we're left with the dead call. 672 if (IsTriviallyDead) { 673 LLVM_DEBUG(dbgs() << " -> Deleting dead call: " << *Instr << "\n"); 674 // Update the call graph by deleting the edge from Callee to Caller. 675 setInlineRemark(CS, "trivially dead"); 676 CG[Caller]->removeCallEdgeFor(*cast<CallBase>(CS.getInstruction())); 677 Instr->eraseFromParent(); 678 ++NumCallsDeleted; 679 } else { 680 // Get DebugLoc to report. CS will be invalid after Inliner. 681 DebugLoc DLoc = CS->getDebugLoc(); 682 BasicBlock *Block = CS.getParent(); 683 684 // Attempt to inline the function. 685 using namespace ore; 686 687 InlineResult IR = InlineCallIfPossible( 688 CS, InlineInfo, InlinedArrayAllocas, InlineHistoryID, 689 InsertLifetime, AARGetter, ImportedFunctionsStats); 690 if (!IR.isSuccess()) { 691 setInlineRemark(CS, std::string(IR.getFailureReason()) + "; " + 692 inlineCostStr(*OIC)); 693 ORE.emit([&]() { 694 return OptimizationRemarkMissed(DEBUG_TYPE, "NotInlined", DLoc, 695 Block) 696 << NV("Callee", Callee) << " will not be inlined into " 697 << NV("Caller", Caller) << ": " 698 << NV("Reason", IR.getFailureReason()); 699 }); 700 continue; 701 } 702 ++NumInlined; 703 704 emit_inlined_into(ORE, DLoc, Block, *Callee, *Caller, *OIC); 705 706 // If inlining this function gave us any new call sites, throw them 707 // onto our worklist to process. They are useful inline candidates. 708 if (!InlineInfo.InlinedCalls.empty()) { 709 // Create a new inline history entry for this, so that we remember 710 // that these new callsites came about due to inlining Callee. 711 int NewHistoryID = InlineHistory.size(); 712 InlineHistory.push_back(std::make_pair(Callee, InlineHistoryID)); 713 714 for (Value *Ptr : InlineInfo.InlinedCalls) 715 CallSites.push_back(std::make_pair(CallSite(Ptr), NewHistoryID)); 716 } 717 } 718 719 // If we inlined or deleted the last possible call site to the function, 720 // delete the function body now. 721 if (Callee && Callee->use_empty() && Callee->hasLocalLinkage() && 722 // TODO: Can remove if in SCC now. 723 !SCCFunctions.count(Callee) && 724 // The function may be apparently dead, but if there are indirect 725 // callgraph references to the node, we cannot delete it yet, this 726 // could invalidate the CGSCC iterator. 727 CG[Callee]->getNumReferences() == 0) { 728 LLVM_DEBUG(dbgs() << " -> Deleting dead function: " 729 << Callee->getName() << "\n"); 730 CallGraphNode *CalleeNode = CG[Callee]; 731 732 // Remove any call graph edges from the callee to its callees. 733 CalleeNode->removeAllCalledFunctions(); 734 735 // Removing the node for callee from the call graph and delete it. 736 delete CG.removeFunctionFromModule(CalleeNode); 737 ++NumDeleted; 738 } 739 740 // Remove this call site from the list. If possible, use 741 // swap/pop_back for efficiency, but do not use it if doing so would 742 // move a call site to a function in this SCC before the 743 // 'FirstCallInSCC' barrier. 744 if (SCC.isSingular()) { 745 CallSites[CSi] = CallSites.back(); 746 CallSites.pop_back(); 747 } else { 748 CallSites.erase(CallSites.begin() + CSi); 749 } 750 --CSi; 751 752 Changed = true; 753 LocalChange = true; 754 } 755 } while (LocalChange); 756 757 return Changed; 758 } 759 760 bool LegacyInlinerBase::inlineCalls(CallGraphSCC &SCC) { 761 CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph(); 762 ACT = &getAnalysis<AssumptionCacheTracker>(); 763 PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI(); 764 auto GetTLI = [&](Function &F) -> TargetLibraryInfo & { 765 return getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F); 766 }; 767 auto GetAssumptionCache = [&](Function &F) -> AssumptionCache & { 768 return ACT->getAssumptionCache(F); 769 }; 770 return inlineCallsImpl( 771 SCC, CG, GetAssumptionCache, PSI, GetTLI, InsertLifetime, 772 [this](CallSite CS) { return getInlineCost(CS); }, LegacyAARGetter(*this), 773 ImportedFunctionsStats); 774 } 775 776 /// Remove now-dead linkonce functions at the end of 777 /// processing to avoid breaking the SCC traversal. 778 bool LegacyInlinerBase::doFinalization(CallGraph &CG) { 779 if (InlinerFunctionImportStats != InlinerFunctionImportStatsOpts::No) 780 ImportedFunctionsStats.dump(InlinerFunctionImportStats == 781 InlinerFunctionImportStatsOpts::Verbose); 782 return removeDeadFunctions(CG); 783 } 784 785 /// Remove dead functions that are not included in DNR (Do Not Remove) list. 786 bool LegacyInlinerBase::removeDeadFunctions(CallGraph &CG, 787 bool AlwaysInlineOnly) { 788 SmallVector<CallGraphNode *, 16> FunctionsToRemove; 789 SmallVector<Function *, 16> DeadFunctionsInComdats; 790 791 auto RemoveCGN = [&](CallGraphNode *CGN) { 792 // Remove any call graph edges from the function to its callees. 793 CGN->removeAllCalledFunctions(); 794 795 // Remove any edges from the external node to the function's call graph 796 // node. These edges might have been made irrelegant due to 797 // optimization of the program. 798 CG.getExternalCallingNode()->removeAnyCallEdgeTo(CGN); 799 800 // Removing the node for callee from the call graph and delete it. 801 FunctionsToRemove.push_back(CGN); 802 }; 803 804 // Scan for all of the functions, looking for ones that should now be removed 805 // from the program. Insert the dead ones in the FunctionsToRemove set. 806 for (const auto &I : CG) { 807 CallGraphNode *CGN = I.second.get(); 808 Function *F = CGN->getFunction(); 809 if (!F || F->isDeclaration()) 810 continue; 811 812 // Handle the case when this function is called and we only want to care 813 // about always-inline functions. This is a bit of a hack to share code 814 // between here and the InlineAlways pass. 815 if (AlwaysInlineOnly && !F->hasFnAttribute(Attribute::AlwaysInline)) 816 continue; 817 818 // If the only remaining users of the function are dead constants, remove 819 // them. 820 F->removeDeadConstantUsers(); 821 822 if (!F->isDefTriviallyDead()) 823 continue; 824 825 // It is unsafe to drop a function with discardable linkage from a COMDAT 826 // without also dropping the other members of the COMDAT. 827 // The inliner doesn't visit non-function entities which are in COMDAT 828 // groups so it is unsafe to do so *unless* the linkage is local. 829 if (!F->hasLocalLinkage()) { 830 if (F->hasComdat()) { 831 DeadFunctionsInComdats.push_back(F); 832 continue; 833 } 834 } 835 836 RemoveCGN(CGN); 837 } 838 if (!DeadFunctionsInComdats.empty()) { 839 // Filter out the functions whose comdats remain alive. 840 filterDeadComdatFunctions(CG.getModule(), DeadFunctionsInComdats); 841 // Remove the rest. 842 for (Function *F : DeadFunctionsInComdats) 843 RemoveCGN(CG[F]); 844 } 845 846 if (FunctionsToRemove.empty()) 847 return false; 848 849 // Now that we know which functions to delete, do so. We didn't want to do 850 // this inline, because that would invalidate our CallGraph::iterator 851 // objects. :( 852 // 853 // Note that it doesn't matter that we are iterating over a non-stable order 854 // here to do this, it doesn't matter which order the functions are deleted 855 // in. 856 array_pod_sort(FunctionsToRemove.begin(), FunctionsToRemove.end()); 857 FunctionsToRemove.erase( 858 std::unique(FunctionsToRemove.begin(), FunctionsToRemove.end()), 859 FunctionsToRemove.end()); 860 for (CallGraphNode *CGN : FunctionsToRemove) { 861 delete CG.removeFunctionFromModule(CGN); 862 ++NumDeleted; 863 } 864 return true; 865 } 866 867 InlinerPass::~InlinerPass() { 868 if (ImportedFunctionsStats) { 869 assert(InlinerFunctionImportStats != InlinerFunctionImportStatsOpts::No); 870 ImportedFunctionsStats->dump(InlinerFunctionImportStats == 871 InlinerFunctionImportStatsOpts::Verbose); 872 } 873 } 874 875 PreservedAnalyses InlinerPass::run(LazyCallGraph::SCC &InitialC, 876 CGSCCAnalysisManager &AM, LazyCallGraph &CG, 877 CGSCCUpdateResult &UR) { 878 const ModuleAnalysisManager &MAM = 879 AM.getResult<ModuleAnalysisManagerCGSCCProxy>(InitialC, CG).getManager(); 880 bool Changed = false; 881 882 assert(InitialC.size() > 0 && "Cannot handle an empty SCC!"); 883 Module &M = *InitialC.begin()->getFunction().getParent(); 884 ProfileSummaryInfo *PSI = MAM.getCachedResult<ProfileSummaryAnalysis>(M); 885 886 if (!ImportedFunctionsStats && 887 InlinerFunctionImportStats != InlinerFunctionImportStatsOpts::No) { 888 ImportedFunctionsStats = 889 std::make_unique<ImportedFunctionsInliningStatistics>(); 890 ImportedFunctionsStats->setModuleInfo(M); 891 } 892 893 // We use a single common worklist for calls across the entire SCC. We 894 // process these in-order and append new calls introduced during inlining to 895 // the end. 896 // 897 // Note that this particular order of processing is actually critical to 898 // avoid very bad behaviors. Consider *highly connected* call graphs where 899 // each function contains a small amonut of code and a couple of calls to 900 // other functions. Because the LLVM inliner is fundamentally a bottom-up 901 // inliner, it can handle gracefully the fact that these all appear to be 902 // reasonable inlining candidates as it will flatten things until they become 903 // too big to inline, and then move on and flatten another batch. 904 // 905 // However, when processing call edges *within* an SCC we cannot rely on this 906 // bottom-up behavior. As a consequence, with heavily connected *SCCs* of 907 // functions we can end up incrementally inlining N calls into each of 908 // N functions because each incremental inlining decision looks good and we 909 // don't have a topological ordering to prevent explosions. 910 // 911 // To compensate for this, we don't process transitive edges made immediate 912 // by inlining until we've done one pass of inlining across the entire SCC. 913 // Large, highly connected SCCs still lead to some amount of code bloat in 914 // this model, but it is uniformly spread across all the functions in the SCC 915 // and eventually they all become too large to inline, rather than 916 // incrementally maknig a single function grow in a super linear fashion. 917 SmallVector<std::pair<CallSite, int>, 16> Calls; 918 919 FunctionAnalysisManager &FAM = 920 AM.getResult<FunctionAnalysisManagerCGSCCProxy>(InitialC, CG) 921 .getManager(); 922 923 // Populate the initial list of calls in this SCC. 924 for (auto &N : InitialC) { 925 auto &ORE = 926 FAM.getResult<OptimizationRemarkEmitterAnalysis>(N.getFunction()); 927 // We want to generally process call sites top-down in order for 928 // simplifications stemming from replacing the call with the returned value 929 // after inlining to be visible to subsequent inlining decisions. 930 // FIXME: Using instructions sequence is a really bad way to do this. 931 // Instead we should do an actual RPO walk of the function body. 932 for (Instruction &I : instructions(N.getFunction())) 933 if (auto CS = CallSite(&I)) 934 if (Function *Callee = CS.getCalledFunction()) { 935 if (!Callee->isDeclaration()) 936 Calls.push_back({CS, -1}); 937 else if (!isa<IntrinsicInst>(I)) { 938 using namespace ore; 939 setInlineRemark(CS, "unavailable definition"); 940 ORE.emit([&]() { 941 return OptimizationRemarkMissed(DEBUG_TYPE, "NoDefinition", &I) 942 << NV("Callee", Callee) << " will not be inlined into " 943 << NV("Caller", CS.getCaller()) 944 << " because its definition is unavailable" 945 << setIsVerbose(); 946 }); 947 } 948 } 949 } 950 if (Calls.empty()) 951 return PreservedAnalyses::all(); 952 953 // Capture updatable variables for the current SCC and RefSCC. 954 auto *C = &InitialC; 955 auto *RC = &C->getOuterRefSCC(); 956 957 // When inlining a callee produces new call sites, we want to keep track of 958 // the fact that they were inlined from the callee. This allows us to avoid 959 // infinite inlining in some obscure cases. To represent this, we use an 960 // index into the InlineHistory vector. 961 SmallVector<std::pair<Function *, int>, 16> InlineHistory; 962 963 // Track a set vector of inlined callees so that we can augment the caller 964 // with all of their edges in the call graph before pruning out the ones that 965 // got simplified away. 966 SmallSetVector<Function *, 4> InlinedCallees; 967 968 // Track the dead functions to delete once finished with inlining calls. We 969 // defer deleting these to make it easier to handle the call graph updates. 970 SmallVector<Function *, 4> DeadFunctions; 971 972 // Loop forward over all of the calls. Note that we cannot cache the size as 973 // inlining can introduce new calls that need to be processed. 974 for (int i = 0; i < (int)Calls.size(); ++i) { 975 // We expect the calls to typically be batched with sequences of calls that 976 // have the same caller, so we first set up some shared infrastructure for 977 // this caller. We also do any pruning we can at this layer on the caller 978 // alone. 979 Function &F = *Calls[i].first.getCaller(); 980 LazyCallGraph::Node &N = *CG.lookup(F); 981 if (CG.lookupSCC(N) != C) 982 continue; 983 if (F.hasOptNone()) { 984 setInlineRemark(Calls[i].first, "optnone attribute"); 985 continue; 986 } 987 988 LLVM_DEBUG(dbgs() << "Inlining calls in: " << F.getName() << "\n"); 989 990 // Get a FunctionAnalysisManager via a proxy for this particular node. We 991 // do this each time we visit a node as the SCC may have changed and as 992 // we're going to mutate this particular function we want to make sure the 993 // proxy is in place to forward any invalidation events. We can use the 994 // manager we get here for looking up results for functions other than this 995 // node however because those functions aren't going to be mutated by this 996 // pass. 997 FunctionAnalysisManager &FAM = 998 AM.getResult<FunctionAnalysisManagerCGSCCProxy>(*C, CG) 999 .getManager(); 1000 1001 // Get the remarks emission analysis for the caller. 1002 auto &ORE = FAM.getResult<OptimizationRemarkEmitterAnalysis>(F); 1003 1004 std::function<AssumptionCache &(Function &)> GetAssumptionCache = 1005 [&](Function &F) -> AssumptionCache & { 1006 return FAM.getResult<AssumptionAnalysis>(F); 1007 }; 1008 auto GetBFI = [&](Function &F) -> BlockFrequencyInfo & { 1009 return FAM.getResult<BlockFrequencyAnalysis>(F); 1010 }; 1011 1012 auto GetInlineCost = [&](CallSite CS) { 1013 Function &Callee = *CS.getCalledFunction(); 1014 auto &CalleeTTI = FAM.getResult<TargetIRAnalysis>(Callee); 1015 bool RemarksEnabled = 1016 Callee.getContext().getDiagHandlerPtr()->isMissedOptRemarkEnabled( 1017 DEBUG_TYPE); 1018 return getInlineCost(cast<CallBase>(*CS.getInstruction()), Params, 1019 CalleeTTI, GetAssumptionCache, {GetBFI}, PSI, 1020 RemarksEnabled ? &ORE : nullptr); 1021 }; 1022 1023 // Now process as many calls as we have within this caller in the sequnece. 1024 // We bail out as soon as the caller has to change so we can update the 1025 // call graph and prepare the context of that new caller. 1026 bool DidInline = false; 1027 for (; i < (int)Calls.size() && Calls[i].first.getCaller() == &F; ++i) { 1028 int InlineHistoryID; 1029 CallSite CS; 1030 std::tie(CS, InlineHistoryID) = Calls[i]; 1031 Function &Callee = *CS.getCalledFunction(); 1032 1033 if (InlineHistoryID != -1 && 1034 InlineHistoryIncludes(&Callee, InlineHistoryID, InlineHistory)) { 1035 setInlineRemark(CS, "recursive"); 1036 continue; 1037 } 1038 1039 // Check if this inlining may repeat breaking an SCC apart that has 1040 // already been split once before. In that case, inlining here may 1041 // trigger infinite inlining, much like is prevented within the inliner 1042 // itself by the InlineHistory above, but spread across CGSCC iterations 1043 // and thus hidden from the full inline history. 1044 if (CG.lookupSCC(*CG.lookup(Callee)) == C && 1045 UR.InlinedInternalEdges.count({&N, C})) { 1046 LLVM_DEBUG(dbgs() << "Skipping inlining internal SCC edge from a node " 1047 "previously split out of this SCC by inlining: " 1048 << F.getName() << " -> " << Callee.getName() << "\n"); 1049 setInlineRemark(CS, "recursive SCC split"); 1050 continue; 1051 } 1052 1053 Optional<InlineCost> OIC = shouldInline(CS, GetInlineCost, ORE); 1054 // Check whether we want to inline this callsite. 1055 if (!OIC.hasValue()) { 1056 setInlineRemark(CS, "deferred"); 1057 continue; 1058 } 1059 1060 if (!OIC.getValue()) { 1061 // shouldInline() call returned a negative inline cost that explains 1062 // why this callsite should not be inlined. 1063 setInlineRemark(CS, inlineCostStr(*OIC)); 1064 continue; 1065 } 1066 1067 // Setup the data structure used to plumb customization into the 1068 // `InlineFunction` routine. 1069 InlineFunctionInfo IFI( 1070 /*cg=*/nullptr, &GetAssumptionCache, PSI, 1071 &FAM.getResult<BlockFrequencyAnalysis>(*(CS.getCaller())), 1072 &FAM.getResult<BlockFrequencyAnalysis>(Callee)); 1073 1074 // Get DebugLoc to report. CS will be invalid after Inliner. 1075 DebugLoc DLoc = CS->getDebugLoc(); 1076 BasicBlock *Block = CS.getParent(); 1077 1078 using namespace ore; 1079 1080 InlineResult IR = InlineFunction(CS, IFI); 1081 if (!IR.isSuccess()) { 1082 setInlineRemark(CS, std::string(IR.getFailureReason()) + "; " + 1083 inlineCostStr(*OIC)); 1084 ORE.emit([&]() { 1085 return OptimizationRemarkMissed(DEBUG_TYPE, "NotInlined", DLoc, Block) 1086 << NV("Callee", &Callee) << " will not be inlined into " 1087 << NV("Caller", &F) << ": " 1088 << NV("Reason", IR.getFailureReason()); 1089 }); 1090 continue; 1091 } 1092 DidInline = true; 1093 InlinedCallees.insert(&Callee); 1094 1095 ++NumInlined; 1096 1097 emit_inlined_into(ORE, DLoc, Block, Callee, F, *OIC); 1098 1099 // Add any new callsites to defined functions to the worklist. 1100 if (!IFI.InlinedCallSites.empty()) { 1101 int NewHistoryID = InlineHistory.size(); 1102 InlineHistory.push_back({&Callee, InlineHistoryID}); 1103 for (CallSite &CS : reverse(IFI.InlinedCallSites)) 1104 if (Function *NewCallee = CS.getCalledFunction()) 1105 if (!NewCallee->isDeclaration()) 1106 Calls.push_back({CS, NewHistoryID}); 1107 } 1108 1109 if (InlinerFunctionImportStats != InlinerFunctionImportStatsOpts::No) 1110 ImportedFunctionsStats->recordInline(F, Callee); 1111 1112 // Merge the attributes based on the inlining. 1113 AttributeFuncs::mergeAttributesForInlining(F, Callee); 1114 1115 // For local functions, check whether this makes the callee trivially 1116 // dead. In that case, we can drop the body of the function eagerly 1117 // which may reduce the number of callers of other functions to one, 1118 // changing inline cost thresholds. 1119 if (Callee.hasLocalLinkage()) { 1120 // To check this we also need to nuke any dead constant uses (perhaps 1121 // made dead by this operation on other functions). 1122 Callee.removeDeadConstantUsers(); 1123 if (Callee.use_empty() && !CG.isLibFunction(Callee)) { 1124 Calls.erase( 1125 std::remove_if(Calls.begin() + i + 1, Calls.end(), 1126 [&Callee](const std::pair<CallSite, int> &Call) { 1127 return Call.first.getCaller() == &Callee; 1128 }), 1129 Calls.end()); 1130 // Clear the body and queue the function itself for deletion when we 1131 // finish inlining and call graph updates. 1132 // Note that after this point, it is an error to do anything other 1133 // than use the callee's address or delete it. 1134 Callee.dropAllReferences(); 1135 assert(find(DeadFunctions, &Callee) == DeadFunctions.end() && 1136 "Cannot put cause a function to become dead twice!"); 1137 DeadFunctions.push_back(&Callee); 1138 } 1139 } 1140 } 1141 1142 // Back the call index up by one to put us in a good position to go around 1143 // the outer loop. 1144 --i; 1145 1146 if (!DidInline) 1147 continue; 1148 Changed = true; 1149 1150 // Add all the inlined callees' edges as ref edges to the caller. These are 1151 // by definition trivial edges as we always have *some* transitive ref edge 1152 // chain. While in some cases these edges are direct calls inside the 1153 // callee, they have to be modeled in the inliner as reference edges as 1154 // there may be a reference edge anywhere along the chain from the current 1155 // caller to the callee that causes the whole thing to appear like 1156 // a (transitive) reference edge that will require promotion to a call edge 1157 // below. 1158 for (Function *InlinedCallee : InlinedCallees) { 1159 LazyCallGraph::Node &CalleeN = *CG.lookup(*InlinedCallee); 1160 for (LazyCallGraph::Edge &E : *CalleeN) 1161 RC->insertTrivialRefEdge(N, E.getNode()); 1162 } 1163 1164 // At this point, since we have made changes we have at least removed 1165 // a call instruction. However, in the process we do some incremental 1166 // simplification of the surrounding code. This simplification can 1167 // essentially do all of the same things as a function pass and we can 1168 // re-use the exact same logic for updating the call graph to reflect the 1169 // change. 1170 LazyCallGraph::SCC *OldC = C; 1171 C = &updateCGAndAnalysisManagerForFunctionPass(CG, *C, N, AM, UR); 1172 LLVM_DEBUG(dbgs() << "Updated inlining SCC: " << *C << "\n"); 1173 RC = &C->getOuterRefSCC(); 1174 1175 // If this causes an SCC to split apart into multiple smaller SCCs, there 1176 // is a subtle risk we need to prepare for. Other transformations may 1177 // expose an "infinite inlining" opportunity later, and because of the SCC 1178 // mutation, we will revisit this function and potentially re-inline. If we 1179 // do, and that re-inlining also has the potentially to mutate the SCC 1180 // structure, the infinite inlining problem can manifest through infinite 1181 // SCC splits and merges. To avoid this, we capture the originating caller 1182 // node and the SCC containing the call edge. This is a slight over 1183 // approximation of the possible inlining decisions that must be avoided, 1184 // but is relatively efficient to store. We use C != OldC to know when 1185 // a new SCC is generated and the original SCC may be generated via merge 1186 // in later iterations. 1187 // 1188 // It is also possible that even if no new SCC is generated 1189 // (i.e., C == OldC), the original SCC could be split and then merged 1190 // into the same one as itself. and the original SCC will be added into 1191 // UR.CWorklist again, we want to catch such cases too. 1192 // 1193 // FIXME: This seems like a very heavyweight way of retaining the inline 1194 // history, we should look for a more efficient way of tracking it. 1195 if ((C != OldC || UR.CWorklist.count(OldC)) && 1196 llvm::any_of(InlinedCallees, [&](Function *Callee) { 1197 return CG.lookupSCC(*CG.lookup(*Callee)) == OldC; 1198 })) { 1199 LLVM_DEBUG(dbgs() << "Inlined an internal call edge and split an SCC, " 1200 "retaining this to avoid infinite inlining.\n"); 1201 UR.InlinedInternalEdges.insert({&N, OldC}); 1202 } 1203 InlinedCallees.clear(); 1204 } 1205 1206 // Now that we've finished inlining all of the calls across this SCC, delete 1207 // all of the trivially dead functions, updating the call graph and the CGSCC 1208 // pass manager in the process. 1209 // 1210 // Note that this walks a pointer set which has non-deterministic order but 1211 // that is OK as all we do is delete things and add pointers to unordered 1212 // sets. 1213 for (Function *DeadF : DeadFunctions) { 1214 // Get the necessary information out of the call graph and nuke the 1215 // function there. Also, cclear out any cached analyses. 1216 auto &DeadC = *CG.lookupSCC(*CG.lookup(*DeadF)); 1217 FunctionAnalysisManager &FAM = 1218 AM.getResult<FunctionAnalysisManagerCGSCCProxy>(DeadC, CG) 1219 .getManager(); 1220 FAM.clear(*DeadF, DeadF->getName()); 1221 AM.clear(DeadC, DeadC.getName()); 1222 auto &DeadRC = DeadC.getOuterRefSCC(); 1223 CG.removeDeadFunction(*DeadF); 1224 1225 // Mark the relevant parts of the call graph as invalid so we don't visit 1226 // them. 1227 UR.InvalidatedSCCs.insert(&DeadC); 1228 UR.InvalidatedRefSCCs.insert(&DeadRC); 1229 1230 // And delete the actual function from the module. 1231 M.getFunctionList().erase(DeadF); 1232 ++NumDeleted; 1233 } 1234 1235 if (!Changed) 1236 return PreservedAnalyses::all(); 1237 1238 // Even if we change the IR, we update the core CGSCC data structures and so 1239 // can preserve the proxy to the function analysis manager. 1240 PreservedAnalyses PA; 1241 PA.preserve<FunctionAnalysisManagerCGSCCProxy>(); 1242 return PA; 1243 } 1244