LLVM API Documentation

InlineFunction.cpp
Go to the documentation of this file.
00001 //===- InlineFunction.cpp - Code to perform function inlining -------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements inlining of a function into a call site, resolving
00011 // parameters and the return value as appropriate.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "llvm/Transforms/Utils/Cloning.h"
00016 #include "llvm/ADT/SmallSet.h"
00017 #include "llvm/ADT/SmallVector.h"
00018 #include "llvm/ADT/SetVector.h"
00019 #include "llvm/ADT/StringExtras.h"
00020 #include "llvm/Analysis/AliasAnalysis.h"
00021 #include "llvm/Analysis/CallGraph.h"
00022 #include "llvm/Analysis/CaptureTracking.h"
00023 #include "llvm/Analysis/InstructionSimplify.h"
00024 #include "llvm/Analysis/ValueTracking.h"
00025 #include "llvm/IR/Attributes.h"
00026 #include "llvm/IR/CallSite.h"
00027 #include "llvm/IR/CFG.h"
00028 #include "llvm/IR/Constants.h"
00029 #include "llvm/IR/DataLayout.h"
00030 #include "llvm/IR/DebugInfo.h"
00031 #include "llvm/IR/DerivedTypes.h"
00032 #include "llvm/IR/Dominators.h"
00033 #include "llvm/IR/IRBuilder.h"
00034 #include "llvm/IR/Instructions.h"
00035 #include "llvm/IR/IntrinsicInst.h"
00036 #include "llvm/IR/Intrinsics.h"
00037 #include "llvm/IR/MDBuilder.h"
00038 #include "llvm/IR/Module.h"
00039 #include "llvm/Transforms/Utils/Local.h"
00040 #include "llvm/Support/CommandLine.h"
00041 #include <algorithm>
00042 using namespace llvm;
00043 
00044 static cl::opt<bool>
00045 EnableNoAliasConversion("enable-noalias-to-md-conversion", cl::init(false),
00046   cl::Hidden,
00047   cl::desc("Convert noalias attributes to metadata during inlining."));
00048 
00049 bool llvm::InlineFunction(CallInst *CI, InlineFunctionInfo &IFI,
00050                           bool InsertLifetime) {
00051   return InlineFunction(CallSite(CI), IFI, InsertLifetime);
00052 }
00053 bool llvm::InlineFunction(InvokeInst *II, InlineFunctionInfo &IFI,
00054                           bool InsertLifetime) {
00055   return InlineFunction(CallSite(II), IFI, InsertLifetime);
00056 }
00057 
00058 namespace {
00059   /// A class for recording information about inlining through an invoke.
00060   class InvokeInliningInfo {
00061     BasicBlock *OuterResumeDest; ///< Destination of the invoke's unwind.
00062     BasicBlock *InnerResumeDest; ///< Destination for the callee's resume.
00063     LandingPadInst *CallerLPad;  ///< LandingPadInst associated with the invoke.
00064     PHINode *InnerEHValuesPHI;   ///< PHI for EH values from landingpad insts.
00065     SmallVector<Value*, 8> UnwindDestPHIValues;
00066 
00067   public:
00068     InvokeInliningInfo(InvokeInst *II)
00069       : OuterResumeDest(II->getUnwindDest()), InnerResumeDest(nullptr),
00070         CallerLPad(nullptr), InnerEHValuesPHI(nullptr) {
00071       // If there are PHI nodes in the unwind destination block, we need to keep
00072       // track of which values came into them from the invoke before removing
00073       // the edge from this block.
00074       llvm::BasicBlock *InvokeBB = II->getParent();
00075       BasicBlock::iterator I = OuterResumeDest->begin();
00076       for (; isa<PHINode>(I); ++I) {
00077         // Save the value to use for this edge.
00078         PHINode *PHI = cast<PHINode>(I);
00079         UnwindDestPHIValues.push_back(PHI->getIncomingValueForBlock(InvokeBB));
00080       }
00081 
00082       CallerLPad = cast<LandingPadInst>(I);
00083     }
00084 
00085     /// getOuterResumeDest - The outer unwind destination is the target of
00086     /// unwind edges introduced for calls within the inlined function.
00087     BasicBlock *getOuterResumeDest() const {
00088       return OuterResumeDest;
00089     }
00090 
00091     BasicBlock *getInnerResumeDest();
00092 
00093     LandingPadInst *getLandingPadInst() const { return CallerLPad; }
00094 
00095     /// forwardResume - Forward the 'resume' instruction to the caller's landing
00096     /// pad block. When the landing pad block has only one predecessor, this is
00097     /// a simple branch. When there is more than one predecessor, we need to
00098     /// split the landing pad block after the landingpad instruction and jump
00099     /// to there.
00100     void forwardResume(ResumeInst *RI,
00101                        SmallPtrSet<LandingPadInst*, 16> &InlinedLPads);
00102 
00103     /// addIncomingPHIValuesFor - Add incoming-PHI values to the unwind
00104     /// destination block for the given basic block, using the values for the
00105     /// original invoke's source block.
00106     void addIncomingPHIValuesFor(BasicBlock *BB) const {
00107       addIncomingPHIValuesForInto(BB, OuterResumeDest);
00108     }
00109 
00110     void addIncomingPHIValuesForInto(BasicBlock *src, BasicBlock *dest) const {
00111       BasicBlock::iterator I = dest->begin();
00112       for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) {
00113         PHINode *phi = cast<PHINode>(I);
00114         phi->addIncoming(UnwindDestPHIValues[i], src);
00115       }
00116     }
00117   };
00118 }
00119 
00120 /// getInnerResumeDest - Get or create a target for the branch from ResumeInsts.
00121 BasicBlock *InvokeInliningInfo::getInnerResumeDest() {
00122   if (InnerResumeDest) return InnerResumeDest;
00123 
00124   // Split the landing pad.
00125   BasicBlock::iterator SplitPoint = CallerLPad; ++SplitPoint;
00126   InnerResumeDest =
00127     OuterResumeDest->splitBasicBlock(SplitPoint,
00128                                      OuterResumeDest->getName() + ".body");
00129 
00130   // The number of incoming edges we expect to the inner landing pad.
00131   const unsigned PHICapacity = 2;
00132 
00133   // Create corresponding new PHIs for all the PHIs in the outer landing pad.
00134   BasicBlock::iterator InsertPoint = InnerResumeDest->begin();
00135   BasicBlock::iterator I = OuterResumeDest->begin();
00136   for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) {
00137     PHINode *OuterPHI = cast<PHINode>(I);
00138     PHINode *InnerPHI = PHINode::Create(OuterPHI->getType(), PHICapacity,
00139                                         OuterPHI->getName() + ".lpad-body",
00140                                         InsertPoint);
00141     OuterPHI->replaceAllUsesWith(InnerPHI);
00142     InnerPHI->addIncoming(OuterPHI, OuterResumeDest);
00143   }
00144 
00145   // Create a PHI for the exception values.
00146   InnerEHValuesPHI = PHINode::Create(CallerLPad->getType(), PHICapacity,
00147                                      "eh.lpad-body", InsertPoint);
00148   CallerLPad->replaceAllUsesWith(InnerEHValuesPHI);
00149   InnerEHValuesPHI->addIncoming(CallerLPad, OuterResumeDest);
00150 
00151   // All done.
00152   return InnerResumeDest;
00153 }
00154 
00155 /// forwardResume - Forward the 'resume' instruction to the caller's landing pad
00156 /// block. When the landing pad block has only one predecessor, this is a simple
00157 /// branch. When there is more than one predecessor, we need to split the
00158 /// landing pad block after the landingpad instruction and jump to there.
00159 void InvokeInliningInfo::forwardResume(ResumeInst *RI,
00160                                SmallPtrSet<LandingPadInst*, 16> &InlinedLPads) {
00161   BasicBlock *Dest = getInnerResumeDest();
00162   BasicBlock *Src = RI->getParent();
00163 
00164   BranchInst::Create(Dest, Src);
00165 
00166   // Update the PHIs in the destination. They were inserted in an order which
00167   // makes this work.
00168   addIncomingPHIValuesForInto(Src, Dest);
00169 
00170   InnerEHValuesPHI->addIncoming(RI->getOperand(0), Src);
00171   RI->eraseFromParent();
00172 }
00173 
00174 /// HandleCallsInBlockInlinedThroughInvoke - When we inline a basic block into
00175 /// an invoke, we have to turn all of the calls that can throw into
00176 /// invokes.  This function analyze BB to see if there are any calls, and if so,
00177 /// it rewrites them to be invokes that jump to InvokeDest and fills in the PHI
00178 /// nodes in that block with the values specified in InvokeDestPHIValues.
00179 static void HandleCallsInBlockInlinedThroughInvoke(BasicBlock *BB,
00180                                                    InvokeInliningInfo &Invoke) {
00181   for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
00182     Instruction *I = BBI++;
00183 
00184     // We only need to check for function calls: inlined invoke
00185     // instructions require no special handling.
00186     CallInst *CI = dyn_cast<CallInst>(I);
00187 
00188     // If this call cannot unwind, don't convert it to an invoke.
00189     // Inline asm calls cannot throw.
00190     if (!CI || CI->doesNotThrow() || isa<InlineAsm>(CI->getCalledValue()))
00191       continue;
00192 
00193     // Convert this function call into an invoke instruction.  First, split the
00194     // basic block.
00195     BasicBlock *Split = BB->splitBasicBlock(CI, CI->getName()+".noexc");
00196 
00197     // Delete the unconditional branch inserted by splitBasicBlock
00198     BB->getInstList().pop_back();
00199 
00200     // Create the new invoke instruction.
00201     ImmutableCallSite CS(CI);
00202     SmallVector<Value*, 8> InvokeArgs(CS.arg_begin(), CS.arg_end());
00203     InvokeInst *II = InvokeInst::Create(CI->getCalledValue(), Split,
00204                                         Invoke.getOuterResumeDest(),
00205                                         InvokeArgs, CI->getName(), BB);
00206     II->setDebugLoc(CI->getDebugLoc());
00207     II->setCallingConv(CI->getCallingConv());
00208     II->setAttributes(CI->getAttributes());
00209     
00210     // Make sure that anything using the call now uses the invoke!  This also
00211     // updates the CallGraph if present, because it uses a WeakVH.
00212     CI->replaceAllUsesWith(II);
00213 
00214     // Delete the original call
00215     Split->getInstList().pop_front();
00216 
00217     // Update any PHI nodes in the exceptional block to indicate that there is
00218     // now a new entry in them.
00219     Invoke.addIncomingPHIValuesFor(BB);
00220     return;
00221   }
00222 }
00223 
00224 /// HandleInlinedInvoke - If we inlined an invoke site, we need to convert calls
00225 /// in the body of the inlined function into invokes.
00226 ///
00227 /// II is the invoke instruction being inlined.  FirstNewBlock is the first
00228 /// block of the inlined code (the last block is the end of the function),
00229 /// and InlineCodeInfo is information about the code that got inlined.
00230 static void HandleInlinedInvoke(InvokeInst *II, BasicBlock *FirstNewBlock,
00231                                 ClonedCodeInfo &InlinedCodeInfo) {
00232   BasicBlock *InvokeDest = II->getUnwindDest();
00233 
00234   Function *Caller = FirstNewBlock->getParent();
00235 
00236   // The inlined code is currently at the end of the function, scan from the
00237   // start of the inlined code to its end, checking for stuff we need to
00238   // rewrite.
00239   InvokeInliningInfo Invoke(II);
00240 
00241   // Get all of the inlined landing pad instructions.
00242   SmallPtrSet<LandingPadInst*, 16> InlinedLPads;
00243   for (Function::iterator I = FirstNewBlock, E = Caller->end(); I != E; ++I)
00244     if (InvokeInst *II = dyn_cast<InvokeInst>(I->getTerminator()))
00245       InlinedLPads.insert(II->getLandingPadInst());
00246 
00247   // Append the clauses from the outer landing pad instruction into the inlined
00248   // landing pad instructions.
00249   LandingPadInst *OuterLPad = Invoke.getLandingPadInst();
00250   for (SmallPtrSet<LandingPadInst*, 16>::iterator I = InlinedLPads.begin(),
00251          E = InlinedLPads.end(); I != E; ++I) {
00252     LandingPadInst *InlinedLPad = *I;
00253     unsigned OuterNum = OuterLPad->getNumClauses();
00254     InlinedLPad->reserveClauses(OuterNum);
00255     for (unsigned OuterIdx = 0; OuterIdx != OuterNum; ++OuterIdx)
00256       InlinedLPad->addClause(OuterLPad->getClause(OuterIdx));
00257     if (OuterLPad->isCleanup())
00258       InlinedLPad->setCleanup(true);
00259   }
00260 
00261   for (Function::iterator BB = FirstNewBlock, E = Caller->end(); BB != E; ++BB){
00262     if (InlinedCodeInfo.ContainsCalls)
00263       HandleCallsInBlockInlinedThroughInvoke(BB, Invoke);
00264 
00265     // Forward any resumes that are remaining here.
00266     if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator()))
00267       Invoke.forwardResume(RI, InlinedLPads);
00268   }
00269 
00270   // Now that everything is happy, we have one final detail.  The PHI nodes in
00271   // the exception destination block still have entries due to the original
00272   // invoke instruction. Eliminate these entries (which might even delete the
00273   // PHI node) now.
00274   InvokeDest->removePredecessor(II->getParent());
00275 }
00276 
00277 /// CloneAliasScopeMetadata - When inlining a function that contains noalias
00278 /// scope metadata, this metadata needs to be cloned so that the inlined blocks
00279 /// have different "unqiue scopes" at every call site. Were this not done, then
00280 /// aliasing scopes from a function inlined into a caller multiple times could
00281 /// not be differentiated (and this would lead to miscompiles because the
00282 /// non-aliasing property communicated by the metadata could have
00283 /// call-site-specific control dependencies).
00284 static void CloneAliasScopeMetadata(CallSite CS, ValueToValueMapTy &VMap) {
00285   const Function *CalledFunc = CS.getCalledFunction();
00286   SetVector<const MDNode *> MD;
00287 
00288   // Note: We could only clone the metadata if it is already used in the
00289   // caller. I'm omitting that check here because it might confuse
00290   // inter-procedural alias analysis passes. We can revisit this if it becomes
00291   // an efficiency or overhead problem.
00292 
00293   for (Function::const_iterator I = CalledFunc->begin(), IE = CalledFunc->end();
00294        I != IE; ++I)
00295     for (BasicBlock::const_iterator J = I->begin(), JE = I->end(); J != JE; ++J) {
00296       if (const MDNode *M = J->getMetadata(LLVMContext::MD_alias_scope))
00297         MD.insert(M);
00298       if (const MDNode *M = J->getMetadata(LLVMContext::MD_noalias))
00299         MD.insert(M);
00300     }
00301 
00302   if (MD.empty())
00303     return;
00304 
00305   // Walk the existing metadata, adding the complete (perhaps cyclic) chain to
00306   // the set.
00307   SmallVector<const Value *, 16> Queue(MD.begin(), MD.end());
00308   while (!Queue.empty()) {
00309     const MDNode *M = cast<MDNode>(Queue.pop_back_val());
00310     for (unsigned i = 0, ie = M->getNumOperands(); i != ie; ++i)
00311       if (const MDNode *M1 = dyn_cast<MDNode>(M->getOperand(i)))
00312         if (MD.insert(M1))
00313           Queue.push_back(M1);
00314   }
00315 
00316   // Now we have a complete set of all metadata in the chains used to specify
00317   // the noalias scopes and the lists of those scopes.
00318   SmallVector<MDNode *, 16> DummyNodes;
00319   DenseMap<const MDNode *, TrackingVH<MDNode> > MDMap;
00320   for (SetVector<const MDNode *>::iterator I = MD.begin(), IE = MD.end();
00321        I != IE; ++I) {
00322     MDNode *Dummy = MDNode::getTemporary(CalledFunc->getContext(),
00323                                          ArrayRef<Value*>());
00324     DummyNodes.push_back(Dummy);
00325     MDMap[*I] = Dummy;
00326   }
00327 
00328   // Create new metadata nodes to replace the dummy nodes, replacing old
00329   // metadata references with either a dummy node or an already-created new
00330   // node.
00331   for (SetVector<const MDNode *>::iterator I = MD.begin(), IE = MD.end();
00332        I != IE; ++I) {
00333     SmallVector<Value *, 4> NewOps;
00334     for (unsigned i = 0, ie = (*I)->getNumOperands(); i != ie; ++i) {
00335       const Value *V = (*I)->getOperand(i);
00336       if (const MDNode *M = dyn_cast<MDNode>(V))
00337         NewOps.push_back(MDMap[M]);
00338       else
00339         NewOps.push_back(const_cast<Value *>(V));
00340     }
00341 
00342     MDNode *NewM = MDNode::get(CalledFunc->getContext(), NewOps),
00343            *TempM = MDMap[*I];
00344 
00345     TempM->replaceAllUsesWith(NewM);
00346   }
00347 
00348   // Now replace the metadata in the new inlined instructions with the
00349   // repacements from the map.
00350   for (ValueToValueMapTy::iterator VMI = VMap.begin(), VMIE = VMap.end();
00351        VMI != VMIE; ++VMI) {
00352     if (!VMI->second)
00353       continue;
00354 
00355     Instruction *NI = dyn_cast<Instruction>(VMI->second);
00356     if (!NI)
00357       continue;
00358 
00359     if (MDNode *M = NI->getMetadata(LLVMContext::MD_alias_scope))
00360       NI->setMetadata(LLVMContext::MD_alias_scope, MDMap[M]);
00361 
00362     if (MDNode *M = NI->getMetadata(LLVMContext::MD_noalias))
00363       NI->setMetadata(LLVMContext::MD_noalias, MDMap[M]);
00364   }
00365 
00366   // Now that everything has been replaced, delete the dummy nodes.
00367   for (unsigned i = 0, ie = DummyNodes.size(); i != ie; ++i)
00368     MDNode::deleteTemporary(DummyNodes[i]);
00369 }
00370 
00371 /// AddAliasScopeMetadata - If the inlined function has noalias arguments, then
00372 /// add new alias scopes for each noalias argument, tag the mapped noalias
00373 /// parameters with noalias metadata specifying the new scope, and tag all
00374 /// non-derived loads, stores and memory intrinsics with the new alias scopes.
00375 static void AddAliasScopeMetadata(CallSite CS, ValueToValueMapTy &VMap,
00376                                   const DataLayout *DL) {
00377   if (!EnableNoAliasConversion)
00378     return;
00379 
00380   const Function *CalledFunc = CS.getCalledFunction();
00381   SmallVector<const Argument *, 4> NoAliasArgs;
00382 
00383   for (Function::const_arg_iterator I = CalledFunc->arg_begin(),
00384        E = CalledFunc->arg_end(); I != E; ++I) {
00385     if (I->hasNoAliasAttr() && !I->hasNUses(0))
00386       NoAliasArgs.push_back(I);
00387   }
00388 
00389   if (NoAliasArgs.empty())
00390     return;
00391 
00392   // To do a good job, if a noalias variable is captured, we need to know if
00393   // the capture point dominates the particular use we're considering.
00394   DominatorTree DT;
00395   DT.recalculate(const_cast<Function&>(*CalledFunc));
00396 
00397   // noalias indicates that pointer values based on the argument do not alias
00398   // pointer values which are not based on it. So we add a new "scope" for each
00399   // noalias function argument. Accesses using pointers based on that argument
00400   // become part of that alias scope, accesses using pointers not based on that
00401   // argument are tagged as noalias with that scope.
00402 
00403   DenseMap<const Argument *, MDNode *> NewScopes;
00404   MDBuilder MDB(CalledFunc->getContext());
00405 
00406   // Create a new scope domain for this function.
00407   MDNode *NewDomain =
00408     MDB.createAnonymousAliasScopeDomain(CalledFunc->getName());
00409   for (unsigned i = 0, e = NoAliasArgs.size(); i != e; ++i) {
00410     const Argument *A = NoAliasArgs[i];
00411 
00412     std::string Name = CalledFunc->getName();
00413     if (A->hasName()) {
00414       Name += ": %";
00415       Name += A->getName();
00416     } else {
00417       Name += ": argument ";
00418       Name += utostr(i);
00419     }
00420 
00421     // Note: We always create a new anonymous root here. This is true regardless
00422     // of the linkage of the callee because the aliasing "scope" is not just a
00423     // property of the callee, but also all control dependencies in the caller.
00424     MDNode *NewScope = MDB.createAnonymousAliasScope(NewDomain, Name);
00425     NewScopes.insert(std::make_pair(A, NewScope));
00426   }
00427 
00428   // Iterate over all new instructions in the map; for all memory-access
00429   // instructions, add the alias scope metadata.
00430   for (ValueToValueMapTy::iterator VMI = VMap.begin(), VMIE = VMap.end();
00431        VMI != VMIE; ++VMI) {
00432     if (const Instruction *I = dyn_cast<Instruction>(VMI->first)) {
00433       if (!VMI->second)
00434         continue;
00435 
00436       Instruction *NI = dyn_cast<Instruction>(VMI->second);
00437       if (!NI)
00438         continue;
00439 
00440       SmallVector<const Value *, 2> PtrArgs;
00441 
00442       if (const LoadInst *LI = dyn_cast<LoadInst>(I))
00443         PtrArgs.push_back(LI->getPointerOperand());
00444       else if (const StoreInst *SI = dyn_cast<StoreInst>(I))
00445         PtrArgs.push_back(SI->getPointerOperand());
00446       else if (const VAArgInst *VAAI = dyn_cast<VAArgInst>(I))
00447         PtrArgs.push_back(VAAI->getPointerOperand());
00448       else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I))
00449         PtrArgs.push_back(CXI->getPointerOperand());
00450       else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I))
00451         PtrArgs.push_back(RMWI->getPointerOperand());
00452       else if (const MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
00453         PtrArgs.push_back(MI->getRawDest());
00454         if (const MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
00455           PtrArgs.push_back(MTI->getRawSource());
00456       }
00457 
00458       // If we found no pointers, then this instruction is not suitable for
00459       // pairing with an instruction to receive aliasing metadata.
00460       // Simplification during cloning could make this happen, and skip these
00461       // cases for now.
00462       if (PtrArgs.empty())
00463         continue;
00464 
00465       // It is possible that there is only one underlying object, but you
00466       // need to go through several PHIs to see it, and thus could be
00467       // repeated in the Objects list.
00468       SmallPtrSet<const Value *, 4> ObjSet;
00469       SmallVector<Value *, 4> Scopes, NoAliases;
00470 
00471       SmallSetVector<const Argument *, 4> NAPtrArgs;
00472       for (unsigned i = 0, ie = PtrArgs.size(); i != ie; ++i) {
00473         SmallVector<Value *, 4> Objects;
00474         GetUnderlyingObjects(const_cast<Value*>(PtrArgs[i]),
00475                              Objects, DL, /* MaxLookup = */ 0);
00476 
00477         for (Value *O : Objects)
00478           ObjSet.insert(O);
00479       }
00480 
00481       // Figure out if we're derived from anyhing that is not a noalias
00482       // argument.
00483       bool CanDeriveViaCapture = false;
00484       for (const Value *V : ObjSet)
00485         if (!isIdentifiedFunctionLocal(const_cast<Value*>(V))) {
00486           CanDeriveViaCapture = true;
00487           break;
00488         }
00489   
00490       // First, we want to figure out all of the sets with which we definitely
00491       // don't alias. Iterate over all noalias set, and add those for which:
00492       //   1. The noalias argument is not in the set of objects from which we
00493       //      definitely derive.
00494       //   2. The noalias argument has not yet been captured.
00495       for (const Argument *A : NoAliasArgs) {
00496         if (!ObjSet.count(A) && (!CanDeriveViaCapture ||
00497                                  A->hasNoCaptureAttr() ||
00498                                  !PointerMayBeCapturedBefore(A,
00499                                    /* ReturnCaptures */ false,
00500                                    /* StoreCaptures */ false, I, &DT)))
00501           NoAliases.push_back(NewScopes[A]);
00502       }
00503 
00504       if (!NoAliases.empty())
00505         NI->setMetadata(LLVMContext::MD_noalias, MDNode::concatenate(
00506           NI->getMetadata(LLVMContext::MD_noalias),
00507             MDNode::get(CalledFunc->getContext(), NoAliases)));
00508       // Next, we want to figure out all of the sets to which we might belong.
00509       // We might below to a set if:
00510       //  1. The noalias argument is in the set of underlying objects
00511       // or
00512       //  2. There is some non-noalias argument in our list and the no-alias
00513       //     argument has been captured.
00514       
00515       for (const Argument *A : NoAliasArgs) {
00516         if (ObjSet.count(A) || (CanDeriveViaCapture &&
00517                                 PointerMayBeCapturedBefore(A,
00518                                   /* ReturnCaptures */ false,
00519                                   /* StoreCaptures */ false,
00520                                   I, &DT)))
00521           Scopes.push_back(NewScopes[A]);
00522       }
00523 
00524       if (!Scopes.empty())
00525         NI->setMetadata(LLVMContext::MD_alias_scope, MDNode::concatenate(
00526           NI->getMetadata(LLVMContext::MD_alias_scope),
00527             MDNode::get(CalledFunc->getContext(), Scopes)));
00528     }
00529   }
00530 }
00531 
00532 /// UpdateCallGraphAfterInlining - Once we have cloned code over from a callee
00533 /// into the caller, update the specified callgraph to reflect the changes we
00534 /// made.  Note that it's possible that not all code was copied over, so only
00535 /// some edges of the callgraph may remain.
00536 static void UpdateCallGraphAfterInlining(CallSite CS,
00537                                          Function::iterator FirstNewBlock,
00538                                          ValueToValueMapTy &VMap,
00539                                          InlineFunctionInfo &IFI) {
00540   CallGraph &CG = *IFI.CG;
00541   const Function *Caller = CS.getInstruction()->getParent()->getParent();
00542   const Function *Callee = CS.getCalledFunction();
00543   CallGraphNode *CalleeNode = CG[Callee];
00544   CallGraphNode *CallerNode = CG[Caller];
00545 
00546   // Since we inlined some uninlined call sites in the callee into the caller,
00547   // add edges from the caller to all of the callees of the callee.
00548   CallGraphNode::iterator I = CalleeNode->begin(), E = CalleeNode->end();
00549 
00550   // Consider the case where CalleeNode == CallerNode.
00551   CallGraphNode::CalledFunctionsVector CallCache;
00552   if (CalleeNode == CallerNode) {
00553     CallCache.assign(I, E);
00554     I = CallCache.begin();
00555     E = CallCache.end();
00556   }
00557 
00558   for (; I != E; ++I) {
00559     const Value *OrigCall = I->first;
00560 
00561     ValueToValueMapTy::iterator VMI = VMap.find(OrigCall);
00562     // Only copy the edge if the call was inlined!
00563     if (VMI == VMap.end() || VMI->second == nullptr)
00564       continue;
00565     
00566     // If the call was inlined, but then constant folded, there is no edge to
00567     // add.  Check for this case.
00568     Instruction *NewCall = dyn_cast<Instruction>(VMI->second);
00569     if (!NewCall) continue;
00570 
00571     // Remember that this call site got inlined for the client of
00572     // InlineFunction.
00573     IFI.InlinedCalls.push_back(NewCall);
00574 
00575     // It's possible that inlining the callsite will cause it to go from an
00576     // indirect to a direct call by resolving a function pointer.  If this
00577     // happens, set the callee of the new call site to a more precise
00578     // destination.  This can also happen if the call graph node of the caller
00579     // was just unnecessarily imprecise.
00580     if (!I->second->getFunction())
00581       if (Function *F = CallSite(NewCall).getCalledFunction()) {
00582         // Indirect call site resolved to direct call.
00583         CallerNode->addCalledFunction(CallSite(NewCall), CG[F]);
00584 
00585         continue;
00586       }
00587 
00588     CallerNode->addCalledFunction(CallSite(NewCall), I->second);
00589   }
00590   
00591   // Update the call graph by deleting the edge from Callee to Caller.  We must
00592   // do this after the loop above in case Caller and Callee are the same.
00593   CallerNode->removeCallEdgeFor(CS);
00594 }
00595 
00596 static void HandleByValArgumentInit(Value *Dst, Value *Src, Module *M,
00597                                     BasicBlock *InsertBlock,
00598                                     InlineFunctionInfo &IFI) {
00599   LLVMContext &Context = Src->getContext();
00600   Type *VoidPtrTy = Type::getInt8PtrTy(Context);
00601   Type *AggTy = cast<PointerType>(Src->getType())->getElementType();
00602   Type *Tys[3] = { VoidPtrTy, VoidPtrTy, Type::getInt64Ty(Context) };
00603   Function *MemCpyFn = Intrinsic::getDeclaration(M, Intrinsic::memcpy, Tys);
00604   IRBuilder<> builder(InsertBlock->begin());
00605   Value *DstCast = builder.CreateBitCast(Dst, VoidPtrTy, "tmp");
00606   Value *SrcCast = builder.CreateBitCast(Src, VoidPtrTy, "tmp");
00607 
00608   Value *Size;
00609   if (IFI.DL == nullptr)
00610     Size = ConstantExpr::getSizeOf(AggTy);
00611   else
00612     Size = ConstantInt::get(Type::getInt64Ty(Context),
00613                             IFI.DL->getTypeStoreSize(AggTy));
00614 
00615   // Always generate a memcpy of alignment 1 here because we don't know
00616   // the alignment of the src pointer.  Other optimizations can infer
00617   // better alignment.
00618   Value *CallArgs[] = {
00619     DstCast, SrcCast, Size,
00620     ConstantInt::get(Type::getInt32Ty(Context), 1),
00621     ConstantInt::getFalse(Context) // isVolatile
00622   };
00623   builder.CreateCall(MemCpyFn, CallArgs);
00624 }
00625 
00626 /// HandleByValArgument - When inlining a call site that has a byval argument,
00627 /// we have to make the implicit memcpy explicit by adding it.
00628 static Value *HandleByValArgument(Value *Arg, Instruction *TheCall,
00629                                   const Function *CalledFunc,
00630                                   InlineFunctionInfo &IFI,
00631                                   unsigned ByValAlignment) {
00632   PointerType *ArgTy = cast<PointerType>(Arg->getType());
00633   Type *AggTy = ArgTy->getElementType();
00634 
00635   // If the called function is readonly, then it could not mutate the caller's
00636   // copy of the byval'd memory.  In this case, it is safe to elide the copy and
00637   // temporary.
00638   if (CalledFunc->onlyReadsMemory()) {
00639     // If the byval argument has a specified alignment that is greater than the
00640     // passed in pointer, then we either have to round up the input pointer or
00641     // give up on this transformation.
00642     if (ByValAlignment <= 1)  // 0 = unspecified, 1 = no particular alignment.
00643       return Arg;
00644 
00645     // If the pointer is already known to be sufficiently aligned, or if we can
00646     // round it up to a larger alignment, then we don't need a temporary.
00647     if (getOrEnforceKnownAlignment(Arg, ByValAlignment,
00648                                    IFI.DL) >= ByValAlignment)
00649       return Arg;
00650     
00651     // Otherwise, we have to make a memcpy to get a safe alignment.  This is bad
00652     // for code quality, but rarely happens and is required for correctness.
00653   }
00654 
00655   // Create the alloca.  If we have DataLayout, use nice alignment.
00656   unsigned Align = 1;
00657   if (IFI.DL)
00658     Align = IFI.DL->getPrefTypeAlignment(AggTy);
00659   
00660   // If the byval had an alignment specified, we *must* use at least that
00661   // alignment, as it is required by the byval argument (and uses of the
00662   // pointer inside the callee).
00663   Align = std::max(Align, ByValAlignment);
00664   
00665   Function *Caller = TheCall->getParent()->getParent(); 
00666   
00667   Value *NewAlloca = new AllocaInst(AggTy, nullptr, Align, Arg->getName(), 
00668                                     &*Caller->begin()->begin());
00669   IFI.StaticAllocas.push_back(cast<AllocaInst>(NewAlloca));
00670   
00671   // Uses of the argument in the function should use our new alloca
00672   // instead.
00673   return NewAlloca;
00674 }
00675 
00676 // isUsedByLifetimeMarker - Check whether this Value is used by a lifetime
00677 // intrinsic.
00678 static bool isUsedByLifetimeMarker(Value *V) {
00679   for (User *U : V->users()) {
00680     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) {
00681       switch (II->getIntrinsicID()) {
00682       default: break;
00683       case Intrinsic::lifetime_start:
00684       case Intrinsic::lifetime_end:
00685         return true;
00686       }
00687     }
00688   }
00689   return false;
00690 }
00691 
00692 // hasLifetimeMarkers - Check whether the given alloca already has
00693 // lifetime.start or lifetime.end intrinsics.
00694 static bool hasLifetimeMarkers(AllocaInst *AI) {
00695   Type *Ty = AI->getType();
00696   Type *Int8PtrTy = Type::getInt8PtrTy(Ty->getContext(),
00697                                        Ty->getPointerAddressSpace());
00698   if (Ty == Int8PtrTy)
00699     return isUsedByLifetimeMarker(AI);
00700 
00701   // Do a scan to find all the casts to i8*.
00702   for (User *U : AI->users()) {
00703     if (U->getType() != Int8PtrTy) continue;
00704     if (U->stripPointerCasts() != AI) continue;
00705     if (isUsedByLifetimeMarker(U))
00706       return true;
00707   }
00708   return false;
00709 }
00710 
00711 /// updateInlinedAtInfo - Helper function used by fixupLineNumbers to
00712 /// recursively update InlinedAtEntry of a DebugLoc.
00713 static DebugLoc updateInlinedAtInfo(const DebugLoc &DL, 
00714                                     const DebugLoc &InlinedAtDL,
00715                                     LLVMContext &Ctx) {
00716   if (MDNode *IA = DL.getInlinedAt(Ctx)) {
00717     DebugLoc NewInlinedAtDL 
00718       = updateInlinedAtInfo(DebugLoc::getFromDILocation(IA), InlinedAtDL, Ctx);
00719     return DebugLoc::get(DL.getLine(), DL.getCol(), DL.getScope(Ctx),
00720                          NewInlinedAtDL.getAsMDNode(Ctx));
00721   }
00722 
00723   return DebugLoc::get(DL.getLine(), DL.getCol(), DL.getScope(Ctx),
00724                        InlinedAtDL.getAsMDNode(Ctx));
00725 }
00726 
00727 /// fixupLineNumbers - Update inlined instructions' line numbers to 
00728 /// to encode location where these instructions are inlined.
00729 static void fixupLineNumbers(Function *Fn, Function::iterator FI,
00730                              Instruction *TheCall) {
00731   DebugLoc TheCallDL = TheCall->getDebugLoc();
00732   if (TheCallDL.isUnknown())
00733     return;
00734 
00735   for (; FI != Fn->end(); ++FI) {
00736     for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
00737          BI != BE; ++BI) {
00738       DebugLoc DL = BI->getDebugLoc();
00739       if (DL.isUnknown()) {
00740         // If the inlined instruction has no line number, make it look as if it
00741         // originates from the call location. This is important for
00742         // ((__always_inline__, __nodebug__)) functions which must use caller
00743         // location for all instructions in their function body.
00744         BI->setDebugLoc(TheCallDL);
00745       } else {
00746         BI->setDebugLoc(updateInlinedAtInfo(DL, TheCallDL, BI->getContext()));
00747         if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(BI)) {
00748           LLVMContext &Ctx = BI->getContext();
00749           MDNode *InlinedAt = BI->getDebugLoc().getInlinedAt(Ctx);
00750           DVI->setOperand(2, createInlinedVariable(DVI->getVariable(), 
00751                                                    InlinedAt, Ctx));
00752         }
00753       }
00754     }
00755   }
00756 }
00757 
00758 /// Returns a musttail call instruction if one immediately precedes the given
00759 /// return instruction with an optional bitcast instruction between them.
00760 static CallInst *getPrecedingMustTailCall(ReturnInst *RI) {
00761   Instruction *Prev = RI->getPrevNode();
00762   if (!Prev)
00763     return nullptr;
00764 
00765   if (Value *RV = RI->getReturnValue()) {
00766     if (RV != Prev)
00767       return nullptr;
00768 
00769     // Look through the optional bitcast.
00770     if (auto *BI = dyn_cast<BitCastInst>(Prev)) {
00771       RV = BI->getOperand(0);
00772       Prev = BI->getPrevNode();
00773       if (!Prev || RV != Prev)
00774         return nullptr;
00775     }
00776   }
00777 
00778   if (auto *CI = dyn_cast<CallInst>(Prev)) {
00779     if (CI->isMustTailCall())
00780       return CI;
00781   }
00782   return nullptr;
00783 }
00784 
00785 /// InlineFunction - This function inlines the called function into the basic
00786 /// block of the caller.  This returns false if it is not possible to inline
00787 /// this call.  The program is still in a well defined state if this occurs
00788 /// though.
00789 ///
00790 /// Note that this only does one level of inlining.  For example, if the
00791 /// instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now
00792 /// exists in the instruction stream.  Similarly this will inline a recursive
00793 /// function by one level.
00794 bool llvm::InlineFunction(CallSite CS, InlineFunctionInfo &IFI,
00795                           bool InsertLifetime) {
00796   Instruction *TheCall = CS.getInstruction();
00797   assert(TheCall->getParent() && TheCall->getParent()->getParent() &&
00798          "Instruction not in function!");
00799 
00800   // If IFI has any state in it, zap it before we fill it in.
00801   IFI.reset();
00802   
00803   const Function *CalledFunc = CS.getCalledFunction();
00804   if (!CalledFunc ||              // Can't inline external function or indirect
00805       CalledFunc->isDeclaration() || // call, or call to a vararg function!
00806       CalledFunc->getFunctionType()->isVarArg()) return false;
00807 
00808   // If the call to the callee cannot throw, set the 'nounwind' flag on any
00809   // calls that we inline.
00810   bool MarkNoUnwind = CS.doesNotThrow();
00811 
00812   BasicBlock *OrigBB = TheCall->getParent();
00813   Function *Caller = OrigBB->getParent();
00814 
00815   // GC poses two hazards to inlining, which only occur when the callee has GC:
00816   //  1. If the caller has no GC, then the callee's GC must be propagated to the
00817   //     caller.
00818   //  2. If the caller has a differing GC, it is invalid to inline.
00819   if (CalledFunc->hasGC()) {
00820     if (!Caller->hasGC())
00821       Caller->setGC(CalledFunc->getGC());
00822     else if (CalledFunc->getGC() != Caller->getGC())
00823       return false;
00824   }
00825 
00826   // Get the personality function from the callee if it contains a landing pad.
00827   Value *CalleePersonality = nullptr;
00828   for (Function::const_iterator I = CalledFunc->begin(), E = CalledFunc->end();
00829        I != E; ++I)
00830     if (const InvokeInst *II = dyn_cast<InvokeInst>(I->getTerminator())) {
00831       const BasicBlock *BB = II->getUnwindDest();
00832       const LandingPadInst *LP = BB->getLandingPadInst();
00833       CalleePersonality = LP->getPersonalityFn();
00834       break;
00835     }
00836 
00837   // Find the personality function used by the landing pads of the caller. If it
00838   // exists, then check to see that it matches the personality function used in
00839   // the callee.
00840   if (CalleePersonality) {
00841     for (Function::const_iterator I = Caller->begin(), E = Caller->end();
00842          I != E; ++I)
00843       if (const InvokeInst *II = dyn_cast<InvokeInst>(I->getTerminator())) {
00844         const BasicBlock *BB = II->getUnwindDest();
00845         const LandingPadInst *LP = BB->getLandingPadInst();
00846 
00847         // If the personality functions match, then we can perform the
00848         // inlining. Otherwise, we can't inline.
00849         // TODO: This isn't 100% true. Some personality functions are proper
00850         //       supersets of others and can be used in place of the other.
00851         if (LP->getPersonalityFn() != CalleePersonality)
00852           return false;
00853 
00854         break;
00855       }
00856   }
00857 
00858   // Get an iterator to the last basic block in the function, which will have
00859   // the new function inlined after it.
00860   Function::iterator LastBlock = &Caller->back();
00861 
00862   // Make sure to capture all of the return instructions from the cloned
00863   // function.
00864   SmallVector<ReturnInst*, 8> Returns;
00865   ClonedCodeInfo InlinedFunctionInfo;
00866   Function::iterator FirstNewBlock;
00867 
00868   { // Scope to destroy VMap after cloning.
00869     ValueToValueMapTy VMap;
00870     // Keep a list of pair (dst, src) to emit byval initializations.
00871     SmallVector<std::pair<Value*, Value*>, 4> ByValInit;
00872 
00873     assert(CalledFunc->arg_size() == CS.arg_size() &&
00874            "No varargs calls can be inlined!");
00875 
00876     // Calculate the vector of arguments to pass into the function cloner, which
00877     // matches up the formal to the actual argument values.
00878     CallSite::arg_iterator AI = CS.arg_begin();
00879     unsigned ArgNo = 0;
00880     for (Function::const_arg_iterator I = CalledFunc->arg_begin(),
00881          E = CalledFunc->arg_end(); I != E; ++I, ++AI, ++ArgNo) {
00882       Value *ActualArg = *AI;
00883 
00884       // When byval arguments actually inlined, we need to make the copy implied
00885       // by them explicit.  However, we don't do this if the callee is readonly
00886       // or readnone, because the copy would be unneeded: the callee doesn't
00887       // modify the struct.
00888       if (CS.isByValArgument(ArgNo)) {
00889         ActualArg = HandleByValArgument(ActualArg, TheCall, CalledFunc, IFI,
00890                                         CalledFunc->getParamAlignment(ArgNo+1));
00891         if (ActualArg != *AI)
00892           ByValInit.push_back(std::make_pair(ActualArg, (Value*) *AI));
00893       }
00894 
00895       VMap[I] = ActualArg;
00896     }
00897 
00898     // We want the inliner to prune the code as it copies.  We would LOVE to
00899     // have no dead or constant instructions leftover after inlining occurs
00900     // (which can happen, e.g., because an argument was constant), but we'll be
00901     // happy with whatever the cloner can do.
00902     CloneAndPruneFunctionInto(Caller, CalledFunc, VMap, 
00903                               /*ModuleLevelChanges=*/false, Returns, ".i",
00904                               &InlinedFunctionInfo, IFI.DL, TheCall);
00905 
00906     // Remember the first block that is newly cloned over.
00907     FirstNewBlock = LastBlock; ++FirstNewBlock;
00908 
00909     // Inject byval arguments initialization.
00910     for (std::pair<Value*, Value*> &Init : ByValInit)
00911       HandleByValArgumentInit(Init.first, Init.second, Caller->getParent(),
00912                               FirstNewBlock, IFI);
00913 
00914     // Update the callgraph if requested.
00915     if (IFI.CG)
00916       UpdateCallGraphAfterInlining(CS, FirstNewBlock, VMap, IFI);
00917 
00918     // Update inlined instructions' line number information.
00919     fixupLineNumbers(Caller, FirstNewBlock, TheCall);
00920 
00921     // Clone existing noalias metadata if necessary.
00922     CloneAliasScopeMetadata(CS, VMap);
00923 
00924     // Add noalias metadata if necessary.
00925     AddAliasScopeMetadata(CS, VMap, IFI.DL);
00926   }
00927 
00928   // If there are any alloca instructions in the block that used to be the entry
00929   // block for the callee, move them to the entry block of the caller.  First
00930   // calculate which instruction they should be inserted before.  We insert the
00931   // instructions at the end of the current alloca list.
00932   {
00933     BasicBlock::iterator InsertPoint = Caller->begin()->begin();
00934     for (BasicBlock::iterator I = FirstNewBlock->begin(),
00935          E = FirstNewBlock->end(); I != E; ) {
00936       AllocaInst *AI = dyn_cast<AllocaInst>(I++);
00937       if (!AI) continue;
00938       
00939       // If the alloca is now dead, remove it.  This often occurs due to code
00940       // specialization.
00941       if (AI->use_empty()) {
00942         AI->eraseFromParent();
00943         continue;
00944       }
00945 
00946       if (!isa<Constant>(AI->getArraySize()))
00947         continue;
00948       
00949       // Keep track of the static allocas that we inline into the caller.
00950       IFI.StaticAllocas.push_back(AI);
00951       
00952       // Scan for the block of allocas that we can move over, and move them
00953       // all at once.
00954       while (isa<AllocaInst>(I) &&
00955              isa<Constant>(cast<AllocaInst>(I)->getArraySize())) {
00956         IFI.StaticAllocas.push_back(cast<AllocaInst>(I));
00957         ++I;
00958       }
00959 
00960       // Transfer all of the allocas over in a block.  Using splice means
00961       // that the instructions aren't removed from the symbol table, then
00962       // reinserted.
00963       Caller->getEntryBlock().getInstList().splice(InsertPoint,
00964                                                    FirstNewBlock->getInstList(),
00965                                                    AI, I);
00966     }
00967   }
00968 
00969   bool InlinedMustTailCalls = false;
00970   if (InlinedFunctionInfo.ContainsCalls) {
00971     CallInst::TailCallKind CallSiteTailKind = CallInst::TCK_None;
00972     if (CallInst *CI = dyn_cast<CallInst>(TheCall))
00973       CallSiteTailKind = CI->getTailCallKind();
00974 
00975     for (Function::iterator BB = FirstNewBlock, E = Caller->end(); BB != E;
00976          ++BB) {
00977       for (Instruction &I : *BB) {
00978         CallInst *CI = dyn_cast<CallInst>(&I);
00979         if (!CI)
00980           continue;
00981 
00982         // We need to reduce the strength of any inlined tail calls.  For
00983         // musttail, we have to avoid introducing potential unbounded stack
00984         // growth.  For example, if functions 'f' and 'g' are mutually recursive
00985         // with musttail, we can inline 'g' into 'f' so long as we preserve
00986         // musttail on the cloned call to 'f'.  If either the inlined call site
00987         // or the cloned call site is *not* musttail, the program already has
00988         // one frame of stack growth, so it's safe to remove musttail.  Here is
00989         // a table of example transformations:
00990         //
00991         //    f -> musttail g -> musttail f  ==>  f -> musttail f
00992         //    f -> musttail g ->     tail f  ==>  f ->     tail f
00993         //    f ->          g -> musttail f  ==>  f ->          f
00994         //    f ->          g ->     tail f  ==>  f ->          f
00995         CallInst::TailCallKind ChildTCK = CI->getTailCallKind();
00996         ChildTCK = std::min(CallSiteTailKind, ChildTCK);
00997         CI->setTailCallKind(ChildTCK);
00998         InlinedMustTailCalls |= CI->isMustTailCall();
00999 
01000         // Calls inlined through a 'nounwind' call site should be marked
01001         // 'nounwind'.
01002         if (MarkNoUnwind)
01003           CI->setDoesNotThrow();
01004       }
01005     }
01006   }
01007 
01008   // Leave lifetime markers for the static alloca's, scoping them to the
01009   // function we just inlined.
01010   if (InsertLifetime && !IFI.StaticAllocas.empty()) {
01011     IRBuilder<> builder(FirstNewBlock->begin());
01012     for (unsigned ai = 0, ae = IFI.StaticAllocas.size(); ai != ae; ++ai) {
01013       AllocaInst *AI = IFI.StaticAllocas[ai];
01014 
01015       // If the alloca is already scoped to something smaller than the whole
01016       // function then there's no need to add redundant, less accurate markers.
01017       if (hasLifetimeMarkers(AI))
01018         continue;
01019 
01020       // Try to determine the size of the allocation.
01021       ConstantInt *AllocaSize = nullptr;
01022       if (ConstantInt *AIArraySize =
01023           dyn_cast<ConstantInt>(AI->getArraySize())) {
01024         if (IFI.DL) {
01025           Type *AllocaType = AI->getAllocatedType();
01026           uint64_t AllocaTypeSize = IFI.DL->getTypeAllocSize(AllocaType);
01027           uint64_t AllocaArraySize = AIArraySize->getLimitedValue();
01028           assert(AllocaArraySize > 0 && "array size of AllocaInst is zero");
01029           // Check that array size doesn't saturate uint64_t and doesn't
01030           // overflow when it's multiplied by type size.
01031           if (AllocaArraySize != ~0ULL &&
01032               UINT64_MAX / AllocaArraySize >= AllocaTypeSize) {
01033             AllocaSize = ConstantInt::get(Type::getInt64Ty(AI->getContext()),
01034                                           AllocaArraySize * AllocaTypeSize);
01035           }
01036         }
01037       }
01038 
01039       builder.CreateLifetimeStart(AI, AllocaSize);
01040       for (ReturnInst *RI : Returns) {
01041         // Don't insert llvm.lifetime.end calls between a musttail call and a
01042         // return.  The return kills all local allocas.
01043         if (InlinedMustTailCalls && getPrecedingMustTailCall(RI))
01044           continue;
01045         IRBuilder<>(RI).CreateLifetimeEnd(AI, AllocaSize);
01046       }
01047     }
01048   }
01049 
01050   // If the inlined code contained dynamic alloca instructions, wrap the inlined
01051   // code with llvm.stacksave/llvm.stackrestore intrinsics.
01052   if (InlinedFunctionInfo.ContainsDynamicAllocas) {
01053     Module *M = Caller->getParent();
01054     // Get the two intrinsics we care about.
01055     Function *StackSave = Intrinsic::getDeclaration(M, Intrinsic::stacksave);
01056     Function *StackRestore=Intrinsic::getDeclaration(M,Intrinsic::stackrestore);
01057 
01058     // Insert the llvm.stacksave.
01059     CallInst *SavedPtr = IRBuilder<>(FirstNewBlock, FirstNewBlock->begin())
01060       .CreateCall(StackSave, "savedstack");
01061 
01062     // Insert a call to llvm.stackrestore before any return instructions in the
01063     // inlined function.
01064     for (ReturnInst *RI : Returns) {
01065       // Don't insert llvm.stackrestore calls between a musttail call and a
01066       // return.  The return will restore the stack pointer.
01067       if (InlinedMustTailCalls && getPrecedingMustTailCall(RI))
01068         continue;
01069       IRBuilder<>(RI).CreateCall(StackRestore, SavedPtr);
01070     }
01071   }
01072 
01073   // If we are inlining for an invoke instruction, we must make sure to rewrite
01074   // any call instructions into invoke instructions.
01075   if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall))
01076     HandleInlinedInvoke(II, FirstNewBlock, InlinedFunctionInfo);
01077 
01078   // Handle any inlined musttail call sites.  In order for a new call site to be
01079   // musttail, the source of the clone and the inlined call site must have been
01080   // musttail.  Therefore it's safe to return without merging control into the
01081   // phi below.
01082   if (InlinedMustTailCalls) {
01083     // Check if we need to bitcast the result of any musttail calls.
01084     Type *NewRetTy = Caller->getReturnType();
01085     bool NeedBitCast = !TheCall->use_empty() && TheCall->getType() != NewRetTy;
01086 
01087     // Handle the returns preceded by musttail calls separately.
01088     SmallVector<ReturnInst *, 8> NormalReturns;
01089     for (ReturnInst *RI : Returns) {
01090       CallInst *ReturnedMustTail = getPrecedingMustTailCall(RI);
01091       if (!ReturnedMustTail) {
01092         NormalReturns.push_back(RI);
01093         continue;
01094       }
01095       if (!NeedBitCast)
01096         continue;
01097 
01098       // Delete the old return and any preceding bitcast.
01099       BasicBlock *CurBB = RI->getParent();
01100       auto *OldCast = dyn_cast_or_null<BitCastInst>(RI->getReturnValue());
01101       RI->eraseFromParent();
01102       if (OldCast)
01103         OldCast->eraseFromParent();
01104 
01105       // Insert a new bitcast and return with the right type.
01106       IRBuilder<> Builder(CurBB);
01107       Builder.CreateRet(Builder.CreateBitCast(ReturnedMustTail, NewRetTy));
01108     }
01109 
01110     // Leave behind the normal returns so we can merge control flow.
01111     std::swap(Returns, NormalReturns);
01112   }
01113 
01114   // If we cloned in _exactly one_ basic block, and if that block ends in a
01115   // return instruction, we splice the body of the inlined callee directly into
01116   // the calling basic block.
01117   if (Returns.size() == 1 && std::distance(FirstNewBlock, Caller->end()) == 1) {
01118     // Move all of the instructions right before the call.
01119     OrigBB->getInstList().splice(TheCall, FirstNewBlock->getInstList(),
01120                                  FirstNewBlock->begin(), FirstNewBlock->end());
01121     // Remove the cloned basic block.
01122     Caller->getBasicBlockList().pop_back();
01123 
01124     // If the call site was an invoke instruction, add a branch to the normal
01125     // destination.
01126     if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
01127       BranchInst *NewBr = BranchInst::Create(II->getNormalDest(), TheCall);
01128       NewBr->setDebugLoc(Returns[0]->getDebugLoc());
01129     }
01130 
01131     // If the return instruction returned a value, replace uses of the call with
01132     // uses of the returned value.
01133     if (!TheCall->use_empty()) {
01134       ReturnInst *R = Returns[0];
01135       if (TheCall == R->getReturnValue())
01136         TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
01137       else
01138         TheCall->replaceAllUsesWith(R->getReturnValue());
01139     }
01140     // Since we are now done with the Call/Invoke, we can delete it.
01141     TheCall->eraseFromParent();
01142 
01143     // Since we are now done with the return instruction, delete it also.
01144     Returns[0]->eraseFromParent();
01145 
01146     // We are now done with the inlining.
01147     return true;
01148   }
01149 
01150   // Otherwise, we have the normal case, of more than one block to inline or
01151   // multiple return sites.
01152 
01153   // We want to clone the entire callee function into the hole between the
01154   // "starter" and "ender" blocks.  How we accomplish this depends on whether
01155   // this is an invoke instruction or a call instruction.
01156   BasicBlock *AfterCallBB;
01157   BranchInst *CreatedBranchToNormalDest = nullptr;
01158   if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
01159 
01160     // Add an unconditional branch to make this look like the CallInst case...
01161     CreatedBranchToNormalDest = BranchInst::Create(II->getNormalDest(), TheCall);
01162 
01163     // Split the basic block.  This guarantees that no PHI nodes will have to be
01164     // updated due to new incoming edges, and make the invoke case more
01165     // symmetric to the call case.
01166     AfterCallBB = OrigBB->splitBasicBlock(CreatedBranchToNormalDest,
01167                                           CalledFunc->getName()+".exit");
01168 
01169   } else {  // It's a call
01170     // If this is a call instruction, we need to split the basic block that
01171     // the call lives in.
01172     //
01173     AfterCallBB = OrigBB->splitBasicBlock(TheCall,
01174                                           CalledFunc->getName()+".exit");
01175   }
01176 
01177   // Change the branch that used to go to AfterCallBB to branch to the first
01178   // basic block of the inlined function.
01179   //
01180   TerminatorInst *Br = OrigBB->getTerminator();
01181   assert(Br && Br->getOpcode() == Instruction::Br &&
01182          "splitBasicBlock broken!");
01183   Br->setOperand(0, FirstNewBlock);
01184 
01185 
01186   // Now that the function is correct, make it a little bit nicer.  In
01187   // particular, move the basic blocks inserted from the end of the function
01188   // into the space made by splitting the source basic block.
01189   Caller->getBasicBlockList().splice(AfterCallBB, Caller->getBasicBlockList(),
01190                                      FirstNewBlock, Caller->end());
01191 
01192   // Handle all of the return instructions that we just cloned in, and eliminate
01193   // any users of the original call/invoke instruction.
01194   Type *RTy = CalledFunc->getReturnType();
01195 
01196   PHINode *PHI = nullptr;
01197   if (Returns.size() > 1) {
01198     // The PHI node should go at the front of the new basic block to merge all
01199     // possible incoming values.
01200     if (!TheCall->use_empty()) {
01201       PHI = PHINode::Create(RTy, Returns.size(), TheCall->getName(),
01202                             AfterCallBB->begin());
01203       // Anything that used the result of the function call should now use the
01204       // PHI node as their operand.
01205       TheCall->replaceAllUsesWith(PHI);
01206     }
01207 
01208     // Loop over all of the return instructions adding entries to the PHI node
01209     // as appropriate.
01210     if (PHI) {
01211       for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
01212         ReturnInst *RI = Returns[i];
01213         assert(RI->getReturnValue()->getType() == PHI->getType() &&
01214                "Ret value not consistent in function!");
01215         PHI->addIncoming(RI->getReturnValue(), RI->getParent());
01216       }
01217     }
01218 
01219 
01220     // Add a branch to the merge points and remove return instructions.
01221     DebugLoc Loc;
01222     for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
01223       ReturnInst *RI = Returns[i];
01224       BranchInst* BI = BranchInst::Create(AfterCallBB, RI);
01225       Loc = RI->getDebugLoc();
01226       BI->setDebugLoc(Loc);
01227       RI->eraseFromParent();
01228     }
01229     // We need to set the debug location to *somewhere* inside the
01230     // inlined function. The line number may be nonsensical, but the
01231     // instruction will at least be associated with the right
01232     // function.
01233     if (CreatedBranchToNormalDest)
01234       CreatedBranchToNormalDest->setDebugLoc(Loc);
01235   } else if (!Returns.empty()) {
01236     // Otherwise, if there is exactly one return value, just replace anything
01237     // using the return value of the call with the computed value.
01238     if (!TheCall->use_empty()) {
01239       if (TheCall == Returns[0]->getReturnValue())
01240         TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
01241       else
01242         TheCall->replaceAllUsesWith(Returns[0]->getReturnValue());
01243     }
01244 
01245     // Update PHI nodes that use the ReturnBB to use the AfterCallBB.
01246     BasicBlock *ReturnBB = Returns[0]->getParent();
01247     ReturnBB->replaceAllUsesWith(AfterCallBB);
01248 
01249     // Splice the code from the return block into the block that it will return
01250     // to, which contains the code that was after the call.
01251     AfterCallBB->getInstList().splice(AfterCallBB->begin(),
01252                                       ReturnBB->getInstList());
01253 
01254     if (CreatedBranchToNormalDest)
01255       CreatedBranchToNormalDest->setDebugLoc(Returns[0]->getDebugLoc());
01256 
01257     // Delete the return instruction now and empty ReturnBB now.
01258     Returns[0]->eraseFromParent();
01259     ReturnBB->eraseFromParent();
01260   } else if (!TheCall->use_empty()) {
01261     // No returns, but something is using the return value of the call.  Just
01262     // nuke the result.
01263     TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
01264   }
01265 
01266   // Since we are now done with the Call/Invoke, we can delete it.
01267   TheCall->eraseFromParent();
01268 
01269   // If we inlined any musttail calls and the original return is now
01270   // unreachable, delete it.  It can only contain a bitcast and ret.
01271   if (InlinedMustTailCalls && pred_begin(AfterCallBB) == pred_end(AfterCallBB))
01272     AfterCallBB->eraseFromParent();
01273 
01274   // We should always be able to fold the entry block of the function into the
01275   // single predecessor of the block...
01276   assert(cast<BranchInst>(Br)->isUnconditional() && "splitBasicBlock broken!");
01277   BasicBlock *CalleeEntry = cast<BranchInst>(Br)->getSuccessor(0);
01278 
01279   // Splice the code entry block into calling block, right before the
01280   // unconditional branch.
01281   CalleeEntry->replaceAllUsesWith(OrigBB);  // Update PHI nodes
01282   OrigBB->getInstList().splice(Br, CalleeEntry->getInstList());
01283 
01284   // Remove the unconditional branch.
01285   OrigBB->getInstList().erase(Br);
01286 
01287   // Now we can remove the CalleeEntry block, which is now empty.
01288   Caller->getBasicBlockList().erase(CalleeEntry);
01289 
01290   // If we inserted a phi node, check to see if it has a single value (e.g. all
01291   // the entries are the same or undef).  If so, remove the PHI so it doesn't
01292   // block other optimizations.
01293   if (PHI) {
01294     if (Value *V = SimplifyInstruction(PHI, IFI.DL)) {
01295       PHI->replaceAllUsesWith(V);
01296       PHI->eraseFromParent();
01297     }
01298   }
01299 
01300   return true;
01301 }