1c0981da4SDimitry Andric //===- ModuleInliner.cpp - Code related to module inliner -----------------===//
2c0981da4SDimitry Andric //
3c0981da4SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4c0981da4SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5c0981da4SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6c0981da4SDimitry Andric //
7c0981da4SDimitry Andric //===----------------------------------------------------------------------===//
8c0981da4SDimitry Andric //
9c0981da4SDimitry Andric // This file implements the mechanics required to implement inlining without
10c0981da4SDimitry Andric // missing any calls in the module level. It doesn't need any infromation about
11c0981da4SDimitry Andric // SCC or call graph, which is different from the SCC inliner. The decisions of
12c0981da4SDimitry Andric // which calls are profitable to inline are implemented elsewhere.
13c0981da4SDimitry Andric //
14c0981da4SDimitry Andric //===----------------------------------------------------------------------===//
15c0981da4SDimitry Andric
16c0981da4SDimitry Andric #include "llvm/Transforms/IPO/ModuleInliner.h"
17c0981da4SDimitry Andric #include "llvm/ADT/ScopeExit.h"
18c0981da4SDimitry Andric #include "llvm/ADT/SmallVector.h"
19c0981da4SDimitry Andric #include "llvm/ADT/Statistic.h"
20145449b1SDimitry Andric #include "llvm/Analysis/AliasAnalysis.h"
21c0981da4SDimitry Andric #include "llvm/Analysis/AssumptionCache.h"
22c0981da4SDimitry Andric #include "llvm/Analysis/BlockFrequencyInfo.h"
23c0981da4SDimitry Andric #include "llvm/Analysis/InlineAdvisor.h"
24c0981da4SDimitry Andric #include "llvm/Analysis/InlineCost.h"
25c0981da4SDimitry Andric #include "llvm/Analysis/InlineOrder.h"
26c0981da4SDimitry Andric #include "llvm/Analysis/OptimizationRemarkEmitter.h"
27c0981da4SDimitry Andric #include "llvm/Analysis/ProfileSummaryInfo.h"
28145449b1SDimitry Andric #include "llvm/Analysis/ReplayInlineAdvisor.h"
29c0981da4SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
30c0981da4SDimitry Andric #include "llvm/IR/DiagnosticInfo.h"
31c0981da4SDimitry Andric #include "llvm/IR/Function.h"
32c0981da4SDimitry Andric #include "llvm/IR/InstIterator.h"
33c0981da4SDimitry Andric #include "llvm/IR/Instruction.h"
34c0981da4SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
35c0981da4SDimitry Andric #include "llvm/IR/Module.h"
36c0981da4SDimitry Andric #include "llvm/IR/PassManager.h"
37c0981da4SDimitry Andric #include "llvm/Support/CommandLine.h"
38c0981da4SDimitry Andric #include "llvm/Support/Debug.h"
39c0981da4SDimitry Andric #include "llvm/Support/raw_ostream.h"
40c0981da4SDimitry Andric #include "llvm/Transforms/Utils/CallPromotionUtils.h"
41c0981da4SDimitry Andric #include "llvm/Transforms/Utils/Cloning.h"
42c0981da4SDimitry Andric #include <cassert>
43c0981da4SDimitry Andric
44c0981da4SDimitry Andric using namespace llvm;
45c0981da4SDimitry Andric
46c0981da4SDimitry Andric #define DEBUG_TYPE "module-inline"
47c0981da4SDimitry Andric
48c0981da4SDimitry Andric STATISTIC(NumInlined, "Number of functions inlined");
49c0981da4SDimitry Andric STATISTIC(NumDeleted, "Number of functions deleted because all callers found");
50c0981da4SDimitry Andric
51c0981da4SDimitry Andric /// Return true if the specified inline history ID
52c0981da4SDimitry Andric /// indicates an inline history that includes the specified function.
inlineHistoryIncludes(Function * F,int InlineHistoryID,const SmallVectorImpl<std::pair<Function *,int>> & InlineHistory)53c0981da4SDimitry Andric static bool inlineHistoryIncludes(
54c0981da4SDimitry Andric Function *F, int InlineHistoryID,
55c0981da4SDimitry Andric const SmallVectorImpl<std::pair<Function *, int>> &InlineHistory) {
56c0981da4SDimitry Andric while (InlineHistoryID != -1) {
57c0981da4SDimitry Andric assert(unsigned(InlineHistoryID) < InlineHistory.size() &&
58c0981da4SDimitry Andric "Invalid inline history ID");
59c0981da4SDimitry Andric if (InlineHistory[InlineHistoryID].first == F)
60c0981da4SDimitry Andric return true;
61c0981da4SDimitry Andric InlineHistoryID = InlineHistory[InlineHistoryID].second;
62c0981da4SDimitry Andric }
63c0981da4SDimitry Andric return false;
64c0981da4SDimitry Andric }
65c0981da4SDimitry Andric
getAdvisor(const ModuleAnalysisManager & MAM,FunctionAnalysisManager & FAM,Module & M)66c0981da4SDimitry Andric InlineAdvisor &ModuleInlinerPass::getAdvisor(const ModuleAnalysisManager &MAM,
67c0981da4SDimitry Andric FunctionAnalysisManager &FAM,
68c0981da4SDimitry Andric Module &M) {
69c0981da4SDimitry Andric if (OwnedAdvisor)
70c0981da4SDimitry Andric return *OwnedAdvisor;
71c0981da4SDimitry Andric
72c0981da4SDimitry Andric auto *IAA = MAM.getCachedResult<InlineAdvisorAnalysis>(M);
73c0981da4SDimitry Andric if (!IAA) {
74c0981da4SDimitry Andric // It should still be possible to run the inliner as a stand-alone module
75c0981da4SDimitry Andric // pass, for test scenarios. In that case, we default to the
76c0981da4SDimitry Andric // DefaultInlineAdvisor, which doesn't need to keep state between module
77c0981da4SDimitry Andric // pass runs. It also uses just the default InlineParams. In this case, we
78c0981da4SDimitry Andric // need to use the provided FAM, which is valid for the duration of the
79c0981da4SDimitry Andric // inliner pass, and thus the lifetime of the owned advisor. The one we
80c0981da4SDimitry Andric // would get from the MAM can be invalidated as a result of the inliner's
81c0981da4SDimitry Andric // activity.
82145449b1SDimitry Andric OwnedAdvisor = std::make_unique<DefaultInlineAdvisor>(
83e3b55780SDimitry Andric M, FAM, Params, InlineContext{LTOPhase, InlinePass::ModuleInliner});
84c0981da4SDimitry Andric
85c0981da4SDimitry Andric return *OwnedAdvisor;
86c0981da4SDimitry Andric }
87c0981da4SDimitry Andric assert(IAA->getAdvisor() &&
88c0981da4SDimitry Andric "Expected a present InlineAdvisorAnalysis also have an "
89c0981da4SDimitry Andric "InlineAdvisor initialized");
90c0981da4SDimitry Andric return *IAA->getAdvisor();
91c0981da4SDimitry Andric }
92c0981da4SDimitry Andric
isKnownLibFunction(Function & F,TargetLibraryInfo & TLI)93c0981da4SDimitry Andric static bool isKnownLibFunction(Function &F, TargetLibraryInfo &TLI) {
94c0981da4SDimitry Andric LibFunc LF;
95c0981da4SDimitry Andric
96c0981da4SDimitry Andric // Either this is a normal library function or a "vectorizable"
97c0981da4SDimitry Andric // function. Not using the VFDatabase here because this query
98c0981da4SDimitry Andric // is related only to libraries handled via the TLI.
99c0981da4SDimitry Andric return TLI.getLibFunc(F, LF) ||
100c0981da4SDimitry Andric TLI.isKnownVectorFunctionInLibrary(F.getName());
101c0981da4SDimitry Andric }
102c0981da4SDimitry Andric
run(Module & M,ModuleAnalysisManager & MAM)103c0981da4SDimitry Andric PreservedAnalyses ModuleInlinerPass::run(Module &M,
104c0981da4SDimitry Andric ModuleAnalysisManager &MAM) {
105c0981da4SDimitry Andric LLVM_DEBUG(dbgs() << "---- Module Inliner is Running ---- \n");
106c0981da4SDimitry Andric
107c0981da4SDimitry Andric auto &IAA = MAM.getResult<InlineAdvisorAnalysis>(M);
108e3b55780SDimitry Andric if (!IAA.tryCreate(Params, Mode, {},
109145449b1SDimitry Andric InlineContext{LTOPhase, InlinePass::ModuleInliner})) {
110c0981da4SDimitry Andric M.getContext().emitError(
111c0981da4SDimitry Andric "Could not setup Inlining Advisor for the requested "
112c0981da4SDimitry Andric "mode and/or options");
113c0981da4SDimitry Andric return PreservedAnalyses::all();
114c0981da4SDimitry Andric }
115c0981da4SDimitry Andric
116c0981da4SDimitry Andric bool Changed = false;
117c0981da4SDimitry Andric
118c0981da4SDimitry Andric ProfileSummaryInfo *PSI = MAM.getCachedResult<ProfileSummaryAnalysis>(M);
119c0981da4SDimitry Andric
120c0981da4SDimitry Andric FunctionAnalysisManager &FAM =
121c0981da4SDimitry Andric MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
122c0981da4SDimitry Andric
123c0981da4SDimitry Andric auto GetTLI = [&FAM](Function &F) -> TargetLibraryInfo & {
124c0981da4SDimitry Andric return FAM.getResult<TargetLibraryAnalysis>(F);
125c0981da4SDimitry Andric };
126c0981da4SDimitry Andric
127c0981da4SDimitry Andric InlineAdvisor &Advisor = getAdvisor(MAM, FAM, M);
128c0981da4SDimitry Andric Advisor.onPassEntry();
129c0981da4SDimitry Andric
130c0981da4SDimitry Andric auto AdvisorOnExit = make_scope_exit([&] { Advisor.onPassExit(); });
131c0981da4SDimitry Andric
132c0981da4SDimitry Andric // In the module inliner, a priority-based worklist is used for calls across
133c0981da4SDimitry Andric // the entire Module. With this module inliner, the inline order is not
134c0981da4SDimitry Andric // limited to bottom-up order. More globally scope inline order is enabled.
135c0981da4SDimitry Andric // Also, the inline deferral logic become unnecessary in this module inliner.
136c0981da4SDimitry Andric // It is possible to use other priority heuristics, e.g. profile-based
137c0981da4SDimitry Andric // heuristic.
138c0981da4SDimitry Andric //
139c0981da4SDimitry Andric // TODO: Here is a huge amount duplicate code between the module inliner and
140c0981da4SDimitry Andric // the SCC inliner, which need some refactoring.
1417fa27ce4SDimitry Andric auto Calls = getInlineOrder(FAM, Params, MAM, M);
142c0981da4SDimitry Andric assert(Calls != nullptr && "Expected an initialized InlineOrder");
143c0981da4SDimitry Andric
144c0981da4SDimitry Andric // Populate the initial list of calls in this module.
145c0981da4SDimitry Andric for (Function &F : M) {
146c0981da4SDimitry Andric auto &ORE = FAM.getResult<OptimizationRemarkEmitterAnalysis>(F);
147c0981da4SDimitry Andric for (Instruction &I : instructions(F))
148c0981da4SDimitry Andric if (auto *CB = dyn_cast<CallBase>(&I))
149c0981da4SDimitry Andric if (Function *Callee = CB->getCalledFunction()) {
150c0981da4SDimitry Andric if (!Callee->isDeclaration())
151c0981da4SDimitry Andric Calls->push({CB, -1});
152c0981da4SDimitry Andric else if (!isa<IntrinsicInst>(I)) {
153c0981da4SDimitry Andric using namespace ore;
154c0981da4SDimitry Andric setInlineRemark(*CB, "unavailable definition");
155c0981da4SDimitry Andric ORE.emit([&]() {
156c0981da4SDimitry Andric return OptimizationRemarkMissed(DEBUG_TYPE, "NoDefinition", &I)
157c0981da4SDimitry Andric << NV("Callee", Callee) << " will not be inlined into "
158c0981da4SDimitry Andric << NV("Caller", CB->getCaller())
159c0981da4SDimitry Andric << " because its definition is unavailable"
160c0981da4SDimitry Andric << setIsVerbose();
161c0981da4SDimitry Andric });
162c0981da4SDimitry Andric }
163c0981da4SDimitry Andric }
164c0981da4SDimitry Andric }
165c0981da4SDimitry Andric if (Calls->empty())
166c0981da4SDimitry Andric return PreservedAnalyses::all();
167c0981da4SDimitry Andric
168c0981da4SDimitry Andric // When inlining a callee produces new call sites, we want to keep track of
169c0981da4SDimitry Andric // the fact that they were inlined from the callee. This allows us to avoid
170c0981da4SDimitry Andric // infinite inlining in some obscure cases. To represent this, we use an
171c0981da4SDimitry Andric // index into the InlineHistory vector.
172c0981da4SDimitry Andric SmallVector<std::pair<Function *, int>, 16> InlineHistory;
173c0981da4SDimitry Andric
174c0981da4SDimitry Andric // Track the dead functions to delete once finished with inlining calls. We
175c0981da4SDimitry Andric // defer deleting these to make it easier to handle the call graph updates.
176c0981da4SDimitry Andric SmallVector<Function *, 4> DeadFunctions;
177c0981da4SDimitry Andric
178c0981da4SDimitry Andric // Loop forward over all of the calls.
179c0981da4SDimitry Andric while (!Calls->empty()) {
180e3b55780SDimitry Andric auto P = Calls->pop();
181e3b55780SDimitry Andric CallBase *CB = P.first;
182e3b55780SDimitry Andric const int InlineHistoryID = P.second;
183e3b55780SDimitry Andric Function &F = *CB->getCaller();
184e3b55780SDimitry Andric Function &Callee = *CB->getCalledFunction();
185c0981da4SDimitry Andric
186c0981da4SDimitry Andric LLVM_DEBUG(dbgs() << "Inlining calls in: " << F.getName() << "\n"
187c0981da4SDimitry Andric << " Function size: " << F.getInstructionCount()
188c0981da4SDimitry Andric << "\n");
189e3b55780SDimitry Andric (void)F;
190c0981da4SDimitry Andric
191c0981da4SDimitry Andric auto GetAssumptionCache = [&](Function &F) -> AssumptionCache & {
192c0981da4SDimitry Andric return FAM.getResult<AssumptionAnalysis>(F);
193c0981da4SDimitry Andric };
194c0981da4SDimitry Andric
195c0981da4SDimitry Andric if (InlineHistoryID != -1 &&
196c0981da4SDimitry Andric inlineHistoryIncludes(&Callee, InlineHistoryID, InlineHistory)) {
197c0981da4SDimitry Andric setInlineRemark(*CB, "recursive");
198c0981da4SDimitry Andric continue;
199c0981da4SDimitry Andric }
200c0981da4SDimitry Andric
201c0981da4SDimitry Andric auto Advice = Advisor.getAdvice(*CB, /*OnlyMandatory*/ false);
202c0981da4SDimitry Andric // Check whether we want to inline this callsite.
203c0981da4SDimitry Andric if (!Advice->isInliningRecommended()) {
204c0981da4SDimitry Andric Advice->recordUnattemptedInlining();
205c0981da4SDimitry Andric continue;
206c0981da4SDimitry Andric }
207c0981da4SDimitry Andric
208c0981da4SDimitry Andric // Setup the data structure used to plumb customization into the
209c0981da4SDimitry Andric // `InlineFunction` routine.
210c0981da4SDimitry Andric InlineFunctionInfo IFI(
2117fa27ce4SDimitry Andric GetAssumptionCache, PSI,
212c0981da4SDimitry Andric &FAM.getResult<BlockFrequencyAnalysis>(*(CB->getCaller())),
213c0981da4SDimitry Andric &FAM.getResult<BlockFrequencyAnalysis>(Callee));
214c0981da4SDimitry Andric
215c0981da4SDimitry Andric InlineResult IR =
216e3b55780SDimitry Andric InlineFunction(*CB, IFI, /*MergeAttributes=*/true,
217e3b55780SDimitry Andric &FAM.getResult<AAManager>(*CB->getCaller()));
218c0981da4SDimitry Andric if (!IR.isSuccess()) {
219c0981da4SDimitry Andric Advice->recordUnsuccessfulInlining(IR);
220c0981da4SDimitry Andric continue;
221c0981da4SDimitry Andric }
222c0981da4SDimitry Andric
223e3b55780SDimitry Andric Changed = true;
224c0981da4SDimitry Andric ++NumInlined;
225c0981da4SDimitry Andric
226e3b55780SDimitry Andric LLVM_DEBUG(dbgs() << " Size after inlining: " << F.getInstructionCount()
227e3b55780SDimitry Andric << "\n");
228c0981da4SDimitry Andric
229c0981da4SDimitry Andric // Add any new callsites to defined functions to the worklist.
230c0981da4SDimitry Andric if (!IFI.InlinedCallSites.empty()) {
231c0981da4SDimitry Andric int NewHistoryID = InlineHistory.size();
232c0981da4SDimitry Andric InlineHistory.push_back({&Callee, InlineHistoryID});
233c0981da4SDimitry Andric
234c0981da4SDimitry Andric for (CallBase *ICB : reverse(IFI.InlinedCallSites)) {
235c0981da4SDimitry Andric Function *NewCallee = ICB->getCalledFunction();
236c0981da4SDimitry Andric if (!NewCallee) {
237c0981da4SDimitry Andric // Try to promote an indirect (virtual) call without waiting for
238c0981da4SDimitry Andric // the post-inline cleanup and the next DevirtSCCRepeatedPass
239c0981da4SDimitry Andric // iteration because the next iteration may not happen and we may
240c0981da4SDimitry Andric // miss inlining it.
241c0981da4SDimitry Andric if (tryPromoteCall(*ICB))
242c0981da4SDimitry Andric NewCallee = ICB->getCalledFunction();
243c0981da4SDimitry Andric }
244c0981da4SDimitry Andric if (NewCallee)
245c0981da4SDimitry Andric if (!NewCallee->isDeclaration())
246c0981da4SDimitry Andric Calls->push({ICB, NewHistoryID});
247c0981da4SDimitry Andric }
248c0981da4SDimitry Andric }
249c0981da4SDimitry Andric
250c0981da4SDimitry Andric // For local functions, check whether this makes the callee trivially
251c0981da4SDimitry Andric // dead. In that case, we can drop the body of the function eagerly
252c0981da4SDimitry Andric // which may reduce the number of callers of other functions to one,
253c0981da4SDimitry Andric // changing inline cost thresholds.
254c0981da4SDimitry Andric bool CalleeWasDeleted = false;
255c0981da4SDimitry Andric if (Callee.hasLocalLinkage()) {
256c0981da4SDimitry Andric // To check this we also need to nuke any dead constant uses (perhaps
257c0981da4SDimitry Andric // made dead by this operation on other functions).
258c0981da4SDimitry Andric Callee.removeDeadConstantUsers();
259c0981da4SDimitry Andric // if (Callee.use_empty() && !CG.isLibFunction(Callee)) {
260c0981da4SDimitry Andric if (Callee.use_empty() && !isKnownLibFunction(Callee, GetTLI(Callee))) {
261c0981da4SDimitry Andric Calls->erase_if([&](const std::pair<CallBase *, int> &Call) {
262c0981da4SDimitry Andric return Call.first->getCaller() == &Callee;
263c0981da4SDimitry Andric });
264c0981da4SDimitry Andric // Clear the body and queue the function itself for deletion when we
265c0981da4SDimitry Andric // finish inlining.
266c0981da4SDimitry Andric // Note that after this point, it is an error to do anything other
267c0981da4SDimitry Andric // than use the callee's address or delete it.
268c0981da4SDimitry Andric Callee.dropAllReferences();
269c0981da4SDimitry Andric assert(!is_contained(DeadFunctions, &Callee) &&
270c0981da4SDimitry Andric "Cannot put cause a function to become dead twice!");
271c0981da4SDimitry Andric DeadFunctions.push_back(&Callee);
272c0981da4SDimitry Andric CalleeWasDeleted = true;
273c0981da4SDimitry Andric }
274c0981da4SDimitry Andric }
275c0981da4SDimitry Andric if (CalleeWasDeleted)
276c0981da4SDimitry Andric Advice->recordInliningWithCalleeDeleted();
277c0981da4SDimitry Andric else
278c0981da4SDimitry Andric Advice->recordInlining();
279c0981da4SDimitry Andric }
280c0981da4SDimitry Andric
281c0981da4SDimitry Andric // Now that we've finished inlining all of the calls across this module,
282c0981da4SDimitry Andric // delete all of the trivially dead functions.
283c0981da4SDimitry Andric //
284c0981da4SDimitry Andric // Note that this walks a pointer set which has non-deterministic order but
285c0981da4SDimitry Andric // that is OK as all we do is delete things and add pointers to unordered
286c0981da4SDimitry Andric // sets.
287c0981da4SDimitry Andric for (Function *DeadF : DeadFunctions) {
288c0981da4SDimitry Andric // Clear out any cached analyses.
289c0981da4SDimitry Andric FAM.clear(*DeadF, DeadF->getName());
290c0981da4SDimitry Andric
291c0981da4SDimitry Andric // And delete the actual function from the module.
2926f8fc217SDimitry Andric M.getFunctionList().erase(DeadF);
293c0981da4SDimitry Andric
294c0981da4SDimitry Andric ++NumDeleted;
295c0981da4SDimitry Andric }
296c0981da4SDimitry Andric
297c0981da4SDimitry Andric if (!Changed)
298c0981da4SDimitry Andric return PreservedAnalyses::all();
299c0981da4SDimitry Andric
300c0981da4SDimitry Andric return PreservedAnalyses::none();
301c0981da4SDimitry Andric }
302