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/FunctionInlining.h"
22 #include "llvm/Module.h"
23 #include "llvm/Pass.h"
24 #include "llvm/iTerminators.h"
25 #include "llvm/iPHINode.h"
26 #include "llvm/iOther.h"
27 #include "llvm/Type.h"
28 #include "Support/StatisticReporter.h"
32 static Statistic<> NumInlined("inline\t\t- Number of functions inlined");
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 // InlineFunction - 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 InlineFunction(CallInst *CI) {
67 assert(isa<CallInst>(CI) && "InlineFunction only works on CallInst nodes");
68 assert(CI->getParent() && "Instruction not embedded in basic block!");
69 assert(CI->getParent()->getParent() && "Instruction not in function!");
71 const Function *CalledFunc = CI->getCalledFunction();
72 if (CalledFunc == 0 || // Can't inline external function or indirect call!
73 CalledFunc->isExternal()) return false;
75 //cerr << "Inlining " << CalledFunc->getName() << " into "
76 // << CurrentMeth->getName() << "\n";
78 BasicBlock *OrigBB = CI->getParent();
80 // Call splitBasicBlock - The original basic block now ends at the instruction
81 // immediately before the call. The original basic block now ends with an
82 // unconditional branch to NewBB, and NewBB starts with the call instruction.
84 BasicBlock *NewBB = OrigBB->splitBasicBlock(CI);
85 NewBB->setName("InlinedFunctionReturnNode");
87 // Remove (unlink) the CallInst from the start of the new basic block.
88 NewBB->getInstList().remove(CI);
90 // If we have a return value generated by this call, convert it into a PHI
91 // node that gets values from each of the old RET instructions in the original
95 if (CalledFunc->getReturnType() != Type::VoidTy) {
96 PHI = new PHINode(CalledFunc->getReturnType(), CI->getName());
98 // The PHI node should go at the front of the new basic block to merge all
99 // possible incoming values.
101 NewBB->getInstList().push_front(PHI);
103 // Anything that used the result of the function call should now use the PHI
104 // node as their operand.
106 CI->replaceAllUsesWith(PHI);
109 // Keep a mapping between the original function's values and the new
110 // duplicated code's values. This includes all of: Function arguments,
111 // instruction values, constant pool entries, and basic blocks.
113 std::map<const Value *, Value*> ValueMap;
115 // Add the function arguments to the mapping: (start counting at 1 to skip the
116 // function reference itself)
118 Function::const_aiterator PTI = CalledFunc->abegin();
119 for (unsigned a = 1, E = CI->getNumOperands(); a != E; ++a, ++PTI)
120 ValueMap[PTI] = CI->getOperand(a);
122 ValueMap[NewBB] = NewBB; // Returns get converted to reference NewBB
124 // Loop over all of the basic blocks in the function, inlining them as
125 // appropriate. Keep track of the first basic block of the function...
127 for (Function::const_iterator BB = CalledFunc->begin();
128 BB != CalledFunc->end(); ++BB) {
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(); ++II) {
147 IBB->getInstList().push_back((NewInst = II->clone()));
148 ValueMap[II] = NewInst; // Add instruction map to value.
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<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(),
163 (BasicBlock*)cast<BasicBlock>(&*BB));
166 // Add a branch to the code that was after the original Call.
167 IBB->getInstList().push_back(new BranchInst(NewBB));
170 case Instruction::Br:
171 IBB->getInstList().push_back(TI->clone());
175 cerr << "FunctionInlining: Don't know how to handle terminator: " << TI;
181 // Loop over all of the instructions in the function, fixing up operand
182 // references as we go. This uses ValueMap to do all the hard work.
184 for (Function::const_iterator BB = CalledFunc->begin();
185 BB != CalledFunc->end(); ++BB) {
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[&CalledFunc->front()]);
204 // Since we are now done with the CallInst, we can finally delete it.
209 static inline bool ShouldInlineFunction(const CallInst *CI, const Function *F) {
210 assert(CI->getParent() && CI->getParent()->getParent() &&
211 "Call not embedded into a function!");
213 // Don't inline a recursive call.
214 if (CI->getParent()->getParent() == F) return false;
216 // Don't inline something too big. This is a really crappy heuristic
217 if (F->size() > 3) return false;
219 // Don't inline into something too big. This is a **really** crappy heuristic
220 if (CI->getParent()->getParent()->size() > 10) return false;
222 // Go ahead and try just about anything else.
227 static inline bool DoFunctionInlining(BasicBlock *BB) {
228 for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
229 if (CallInst *CI = dyn_cast<CallInst>(&*I)) {
230 // Check to see if we should inline this function
231 Function *F = CI->getCalledFunction();
232 if (F && ShouldInlineFunction(CI, F)) {
233 return InlineFunction(CI);
240 // doFunctionInlining - Use a heuristic based approach to inline functions that
241 // seem to look good.
243 static bool doFunctionInlining(Function &F) {
244 bool Changed = false;
246 // Loop through now and inline instructions a basic block at a time...
247 for (Function::iterator I = F.begin(); I != F.end(); )
248 if (DoFunctionInlining(I)) {
259 struct FunctionInlining : public FunctionPass {
260 virtual bool runOnFunction(Function &F) {
261 return doFunctionInlining(F);
264 RegisterPass<FunctionInlining> X("inline", "Function Integration/Inlining");
267 Pass *createFunctionInliningPass() { return new FunctionInlining(); }