InlineFunction.cpp revision 824b958e6fb1236e92e4d07f3acf18fca107cdc0
1ca398dc3989d35e8516489fd163e012133bd41cbChris Lattner//===- InlineFunction.cpp - Code to perform function inlining -------------===//
2fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman//
3b576c94c15af9a440f69d9d03c2afead7971118cJohn Criswell//                     The LLVM Compiler Infrastructure
4b576c94c15af9a440f69d9d03c2afead7971118cJohn Criswell//
54ee451de366474b9c228b4e5fa573795a715216dChris Lattner// This file is distributed under the University of Illinois Open Source
64ee451de366474b9c228b4e5fa573795a715216dChris Lattner// License. See LICENSE.TXT for details.
7fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman//
8b576c94c15af9a440f69d9d03c2afead7971118cJohn Criswell//===----------------------------------------------------------------------===//
9ca398dc3989d35e8516489fd163e012133bd41cbChris Lattner//
10ca398dc3989d35e8516489fd163e012133bd41cbChris Lattner// This file implements inlining of a function into a call site, resolving
11ca398dc3989d35e8516489fd163e012133bd41cbChris Lattner// parameters and the return value as appropriate.
12ca398dc3989d35e8516489fd163e012133bd41cbChris Lattner//
13ca398dc3989d35e8516489fd163e012133bd41cbChris Lattner//===----------------------------------------------------------------------===//
14ca398dc3989d35e8516489fd163e012133bd41cbChris Lattner
15ca398dc3989d35e8516489fd163e012133bd41cbChris Lattner#include "llvm/Transforms/Utils/Cloning.h"
163787e765facfad5ea62753922d940bcdd52afd57Chris Lattner#include "llvm/Constants.h"
177152c237b46a920b29d5605af934766b8f9a07a1Chris Lattner#include "llvm/DerivedTypes.h"
18ca398dc3989d35e8516489fd163e012133bd41cbChris Lattner#include "llvm/Module.h"
1980a38d245359cb0a3be8f78f5d7d911232886b9aChris Lattner#include "llvm/Instructions.h"
2080a38d245359cb0a3be8f78f5d7d911232886b9aChris Lattner#include "llvm/Intrinsics.h"
21eaf42abab6d465c38891345d999255871cf03943Devang Patel#include "llvm/Attributes.h"
22468fb1df7db466e5682ee44341c3990b599e8d6aChris Lattner#include "llvm/Analysis/CallGraph.h"
23c93adca35856d0eaae088e52ba30cfefbd7ad910Chris Lattner#include "llvm/Target/TargetData.h"
2493e985f1b17aef62d58e3198a4604f9f6cfe8d19Chris Lattner#include "llvm/ADT/SmallVector.h"
25641ca93cff0f957fc5fb9dfb05d2a4a340aa8af7Devang Patel#include "llvm/ADT/StringExtras.h"
2680a38d245359cb0a3be8f78f5d7d911232886b9aChris Lattner#include "llvm/Support/CallSite.h"
27f7703df4968084c18c248c1feea9961c19a32e6aChris Lattnerusing namespace llvm;
28ca398dc3989d35e8516489fd163e012133bd41cbChris Lattner
291dfdf8255e803d6376f5fe94a113f892e796ae6cChris Lattnerbool llvm::InlineFunction(CallInst *CI, CallGraph *CG, const TargetData *TD) {
301dfdf8255e803d6376f5fe94a113f892e796ae6cChris Lattner  return InlineFunction(CallSite(CI), CG, TD);
31468fb1df7db466e5682ee44341c3990b599e8d6aChris Lattner}
321dfdf8255e803d6376f5fe94a113f892e796ae6cChris Lattnerbool llvm::InlineFunction(InvokeInst *II, CallGraph *CG, const TargetData *TD) {
331dfdf8255e803d6376f5fe94a113f892e796ae6cChris Lattner  return InlineFunction(CallSite(II), CG, TD);
34468fb1df7db466e5682ee44341c3990b599e8d6aChris Lattner}
3580a38d245359cb0a3be8f78f5d7d911232886b9aChris Lattner
36cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner/// HandleInlinedInvoke - If we inlined an invoke site, we need to convert calls
37cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner/// in the body of the inlined function into invokes and turn unwind
38cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner/// instructions into branches to the invoke unwind dest.
39cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner///
40cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner/// II is the invoke instruction begin inlined.  FirstNewBlock is the first
41cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner/// block of the inlined code (the last block is the end of the function),
42cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner/// and InlineCodeInfo is information about the code that got inlined.
43cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattnerstatic void HandleInlinedInvoke(InvokeInst *II, BasicBlock *FirstNewBlock,
44cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner                                ClonedCodeInfo &InlinedCodeInfo) {
45cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner  BasicBlock *InvokeDest = II->getUnwindDest();
46cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner  std::vector<Value*> InvokeDestPHIValues;
47cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner
48cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner  // If there are PHI nodes in the unwind destination block, we need to
49cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner  // keep track of which values came into them from this invoke, then remove
50cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner  // the entry for this block.
51cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner  BasicBlock *InvokeBlock = II->getParent();
52cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner  for (BasicBlock::iterator I = InvokeDest->begin(); isa<PHINode>(I); ++I) {
53cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner    PHINode *PN = cast<PHINode>(I);
54cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner    // Save the value to use for this edge.
55cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner    InvokeDestPHIValues.push_back(PN->getIncomingValueForBlock(InvokeBlock));
56cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner  }
57cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner
58cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner  Function *Caller = FirstNewBlock->getParent();
59a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands
60cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner  // The inlined code is currently at the end of the function, scan from the
61cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner  // start of the inlined code to its end, checking for stuff we need to
62cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner  // rewrite.
63727d1dd58793447e83ade712f0e58172f156edcfChris Lattner  if (InlinedCodeInfo.ContainsCalls || InlinedCodeInfo.ContainsUnwinds) {
64727d1dd58793447e83ade712f0e58172f156edcfChris Lattner    for (Function::iterator BB = FirstNewBlock, E = Caller->end();
65727d1dd58793447e83ade712f0e58172f156edcfChris Lattner         BB != E; ++BB) {
66727d1dd58793447e83ade712f0e58172f156edcfChris Lattner      if (InlinedCodeInfo.ContainsCalls) {
67727d1dd58793447e83ade712f0e58172f156edcfChris Lattner        for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ){
68727d1dd58793447e83ade712f0e58172f156edcfChris Lattner          Instruction *I = BBI++;
69a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands
70727d1dd58793447e83ade712f0e58172f156edcfChris Lattner          // We only need to check for function calls: inlined invoke
71727d1dd58793447e83ade712f0e58172f156edcfChris Lattner          // instructions require no special handling.
72727d1dd58793447e83ade712f0e58172f156edcfChris Lattner          if (!isa<CallInst>(I)) continue;
73727d1dd58793447e83ade712f0e58172f156edcfChris Lattner          CallInst *CI = cast<CallInst>(I);
74cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner
75fd7b326bea39c077eea8d378156bcf09051cc4ecDuncan Sands          // If this call cannot unwind, don't convert it to an invoke.
762b0e8990ab33ec2dad21286d3ce01dbb4bbe63c1Duncan Sands          if (CI->doesNotThrow())
77727d1dd58793447e83ade712f0e58172f156edcfChris Lattner            continue;
78a3355ffb3d30d19d226bbb75707991c60f236e37Duncan Sands
79727d1dd58793447e83ade712f0e58172f156edcfChris Lattner          // Convert this function call into an invoke instruction.
80727d1dd58793447e83ade712f0e58172f156edcfChris Lattner          // First, split the basic block.
81727d1dd58793447e83ade712f0e58172f156edcfChris Lattner          BasicBlock *Split = BB->splitBasicBlock(CI, CI->getName()+".noexc");
82a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands
83727d1dd58793447e83ade712f0e58172f156edcfChris Lattner          // Next, create the new invoke instruction, inserting it at the end
84727d1dd58793447e83ade712f0e58172f156edcfChris Lattner          // of the old basic block.
8593e985f1b17aef62d58e3198a4604f9f6cfe8d19Chris Lattner          SmallVector<Value*, 8> InvokeArgs(CI->op_begin()+1, CI->op_end());
86727d1dd58793447e83ade712f0e58172f156edcfChris Lattner          InvokeInst *II =
87051a950000e21935165db56695e35bade668193bGabor Greif            InvokeInst::Create(CI->getCalledValue(), Split, InvokeDest,
88051a950000e21935165db56695e35bade668193bGabor Greif                               InvokeArgs.begin(), InvokeArgs.end(),
89051a950000e21935165db56695e35bade668193bGabor Greif                               CI->getName(), BB->getTerminator());
90727d1dd58793447e83ade712f0e58172f156edcfChris Lattner          II->setCallingConv(CI->getCallingConv());
910598866c052147c31b808391f58434ce3dbfb838Devang Patel          II->setAttributes(CI->getAttributes());
92a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands
93727d1dd58793447e83ade712f0e58172f156edcfChris Lattner          // Make sure that anything using the call now uses the invoke!
94727d1dd58793447e83ade712f0e58172f156edcfChris Lattner          CI->replaceAllUsesWith(II);
95a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands
96727d1dd58793447e83ade712f0e58172f156edcfChris Lattner          // Delete the unconditional branch inserted by splitBasicBlock
97727d1dd58793447e83ade712f0e58172f156edcfChris Lattner          BB->getInstList().pop_back();
98727d1dd58793447e83ade712f0e58172f156edcfChris Lattner          Split->getInstList().pop_front();  // Delete the original call
99a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands
100727d1dd58793447e83ade712f0e58172f156edcfChris Lattner          // Update any PHI nodes in the exceptional block to indicate that
101727d1dd58793447e83ade712f0e58172f156edcfChris Lattner          // there is now a new entry in them.
102727d1dd58793447e83ade712f0e58172f156edcfChris Lattner          unsigned i = 0;
103727d1dd58793447e83ade712f0e58172f156edcfChris Lattner          for (BasicBlock::iterator I = InvokeDest->begin();
104727d1dd58793447e83ade712f0e58172f156edcfChris Lattner               isa<PHINode>(I); ++I, ++i) {
105727d1dd58793447e83ade712f0e58172f156edcfChris Lattner            PHINode *PN = cast<PHINode>(I);
106727d1dd58793447e83ade712f0e58172f156edcfChris Lattner            PN->addIncoming(InvokeDestPHIValues[i], BB);
107727d1dd58793447e83ade712f0e58172f156edcfChris Lattner          }
108a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands
109727d1dd58793447e83ade712f0e58172f156edcfChris Lattner          // This basic block is now complete, start scanning the next one.
110727d1dd58793447e83ade712f0e58172f156edcfChris Lattner          break;
111727d1dd58793447e83ade712f0e58172f156edcfChris Lattner        }
112cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner      }
113a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands
114727d1dd58793447e83ade712f0e58172f156edcfChris Lattner      if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
115727d1dd58793447e83ade712f0e58172f156edcfChris Lattner        // An UnwindInst requires special handling when it gets inlined into an
116727d1dd58793447e83ade712f0e58172f156edcfChris Lattner        // invoke site.  Once this happens, we know that the unwind would cause
117727d1dd58793447e83ade712f0e58172f156edcfChris Lattner        // a control transfer to the invoke exception destination, so we can
118727d1dd58793447e83ade712f0e58172f156edcfChris Lattner        // transform it into a direct branch to the exception destination.
119051a950000e21935165db56695e35bade668193bGabor Greif        BranchInst::Create(InvokeDest, UI);
120a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands
121727d1dd58793447e83ade712f0e58172f156edcfChris Lattner        // Delete the unwind instruction!
1221adec83ae84031bfa9f0bf209c5ee6c64906a1ffDan Gohman        UI->eraseFromParent();
123a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands
124727d1dd58793447e83ade712f0e58172f156edcfChris Lattner        // Update any PHI nodes in the exceptional block to indicate that
125727d1dd58793447e83ade712f0e58172f156edcfChris Lattner        // there is now a new entry in them.
126727d1dd58793447e83ade712f0e58172f156edcfChris Lattner        unsigned i = 0;
127727d1dd58793447e83ade712f0e58172f156edcfChris Lattner        for (BasicBlock::iterator I = InvokeDest->begin();
128727d1dd58793447e83ade712f0e58172f156edcfChris Lattner             isa<PHINode>(I); ++I, ++i) {
129727d1dd58793447e83ade712f0e58172f156edcfChris Lattner          PHINode *PN = cast<PHINode>(I);
130727d1dd58793447e83ade712f0e58172f156edcfChris Lattner          PN->addIncoming(InvokeDestPHIValues[i], BB);
131727d1dd58793447e83ade712f0e58172f156edcfChris Lattner        }
132cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner      }
133cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner    }
134cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner  }
135cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner
136cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner  // Now that everything is happy, we have one final detail.  The PHI nodes in
137cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner  // the exception destination block still have entries due to the original
138cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner  // invoke instruction.  Eliminate these entries (which might even delete the
139cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner  // PHI node) now.
140cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner  InvokeDest->removePredecessor(II->getParent());
141cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner}
142cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner
143d85340f4ec587e22b0239617f3b747a6df113894Chris Lattner/// UpdateCallGraphAfterInlining - Once we have cloned code over from a callee
144d85340f4ec587e22b0239617f3b747a6df113894Chris Lattner/// into the caller, update the specified callgraph to reflect the changes we
145d85340f4ec587e22b0239617f3b747a6df113894Chris Lattner/// made.  Note that it's possible that not all code was copied over, so only
146d7b9851c4e634ed3599b1a4c70b1c76c90a11686Duncan Sands/// some edges of the callgraph may remain.
147d7b9851c4e634ed3599b1a4c70b1c76c90a11686Duncan Sandsstatic void UpdateCallGraphAfterInlining(CallSite CS,
148d85340f4ec587e22b0239617f3b747a6df113894Chris Lattner                                         Function::iterator FirstNewBlock,
1495e665f559419c7f58a4fd9360cd488f065505c44Chris Lattner                                       DenseMap<const Value*, Value*> &ValueMap,
150468fb1df7db466e5682ee44341c3990b599e8d6aChris Lattner                                         CallGraph &CG) {
151d7b9851c4e634ed3599b1a4c70b1c76c90a11686Duncan Sands  const Function *Caller = CS.getInstruction()->getParent()->getParent();
152d7b9851c4e634ed3599b1a4c70b1c76c90a11686Duncan Sands  const Function *Callee = CS.getCalledFunction();
153d7b9851c4e634ed3599b1a4c70b1c76c90a11686Duncan Sands
154468fb1df7db466e5682ee44341c3990b599e8d6aChris Lattner  // Update the call graph by deleting the edge from Callee to Caller
155468fb1df7db466e5682ee44341c3990b599e8d6aChris Lattner  CallGraphNode *CalleeNode = CG[Callee];
156468fb1df7db466e5682ee44341c3990b599e8d6aChris Lattner  CallGraphNode *CallerNode = CG[Caller];
157d7b9851c4e634ed3599b1a4c70b1c76c90a11686Duncan Sands  CallerNode->removeCallEdgeFor(CS);
158a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands
159d85340f4ec587e22b0239617f3b747a6df113894Chris Lattner  // Since we inlined some uninlined call sites in the callee into the caller,
160468fb1df7db466e5682ee44341c3990b599e8d6aChris Lattner  // add edges from the caller to all of the callees of the callee.
161468fb1df7db466e5682ee44341c3990b599e8d6aChris Lattner  for (CallGraphNode::iterator I = CalleeNode->begin(),
162d85340f4ec587e22b0239617f3b747a6df113894Chris Lattner       E = CalleeNode->end(); I != E; ++I) {
163d85340f4ec587e22b0239617f3b747a6df113894Chris Lattner    const Instruction *OrigCall = I->first.getInstruction();
164a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands
1655e665f559419c7f58a4fd9360cd488f065505c44Chris Lattner    DenseMap<const Value*, Value*>::iterator VMI = ValueMap.find(OrigCall);
166981418bf1562d0b5b470ddc7d0034c9f3297b893Chris Lattner    // Only copy the edge if the call was inlined!
167981418bf1562d0b5b470ddc7d0034c9f3297b893Chris Lattner    if (VMI != ValueMap.end() && VMI->second) {
1681bb3a402574557cb228f8a96030776c229e282e5Chris Lattner      // If the call was inlined, but then constant folded, there is no edge to
1691bb3a402574557cb228f8a96030776c229e282e5Chris Lattner      // add.  Check for this case.
1701bb3a402574557cb228f8a96030776c229e282e5Chris Lattner      if (Instruction *NewCall = dyn_cast<Instruction>(VMI->second))
1711bb3a402574557cb228f8a96030776c229e282e5Chris Lattner        CallerNode->addCalledFunction(CallSite::get(NewCall), I->second);
172d85340f4ec587e22b0239617f3b747a6df113894Chris Lattner    }
173d85340f4ec587e22b0239617f3b747a6df113894Chris Lattner  }
174468fb1df7db466e5682ee44341c3990b599e8d6aChris Lattner}
175468fb1df7db466e5682ee44341c3990b599e8d6aChris Lattner
176cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner
177ca398dc3989d35e8516489fd163e012133bd41cbChris Lattner// InlineFunction - This function inlines the called function into the basic
178ca398dc3989d35e8516489fd163e012133bd41cbChris Lattner// block of the caller.  This returns false if it is not possible to inline this
179ca398dc3989d35e8516489fd163e012133bd41cbChris Lattner// call.  The program is still in a well defined state if this occurs though.
180ca398dc3989d35e8516489fd163e012133bd41cbChris Lattner//
181fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman// Note that this only does one level of inlining.  For example, if the
182fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman// instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now
183ca398dc3989d35e8516489fd163e012133bd41cbChris Lattner// exists in the instruction stream.  Similiarly this will inline a recursive
184ca398dc3989d35e8516489fd163e012133bd41cbChris Lattner// function by one level.
185ca398dc3989d35e8516489fd163e012133bd41cbChris Lattner//
1861dfdf8255e803d6376f5fe94a113f892e796ae6cChris Lattnerbool llvm::InlineFunction(CallSite CS, CallGraph *CG, const TargetData *TD) {
18780a38d245359cb0a3be8f78f5d7d911232886b9aChris Lattner  Instruction *TheCall = CS.getInstruction();
18880a38d245359cb0a3be8f78f5d7d911232886b9aChris Lattner  assert(TheCall->getParent() && TheCall->getParent()->getParent() &&
18980a38d245359cb0a3be8f78f5d7d911232886b9aChris Lattner         "Instruction not in function!");
190ca398dc3989d35e8516489fd163e012133bd41cbChris Lattner
19180a38d245359cb0a3be8f78f5d7d911232886b9aChris Lattner  const Function *CalledFunc = CS.getCalledFunction();
192ca398dc3989d35e8516489fd163e012133bd41cbChris Lattner  if (CalledFunc == 0 ||          // Can't inline external function or indirect
1935cbf985dcbc89fba3208e7baf8b6f488b06d3ec9Reid Spencer      CalledFunc->isDeclaration() || // call, or call to a vararg function!
194ca398dc3989d35e8516489fd163e012133bd41cbChris Lattner      CalledFunc->getFunctionType()->isVarArg()) return false;
195ca398dc3989d35e8516489fd163e012133bd41cbChris Lattner
1961b49141821e98e4321bfe6234c7001c836b2a289Chris Lattner
1971b49141821e98e4321bfe6234c7001c836b2a289Chris Lattner  // If the call to the callee is a non-tail call, we must clear the 'tail'
1981b49141821e98e4321bfe6234c7001c836b2a289Chris Lattner  // flags on any calls that we inline.
1991b49141821e98e4321bfe6234c7001c836b2a289Chris Lattner  bool MustClearTailCallFlags =
2003799ed83b4cb80695a81294da6a7d18cf0884f5eChris Lattner    isa<CallInst>(TheCall) && !cast<CallInst>(TheCall)->isTailCall();
2011b49141821e98e4321bfe6234c7001c836b2a289Chris Lattner
202f0c3354d998507515ab39e26b5292ea0ceb06aefDuncan Sands  // If the call to the callee cannot throw, set the 'nounwind' flag on any
203f0c3354d998507515ab39e26b5292ea0ceb06aefDuncan Sands  // calls that we inline.
204f0c3354d998507515ab39e26b5292ea0ceb06aefDuncan Sands  bool MarkNoUnwind = CS.doesNotThrow();
205f0c3354d998507515ab39e26b5292ea0ceb06aefDuncan Sands
20680a38d245359cb0a3be8f78f5d7d911232886b9aChris Lattner  BasicBlock *OrigBB = TheCall->getParent();
207ca398dc3989d35e8516489fd163e012133bd41cbChris Lattner  Function *Caller = OrigBB->getParent();
208ca398dc3989d35e8516489fd163e012133bd41cbChris Lattner
2090e13821c96937830ec817f08095c3cef1fdcac8dGordon Henriksen  // GC poses two hazards to inlining, which only occur when the callee has GC:
2100e13821c96937830ec817f08095c3cef1fdcac8dGordon Henriksen  //  1. If the caller has no GC, then the callee's GC must be propagated to the
2110e13821c96937830ec817f08095c3cef1fdcac8dGordon Henriksen  //     caller.
2120e13821c96937830ec817f08095c3cef1fdcac8dGordon Henriksen  //  2. If the caller has a differing GC, it is invalid to inline.
2135eca075b74d62c621b160aa216b4cd50829a2cc7Gordon Henriksen  if (CalledFunc->hasGC()) {
2145eca075b74d62c621b160aa216b4cd50829a2cc7Gordon Henriksen    if (!Caller->hasGC())
2155eca075b74d62c621b160aa216b4cd50829a2cc7Gordon Henriksen      Caller->setGC(CalledFunc->getGC());
2165eca075b74d62c621b160aa216b4cd50829a2cc7Gordon Henriksen    else if (CalledFunc->getGC() != Caller->getGC())
2170e13821c96937830ec817f08095c3cef1fdcac8dGordon Henriksen      return false;
2180e13821c96937830ec817f08095c3cef1fdcac8dGordon Henriksen  }
219a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands
2205052c911ec1be51ecb36e7f025c26412e9f1bfacChris Lattner  // Get an iterator to the last basic block in the function, which will have
2215052c911ec1be51ecb36e7f025c26412e9f1bfacChris Lattner  // the new function inlined after it.
2225052c911ec1be51ecb36e7f025c26412e9f1bfacChris Lattner  //
2235052c911ec1be51ecb36e7f025c26412e9f1bfacChris Lattner  Function::iterator LastBlock = &Caller->back();
2245052c911ec1be51ecb36e7f025c26412e9f1bfacChris Lattner
2255e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner  // Make sure to capture all of the return instructions from the cloned
2265e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner  // function.
2275052c911ec1be51ecb36e7f025c26412e9f1bfacChris Lattner  std::vector<ReturnInst*> Returns;
228cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner  ClonedCodeInfo InlinedFunctionInfo;
229d85340f4ec587e22b0239617f3b747a6df113894Chris Lattner  Function::iterator FirstNewBlock;
230f0c3354d998507515ab39e26b5292ea0ceb06aefDuncan Sands
2315e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner  { // Scope to destroy ValueMap after cloning.
2325e665f559419c7f58a4fd9360cd488f065505c44Chris Lattner    DenseMap<const Value*, Value*> ValueMap;
2335b5bc3032f97cfa7bfa3e22282d3a9c1ed05eec6Chris Lattner
2349614fcc640eb628cc5dfddb277ebae9f6cb61014Dan Gohman    assert(CalledFunc->arg_size() == CS.arg_size() &&
2355e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner           "No varargs calls can be inlined!");
236a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands
237c93adca35856d0eaae088e52ba30cfefbd7ad910Chris Lattner    // Calculate the vector of arguments to pass into the function cloner, which
238c93adca35856d0eaae088e52ba30cfefbd7ad910Chris Lattner    // matches up the formal to the actual argument values.
2395e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner    CallSite::arg_iterator AI = CS.arg_begin();
240c93adca35856d0eaae088e52ba30cfefbd7ad910Chris Lattner    unsigned ArgNo = 0;
241e4d5c441e04bdc00ccf1804744af670655123b07Chris Lattner    for (Function::const_arg_iterator I = CalledFunc->arg_begin(),
242c93adca35856d0eaae088e52ba30cfefbd7ad910Chris Lattner         E = CalledFunc->arg_end(); I != E; ++I, ++AI, ++ArgNo) {
243c93adca35856d0eaae088e52ba30cfefbd7ad910Chris Lattner      Value *ActualArg = *AI;
244a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands
245d82375c1c43db7f823dd4660d3495e76566699e3Duncan Sands      // When byval arguments actually inlined, we need to make the copy implied
246d82375c1c43db7f823dd4660d3495e76566699e3Duncan Sands      // by them explicit.  However, we don't do this if the callee is readonly
247d82375c1c43db7f823dd4660d3495e76566699e3Duncan Sands      // or readnone, because the copy would be unneeded: the callee doesn't
248d82375c1c43db7f823dd4660d3495e76566699e3Duncan Sands      // modify the struct.
2490598866c052147c31b808391f58434ce3dbfb838Devang Patel      if (CalledFunc->paramHasAttr(ArgNo+1, Attribute::ByVal) &&
250d82375c1c43db7f823dd4660d3495e76566699e3Duncan Sands          !CalledFunc->onlyReadsMemory()) {
251c93adca35856d0eaae088e52ba30cfefbd7ad910Chris Lattner        const Type *AggTy = cast<PointerType>(I->getType())->getElementType();
252c93adca35856d0eaae088e52ba30cfefbd7ad910Chris Lattner        const Type *VoidPtrTy = PointerType::getUnqual(Type::Int8Ty);
253a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands
254c93adca35856d0eaae088e52ba30cfefbd7ad910Chris Lattner        // Create the alloca.  If we have TargetData, use nice alignment.
255c93adca35856d0eaae088e52ba30cfefbd7ad910Chris Lattner        unsigned Align = 1;
256c93adca35856d0eaae088e52ba30cfefbd7ad910Chris Lattner        if (TD) Align = TD->getPrefTypeAlignment(AggTy);
257a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands        Value *NewAlloca = new AllocaInst(AggTy, 0, Align, I->getName(),
258c93adca35856d0eaae088e52ba30cfefbd7ad910Chris Lattner                                          Caller->begin()->begin());
259c93adca35856d0eaae088e52ba30cfefbd7ad910Chris Lattner        // Emit a memcpy.
260824b958e6fb1236e92e4d07f3acf18fca107cdc0Chris Lattner        const Type *Tys[] = { Type::Int64Ty };
261c93adca35856d0eaae088e52ba30cfefbd7ad910Chris Lattner        Function *MemCpyFn = Intrinsic::getDeclaration(Caller->getParent(),
262824b958e6fb1236e92e4d07f3acf18fca107cdc0Chris Lattner                                                       Intrinsic::memcpy,
263824b958e6fb1236e92e4d07f3acf18fca107cdc0Chris Lattner                                                       Tys, 1);
264c93adca35856d0eaae088e52ba30cfefbd7ad910Chris Lattner        Value *DestCast = new BitCastInst(NewAlloca, VoidPtrTy, "tmp", TheCall);
265c93adca35856d0eaae088e52ba30cfefbd7ad910Chris Lattner        Value *SrcCast = new BitCastInst(*AI, VoidPtrTy, "tmp", TheCall);
266a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands
267c93adca35856d0eaae088e52ba30cfefbd7ad910Chris Lattner        Value *Size;
268c93adca35856d0eaae088e52ba30cfefbd7ad910Chris Lattner        if (TD == 0)
269c93adca35856d0eaae088e52ba30cfefbd7ad910Chris Lattner          Size = ConstantExpr::getSizeOf(AggTy);
270c93adca35856d0eaae088e52ba30cfefbd7ad910Chris Lattner        else
271c93adca35856d0eaae088e52ba30cfefbd7ad910Chris Lattner          Size = ConstantInt::get(Type::Int64Ty, TD->getTypeStoreSize(AggTy));
272a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands
273c93adca35856d0eaae088e52ba30cfefbd7ad910Chris Lattner        // Always generate a memcpy of alignment 1 here because we don't know
274c93adca35856d0eaae088e52ba30cfefbd7ad910Chris Lattner        // the alignment of the src pointer.  Other optimizations can infer
275c93adca35856d0eaae088e52ba30cfefbd7ad910Chris Lattner        // better alignment.
276c93adca35856d0eaae088e52ba30cfefbd7ad910Chris Lattner        Value *CallArgs[] = {
277c93adca35856d0eaae088e52ba30cfefbd7ad910Chris Lattner          DestCast, SrcCast, Size, ConstantInt::get(Type::Int32Ty, 1)
278c93adca35856d0eaae088e52ba30cfefbd7ad910Chris Lattner        };
279c93adca35856d0eaae088e52ba30cfefbd7ad910Chris Lattner        CallInst *TheMemCpy =
280051a950000e21935165db56695e35bade668193bGabor Greif          CallInst::Create(MemCpyFn, CallArgs, CallArgs+4, "", TheCall);
281a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands
282c93adca35856d0eaae088e52ba30cfefbd7ad910Chris Lattner        // If we have a call graph, update it.
283c93adca35856d0eaae088e52ba30cfefbd7ad910Chris Lattner        if (CG) {
284c93adca35856d0eaae088e52ba30cfefbd7ad910Chris Lattner          CallGraphNode *MemCpyCGN = CG->getOrInsertFunction(MemCpyFn);
285c93adca35856d0eaae088e52ba30cfefbd7ad910Chris Lattner          CallGraphNode *CallerNode = (*CG)[Caller];
286c93adca35856d0eaae088e52ba30cfefbd7ad910Chris Lattner          CallerNode->addCalledFunction(TheMemCpy, MemCpyCGN);
287c93adca35856d0eaae088e52ba30cfefbd7ad910Chris Lattner        }
288a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands
289c93adca35856d0eaae088e52ba30cfefbd7ad910Chris Lattner        // Uses of the argument in the function should use our new alloca
290c93adca35856d0eaae088e52ba30cfefbd7ad910Chris Lattner        // instead.
291c93adca35856d0eaae088e52ba30cfefbd7ad910Chris Lattner        ActualArg = NewAlloca;
292c93adca35856d0eaae088e52ba30cfefbd7ad910Chris Lattner      }
293a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands
294c93adca35856d0eaae088e52ba30cfefbd7ad910Chris Lattner      ValueMap[I] = ActualArg;
295c93adca35856d0eaae088e52ba30cfefbd7ad910Chris Lattner    }
296fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
2975b5bc3032f97cfa7bfa3e22282d3a9c1ed05eec6Chris Lattner    // We want the inliner to prune the code as it copies.  We would LOVE to
2985b5bc3032f97cfa7bfa3e22282d3a9c1ed05eec6Chris Lattner    // have no dead or constant instructions leftover after inlining occurs
2995b5bc3032f97cfa7bfa3e22282d3a9c1ed05eec6Chris Lattner    // (which can happen, e.g., because an argument was constant), but we'll be
3005b5bc3032f97cfa7bfa3e22282d3a9c1ed05eec6Chris Lattner    // happy with whatever the cloner can do.
3015b5bc3032f97cfa7bfa3e22282d3a9c1ed05eec6Chris Lattner    CloneAndPruneFunctionInto(Caller, CalledFunc, ValueMap, Returns, ".i",
3021dfdf8255e803d6376f5fe94a113f892e796ae6cChris Lattner                              &InlinedFunctionInfo, TD);
303a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands
304d85340f4ec587e22b0239617f3b747a6df113894Chris Lattner    // Remember the first block that is newly cloned over.
305d85340f4ec587e22b0239617f3b747a6df113894Chris Lattner    FirstNewBlock = LastBlock; ++FirstNewBlock;
306a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands
307d85340f4ec587e22b0239617f3b747a6df113894Chris Lattner    // Update the callgraph if requested.
308d85340f4ec587e22b0239617f3b747a6df113894Chris Lattner    if (CG)
309d7b9851c4e634ed3599b1a4c70b1c76c90a11686Duncan Sands      UpdateCallGraphAfterInlining(CS, FirstNewBlock, ValueMap, *CG);
310fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman  }
311a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands
312ca398dc3989d35e8516489fd163e012133bd41cbChris Lattner  // If there are any alloca instructions in the block that used to be the entry
313ca398dc3989d35e8516489fd163e012133bd41cbChris Lattner  // block for the callee, move them to the entry block of the caller.  First
314ca398dc3989d35e8516489fd163e012133bd41cbChris Lattner  // calculate which instruction they should be inserted before.  We insert the
315ca398dc3989d35e8516489fd163e012133bd41cbChris Lattner  // instructions at the end of the current alloca list.
316ca398dc3989d35e8516489fd163e012133bd41cbChris Lattner  //
31721f20558d629f7ff8f64c20746d890d29328a544Chris Lattner  {
31880a38d245359cb0a3be8f78f5d7d911232886b9aChris Lattner    BasicBlock::iterator InsertPoint = Caller->begin()->begin();
3195e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner    for (BasicBlock::iterator I = FirstNewBlock->begin(),
3205e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner           E = FirstNewBlock->end(); I != E; )
32133bb3c8be355d179ece8e751f6e0f0978d0dd038Chris Lattner      if (AllocaInst *AI = dyn_cast<AllocaInst>(I++)) {
32233bb3c8be355d179ece8e751f6e0f0978d0dd038Chris Lattner        // If the alloca is now dead, remove it.  This often occurs due to code
32333bb3c8be355d179ece8e751f6e0f0978d0dd038Chris Lattner        // specialization.
32433bb3c8be355d179ece8e751f6e0f0978d0dd038Chris Lattner        if (AI->use_empty()) {
32533bb3c8be355d179ece8e751f6e0f0978d0dd038Chris Lattner          AI->eraseFromParent();
32633bb3c8be355d179ece8e751f6e0f0978d0dd038Chris Lattner          continue;
32733bb3c8be355d179ece8e751f6e0f0978d0dd038Chris Lattner        }
328a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands
329f775f95369ba7d88a5cb8b6f1900241699d79351Chris Lattner        if (isa<Constant>(AI->getArraySize())) {
33021f20558d629f7ff8f64c20746d890d29328a544Chris Lattner          // Scan for the block of allocas that we can move over, and move them
33121f20558d629f7ff8f64c20746d890d29328a544Chris Lattner          // all at once.
332c1df7e1799a7a97602bdedec818f7ab1dc514b4eChris Lattner          while (isa<AllocaInst>(I) &&
333c1df7e1799a7a97602bdedec818f7ab1dc514b4eChris Lattner                 isa<Constant>(cast<AllocaInst>(I)->getArraySize()))
334c1df7e1799a7a97602bdedec818f7ab1dc514b4eChris Lattner            ++I;
335c1df7e1799a7a97602bdedec818f7ab1dc514b4eChris Lattner
336c1df7e1799a7a97602bdedec818f7ab1dc514b4eChris Lattner          // Transfer all of the allocas over in a block.  Using splice means
337e26bff22dbcfec2074a7502dd56683fc7f55912aDan Gohman          // that the instructions aren't removed from the symbol table, then
338c1df7e1799a7a97602bdedec818f7ab1dc514b4eChris Lattner          // reinserted.
339ecb7a77885b174cf4d001a9b48533b3979e7810dDan Gohman          Caller->getEntryBlock().getInstList().splice(
340ecb7a77885b174cf4d001a9b48533b3979e7810dDan Gohman              InsertPoint,
341ecb7a77885b174cf4d001a9b48533b3979e7810dDan Gohman              FirstNewBlock->getInstList(),
342ecb7a77885b174cf4d001a9b48533b3979e7810dDan Gohman              AI, I);
343f775f95369ba7d88a5cb8b6f1900241699d79351Chris Lattner        }
34433bb3c8be355d179ece8e751f6e0f0978d0dd038Chris Lattner      }
34580a38d245359cb0a3be8f78f5d7d911232886b9aChris Lattner  }
34680a38d245359cb0a3be8f78f5d7d911232886b9aChris Lattner
347bf229f488a7541abd979cc3fbe9c3ce1c100e5c0Chris Lattner  // If the inlined code contained dynamic alloca instructions, wrap the inlined
348bf229f488a7541abd979cc3fbe9c3ce1c100e5c0Chris Lattner  // code with llvm.stacksave/llvm.stackrestore intrinsics.
349bf229f488a7541abd979cc3fbe9c3ce1c100e5c0Chris Lattner  if (InlinedFunctionInfo.ContainsDynamicAllocas) {
350bf229f488a7541abd979cc3fbe9c3ce1c100e5c0Chris Lattner    Module *M = Caller->getParent();
351bf229f488a7541abd979cc3fbe9c3ce1c100e5c0Chris Lattner    // Get the two intrinsics we care about.
352a121fddf3c34938d866ac4bb67247a479dedcd1bChris Lattner    Constant *StackSave, *StackRestore;
3533d292aca0306fbb65da4622c80df01432ab6559bDuncan Sands    StackSave    = Intrinsic::getDeclaration(M, Intrinsic::stacksave);
3543d292aca0306fbb65da4622c80df01432ab6559bDuncan Sands    StackRestore = Intrinsic::getDeclaration(M, Intrinsic::stackrestore);
355d85340f4ec587e22b0239617f3b747a6df113894Chris Lattner
356d85340f4ec587e22b0239617f3b747a6df113894Chris Lattner    // If we are preserving the callgraph, add edges to the stacksave/restore
357d85340f4ec587e22b0239617f3b747a6df113894Chris Lattner    // functions for the calls we insert.
35821ba23d0d88cff57dcdf104cd6914dabcbc68131Chris Lattner    CallGraphNode *StackSaveCGN = 0, *StackRestoreCGN = 0, *CallerNode = 0;
359d85340f4ec587e22b0239617f3b747a6df113894Chris Lattner    if (CG) {
360a121fddf3c34938d866ac4bb67247a479dedcd1bChris Lattner      // We know that StackSave/StackRestore are Function*'s, because they are
361a121fddf3c34938d866ac4bb67247a479dedcd1bChris Lattner      // intrinsics which must have the right types.
362a121fddf3c34938d866ac4bb67247a479dedcd1bChris Lattner      StackSaveCGN    = CG->getOrInsertFunction(cast<Function>(StackSave));
363a121fddf3c34938d866ac4bb67247a479dedcd1bChris Lattner      StackRestoreCGN = CG->getOrInsertFunction(cast<Function>(StackRestore));
364d85340f4ec587e22b0239617f3b747a6df113894Chris Lattner      CallerNode = (*CG)[Caller];
365d85340f4ec587e22b0239617f3b747a6df113894Chris Lattner    }
366a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands
367bf229f488a7541abd979cc3fbe9c3ce1c100e5c0Chris Lattner    // Insert the llvm.stacksave.
368a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands    CallInst *SavedPtr = CallInst::Create(StackSave, "savedstack",
369051a950000e21935165db56695e35bade668193bGabor Greif                                          FirstNewBlock->begin());
370d85340f4ec587e22b0239617f3b747a6df113894Chris Lattner    if (CG) CallerNode->addCalledFunction(SavedPtr, StackSaveCGN);
371a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands
372bf229f488a7541abd979cc3fbe9c3ce1c100e5c0Chris Lattner    // Insert a call to llvm.stackrestore before any return instructions in the
373bf229f488a7541abd979cc3fbe9c3ce1c100e5c0Chris Lattner    // inlined function.
374d85340f4ec587e22b0239617f3b747a6df113894Chris Lattner    for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
375051a950000e21935165db56695e35bade668193bGabor Greif      CallInst *CI = CallInst::Create(StackRestore, SavedPtr, "", Returns[i]);
376d85340f4ec587e22b0239617f3b747a6df113894Chris Lattner      if (CG) CallerNode->addCalledFunction(CI, StackRestoreCGN);
377d85340f4ec587e22b0239617f3b747a6df113894Chris Lattner    }
378468fb1df7db466e5682ee44341c3990b599e8d6aChris Lattner
379468fb1df7db466e5682ee44341c3990b599e8d6aChris Lattner    // Count the number of StackRestore calls we insert.
380468fb1df7db466e5682ee44341c3990b599e8d6aChris Lattner    unsigned NumStackRestores = Returns.size();
381a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands
382bf229f488a7541abd979cc3fbe9c3ce1c100e5c0Chris Lattner    // If we are inlining an invoke instruction, insert restores before each
383bf229f488a7541abd979cc3fbe9c3ce1c100e5c0Chris Lattner    // unwind.  These unwinds will be rewritten into branches later.
384bf229f488a7541abd979cc3fbe9c3ce1c100e5c0Chris Lattner    if (InlinedFunctionInfo.ContainsUnwinds && isa<InvokeInst>(TheCall)) {
385bf229f488a7541abd979cc3fbe9c3ce1c100e5c0Chris Lattner      for (Function::iterator BB = FirstNewBlock, E = Caller->end();
386bf229f488a7541abd979cc3fbe9c3ce1c100e5c0Chris Lattner           BB != E; ++BB)
387468fb1df7db466e5682ee44341c3990b599e8d6aChris Lattner        if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
3883d292aca0306fbb65da4622c80df01432ab6559bDuncan Sands          CallInst::Create(StackRestore, SavedPtr, "", UI);
389468fb1df7db466e5682ee44341c3990b599e8d6aChris Lattner          ++NumStackRestores;
390468fb1df7db466e5682ee44341c3990b599e8d6aChris Lattner        }
391468fb1df7db466e5682ee44341c3990b599e8d6aChris Lattner    }
392bf229f488a7541abd979cc3fbe9c3ce1c100e5c0Chris Lattner  }
393bf229f488a7541abd979cc3fbe9c3ce1c100e5c0Chris Lattner
394a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands  // If we are inlining tail call instruction through a call site that isn't
3951fdf4a859f03ce5aa4ce9acba29ce321c847388eChris Lattner  // marked 'tail', we must remove the tail marker for any calls in the inlined
396f0c3354d998507515ab39e26b5292ea0ceb06aefDuncan Sands  // code.  Also, calls inlined through a 'nounwind' call site should be marked
397f0c3354d998507515ab39e26b5292ea0ceb06aefDuncan Sands  // 'nounwind'.
398f0c3354d998507515ab39e26b5292ea0ceb06aefDuncan Sands  if (InlinedFunctionInfo.ContainsCalls &&
399f0c3354d998507515ab39e26b5292ea0ceb06aefDuncan Sands      (MustClearTailCallFlags || MarkNoUnwind)) {
4001b49141821e98e4321bfe6234c7001c836b2a289Chris Lattner    for (Function::iterator BB = FirstNewBlock, E = Caller->end();
4011b49141821e98e4321bfe6234c7001c836b2a289Chris Lattner         BB != E; ++BB)
4021b49141821e98e4321bfe6234c7001c836b2a289Chris Lattner      for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
403f0c3354d998507515ab39e26b5292ea0ceb06aefDuncan Sands        if (CallInst *CI = dyn_cast<CallInst>(I)) {
404f0c3354d998507515ab39e26b5292ea0ceb06aefDuncan Sands          if (MustClearTailCallFlags)
405f0c3354d998507515ab39e26b5292ea0ceb06aefDuncan Sands            CI->setTailCall(false);
406f0c3354d998507515ab39e26b5292ea0ceb06aefDuncan Sands          if (MarkNoUnwind)
407f0c3354d998507515ab39e26b5292ea0ceb06aefDuncan Sands            CI->setDoesNotThrow();
408f0c3354d998507515ab39e26b5292ea0ceb06aefDuncan Sands        }
4091b49141821e98e4321bfe6234c7001c836b2a289Chris Lattner  }
4101b49141821e98e4321bfe6234c7001c836b2a289Chris Lattner
411f0c3354d998507515ab39e26b5292ea0ceb06aefDuncan Sands  // If we are inlining through a 'nounwind' call site then any inlined 'unwind'
412f0c3354d998507515ab39e26b5292ea0ceb06aefDuncan Sands  // instructions are unreachable.
413f0c3354d998507515ab39e26b5292ea0ceb06aefDuncan Sands  if (InlinedFunctionInfo.ContainsUnwinds && MarkNoUnwind)
414f0c3354d998507515ab39e26b5292ea0ceb06aefDuncan Sands    for (Function::iterator BB = FirstNewBlock, E = Caller->end();
415f0c3354d998507515ab39e26b5292ea0ceb06aefDuncan Sands         BB != E; ++BB) {
416f0c3354d998507515ab39e26b5292ea0ceb06aefDuncan Sands      TerminatorInst *Term = BB->getTerminator();
417f0c3354d998507515ab39e26b5292ea0ceb06aefDuncan Sands      if (isa<UnwindInst>(Term)) {
418f0c3354d998507515ab39e26b5292ea0ceb06aefDuncan Sands        new UnreachableInst(Term);
419f0c3354d998507515ab39e26b5292ea0ceb06aefDuncan Sands        BB->getInstList().erase(Term);
420f0c3354d998507515ab39e26b5292ea0ceb06aefDuncan Sands      }
421f0c3354d998507515ab39e26b5292ea0ceb06aefDuncan Sands    }
422f0c3354d998507515ab39e26b5292ea0ceb06aefDuncan Sands
4235e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner  // If we are inlining for an invoke instruction, we must make sure to rewrite
4245e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner  // any inlined 'unwind' instructions into branches to the invoke exception
4255e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner  // destination, and call instructions into invoke instructions.
426cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner  if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall))
427cd4d339ec187182c9abc22b80560349f8ba5010fChris Lattner    HandleInlinedInvoke(II, FirstNewBlock, InlinedFunctionInfo);
4285e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner
42944a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner  // If we cloned in _exactly one_ basic block, and if that block ends in a
43044a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner  // return instruction, we splice the body of the inlined callee directly into
43144a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner  // the calling basic block.
43244a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner  if (Returns.size() == 1 && std::distance(FirstNewBlock, Caller->end()) == 1) {
43344a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner    // Move all of the instructions right before the call.
43444a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner    OrigBB->getInstList().splice(TheCall, FirstNewBlock->getInstList(),
43544a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner                                 FirstNewBlock->begin(), FirstNewBlock->end());
43644a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner    // Remove the cloned basic block.
43744a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner    Caller->getBasicBlockList().pop_back();
438fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
43944a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner    // If the call site was an invoke instruction, add a branch to the normal
44044a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner    // destination.
44144a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner    if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall))
442051a950000e21935165db56695e35bade668193bGabor Greif      BranchInst::Create(II->getNormalDest(), TheCall);
44344a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner
44444a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner    // If the return instruction returned a value, replace uses of the call with
44544a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner    // uses of the returned value.
446dc00d42bb18a6748f43c365d9bd30c1ed0e800acDevang Patel    if (!TheCall->use_empty()) {
447dc00d42bb18a6748f43c365d9bd30c1ed0e800acDevang Patel      ReturnInst *R = Returns[0];
448fc74abfba5128544a750fce22fdf13eb0403e3ceDan Gohman      TheCall->replaceAllUsesWith(R->getReturnValue());
449dc00d42bb18a6748f43c365d9bd30c1ed0e800acDevang Patel    }
45044a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner    // Since we are now done with the Call/Invoke, we can delete it.
4511adec83ae84031bfa9f0bf209c5ee6c64906a1ffDan Gohman    TheCall->eraseFromParent();
45244a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner
45344a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner    // Since we are now done with the return instruction, delete it also.
4541adec83ae84031bfa9f0bf209c5ee6c64906a1ffDan Gohman    Returns[0]->eraseFromParent();
45544a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner
45644a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner    // We are now done with the inlining.
45744a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner    return true;
45844a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner  }
45944a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner
46044a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner  // Otherwise, we have the normal case, of more than one block to inline or
46144a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner  // multiple return sites.
46244a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner
4635e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner  // We want to clone the entire callee function into the hole between the
4645e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner  // "starter" and "ender" blocks.  How we accomplish this depends on whether
4655e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner  // this is an invoke instruction or a call instruction.
4665e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner  BasicBlock *AfterCallBB;
4675e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner  if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
468fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
4695e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner    // Add an unconditional branch to make this look like the CallInst case...
470051a950000e21935165db56695e35bade668193bGabor Greif    BranchInst *NewBr = BranchInst::Create(II->getNormalDest(), TheCall);
471fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
4725e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner    // Split the basic block.  This guarantees that no PHI nodes will have to be
4735e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner    // updated due to new incoming edges, and make the invoke case more
4745e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner    // symmetric to the call case.
4755e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner    AfterCallBB = OrigBB->splitBasicBlock(NewBr,
476284d1b88273eb1967c8faef407f1167791c760e0Chris Lattner                                          CalledFunc->getName()+".exit");
477fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
4785e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner  } else {  // It's a call
47944a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner    // If this is a call instruction, we need to split the basic block that
48044a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner    // the call lives in.
4815e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner    //
4825e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner    AfterCallBB = OrigBB->splitBasicBlock(TheCall,
483284d1b88273eb1967c8faef407f1167791c760e0Chris Lattner                                          CalledFunc->getName()+".exit");
4845e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner  }
4855e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner
48644a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner  // Change the branch that used to go to AfterCallBB to branch to the first
48744a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner  // basic block of the inlined function.
48844a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner  //
48944a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner  TerminatorInst *Br = OrigBB->getTerminator();
490fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman  assert(Br && Br->getOpcode() == Instruction::Br &&
49144a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner         "splitBasicBlock broken!");
49244a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner  Br->setOperand(0, FirstNewBlock);
49344a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner
49444a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner
49544a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner  // Now that the function is correct, make it a little bit nicer.  In
49644a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner  // particular, move the basic blocks inserted from the end of the function
49744a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner  // into the space made by splitting the source basic block.
49844a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner  Caller->getBasicBlockList().splice(AfterCallBB, Caller->getBasicBlockList(),
49944a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner                                     FirstNewBlock, Caller->end());
50044a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner
5015e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner  // Handle all of the return instructions that we just cloned in, and eliminate
5025e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner  // any users of the original call/invoke instruction.
503b8f198af1b62f2ed48dcb914973a9d211dcba38bDevang Patel  const Type *RTy = CalledFunc->getReturnType();
5042c31750cd0ebdc83a890ace97dbb6249b3abe44eDan Gohman
505fc74abfba5128544a750fce22fdf13eb0403e3ceDan Gohman  if (Returns.size() > 1) {
5065e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner    // The PHI node should go at the front of the new basic block to merge all
5075e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner    // possible incoming values.
508fc74abfba5128544a750fce22fdf13eb0403e3ceDan Gohman    PHINode *PHI = 0;
5095e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner    if (!TheCall->use_empty()) {
510fc74abfba5128544a750fce22fdf13eb0403e3ceDan Gohman      PHI = PHINode::Create(RTy, TheCall->getName(),
511fc74abfba5128544a750fce22fdf13eb0403e3ceDan Gohman                            AfterCallBB->begin());
512fc74abfba5128544a750fce22fdf13eb0403e3ceDan Gohman      // Anything that used the result of the function call should now use the
513fc74abfba5128544a750fce22fdf13eb0403e3ceDan Gohman      // PHI node as their operand.
514a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands      TheCall->replaceAllUsesWith(PHI);
5155e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner    }
516fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
51712a466b9d0e27be453cfa05cff18acc9d7c1cfbaDevang Patel    // Loop over all of the return instructions adding entries to the PHI node as
5185e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner    // appropriate.
519fc74abfba5128544a750fce22fdf13eb0403e3ceDan Gohman    if (PHI) {
520fc74abfba5128544a750fce22fdf13eb0403e3ceDan Gohman      for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
521fc74abfba5128544a750fce22fdf13eb0403e3ceDan Gohman        ReturnInst *RI = Returns[i];
522fc74abfba5128544a750fce22fdf13eb0403e3ceDan Gohman        assert(RI->getReturnValue()->getType() == PHI->getType() &&
523fc74abfba5128544a750fce22fdf13eb0403e3ceDan Gohman               "Ret value not consistent in function!");
524fc74abfba5128544a750fce22fdf13eb0403e3ceDan Gohman        PHI->addIncoming(RI->getReturnValue(), RI->getParent());
5255e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner      }
52612a466b9d0e27be453cfa05cff18acc9d7c1cfbaDevang Patel    }
527fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
52812a466b9d0e27be453cfa05cff18acc9d7c1cfbaDevang Patel    // Add a branch to the merge points and remove retrun instructions.
52912a466b9d0e27be453cfa05cff18acc9d7c1cfbaDevang Patel    for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
53012a466b9d0e27be453cfa05cff18acc9d7c1cfbaDevang Patel      ReturnInst *RI = Returns[i];
531051a950000e21935165db56695e35bade668193bGabor Greif      BranchInst::Create(AfterCallBB, RI);
532b8f198af1b62f2ed48dcb914973a9d211dcba38bDevang Patel      RI->eraseFromParent();
5335e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner    }
534b8f198af1b62f2ed48dcb914973a9d211dcba38bDevang Patel  } else if (!Returns.empty()) {
535b8f198af1b62f2ed48dcb914973a9d211dcba38bDevang Patel    // Otherwise, if there is exactly one return value, just replace anything
536b8f198af1b62f2ed48dcb914973a9d211dcba38bDevang Patel    // using the return value of the call with the computed value.
537b8f198af1b62f2ed48dcb914973a9d211dcba38bDevang Patel    if (!TheCall->use_empty())
538b8f198af1b62f2ed48dcb914973a9d211dcba38bDevang Patel      TheCall->replaceAllUsesWith(Returns[0]->getReturnValue());
539a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands
540b8f198af1b62f2ed48dcb914973a9d211dcba38bDevang Patel    // Splice the code from the return block into the block that it will return
541b8f198af1b62f2ed48dcb914973a9d211dcba38bDevang Patel    // to, which contains the code that was after the call.
542b8f198af1b62f2ed48dcb914973a9d211dcba38bDevang Patel    BasicBlock *ReturnBB = Returns[0]->getParent();
543b8f198af1b62f2ed48dcb914973a9d211dcba38bDevang Patel    AfterCallBB->getInstList().splice(AfterCallBB->begin(),
544b8f198af1b62f2ed48dcb914973a9d211dcba38bDevang Patel                                      ReturnBB->getInstList());
545a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands
546b8f198af1b62f2ed48dcb914973a9d211dcba38bDevang Patel    // Update PHI nodes that use the ReturnBB to use the AfterCallBB.
547b8f198af1b62f2ed48dcb914973a9d211dcba38bDevang Patel    ReturnBB->replaceAllUsesWith(AfterCallBB);
548a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands
549b8f198af1b62f2ed48dcb914973a9d211dcba38bDevang Patel    // Delete the return instruction now and empty ReturnBB now.
550b8f198af1b62f2ed48dcb914973a9d211dcba38bDevang Patel    Returns[0]->eraseFromParent();
551b8f198af1b62f2ed48dcb914973a9d211dcba38bDevang Patel    ReturnBB->eraseFromParent();
5523787e765facfad5ea62753922d940bcdd52afd57Chris Lattner  } else if (!TheCall->use_empty()) {
5533787e765facfad5ea62753922d940bcdd52afd57Chris Lattner    // No returns, but something is using the return value of the call.  Just
5543787e765facfad5ea62753922d940bcdd52afd57Chris Lattner    // nuke the result.
5553787e765facfad5ea62753922d940bcdd52afd57Chris Lattner    TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
5565e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner  }
557fd93908ae8b9684fe71c239e3c6cfe13ff6a2663Misha Brukman
5585e923dee6024248f58fa83a7c7299437f44f0d1aChris Lattner  // Since we are now done with the Call/Invoke, we can delete it.
5593787e765facfad5ea62753922d940bcdd52afd57Chris Lattner  TheCall->eraseFromParent();
560ca398dc3989d35e8516489fd163e012133bd41cbChris Lattner
5617152c237b46a920b29d5605af934766b8f9a07a1Chris Lattner  // We should always be able to fold the entry block of the function into the
5627152c237b46a920b29d5605af934766b8f9a07a1Chris Lattner  // single predecessor of the block...
563cd01ae5c7071fb99a665b2bbea7428d769792ab8Chris Lattner  assert(cast<BranchInst>(Br)->isUnconditional() && "splitBasicBlock broken!");
5647152c237b46a920b29d5605af934766b8f9a07a1Chris Lattner  BasicBlock *CalleeEntry = cast<BranchInst>(Br)->getSuccessor(0);
56544a6807f4f785ecdd96b3aa67dad056677131b98Chris Lattner
566cd01ae5c7071fb99a665b2bbea7428d769792ab8Chris Lattner  // Splice the code entry block into calling block, right before the
567cd01ae5c7071fb99a665b2bbea7428d769792ab8Chris Lattner  // unconditional branch.
568cd01ae5c7071fb99a665b2bbea7428d769792ab8Chris Lattner  OrigBB->getInstList().splice(Br, CalleeEntry->getInstList());
569cd01ae5c7071fb99a665b2bbea7428d769792ab8Chris Lattner  CalleeEntry->replaceAllUsesWith(OrigBB);  // Update PHI nodes
570cd01ae5c7071fb99a665b2bbea7428d769792ab8Chris Lattner
571cd01ae5c7071fb99a665b2bbea7428d769792ab8Chris Lattner  // Remove the unconditional branch.
572cd01ae5c7071fb99a665b2bbea7428d769792ab8Chris Lattner  OrigBB->getInstList().erase(Br);
573cd01ae5c7071fb99a665b2bbea7428d769792ab8Chris Lattner
574cd01ae5c7071fb99a665b2bbea7428d769792ab8Chris Lattner  // Now we can remove the CalleeEntry block, which is now empty.
575cd01ae5c7071fb99a665b2bbea7428d769792ab8Chris Lattner  Caller->getBasicBlockList().erase(CalleeEntry);
576a7212e58260f6d1ead0c4eec7af400cf6c0d289eDuncan Sands
577ca398dc3989d35e8516489fd163e012133bd41cbChris Lattner  return true;
578ca398dc3989d35e8516489fd163e012133bd41cbChris Lattner}
579