1 //===- MethodInlining.cpp - Code to perform method inlining ---------------===//
3 // This file implements inlining of methods.
6 // * Exports functionality to inline any method call
7 // * Inlines methods that consist of a single basic block
8 // * Is able to inline ANY method call
9 // . Has a smart heuristic for when to inline a method
12 // * This pass has a habit of introducing duplicated constant pool entries,
13 // and also opens up a lot of opportunities for constant propogation. It is
14 // a good idea to to run a constant propogation pass, then a DCE pass
15 // sometime after running this pass.
17 // TODO: Currently this throws away all of the symbol names in the method being
18 // inlined to try to avoid name clashes. Use a name if it's not taken
20 //===----------------------------------------------------------------------===//
22 #include "llvm/Optimizations/MethodInlining.h"
23 #include "llvm/Module.h"
24 #include "llvm/Method.h"
25 #include "llvm/iTerminators.h"
26 #include "llvm/iOther.h"
30 #include "llvm/Assembly/Writer.h"
34 // RemapInstruction - Convert the instruction operands from referencing the
35 // current values into those specified by ValueMap.
37 static inline void RemapInstruction(Instruction *I,
38 map<const Value *, Value*> &ValueMap) {
40 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
41 const Value *Op = I->getOperand(op);
42 Value *V = ValueMap[Op];
43 if (!V && Op->isMethod())
44 continue; // Methods don't get relocated
47 cerr << "Val = " << endl << Op << "Addr = " << (void*)Op << endl;
48 cerr << "Inst = " << I;
50 assert(V && "Referenced value not in value map!");
55 // InlineMethod - This function forcibly inlines the called method into the
56 // basic block of the caller. This returns false if it is not possible to
57 // inline this call. The program is still in a well defined state if this
60 // Note that this only does one level of inlining. For example, if the
61 // instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now
62 // exists in the instruction stream. Similiarly this will inline a recursive
63 // method by one level.
65 bool opt::InlineMethod(BasicBlock::iterator CIIt) {
66 assert((*CIIt)->getInstType() == Instruction::Call &&
67 "InlineMethod only works on CallInst nodes!");
68 assert((*CIIt)->getParent() && "Instruction not embedded in basic block!");
69 assert((*CIIt)->getParent()->getParent() && "Instruction not in method!");
71 CallInst *CI = (CallInst*)*CIIt;
72 const Method *CalledMeth = CI->getCalledMethod();
73 Method *CurrentMeth = CI->getParent()->getParent();
75 //cerr << "Inlining " << CalledMeth->getName() << " into "
76 // << CurrentMeth->getName() << endl;
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(CIIt);
86 // Remove (unlink) the CallInst from the start of the new basic block.
87 NewBB->getInstList().remove(CI);
89 // If we have a return value generated by this call, convert it into a PHI
90 // node that gets values from each of the old RET instructions in the original
94 if (CalledMeth->getReturnType() != Type::VoidTy) {
95 PHI = new PHINode(CalledMeth->getReturnType(), CI->getName());
97 // The PHI node should go at the front of the new basic block to merge all
98 // possible incoming values.
100 NewBB->getInstList().push_front(PHI);
102 // Anything that used the result of the function call should now use the PHI
103 // node as their operand.
105 CI->replaceAllUsesWith(PHI);
108 // Keep a mapping between the original method's values and the new duplicated
109 // code's values. This includes all of: Method arguments, instruction values,
110 // constant pool entries, and basic blocks.
112 map<const Value *, Value*> ValueMap;
114 // Add the method arguments to the mapping: (start counting at 1 to skip the
115 // method reference itself)
117 Method::ArgumentListType::const_iterator PTI =
118 CalledMeth->getArgumentList().begin();
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 method, inlining them as
125 // appropriate. Keep track of the first basic block of the method...
127 for (Method::const_iterator BI = CalledMeth->begin();
128 BI != CalledMeth->end(); ++BI) {
129 const BasicBlock *BB = *BI;
130 assert(BB->getTerminator() && "BasicBlock doesn't have terminator!?!?");
132 // Create a new basic block to copy instructions into!
133 BasicBlock *IBB = new BasicBlock("", NewBB->getParent());
135 ValueMap[*BI] = 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.
151 // Copy over the terminator now...
152 switch (TI->getInstType()) {
153 case Instruction::Ret: {
154 const ReturnInst *RI = (const ReturnInst*)TI;
156 if (PHI) { // The PHI node should include this value!
157 assert(RI->getReturnValue() && "Ret should have value!");
158 assert(RI->getReturnValue()->getType() == PHI->getType() &&
159 "Ret value not consistent in method!");
160 PHI->addIncoming((Value*)RI->getReturnValue(), (BasicBlock*)BB);
163 // Add a branch to the code that was after the original Call.
164 IBB->getInstList().push_back(new BranchInst(NewBB));
167 case Instruction::Br:
168 IBB->getInstList().push_back(TI->clone());
172 cerr << "MethodInlining: Don't know how to handle terminator: " << TI;
178 // Copy over the constant pool...
180 const ConstantPool &CP = CalledMeth->getConstantPool();
181 ConstantPool &NewCP = CurrentMeth->getConstantPool();
182 for (ConstantPool::plane_const_iterator PI = CP.begin(); PI != CP.end(); ++PI){
183 ConstantPool::PlaneType &Plane = **PI;
184 for (ConstantPool::PlaneType::const_iterator I = Plane.begin();
185 I != Plane.end(); ++I) {
186 ConstPoolVal *NewVal = (*I)->clone(); // Copy existing constant
187 NewCP.insert(NewVal); // Insert the new copy into local const pool
188 ValueMap[*I] = NewVal; // Keep track of constant value mappings
192 // Loop over all of the instructions in the method, fixing up operand
193 // references as we go. This uses ValueMap to do all the hard work.
195 for (Method::const_iterator BI = CalledMeth->begin();
196 BI != CalledMeth->end(); ++BI) {
197 const BasicBlock *BB = *BI;
198 BasicBlock *NBB = (BasicBlock*)ValueMap[BB];
200 // Loop over all instructions, fixing each one as we find it...
202 for (BasicBlock::iterator II = NBB->begin(); II != NBB->end(); II++)
203 RemapInstruction(*II, ValueMap);
206 if (PHI) RemapInstruction(PHI, ValueMap); // Fix the PHI node also...
208 // Change the branch that used to go to NewBB to branch to the first basic
209 // block of the inlined method.
211 TerminatorInst *Br = OrigBB->getTerminator();
212 assert(Br && Br->getInstType() == Instruction::Br &&
213 "splitBasicBlock broken!");
214 Br->setOperand(0, ValueMap[CalledMeth->front()]);
216 // Since we are now done with the CallInst, we can finally delete it.
221 bool opt::InlineMethod(CallInst *CI) {
222 assert(CI->getParent() && "CallInst not embeded in BasicBlock!");
223 BasicBlock *PBB = CI->getParent();
225 BasicBlock::iterator CallIt = find(PBB->begin(), PBB->end(), CI);
227 assert(CallIt != PBB->end() &&
228 "CallInst has parent that doesn't contain CallInst?!?");
229 return InlineMethod(CallIt);
232 static inline bool ShouldInlineMethod(const CallInst *CI, const Method *M) {
233 assert(CI->getParent() && CI->getParent()->getParent() &&
234 "Call not embedded into a method!");
236 // Don't inline a recursive call.
237 if (CI->getParent()->getParent() == M) return false;
239 // Don't inline something too big. This is a really crappy heuristic
240 if (M->size() > 3) return false;
242 // Don't inline into something too big. This is a **really** crappy heuristic
243 if (CI->getParent()->getParent()->size() > 10) return false;
245 // Go ahead and try just about anything else.
250 static inline bool DoMethodInlining(BasicBlock *BB) {
251 for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
252 if ((*I)->getInstType() == Instruction::Call) {
253 // Check to see if we should inline this method
254 CallInst *CI = (CallInst*)*I;
255 Method *M = CI->getCalledMethod();
256 if (ShouldInlineMethod(CI, M))
257 return InlineMethod(I);
263 bool opt::DoMethodInlining(Method *M) {
264 bool Changed = false;
266 // Loop through now and inline instructions a basic block at a time...
267 for (Method::iterator I = M->begin(); I != M->end(); )
268 if (DoMethodInlining(*I)) {
270 // Iterator is now invalidated by new basic blocks inserted