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