1 //===- InlineFunction.cpp - Code to perform function inlining -------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements inlining of a function into a call site, resolving
10 // parameters and the return value as appropriate.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/ADT/DenseMap.h"
15 #include "llvm/ADT/None.h"
16 #include "llvm/ADT/Optional.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SetVector.h"
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/iterator_range.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/Analysis/AssumptionCache.h"
25 #include "llvm/Analysis/BlockFrequencyInfo.h"
26 #include "llvm/Analysis/CallGraph.h"
27 #include "llvm/Analysis/CaptureTracking.h"
28 #include "llvm/Analysis/EHPersonalities.h"
29 #include "llvm/Analysis/InstructionSimplify.h"
30 #include "llvm/Analysis/ProfileSummaryInfo.h"
31 #include "llvm/Transforms/Utils/Local.h"
32 #include "llvm/Analysis/ValueTracking.h"
33 #include "llvm/Analysis/VectorUtils.h"
34 #include "llvm/IR/Argument.h"
35 #include "llvm/IR/BasicBlock.h"
36 #include "llvm/IR/CFG.h"
37 #include "llvm/IR/Constant.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/DIBuilder.h"
40 #include "llvm/IR/DataLayout.h"
41 #include "llvm/IR/DebugInfoMetadata.h"
42 #include "llvm/IR/DebugLoc.h"
43 #include "llvm/IR/DerivedTypes.h"
44 #include "llvm/IR/Dominators.h"
45 #include "llvm/IR/Function.h"
46 #include "llvm/IR/IRBuilder.h"
47 #include "llvm/IR/InstrTypes.h"
48 #include "llvm/IR/Instruction.h"
49 #include "llvm/IR/Instructions.h"
50 #include "llvm/IR/IntrinsicInst.h"
51 #include "llvm/IR/Intrinsics.h"
52 #include "llvm/IR/LLVMContext.h"
53 #include "llvm/IR/MDBuilder.h"
54 #include "llvm/IR/Metadata.h"
55 #include "llvm/IR/Module.h"
56 #include "llvm/IR/Type.h"
57 #include "llvm/IR/User.h"
58 #include "llvm/IR/Value.h"
59 #include "llvm/Support/Casting.h"
60 #include "llvm/Support/CommandLine.h"
61 #include "llvm/Support/ErrorHandling.h"
62 #include "llvm/Transforms/Utils/AssumeBundleBuilder.h"
63 #include "llvm/Transforms/Utils/Cloning.h"
64 #include "llvm/Transforms/Utils/ValueMapper.h"
65 #include <algorithm>
66 #include <cassert>
67 #include <cstdint>
68 #include <iterator>
69 #include <limits>
70 #include <string>
71 #include <utility>
72 #include <vector>
73 
74 using namespace llvm;
75 using ProfileCount = Function::ProfileCount;
76 
77 static cl::opt<bool>
78 EnableNoAliasConversion("enable-noalias-to-md-conversion", cl::init(true),
79   cl::Hidden,
80   cl::desc("Convert noalias attributes to metadata during inlining."));
81 
82 static cl::opt<bool>
83 PreserveAlignmentAssumptions("preserve-alignment-assumptions-during-inlining",
84   cl::init(true), cl::Hidden,
85   cl::desc("Convert align attributes to assumptions during inlining."));
86 
87 static cl::opt<bool> UpdateReturnAttributes(
88         "update-return-attrs", cl::init(true), cl::Hidden,
89             cl::desc("Update return attributes on calls within inlined body"));
90 
91 static cl::opt<bool> UpdateLoadMetadataDuringInlining(
92         "update-load-metadata-during-inlining", cl::init(true), cl::Hidden,
93             cl::desc("Update metadata on loads within inlined body"));
94 
95 static cl::opt<unsigned> InlinerAttributeWindow(
96     "max-inst-checked-for-throw-during-inlining", cl::Hidden,
97     cl::desc("the maximum number of instructions analyzed for may throw during "
98              "attribute inference in inlined body"),
99     cl::init(4));
100 
101 namespace {
102 
103   /// A class for recording information about inlining a landing pad.
104   class LandingPadInliningInfo {
105     /// Destination of the invoke's unwind.
106     BasicBlock *OuterResumeDest;
107 
108     /// Destination for the callee's resume.
109     BasicBlock *InnerResumeDest = nullptr;
110 
111     /// LandingPadInst associated with the invoke.
112     LandingPadInst *CallerLPad = nullptr;
113 
114     /// PHI for EH values from landingpad insts.
115     PHINode *InnerEHValuesPHI = nullptr;
116 
117     SmallVector<Value*, 8> UnwindDestPHIValues;
118 
119   public:
120     LandingPadInliningInfo(InvokeInst *II)
121         : OuterResumeDest(II->getUnwindDest()) {
122       // If there are PHI nodes in the unwind destination block, we need to keep
123       // track of which values came into them from the invoke before removing
124       // the edge from this block.
125       BasicBlock *InvokeBB = II->getParent();
126       BasicBlock::iterator I = OuterResumeDest->begin();
127       for (; isa<PHINode>(I); ++I) {
128         // Save the value to use for this edge.
129         PHINode *PHI = cast<PHINode>(I);
130         UnwindDestPHIValues.push_back(PHI->getIncomingValueForBlock(InvokeBB));
131       }
132 
133       CallerLPad = cast<LandingPadInst>(I);
134     }
135 
136     /// The outer unwind destination is the target of
137     /// unwind edges introduced for calls within the inlined function.
138     BasicBlock *getOuterResumeDest() const {
139       return OuterResumeDest;
140     }
141 
142     BasicBlock *getInnerResumeDest();
143 
144     LandingPadInst *getLandingPadInst() const { return CallerLPad; }
145 
146     /// Forward the 'resume' instruction to the caller's landing pad block.
147     /// When the landing pad block has only one predecessor, this is
148     /// a simple branch. When there is more than one predecessor, we need to
149     /// split the landing pad block after the landingpad instruction and jump
150     /// to there.
151     void forwardResume(ResumeInst *RI,
152                        SmallPtrSetImpl<LandingPadInst*> &InlinedLPads);
153 
154     /// Add incoming-PHI values to the unwind destination block for the given
155     /// basic block, using the values for the original invoke's source block.
156     void addIncomingPHIValuesFor(BasicBlock *BB) const {
157       addIncomingPHIValuesForInto(BB, OuterResumeDest);
158     }
159 
160     void addIncomingPHIValuesForInto(BasicBlock *src, BasicBlock *dest) const {
161       BasicBlock::iterator I = dest->begin();
162       for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) {
163         PHINode *phi = cast<PHINode>(I);
164         phi->addIncoming(UnwindDestPHIValues[i], src);
165       }
166     }
167   };
168 
169 } // end anonymous namespace
170 
171 /// Get or create a target for the branch from ResumeInsts.
172 BasicBlock *LandingPadInliningInfo::getInnerResumeDest() {
173   if (InnerResumeDest) return InnerResumeDest;
174 
175   // Split the landing pad.
176   BasicBlock::iterator SplitPoint = ++CallerLPad->getIterator();
177   InnerResumeDest =
178     OuterResumeDest->splitBasicBlock(SplitPoint,
179                                      OuterResumeDest->getName() + ".body");
180 
181   // The number of incoming edges we expect to the inner landing pad.
182   const unsigned PHICapacity = 2;
183 
184   // Create corresponding new PHIs for all the PHIs in the outer landing pad.
185   Instruction *InsertPoint = &InnerResumeDest->front();
186   BasicBlock::iterator I = OuterResumeDest->begin();
187   for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) {
188     PHINode *OuterPHI = cast<PHINode>(I);
189     PHINode *InnerPHI = PHINode::Create(OuterPHI->getType(), PHICapacity,
190                                         OuterPHI->getName() + ".lpad-body",
191                                         InsertPoint);
192     OuterPHI->replaceAllUsesWith(InnerPHI);
193     InnerPHI->addIncoming(OuterPHI, OuterResumeDest);
194   }
195 
196   // Create a PHI for the exception values.
197   InnerEHValuesPHI = PHINode::Create(CallerLPad->getType(), PHICapacity,
198                                      "eh.lpad-body", InsertPoint);
199   CallerLPad->replaceAllUsesWith(InnerEHValuesPHI);
200   InnerEHValuesPHI->addIncoming(CallerLPad, OuterResumeDest);
201 
202   // All done.
203   return InnerResumeDest;
204 }
205 
206 /// Forward the 'resume' instruction to the caller's landing pad block.
207 /// When the landing pad block has only one predecessor, this is a simple
208 /// branch. When there is more than one predecessor, we need to split the
209 /// landing pad block after the landingpad instruction and jump to there.
210 void LandingPadInliningInfo::forwardResume(
211     ResumeInst *RI, SmallPtrSetImpl<LandingPadInst *> &InlinedLPads) {
212   BasicBlock *Dest = getInnerResumeDest();
213   BasicBlock *Src = RI->getParent();
214 
215   BranchInst::Create(Dest, Src);
216 
217   // Update the PHIs in the destination. They were inserted in an order which
218   // makes this work.
219   addIncomingPHIValuesForInto(Src, Dest);
220 
221   InnerEHValuesPHI->addIncoming(RI->getOperand(0), Src);
222   RI->eraseFromParent();
223 }
224 
225 /// Helper for getUnwindDestToken/getUnwindDestTokenHelper.
226 static Value *getParentPad(Value *EHPad) {
227   if (auto *FPI = dyn_cast<FuncletPadInst>(EHPad))
228     return FPI->getParentPad();
229   return cast<CatchSwitchInst>(EHPad)->getParentPad();
230 }
231 
232 using UnwindDestMemoTy = DenseMap<Instruction *, Value *>;
233 
234 /// Helper for getUnwindDestToken that does the descendant-ward part of
235 /// the search.
236 static Value *getUnwindDestTokenHelper(Instruction *EHPad,
237                                        UnwindDestMemoTy &MemoMap) {
238   SmallVector<Instruction *, 8> Worklist(1, EHPad);
239 
240   while (!Worklist.empty()) {
241     Instruction *CurrentPad = Worklist.pop_back_val();
242     // We only put pads on the worklist that aren't in the MemoMap.  When
243     // we find an unwind dest for a pad we may update its ancestors, but
244     // the queue only ever contains uncles/great-uncles/etc. of CurrentPad,
245     // so they should never get updated while queued on the worklist.
246     assert(!MemoMap.count(CurrentPad));
247     Value *UnwindDestToken = nullptr;
248     if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(CurrentPad)) {
249       if (CatchSwitch->hasUnwindDest()) {
250         UnwindDestToken = CatchSwitch->getUnwindDest()->getFirstNonPHI();
251       } else {
252         // Catchswitch doesn't have a 'nounwind' variant, and one might be
253         // annotated as "unwinds to caller" when really it's nounwind (see
254         // e.g. SimplifyCFGOpt::SimplifyUnreachable), so we can't infer the
255         // parent's unwind dest from this.  We can check its catchpads'
256         // descendants, since they might include a cleanuppad with an
257         // "unwinds to caller" cleanupret, which can be trusted.
258         for (auto HI = CatchSwitch->handler_begin(),
259                   HE = CatchSwitch->handler_end();
260              HI != HE && !UnwindDestToken; ++HI) {
261           BasicBlock *HandlerBlock = *HI;
262           auto *CatchPad = cast<CatchPadInst>(HandlerBlock->getFirstNonPHI());
263           for (User *Child : CatchPad->users()) {
264             // Intentionally ignore invokes here -- since the catchswitch is
265             // marked "unwind to caller", it would be a verifier error if it
266             // contained an invoke which unwinds out of it, so any invoke we'd
267             // encounter must unwind to some child of the catch.
268             if (!isa<CleanupPadInst>(Child) && !isa<CatchSwitchInst>(Child))
269               continue;
270 
271             Instruction *ChildPad = cast<Instruction>(Child);
272             auto Memo = MemoMap.find(ChildPad);
273             if (Memo == MemoMap.end()) {
274               // Haven't figured out this child pad yet; queue it.
275               Worklist.push_back(ChildPad);
276               continue;
277             }
278             // We've already checked this child, but might have found that
279             // it offers no proof either way.
280             Value *ChildUnwindDestToken = Memo->second;
281             if (!ChildUnwindDestToken)
282               continue;
283             // We already know the child's unwind dest, which can either
284             // be ConstantTokenNone to indicate unwind to caller, or can
285             // be another child of the catchpad.  Only the former indicates
286             // the unwind dest of the catchswitch.
287             if (isa<ConstantTokenNone>(ChildUnwindDestToken)) {
288               UnwindDestToken = ChildUnwindDestToken;
289               break;
290             }
291             assert(getParentPad(ChildUnwindDestToken) == CatchPad);
292           }
293         }
294       }
295     } else {
296       auto *CleanupPad = cast<CleanupPadInst>(CurrentPad);
297       for (User *U : CleanupPad->users()) {
298         if (auto *CleanupRet = dyn_cast<CleanupReturnInst>(U)) {
299           if (BasicBlock *RetUnwindDest = CleanupRet->getUnwindDest())
300             UnwindDestToken = RetUnwindDest->getFirstNonPHI();
301           else
302             UnwindDestToken = ConstantTokenNone::get(CleanupPad->getContext());
303           break;
304         }
305         Value *ChildUnwindDestToken;
306         if (auto *Invoke = dyn_cast<InvokeInst>(U)) {
307           ChildUnwindDestToken = Invoke->getUnwindDest()->getFirstNonPHI();
308         } else if (isa<CleanupPadInst>(U) || isa<CatchSwitchInst>(U)) {
309           Instruction *ChildPad = cast<Instruction>(U);
310           auto Memo = MemoMap.find(ChildPad);
311           if (Memo == MemoMap.end()) {
312             // Haven't resolved this child yet; queue it and keep searching.
313             Worklist.push_back(ChildPad);
314             continue;
315           }
316           // We've checked this child, but still need to ignore it if it
317           // had no proof either way.
318           ChildUnwindDestToken = Memo->second;
319           if (!ChildUnwindDestToken)
320             continue;
321         } else {
322           // Not a relevant user of the cleanuppad
323           continue;
324         }
325         // In a well-formed program, the child/invoke must either unwind to
326         // an(other) child of the cleanup, or exit the cleanup.  In the
327         // first case, continue searching.
328         if (isa<Instruction>(ChildUnwindDestToken) &&
329             getParentPad(ChildUnwindDestToken) == CleanupPad)
330           continue;
331         UnwindDestToken = ChildUnwindDestToken;
332         break;
333       }
334     }
335     // If we haven't found an unwind dest for CurrentPad, we may have queued its
336     // children, so move on to the next in the worklist.
337     if (!UnwindDestToken)
338       continue;
339 
340     // Now we know that CurrentPad unwinds to UnwindDestToken.  It also exits
341     // any ancestors of CurrentPad up to but not including UnwindDestToken's
342     // parent pad.  Record this in the memo map, and check to see if the
343     // original EHPad being queried is one of the ones exited.
344     Value *UnwindParent;
345     if (auto *UnwindPad = dyn_cast<Instruction>(UnwindDestToken))
346       UnwindParent = getParentPad(UnwindPad);
347     else
348       UnwindParent = nullptr;
349     bool ExitedOriginalPad = false;
350     for (Instruction *ExitedPad = CurrentPad;
351          ExitedPad && ExitedPad != UnwindParent;
352          ExitedPad = dyn_cast<Instruction>(getParentPad(ExitedPad))) {
353       // Skip over catchpads since they just follow their catchswitches.
354       if (isa<CatchPadInst>(ExitedPad))
355         continue;
356       MemoMap[ExitedPad] = UnwindDestToken;
357       ExitedOriginalPad |= (ExitedPad == EHPad);
358     }
359 
360     if (ExitedOriginalPad)
361       return UnwindDestToken;
362 
363     // Continue the search.
364   }
365 
366   // No definitive information is contained within this funclet.
367   return nullptr;
368 }
369 
370 /// Given an EH pad, find where it unwinds.  If it unwinds to an EH pad,
371 /// return that pad instruction.  If it unwinds to caller, return
372 /// ConstantTokenNone.  If it does not have a definitive unwind destination,
373 /// return nullptr.
374 ///
375 /// This routine gets invoked for calls in funclets in inlinees when inlining
376 /// an invoke.  Since many funclets don't have calls inside them, it's queried
377 /// on-demand rather than building a map of pads to unwind dests up front.
378 /// Determining a funclet's unwind dest may require recursively searching its
379 /// descendants, and also ancestors and cousins if the descendants don't provide
380 /// an answer.  Since most funclets will have their unwind dest immediately
381 /// available as the unwind dest of a catchswitch or cleanupret, this routine
382 /// searches top-down from the given pad and then up. To avoid worst-case
383 /// quadratic run-time given that approach, it uses a memo map to avoid
384 /// re-processing funclet trees.  The callers that rewrite the IR as they go
385 /// take advantage of this, for correctness, by checking/forcing rewritten
386 /// pads' entries to match the original callee view.
387 static Value *getUnwindDestToken(Instruction *EHPad,
388                                  UnwindDestMemoTy &MemoMap) {
389   // Catchpads unwind to the same place as their catchswitch;
390   // redirct any queries on catchpads so the code below can
391   // deal with just catchswitches and cleanuppads.
392   if (auto *CPI = dyn_cast<CatchPadInst>(EHPad))
393     EHPad = CPI->getCatchSwitch();
394 
395   // Check if we've already determined the unwind dest for this pad.
396   auto Memo = MemoMap.find(EHPad);
397   if (Memo != MemoMap.end())
398     return Memo->second;
399 
400   // Search EHPad and, if necessary, its descendants.
401   Value *UnwindDestToken = getUnwindDestTokenHelper(EHPad, MemoMap);
402   assert((UnwindDestToken == nullptr) != (MemoMap.count(EHPad) != 0));
403   if (UnwindDestToken)
404     return UnwindDestToken;
405 
406   // No information is available for this EHPad from itself or any of its
407   // descendants.  An unwind all the way out to a pad in the caller would
408   // need also to agree with the unwind dest of the parent funclet, so
409   // search up the chain to try to find a funclet with information.  Put
410   // null entries in the memo map to avoid re-processing as we go up.
411   MemoMap[EHPad] = nullptr;
412 #ifndef NDEBUG
413   SmallPtrSet<Instruction *, 4> TempMemos;
414   TempMemos.insert(EHPad);
415 #endif
416   Instruction *LastUselessPad = EHPad;
417   Value *AncestorToken;
418   for (AncestorToken = getParentPad(EHPad);
419        auto *AncestorPad = dyn_cast<Instruction>(AncestorToken);
420        AncestorToken = getParentPad(AncestorToken)) {
421     // Skip over catchpads since they just follow their catchswitches.
422     if (isa<CatchPadInst>(AncestorPad))
423       continue;
424     // If the MemoMap had an entry mapping AncestorPad to nullptr, since we
425     // haven't yet called getUnwindDestTokenHelper for AncestorPad in this
426     // call to getUnwindDestToken, that would mean that AncestorPad had no
427     // information in itself, its descendants, or its ancestors.  If that
428     // were the case, then we should also have recorded the lack of information
429     // for the descendant that we're coming from.  So assert that we don't
430     // find a null entry in the MemoMap for AncestorPad.
431     assert(!MemoMap.count(AncestorPad) || MemoMap[AncestorPad]);
432     auto AncestorMemo = MemoMap.find(AncestorPad);
433     if (AncestorMemo == MemoMap.end()) {
434       UnwindDestToken = getUnwindDestTokenHelper(AncestorPad, MemoMap);
435     } else {
436       UnwindDestToken = AncestorMemo->second;
437     }
438     if (UnwindDestToken)
439       break;
440     LastUselessPad = AncestorPad;
441     MemoMap[LastUselessPad] = nullptr;
442 #ifndef NDEBUG
443     TempMemos.insert(LastUselessPad);
444 #endif
445   }
446 
447   // We know that getUnwindDestTokenHelper was called on LastUselessPad and
448   // returned nullptr (and likewise for EHPad and any of its ancestors up to
449   // LastUselessPad), so LastUselessPad has no information from below.  Since
450   // getUnwindDestTokenHelper must investigate all downward paths through
451   // no-information nodes to prove that a node has no information like this,
452   // and since any time it finds information it records it in the MemoMap for
453   // not just the immediately-containing funclet but also any ancestors also
454   // exited, it must be the case that, walking downward from LastUselessPad,
455   // visiting just those nodes which have not been mapped to an unwind dest
456   // by getUnwindDestTokenHelper (the nullptr TempMemos notwithstanding, since
457   // they are just used to keep getUnwindDestTokenHelper from repeating work),
458   // any node visited must have been exhaustively searched with no information
459   // for it found.
460   SmallVector<Instruction *, 8> Worklist(1, LastUselessPad);
461   while (!Worklist.empty()) {
462     Instruction *UselessPad = Worklist.pop_back_val();
463     auto Memo = MemoMap.find(UselessPad);
464     if (Memo != MemoMap.end() && Memo->second) {
465       // Here the name 'UselessPad' is a bit of a misnomer, because we've found
466       // that it is a funclet that does have information about unwinding to
467       // a particular destination; its parent was a useless pad.
468       // Since its parent has no information, the unwind edge must not escape
469       // the parent, and must target a sibling of this pad.  This local unwind
470       // gives us no information about EHPad.  Leave it and the subtree rooted
471       // at it alone.
472       assert(getParentPad(Memo->second) == getParentPad(UselessPad));
473       continue;
474     }
475     // We know we don't have information for UselesPad.  If it has an entry in
476     // the MemoMap (mapping it to nullptr), it must be one of the TempMemos
477     // added on this invocation of getUnwindDestToken; if a previous invocation
478     // recorded nullptr, it would have had to prove that the ancestors of
479     // UselessPad, which include LastUselessPad, had no information, and that
480     // in turn would have required proving that the descendants of
481     // LastUselesPad, which include EHPad, have no information about
482     // LastUselessPad, which would imply that EHPad was mapped to nullptr in
483     // the MemoMap on that invocation, which isn't the case if we got here.
484     assert(!MemoMap.count(UselessPad) || TempMemos.count(UselessPad));
485     // Assert as we enumerate users that 'UselessPad' doesn't have any unwind
486     // information that we'd be contradicting by making a map entry for it
487     // (which is something that getUnwindDestTokenHelper must have proved for
488     // us to get here).  Just assert on is direct users here; the checks in
489     // this downward walk at its descendants will verify that they don't have
490     // any unwind edges that exit 'UselessPad' either (i.e. they either have no
491     // unwind edges or unwind to a sibling).
492     MemoMap[UselessPad] = UnwindDestToken;
493     if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(UselessPad)) {
494       assert(CatchSwitch->getUnwindDest() == nullptr && "Expected useless pad");
495       for (BasicBlock *HandlerBlock : CatchSwitch->handlers()) {
496         auto *CatchPad = HandlerBlock->getFirstNonPHI();
497         for (User *U : CatchPad->users()) {
498           assert(
499               (!isa<InvokeInst>(U) ||
500                (getParentPad(
501                     cast<InvokeInst>(U)->getUnwindDest()->getFirstNonPHI()) ==
502                 CatchPad)) &&
503               "Expected useless pad");
504           if (isa<CatchSwitchInst>(U) || isa<CleanupPadInst>(U))
505             Worklist.push_back(cast<Instruction>(U));
506         }
507       }
508     } else {
509       assert(isa<CleanupPadInst>(UselessPad));
510       for (User *U : UselessPad->users()) {
511         assert(!isa<CleanupReturnInst>(U) && "Expected useless pad");
512         assert((!isa<InvokeInst>(U) ||
513                 (getParentPad(
514                      cast<InvokeInst>(U)->getUnwindDest()->getFirstNonPHI()) ==
515                  UselessPad)) &&
516                "Expected useless pad");
517         if (isa<CatchSwitchInst>(U) || isa<CleanupPadInst>(U))
518           Worklist.push_back(cast<Instruction>(U));
519       }
520     }
521   }
522 
523   return UnwindDestToken;
524 }
525 
526 /// When we inline a basic block into an invoke,
527 /// we have to turn all of the calls that can throw into invokes.
528 /// This function analyze BB to see if there are any calls, and if so,
529 /// it rewrites them to be invokes that jump to InvokeDest and fills in the PHI
530 /// nodes in that block with the values specified in InvokeDestPHIValues.
531 static BasicBlock *HandleCallsInBlockInlinedThroughInvoke(
532     BasicBlock *BB, BasicBlock *UnwindEdge,
533     UnwindDestMemoTy *FuncletUnwindMap = nullptr) {
534   for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
535     Instruction *I = &*BBI++;
536 
537     // We only need to check for function calls: inlined invoke
538     // instructions require no special handling.
539     CallInst *CI = dyn_cast<CallInst>(I);
540 
541     if (!CI || CI->doesNotThrow() || isa<InlineAsm>(CI->getCalledValue()))
542       continue;
543 
544     // We do not need to (and in fact, cannot) convert possibly throwing calls
545     // to @llvm.experimental_deoptimize (resp. @llvm.experimental.guard) into
546     // invokes.  The caller's "segment" of the deoptimization continuation
547     // attached to the newly inlined @llvm.experimental_deoptimize
548     // (resp. @llvm.experimental.guard) call should contain the exception
549     // handling logic, if any.
550     if (auto *F = CI->getCalledFunction())
551       if (F->getIntrinsicID() == Intrinsic::experimental_deoptimize ||
552           F->getIntrinsicID() == Intrinsic::experimental_guard)
553         continue;
554 
555     if (auto FuncletBundle = CI->getOperandBundle(LLVMContext::OB_funclet)) {
556       // This call is nested inside a funclet.  If that funclet has an unwind
557       // destination within the inlinee, then unwinding out of this call would
558       // be UB.  Rewriting this call to an invoke which targets the inlined
559       // invoke's unwind dest would give the call's parent funclet multiple
560       // unwind destinations, which is something that subsequent EH table
561       // generation can't handle and that the veirifer rejects.  So when we
562       // see such a call, leave it as a call.
563       auto *FuncletPad = cast<Instruction>(FuncletBundle->Inputs[0]);
564       Value *UnwindDestToken =
565           getUnwindDestToken(FuncletPad, *FuncletUnwindMap);
566       if (UnwindDestToken && !isa<ConstantTokenNone>(UnwindDestToken))
567         continue;
568 #ifndef NDEBUG
569       Instruction *MemoKey;
570       if (auto *CatchPad = dyn_cast<CatchPadInst>(FuncletPad))
571         MemoKey = CatchPad->getCatchSwitch();
572       else
573         MemoKey = FuncletPad;
574       assert(FuncletUnwindMap->count(MemoKey) &&
575              (*FuncletUnwindMap)[MemoKey] == UnwindDestToken &&
576              "must get memoized to avoid confusing later searches");
577 #endif // NDEBUG
578     }
579 
580     changeToInvokeAndSplitBasicBlock(CI, UnwindEdge);
581     return BB;
582   }
583   return nullptr;
584 }
585 
586 /// If we inlined an invoke site, we need to convert calls
587 /// in the body of the inlined function into invokes.
588 ///
589 /// II is the invoke instruction being inlined.  FirstNewBlock is the first
590 /// block of the inlined code (the last block is the end of the function),
591 /// and InlineCodeInfo is information about the code that got inlined.
592 static void HandleInlinedLandingPad(InvokeInst *II, BasicBlock *FirstNewBlock,
593                                     ClonedCodeInfo &InlinedCodeInfo) {
594   BasicBlock *InvokeDest = II->getUnwindDest();
595 
596   Function *Caller = FirstNewBlock->getParent();
597 
598   // The inlined code is currently at the end of the function, scan from the
599   // start of the inlined code to its end, checking for stuff we need to
600   // rewrite.
601   LandingPadInliningInfo Invoke(II);
602 
603   // Get all of the inlined landing pad instructions.
604   SmallPtrSet<LandingPadInst*, 16> InlinedLPads;
605   for (Function::iterator I = FirstNewBlock->getIterator(), E = Caller->end();
606        I != E; ++I)
607     if (InvokeInst *II = dyn_cast<InvokeInst>(I->getTerminator()))
608       InlinedLPads.insert(II->getLandingPadInst());
609 
610   // Append the clauses from the outer landing pad instruction into the inlined
611   // landing pad instructions.
612   LandingPadInst *OuterLPad = Invoke.getLandingPadInst();
613   for (LandingPadInst *InlinedLPad : InlinedLPads) {
614     unsigned OuterNum = OuterLPad->getNumClauses();
615     InlinedLPad->reserveClauses(OuterNum);
616     for (unsigned OuterIdx = 0; OuterIdx != OuterNum; ++OuterIdx)
617       InlinedLPad->addClause(OuterLPad->getClause(OuterIdx));
618     if (OuterLPad->isCleanup())
619       InlinedLPad->setCleanup(true);
620   }
621 
622   for (Function::iterator BB = FirstNewBlock->getIterator(), E = Caller->end();
623        BB != E; ++BB) {
624     if (InlinedCodeInfo.ContainsCalls)
625       if (BasicBlock *NewBB = HandleCallsInBlockInlinedThroughInvoke(
626               &*BB, Invoke.getOuterResumeDest()))
627         // Update any PHI nodes in the exceptional block to indicate that there
628         // is now a new entry in them.
629         Invoke.addIncomingPHIValuesFor(NewBB);
630 
631     // Forward any resumes that are remaining here.
632     if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator()))
633       Invoke.forwardResume(RI, InlinedLPads);
634   }
635 
636   // Now that everything is happy, we have one final detail.  The PHI nodes in
637   // the exception destination block still have entries due to the original
638   // invoke instruction. Eliminate these entries (which might even delete the
639   // PHI node) now.
640   InvokeDest->removePredecessor(II->getParent());
641 }
642 
643 /// If we inlined an invoke site, we need to convert calls
644 /// in the body of the inlined function into invokes.
645 ///
646 /// II is the invoke instruction being inlined.  FirstNewBlock is the first
647 /// block of the inlined code (the last block is the end of the function),
648 /// and InlineCodeInfo is information about the code that got inlined.
649 static void HandleInlinedEHPad(InvokeInst *II, BasicBlock *FirstNewBlock,
650                                ClonedCodeInfo &InlinedCodeInfo) {
651   BasicBlock *UnwindDest = II->getUnwindDest();
652   Function *Caller = FirstNewBlock->getParent();
653 
654   assert(UnwindDest->getFirstNonPHI()->isEHPad() && "unexpected BasicBlock!");
655 
656   // If there are PHI nodes in the unwind destination block, we need to keep
657   // track of which values came into them from the invoke before removing the
658   // edge from this block.
659   SmallVector<Value *, 8> UnwindDestPHIValues;
660   BasicBlock *InvokeBB = II->getParent();
661   for (Instruction &I : *UnwindDest) {
662     // Save the value to use for this edge.
663     PHINode *PHI = dyn_cast<PHINode>(&I);
664     if (!PHI)
665       break;
666     UnwindDestPHIValues.push_back(PHI->getIncomingValueForBlock(InvokeBB));
667   }
668 
669   // Add incoming-PHI values to the unwind destination block for the given basic
670   // block, using the values for the original invoke's source block.
671   auto UpdatePHINodes = [&](BasicBlock *Src) {
672     BasicBlock::iterator I = UnwindDest->begin();
673     for (Value *V : UnwindDestPHIValues) {
674       PHINode *PHI = cast<PHINode>(I);
675       PHI->addIncoming(V, Src);
676       ++I;
677     }
678   };
679 
680   // This connects all the instructions which 'unwind to caller' to the invoke
681   // destination.
682   UnwindDestMemoTy FuncletUnwindMap;
683   for (Function::iterator BB = FirstNewBlock->getIterator(), E = Caller->end();
684        BB != E; ++BB) {
685     if (auto *CRI = dyn_cast<CleanupReturnInst>(BB->getTerminator())) {
686       if (CRI->unwindsToCaller()) {
687         auto *CleanupPad = CRI->getCleanupPad();
688         CleanupReturnInst::Create(CleanupPad, UnwindDest, CRI);
689         CRI->eraseFromParent();
690         UpdatePHINodes(&*BB);
691         // Finding a cleanupret with an unwind destination would confuse
692         // subsequent calls to getUnwindDestToken, so map the cleanuppad
693         // to short-circuit any such calls and recognize this as an "unwind
694         // to caller" cleanup.
695         assert(!FuncletUnwindMap.count(CleanupPad) ||
696                isa<ConstantTokenNone>(FuncletUnwindMap[CleanupPad]));
697         FuncletUnwindMap[CleanupPad] =
698             ConstantTokenNone::get(Caller->getContext());
699       }
700     }
701 
702     Instruction *I = BB->getFirstNonPHI();
703     if (!I->isEHPad())
704       continue;
705 
706     Instruction *Replacement = nullptr;
707     if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(I)) {
708       if (CatchSwitch->unwindsToCaller()) {
709         Value *UnwindDestToken;
710         if (auto *ParentPad =
711                 dyn_cast<Instruction>(CatchSwitch->getParentPad())) {
712           // This catchswitch is nested inside another funclet.  If that
713           // funclet has an unwind destination within the inlinee, then
714           // unwinding out of this catchswitch would be UB.  Rewriting this
715           // catchswitch to unwind to the inlined invoke's unwind dest would
716           // give the parent funclet multiple unwind destinations, which is
717           // something that subsequent EH table generation can't handle and
718           // that the veirifer rejects.  So when we see such a call, leave it
719           // as "unwind to caller".
720           UnwindDestToken = getUnwindDestToken(ParentPad, FuncletUnwindMap);
721           if (UnwindDestToken && !isa<ConstantTokenNone>(UnwindDestToken))
722             continue;
723         } else {
724           // This catchswitch has no parent to inherit constraints from, and
725           // none of its descendants can have an unwind edge that exits it and
726           // targets another funclet in the inlinee.  It may or may not have a
727           // descendant that definitively has an unwind to caller.  In either
728           // case, we'll have to assume that any unwinds out of it may need to
729           // be routed to the caller, so treat it as though it has a definitive
730           // unwind to caller.
731           UnwindDestToken = ConstantTokenNone::get(Caller->getContext());
732         }
733         auto *NewCatchSwitch = CatchSwitchInst::Create(
734             CatchSwitch->getParentPad(), UnwindDest,
735             CatchSwitch->getNumHandlers(), CatchSwitch->getName(),
736             CatchSwitch);
737         for (BasicBlock *PadBB : CatchSwitch->handlers())
738           NewCatchSwitch->addHandler(PadBB);
739         // Propagate info for the old catchswitch over to the new one in
740         // the unwind map.  This also serves to short-circuit any subsequent
741         // checks for the unwind dest of this catchswitch, which would get
742         // confused if they found the outer handler in the callee.
743         FuncletUnwindMap[NewCatchSwitch] = UnwindDestToken;
744         Replacement = NewCatchSwitch;
745       }
746     } else if (!isa<FuncletPadInst>(I)) {
747       llvm_unreachable("unexpected EHPad!");
748     }
749 
750     if (Replacement) {
751       Replacement->takeName(I);
752       I->replaceAllUsesWith(Replacement);
753       I->eraseFromParent();
754       UpdatePHINodes(&*BB);
755     }
756   }
757 
758   if (InlinedCodeInfo.ContainsCalls)
759     for (Function::iterator BB = FirstNewBlock->getIterator(),
760                             E = Caller->end();
761          BB != E; ++BB)
762       if (BasicBlock *NewBB = HandleCallsInBlockInlinedThroughInvoke(
763               &*BB, UnwindDest, &FuncletUnwindMap))
764         // Update any PHI nodes in the exceptional block to indicate that there
765         // is now a new entry in them.
766         UpdatePHINodes(NewBB);
767 
768   // Now that everything is happy, we have one final detail.  The PHI nodes in
769   // the exception destination block still have entries due to the original
770   // invoke instruction. Eliminate these entries (which might even delete the
771   // PHI node) now.
772   UnwindDest->removePredecessor(InvokeBB);
773 }
774 
775 /// When inlining a call site that has !llvm.mem.parallel_loop_access or
776 /// llvm.access.group metadata, that metadata should be propagated to all
777 /// memory-accessing cloned instructions.
778 static void PropagateParallelLoopAccessMetadata(CallBase &CB,
779                                                 ValueToValueMapTy &VMap) {
780   MDNode *M = CB.getMetadata(LLVMContext::MD_mem_parallel_loop_access);
781   MDNode *CallAccessGroup = CB.getMetadata(LLVMContext::MD_access_group);
782   if (!M && !CallAccessGroup)
783     return;
784 
785   for (ValueToValueMapTy::iterator VMI = VMap.begin(), VMIE = VMap.end();
786        VMI != VMIE; ++VMI) {
787     if (!VMI->second)
788       continue;
789 
790     Instruction *NI = dyn_cast<Instruction>(VMI->second);
791     if (!NI)
792       continue;
793 
794     if (M) {
795       if (MDNode *PM =
796               NI->getMetadata(LLVMContext::MD_mem_parallel_loop_access)) {
797         M = MDNode::concatenate(PM, M);
798       NI->setMetadata(LLVMContext::MD_mem_parallel_loop_access, M);
799       } else if (NI->mayReadOrWriteMemory()) {
800         NI->setMetadata(LLVMContext::MD_mem_parallel_loop_access, M);
801       }
802     }
803 
804     if (NI->mayReadOrWriteMemory()) {
805       MDNode *UnitedAccGroups = uniteAccessGroups(
806           NI->getMetadata(LLVMContext::MD_access_group), CallAccessGroup);
807       NI->setMetadata(LLVMContext::MD_access_group, UnitedAccGroups);
808     }
809   }
810 }
811 
812 /// When inlining a function that contains noalias scope metadata,
813 /// this metadata needs to be cloned so that the inlined blocks
814 /// have different "unique scopes" at every call site. Were this not done, then
815 /// aliasing scopes from a function inlined into a caller multiple times could
816 /// not be differentiated (and this would lead to miscompiles because the
817 /// non-aliasing property communicated by the metadata could have
818 /// call-site-specific control dependencies).
819 static void CloneAliasScopeMetadata(CallBase &CB, ValueToValueMapTy &VMap) {
820   const Function *CalledFunc = CB.getCalledFunction();
821   SetVector<const MDNode *> MD;
822 
823   // Note: We could only clone the metadata if it is already used in the
824   // caller. I'm omitting that check here because it might confuse
825   // inter-procedural alias analysis passes. We can revisit this if it becomes
826   // an efficiency or overhead problem.
827 
828   for (const BasicBlock &I : *CalledFunc)
829     for (const Instruction &J : I) {
830       if (const MDNode *M = J.getMetadata(LLVMContext::MD_alias_scope))
831         MD.insert(M);
832       if (const MDNode *M = J.getMetadata(LLVMContext::MD_noalias))
833         MD.insert(M);
834     }
835 
836   if (MD.empty())
837     return;
838 
839   // Walk the existing metadata, adding the complete (perhaps cyclic) chain to
840   // the set.
841   SmallVector<const Metadata *, 16> Queue(MD.begin(), MD.end());
842   while (!Queue.empty()) {
843     const MDNode *M = cast<MDNode>(Queue.pop_back_val());
844     for (unsigned i = 0, ie = M->getNumOperands(); i != ie; ++i)
845       if (const MDNode *M1 = dyn_cast<MDNode>(M->getOperand(i)))
846         if (MD.insert(M1))
847           Queue.push_back(M1);
848   }
849 
850   // Now we have a complete set of all metadata in the chains used to specify
851   // the noalias scopes and the lists of those scopes.
852   SmallVector<TempMDTuple, 16> DummyNodes;
853   DenseMap<const MDNode *, TrackingMDNodeRef> MDMap;
854   for (const MDNode *I : MD) {
855     DummyNodes.push_back(MDTuple::getTemporary(CalledFunc->getContext(), None));
856     MDMap[I].reset(DummyNodes.back().get());
857   }
858 
859   // Create new metadata nodes to replace the dummy nodes, replacing old
860   // metadata references with either a dummy node or an already-created new
861   // node.
862   for (const MDNode *I : MD) {
863     SmallVector<Metadata *, 4> NewOps;
864     for (unsigned i = 0, ie = I->getNumOperands(); i != ie; ++i) {
865       const Metadata *V = I->getOperand(i);
866       if (const MDNode *M = dyn_cast<MDNode>(V))
867         NewOps.push_back(MDMap[M]);
868       else
869         NewOps.push_back(const_cast<Metadata *>(V));
870     }
871 
872     MDNode *NewM = MDNode::get(CalledFunc->getContext(), NewOps);
873     MDTuple *TempM = cast<MDTuple>(MDMap[I]);
874     assert(TempM->isTemporary() && "Expected temporary node");
875 
876     TempM->replaceAllUsesWith(NewM);
877   }
878 
879   // Now replace the metadata in the new inlined instructions with the
880   // repacements from the map.
881   for (ValueToValueMapTy::iterator VMI = VMap.begin(), VMIE = VMap.end();
882        VMI != VMIE; ++VMI) {
883     if (!VMI->second)
884       continue;
885 
886     Instruction *NI = dyn_cast<Instruction>(VMI->second);
887     if (!NI)
888       continue;
889 
890     if (MDNode *M = NI->getMetadata(LLVMContext::MD_alias_scope)) {
891       MDNode *NewMD = MDMap[M];
892       // If the call site also had alias scope metadata (a list of scopes to
893       // which instructions inside it might belong), propagate those scopes to
894       // the inlined instructions.
895       if (MDNode *CSM = CB.getMetadata(LLVMContext::MD_alias_scope))
896         NewMD = MDNode::concatenate(NewMD, CSM);
897       NI->setMetadata(LLVMContext::MD_alias_scope, NewMD);
898     } else if (NI->mayReadOrWriteMemory()) {
899       if (MDNode *M = CB.getMetadata(LLVMContext::MD_alias_scope))
900         NI->setMetadata(LLVMContext::MD_alias_scope, M);
901     }
902 
903     if (MDNode *M = NI->getMetadata(LLVMContext::MD_noalias)) {
904       MDNode *NewMD = MDMap[M];
905       // If the call site also had noalias metadata (a list of scopes with
906       // which instructions inside it don't alias), propagate those scopes to
907       // the inlined instructions.
908       if (MDNode *CSM = CB.getMetadata(LLVMContext::MD_noalias))
909         NewMD = MDNode::concatenate(NewMD, CSM);
910       NI->setMetadata(LLVMContext::MD_noalias, NewMD);
911     } else if (NI->mayReadOrWriteMemory()) {
912       if (MDNode *M = CB.getMetadata(LLVMContext::MD_noalias))
913         NI->setMetadata(LLVMContext::MD_noalias, M);
914     }
915   }
916 }
917 
918 /// If the inlined function has noalias arguments,
919 /// then add new alias scopes for each noalias argument, tag the mapped noalias
920 /// parameters with noalias metadata specifying the new scope, and tag all
921 /// non-derived loads, stores and memory intrinsics with the new alias scopes.
922 static void AddAliasScopeMetadata(CallBase &CB, ValueToValueMapTy &VMap,
923                                   const DataLayout &DL, AAResults *CalleeAAR) {
924   if (!EnableNoAliasConversion)
925     return;
926 
927   const Function *CalledFunc = CB.getCalledFunction();
928   SmallVector<const Argument *, 4> NoAliasArgs;
929 
930   for (const Argument &Arg : CalledFunc->args())
931     if (CB.paramHasAttr(Arg.getArgNo(), Attribute::NoAlias) && !Arg.use_empty())
932       NoAliasArgs.push_back(&Arg);
933 
934   if (NoAliasArgs.empty())
935     return;
936 
937   // To do a good job, if a noalias variable is captured, we need to know if
938   // the capture point dominates the particular use we're considering.
939   DominatorTree DT;
940   DT.recalculate(const_cast<Function&>(*CalledFunc));
941 
942   // noalias indicates that pointer values based on the argument do not alias
943   // pointer values which are not based on it. So we add a new "scope" for each
944   // noalias function argument. Accesses using pointers based on that argument
945   // become part of that alias scope, accesses using pointers not based on that
946   // argument are tagged as noalias with that scope.
947 
948   DenseMap<const Argument *, MDNode *> NewScopes;
949   MDBuilder MDB(CalledFunc->getContext());
950 
951   // Create a new scope domain for this function.
952   MDNode *NewDomain =
953     MDB.createAnonymousAliasScopeDomain(CalledFunc->getName());
954   for (unsigned i = 0, e = NoAliasArgs.size(); i != e; ++i) {
955     const Argument *A = NoAliasArgs[i];
956 
957     std::string Name = std::string(CalledFunc->getName());
958     if (A->hasName()) {
959       Name += ": %";
960       Name += A->getName();
961     } else {
962       Name += ": argument ";
963       Name += utostr(i);
964     }
965 
966     // Note: We always create a new anonymous root here. This is true regardless
967     // of the linkage of the callee because the aliasing "scope" is not just a
968     // property of the callee, but also all control dependencies in the caller.
969     MDNode *NewScope = MDB.createAnonymousAliasScope(NewDomain, Name);
970     NewScopes.insert(std::make_pair(A, NewScope));
971   }
972 
973   // Iterate over all new instructions in the map; for all memory-access
974   // instructions, add the alias scope metadata.
975   for (ValueToValueMapTy::iterator VMI = VMap.begin(), VMIE = VMap.end();
976        VMI != VMIE; ++VMI) {
977     if (const Instruction *I = dyn_cast<Instruction>(VMI->first)) {
978       if (!VMI->second)
979         continue;
980 
981       Instruction *NI = dyn_cast<Instruction>(VMI->second);
982       if (!NI)
983         continue;
984 
985       bool IsArgMemOnlyCall = false, IsFuncCall = false;
986       SmallVector<const Value *, 2> PtrArgs;
987 
988       if (const LoadInst *LI = dyn_cast<LoadInst>(I))
989         PtrArgs.push_back(LI->getPointerOperand());
990       else if (const StoreInst *SI = dyn_cast<StoreInst>(I))
991         PtrArgs.push_back(SI->getPointerOperand());
992       else if (const VAArgInst *VAAI = dyn_cast<VAArgInst>(I))
993         PtrArgs.push_back(VAAI->getPointerOperand());
994       else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I))
995         PtrArgs.push_back(CXI->getPointerOperand());
996       else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I))
997         PtrArgs.push_back(RMWI->getPointerOperand());
998       else if (const auto *Call = dyn_cast<CallBase>(I)) {
999         // If we know that the call does not access memory, then we'll still
1000         // know that about the inlined clone of this call site, and we don't
1001         // need to add metadata.
1002         if (Call->doesNotAccessMemory())
1003           continue;
1004 
1005         IsFuncCall = true;
1006         if (CalleeAAR) {
1007           FunctionModRefBehavior MRB = CalleeAAR->getModRefBehavior(Call);
1008           if (AAResults::onlyAccessesArgPointees(MRB))
1009             IsArgMemOnlyCall = true;
1010         }
1011 
1012         for (Value *Arg : Call->args()) {
1013           // We need to check the underlying objects of all arguments, not just
1014           // the pointer arguments, because we might be passing pointers as
1015           // integers, etc.
1016           // However, if we know that the call only accesses pointer arguments,
1017           // then we only need to check the pointer arguments.
1018           if (IsArgMemOnlyCall && !Arg->getType()->isPointerTy())
1019             continue;
1020 
1021           PtrArgs.push_back(Arg);
1022         }
1023       }
1024 
1025       // If we found no pointers, then this instruction is not suitable for
1026       // pairing with an instruction to receive aliasing metadata.
1027       // However, if this is a call, this we might just alias with none of the
1028       // noalias arguments.
1029       if (PtrArgs.empty() && !IsFuncCall)
1030         continue;
1031 
1032       // It is possible that there is only one underlying object, but you
1033       // need to go through several PHIs to see it, and thus could be
1034       // repeated in the Objects list.
1035       SmallPtrSet<const Value *, 4> ObjSet;
1036       SmallVector<Metadata *, 4> Scopes, NoAliases;
1037 
1038       SmallSetVector<const Argument *, 4> NAPtrArgs;
1039       for (const Value *V : PtrArgs) {
1040         SmallVector<const Value *, 4> Objects;
1041         GetUnderlyingObjects(V, Objects, DL, /* LI = */ nullptr);
1042 
1043         for (const Value *O : Objects)
1044           ObjSet.insert(O);
1045       }
1046 
1047       // Figure out if we're derived from anything that is not a noalias
1048       // argument.
1049       bool CanDeriveViaCapture = false, UsesAliasingPtr = false;
1050       for (const Value *V : ObjSet) {
1051         // Is this value a constant that cannot be derived from any pointer
1052         // value (we need to exclude constant expressions, for example, that
1053         // are formed from arithmetic on global symbols).
1054         bool IsNonPtrConst = isa<ConstantInt>(V) || isa<ConstantFP>(V) ||
1055                              isa<ConstantPointerNull>(V) ||
1056                              isa<ConstantDataVector>(V) || isa<UndefValue>(V);
1057         if (IsNonPtrConst)
1058           continue;
1059 
1060         // If this is anything other than a noalias argument, then we cannot
1061         // completely describe the aliasing properties using alias.scope
1062         // metadata (and, thus, won't add any).
1063         if (const Argument *A = dyn_cast<Argument>(V)) {
1064           if (!CB.paramHasAttr(A->getArgNo(), Attribute::NoAlias))
1065             UsesAliasingPtr = true;
1066         } else {
1067           UsesAliasingPtr = true;
1068         }
1069 
1070         // If this is not some identified function-local object (which cannot
1071         // directly alias a noalias argument), or some other argument (which,
1072         // by definition, also cannot alias a noalias argument), then we could
1073         // alias a noalias argument that has been captured).
1074         if (!isa<Argument>(V) &&
1075             !isIdentifiedFunctionLocal(const_cast<Value*>(V)))
1076           CanDeriveViaCapture = true;
1077       }
1078 
1079       // A function call can always get captured noalias pointers (via other
1080       // parameters, globals, etc.).
1081       if (IsFuncCall && !IsArgMemOnlyCall)
1082         CanDeriveViaCapture = true;
1083 
1084       // First, we want to figure out all of the sets with which we definitely
1085       // don't alias. Iterate over all noalias set, and add those for which:
1086       //   1. The noalias argument is not in the set of objects from which we
1087       //      definitely derive.
1088       //   2. The noalias argument has not yet been captured.
1089       // An arbitrary function that might load pointers could see captured
1090       // noalias arguments via other noalias arguments or globals, and so we
1091       // must always check for prior capture.
1092       for (const Argument *A : NoAliasArgs) {
1093         if (!ObjSet.count(A) && (!CanDeriveViaCapture ||
1094                                  // It might be tempting to skip the
1095                                  // PointerMayBeCapturedBefore check if
1096                                  // A->hasNoCaptureAttr() is true, but this is
1097                                  // incorrect because nocapture only guarantees
1098                                  // that no copies outlive the function, not
1099                                  // that the value cannot be locally captured.
1100                                  !PointerMayBeCapturedBefore(A,
1101                                    /* ReturnCaptures */ false,
1102                                    /* StoreCaptures */ false, I, &DT)))
1103           NoAliases.push_back(NewScopes[A]);
1104       }
1105 
1106       if (!NoAliases.empty())
1107         NI->setMetadata(LLVMContext::MD_noalias,
1108                         MDNode::concatenate(
1109                             NI->getMetadata(LLVMContext::MD_noalias),
1110                             MDNode::get(CalledFunc->getContext(), NoAliases)));
1111 
1112       // Next, we want to figure out all of the sets to which we might belong.
1113       // We might belong to a set if the noalias argument is in the set of
1114       // underlying objects. If there is some non-noalias argument in our list
1115       // of underlying objects, then we cannot add a scope because the fact
1116       // that some access does not alias with any set of our noalias arguments
1117       // cannot itself guarantee that it does not alias with this access
1118       // (because there is some pointer of unknown origin involved and the
1119       // other access might also depend on this pointer). We also cannot add
1120       // scopes to arbitrary functions unless we know they don't access any
1121       // non-parameter pointer-values.
1122       bool CanAddScopes = !UsesAliasingPtr;
1123       if (CanAddScopes && IsFuncCall)
1124         CanAddScopes = IsArgMemOnlyCall;
1125 
1126       if (CanAddScopes)
1127         for (const Argument *A : NoAliasArgs) {
1128           if (ObjSet.count(A))
1129             Scopes.push_back(NewScopes[A]);
1130         }
1131 
1132       if (!Scopes.empty())
1133         NI->setMetadata(
1134             LLVMContext::MD_alias_scope,
1135             MDNode::concatenate(NI->getMetadata(LLVMContext::MD_alias_scope),
1136                                 MDNode::get(CalledFunc->getContext(), Scopes)));
1137     }
1138   }
1139 }
1140 
1141 static bool MayContainThrowingOrExitingCall(Instruction *Begin,
1142                                             Instruction *End) {
1143 
1144   assert(Begin->getParent() == End->getParent() &&
1145          "Expected to be in same basic block!");
1146   unsigned NumInstChecked = 0;
1147   // Check that all instructions in the range [Begin, End) are guaranteed to
1148   // transfer execution to successor.
1149   for (auto &I : make_range(Begin->getIterator(), End->getIterator()))
1150     if (NumInstChecked++ > InlinerAttributeWindow ||
1151         !isGuaranteedToTransferExecutionToSuccessor(&I))
1152       return true;
1153   return false;
1154 }
1155 
1156 static AttrBuilder IdentifyValidAttributes(CallBase &CB) {
1157 
1158   AttrBuilder AB(CB.getAttributes(), AttributeList::ReturnIndex);
1159   if (AB.empty())
1160     return AB;
1161   AttrBuilder Valid;
1162   // Only allow these white listed attributes to be propagated back to the
1163   // callee. This is because other attributes may only be valid on the call
1164   // itself, i.e. attributes such as signext and zeroext.
1165   if (auto DerefBytes = AB.getDereferenceableBytes())
1166     Valid.addDereferenceableAttr(DerefBytes);
1167   if (auto DerefOrNullBytes = AB.getDereferenceableOrNullBytes())
1168     Valid.addDereferenceableOrNullAttr(DerefOrNullBytes);
1169   if (AB.contains(Attribute::NoAlias))
1170     Valid.addAttribute(Attribute::NoAlias);
1171   if (AB.contains(Attribute::NonNull))
1172     Valid.addAttribute(Attribute::NonNull);
1173   return Valid;
1174 }
1175 
1176 static void AddReturnAttributes(CallBase &CB, ValueToValueMapTy &VMap) {
1177   if (!UpdateReturnAttributes && !UpdateLoadMetadataDuringInlining)
1178     return;
1179 
1180   AttrBuilder Valid = IdentifyValidAttributes(CB);
1181   if (Valid.empty())
1182     return;
1183   auto *CalledFunction = CB.getCalledFunction();
1184   auto &Context = CalledFunction->getContext();
1185 
1186   auto getExpectedRV = [&](Value *V) -> Instruction * {
1187     if (UpdateReturnAttributes && isa<CallBase>(V))
1188       return dyn_cast_or_null<CallBase>(VMap.lookup(V));
1189     if (UpdateLoadMetadataDuringInlining && isa<LoadInst>(V))
1190       return dyn_cast_or_null<LoadInst>(VMap.lookup(V));
1191     return nullptr;
1192   };
1193 
1194  MDBuilder MDB(Context);
1195   auto CreateMDNode = [&](uint64_t Num) -> MDNode * {
1196     auto *Int = ConstantInt::get(Type::getInt64Ty(Context), Num);
1197     return MDNode::get(Context, MDB.createConstant(Int));
1198   };
1199 
1200   for (auto &BB : *CalledFunction) {
1201     auto *RI = dyn_cast<ReturnInst>(BB.getTerminator());
1202     if (!RI)
1203       continue;
1204     // Sanity check that the cloned RetVal exists and is a call, otherwise we
1205     // cannot add the attributes on the cloned RetVal.
1206     // Simplification during inlining could have transformed the cloned
1207     // instruction.
1208     auto *NewRetVal = getExpectedRV(RI->getOperand(0));
1209     if (!NewRetVal)
1210       continue;
1211     auto *RetVal = cast<Instruction>(RI->getOperand(0));
1212     // Backward propagation of attributes to the returned value may be incorrect
1213     // if it is control flow dependent.
1214     // Consider:
1215     // @callee {
1216     //  %rv = call @foo()
1217     //  %rv2 = call @bar()
1218     //  if (%rv2 != null)
1219     //    return %rv2
1220     //  if (%rv == null)
1221     //    exit()
1222     //  return %rv
1223     // }
1224     // caller() {
1225     //   %val = call nonnull @callee()
1226     // }
1227     // Here we cannot add the nonnull attribute on either foo or bar. So, we
1228     // limit the check to both RetVal and RI are in the same basic block and
1229     // there are no throwing/exiting instructions between these instructions.
1230     if (RI->getParent() != RetVal->getParent() ||
1231         MayContainThrowingOrExitingCall(RetVal, RI))
1232       continue;
1233     // Add to the existing attributes of NewRetVal, i.e. the cloned call
1234     // instruction.
1235     // NB! When we have the same attribute already existing on NewRetVal, but
1236     // with a differing value, the AttributeList's merge API honours the already
1237     // existing attribute value (i.e. attributes such as dereferenceable,
1238     // dereferenceable_or_null etc). See AttrBuilder::merge for more details.
1239     if (auto *NewRetValCB = dyn_cast<CallBase>(NewRetVal)) {
1240       AttributeList AL = NewRetValCB->getAttributes();
1241       AttributeList NewAL =
1242           AL.addAttributes(Context, AttributeList::ReturnIndex, Valid);
1243       NewRetValCB->setAttributes(NewAL);
1244     } else {
1245       auto *NewLI = cast<LoadInst>(NewRetVal);
1246       if (CB.isReturnNonNull())
1247         NewLI->setMetadata(LLVMContext::MD_nonnull, CreateMDNode(1));
1248       // If the load already has a dereferenceable/dereferenceable_or_null
1249       // metadata, we should honour it.
1250       if (uint64_t DerefBytes = Valid.getDereferenceableBytes())
1251        if(!NewLI->getMetadata(LLVMContext::MD_dereferenceable))
1252          NewLI->setMetadata(LLVMContext::MD_dereferenceable,
1253                             CreateMDNode(DerefBytes));
1254       if (uint64_t DerefOrNullBytes = Valid.getDereferenceableOrNullBytes())
1255        if (!NewLI->getMetadata(LLVMContext::MD_dereferenceable_or_null))
1256          NewLI->setMetadata(LLVMContext::MD_dereferenceable_or_null,
1257                             CreateMDNode(DerefOrNullBytes));
1258     }
1259   }
1260 }
1261 
1262 /// If the inlined function has non-byval align arguments, then
1263 /// add @llvm.assume-based alignment assumptions to preserve this information.
1264 static void AddAlignmentAssumptions(CallBase &CB, InlineFunctionInfo &IFI) {
1265   if (!PreserveAlignmentAssumptions || !IFI.GetAssumptionCache)
1266     return;
1267 
1268   AssumptionCache *AC = &(*IFI.GetAssumptionCache)(*CB.getCaller());
1269   auto &DL = CB.getCaller()->getParent()->getDataLayout();
1270 
1271   // To avoid inserting redundant assumptions, we should check for assumptions
1272   // already in the caller. To do this, we might need a DT of the caller.
1273   DominatorTree DT;
1274   bool DTCalculated = false;
1275 
1276   Function *CalledFunc = CB.getCalledFunction();
1277   for (Argument &Arg : CalledFunc->args()) {
1278     unsigned Align = Arg.getType()->isPointerTy() ? Arg.getParamAlignment() : 0;
1279     if (Align && !Arg.hasByValOrInAllocaAttr() && !Arg.hasNUses(0)) {
1280       if (!DTCalculated) {
1281         DT.recalculate(*CB.getCaller());
1282         DTCalculated = true;
1283       }
1284 
1285       // If we can already prove the asserted alignment in the context of the
1286       // caller, then don't bother inserting the assumption.
1287       Value *ArgVal = CB.getArgOperand(Arg.getArgNo());
1288       if (getKnownAlignment(ArgVal, DL, &CB, AC, &DT) >= Align)
1289         continue;
1290 
1291       CallInst *NewAsmp =
1292           IRBuilder<>(&CB).CreateAlignmentAssumption(DL, ArgVal, Align);
1293       AC->registerAssumption(NewAsmp);
1294     }
1295   }
1296 }
1297 
1298 /// Once we have cloned code over from a callee into the caller,
1299 /// update the specified callgraph to reflect the changes we made.
1300 /// Note that it's possible that not all code was copied over, so only
1301 /// some edges of the callgraph may remain.
1302 static void UpdateCallGraphAfterInlining(CallBase &CB,
1303                                          Function::iterator FirstNewBlock,
1304                                          ValueToValueMapTy &VMap,
1305                                          InlineFunctionInfo &IFI) {
1306   CallGraph &CG = *IFI.CG;
1307   const Function *Caller = CB.getCaller();
1308   const Function *Callee = CB.getCalledFunction();
1309   CallGraphNode *CalleeNode = CG[Callee];
1310   CallGraphNode *CallerNode = CG[Caller];
1311 
1312   // Since we inlined some uninlined call sites in the callee into the caller,
1313   // add edges from the caller to all of the callees of the callee.
1314   CallGraphNode::iterator I = CalleeNode->begin(), E = CalleeNode->end();
1315 
1316   // Consider the case where CalleeNode == CallerNode.
1317   CallGraphNode::CalledFunctionsVector CallCache;
1318   if (CalleeNode == CallerNode) {
1319     CallCache.assign(I, E);
1320     I = CallCache.begin();
1321     E = CallCache.end();
1322   }
1323 
1324   for (; I != E; ++I) {
1325     const Value *OrigCall = I->first;
1326 
1327     ValueToValueMapTy::iterator VMI = VMap.find(OrigCall);
1328     // Only copy the edge if the call was inlined!
1329     if (VMI == VMap.end() || VMI->second == nullptr)
1330       continue;
1331 
1332     // If the call was inlined, but then constant folded, there is no edge to
1333     // add.  Check for this case.
1334     auto *NewCall = dyn_cast<CallBase>(VMI->second);
1335     if (!NewCall)
1336       continue;
1337 
1338     // We do not treat intrinsic calls like real function calls because we
1339     // expect them to become inline code; do not add an edge for an intrinsic.
1340     if (NewCall->getCalledFunction() &&
1341         NewCall->getCalledFunction()->isIntrinsic())
1342       continue;
1343 
1344     // Remember that this call site got inlined for the client of
1345     // InlineFunction.
1346     IFI.InlinedCalls.push_back(NewCall);
1347 
1348     // It's possible that inlining the callsite will cause it to go from an
1349     // indirect to a direct call by resolving a function pointer.  If this
1350     // happens, set the callee of the new call site to a more precise
1351     // destination.  This can also happen if the call graph node of the caller
1352     // was just unnecessarily imprecise.
1353     if (!I->second->getFunction())
1354       if (Function *F = NewCall->getCalledFunction()) {
1355         // Indirect call site resolved to direct call.
1356         CallerNode->addCalledFunction(NewCall, CG[F]);
1357 
1358         continue;
1359       }
1360 
1361     CallerNode->addCalledFunction(NewCall, I->second);
1362   }
1363 
1364   // Update the call graph by deleting the edge from Callee to Caller.  We must
1365   // do this after the loop above in case Caller and Callee are the same.
1366   CallerNode->removeCallEdgeFor(*cast<CallBase>(&CB));
1367 }
1368 
1369 static void HandleByValArgumentInit(Value *Dst, Value *Src, Module *M,
1370                                     BasicBlock *InsertBlock,
1371                                     InlineFunctionInfo &IFI) {
1372   Type *AggTy = cast<PointerType>(Src->getType())->getElementType();
1373   IRBuilder<> Builder(InsertBlock, InsertBlock->begin());
1374 
1375   Value *Size = Builder.getInt64(M->getDataLayout().getTypeStoreSize(AggTy));
1376 
1377   // Always generate a memcpy of alignment 1 here because we don't know
1378   // the alignment of the src pointer.  Other optimizations can infer
1379   // better alignment.
1380   Builder.CreateMemCpy(Dst, /*DstAlign*/ Align(1), Src,
1381                        /*SrcAlign*/ Align(1), Size);
1382 }
1383 
1384 /// When inlining a call site that has a byval argument,
1385 /// we have to make the implicit memcpy explicit by adding it.
1386 static Value *HandleByValArgument(Value *Arg, Instruction *TheCall,
1387                                   const Function *CalledFunc,
1388                                   InlineFunctionInfo &IFI,
1389                                   unsigned ByValAlignment) {
1390   PointerType *ArgTy = cast<PointerType>(Arg->getType());
1391   Type *AggTy = ArgTy->getElementType();
1392 
1393   Function *Caller = TheCall->getFunction();
1394   const DataLayout &DL = Caller->getParent()->getDataLayout();
1395 
1396   // If the called function is readonly, then it could not mutate the caller's
1397   // copy of the byval'd memory.  In this case, it is safe to elide the copy and
1398   // temporary.
1399   if (CalledFunc->onlyReadsMemory()) {
1400     // If the byval argument has a specified alignment that is greater than the
1401     // passed in pointer, then we either have to round up the input pointer or
1402     // give up on this transformation.
1403     if (ByValAlignment <= 1)  // 0 = unspecified, 1 = no particular alignment.
1404       return Arg;
1405 
1406     AssumptionCache *AC =
1407         IFI.GetAssumptionCache ? &(*IFI.GetAssumptionCache)(*Caller) : nullptr;
1408 
1409     // If the pointer is already known to be sufficiently aligned, or if we can
1410     // round it up to a larger alignment, then we don't need a temporary.
1411     if (getOrEnforceKnownAlignment(Arg, ByValAlignment, DL, TheCall, AC) >=
1412         ByValAlignment)
1413       return Arg;
1414 
1415     // Otherwise, we have to make a memcpy to get a safe alignment.  This is bad
1416     // for code quality, but rarely happens and is required for correctness.
1417   }
1418 
1419   // Create the alloca.  If we have DataLayout, use nice alignment.
1420   Align Alignment(DL.getPrefTypeAlignment(AggTy));
1421 
1422   // If the byval had an alignment specified, we *must* use at least that
1423   // alignment, as it is required by the byval argument (and uses of the
1424   // pointer inside the callee).
1425   Alignment = max(Alignment, MaybeAlign(ByValAlignment));
1426 
1427   Value *NewAlloca =
1428       new AllocaInst(AggTy, DL.getAllocaAddrSpace(), nullptr, Alignment,
1429                      Arg->getName(), &*Caller->begin()->begin());
1430   IFI.StaticAllocas.push_back(cast<AllocaInst>(NewAlloca));
1431 
1432   // Uses of the argument in the function should use our new alloca
1433   // instead.
1434   return NewAlloca;
1435 }
1436 
1437 // Check whether this Value is used by a lifetime intrinsic.
1438 static bool isUsedByLifetimeMarker(Value *V) {
1439   for (User *U : V->users())
1440     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U))
1441       if (II->isLifetimeStartOrEnd())
1442         return true;
1443   return false;
1444 }
1445 
1446 // Check whether the given alloca already has
1447 // lifetime.start or lifetime.end intrinsics.
1448 static bool hasLifetimeMarkers(AllocaInst *AI) {
1449   Type *Ty = AI->getType();
1450   Type *Int8PtrTy = Type::getInt8PtrTy(Ty->getContext(),
1451                                        Ty->getPointerAddressSpace());
1452   if (Ty == Int8PtrTy)
1453     return isUsedByLifetimeMarker(AI);
1454 
1455   // Do a scan to find all the casts to i8*.
1456   for (User *U : AI->users()) {
1457     if (U->getType() != Int8PtrTy) continue;
1458     if (U->stripPointerCasts() != AI) continue;
1459     if (isUsedByLifetimeMarker(U))
1460       return true;
1461   }
1462   return false;
1463 }
1464 
1465 /// Return the result of AI->isStaticAlloca() if AI were moved to the entry
1466 /// block. Allocas used in inalloca calls and allocas of dynamic array size
1467 /// cannot be static.
1468 static bool allocaWouldBeStaticInEntry(const AllocaInst *AI ) {
1469   return isa<Constant>(AI->getArraySize()) && !AI->isUsedWithInAlloca();
1470 }
1471 
1472 /// Returns a DebugLoc for a new DILocation which is a clone of \p OrigDL
1473 /// inlined at \p InlinedAt. \p IANodes is an inlined-at cache.
1474 static DebugLoc inlineDebugLoc(DebugLoc OrigDL, DILocation *InlinedAt,
1475                                LLVMContext &Ctx,
1476                                DenseMap<const MDNode *, MDNode *> &IANodes) {
1477   auto IA = DebugLoc::appendInlinedAt(OrigDL, InlinedAt, Ctx, IANodes);
1478   return DebugLoc::get(OrigDL.getLine(), OrigDL.getCol(), OrigDL.getScope(),
1479                        IA);
1480 }
1481 
1482 /// Update inlined instructions' line numbers to
1483 /// to encode location where these instructions are inlined.
1484 static void fixupLineNumbers(Function *Fn, Function::iterator FI,
1485                              Instruction *TheCall, bool CalleeHasDebugInfo) {
1486   const DebugLoc &TheCallDL = TheCall->getDebugLoc();
1487   if (!TheCallDL)
1488     return;
1489 
1490   auto &Ctx = Fn->getContext();
1491   DILocation *InlinedAtNode = TheCallDL;
1492 
1493   // Create a unique call site, not to be confused with any other call from the
1494   // same location.
1495   InlinedAtNode = DILocation::getDistinct(
1496       Ctx, InlinedAtNode->getLine(), InlinedAtNode->getColumn(),
1497       InlinedAtNode->getScope(), InlinedAtNode->getInlinedAt());
1498 
1499   // Cache the inlined-at nodes as they're built so they are reused, without
1500   // this every instruction's inlined-at chain would become distinct from each
1501   // other.
1502   DenseMap<const MDNode *, MDNode *> IANodes;
1503 
1504   // Check if we are not generating inline line tables and want to use
1505   // the call site location instead.
1506   bool NoInlineLineTables = Fn->hasFnAttribute("no-inline-line-tables");
1507 
1508   for (; FI != Fn->end(); ++FI) {
1509     for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
1510          BI != BE; ++BI) {
1511       // Loop metadata needs to be updated so that the start and end locs
1512       // reference inlined-at locations.
1513       auto updateLoopInfoLoc = [&Ctx, &InlinedAtNode, &IANodes](
1514                                    const DILocation &Loc) -> DILocation * {
1515         return inlineDebugLoc(&Loc, InlinedAtNode, Ctx, IANodes).get();
1516       };
1517       updateLoopMetadataDebugLocations(*BI, updateLoopInfoLoc);
1518 
1519       if (!NoInlineLineTables)
1520         if (DebugLoc DL = BI->getDebugLoc()) {
1521           DebugLoc IDL =
1522               inlineDebugLoc(DL, InlinedAtNode, BI->getContext(), IANodes);
1523           BI->setDebugLoc(IDL);
1524           continue;
1525         }
1526 
1527       if (CalleeHasDebugInfo && !NoInlineLineTables)
1528         continue;
1529 
1530       // If the inlined instruction has no line number, or if inline info
1531       // is not being generated, make it look as if it originates from the call
1532       // location. This is important for ((__always_inline, __nodebug__))
1533       // functions which must use caller location for all instructions in their
1534       // function body.
1535 
1536       // Don't update static allocas, as they may get moved later.
1537       if (auto *AI = dyn_cast<AllocaInst>(BI))
1538         if (allocaWouldBeStaticInEntry(AI))
1539           continue;
1540 
1541       BI->setDebugLoc(TheCallDL);
1542     }
1543 
1544     // Remove debug info intrinsics if we're not keeping inline info.
1545     if (NoInlineLineTables) {
1546       BasicBlock::iterator BI = FI->begin();
1547       while (BI != FI->end()) {
1548         if (isa<DbgInfoIntrinsic>(BI)) {
1549           BI = BI->eraseFromParent();
1550           continue;
1551         }
1552         ++BI;
1553       }
1554     }
1555 
1556   }
1557 }
1558 
1559 /// Update the block frequencies of the caller after a callee has been inlined.
1560 ///
1561 /// Each block cloned into the caller has its block frequency scaled by the
1562 /// ratio of CallSiteFreq/CalleeEntryFreq. This ensures that the cloned copy of
1563 /// callee's entry block gets the same frequency as the callsite block and the
1564 /// relative frequencies of all cloned blocks remain the same after cloning.
1565 static void updateCallerBFI(BasicBlock *CallSiteBlock,
1566                             const ValueToValueMapTy &VMap,
1567                             BlockFrequencyInfo *CallerBFI,
1568                             BlockFrequencyInfo *CalleeBFI,
1569                             const BasicBlock &CalleeEntryBlock) {
1570   SmallPtrSet<BasicBlock *, 16> ClonedBBs;
1571   for (auto Entry : VMap) {
1572     if (!isa<BasicBlock>(Entry.first) || !Entry.second)
1573       continue;
1574     auto *OrigBB = cast<BasicBlock>(Entry.first);
1575     auto *ClonedBB = cast<BasicBlock>(Entry.second);
1576     uint64_t Freq = CalleeBFI->getBlockFreq(OrigBB).getFrequency();
1577     if (!ClonedBBs.insert(ClonedBB).second) {
1578       // Multiple blocks in the callee might get mapped to one cloned block in
1579       // the caller since we prune the callee as we clone it. When that happens,
1580       // we want to use the maximum among the original blocks' frequencies.
1581       uint64_t NewFreq = CallerBFI->getBlockFreq(ClonedBB).getFrequency();
1582       if (NewFreq > Freq)
1583         Freq = NewFreq;
1584     }
1585     CallerBFI->setBlockFreq(ClonedBB, Freq);
1586   }
1587   BasicBlock *EntryClone = cast<BasicBlock>(VMap.lookup(&CalleeEntryBlock));
1588   CallerBFI->setBlockFreqAndScale(
1589       EntryClone, CallerBFI->getBlockFreq(CallSiteBlock).getFrequency(),
1590       ClonedBBs);
1591 }
1592 
1593 /// Update the branch metadata for cloned call instructions.
1594 static void updateCallProfile(Function *Callee, const ValueToValueMapTy &VMap,
1595                               const ProfileCount &CalleeEntryCount,
1596                               const Instruction *TheCall,
1597                               ProfileSummaryInfo *PSI,
1598                               BlockFrequencyInfo *CallerBFI) {
1599   if (!CalleeEntryCount.hasValue() || CalleeEntryCount.isSynthetic() ||
1600       CalleeEntryCount.getCount() < 1)
1601     return;
1602   auto CallSiteCount = PSI ? PSI->getProfileCount(TheCall, CallerBFI) : None;
1603   int64_t CallCount =
1604       std::min(CallSiteCount.hasValue() ? CallSiteCount.getValue() : 0,
1605                CalleeEntryCount.getCount());
1606   updateProfileCallee(Callee, -CallCount, &VMap);
1607 }
1608 
1609 void llvm::updateProfileCallee(
1610     Function *Callee, int64_t entryDelta,
1611     const ValueMap<const Value *, WeakTrackingVH> *VMap) {
1612   auto CalleeCount = Callee->getEntryCount();
1613   if (!CalleeCount.hasValue())
1614     return;
1615 
1616   uint64_t priorEntryCount = CalleeCount.getCount();
1617   uint64_t newEntryCount;
1618 
1619   // Since CallSiteCount is an estimate, it could exceed the original callee
1620   // count and has to be set to 0 so guard against underflow.
1621   if (entryDelta < 0 && static_cast<uint64_t>(-entryDelta) > priorEntryCount)
1622     newEntryCount = 0;
1623   else
1624     newEntryCount = priorEntryCount + entryDelta;
1625 
1626   // During inlining ?
1627   if (VMap) {
1628     uint64_t cloneEntryCount = priorEntryCount - newEntryCount;
1629     for (auto Entry : *VMap)
1630       if (isa<CallInst>(Entry.first))
1631         if (auto *CI = dyn_cast_or_null<CallInst>(Entry.second))
1632           CI->updateProfWeight(cloneEntryCount, priorEntryCount);
1633   }
1634 
1635   if (entryDelta) {
1636     Callee->setEntryCount(newEntryCount);
1637 
1638     for (BasicBlock &BB : *Callee)
1639       // No need to update the callsite if it is pruned during inlining.
1640       if (!VMap || VMap->count(&BB))
1641         for (Instruction &I : BB)
1642           if (CallInst *CI = dyn_cast<CallInst>(&I))
1643             CI->updateProfWeight(newEntryCount, priorEntryCount);
1644   }
1645 }
1646 
1647 /// This function inlines the called function into the basic block of the
1648 /// caller. This returns false if it is not possible to inline this call.
1649 /// The program is still in a well defined state if this occurs though.
1650 ///
1651 /// Note that this only does one level of inlining.  For example, if the
1652 /// instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now
1653 /// exists in the instruction stream.  Similarly this will inline a recursive
1654 /// function by one level.
1655 llvm::InlineResult llvm::InlineFunction(CallBase &CB, InlineFunctionInfo &IFI,
1656                                         AAResults *CalleeAAR,
1657                                         bool InsertLifetime,
1658                                         Function *ForwardVarArgsTo) {
1659   assert(CB.getParent() && CB.getFunction() && "Instruction not in function!");
1660 
1661   // FIXME: we don't inline callbr yet.
1662   if (isa<CallBrInst>(CB))
1663     return InlineResult::failure("We don't inline callbr yet.");
1664 
1665   // If IFI has any state in it, zap it before we fill it in.
1666   IFI.reset();
1667 
1668   Function *CalledFunc = CB.getCalledFunction();
1669   if (!CalledFunc ||               // Can't inline external function or indirect
1670       CalledFunc->isDeclaration()) // call!
1671     return InlineResult::failure("external or indirect");
1672 
1673   // The inliner does not know how to inline through calls with operand bundles
1674   // in general ...
1675   if (CB.hasOperandBundles()) {
1676     for (int i = 0, e = CB.getNumOperandBundles(); i != e; ++i) {
1677       uint32_t Tag = CB.getOperandBundleAt(i).getTagID();
1678       // ... but it knows how to inline through "deopt" operand bundles ...
1679       if (Tag == LLVMContext::OB_deopt)
1680         continue;
1681       // ... and "funclet" operand bundles.
1682       if (Tag == LLVMContext::OB_funclet)
1683         continue;
1684 
1685       return InlineResult::failure("unsupported operand bundle");
1686     }
1687   }
1688 
1689   // If the call to the callee cannot throw, set the 'nounwind' flag on any
1690   // calls that we inline.
1691   bool MarkNoUnwind = CB.doesNotThrow();
1692 
1693   BasicBlock *OrigBB = CB.getParent();
1694   Function *Caller = OrigBB->getParent();
1695 
1696   // GC poses two hazards to inlining, which only occur when the callee has GC:
1697   //  1. If the caller has no GC, then the callee's GC must be propagated to the
1698   //     caller.
1699   //  2. If the caller has a differing GC, it is invalid to inline.
1700   if (CalledFunc->hasGC()) {
1701     if (!Caller->hasGC())
1702       Caller->setGC(CalledFunc->getGC());
1703     else if (CalledFunc->getGC() != Caller->getGC())
1704       return InlineResult::failure("incompatible GC");
1705   }
1706 
1707   // Get the personality function from the callee if it contains a landing pad.
1708   Constant *CalledPersonality =
1709       CalledFunc->hasPersonalityFn()
1710           ? CalledFunc->getPersonalityFn()->stripPointerCasts()
1711           : nullptr;
1712 
1713   // Find the personality function used by the landing pads of the caller. If it
1714   // exists, then check to see that it matches the personality function used in
1715   // the callee.
1716   Constant *CallerPersonality =
1717       Caller->hasPersonalityFn()
1718           ? Caller->getPersonalityFn()->stripPointerCasts()
1719           : nullptr;
1720   if (CalledPersonality) {
1721     if (!CallerPersonality)
1722       Caller->setPersonalityFn(CalledPersonality);
1723     // If the personality functions match, then we can perform the
1724     // inlining. Otherwise, we can't inline.
1725     // TODO: This isn't 100% true. Some personality functions are proper
1726     //       supersets of others and can be used in place of the other.
1727     else if (CalledPersonality != CallerPersonality)
1728       return InlineResult::failure("incompatible personality");
1729   }
1730 
1731   // We need to figure out which funclet the callsite was in so that we may
1732   // properly nest the callee.
1733   Instruction *CallSiteEHPad = nullptr;
1734   if (CallerPersonality) {
1735     EHPersonality Personality = classifyEHPersonality(CallerPersonality);
1736     if (isScopedEHPersonality(Personality)) {
1737       Optional<OperandBundleUse> ParentFunclet =
1738           CB.getOperandBundle(LLVMContext::OB_funclet);
1739       if (ParentFunclet)
1740         CallSiteEHPad = cast<FuncletPadInst>(ParentFunclet->Inputs.front());
1741 
1742       // OK, the inlining site is legal.  What about the target function?
1743 
1744       if (CallSiteEHPad) {
1745         if (Personality == EHPersonality::MSVC_CXX) {
1746           // The MSVC personality cannot tolerate catches getting inlined into
1747           // cleanup funclets.
1748           if (isa<CleanupPadInst>(CallSiteEHPad)) {
1749             // Ok, the call site is within a cleanuppad.  Let's check the callee
1750             // for catchpads.
1751             for (const BasicBlock &CalledBB : *CalledFunc) {
1752               if (isa<CatchSwitchInst>(CalledBB.getFirstNonPHI()))
1753                 return InlineResult::failure("catch in cleanup funclet");
1754             }
1755           }
1756         } else if (isAsynchronousEHPersonality(Personality)) {
1757           // SEH is even less tolerant, there may not be any sort of exceptional
1758           // funclet in the callee.
1759           for (const BasicBlock &CalledBB : *CalledFunc) {
1760             if (CalledBB.isEHPad())
1761               return InlineResult::failure("SEH in cleanup funclet");
1762           }
1763         }
1764       }
1765     }
1766   }
1767 
1768   // Determine if we are dealing with a call in an EHPad which does not unwind
1769   // to caller.
1770   bool EHPadForCallUnwindsLocally = false;
1771   if (CallSiteEHPad && isa<CallInst>(CB)) {
1772     UnwindDestMemoTy FuncletUnwindMap;
1773     Value *CallSiteUnwindDestToken =
1774         getUnwindDestToken(CallSiteEHPad, FuncletUnwindMap);
1775 
1776     EHPadForCallUnwindsLocally =
1777         CallSiteUnwindDestToken &&
1778         !isa<ConstantTokenNone>(CallSiteUnwindDestToken);
1779   }
1780 
1781   // Get an iterator to the last basic block in the function, which will have
1782   // the new function inlined after it.
1783   Function::iterator LastBlock = --Caller->end();
1784 
1785   // Make sure to capture all of the return instructions from the cloned
1786   // function.
1787   SmallVector<ReturnInst*, 8> Returns;
1788   ClonedCodeInfo InlinedFunctionInfo;
1789   Function::iterator FirstNewBlock;
1790 
1791   { // Scope to destroy VMap after cloning.
1792     ValueToValueMapTy VMap;
1793     // Keep a list of pair (dst, src) to emit byval initializations.
1794     SmallVector<std::pair<Value*, Value*>, 4> ByValInit;
1795 
1796     auto &DL = Caller->getParent()->getDataLayout();
1797 
1798     // Calculate the vector of arguments to pass into the function cloner, which
1799     // matches up the formal to the actual argument values.
1800     auto AI = CB.arg_begin();
1801     unsigned ArgNo = 0;
1802     for (Function::arg_iterator I = CalledFunc->arg_begin(),
1803          E = CalledFunc->arg_end(); I != E; ++I, ++AI, ++ArgNo) {
1804       Value *ActualArg = *AI;
1805 
1806       // When byval arguments actually inlined, we need to make the copy implied
1807       // by them explicit.  However, we don't do this if the callee is readonly
1808       // or readnone, because the copy would be unneeded: the callee doesn't
1809       // modify the struct.
1810       if (CB.isByValArgument(ArgNo)) {
1811         ActualArg = HandleByValArgument(ActualArg, &CB, CalledFunc, IFI,
1812                                         CalledFunc->getParamAlignment(ArgNo));
1813         if (ActualArg != *AI)
1814           ByValInit.push_back(std::make_pair(ActualArg, (Value*) *AI));
1815       }
1816 
1817       VMap[&*I] = ActualArg;
1818     }
1819 
1820     // TODO: Remove this when users have been updated to the assume bundles.
1821     // Add alignment assumptions if necessary. We do this before the inlined
1822     // instructions are actually cloned into the caller so that we can easily
1823     // check what will be known at the start of the inlined code.
1824     AddAlignmentAssumptions(CB, IFI);
1825 
1826     AssumptionCache *AC =
1827         IFI.GetAssumptionCache ? &(*IFI.GetAssumptionCache)(*Caller) : nullptr;
1828 
1829     /// Preserve all attributes on of the call and its parameters.
1830     salvageKnowledge(&CB, AC);
1831 
1832     // We want the inliner to prune the code as it copies.  We would LOVE to
1833     // have no dead or constant instructions leftover after inlining occurs
1834     // (which can happen, e.g., because an argument was constant), but we'll be
1835     // happy with whatever the cloner can do.
1836     CloneAndPruneFunctionInto(Caller, CalledFunc, VMap,
1837                               /*ModuleLevelChanges=*/false, Returns, ".i",
1838                               &InlinedFunctionInfo, &CB);
1839     // Remember the first block that is newly cloned over.
1840     FirstNewBlock = LastBlock; ++FirstNewBlock;
1841 
1842     if (IFI.CallerBFI != nullptr && IFI.CalleeBFI != nullptr)
1843       // Update the BFI of blocks cloned into the caller.
1844       updateCallerBFI(OrigBB, VMap, IFI.CallerBFI, IFI.CalleeBFI,
1845                       CalledFunc->front());
1846 
1847     updateCallProfile(CalledFunc, VMap, CalledFunc->getEntryCount(), &CB,
1848                       IFI.PSI, IFI.CallerBFI);
1849 
1850     // Inject byval arguments initialization.
1851     for (std::pair<Value*, Value*> &Init : ByValInit)
1852       HandleByValArgumentInit(Init.first, Init.second, Caller->getParent(),
1853                               &*FirstNewBlock, IFI);
1854 
1855     Optional<OperandBundleUse> ParentDeopt =
1856         CB.getOperandBundle(LLVMContext::OB_deopt);
1857     if (ParentDeopt) {
1858       SmallVector<OperandBundleDef, 2> OpDefs;
1859 
1860       for (auto &VH : InlinedFunctionInfo.OperandBundleCallSites) {
1861         CallBase *ICS = dyn_cast_or_null<CallBase>(VH);
1862         if (!ICS)
1863           continue; // instruction was DCE'd or RAUW'ed to undef
1864 
1865         OpDefs.clear();
1866 
1867         OpDefs.reserve(ICS->getNumOperandBundles());
1868 
1869         for (unsigned COBi = 0, COBe = ICS->getNumOperandBundles(); COBi < COBe;
1870              ++COBi) {
1871           auto ChildOB = ICS->getOperandBundleAt(COBi);
1872           if (ChildOB.getTagID() != LLVMContext::OB_deopt) {
1873             // If the inlined call has other operand bundles, let them be
1874             OpDefs.emplace_back(ChildOB);
1875             continue;
1876           }
1877 
1878           // It may be useful to separate this logic (of handling operand
1879           // bundles) out to a separate "policy" component if this gets crowded.
1880           // Prepend the parent's deoptimization continuation to the newly
1881           // inlined call's deoptimization continuation.
1882           std::vector<Value *> MergedDeoptArgs;
1883           MergedDeoptArgs.reserve(ParentDeopt->Inputs.size() +
1884                                   ChildOB.Inputs.size());
1885 
1886           MergedDeoptArgs.insert(MergedDeoptArgs.end(),
1887                                  ParentDeopt->Inputs.begin(),
1888                                  ParentDeopt->Inputs.end());
1889           MergedDeoptArgs.insert(MergedDeoptArgs.end(), ChildOB.Inputs.begin(),
1890                                  ChildOB.Inputs.end());
1891 
1892           OpDefs.emplace_back("deopt", std::move(MergedDeoptArgs));
1893         }
1894 
1895         Instruction *NewI = nullptr;
1896         if (isa<CallInst>(ICS))
1897           NewI = CallInst::Create(cast<CallInst>(ICS), OpDefs, ICS);
1898         else if (isa<CallBrInst>(ICS))
1899           NewI = CallBrInst::Create(cast<CallBrInst>(ICS), OpDefs, ICS);
1900         else
1901           NewI = InvokeInst::Create(cast<InvokeInst>(ICS), OpDefs, ICS);
1902 
1903         // Note: the RAUW does the appropriate fixup in VMap, so we need to do
1904         // this even if the call returns void.
1905         ICS->replaceAllUsesWith(NewI);
1906 
1907         VH = nullptr;
1908         ICS->eraseFromParent();
1909       }
1910     }
1911 
1912     // Update the callgraph if requested.
1913     if (IFI.CG)
1914       UpdateCallGraphAfterInlining(CB, FirstNewBlock, VMap, IFI);
1915 
1916     // For 'nodebug' functions, the associated DISubprogram is always null.
1917     // Conservatively avoid propagating the callsite debug location to
1918     // instructions inlined from a function whose DISubprogram is not null.
1919     fixupLineNumbers(Caller, FirstNewBlock, &CB,
1920                      CalledFunc->getSubprogram() != nullptr);
1921 
1922     // Clone existing noalias metadata if necessary.
1923     CloneAliasScopeMetadata(CB, VMap);
1924 
1925     // Add noalias metadata if necessary.
1926     AddAliasScopeMetadata(CB, VMap, DL, CalleeAAR);
1927 
1928     // Clone return attributes on the callsite into the calls within the inlined
1929     // function which feed into its return value.
1930     AddReturnAttributes(CB, VMap);
1931 
1932     // Propagate llvm.mem.parallel_loop_access if necessary.
1933     PropagateParallelLoopAccessMetadata(CB, VMap);
1934 
1935     // Register any cloned assumptions.
1936     if (IFI.GetAssumptionCache)
1937       for (BasicBlock &NewBlock :
1938            make_range(FirstNewBlock->getIterator(), Caller->end()))
1939         for (Instruction &I : NewBlock) {
1940           if (auto *II = dyn_cast<IntrinsicInst>(&I))
1941             if (II->getIntrinsicID() == Intrinsic::assume)
1942               (*IFI.GetAssumptionCache)(*Caller).registerAssumption(II);
1943         }
1944   }
1945 
1946   // If there are any alloca instructions in the block that used to be the entry
1947   // block for the callee, move them to the entry block of the caller.  First
1948   // calculate which instruction they should be inserted before.  We insert the
1949   // instructions at the end of the current alloca list.
1950   {
1951     BasicBlock::iterator InsertPoint = Caller->begin()->begin();
1952     for (BasicBlock::iterator I = FirstNewBlock->begin(),
1953          E = FirstNewBlock->end(); I != E; ) {
1954       AllocaInst *AI = dyn_cast<AllocaInst>(I++);
1955       if (!AI) continue;
1956 
1957       // If the alloca is now dead, remove it.  This often occurs due to code
1958       // specialization.
1959       if (AI->use_empty()) {
1960         AI->eraseFromParent();
1961         continue;
1962       }
1963 
1964       if (!allocaWouldBeStaticInEntry(AI))
1965         continue;
1966 
1967       // Keep track of the static allocas that we inline into the caller.
1968       IFI.StaticAllocas.push_back(AI);
1969 
1970       // Scan for the block of allocas that we can move over, and move them
1971       // all at once.
1972       while (isa<AllocaInst>(I) &&
1973              !cast<AllocaInst>(I)->use_empty() &&
1974              allocaWouldBeStaticInEntry(cast<AllocaInst>(I))) {
1975         IFI.StaticAllocas.push_back(cast<AllocaInst>(I));
1976         ++I;
1977       }
1978 
1979       // Transfer all of the allocas over in a block.  Using splice means
1980       // that the instructions aren't removed from the symbol table, then
1981       // reinserted.
1982       Caller->getEntryBlock().getInstList().splice(
1983           InsertPoint, FirstNewBlock->getInstList(), AI->getIterator(), I);
1984     }
1985   }
1986 
1987   SmallVector<Value*,4> VarArgsToForward;
1988   SmallVector<AttributeSet, 4> VarArgsAttrs;
1989   for (unsigned i = CalledFunc->getFunctionType()->getNumParams();
1990        i < CB.getNumArgOperands(); i++) {
1991     VarArgsToForward.push_back(CB.getArgOperand(i));
1992     VarArgsAttrs.push_back(CB.getAttributes().getParamAttributes(i));
1993   }
1994 
1995   bool InlinedMustTailCalls = false, InlinedDeoptimizeCalls = false;
1996   if (InlinedFunctionInfo.ContainsCalls) {
1997     CallInst::TailCallKind CallSiteTailKind = CallInst::TCK_None;
1998     if (CallInst *CI = dyn_cast<CallInst>(&CB))
1999       CallSiteTailKind = CI->getTailCallKind();
2000 
2001     // For inlining purposes, the "notail" marker is the same as no marker.
2002     if (CallSiteTailKind == CallInst::TCK_NoTail)
2003       CallSiteTailKind = CallInst::TCK_None;
2004 
2005     for (Function::iterator BB = FirstNewBlock, E = Caller->end(); BB != E;
2006          ++BB) {
2007       for (auto II = BB->begin(); II != BB->end();) {
2008         Instruction &I = *II++;
2009         CallInst *CI = dyn_cast<CallInst>(&I);
2010         if (!CI)
2011           continue;
2012 
2013         // Forward varargs from inlined call site to calls to the
2014         // ForwardVarArgsTo function, if requested, and to musttail calls.
2015         if (!VarArgsToForward.empty() &&
2016             ((ForwardVarArgsTo &&
2017               CI->getCalledFunction() == ForwardVarArgsTo) ||
2018              CI->isMustTailCall())) {
2019           // Collect attributes for non-vararg parameters.
2020           AttributeList Attrs = CI->getAttributes();
2021           SmallVector<AttributeSet, 8> ArgAttrs;
2022           if (!Attrs.isEmpty() || !VarArgsAttrs.empty()) {
2023             for (unsigned ArgNo = 0;
2024                  ArgNo < CI->getFunctionType()->getNumParams(); ++ArgNo)
2025               ArgAttrs.push_back(Attrs.getParamAttributes(ArgNo));
2026           }
2027 
2028           // Add VarArg attributes.
2029           ArgAttrs.append(VarArgsAttrs.begin(), VarArgsAttrs.end());
2030           Attrs = AttributeList::get(CI->getContext(), Attrs.getFnAttributes(),
2031                                      Attrs.getRetAttributes(), ArgAttrs);
2032           // Add VarArgs to existing parameters.
2033           SmallVector<Value *, 6> Params(CI->arg_operands());
2034           Params.append(VarArgsToForward.begin(), VarArgsToForward.end());
2035           CallInst *NewCI = CallInst::Create(
2036               CI->getFunctionType(), CI->getCalledOperand(), Params, "", CI);
2037           NewCI->setDebugLoc(CI->getDebugLoc());
2038           NewCI->setAttributes(Attrs);
2039           NewCI->setCallingConv(CI->getCallingConv());
2040           CI->replaceAllUsesWith(NewCI);
2041           CI->eraseFromParent();
2042           CI = NewCI;
2043         }
2044 
2045         if (Function *F = CI->getCalledFunction())
2046           InlinedDeoptimizeCalls |=
2047               F->getIntrinsicID() == Intrinsic::experimental_deoptimize;
2048 
2049         // We need to reduce the strength of any inlined tail calls.  For
2050         // musttail, we have to avoid introducing potential unbounded stack
2051         // growth.  For example, if functions 'f' and 'g' are mutually recursive
2052         // with musttail, we can inline 'g' into 'f' so long as we preserve
2053         // musttail on the cloned call to 'f'.  If either the inlined call site
2054         // or the cloned call site is *not* musttail, the program already has
2055         // one frame of stack growth, so it's safe to remove musttail.  Here is
2056         // a table of example transformations:
2057         //
2058         //    f -> musttail g -> musttail f  ==>  f -> musttail f
2059         //    f -> musttail g ->     tail f  ==>  f ->     tail f
2060         //    f ->          g -> musttail f  ==>  f ->          f
2061         //    f ->          g ->     tail f  ==>  f ->          f
2062         //
2063         // Inlined notail calls should remain notail calls.
2064         CallInst::TailCallKind ChildTCK = CI->getTailCallKind();
2065         if (ChildTCK != CallInst::TCK_NoTail)
2066           ChildTCK = std::min(CallSiteTailKind, ChildTCK);
2067         CI->setTailCallKind(ChildTCK);
2068         InlinedMustTailCalls |= CI->isMustTailCall();
2069 
2070         // Calls inlined through a 'nounwind' call site should be marked
2071         // 'nounwind'.
2072         if (MarkNoUnwind)
2073           CI->setDoesNotThrow();
2074       }
2075     }
2076   }
2077 
2078   // Leave lifetime markers for the static alloca's, scoping them to the
2079   // function we just inlined.
2080   if (InsertLifetime && !IFI.StaticAllocas.empty()) {
2081     IRBuilder<> builder(&FirstNewBlock->front());
2082     for (unsigned ai = 0, ae = IFI.StaticAllocas.size(); ai != ae; ++ai) {
2083       AllocaInst *AI = IFI.StaticAllocas[ai];
2084       // Don't mark swifterror allocas. They can't have bitcast uses.
2085       if (AI->isSwiftError())
2086         continue;
2087 
2088       // If the alloca is already scoped to something smaller than the whole
2089       // function then there's no need to add redundant, less accurate markers.
2090       if (hasLifetimeMarkers(AI))
2091         continue;
2092 
2093       // Try to determine the size of the allocation.
2094       ConstantInt *AllocaSize = nullptr;
2095       if (ConstantInt *AIArraySize =
2096           dyn_cast<ConstantInt>(AI->getArraySize())) {
2097         auto &DL = Caller->getParent()->getDataLayout();
2098         Type *AllocaType = AI->getAllocatedType();
2099         uint64_t AllocaTypeSize = DL.getTypeAllocSize(AllocaType);
2100         uint64_t AllocaArraySize = AIArraySize->getLimitedValue();
2101 
2102         // Don't add markers for zero-sized allocas.
2103         if (AllocaArraySize == 0)
2104           continue;
2105 
2106         // Check that array size doesn't saturate uint64_t and doesn't
2107         // overflow when it's multiplied by type size.
2108         if (AllocaArraySize != std::numeric_limits<uint64_t>::max() &&
2109             std::numeric_limits<uint64_t>::max() / AllocaArraySize >=
2110                 AllocaTypeSize) {
2111           AllocaSize = ConstantInt::get(Type::getInt64Ty(AI->getContext()),
2112                                         AllocaArraySize * AllocaTypeSize);
2113         }
2114       }
2115 
2116       builder.CreateLifetimeStart(AI, AllocaSize);
2117       for (ReturnInst *RI : Returns) {
2118         // Don't insert llvm.lifetime.end calls between a musttail or deoptimize
2119         // call and a return.  The return kills all local allocas.
2120         if (InlinedMustTailCalls &&
2121             RI->getParent()->getTerminatingMustTailCall())
2122           continue;
2123         if (InlinedDeoptimizeCalls &&
2124             RI->getParent()->getTerminatingDeoptimizeCall())
2125           continue;
2126         IRBuilder<>(RI).CreateLifetimeEnd(AI, AllocaSize);
2127       }
2128     }
2129   }
2130 
2131   // If the inlined code contained dynamic alloca instructions, wrap the inlined
2132   // code with llvm.stacksave/llvm.stackrestore intrinsics.
2133   if (InlinedFunctionInfo.ContainsDynamicAllocas) {
2134     Module *M = Caller->getParent();
2135     // Get the two intrinsics we care about.
2136     Function *StackSave = Intrinsic::getDeclaration(M, Intrinsic::stacksave);
2137     Function *StackRestore=Intrinsic::getDeclaration(M,Intrinsic::stackrestore);
2138 
2139     // Insert the llvm.stacksave.
2140     CallInst *SavedPtr = IRBuilder<>(&*FirstNewBlock, FirstNewBlock->begin())
2141                              .CreateCall(StackSave, {}, "savedstack");
2142 
2143     // Insert a call to llvm.stackrestore before any return instructions in the
2144     // inlined function.
2145     for (ReturnInst *RI : Returns) {
2146       // Don't insert llvm.stackrestore calls between a musttail or deoptimize
2147       // call and a return.  The return will restore the stack pointer.
2148       if (InlinedMustTailCalls && RI->getParent()->getTerminatingMustTailCall())
2149         continue;
2150       if (InlinedDeoptimizeCalls && RI->getParent()->getTerminatingDeoptimizeCall())
2151         continue;
2152       IRBuilder<>(RI).CreateCall(StackRestore, SavedPtr);
2153     }
2154   }
2155 
2156   // If we are inlining for an invoke instruction, we must make sure to rewrite
2157   // any call instructions into invoke instructions.  This is sensitive to which
2158   // funclet pads were top-level in the inlinee, so must be done before
2159   // rewriting the "parent pad" links.
2160   if (auto *II = dyn_cast<InvokeInst>(&CB)) {
2161     BasicBlock *UnwindDest = II->getUnwindDest();
2162     Instruction *FirstNonPHI = UnwindDest->getFirstNonPHI();
2163     if (isa<LandingPadInst>(FirstNonPHI)) {
2164       HandleInlinedLandingPad(II, &*FirstNewBlock, InlinedFunctionInfo);
2165     } else {
2166       HandleInlinedEHPad(II, &*FirstNewBlock, InlinedFunctionInfo);
2167     }
2168   }
2169 
2170   // Update the lexical scopes of the new funclets and callsites.
2171   // Anything that had 'none' as its parent is now nested inside the callsite's
2172   // EHPad.
2173 
2174   if (CallSiteEHPad) {
2175     for (Function::iterator BB = FirstNewBlock->getIterator(),
2176                             E = Caller->end();
2177          BB != E; ++BB) {
2178       // Add bundle operands to any top-level call sites.
2179       SmallVector<OperandBundleDef, 1> OpBundles;
2180       for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E;) {
2181         CallBase *I = dyn_cast<CallBase>(&*BBI++);
2182         if (!I)
2183           continue;
2184 
2185         // Skip call sites which are nounwind intrinsics.
2186         auto *CalledFn =
2187             dyn_cast<Function>(I->getCalledValue()->stripPointerCasts());
2188         if (CalledFn && CalledFn->isIntrinsic() && I->doesNotThrow())
2189           continue;
2190 
2191         // Skip call sites which already have a "funclet" bundle.
2192         if (I->getOperandBundle(LLVMContext::OB_funclet))
2193           continue;
2194 
2195         I->getOperandBundlesAsDefs(OpBundles);
2196         OpBundles.emplace_back("funclet", CallSiteEHPad);
2197 
2198         Instruction *NewInst;
2199         if (auto *CallI = dyn_cast<CallInst>(I))
2200           NewInst = CallInst::Create(CallI, OpBundles, CallI);
2201         else if (auto *CallBrI = dyn_cast<CallBrInst>(I))
2202           NewInst = CallBrInst::Create(CallBrI, OpBundles, CallBrI);
2203         else
2204           NewInst = InvokeInst::Create(cast<InvokeInst>(I), OpBundles, I);
2205         NewInst->takeName(I);
2206         I->replaceAllUsesWith(NewInst);
2207         I->eraseFromParent();
2208 
2209         OpBundles.clear();
2210       }
2211 
2212       // It is problematic if the inlinee has a cleanupret which unwinds to
2213       // caller and we inline it into a call site which doesn't unwind but into
2214       // an EH pad that does.  Such an edge must be dynamically unreachable.
2215       // As such, we replace the cleanupret with unreachable.
2216       if (auto *CleanupRet = dyn_cast<CleanupReturnInst>(BB->getTerminator()))
2217         if (CleanupRet->unwindsToCaller() && EHPadForCallUnwindsLocally)
2218           changeToUnreachable(CleanupRet, /*UseLLVMTrap=*/false);
2219 
2220       Instruction *I = BB->getFirstNonPHI();
2221       if (!I->isEHPad())
2222         continue;
2223 
2224       if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(I)) {
2225         if (isa<ConstantTokenNone>(CatchSwitch->getParentPad()))
2226           CatchSwitch->setParentPad(CallSiteEHPad);
2227       } else {
2228         auto *FPI = cast<FuncletPadInst>(I);
2229         if (isa<ConstantTokenNone>(FPI->getParentPad()))
2230           FPI->setParentPad(CallSiteEHPad);
2231       }
2232     }
2233   }
2234 
2235   if (InlinedDeoptimizeCalls) {
2236     // We need to at least remove the deoptimizing returns from the Return set,
2237     // so that the control flow from those returns does not get merged into the
2238     // caller (but terminate it instead).  If the caller's return type does not
2239     // match the callee's return type, we also need to change the return type of
2240     // the intrinsic.
2241     if (Caller->getReturnType() == CB.getType()) {
2242       auto NewEnd = llvm::remove_if(Returns, [](ReturnInst *RI) {
2243         return RI->getParent()->getTerminatingDeoptimizeCall() != nullptr;
2244       });
2245       Returns.erase(NewEnd, Returns.end());
2246     } else {
2247       SmallVector<ReturnInst *, 8> NormalReturns;
2248       Function *NewDeoptIntrinsic = Intrinsic::getDeclaration(
2249           Caller->getParent(), Intrinsic::experimental_deoptimize,
2250           {Caller->getReturnType()});
2251 
2252       for (ReturnInst *RI : Returns) {
2253         CallInst *DeoptCall = RI->getParent()->getTerminatingDeoptimizeCall();
2254         if (!DeoptCall) {
2255           NormalReturns.push_back(RI);
2256           continue;
2257         }
2258 
2259         // The calling convention on the deoptimize call itself may be bogus,
2260         // since the code we're inlining may have undefined behavior (and may
2261         // never actually execute at runtime); but all
2262         // @llvm.experimental.deoptimize declarations have to have the same
2263         // calling convention in a well-formed module.
2264         auto CallingConv = DeoptCall->getCalledFunction()->getCallingConv();
2265         NewDeoptIntrinsic->setCallingConv(CallingConv);
2266         auto *CurBB = RI->getParent();
2267         RI->eraseFromParent();
2268 
2269         SmallVector<Value *, 4> CallArgs(DeoptCall->arg_begin(),
2270                                          DeoptCall->arg_end());
2271 
2272         SmallVector<OperandBundleDef, 1> OpBundles;
2273         DeoptCall->getOperandBundlesAsDefs(OpBundles);
2274         DeoptCall->eraseFromParent();
2275         assert(!OpBundles.empty() &&
2276                "Expected at least the deopt operand bundle");
2277 
2278         IRBuilder<> Builder(CurBB);
2279         CallInst *NewDeoptCall =
2280             Builder.CreateCall(NewDeoptIntrinsic, CallArgs, OpBundles);
2281         NewDeoptCall->setCallingConv(CallingConv);
2282         if (NewDeoptCall->getType()->isVoidTy())
2283           Builder.CreateRetVoid();
2284         else
2285           Builder.CreateRet(NewDeoptCall);
2286       }
2287 
2288       // Leave behind the normal returns so we can merge control flow.
2289       std::swap(Returns, NormalReturns);
2290     }
2291   }
2292 
2293   // Handle any inlined musttail call sites.  In order for a new call site to be
2294   // musttail, the source of the clone and the inlined call site must have been
2295   // musttail.  Therefore it's safe to return without merging control into the
2296   // phi below.
2297   if (InlinedMustTailCalls) {
2298     // Check if we need to bitcast the result of any musttail calls.
2299     Type *NewRetTy = Caller->getReturnType();
2300     bool NeedBitCast = !CB.use_empty() && CB.getType() != NewRetTy;
2301 
2302     // Handle the returns preceded by musttail calls separately.
2303     SmallVector<ReturnInst *, 8> NormalReturns;
2304     for (ReturnInst *RI : Returns) {
2305       CallInst *ReturnedMustTail =
2306           RI->getParent()->getTerminatingMustTailCall();
2307       if (!ReturnedMustTail) {
2308         NormalReturns.push_back(RI);
2309         continue;
2310       }
2311       if (!NeedBitCast)
2312         continue;
2313 
2314       // Delete the old return and any preceding bitcast.
2315       BasicBlock *CurBB = RI->getParent();
2316       auto *OldCast = dyn_cast_or_null<BitCastInst>(RI->getReturnValue());
2317       RI->eraseFromParent();
2318       if (OldCast)
2319         OldCast->eraseFromParent();
2320 
2321       // Insert a new bitcast and return with the right type.
2322       IRBuilder<> Builder(CurBB);
2323       Builder.CreateRet(Builder.CreateBitCast(ReturnedMustTail, NewRetTy));
2324     }
2325 
2326     // Leave behind the normal returns so we can merge control flow.
2327     std::swap(Returns, NormalReturns);
2328   }
2329 
2330   // Now that all of the transforms on the inlined code have taken place but
2331   // before we splice the inlined code into the CFG and lose track of which
2332   // blocks were actually inlined, collect the call sites. We only do this if
2333   // call graph updates weren't requested, as those provide value handle based
2334   // tracking of inlined call sites instead.
2335   if (InlinedFunctionInfo.ContainsCalls && !IFI.CG) {
2336     // Otherwise just collect the raw call sites that were inlined.
2337     for (BasicBlock &NewBB :
2338          make_range(FirstNewBlock->getIterator(), Caller->end()))
2339       for (Instruction &I : NewBB)
2340         if (auto *CB = dyn_cast<CallBase>(&I))
2341           IFI.InlinedCallSites.push_back(CB);
2342   }
2343 
2344   // If we cloned in _exactly one_ basic block, and if that block ends in a
2345   // return instruction, we splice the body of the inlined callee directly into
2346   // the calling basic block.
2347   if (Returns.size() == 1 && std::distance(FirstNewBlock, Caller->end()) == 1) {
2348     // Move all of the instructions right before the call.
2349     OrigBB->getInstList().splice(CB.getIterator(), FirstNewBlock->getInstList(),
2350                                  FirstNewBlock->begin(), FirstNewBlock->end());
2351     // Remove the cloned basic block.
2352     Caller->getBasicBlockList().pop_back();
2353 
2354     // If the call site was an invoke instruction, add a branch to the normal
2355     // destination.
2356     if (InvokeInst *II = dyn_cast<InvokeInst>(&CB)) {
2357       BranchInst *NewBr = BranchInst::Create(II->getNormalDest(), &CB);
2358       NewBr->setDebugLoc(Returns[0]->getDebugLoc());
2359     }
2360 
2361     // If the return instruction returned a value, replace uses of the call with
2362     // uses of the returned value.
2363     if (!CB.use_empty()) {
2364       ReturnInst *R = Returns[0];
2365       if (&CB == R->getReturnValue())
2366         CB.replaceAllUsesWith(UndefValue::get(CB.getType()));
2367       else
2368         CB.replaceAllUsesWith(R->getReturnValue());
2369     }
2370     // Since we are now done with the Call/Invoke, we can delete it.
2371     CB.eraseFromParent();
2372 
2373     // Since we are now done with the return instruction, delete it also.
2374     Returns[0]->eraseFromParent();
2375 
2376     // We are now done with the inlining.
2377     return InlineResult::success();
2378   }
2379 
2380   // Otherwise, we have the normal case, of more than one block to inline or
2381   // multiple return sites.
2382 
2383   // We want to clone the entire callee function into the hole between the
2384   // "starter" and "ender" blocks.  How we accomplish this depends on whether
2385   // this is an invoke instruction or a call instruction.
2386   BasicBlock *AfterCallBB;
2387   BranchInst *CreatedBranchToNormalDest = nullptr;
2388   if (InvokeInst *II = dyn_cast<InvokeInst>(&CB)) {
2389 
2390     // Add an unconditional branch to make this look like the CallInst case...
2391     CreatedBranchToNormalDest = BranchInst::Create(II->getNormalDest(), &CB);
2392 
2393     // Split the basic block.  This guarantees that no PHI nodes will have to be
2394     // updated due to new incoming edges, and make the invoke case more
2395     // symmetric to the call case.
2396     AfterCallBB =
2397         OrigBB->splitBasicBlock(CreatedBranchToNormalDest->getIterator(),
2398                                 CalledFunc->getName() + ".exit");
2399 
2400   } else { // It's a call
2401     // If this is a call instruction, we need to split the basic block that
2402     // the call lives in.
2403     //
2404     AfterCallBB = OrigBB->splitBasicBlock(CB.getIterator(),
2405                                           CalledFunc->getName() + ".exit");
2406   }
2407 
2408   if (IFI.CallerBFI) {
2409     // Copy original BB's block frequency to AfterCallBB
2410     IFI.CallerBFI->setBlockFreq(
2411         AfterCallBB, IFI.CallerBFI->getBlockFreq(OrigBB).getFrequency());
2412   }
2413 
2414   // Change the branch that used to go to AfterCallBB to branch to the first
2415   // basic block of the inlined function.
2416   //
2417   Instruction *Br = OrigBB->getTerminator();
2418   assert(Br && Br->getOpcode() == Instruction::Br &&
2419          "splitBasicBlock broken!");
2420   Br->setOperand(0, &*FirstNewBlock);
2421 
2422   // Now that the function is correct, make it a little bit nicer.  In
2423   // particular, move the basic blocks inserted from the end of the function
2424   // into the space made by splitting the source basic block.
2425   Caller->getBasicBlockList().splice(AfterCallBB->getIterator(),
2426                                      Caller->getBasicBlockList(), FirstNewBlock,
2427                                      Caller->end());
2428 
2429   // Handle all of the return instructions that we just cloned in, and eliminate
2430   // any users of the original call/invoke instruction.
2431   Type *RTy = CalledFunc->getReturnType();
2432 
2433   PHINode *PHI = nullptr;
2434   if (Returns.size() > 1) {
2435     // The PHI node should go at the front of the new basic block to merge all
2436     // possible incoming values.
2437     if (!CB.use_empty()) {
2438       PHI = PHINode::Create(RTy, Returns.size(), CB.getName(),
2439                             &AfterCallBB->front());
2440       // Anything that used the result of the function call should now use the
2441       // PHI node as their operand.
2442       CB.replaceAllUsesWith(PHI);
2443     }
2444 
2445     // Loop over all of the return instructions adding entries to the PHI node
2446     // as appropriate.
2447     if (PHI) {
2448       for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
2449         ReturnInst *RI = Returns[i];
2450         assert(RI->getReturnValue()->getType() == PHI->getType() &&
2451                "Ret value not consistent in function!");
2452         PHI->addIncoming(RI->getReturnValue(), RI->getParent());
2453       }
2454     }
2455 
2456     // Add a branch to the merge points and remove return instructions.
2457     DebugLoc Loc;
2458     for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
2459       ReturnInst *RI = Returns[i];
2460       BranchInst* BI = BranchInst::Create(AfterCallBB, RI);
2461       Loc = RI->getDebugLoc();
2462       BI->setDebugLoc(Loc);
2463       RI->eraseFromParent();
2464     }
2465     // We need to set the debug location to *somewhere* inside the
2466     // inlined function. The line number may be nonsensical, but the
2467     // instruction will at least be associated with the right
2468     // function.
2469     if (CreatedBranchToNormalDest)
2470       CreatedBranchToNormalDest->setDebugLoc(Loc);
2471   } else if (!Returns.empty()) {
2472     // Otherwise, if there is exactly one return value, just replace anything
2473     // using the return value of the call with the computed value.
2474     if (!CB.use_empty()) {
2475       if (&CB == Returns[0]->getReturnValue())
2476         CB.replaceAllUsesWith(UndefValue::get(CB.getType()));
2477       else
2478         CB.replaceAllUsesWith(Returns[0]->getReturnValue());
2479     }
2480 
2481     // Update PHI nodes that use the ReturnBB to use the AfterCallBB.
2482     BasicBlock *ReturnBB = Returns[0]->getParent();
2483     ReturnBB->replaceAllUsesWith(AfterCallBB);
2484 
2485     // Splice the code from the return block into the block that it will return
2486     // to, which contains the code that was after the call.
2487     AfterCallBB->getInstList().splice(AfterCallBB->begin(),
2488                                       ReturnBB->getInstList());
2489 
2490     if (CreatedBranchToNormalDest)
2491       CreatedBranchToNormalDest->setDebugLoc(Returns[0]->getDebugLoc());
2492 
2493     // Delete the return instruction now and empty ReturnBB now.
2494     Returns[0]->eraseFromParent();
2495     ReturnBB->eraseFromParent();
2496   } else if (!CB.use_empty()) {
2497     // No returns, but something is using the return value of the call.  Just
2498     // nuke the result.
2499     CB.replaceAllUsesWith(UndefValue::get(CB.getType()));
2500   }
2501 
2502   // Since we are now done with the Call/Invoke, we can delete it.
2503   CB.eraseFromParent();
2504 
2505   // If we inlined any musttail calls and the original return is now
2506   // unreachable, delete it.  It can only contain a bitcast and ret.
2507   if (InlinedMustTailCalls && pred_begin(AfterCallBB) == pred_end(AfterCallBB))
2508     AfterCallBB->eraseFromParent();
2509 
2510   // We should always be able to fold the entry block of the function into the
2511   // single predecessor of the block...
2512   assert(cast<BranchInst>(Br)->isUnconditional() && "splitBasicBlock broken!");
2513   BasicBlock *CalleeEntry = cast<BranchInst>(Br)->getSuccessor(0);
2514 
2515   // Splice the code entry block into calling block, right before the
2516   // unconditional branch.
2517   CalleeEntry->replaceAllUsesWith(OrigBB);  // Update PHI nodes
2518   OrigBB->getInstList().splice(Br->getIterator(), CalleeEntry->getInstList());
2519 
2520   // Remove the unconditional branch.
2521   OrigBB->getInstList().erase(Br);
2522 
2523   // Now we can remove the CalleeEntry block, which is now empty.
2524   Caller->getBasicBlockList().erase(CalleeEntry);
2525 
2526   // If we inserted a phi node, check to see if it has a single value (e.g. all
2527   // the entries are the same or undef).  If so, remove the PHI so it doesn't
2528   // block other optimizations.
2529   if (PHI) {
2530     AssumptionCache *AC =
2531         IFI.GetAssumptionCache ? &(*IFI.GetAssumptionCache)(*Caller) : nullptr;
2532     auto &DL = Caller->getParent()->getDataLayout();
2533     if (Value *V = SimplifyInstruction(PHI, {DL, nullptr, nullptr, AC})) {
2534       PHI->replaceAllUsesWith(V);
2535       PHI->eraseFromParent();
2536     }
2537   }
2538 
2539   return InlineResult::success();
2540 }
2541