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