InlineFunction.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643
  1. //===- InlineFunction.cpp - Code to perform function inlining -------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // 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. //===----------------------------------------------------------------------===//
  14. #include "llvm/Transforms/Utils/Cloning.h"
  15. #include "llvm/Constants.h"
  16. #include "llvm/DerivedTypes.h"
  17. #include "llvm/LLVMContext.h"
  18. #include "llvm/Module.h"
  19. #include "llvm/Instructions.h"
  20. #include "llvm/IntrinsicInst.h"
  21. #include "llvm/Intrinsics.h"
  22. #include "llvm/Attributes.h"
  23. #include "llvm/Analysis/CallGraph.h"
  24. #include "llvm/Analysis/DebugInfo.h"
  25. #include "llvm/Target/TargetData.h"
  26. #include "llvm/ADT/SmallVector.h"
  27. #include "llvm/ADT/StringExtras.h"
  28. #include "llvm/Support/CallSite.h"
  29. using namespace llvm;
  30. bool llvm::InlineFunction(CallInst *CI, CallGraph *CG, const TargetData *TD,
  31. SmallVectorImpl<AllocaInst*> *StaticAllocas) {
  32. return InlineFunction(CallSite(CI), CG, TD, StaticAllocas);
  33. }
  34. bool llvm::InlineFunction(InvokeInst *II, CallGraph *CG, const TargetData *TD,
  35. SmallVectorImpl<AllocaInst*> *StaticAllocas) {
  36. return InlineFunction(CallSite(II), CG, TD, StaticAllocas);
  37. }
  38. /// HandleCallsInBlockInlinedThroughInvoke - When we inline a basic block into
  39. /// an invoke, we have to turn all of the calls that can throw into
  40. /// invokes. This function analyze BB to see if there are any calls, and if so,
  41. /// it rewrites them to be invokes that jump to InvokeDest and fills in the PHI
  42. /// nodes in that block with the values specified in InvokeDestPHIValues.
  43. ///
  44. static void HandleCallsInBlockInlinedThroughInvoke(BasicBlock *BB,
  45. BasicBlock *InvokeDest,
  46. const SmallVectorImpl<Value*> &InvokeDestPHIValues) {
  47. for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
  48. Instruction *I = BBI++;
  49. // We only need to check for function calls: inlined invoke
  50. // instructions require no special handling.
  51. CallInst *CI = dyn_cast<CallInst>(I);
  52. if (CI == 0) continue;
  53. // If this call cannot unwind, don't convert it to an invoke.
  54. if (CI->doesNotThrow())
  55. continue;
  56. // Convert this function call into an invoke instruction.
  57. // First, split the basic block.
  58. BasicBlock *Split = BB->splitBasicBlock(CI, CI->getName()+".noexc");
  59. // Next, create the new invoke instruction, inserting it at the end
  60. // of the old basic block.
  61. SmallVector<Value*, 8> InvokeArgs(CI->op_begin(), CI->op_end() - 1);
  62. InvokeInst *II =
  63. InvokeInst::Create(CI->getCalledValue(), Split, InvokeDest,
  64. InvokeArgs.begin(), InvokeArgs.end(),
  65. CI->getName(), BB->getTerminator());
  66. II->setCallingConv(CI->getCallingConv());
  67. II->setAttributes(CI->getAttributes());
  68. // Make sure that anything using the call now uses the invoke! This also
  69. // updates the CallGraph if present.
  70. CI->replaceAllUsesWith(II);
  71. // Delete the unconditional branch inserted by splitBasicBlock
  72. BB->getInstList().pop_back();
  73. Split->getInstList().pop_front(); // Delete the original call
  74. // Update any PHI nodes in the exceptional block to indicate that
  75. // there is now a new entry in them.
  76. unsigned i = 0;
  77. for (BasicBlock::iterator I = InvokeDest->begin();
  78. isa<PHINode>(I); ++I, ++i)
  79. cast<PHINode>(I)->addIncoming(InvokeDestPHIValues[i], BB);
  80. // This basic block is now complete, the caller will continue scanning the
  81. // next one.
  82. return;
  83. }
  84. }
  85. /// HandleInlinedInvoke - If we inlined an invoke site, we need to convert calls
  86. /// in the body of the inlined function into invokes and turn unwind
  87. /// instructions into branches to the invoke unwind dest.
  88. ///
  89. /// II is the invoke instruction being inlined. FirstNewBlock is the first
  90. /// block of the inlined code (the last block is the end of the function),
  91. /// and InlineCodeInfo is information about the code that got inlined.
  92. static void HandleInlinedInvoke(InvokeInst *II, BasicBlock *FirstNewBlock,
  93. ClonedCodeInfo &InlinedCodeInfo) {
  94. BasicBlock *InvokeDest = II->getUnwindDest();
  95. SmallVector<Value*, 8> InvokeDestPHIValues;
  96. // If there are PHI nodes in the unwind destination block, we need to
  97. // keep track of which values came into them from this invoke, then remove
  98. // the entry for this block.
  99. BasicBlock *InvokeBlock = II->getParent();
  100. for (BasicBlock::iterator I = InvokeDest->begin(); isa<PHINode>(I); ++I) {
  101. PHINode *PN = cast<PHINode>(I);
  102. // Save the value to use for this edge.
  103. InvokeDestPHIValues.push_back(PN->getIncomingValueForBlock(InvokeBlock));
  104. }
  105. Function *Caller = FirstNewBlock->getParent();
  106. // The inlined code is currently at the end of the function, scan from the
  107. // start of the inlined code to its end, checking for stuff we need to
  108. // rewrite. If the code doesn't have calls or unwinds, we know there is
  109. // nothing to rewrite.
  110. if (!InlinedCodeInfo.ContainsCalls && !InlinedCodeInfo.ContainsUnwinds) {
  111. // Now that everything is happy, we have one final detail. The PHI nodes in
  112. // the exception destination block still have entries due to the original
  113. // invoke instruction. Eliminate these entries (which might even delete the
  114. // PHI node) now.
  115. InvokeDest->removePredecessor(II->getParent());
  116. return;
  117. }
  118. for (Function::iterator BB = FirstNewBlock, E = Caller->end(); BB != E; ++BB){
  119. if (InlinedCodeInfo.ContainsCalls)
  120. HandleCallsInBlockInlinedThroughInvoke(BB, InvokeDest,
  121. InvokeDestPHIValues);
  122. if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
  123. // An UnwindInst requires special handling when it gets inlined into an
  124. // invoke site. Once this happens, we know that the unwind would cause
  125. // a control transfer to the invoke exception destination, so we can
  126. // transform it into a direct branch to the exception destination.
  127. BranchInst::Create(InvokeDest, UI);
  128. // Delete the unwind instruction!
  129. UI->eraseFromParent();
  130. // Update any PHI nodes in the exceptional block to indicate that
  131. // there is now a new entry in them.
  132. unsigned i = 0;
  133. for (BasicBlock::iterator I = InvokeDest->begin();
  134. isa<PHINode>(I); ++I, ++i) {
  135. PHINode *PN = cast<PHINode>(I);
  136. PN->addIncoming(InvokeDestPHIValues[i], BB);
  137. }
  138. }
  139. }
  140. // Now that everything is happy, we have one final detail. The PHI nodes in
  141. // the exception destination block still have entries due to the original
  142. // invoke instruction. Eliminate these entries (which might even delete the
  143. // PHI node) now.
  144. InvokeDest->removePredecessor(II->getParent());
  145. }
  146. /// UpdateCallGraphAfterInlining - Once we have cloned code over from a callee
  147. /// into the caller, update the specified callgraph to reflect the changes we
  148. /// made. Note that it's possible that not all code was copied over, so only
  149. /// some edges of the callgraph may remain.
  150. static void UpdateCallGraphAfterInlining(CallSite CS,
  151. Function::iterator FirstNewBlock,
  152. DenseMap<const Value*, Value*> &ValueMap,
  153. CallGraph &CG) {
  154. const Function *Caller = CS.getInstruction()->getParent()->getParent();
  155. const Function *Callee = CS.getCalledFunction();
  156. CallGraphNode *CalleeNode = CG[Callee];
  157. CallGraphNode *CallerNode = CG[Caller];
  158. // Since we inlined some uninlined call sites in the callee into the caller,
  159. // add edges from the caller to all of the callees of the callee.
  160. CallGraphNode::iterator I = CalleeNode->begin(), E = CalleeNode->end();
  161. // Consider the case where CalleeNode == CallerNode.
  162. CallGraphNode::CalledFunctionsVector CallCache;
  163. if (CalleeNode == CallerNode) {
  164. CallCache.assign(I, E);
  165. I = CallCache.begin();
  166. E = CallCache.end();
  167. }
  168. for (; I != E; ++I) {
  169. const Value *OrigCall = I->first;
  170. DenseMap<const Value*, Value*>::iterator VMI = ValueMap.find(OrigCall);
  171. // Only copy the edge if the call was inlined!
  172. if (VMI == ValueMap.end() || VMI->second == 0)
  173. continue;
  174. // If the call was inlined, but then constant folded, there is no edge to
  175. // add. Check for this case.
  176. if (Instruction *NewCall = dyn_cast<Instruction>(VMI->second))
  177. CallerNode->addCalledFunction(CallSite::get(NewCall), I->second);
  178. }
  179. // Update the call graph by deleting the edge from Callee to Caller. We must
  180. // do this after the loop above in case Caller and Callee are the same.
  181. CallerNode->removeCallEdgeFor(CS);
  182. }
  183. // InlineFunction - This function inlines the called function into the basic
  184. // block of the caller. This returns false if it is not possible to inline this
  185. // call. The program is still in a well defined state if this occurs though.
  186. //
  187. // Note that this only does one level of inlining. For example, if the
  188. // instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now
  189. // exists in the instruction stream. Similiarly this will inline a recursive
  190. // function by one level.
  191. //
  192. bool llvm::InlineFunction(CallSite CS, CallGraph *CG, const TargetData *TD,
  193. SmallVectorImpl<AllocaInst*> *StaticAllocas) {
  194. Instruction *TheCall = CS.getInstruction();
  195. LLVMContext &Context = TheCall->getContext();
  196. assert(TheCall->getParent() && TheCall->getParent()->getParent() &&
  197. "Instruction not in function!");
  198. const Function *CalledFunc = CS.getCalledFunction();
  199. if (CalledFunc == 0 || // Can't inline external function or indirect
  200. CalledFunc->isDeclaration() || // call, or call to a vararg function!
  201. CalledFunc->getFunctionType()->isVarArg()) return false;
  202. // If the call to the callee is not a tail call, we must clear the 'tail'
  203. // flags on any calls that we inline.
  204. bool MustClearTailCallFlags =
  205. !(isa<CallInst>(TheCall) && cast<CallInst>(TheCall)->isTailCall());
  206. // If the call to the callee cannot throw, set the 'nounwind' flag on any
  207. // calls that we inline.
  208. bool MarkNoUnwind = CS.doesNotThrow();
  209. BasicBlock *OrigBB = TheCall->getParent();
  210. Function *Caller = OrigBB->getParent();
  211. // GC poses two hazards to inlining, which only occur when the callee has GC:
  212. // 1. If the caller has no GC, then the callee's GC must be propagated to the
  213. // caller.
  214. // 2. If the caller has a differing GC, it is invalid to inline.
  215. if (CalledFunc->hasGC()) {
  216. if (!Caller->hasGC())
  217. Caller->setGC(CalledFunc->getGC());
  218. else if (CalledFunc->getGC() != Caller->getGC())
  219. return false;
  220. }
  221. // Get an iterator to the last basic block in the function, which will have
  222. // the new function inlined after it.
  223. //
  224. Function::iterator LastBlock = &Caller->back();
  225. // Make sure to capture all of the return instructions from the cloned
  226. // function.
  227. SmallVector<ReturnInst*, 8> Returns;
  228. ClonedCodeInfo InlinedFunctionInfo;
  229. Function::iterator FirstNewBlock;
  230. { // Scope to destroy ValueMap after cloning.
  231. DenseMap<const Value*, Value*> ValueMap;
  232. assert(CalledFunc->arg_size() == CS.arg_size() &&
  233. "No varargs calls can be inlined!");
  234. // Calculate the vector of arguments to pass into the function cloner, which
  235. // matches up the formal to the actual argument values.
  236. CallSite::arg_iterator AI = CS.arg_begin();
  237. unsigned ArgNo = 0;
  238. for (Function::const_arg_iterator I = CalledFunc->arg_begin(),
  239. E = CalledFunc->arg_end(); I != E; ++I, ++AI, ++ArgNo) {
  240. Value *ActualArg = *AI;
  241. // When byval arguments actually inlined, we need to make the copy implied
  242. // by them explicit. However, we don't do this if the callee is readonly
  243. // or readnone, because the copy would be unneeded: the callee doesn't
  244. // modify the struct.
  245. if (CalledFunc->paramHasAttr(ArgNo+1, Attribute::ByVal) &&
  246. !CalledFunc->onlyReadsMemory()) {
  247. const Type *AggTy = cast<PointerType>(I->getType())->getElementType();
  248. const Type *VoidPtrTy =
  249. Type::getInt8PtrTy(Context);
  250. // Create the alloca. If we have TargetData, use nice alignment.
  251. unsigned Align = 1;
  252. if (TD) Align = TD->getPrefTypeAlignment(AggTy);
  253. Value *NewAlloca = new AllocaInst(AggTy, 0, Align,
  254. I->getName(),
  255. &*Caller->begin()->begin());
  256. // Emit a memcpy.
  257. const Type *Tys[3] = {VoidPtrTy, VoidPtrTy, Type::getInt64Ty(Context)};
  258. Function *MemCpyFn = Intrinsic::getDeclaration(Caller->getParent(),
  259. Intrinsic::memcpy,
  260. Tys, 3);
  261. Value *DestCast = new BitCastInst(NewAlloca, VoidPtrTy, "tmp", TheCall);
  262. Value *SrcCast = new BitCastInst(*AI, VoidPtrTy, "tmp", TheCall);
  263. Value *Size;
  264. if (TD == 0)
  265. Size = ConstantExpr::getSizeOf(AggTy);
  266. else
  267. Size = ConstantInt::get(Type::getInt64Ty(Context),
  268. TD->getTypeStoreSize(AggTy));
  269. // Always generate a memcpy of alignment 1 here because we don't know
  270. // the alignment of the src pointer. Other optimizations can infer
  271. // better alignment.
  272. Value *CallArgs[] = {
  273. DestCast, SrcCast, Size,
  274. ConstantInt::get(Type::getInt32Ty(Context), 1),
  275. ConstantInt::get(Type::getInt1Ty(Context), 0)
  276. };
  277. CallInst *TheMemCpy =
  278. CallInst::Create(MemCpyFn, CallArgs, CallArgs+5, "", TheCall);
  279. // If we have a call graph, update it.
  280. if (CG) {
  281. CallGraphNode *MemCpyCGN = CG->getOrInsertFunction(MemCpyFn);
  282. CallGraphNode *CallerNode = (*CG)[Caller];
  283. CallerNode->addCalledFunction(TheMemCpy, MemCpyCGN);
  284. }
  285. // Uses of the argument in the function should use our new alloca
  286. // instead.
  287. ActualArg = NewAlloca;
  288. }
  289. ValueMap[I] = ActualArg;
  290. }
  291. // We want the inliner to prune the code as it copies. We would LOVE to
  292. // have no dead or constant instructions leftover after inlining occurs
  293. // (which can happen, e.g., because an argument was constant), but we'll be
  294. // happy with whatever the cloner can do.
  295. CloneAndPruneFunctionInto(Caller, CalledFunc, ValueMap, Returns, ".i",
  296. &InlinedFunctionInfo, TD, TheCall);
  297. // Remember the first block that is newly cloned over.
  298. FirstNewBlock = LastBlock; ++FirstNewBlock;
  299. // Update the callgraph if requested.
  300. if (CG)
  301. UpdateCallGraphAfterInlining(CS, FirstNewBlock, ValueMap, *CG);
  302. }
  303. // If there are any alloca instructions in the block that used to be the entry
  304. // block for the callee, move them to the entry block of the caller. First
  305. // calculate which instruction they should be inserted before. We insert the
  306. // instructions at the end of the current alloca list.
  307. //
  308. {
  309. BasicBlock::iterator InsertPoint = Caller->begin()->begin();
  310. for (BasicBlock::iterator I = FirstNewBlock->begin(),
  311. E = FirstNewBlock->end(); I != E; ) {
  312. AllocaInst *AI = dyn_cast<AllocaInst>(I++);
  313. if (AI == 0) continue;
  314. // If the alloca is now dead, remove it. This often occurs due to code
  315. // specialization.
  316. if (AI->use_empty()) {
  317. AI->eraseFromParent();
  318. continue;
  319. }
  320. if (!isa<Constant>(AI->getArraySize()))
  321. continue;
  322. // Keep track of the static allocas that we inline into the caller if the
  323. // StaticAllocas pointer is non-null.
  324. if (StaticAllocas) StaticAllocas->push_back(AI);
  325. // Scan for the block of allocas that we can move over, and move them
  326. // all at once.
  327. while (isa<AllocaInst>(I) &&
  328. isa<Constant>(cast<AllocaInst>(I)->getArraySize())) {
  329. if (StaticAllocas) StaticAllocas->push_back(cast<AllocaInst>(I));
  330. ++I;
  331. }
  332. // Transfer all of the allocas over in a block. Using splice means
  333. // that the instructions aren't removed from the symbol table, then
  334. // reinserted.
  335. Caller->getEntryBlock().getInstList().splice(InsertPoint,
  336. FirstNewBlock->getInstList(),
  337. AI, I);
  338. }
  339. }
  340. // If the inlined code contained dynamic alloca instructions, wrap the inlined
  341. // code with llvm.stacksave/llvm.stackrestore intrinsics.
  342. if (InlinedFunctionInfo.ContainsDynamicAllocas) {
  343. Module *M = Caller->getParent();
  344. // Get the two intrinsics we care about.
  345. Function *StackSave = Intrinsic::getDeclaration(M, Intrinsic::stacksave);
  346. Function *StackRestore=Intrinsic::getDeclaration(M,Intrinsic::stackrestore);
  347. // If we are preserving the callgraph, add edges to the stacksave/restore
  348. // functions for the calls we insert.
  349. CallGraphNode *StackSaveCGN = 0, *StackRestoreCGN = 0, *CallerNode = 0;
  350. if (CG) {
  351. StackSaveCGN = CG->getOrInsertFunction(StackSave);
  352. StackRestoreCGN = CG->getOrInsertFunction(StackRestore);
  353. CallerNode = (*CG)[Caller];
  354. }
  355. // Insert the llvm.stacksave.
  356. CallInst *SavedPtr = CallInst::Create(StackSave, "savedstack",
  357. FirstNewBlock->begin());
  358. if (CG) CallerNode->addCalledFunction(SavedPtr, StackSaveCGN);
  359. // Insert a call to llvm.stackrestore before any return instructions in the
  360. // inlined function.
  361. for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
  362. CallInst *CI = CallInst::Create(StackRestore, SavedPtr, "", Returns[i]);
  363. if (CG) CallerNode->addCalledFunction(CI, StackRestoreCGN);
  364. }
  365. // Count the number of StackRestore calls we insert.
  366. unsigned NumStackRestores = Returns.size();
  367. // If we are inlining an invoke instruction, insert restores before each
  368. // unwind. These unwinds will be rewritten into branches later.
  369. if (InlinedFunctionInfo.ContainsUnwinds && isa<InvokeInst>(TheCall)) {
  370. for (Function::iterator BB = FirstNewBlock, E = Caller->end();
  371. BB != E; ++BB)
  372. if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
  373. CallInst *CI = CallInst::Create(StackRestore, SavedPtr, "", UI);
  374. if (CG) CallerNode->addCalledFunction(CI, StackRestoreCGN);
  375. ++NumStackRestores;
  376. }
  377. }
  378. }
  379. // If we are inlining tail call instruction through a call site that isn't
  380. // marked 'tail', we must remove the tail marker for any calls in the inlined
  381. // code. Also, calls inlined through a 'nounwind' call site should be marked
  382. // 'nounwind'.
  383. if (InlinedFunctionInfo.ContainsCalls &&
  384. (MustClearTailCallFlags || MarkNoUnwind)) {
  385. for (Function::iterator BB = FirstNewBlock, E = Caller->end();
  386. BB != E; ++BB)
  387. for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
  388. if (CallInst *CI = dyn_cast<CallInst>(I)) {
  389. if (MustClearTailCallFlags)
  390. CI->setTailCall(false);
  391. if (MarkNoUnwind)
  392. CI->setDoesNotThrow();
  393. }
  394. }
  395. // If we are inlining through a 'nounwind' call site then any inlined 'unwind'
  396. // instructions are unreachable.
  397. if (InlinedFunctionInfo.ContainsUnwinds && MarkNoUnwind)
  398. for (Function::iterator BB = FirstNewBlock, E = Caller->end();
  399. BB != E; ++BB) {
  400. TerminatorInst *Term = BB->getTerminator();
  401. if (isa<UnwindInst>(Term)) {
  402. new UnreachableInst(Context, Term);
  403. BB->getInstList().erase(Term);
  404. }
  405. }
  406. // If we are inlining for an invoke instruction, we must make sure to rewrite
  407. // any inlined 'unwind' instructions into branches to the invoke exception
  408. // destination, and call instructions into invoke instructions.
  409. if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall))
  410. HandleInlinedInvoke(II, FirstNewBlock, InlinedFunctionInfo);
  411. // If we cloned in _exactly one_ basic block, and if that block ends in a
  412. // return instruction, we splice the body of the inlined callee directly into
  413. // the calling basic block.
  414. if (Returns.size() == 1 && std::distance(FirstNewBlock, Caller->end()) == 1) {
  415. // Move all of the instructions right before the call.
  416. OrigBB->getInstList().splice(TheCall, FirstNewBlock->getInstList(),
  417. FirstNewBlock->begin(), FirstNewBlock->end());
  418. // Remove the cloned basic block.
  419. Caller->getBasicBlockList().pop_back();
  420. // If the call site was an invoke instruction, add a branch to the normal
  421. // destination.
  422. if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall))
  423. BranchInst::Create(II->getNormalDest(), TheCall);
  424. // If the return instruction returned a value, replace uses of the call with
  425. // uses of the returned value.
  426. if (!TheCall->use_empty()) {
  427. ReturnInst *R = Returns[0];
  428. if (TheCall == R->getReturnValue())
  429. TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
  430. else
  431. TheCall->replaceAllUsesWith(R->getReturnValue());
  432. }
  433. // Since we are now done with the Call/Invoke, we can delete it.
  434. TheCall->eraseFromParent();
  435. // Since we are now done with the return instruction, delete it also.
  436. Returns[0]->eraseFromParent();
  437. // We are now done with the inlining.
  438. return true;
  439. }
  440. // Otherwise, we have the normal case, of more than one block to inline or
  441. // multiple return sites.
  442. // We want to clone the entire callee function into the hole between the
  443. // "starter" and "ender" blocks. How we accomplish this depends on whether
  444. // this is an invoke instruction or a call instruction.
  445. BasicBlock *AfterCallBB;
  446. if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
  447. // Add an unconditional branch to make this look like the CallInst case...
  448. BranchInst *NewBr = BranchInst::Create(II->getNormalDest(), TheCall);
  449. // Split the basic block. This guarantees that no PHI nodes will have to be
  450. // updated due to new incoming edges, and make the invoke case more
  451. // symmetric to the call case.
  452. AfterCallBB = OrigBB->splitBasicBlock(NewBr,
  453. CalledFunc->getName()+".exit");
  454. } else { // It's a call
  455. // If this is a call instruction, we need to split the basic block that
  456. // the call lives in.
  457. //
  458. AfterCallBB = OrigBB->splitBasicBlock(TheCall,
  459. CalledFunc->getName()+".exit");
  460. }
  461. // Change the branch that used to go to AfterCallBB to branch to the first
  462. // basic block of the inlined function.
  463. //
  464. TerminatorInst *Br = OrigBB->getTerminator();
  465. assert(Br && Br->getOpcode() == Instruction::Br &&
  466. "splitBasicBlock broken!");
  467. Br->setOperand(0, FirstNewBlock);
  468. // Now that the function is correct, make it a little bit nicer. In
  469. // particular, move the basic blocks inserted from the end of the function
  470. // into the space made by splitting the source basic block.
  471. Caller->getBasicBlockList().splice(AfterCallBB, Caller->getBasicBlockList(),
  472. FirstNewBlock, Caller->end());
  473. // Handle all of the return instructions that we just cloned in, and eliminate
  474. // any users of the original call/invoke instruction.
  475. const Type *RTy = CalledFunc->getReturnType();
  476. if (Returns.size() > 1) {
  477. // The PHI node should go at the front of the new basic block to merge all
  478. // possible incoming values.
  479. PHINode *PHI = 0;
  480. if (!TheCall->use_empty()) {
  481. PHI = PHINode::Create(RTy, TheCall->getName(),
  482. AfterCallBB->begin());
  483. // Anything that used the result of the function call should now use the
  484. // PHI node as their operand.
  485. TheCall->replaceAllUsesWith(PHI);
  486. }
  487. // Loop over all of the return instructions adding entries to the PHI node
  488. // as appropriate.
  489. if (PHI) {
  490. for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
  491. ReturnInst *RI = Returns[i];
  492. assert(RI->getReturnValue()->getType() == PHI->getType() &&
  493. "Ret value not consistent in function!");
  494. PHI->addIncoming(RI->getReturnValue(), RI->getParent());
  495. }
  496. // Now that we inserted the PHI, check to see if it has a single value
  497. // (e.g. all the entries are the same or undef). If so, remove the PHI so
  498. // it doesn't block other optimizations.
  499. if (Value *V = PHI->hasConstantValue()) {
  500. PHI->replaceAllUsesWith(V);
  501. PHI->eraseFromParent();
  502. }
  503. }
  504. // Add a branch to the merge points and remove return instructions.
  505. for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
  506. ReturnInst *RI = Returns[i];
  507. BranchInst::Create(AfterCallBB, RI);
  508. RI->eraseFromParent();
  509. }
  510. } else if (!Returns.empty()) {
  511. // Otherwise, if there is exactly one return value, just replace anything
  512. // using the return value of the call with the computed value.
  513. if (!TheCall->use_empty()) {
  514. if (TheCall == Returns[0]->getReturnValue())
  515. TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
  516. else
  517. TheCall->replaceAllUsesWith(Returns[0]->getReturnValue());
  518. }
  519. // Splice the code from the return block into the block that it will return
  520. // to, which contains the code that was after the call.
  521. BasicBlock *ReturnBB = Returns[0]->getParent();
  522. AfterCallBB->getInstList().splice(AfterCallBB->begin(),
  523. ReturnBB->getInstList());
  524. // Update PHI nodes that use the ReturnBB to use the AfterCallBB.
  525. ReturnBB->replaceAllUsesWith(AfterCallBB);
  526. // Delete the return instruction now and empty ReturnBB now.
  527. Returns[0]->eraseFromParent();
  528. ReturnBB->eraseFromParent();
  529. } else if (!TheCall->use_empty()) {
  530. // No returns, but something is using the return value of the call. Just
  531. // nuke the result.
  532. TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
  533. }
  534. // Since we are now done with the Call/Invoke, we can delete it.
  535. TheCall->eraseFromParent();
  536. // We should always be able to fold the entry block of the function into the
  537. // single predecessor of the block...
  538. assert(cast<BranchInst>(Br)->isUnconditional() && "splitBasicBlock broken!");
  539. BasicBlock *CalleeEntry = cast<BranchInst>(Br)->getSuccessor(0);
  540. // Splice the code entry block into calling block, right before the
  541. // unconditional branch.
  542. OrigBB->getInstList().splice(Br, CalleeEntry->getInstList());
  543. CalleeEntry->replaceAllUsesWith(OrigBB); // Update PHI nodes
  544. // Remove the unconditional branch.
  545. OrigBB->getInstList().erase(Br);
  546. // Now we can remove the CalleeEntry block, which is now empty.
  547. Caller->getBasicBlockList().erase(CalleeEntry);
  548. return true;
  549. }