InlineSimple.cpp revision dbcbe3f7e8dad01a6d4ad8460992b9139e4861ba
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/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"
29#include <algorithm>
30#include <iostream>
31
32static Statistic<> NumInlined("inline\t\t- Number of functions inlined");
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(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!");
70
71  const Function *CalledFunc = CI->getCalledFunction();
72  if (CalledFunc == 0 ||   // Can't inline external function or indirect call!
73      CalledFunc->isExternal()) return false;
74
75  //cerr << "Inlining " << CalledFunc->getName() << " into "
76  //     << CurrentMeth->getName() << "\n";
77
78  BasicBlock *OrigBB = CI->getParent();
79
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.
83  //
84  BasicBlock *NewBB = OrigBB->splitBasicBlock(CI);
85  NewBB->setName("InlinedFunctionReturnNode");
86
87  // Remove (unlink) the CallInst from the start of the new basic block.
88  NewBB->getInstList().remove(CI);
89
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
92  // function.
93  //
94  PHINode *PHI = 0;
95  if (CalledFunc->getReturnType() != Type::VoidTy) {
96    // The PHI node should go at the front of the new basic block to merge all
97    // possible incoming values.
98    //
99    PHI = new PHINode(CalledFunc->getReturnType(), CI->getName(),
100                      NewBB->begin());
101
102    // Anything that used the result of the function call should now use the PHI
103    // node as their operand.
104    //
105    CI->replaceAllUsesWith(PHI);
106  }
107
108  // Keep a mapping between the original function's values and the new
109  // duplicated code's values.  This includes all of: Function arguments,
110  // instruction values, constant pool entries, and basic blocks.
111  //
112  std::map<const Value *, Value*> ValueMap;
113
114  // Add the function arguments to the mapping: (start counting at 1 to skip the
115  // function reference itself)
116  //
117  Function::const_aiterator PTI = CalledFunc->abegin();
118  for (unsigned a = 1, E = CI->getNumOperands(); a != E; ++a, ++PTI)
119    ValueMap[PTI] = CI->getOperand(a);
120
121  ValueMap[NewBB] = NewBB;  // Returns get converted to reference NewBB
122
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...
125  //
126  for (Function::const_iterator BB = CalledFunc->begin();
127       BB != CalledFunc->end(); ++BB) {
128    assert(BB->getTerminator() && "BasicBlock doesn't have terminator!?!?");
129
130    // Create a new basic block to copy instructions into!
131    BasicBlock *IBB = new BasicBlock("", NewBB->getParent());
132    if (BB->hasName()) IBB->setName(BB->getName()+".i");  // .i = inlined once
133
134    ValueMap[BB] = IBB;                       // Add basic block mapping.
135
136    // Make sure to capture the mapping that a return will use...
137    // TODO: This assumes that the RET is returning a value computed in the same
138    //       basic block as the return was issued from!
139    //
140    const TerminatorInst *TI = BB->getTerminator();
141
142    // Loop over all instructions copying them over...
143    Instruction *NewInst;
144    for (BasicBlock::const_iterator II = BB->begin();
145	 II != --BB->end(); ++II) {
146      IBB->getInstList().push_back((NewInst = II->clone()));
147      ValueMap[II] = NewInst;                  // Add instruction map to value.
148      if (II->hasName())
149        NewInst->setName(II->getName()+".i");  // .i = inlined once
150    }
151
152    // Copy over the terminator now...
153    switch (TI->getOpcode()) {
154    case Instruction::Ret: {
155      const ReturnInst *RI = cast<ReturnInst>(TI);
156
157      if (PHI) {   // The PHI node should include this value!
158	assert(RI->getReturnValue() && "Ret should have value!");
159	assert(RI->getReturnValue()->getType() == PHI->getType() &&
160	       "Ret value not consistent in function!");
161	PHI->addIncoming((Value*)RI->getReturnValue(),
162                         (BasicBlock*)cast<BasicBlock>(&*BB));
163      }
164
165      // Add a branch to the code that was after the original Call.
166      IBB->getInstList().push_back(new BranchInst(NewBB));
167      break;
168    }
169    case Instruction::Br:
170      IBB->getInstList().push_back(TI->clone());
171      break;
172
173    default:
174      cerr << "FunctionInlining: Don't know how to handle terminator: " << TI;
175      abort();
176    }
177  }
178
179
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.
182  //
183  for (Function::const_iterator BB = CalledFunc->begin();
184       BB != CalledFunc->end(); ++BB) {
185    BasicBlock *NBB = (BasicBlock*)ValueMap[BB];
186
187    // Loop over all instructions, fixing each one as we find it...
188    //
189    for (BasicBlock::iterator II = NBB->begin(); II != NBB->end(); ++II)
190      RemapInstruction(II, ValueMap);
191  }
192
193  if (PHI) RemapInstruction(PHI, ValueMap);  // Fix the PHI node also...
194
195  // Change the branch that used to go to NewBB to branch to the first basic
196  // block of the inlined function.
197  //
198  TerminatorInst *Br = OrigBB->getTerminator();
199  assert(Br && Br->getOpcode() == Instruction::Br &&
200	 "splitBasicBlock broken!");
201  Br->setOperand(0, ValueMap[&CalledFunc->front()]);
202
203  // Since we are now done with the CallInst, we can finally delete it.
204  delete CI;
205  return true;
206}
207
208static inline bool ShouldInlineFunction(const CallInst *CI, const Function *F) {
209  assert(CI->getParent() && CI->getParent()->getParent() &&
210	 "Call not embedded into a function!");
211
212  // Don't inline a recursive call.
213  if (CI->getParent()->getParent() == F) return false;
214
215  // Don't inline something too big.  This is a really crappy heuristic
216  if (F->size() > 3) return false;
217
218  // Don't inline into something too big. This is a **really** crappy heuristic
219  if (CI->getParent()->getParent()->size() > 10) return false;
220
221  // Go ahead and try just about anything else.
222  return true;
223}
224
225
226static inline bool DoFunctionInlining(BasicBlock *BB) {
227  for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
228    if (CallInst *CI = dyn_cast<CallInst>(&*I)) {
229      // Check to see if we should inline this function
230      Function *F = CI->getCalledFunction();
231      if (F && ShouldInlineFunction(CI, F)) {
232	return InlineFunction(CI);
233      }
234    }
235  }
236  return false;
237}
238
239// doFunctionInlining - Use a heuristic based approach to inline functions that
240// seem to look good.
241//
242static bool doFunctionInlining(Function &F) {
243  bool Changed = false;
244
245  // Loop through now and inline instructions a basic block at a time...
246  for (Function::iterator I = F.begin(); I != F.end(); )
247    if (DoFunctionInlining(I)) {
248      ++NumInlined;
249      Changed = true;
250    } else {
251      ++I;
252    }
253
254  return Changed;
255}
256
257namespace {
258  struct FunctionInlining : public FunctionPass {
259    virtual bool runOnFunction(Function &F) {
260      return doFunctionInlining(F);
261    }
262  };
263  RegisterOpt<FunctionInlining> X("inline", "Function Integration/Inlining");
264}
265
266Pass *createFunctionInliningPass() { return new FunctionInlining(); }
267