Add an early implementation of a partial inlining pass. The idea behind this
[oota-llvm.git] / lib / Transforms / IPO / PartialInlining.cpp
1 //===- 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
15 #define DEBUG_TYPE "partialinlining"
16 #include "llvm/Transforms/IPO.h"
17 #include "llvm/Instructions.h"
18 #include "llvm/Module.h"
19 #include "llvm/Pass.h"
20 #include "llvm/Analysis/Dominators.h"
21 #include "llvm/Transforms/Utils/Cloning.h"
22 #include "llvm/Transforms/Utils/FunctionUtils.h"
23 #include "llvm/Support/Compiler.h"
24 #include "llvm/Support/CFG.h"
25 using namespace llvm;
26
27 namespace {
28   struct VISIBILITY_HIDDEN PartialInliner : public ModulePass {
29     virtual void getAnalysisUsage(AnalysisUsage &AU) const { }
30     static char ID; // Pass identification, replacement for typeid
31     PartialInliner() : ModulePass(&ID) {}
32     
33     bool runOnModule(Module& M);
34     
35   private:
36     Function* unswitchFunction(Function* F);
37   };
38 }
39
40 char PartialInliner::ID = 0;
41 static RegisterPass<PartialInliner> X("partial-inliner", "Partial Inliner");
42
43 ModulePass* llvm::createPartialInliningPass() { return new PartialInliner(); }
44
45 Function* PartialInliner::unswitchFunction(Function* F) {
46   // First, verify that this function is an unswitching candidate...
47   BasicBlock* entryBlock = F->begin();
48   if (!isa<BranchInst>(entryBlock->getTerminator()))
49     return 0;
50   
51   BasicBlock* returnBlock = 0;
52   BasicBlock* nonReturnBlock = 0;
53   unsigned returnCount = 0;
54   for (succ_iterator SI = succ_begin(entryBlock), SE = succ_end(entryBlock);
55        SI != SE; ++SI)
56     if (isa<ReturnInst>((*SI)->getTerminator())) {
57       returnBlock = *SI;
58       returnCount++;
59     } else
60       nonReturnBlock = *SI;
61   
62   if (returnCount != 1)
63     return 0;
64   
65   // Clone the function, so that we can hack away on it.
66   DenseMap<const Value*, Value*> ValueMap;
67   Function* duplicateFunction = CloneFunction(F, ValueMap);
68   duplicateFunction->setLinkage(GlobalValue::InternalLinkage);
69   F->getParent()->getFunctionList().push_back(duplicateFunction);
70   BasicBlock* newEntryBlock = cast<BasicBlock>(ValueMap[entryBlock]);
71   BasicBlock* newReturnBlock = cast<BasicBlock>(ValueMap[returnBlock]);
72   BasicBlock* newNonReturnBlock = cast<BasicBlock>(ValueMap[nonReturnBlock]);
73   
74   // Go ahead and update all uses to the duplicate, so that we can just
75   // use the inliner functionality when we're done hacking.
76   F->replaceAllUsesWith(duplicateFunction);
77   
78   // Special hackery is needed with PHI nodes that have inputs from more than
79   // one extracted block.  For simplicity, just split the PHIs into a two-level
80   // sequence of PHIs, some of which will go in the extracted region, and some
81   // of which will go outside.
82   BasicBlock* preReturn = newReturnBlock;
83   newReturnBlock = newReturnBlock->splitBasicBlock(
84                                               newReturnBlock->getFirstNonPHI());
85   BasicBlock::iterator I = preReturn->begin();
86   BasicBlock::iterator Ins = newReturnBlock->begin();
87   while (I != preReturn->end()) {
88     PHINode* OldPhi = dyn_cast<PHINode>(I);
89     if (!OldPhi) break;
90     
91     PHINode* retPhi = PHINode::Create(OldPhi->getType(), "", Ins);
92     OldPhi->replaceAllUsesWith(retPhi);
93     Ins = newReturnBlock->getFirstNonPHI();
94     
95     retPhi->addIncoming(I, preReturn);
96     retPhi->addIncoming(OldPhi->getIncomingValueForBlock(newEntryBlock),
97                         newEntryBlock);
98     OldPhi->removeIncomingValue(newEntryBlock);
99     
100     ++I;
101   }
102   newEntryBlock->getTerminator()->replaceUsesOfWith(preReturn, newReturnBlock);
103   
104   // Gather up the blocks that we're going to extract.
105   std::vector<BasicBlock*> toExtract;
106   toExtract.push_back(newNonReturnBlock);
107   for (Function::iterator FI = duplicateFunction->begin(),
108        FE = duplicateFunction->end(); FI != FE; ++FI)
109     if (&*FI != newEntryBlock && &*FI != newReturnBlock &&
110         &*FI != newNonReturnBlock)
111       toExtract.push_back(FI);
112       
113   // The CodeExtractor needs a dominator tree.
114   DominatorTree DT;
115   DT.runOnFunction(*duplicateFunction);
116   
117   // Extract the body of the the if.
118   Function* extractedFunction = ExtractCodeRegion(DT, toExtract);
119   
120   // Inline the top-level if test into all callers.
121   std::vector<User*> Users(duplicateFunction->use_begin(), 
122                            duplicateFunction->use_end());
123   for (std::vector<User*>::iterator UI = Users.begin(), UE = Users.end();
124        UI != UE; ++UI)
125     if (CallInst* CI = dyn_cast<CallInst>(*UI))
126       InlineFunction(CI);
127     else if (InvokeInst* II = dyn_cast<InvokeInst>(*UI))
128       InlineFunction(II);
129   
130   // Ditch the duplicate, since we're done with it, and rewrite all remaining
131   // users (function pointers, etc.) back to the original function.
132   duplicateFunction->replaceAllUsesWith(F);
133   duplicateFunction->eraseFromParent();
134   
135   return extractedFunction;
136 }
137
138 bool PartialInliner::runOnModule(Module& M) {
139   std::vector<Function*> worklist;
140   worklist.reserve(M.size());
141   for (Module::iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI)
142     if (!FI->use_empty() && !FI->isDeclaration())
143     worklist.push_back(&*FI);
144     
145   bool changed = false;
146   while (!worklist.empty()) {
147     Function* currFunc = worklist.back();
148     worklist.pop_back();
149   
150     if (currFunc->use_empty()) continue;
151     
152     bool recursive = false;
153     for (Function::use_iterator UI = currFunc->use_begin(),
154          UE = currFunc->use_end(); UI != UE; ++UI)
155       if (Instruction* I = dyn_cast<Instruction>(UI))
156         if (I->getParent()->getParent() == currFunc) {
157           recursive = true;
158           break;
159         }
160     if (recursive) continue;
161           
162     
163     if (Function* newFunc = unswitchFunction(currFunc)) {
164       worklist.push_back(newFunc);
165       changed = true;
166     }
167     
168   }
169   
170   return changed;
171 }