[SimplifyLibCalls] Use hasFloatVersion(). NFCI.
[oota-llvm.git] / lib / Transforms / Utils / InlineFunction.cpp
1 //===- InlineFunction.cpp - Code to perform function inlining -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements inlining of a function into a call site, resolving
11 // parameters and the return value as appropriate.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/Transforms/Utils/Cloning.h"
16 #include "llvm/ADT/SmallSet.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/SetVector.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/Analysis/AliasAnalysis.h"
21 #include "llvm/Analysis/AssumptionCache.h"
22 #include "llvm/Analysis/CallGraph.h"
23 #include "llvm/Analysis/CaptureTracking.h"
24 #include "llvm/Analysis/InstructionSimplify.h"
25 #include "llvm/Analysis/ValueTracking.h"
26 #include "llvm/IR/Attributes.h"
27 #include "llvm/IR/CallSite.h"
28 #include "llvm/IR/CFG.h"
29 #include "llvm/IR/Constants.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/DebugInfo.h"
32 #include "llvm/IR/DerivedTypes.h"
33 #include "llvm/IR/DIBuilder.h"
34 #include "llvm/IR/Dominators.h"
35 #include "llvm/IR/IRBuilder.h"
36 #include "llvm/IR/Instructions.h"
37 #include "llvm/IR/IntrinsicInst.h"
38 #include "llvm/IR/Intrinsics.h"
39 #include "llvm/IR/MDBuilder.h"
40 #include "llvm/IR/Module.h"
41 #include "llvm/Transforms/Utils/Local.h"
42 #include "llvm/Support/CommandLine.h"
43 #include <algorithm>
44
45 using namespace llvm;
46
47 static cl::opt<bool>
48 EnableNoAliasConversion("enable-noalias-to-md-conversion", cl::init(true),
49   cl::Hidden,
50   cl::desc("Convert noalias attributes to metadata during inlining."));
51
52 static cl::opt<bool>
53 PreserveAlignmentAssumptions("preserve-alignment-assumptions-during-inlining",
54   cl::init(true), cl::Hidden,
55   cl::desc("Convert align attributes to assumptions during inlining."));
56
57 bool llvm::InlineFunction(CallInst *CI, InlineFunctionInfo &IFI,
58                           AAResults *CalleeAAR, bool InsertLifetime) {
59   return InlineFunction(CallSite(CI), IFI, CalleeAAR, InsertLifetime);
60 }
61 bool llvm::InlineFunction(InvokeInst *II, InlineFunctionInfo &IFI,
62                           AAResults *CalleeAAR, bool InsertLifetime) {
63   return InlineFunction(CallSite(II), IFI, CalleeAAR, InsertLifetime);
64 }
65
66 namespace {
67   /// A class for recording information about inlining a landing pad.
68   class LandingPadInliningInfo {
69     BasicBlock *OuterResumeDest; ///< Destination of the invoke's unwind.
70     BasicBlock *InnerResumeDest; ///< Destination for the callee's resume.
71     LandingPadInst *CallerLPad;  ///< LandingPadInst associated with the invoke.
72     PHINode *InnerEHValuesPHI;   ///< PHI for EH values from landingpad insts.
73     SmallVector<Value*, 8> UnwindDestPHIValues;
74
75   public:
76     LandingPadInliningInfo(InvokeInst *II)
77       : OuterResumeDest(II->getUnwindDest()), InnerResumeDest(nullptr),
78         CallerLPad(nullptr), InnerEHValuesPHI(nullptr) {
79       // If there are PHI nodes in the unwind destination block, we need to keep
80       // track of which values came into them from the invoke before removing
81       // the edge from this block.
82       llvm::BasicBlock *InvokeBB = II->getParent();
83       BasicBlock::iterator I = OuterResumeDest->begin();
84       for (; isa<PHINode>(I); ++I) {
85         // Save the value to use for this edge.
86         PHINode *PHI = cast<PHINode>(I);
87         UnwindDestPHIValues.push_back(PHI->getIncomingValueForBlock(InvokeBB));
88       }
89
90       CallerLPad = cast<LandingPadInst>(I);
91     }
92
93     /// The outer unwind destination is the target of
94     /// unwind edges introduced for calls within the inlined function.
95     BasicBlock *getOuterResumeDest() const {
96       return OuterResumeDest;
97     }
98
99     BasicBlock *getInnerResumeDest();
100
101     LandingPadInst *getLandingPadInst() const { return CallerLPad; }
102
103     /// Forward the 'resume' instruction to the caller's landing pad block.
104     /// When the landing pad block has only one predecessor, this is
105     /// a simple branch. When there is more than one predecessor, we need to
106     /// split the landing pad block after the landingpad instruction and jump
107     /// to there.
108     void forwardResume(ResumeInst *RI,
109                        SmallPtrSetImpl<LandingPadInst*> &InlinedLPads);
110
111     /// Add incoming-PHI values to the unwind destination block for the given
112     /// basic block, using the values for the original invoke's source block.
113     void addIncomingPHIValuesFor(BasicBlock *BB) const {
114       addIncomingPHIValuesForInto(BB, OuterResumeDest);
115     }
116
117     void addIncomingPHIValuesForInto(BasicBlock *src, BasicBlock *dest) const {
118       BasicBlock::iterator I = dest->begin();
119       for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) {
120         PHINode *phi = cast<PHINode>(I);
121         phi->addIncoming(UnwindDestPHIValues[i], src);
122       }
123     }
124   };
125 } // anonymous namespace
126
127 /// Get or create a target for the branch from ResumeInsts.
128 BasicBlock *LandingPadInliningInfo::getInnerResumeDest() {
129   if (InnerResumeDest) return InnerResumeDest;
130
131   // Split the landing pad.
132   BasicBlock::iterator SplitPoint = ++CallerLPad->getIterator();
133   InnerResumeDest =
134     OuterResumeDest->splitBasicBlock(SplitPoint,
135                                      OuterResumeDest->getName() + ".body");
136
137   // The number of incoming edges we expect to the inner landing pad.
138   const unsigned PHICapacity = 2;
139
140   // Create corresponding new PHIs for all the PHIs in the outer landing pad.
141   Instruction *InsertPoint = &InnerResumeDest->front();
142   BasicBlock::iterator I = OuterResumeDest->begin();
143   for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) {
144     PHINode *OuterPHI = cast<PHINode>(I);
145     PHINode *InnerPHI = PHINode::Create(OuterPHI->getType(), PHICapacity,
146                                         OuterPHI->getName() + ".lpad-body",
147                                         InsertPoint);
148     OuterPHI->replaceAllUsesWith(InnerPHI);
149     InnerPHI->addIncoming(OuterPHI, OuterResumeDest);
150   }
151
152   // Create a PHI for the exception values.
153   InnerEHValuesPHI = PHINode::Create(CallerLPad->getType(), PHICapacity,
154                                      "eh.lpad-body", InsertPoint);
155   CallerLPad->replaceAllUsesWith(InnerEHValuesPHI);
156   InnerEHValuesPHI->addIncoming(CallerLPad, OuterResumeDest);
157
158   // All done.
159   return InnerResumeDest;
160 }
161
162 /// Forward the 'resume' instruction to the caller's landing pad block.
163 /// When the landing pad block has only one predecessor, this is a simple
164 /// branch. When there is more than one predecessor, we need to split the
165 /// landing pad block after the landingpad instruction and jump to there.
166 void LandingPadInliningInfo::forwardResume(
167     ResumeInst *RI, SmallPtrSetImpl<LandingPadInst *> &InlinedLPads) {
168   BasicBlock *Dest = getInnerResumeDest();
169   BasicBlock *Src = RI->getParent();
170
171   BranchInst::Create(Dest, Src);
172
173   // Update the PHIs in the destination. They were inserted in an order which
174   // makes this work.
175   addIncomingPHIValuesForInto(Src, Dest);
176
177   InnerEHValuesPHI->addIncoming(RI->getOperand(0), Src);
178   RI->eraseFromParent();
179 }
180
181 /// When we inline a basic block into an invoke,
182 /// we have to turn all of the calls that can throw into invokes.
183 /// This function analyze BB to see if there are any calls, and if so,
184 /// it rewrites them to be invokes that jump to InvokeDest and fills in the PHI
185 /// nodes in that block with the values specified in InvokeDestPHIValues.
186 static BasicBlock *
187 HandleCallsInBlockInlinedThroughInvoke(BasicBlock *BB, BasicBlock *UnwindEdge) {
188   for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
189     Instruction *I = &*BBI++;
190
191     // We only need to check for function calls: inlined invoke
192     // instructions require no special handling.
193     CallInst *CI = dyn_cast<CallInst>(I);
194
195     // If this call cannot unwind, don't convert it to an invoke.
196     // Inline asm calls cannot throw.
197     if (!CI || CI->doesNotThrow() || isa<InlineAsm>(CI->getCalledValue()))
198       continue;
199
200     // Convert this function call into an invoke instruction.  First, split the
201     // basic block.
202     BasicBlock *Split =
203         BB->splitBasicBlock(CI->getIterator(), CI->getName() + ".noexc");
204
205     // Delete the unconditional branch inserted by splitBasicBlock
206     BB->getInstList().pop_back();
207
208     // Create the new invoke instruction.
209     ImmutableCallSite CS(CI);
210     SmallVector<Value*, 8> InvokeArgs(CS.arg_begin(), CS.arg_end());
211     InvokeInst *II = InvokeInst::Create(CI->getCalledValue(), Split, UnwindEdge,
212                                         InvokeArgs, CI->getName(), BB);
213     II->setDebugLoc(CI->getDebugLoc());
214     II->setCallingConv(CI->getCallingConv());
215     II->setAttributes(CI->getAttributes());
216     
217     // Make sure that anything using the call now uses the invoke!  This also
218     // updates the CallGraph if present, because it uses a WeakVH.
219     CI->replaceAllUsesWith(II);
220
221     // Delete the original call
222     Split->getInstList().pop_front();
223     return BB;
224   }
225   return nullptr;
226 }
227
228 /// If we inlined an invoke site, we need to convert calls
229 /// in the body of the inlined function into invokes.
230 ///
231 /// II is the invoke instruction being inlined.  FirstNewBlock is the first
232 /// block of the inlined code (the last block is the end of the function),
233 /// and InlineCodeInfo is information about the code that got inlined.
234 static void HandleInlinedLandingPad(InvokeInst *II, BasicBlock *FirstNewBlock,
235                                     ClonedCodeInfo &InlinedCodeInfo) {
236   BasicBlock *InvokeDest = II->getUnwindDest();
237
238   Function *Caller = FirstNewBlock->getParent();
239
240   // The inlined code is currently at the end of the function, scan from the
241   // start of the inlined code to its end, checking for stuff we need to
242   // rewrite.
243   LandingPadInliningInfo Invoke(II);
244
245   // Get all of the inlined landing pad instructions.
246   SmallPtrSet<LandingPadInst*, 16> InlinedLPads;
247   for (Function::iterator I = FirstNewBlock->getIterator(), E = Caller->end();
248        I != E; ++I)
249     if (InvokeInst *II = dyn_cast<InvokeInst>(I->getTerminator()))
250       InlinedLPads.insert(II->getLandingPadInst());
251
252   // Append the clauses from the outer landing pad instruction into the inlined
253   // landing pad instructions.
254   LandingPadInst *OuterLPad = Invoke.getLandingPadInst();
255   for (LandingPadInst *InlinedLPad : InlinedLPads) {
256     unsigned OuterNum = OuterLPad->getNumClauses();
257     InlinedLPad->reserveClauses(OuterNum);
258     for (unsigned OuterIdx = 0; OuterIdx != OuterNum; ++OuterIdx)
259       InlinedLPad->addClause(OuterLPad->getClause(OuterIdx));
260     if (OuterLPad->isCleanup())
261       InlinedLPad->setCleanup(true);
262   }
263
264   for (Function::iterator BB = FirstNewBlock->getIterator(), E = Caller->end();
265        BB != E; ++BB) {
266     if (InlinedCodeInfo.ContainsCalls)
267       if (BasicBlock *NewBB = HandleCallsInBlockInlinedThroughInvoke(
268               &*BB, Invoke.getOuterResumeDest()))
269         // Update any PHI nodes in the exceptional block to indicate that there
270         // is now a new entry in them.
271         Invoke.addIncomingPHIValuesFor(NewBB);
272
273     // Forward any resumes that are remaining here.
274     if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator()))
275       Invoke.forwardResume(RI, InlinedLPads);
276   }
277
278   // Now that everything is happy, we have one final detail.  The PHI nodes in
279   // the exception destination block still have entries due to the original
280   // invoke instruction. Eliminate these entries (which might even delete the
281   // PHI node) now.
282   InvokeDest->removePredecessor(II->getParent());
283 }
284
285 /// If we inlined an invoke site, we need to convert calls
286 /// in the body of the inlined function into invokes.
287 ///
288 /// II is the invoke instruction being inlined.  FirstNewBlock is the first
289 /// block of the inlined code (the last block is the end of the function),
290 /// and InlineCodeInfo is information about the code that got inlined.
291 static void HandleInlinedEHPad(InvokeInst *II, BasicBlock *FirstNewBlock,
292                                ClonedCodeInfo &InlinedCodeInfo) {
293   BasicBlock *UnwindDest = II->getUnwindDest();
294   Function *Caller = FirstNewBlock->getParent();
295
296   assert(UnwindDest->getFirstNonPHI()->isEHPad() && "unexpected BasicBlock!");
297
298   // If there are PHI nodes in the unwind destination block, we need to keep
299   // track of which values came into them from the invoke before removing the
300   // edge from this block.
301   SmallVector<Value *, 8> UnwindDestPHIValues;
302   llvm::BasicBlock *InvokeBB = II->getParent();
303   for (Instruction &I : *UnwindDest) {
304     // Save the value to use for this edge.
305     PHINode *PHI = dyn_cast<PHINode>(&I);
306     if (!PHI)
307       break;
308     UnwindDestPHIValues.push_back(PHI->getIncomingValueForBlock(InvokeBB));
309   }
310
311   // Add incoming-PHI values to the unwind destination block for the given basic
312   // block, using the values for the original invoke's source block.
313   auto UpdatePHINodes = [&](BasicBlock *Src) {
314     BasicBlock::iterator I = UnwindDest->begin();
315     for (Value *V : UnwindDestPHIValues) {
316       PHINode *PHI = cast<PHINode>(I);
317       PHI->addIncoming(V, Src);
318       ++I;
319     }
320   };
321
322   // Forward EH terminator instructions to the caller's invoke destination.
323   // This is as simple as connect all the instructions which 'unwind to caller'
324   // to the invoke destination.
325   for (Function::iterator BB = FirstNewBlock->getIterator(), E = Caller->end();
326        BB != E; ++BB) {
327     Instruction *I = BB->getFirstNonPHI();
328     if (I->isEHPad()) {
329       if (auto *CEPI = dyn_cast<CatchEndPadInst>(I)) {
330         if (CEPI->unwindsToCaller()) {
331           CatchEndPadInst::Create(CEPI->getContext(), UnwindDest, CEPI);
332           CEPI->eraseFromParent();
333           UpdatePHINodes(&*BB);
334         }
335       } else if (auto *CEPI = dyn_cast<CleanupEndPadInst>(I)) {
336         if (CEPI->unwindsToCaller()) {
337           CleanupEndPadInst::Create(CEPI->getCleanupPad(), UnwindDest, CEPI);
338           CEPI->eraseFromParent();
339           UpdatePHINodes(&*BB);
340         }
341       } else if (auto *TPI = dyn_cast<TerminatePadInst>(I)) {
342         if (TPI->unwindsToCaller()) {
343           SmallVector<Value *, 3> TerminatePadArgs;
344           for (Value *ArgOperand : TPI->arg_operands())
345             TerminatePadArgs.push_back(ArgOperand);
346           TerminatePadInst::Create(TPI->getContext(), UnwindDest,
347                                    TerminatePadArgs, TPI);
348           TPI->eraseFromParent();
349           UpdatePHINodes(&*BB);
350         }
351       } else {
352         assert(isa<CatchPadInst>(I) || isa<CleanupPadInst>(I));
353       }
354     }
355
356     if (auto *CRI = dyn_cast<CleanupReturnInst>(BB->getTerminator())) {
357       if (CRI->unwindsToCaller()) {
358         CleanupReturnInst::Create(CRI->getCleanupPad(), UnwindDest, CRI);
359         CRI->eraseFromParent();
360         UpdatePHINodes(&*BB);
361       }
362     }
363   }
364
365   if (InlinedCodeInfo.ContainsCalls)
366     for (Function::iterator BB = FirstNewBlock->getIterator(),
367                             E = Caller->end();
368          BB != E; ++BB)
369       if (BasicBlock *NewBB =
370               HandleCallsInBlockInlinedThroughInvoke(&*BB, UnwindDest))
371         // Update any PHI nodes in the exceptional block to indicate that there
372         // is now a new entry in them.
373         UpdatePHINodes(NewBB);
374
375   // Now that everything is happy, we have one final detail.  The PHI nodes in
376   // the exception destination block still have entries due to the original
377   // invoke instruction. Eliminate these entries (which might even delete the
378   // PHI node) now.
379   UnwindDest->removePredecessor(InvokeBB);
380 }
381
382 /// When inlining a function that contains noalias scope metadata,
383 /// this metadata needs to be cloned so that the inlined blocks
384 /// have different "unqiue scopes" at every call site. Were this not done, then
385 /// aliasing scopes from a function inlined into a caller multiple times could
386 /// not be differentiated (and this would lead to miscompiles because the
387 /// non-aliasing property communicated by the metadata could have
388 /// call-site-specific control dependencies).
389 static void CloneAliasScopeMetadata(CallSite CS, ValueToValueMapTy &VMap) {
390   const Function *CalledFunc = CS.getCalledFunction();
391   SetVector<const MDNode *> MD;
392
393   // Note: We could only clone the metadata if it is already used in the
394   // caller. I'm omitting that check here because it might confuse
395   // inter-procedural alias analysis passes. We can revisit this if it becomes
396   // an efficiency or overhead problem.
397
398   for (Function::const_iterator I = CalledFunc->begin(), IE = CalledFunc->end();
399        I != IE; ++I)
400     for (BasicBlock::const_iterator J = I->begin(), JE = I->end(); J != JE; ++J) {
401       if (const MDNode *M = J->getMetadata(LLVMContext::MD_alias_scope))
402         MD.insert(M);
403       if (const MDNode *M = J->getMetadata(LLVMContext::MD_noalias))
404         MD.insert(M);
405     }
406
407   if (MD.empty())
408     return;
409
410   // Walk the existing metadata, adding the complete (perhaps cyclic) chain to
411   // the set.
412   SmallVector<const Metadata *, 16> Queue(MD.begin(), MD.end());
413   while (!Queue.empty()) {
414     const MDNode *M = cast<MDNode>(Queue.pop_back_val());
415     for (unsigned i = 0, ie = M->getNumOperands(); i != ie; ++i)
416       if (const MDNode *M1 = dyn_cast<MDNode>(M->getOperand(i)))
417         if (MD.insert(M1))
418           Queue.push_back(M1);
419   }
420
421   // Now we have a complete set of all metadata in the chains used to specify
422   // the noalias scopes and the lists of those scopes.
423   SmallVector<TempMDTuple, 16> DummyNodes;
424   DenseMap<const MDNode *, TrackingMDNodeRef> MDMap;
425   for (SetVector<const MDNode *>::iterator I = MD.begin(), IE = MD.end();
426        I != IE; ++I) {
427     DummyNodes.push_back(MDTuple::getTemporary(CalledFunc->getContext(), None));
428     MDMap[*I].reset(DummyNodes.back().get());
429   }
430
431   // Create new metadata nodes to replace the dummy nodes, replacing old
432   // metadata references with either a dummy node or an already-created new
433   // node.
434   for (SetVector<const MDNode *>::iterator I = MD.begin(), IE = MD.end();
435        I != IE; ++I) {
436     SmallVector<Metadata *, 4> NewOps;
437     for (unsigned i = 0, ie = (*I)->getNumOperands(); i != ie; ++i) {
438       const Metadata *V = (*I)->getOperand(i);
439       if (const MDNode *M = dyn_cast<MDNode>(V))
440         NewOps.push_back(MDMap[M]);
441       else
442         NewOps.push_back(const_cast<Metadata *>(V));
443     }
444
445     MDNode *NewM = MDNode::get(CalledFunc->getContext(), NewOps);
446     MDTuple *TempM = cast<MDTuple>(MDMap[*I]);
447     assert(TempM->isTemporary() && "Expected temporary node");
448
449     TempM->replaceAllUsesWith(NewM);
450   }
451
452   // Now replace the metadata in the new inlined instructions with the
453   // repacements from the map.
454   for (ValueToValueMapTy::iterator VMI = VMap.begin(), VMIE = VMap.end();
455        VMI != VMIE; ++VMI) {
456     if (!VMI->second)
457       continue;
458
459     Instruction *NI = dyn_cast<Instruction>(VMI->second);
460     if (!NI)
461       continue;
462
463     if (MDNode *M = NI->getMetadata(LLVMContext::MD_alias_scope)) {
464       MDNode *NewMD = MDMap[M];
465       // If the call site also had alias scope metadata (a list of scopes to
466       // which instructions inside it might belong), propagate those scopes to
467       // the inlined instructions.
468       if (MDNode *CSM =
469               CS.getInstruction()->getMetadata(LLVMContext::MD_alias_scope))
470         NewMD = MDNode::concatenate(NewMD, CSM);
471       NI->setMetadata(LLVMContext::MD_alias_scope, NewMD);
472     } else if (NI->mayReadOrWriteMemory()) {
473       if (MDNode *M =
474               CS.getInstruction()->getMetadata(LLVMContext::MD_alias_scope))
475         NI->setMetadata(LLVMContext::MD_alias_scope, M);
476     }
477
478     if (MDNode *M = NI->getMetadata(LLVMContext::MD_noalias)) {
479       MDNode *NewMD = MDMap[M];
480       // If the call site also had noalias metadata (a list of scopes with
481       // which instructions inside it don't alias), propagate those scopes to
482       // the inlined instructions.
483       if (MDNode *CSM =
484               CS.getInstruction()->getMetadata(LLVMContext::MD_noalias))
485         NewMD = MDNode::concatenate(NewMD, CSM);
486       NI->setMetadata(LLVMContext::MD_noalias, NewMD);
487     } else if (NI->mayReadOrWriteMemory()) {
488       if (MDNode *M = CS.getInstruction()->getMetadata(LLVMContext::MD_noalias))
489         NI->setMetadata(LLVMContext::MD_noalias, M);
490     }
491   }
492 }
493
494 /// If the inlined function has noalias arguments,
495 /// then add new alias scopes for each noalias argument, tag the mapped noalias
496 /// parameters with noalias metadata specifying the new scope, and tag all
497 /// non-derived loads, stores and memory intrinsics with the new alias scopes.
498 static void AddAliasScopeMetadata(CallSite CS, ValueToValueMapTy &VMap,
499                                   const DataLayout &DL, AAResults *CalleeAAR) {
500   if (!EnableNoAliasConversion)
501     return;
502
503   const Function *CalledFunc = CS.getCalledFunction();
504   SmallVector<const Argument *, 4> NoAliasArgs;
505
506   for (const Argument &I : CalledFunc->args()) {
507     if (I.hasNoAliasAttr() && !I.hasNUses(0))
508       NoAliasArgs.push_back(&I);
509   }
510
511   if (NoAliasArgs.empty())
512     return;
513
514   // To do a good job, if a noalias variable is captured, we need to know if
515   // the capture point dominates the particular use we're considering.
516   DominatorTree DT;
517   DT.recalculate(const_cast<Function&>(*CalledFunc));
518
519   // noalias indicates that pointer values based on the argument do not alias
520   // pointer values which are not based on it. So we add a new "scope" for each
521   // noalias function argument. Accesses using pointers based on that argument
522   // become part of that alias scope, accesses using pointers not based on that
523   // argument are tagged as noalias with that scope.
524
525   DenseMap<const Argument *, MDNode *> NewScopes;
526   MDBuilder MDB(CalledFunc->getContext());
527
528   // Create a new scope domain for this function.
529   MDNode *NewDomain =
530     MDB.createAnonymousAliasScopeDomain(CalledFunc->getName());
531   for (unsigned i = 0, e = NoAliasArgs.size(); i != e; ++i) {
532     const Argument *A = NoAliasArgs[i];
533
534     std::string Name = CalledFunc->getName();
535     if (A->hasName()) {
536       Name += ": %";
537       Name += A->getName();
538     } else {
539       Name += ": argument ";
540       Name += utostr(i);
541     }
542
543     // Note: We always create a new anonymous root here. This is true regardless
544     // of the linkage of the callee because the aliasing "scope" is not just a
545     // property of the callee, but also all control dependencies in the caller.
546     MDNode *NewScope = MDB.createAnonymousAliasScope(NewDomain, Name);
547     NewScopes.insert(std::make_pair(A, NewScope));
548   }
549
550   // Iterate over all new instructions in the map; for all memory-access
551   // instructions, add the alias scope metadata.
552   for (ValueToValueMapTy::iterator VMI = VMap.begin(), VMIE = VMap.end();
553        VMI != VMIE; ++VMI) {
554     if (const Instruction *I = dyn_cast<Instruction>(VMI->first)) {
555       if (!VMI->second)
556         continue;
557
558       Instruction *NI = dyn_cast<Instruction>(VMI->second);
559       if (!NI)
560         continue;
561
562       bool IsArgMemOnlyCall = false, IsFuncCall = false;
563       SmallVector<const Value *, 2> PtrArgs;
564
565       if (const LoadInst *LI = dyn_cast<LoadInst>(I))
566         PtrArgs.push_back(LI->getPointerOperand());
567       else if (const StoreInst *SI = dyn_cast<StoreInst>(I))
568         PtrArgs.push_back(SI->getPointerOperand());
569       else if (const VAArgInst *VAAI = dyn_cast<VAArgInst>(I))
570         PtrArgs.push_back(VAAI->getPointerOperand());
571       else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I))
572         PtrArgs.push_back(CXI->getPointerOperand());
573       else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I))
574         PtrArgs.push_back(RMWI->getPointerOperand());
575       else if (ImmutableCallSite ICS = ImmutableCallSite(I)) {
576         // If we know that the call does not access memory, then we'll still
577         // know that about the inlined clone of this call site, and we don't
578         // need to add metadata.
579         if (ICS.doesNotAccessMemory())
580           continue;
581
582         IsFuncCall = true;
583         if (CalleeAAR) {
584           FunctionModRefBehavior MRB = CalleeAAR->getModRefBehavior(ICS);
585           if (MRB == FMRB_OnlyAccessesArgumentPointees ||
586               MRB == FMRB_OnlyReadsArgumentPointees)
587             IsArgMemOnlyCall = true;
588         }
589
590         for (ImmutableCallSite::arg_iterator AI = ICS.arg_begin(),
591              AE = ICS.arg_end(); AI != AE; ++AI) {
592           // We need to check the underlying objects of all arguments, not just
593           // the pointer arguments, because we might be passing pointers as
594           // integers, etc.
595           // However, if we know that the call only accesses pointer arguments,
596           // then we only need to check the pointer arguments.
597           if (IsArgMemOnlyCall && !(*AI)->getType()->isPointerTy())
598             continue;
599
600           PtrArgs.push_back(*AI);
601         }
602       }
603
604       // If we found no pointers, then this instruction is not suitable for
605       // pairing with an instruction to receive aliasing metadata.
606       // However, if this is a call, this we might just alias with none of the
607       // noalias arguments.
608       if (PtrArgs.empty() && !IsFuncCall)
609         continue;
610
611       // It is possible that there is only one underlying object, but you
612       // need to go through several PHIs to see it, and thus could be
613       // repeated in the Objects list.
614       SmallPtrSet<const Value *, 4> ObjSet;
615       SmallVector<Metadata *, 4> Scopes, NoAliases;
616
617       SmallSetVector<const Argument *, 4> NAPtrArgs;
618       for (unsigned i = 0, ie = PtrArgs.size(); i != ie; ++i) {
619         SmallVector<Value *, 4> Objects;
620         GetUnderlyingObjects(const_cast<Value*>(PtrArgs[i]),
621                              Objects, DL, /* LI = */ nullptr);
622
623         for (Value *O : Objects)
624           ObjSet.insert(O);
625       }
626
627       // Figure out if we're derived from anything that is not a noalias
628       // argument.
629       bool CanDeriveViaCapture = false, UsesAliasingPtr = false;
630       for (const Value *V : ObjSet) {
631         // Is this value a constant that cannot be derived from any pointer
632         // value (we need to exclude constant expressions, for example, that
633         // are formed from arithmetic on global symbols).
634         bool IsNonPtrConst = isa<ConstantInt>(V) || isa<ConstantFP>(V) ||
635                              isa<ConstantPointerNull>(V) ||
636                              isa<ConstantDataVector>(V) || isa<UndefValue>(V);
637         if (IsNonPtrConst)
638           continue;
639
640         // If this is anything other than a noalias argument, then we cannot
641         // completely describe the aliasing properties using alias.scope
642         // metadata (and, thus, won't add any).
643         if (const Argument *A = dyn_cast<Argument>(V)) {
644           if (!A->hasNoAliasAttr())
645             UsesAliasingPtr = true;
646         } else {
647           UsesAliasingPtr = true;
648         }
649
650         // If this is not some identified function-local object (which cannot
651         // directly alias a noalias argument), or some other argument (which,
652         // by definition, also cannot alias a noalias argument), then we could
653         // alias a noalias argument that has been captured).
654         if (!isa<Argument>(V) &&
655             !isIdentifiedFunctionLocal(const_cast<Value*>(V)))
656           CanDeriveViaCapture = true;
657       }
658
659       // A function call can always get captured noalias pointers (via other
660       // parameters, globals, etc.).
661       if (IsFuncCall && !IsArgMemOnlyCall)
662         CanDeriveViaCapture = true;
663
664       // First, we want to figure out all of the sets with which we definitely
665       // don't alias. Iterate over all noalias set, and add those for which:
666       //   1. The noalias argument is not in the set of objects from which we
667       //      definitely derive.
668       //   2. The noalias argument has not yet been captured.
669       // An arbitrary function that might load pointers could see captured
670       // noalias arguments via other noalias arguments or globals, and so we
671       // must always check for prior capture.
672       for (const Argument *A : NoAliasArgs) {
673         if (!ObjSet.count(A) && (!CanDeriveViaCapture ||
674                                  // It might be tempting to skip the
675                                  // PointerMayBeCapturedBefore check if
676                                  // A->hasNoCaptureAttr() is true, but this is
677                                  // incorrect because nocapture only guarantees
678                                  // that no copies outlive the function, not
679                                  // that the value cannot be locally captured.
680                                  !PointerMayBeCapturedBefore(A,
681                                    /* ReturnCaptures */ false,
682                                    /* StoreCaptures */ false, I, &DT)))
683           NoAliases.push_back(NewScopes[A]);
684       }
685
686       if (!NoAliases.empty())
687         NI->setMetadata(LLVMContext::MD_noalias,
688                         MDNode::concatenate(
689                             NI->getMetadata(LLVMContext::MD_noalias),
690                             MDNode::get(CalledFunc->getContext(), NoAliases)));
691
692       // Next, we want to figure out all of the sets to which we might belong.
693       // We might belong to a set if the noalias argument is in the set of
694       // underlying objects. If there is some non-noalias argument in our list
695       // of underlying objects, then we cannot add a scope because the fact
696       // that some access does not alias with any set of our noalias arguments
697       // cannot itself guarantee that it does not alias with this access
698       // (because there is some pointer of unknown origin involved and the
699       // other access might also depend on this pointer). We also cannot add
700       // scopes to arbitrary functions unless we know they don't access any
701       // non-parameter pointer-values.
702       bool CanAddScopes = !UsesAliasingPtr;
703       if (CanAddScopes && IsFuncCall)
704         CanAddScopes = IsArgMemOnlyCall;
705
706       if (CanAddScopes)
707         for (const Argument *A : NoAliasArgs) {
708           if (ObjSet.count(A))
709             Scopes.push_back(NewScopes[A]);
710         }
711
712       if (!Scopes.empty())
713         NI->setMetadata(
714             LLVMContext::MD_alias_scope,
715             MDNode::concatenate(NI->getMetadata(LLVMContext::MD_alias_scope),
716                                 MDNode::get(CalledFunc->getContext(), Scopes)));
717     }
718   }
719 }
720
721 /// If the inlined function has non-byval align arguments, then
722 /// add @llvm.assume-based alignment assumptions to preserve this information.
723 static void AddAlignmentAssumptions(CallSite CS, InlineFunctionInfo &IFI) {
724   if (!PreserveAlignmentAssumptions)
725     return;
726   auto &DL = CS.getCaller()->getParent()->getDataLayout();
727
728   // To avoid inserting redundant assumptions, we should check for assumptions
729   // already in the caller. To do this, we might need a DT of the caller.
730   DominatorTree DT;
731   bool DTCalculated = false;
732
733   Function *CalledFunc = CS.getCalledFunction();
734   for (Function::arg_iterator I = CalledFunc->arg_begin(),
735                               E = CalledFunc->arg_end();
736        I != E; ++I) {
737     unsigned Align = I->getType()->isPointerTy() ? I->getParamAlignment() : 0;
738     if (Align && !I->hasByValOrInAllocaAttr() && !I->hasNUses(0)) {
739       if (!DTCalculated) {
740         DT.recalculate(const_cast<Function&>(*CS.getInstruction()->getParent()
741                                                ->getParent()));
742         DTCalculated = true;
743       }
744
745       // If we can already prove the asserted alignment in the context of the
746       // caller, then don't bother inserting the assumption.
747       Value *Arg = CS.getArgument(I->getArgNo());
748       if (getKnownAlignment(Arg, DL, CS.getInstruction(),
749                             &IFI.ACT->getAssumptionCache(*CS.getCaller()),
750                             &DT) >= Align)
751         continue;
752
753       IRBuilder<>(CS.getInstruction())
754           .CreateAlignmentAssumption(DL, Arg, Align);
755     }
756   }
757 }
758
759 /// Once we have cloned code over from a callee into the caller,
760 /// update the specified callgraph to reflect the changes we made.
761 /// Note that it's possible that not all code was copied over, so only
762 /// some edges of the callgraph may remain.
763 static void UpdateCallGraphAfterInlining(CallSite CS,
764                                          Function::iterator FirstNewBlock,
765                                          ValueToValueMapTy &VMap,
766                                          InlineFunctionInfo &IFI) {
767   CallGraph &CG = *IFI.CG;
768   const Function *Caller = CS.getInstruction()->getParent()->getParent();
769   const Function *Callee = CS.getCalledFunction();
770   CallGraphNode *CalleeNode = CG[Callee];
771   CallGraphNode *CallerNode = CG[Caller];
772
773   // Since we inlined some uninlined call sites in the callee into the caller,
774   // add edges from the caller to all of the callees of the callee.
775   CallGraphNode::iterator I = CalleeNode->begin(), E = CalleeNode->end();
776
777   // Consider the case where CalleeNode == CallerNode.
778   CallGraphNode::CalledFunctionsVector CallCache;
779   if (CalleeNode == CallerNode) {
780     CallCache.assign(I, E);
781     I = CallCache.begin();
782     E = CallCache.end();
783   }
784
785   for (; I != E; ++I) {
786     const Value *OrigCall = I->first;
787
788     ValueToValueMapTy::iterator VMI = VMap.find(OrigCall);
789     // Only copy the edge if the call was inlined!
790     if (VMI == VMap.end() || VMI->second == nullptr)
791       continue;
792     
793     // If the call was inlined, but then constant folded, there is no edge to
794     // add.  Check for this case.
795     Instruction *NewCall = dyn_cast<Instruction>(VMI->second);
796     if (!NewCall)
797       continue;
798
799     // We do not treat intrinsic calls like real function calls because we
800     // expect them to become inline code; do not add an edge for an intrinsic.
801     CallSite CS = CallSite(NewCall);
802     if (CS && CS.getCalledFunction() && CS.getCalledFunction()->isIntrinsic())
803       continue;
804     
805     // Remember that this call site got inlined for the client of
806     // InlineFunction.
807     IFI.InlinedCalls.push_back(NewCall);
808
809     // It's possible that inlining the callsite will cause it to go from an
810     // indirect to a direct call by resolving a function pointer.  If this
811     // happens, set the callee of the new call site to a more precise
812     // destination.  This can also happen if the call graph node of the caller
813     // was just unnecessarily imprecise.
814     if (!I->second->getFunction())
815       if (Function *F = CallSite(NewCall).getCalledFunction()) {
816         // Indirect call site resolved to direct call.
817         CallerNode->addCalledFunction(CallSite(NewCall), CG[F]);
818
819         continue;
820       }
821
822     CallerNode->addCalledFunction(CallSite(NewCall), I->second);
823   }
824   
825   // Update the call graph by deleting the edge from Callee to Caller.  We must
826   // do this after the loop above in case Caller and Callee are the same.
827   CallerNode->removeCallEdgeFor(CS);
828 }
829
830 static void HandleByValArgumentInit(Value *Dst, Value *Src, Module *M,
831                                     BasicBlock *InsertBlock,
832                                     InlineFunctionInfo &IFI) {
833   Type *AggTy = cast<PointerType>(Src->getType())->getElementType();
834   IRBuilder<> Builder(InsertBlock, InsertBlock->begin());
835
836   Value *Size = Builder.getInt64(M->getDataLayout().getTypeStoreSize(AggTy));
837
838   // Always generate a memcpy of alignment 1 here because we don't know
839   // the alignment of the src pointer.  Other optimizations can infer
840   // better alignment.
841   Builder.CreateMemCpy(Dst, Src, Size, /*Align=*/1);
842 }
843
844 /// When inlining a call site that has a byval argument,
845 /// we have to make the implicit memcpy explicit by adding it.
846 static Value *HandleByValArgument(Value *Arg, Instruction *TheCall,
847                                   const Function *CalledFunc,
848                                   InlineFunctionInfo &IFI,
849                                   unsigned ByValAlignment) {
850   PointerType *ArgTy = cast<PointerType>(Arg->getType());
851   Type *AggTy = ArgTy->getElementType();
852
853   Function *Caller = TheCall->getParent()->getParent();
854
855   // If the called function is readonly, then it could not mutate the caller's
856   // copy of the byval'd memory.  In this case, it is safe to elide the copy and
857   // temporary.
858   if (CalledFunc->onlyReadsMemory()) {
859     // If the byval argument has a specified alignment that is greater than the
860     // passed in pointer, then we either have to round up the input pointer or
861     // give up on this transformation.
862     if (ByValAlignment <= 1)  // 0 = unspecified, 1 = no particular alignment.
863       return Arg;
864
865     const DataLayout &DL = Caller->getParent()->getDataLayout();
866
867     // If the pointer is already known to be sufficiently aligned, or if we can
868     // round it up to a larger alignment, then we don't need a temporary.
869     if (getOrEnforceKnownAlignment(Arg, ByValAlignment, DL, TheCall,
870                                    &IFI.ACT->getAssumptionCache(*Caller)) >=
871         ByValAlignment)
872       return Arg;
873     
874     // Otherwise, we have to make a memcpy to get a safe alignment.  This is bad
875     // for code quality, but rarely happens and is required for correctness.
876   }
877
878   // Create the alloca.  If we have DataLayout, use nice alignment.
879   unsigned Align =
880       Caller->getParent()->getDataLayout().getPrefTypeAlignment(AggTy);
881
882   // If the byval had an alignment specified, we *must* use at least that
883   // alignment, as it is required by the byval argument (and uses of the
884   // pointer inside the callee).
885   Align = std::max(Align, ByValAlignment);
886   
887   Value *NewAlloca = new AllocaInst(AggTy, nullptr, Align, Arg->getName(), 
888                                     &*Caller->begin()->begin());
889   IFI.StaticAllocas.push_back(cast<AllocaInst>(NewAlloca));
890   
891   // Uses of the argument in the function should use our new alloca
892   // instead.
893   return NewAlloca;
894 }
895
896 // Check whether this Value is used by a lifetime intrinsic.
897 static bool isUsedByLifetimeMarker(Value *V) {
898   for (User *U : V->users()) {
899     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) {
900       switch (II->getIntrinsicID()) {
901       default: break;
902       case Intrinsic::lifetime_start:
903       case Intrinsic::lifetime_end:
904         return true;
905       }
906     }
907   }
908   return false;
909 }
910
911 // Check whether the given alloca already has
912 // lifetime.start or lifetime.end intrinsics.
913 static bool hasLifetimeMarkers(AllocaInst *AI) {
914   Type *Ty = AI->getType();
915   Type *Int8PtrTy = Type::getInt8PtrTy(Ty->getContext(),
916                                        Ty->getPointerAddressSpace());
917   if (Ty == Int8PtrTy)
918     return isUsedByLifetimeMarker(AI);
919
920   // Do a scan to find all the casts to i8*.
921   for (User *U : AI->users()) {
922     if (U->getType() != Int8PtrTy) continue;
923     if (U->stripPointerCasts() != AI) continue;
924     if (isUsedByLifetimeMarker(U))
925       return true;
926   }
927   return false;
928 }
929
930 /// Rebuild the entire inlined-at chain for this instruction so that the top of
931 /// the chain now is inlined-at the new call site.
932 static DebugLoc
933 updateInlinedAtInfo(DebugLoc DL, DILocation *InlinedAtNode, LLVMContext &Ctx,
934                     DenseMap<const DILocation *, DILocation *> &IANodes) {
935   SmallVector<DILocation *, 3> InlinedAtLocations;
936   DILocation *Last = InlinedAtNode;
937   DILocation *CurInlinedAt = DL;
938
939   // Gather all the inlined-at nodes
940   while (DILocation *IA = CurInlinedAt->getInlinedAt()) {
941     // Skip any we've already built nodes for
942     if (DILocation *Found = IANodes[IA]) {
943       Last = Found;
944       break;
945     }
946
947     InlinedAtLocations.push_back(IA);
948     CurInlinedAt = IA;
949   }
950
951   // Starting from the top, rebuild the nodes to point to the new inlined-at
952   // location (then rebuilding the rest of the chain behind it) and update the
953   // map of already-constructed inlined-at nodes.
954   for (const DILocation *MD : make_range(InlinedAtLocations.rbegin(),
955                                          InlinedAtLocations.rend())) {
956     Last = IANodes[MD] = DILocation::getDistinct(
957         Ctx, MD->getLine(), MD->getColumn(), MD->getScope(), Last);
958   }
959
960   // And finally create the normal location for this instruction, referring to
961   // the new inlined-at chain.
962   return DebugLoc::get(DL.getLine(), DL.getCol(), DL.getScope(), Last);
963 }
964
965 /// Update inlined instructions' line numbers to
966 /// to encode location where these instructions are inlined.
967 static void fixupLineNumbers(Function *Fn, Function::iterator FI,
968                              Instruction *TheCall) {
969   DebugLoc TheCallDL = TheCall->getDebugLoc();
970   if (!TheCallDL)
971     return;
972
973   auto &Ctx = Fn->getContext();
974   DILocation *InlinedAtNode = TheCallDL;
975
976   // Create a unique call site, not to be confused with any other call from the
977   // same location.
978   InlinedAtNode = DILocation::getDistinct(
979       Ctx, InlinedAtNode->getLine(), InlinedAtNode->getColumn(),
980       InlinedAtNode->getScope(), InlinedAtNode->getInlinedAt());
981
982   // Cache the inlined-at nodes as they're built so they are reused, without
983   // this every instruction's inlined-at chain would become distinct from each
984   // other.
985   DenseMap<const DILocation *, DILocation *> IANodes;
986
987   for (; FI != Fn->end(); ++FI) {
988     for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
989          BI != BE; ++BI) {
990       DebugLoc DL = BI->getDebugLoc();
991       if (!DL) {
992         // If the inlined instruction has no line number, make it look as if it
993         // originates from the call location. This is important for
994         // ((__always_inline__, __nodebug__)) functions which must use caller
995         // location for all instructions in their function body.
996
997         // Don't update static allocas, as they may get moved later.
998         if (auto *AI = dyn_cast<AllocaInst>(BI))
999           if (isa<Constant>(AI->getArraySize()))
1000             continue;
1001
1002         BI->setDebugLoc(TheCallDL);
1003       } else {
1004         BI->setDebugLoc(updateInlinedAtInfo(DL, InlinedAtNode, BI->getContext(), IANodes));
1005       }
1006     }
1007   }
1008 }
1009
1010 /// This function inlines the called function into the basic block of the
1011 /// caller. This returns false if it is not possible to inline this call.
1012 /// The program is still in a well defined state if this occurs though.
1013 ///
1014 /// Note that this only does one level of inlining.  For example, if the
1015 /// instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now
1016 /// exists in the instruction stream.  Similarly this will inline a recursive
1017 /// function by one level.
1018 bool llvm::InlineFunction(CallSite CS, InlineFunctionInfo &IFI,
1019                           AAResults *CalleeAAR, bool InsertLifetime) {
1020   Instruction *TheCall = CS.getInstruction();
1021   assert(TheCall->getParent() && TheCall->getParent()->getParent() &&
1022          "Instruction not in function!");
1023
1024   // If IFI has any state in it, zap it before we fill it in.
1025   IFI.reset();
1026   
1027   const Function *CalledFunc = CS.getCalledFunction();
1028   if (!CalledFunc ||              // Can't inline external function or indirect
1029       CalledFunc->isDeclaration() || // call, or call to a vararg function!
1030       CalledFunc->getFunctionType()->isVarArg()) return false;
1031
1032   // The inliner does not know how to inline through calls with operand bundles.
1033   if (CS.hasOperandBundles())
1034     return false;
1035
1036   // If the call to the callee cannot throw, set the 'nounwind' flag on any
1037   // calls that we inline.
1038   bool MarkNoUnwind = CS.doesNotThrow();
1039
1040   BasicBlock *OrigBB = TheCall->getParent();
1041   Function *Caller = OrigBB->getParent();
1042
1043   // GC poses two hazards to inlining, which only occur when the callee has GC:
1044   //  1. If the caller has no GC, then the callee's GC must be propagated to the
1045   //     caller.
1046   //  2. If the caller has a differing GC, it is invalid to inline.
1047   if (CalledFunc->hasGC()) {
1048     if (!Caller->hasGC())
1049       Caller->setGC(CalledFunc->getGC());
1050     else if (CalledFunc->getGC() != Caller->getGC())
1051       return false;
1052   }
1053
1054   // Get the personality function from the callee if it contains a landing pad.
1055   Constant *CalledPersonality =
1056       CalledFunc->hasPersonalityFn()
1057           ? CalledFunc->getPersonalityFn()->stripPointerCasts()
1058           : nullptr;
1059
1060   // Find the personality function used by the landing pads of the caller. If it
1061   // exists, then check to see that it matches the personality function used in
1062   // the callee.
1063   Constant *CallerPersonality =
1064       Caller->hasPersonalityFn()
1065           ? Caller->getPersonalityFn()->stripPointerCasts()
1066           : nullptr;
1067   if (CalledPersonality) {
1068     if (!CallerPersonality)
1069       Caller->setPersonalityFn(CalledPersonality);
1070     // If the personality functions match, then we can perform the
1071     // inlining. Otherwise, we can't inline.
1072     // TODO: This isn't 100% true. Some personality functions are proper
1073     //       supersets of others and can be used in place of the other.
1074     else if (CalledPersonality != CallerPersonality)
1075       return false;
1076   }
1077
1078   // Get an iterator to the last basic block in the function, which will have
1079   // the new function inlined after it.
1080   Function::iterator LastBlock = --Caller->end();
1081
1082   // Make sure to capture all of the return instructions from the cloned
1083   // function.
1084   SmallVector<ReturnInst*, 8> Returns;
1085   ClonedCodeInfo InlinedFunctionInfo;
1086   Function::iterator FirstNewBlock;
1087
1088   { // Scope to destroy VMap after cloning.
1089     ValueToValueMapTy VMap;
1090     // Keep a list of pair (dst, src) to emit byval initializations.
1091     SmallVector<std::pair<Value*, Value*>, 4> ByValInit;
1092
1093     auto &DL = Caller->getParent()->getDataLayout();
1094
1095     assert(CalledFunc->arg_size() == CS.arg_size() &&
1096            "No varargs calls can be inlined!");
1097
1098     // Calculate the vector of arguments to pass into the function cloner, which
1099     // matches up the formal to the actual argument values.
1100     CallSite::arg_iterator AI = CS.arg_begin();
1101     unsigned ArgNo = 0;
1102     for (Function::const_arg_iterator I = CalledFunc->arg_begin(),
1103          E = CalledFunc->arg_end(); I != E; ++I, ++AI, ++ArgNo) {
1104       Value *ActualArg = *AI;
1105
1106       // When byval arguments actually inlined, we need to make the copy implied
1107       // by them explicit.  However, we don't do this if the callee is readonly
1108       // or readnone, because the copy would be unneeded: the callee doesn't
1109       // modify the struct.
1110       if (CS.isByValArgument(ArgNo)) {
1111         ActualArg = HandleByValArgument(ActualArg, TheCall, CalledFunc, IFI,
1112                                         CalledFunc->getParamAlignment(ArgNo+1));
1113         if (ActualArg != *AI)
1114           ByValInit.push_back(std::make_pair(ActualArg, (Value*) *AI));
1115       }
1116
1117       VMap[&*I] = ActualArg;
1118     }
1119
1120     // Add alignment assumptions if necessary. We do this before the inlined
1121     // instructions are actually cloned into the caller so that we can easily
1122     // check what will be known at the start of the inlined code.
1123     AddAlignmentAssumptions(CS, IFI);
1124
1125     // We want the inliner to prune the code as it copies.  We would LOVE to
1126     // have no dead or constant instructions leftover after inlining occurs
1127     // (which can happen, e.g., because an argument was constant), but we'll be
1128     // happy with whatever the cloner can do.
1129     CloneAndPruneFunctionInto(Caller, CalledFunc, VMap,
1130                               /*ModuleLevelChanges=*/false, Returns, ".i",
1131                               &InlinedFunctionInfo, TheCall);
1132
1133     // Remember the first block that is newly cloned over.
1134     FirstNewBlock = LastBlock; ++FirstNewBlock;
1135
1136     // Inject byval arguments initialization.
1137     for (std::pair<Value*, Value*> &Init : ByValInit)
1138       HandleByValArgumentInit(Init.first, Init.second, Caller->getParent(),
1139                               &*FirstNewBlock, IFI);
1140
1141     // Update the callgraph if requested.
1142     if (IFI.CG)
1143       UpdateCallGraphAfterInlining(CS, FirstNewBlock, VMap, IFI);
1144
1145     // Update inlined instructions' line number information.
1146     fixupLineNumbers(Caller, FirstNewBlock, TheCall);
1147
1148     // Clone existing noalias metadata if necessary.
1149     CloneAliasScopeMetadata(CS, VMap);
1150
1151     // Add noalias metadata if necessary.
1152     AddAliasScopeMetadata(CS, VMap, DL, CalleeAAR);
1153
1154     // FIXME: We could register any cloned assumptions instead of clearing the
1155     // whole function's cache.
1156     if (IFI.ACT)
1157       IFI.ACT->getAssumptionCache(*Caller).clear();
1158   }
1159
1160   // If there are any alloca instructions in the block that used to be the entry
1161   // block for the callee, move them to the entry block of the caller.  First
1162   // calculate which instruction they should be inserted before.  We insert the
1163   // instructions at the end of the current alloca list.
1164   {
1165     BasicBlock::iterator InsertPoint = Caller->begin()->begin();
1166     for (BasicBlock::iterator I = FirstNewBlock->begin(),
1167          E = FirstNewBlock->end(); I != E; ) {
1168       AllocaInst *AI = dyn_cast<AllocaInst>(I++);
1169       if (!AI) continue;
1170       
1171       // If the alloca is now dead, remove it.  This often occurs due to code
1172       // specialization.
1173       if (AI->use_empty()) {
1174         AI->eraseFromParent();
1175         continue;
1176       }
1177
1178       if (!isa<Constant>(AI->getArraySize()))
1179         continue;
1180       
1181       // Keep track of the static allocas that we inline into the caller.
1182       IFI.StaticAllocas.push_back(AI);
1183       
1184       // Scan for the block of allocas that we can move over, and move them
1185       // all at once.
1186       while (isa<AllocaInst>(I) &&
1187              isa<Constant>(cast<AllocaInst>(I)->getArraySize())) {
1188         IFI.StaticAllocas.push_back(cast<AllocaInst>(I));
1189         ++I;
1190       }
1191
1192       // Transfer all of the allocas over in a block.  Using splice means
1193       // that the instructions aren't removed from the symbol table, then
1194       // reinserted.
1195       Caller->getEntryBlock().getInstList().splice(
1196           InsertPoint, FirstNewBlock->getInstList(), AI->getIterator(), I);
1197     }
1198     // Move any dbg.declares describing the allocas into the entry basic block.
1199     DIBuilder DIB(*Caller->getParent());
1200     for (auto &AI : IFI.StaticAllocas)
1201       replaceDbgDeclareForAlloca(AI, AI, DIB, /*Deref=*/false);
1202   }
1203
1204   bool InlinedMustTailCalls = false;
1205   if (InlinedFunctionInfo.ContainsCalls) {
1206     CallInst::TailCallKind CallSiteTailKind = CallInst::TCK_None;
1207     if (CallInst *CI = dyn_cast<CallInst>(TheCall))
1208       CallSiteTailKind = CI->getTailCallKind();
1209
1210     for (Function::iterator BB = FirstNewBlock, E = Caller->end(); BB != E;
1211          ++BB) {
1212       for (Instruction &I : *BB) {
1213         CallInst *CI = dyn_cast<CallInst>(&I);
1214         if (!CI)
1215           continue;
1216
1217         // We need to reduce the strength of any inlined tail calls.  For
1218         // musttail, we have to avoid introducing potential unbounded stack
1219         // growth.  For example, if functions 'f' and 'g' are mutually recursive
1220         // with musttail, we can inline 'g' into 'f' so long as we preserve
1221         // musttail on the cloned call to 'f'.  If either the inlined call site
1222         // or the cloned call site is *not* musttail, the program already has
1223         // one frame of stack growth, so it's safe to remove musttail.  Here is
1224         // a table of example transformations:
1225         //
1226         //    f -> musttail g -> musttail f  ==>  f -> musttail f
1227         //    f -> musttail g ->     tail f  ==>  f ->     tail f
1228         //    f ->          g -> musttail f  ==>  f ->          f
1229         //    f ->          g ->     tail f  ==>  f ->          f
1230         CallInst::TailCallKind ChildTCK = CI->getTailCallKind();
1231         ChildTCK = std::min(CallSiteTailKind, ChildTCK);
1232         CI->setTailCallKind(ChildTCK);
1233         InlinedMustTailCalls |= CI->isMustTailCall();
1234
1235         // Calls inlined through a 'nounwind' call site should be marked
1236         // 'nounwind'.
1237         if (MarkNoUnwind)
1238           CI->setDoesNotThrow();
1239       }
1240     }
1241   }
1242
1243   // Leave lifetime markers for the static alloca's, scoping them to the
1244   // function we just inlined.
1245   if (InsertLifetime && !IFI.StaticAllocas.empty()) {
1246     IRBuilder<> builder(&FirstNewBlock->front());
1247     for (unsigned ai = 0, ae = IFI.StaticAllocas.size(); ai != ae; ++ai) {
1248       AllocaInst *AI = IFI.StaticAllocas[ai];
1249
1250       // If the alloca is already scoped to something smaller than the whole
1251       // function then there's no need to add redundant, less accurate markers.
1252       if (hasLifetimeMarkers(AI))
1253         continue;
1254
1255       // Try to determine the size of the allocation.
1256       ConstantInt *AllocaSize = nullptr;
1257       if (ConstantInt *AIArraySize =
1258           dyn_cast<ConstantInt>(AI->getArraySize())) {
1259         auto &DL = Caller->getParent()->getDataLayout();
1260         Type *AllocaType = AI->getAllocatedType();
1261         uint64_t AllocaTypeSize = DL.getTypeAllocSize(AllocaType);
1262         uint64_t AllocaArraySize = AIArraySize->getLimitedValue();
1263
1264         // Don't add markers for zero-sized allocas.
1265         if (AllocaArraySize == 0)
1266           continue;
1267
1268         // Check that array size doesn't saturate uint64_t and doesn't
1269         // overflow when it's multiplied by type size.
1270         if (AllocaArraySize != ~0ULL &&
1271             UINT64_MAX / AllocaArraySize >= AllocaTypeSize) {
1272           AllocaSize = ConstantInt::get(Type::getInt64Ty(AI->getContext()),
1273                                         AllocaArraySize * AllocaTypeSize);
1274         }
1275       }
1276
1277       builder.CreateLifetimeStart(AI, AllocaSize);
1278       for (ReturnInst *RI : Returns) {
1279         // Don't insert llvm.lifetime.end calls between a musttail call and a
1280         // return.  The return kills all local allocas.
1281         if (InlinedMustTailCalls &&
1282             RI->getParent()->getTerminatingMustTailCall())
1283           continue;
1284         IRBuilder<>(RI).CreateLifetimeEnd(AI, AllocaSize);
1285       }
1286     }
1287   }
1288
1289   // If the inlined code contained dynamic alloca instructions, wrap the inlined
1290   // code with llvm.stacksave/llvm.stackrestore intrinsics.
1291   if (InlinedFunctionInfo.ContainsDynamicAllocas) {
1292     Module *M = Caller->getParent();
1293     // Get the two intrinsics we care about.
1294     Function *StackSave = Intrinsic::getDeclaration(M, Intrinsic::stacksave);
1295     Function *StackRestore=Intrinsic::getDeclaration(M,Intrinsic::stackrestore);
1296
1297     // Insert the llvm.stacksave.
1298     CallInst *SavedPtr = IRBuilder<>(&*FirstNewBlock, FirstNewBlock->begin())
1299                              .CreateCall(StackSave, {}, "savedstack");
1300
1301     // Insert a call to llvm.stackrestore before any return instructions in the
1302     // inlined function.
1303     for (ReturnInst *RI : Returns) {
1304       // Don't insert llvm.stackrestore calls between a musttail call and a
1305       // return.  The return will restore the stack pointer.
1306       if (InlinedMustTailCalls && RI->getParent()->getTerminatingMustTailCall())
1307         continue;
1308       IRBuilder<>(RI).CreateCall(StackRestore, SavedPtr);
1309     }
1310   }
1311
1312   // If we are inlining for an invoke instruction, we must make sure to rewrite
1313   // any call instructions into invoke instructions.
1314   if (auto *II = dyn_cast<InvokeInst>(TheCall)) {
1315     BasicBlock *UnwindDest = II->getUnwindDest();
1316     Instruction *FirstNonPHI = UnwindDest->getFirstNonPHI();
1317     if (isa<LandingPadInst>(FirstNonPHI)) {
1318       HandleInlinedLandingPad(II, &*FirstNewBlock, InlinedFunctionInfo);
1319     } else {
1320       HandleInlinedEHPad(II, &*FirstNewBlock, InlinedFunctionInfo);
1321     }
1322   }
1323
1324   // Handle any inlined musttail call sites.  In order for a new call site to be
1325   // musttail, the source of the clone and the inlined call site must have been
1326   // musttail.  Therefore it's safe to return without merging control into the
1327   // phi below.
1328   if (InlinedMustTailCalls) {
1329     // Check if we need to bitcast the result of any musttail calls.
1330     Type *NewRetTy = Caller->getReturnType();
1331     bool NeedBitCast = !TheCall->use_empty() && TheCall->getType() != NewRetTy;
1332
1333     // Handle the returns preceded by musttail calls separately.
1334     SmallVector<ReturnInst *, 8> NormalReturns;
1335     for (ReturnInst *RI : Returns) {
1336       CallInst *ReturnedMustTail =
1337           RI->getParent()->getTerminatingMustTailCall();
1338       if (!ReturnedMustTail) {
1339         NormalReturns.push_back(RI);
1340         continue;
1341       }
1342       if (!NeedBitCast)
1343         continue;
1344
1345       // Delete the old return and any preceding bitcast.
1346       BasicBlock *CurBB = RI->getParent();
1347       auto *OldCast = dyn_cast_or_null<BitCastInst>(RI->getReturnValue());
1348       RI->eraseFromParent();
1349       if (OldCast)
1350         OldCast->eraseFromParent();
1351
1352       // Insert a new bitcast and return with the right type.
1353       IRBuilder<> Builder(CurBB);
1354       Builder.CreateRet(Builder.CreateBitCast(ReturnedMustTail, NewRetTy));
1355     }
1356
1357     // Leave behind the normal returns so we can merge control flow.
1358     std::swap(Returns, NormalReturns);
1359   }
1360
1361   // If we cloned in _exactly one_ basic block, and if that block ends in a
1362   // return instruction, we splice the body of the inlined callee directly into
1363   // the calling basic block.
1364   if (Returns.size() == 1 && std::distance(FirstNewBlock, Caller->end()) == 1) {
1365     // Move all of the instructions right before the call.
1366     OrigBB->getInstList().splice(TheCall->getIterator(),
1367                                  FirstNewBlock->getInstList(),
1368                                  FirstNewBlock->begin(), FirstNewBlock->end());
1369     // Remove the cloned basic block.
1370     Caller->getBasicBlockList().pop_back();
1371
1372     // If the call site was an invoke instruction, add a branch to the normal
1373     // destination.
1374     if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
1375       BranchInst *NewBr = BranchInst::Create(II->getNormalDest(), TheCall);
1376       NewBr->setDebugLoc(Returns[0]->getDebugLoc());
1377     }
1378
1379     // If the return instruction returned a value, replace uses of the call with
1380     // uses of the returned value.
1381     if (!TheCall->use_empty()) {
1382       ReturnInst *R = Returns[0];
1383       if (TheCall == R->getReturnValue())
1384         TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
1385       else
1386         TheCall->replaceAllUsesWith(R->getReturnValue());
1387     }
1388     // Since we are now done with the Call/Invoke, we can delete it.
1389     TheCall->eraseFromParent();
1390
1391     // Since we are now done with the return instruction, delete it also.
1392     Returns[0]->eraseFromParent();
1393
1394     // We are now done with the inlining.
1395     return true;
1396   }
1397
1398   // Otherwise, we have the normal case, of more than one block to inline or
1399   // multiple return sites.
1400
1401   // We want to clone the entire callee function into the hole between the
1402   // "starter" and "ender" blocks.  How we accomplish this depends on whether
1403   // this is an invoke instruction or a call instruction.
1404   BasicBlock *AfterCallBB;
1405   BranchInst *CreatedBranchToNormalDest = nullptr;
1406   if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
1407
1408     // Add an unconditional branch to make this look like the CallInst case...
1409     CreatedBranchToNormalDest = BranchInst::Create(II->getNormalDest(), TheCall);
1410
1411     // Split the basic block.  This guarantees that no PHI nodes will have to be
1412     // updated due to new incoming edges, and make the invoke case more
1413     // symmetric to the call case.
1414     AfterCallBB =
1415         OrigBB->splitBasicBlock(CreatedBranchToNormalDest->getIterator(),
1416                                 CalledFunc->getName() + ".exit");
1417
1418   } else {  // It's a call
1419     // If this is a call instruction, we need to split the basic block that
1420     // the call lives in.
1421     //
1422     AfterCallBB = OrigBB->splitBasicBlock(TheCall->getIterator(),
1423                                           CalledFunc->getName() + ".exit");
1424   }
1425
1426   // Change the branch that used to go to AfterCallBB to branch to the first
1427   // basic block of the inlined function.
1428   //
1429   TerminatorInst *Br = OrigBB->getTerminator();
1430   assert(Br && Br->getOpcode() == Instruction::Br &&
1431          "splitBasicBlock broken!");
1432   Br->setOperand(0, &*FirstNewBlock);
1433
1434   // Now that the function is correct, make it a little bit nicer.  In
1435   // particular, move the basic blocks inserted from the end of the function
1436   // into the space made by splitting the source basic block.
1437   Caller->getBasicBlockList().splice(AfterCallBB->getIterator(),
1438                                      Caller->getBasicBlockList(), FirstNewBlock,
1439                                      Caller->end());
1440
1441   // Handle all of the return instructions that we just cloned in, and eliminate
1442   // any users of the original call/invoke instruction.
1443   Type *RTy = CalledFunc->getReturnType();
1444
1445   PHINode *PHI = nullptr;
1446   if (Returns.size() > 1) {
1447     // The PHI node should go at the front of the new basic block to merge all
1448     // possible incoming values.
1449     if (!TheCall->use_empty()) {
1450       PHI = PHINode::Create(RTy, Returns.size(), TheCall->getName(),
1451                             &AfterCallBB->front());
1452       // Anything that used the result of the function call should now use the
1453       // PHI node as their operand.
1454       TheCall->replaceAllUsesWith(PHI);
1455     }
1456
1457     // Loop over all of the return instructions adding entries to the PHI node
1458     // as appropriate.
1459     if (PHI) {
1460       for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
1461         ReturnInst *RI = Returns[i];
1462         assert(RI->getReturnValue()->getType() == PHI->getType() &&
1463                "Ret value not consistent in function!");
1464         PHI->addIncoming(RI->getReturnValue(), RI->getParent());
1465       }
1466     }
1467
1468     // Add a branch to the merge points and remove return instructions.
1469     DebugLoc Loc;
1470     for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
1471       ReturnInst *RI = Returns[i];
1472       BranchInst* BI = BranchInst::Create(AfterCallBB, RI);
1473       Loc = RI->getDebugLoc();
1474       BI->setDebugLoc(Loc);
1475       RI->eraseFromParent();
1476     }
1477     // We need to set the debug location to *somewhere* inside the
1478     // inlined function. The line number may be nonsensical, but the
1479     // instruction will at least be associated with the right
1480     // function.
1481     if (CreatedBranchToNormalDest)
1482       CreatedBranchToNormalDest->setDebugLoc(Loc);
1483   } else if (!Returns.empty()) {
1484     // Otherwise, if there is exactly one return value, just replace anything
1485     // using the return value of the call with the computed value.
1486     if (!TheCall->use_empty()) {
1487       if (TheCall == Returns[0]->getReturnValue())
1488         TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
1489       else
1490         TheCall->replaceAllUsesWith(Returns[0]->getReturnValue());
1491     }
1492
1493     // Update PHI nodes that use the ReturnBB to use the AfterCallBB.
1494     BasicBlock *ReturnBB = Returns[0]->getParent();
1495     ReturnBB->replaceAllUsesWith(AfterCallBB);
1496
1497     // Splice the code from the return block into the block that it will return
1498     // to, which contains the code that was after the call.
1499     AfterCallBB->getInstList().splice(AfterCallBB->begin(),
1500                                       ReturnBB->getInstList());
1501
1502     if (CreatedBranchToNormalDest)
1503       CreatedBranchToNormalDest->setDebugLoc(Returns[0]->getDebugLoc());
1504
1505     // Delete the return instruction now and empty ReturnBB now.
1506     Returns[0]->eraseFromParent();
1507     ReturnBB->eraseFromParent();
1508   } else if (!TheCall->use_empty()) {
1509     // No returns, but something is using the return value of the call.  Just
1510     // nuke the result.
1511     TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
1512   }
1513
1514   // Since we are now done with the Call/Invoke, we can delete it.
1515   TheCall->eraseFromParent();
1516
1517   // If we inlined any musttail calls and the original return is now
1518   // unreachable, delete it.  It can only contain a bitcast and ret.
1519   if (InlinedMustTailCalls && pred_begin(AfterCallBB) == pred_end(AfterCallBB))
1520     AfterCallBB->eraseFromParent();
1521
1522   // We should always be able to fold the entry block of the function into the
1523   // single predecessor of the block...
1524   assert(cast<BranchInst>(Br)->isUnconditional() && "splitBasicBlock broken!");
1525   BasicBlock *CalleeEntry = cast<BranchInst>(Br)->getSuccessor(0);
1526
1527   // Splice the code entry block into calling block, right before the
1528   // unconditional branch.
1529   CalleeEntry->replaceAllUsesWith(OrigBB);  // Update PHI nodes
1530   OrigBB->getInstList().splice(Br->getIterator(), CalleeEntry->getInstList());
1531
1532   // Remove the unconditional branch.
1533   OrigBB->getInstList().erase(Br);
1534
1535   // Now we can remove the CalleeEntry block, which is now empty.
1536   Caller->getBasicBlockList().erase(CalleeEntry);
1537
1538   // If we inserted a phi node, check to see if it has a single value (e.g. all
1539   // the entries are the same or undef).  If so, remove the PHI so it doesn't
1540   // block other optimizations.
1541   if (PHI) {
1542     auto &DL = Caller->getParent()->getDataLayout();
1543     if (Value *V = SimplifyInstruction(PHI, DL, nullptr, nullptr,
1544                                        &IFI.ACT->getAssumptionCache(*Caller))) {
1545       PHI->replaceAllUsesWith(V);
1546       PHI->eraseFromParent();
1547     }
1548   }
1549
1550   return true;
1551 }