1 //===- InlineAdvisor.cpp - analysis pass implementation -------------------===// 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 InlineAdvisorAnalysis and DefaultInlineAdvisor, and 10 // related types. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/Analysis/InlineAdvisor.h" 15 #include "llvm/ADT/Statistic.h" 16 #include "llvm/Analysis/InlineCost.h" 17 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 18 #include "llvm/Analysis/ProfileSummaryInfo.h" 19 #include "llvm/Analysis/ReplayInlineAdvisor.h" 20 #include "llvm/Analysis/TargetLibraryInfo.h" 21 #include "llvm/Analysis/TargetTransformInfo.h" 22 #include "llvm/IR/DebugInfoMetadata.h" 23 #include "llvm/IR/Instructions.h" 24 #include "llvm/Support/CommandLine.h" 25 #include "llvm/Support/raw_ostream.h" 26 27 using namespace llvm; 28 #define DEBUG_TYPE "inline" 29 30 // This weirdly named statistic tracks the number of times that, when attempting 31 // to inline a function A into B, we analyze the callers of B in order to see 32 // if those would be more profitable and blocked inline steps. 33 STATISTIC(NumCallerCallersAnalyzed, "Number of caller-callers analyzed"); 34 35 /// Flag to add inline messages as callsite attributes 'inline-remark'. 36 static cl::opt<bool> 37 InlineRemarkAttribute("inline-remark-attribute", cl::init(false), 38 cl::Hidden, 39 cl::desc("Enable adding inline-remark attribute to" 40 " callsites processed by inliner but decided" 41 " to be not inlined")); 42 43 static cl::opt<bool> EnableInlineDeferral("inline-deferral", cl::init(false), 44 cl::Hidden, 45 cl::desc("Enable deferred inlining")); 46 47 // An integer used to limit the cost of inline deferral. The default negative 48 // number tells shouldBeDeferred to only take the secondary cost into account. 49 static cl::opt<int> 50 InlineDeferralScale("inline-deferral-scale", 51 cl::desc("Scale to limit the cost of inline deferral"), 52 cl::init(2), cl::Hidden); 53 54 extern cl::opt<InlinerFunctionImportStatsOpts> InlinerFunctionImportStats; 55 56 namespace { 57 using namespace llvm::ore; 58 class MandatoryInlineAdvice : public InlineAdvice { 59 public: 60 MandatoryInlineAdvice(InlineAdvisor *Advisor, CallBase &CB, 61 OptimizationRemarkEmitter &ORE, 62 bool IsInliningMandatory) 63 : InlineAdvice(Advisor, CB, ORE, IsInliningMandatory) {} 64 65 private: 66 void recordInliningWithCalleeDeletedImpl() override { recordInliningImpl(); } 67 68 void recordInliningImpl() override { 69 if (IsInliningRecommended) 70 emitInlinedInto(ORE, DLoc, Block, *Callee, *Caller, IsInliningRecommended, 71 [&](OptimizationRemark &Remark) { 72 Remark << ": always inline attribute"; 73 }); 74 } 75 76 void recordUnsuccessfulInliningImpl(const InlineResult &Result) override { 77 if (IsInliningRecommended) 78 ORE.emit([&]() { 79 return OptimizationRemarkMissed(DEBUG_TYPE, "NotInlined", DLoc, Block) 80 << "'" << NV("Callee", Callee) << "' is not AlwaysInline into '" 81 << NV("Caller", Caller) 82 << "': " << NV("Reason", Result.getFailureReason()); 83 }); 84 } 85 86 void recordUnattemptedInliningImpl() override { 87 assert(!IsInliningRecommended && "Expected to attempt inlining"); 88 } 89 }; 90 } // namespace 91 92 void DefaultInlineAdvice::recordUnsuccessfulInliningImpl( 93 const InlineResult &Result) { 94 using namespace ore; 95 llvm::setInlineRemark(*OriginalCB, std::string(Result.getFailureReason()) + 96 "; " + inlineCostStr(*OIC)); 97 ORE.emit([&]() { 98 return OptimizationRemarkMissed(DEBUG_TYPE, "NotInlined", DLoc, Block) 99 << "'" << NV("Callee", Callee) << "' is not inlined into '" 100 << NV("Caller", Caller) 101 << "': " << NV("Reason", Result.getFailureReason()); 102 }); 103 } 104 105 void DefaultInlineAdvice::recordInliningWithCalleeDeletedImpl() { 106 if (EmitRemarks) 107 emitInlinedIntoBasedOnCost(ORE, DLoc, Block, *Callee, *Caller, *OIC); 108 } 109 110 void DefaultInlineAdvice::recordInliningImpl() { 111 if (EmitRemarks) 112 emitInlinedIntoBasedOnCost(ORE, DLoc, Block, *Callee, *Caller, *OIC); 113 } 114 115 llvm::Optional<llvm::InlineCost> static getDefaultInlineAdvice( 116 CallBase &CB, FunctionAnalysisManager &FAM, const InlineParams &Params) { 117 Function &Caller = *CB.getCaller(); 118 ProfileSummaryInfo *PSI = 119 FAM.getResult<ModuleAnalysisManagerFunctionProxy>(Caller) 120 .getCachedResult<ProfileSummaryAnalysis>( 121 *CB.getParent()->getParent()->getParent()); 122 123 auto &ORE = FAM.getResult<OptimizationRemarkEmitterAnalysis>(Caller); 124 auto GetAssumptionCache = [&](Function &F) -> AssumptionCache & { 125 return FAM.getResult<AssumptionAnalysis>(F); 126 }; 127 auto GetBFI = [&](Function &F) -> BlockFrequencyInfo & { 128 return FAM.getResult<BlockFrequencyAnalysis>(F); 129 }; 130 auto GetTLI = [&](Function &F) -> const TargetLibraryInfo & { 131 return FAM.getResult<TargetLibraryAnalysis>(F); 132 }; 133 134 auto GetInlineCost = [&](CallBase &CB) { 135 Function &Callee = *CB.getCalledFunction(); 136 auto &CalleeTTI = FAM.getResult<TargetIRAnalysis>(Callee); 137 bool RemarksEnabled = 138 Callee.getContext().getDiagHandlerPtr()->isMissedOptRemarkEnabled( 139 DEBUG_TYPE); 140 return getInlineCost(CB, Params, CalleeTTI, GetAssumptionCache, GetTLI, 141 GetBFI, PSI, RemarksEnabled ? &ORE : nullptr); 142 }; 143 return llvm::shouldInline( 144 CB, GetInlineCost, ORE, 145 Params.EnableDeferral.getValueOr(EnableInlineDeferral)); 146 } 147 148 std::unique_ptr<InlineAdvice> 149 DefaultInlineAdvisor::getAdviceImpl(CallBase &CB) { 150 auto OIC = getDefaultInlineAdvice(CB, FAM, Params); 151 return std::make_unique<DefaultInlineAdvice>( 152 this, CB, OIC, 153 FAM.getResult<OptimizationRemarkEmitterAnalysis>(*CB.getCaller())); 154 } 155 156 InlineAdvice::InlineAdvice(InlineAdvisor *Advisor, CallBase &CB, 157 OptimizationRemarkEmitter &ORE, 158 bool IsInliningRecommended) 159 : Advisor(Advisor), Caller(CB.getCaller()), Callee(CB.getCalledFunction()), 160 DLoc(CB.getDebugLoc()), Block(CB.getParent()), ORE(ORE), 161 IsInliningRecommended(IsInliningRecommended) {} 162 163 void InlineAdvice::recordInlineStatsIfNeeded() { 164 if (Advisor->ImportedFunctionsStats) 165 Advisor->ImportedFunctionsStats->recordInline(*Caller, *Callee); 166 } 167 168 void InlineAdvice::recordInlining() { 169 markRecorded(); 170 recordInlineStatsIfNeeded(); 171 recordInliningImpl(); 172 } 173 174 void InlineAdvice::recordInliningWithCalleeDeleted() { 175 markRecorded(); 176 recordInlineStatsIfNeeded(); 177 recordInliningWithCalleeDeletedImpl(); 178 } 179 180 AnalysisKey InlineAdvisorAnalysis::Key; 181 182 bool InlineAdvisorAnalysis::Result::tryCreate( 183 InlineParams Params, InliningAdvisorMode Mode, 184 const ReplayInlinerSettings &ReplaySettings) { 185 auto &FAM = MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager(); 186 switch (Mode) { 187 case InliningAdvisorMode::Default: 188 LLVM_DEBUG(dbgs() << "Using default inliner heuristic.\n"); 189 Advisor.reset(new DefaultInlineAdvisor(M, FAM, Params)); 190 // Restrict replay to default advisor, ML advisors are stateful so 191 // replay will need augmentations to interleave with them correctly. 192 if (!ReplaySettings.ReplayFile.empty()) { 193 Advisor = llvm::getReplayInlineAdvisor(M, FAM, M.getContext(), 194 std::move(Advisor), ReplaySettings, 195 /* EmitRemarks =*/true); 196 } 197 break; 198 case InliningAdvisorMode::Development: 199 #ifdef LLVM_HAVE_TF_API 200 LLVM_DEBUG(dbgs() << "Using development-mode inliner policy.\n"); 201 Advisor = 202 llvm::getDevelopmentModeAdvisor(M, MAM, [&FAM, Params](CallBase &CB) { 203 auto OIC = getDefaultInlineAdvice(CB, FAM, Params); 204 return OIC.hasValue(); 205 }); 206 #endif 207 break; 208 case InliningAdvisorMode::Release: 209 #ifdef LLVM_HAVE_TF_AOT 210 LLVM_DEBUG(dbgs() << "Using release-mode inliner policy.\n"); 211 Advisor = llvm::getReleaseModeAdvisor(M, MAM); 212 #endif 213 break; 214 } 215 216 return !!Advisor; 217 } 218 219 /// Return true if inlining of CB can block the caller from being 220 /// inlined which is proved to be more beneficial. \p IC is the 221 /// estimated inline cost associated with callsite \p CB. 222 /// \p TotalSecondaryCost will be set to the estimated cost of inlining the 223 /// caller if \p CB is suppressed for inlining. 224 static bool 225 shouldBeDeferred(Function *Caller, InlineCost IC, int &TotalSecondaryCost, 226 function_ref<InlineCost(CallBase &CB)> GetInlineCost) { 227 // For now we only handle local or inline functions. 228 if (!Caller->hasLocalLinkage() && !Caller->hasLinkOnceODRLinkage()) 229 return false; 230 // If the cost of inlining CB is non-positive, it is not going to prevent the 231 // caller from being inlined into its callers and hence we don't need to 232 // defer. 233 if (IC.getCost() <= 0) 234 return false; 235 // Try to detect the case where the current inlining candidate caller (call 236 // it B) is a static or linkonce-ODR function and is an inlining candidate 237 // elsewhere, and the current candidate callee (call it C) is large enough 238 // that inlining it into B would make B too big to inline later. In these 239 // circumstances it may be best not to inline C into B, but to inline B into 240 // its callers. 241 // 242 // This only applies to static and linkonce-ODR functions because those are 243 // expected to be available for inlining in the translation units where they 244 // are used. Thus we will always have the opportunity to make local inlining 245 // decisions. Importantly the linkonce-ODR linkage covers inline functions 246 // and templates in C++. 247 // 248 // FIXME: All of this logic should be sunk into getInlineCost. It relies on 249 // the internal implementation of the inline cost metrics rather than 250 // treating them as truly abstract units etc. 251 TotalSecondaryCost = 0; 252 // The candidate cost to be imposed upon the current function. 253 int CandidateCost = IC.getCost() - 1; 254 // If the caller has local linkage and can be inlined to all its callers, we 255 // can apply a huge negative bonus to TotalSecondaryCost. 256 bool ApplyLastCallBonus = Caller->hasLocalLinkage() && !Caller->hasOneUse(); 257 // This bool tracks what happens if we DO inline C into B. 258 bool InliningPreventsSomeOuterInline = false; 259 unsigned NumCallerUsers = 0; 260 for (User *U : Caller->users()) { 261 CallBase *CS2 = dyn_cast<CallBase>(U); 262 263 // If this isn't a call to Caller (it could be some other sort 264 // of reference) skip it. Such references will prevent the caller 265 // from being removed. 266 if (!CS2 || CS2->getCalledFunction() != Caller) { 267 ApplyLastCallBonus = false; 268 continue; 269 } 270 271 InlineCost IC2 = GetInlineCost(*CS2); 272 ++NumCallerCallersAnalyzed; 273 if (!IC2) { 274 ApplyLastCallBonus = false; 275 continue; 276 } 277 if (IC2.isAlways()) 278 continue; 279 280 // See if inlining of the original callsite would erase the cost delta of 281 // this callsite. We subtract off the penalty for the call instruction, 282 // which we would be deleting. 283 if (IC2.getCostDelta() <= CandidateCost) { 284 InliningPreventsSomeOuterInline = true; 285 TotalSecondaryCost += IC2.getCost(); 286 NumCallerUsers++; 287 } 288 } 289 290 if (!InliningPreventsSomeOuterInline) 291 return false; 292 293 // If all outer calls to Caller would get inlined, the cost for the last 294 // one is set very low by getInlineCost, in anticipation that Caller will 295 // be removed entirely. We did not account for this above unless there 296 // is only one caller of Caller. 297 if (ApplyLastCallBonus) 298 TotalSecondaryCost -= InlineConstants::LastCallToStaticBonus; 299 300 // If InlineDeferralScale is negative, then ignore the cost of primary 301 // inlining -- IC.getCost() multiplied by the number of callers to Caller. 302 if (InlineDeferralScale < 0) 303 return TotalSecondaryCost < IC.getCost(); 304 305 int TotalCost = TotalSecondaryCost + IC.getCost() * NumCallerUsers; 306 int Allowance = IC.getCost() * InlineDeferralScale; 307 return TotalCost < Allowance; 308 } 309 310 namespace llvm { 311 static raw_ostream &operator<<(raw_ostream &R, const ore::NV &Arg) { 312 return R << Arg.Val; 313 } 314 315 template <class RemarkT> 316 RemarkT &operator<<(RemarkT &&R, const InlineCost &IC) { 317 using namespace ore; 318 if (IC.isAlways()) { 319 R << "(cost=always)"; 320 } else if (IC.isNever()) { 321 R << "(cost=never)"; 322 } else { 323 R << "(cost=" << ore::NV("Cost", IC.getCost()) 324 << ", threshold=" << ore::NV("Threshold", IC.getThreshold()) << ")"; 325 } 326 if (const char *Reason = IC.getReason()) 327 R << ": " << ore::NV("Reason", Reason); 328 return R; 329 } 330 } // namespace llvm 331 332 std::string llvm::inlineCostStr(const InlineCost &IC) { 333 std::string Buffer; 334 raw_string_ostream Remark(Buffer); 335 Remark << IC; 336 return Remark.str(); 337 } 338 339 void llvm::setInlineRemark(CallBase &CB, StringRef Message) { 340 if (!InlineRemarkAttribute) 341 return; 342 343 Attribute Attr = Attribute::get(CB.getContext(), "inline-remark", Message); 344 CB.addFnAttr(Attr); 345 } 346 347 /// Return the cost only if the inliner should attempt to inline at the given 348 /// CallSite. If we return the cost, we will emit an optimisation remark later 349 /// using that cost, so we won't do so from this function. Return None if 350 /// inlining should not be attempted. 351 Optional<InlineCost> 352 llvm::shouldInline(CallBase &CB, 353 function_ref<InlineCost(CallBase &CB)> GetInlineCost, 354 OptimizationRemarkEmitter &ORE, bool EnableDeferral) { 355 using namespace ore; 356 357 InlineCost IC = GetInlineCost(CB); 358 Instruction *Call = &CB; 359 Function *Callee = CB.getCalledFunction(); 360 Function *Caller = CB.getCaller(); 361 362 if (IC.isAlways()) { 363 LLVM_DEBUG(dbgs() << " Inlining " << inlineCostStr(IC) 364 << ", Call: " << CB << "\n"); 365 return IC; 366 } 367 368 if (!IC) { 369 LLVM_DEBUG(dbgs() << " NOT Inlining " << inlineCostStr(IC) 370 << ", Call: " << CB << "\n"); 371 if (IC.isNever()) { 372 ORE.emit([&]() { 373 return OptimizationRemarkMissed(DEBUG_TYPE, "NeverInline", Call) 374 << "'" << NV("Callee", Callee) << "' not inlined into '" 375 << NV("Caller", Caller) 376 << "' because it should never be inlined " << IC; 377 }); 378 } else { 379 ORE.emit([&]() { 380 return OptimizationRemarkMissed(DEBUG_TYPE, "TooCostly", Call) 381 << "'" << NV("Callee", Callee) << "' not inlined into '" 382 << NV("Caller", Caller) << "' because too costly to inline " 383 << IC; 384 }); 385 } 386 setInlineRemark(CB, inlineCostStr(IC)); 387 return None; 388 } 389 390 int TotalSecondaryCost = 0; 391 if (EnableDeferral && 392 shouldBeDeferred(Caller, IC, TotalSecondaryCost, GetInlineCost)) { 393 LLVM_DEBUG(dbgs() << " NOT Inlining: " << CB 394 << " Cost = " << IC.getCost() 395 << ", outer Cost = " << TotalSecondaryCost << '\n'); 396 ORE.emit([&]() { 397 return OptimizationRemarkMissed(DEBUG_TYPE, "IncreaseCostInOtherContexts", 398 Call) 399 << "Not inlining. Cost of inlining '" << NV("Callee", Callee) 400 << "' increases the cost of inlining '" << NV("Caller", Caller) 401 << "' in other contexts"; 402 }); 403 setInlineRemark(CB, "deferred"); 404 return None; 405 } 406 407 LLVM_DEBUG(dbgs() << " Inlining " << inlineCostStr(IC) << ", Call: " << CB 408 << '\n'); 409 return IC; 410 } 411 412 std::string llvm::formatCallSiteLocation(DebugLoc DLoc, 413 const CallSiteFormat &Format) { 414 std::string Buffer; 415 raw_string_ostream CallSiteLoc(Buffer); 416 bool First = true; 417 for (DILocation *DIL = DLoc.get(); DIL; DIL = DIL->getInlinedAt()) { 418 if (!First) 419 CallSiteLoc << " @ "; 420 // Note that negative line offset is actually possible, but we use 421 // unsigned int to match line offset representation in remarks so 422 // it's directly consumable by relay advisor. 423 uint32_t Offset = 424 DIL->getLine() - DIL->getScope()->getSubprogram()->getLine(); 425 uint32_t Discriminator = DIL->getBaseDiscriminator(); 426 StringRef Name = DIL->getScope()->getSubprogram()->getLinkageName(); 427 if (Name.empty()) 428 Name = DIL->getScope()->getSubprogram()->getName(); 429 CallSiteLoc << Name.str() << ":" << llvm::utostr(Offset); 430 if (Format.outputColumn()) 431 CallSiteLoc << ":" << llvm::utostr(DIL->getColumn()); 432 if (Format.outputDiscriminator() && Discriminator) 433 CallSiteLoc << "." << llvm::utostr(Discriminator); 434 First = false; 435 } 436 437 return CallSiteLoc.str(); 438 } 439 440 void llvm::addLocationToRemarks(OptimizationRemark &Remark, DebugLoc DLoc) { 441 if (!DLoc.get()) { 442 return; 443 } 444 445 bool First = true; 446 Remark << " at callsite "; 447 for (DILocation *DIL = DLoc.get(); DIL; DIL = DIL->getInlinedAt()) { 448 if (!First) 449 Remark << " @ "; 450 unsigned int Offset = DIL->getLine(); 451 Offset -= DIL->getScope()->getSubprogram()->getLine(); 452 unsigned int Discriminator = DIL->getBaseDiscriminator(); 453 StringRef Name = DIL->getScope()->getSubprogram()->getLinkageName(); 454 if (Name.empty()) 455 Name = DIL->getScope()->getSubprogram()->getName(); 456 Remark << Name << ":" << ore::NV("Line", Offset) << ":" 457 << ore::NV("Column", DIL->getColumn()); 458 if (Discriminator) 459 Remark << "." << ore::NV("Disc", Discriminator); 460 First = false; 461 } 462 463 Remark << ";"; 464 } 465 466 void llvm::emitInlinedInto( 467 OptimizationRemarkEmitter &ORE, DebugLoc DLoc, const BasicBlock *Block, 468 const Function &Callee, const Function &Caller, bool AlwaysInline, 469 function_ref<void(OptimizationRemark &)> ExtraContext, 470 const char *PassName) { 471 ORE.emit([&]() { 472 StringRef RemarkName = AlwaysInline ? "AlwaysInline" : "Inlined"; 473 OptimizationRemark Remark(PassName ? PassName : DEBUG_TYPE, RemarkName, 474 DLoc, Block); 475 Remark << "'" << ore::NV("Callee", &Callee) << "' inlined into '" 476 << ore::NV("Caller", &Caller) << "'"; 477 if (ExtraContext) 478 ExtraContext(Remark); 479 addLocationToRemarks(Remark, DLoc); 480 return Remark; 481 }); 482 } 483 484 void llvm::emitInlinedIntoBasedOnCost( 485 OptimizationRemarkEmitter &ORE, DebugLoc DLoc, const BasicBlock *Block, 486 const Function &Callee, const Function &Caller, const InlineCost &IC, 487 bool ForProfileContext, const char *PassName) { 488 llvm::emitInlinedInto( 489 ORE, DLoc, Block, Callee, Caller, IC.isAlways(), 490 [&](OptimizationRemark &Remark) { 491 if (ForProfileContext) 492 Remark << " to match profiling context"; 493 Remark << " with " << IC; 494 }, 495 PassName); 496 } 497 498 InlineAdvisor::InlineAdvisor(Module &M, FunctionAnalysisManager &FAM) 499 : M(M), FAM(FAM) { 500 if (InlinerFunctionImportStats != InlinerFunctionImportStatsOpts::No) { 501 ImportedFunctionsStats = 502 std::make_unique<ImportedFunctionsInliningStatistics>(); 503 ImportedFunctionsStats->setModuleInfo(M); 504 } 505 } 506 507 InlineAdvisor::~InlineAdvisor() { 508 if (ImportedFunctionsStats) { 509 assert(InlinerFunctionImportStats != InlinerFunctionImportStatsOpts::No); 510 ImportedFunctionsStats->dump(InlinerFunctionImportStats == 511 InlinerFunctionImportStatsOpts::Verbose); 512 } 513 } 514 515 std::unique_ptr<InlineAdvice> InlineAdvisor::getMandatoryAdvice(CallBase &CB, 516 bool Advice) { 517 return std::make_unique<MandatoryInlineAdvice>(this, CB, getCallerORE(CB), 518 Advice); 519 } 520 521 InlineAdvisor::MandatoryInliningKind 522 InlineAdvisor::getMandatoryKind(CallBase &CB, FunctionAnalysisManager &FAM, 523 OptimizationRemarkEmitter &ORE) { 524 auto &Callee = *CB.getCalledFunction(); 525 526 auto GetTLI = [&](Function &F) -> const TargetLibraryInfo & { 527 return FAM.getResult<TargetLibraryAnalysis>(F); 528 }; 529 530 auto &TIR = FAM.getResult<TargetIRAnalysis>(Callee); 531 532 auto TrivialDecision = 533 llvm::getAttributeBasedInliningDecision(CB, &Callee, TIR, GetTLI); 534 535 if (TrivialDecision.hasValue()) { 536 if (TrivialDecision->isSuccess()) 537 return MandatoryInliningKind::Always; 538 else 539 return MandatoryInliningKind::Never; 540 } 541 return MandatoryInliningKind::NotMandatory; 542 } 543 544 std::unique_ptr<InlineAdvice> InlineAdvisor::getAdvice(CallBase &CB, 545 bool MandatoryOnly) { 546 if (!MandatoryOnly) 547 return getAdviceImpl(CB); 548 bool Advice = CB.getCaller() != CB.getCalledFunction() && 549 MandatoryInliningKind::Always == 550 getMandatoryKind(CB, FAM, getCallerORE(CB)); 551 return getMandatoryAdvice(CB, Advice); 552 } 553 554 OptimizationRemarkEmitter &InlineAdvisor::getCallerORE(CallBase &CB) { 555 return FAM.getResult<OptimizationRemarkEmitterAnalysis>(*CB.getCaller()); 556 } 557