1 //===- FunctionInlining.cpp - Code to perform function inlining -----------===//
3 // This file implements inlining of functions.
6 // * Exports functionality to inline any function call
7 // * Inlines functions that consist of a single basic block
8 // * Is able to inline ANY function call
9 // . Has a smart heuristic for when to inline a function
12 // * This pass opens up a lot of opportunities for constant propogation. It
13 // is a good idea to to run a constant propogation pass, then a DCE pass
14 // sometime after running this pass.
16 //===----------------------------------------------------------------------===//
18 #include "llvm/Transforms/MethodInlining.h"
19 #include "llvm/Module.h"
20 #include "llvm/Function.h"
21 #include "llvm/Pass.h"
22 #include "llvm/iTerminators.h"
23 #include "llvm/iPHINode.h"
24 #include "llvm/iOther.h"
30 #include "llvm/Assembly/Writer.h"
32 // RemapInstruction - Convert the instruction operands from referencing the
33 // current values into those specified by ValueMap.
35 static inline void RemapInstruction(Instruction *I,
36 std::map<const Value *, Value*> &ValueMap) {
38 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
39 const Value *Op = I->getOperand(op);
40 Value *V = ValueMap[Op];
41 if (!V && (isa<GlobalValue>(Op) || isa<Constant>(Op)))
42 continue; // Globals and constants don't get relocated
45 cerr << "Val = \n" << Op << "Addr = " << (void*)Op;
46 cerr << "\nInst = " << I;
48 assert(V && "Referenced value not in value map!");
53 // InlineMethod - This function forcibly inlines the called function into the
54 // basic block of the caller. This returns false if it is not possible to
55 // inline this call. The program is still in a well defined state if this
58 // Note that this only does one level of inlining. For example, if the
59 // instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now
60 // exists in the instruction stream. Similiarly this will inline a recursive
61 // function by one level.
63 bool InlineMethod(BasicBlock::iterator CIIt) {
64 assert(isa<CallInst>(*CIIt) && "InlineMethod only works on CallInst nodes!");
65 assert((*CIIt)->getParent() && "Instruction not embedded in basic block!");
66 assert((*CIIt)->getParent()->getParent() && "Instruction not in function!");
68 CallInst *CI = cast<CallInst>(*CIIt);
69 const Function *CalledMeth = CI->getCalledFunction();
70 if (CalledMeth == 0 || // Can't inline external function or indirect call!
71 CalledMeth->isExternal()) return false;
73 //cerr << "Inlining " << CalledMeth->getName() << " into "
74 // << CurrentMeth->getName() << "\n";
76 BasicBlock *OrigBB = CI->getParent();
78 // Call splitBasicBlock - The original basic block now ends at the instruction
79 // immediately before the call. The original basic block now ends with an
80 // unconditional branch to NewBB, and NewBB starts with the call instruction.
82 BasicBlock *NewBB = OrigBB->splitBasicBlock(CIIt);
83 NewBB->setName("InlinedFunctionReturnNode");
85 // Remove (unlink) the CallInst from the start of the new basic block.
86 NewBB->getInstList().remove(CI);
88 // If we have a return value generated by this call, convert it into a PHI
89 // node that gets values from each of the old RET instructions in the original
93 if (CalledMeth->getReturnType() != Type::VoidTy) {
94 PHI = new PHINode(CalledMeth->getReturnType(), CI->getName());
96 // The PHI node should go at the front of the new basic block to merge all
97 // possible incoming values.
99 NewBB->getInstList().push_front(PHI);
101 // Anything that used the result of the function call should now use the PHI
102 // node as their operand.
104 CI->replaceAllUsesWith(PHI);
107 // Keep a mapping between the original function's values and the new
108 // duplicated code's values. This includes all of: Function arguments,
109 // instruction values, constant pool entries, and basic blocks.
111 std::map<const Value *, Value*> ValueMap;
113 // Add the function arguments to the mapping: (start counting at 1 to skip the
114 // function reference itself)
116 Function::ArgumentListType::const_iterator PTI =
117 CalledMeth->getArgumentList().begin();
118 for (unsigned a = 1, E = CI->getNumOperands(); a != E; ++a, ++PTI)
119 ValueMap[*PTI] = CI->getOperand(a);
121 ValueMap[NewBB] = NewBB; // Returns get converted to reference NewBB
123 // Loop over all of the basic blocks in the function, inlining them as
124 // appropriate. Keep track of the first basic block of the function...
126 for (Function::const_iterator BI = CalledMeth->begin();
127 BI != CalledMeth->end(); ++BI) {
128 const BasicBlock *BB = *BI;
129 assert(BB->getTerminator() && "BasicBlock doesn't have terminator!?!?");
131 // Create a new basic block to copy instructions into!
132 BasicBlock *IBB = new BasicBlock("", NewBB->getParent());
133 if (BB->hasName()) IBB->setName(BB->getName()+".i"); // .i = inlined once
135 ValueMap[BB] = IBB; // Add basic block mapping.
137 // Make sure to capture the mapping that a return will use...
138 // TODO: This assumes that the RET is returning a value computed in the same
139 // basic block as the return was issued from!
141 const TerminatorInst *TI = BB->getTerminator();
143 // Loop over all instructions copying them over...
144 Instruction *NewInst;
145 for (BasicBlock::const_iterator II = BB->begin();
146 II != (BB->end()-1); ++II) {
147 IBB->getInstList().push_back((NewInst = (*II)->clone()));
148 ValueMap[*II] = NewInst; // Add instruction map to value.
149 if ((*II)->hasName())
150 NewInst->setName((*II)->getName()+".i"); // .i = inlined once
153 // Copy over the terminator now...
154 switch (TI->getOpcode()) {
155 case Instruction::Ret: {
156 const ReturnInst *RI = cast<const ReturnInst>(TI);
158 if (PHI) { // The PHI node should include this value!
159 assert(RI->getReturnValue() && "Ret should have value!");
160 assert(RI->getReturnValue()->getType() == PHI->getType() &&
161 "Ret value not consistent in function!");
162 PHI->addIncoming((Value*)RI->getReturnValue(), cast<BasicBlock>(BB));
165 // Add a branch to the code that was after the original Call.
166 IBB->getInstList().push_back(new BranchInst(NewBB));
169 case Instruction::Br:
170 IBB->getInstList().push_back(TI->clone());
174 cerr << "FunctionInlining: Don't know how to handle terminator: " << TI;
180 // Loop over all of the instructions in the function, fixing up operand
181 // references as we go. This uses ValueMap to do all the hard work.
183 for (Function::const_iterator BI = CalledMeth->begin();
184 BI != CalledMeth->end(); ++BI) {
185 const BasicBlock *BB = *BI;
186 BasicBlock *NBB = (BasicBlock*)ValueMap[BB];
188 // Loop over all instructions, fixing each one as we find it...
190 for (BasicBlock::iterator II = NBB->begin(); II != NBB->end(); II++)
191 RemapInstruction(*II, ValueMap);
194 if (PHI) RemapInstruction(PHI, ValueMap); // Fix the PHI node also...
196 // Change the branch that used to go to NewBB to branch to the first basic
197 // block of the inlined function.
199 TerminatorInst *Br = OrigBB->getTerminator();
200 assert(Br && Br->getOpcode() == Instruction::Br &&
201 "splitBasicBlock broken!");
202 Br->setOperand(0, ValueMap[CalledMeth->front()]);
204 // Since we are now done with the CallInst, we can finally delete it.
209 bool InlineMethod(CallInst *CI) {
210 assert(CI->getParent() && "CallInst not embeded in BasicBlock!");
211 BasicBlock *PBB = CI->getParent();
213 BasicBlock::iterator CallIt = find(PBB->begin(), PBB->end(), CI);
215 assert(CallIt != PBB->end() &&
216 "CallInst has parent that doesn't contain CallInst?!?");
217 return InlineMethod(CallIt);
220 static inline bool ShouldInlineFunction(const CallInst *CI, const Function *F) {
221 assert(CI->getParent() && CI->getParent()->getParent() &&
222 "Call not embedded into a method!");
224 // Don't inline a recursive call.
225 if (CI->getParent()->getParent() == F) return false;
227 // Don't inline something too big. This is a really crappy heuristic
228 if (F->size() > 3) return false;
230 // Don't inline into something too big. This is a **really** crappy heuristic
231 if (CI->getParent()->getParent()->size() > 10) return false;
233 // Go ahead and try just about anything else.
238 static inline bool DoFunctionInlining(BasicBlock *BB) {
239 for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
240 if (CallInst *CI = dyn_cast<CallInst>(*I)) {
241 // Check to see if we should inline this function
242 Function *F = CI->getCalledFunction();
243 if (F && ShouldInlineFunction(CI, F))
244 return InlineMethod(I);
250 // doFunctionInlining - Use a heuristic based approach to inline functions that
251 // seem to look good.
253 static bool doFunctionInlining(Function *F) {
254 bool Changed = false;
256 // Loop through now and inline instructions a basic block at a time...
257 for (Function::iterator I = F->begin(); I != F->end(); )
258 if (DoFunctionInlining(*I)) {
260 // Iterator is now invalidated by new basic blocks inserted
270 struct FunctionInlining : public MethodPass {
271 virtual bool runOnMethod(Function *F) {
272 return doFunctionInlining(F);
277 Pass *createMethodInliningPass() { return new FunctionInlining(); }