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