InlineFunction.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. //===- InlineFunction.cpp - Code to perform function inlining -------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file was developed by the LLVM research group and is distributed under
  6. // the University of Illinois Open Source License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements inlining of a function into a call site, resolving
  11. // parameters and the return value as appropriate.
  12. //
  13. // FIXME: This pass should transform alloca instructions in the called function
  14. // into alloca/dealloca pairs! Or perhaps it should refuse to inline them!
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #include "llvm/Transforms/Utils/Cloning.h"
  18. #include "llvm/Constants.h"
  19. #include "llvm/DerivedTypes.h"
  20. #include "llvm/Module.h"
  21. #include "llvm/Instructions.h"
  22. #include "llvm/Intrinsics.h"
  23. #include "llvm/Support/CallSite.h"
  24. using namespace llvm;
  25. bool llvm::InlineFunction(CallInst *CI) { return InlineFunction(CallSite(CI)); }
  26. bool llvm::InlineFunction(InvokeInst *II) {return InlineFunction(CallSite(II));}
  27. // InlineFunction - This function inlines the called function into the basic
  28. // block of the caller. This returns false if it is not possible to inline this
  29. // call. The program is still in a well defined state if this occurs though.
  30. //
  31. // Note that this only does one level of inlining. For example, if the
  32. // instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now
  33. // exists in the instruction stream. Similiarly this will inline a recursive
  34. // function by one level.
  35. //
  36. bool llvm::InlineFunction(CallSite CS) {
  37. Instruction *TheCall = CS.getInstruction();
  38. assert(TheCall->getParent() && TheCall->getParent()->getParent() &&
  39. "Instruction not in function!");
  40. const Function *CalledFunc = CS.getCalledFunction();
  41. if (CalledFunc == 0 || // Can't inline external function or indirect
  42. CalledFunc->isExternal() || // call, or call to a vararg function!
  43. CalledFunc->getFunctionType()->isVarArg()) return false;
  44. // If the call to the callee is a non-tail call, we must clear the 'tail'
  45. // flags on any calls that we inline.
  46. bool MustClearTailCallFlags =
  47. isa<CallInst>(TheCall) && !cast<CallInst>(TheCall)->isTailCall();
  48. BasicBlock *OrigBB = TheCall->getParent();
  49. Function *Caller = OrigBB->getParent();
  50. // Get an iterator to the last basic block in the function, which will have
  51. // the new function inlined after it.
  52. //
  53. Function::iterator LastBlock = &Caller->back();
  54. // Make sure to capture all of the return instructions from the cloned
  55. // function.
  56. std::vector<ReturnInst*> Returns;
  57. { // Scope to destroy ValueMap after cloning.
  58. // Calculate the vector of arguments to pass into the function cloner...
  59. std::map<const Value*, Value*> ValueMap;
  60. assert(std::distance(CalledFunc->arg_begin(), CalledFunc->arg_end()) ==
  61. std::distance(CS.arg_begin(), CS.arg_end()) &&
  62. "No varargs calls can be inlined!");
  63. CallSite::arg_iterator AI = CS.arg_begin();
  64. for (Function::const_arg_iterator I = CalledFunc->arg_begin(),
  65. E = CalledFunc->arg_end(); I != E; ++I, ++AI)
  66. ValueMap[I] = *AI;
  67. // Clone the entire body of the callee into the caller.
  68. CloneFunctionInto(Caller, CalledFunc, ValueMap, Returns, ".i");
  69. }
  70. // Remember the first block that is newly cloned over.
  71. Function::iterator FirstNewBlock = LastBlock; ++FirstNewBlock;
  72. // If there are any alloca instructions in the block that used to be the entry
  73. // block for the callee, move them to the entry block of the caller. First
  74. // calculate which instruction they should be inserted before. We insert the
  75. // instructions at the end of the current alloca list.
  76. //
  77. if (isa<AllocaInst>(FirstNewBlock->begin())) {
  78. BasicBlock::iterator InsertPoint = Caller->begin()->begin();
  79. for (BasicBlock::iterator I = FirstNewBlock->begin(),
  80. E = FirstNewBlock->end(); I != E; )
  81. if (AllocaInst *AI = dyn_cast<AllocaInst>(I++))
  82. if (isa<Constant>(AI->getArraySize())) {
  83. // Scan for the block of allocas that we can move over.
  84. while (isa<AllocaInst>(I) &&
  85. isa<Constant>(cast<AllocaInst>(I)->getArraySize()))
  86. ++I;
  87. // Transfer all of the allocas over in a block. Using splice means
  88. // that they instructions aren't removed from the symbol table, then
  89. // reinserted.
  90. Caller->front().getInstList().splice(InsertPoint,
  91. FirstNewBlock->getInstList(),
  92. AI, I);
  93. }
  94. }
  95. // If we are inlining tail call instruction through an invoke or
  96. if (MustClearTailCallFlags) {
  97. for (Function::iterator BB = FirstNewBlock, E = Caller->end();
  98. BB != E; ++BB)
  99. for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
  100. if (CallInst *CI = dyn_cast<CallInst>(I))
  101. CI->setTailCall(false);
  102. }
  103. // If we are inlining for an invoke instruction, we must make sure to rewrite
  104. // any inlined 'unwind' instructions into branches to the invoke exception
  105. // destination, and call instructions into invoke instructions.
  106. if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
  107. BasicBlock *InvokeDest = II->getUnwindDest();
  108. std::vector<Value*> InvokeDestPHIValues;
  109. // If there are PHI nodes in the exceptional destination block, we need to
  110. // keep track of which values came into them from this invoke, then remove
  111. // the entry for this block.
  112. for (BasicBlock::iterator I = InvokeDest->begin(); isa<PHINode>(I); ++I) {
  113. PHINode *PN = cast<PHINode>(I);
  114. // Save the value to use for this edge...
  115. InvokeDestPHIValues.push_back(PN->getIncomingValueForBlock(OrigBB));
  116. }
  117. for (Function::iterator BB = FirstNewBlock, E = Caller->end();
  118. BB != E; ++BB) {
  119. for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
  120. // We only need to check for function calls: inlined invoke instructions
  121. // require no special handling...
  122. if (CallInst *CI = dyn_cast<CallInst>(I)) {
  123. // Convert this function call into an invoke instruction... if it's
  124. // not an intrinsic function call (which are known to not unwind).
  125. if (CI->getCalledFunction() &&
  126. CI->getCalledFunction()->getIntrinsicID()) {
  127. ++I;
  128. } else {
  129. // First, split the basic block...
  130. BasicBlock *Split = BB->splitBasicBlock(CI, CI->getName()+".noexc");
  131. // Next, create the new invoke instruction, inserting it at the end
  132. // of the old basic block.
  133. InvokeInst *II =
  134. new InvokeInst(CI->getCalledValue(), Split, InvokeDest,
  135. std::vector<Value*>(CI->op_begin()+1, CI->op_end()),
  136. CI->getName(), BB->getTerminator());
  137. II->setCallingConv(CI->getCallingConv());
  138. // Make sure that anything using the call now uses the invoke!
  139. CI->replaceAllUsesWith(II);
  140. // Delete the unconditional branch inserted by splitBasicBlock
  141. BB->getInstList().pop_back();
  142. Split->getInstList().pop_front(); // Delete the original call
  143. // Update any PHI nodes in the exceptional block to indicate that
  144. // there is now a new entry in them.
  145. unsigned i = 0;
  146. for (BasicBlock::iterator I = InvokeDest->begin();
  147. isa<PHINode>(I); ++I, ++i) {
  148. PHINode *PN = cast<PHINode>(I);
  149. PN->addIncoming(InvokeDestPHIValues[i], BB);
  150. }
  151. // This basic block is now complete, start scanning the next one.
  152. break;
  153. }
  154. } else {
  155. ++I;
  156. }
  157. }
  158. if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
  159. // An UnwindInst requires special handling when it gets inlined into an
  160. // invoke site. Once this happens, we know that the unwind would cause
  161. // a control transfer to the invoke exception destination, so we can
  162. // transform it into a direct branch to the exception destination.
  163. new BranchInst(InvokeDest, UI);
  164. // Delete the unwind instruction!
  165. UI->getParent()->getInstList().pop_back();
  166. // Update any PHI nodes in the exceptional block to indicate that
  167. // there is now a new entry in them.
  168. unsigned i = 0;
  169. for (BasicBlock::iterator I = InvokeDest->begin();
  170. isa<PHINode>(I); ++I, ++i) {
  171. PHINode *PN = cast<PHINode>(I);
  172. PN->addIncoming(InvokeDestPHIValues[i], BB);
  173. }
  174. }
  175. }
  176. // Now that everything is happy, we have one final detail. The PHI nodes in
  177. // the exception destination block still have entries due to the original
  178. // invoke instruction. Eliminate these entries (which might even delete the
  179. // PHI node) now.
  180. InvokeDest->removePredecessor(II->getParent());
  181. }
  182. // If we cloned in _exactly one_ basic block, and if that block ends in a
  183. // return instruction, we splice the body of the inlined callee directly into
  184. // the calling basic block.
  185. if (Returns.size() == 1 && std::distance(FirstNewBlock, Caller->end()) == 1) {
  186. // Move all of the instructions right before the call.
  187. OrigBB->getInstList().splice(TheCall, FirstNewBlock->getInstList(),
  188. FirstNewBlock->begin(), FirstNewBlock->end());
  189. // Remove the cloned basic block.
  190. Caller->getBasicBlockList().pop_back();
  191. // If the call site was an invoke instruction, add a branch to the normal
  192. // destination.
  193. if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall))
  194. new BranchInst(II->getNormalDest(), TheCall);
  195. // If the return instruction returned a value, replace uses of the call with
  196. // uses of the returned value.
  197. if (!TheCall->use_empty())
  198. TheCall->replaceAllUsesWith(Returns[0]->getReturnValue());
  199. // Since we are now done with the Call/Invoke, we can delete it.
  200. TheCall->getParent()->getInstList().erase(TheCall);
  201. // Since we are now done with the return instruction, delete it also.
  202. Returns[0]->getParent()->getInstList().erase(Returns[0]);
  203. // We are now done with the inlining.
  204. return true;
  205. }
  206. // Otherwise, we have the normal case, of more than one block to inline or
  207. // multiple return sites.
  208. // We want to clone the entire callee function into the hole between the
  209. // "starter" and "ender" blocks. How we accomplish this depends on whether
  210. // this is an invoke instruction or a call instruction.
  211. BasicBlock *AfterCallBB;
  212. if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
  213. // Add an unconditional branch to make this look like the CallInst case...
  214. BranchInst *NewBr = new BranchInst(II->getNormalDest(), TheCall);
  215. // Split the basic block. This guarantees that no PHI nodes will have to be
  216. // updated due to new incoming edges, and make the invoke case more
  217. // symmetric to the call case.
  218. AfterCallBB = OrigBB->splitBasicBlock(NewBr,
  219. CalledFunc->getName()+".exit");
  220. } else { // It's a call
  221. // If this is a call instruction, we need to split the basic block that
  222. // the call lives in.
  223. //
  224. AfterCallBB = OrigBB->splitBasicBlock(TheCall,
  225. CalledFunc->getName()+".exit");
  226. }
  227. // Change the branch that used to go to AfterCallBB to branch to the first
  228. // basic block of the inlined function.
  229. //
  230. TerminatorInst *Br = OrigBB->getTerminator();
  231. assert(Br && Br->getOpcode() == Instruction::Br &&
  232. "splitBasicBlock broken!");
  233. Br->setOperand(0, FirstNewBlock);
  234. // Now that the function is correct, make it a little bit nicer. In
  235. // particular, move the basic blocks inserted from the end of the function
  236. // into the space made by splitting the source basic block.
  237. //
  238. Caller->getBasicBlockList().splice(AfterCallBB, Caller->getBasicBlockList(),
  239. FirstNewBlock, Caller->end());
  240. // Handle all of the return instructions that we just cloned in, and eliminate
  241. // any users of the original call/invoke instruction.
  242. if (Returns.size() > 1) {
  243. // The PHI node should go at the front of the new basic block to merge all
  244. // possible incoming values.
  245. //
  246. PHINode *PHI = 0;
  247. if (!TheCall->use_empty()) {
  248. PHI = new PHINode(CalledFunc->getReturnType(),
  249. TheCall->getName(), AfterCallBB->begin());
  250. // Anything that used the result of the function call should now use the
  251. // PHI node as their operand.
  252. //
  253. TheCall->replaceAllUsesWith(PHI);
  254. }
  255. // Loop over all of the return instructions, turning them into unconditional
  256. // branches to the merge point now, and adding entries to the PHI node as
  257. // appropriate.
  258. for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
  259. ReturnInst *RI = Returns[i];
  260. if (PHI) {
  261. assert(RI->getReturnValue() && "Ret should have value!");
  262. assert(RI->getReturnValue()->getType() == PHI->getType() &&
  263. "Ret value not consistent in function!");
  264. PHI->addIncoming(RI->getReturnValue(), RI->getParent());
  265. }
  266. // Add a branch to the merge point where the PHI node lives if it exists.
  267. new BranchInst(AfterCallBB, RI);
  268. // Delete the return instruction now
  269. RI->getParent()->getInstList().erase(RI);
  270. }
  271. } else if (!Returns.empty()) {
  272. // Otherwise, if there is exactly one return value, just replace anything
  273. // using the return value of the call with the computed value.
  274. if (!TheCall->use_empty())
  275. TheCall->replaceAllUsesWith(Returns[0]->getReturnValue());
  276. // Splice the code from the return block into the block that it will return
  277. // to, which contains the code that was after the call.
  278. BasicBlock *ReturnBB = Returns[0]->getParent();
  279. AfterCallBB->getInstList().splice(AfterCallBB->begin(),
  280. ReturnBB->getInstList());
  281. // Update PHI nodes that use the ReturnBB to use the AfterCallBB.
  282. ReturnBB->replaceAllUsesWith(AfterCallBB);
  283. // Delete the return instruction now and empty ReturnBB now.
  284. Returns[0]->eraseFromParent();
  285. ReturnBB->eraseFromParent();
  286. } else if (!TheCall->use_empty()) {
  287. // No returns, but something is using the return value of the call. Just
  288. // nuke the result.
  289. TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
  290. }
  291. // Since we are now done with the Call/Invoke, we can delete it.
  292. TheCall->eraseFromParent();
  293. // We should always be able to fold the entry block of the function into the
  294. // single predecessor of the block...
  295. assert(cast<BranchInst>(Br)->isUnconditional() && "splitBasicBlock broken!");
  296. BasicBlock *CalleeEntry = cast<BranchInst>(Br)->getSuccessor(0);
  297. // Splice the code entry block into calling block, right before the
  298. // unconditional branch.
  299. OrigBB->getInstList().splice(Br, CalleeEntry->getInstList());
  300. CalleeEntry->replaceAllUsesWith(OrigBB); // Update PHI nodes
  301. // Remove the unconditional branch.
  302. OrigBB->getInstList().erase(Br);
  303. // Now we can remove the CalleeEntry block, which is now empty.
  304. Caller->getBasicBlockList().erase(CalleeEntry);
  305. return true;
  306. }