blob: 6a9a6a272da22acadb7beb3ca82ef8594ba9c399 [file] [log] [blame]
Owen Anderson2f82e272009-06-14 08:26:32 +00001//===- PartialInlining.cpp - Inline parts of functions --------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass performs partial inlining, typically by inlining an if statement
11// that surrounds the body of the function.
12//
13//===----------------------------------------------------------------------===//
14
Easwaran Raman1832bf62016-06-27 16:50:18 +000015#include "llvm/Transforms/IPO/PartialInlining.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "llvm/ADT/Statistic.h"
Sean Silvaf8015752016-08-02 02:15:45 +000017#include "llvm/Analysis/BlockFrequencyInfo.h"
18#include "llvm/Analysis/BranchProbabilityInfo.h"
19#include "llvm/Analysis/LoopInfo.h"
Xinliang David Li15744ad2017-04-23 21:40:58 +000020#include "llvm/Analysis/OptimizationDiagnosticInfo.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000021#include "llvm/IR/CFG.h"
Xinliang David Li15744ad2017-04-23 21:40:58 +000022#include "llvm/IR/DiagnosticInfo.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000023#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/Instructions.h"
25#include "llvm/IR/Module.h"
Owen Anderson2f82e272009-06-14 08:26:32 +000026#include "llvm/Pass.h"
Easwaran Raman1832bf62016-06-27 16:50:18 +000027#include "llvm/Transforms/IPO.h"
Owen Anderson2f82e272009-06-14 08:26:32 +000028#include "llvm/Transforms/Utils/Cloning.h"
Chandler Carruth0fde0012012-05-04 10:18:49 +000029#include "llvm/Transforms/Utils/CodeExtractor.h"
Owen Anderson2f82e272009-06-14 08:26:32 +000030using namespace llvm;
31
Xinliang David Li15744ad2017-04-23 21:40:58 +000032#define DEBUG_TYPE "partial-inlining"
Chandler Carruth964daaa2014-04-22 02:55:47 +000033
Owen Andersonbd6a2132009-06-15 20:50:26 +000034STATISTIC(NumPartialInlined, "Number of functions partially inlined");
35
Owen Anderson2f82e272009-06-14 08:26:32 +000036namespace {
Sean Silvafe5abd52016-07-25 05:00:00 +000037struct PartialInlinerImpl {
Benjamin Kramer061f4a52017-01-13 14:39:03 +000038 PartialInlinerImpl(InlineFunctionInfo IFI) : IFI(std::move(IFI)) {}
Sean Silvafe5abd52016-07-25 05:00:00 +000039 bool run(Module &M);
40 Function *unswitchFunction(Function *F);
41
42private:
43 InlineFunctionInfo IFI;
44};
Easwaran Raman1832bf62016-06-27 16:50:18 +000045struct PartialInlinerLegacyPass : public ModulePass {
46 static char ID; // Pass identification, replacement for typeid
47 PartialInlinerLegacyPass() : ModulePass(ID) {
48 initializePartialInlinerLegacyPassPass(*PassRegistry::getPassRegistry());
49 }
Craig Topper3e4c6972014-03-05 09:10:37 +000050
Daniel Jasperaec2fa32016-12-19 08:22:17 +000051 void getAnalysisUsage(AnalysisUsage &AU) const override {
52 AU.addRequired<AssumptionCacheTracker>();
53 }
Easwaran Raman1832bf62016-06-27 16:50:18 +000054 bool runOnModule(Module &M) override {
55 if (skipModule(M))
56 return false;
Craig Topper3e4c6972014-03-05 09:10:37 +000057
Daniel Jasperaec2fa32016-12-19 08:22:17 +000058 AssumptionCacheTracker *ACT = &getAnalysis<AssumptionCacheTracker>();
59 std::function<AssumptionCache &(Function &)> GetAssumptionCache =
60 [&ACT](Function &F) -> AssumptionCache & {
61 return ACT->getAssumptionCache(F);
62 };
63 InlineFunctionInfo IFI(nullptr, &GetAssumptionCache);
Sean Silva423c7142016-08-01 04:16:09 +000064 return PartialInlinerImpl(IFI).run(M);
Sean Silvafe5abd52016-07-25 05:00:00 +000065 }
Sean Silva519323d2016-07-25 05:57:59 +000066};
Alexander Kornienkof00654e2015-06-23 09:49:53 +000067}
Owen Anderson2f82e272009-06-14 08:26:32 +000068
Sean Silvafe5abd52016-07-25 05:00:00 +000069Function *PartialInlinerImpl::unswitchFunction(Function *F) {
Owen Anderson2f82e272009-06-14 08:26:32 +000070 // First, verify that this function is an unswitching candidate...
Xinliang David Li016a82b2017-04-22 19:24:19 +000071 if (F->hasAddressTaken())
72 return nullptr;
73
Sean Silva519323d2016-07-25 05:57:59 +000074 BasicBlock *EntryBlock = &F->front();
75 BranchInst *BR = dyn_cast<BranchInst>(EntryBlock->getTerminator());
Owen Andersonf0081db2009-09-08 19:53:15 +000076 if (!BR || BR->isUnconditional())
Craig Topperf40110f2014-04-25 05:29:35 +000077 return nullptr;
Sean Silvafe5abd52016-07-25 05:00:00 +000078
Sean Silva519323d2016-07-25 05:57:59 +000079 BasicBlock *ReturnBlock = nullptr;
80 BasicBlock *NonReturnBlock = nullptr;
81 unsigned ReturnCount = 0;
82 for (BasicBlock *BB : successors(EntryBlock)) {
Reid Klecknerc26a17a2015-02-04 19:14:57 +000083 if (isa<ReturnInst>(BB->getTerminator())) {
Sean Silva519323d2016-07-25 05:57:59 +000084 ReturnBlock = BB;
85 ReturnCount++;
Owen Anderson2f82e272009-06-14 08:26:32 +000086 } else
Sean Silva519323d2016-07-25 05:57:59 +000087 NonReturnBlock = BB;
Reid Klecknerc26a17a2015-02-04 19:14:57 +000088 }
Sean Silvafe5abd52016-07-25 05:00:00 +000089
Sean Silva519323d2016-07-25 05:57:59 +000090 if (ReturnCount != 1)
Craig Topperf40110f2014-04-25 05:29:35 +000091 return nullptr;
Sean Silvafe5abd52016-07-25 05:00:00 +000092
Owen Anderson2f82e272009-06-14 08:26:32 +000093 // Clone the function, so that we can hack away on it.
Rafael Espindola229e38f2010-10-13 01:36:30 +000094 ValueToValueMapTy VMap;
Sean Silva519323d2016-07-25 05:57:59 +000095 Function *DuplicateFunction = CloneFunction(F, VMap);
96 DuplicateFunction->setLinkage(GlobalValue::InternalLinkage);
97 BasicBlock *NewEntryBlock = cast<BasicBlock>(VMap[EntryBlock]);
98 BasicBlock *NewReturnBlock = cast<BasicBlock>(VMap[ReturnBlock]);
99 BasicBlock *NewNonReturnBlock = cast<BasicBlock>(VMap[NonReturnBlock]);
Sean Silvafe5abd52016-07-25 05:00:00 +0000100
Owen Anderson2f82e272009-06-14 08:26:32 +0000101 // Go ahead and update all uses to the duplicate, so that we can just
102 // use the inliner functionality when we're done hacking.
Sean Silva519323d2016-07-25 05:57:59 +0000103 F->replaceAllUsesWith(DuplicateFunction);
Sean Silvafe5abd52016-07-25 05:00:00 +0000104
Owen Anderson2f82e272009-06-14 08:26:32 +0000105 // Special hackery is needed with PHI nodes that have inputs from more than
106 // one extracted block. For simplicity, just split the PHIs into a two-level
107 // sequence of PHIs, some of which will go in the extracted region, and some
108 // of which will go outside.
Sean Silva519323d2016-07-25 05:57:59 +0000109 BasicBlock *PreReturn = NewReturnBlock;
110 NewReturnBlock = NewReturnBlock->splitBasicBlock(
111 NewReturnBlock->getFirstNonPHI()->getIterator());
112 BasicBlock::iterator I = PreReturn->begin();
113 Instruction *Ins = &NewReturnBlock->front();
114 while (I != PreReturn->end()) {
115 PHINode *OldPhi = dyn_cast<PHINode>(I);
116 if (!OldPhi)
117 break;
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000118
Sean Silva519323d2016-07-25 05:57:59 +0000119 PHINode *RetPhi = PHINode::Create(OldPhi->getType(), 2, "", Ins);
120 OldPhi->replaceAllUsesWith(RetPhi);
121 Ins = NewReturnBlock->getFirstNonPHI();
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000122
Sean Silva519323d2016-07-25 05:57:59 +0000123 RetPhi->addIncoming(&*I, PreReturn);
124 RetPhi->addIncoming(OldPhi->getIncomingValueForBlock(NewEntryBlock),
125 NewEntryBlock);
126 OldPhi->removeIncomingValue(NewEntryBlock);
Sean Silvafe5abd52016-07-25 05:00:00 +0000127
Owen Anderson2f82e272009-06-14 08:26:32 +0000128 ++I;
129 }
Sean Silva519323d2016-07-25 05:57:59 +0000130 NewEntryBlock->getTerminator()->replaceUsesOfWith(PreReturn, NewReturnBlock);
Sean Silvafe5abd52016-07-25 05:00:00 +0000131
Owen Anderson2f82e272009-06-14 08:26:32 +0000132 // Gather up the blocks that we're going to extract.
Sean Silva519323d2016-07-25 05:57:59 +0000133 std::vector<BasicBlock *> ToExtract;
134 ToExtract.push_back(NewNonReturnBlock);
135 for (BasicBlock &BB : *DuplicateFunction)
136 if (&BB != NewEntryBlock && &BB != NewReturnBlock &&
137 &BB != NewNonReturnBlock)
138 ToExtract.push_back(&BB);
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000139
Owen Anderson2f82e272009-06-14 08:26:32 +0000140 // The CodeExtractor needs a dominator tree.
141 DominatorTree DT;
Sean Silva519323d2016-07-25 05:57:59 +0000142 DT.recalculate(*DuplicateFunction);
Chandler Carruth73523022014-01-13 13:07:17 +0000143
Sean Silvaf8015752016-08-02 02:15:45 +0000144 // Manually calculate a BlockFrequencyInfo and BranchProbabilityInfo.
145 LoopInfo LI(DT);
146 BranchProbabilityInfo BPI(*DuplicateFunction, LI);
147 BlockFrequencyInfo BFI(*DuplicateFunction, BPI, LI);
148
Dan Gohman4a618822010-02-10 16:03:48 +0000149 // Extract the body of the if.
Sean Silva519323d2016-07-25 05:57:59 +0000150 Function *ExtractedFunction =
Sean Silvaf8015752016-08-02 02:15:45 +0000151 CodeExtractor(ToExtract, &DT, /*AggregateArgs*/ false, &BFI, &BPI)
152 .extractCodeRegion();
Sean Silvafe5abd52016-07-25 05:00:00 +0000153
Owen Anderson2f82e272009-06-14 08:26:32 +0000154 // Inline the top-level if test into all callers.
Sean Silva519323d2016-07-25 05:57:59 +0000155 std::vector<User *> Users(DuplicateFunction->user_begin(),
156 DuplicateFunction->user_end());
Xinliang David Li15744ad2017-04-23 21:40:58 +0000157
158 for (User *User : Users) {
159 CallSite CS;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000160 if (CallInst *CI = dyn_cast<CallInst>(User))
Xinliang David Li15744ad2017-04-23 21:40:58 +0000161 CS = CallSite(CI);
Benjamin Kramer135f7352016-06-26 12:28:59 +0000162 else if (InvokeInst *II = dyn_cast<InvokeInst>(User))
Xinliang David Li15744ad2017-04-23 21:40:58 +0000163 CS = CallSite(II);
164 else
165 llvm_unreachable("All uses must be calls");
166
167 OptimizationRemarkEmitter ORE(CS.getCaller());
168 DebugLoc DLoc = CS.getInstruction()->getDebugLoc();
169 BasicBlock *Block = CS.getParent();
170 ORE.emit(OptimizationRemark(DEBUG_TYPE, "PartiallyInlined", DLoc, Block)
171 << ore::NV("Callee", F) << " partially inlined into "
172 << ore::NV("Caller", CS.getCaller()));
173
174 InlineFunction(CS, IFI);
175 }
Sean Silvafe5abd52016-07-25 05:00:00 +0000176
Owen Anderson2f82e272009-06-14 08:26:32 +0000177 // Ditch the duplicate, since we're done with it, and rewrite all remaining
178 // users (function pointers, etc.) back to the original function.
Sean Silva519323d2016-07-25 05:57:59 +0000179 DuplicateFunction->replaceAllUsesWith(F);
180 DuplicateFunction->eraseFromParent();
Sean Silvafe5abd52016-07-25 05:00:00 +0000181
Owen Andersonbd6a2132009-06-15 20:50:26 +0000182 ++NumPartialInlined;
Sean Silvafe5abd52016-07-25 05:00:00 +0000183
Sean Silva519323d2016-07-25 05:57:59 +0000184 return ExtractedFunction;
Owen Anderson2f82e272009-06-14 08:26:32 +0000185}
186
Sean Silvafe5abd52016-07-25 05:00:00 +0000187bool PartialInlinerImpl::run(Module &M) {
Sean Silva519323d2016-07-25 05:57:59 +0000188 std::vector<Function *> Worklist;
189 Worklist.reserve(M.size());
Benjamin Kramer135f7352016-06-26 12:28:59 +0000190 for (Function &F : M)
191 if (!F.use_empty() && !F.isDeclaration())
Sean Silva519323d2016-07-25 05:57:59 +0000192 Worklist.push_back(&F);
Benjamin Kramer135f7352016-06-26 12:28:59 +0000193
Sean Silva519323d2016-07-25 05:57:59 +0000194 bool Changed = false;
195 while (!Worklist.empty()) {
196 Function *CurrFunc = Worklist.back();
197 Worklist.pop_back();
Sean Silvafe5abd52016-07-25 05:00:00 +0000198
Sean Silva519323d2016-07-25 05:57:59 +0000199 if (CurrFunc->use_empty())
200 continue;
Sean Silvafe5abd52016-07-25 05:00:00 +0000201
Sean Silva519323d2016-07-25 05:57:59 +0000202 bool Recursive = false;
203 for (User *U : CurrFunc->users())
204 if (Instruction *I = dyn_cast<Instruction>(U))
205 if (I->getParent()->getParent() == CurrFunc) {
206 Recursive = true;
Owen Anderson2f82e272009-06-14 08:26:32 +0000207 break;
208 }
Sean Silva519323d2016-07-25 05:57:59 +0000209 if (Recursive)
210 continue;
Sean Silvafe5abd52016-07-25 05:00:00 +0000211
Sean Silvaf8015752016-08-02 02:15:45 +0000212 if (Function *NewFunc = unswitchFunction(CurrFunc)) {
213 Worklist.push_back(NewFunc);
Sean Silva519323d2016-07-25 05:57:59 +0000214 Changed = true;
Owen Anderson2f82e272009-06-14 08:26:32 +0000215 }
Owen Anderson2f82e272009-06-14 08:26:32 +0000216 }
Easwaran Raman1832bf62016-06-27 16:50:18 +0000217
Sean Silva519323d2016-07-25 05:57:59 +0000218 return Changed;
Sean Silvafe5abd52016-07-25 05:00:00 +0000219}
220
221char PartialInlinerLegacyPass::ID = 0;
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000222INITIALIZE_PASS_BEGIN(PartialInlinerLegacyPass, "partial-inliner",
223 "Partial Inliner", false, false)
224INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
225INITIALIZE_PASS_END(PartialInlinerLegacyPass, "partial-inliner",
226 "Partial Inliner", false, false)
Sean Silvafe5abd52016-07-25 05:00:00 +0000227
228ModulePass *llvm::createPartialInliningPass() {
229 return new PartialInlinerLegacyPass();
230}
231
232PreservedAnalyses PartialInlinerPass::run(Module &M,
233 ModuleAnalysisManager &AM) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000234 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
235 std::function<AssumptionCache &(Function &)> GetAssumptionCache =
236 [&FAM](Function &F) -> AssumptionCache & {
237 return FAM.getResult<AssumptionAnalysis>(F);
238 };
239 InlineFunctionInfo IFI(nullptr, &GetAssumptionCache);
Sean Silva423c7142016-08-01 04:16:09 +0000240 if (PartialInlinerImpl(IFI).run(M))
Easwaran Raman1832bf62016-06-27 16:50:18 +0000241 return PreservedAnalyses::none();
242 return PreservedAnalyses::all();
Duncan Sands29c8efc2009-07-03 15:30:58 +0000243}