InlineFunction.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710
  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/Module.h"
  18. #include "llvm/Instructions.h"
  19. #include "llvm/IntrinsicInst.h"
  20. #include "llvm/Intrinsics.h"
  21. #include "llvm/Attributes.h"
  22. #include "llvm/Analysis/CallGraph.h"
  23. #include "llvm/Analysis/DebugInfo.h"
  24. #include "llvm/Analysis/InstructionSimplify.h"
  25. #include "llvm/Target/TargetData.h"
  26. #include "llvm/Transforms/Utils/Local.h"
  27. #include "llvm/ADT/SmallVector.h"
  28. #include "llvm/ADT/StringExtras.h"
  29. #include "llvm/Support/CallSite.h"
  30. using namespace llvm;
  31. bool llvm::InlineFunction(CallInst *CI, InlineFunctionInfo &IFI) {
  32. return InlineFunction(CallSite(CI), IFI);
  33. }
  34. bool llvm::InlineFunction(InvokeInst *II, InlineFunctionInfo &IFI) {
  35. return InlineFunction(CallSite(II), IFI);
  36. }
  37. /// HandleCallsInBlockInlinedThroughInvoke - When we inline a basic block into
  38. /// an invoke, we have to turn all of the calls that can throw into
  39. /// invokes. This function analyze BB to see if there are any calls, and if so,
  40. /// it rewrites them to be invokes that jump to InvokeDest and fills in the PHI
  41. /// nodes in that block with the values specified in InvokeDestPHIValues.
  42. ///
  43. static void HandleCallsInBlockInlinedThroughInvoke(BasicBlock *BB,
  44. BasicBlock *InvokeDest,
  45. const SmallVectorImpl<Value*> &InvokeDestPHIValues) {
  46. for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
  47. Instruction *I = BBI++;
  48. // We only need to check for function calls: inlined invoke
  49. // instructions require no special handling.
  50. CallInst *CI = dyn_cast<CallInst>(I);
  51. if (CI == 0) continue;
  52. // If this call cannot unwind, don't convert it to an invoke.
  53. if (CI->doesNotThrow())
  54. continue;
  55. // Convert this function call into an invoke instruction.
  56. // First, split the basic block.
  57. BasicBlock *Split = BB->splitBasicBlock(CI, CI->getName()+".noexc");
  58. // Next, create the new invoke instruction, inserting it at the end
  59. // of the old basic block.
  60. ImmutableCallSite CS(CI);
  61. SmallVector<Value*, 8> InvokeArgs(CS.arg_begin(), CS.arg_end());
  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, because it uses a WeakVH.
  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. ValueToValueMapTy &VMap,
  153. InlineFunctionInfo &IFI) {
  154. CallGraph &CG = *IFI.CG;
  155. const Function *Caller = CS.getInstruction()->getParent()->getParent();
  156. const Function *Callee = CS.getCalledFunction();
  157. CallGraphNode *CalleeNode = CG[Callee];
  158. CallGraphNode *CallerNode = CG[Caller];
  159. // Since we inlined some uninlined call sites in the callee into the caller,
  160. // add edges from the caller to all of the callees of the callee.
  161. CallGraphNode::iterator I = CalleeNode->begin(), E = CalleeNode->end();
  162. // Consider the case where CalleeNode == CallerNode.
  163. CallGraphNode::CalledFunctionsVector CallCache;
  164. if (CalleeNode == CallerNode) {
  165. CallCache.assign(I, E);
  166. I = CallCache.begin();
  167. E = CallCache.end();
  168. }
  169. for (; I != E; ++I) {
  170. const Value *OrigCall = I->first;
  171. ValueToValueMapTy::iterator VMI = VMap.find(OrigCall);
  172. // Only copy the edge if the call was inlined!
  173. if (VMI == VMap.end() || VMI->second == 0)
  174. continue;
  175. // If the call was inlined, but then constant folded, there is no edge to
  176. // add. Check for this case.
  177. Instruction *NewCall = dyn_cast<Instruction>(VMI->second);
  178. if (NewCall == 0) continue;
  179. // Remember that this call site got inlined for the client of
  180. // InlineFunction.
  181. IFI.InlinedCalls.push_back(NewCall);
  182. // It's possible that inlining the callsite will cause it to go from an
  183. // indirect to a direct call by resolving a function pointer. If this
  184. // happens, set the callee of the new call site to a more precise
  185. // destination. This can also happen if the call graph node of the caller
  186. // was just unnecessarily imprecise.
  187. if (I->second->getFunction() == 0)
  188. if (Function *F = CallSite(NewCall).getCalledFunction()) {
  189. // Indirect call site resolved to direct call.
  190. CallerNode->addCalledFunction(CallSite(NewCall), CG[F]);
  191. continue;
  192. }
  193. CallerNode->addCalledFunction(CallSite(NewCall), I->second);
  194. }
  195. // Update the call graph by deleting the edge from Callee to Caller. We must
  196. // do this after the loop above in case Caller and Callee are the same.
  197. CallerNode->removeCallEdgeFor(CS);
  198. }
  199. /// HandleByValArgument - When inlining a call site that has a byval argument,
  200. /// we have to make the implicit memcpy explicit by adding it.
  201. static Value *HandleByValArgument(Value *Arg, Instruction *TheCall,
  202. const Function *CalledFunc,
  203. InlineFunctionInfo &IFI,
  204. unsigned ByValAlignment) {
  205. const Type *AggTy = cast<PointerType>(Arg->getType())->getElementType();
  206. // If the called function is readonly, then it could not mutate the caller's
  207. // copy of the byval'd memory. In this case, it is safe to elide the copy and
  208. // temporary.
  209. if (CalledFunc->onlyReadsMemory()) {
  210. // If the byval argument has a specified alignment that is greater than the
  211. // passed in pointer, then we either have to round up the input pointer or
  212. // give up on this transformation.
  213. if (ByValAlignment <= 1) // 0 = unspecified, 1 = no particular alignment.
  214. return Arg;
  215. // If the pointer is already known to be sufficiently aligned, or if we can
  216. // round it up to a larger alignment, then we don't need a temporary.
  217. if (getOrEnforceKnownAlignment(Arg, ByValAlignment,
  218. IFI.TD) >= ByValAlignment)
  219. return Arg;
  220. // Otherwise, we have to make a memcpy to get a safe alignment. This is bad
  221. // for code quality, but rarely happens and is required for correctness.
  222. }
  223. LLVMContext &Context = Arg->getContext();
  224. const Type *VoidPtrTy = Type::getInt8PtrTy(Context);
  225. // Create the alloca. If we have TargetData, use nice alignment.
  226. unsigned Align = 1;
  227. if (IFI.TD)
  228. Align = IFI.TD->getPrefTypeAlignment(AggTy);
  229. // If the byval had an alignment specified, we *must* use at least that
  230. // alignment, as it is required by the byval argument (and uses of the
  231. // pointer inside the callee).
  232. Align = std::max(Align, ByValAlignment);
  233. Function *Caller = TheCall->getParent()->getParent();
  234. Value *NewAlloca = new AllocaInst(AggTy, 0, Align, Arg->getName(),
  235. &*Caller->begin()->begin());
  236. // Emit a memcpy.
  237. const Type *Tys[3] = {VoidPtrTy, VoidPtrTy, Type::getInt64Ty(Context)};
  238. Function *MemCpyFn = Intrinsic::getDeclaration(Caller->getParent(),
  239. Intrinsic::memcpy,
  240. Tys, 3);
  241. Value *DestCast = new BitCastInst(NewAlloca, VoidPtrTy, "tmp", TheCall);
  242. Value *SrcCast = new BitCastInst(Arg, VoidPtrTy, "tmp", TheCall);
  243. Value *Size;
  244. if (IFI.TD == 0)
  245. Size = ConstantExpr::getSizeOf(AggTy);
  246. else
  247. Size = ConstantInt::get(Type::getInt64Ty(Context),
  248. IFI.TD->getTypeStoreSize(AggTy));
  249. // Always generate a memcpy of alignment 1 here because we don't know
  250. // the alignment of the src pointer. Other optimizations can infer
  251. // better alignment.
  252. Value *CallArgs[] = {
  253. DestCast, SrcCast, Size,
  254. ConstantInt::get(Type::getInt32Ty(Context), 1),
  255. ConstantInt::getFalse(Context) // isVolatile
  256. };
  257. CallInst *TheMemCpy =
  258. CallInst::Create(MemCpyFn, CallArgs, CallArgs+5, "", TheCall);
  259. // If we have a call graph, update it.
  260. if (CallGraph *CG = IFI.CG) {
  261. CallGraphNode *MemCpyCGN = CG->getOrInsertFunction(MemCpyFn);
  262. CallGraphNode *CallerNode = (*CG)[Caller];
  263. CallerNode->addCalledFunction(TheMemCpy, MemCpyCGN);
  264. }
  265. // Uses of the argument in the function should use our new alloca
  266. // instead.
  267. return NewAlloca;
  268. }
  269. // InlineFunction - This function inlines the called function into the basic
  270. // block of the caller. This returns false if it is not possible to inline this
  271. // call. The program is still in a well defined state if this occurs though.
  272. //
  273. // Note that this only does one level of inlining. For example, if the
  274. // instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now
  275. // exists in the instruction stream. Similiarly this will inline a recursive
  276. // function by one level.
  277. //
  278. bool llvm::InlineFunction(CallSite CS, InlineFunctionInfo &IFI) {
  279. Instruction *TheCall = CS.getInstruction();
  280. LLVMContext &Context = TheCall->getContext();
  281. assert(TheCall->getParent() && TheCall->getParent()->getParent() &&
  282. "Instruction not in function!");
  283. // If IFI has any state in it, zap it before we fill it in.
  284. IFI.reset();
  285. const Function *CalledFunc = CS.getCalledFunction();
  286. if (CalledFunc == 0 || // Can't inline external function or indirect
  287. CalledFunc->isDeclaration() || // call, or call to a vararg function!
  288. CalledFunc->getFunctionType()->isVarArg()) return false;
  289. // If the call to the callee is not a tail call, we must clear the 'tail'
  290. // flags on any calls that we inline.
  291. bool MustClearTailCallFlags =
  292. !(isa<CallInst>(TheCall) && cast<CallInst>(TheCall)->isTailCall());
  293. // If the call to the callee cannot throw, set the 'nounwind' flag on any
  294. // calls that we inline.
  295. bool MarkNoUnwind = CS.doesNotThrow();
  296. BasicBlock *OrigBB = TheCall->getParent();
  297. Function *Caller = OrigBB->getParent();
  298. // GC poses two hazards to inlining, which only occur when the callee has GC:
  299. // 1. If the caller has no GC, then the callee's GC must be propagated to the
  300. // caller.
  301. // 2. If the caller has a differing GC, it is invalid to inline.
  302. if (CalledFunc->hasGC()) {
  303. if (!Caller->hasGC())
  304. Caller->setGC(CalledFunc->getGC());
  305. else if (CalledFunc->getGC() != Caller->getGC())
  306. return false;
  307. }
  308. // Get an iterator to the last basic block in the function, which will have
  309. // the new function inlined after it.
  310. //
  311. Function::iterator LastBlock = &Caller->back();
  312. // Make sure to capture all of the return instructions from the cloned
  313. // function.
  314. SmallVector<ReturnInst*, 8> Returns;
  315. ClonedCodeInfo InlinedFunctionInfo;
  316. Function::iterator FirstNewBlock;
  317. { // Scope to destroy VMap after cloning.
  318. ValueToValueMapTy VMap;
  319. assert(CalledFunc->arg_size() == CS.arg_size() &&
  320. "No varargs calls can be inlined!");
  321. // Calculate the vector of arguments to pass into the function cloner, which
  322. // matches up the formal to the actual argument values.
  323. CallSite::arg_iterator AI = CS.arg_begin();
  324. unsigned ArgNo = 0;
  325. for (Function::const_arg_iterator I = CalledFunc->arg_begin(),
  326. E = CalledFunc->arg_end(); I != E; ++I, ++AI, ++ArgNo) {
  327. Value *ActualArg = *AI;
  328. // When byval arguments actually inlined, we need to make the copy implied
  329. // by them explicit. However, we don't do this if the callee is readonly
  330. // or readnone, because the copy would be unneeded: the callee doesn't
  331. // modify the struct.
  332. if (CalledFunc->paramHasAttr(ArgNo+1, Attribute::ByVal)) {
  333. ActualArg = HandleByValArgument(ActualArg, TheCall, CalledFunc, IFI,
  334. CalledFunc->getParamAlignment(ArgNo+1));
  335. // Calls that we inline may use the new alloca, so we need to clear
  336. // their 'tail' flags if HandleByValArgument introduced a new alloca and
  337. // the callee has calls.
  338. MustClearTailCallFlags |= ActualArg != *AI;
  339. }
  340. VMap[I] = ActualArg;
  341. }
  342. // We want the inliner to prune the code as it copies. We would LOVE to
  343. // have no dead or constant instructions leftover after inlining occurs
  344. // (which can happen, e.g., because an argument was constant), but we'll be
  345. // happy with whatever the cloner can do.
  346. CloneAndPruneFunctionInto(Caller, CalledFunc, VMap,
  347. /*ModuleLevelChanges=*/false, Returns, ".i",
  348. &InlinedFunctionInfo, IFI.TD, TheCall);
  349. // Remember the first block that is newly cloned over.
  350. FirstNewBlock = LastBlock; ++FirstNewBlock;
  351. // Update the callgraph if requested.
  352. if (IFI.CG)
  353. UpdateCallGraphAfterInlining(CS, FirstNewBlock, VMap, IFI);
  354. }
  355. // If there are any alloca instructions in the block that used to be the entry
  356. // block for the callee, move them to the entry block of the caller. First
  357. // calculate which instruction they should be inserted before. We insert the
  358. // instructions at the end of the current alloca list.
  359. //
  360. {
  361. BasicBlock::iterator InsertPoint = Caller->begin()->begin();
  362. for (BasicBlock::iterator I = FirstNewBlock->begin(),
  363. E = FirstNewBlock->end(); I != E; ) {
  364. AllocaInst *AI = dyn_cast<AllocaInst>(I++);
  365. if (AI == 0) continue;
  366. // If the alloca is now dead, remove it. This often occurs due to code
  367. // specialization.
  368. if (AI->use_empty()) {
  369. AI->eraseFromParent();
  370. continue;
  371. }
  372. if (!isa<Constant>(AI->getArraySize()))
  373. continue;
  374. // Keep track of the static allocas that we inline into the caller.
  375. IFI.StaticAllocas.push_back(AI);
  376. // Scan for the block of allocas that we can move over, and move them
  377. // all at once.
  378. while (isa<AllocaInst>(I) &&
  379. isa<Constant>(cast<AllocaInst>(I)->getArraySize())) {
  380. IFI.StaticAllocas.push_back(cast<AllocaInst>(I));
  381. ++I;
  382. }
  383. // Transfer all of the allocas over in a block. Using splice means
  384. // that the instructions aren't removed from the symbol table, then
  385. // reinserted.
  386. Caller->getEntryBlock().getInstList().splice(InsertPoint,
  387. FirstNewBlock->getInstList(),
  388. AI, I);
  389. }
  390. }
  391. // If the inlined code contained dynamic alloca instructions, wrap the inlined
  392. // code with llvm.stacksave/llvm.stackrestore intrinsics.
  393. if (InlinedFunctionInfo.ContainsDynamicAllocas) {
  394. Module *M = Caller->getParent();
  395. // Get the two intrinsics we care about.
  396. Function *StackSave = Intrinsic::getDeclaration(M, Intrinsic::stacksave);
  397. Function *StackRestore=Intrinsic::getDeclaration(M,Intrinsic::stackrestore);
  398. // If we are preserving the callgraph, add edges to the stacksave/restore
  399. // functions for the calls we insert.
  400. CallGraphNode *StackSaveCGN = 0, *StackRestoreCGN = 0, *CallerNode = 0;
  401. if (CallGraph *CG = IFI.CG) {
  402. StackSaveCGN = CG->getOrInsertFunction(StackSave);
  403. StackRestoreCGN = CG->getOrInsertFunction(StackRestore);
  404. CallerNode = (*CG)[Caller];
  405. }
  406. // Insert the llvm.stacksave.
  407. CallInst *SavedPtr = CallInst::Create(StackSave, "savedstack",
  408. FirstNewBlock->begin());
  409. if (IFI.CG) CallerNode->addCalledFunction(SavedPtr, StackSaveCGN);
  410. // Insert a call to llvm.stackrestore before any return instructions in the
  411. // inlined function.
  412. for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
  413. CallInst *CI = CallInst::Create(StackRestore, SavedPtr, "", Returns[i]);
  414. if (IFI.CG) CallerNode->addCalledFunction(CI, StackRestoreCGN);
  415. }
  416. // Count the number of StackRestore calls we insert.
  417. unsigned NumStackRestores = Returns.size();
  418. // If we are inlining an invoke instruction, insert restores before each
  419. // unwind. These unwinds will be rewritten into branches later.
  420. if (InlinedFunctionInfo.ContainsUnwinds && isa<InvokeInst>(TheCall)) {
  421. for (Function::iterator BB = FirstNewBlock, E = Caller->end();
  422. BB != E; ++BB)
  423. if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
  424. CallInst *CI = CallInst::Create(StackRestore, SavedPtr, "", UI);
  425. if (IFI.CG) CallerNode->addCalledFunction(CI, StackRestoreCGN);
  426. ++NumStackRestores;
  427. }
  428. }
  429. }
  430. // If we are inlining tail call instruction through a call site that isn't
  431. // marked 'tail', we must remove the tail marker for any calls in the inlined
  432. // code. Also, calls inlined through a 'nounwind' call site should be marked
  433. // 'nounwind'.
  434. if (InlinedFunctionInfo.ContainsCalls &&
  435. (MustClearTailCallFlags || MarkNoUnwind)) {
  436. for (Function::iterator BB = FirstNewBlock, E = Caller->end();
  437. BB != E; ++BB)
  438. for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
  439. if (CallInst *CI = dyn_cast<CallInst>(I)) {
  440. if (MustClearTailCallFlags)
  441. CI->setTailCall(false);
  442. if (MarkNoUnwind)
  443. CI->setDoesNotThrow();
  444. }
  445. }
  446. // If we are inlining through a 'nounwind' call site then any inlined 'unwind'
  447. // instructions are unreachable.
  448. if (InlinedFunctionInfo.ContainsUnwinds && MarkNoUnwind)
  449. for (Function::iterator BB = FirstNewBlock, E = Caller->end();
  450. BB != E; ++BB) {
  451. TerminatorInst *Term = BB->getTerminator();
  452. if (isa<UnwindInst>(Term)) {
  453. new UnreachableInst(Context, Term);
  454. BB->getInstList().erase(Term);
  455. }
  456. }
  457. // If we are inlining for an invoke instruction, we must make sure to rewrite
  458. // any inlined 'unwind' instructions into branches to the invoke exception
  459. // destination, and call instructions into invoke instructions.
  460. if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall))
  461. HandleInlinedInvoke(II, FirstNewBlock, InlinedFunctionInfo);
  462. // If we cloned in _exactly one_ basic block, and if that block ends in a
  463. // return instruction, we splice the body of the inlined callee directly into
  464. // the calling basic block.
  465. if (Returns.size() == 1 && std::distance(FirstNewBlock, Caller->end()) == 1) {
  466. // Move all of the instructions right before the call.
  467. OrigBB->getInstList().splice(TheCall, FirstNewBlock->getInstList(),
  468. FirstNewBlock->begin(), FirstNewBlock->end());
  469. // Remove the cloned basic block.
  470. Caller->getBasicBlockList().pop_back();
  471. // If the call site was an invoke instruction, add a branch to the normal
  472. // destination.
  473. if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall))
  474. BranchInst::Create(II->getNormalDest(), TheCall);
  475. // If the return instruction returned a value, replace uses of the call with
  476. // uses of the returned value.
  477. if (!TheCall->use_empty()) {
  478. ReturnInst *R = Returns[0];
  479. if (TheCall == R->getReturnValue())
  480. TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
  481. else
  482. TheCall->replaceAllUsesWith(R->getReturnValue());
  483. }
  484. // Since we are now done with the Call/Invoke, we can delete it.
  485. TheCall->eraseFromParent();
  486. // Since we are now done with the return instruction, delete it also.
  487. Returns[0]->eraseFromParent();
  488. // We are now done with the inlining.
  489. return true;
  490. }
  491. // Otherwise, we have the normal case, of more than one block to inline or
  492. // multiple return sites.
  493. // We want to clone the entire callee function into the hole between the
  494. // "starter" and "ender" blocks. How we accomplish this depends on whether
  495. // this is an invoke instruction or a call instruction.
  496. BasicBlock *AfterCallBB;
  497. if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
  498. // Add an unconditional branch to make this look like the CallInst case...
  499. BranchInst *NewBr = BranchInst::Create(II->getNormalDest(), TheCall);
  500. // Split the basic block. This guarantees that no PHI nodes will have to be
  501. // updated due to new incoming edges, and make the invoke case more
  502. // symmetric to the call case.
  503. AfterCallBB = OrigBB->splitBasicBlock(NewBr,
  504. CalledFunc->getName()+".exit");
  505. } else { // It's a call
  506. // If this is a call instruction, we need to split the basic block that
  507. // the call lives in.
  508. //
  509. AfterCallBB = OrigBB->splitBasicBlock(TheCall,
  510. CalledFunc->getName()+".exit");
  511. }
  512. // Change the branch that used to go to AfterCallBB to branch to the first
  513. // basic block of the inlined function.
  514. //
  515. TerminatorInst *Br = OrigBB->getTerminator();
  516. assert(Br && Br->getOpcode() == Instruction::Br &&
  517. "splitBasicBlock broken!");
  518. Br->setOperand(0, FirstNewBlock);
  519. // Now that the function is correct, make it a little bit nicer. In
  520. // particular, move the basic blocks inserted from the end of the function
  521. // into the space made by splitting the source basic block.
  522. Caller->getBasicBlockList().splice(AfterCallBB, Caller->getBasicBlockList(),
  523. FirstNewBlock, Caller->end());
  524. // Handle all of the return instructions that we just cloned in, and eliminate
  525. // any users of the original call/invoke instruction.
  526. const Type *RTy = CalledFunc->getReturnType();
  527. PHINode *PHI = 0;
  528. if (Returns.size() > 1) {
  529. // The PHI node should go at the front of the new basic block to merge all
  530. // possible incoming values.
  531. if (!TheCall->use_empty()) {
  532. PHI = PHINode::Create(RTy, TheCall->getName(),
  533. AfterCallBB->begin());
  534. PHI->reserveOperandSpace(Returns.size());
  535. // Anything that used the result of the function call should now use the
  536. // PHI node as their operand.
  537. TheCall->replaceAllUsesWith(PHI);
  538. }
  539. // Loop over all of the return instructions adding entries to the PHI node
  540. // as appropriate.
  541. if (PHI) {
  542. for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
  543. ReturnInst *RI = Returns[i];
  544. assert(RI->getReturnValue()->getType() == PHI->getType() &&
  545. "Ret value not consistent in function!");
  546. PHI->addIncoming(RI->getReturnValue(), RI->getParent());
  547. }
  548. }
  549. // Add a branch to the merge points and remove return instructions.
  550. for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
  551. ReturnInst *RI = Returns[i];
  552. BranchInst::Create(AfterCallBB, RI);
  553. RI->eraseFromParent();
  554. }
  555. } else if (!Returns.empty()) {
  556. // Otherwise, if there is exactly one return value, just replace anything
  557. // using the return value of the call with the computed value.
  558. if (!TheCall->use_empty()) {
  559. if (TheCall == Returns[0]->getReturnValue())
  560. TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
  561. else
  562. TheCall->replaceAllUsesWith(Returns[0]->getReturnValue());
  563. }
  564. // Splice the code from the return block into the block that it will return
  565. // to, which contains the code that was after the call.
  566. BasicBlock *ReturnBB = Returns[0]->getParent();
  567. AfterCallBB->getInstList().splice(AfterCallBB->begin(),
  568. ReturnBB->getInstList());
  569. // Update PHI nodes that use the ReturnBB to use the AfterCallBB.
  570. ReturnBB->replaceAllUsesWith(AfterCallBB);
  571. // Delete the return instruction now and empty ReturnBB now.
  572. Returns[0]->eraseFromParent();
  573. ReturnBB->eraseFromParent();
  574. } else if (!TheCall->use_empty()) {
  575. // No returns, but something is using the return value of the call. Just
  576. // nuke the result.
  577. TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
  578. }
  579. // Since we are now done with the Call/Invoke, we can delete it.
  580. TheCall->eraseFromParent();
  581. // We should always be able to fold the entry block of the function into the
  582. // single predecessor of the block...
  583. assert(cast<BranchInst>(Br)->isUnconditional() && "splitBasicBlock broken!");
  584. BasicBlock *CalleeEntry = cast<BranchInst>(Br)->getSuccessor(0);
  585. // Splice the code entry block into calling block, right before the
  586. // unconditional branch.
  587. OrigBB->getInstList().splice(Br, CalleeEntry->getInstList());
  588. CalleeEntry->replaceAllUsesWith(OrigBB); // Update PHI nodes
  589. // Remove the unconditional branch.
  590. OrigBB->getInstList().erase(Br);
  591. // Now we can remove the CalleeEntry block, which is now empty.
  592. Caller->getBasicBlockList().erase(CalleeEntry);
  593. // If we inserted a phi node, check to see if it has a single value (e.g. all
  594. // the entries are the same or undef). If so, remove the PHI so it doesn't
  595. // block other optimizations.
  596. if (PHI)
  597. if (Value *V = SimplifyInstruction(PHI, IFI.TD)) {
  598. PHI->replaceAllUsesWith(V);
  599. PHI->eraseFromParent();
  600. }
  601. return true;
  602. }