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 // FIXME: This pass should transform alloca instructions in the called function
17 // into malloc/free pairs!
19 //===----------------------------------------------------------------------===//
21 #include "llvm/Transforms/MethodInlining.h"
22 #include "llvm/Module.h"
23 #include "llvm/Function.h"
24 #include "llvm/Pass.h"
25 #include "llvm/iTerminators.h"
26 #include "llvm/iPHINode.h"
27 #include "llvm/iOther.h"
28 #include "llvm/Type.h"
29 #include "llvm/Argument.h"
35 // RemapInstruction - Convert the instruction operands from referencing the
36 // current values into those specified by ValueMap.
38 static inline void RemapInstruction(Instruction *I,
39 std::map<const Value *, Value*> &ValueMap) {
41 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
42 const Value *Op = I->getOperand(op);
43 Value *V = ValueMap[Op];
44 if (!V && (isa<GlobalValue>(Op) || isa<Constant>(Op)))
45 continue; // Globals and constants don't get relocated
48 cerr << "Val = \n" << Op << "Addr = " << (void*)Op;
49 cerr << "\nInst = " << I;
51 assert(V && "Referenced value not in value map!");
56 // InlineMethod - This function forcibly inlines the called function into the
57 // basic block of the caller. This returns false if it is not possible to
58 // inline this call. The program is still in a well defined state if this
61 // Note that this only does one level of inlining. For example, if the
62 // instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now
63 // exists in the instruction stream. Similiarly this will inline a recursive
64 // function by one level.
66 bool InlineMethod(BasicBlock::iterator CIIt) {
67 assert(isa<CallInst>(*CIIt) && "InlineMethod only works on CallInst nodes!");
68 assert((*CIIt)->getParent() && "Instruction not embedded in basic block!");
69 assert((*CIIt)->getParent()->getParent() && "Instruction not in function!");
71 CallInst *CI = cast<CallInst>(*CIIt);
72 const Function *CalledMeth = CI->getCalledFunction();
73 if (CalledMeth == 0 || // Can't inline external function or indirect call!
74 CalledMeth->isExternal()) return false;
76 //cerr << "Inlining " << CalledMeth->getName() << " into "
77 // << CurrentMeth->getName() << "\n";
79 BasicBlock *OrigBB = CI->getParent();
81 // Call splitBasicBlock - The original basic block now ends at the instruction
82 // immediately before the call. The original basic block now ends with an
83 // unconditional branch to NewBB, and NewBB starts with the call instruction.
85 BasicBlock *NewBB = OrigBB->splitBasicBlock(CIIt);
86 NewBB->setName("InlinedFunctionReturnNode");
88 // Remove (unlink) the CallInst from the start of the new basic block.
89 NewBB->getInstList().remove(CI);
91 // If we have a return value generated by this call, convert it into a PHI
92 // node that gets values from each of the old RET instructions in the original
96 if (CalledMeth->getReturnType() != Type::VoidTy) {
97 PHI = new PHINode(CalledMeth->getReturnType(), CI->getName());
99 // The PHI node should go at the front of the new basic block to merge all
100 // possible incoming values.
102 NewBB->getInstList().push_front(PHI);
104 // Anything that used the result of the function call should now use the PHI
105 // node as their operand.
107 CI->replaceAllUsesWith(PHI);
110 // Keep a mapping between the original function's values and the new
111 // duplicated code's values. This includes all of: Function arguments,
112 // instruction values, constant pool entries, and basic blocks.
114 std::map<const Value *, Value*> ValueMap;
116 // Add the function arguments to the mapping: (start counting at 1 to skip the
117 // function reference itself)
119 Function::ArgumentListType::const_iterator PTI =
120 CalledMeth->getArgumentList().begin();
121 for (unsigned a = 1, E = CI->getNumOperands(); a != E; ++a, ++PTI)
122 ValueMap[*PTI] = CI->getOperand(a);
124 ValueMap[NewBB] = NewBB; // Returns get converted to reference NewBB
126 // Loop over all of the basic blocks in the function, inlining them as
127 // appropriate. Keep track of the first basic block of the function...
129 for (Function::const_iterator BI = CalledMeth->begin();
130 BI != CalledMeth->end(); ++BI) {
131 const BasicBlock *BB = *BI;
132 assert(BB->getTerminator() && "BasicBlock doesn't have terminator!?!?");
134 // Create a new basic block to copy instructions into!
135 BasicBlock *IBB = new BasicBlock("", NewBB->getParent());
136 if (BB->hasName()) IBB->setName(BB->getName()+".i"); // .i = inlined once
138 ValueMap[BB] = IBB; // Add basic block mapping.
140 // Make sure to capture the mapping that a return will use...
141 // TODO: This assumes that the RET is returning a value computed in the same
142 // basic block as the return was issued from!
144 const TerminatorInst *TI = BB->getTerminator();
146 // Loop over all instructions copying them over...
147 Instruction *NewInst;
148 for (BasicBlock::const_iterator II = BB->begin();
149 II != (BB->end()-1); ++II) {
150 IBB->getInstList().push_back((NewInst = (*II)->clone()));
151 ValueMap[*II] = NewInst; // Add instruction map to value.
152 if ((*II)->hasName())
153 NewInst->setName((*II)->getName()+".i"); // .i = inlined once
156 // Copy over the terminator now...
157 switch (TI->getOpcode()) {
158 case Instruction::Ret: {
159 const ReturnInst *RI = cast<const ReturnInst>(TI);
161 if (PHI) { // The PHI node should include this value!
162 assert(RI->getReturnValue() && "Ret should have value!");
163 assert(RI->getReturnValue()->getType() == PHI->getType() &&
164 "Ret value not consistent in function!");
165 PHI->addIncoming((Value*)RI->getReturnValue(), cast<BasicBlock>(BB));
168 // Add a branch to the code that was after the original Call.
169 IBB->getInstList().push_back(new BranchInst(NewBB));
172 case Instruction::Br:
173 IBB->getInstList().push_back(TI->clone());
177 cerr << "FunctionInlining: Don't know how to handle terminator: " << TI;
183 // Loop over all of the instructions in the function, fixing up operand
184 // references as we go. This uses ValueMap to do all the hard work.
186 for (Function::const_iterator BI = CalledMeth->begin();
187 BI != CalledMeth->end(); ++BI) {
188 const BasicBlock *BB = *BI;
189 BasicBlock *NBB = (BasicBlock*)ValueMap[BB];
191 // Loop over all instructions, fixing each one as we find it...
193 for (BasicBlock::iterator II = NBB->begin(); II != NBB->end(); II++)
194 RemapInstruction(*II, ValueMap);
197 if (PHI) RemapInstruction(PHI, ValueMap); // Fix the PHI node also...
199 // Change the branch that used to go to NewBB to branch to the first basic
200 // block of the inlined function.
202 TerminatorInst *Br = OrigBB->getTerminator();
203 assert(Br && Br->getOpcode() == Instruction::Br &&
204 "splitBasicBlock broken!");
205 Br->setOperand(0, ValueMap[CalledMeth->front()]);
207 // Since we are now done with the CallInst, we can finally delete it.
212 bool InlineMethod(CallInst *CI) {
213 assert(CI->getParent() && "CallInst not embeded in BasicBlock!");
214 BasicBlock *PBB = CI->getParent();
216 BasicBlock::iterator CallIt = find(PBB->begin(), PBB->end(), CI);
218 assert(CallIt != PBB->end() &&
219 "CallInst has parent that doesn't contain CallInst?!?");
220 return InlineMethod(CallIt);
223 static inline bool ShouldInlineFunction(const CallInst *CI, const Function *F) {
224 assert(CI->getParent() && CI->getParent()->getParent() &&
225 "Call not embedded into a method!");
227 // Don't inline a recursive call.
228 if (CI->getParent()->getParent() == F) return false;
230 // Don't inline something too big. This is a really crappy heuristic
231 if (F->size() > 3) return false;
233 // Don't inline into something too big. This is a **really** crappy heuristic
234 if (CI->getParent()->getParent()->size() > 10) return false;
236 // Go ahead and try just about anything else.
241 static inline bool DoFunctionInlining(BasicBlock *BB) {
242 for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
243 if (CallInst *CI = dyn_cast<CallInst>(*I)) {
244 // Check to see if we should inline this function
245 Function *F = CI->getCalledFunction();
246 if (F && ShouldInlineFunction(CI, F))
247 return InlineMethod(I);
253 // doFunctionInlining - Use a heuristic based approach to inline functions that
254 // seem to look good.
256 static bool doFunctionInlining(Function *F) {
257 bool Changed = false;
259 // Loop through now and inline instructions a basic block at a time...
260 for (Function::iterator I = F->begin(); I != F->end(); )
261 if (DoFunctionInlining(*I)) {
263 // Iterator is now invalidated by new basic blocks inserted
273 struct FunctionInlining : public MethodPass {
274 virtual bool runOnMethod(Function *F) {
275 return doFunctionInlining(F);
280 Pass *createMethodInliningPass() { return new FunctionInlining(); }