InlineSimple.cpp revision 96c466b06ab0c830b07329c1b16037f585ccbe40
1//===- FunctionInlining.cpp - Code to perform function inlining -----------===//
2//
3// This file implements inlining of functions.
4//
5// Specifically, this:
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
10//
11// Notice that:
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.
15//
16// FIXME: This pass should transform alloca instructions in the called function
17//        into malloc/free pairs!
18//
19//===----------------------------------------------------------------------===//
20
21#include "llvm/Transforms/FunctionInlining.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"
30#include <algorithm>
31#include <map>
32#include <iostream>
33using std::cerr;
34
35// RemapInstruction - Convert the instruction operands from referencing the
36// current values into those specified by ValueMap.
37//
38static inline void RemapInstruction(Instruction *I,
39				    std::map<const Value *, Value*> &ValueMap) {
40
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
46
47    if (!V) {
48      cerr << "Val = \n" << Op << "Addr = " << (void*)Op;
49      cerr << "\nInst = " << I;
50    }
51    assert(V && "Referenced value not in value map!");
52    I->setOperand(op, V);
53  }
54}
55
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
59// occurs though.
60//
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.
65//
66bool InlineFunction(BasicBlock::iterator CIIt) {
67  assert(isa<CallInst>(*CIIt) && "InlineFunction only works on CallInst nodes");
68  assert((*CIIt)->getParent() && "Instruction not embedded in basic block!");
69  assert((*CIIt)->getParent()->getParent() && "Instruction not in function!");
70
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;
75
76  //cerr << "Inlining " << CalledMeth->getName() << " into "
77  //     << CurrentMeth->getName() << "\n";
78
79  BasicBlock *OrigBB = CI->getParent();
80
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.
84  //
85  BasicBlock *NewBB = OrigBB->splitBasicBlock(CIIt);
86  NewBB->setName("InlinedFunctionReturnNode");
87
88  // Remove (unlink) the CallInst from the start of the new basic block.
89  NewBB->getInstList().remove(CI);
90
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
93  // function.
94  //
95  PHINode *PHI = 0;
96  if (CalledMeth->getReturnType() != Type::VoidTy) {
97    PHI = new PHINode(CalledMeth->getReturnType(), CI->getName());
98
99    // The PHI node should go at the front of the new basic block to merge all
100    // possible incoming values.
101    //
102    NewBB->getInstList().push_front(PHI);
103
104    // Anything that used the result of the function call should now use the PHI
105    // node as their operand.
106    //
107    CI->replaceAllUsesWith(PHI);
108  }
109
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.
113  //
114  std::map<const Value *, Value*> ValueMap;
115
116  // Add the function arguments to the mapping: (start counting at 1 to skip the
117  // function reference itself)
118  //
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);
123
124  ValueMap[NewBB] = NewBB;  // Returns get converted to reference NewBB
125
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...
128  //
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!?!?");
133
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
137
138    ValueMap[BB] = IBB;                       // Add basic block mapping.
139
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!
143    //
144    const TerminatorInst *TI = BB->getTerminator();
145
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
154    }
155
156    // Copy over the terminator now...
157    switch (TI->getOpcode()) {
158    case Instruction::Ret: {
159      const ReturnInst *RI = cast<const ReturnInst>(TI);
160
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));
166      }
167
168      // Add a branch to the code that was after the original Call.
169      IBB->getInstList().push_back(new BranchInst(NewBB));
170      break;
171    }
172    case Instruction::Br:
173      IBB->getInstList().push_back(TI->clone());
174      break;
175
176    default:
177      cerr << "FunctionInlining: Don't know how to handle terminator: " << TI;
178      abort();
179    }
180  }
181
182
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.
185  //
186  for (Function::const_iterator BI = CalledMeth->begin();
187       BI != CalledMeth->end(); ++BI) {
188    const BasicBlock *BB = *BI;
189    BasicBlock *NBB = (BasicBlock*)ValueMap[BB];
190
191    // Loop over all instructions, fixing each one as we find it...
192    //
193    for (BasicBlock::iterator II = NBB->begin(); II != NBB->end(); II++)
194      RemapInstruction(*II, ValueMap);
195  }
196
197  if (PHI) RemapInstruction(PHI, ValueMap);  // Fix the PHI node also...
198
199  // Change the branch that used to go to NewBB to branch to the first basic
200  // block of the inlined function.
201  //
202  TerminatorInst *Br = OrigBB->getTerminator();
203  assert(Br && Br->getOpcode() == Instruction::Br &&
204	 "splitBasicBlock broken!");
205  Br->setOperand(0, ValueMap[CalledMeth->front()]);
206
207  // Since we are now done with the CallInst, we can finally delete it.
208  delete CI;
209  return true;
210}
211
212bool InlineFunction(CallInst *CI) {
213  assert(CI->getParent() && "CallInst not embeded in BasicBlock!");
214  BasicBlock *PBB = CI->getParent();
215
216  BasicBlock::iterator CallIt = find(PBB->begin(), PBB->end(), CI);
217
218  assert(CallIt != PBB->end() &&
219	 "CallInst has parent that doesn't contain CallInst?!?");
220  return InlineFunction(CallIt);
221}
222
223static inline bool ShouldInlineFunction(const CallInst *CI, const Function *F) {
224  assert(CI->getParent() && CI->getParent()->getParent() &&
225	 "Call not embedded into a function!");
226
227  // Don't inline a recursive call.
228  if (CI->getParent()->getParent() == F) return false;
229
230  // Don't inline something too big.  This is a really crappy heuristic
231  if (F->size() > 3) return false;
232
233  // Don't inline into something too big. This is a **really** crappy heuristic
234  if (CI->getParent()->getParent()->size() > 10) return false;
235
236  // Go ahead and try just about anything else.
237  return true;
238}
239
240
241static 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 InlineFunction(I);
248    }
249  }
250  return false;
251}
252
253// doFunctionInlining - Use a heuristic based approach to inline functions that
254// seem to look good.
255//
256static bool doFunctionInlining(Function *F) {
257  bool Changed = false;
258
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)) {
262      Changed = true;
263      // Iterator is now invalidated by new basic blocks inserted
264      I = F->begin();
265    } else {
266      ++I;
267    }
268
269  return Changed;
270}
271
272namespace {
273  struct FunctionInlining : public FunctionPass {
274    const char *getPassName() const { return "Function Inlining"; }
275    virtual bool runOnFunction(Function *F) {
276      return doFunctionInlining(F);
277    }
278  };
279}
280
281Pass *createFunctionInliningPass() { return new FunctionInlining(); }
282