AlwaysInliner.cpp 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. //===- InlineAlways.cpp - Code to inline always_inline functions ----------===//
  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 a custom inliner that handles only functions that
  10. // are marked as "always inline".
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/Transforms/IPO/AlwaysInliner.h"
  14. #include "llvm/ADT/SetVector.h"
  15. #include "llvm/Analysis/AliasAnalysis.h"
  16. #include "llvm/Analysis/AssumptionCache.h"
  17. #include "llvm/Analysis/InlineCost.h"
  18. #include "llvm/Analysis/ProfileSummaryInfo.h"
  19. #include "llvm/Analysis/TargetLibraryInfo.h"
  20. #include "llvm/IR/CallingConv.h"
  21. #include "llvm/IR/DataLayout.h"
  22. #include "llvm/IR/Instructions.h"
  23. #include "llvm/IR/Module.h"
  24. #include "llvm/IR/Type.h"
  25. #include "llvm/InitializePasses.h"
  26. #include "llvm/Transforms/IPO.h"
  27. #include "llvm/Transforms/IPO/Inliner.h"
  28. #include "llvm/Transforms/Utils/Cloning.h"
  29. #include "llvm/Transforms/Utils/ModuleUtils.h"
  30. using namespace llvm;
  31. #define DEBUG_TYPE "inline"
  32. PreservedAnalyses AlwaysInlinerPass::run(Module &M,
  33. ModuleAnalysisManager &MAM) {
  34. // Add inline assumptions during code generation.
  35. FunctionAnalysisManager &FAM =
  36. MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
  37. auto GetAssumptionCache = [&](Function &F) -> AssumptionCache & {
  38. return FAM.getResult<AssumptionAnalysis>(F);
  39. };
  40. auto &PSI = MAM.getResult<ProfileSummaryAnalysis>(M);
  41. SmallSetVector<CallBase *, 16> Calls;
  42. bool Changed = false;
  43. SmallVector<Function *, 16> InlinedFunctions;
  44. for (Function &F : M) {
  45. // When callee coroutine function is inlined into caller coroutine function
  46. // before coro-split pass,
  47. // coro-early pass can not handle this quiet well.
  48. // So we won't inline the coroutine function if it have not been unsplited
  49. if (F.isPresplitCoroutine())
  50. continue;
  51. if (!F.isDeclaration() && F.hasFnAttribute(Attribute::AlwaysInline) &&
  52. isInlineViable(F).isSuccess()) {
  53. Calls.clear();
  54. for (User *U : F.users())
  55. if (auto *CB = dyn_cast<CallBase>(U))
  56. if (CB->getCalledFunction() == &F)
  57. Calls.insert(CB);
  58. for (CallBase *CB : Calls) {
  59. Function *Caller = CB->getCaller();
  60. OptimizationRemarkEmitter ORE(Caller);
  61. auto OIC = shouldInline(
  62. *CB,
  63. [&](CallBase &CB) {
  64. return InlineCost::getAlways("always inline attribute");
  65. },
  66. ORE);
  67. assert(OIC);
  68. emitInlinedInto(ORE, CB->getDebugLoc(), CB->getParent(), F, *Caller,
  69. *OIC, false, DEBUG_TYPE);
  70. InlineFunctionInfo IFI(
  71. /*cg=*/nullptr, GetAssumptionCache, &PSI,
  72. &FAM.getResult<BlockFrequencyAnalysis>(*(CB->getCaller())),
  73. &FAM.getResult<BlockFrequencyAnalysis>(F));
  74. InlineResult Res = InlineFunction(
  75. *CB, IFI, &FAM.getResult<AAManager>(F), InsertLifetime);
  76. assert(Res.isSuccess() && "unexpected failure to inline");
  77. (void)Res;
  78. // Merge the attributes based on the inlining.
  79. AttributeFuncs::mergeAttributesForInlining(*Caller, F);
  80. Changed = true;
  81. }
  82. // Remember to try and delete this function afterward. This both avoids
  83. // re-walking the rest of the module and avoids dealing with any iterator
  84. // invalidation issues while deleting functions.
  85. InlinedFunctions.push_back(&F);
  86. }
  87. }
  88. // Remove any live functions.
  89. erase_if(InlinedFunctions, [&](Function *F) {
  90. F->removeDeadConstantUsers();
  91. return !F->isDefTriviallyDead();
  92. });
  93. // Delete the non-comdat ones from the module and also from our vector.
  94. auto NonComdatBegin = partition(
  95. InlinedFunctions, [&](Function *F) { return F->hasComdat(); });
  96. for (Function *F : make_range(NonComdatBegin, InlinedFunctions.end()))
  97. M.getFunctionList().erase(F);
  98. InlinedFunctions.erase(NonComdatBegin, InlinedFunctions.end());
  99. if (!InlinedFunctions.empty()) {
  100. // Now we just have the comdat functions. Filter out the ones whose comdats
  101. // are not actually dead.
  102. filterDeadComdatFunctions(M, InlinedFunctions);
  103. // The remaining functions are actually dead.
  104. for (Function *F : InlinedFunctions)
  105. M.getFunctionList().erase(F);
  106. }
  107. return Changed ? PreservedAnalyses::none() : PreservedAnalyses::all();
  108. }
  109. namespace {
  110. /// Inliner pass which only handles "always inline" functions.
  111. ///
  112. /// Unlike the \c AlwaysInlinerPass, this uses the more heavyweight \c Inliner
  113. /// base class to provide several facilities such as array alloca merging.
  114. class AlwaysInlinerLegacyPass : public LegacyInlinerBase {
  115. public:
  116. AlwaysInlinerLegacyPass() : LegacyInlinerBase(ID, /*InsertLifetime*/ true) {
  117. initializeAlwaysInlinerLegacyPassPass(*PassRegistry::getPassRegistry());
  118. }
  119. AlwaysInlinerLegacyPass(bool InsertLifetime)
  120. : LegacyInlinerBase(ID, InsertLifetime) {
  121. initializeAlwaysInlinerLegacyPassPass(*PassRegistry::getPassRegistry());
  122. }
  123. /// Main run interface method. We override here to avoid calling skipSCC().
  124. bool runOnSCC(CallGraphSCC &SCC) override { return inlineCalls(SCC); }
  125. static char ID; // Pass identification, replacement for typeid
  126. InlineCost getInlineCost(CallBase &CB) override;
  127. using llvm::Pass::doFinalization;
  128. bool doFinalization(CallGraph &CG) override {
  129. return removeDeadFunctions(CG, /*AlwaysInlineOnly=*/true);
  130. }
  131. };
  132. }
  133. char AlwaysInlinerLegacyPass::ID = 0;
  134. INITIALIZE_PASS_BEGIN(AlwaysInlinerLegacyPass, "always-inline",
  135. "Inliner for always_inline functions", false, false)
  136. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  137. INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
  138. INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
  139. INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
  140. INITIALIZE_PASS_END(AlwaysInlinerLegacyPass, "always-inline",
  141. "Inliner for always_inline functions", false, false)
  142. Pass *llvm::createAlwaysInlinerLegacyPass(bool InsertLifetime) {
  143. return new AlwaysInlinerLegacyPass(InsertLifetime);
  144. }
  145. /// Get the inline cost for the always-inliner.
  146. ///
  147. /// The always inliner *only* handles functions which are marked with the
  148. /// attribute to force inlining. As such, it is dramatically simpler and avoids
  149. /// using the powerful (but expensive) inline cost analysis. Instead it uses
  150. /// a very simple and boring direct walk of the instructions looking for
  151. /// impossible-to-inline constructs.
  152. ///
  153. /// Note, it would be possible to go to some lengths to cache the information
  154. /// computed here, but as we only expect to do this for relatively few and
  155. /// small functions which have the explicit attribute to force inlining, it is
  156. /// likely not worth it in practice.
  157. InlineCost AlwaysInlinerLegacyPass::getInlineCost(CallBase &CB) {
  158. Function *Callee = CB.getCalledFunction();
  159. // Only inline direct calls to functions with always-inline attributes
  160. // that are viable for inlining.
  161. if (!Callee)
  162. return InlineCost::getNever("indirect call");
  163. // When callee coroutine function is inlined into caller coroutine function
  164. // before coro-split pass,
  165. // coro-early pass can not handle this quiet well.
  166. // So we won't inline the coroutine function if it have not been unsplited
  167. if (Callee->isPresplitCoroutine())
  168. return InlineCost::getNever("unsplited coroutine call");
  169. // FIXME: We shouldn't even get here for declarations.
  170. if (Callee->isDeclaration())
  171. return InlineCost::getNever("no definition");
  172. if (!CB.hasFnAttr(Attribute::AlwaysInline))
  173. return InlineCost::getNever("no alwaysinline attribute");
  174. auto IsViable = isInlineViable(*Callee);
  175. if (!IsViable.isSuccess())
  176. return InlineCost::getNever(IsViable.getFailureReason());
  177. return InlineCost::getAlways("always inliner");
  178. }