xref: /src/contrib/llvm-project/llvm/lib/Transforms/Utils/InlineFunction.cpp (revision d686ce931cab72612a9e1ada9fe99d65e11a32a3)
1009b1c42SEd Schouten //===- InlineFunction.cpp - Code to perform function inlining -------------===//
2009b1c42SEd Schouten //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6009b1c42SEd Schouten //
7009b1c42SEd Schouten //===----------------------------------------------------------------------===//
8009b1c42SEd Schouten //
9009b1c42SEd Schouten // This file implements inlining of a function into a call site, resolving
10009b1c42SEd Schouten // parameters and the return value as appropriate.
11009b1c42SEd Schouten //
12009b1c42SEd Schouten //===----------------------------------------------------------------------===//
13009b1c42SEd Schouten 
14044eb2f6SDimitry Andric #include "llvm/ADT/DenseMap.h"
15044eb2f6SDimitry Andric #include "llvm/ADT/STLExtras.h"
16dd58ef01SDimitry Andric #include "llvm/ADT/SetVector.h"
17b915e9e0SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
18009b1c42SEd Schouten #include "llvm/ADT/SmallVector.h"
19009b1c42SEd Schouten #include "llvm/ADT/StringExtras.h"
20044eb2f6SDimitry Andric #include "llvm/ADT/iterator_range.h"
2167c32a98SDimitry Andric #include "llvm/Analysis/AliasAnalysis.h"
2267c32a98SDimitry Andric #include "llvm/Analysis/AssumptionCache.h"
2371d5a254SDimitry Andric #include "llvm/Analysis/BlockFrequencyInfo.h"
2458b69754SDimitry Andric #include "llvm/Analysis/CallGraph.h"
2567c32a98SDimitry Andric #include "llvm/Analysis/CaptureTracking.h"
26ac9a064cSDimitry Andric #include "llvm/Analysis/IndirectCallVisitor.h"
2758b69754SDimitry Andric #include "llvm/Analysis/InstructionSimplify.h"
28e3b55780SDimitry Andric #include "llvm/Analysis/MemoryProfileInfo.h"
29344a3780SDimitry Andric #include "llvm/Analysis/ObjCARCAnalysisUtils.h"
30344a3780SDimitry Andric #include "llvm/Analysis/ObjCARCUtil.h"
3171d5a254SDimitry Andric #include "llvm/Analysis/ProfileSummaryInfo.h"
3267c32a98SDimitry Andric #include "llvm/Analysis/ValueTracking.h"
33d8e91e46SDimitry Andric #include "llvm/Analysis/VectorUtils.h"
34044eb2f6SDimitry Andric #include "llvm/IR/Argument.h"
35ac9a064cSDimitry Andric #include "llvm/IR/AttributeMask.h"
36044eb2f6SDimitry Andric #include "llvm/IR/BasicBlock.h"
375ca98fd9SDimitry Andric #include "llvm/IR/CFG.h"
38044eb2f6SDimitry Andric #include "llvm/IR/Constant.h"
39ac9a064cSDimitry Andric #include "llvm/IR/ConstantRange.h"
404a16efa3SDimitry Andric #include "llvm/IR/Constants.h"
414a16efa3SDimitry Andric #include "llvm/IR/DataLayout.h"
42ecbca9f5SDimitry Andric #include "llvm/IR/DebugInfo.h"
43044eb2f6SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
44044eb2f6SDimitry Andric #include "llvm/IR/DebugLoc.h"
454a16efa3SDimitry Andric #include "llvm/IR/DerivedTypes.h"
4667c32a98SDimitry Andric #include "llvm/IR/Dominators.h"
477fa27ce4SDimitry Andric #include "llvm/IR/EHPersonalities.h"
48044eb2f6SDimitry Andric #include "llvm/IR/Function.h"
494a16efa3SDimitry Andric #include "llvm/IR/IRBuilder.h"
50344a3780SDimitry Andric #include "llvm/IR/InlineAsm.h"
51044eb2f6SDimitry Andric #include "llvm/IR/InstrTypes.h"
52044eb2f6SDimitry Andric #include "llvm/IR/Instruction.h"
534a16efa3SDimitry Andric #include "llvm/IR/Instructions.h"
544a16efa3SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
554a16efa3SDimitry Andric #include "llvm/IR/Intrinsics.h"
56044eb2f6SDimitry Andric #include "llvm/IR/LLVMContext.h"
5767c32a98SDimitry Andric #include "llvm/IR/MDBuilder.h"
58044eb2f6SDimitry Andric #include "llvm/IR/Metadata.h"
594a16efa3SDimitry Andric #include "llvm/IR/Module.h"
60ac9a064cSDimitry Andric #include "llvm/IR/ProfDataUtils.h"
61044eb2f6SDimitry Andric #include "llvm/IR/Type.h"
62044eb2f6SDimitry Andric #include "llvm/IR/User.h"
63044eb2f6SDimitry Andric #include "llvm/IR/Value.h"
64044eb2f6SDimitry Andric #include "llvm/Support/Casting.h"
6567c32a98SDimitry Andric #include "llvm/Support/CommandLine.h"
66044eb2f6SDimitry Andric #include "llvm/Support/ErrorHandling.h"
67cfca06d7SDimitry Andric #include "llvm/Transforms/Utils/AssumeBundleBuilder.h"
687ab83427SDimitry Andric #include "llvm/Transforms/Utils/Cloning.h"
69344a3780SDimitry Andric #include "llvm/Transforms/Utils/Local.h"
70044eb2f6SDimitry Andric #include "llvm/Transforms/Utils/ValueMapper.h"
7167c32a98SDimitry Andric #include <algorithm>
72044eb2f6SDimitry Andric #include <cassert>
73044eb2f6SDimitry Andric #include <cstdint>
74044eb2f6SDimitry Andric #include <iterator>
75044eb2f6SDimitry Andric #include <limits>
76e3b55780SDimitry Andric #include <optional>
77044eb2f6SDimitry Andric #include <string>
78044eb2f6SDimitry Andric #include <utility>
79044eb2f6SDimitry Andric #include <vector>
80dd58ef01SDimitry Andric 
81e3b55780SDimitry Andric #define DEBUG_TYPE "inline-function"
82e3b55780SDimitry Andric 
83009b1c42SEd Schouten using namespace llvm;
84e3b55780SDimitry Andric using namespace llvm::memprof;
85eb11fae6SDimitry Andric using ProfileCount = Function::ProfileCount;
86009b1c42SEd Schouten 
8767c32a98SDimitry Andric static cl::opt<bool>
8867c32a98SDimitry Andric EnableNoAliasConversion("enable-noalias-to-md-conversion", cl::init(true),
8967c32a98SDimitry Andric   cl::Hidden,
9067c32a98SDimitry Andric   cl::desc("Convert noalias attributes to metadata during inlining."));
9167c32a98SDimitry Andric 
92b60736ecSDimitry Andric static cl::opt<bool>
93b60736ecSDimitry Andric     UseNoAliasIntrinsic("use-noalias-intrinsic-during-inlining", cl::Hidden,
94145449b1SDimitry Andric                         cl::init(true),
95b60736ecSDimitry Andric                         cl::desc("Use the llvm.experimental.noalias.scope.decl "
96b60736ecSDimitry Andric                                  "intrinsic during inlining."));
97b60736ecSDimitry Andric 
98cfca06d7SDimitry Andric // Disabled by default, because the added alignment assumptions may increase
99cfca06d7SDimitry Andric // compile-time and block optimizations. This option is not suitable for use
100cfca06d7SDimitry Andric // with frontends that emit comprehensive parameter alignment annotations.
10167c32a98SDimitry Andric static cl::opt<bool>
10267c32a98SDimitry Andric PreserveAlignmentAssumptions("preserve-alignment-assumptions-during-inlining",
103cfca06d7SDimitry Andric   cl::init(false), cl::Hidden,
10467c32a98SDimitry Andric   cl::desc("Convert align attributes to assumptions during inlining."));
10567c32a98SDimitry Andric 
106cfca06d7SDimitry Andric static cl::opt<unsigned> InlinerAttributeWindow(
107cfca06d7SDimitry Andric     "max-inst-checked-for-throw-during-inlining", cl::Hidden,
108cfca06d7SDimitry Andric     cl::desc("the maximum number of instructions analyzed for may throw during "
109cfca06d7SDimitry Andric              "attribute inference in inlined body"),
110cfca06d7SDimitry Andric     cl::init(4));
11156fe8f14SDimitry Andric 
11256fe8f14SDimitry Andric namespace {
113044eb2f6SDimitry Andric 
114dd58ef01SDimitry Andric   /// A class for recording information about inlining a landing pad.
115dd58ef01SDimitry Andric   class LandingPadInliningInfo {
116044eb2f6SDimitry Andric     /// Destination of the invoke's unwind.
117044eb2f6SDimitry Andric     BasicBlock *OuterResumeDest;
118044eb2f6SDimitry Andric 
119044eb2f6SDimitry Andric     /// Destination for the callee's resume.
120044eb2f6SDimitry Andric     BasicBlock *InnerResumeDest = nullptr;
121044eb2f6SDimitry Andric 
122044eb2f6SDimitry Andric     /// LandingPadInst associated with the invoke.
123044eb2f6SDimitry Andric     LandingPadInst *CallerLPad = nullptr;
124044eb2f6SDimitry Andric 
125044eb2f6SDimitry Andric     /// PHI for EH values from landingpad insts.
126044eb2f6SDimitry Andric     PHINode *InnerEHValuesPHI = nullptr;
127044eb2f6SDimitry Andric 
12863faed5bSDimitry Andric     SmallVector<Value*, 8> UnwindDestPHIValues;
12956fe8f14SDimitry Andric 
13030815c53SDimitry Andric   public:
LandingPadInliningInfo(InvokeInst * II)131dd58ef01SDimitry Andric     LandingPadInliningInfo(InvokeInst *II)
132044eb2f6SDimitry Andric         : OuterResumeDest(II->getUnwindDest()) {
13330815c53SDimitry Andric       // If there are PHI nodes in the unwind destination block, we need to keep
13430815c53SDimitry Andric       // track of which values came into them from the invoke before removing
13530815c53SDimitry Andric       // the edge from this block.
136044eb2f6SDimitry Andric       BasicBlock *InvokeBB = II->getParent();
13763faed5bSDimitry Andric       BasicBlock::iterator I = OuterResumeDest->begin();
13830815c53SDimitry Andric       for (; isa<PHINode>(I); ++I) {
13956fe8f14SDimitry Andric         // Save the value to use for this edge.
14030815c53SDimitry Andric         PHINode *PHI = cast<PHINode>(I);
14130815c53SDimitry Andric         UnwindDestPHIValues.push_back(PHI->getIncomingValueForBlock(InvokeBB));
14230815c53SDimitry Andric       }
14330815c53SDimitry Andric 
14463faed5bSDimitry Andric       CallerLPad = cast<LandingPadInst>(I);
14556fe8f14SDimitry Andric     }
14656fe8f14SDimitry Andric 
1475a5ac124SDimitry Andric     /// The outer unwind destination is the target of
14863faed5bSDimitry Andric     /// unwind edges introduced for calls within the inlined function.
getOuterResumeDest() const14963faed5bSDimitry Andric     BasicBlock *getOuterResumeDest() const {
15063faed5bSDimitry Andric       return OuterResumeDest;
15156fe8f14SDimitry Andric     }
15256fe8f14SDimitry Andric 
15363faed5bSDimitry Andric     BasicBlock *getInnerResumeDest();
15430815c53SDimitry Andric 
getLandingPadInst() const15530815c53SDimitry Andric     LandingPadInst *getLandingPadInst() const { return CallerLPad; }
15630815c53SDimitry Andric 
1575a5ac124SDimitry Andric     /// Forward the 'resume' instruction to the caller's landing pad block.
1585a5ac124SDimitry Andric     /// When the landing pad block has only one predecessor, this is
15930815c53SDimitry Andric     /// a simple branch. When there is more than one predecessor, we need to
16030815c53SDimitry Andric     /// split the landing pad block after the landingpad instruction and jump
16130815c53SDimitry Andric     /// to there.
1624a16efa3SDimitry Andric     void forwardResume(ResumeInst *RI,
16367c32a98SDimitry Andric                        SmallPtrSetImpl<LandingPadInst*> &InlinedLPads);
16430815c53SDimitry Andric 
1655a5ac124SDimitry Andric     /// Add incoming-PHI values to the unwind destination block for the given
1665a5ac124SDimitry Andric     /// basic block, using the values for the original invoke's source block.
addIncomingPHIValuesFor(BasicBlock * BB) const16756fe8f14SDimitry Andric     void addIncomingPHIValuesFor(BasicBlock *BB) const {
16863faed5bSDimitry Andric       addIncomingPHIValuesForInto(BB, OuterResumeDest);
16956fe8f14SDimitry Andric     }
17056fe8f14SDimitry Andric 
addIncomingPHIValuesForInto(BasicBlock * src,BasicBlock * dest) const17156fe8f14SDimitry Andric     void addIncomingPHIValuesForInto(BasicBlock *src, BasicBlock *dest) const {
17256fe8f14SDimitry Andric       BasicBlock::iterator I = dest->begin();
17356fe8f14SDimitry Andric       for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) {
17456fe8f14SDimitry Andric         PHINode *phi = cast<PHINode>(I);
17556fe8f14SDimitry Andric         phi->addIncoming(UnwindDestPHIValues[i], src);
17656fe8f14SDimitry Andric       }
17756fe8f14SDimitry Andric     }
17856fe8f14SDimitry Andric   };
179044eb2f6SDimitry Andric 
180044eb2f6SDimitry Andric } // end anonymous namespace
18156fe8f14SDimitry Andric 
1825a5ac124SDimitry Andric /// Get or create a target for the branch from ResumeInsts.
getInnerResumeDest()183dd58ef01SDimitry Andric BasicBlock *LandingPadInliningInfo::getInnerResumeDest() {
18430815c53SDimitry Andric   if (InnerResumeDest) return InnerResumeDest;
18530815c53SDimitry Andric 
18630815c53SDimitry Andric   // Split the landing pad.
187dd58ef01SDimitry Andric   BasicBlock::iterator SplitPoint = ++CallerLPad->getIterator();
18830815c53SDimitry Andric   InnerResumeDest =
18930815c53SDimitry Andric     OuterResumeDest->splitBasicBlock(SplitPoint,
19030815c53SDimitry Andric                                      OuterResumeDest->getName() + ".body");
19130815c53SDimitry Andric 
19230815c53SDimitry Andric   // The number of incoming edges we expect to the inner landing pad.
19330815c53SDimitry Andric   const unsigned PHICapacity = 2;
19430815c53SDimitry Andric 
19530815c53SDimitry Andric   // Create corresponding new PHIs for all the PHIs in the outer landing pad.
196b1c73532SDimitry Andric   BasicBlock::iterator InsertPoint = InnerResumeDest->begin();
19730815c53SDimitry Andric   BasicBlock::iterator I = OuterResumeDest->begin();
19830815c53SDimitry Andric   for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) {
19930815c53SDimitry Andric     PHINode *OuterPHI = cast<PHINode>(I);
20030815c53SDimitry Andric     PHINode *InnerPHI = PHINode::Create(OuterPHI->getType(), PHICapacity,
201b1c73532SDimitry Andric                                         OuterPHI->getName() + ".lpad-body");
202b1c73532SDimitry Andric     InnerPHI->insertBefore(InsertPoint);
20330815c53SDimitry Andric     OuterPHI->replaceAllUsesWith(InnerPHI);
20430815c53SDimitry Andric     InnerPHI->addIncoming(OuterPHI, OuterResumeDest);
20530815c53SDimitry Andric   }
20630815c53SDimitry Andric 
20730815c53SDimitry Andric   // Create a PHI for the exception values.
208b1c73532SDimitry Andric   InnerEHValuesPHI =
209b1c73532SDimitry Andric       PHINode::Create(CallerLPad->getType(), PHICapacity, "eh.lpad-body");
210b1c73532SDimitry Andric   InnerEHValuesPHI->insertBefore(InsertPoint);
21130815c53SDimitry Andric   CallerLPad->replaceAllUsesWith(InnerEHValuesPHI);
21230815c53SDimitry Andric   InnerEHValuesPHI->addIncoming(CallerLPad, OuterResumeDest);
21330815c53SDimitry Andric 
21430815c53SDimitry Andric   // All done.
21530815c53SDimitry Andric   return InnerResumeDest;
21630815c53SDimitry Andric }
21730815c53SDimitry Andric 
2185a5ac124SDimitry Andric /// Forward the 'resume' instruction to the caller's landing pad block.
2195a5ac124SDimitry Andric /// When the landing pad block has only one predecessor, this is a simple
22030815c53SDimitry Andric /// branch. When there is more than one predecessor, we need to split the
22130815c53SDimitry Andric /// landing pad block after the landingpad instruction and jump to there.
forwardResume(ResumeInst * RI,SmallPtrSetImpl<LandingPadInst * > & InlinedLPads)222dd58ef01SDimitry Andric void LandingPadInliningInfo::forwardResume(
223dd58ef01SDimitry Andric     ResumeInst *RI, SmallPtrSetImpl<LandingPadInst *> &InlinedLPads) {
22463faed5bSDimitry Andric   BasicBlock *Dest = getInnerResumeDest();
22530815c53SDimitry Andric   BasicBlock *Src = RI->getParent();
22630815c53SDimitry Andric 
22730815c53SDimitry Andric   BranchInst::Create(Dest, Src);
22830815c53SDimitry Andric 
22930815c53SDimitry Andric   // Update the PHIs in the destination. They were inserted in an order which
23030815c53SDimitry Andric   // makes this work.
23130815c53SDimitry Andric   addIncomingPHIValuesForInto(Src, Dest);
23230815c53SDimitry Andric 
23330815c53SDimitry Andric   InnerEHValuesPHI->addIncoming(RI->getOperand(0), Src);
23430815c53SDimitry Andric   RI->eraseFromParent();
23530815c53SDimitry Andric }
23630815c53SDimitry Andric 
237dadbdfffSDimitry Andric /// Helper for getUnwindDestToken/getUnwindDestTokenHelper.
getParentPad(Value * EHPad)238dadbdfffSDimitry Andric static Value *getParentPad(Value *EHPad) {
239dadbdfffSDimitry Andric   if (auto *FPI = dyn_cast<FuncletPadInst>(EHPad))
240dadbdfffSDimitry Andric     return FPI->getParentPad();
241dadbdfffSDimitry Andric   return cast<CatchSwitchInst>(EHPad)->getParentPad();
242dadbdfffSDimitry Andric }
243dadbdfffSDimitry Andric 
244044eb2f6SDimitry Andric using UnwindDestMemoTy = DenseMap<Instruction *, Value *>;
245dadbdfffSDimitry Andric 
246dadbdfffSDimitry Andric /// Helper for getUnwindDestToken that does the descendant-ward part of
247dadbdfffSDimitry Andric /// the search.
getUnwindDestTokenHelper(Instruction * EHPad,UnwindDestMemoTy & MemoMap)248dadbdfffSDimitry Andric static Value *getUnwindDestTokenHelper(Instruction *EHPad,
249dadbdfffSDimitry Andric                                        UnwindDestMemoTy &MemoMap) {
250dadbdfffSDimitry Andric   SmallVector<Instruction *, 8> Worklist(1, EHPad);
251dadbdfffSDimitry Andric 
252dadbdfffSDimitry Andric   while (!Worklist.empty()) {
253dadbdfffSDimitry Andric     Instruction *CurrentPad = Worklist.pop_back_val();
254dadbdfffSDimitry Andric     // We only put pads on the worklist that aren't in the MemoMap.  When
255dadbdfffSDimitry Andric     // we find an unwind dest for a pad we may update its ancestors, but
256dadbdfffSDimitry Andric     // the queue only ever contains uncles/great-uncles/etc. of CurrentPad,
257dadbdfffSDimitry Andric     // so they should never get updated while queued on the worklist.
258dadbdfffSDimitry Andric     assert(!MemoMap.count(CurrentPad));
259dadbdfffSDimitry Andric     Value *UnwindDestToken = nullptr;
260dadbdfffSDimitry Andric     if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(CurrentPad)) {
261dadbdfffSDimitry Andric       if (CatchSwitch->hasUnwindDest()) {
262dadbdfffSDimitry Andric         UnwindDestToken = CatchSwitch->getUnwindDest()->getFirstNonPHI();
263dadbdfffSDimitry Andric       } else {
264dadbdfffSDimitry Andric         // Catchswitch doesn't have a 'nounwind' variant, and one might be
265dadbdfffSDimitry Andric         // annotated as "unwinds to caller" when really it's nounwind (see
266dadbdfffSDimitry Andric         // e.g. SimplifyCFGOpt::SimplifyUnreachable), so we can't infer the
267dadbdfffSDimitry Andric         // parent's unwind dest from this.  We can check its catchpads'
268dadbdfffSDimitry Andric         // descendants, since they might include a cleanuppad with an
269dadbdfffSDimitry Andric         // "unwinds to caller" cleanupret, which can be trusted.
270dadbdfffSDimitry Andric         for (auto HI = CatchSwitch->handler_begin(),
271dadbdfffSDimitry Andric                   HE = CatchSwitch->handler_end();
272dadbdfffSDimitry Andric              HI != HE && !UnwindDestToken; ++HI) {
273dadbdfffSDimitry Andric           BasicBlock *HandlerBlock = *HI;
274dadbdfffSDimitry Andric           auto *CatchPad = cast<CatchPadInst>(HandlerBlock->getFirstNonPHI());
275dadbdfffSDimitry Andric           for (User *Child : CatchPad->users()) {
276dadbdfffSDimitry Andric             // Intentionally ignore invokes here -- since the catchswitch is
277dadbdfffSDimitry Andric             // marked "unwind to caller", it would be a verifier error if it
278dadbdfffSDimitry Andric             // contained an invoke which unwinds out of it, so any invoke we'd
279dadbdfffSDimitry Andric             // encounter must unwind to some child of the catch.
280dadbdfffSDimitry Andric             if (!isa<CleanupPadInst>(Child) && !isa<CatchSwitchInst>(Child))
281dadbdfffSDimitry Andric               continue;
282dadbdfffSDimitry Andric 
283dadbdfffSDimitry Andric             Instruction *ChildPad = cast<Instruction>(Child);
284dadbdfffSDimitry Andric             auto Memo = MemoMap.find(ChildPad);
285dadbdfffSDimitry Andric             if (Memo == MemoMap.end()) {
286b915e9e0SDimitry Andric               // Haven't figured out this child pad yet; queue it.
287dadbdfffSDimitry Andric               Worklist.push_back(ChildPad);
288dadbdfffSDimitry Andric               continue;
289dadbdfffSDimitry Andric             }
290dadbdfffSDimitry Andric             // We've already checked this child, but might have found that
291dadbdfffSDimitry Andric             // it offers no proof either way.
292dadbdfffSDimitry Andric             Value *ChildUnwindDestToken = Memo->second;
293dadbdfffSDimitry Andric             if (!ChildUnwindDestToken)
294dadbdfffSDimitry Andric               continue;
295dadbdfffSDimitry Andric             // We already know the child's unwind dest, which can either
296dadbdfffSDimitry Andric             // be ConstantTokenNone to indicate unwind to caller, or can
297dadbdfffSDimitry Andric             // be another child of the catchpad.  Only the former indicates
298dadbdfffSDimitry Andric             // the unwind dest of the catchswitch.
299dadbdfffSDimitry Andric             if (isa<ConstantTokenNone>(ChildUnwindDestToken)) {
300dadbdfffSDimitry Andric               UnwindDestToken = ChildUnwindDestToken;
301dadbdfffSDimitry Andric               break;
302dadbdfffSDimitry Andric             }
303dadbdfffSDimitry Andric             assert(getParentPad(ChildUnwindDestToken) == CatchPad);
304dadbdfffSDimitry Andric           }
305dadbdfffSDimitry Andric         }
306dadbdfffSDimitry Andric       }
307dadbdfffSDimitry Andric     } else {
308dadbdfffSDimitry Andric       auto *CleanupPad = cast<CleanupPadInst>(CurrentPad);
309dadbdfffSDimitry Andric       for (User *U : CleanupPad->users()) {
310dadbdfffSDimitry Andric         if (auto *CleanupRet = dyn_cast<CleanupReturnInst>(U)) {
311dadbdfffSDimitry Andric           if (BasicBlock *RetUnwindDest = CleanupRet->getUnwindDest())
312dadbdfffSDimitry Andric             UnwindDestToken = RetUnwindDest->getFirstNonPHI();
313dadbdfffSDimitry Andric           else
314dadbdfffSDimitry Andric             UnwindDestToken = ConstantTokenNone::get(CleanupPad->getContext());
315dadbdfffSDimitry Andric           break;
316dadbdfffSDimitry Andric         }
317dadbdfffSDimitry Andric         Value *ChildUnwindDestToken;
318dadbdfffSDimitry Andric         if (auto *Invoke = dyn_cast<InvokeInst>(U)) {
319dadbdfffSDimitry Andric           ChildUnwindDestToken = Invoke->getUnwindDest()->getFirstNonPHI();
320dadbdfffSDimitry Andric         } else if (isa<CleanupPadInst>(U) || isa<CatchSwitchInst>(U)) {
321dadbdfffSDimitry Andric           Instruction *ChildPad = cast<Instruction>(U);
322dadbdfffSDimitry Andric           auto Memo = MemoMap.find(ChildPad);
323dadbdfffSDimitry Andric           if (Memo == MemoMap.end()) {
324dadbdfffSDimitry Andric             // Haven't resolved this child yet; queue it and keep searching.
325dadbdfffSDimitry Andric             Worklist.push_back(ChildPad);
326dadbdfffSDimitry Andric             continue;
327dadbdfffSDimitry Andric           }
328dadbdfffSDimitry Andric           // We've checked this child, but still need to ignore it if it
329dadbdfffSDimitry Andric           // had no proof either way.
330dadbdfffSDimitry Andric           ChildUnwindDestToken = Memo->second;
331dadbdfffSDimitry Andric           if (!ChildUnwindDestToken)
332dadbdfffSDimitry Andric             continue;
333dadbdfffSDimitry Andric         } else {
334dadbdfffSDimitry Andric           // Not a relevant user of the cleanuppad
335dadbdfffSDimitry Andric           continue;
336dadbdfffSDimitry Andric         }
337dadbdfffSDimitry Andric         // In a well-formed program, the child/invoke must either unwind to
338dadbdfffSDimitry Andric         // an(other) child of the cleanup, or exit the cleanup.  In the
339dadbdfffSDimitry Andric         // first case, continue searching.
340dadbdfffSDimitry Andric         if (isa<Instruction>(ChildUnwindDestToken) &&
341dadbdfffSDimitry Andric             getParentPad(ChildUnwindDestToken) == CleanupPad)
342dadbdfffSDimitry Andric           continue;
343dadbdfffSDimitry Andric         UnwindDestToken = ChildUnwindDestToken;
344dadbdfffSDimitry Andric         break;
345dadbdfffSDimitry Andric       }
346dadbdfffSDimitry Andric     }
347dadbdfffSDimitry Andric     // If we haven't found an unwind dest for CurrentPad, we may have queued its
348dadbdfffSDimitry Andric     // children, so move on to the next in the worklist.
349dadbdfffSDimitry Andric     if (!UnwindDestToken)
350dadbdfffSDimitry Andric       continue;
351dadbdfffSDimitry Andric 
352dadbdfffSDimitry Andric     // Now we know that CurrentPad unwinds to UnwindDestToken.  It also exits
353dadbdfffSDimitry Andric     // any ancestors of CurrentPad up to but not including UnwindDestToken's
354dadbdfffSDimitry Andric     // parent pad.  Record this in the memo map, and check to see if the
355dadbdfffSDimitry Andric     // original EHPad being queried is one of the ones exited.
356dadbdfffSDimitry Andric     Value *UnwindParent;
357dadbdfffSDimitry Andric     if (auto *UnwindPad = dyn_cast<Instruction>(UnwindDestToken))
358dadbdfffSDimitry Andric       UnwindParent = getParentPad(UnwindPad);
359dadbdfffSDimitry Andric     else
360dadbdfffSDimitry Andric       UnwindParent = nullptr;
361dadbdfffSDimitry Andric     bool ExitedOriginalPad = false;
362dadbdfffSDimitry Andric     for (Instruction *ExitedPad = CurrentPad;
363dadbdfffSDimitry Andric          ExitedPad && ExitedPad != UnwindParent;
364dadbdfffSDimitry Andric          ExitedPad = dyn_cast<Instruction>(getParentPad(ExitedPad))) {
365dadbdfffSDimitry Andric       // Skip over catchpads since they just follow their catchswitches.
366dadbdfffSDimitry Andric       if (isa<CatchPadInst>(ExitedPad))
367dadbdfffSDimitry Andric         continue;
368dadbdfffSDimitry Andric       MemoMap[ExitedPad] = UnwindDestToken;
369dadbdfffSDimitry Andric       ExitedOriginalPad |= (ExitedPad == EHPad);
370dadbdfffSDimitry Andric     }
371dadbdfffSDimitry Andric 
372dadbdfffSDimitry Andric     if (ExitedOriginalPad)
373dadbdfffSDimitry Andric       return UnwindDestToken;
374dadbdfffSDimitry Andric 
375dadbdfffSDimitry Andric     // Continue the search.
376dadbdfffSDimitry Andric   }
377dadbdfffSDimitry Andric 
378dadbdfffSDimitry Andric   // No definitive information is contained within this funclet.
379dadbdfffSDimitry Andric   return nullptr;
380dadbdfffSDimitry Andric }
381dadbdfffSDimitry Andric 
382dadbdfffSDimitry Andric /// Given an EH pad, find where it unwinds.  If it unwinds to an EH pad,
383dadbdfffSDimitry Andric /// return that pad instruction.  If it unwinds to caller, return
384dadbdfffSDimitry Andric /// ConstantTokenNone.  If it does not have a definitive unwind destination,
385dadbdfffSDimitry Andric /// return nullptr.
386dadbdfffSDimitry Andric ///
387dadbdfffSDimitry Andric /// This routine gets invoked for calls in funclets in inlinees when inlining
388dadbdfffSDimitry Andric /// an invoke.  Since many funclets don't have calls inside them, it's queried
389dadbdfffSDimitry Andric /// on-demand rather than building a map of pads to unwind dests up front.
390dadbdfffSDimitry Andric /// Determining a funclet's unwind dest may require recursively searching its
391dadbdfffSDimitry Andric /// descendants, and also ancestors and cousins if the descendants don't provide
392dadbdfffSDimitry Andric /// an answer.  Since most funclets will have their unwind dest immediately
393dadbdfffSDimitry Andric /// available as the unwind dest of a catchswitch or cleanupret, this routine
394dadbdfffSDimitry Andric /// searches top-down from the given pad and then up. To avoid worst-case
395dadbdfffSDimitry Andric /// quadratic run-time given that approach, it uses a memo map to avoid
396dadbdfffSDimitry Andric /// re-processing funclet trees.  The callers that rewrite the IR as they go
397dadbdfffSDimitry Andric /// take advantage of this, for correctness, by checking/forcing rewritten
398dadbdfffSDimitry Andric /// pads' entries to match the original callee view.
getUnwindDestToken(Instruction * EHPad,UnwindDestMemoTy & MemoMap)399dadbdfffSDimitry Andric static Value *getUnwindDestToken(Instruction *EHPad,
400dadbdfffSDimitry Andric                                  UnwindDestMemoTy &MemoMap) {
401dadbdfffSDimitry Andric   // Catchpads unwind to the same place as their catchswitch;
402dadbdfffSDimitry Andric   // redirct any queries on catchpads so the code below can
403dadbdfffSDimitry Andric   // deal with just catchswitches and cleanuppads.
404dadbdfffSDimitry Andric   if (auto *CPI = dyn_cast<CatchPadInst>(EHPad))
405dadbdfffSDimitry Andric     EHPad = CPI->getCatchSwitch();
406dadbdfffSDimitry Andric 
407dadbdfffSDimitry Andric   // Check if we've already determined the unwind dest for this pad.
408dadbdfffSDimitry Andric   auto Memo = MemoMap.find(EHPad);
409dadbdfffSDimitry Andric   if (Memo != MemoMap.end())
410dadbdfffSDimitry Andric     return Memo->second;
411dadbdfffSDimitry Andric 
412dadbdfffSDimitry Andric   // Search EHPad and, if necessary, its descendants.
413dadbdfffSDimitry Andric   Value *UnwindDestToken = getUnwindDestTokenHelper(EHPad, MemoMap);
414dadbdfffSDimitry Andric   assert((UnwindDestToken == nullptr) != (MemoMap.count(EHPad) != 0));
415dadbdfffSDimitry Andric   if (UnwindDestToken)
416dadbdfffSDimitry Andric     return UnwindDestToken;
417dadbdfffSDimitry Andric 
418dadbdfffSDimitry Andric   // No information is available for this EHPad from itself or any of its
419dadbdfffSDimitry Andric   // descendants.  An unwind all the way out to a pad in the caller would
420dadbdfffSDimitry Andric   // need also to agree with the unwind dest of the parent funclet, so
421dadbdfffSDimitry Andric   // search up the chain to try to find a funclet with information.  Put
422dadbdfffSDimitry Andric   // null entries in the memo map to avoid re-processing as we go up.
423dadbdfffSDimitry Andric   MemoMap[EHPad] = nullptr;
424b915e9e0SDimitry Andric #ifndef NDEBUG
425b915e9e0SDimitry Andric   SmallPtrSet<Instruction *, 4> TempMemos;
426b915e9e0SDimitry Andric   TempMemos.insert(EHPad);
427b915e9e0SDimitry Andric #endif
428dadbdfffSDimitry Andric   Instruction *LastUselessPad = EHPad;
429dadbdfffSDimitry Andric   Value *AncestorToken;
430dadbdfffSDimitry Andric   for (AncestorToken = getParentPad(EHPad);
431dadbdfffSDimitry Andric        auto *AncestorPad = dyn_cast<Instruction>(AncestorToken);
432dadbdfffSDimitry Andric        AncestorToken = getParentPad(AncestorToken)) {
433dadbdfffSDimitry Andric     // Skip over catchpads since they just follow their catchswitches.
434dadbdfffSDimitry Andric     if (isa<CatchPadInst>(AncestorPad))
435dadbdfffSDimitry Andric       continue;
436b915e9e0SDimitry Andric     // If the MemoMap had an entry mapping AncestorPad to nullptr, since we
437b915e9e0SDimitry Andric     // haven't yet called getUnwindDestTokenHelper for AncestorPad in this
438b915e9e0SDimitry Andric     // call to getUnwindDestToken, that would mean that AncestorPad had no
439b915e9e0SDimitry Andric     // information in itself, its descendants, or its ancestors.  If that
440b915e9e0SDimitry Andric     // were the case, then we should also have recorded the lack of information
441b915e9e0SDimitry Andric     // for the descendant that we're coming from.  So assert that we don't
442b915e9e0SDimitry Andric     // find a null entry in the MemoMap for AncestorPad.
443dadbdfffSDimitry Andric     assert(!MemoMap.count(AncestorPad) || MemoMap[AncestorPad]);
444dadbdfffSDimitry Andric     auto AncestorMemo = MemoMap.find(AncestorPad);
445dadbdfffSDimitry Andric     if (AncestorMemo == MemoMap.end()) {
446dadbdfffSDimitry Andric       UnwindDestToken = getUnwindDestTokenHelper(AncestorPad, MemoMap);
447dadbdfffSDimitry Andric     } else {
448dadbdfffSDimitry Andric       UnwindDestToken = AncestorMemo->second;
449dadbdfffSDimitry Andric     }
450dadbdfffSDimitry Andric     if (UnwindDestToken)
451dadbdfffSDimitry Andric       break;
452dadbdfffSDimitry Andric     LastUselessPad = AncestorPad;
453b915e9e0SDimitry Andric     MemoMap[LastUselessPad] = nullptr;
454b915e9e0SDimitry Andric #ifndef NDEBUG
455b915e9e0SDimitry Andric     TempMemos.insert(LastUselessPad);
456b915e9e0SDimitry Andric #endif
457dadbdfffSDimitry Andric   }
458dadbdfffSDimitry Andric 
459b915e9e0SDimitry Andric   // We know that getUnwindDestTokenHelper was called on LastUselessPad and
460b915e9e0SDimitry Andric   // returned nullptr (and likewise for EHPad and any of its ancestors up to
461b915e9e0SDimitry Andric   // LastUselessPad), so LastUselessPad has no information from below.  Since
462b915e9e0SDimitry Andric   // getUnwindDestTokenHelper must investigate all downward paths through
463b915e9e0SDimitry Andric   // no-information nodes to prove that a node has no information like this,
464b915e9e0SDimitry Andric   // and since any time it finds information it records it in the MemoMap for
465b915e9e0SDimitry Andric   // not just the immediately-containing funclet but also any ancestors also
466b915e9e0SDimitry Andric   // exited, it must be the case that, walking downward from LastUselessPad,
467b915e9e0SDimitry Andric   // visiting just those nodes which have not been mapped to an unwind dest
468b915e9e0SDimitry Andric   // by getUnwindDestTokenHelper (the nullptr TempMemos notwithstanding, since
469b915e9e0SDimitry Andric   // they are just used to keep getUnwindDestTokenHelper from repeating work),
470b915e9e0SDimitry Andric   // any node visited must have been exhaustively searched with no information
471b915e9e0SDimitry Andric   // for it found.
472dadbdfffSDimitry Andric   SmallVector<Instruction *, 8> Worklist(1, LastUselessPad);
473dadbdfffSDimitry Andric   while (!Worklist.empty()) {
474dadbdfffSDimitry Andric     Instruction *UselessPad = Worklist.pop_back_val();
475b915e9e0SDimitry Andric     auto Memo = MemoMap.find(UselessPad);
476b915e9e0SDimitry Andric     if (Memo != MemoMap.end() && Memo->second) {
477b915e9e0SDimitry Andric       // Here the name 'UselessPad' is a bit of a misnomer, because we've found
478b915e9e0SDimitry Andric       // that it is a funclet that does have information about unwinding to
479b915e9e0SDimitry Andric       // a particular destination; its parent was a useless pad.
480b915e9e0SDimitry Andric       // Since its parent has no information, the unwind edge must not escape
481b915e9e0SDimitry Andric       // the parent, and must target a sibling of this pad.  This local unwind
482b915e9e0SDimitry Andric       // gives us no information about EHPad.  Leave it and the subtree rooted
483b915e9e0SDimitry Andric       // at it alone.
484b915e9e0SDimitry Andric       assert(getParentPad(Memo->second) == getParentPad(UselessPad));
485b915e9e0SDimitry Andric       continue;
486b915e9e0SDimitry Andric     }
487b915e9e0SDimitry Andric     // We know we don't have information for UselesPad.  If it has an entry in
488b915e9e0SDimitry Andric     // the MemoMap (mapping it to nullptr), it must be one of the TempMemos
489b915e9e0SDimitry Andric     // added on this invocation of getUnwindDestToken; if a previous invocation
490b915e9e0SDimitry Andric     // recorded nullptr, it would have had to prove that the ancestors of
491b915e9e0SDimitry Andric     // UselessPad, which include LastUselessPad, had no information, and that
492b915e9e0SDimitry Andric     // in turn would have required proving that the descendants of
493b915e9e0SDimitry Andric     // LastUselesPad, which include EHPad, have no information about
494b915e9e0SDimitry Andric     // LastUselessPad, which would imply that EHPad was mapped to nullptr in
495b915e9e0SDimitry Andric     // the MemoMap on that invocation, which isn't the case if we got here.
496b915e9e0SDimitry Andric     assert(!MemoMap.count(UselessPad) || TempMemos.count(UselessPad));
497b915e9e0SDimitry Andric     // Assert as we enumerate users that 'UselessPad' doesn't have any unwind
498b915e9e0SDimitry Andric     // information that we'd be contradicting by making a map entry for it
499b915e9e0SDimitry Andric     // (which is something that getUnwindDestTokenHelper must have proved for
500b915e9e0SDimitry Andric     // us to get here).  Just assert on is direct users here; the checks in
501b915e9e0SDimitry Andric     // this downward walk at its descendants will verify that they don't have
502b915e9e0SDimitry Andric     // any unwind edges that exit 'UselessPad' either (i.e. they either have no
503b915e9e0SDimitry Andric     // unwind edges or unwind to a sibling).
504dadbdfffSDimitry Andric     MemoMap[UselessPad] = UnwindDestToken;
505dadbdfffSDimitry Andric     if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(UselessPad)) {
506b915e9e0SDimitry Andric       assert(CatchSwitch->getUnwindDest() == nullptr && "Expected useless pad");
507b915e9e0SDimitry Andric       for (BasicBlock *HandlerBlock : CatchSwitch->handlers()) {
508b915e9e0SDimitry Andric         auto *CatchPad = HandlerBlock->getFirstNonPHI();
509b915e9e0SDimitry Andric         for (User *U : CatchPad->users()) {
510b915e9e0SDimitry Andric           assert(
511b915e9e0SDimitry Andric               (!isa<InvokeInst>(U) ||
512b915e9e0SDimitry Andric                (getParentPad(
513b915e9e0SDimitry Andric                     cast<InvokeInst>(U)->getUnwindDest()->getFirstNonPHI()) ==
514b915e9e0SDimitry Andric                 CatchPad)) &&
515b915e9e0SDimitry Andric               "Expected useless pad");
516dadbdfffSDimitry Andric           if (isa<CatchSwitchInst>(U) || isa<CleanupPadInst>(U))
517dadbdfffSDimitry Andric             Worklist.push_back(cast<Instruction>(U));
518b915e9e0SDimitry Andric         }
519b915e9e0SDimitry Andric       }
520dadbdfffSDimitry Andric     } else {
521dadbdfffSDimitry Andric       assert(isa<CleanupPadInst>(UselessPad));
522b915e9e0SDimitry Andric       for (User *U : UselessPad->users()) {
523b915e9e0SDimitry Andric         assert(!isa<CleanupReturnInst>(U) && "Expected useless pad");
524b915e9e0SDimitry Andric         assert((!isa<InvokeInst>(U) ||
525b915e9e0SDimitry Andric                 (getParentPad(
526b915e9e0SDimitry Andric                      cast<InvokeInst>(U)->getUnwindDest()->getFirstNonPHI()) ==
527b915e9e0SDimitry Andric                  UselessPad)) &&
528b915e9e0SDimitry Andric                "Expected useless pad");
529dadbdfffSDimitry Andric         if (isa<CatchSwitchInst>(U) || isa<CleanupPadInst>(U))
530dadbdfffSDimitry Andric           Worklist.push_back(cast<Instruction>(U));
531dadbdfffSDimitry Andric       }
532dadbdfffSDimitry Andric     }
533b915e9e0SDimitry Andric   }
534dadbdfffSDimitry Andric 
535dadbdfffSDimitry Andric   return UnwindDestToken;
536dadbdfffSDimitry Andric }
537dadbdfffSDimitry Andric 
5385a5ac124SDimitry Andric /// When we inline a basic block into an invoke,
5395a5ac124SDimitry Andric /// we have to turn all of the calls that can throw into invokes.
5405a5ac124SDimitry Andric /// This function analyze BB to see if there are any calls, and if so,
54159850d08SRoman Divacky /// it rewrites them to be invokes that jump to InvokeDest and fills in the PHI
54259850d08SRoman Divacky /// nodes in that block with the values specified in InvokeDestPHIValues.
HandleCallsInBlockInlinedThroughInvoke(BasicBlock * BB,BasicBlock * UnwindEdge,UnwindDestMemoTy * FuncletUnwindMap=nullptr)543dadbdfffSDimitry Andric static BasicBlock *HandleCallsInBlockInlinedThroughInvoke(
544dadbdfffSDimitry Andric     BasicBlock *BB, BasicBlock *UnwindEdge,
545dadbdfffSDimitry Andric     UnwindDestMemoTy *FuncletUnwindMap = nullptr) {
546c0981da4SDimitry Andric   for (Instruction &I : llvm::make_early_inc_range(*BB)) {
547009b1c42SEd Schouten     // We only need to check for function calls: inlined invoke
548009b1c42SEd Schouten     // instructions require no special handling.
549c0981da4SDimitry Andric     CallInst *CI = dyn_cast<CallInst>(&I);
55056fe8f14SDimitry Andric 
551344a3780SDimitry Andric     if (!CI || CI->doesNotThrow())
552009b1c42SEd Schouten       continue;
553009b1c42SEd Schouten 
55401095a5dSDimitry Andric     // We do not need to (and in fact, cannot) convert possibly throwing calls
55501095a5dSDimitry Andric     // to @llvm.experimental_deoptimize (resp. @llvm.experimental.guard) into
55601095a5dSDimitry Andric     // invokes.  The caller's "segment" of the deoptimization continuation
55701095a5dSDimitry Andric     // attached to the newly inlined @llvm.experimental_deoptimize
55801095a5dSDimitry Andric     // (resp. @llvm.experimental.guard) call should contain the exception
55901095a5dSDimitry Andric     // handling logic, if any.
56001095a5dSDimitry Andric     if (auto *F = CI->getCalledFunction())
56101095a5dSDimitry Andric       if (F->getIntrinsicID() == Intrinsic::experimental_deoptimize ||
56201095a5dSDimitry Andric           F->getIntrinsicID() == Intrinsic::experimental_guard)
56301095a5dSDimitry Andric         continue;
56401095a5dSDimitry Andric 
565dadbdfffSDimitry Andric     if (auto FuncletBundle = CI->getOperandBundle(LLVMContext::OB_funclet)) {
566dadbdfffSDimitry Andric       // This call is nested inside a funclet.  If that funclet has an unwind
567dadbdfffSDimitry Andric       // destination within the inlinee, then unwinding out of this call would
568dadbdfffSDimitry Andric       // be UB.  Rewriting this call to an invoke which targets the inlined
569dadbdfffSDimitry Andric       // invoke's unwind dest would give the call's parent funclet multiple
570dadbdfffSDimitry Andric       // unwind destinations, which is something that subsequent EH table
571dadbdfffSDimitry Andric       // generation can't handle and that the veirifer rejects.  So when we
572dadbdfffSDimitry Andric       // see such a call, leave it as a call.
573dadbdfffSDimitry Andric       auto *FuncletPad = cast<Instruction>(FuncletBundle->Inputs[0]);
574dadbdfffSDimitry Andric       Value *UnwindDestToken =
575dadbdfffSDimitry Andric           getUnwindDestToken(FuncletPad, *FuncletUnwindMap);
576dadbdfffSDimitry Andric       if (UnwindDestToken && !isa<ConstantTokenNone>(UnwindDestToken))
577dadbdfffSDimitry Andric         continue;
578dadbdfffSDimitry Andric #ifndef NDEBUG
579dadbdfffSDimitry Andric       Instruction *MemoKey;
580dadbdfffSDimitry Andric       if (auto *CatchPad = dyn_cast<CatchPadInst>(FuncletPad))
581dadbdfffSDimitry Andric         MemoKey = CatchPad->getCatchSwitch();
582dadbdfffSDimitry Andric       else
583dadbdfffSDimitry Andric         MemoKey = FuncletPad;
584dadbdfffSDimitry Andric       assert(FuncletUnwindMap->count(MemoKey) &&
585dadbdfffSDimitry Andric              (*FuncletUnwindMap)[MemoKey] == UnwindDestToken &&
586dadbdfffSDimitry Andric              "must get memoized to avoid confusing later searches");
587dadbdfffSDimitry Andric #endif // NDEBUG
588dadbdfffSDimitry Andric     }
589dadbdfffSDimitry Andric 
590b915e9e0SDimitry Andric     changeToInvokeAndSplitBasicBlock(CI, UnwindEdge);
591dd58ef01SDimitry Andric     return BB;
59259850d08SRoman Divacky   }
593dd58ef01SDimitry Andric   return nullptr;
594009b1c42SEd Schouten }
595009b1c42SEd Schouten 
5965a5ac124SDimitry Andric /// If we inlined an invoke site, we need to convert calls
59763faed5bSDimitry Andric /// in the body of the inlined function into invokes.
59859850d08SRoman Divacky ///
59959850d08SRoman Divacky /// II is the invoke instruction being inlined.  FirstNewBlock is the first
60059850d08SRoman Divacky /// block of the inlined code (the last block is the end of the function),
60159850d08SRoman Divacky /// and InlineCodeInfo is information about the code that got inlined.
HandleInlinedLandingPad(InvokeInst * II,BasicBlock * FirstNewBlock,ClonedCodeInfo & InlinedCodeInfo)602dd58ef01SDimitry Andric static void HandleInlinedLandingPad(InvokeInst *II, BasicBlock *FirstNewBlock,
60359850d08SRoman Divacky                                     ClonedCodeInfo &InlinedCodeInfo) {
60459850d08SRoman Divacky   BasicBlock *InvokeDest = II->getUnwindDest();
60559850d08SRoman Divacky 
60659850d08SRoman Divacky   Function *Caller = FirstNewBlock->getParent();
60759850d08SRoman Divacky 
60859850d08SRoman Divacky   // The inlined code is currently at the end of the function, scan from the
60959850d08SRoman Divacky   // start of the inlined code to its end, checking for stuff we need to
6104a16efa3SDimitry Andric   // rewrite.
611dd58ef01SDimitry Andric   LandingPadInliningInfo Invoke(II);
61256fe8f14SDimitry Andric 
6134a16efa3SDimitry Andric   // Get all of the inlined landing pad instructions.
6144a16efa3SDimitry Andric   SmallPtrSet<LandingPadInst*, 16> InlinedLPads;
615dd58ef01SDimitry Andric   for (Function::iterator I = FirstNewBlock->getIterator(), E = Caller->end();
616dd58ef01SDimitry Andric        I != E; ++I)
6174a16efa3SDimitry Andric     if (InvokeInst *II = dyn_cast<InvokeInst>(I->getTerminator()))
6184a16efa3SDimitry Andric       InlinedLPads.insert(II->getLandingPadInst());
6194a16efa3SDimitry Andric 
6205ca98fd9SDimitry Andric   // Append the clauses from the outer landing pad instruction into the inlined
6215ca98fd9SDimitry Andric   // landing pad instructions.
6225ca98fd9SDimitry Andric   LandingPadInst *OuterLPad = Invoke.getLandingPadInst();
62367c32a98SDimitry Andric   for (LandingPadInst *InlinedLPad : InlinedLPads) {
6245ca98fd9SDimitry Andric     unsigned OuterNum = OuterLPad->getNumClauses();
6255ca98fd9SDimitry Andric     InlinedLPad->reserveClauses(OuterNum);
6265ca98fd9SDimitry Andric     for (unsigned OuterIdx = 0; OuterIdx != OuterNum; ++OuterIdx)
6275ca98fd9SDimitry Andric       InlinedLPad->addClause(OuterLPad->getClause(OuterIdx));
6285ca98fd9SDimitry Andric     if (OuterLPad->isCleanup())
6295ca98fd9SDimitry Andric       InlinedLPad->setCleanup(true);
6305ca98fd9SDimitry Andric   }
6315ca98fd9SDimitry Andric 
632dd58ef01SDimitry Andric   for (Function::iterator BB = FirstNewBlock->getIterator(), E = Caller->end();
633dd58ef01SDimitry Andric        BB != E; ++BB) {
63459850d08SRoman Divacky     if (InlinedCodeInfo.ContainsCalls)
635dd58ef01SDimitry Andric       if (BasicBlock *NewBB = HandleCallsInBlockInlinedThroughInvoke(
636dd58ef01SDimitry Andric               &*BB, Invoke.getOuterResumeDest()))
637dd58ef01SDimitry Andric         // Update any PHI nodes in the exceptional block to indicate that there
638dd58ef01SDimitry Andric         // is now a new entry in them.
639dd58ef01SDimitry Andric         Invoke.addIncomingPHIValuesFor(NewBB);
64059850d08SRoman Divacky 
6414a16efa3SDimitry Andric     // Forward any resumes that are remaining here.
64263faed5bSDimitry Andric     if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator()))
6434a16efa3SDimitry Andric       Invoke.forwardResume(RI, InlinedLPads);
64430815c53SDimitry Andric   }
645009b1c42SEd Schouten 
646009b1c42SEd Schouten   // Now that everything is happy, we have one final detail.  The PHI nodes in
647009b1c42SEd Schouten   // the exception destination block still have entries due to the original
648009b1c42SEd Schouten   // invoke instruction. Eliminate these entries (which might even delete the
649009b1c42SEd Schouten   // PHI node) now.
650009b1c42SEd Schouten   InvokeDest->removePredecessor(II->getParent());
651009b1c42SEd Schouten }
652009b1c42SEd Schouten 
653dd58ef01SDimitry Andric /// If we inlined an invoke site, we need to convert calls
654dd58ef01SDimitry Andric /// in the body of the inlined function into invokes.
655dd58ef01SDimitry Andric ///
656dd58ef01SDimitry Andric /// II is the invoke instruction being inlined.  FirstNewBlock is the first
657dd58ef01SDimitry Andric /// block of the inlined code (the last block is the end of the function),
658dd58ef01SDimitry Andric /// and InlineCodeInfo is information about the code that got inlined.
HandleInlinedEHPad(InvokeInst * II,BasicBlock * FirstNewBlock,ClonedCodeInfo & InlinedCodeInfo)659dd58ef01SDimitry Andric static void HandleInlinedEHPad(InvokeInst *II, BasicBlock *FirstNewBlock,
660dd58ef01SDimitry Andric                                ClonedCodeInfo &InlinedCodeInfo) {
661dd58ef01SDimitry Andric   BasicBlock *UnwindDest = II->getUnwindDest();
662dd58ef01SDimitry Andric   Function *Caller = FirstNewBlock->getParent();
663dd58ef01SDimitry Andric 
664dd58ef01SDimitry Andric   assert(UnwindDest->getFirstNonPHI()->isEHPad() && "unexpected BasicBlock!");
665dd58ef01SDimitry Andric 
666dd58ef01SDimitry Andric   // If there are PHI nodes in the unwind destination block, we need to keep
667dd58ef01SDimitry Andric   // track of which values came into them from the invoke before removing the
668dd58ef01SDimitry Andric   // edge from this block.
669dd58ef01SDimitry Andric   SmallVector<Value *, 8> UnwindDestPHIValues;
670044eb2f6SDimitry Andric   BasicBlock *InvokeBB = II->getParent();
671ecbca9f5SDimitry Andric   for (PHINode &PHI : UnwindDest->phis()) {
672dd58ef01SDimitry Andric     // Save the value to use for this edge.
673ecbca9f5SDimitry Andric     UnwindDestPHIValues.push_back(PHI.getIncomingValueForBlock(InvokeBB));
674dd58ef01SDimitry Andric   }
675dd58ef01SDimitry Andric 
676dd58ef01SDimitry Andric   // Add incoming-PHI values to the unwind destination block for the given basic
677dd58ef01SDimitry Andric   // block, using the values for the original invoke's source block.
678dd58ef01SDimitry Andric   auto UpdatePHINodes = [&](BasicBlock *Src) {
679dd58ef01SDimitry Andric     BasicBlock::iterator I = UnwindDest->begin();
680dd58ef01SDimitry Andric     for (Value *V : UnwindDestPHIValues) {
681dd58ef01SDimitry Andric       PHINode *PHI = cast<PHINode>(I);
682dd58ef01SDimitry Andric       PHI->addIncoming(V, Src);
683dd58ef01SDimitry Andric       ++I;
684dd58ef01SDimitry Andric     }
685dd58ef01SDimitry Andric   };
686dd58ef01SDimitry Andric 
687dd58ef01SDimitry Andric   // This connects all the instructions which 'unwind to caller' to the invoke
688dd58ef01SDimitry Andric   // destination.
689dadbdfffSDimitry Andric   UnwindDestMemoTy FuncletUnwindMap;
690dd58ef01SDimitry Andric   for (Function::iterator BB = FirstNewBlock->getIterator(), E = Caller->end();
691dd58ef01SDimitry Andric        BB != E; ++BB) {
692dd58ef01SDimitry Andric     if (auto *CRI = dyn_cast<CleanupReturnInst>(BB->getTerminator())) {
693dd58ef01SDimitry Andric       if (CRI->unwindsToCaller()) {
694dadbdfffSDimitry Andric         auto *CleanupPad = CRI->getCleanupPad();
695ac9a064cSDimitry Andric         CleanupReturnInst::Create(CleanupPad, UnwindDest, CRI->getIterator());
696dd58ef01SDimitry Andric         CRI->eraseFromParent();
697dd58ef01SDimitry Andric         UpdatePHINodes(&*BB);
698dadbdfffSDimitry Andric         // Finding a cleanupret with an unwind destination would confuse
699dadbdfffSDimitry Andric         // subsequent calls to getUnwindDestToken, so map the cleanuppad
700dadbdfffSDimitry Andric         // to short-circuit any such calls and recognize this as an "unwind
701dadbdfffSDimitry Andric         // to caller" cleanup.
702dadbdfffSDimitry Andric         assert(!FuncletUnwindMap.count(CleanupPad) ||
703dadbdfffSDimitry Andric                isa<ConstantTokenNone>(FuncletUnwindMap[CleanupPad]));
704dadbdfffSDimitry Andric         FuncletUnwindMap[CleanupPad] =
705dadbdfffSDimitry Andric             ConstantTokenNone::get(Caller->getContext());
706dd58ef01SDimitry Andric       }
707dd58ef01SDimitry Andric     }
708dd58ef01SDimitry Andric 
709dd58ef01SDimitry Andric     Instruction *I = BB->getFirstNonPHI();
710dd58ef01SDimitry Andric     if (!I->isEHPad())
711dd58ef01SDimitry Andric       continue;
712dd58ef01SDimitry Andric 
713dd58ef01SDimitry Andric     Instruction *Replacement = nullptr;
714dd58ef01SDimitry Andric     if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(I)) {
715dd58ef01SDimitry Andric       if (CatchSwitch->unwindsToCaller()) {
716dadbdfffSDimitry Andric         Value *UnwindDestToken;
717dadbdfffSDimitry Andric         if (auto *ParentPad =
718dadbdfffSDimitry Andric                 dyn_cast<Instruction>(CatchSwitch->getParentPad())) {
719dadbdfffSDimitry Andric           // This catchswitch is nested inside another funclet.  If that
720dadbdfffSDimitry Andric           // funclet has an unwind destination within the inlinee, then
721dadbdfffSDimitry Andric           // unwinding out of this catchswitch would be UB.  Rewriting this
722dadbdfffSDimitry Andric           // catchswitch to unwind to the inlined invoke's unwind dest would
723dadbdfffSDimitry Andric           // give the parent funclet multiple unwind destinations, which is
724dadbdfffSDimitry Andric           // something that subsequent EH table generation can't handle and
725dadbdfffSDimitry Andric           // that the veirifer rejects.  So when we see such a call, leave it
726dadbdfffSDimitry Andric           // as "unwind to caller".
727dadbdfffSDimitry Andric           UnwindDestToken = getUnwindDestToken(ParentPad, FuncletUnwindMap);
728dadbdfffSDimitry Andric           if (UnwindDestToken && !isa<ConstantTokenNone>(UnwindDestToken))
729dadbdfffSDimitry Andric             continue;
730dadbdfffSDimitry Andric         } else {
731dadbdfffSDimitry Andric           // This catchswitch has no parent to inherit constraints from, and
732dadbdfffSDimitry Andric           // none of its descendants can have an unwind edge that exits it and
733dadbdfffSDimitry Andric           // targets another funclet in the inlinee.  It may or may not have a
734dadbdfffSDimitry Andric           // descendant that definitively has an unwind to caller.  In either
735dadbdfffSDimitry Andric           // case, we'll have to assume that any unwinds out of it may need to
736dadbdfffSDimitry Andric           // be routed to the caller, so treat it as though it has a definitive
737dadbdfffSDimitry Andric           // unwind to caller.
738dadbdfffSDimitry Andric           UnwindDestToken = ConstantTokenNone::get(Caller->getContext());
739dadbdfffSDimitry Andric         }
740dd58ef01SDimitry Andric         auto *NewCatchSwitch = CatchSwitchInst::Create(
741dd58ef01SDimitry Andric             CatchSwitch->getParentPad(), UnwindDest,
742dd58ef01SDimitry Andric             CatchSwitch->getNumHandlers(), CatchSwitch->getName(),
743ac9a064cSDimitry Andric             CatchSwitch->getIterator());
744dd58ef01SDimitry Andric         for (BasicBlock *PadBB : CatchSwitch->handlers())
745dd58ef01SDimitry Andric           NewCatchSwitch->addHandler(PadBB);
746dadbdfffSDimitry Andric         // Propagate info for the old catchswitch over to the new one in
747dadbdfffSDimitry Andric         // the unwind map.  This also serves to short-circuit any subsequent
748dadbdfffSDimitry Andric         // checks for the unwind dest of this catchswitch, which would get
749dadbdfffSDimitry Andric         // confused if they found the outer handler in the callee.
750dadbdfffSDimitry Andric         FuncletUnwindMap[NewCatchSwitch] = UnwindDestToken;
751dd58ef01SDimitry Andric         Replacement = NewCatchSwitch;
752dd58ef01SDimitry Andric       }
753dd58ef01SDimitry Andric     } else if (!isa<FuncletPadInst>(I)) {
754dd58ef01SDimitry Andric       llvm_unreachable("unexpected EHPad!");
755dd58ef01SDimitry Andric     }
756dd58ef01SDimitry Andric 
757dd58ef01SDimitry Andric     if (Replacement) {
758dd58ef01SDimitry Andric       Replacement->takeName(I);
759dd58ef01SDimitry Andric       I->replaceAllUsesWith(Replacement);
760dd58ef01SDimitry Andric       I->eraseFromParent();
761dd58ef01SDimitry Andric       UpdatePHINodes(&*BB);
762dd58ef01SDimitry Andric     }
763dd58ef01SDimitry Andric   }
764dd58ef01SDimitry Andric 
765dd58ef01SDimitry Andric   if (InlinedCodeInfo.ContainsCalls)
766dd58ef01SDimitry Andric     for (Function::iterator BB = FirstNewBlock->getIterator(),
767dd58ef01SDimitry Andric                             E = Caller->end();
768dd58ef01SDimitry Andric          BB != E; ++BB)
769dadbdfffSDimitry Andric       if (BasicBlock *NewBB = HandleCallsInBlockInlinedThroughInvoke(
770dadbdfffSDimitry Andric               &*BB, UnwindDest, &FuncletUnwindMap))
771dd58ef01SDimitry Andric         // Update any PHI nodes in the exceptional block to indicate that there
772dd58ef01SDimitry Andric         // is now a new entry in them.
773dd58ef01SDimitry Andric         UpdatePHINodes(NewBB);
774dd58ef01SDimitry Andric 
775dd58ef01SDimitry Andric   // Now that everything is happy, we have one final detail.  The PHI nodes in
776dd58ef01SDimitry Andric   // the exception destination block still have entries due to the original
777dd58ef01SDimitry Andric   // invoke instruction. Eliminate these entries (which might even delete the
778dd58ef01SDimitry Andric   // PHI node) now.
779dd58ef01SDimitry Andric   UnwindDest->removePredecessor(InvokeBB);
780dd58ef01SDimitry Andric }
781dd58ef01SDimitry Andric 
haveCommonPrefix(MDNode * MIBStackContext,MDNode * CallsiteStackContext)782e3b55780SDimitry Andric static bool haveCommonPrefix(MDNode *MIBStackContext,
783e3b55780SDimitry Andric                              MDNode *CallsiteStackContext) {
784e3b55780SDimitry Andric   assert(MIBStackContext->getNumOperands() > 0 &&
785e3b55780SDimitry Andric          CallsiteStackContext->getNumOperands() > 0);
786e3b55780SDimitry Andric   // Because of the context trimming performed during matching, the callsite
787e3b55780SDimitry Andric   // context could have more stack ids than the MIB. We match up to the end of
788e3b55780SDimitry Andric   // the shortest stack context.
789e3b55780SDimitry Andric   for (auto MIBStackIter = MIBStackContext->op_begin(),
790e3b55780SDimitry Andric             CallsiteStackIter = CallsiteStackContext->op_begin();
791e3b55780SDimitry Andric        MIBStackIter != MIBStackContext->op_end() &&
792e3b55780SDimitry Andric        CallsiteStackIter != CallsiteStackContext->op_end();
793e3b55780SDimitry Andric        MIBStackIter++, CallsiteStackIter++) {
794e3b55780SDimitry Andric     auto *Val1 = mdconst::dyn_extract<ConstantInt>(*MIBStackIter);
795e3b55780SDimitry Andric     auto *Val2 = mdconst::dyn_extract<ConstantInt>(*CallsiteStackIter);
796e3b55780SDimitry Andric     assert(Val1 && Val2);
797e3b55780SDimitry Andric     if (Val1->getZExtValue() != Val2->getZExtValue())
798e3b55780SDimitry Andric       return false;
799e3b55780SDimitry Andric   }
800e3b55780SDimitry Andric   return true;
801e3b55780SDimitry Andric }
802e3b55780SDimitry Andric 
removeMemProfMetadata(CallBase * Call)803e3b55780SDimitry Andric static void removeMemProfMetadata(CallBase *Call) {
804e3b55780SDimitry Andric   Call->setMetadata(LLVMContext::MD_memprof, nullptr);
805e3b55780SDimitry Andric }
806e3b55780SDimitry Andric 
removeCallsiteMetadata(CallBase * Call)807e3b55780SDimitry Andric static void removeCallsiteMetadata(CallBase *Call) {
808e3b55780SDimitry Andric   Call->setMetadata(LLVMContext::MD_callsite, nullptr);
809e3b55780SDimitry Andric }
810e3b55780SDimitry Andric 
updateMemprofMetadata(CallBase * CI,const std::vector<Metadata * > & MIBList)811e3b55780SDimitry Andric static void updateMemprofMetadata(CallBase *CI,
812e3b55780SDimitry Andric                                   const std::vector<Metadata *> &MIBList) {
813e3b55780SDimitry Andric   assert(!MIBList.empty());
814e3b55780SDimitry Andric   // Remove existing memprof, which will either be replaced or may not be needed
815e3b55780SDimitry Andric   // if we are able to use a single allocation type function attribute.
816e3b55780SDimitry Andric   removeMemProfMetadata(CI);
817e3b55780SDimitry Andric   CallStackTrie CallStack;
818e3b55780SDimitry Andric   for (Metadata *MIB : MIBList)
819e3b55780SDimitry Andric     CallStack.addCallStack(cast<MDNode>(MIB));
820e3b55780SDimitry Andric   bool MemprofMDAttached = CallStack.buildAndAttachMIBMetadata(CI);
821e3b55780SDimitry Andric   assert(MemprofMDAttached == CI->hasMetadata(LLVMContext::MD_memprof));
822e3b55780SDimitry Andric   if (!MemprofMDAttached)
823e3b55780SDimitry Andric     // If we used a function attribute remove the callsite metadata as well.
824e3b55780SDimitry Andric     removeCallsiteMetadata(CI);
825e3b55780SDimitry Andric }
826e3b55780SDimitry Andric 
827e3b55780SDimitry Andric // Update the metadata on the inlined copy ClonedCall of a call OrigCall in the
828e3b55780SDimitry Andric // inlined callee body, based on the callsite metadata InlinedCallsiteMD from
829e3b55780SDimitry Andric // the call that was inlined.
propagateMemProfHelper(const CallBase * OrigCall,CallBase * ClonedCall,MDNode * InlinedCallsiteMD)830e3b55780SDimitry Andric static void propagateMemProfHelper(const CallBase *OrigCall,
831e3b55780SDimitry Andric                                    CallBase *ClonedCall,
832e3b55780SDimitry Andric                                    MDNode *InlinedCallsiteMD) {
833e3b55780SDimitry Andric   MDNode *OrigCallsiteMD = ClonedCall->getMetadata(LLVMContext::MD_callsite);
834e3b55780SDimitry Andric   MDNode *ClonedCallsiteMD = nullptr;
835e3b55780SDimitry Andric   // Check if the call originally had callsite metadata, and update it for the
836e3b55780SDimitry Andric   // new call in the inlined body.
837e3b55780SDimitry Andric   if (OrigCallsiteMD) {
838e3b55780SDimitry Andric     // The cloned call's context is now the concatenation of the original call's
839e3b55780SDimitry Andric     // callsite metadata and the callsite metadata on the call where it was
840e3b55780SDimitry Andric     // inlined.
841e3b55780SDimitry Andric     ClonedCallsiteMD = MDNode::concatenate(OrigCallsiteMD, InlinedCallsiteMD);
842e3b55780SDimitry Andric     ClonedCall->setMetadata(LLVMContext::MD_callsite, ClonedCallsiteMD);
843e3b55780SDimitry Andric   }
844e3b55780SDimitry Andric 
845e3b55780SDimitry Andric   // Update any memprof metadata on the cloned call.
846e3b55780SDimitry Andric   MDNode *OrigMemProfMD = ClonedCall->getMetadata(LLVMContext::MD_memprof);
847e3b55780SDimitry Andric   if (!OrigMemProfMD)
848e3b55780SDimitry Andric     return;
849e3b55780SDimitry Andric   // We currently expect that allocations with memprof metadata also have
850e3b55780SDimitry Andric   // callsite metadata for the allocation's part of the context.
851e3b55780SDimitry Andric   assert(OrigCallsiteMD);
852e3b55780SDimitry Andric 
853e3b55780SDimitry Andric   // New call's MIB list.
854e3b55780SDimitry Andric   std::vector<Metadata *> NewMIBList;
855e3b55780SDimitry Andric 
856e3b55780SDimitry Andric   // For each MIB metadata, check if its call stack context starts with the
857e3b55780SDimitry Andric   // new clone's callsite metadata. If so, that MIB goes onto the cloned call in
858e3b55780SDimitry Andric   // the inlined body. If not, it stays on the out-of-line original call.
859e3b55780SDimitry Andric   for (auto &MIBOp : OrigMemProfMD->operands()) {
860e3b55780SDimitry Andric     MDNode *MIB = dyn_cast<MDNode>(MIBOp);
861e3b55780SDimitry Andric     // Stack is first operand of MIB.
862e3b55780SDimitry Andric     MDNode *StackMD = getMIBStackNode(MIB);
863e3b55780SDimitry Andric     assert(StackMD);
864e3b55780SDimitry Andric     // See if the new cloned callsite context matches this profiled context.
865e3b55780SDimitry Andric     if (haveCommonPrefix(StackMD, ClonedCallsiteMD))
866e3b55780SDimitry Andric       // Add it to the cloned call's MIB list.
867e3b55780SDimitry Andric       NewMIBList.push_back(MIB);
868e3b55780SDimitry Andric   }
869e3b55780SDimitry Andric   if (NewMIBList.empty()) {
870e3b55780SDimitry Andric     removeMemProfMetadata(ClonedCall);
871e3b55780SDimitry Andric     removeCallsiteMetadata(ClonedCall);
872e3b55780SDimitry Andric     return;
873e3b55780SDimitry Andric   }
874e3b55780SDimitry Andric   if (NewMIBList.size() < OrigMemProfMD->getNumOperands())
875e3b55780SDimitry Andric     updateMemprofMetadata(ClonedCall, NewMIBList);
876e3b55780SDimitry Andric }
877e3b55780SDimitry Andric 
878e3b55780SDimitry Andric // Update memprof related metadata (!memprof and !callsite) based on the
879e3b55780SDimitry Andric // inlining of Callee into the callsite at CB. The updates include merging the
880e3b55780SDimitry Andric // inlined callee's callsite metadata with that of the inlined call,
881e3b55780SDimitry Andric // and moving the subset of any memprof contexts to the inlined callee
882e3b55780SDimitry Andric // allocations if they match the new inlined call stack.
883e3b55780SDimitry Andric static void
propagateMemProfMetadata(Function * Callee,CallBase & CB,bool ContainsMemProfMetadata,const ValueMap<const Value *,WeakTrackingVH> & VMap)884e3b55780SDimitry Andric propagateMemProfMetadata(Function *Callee, CallBase &CB,
885e3b55780SDimitry Andric                          bool ContainsMemProfMetadata,
886e3b55780SDimitry Andric                          const ValueMap<const Value *, WeakTrackingVH> &VMap) {
887e3b55780SDimitry Andric   MDNode *CallsiteMD = CB.getMetadata(LLVMContext::MD_callsite);
888e3b55780SDimitry Andric   // Only need to update if the inlined callsite had callsite metadata, or if
889e3b55780SDimitry Andric   // there was any memprof metadata inlined.
890e3b55780SDimitry Andric   if (!CallsiteMD && !ContainsMemProfMetadata)
891e3b55780SDimitry Andric     return;
892e3b55780SDimitry Andric 
893e3b55780SDimitry Andric   // Propagate metadata onto the cloned calls in the inlined callee.
894e3b55780SDimitry Andric   for (const auto &Entry : VMap) {
895e3b55780SDimitry Andric     // See if this is a call that has been inlined and remapped, and not
896e3b55780SDimitry Andric     // simplified away in the process.
897e3b55780SDimitry Andric     auto *OrigCall = dyn_cast_or_null<CallBase>(Entry.first);
898e3b55780SDimitry Andric     auto *ClonedCall = dyn_cast_or_null<CallBase>(Entry.second);
899e3b55780SDimitry Andric     if (!OrigCall || !ClonedCall)
900e3b55780SDimitry Andric       continue;
901e3b55780SDimitry Andric     // If the inlined callsite did not have any callsite metadata, then it isn't
902e3b55780SDimitry Andric     // involved in any profiled call contexts, and we can remove any memprof
903e3b55780SDimitry Andric     // metadata on the cloned call.
904e3b55780SDimitry Andric     if (!CallsiteMD) {
905e3b55780SDimitry Andric       removeMemProfMetadata(ClonedCall);
906e3b55780SDimitry Andric       removeCallsiteMetadata(ClonedCall);
907e3b55780SDimitry Andric       continue;
908e3b55780SDimitry Andric     }
909e3b55780SDimitry Andric     propagateMemProfHelper(OrigCall, ClonedCall, CallsiteMD);
910e3b55780SDimitry Andric   }
911e3b55780SDimitry Andric }
912e3b55780SDimitry Andric 
913b60736ecSDimitry Andric /// When inlining a call site that has !llvm.mem.parallel_loop_access,
914b60736ecSDimitry Andric /// !llvm.access.group, !alias.scope or !noalias metadata, that metadata should
915b60736ecSDimitry Andric /// be propagated to all memory-accessing cloned instructions.
PropagateCallSiteMetadata(CallBase & CB,Function::iterator FStart,Function::iterator FEnd)916344a3780SDimitry Andric static void PropagateCallSiteMetadata(CallBase &CB, Function::iterator FStart,
917344a3780SDimitry Andric                                       Function::iterator FEnd) {
918b60736ecSDimitry Andric   MDNode *MemParallelLoopAccess =
919b60736ecSDimitry Andric       CB.getMetadata(LLVMContext::MD_mem_parallel_loop_access);
920b60736ecSDimitry Andric   MDNode *AccessGroup = CB.getMetadata(LLVMContext::MD_access_group);
921b60736ecSDimitry Andric   MDNode *AliasScope = CB.getMetadata(LLVMContext::MD_alias_scope);
922b60736ecSDimitry Andric   MDNode *NoAlias = CB.getMetadata(LLVMContext::MD_noalias);
923b60736ecSDimitry Andric   if (!MemParallelLoopAccess && !AccessGroup && !AliasScope && !NoAlias)
92401095a5dSDimitry Andric     return;
92501095a5dSDimitry Andric 
926344a3780SDimitry Andric   for (BasicBlock &BB : make_range(FStart, FEnd)) {
927344a3780SDimitry Andric     for (Instruction &I : BB) {
928b60736ecSDimitry Andric       // This metadata is only relevant for instructions that access memory.
929344a3780SDimitry Andric       if (!I.mayReadOrWriteMemory())
930b60736ecSDimitry Andric         continue;
931b60736ecSDimitry Andric 
932b60736ecSDimitry Andric       if (MemParallelLoopAccess) {
933b60736ecSDimitry Andric         // TODO: This probably should not overwrite MemParalleLoopAccess.
934b60736ecSDimitry Andric         MemParallelLoopAccess = MDNode::concatenate(
935344a3780SDimitry Andric             I.getMetadata(LLVMContext::MD_mem_parallel_loop_access),
936b60736ecSDimitry Andric             MemParallelLoopAccess);
937344a3780SDimitry Andric         I.setMetadata(LLVMContext::MD_mem_parallel_loop_access,
938b60736ecSDimitry Andric                       MemParallelLoopAccess);
939b60736ecSDimitry Andric       }
940b60736ecSDimitry Andric 
941b60736ecSDimitry Andric       if (AccessGroup)
942344a3780SDimitry Andric         I.setMetadata(LLVMContext::MD_access_group, uniteAccessGroups(
943344a3780SDimitry Andric             I.getMetadata(LLVMContext::MD_access_group), AccessGroup));
944b60736ecSDimitry Andric 
945b60736ecSDimitry Andric       if (AliasScope)
946344a3780SDimitry Andric         I.setMetadata(LLVMContext::MD_alias_scope, MDNode::concatenate(
947344a3780SDimitry Andric             I.getMetadata(LLVMContext::MD_alias_scope), AliasScope));
948b60736ecSDimitry Andric 
949b60736ecSDimitry Andric       if (NoAlias)
950344a3780SDimitry Andric         I.setMetadata(LLVMContext::MD_noalias, MDNode::concatenate(
951344a3780SDimitry Andric             I.getMetadata(LLVMContext::MD_noalias), NoAlias));
952344a3780SDimitry Andric     }
95301095a5dSDimitry Andric   }
95401095a5dSDimitry Andric }
955d8e91e46SDimitry Andric 
95608e8dd7bSDimitry Andric /// Bundle operands of the inlined function must be added to inlined call sites.
PropagateOperandBundles(Function::iterator InlinedBB,Instruction * CallSiteEHPad)95708e8dd7bSDimitry Andric static void PropagateOperandBundles(Function::iterator InlinedBB,
95808e8dd7bSDimitry Andric                                     Instruction *CallSiteEHPad) {
95908e8dd7bSDimitry Andric   for (Instruction &II : llvm::make_early_inc_range(*InlinedBB)) {
96008e8dd7bSDimitry Andric     CallBase *I = dyn_cast<CallBase>(&II);
96108e8dd7bSDimitry Andric     if (!I)
96208e8dd7bSDimitry Andric       continue;
96308e8dd7bSDimitry Andric     // Skip call sites which already have a "funclet" bundle.
96408e8dd7bSDimitry Andric     if (I->getOperandBundle(LLVMContext::OB_funclet))
96508e8dd7bSDimitry Andric       continue;
96608e8dd7bSDimitry Andric     // Skip call sites which are nounwind intrinsics (as long as they don't
96708e8dd7bSDimitry Andric     // lower into regular function calls in the course of IR transformations).
96808e8dd7bSDimitry Andric     auto *CalledFn =
96908e8dd7bSDimitry Andric         dyn_cast<Function>(I->getCalledOperand()->stripPointerCasts());
97008e8dd7bSDimitry Andric     if (CalledFn && CalledFn->isIntrinsic() && I->doesNotThrow() &&
97108e8dd7bSDimitry Andric         !IntrinsicInst::mayLowerToFunctionCall(CalledFn->getIntrinsicID()))
97208e8dd7bSDimitry Andric       continue;
97308e8dd7bSDimitry Andric 
97408e8dd7bSDimitry Andric     SmallVector<OperandBundleDef, 1> OpBundles;
97508e8dd7bSDimitry Andric     I->getOperandBundlesAsDefs(OpBundles);
97608e8dd7bSDimitry Andric     OpBundles.emplace_back("funclet", CallSiteEHPad);
97708e8dd7bSDimitry Andric 
978ac9a064cSDimitry Andric     Instruction *NewInst = CallBase::Create(I, OpBundles, I->getIterator());
97908e8dd7bSDimitry Andric     NewInst->takeName(I);
98008e8dd7bSDimitry Andric     I->replaceAllUsesWith(NewInst);
98108e8dd7bSDimitry Andric     I->eraseFromParent();
98208e8dd7bSDimitry Andric   }
98308e8dd7bSDimitry Andric }
98408e8dd7bSDimitry Andric 
985c0981da4SDimitry Andric namespace {
986b60736ecSDimitry Andric /// Utility for cloning !noalias and !alias.scope metadata. When a code region
987b60736ecSDimitry Andric /// using scoped alias metadata is inlined, the aliasing relationships may not
988b60736ecSDimitry Andric /// hold between the two version. It is necessary to create a deep clone of the
989b60736ecSDimitry Andric /// metadata, putting the two versions in separate scope domains.
990b60736ecSDimitry Andric class ScopedAliasMetadataDeepCloner {
991b60736ecSDimitry Andric   using MetadataMap = DenseMap<const MDNode *, TrackingMDNodeRef>;
99267c32a98SDimitry Andric   SetVector<const MDNode *> MD;
993b60736ecSDimitry Andric   MetadataMap MDMap;
994b60736ecSDimitry Andric   void addRecursiveMetadataUses();
99567c32a98SDimitry Andric 
996b60736ecSDimitry Andric public:
997b60736ecSDimitry Andric   ScopedAliasMetadataDeepCloner(const Function *F);
99867c32a98SDimitry Andric 
999b60736ecSDimitry Andric   /// Create a new clone of the scoped alias metadata, which will be used by
1000b60736ecSDimitry Andric   /// subsequent remap() calls.
1001b60736ecSDimitry Andric   void clone();
1002b60736ecSDimitry Andric 
1003344a3780SDimitry Andric   /// Remap instructions in the given range from the original to the cloned
1004b60736ecSDimitry Andric   /// metadata.
1005344a3780SDimitry Andric   void remap(Function::iterator FStart, Function::iterator FEnd);
1006b60736ecSDimitry Andric };
1007c0981da4SDimitry Andric } // namespace
1008b60736ecSDimitry Andric 
ScopedAliasMetadataDeepCloner(const Function * F)1009b60736ecSDimitry Andric ScopedAliasMetadataDeepCloner::ScopedAliasMetadataDeepCloner(
1010b60736ecSDimitry Andric     const Function *F) {
1011b60736ecSDimitry Andric   for (const BasicBlock &BB : *F) {
1012b60736ecSDimitry Andric     for (const Instruction &I : BB) {
1013b60736ecSDimitry Andric       if (const MDNode *M = I.getMetadata(LLVMContext::MD_alias_scope))
101467c32a98SDimitry Andric         MD.insert(M);
1015b60736ecSDimitry Andric       if (const MDNode *M = I.getMetadata(LLVMContext::MD_noalias))
101667c32a98SDimitry Andric         MD.insert(M);
1017b60736ecSDimitry Andric 
1018b60736ecSDimitry Andric       // We also need to clone the metadata in noalias intrinsics.
1019b60736ecSDimitry Andric       if (const auto *Decl = dyn_cast<NoAliasScopeDeclInst>(&I))
1020b60736ecSDimitry Andric         MD.insert(Decl->getScopeList());
1021b60736ecSDimitry Andric     }
1022b60736ecSDimitry Andric   }
1023b60736ecSDimitry Andric   addRecursiveMetadataUses();
102467c32a98SDimitry Andric }
102567c32a98SDimitry Andric 
addRecursiveMetadataUses()1026b60736ecSDimitry Andric void ScopedAliasMetadataDeepCloner::addRecursiveMetadataUses() {
102767c32a98SDimitry Andric   SmallVector<const Metadata *, 16> Queue(MD.begin(), MD.end());
102867c32a98SDimitry Andric   while (!Queue.empty()) {
102967c32a98SDimitry Andric     const MDNode *M = cast<MDNode>(Queue.pop_back_val());
1030b60736ecSDimitry Andric     for (const Metadata *Op : M->operands())
1031b60736ecSDimitry Andric       if (const MDNode *OpMD = dyn_cast<MDNode>(Op))
1032b60736ecSDimitry Andric         if (MD.insert(OpMD))
1033b60736ecSDimitry Andric           Queue.push_back(OpMD);
1034b60736ecSDimitry Andric   }
103567c32a98SDimitry Andric }
103667c32a98SDimitry Andric 
clone()1037b60736ecSDimitry Andric void ScopedAliasMetadataDeepCloner::clone() {
1038b60736ecSDimitry Andric   assert(MDMap.empty() && "clone() already called ?");
1039b60736ecSDimitry Andric 
10405a5ac124SDimitry Andric   SmallVector<TempMDTuple, 16> DummyNodes;
104101095a5dSDimitry Andric   for (const MDNode *I : MD) {
1042e3b55780SDimitry Andric     DummyNodes.push_back(MDTuple::getTemporary(I->getContext(), std::nullopt));
104301095a5dSDimitry Andric     MDMap[I].reset(DummyNodes.back().get());
104467c32a98SDimitry Andric   }
104567c32a98SDimitry Andric 
104667c32a98SDimitry Andric   // Create new metadata nodes to replace the dummy nodes, replacing old
104767c32a98SDimitry Andric   // metadata references with either a dummy node or an already-created new
104867c32a98SDimitry Andric   // node.
104967c32a98SDimitry Andric   SmallVector<Metadata *, 4> NewOps;
1050b60736ecSDimitry Andric   for (const MDNode *I : MD) {
1051b60736ecSDimitry Andric     for (const Metadata *Op : I->operands()) {
1052b60736ecSDimitry Andric       if (const MDNode *M = dyn_cast<MDNode>(Op))
105367c32a98SDimitry Andric         NewOps.push_back(MDMap[M]);
105467c32a98SDimitry Andric       else
1055b60736ecSDimitry Andric         NewOps.push_back(const_cast<Metadata *>(Op));
105667c32a98SDimitry Andric     }
105767c32a98SDimitry Andric 
1058b60736ecSDimitry Andric     MDNode *NewM = MDNode::get(I->getContext(), NewOps);
105901095a5dSDimitry Andric     MDTuple *TempM = cast<MDTuple>(MDMap[I]);
10605a5ac124SDimitry Andric     assert(TempM->isTemporary() && "Expected temporary node");
106167c32a98SDimitry Andric 
106267c32a98SDimitry Andric     TempM->replaceAllUsesWith(NewM);
1063b60736ecSDimitry Andric     NewOps.clear();
1064b60736ecSDimitry Andric   }
106567c32a98SDimitry Andric }
106667c32a98SDimitry Andric 
remap(Function::iterator FStart,Function::iterator FEnd)1067344a3780SDimitry Andric void ScopedAliasMetadataDeepCloner::remap(Function::iterator FStart,
1068344a3780SDimitry Andric                                           Function::iterator FEnd) {
1069b60736ecSDimitry Andric   if (MDMap.empty())
1070b60736ecSDimitry Andric     return; // Nothing to do.
1071b60736ecSDimitry Andric 
1072344a3780SDimitry Andric   for (BasicBlock &BB : make_range(FStart, FEnd)) {
1073344a3780SDimitry Andric     for (Instruction &I : BB) {
1074344a3780SDimitry Andric       // TODO: The null checks for the MDMap.lookup() results should no longer
1075344a3780SDimitry Andric       // be necessary.
1076344a3780SDimitry Andric       if (MDNode *M = I.getMetadata(LLVMContext::MD_alias_scope))
1077344a3780SDimitry Andric         if (MDNode *MNew = MDMap.lookup(M))
1078344a3780SDimitry Andric           I.setMetadata(LLVMContext::MD_alias_scope, MNew);
107967c32a98SDimitry Andric 
1080344a3780SDimitry Andric       if (MDNode *M = I.getMetadata(LLVMContext::MD_noalias))
1081344a3780SDimitry Andric         if (MDNode *MNew = MDMap.lookup(M))
1082344a3780SDimitry Andric           I.setMetadata(LLVMContext::MD_noalias, MNew);
108367c32a98SDimitry Andric 
1084344a3780SDimitry Andric       if (auto *Decl = dyn_cast<NoAliasScopeDeclInst>(&I))
1085344a3780SDimitry Andric         if (MDNode *MNew = MDMap.lookup(Decl->getScopeList()))
1086344a3780SDimitry Andric           Decl->setScopeList(MNew);
1087344a3780SDimitry Andric     }
108867c32a98SDimitry Andric   }
108967c32a98SDimitry Andric }
109067c32a98SDimitry Andric 
10915a5ac124SDimitry Andric /// If the inlined function has noalias arguments,
10925a5ac124SDimitry Andric /// then add new alias scopes for each noalias argument, tag the mapped noalias
109367c32a98SDimitry Andric /// parameters with noalias metadata specifying the new scope, and tag all
109467c32a98SDimitry Andric /// non-derived loads, stores and memory intrinsics with the new alias scopes.
AddAliasScopeMetadata(CallBase & CB,ValueToValueMapTy & VMap,const DataLayout & DL,AAResults * CalleeAAR,ClonedCodeInfo & InlinedFunctionInfo)1095cfca06d7SDimitry Andric static void AddAliasScopeMetadata(CallBase &CB, ValueToValueMapTy &VMap,
1096344a3780SDimitry Andric                                   const DataLayout &DL, AAResults *CalleeAAR,
1097344a3780SDimitry Andric                                   ClonedCodeInfo &InlinedFunctionInfo) {
109867c32a98SDimitry Andric   if (!EnableNoAliasConversion)
109967c32a98SDimitry Andric     return;
110067c32a98SDimitry Andric 
1101cfca06d7SDimitry Andric   const Function *CalledFunc = CB.getCalledFunction();
110267c32a98SDimitry Andric   SmallVector<const Argument *, 4> NoAliasArgs;
110367c32a98SDimitry Andric 
110401095a5dSDimitry Andric   for (const Argument &Arg : CalledFunc->args())
1105cfca06d7SDimitry Andric     if (CB.paramHasAttr(Arg.getArgNo(), Attribute::NoAlias) && !Arg.use_empty())
110601095a5dSDimitry Andric       NoAliasArgs.push_back(&Arg);
110767c32a98SDimitry Andric 
110867c32a98SDimitry Andric   if (NoAliasArgs.empty())
110967c32a98SDimitry Andric     return;
111067c32a98SDimitry Andric 
111167c32a98SDimitry Andric   // To do a good job, if a noalias variable is captured, we need to know if
111267c32a98SDimitry Andric   // the capture point dominates the particular use we're considering.
111367c32a98SDimitry Andric   DominatorTree DT;
111467c32a98SDimitry Andric   DT.recalculate(const_cast<Function&>(*CalledFunc));
111567c32a98SDimitry Andric 
111667c32a98SDimitry Andric   // noalias indicates that pointer values based on the argument do not alias
111767c32a98SDimitry Andric   // pointer values which are not based on it. So we add a new "scope" for each
111867c32a98SDimitry Andric   // noalias function argument. Accesses using pointers based on that argument
111967c32a98SDimitry Andric   // become part of that alias scope, accesses using pointers not based on that
112067c32a98SDimitry Andric   // argument are tagged as noalias with that scope.
112167c32a98SDimitry Andric 
112267c32a98SDimitry Andric   DenseMap<const Argument *, MDNode *> NewScopes;
112367c32a98SDimitry Andric   MDBuilder MDB(CalledFunc->getContext());
112467c32a98SDimitry Andric 
112567c32a98SDimitry Andric   // Create a new scope domain for this function.
112667c32a98SDimitry Andric   MDNode *NewDomain =
112767c32a98SDimitry Andric     MDB.createAnonymousAliasScopeDomain(CalledFunc->getName());
112867c32a98SDimitry Andric   for (unsigned i = 0, e = NoAliasArgs.size(); i != e; ++i) {
112967c32a98SDimitry Andric     const Argument *A = NoAliasArgs[i];
113067c32a98SDimitry Andric 
1131cfca06d7SDimitry Andric     std::string Name = std::string(CalledFunc->getName());
113267c32a98SDimitry Andric     if (A->hasName()) {
113367c32a98SDimitry Andric       Name += ": %";
113467c32a98SDimitry Andric       Name += A->getName();
113567c32a98SDimitry Andric     } else {
113667c32a98SDimitry Andric       Name += ": argument ";
113767c32a98SDimitry Andric       Name += utostr(i);
113867c32a98SDimitry Andric     }
113967c32a98SDimitry Andric 
114067c32a98SDimitry Andric     // Note: We always create a new anonymous root here. This is true regardless
114167c32a98SDimitry Andric     // of the linkage of the callee because the aliasing "scope" is not just a
114267c32a98SDimitry Andric     // property of the callee, but also all control dependencies in the caller.
114367c32a98SDimitry Andric     MDNode *NewScope = MDB.createAnonymousAliasScope(NewDomain, Name);
114467c32a98SDimitry Andric     NewScopes.insert(std::make_pair(A, NewScope));
1145b60736ecSDimitry Andric 
1146b60736ecSDimitry Andric     if (UseNoAliasIntrinsic) {
1147b60736ecSDimitry Andric       // Introduce a llvm.experimental.noalias.scope.decl for the noalias
1148b60736ecSDimitry Andric       // argument.
1149b60736ecSDimitry Andric       MDNode *AScopeList = MDNode::get(CalledFunc->getContext(), NewScope);
1150b60736ecSDimitry Andric       auto *NoAliasDecl =
1151b60736ecSDimitry Andric           IRBuilder<>(&CB).CreateNoAliasScopeDeclaration(AScopeList);
1152b60736ecSDimitry Andric       // Ignore the result for now. The result will be used when the
1153b60736ecSDimitry Andric       // llvm.noalias intrinsic is introduced.
1154b60736ecSDimitry Andric       (void)NoAliasDecl;
1155b60736ecSDimitry Andric     }
115667c32a98SDimitry Andric   }
115767c32a98SDimitry Andric 
115867c32a98SDimitry Andric   // Iterate over all new instructions in the map; for all memory-access
115967c32a98SDimitry Andric   // instructions, add the alias scope metadata.
116067c32a98SDimitry Andric   for (ValueToValueMapTy::iterator VMI = VMap.begin(), VMIE = VMap.end();
116167c32a98SDimitry Andric        VMI != VMIE; ++VMI) {
116267c32a98SDimitry Andric     if (const Instruction *I = dyn_cast<Instruction>(VMI->first)) {
116367c32a98SDimitry Andric       if (!VMI->second)
116467c32a98SDimitry Andric         continue;
116567c32a98SDimitry Andric 
116667c32a98SDimitry Andric       Instruction *NI = dyn_cast<Instruction>(VMI->second);
1167344a3780SDimitry Andric       if (!NI || InlinedFunctionInfo.isSimplified(I, NI))
116867c32a98SDimitry Andric         continue;
116967c32a98SDimitry Andric 
117067c32a98SDimitry Andric       bool IsArgMemOnlyCall = false, IsFuncCall = false;
117167c32a98SDimitry Andric       SmallVector<const Value *, 2> PtrArgs;
117267c32a98SDimitry Andric 
117367c32a98SDimitry Andric       if (const LoadInst *LI = dyn_cast<LoadInst>(I))
117467c32a98SDimitry Andric         PtrArgs.push_back(LI->getPointerOperand());
117567c32a98SDimitry Andric       else if (const StoreInst *SI = dyn_cast<StoreInst>(I))
117667c32a98SDimitry Andric         PtrArgs.push_back(SI->getPointerOperand());
117767c32a98SDimitry Andric       else if (const VAArgInst *VAAI = dyn_cast<VAArgInst>(I))
117867c32a98SDimitry Andric         PtrArgs.push_back(VAAI->getPointerOperand());
117967c32a98SDimitry Andric       else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I))
118067c32a98SDimitry Andric         PtrArgs.push_back(CXI->getPointerOperand());
118167c32a98SDimitry Andric       else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I))
118267c32a98SDimitry Andric         PtrArgs.push_back(RMWI->getPointerOperand());
1183d8e91e46SDimitry Andric       else if (const auto *Call = dyn_cast<CallBase>(I)) {
118467c32a98SDimitry Andric         // If we know that the call does not access memory, then we'll still
118567c32a98SDimitry Andric         // know that about the inlined clone of this call site, and we don't
118667c32a98SDimitry Andric         // need to add metadata.
1187d8e91e46SDimitry Andric         if (Call->doesNotAccessMemory())
118867c32a98SDimitry Andric           continue;
118967c32a98SDimitry Andric 
119067c32a98SDimitry Andric         IsFuncCall = true;
1191dd58ef01SDimitry Andric         if (CalleeAAR) {
1192e3b55780SDimitry Andric           MemoryEffects ME = CalleeAAR->getMemoryEffects(Call);
1193344a3780SDimitry Andric 
1194344a3780SDimitry Andric           // We'll retain this knowledge without additional metadata.
1195e3b55780SDimitry Andric           if (ME.onlyAccessesInaccessibleMem())
1196344a3780SDimitry Andric             continue;
1197344a3780SDimitry Andric 
1198e3b55780SDimitry Andric           if (ME.onlyAccessesArgPointees())
119967c32a98SDimitry Andric             IsArgMemOnlyCall = true;
120067c32a98SDimitry Andric         }
120167c32a98SDimitry Andric 
1202d8e91e46SDimitry Andric         for (Value *Arg : Call->args()) {
1203145449b1SDimitry Andric           // Only care about pointer arguments. If a noalias argument is
1204145449b1SDimitry Andric           // accessed through a non-pointer argument, it must be captured
1205145449b1SDimitry Andric           // first (e.g. via ptrtoint), and we protect against captures below.
1206145449b1SDimitry Andric           if (!Arg->getType()->isPointerTy())
120767c32a98SDimitry Andric             continue;
120867c32a98SDimitry Andric 
120901095a5dSDimitry Andric           PtrArgs.push_back(Arg);
121067c32a98SDimitry Andric         }
121167c32a98SDimitry Andric       }
121267c32a98SDimitry Andric 
121367c32a98SDimitry Andric       // If we found no pointers, then this instruction is not suitable for
121467c32a98SDimitry Andric       // pairing with an instruction to receive aliasing metadata.
121567c32a98SDimitry Andric       // However, if this is a call, this we might just alias with none of the
121667c32a98SDimitry Andric       // noalias arguments.
121767c32a98SDimitry Andric       if (PtrArgs.empty() && !IsFuncCall)
121867c32a98SDimitry Andric         continue;
121967c32a98SDimitry Andric 
122067c32a98SDimitry Andric       // It is possible that there is only one underlying object, but you
122167c32a98SDimitry Andric       // need to go through several PHIs to see it, and thus could be
122267c32a98SDimitry Andric       // repeated in the Objects list.
122367c32a98SDimitry Andric       SmallPtrSet<const Value *, 4> ObjSet;
122467c32a98SDimitry Andric       SmallVector<Metadata *, 4> Scopes, NoAliases;
122567c32a98SDimitry Andric 
122601095a5dSDimitry Andric       for (const Value *V : PtrArgs) {
1227e6d15924SDimitry Andric         SmallVector<const Value *, 4> Objects;
1228b60736ecSDimitry Andric         getUnderlyingObjects(V, Objects, /* LI = */ nullptr);
122967c32a98SDimitry Andric 
1230e6d15924SDimitry Andric         for (const Value *O : Objects)
123167c32a98SDimitry Andric           ObjSet.insert(O);
123267c32a98SDimitry Andric       }
123367c32a98SDimitry Andric 
123467c32a98SDimitry Andric       // Figure out if we're derived from anything that is not a noalias
123567c32a98SDimitry Andric       // argument.
1236145449b1SDimitry Andric       bool RequiresNoCaptureBefore = false, UsesAliasingPtr = false,
1237145449b1SDimitry Andric            UsesUnknownObject = false;
123867c32a98SDimitry Andric       for (const Value *V : ObjSet) {
123967c32a98SDimitry Andric         // Is this value a constant that cannot be derived from any pointer
124067c32a98SDimitry Andric         // value (we need to exclude constant expressions, for example, that
124167c32a98SDimitry Andric         // are formed from arithmetic on global symbols).
124267c32a98SDimitry Andric         bool IsNonPtrConst = isa<ConstantInt>(V) || isa<ConstantFP>(V) ||
124367c32a98SDimitry Andric                              isa<ConstantPointerNull>(V) ||
124467c32a98SDimitry Andric                              isa<ConstantDataVector>(V) || isa<UndefValue>(V);
124567c32a98SDimitry Andric         if (IsNonPtrConst)
124667c32a98SDimitry Andric           continue;
124767c32a98SDimitry Andric 
124867c32a98SDimitry Andric         // If this is anything other than a noalias argument, then we cannot
124967c32a98SDimitry Andric         // completely describe the aliasing properties using alias.scope
125067c32a98SDimitry Andric         // metadata (and, thus, won't add any).
125167c32a98SDimitry Andric         if (const Argument *A = dyn_cast<Argument>(V)) {
1252cfca06d7SDimitry Andric           if (!CB.paramHasAttr(A->getArgNo(), Attribute::NoAlias))
125367c32a98SDimitry Andric             UsesAliasingPtr = true;
125467c32a98SDimitry Andric         } else {
125567c32a98SDimitry Andric           UsesAliasingPtr = true;
125667c32a98SDimitry Andric         }
125767c32a98SDimitry Andric 
1258145449b1SDimitry Andric         if (isEscapeSource(V)) {
1259145449b1SDimitry Andric           // An escape source can only alias with a noalias argument if it has
1260145449b1SDimitry Andric           // been captured beforehand.
1261145449b1SDimitry Andric           RequiresNoCaptureBefore = true;
1262145449b1SDimitry Andric         } else if (!isa<Argument>(V) && !isIdentifiedObject(V)) {
1263145449b1SDimitry Andric           // If this is neither an escape source, nor some identified object
1264145449b1SDimitry Andric           // (which cannot directly alias a noalias argument), nor some other
1265145449b1SDimitry Andric           // argument (which, by definition, also cannot alias a noalias
1266145449b1SDimitry Andric           // argument), conservatively do not make any assumptions.
1267145449b1SDimitry Andric           UsesUnknownObject = true;
126867c32a98SDimitry Andric         }
1269145449b1SDimitry Andric       }
1270145449b1SDimitry Andric 
1271145449b1SDimitry Andric       // Nothing we can do if the used underlying object cannot be reliably
1272145449b1SDimitry Andric       // determined.
1273145449b1SDimitry Andric       if (UsesUnknownObject)
1274145449b1SDimitry Andric         continue;
127567c32a98SDimitry Andric 
127667c32a98SDimitry Andric       // A function call can always get captured noalias pointers (via other
127767c32a98SDimitry Andric       // parameters, globals, etc.).
127867c32a98SDimitry Andric       if (IsFuncCall && !IsArgMemOnlyCall)
1279145449b1SDimitry Andric         RequiresNoCaptureBefore = true;
128067c32a98SDimitry Andric 
128167c32a98SDimitry Andric       // First, we want to figure out all of the sets with which we definitely
128267c32a98SDimitry Andric       // don't alias. Iterate over all noalias set, and add those for which:
128367c32a98SDimitry Andric       //   1. The noalias argument is not in the set of objects from which we
128467c32a98SDimitry Andric       //      definitely derive.
128567c32a98SDimitry Andric       //   2. The noalias argument has not yet been captured.
128667c32a98SDimitry Andric       // An arbitrary function that might load pointers could see captured
128767c32a98SDimitry Andric       // noalias arguments via other noalias arguments or globals, and so we
128867c32a98SDimitry Andric       // must always check for prior capture.
128967c32a98SDimitry Andric       for (const Argument *A : NoAliasArgs) {
1290145449b1SDimitry Andric         if (ObjSet.contains(A))
1291145449b1SDimitry Andric           continue; // May be based on a noalias argument.
1292145449b1SDimitry Andric 
1293145449b1SDimitry Andric         // It might be tempting to skip the PointerMayBeCapturedBefore check if
1294145449b1SDimitry Andric         // A->hasNoCaptureAttr() is true, but this is incorrect because
1295145449b1SDimitry Andric         // nocapture only guarantees that no copies outlive the function, not
129667c32a98SDimitry Andric         // that the value cannot be locally captured.
1297145449b1SDimitry Andric         if (!RequiresNoCaptureBefore ||
1298145449b1SDimitry Andric             !PointerMayBeCapturedBefore(A, /* ReturnCaptures */ false,
1299145449b1SDimitry Andric                                         /* StoreCaptures */ false, I, &DT))
130067c32a98SDimitry Andric           NoAliases.push_back(NewScopes[A]);
130167c32a98SDimitry Andric       }
130267c32a98SDimitry Andric 
130367c32a98SDimitry Andric       if (!NoAliases.empty())
130467c32a98SDimitry Andric         NI->setMetadata(LLVMContext::MD_noalias,
130567c32a98SDimitry Andric                         MDNode::concatenate(
130667c32a98SDimitry Andric                             NI->getMetadata(LLVMContext::MD_noalias),
130767c32a98SDimitry Andric                             MDNode::get(CalledFunc->getContext(), NoAliases)));
130867c32a98SDimitry Andric 
130967c32a98SDimitry Andric       // Next, we want to figure out all of the sets to which we might belong.
131067c32a98SDimitry Andric       // We might belong to a set if the noalias argument is in the set of
131167c32a98SDimitry Andric       // underlying objects. If there is some non-noalias argument in our list
131267c32a98SDimitry Andric       // of underlying objects, then we cannot add a scope because the fact
131367c32a98SDimitry Andric       // that some access does not alias with any set of our noalias arguments
131467c32a98SDimitry Andric       // cannot itself guarantee that it does not alias with this access
131567c32a98SDimitry Andric       // (because there is some pointer of unknown origin involved and the
131667c32a98SDimitry Andric       // other access might also depend on this pointer). We also cannot add
131767c32a98SDimitry Andric       // scopes to arbitrary functions unless we know they don't access any
131867c32a98SDimitry Andric       // non-parameter pointer-values.
131967c32a98SDimitry Andric       bool CanAddScopes = !UsesAliasingPtr;
132067c32a98SDimitry Andric       if (CanAddScopes && IsFuncCall)
132167c32a98SDimitry Andric         CanAddScopes = IsArgMemOnlyCall;
132267c32a98SDimitry Andric 
132367c32a98SDimitry Andric       if (CanAddScopes)
132467c32a98SDimitry Andric         for (const Argument *A : NoAliasArgs) {
132567c32a98SDimitry Andric           if (ObjSet.count(A))
132667c32a98SDimitry Andric             Scopes.push_back(NewScopes[A]);
132767c32a98SDimitry Andric         }
132867c32a98SDimitry Andric 
132967c32a98SDimitry Andric       if (!Scopes.empty())
133067c32a98SDimitry Andric         NI->setMetadata(
133167c32a98SDimitry Andric             LLVMContext::MD_alias_scope,
133267c32a98SDimitry Andric             MDNode::concatenate(NI->getMetadata(LLVMContext::MD_alias_scope),
133367c32a98SDimitry Andric                                 MDNode::get(CalledFunc->getContext(), Scopes)));
133467c32a98SDimitry Andric     }
133567c32a98SDimitry Andric   }
133667c32a98SDimitry Andric }
133767c32a98SDimitry Andric 
MayContainThrowingOrExitingCallAfterCB(CallBase * Begin,ReturnInst * End)1338b1c73532SDimitry Andric static bool MayContainThrowingOrExitingCallAfterCB(CallBase *Begin,
1339b1c73532SDimitry Andric                                                    ReturnInst *End) {
1340cfca06d7SDimitry Andric 
1341cfca06d7SDimitry Andric   assert(Begin->getParent() == End->getParent() &&
1342cfca06d7SDimitry Andric          "Expected to be in same basic block!");
1343b1c73532SDimitry Andric   auto BeginIt = Begin->getIterator();
1344b1c73532SDimitry Andric   assert(BeginIt != End->getIterator() && "Non-empty BB has empty iterator");
1345c0981da4SDimitry Andric   return !llvm::isGuaranteedToTransferExecutionToSuccessor(
1346b1c73532SDimitry Andric       ++BeginIt, End->getIterator(), InlinerAttributeWindow + 1);
1347cfca06d7SDimitry Andric }
1348cfca06d7SDimitry Andric 
1349ac9a064cSDimitry Andric // Add attributes from CB params and Fn attributes that can always be propagated
1350ac9a064cSDimitry Andric // to the corresponding argument / inner callbases.
AddParamAndFnBasicAttributes(const CallBase & CB,ValueToValueMapTy & VMap,ClonedCodeInfo & InlinedFunctionInfo)1351ac9a064cSDimitry Andric static void AddParamAndFnBasicAttributes(const CallBase &CB,
135203706295SDimitry Andric                                          ValueToValueMapTy &VMap,
135303706295SDimitry Andric                                          ClonedCodeInfo &InlinedFunctionInfo) {
1354ac9a064cSDimitry Andric   auto *CalledFunction = CB.getCalledFunction();
1355ac9a064cSDimitry Andric   auto &Context = CalledFunction->getContext();
1356ac9a064cSDimitry Andric 
1357ac9a064cSDimitry Andric   // Collect valid attributes for all params.
1358ac9a064cSDimitry Andric   SmallVector<AttrBuilder> ValidParamAttrs;
1359ac9a064cSDimitry Andric   bool HasAttrToPropagate = false;
1360ac9a064cSDimitry Andric 
1361ac9a064cSDimitry Andric   for (unsigned I = 0, E = CB.arg_size(); I < E; ++I) {
1362ac9a064cSDimitry Andric     ValidParamAttrs.emplace_back(AttrBuilder{CB.getContext()});
1363ac9a064cSDimitry Andric     // Access attributes can be propagated to any param with the same underlying
1364ac9a064cSDimitry Andric     // object as the argument.
1365ac9a064cSDimitry Andric     if (CB.paramHasAttr(I, Attribute::ReadNone))
1366ac9a064cSDimitry Andric       ValidParamAttrs.back().addAttribute(Attribute::ReadNone);
1367ac9a064cSDimitry Andric     if (CB.paramHasAttr(I, Attribute::ReadOnly))
1368ac9a064cSDimitry Andric       ValidParamAttrs.back().addAttribute(Attribute::ReadOnly);
1369ac9a064cSDimitry Andric     HasAttrToPropagate |= ValidParamAttrs.back().hasAttributes();
1370ac9a064cSDimitry Andric   }
1371ac9a064cSDimitry Andric 
1372ac9a064cSDimitry Andric   // Won't be able to propagate anything.
1373ac9a064cSDimitry Andric   if (!HasAttrToPropagate)
1374ac9a064cSDimitry Andric     return;
1375ac9a064cSDimitry Andric 
1376ac9a064cSDimitry Andric   for (BasicBlock &BB : *CalledFunction) {
1377ac9a064cSDimitry Andric     for (Instruction &Ins : BB) {
1378ac9a064cSDimitry Andric       const auto *InnerCB = dyn_cast<CallBase>(&Ins);
1379ac9a064cSDimitry Andric       if (!InnerCB)
1380ac9a064cSDimitry Andric         continue;
1381ac9a064cSDimitry Andric       auto *NewInnerCB = dyn_cast_or_null<CallBase>(VMap.lookup(InnerCB));
1382ac9a064cSDimitry Andric       if (!NewInnerCB)
1383ac9a064cSDimitry Andric         continue;
138403706295SDimitry Andric       // The InnerCB might have be simplified during the inlining
138503706295SDimitry Andric       // process which can make propagation incorrect.
138603706295SDimitry Andric       if (InlinedFunctionInfo.isSimplified(InnerCB, NewInnerCB))
138703706295SDimitry Andric         continue;
138803706295SDimitry Andric 
1389ac9a064cSDimitry Andric       AttributeList AL = NewInnerCB->getAttributes();
1390ac9a064cSDimitry Andric       for (unsigned I = 0, E = InnerCB->arg_size(); I < E; ++I) {
1391ac9a064cSDimitry Andric         // Check if the underlying value for the parameter is an argument.
1392ac9a064cSDimitry Andric         const Value *UnderlyingV =
1393ac9a064cSDimitry Andric             getUnderlyingObject(InnerCB->getArgOperand(I));
1394ac9a064cSDimitry Andric         const Argument *Arg = dyn_cast<Argument>(UnderlyingV);
1395ac9a064cSDimitry Andric         if (!Arg)
1396ac9a064cSDimitry Andric           continue;
1397ac9a064cSDimitry Andric 
1398efdccd83SDimitry Andric         if (NewInnerCB->paramHasAttr(I, Attribute::ByVal))
1399ac9a064cSDimitry Andric           // It's unsound to propagate memory attributes to byval arguments.
1400ac9a064cSDimitry Andric           // Even if CalledFunction doesn't e.g. write to the argument,
1401ac9a064cSDimitry Andric           // the call to NewInnerCB may write to its by-value copy.
1402ac9a064cSDimitry Andric           continue;
1403ac9a064cSDimitry Andric 
1404ac9a064cSDimitry Andric         unsigned ArgNo = Arg->getArgNo();
1405ac9a064cSDimitry Andric         // If so, propagate its access attributes.
1406ac9a064cSDimitry Andric         AL = AL.addParamAttributes(Context, I, ValidParamAttrs[ArgNo]);
1407ac9a064cSDimitry Andric         // We can have conflicting attributes from the inner callsite and
1408ac9a064cSDimitry Andric         // to-be-inlined callsite. In that case, choose the most
1409ac9a064cSDimitry Andric         // restrictive.
1410ac9a064cSDimitry Andric 
1411ac9a064cSDimitry Andric         // readonly + writeonly means we can never deref so make readnone.
1412ac9a064cSDimitry Andric         if (AL.hasParamAttr(I, Attribute::ReadOnly) &&
1413ac9a064cSDimitry Andric             AL.hasParamAttr(I, Attribute::WriteOnly))
1414ac9a064cSDimitry Andric           AL = AL.addParamAttribute(Context, I, Attribute::ReadNone);
1415ac9a064cSDimitry Andric 
1416ac9a064cSDimitry Andric         // If have readnone, need to clear readonly/writeonly
1417ac9a064cSDimitry Andric         if (AL.hasParamAttr(I, Attribute::ReadNone)) {
1418ac9a064cSDimitry Andric           AL = AL.removeParamAttribute(Context, I, Attribute::ReadOnly);
1419ac9a064cSDimitry Andric           AL = AL.removeParamAttribute(Context, I, Attribute::WriteOnly);
1420ac9a064cSDimitry Andric         }
1421ac9a064cSDimitry Andric 
1422ac9a064cSDimitry Andric         // Writable cannot exist in conjunction w/ readonly/readnone
1423ac9a064cSDimitry Andric         if (AL.hasParamAttr(I, Attribute::ReadOnly) ||
1424ac9a064cSDimitry Andric             AL.hasParamAttr(I, Attribute::ReadNone))
1425ac9a064cSDimitry Andric           AL = AL.removeParamAttribute(Context, I, Attribute::Writable);
1426ac9a064cSDimitry Andric       }
1427ac9a064cSDimitry Andric       NewInnerCB->setAttributes(AL);
1428ac9a064cSDimitry Andric     }
1429ac9a064cSDimitry Andric   }
1430ac9a064cSDimitry Andric }
1431ac9a064cSDimitry Andric 
1432cfca06d7SDimitry Andric // Only allow these white listed attributes to be propagated back to the
1433cfca06d7SDimitry Andric // callee. This is because other attributes may only be valid on the call
1434cfca06d7SDimitry Andric // itself, i.e. attributes such as signext and zeroext.
1435b1c73532SDimitry Andric 
1436b1c73532SDimitry Andric // Attributes that are always okay to propagate as if they are violated its
1437b1c73532SDimitry Andric // immediate UB.
IdentifyValidUBGeneratingAttributes(CallBase & CB)1438b1c73532SDimitry Andric static AttrBuilder IdentifyValidUBGeneratingAttributes(CallBase &CB) {
1439b1c73532SDimitry Andric   AttrBuilder Valid(CB.getContext());
1440b1c73532SDimitry Andric   if (auto DerefBytes = CB.getRetDereferenceableBytes())
1441cfca06d7SDimitry Andric     Valid.addDereferenceableAttr(DerefBytes);
1442b1c73532SDimitry Andric   if (auto DerefOrNullBytes = CB.getRetDereferenceableOrNullBytes())
1443cfca06d7SDimitry Andric     Valid.addDereferenceableOrNullAttr(DerefOrNullBytes);
1444b1c73532SDimitry Andric   if (CB.hasRetAttr(Attribute::NoAlias))
1445cfca06d7SDimitry Andric     Valid.addAttribute(Attribute::NoAlias);
1446b1c73532SDimitry Andric   if (CB.hasRetAttr(Attribute::NoUndef))
1447b1c73532SDimitry Andric     Valid.addAttribute(Attribute::NoUndef);
1448b1c73532SDimitry Andric   return Valid;
1449b1c73532SDimitry Andric }
1450b1c73532SDimitry Andric 
1451b1c73532SDimitry Andric // Attributes that need additional checks as propagating them may change
1452b1c73532SDimitry Andric // behavior or cause new UB.
IdentifyValidPoisonGeneratingAttributes(CallBase & CB)1453b1c73532SDimitry Andric static AttrBuilder IdentifyValidPoisonGeneratingAttributes(CallBase &CB) {
1454b1c73532SDimitry Andric   AttrBuilder Valid(CB.getContext());
1455b1c73532SDimitry Andric   if (CB.hasRetAttr(Attribute::NonNull))
1456cfca06d7SDimitry Andric     Valid.addAttribute(Attribute::NonNull);
1457b1c73532SDimitry Andric   if (CB.hasRetAttr(Attribute::Alignment))
1458b1c73532SDimitry Andric     Valid.addAlignmentAttr(CB.getRetAlign());
1459ac9a064cSDimitry Andric   if (std::optional<ConstantRange> Range = CB.getRange())
1460ac9a064cSDimitry Andric     Valid.addRangeAttr(*Range);
1461cfca06d7SDimitry Andric   return Valid;
1462cfca06d7SDimitry Andric }
1463cfca06d7SDimitry Andric 
AddReturnAttributes(CallBase & CB,ValueToValueMapTy & VMap,ClonedCodeInfo & InlinedFunctionInfo)146403706295SDimitry Andric static void AddReturnAttributes(CallBase &CB, ValueToValueMapTy &VMap,
146503706295SDimitry Andric                                 ClonedCodeInfo &InlinedFunctionInfo) {
1466b1c73532SDimitry Andric   AttrBuilder ValidUB = IdentifyValidUBGeneratingAttributes(CB);
1467b1c73532SDimitry Andric   AttrBuilder ValidPG = IdentifyValidPoisonGeneratingAttributes(CB);
1468b1c73532SDimitry Andric   if (!ValidUB.hasAttributes() && !ValidPG.hasAttributes())
1469cfca06d7SDimitry Andric     return;
1470cfca06d7SDimitry Andric   auto *CalledFunction = CB.getCalledFunction();
1471cfca06d7SDimitry Andric   auto &Context = CalledFunction->getContext();
1472cfca06d7SDimitry Andric 
1473cfca06d7SDimitry Andric   for (auto &BB : *CalledFunction) {
1474cfca06d7SDimitry Andric     auto *RI = dyn_cast<ReturnInst>(BB.getTerminator());
1475cfca06d7SDimitry Andric     if (!RI || !isa<CallBase>(RI->getOperand(0)))
1476cfca06d7SDimitry Andric       continue;
1477cfca06d7SDimitry Andric     auto *RetVal = cast<CallBase>(RI->getOperand(0));
1478f65dcba8SDimitry Andric     // Check that the cloned RetVal exists and is a call, otherwise we cannot
1479f65dcba8SDimitry Andric     // add the attributes on the cloned RetVal. Simplification during inlining
1480f65dcba8SDimitry Andric     // could have transformed the cloned instruction.
1481cfca06d7SDimitry Andric     auto *NewRetVal = dyn_cast_or_null<CallBase>(VMap.lookup(RetVal));
1482cfca06d7SDimitry Andric     if (!NewRetVal)
1483cfca06d7SDimitry Andric       continue;
148403706295SDimitry Andric 
148503706295SDimitry Andric     // The RetVal might have be simplified during the inlining
148603706295SDimitry Andric     // process which can make propagation incorrect.
148703706295SDimitry Andric     if (InlinedFunctionInfo.isSimplified(RetVal, NewRetVal))
148803706295SDimitry Andric       continue;
1489cfca06d7SDimitry Andric     // Backward propagation of attributes to the returned value may be incorrect
1490cfca06d7SDimitry Andric     // if it is control flow dependent.
1491cfca06d7SDimitry Andric     // Consider:
1492cfca06d7SDimitry Andric     // @callee {
1493cfca06d7SDimitry Andric     //  %rv = call @foo()
1494cfca06d7SDimitry Andric     //  %rv2 = call @bar()
1495cfca06d7SDimitry Andric     //  if (%rv2 != null)
1496cfca06d7SDimitry Andric     //    return %rv2
1497cfca06d7SDimitry Andric     //  if (%rv == null)
1498cfca06d7SDimitry Andric     //    exit()
1499cfca06d7SDimitry Andric     //  return %rv
1500cfca06d7SDimitry Andric     // }
1501cfca06d7SDimitry Andric     // caller() {
1502cfca06d7SDimitry Andric     //   %val = call nonnull @callee()
1503cfca06d7SDimitry Andric     // }
1504cfca06d7SDimitry Andric     // Here we cannot add the nonnull attribute on either foo or bar. So, we
1505cfca06d7SDimitry Andric     // limit the check to both RetVal and RI are in the same basic block and
1506cfca06d7SDimitry Andric     // there are no throwing/exiting instructions between these instructions.
1507cfca06d7SDimitry Andric     if (RI->getParent() != RetVal->getParent() ||
1508b1c73532SDimitry Andric         MayContainThrowingOrExitingCallAfterCB(RetVal, RI))
1509cfca06d7SDimitry Andric       continue;
1510cfca06d7SDimitry Andric     // Add to the existing attributes of NewRetVal, i.e. the cloned call
1511cfca06d7SDimitry Andric     // instruction.
1512cfca06d7SDimitry Andric     // NB! When we have the same attribute already existing on NewRetVal, but
1513cfca06d7SDimitry Andric     // with a differing value, the AttributeList's merge API honours the already
1514cfca06d7SDimitry Andric     // existing attribute value (i.e. attributes such as dereferenceable,
1515cfca06d7SDimitry Andric     // dereferenceable_or_null etc). See AttrBuilder::merge for more details.
1516cfca06d7SDimitry Andric     AttributeList AL = NewRetVal->getAttributes();
1517b1c73532SDimitry Andric     if (ValidUB.getDereferenceableBytes() < AL.getRetDereferenceableBytes())
1518b1c73532SDimitry Andric       ValidUB.removeAttribute(Attribute::Dereferenceable);
1519b1c73532SDimitry Andric     if (ValidUB.getDereferenceableOrNullBytes() <
1520b1c73532SDimitry Andric         AL.getRetDereferenceableOrNullBytes())
1521b1c73532SDimitry Andric       ValidUB.removeAttribute(Attribute::DereferenceableOrNull);
1522b1c73532SDimitry Andric     AttributeList NewAL = AL.addRetAttributes(Context, ValidUB);
1523b1c73532SDimitry Andric     // Attributes that may generate poison returns are a bit tricky. If we
1524b1c73532SDimitry Andric     // propagate them, other uses of the callsite might have their behavior
1525b1c73532SDimitry Andric     // change or cause UB (if they have noundef) b.c of the new potential
1526b1c73532SDimitry Andric     // poison.
1527b1c73532SDimitry Andric     // Take the following three cases:
1528b1c73532SDimitry Andric     //
1529b1c73532SDimitry Andric     // 1)
1530b1c73532SDimitry Andric     // define nonnull ptr @foo() {
1531b1c73532SDimitry Andric     //   %p = call ptr @bar()
1532b1c73532SDimitry Andric     //   call void @use(ptr %p) willreturn nounwind
1533b1c73532SDimitry Andric     //   ret ptr %p
1534b1c73532SDimitry Andric     // }
1535b1c73532SDimitry Andric     //
1536b1c73532SDimitry Andric     // 2)
1537b1c73532SDimitry Andric     // define noundef nonnull ptr @foo() {
1538b1c73532SDimitry Andric     //   %p = call ptr @bar()
1539b1c73532SDimitry Andric     //   call void @use(ptr %p) willreturn nounwind
1540b1c73532SDimitry Andric     //   ret ptr %p
1541b1c73532SDimitry Andric     // }
1542b1c73532SDimitry Andric     //
1543b1c73532SDimitry Andric     // 3)
1544b1c73532SDimitry Andric     // define nonnull ptr @foo() {
1545b1c73532SDimitry Andric     //   %p = call noundef ptr @bar()
1546b1c73532SDimitry Andric     //   ret ptr %p
1547b1c73532SDimitry Andric     // }
1548b1c73532SDimitry Andric     //
1549b1c73532SDimitry Andric     // In case 1, we can't propagate nonnull because poison value in @use may
1550b1c73532SDimitry Andric     // change behavior or trigger UB.
1551b1c73532SDimitry Andric     // In case 2, we don't need to be concerned about propagating nonnull, as
1552b1c73532SDimitry Andric     // any new poison at @use will trigger UB anyways.
1553b1c73532SDimitry Andric     // In case 3, we can never propagate nonnull because it may create UB due to
1554b1c73532SDimitry Andric     // the noundef on @bar.
1555b1c73532SDimitry Andric     if (ValidPG.getAlignment().valueOrOne() < AL.getRetAlignment().valueOrOne())
1556b1c73532SDimitry Andric       ValidPG.removeAttribute(Attribute::Alignment);
1557b1c73532SDimitry Andric     if (ValidPG.hasAttributes()) {
1558ac9a064cSDimitry Andric       Attribute CBRange = ValidPG.getAttribute(Attribute::Range);
1559ac9a064cSDimitry Andric       if (CBRange.isValid()) {
1560ac9a064cSDimitry Andric         Attribute NewRange = AL.getRetAttr(Attribute::Range);
1561ac9a064cSDimitry Andric         if (NewRange.isValid()) {
1562ac9a064cSDimitry Andric           ValidPG.addRangeAttr(
1563ac9a064cSDimitry Andric               CBRange.getRange().intersectWith(NewRange.getRange()));
1564ac9a064cSDimitry Andric         }
1565ac9a064cSDimitry Andric       }
1566b1c73532SDimitry Andric       // Three checks.
1567b1c73532SDimitry Andric       // If the callsite has `noundef`, then a poison due to violating the
1568b1c73532SDimitry Andric       // return attribute will create UB anyways so we can always propagate.
1569b1c73532SDimitry Andric       // Otherwise, if the return value (callee to be inlined) has `noundef`, we
1570b1c73532SDimitry Andric       // can't propagate as a new poison return will cause UB.
1571b1c73532SDimitry Andric       // Finally, check if the return value has no uses whose behavior may
1572b1c73532SDimitry Andric       // change/may cause UB if we potentially return poison. At the moment this
1573b1c73532SDimitry Andric       // is implemented overly conservatively with a single-use check.
1574b1c73532SDimitry Andric       // TODO: Update the single-use check to iterate through uses and only bail
1575b1c73532SDimitry Andric       // if we have a potentially dangerous use.
1576b1c73532SDimitry Andric 
1577b1c73532SDimitry Andric       if (CB.hasRetAttr(Attribute::NoUndef) ||
1578b1c73532SDimitry Andric           (RetVal->hasOneUse() && !RetVal->hasRetAttr(Attribute::NoUndef)))
1579b1c73532SDimitry Andric         NewAL = NewAL.addRetAttributes(Context, ValidPG);
1580b1c73532SDimitry Andric     }
1581cfca06d7SDimitry Andric     NewRetVal->setAttributes(NewAL);
1582cfca06d7SDimitry Andric   }
1583cfca06d7SDimitry Andric }
1584cfca06d7SDimitry Andric 
158567c32a98SDimitry Andric /// If the inlined function has non-byval align arguments, then
158667c32a98SDimitry Andric /// add @llvm.assume-based alignment assumptions to preserve this information.
AddAlignmentAssumptions(CallBase & CB,InlineFunctionInfo & IFI)1587cfca06d7SDimitry Andric static void AddAlignmentAssumptions(CallBase &CB, InlineFunctionInfo &IFI) {
1588b915e9e0SDimitry Andric   if (!PreserveAlignmentAssumptions || !IFI.GetAssumptionCache)
158967c32a98SDimitry Andric     return;
1590b915e9e0SDimitry Andric 
1591cfca06d7SDimitry Andric   AssumptionCache *AC = &IFI.GetAssumptionCache(*CB.getCaller());
1592ac9a064cSDimitry Andric   auto &DL = CB.getDataLayout();
159367c32a98SDimitry Andric 
159467c32a98SDimitry Andric   // To avoid inserting redundant assumptions, we should check for assumptions
159567c32a98SDimitry Andric   // already in the caller. To do this, we might need a DT of the caller.
159667c32a98SDimitry Andric   DominatorTree DT;
159767c32a98SDimitry Andric   bool DTCalculated = false;
159867c32a98SDimitry Andric 
1599cfca06d7SDimitry Andric   Function *CalledFunc = CB.getCalledFunction();
160071d5a254SDimitry Andric   for (Argument &Arg : CalledFunc->args()) {
1601e3b55780SDimitry Andric     if (!Arg.getType()->isPointerTy() || Arg.hasPassPointeeByValueCopyAttr() ||
1602e3b55780SDimitry Andric         Arg.hasNUses(0))
1603e3b55780SDimitry Andric       continue;
1604e3b55780SDimitry Andric     MaybeAlign Alignment = Arg.getParamAlign();
1605e3b55780SDimitry Andric     if (!Alignment)
1606e3b55780SDimitry Andric       continue;
1607e3b55780SDimitry Andric 
160867c32a98SDimitry Andric     if (!DTCalculated) {
1609cfca06d7SDimitry Andric       DT.recalculate(*CB.getCaller());
161067c32a98SDimitry Andric       DTCalculated = true;
161167c32a98SDimitry Andric     }
161267c32a98SDimitry Andric     // If we can already prove the asserted alignment in the context of the
161367c32a98SDimitry Andric     // caller, then don't bother inserting the assumption.
1614cfca06d7SDimitry Andric     Value *ArgVal = CB.getArgOperand(Arg.getArgNo());
1615e3b55780SDimitry Andric     if (getKnownAlignment(ArgVal, DL, &CB, AC, &DT) >= *Alignment)
161667c32a98SDimitry Andric       continue;
161767c32a98SDimitry Andric 
1618e3b55780SDimitry Andric     CallInst *NewAsmp = IRBuilder<>(&CB).CreateAlignmentAssumption(
1619e3b55780SDimitry Andric         DL, ArgVal, Alignment->value());
1620344a3780SDimitry Andric     AC->registerAssumption(cast<AssumeInst>(NewAsmp));
162167c32a98SDimitry Andric   }
162267c32a98SDimitry Andric }
162367c32a98SDimitry Andric 
HandleByValArgumentInit(Type * ByValType,Value * Dst,Value * Src,Module * M,BasicBlock * InsertBlock,InlineFunctionInfo & IFI,Function * CalledFunc)1624c0981da4SDimitry Andric static void HandleByValArgumentInit(Type *ByValType, Value *Dst, Value *Src,
1625c0981da4SDimitry Andric                                     Module *M, BasicBlock *InsertBlock,
16267fa27ce4SDimitry Andric                                     InlineFunctionInfo &IFI,
16277fa27ce4SDimitry Andric                                     Function *CalledFunc) {
1628dd58ef01SDimitry Andric   IRBuilder<> Builder(InsertBlock, InsertBlock->begin());
16295ca98fd9SDimitry Andric 
1630c0981da4SDimitry Andric   Value *Size =
1631c0981da4SDimitry Andric       Builder.getInt64(M->getDataLayout().getTypeStoreSize(ByValType));
16325ca98fd9SDimitry Andric 
16335ca98fd9SDimitry Andric   // Always generate a memcpy of alignment 1 here because we don't know
16345ca98fd9SDimitry Andric   // the alignment of the src pointer.  Other optimizations can infer
16355ca98fd9SDimitry Andric   // better alignment.
16367fa27ce4SDimitry Andric   CallInst *CI = Builder.CreateMemCpy(Dst, /*DstAlign*/ Align(1), Src,
1637cfca06d7SDimitry Andric                                       /*SrcAlign*/ Align(1), Size);
16387fa27ce4SDimitry Andric 
16397fa27ce4SDimitry Andric   // The verifier requires that all calls of debug-info-bearing functions
16407fa27ce4SDimitry Andric   // from debug-info-bearing functions have a debug location (for inlining
16417fa27ce4SDimitry Andric   // purposes). Assign a dummy location to satisfy the constraint.
16427fa27ce4SDimitry Andric   if (!CI->getDebugLoc() && InsertBlock->getParent()->getSubprogram())
16437fa27ce4SDimitry Andric     if (DISubprogram *SP = CalledFunc->getSubprogram())
16447fa27ce4SDimitry Andric       CI->setDebugLoc(DILocation::get(SP->getContext(), 0, 0, SP));
16455ca98fd9SDimitry Andric }
16465ca98fd9SDimitry Andric 
16475a5ac124SDimitry Andric /// When inlining a call site that has a byval argument,
1648cf099d11SDimitry Andric /// we have to make the implicit memcpy explicit by adding it.
HandleByValArgument(Type * ByValType,Value * Arg,Instruction * TheCall,const Function * CalledFunc,InlineFunctionInfo & IFI,MaybeAlign ByValAlignment)1649c0981da4SDimitry Andric static Value *HandleByValArgument(Type *ByValType, Value *Arg,
1650c0981da4SDimitry Andric                                   Instruction *TheCall,
1651cf099d11SDimitry Andric                                   const Function *CalledFunc,
1652cf099d11SDimitry Andric                                   InlineFunctionInfo &IFI,
1653e3b55780SDimitry Andric                                   MaybeAlign ByValAlignment) {
165471d5a254SDimitry Andric   Function *Caller = TheCall->getFunction();
1655ac9a064cSDimitry Andric   const DataLayout &DL = Caller->getDataLayout();
165667c32a98SDimitry Andric 
1657cf099d11SDimitry Andric   // If the called function is readonly, then it could not mutate the caller's
1658cf099d11SDimitry Andric   // copy of the byval'd memory.  In this case, it is safe to elide the copy and
1659cf099d11SDimitry Andric   // temporary.
1660cf099d11SDimitry Andric   if (CalledFunc->onlyReadsMemory()) {
1661cf099d11SDimitry Andric     // If the byval argument has a specified alignment that is greater than the
1662cf099d11SDimitry Andric     // passed in pointer, then we either have to round up the input pointer or
1663cf099d11SDimitry Andric     // give up on this transformation.
1664e3b55780SDimitry Andric     if (ByValAlignment.valueOrOne() == 1)
1665cf099d11SDimitry Andric       return Arg;
1666cf099d11SDimitry Andric 
1667b915e9e0SDimitry Andric     AssumptionCache *AC =
1668cfca06d7SDimitry Andric         IFI.GetAssumptionCache ? &IFI.GetAssumptionCache(*Caller) : nullptr;
16695a5ac124SDimitry Andric 
1670cf099d11SDimitry Andric     // If the pointer is already known to be sufficiently aligned, or if we can
1671cf099d11SDimitry Andric     // round it up to a larger alignment, then we don't need a temporary.
1672e3b55780SDimitry Andric     if (getOrEnforceKnownAlignment(Arg, *ByValAlignment, DL, TheCall, AC) >=
1673e3b55780SDimitry Andric         *ByValAlignment)
1674cf099d11SDimitry Andric       return Arg;
1675cf099d11SDimitry Andric 
1676cf099d11SDimitry Andric     // Otherwise, we have to make a memcpy to get a safe alignment.  This is bad
1677cf099d11SDimitry Andric     // for code quality, but rarely happens and is required for correctness.
1678cf099d11SDimitry Andric   }
1679cf099d11SDimitry Andric 
1680522600a2SDimitry Andric   // Create the alloca.  If we have DataLayout, use nice alignment.
1681e3b55780SDimitry Andric   Align Alignment = DL.getPrefTypeAlign(ByValType);
1682cf099d11SDimitry Andric 
1683cf099d11SDimitry Andric   // If the byval had an alignment specified, we *must* use at least that
1684cf099d11SDimitry Andric   // alignment, as it is required by the byval argument (and uses of the
1685cf099d11SDimitry Andric   // pointer inside the callee).
1686e3b55780SDimitry Andric   if (ByValAlignment)
1687e3b55780SDimitry Andric     Alignment = std::max(Alignment, *ByValAlignment);
1688cf099d11SDimitry Andric 
1689ac9a064cSDimitry Andric   AllocaInst *NewAlloca =
1690ac9a064cSDimitry Andric       new AllocaInst(ByValType, Arg->getType()->getPointerAddressSpace(),
1691b1c73532SDimitry Andric                      nullptr, Alignment, Arg->getName());
1692b1c73532SDimitry Andric   NewAlloca->insertBefore(Caller->begin()->begin());
1693b1c73532SDimitry Andric   IFI.StaticAllocas.push_back(NewAlloca);
1694cf099d11SDimitry Andric 
1695cf099d11SDimitry Andric   // Uses of the argument in the function should use our new alloca
1696cf099d11SDimitry Andric   // instead.
1697cf099d11SDimitry Andric   return NewAlloca;
1698cf099d11SDimitry Andric }
1699cf099d11SDimitry Andric 
17005a5ac124SDimitry Andric // Check whether this Value is used by a lifetime intrinsic.
isUsedByLifetimeMarker(Value * V)170156fe8f14SDimitry Andric static bool isUsedByLifetimeMarker(Value *V) {
1702d8e91e46SDimitry Andric   for (User *U : V->users())
1703d8e91e46SDimitry Andric     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U))
1704d8e91e46SDimitry Andric       if (II->isLifetimeStartOrEnd())
170556fe8f14SDimitry Andric         return true;
170656fe8f14SDimitry Andric   return false;
170756fe8f14SDimitry Andric }
170856fe8f14SDimitry Andric 
17095a5ac124SDimitry Andric // Check whether the given alloca already has
171056fe8f14SDimitry Andric // lifetime.start or lifetime.end intrinsics.
hasLifetimeMarkers(AllocaInst * AI)171156fe8f14SDimitry Andric static bool hasLifetimeMarkers(AllocaInst *AI) {
17125ca98fd9SDimitry Andric   Type *Ty = AI->getType();
1713b1c73532SDimitry Andric   Type *Int8PtrTy =
1714b1c73532SDimitry Andric       PointerType::get(Ty->getContext(), Ty->getPointerAddressSpace());
17155ca98fd9SDimitry Andric   if (Ty == Int8PtrTy)
171656fe8f14SDimitry Andric     return isUsedByLifetimeMarker(AI);
171756fe8f14SDimitry Andric 
1718411bd29eSDimitry Andric   // Do a scan to find all the casts to i8*.
17195ca98fd9SDimitry Andric   for (User *U : AI->users()) {
17205ca98fd9SDimitry Andric     if (U->getType() != Int8PtrTy) continue;
17215ca98fd9SDimitry Andric     if (U->stripPointerCasts() != AI) continue;
17225ca98fd9SDimitry Andric     if (isUsedByLifetimeMarker(U))
172356fe8f14SDimitry Andric       return true;
172456fe8f14SDimitry Andric   }
172556fe8f14SDimitry Andric   return false;
172656fe8f14SDimitry Andric }
172756fe8f14SDimitry Andric 
1728a7fe922bSDimitry Andric /// Return the result of AI->isStaticAlloca() if AI were moved to the entry
1729a7fe922bSDimitry Andric /// block. Allocas used in inalloca calls and allocas of dynamic array size
1730a7fe922bSDimitry Andric /// cannot be static.
allocaWouldBeStaticInEntry(const AllocaInst * AI)1731a7fe922bSDimitry Andric static bool allocaWouldBeStaticInEntry(const AllocaInst *AI ) {
1732a7fe922bSDimitry Andric   return isa<Constant>(AI->getArraySize()) && !AI->isUsedWithInAlloca();
1733a7fe922bSDimitry Andric }
1734a7fe922bSDimitry Andric 
1735e6d15924SDimitry Andric /// Returns a DebugLoc for a new DILocation which is a clone of \p OrigDL
1736e6d15924SDimitry Andric /// inlined at \p InlinedAt. \p IANodes is an inlined-at cache.
inlineDebugLoc(DebugLoc OrigDL,DILocation * InlinedAt,LLVMContext & Ctx,DenseMap<const MDNode *,MDNode * > & IANodes)1737e6d15924SDimitry Andric static DebugLoc inlineDebugLoc(DebugLoc OrigDL, DILocation *InlinedAt,
1738e6d15924SDimitry Andric                                LLVMContext &Ctx,
1739e6d15924SDimitry Andric                                DenseMap<const MDNode *, MDNode *> &IANodes) {
1740e6d15924SDimitry Andric   auto IA = DebugLoc::appendInlinedAt(OrigDL, InlinedAt, Ctx, IANodes);
1741b60736ecSDimitry Andric   return DILocation::get(Ctx, OrigDL.getLine(), OrigDL.getCol(),
1742b60736ecSDimitry Andric                          OrigDL.getScope(), IA);
1743e6d15924SDimitry Andric }
1744e6d15924SDimitry Andric 
17455a5ac124SDimitry Andric /// Update inlined instructions' line numbers to
1746411bd29eSDimitry Andric /// to encode location where these instructions are inlined.
fixupLineNumbers(Function * Fn,Function::iterator FI,Instruction * TheCall,bool CalleeHasDebugInfo)1747411bd29eSDimitry Andric static void fixupLineNumbers(Function *Fn, Function::iterator FI,
1748b915e9e0SDimitry Andric                              Instruction *TheCall, bool CalleeHasDebugInfo) {
174901095a5dSDimitry Andric   const DebugLoc &TheCallDL = TheCall->getDebugLoc();
17505a5ac124SDimitry Andric   if (!TheCallDL)
1751411bd29eSDimitry Andric     return;
1752411bd29eSDimitry Andric 
17535a5ac124SDimitry Andric   auto &Ctx = Fn->getContext();
17545a5ac124SDimitry Andric   DILocation *InlinedAtNode = TheCallDL;
17555a5ac124SDimitry Andric 
17565a5ac124SDimitry Andric   // Create a unique call site, not to be confused with any other call from the
17575a5ac124SDimitry Andric   // same location.
17585a5ac124SDimitry Andric   InlinedAtNode = DILocation::getDistinct(
17595a5ac124SDimitry Andric       Ctx, InlinedAtNode->getLine(), InlinedAtNode->getColumn(),
17605a5ac124SDimitry Andric       InlinedAtNode->getScope(), InlinedAtNode->getInlinedAt());
17615a5ac124SDimitry Andric 
17625a5ac124SDimitry Andric   // Cache the inlined-at nodes as they're built so they are reused, without
17635a5ac124SDimitry Andric   // this every instruction's inlined-at chain would become distinct from each
17645a5ac124SDimitry Andric   // other.
17656b3f41edSDimitry Andric   DenseMap<const MDNode *, MDNode *> IANodes;
17665a5ac124SDimitry Andric 
1767706b4fc4SDimitry Andric   // Check if we are not generating inline line tables and want to use
1768706b4fc4SDimitry Andric   // the call site location instead.
1769706b4fc4SDimitry Andric   bool NoInlineLineTables = Fn->hasFnAttribute("no-inline-line-tables");
1770706b4fc4SDimitry Andric 
1771b1c73532SDimitry Andric   // Helper-util for updating the metadata attached to an instruction.
1772b1c73532SDimitry Andric   auto UpdateInst = [&](Instruction &I) {
1773e6d15924SDimitry Andric     // Loop metadata needs to be updated so that the start and end locs
1774e6d15924SDimitry Andric     // reference inlined-at locations.
1775344a3780SDimitry Andric     auto updateLoopInfoLoc = [&Ctx, &InlinedAtNode,
1776344a3780SDimitry Andric                               &IANodes](Metadata *MD) -> Metadata * {
1777344a3780SDimitry Andric       if (auto *Loc = dyn_cast_or_null<DILocation>(MD))
1778344a3780SDimitry Andric         return inlineDebugLoc(Loc, InlinedAtNode, Ctx, IANodes).get();
1779344a3780SDimitry Andric       return MD;
1780cfca06d7SDimitry Andric     };
1781b1c73532SDimitry Andric     updateLoopMetadataDebugLocations(I, updateLoopInfoLoc);
1782e6d15924SDimitry Andric 
1783706b4fc4SDimitry Andric     if (!NoInlineLineTables)
1784b1c73532SDimitry Andric       if (DebugLoc DL = I.getDebugLoc()) {
1785e6d15924SDimitry Andric         DebugLoc IDL =
1786b1c73532SDimitry Andric             inlineDebugLoc(DL, InlinedAtNode, I.getContext(), IANodes);
1787b1c73532SDimitry Andric         I.setDebugLoc(IDL);
1788b1c73532SDimitry Andric         return;
1789b915e9e0SDimitry Andric       }
1790b915e9e0SDimitry Andric 
1791706b4fc4SDimitry Andric     if (CalleeHasDebugInfo && !NoInlineLineTables)
1792b1c73532SDimitry Andric       return;
1793b915e9e0SDimitry Andric 
1794706b4fc4SDimitry Andric     // If the inlined instruction has no line number, or if inline info
1795706b4fc4SDimitry Andric     // is not being generated, make it look as if it originates from the call
1796706b4fc4SDimitry Andric     // location. This is important for ((__always_inline, __nodebug__))
1797706b4fc4SDimitry Andric     // functions which must use caller location for all instructions in their
1798706b4fc4SDimitry Andric     // function body.
179967c32a98SDimitry Andric 
180067c32a98SDimitry Andric     // Don't update static allocas, as they may get moved later.
1801b1c73532SDimitry Andric     if (auto *AI = dyn_cast<AllocaInst>(&I))
1802a7fe922bSDimitry Andric       if (allocaWouldBeStaticInEntry(AI))
1803b1c73532SDimitry Andric         return;
180467c32a98SDimitry Andric 
18057fa27ce4SDimitry Andric     // Do not force a debug loc for pseudo probes, since they do not need to
18067fa27ce4SDimitry Andric     // be debuggable, and also they are expected to have a zero/null dwarf
18077fa27ce4SDimitry Andric     // discriminator at this point which could be violated otherwise.
1808b1c73532SDimitry Andric     if (isa<PseudoProbeInst>(I))
1809b1c73532SDimitry Andric       return;
18107fa27ce4SDimitry Andric 
1811b1c73532SDimitry Andric     I.setDebugLoc(TheCallDL);
1812b1c73532SDimitry Andric   };
1813b1c73532SDimitry Andric 
1814b1c73532SDimitry Andric   // Helper-util for updating debug-info records attached to instructions.
1815ac9a064cSDimitry Andric   auto UpdateDVR = [&](DbgRecord *DVR) {
1816ac9a064cSDimitry Andric     assert(DVR->getDebugLoc() && "Debug Value must have debug loc");
1817b1c73532SDimitry Andric     if (NoInlineLineTables) {
1818ac9a064cSDimitry Andric       DVR->setDebugLoc(TheCallDL);
1819b1c73532SDimitry Andric       return;
1820b1c73532SDimitry Andric     }
1821ac9a064cSDimitry Andric     DebugLoc DL = DVR->getDebugLoc();
1822b1c73532SDimitry Andric     DebugLoc IDL =
1823b1c73532SDimitry Andric         inlineDebugLoc(DL, InlinedAtNode,
1824ac9a064cSDimitry Andric                        DVR->getMarker()->getParent()->getContext(), IANodes);
1825ac9a064cSDimitry Andric     DVR->setDebugLoc(IDL);
1826b1c73532SDimitry Andric   };
1827b1c73532SDimitry Andric 
1828b1c73532SDimitry Andric   // Iterate over all instructions, updating metadata and debug-info records.
1829b1c73532SDimitry Andric   for (; FI != Fn->end(); ++FI) {
1830ac9a064cSDimitry Andric     for (Instruction &I : *FI) {
1831ac9a064cSDimitry Andric       UpdateInst(I);
1832ac9a064cSDimitry Andric       for (DbgRecord &DVR : I.getDbgRecordRange()) {
1833ac9a064cSDimitry Andric         UpdateDVR(&DVR);
1834b1c73532SDimitry Andric       }
1835411bd29eSDimitry Andric     }
1836706b4fc4SDimitry Andric 
1837706b4fc4SDimitry Andric     // Remove debug info intrinsics if we're not keeping inline info.
1838706b4fc4SDimitry Andric     if (NoInlineLineTables) {
1839706b4fc4SDimitry Andric       BasicBlock::iterator BI = FI->begin();
1840706b4fc4SDimitry Andric       while (BI != FI->end()) {
1841706b4fc4SDimitry Andric         if (isa<DbgInfoIntrinsic>(BI)) {
1842706b4fc4SDimitry Andric           BI = BI->eraseFromParent();
1843706b4fc4SDimitry Andric           continue;
1844b1c73532SDimitry Andric         } else {
1845ac9a064cSDimitry Andric           BI->dropDbgRecords();
1846706b4fc4SDimitry Andric         }
1847706b4fc4SDimitry Andric         ++BI;
1848706b4fc4SDimitry Andric       }
1849706b4fc4SDimitry Andric     }
1850411bd29eSDimitry Andric   }
1851411bd29eSDimitry Andric }
1852044eb2f6SDimitry Andric 
1853e3b55780SDimitry Andric #undef DEBUG_TYPE
1854e3b55780SDimitry Andric #define DEBUG_TYPE "assignment-tracking"
1855e3b55780SDimitry Andric /// Find Alloca and linked DbgAssignIntrinsic for locals escaped by \p CB.
collectEscapedLocals(const DataLayout & DL,const CallBase & CB)1856e3b55780SDimitry Andric static at::StorageToVarsMap collectEscapedLocals(const DataLayout &DL,
1857e3b55780SDimitry Andric                                                  const CallBase &CB) {
1858e3b55780SDimitry Andric   at::StorageToVarsMap EscapedLocals;
1859e3b55780SDimitry Andric   SmallPtrSet<const Value *, 4> SeenBases;
1860e3b55780SDimitry Andric 
1861e3b55780SDimitry Andric   LLVM_DEBUG(
1862e3b55780SDimitry Andric       errs() << "# Finding caller local variables escaped by callee\n");
1863e3b55780SDimitry Andric   for (const Value *Arg : CB.args()) {
1864e3b55780SDimitry Andric     LLVM_DEBUG(errs() << "INSPECT: " << *Arg << "\n");
1865e3b55780SDimitry Andric     if (!Arg->getType()->isPointerTy()) {
1866e3b55780SDimitry Andric       LLVM_DEBUG(errs() << " | SKIP: Not a pointer\n");
1867e3b55780SDimitry Andric       continue;
1868e3b55780SDimitry Andric     }
1869e3b55780SDimitry Andric 
1870e3b55780SDimitry Andric     const Instruction *I = dyn_cast<Instruction>(Arg);
1871e3b55780SDimitry Andric     if (!I) {
1872e3b55780SDimitry Andric       LLVM_DEBUG(errs() << " | SKIP: Not result of instruction\n");
1873e3b55780SDimitry Andric       continue;
1874e3b55780SDimitry Andric     }
1875e3b55780SDimitry Andric 
1876e3b55780SDimitry Andric     // Walk back to the base storage.
1877e3b55780SDimitry Andric     assert(Arg->getType()->isPtrOrPtrVectorTy());
1878e3b55780SDimitry Andric     APInt TmpOffset(DL.getIndexTypeSizeInBits(Arg->getType()), 0, false);
1879e3b55780SDimitry Andric     const AllocaInst *Base = dyn_cast<AllocaInst>(
1880e3b55780SDimitry Andric         Arg->stripAndAccumulateConstantOffsets(DL, TmpOffset, true));
1881e3b55780SDimitry Andric     if (!Base) {
1882e3b55780SDimitry Andric       LLVM_DEBUG(errs() << " | SKIP: Couldn't walk back to base storage\n");
1883e3b55780SDimitry Andric       continue;
1884e3b55780SDimitry Andric     }
1885e3b55780SDimitry Andric 
1886e3b55780SDimitry Andric     assert(Base);
1887e3b55780SDimitry Andric     LLVM_DEBUG(errs() << " | BASE: " << *Base << "\n");
1888e3b55780SDimitry Andric     // We only need to process each base address once - skip any duplicates.
1889e3b55780SDimitry Andric     if (!SeenBases.insert(Base).second)
1890e3b55780SDimitry Andric       continue;
1891e3b55780SDimitry Andric 
1892e3b55780SDimitry Andric     // Find all local variables associated with the backing storage.
18934df029ccSDimitry Andric     auto CollectAssignsForStorage = [&](auto *DbgAssign) {
1894e3b55780SDimitry Andric       // Skip variables from inlined functions - they are not local variables.
18954df029ccSDimitry Andric       if (DbgAssign->getDebugLoc().getInlinedAt())
18964df029ccSDimitry Andric         return;
18974df029ccSDimitry Andric       LLVM_DEBUG(errs() << " > DEF : " << *DbgAssign << "\n");
18984df029ccSDimitry Andric       EscapedLocals[Base].insert(at::VarRecord(DbgAssign));
18994df029ccSDimitry Andric     };
19004df029ccSDimitry Andric     for_each(at::getAssignmentMarkers(Base), CollectAssignsForStorage);
1901ac9a064cSDimitry Andric     for_each(at::getDVRAssignmentMarkers(Base), CollectAssignsForStorage);
1902e3b55780SDimitry Andric   }
1903e3b55780SDimitry Andric   return EscapedLocals;
1904e3b55780SDimitry Andric }
1905e3b55780SDimitry Andric 
trackInlinedStores(Function::iterator Start,Function::iterator End,const CallBase & CB)1906e3b55780SDimitry Andric static void trackInlinedStores(Function::iterator Start, Function::iterator End,
1907e3b55780SDimitry Andric                                const CallBase &CB) {
1908e3b55780SDimitry Andric   LLVM_DEBUG(errs() << "trackInlinedStores into "
1909e3b55780SDimitry Andric                     << Start->getParent()->getName() << " from "
1910e3b55780SDimitry Andric                     << CB.getCalledFunction()->getName() << "\n");
1911e3b55780SDimitry Andric   std::unique_ptr<DataLayout> DL = std::make_unique<DataLayout>(CB.getModule());
1912e3b55780SDimitry Andric   at::trackAssignments(Start, End, collectEscapedLocals(*DL, CB), *DL);
1913e3b55780SDimitry Andric }
1914e3b55780SDimitry Andric 
1915e3b55780SDimitry Andric /// Update inlined instructions' DIAssignID metadata. We need to do this
1916e3b55780SDimitry Andric /// otherwise a function inlined more than once into the same function
1917e3b55780SDimitry Andric /// will cause DIAssignID to be shared by many instructions.
fixupAssignments(Function::iterator Start,Function::iterator End)1918e3b55780SDimitry Andric static void fixupAssignments(Function::iterator Start, Function::iterator End) {
1919e3b55780SDimitry Andric   DenseMap<DIAssignID *, DIAssignID *> Map;
1920e3b55780SDimitry Andric   // Loop over all the inlined instructions. If we find a DIAssignID
1921e3b55780SDimitry Andric   // attachment or use, replace it with a new version.
1922e3b55780SDimitry Andric   for (auto BBI = Start; BBI != End; ++BBI) {
1923ac9a064cSDimitry Andric     for (Instruction &I : *BBI)
1924ac9a064cSDimitry Andric       at::remapAssignID(Map, I);
1925e3b55780SDimitry Andric   }
1926e3b55780SDimitry Andric }
1927e3b55780SDimitry Andric #undef DEBUG_TYPE
1928e3b55780SDimitry Andric #define DEBUG_TYPE "inline-function"
1929e3b55780SDimitry Andric 
193071d5a254SDimitry Andric /// Update the block frequencies of the caller after a callee has been inlined.
193171d5a254SDimitry Andric ///
193271d5a254SDimitry Andric /// Each block cloned into the caller has its block frequency scaled by the
193371d5a254SDimitry Andric /// ratio of CallSiteFreq/CalleeEntryFreq. This ensures that the cloned copy of
193471d5a254SDimitry Andric /// callee's entry block gets the same frequency as the callsite block and the
193571d5a254SDimitry Andric /// relative frequencies of all cloned blocks remain the same after cloning.
updateCallerBFI(BasicBlock * CallSiteBlock,const ValueToValueMapTy & VMap,BlockFrequencyInfo * CallerBFI,BlockFrequencyInfo * CalleeBFI,const BasicBlock & CalleeEntryBlock)193671d5a254SDimitry Andric static void updateCallerBFI(BasicBlock *CallSiteBlock,
193771d5a254SDimitry Andric                             const ValueToValueMapTy &VMap,
193871d5a254SDimitry Andric                             BlockFrequencyInfo *CallerBFI,
193971d5a254SDimitry Andric                             BlockFrequencyInfo *CalleeBFI,
194071d5a254SDimitry Andric                             const BasicBlock &CalleeEntryBlock) {
194171d5a254SDimitry Andric   SmallPtrSet<BasicBlock *, 16> ClonedBBs;
1942706b4fc4SDimitry Andric   for (auto Entry : VMap) {
194371d5a254SDimitry Andric     if (!isa<BasicBlock>(Entry.first) || !Entry.second)
194471d5a254SDimitry Andric       continue;
194571d5a254SDimitry Andric     auto *OrigBB = cast<BasicBlock>(Entry.first);
194671d5a254SDimitry Andric     auto *ClonedBB = cast<BasicBlock>(Entry.second);
1947b1c73532SDimitry Andric     BlockFrequency Freq = CalleeBFI->getBlockFreq(OrigBB);
194871d5a254SDimitry Andric     if (!ClonedBBs.insert(ClonedBB).second) {
194971d5a254SDimitry Andric       // Multiple blocks in the callee might get mapped to one cloned block in
195071d5a254SDimitry Andric       // the caller since we prune the callee as we clone it. When that happens,
195171d5a254SDimitry Andric       // we want to use the maximum among the original blocks' frequencies.
1952b1c73532SDimitry Andric       BlockFrequency NewFreq = CallerBFI->getBlockFreq(ClonedBB);
195371d5a254SDimitry Andric       if (NewFreq > Freq)
195471d5a254SDimitry Andric         Freq = NewFreq;
195571d5a254SDimitry Andric     }
195671d5a254SDimitry Andric     CallerBFI->setBlockFreq(ClonedBB, Freq);
195771d5a254SDimitry Andric   }
195871d5a254SDimitry Andric   BasicBlock *EntryClone = cast<BasicBlock>(VMap.lookup(&CalleeEntryBlock));
195971d5a254SDimitry Andric   CallerBFI->setBlockFreqAndScale(
1960b1c73532SDimitry Andric       EntryClone, CallerBFI->getBlockFreq(CallSiteBlock), ClonedBBs);
196171d5a254SDimitry Andric }
196271d5a254SDimitry Andric 
196371d5a254SDimitry Andric /// Update the branch metadata for cloned call instructions.
updateCallProfile(Function * Callee,const ValueToValueMapTy & VMap,const ProfileCount & CalleeEntryCount,const CallBase & TheCall,ProfileSummaryInfo * PSI,BlockFrequencyInfo * CallerBFI)196471d5a254SDimitry Andric static void updateCallProfile(Function *Callee, const ValueToValueMapTy &VMap,
1965eb11fae6SDimitry Andric                               const ProfileCount &CalleeEntryCount,
1966cfca06d7SDimitry Andric                               const CallBase &TheCall, ProfileSummaryInfo *PSI,
1967ab44ce3dSDimitry Andric                               BlockFrequencyInfo *CallerBFI) {
1968c0981da4SDimitry Andric   if (CalleeEntryCount.isSynthetic() || CalleeEntryCount.getCount() < 1)
196971d5a254SDimitry Andric     return;
1970e3b55780SDimitry Andric   auto CallSiteCount =
1971e3b55780SDimitry Andric       PSI ? PSI->getProfileCount(TheCall, CallerBFI) : std::nullopt;
1972e6d15924SDimitry Andric   int64_t CallCount =
1973145449b1SDimitry Andric       std::min(CallSiteCount.value_or(0), CalleeEntryCount.getCount());
1974e6d15924SDimitry Andric   updateProfileCallee(Callee, -CallCount, &VMap);
197571d5a254SDimitry Andric }
197671d5a254SDimitry Andric 
updateProfileCallee(Function * Callee,int64_t EntryDelta,const ValueMap<const Value *,WeakTrackingVH> * VMap)1977e6d15924SDimitry Andric void llvm::updateProfileCallee(
1978c0981da4SDimitry Andric     Function *Callee, int64_t EntryDelta,
1979e6d15924SDimitry Andric     const ValueMap<const Value *, WeakTrackingVH> *VMap) {
1980eb11fae6SDimitry Andric   auto CalleeCount = Callee->getEntryCount();
1981145449b1SDimitry Andric   if (!CalleeCount)
198271d5a254SDimitry Andric     return;
1983e6d15924SDimitry Andric 
1984c0981da4SDimitry Andric   const uint64_t PriorEntryCount = CalleeCount->getCount();
1985e6d15924SDimitry Andric 
198671d5a254SDimitry Andric   // Since CallSiteCount is an estimate, it could exceed the original callee
1987e6d15924SDimitry Andric   // count and has to be set to 0 so guard against underflow.
1988c0981da4SDimitry Andric   const uint64_t NewEntryCount =
1989c0981da4SDimitry Andric       (EntryDelta < 0 && static_cast<uint64_t>(-EntryDelta) > PriorEntryCount)
1990c0981da4SDimitry Andric           ? 0
1991c0981da4SDimitry Andric           : PriorEntryCount + EntryDelta;
1992e6d15924SDimitry Andric 
1993ac9a064cSDimitry Andric   auto updateVTableProfWeight = [](CallBase *CB, const uint64_t NewEntryCount,
1994ac9a064cSDimitry Andric                                    const uint64_t PriorEntryCount) {
1995ac9a064cSDimitry Andric     Instruction *VPtr = PGOIndirectCallVisitor::tryGetVTableInstruction(CB);
1996ac9a064cSDimitry Andric     if (VPtr)
1997ac9a064cSDimitry Andric       scaleProfData(*VPtr, NewEntryCount, PriorEntryCount);
1998ac9a064cSDimitry Andric   };
1999ac9a064cSDimitry Andric 
2000e6d15924SDimitry Andric   // During inlining ?
2001e6d15924SDimitry Andric   if (VMap) {
2002c0981da4SDimitry Andric     uint64_t CloneEntryCount = PriorEntryCount - NewEntryCount;
2003ac9a064cSDimitry Andric     for (auto Entry : *VMap) {
2004e6d15924SDimitry Andric       if (isa<CallInst>(Entry.first))
2005ac9a064cSDimitry Andric         if (auto *CI = dyn_cast_or_null<CallInst>(Entry.second)) {
2006c0981da4SDimitry Andric           CI->updateProfWeight(CloneEntryCount, PriorEntryCount);
2007ac9a064cSDimitry Andric           updateVTableProfWeight(CI, CloneEntryCount, PriorEntryCount);
2008ac9a064cSDimitry Andric         }
2009ac9a064cSDimitry Andric 
2010ac9a064cSDimitry Andric       if (isa<InvokeInst>(Entry.first))
2011ac9a064cSDimitry Andric         if (auto *II = dyn_cast_or_null<InvokeInst>(Entry.second)) {
2012ac9a064cSDimitry Andric           II->updateProfWeight(CloneEntryCount, PriorEntryCount);
2013ac9a064cSDimitry Andric           updateVTableProfWeight(II, CloneEntryCount, PriorEntryCount);
2014ac9a064cSDimitry Andric         }
2015ac9a064cSDimitry Andric     }
2016e6d15924SDimitry Andric   }
2017706b4fc4SDimitry Andric 
2018c0981da4SDimitry Andric   if (EntryDelta) {
2019c0981da4SDimitry Andric     Callee->setEntryCount(NewEntryCount);
2020706b4fc4SDimitry Andric 
2021e6d15924SDimitry Andric     for (BasicBlock &BB : *Callee)
2022e6d15924SDimitry Andric       // No need to update the callsite if it is pruned during inlining.
2023e6d15924SDimitry Andric       if (!VMap || VMap->count(&BB))
2024ac9a064cSDimitry Andric         for (Instruction &I : BB) {
2025ac9a064cSDimitry Andric           if (CallInst *CI = dyn_cast<CallInst>(&I)) {
2026c0981da4SDimitry Andric             CI->updateProfWeight(NewEntryCount, PriorEntryCount);
2027ac9a064cSDimitry Andric             updateVTableProfWeight(CI, NewEntryCount, PriorEntryCount);
2028ac9a064cSDimitry Andric           }
2029ac9a064cSDimitry Andric           if (InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
2030ac9a064cSDimitry Andric             II->updateProfWeight(NewEntryCount, PriorEntryCount);
2031ac9a064cSDimitry Andric             updateVTableProfWeight(II, NewEntryCount, PriorEntryCount);
2032ac9a064cSDimitry Andric           }
2033ac9a064cSDimitry Andric         }
203471d5a254SDimitry Andric   }
2035706b4fc4SDimitry Andric }
2036411bd29eSDimitry Andric 
2037344a3780SDimitry Andric /// An operand bundle "clang.arc.attachedcall" on a call indicates the call
2038344a3780SDimitry Andric /// result is implicitly consumed by a call to retainRV or claimRV immediately
2039344a3780SDimitry Andric /// after the call. This function inlines the retainRV/claimRV calls.
2040344a3780SDimitry Andric ///
2041344a3780SDimitry Andric /// There are three cases to consider:
2042344a3780SDimitry Andric ///
2043344a3780SDimitry Andric /// 1. If there is a call to autoreleaseRV that takes a pointer to the returned
2044344a3780SDimitry Andric ///    object in the callee return block, the autoreleaseRV call and the
2045344a3780SDimitry Andric ///    retainRV/claimRV call in the caller cancel out. If the call in the caller
2046344a3780SDimitry Andric ///    is a claimRV call, a call to objc_release is emitted.
2047344a3780SDimitry Andric ///
2048344a3780SDimitry Andric /// 2. If there is a call in the callee return block that doesn't have operand
2049344a3780SDimitry Andric ///    bundle "clang.arc.attachedcall", the operand bundle on the original call
2050344a3780SDimitry Andric ///    is transferred to the call in the callee.
2051344a3780SDimitry Andric ///
2052344a3780SDimitry Andric /// 3. Otherwise, a call to objc_retain is inserted if the call in the caller is
2053344a3780SDimitry Andric ///    a retainRV call.
2054344a3780SDimitry Andric static void
inlineRetainOrClaimRVCalls(CallBase & CB,objcarc::ARCInstKind RVCallKind,const SmallVectorImpl<ReturnInst * > & Returns)2055c0981da4SDimitry Andric inlineRetainOrClaimRVCalls(CallBase &CB, objcarc::ARCInstKind RVCallKind,
2056344a3780SDimitry Andric                            const SmallVectorImpl<ReturnInst *> &Returns) {
2057344a3780SDimitry Andric   Module *Mod = CB.getModule();
2058c0981da4SDimitry Andric   assert(objcarc::isRetainOrClaimRV(RVCallKind) && "unexpected ARC function");
2059c0981da4SDimitry Andric   bool IsRetainRV = RVCallKind == objcarc::ARCInstKind::RetainRV,
20606f8fc217SDimitry Andric        IsUnsafeClaimRV = !IsRetainRV;
2061344a3780SDimitry Andric 
2062344a3780SDimitry Andric   for (auto *RI : Returns) {
2063344a3780SDimitry Andric     Value *RetOpnd = objcarc::GetRCIdentityRoot(RI->getOperand(0));
2064344a3780SDimitry Andric     bool InsertRetainCall = IsRetainRV;
2065344a3780SDimitry Andric     IRBuilder<> Builder(RI->getContext());
2066344a3780SDimitry Andric 
2067344a3780SDimitry Andric     // Walk backwards through the basic block looking for either a matching
2068344a3780SDimitry Andric     // autoreleaseRV call or an unannotated call.
2069c0981da4SDimitry Andric     auto InstRange = llvm::make_range(++(RI->getIterator().getReverse()),
2070c0981da4SDimitry Andric                                       RI->getParent()->rend());
2071c0981da4SDimitry Andric     for (Instruction &I : llvm::make_early_inc_range(InstRange)) {
2072344a3780SDimitry Andric       // Ignore casts.
2073c0981da4SDimitry Andric       if (isa<CastInst>(I))
2074344a3780SDimitry Andric         continue;
2075344a3780SDimitry Andric 
2076c0981da4SDimitry Andric       if (auto *II = dyn_cast<IntrinsicInst>(&I)) {
2077c0981da4SDimitry Andric         if (II->getIntrinsicID() != Intrinsic::objc_autoreleaseReturnValue ||
2078c0981da4SDimitry Andric             !II->hasNUses(0) ||
2079c0981da4SDimitry Andric             objcarc::GetRCIdentityRoot(II->getOperand(0)) != RetOpnd)
2080c0981da4SDimitry Andric           break;
2081c0981da4SDimitry Andric 
2082344a3780SDimitry Andric         // If we've found a matching authoreleaseRV call:
2083344a3780SDimitry Andric         // - If claimRV is attached to the call, insert a call to objc_release
2084344a3780SDimitry Andric         //   and erase the autoreleaseRV call.
2085344a3780SDimitry Andric         // - If retainRV is attached to the call, just erase the autoreleaseRV
2086344a3780SDimitry Andric         //   call.
20876f8fc217SDimitry Andric         if (IsUnsafeClaimRV) {
2088344a3780SDimitry Andric           Builder.SetInsertPoint(II);
2089344a3780SDimitry Andric           Function *IFn =
2090344a3780SDimitry Andric               Intrinsic::getDeclaration(Mod, Intrinsic::objc_release);
2091b1c73532SDimitry Andric           Builder.CreateCall(IFn, RetOpnd, "");
2092344a3780SDimitry Andric         }
2093344a3780SDimitry Andric         II->eraseFromParent();
2094344a3780SDimitry Andric         InsertRetainCall = false;
2095c0981da4SDimitry Andric         break;
2096344a3780SDimitry Andric       }
2097c0981da4SDimitry Andric 
2098c0981da4SDimitry Andric       auto *CI = dyn_cast<CallInst>(&I);
2099c0981da4SDimitry Andric 
2100c0981da4SDimitry Andric       if (!CI)
2101c0981da4SDimitry Andric         break;
2102c0981da4SDimitry Andric 
2103c0981da4SDimitry Andric       if (objcarc::GetRCIdentityRoot(CI) != RetOpnd ||
2104c0981da4SDimitry Andric           objcarc::hasAttachedCallOpBundle(CI))
2105c0981da4SDimitry Andric         break;
2106c0981da4SDimitry Andric 
2107344a3780SDimitry Andric       // If we've found an unannotated call that defines RetOpnd, add a
2108344a3780SDimitry Andric       // "clang.arc.attachedcall" operand bundle.
2109c0981da4SDimitry Andric       Value *BundleArgs[] = {*objcarc::getAttachedARCFunction(&CB)};
2110344a3780SDimitry Andric       OperandBundleDef OB("clang.arc.attachedcall", BundleArgs);
2111344a3780SDimitry Andric       auto *NewCall = CallBase::addOperandBundle(
2112ac9a064cSDimitry Andric           CI, LLVMContext::OB_clang_arc_attachedcall, OB, CI->getIterator());
2113344a3780SDimitry Andric       NewCall->copyMetadata(*CI);
2114344a3780SDimitry Andric       CI->replaceAllUsesWith(NewCall);
2115344a3780SDimitry Andric       CI->eraseFromParent();
2116344a3780SDimitry Andric       InsertRetainCall = false;
2117344a3780SDimitry Andric       break;
2118344a3780SDimitry Andric     }
2119344a3780SDimitry Andric 
2120344a3780SDimitry Andric     if (InsertRetainCall) {
2121344a3780SDimitry Andric       // The retainRV is attached to the call and we've failed to find a
2122344a3780SDimitry Andric       // matching autoreleaseRV or an annotated call in the callee. Emit a call
2123344a3780SDimitry Andric       // to objc_retain.
2124344a3780SDimitry Andric       Builder.SetInsertPoint(RI);
2125344a3780SDimitry Andric       Function *IFn = Intrinsic::getDeclaration(Mod, Intrinsic::objc_retain);
2126b1c73532SDimitry Andric       Builder.CreateCall(IFn, RetOpnd, "");
2127344a3780SDimitry Andric     }
2128344a3780SDimitry Andric   }
2129344a3780SDimitry Andric }
2130344a3780SDimitry Andric 
21315a5ac124SDimitry Andric /// This function inlines the called function into the basic block of the
21325a5ac124SDimitry Andric /// caller. This returns false if it is not possible to inline this call.
21335a5ac124SDimitry Andric /// The program is still in a well defined state if this occurs though.
213463faed5bSDimitry Andric ///
213563faed5bSDimitry Andric /// Note that this only does one level of inlining.  For example, if the
213663faed5bSDimitry Andric /// instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now
213763faed5bSDimitry Andric /// exists in the instruction stream.  Similarly this will inline a recursive
213863faed5bSDimitry Andric /// function by one level.
InlineFunction(CallBase & CB,InlineFunctionInfo & IFI,bool MergeAttributes,AAResults * CalleeAAR,bool InsertLifetime,Function * ForwardVarArgsTo)2139cfca06d7SDimitry Andric llvm::InlineResult llvm::InlineFunction(CallBase &CB, InlineFunctionInfo &IFI,
2140e3b55780SDimitry Andric                                         bool MergeAttributes,
2141d8e91e46SDimitry Andric                                         AAResults *CalleeAAR,
2142d8e91e46SDimitry Andric                                         bool InsertLifetime,
2143044eb2f6SDimitry Andric                                         Function *ForwardVarArgsTo) {
2144cfca06d7SDimitry Andric   assert(CB.getParent() && CB.getFunction() && "Instruction not in function!");
2145009b1c42SEd Schouten 
2146e6d15924SDimitry Andric   // FIXME: we don't inline callbr yet.
2147cfca06d7SDimitry Andric   if (isa<CallBrInst>(CB))
2148cfca06d7SDimitry Andric     return InlineResult::failure("We don't inline callbr yet.");
2149e6d15924SDimitry Andric 
2150d7f7719eSRoman Divacky   // If IFI has any state in it, zap it before we fill it in.
2151d7f7719eSRoman Divacky   IFI.reset();
2152d7f7719eSRoman Divacky 
2153cfca06d7SDimitry Andric   Function *CalledFunc = CB.getCalledFunction();
21545ca98fd9SDimitry Andric   if (!CalledFunc ||               // Can't inline external function or indirect
2155eb11fae6SDimitry Andric       CalledFunc->isDeclaration()) // call!
2156cfca06d7SDimitry Andric     return InlineResult::failure("external or indirect");
2157009b1c42SEd Schouten 
2158dd58ef01SDimitry Andric   // The inliner does not know how to inline through calls with operand bundles
2159dd58ef01SDimitry Andric   // in general ...
2160b1c73532SDimitry Andric   Value *ConvergenceControlToken = nullptr;
2161cfca06d7SDimitry Andric   if (CB.hasOperandBundles()) {
2162cfca06d7SDimitry Andric     for (int i = 0, e = CB.getNumOperandBundles(); i != e; ++i) {
2163b1c73532SDimitry Andric       auto OBUse = CB.getOperandBundleAt(i);
2164b1c73532SDimitry Andric       uint32_t Tag = OBUse.getTagID();
2165dd58ef01SDimitry Andric       // ... but it knows how to inline through "deopt" operand bundles ...
2166dd58ef01SDimitry Andric       if (Tag == LLVMContext::OB_deopt)
2167dd58ef01SDimitry Andric         continue;
2168dd58ef01SDimitry Andric       // ... and "funclet" operand bundles.
2169dd58ef01SDimitry Andric       if (Tag == LLVMContext::OB_funclet)
2170dd58ef01SDimitry Andric         continue;
2171344a3780SDimitry Andric       if (Tag == LLVMContext::OB_clang_arc_attachedcall)
2172344a3780SDimitry Andric         continue;
2173e3b55780SDimitry Andric       if (Tag == LLVMContext::OB_kcfi)
2174e3b55780SDimitry Andric         continue;
2175b1c73532SDimitry Andric       if (Tag == LLVMContext::OB_convergencectrl) {
2176b1c73532SDimitry Andric         ConvergenceControlToken = OBUse.Inputs[0].get();
2177b1c73532SDimitry Andric         continue;
2178b1c73532SDimitry Andric       }
2179dd58ef01SDimitry Andric 
2180cfca06d7SDimitry Andric       return InlineResult::failure("unsupported operand bundle");
2181dd58ef01SDimitry Andric     }
2182dd58ef01SDimitry Andric   }
2183dd58ef01SDimitry Andric 
2184b1c73532SDimitry Andric   // FIXME: The check below is redundant and incomplete. According to spec, if a
2185b1c73532SDimitry Andric   // convergent call is missing a token, then the caller is using uncontrolled
2186b1c73532SDimitry Andric   // convergence. If the callee has an entry intrinsic, then the callee is using
2187b1c73532SDimitry Andric   // controlled convergence, and the call cannot be inlined. A proper
2188b1c73532SDimitry Andric   // implemenation of this check requires a whole new analysis that identifies
2189b1c73532SDimitry Andric   // convergence in every function. For now, we skip that and just do this one
2190b1c73532SDimitry Andric   // cursory check. The underlying assumption is that in a compiler flow that
2191b1c73532SDimitry Andric   // fully implements convergence control tokens, there is no mixing of
2192b1c73532SDimitry Andric   // controlled and uncontrolled convergent operations in the whole program.
2193b1c73532SDimitry Andric   if (CB.isConvergent()) {
2194b1c73532SDimitry Andric     auto *I = CalledFunc->getEntryBlock().getFirstNonPHI();
2195b1c73532SDimitry Andric     if (auto *IntrinsicCall = dyn_cast<IntrinsicInst>(I)) {
2196b1c73532SDimitry Andric       if (IntrinsicCall->getIntrinsicID() ==
2197b1c73532SDimitry Andric           Intrinsic::experimental_convergence_entry) {
2198b1c73532SDimitry Andric         if (!ConvergenceControlToken) {
2199b1c73532SDimitry Andric           return InlineResult::failure(
2200b1c73532SDimitry Andric               "convergent call needs convergencectrl operand");
2201b1c73532SDimitry Andric         }
2202b1c73532SDimitry Andric       }
2203b1c73532SDimitry Andric     }
2204b1c73532SDimitry Andric   }
2205b1c73532SDimitry Andric 
2206009b1c42SEd Schouten   // If the call to the callee cannot throw, set the 'nounwind' flag on any
2207009b1c42SEd Schouten   // calls that we inline.
2208cfca06d7SDimitry Andric   bool MarkNoUnwind = CB.doesNotThrow();
2209009b1c42SEd Schouten 
2210cfca06d7SDimitry Andric   BasicBlock *OrigBB = CB.getParent();
2211009b1c42SEd Schouten   Function *Caller = OrigBB->getParent();
2212009b1c42SEd Schouten 
2213009b1c42SEd Schouten   // GC poses two hazards to inlining, which only occur when the callee has GC:
2214009b1c42SEd Schouten   //  1. If the caller has no GC, then the callee's GC must be propagated to the
2215009b1c42SEd Schouten   //     caller.
2216009b1c42SEd Schouten   //  2. If the caller has a differing GC, it is invalid to inline.
2217009b1c42SEd Schouten   if (CalledFunc->hasGC()) {
2218009b1c42SEd Schouten     if (!Caller->hasGC())
2219009b1c42SEd Schouten       Caller->setGC(CalledFunc->getGC());
2220009b1c42SEd Schouten     else if (CalledFunc->getGC() != Caller->getGC())
2221cfca06d7SDimitry Andric       return InlineResult::failure("incompatible GC");
2222009b1c42SEd Schouten   }
2223009b1c42SEd Schouten 
222463faed5bSDimitry Andric   // Get the personality function from the callee if it contains a landing pad.
22253a0822f0SDimitry Andric   Constant *CalledPersonality =
2226dd58ef01SDimitry Andric       CalledFunc->hasPersonalityFn()
2227dd58ef01SDimitry Andric           ? CalledFunc->getPersonalityFn()->stripPointerCasts()
2228dd58ef01SDimitry Andric           : nullptr;
222963faed5bSDimitry Andric 
223030815c53SDimitry Andric   // Find the personality function used by the landing pads of the caller. If it
223130815c53SDimitry Andric   // exists, then check to see that it matches the personality function used in
223230815c53SDimitry Andric   // the callee.
22333a0822f0SDimitry Andric   Constant *CallerPersonality =
2234dd58ef01SDimitry Andric       Caller->hasPersonalityFn()
2235dd58ef01SDimitry Andric           ? Caller->getPersonalityFn()->stripPointerCasts()
2236dd58ef01SDimitry Andric           : nullptr;
22373a0822f0SDimitry Andric   if (CalledPersonality) {
22383a0822f0SDimitry Andric     if (!CallerPersonality)
22393a0822f0SDimitry Andric       Caller->setPersonalityFn(CalledPersonality);
224030815c53SDimitry Andric     // If the personality functions match, then we can perform the
224130815c53SDimitry Andric     // inlining. Otherwise, we can't inline.
224230815c53SDimitry Andric     // TODO: This isn't 100% true. Some personality functions are proper
224330815c53SDimitry Andric     //       supersets of others and can be used in place of the other.
22443a0822f0SDimitry Andric     else if (CalledPersonality != CallerPersonality)
2245cfca06d7SDimitry Andric       return InlineResult::failure("incompatible personality");
224663faed5bSDimitry Andric   }
224730815c53SDimitry Andric 
2248dd58ef01SDimitry Andric   // We need to figure out which funclet the callsite was in so that we may
2249dd58ef01SDimitry Andric   // properly nest the callee.
2250dd58ef01SDimitry Andric   Instruction *CallSiteEHPad = nullptr;
2251dd58ef01SDimitry Andric   if (CallerPersonality) {
2252dd58ef01SDimitry Andric     EHPersonality Personality = classifyEHPersonality(CallerPersonality);
2253eb11fae6SDimitry Andric     if (isScopedEHPersonality(Personality)) {
2254e3b55780SDimitry Andric       std::optional<OperandBundleUse> ParentFunclet =
2255cfca06d7SDimitry Andric           CB.getOperandBundle(LLVMContext::OB_funclet);
2256dd58ef01SDimitry Andric       if (ParentFunclet)
2257dd58ef01SDimitry Andric         CallSiteEHPad = cast<FuncletPadInst>(ParentFunclet->Inputs.front());
2258dd58ef01SDimitry Andric 
2259dd58ef01SDimitry Andric       // OK, the inlining site is legal.  What about the target function?
2260dd58ef01SDimitry Andric 
2261dd58ef01SDimitry Andric       if (CallSiteEHPad) {
2262dd58ef01SDimitry Andric         if (Personality == EHPersonality::MSVC_CXX) {
2263dd58ef01SDimitry Andric           // The MSVC personality cannot tolerate catches getting inlined into
2264dd58ef01SDimitry Andric           // cleanup funclets.
2265dd58ef01SDimitry Andric           if (isa<CleanupPadInst>(CallSiteEHPad)) {
2266dd58ef01SDimitry Andric             // Ok, the call site is within a cleanuppad.  Let's check the callee
2267dd58ef01SDimitry Andric             // for catchpads.
2268dd58ef01SDimitry Andric             for (const BasicBlock &CalledBB : *CalledFunc) {
2269dd58ef01SDimitry Andric               if (isa<CatchSwitchInst>(CalledBB.getFirstNonPHI()))
2270cfca06d7SDimitry Andric                 return InlineResult::failure("catch in cleanup funclet");
2271dd58ef01SDimitry Andric             }
2272dd58ef01SDimitry Andric           }
2273dd58ef01SDimitry Andric         } else if (isAsynchronousEHPersonality(Personality)) {
2274dd58ef01SDimitry Andric           // SEH is even less tolerant, there may not be any sort of exceptional
2275dd58ef01SDimitry Andric           // funclet in the callee.
2276dd58ef01SDimitry Andric           for (const BasicBlock &CalledBB : *CalledFunc) {
2277dd58ef01SDimitry Andric             if (CalledBB.isEHPad())
2278cfca06d7SDimitry Andric               return InlineResult::failure("SEH in cleanup funclet");
2279dd58ef01SDimitry Andric           }
2280dd58ef01SDimitry Andric         }
2281dd58ef01SDimitry Andric       }
2282dd58ef01SDimitry Andric     }
2283dd58ef01SDimitry Andric   }
2284dd58ef01SDimitry Andric 
228501095a5dSDimitry Andric   // Determine if we are dealing with a call in an EHPad which does not unwind
228601095a5dSDimitry Andric   // to caller.
228701095a5dSDimitry Andric   bool EHPadForCallUnwindsLocally = false;
2288cfca06d7SDimitry Andric   if (CallSiteEHPad && isa<CallInst>(CB)) {
228901095a5dSDimitry Andric     UnwindDestMemoTy FuncletUnwindMap;
229001095a5dSDimitry Andric     Value *CallSiteUnwindDestToken =
229101095a5dSDimitry Andric         getUnwindDestToken(CallSiteEHPad, FuncletUnwindMap);
229201095a5dSDimitry Andric 
229301095a5dSDimitry Andric     EHPadForCallUnwindsLocally =
229401095a5dSDimitry Andric         CallSiteUnwindDestToken &&
229501095a5dSDimitry Andric         !isa<ConstantTokenNone>(CallSiteUnwindDestToken);
229601095a5dSDimitry Andric   }
229701095a5dSDimitry Andric 
2298009b1c42SEd Schouten   // Get an iterator to the last basic block in the function, which will have
2299009b1c42SEd Schouten   // the new function inlined after it.
2300dd58ef01SDimitry Andric   Function::iterator LastBlock = --Caller->end();
2301009b1c42SEd Schouten 
2302009b1c42SEd Schouten   // Make sure to capture all of the return instructions from the cloned
2303009b1c42SEd Schouten   // function.
230459850d08SRoman Divacky   SmallVector<ReturnInst*, 8> Returns;
2305009b1c42SEd Schouten   ClonedCodeInfo InlinedFunctionInfo;
2306009b1c42SEd Schouten   Function::iterator FirstNewBlock;
2307009b1c42SEd Schouten 
230866e41e3cSRoman Divacky   { // Scope to destroy VMap after cloning.
2309cf099d11SDimitry Andric     ValueToValueMapTy VMap;
2310c0981da4SDimitry Andric     struct ByValInit {
2311c0981da4SDimitry Andric       Value *Dst;
2312c0981da4SDimitry Andric       Value *Src;
2313c0981da4SDimitry Andric       Type *Ty;
2314c0981da4SDimitry Andric     };
23155ca98fd9SDimitry Andric     // Keep a list of pair (dst, src) to emit byval initializations.
2316c0981da4SDimitry Andric     SmallVector<ByValInit, 4> ByValInits;
2317009b1c42SEd Schouten 
2318b60736ecSDimitry Andric     // When inlining a function that contains noalias scope metadata,
2319b60736ecSDimitry Andric     // this metadata needs to be cloned so that the inlined blocks
2320b60736ecSDimitry Andric     // have different "unique scopes" at every call site.
2321b60736ecSDimitry Andric     // Track the metadata that must be cloned. Do this before other changes to
2322b60736ecSDimitry Andric     // the function, so that we do not get in trouble when inlining caller ==
2323b60736ecSDimitry Andric     // callee.
2324b60736ecSDimitry Andric     ScopedAliasMetadataDeepCloner SAMetadataCloner(CB.getCalledFunction());
2325b60736ecSDimitry Andric 
2326ac9a064cSDimitry Andric     auto &DL = Caller->getDataLayout();
23275a5ac124SDimitry Andric 
2328009b1c42SEd Schouten     // Calculate the vector of arguments to pass into the function cloner, which
2329009b1c42SEd Schouten     // matches up the formal to the actual argument values.
2330cfca06d7SDimitry Andric     auto AI = CB.arg_begin();
2331009b1c42SEd Schouten     unsigned ArgNo = 0;
233271d5a254SDimitry Andric     for (Function::arg_iterator I = CalledFunc->arg_begin(),
2333009b1c42SEd Schouten          E = CalledFunc->arg_end(); I != E; ++I, ++AI, ++ArgNo) {
2334009b1c42SEd Schouten       Value *ActualArg = *AI;
2335009b1c42SEd Schouten 
2336009b1c42SEd Schouten       // When byval arguments actually inlined, we need to make the copy implied
2337009b1c42SEd Schouten       // by them explicit.  However, we don't do this if the callee is readonly
2338009b1c42SEd Schouten       // or readnone, because the copy would be unneeded: the callee doesn't
2339009b1c42SEd Schouten       // modify the struct.
2340cfca06d7SDimitry Andric       if (CB.isByValArgument(ArgNo)) {
2341c0981da4SDimitry Andric         ActualArg = HandleByValArgument(CB.getParamByValType(ArgNo), ActualArg,
2342c0981da4SDimitry Andric                                         &CB, CalledFunc, IFI,
2343e3b55780SDimitry Andric                                         CalledFunc->getParamAlign(ArgNo));
23445ca98fd9SDimitry Andric         if (ActualArg != *AI)
2345c0981da4SDimitry Andric           ByValInits.push_back(
2346c0981da4SDimitry Andric               {ActualArg, (Value *)*AI, CB.getParamByValType(ArgNo)});
2347009b1c42SEd Schouten       }
2348009b1c42SEd Schouten 
2349dd58ef01SDimitry Andric       VMap[&*I] = ActualArg;
2350009b1c42SEd Schouten     }
2351009b1c42SEd Schouten 
2352cfca06d7SDimitry Andric     // TODO: Remove this when users have been updated to the assume bundles.
235367c32a98SDimitry Andric     // Add alignment assumptions if necessary. We do this before the inlined
235467c32a98SDimitry Andric     // instructions are actually cloned into the caller so that we can easily
235567c32a98SDimitry Andric     // check what will be known at the start of the inlined code.
2356cfca06d7SDimitry Andric     AddAlignmentAssumptions(CB, IFI);
2357cfca06d7SDimitry Andric 
2358cfca06d7SDimitry Andric     AssumptionCache *AC =
2359cfca06d7SDimitry Andric         IFI.GetAssumptionCache ? &IFI.GetAssumptionCache(*Caller) : nullptr;
2360cfca06d7SDimitry Andric 
2361cfca06d7SDimitry Andric     /// Preserve all attributes on of the call and its parameters.
2362cfca06d7SDimitry Andric     salvageKnowledge(&CB, AC);
236367c32a98SDimitry Andric 
2364009b1c42SEd Schouten     // We want the inliner to prune the code as it copies.  We would LOVE to
2365009b1c42SEd Schouten     // have no dead or constant instructions leftover after inlining occurs
2366009b1c42SEd Schouten     // (which can happen, e.g., because an argument was constant), but we'll be
2367009b1c42SEd Schouten     // happy with whatever the cloner can do.
2368d39c594dSDimitry Andric     CloneAndPruneFunctionInto(Caller, CalledFunc, VMap,
2369d39c594dSDimitry Andric                               /*ModuleLevelChanges=*/false, Returns, ".i",
2370344a3780SDimitry Andric                               &InlinedFunctionInfo);
2371009b1c42SEd Schouten     // Remember the first block that is newly cloned over.
2372009b1c42SEd Schouten     FirstNewBlock = LastBlock; ++FirstNewBlock;
2373009b1c42SEd Schouten 
2374344a3780SDimitry Andric     // Insert retainRV/clainRV runtime calls.
2375c0981da4SDimitry Andric     objcarc::ARCInstKind RVCallKind = objcarc::getAttachedARCFunctionKind(&CB);
2376c0981da4SDimitry Andric     if (RVCallKind != objcarc::ARCInstKind::None)
2377c0981da4SDimitry Andric       inlineRetainOrClaimRVCalls(CB, RVCallKind, Returns);
2378344a3780SDimitry Andric 
2379344a3780SDimitry Andric     // Updated caller/callee profiles only when requested. For sample loader
2380344a3780SDimitry Andric     // inlining, the context-sensitive inlinee profile doesn't need to be
2381344a3780SDimitry Andric     // subtracted from callee profile, and the inlined clone also doesn't need
2382344a3780SDimitry Andric     // to be scaled based on call site count.
2383344a3780SDimitry Andric     if (IFI.UpdateProfile) {
238471d5a254SDimitry Andric       if (IFI.CallerBFI != nullptr && IFI.CalleeBFI != nullptr)
238571d5a254SDimitry Andric         // Update the BFI of blocks cloned into the caller.
238671d5a254SDimitry Andric         updateCallerBFI(OrigBB, VMap, IFI.CallerBFI, IFI.CalleeBFI,
238771d5a254SDimitry Andric                         CalledFunc->front());
238871d5a254SDimitry Andric 
2389c0981da4SDimitry Andric       if (auto Profile = CalledFunc->getEntryCount())
2390c0981da4SDimitry Andric         updateCallProfile(CalledFunc, VMap, *Profile, CB, IFI.PSI,
2391c0981da4SDimitry Andric                           IFI.CallerBFI);
2392344a3780SDimitry Andric     }
239371d5a254SDimitry Andric 
23945ca98fd9SDimitry Andric     // Inject byval arguments initialization.
2395c0981da4SDimitry Andric     for (ByValInit &Init : ByValInits)
2396c0981da4SDimitry Andric       HandleByValArgumentInit(Init.Ty, Init.Dst, Init.Src, Caller->getParent(),
23977fa27ce4SDimitry Andric                               &*FirstNewBlock, IFI, CalledFunc);
2398dd58ef01SDimitry Andric 
2399e3b55780SDimitry Andric     std::optional<OperandBundleUse> ParentDeopt =
2400cfca06d7SDimitry Andric         CB.getOperandBundle(LLVMContext::OB_deopt);
2401dd58ef01SDimitry Andric     if (ParentDeopt) {
2402dd58ef01SDimitry Andric       SmallVector<OperandBundleDef, 2> OpDefs;
2403dd58ef01SDimitry Andric 
2404dd58ef01SDimitry Andric       for (auto &VH : InlinedFunctionInfo.OperandBundleCallSites) {
2405cfca06d7SDimitry Andric         CallBase *ICS = dyn_cast_or_null<CallBase>(VH);
2406cfca06d7SDimitry Andric         if (!ICS)
2407cfca06d7SDimitry Andric           continue; // instruction was DCE'd or RAUW'ed to undef
2408dd58ef01SDimitry Andric 
2409dd58ef01SDimitry Andric         OpDefs.clear();
2410dd58ef01SDimitry Andric 
2411cfca06d7SDimitry Andric         OpDefs.reserve(ICS->getNumOperandBundles());
2412dd58ef01SDimitry Andric 
2413cfca06d7SDimitry Andric         for (unsigned COBi = 0, COBe = ICS->getNumOperandBundles(); COBi < COBe;
2414cfca06d7SDimitry Andric              ++COBi) {
2415cfca06d7SDimitry Andric           auto ChildOB = ICS->getOperandBundleAt(COBi);
2416dd58ef01SDimitry Andric           if (ChildOB.getTagID() != LLVMContext::OB_deopt) {
2417dd58ef01SDimitry Andric             // If the inlined call has other operand bundles, let them be
2418dd58ef01SDimitry Andric             OpDefs.emplace_back(ChildOB);
2419dd58ef01SDimitry Andric             continue;
2420dd58ef01SDimitry Andric           }
2421dd58ef01SDimitry Andric 
2422dd58ef01SDimitry Andric           // It may be useful to separate this logic (of handling operand
2423dd58ef01SDimitry Andric           // bundles) out to a separate "policy" component if this gets crowded.
2424dd58ef01SDimitry Andric           // Prepend the parent's deoptimization continuation to the newly
2425dd58ef01SDimitry Andric           // inlined call's deoptimization continuation.
2426dd58ef01SDimitry Andric           std::vector<Value *> MergedDeoptArgs;
2427dd58ef01SDimitry Andric           MergedDeoptArgs.reserve(ParentDeopt->Inputs.size() +
2428dd58ef01SDimitry Andric                                   ChildOB.Inputs.size());
2429dd58ef01SDimitry Andric 
2430b60736ecSDimitry Andric           llvm::append_range(MergedDeoptArgs, ParentDeopt->Inputs);
2431b60736ecSDimitry Andric           llvm::append_range(MergedDeoptArgs, ChildOB.Inputs);
2432dd58ef01SDimitry Andric 
2433dd58ef01SDimitry Andric           OpDefs.emplace_back("deopt", std::move(MergedDeoptArgs));
2434dd58ef01SDimitry Andric         }
2435dd58ef01SDimitry Andric 
2436ac9a064cSDimitry Andric         Instruction *NewI = CallBase::Create(ICS, OpDefs, ICS->getIterator());
2437dd58ef01SDimitry Andric 
2438dd58ef01SDimitry Andric         // Note: the RAUW does the appropriate fixup in VMap, so we need to do
2439dd58ef01SDimitry Andric         // this even if the call returns void.
2440cfca06d7SDimitry Andric         ICS->replaceAllUsesWith(NewI);
2441dd58ef01SDimitry Andric 
2442dd58ef01SDimitry Andric         VH = nullptr;
2443cfca06d7SDimitry Andric         ICS->eraseFromParent();
2444dd58ef01SDimitry Andric       }
2445dd58ef01SDimitry Andric     }
24465ca98fd9SDimitry Andric 
2447b915e9e0SDimitry Andric     // For 'nodebug' functions, the associated DISubprogram is always null.
2448b915e9e0SDimitry Andric     // Conservatively avoid propagating the callsite debug location to
2449b915e9e0SDimitry Andric     // instructions inlined from a function whose DISubprogram is not null.
2450cfca06d7SDimitry Andric     fixupLineNumbers(Caller, FirstNewBlock, &CB,
2451b915e9e0SDimitry Andric                      CalledFunc->getSubprogram() != nullptr);
245267c32a98SDimitry Andric 
2453e3b55780SDimitry Andric     if (isAssignmentTrackingEnabled(*Caller->getParent())) {
2454e3b55780SDimitry Andric       // Interpret inlined stores to caller-local variables as assignments.
2455e3b55780SDimitry Andric       trackInlinedStores(FirstNewBlock, Caller->end(), CB);
2456e3b55780SDimitry Andric 
2457e3b55780SDimitry Andric       // Update DIAssignID metadata attachments and uses so that they are
2458e3b55780SDimitry Andric       // unique to this inlined instance.
2459e3b55780SDimitry Andric       fixupAssignments(FirstNewBlock, Caller->end());
2460e3b55780SDimitry Andric     }
2461e3b55780SDimitry Andric 
2462b60736ecSDimitry Andric     // Now clone the inlined noalias scope metadata.
2463b60736ecSDimitry Andric     SAMetadataCloner.clone();
2464344a3780SDimitry Andric     SAMetadataCloner.remap(FirstNewBlock, Caller->end());
246567c32a98SDimitry Andric 
246667c32a98SDimitry Andric     // Add noalias metadata if necessary.
2467344a3780SDimitry Andric     AddAliasScopeMetadata(CB, VMap, DL, CalleeAAR, InlinedFunctionInfo);
2468cfca06d7SDimitry Andric 
2469cfca06d7SDimitry Andric     // Clone return attributes on the callsite into the calls within the inlined
2470cfca06d7SDimitry Andric     // function which feed into its return value.
247103706295SDimitry Andric     AddReturnAttributes(CB, VMap, InlinedFunctionInfo);
247267c32a98SDimitry Andric 
2473ac9a064cSDimitry Andric     // Clone attributes on the params of the callsite to calls within the
2474ac9a064cSDimitry Andric     // inlined function which use the same param.
247503706295SDimitry Andric     AddParamAndFnBasicAttributes(CB, VMap, InlinedFunctionInfo);
2476ac9a064cSDimitry Andric 
2477e3b55780SDimitry Andric     propagateMemProfMetadata(CalledFunc, CB,
2478e3b55780SDimitry Andric                              InlinedFunctionInfo.ContainsMemProfMetadata, VMap);
2479e3b55780SDimitry Andric 
2480b60736ecSDimitry Andric     // Propagate metadata on the callsite if necessary.
2481344a3780SDimitry Andric     PropagateCallSiteMetadata(CB, FirstNewBlock, Caller->end());
248201095a5dSDimitry Andric 
2483b915e9e0SDimitry Andric     // Register any cloned assumptions.
2484b915e9e0SDimitry Andric     if (IFI.GetAssumptionCache)
2485b915e9e0SDimitry Andric       for (BasicBlock &NewBlock :
2486b915e9e0SDimitry Andric            make_range(FirstNewBlock->getIterator(), Caller->end()))
2487cfca06d7SDimitry Andric         for (Instruction &I : NewBlock)
24887fa27ce4SDimitry Andric           if (auto *II = dyn_cast<AssumeInst>(&I))
2489cfca06d7SDimitry Andric             IFI.GetAssumptionCache(*Caller).registerAssumption(II);
2490009b1c42SEd Schouten   }
2491009b1c42SEd Schouten 
2492b1c73532SDimitry Andric   if (ConvergenceControlToken) {
2493b1c73532SDimitry Andric     auto *I = FirstNewBlock->getFirstNonPHI();
2494b1c73532SDimitry Andric     if (auto *IntrinsicCall = dyn_cast<IntrinsicInst>(I)) {
2495b1c73532SDimitry Andric       if (IntrinsicCall->getIntrinsicID() ==
2496b1c73532SDimitry Andric           Intrinsic::experimental_convergence_entry) {
2497b1c73532SDimitry Andric         IntrinsicCall->replaceAllUsesWith(ConvergenceControlToken);
2498b1c73532SDimitry Andric         IntrinsicCall->eraseFromParent();
2499b1c73532SDimitry Andric       }
2500b1c73532SDimitry Andric     }
2501b1c73532SDimitry Andric   }
2502b1c73532SDimitry Andric 
2503009b1c42SEd Schouten   // If there are any alloca instructions in the block that used to be the entry
2504009b1c42SEd Schouten   // block for the callee, move them to the entry block of the caller.  First
2505009b1c42SEd Schouten   // calculate which instruction they should be inserted before.  We insert the
2506009b1c42SEd Schouten   // instructions at the end of the current alloca list.
2507009b1c42SEd Schouten   {
2508009b1c42SEd Schouten     BasicBlock::iterator InsertPoint = Caller->begin()->begin();
2509009b1c42SEd Schouten     for (BasicBlock::iterator I = FirstNewBlock->begin(),
251059850d08SRoman Divacky          E = FirstNewBlock->end(); I != E; ) {
251159850d08SRoman Divacky       AllocaInst *AI = dyn_cast<AllocaInst>(I++);
25125ca98fd9SDimitry Andric       if (!AI) continue;
251359850d08SRoman Divacky 
2514009b1c42SEd Schouten       // If the alloca is now dead, remove it.  This often occurs due to code
2515009b1c42SEd Schouten       // specialization.
2516009b1c42SEd Schouten       if (AI->use_empty()) {
2517009b1c42SEd Schouten         AI->eraseFromParent();
2518009b1c42SEd Schouten         continue;
2519009b1c42SEd Schouten       }
2520009b1c42SEd Schouten 
2521a7fe922bSDimitry Andric       if (!allocaWouldBeStaticInEntry(AI))
252259850d08SRoman Divacky         continue;
252359850d08SRoman Divacky 
2524cf099d11SDimitry Andric       // Keep track of the static allocas that we inline into the caller.
2525d7f7719eSRoman Divacky       IFI.StaticAllocas.push_back(AI);
252659850d08SRoman Divacky 
2527009b1c42SEd Schouten       // Scan for the block of allocas that we can move over, and move them
2528009b1c42SEd Schouten       // all at once.
2529009b1c42SEd Schouten       while (isa<AllocaInst>(I) &&
2530706b4fc4SDimitry Andric              !cast<AllocaInst>(I)->use_empty() &&
2531a7fe922bSDimitry Andric              allocaWouldBeStaticInEntry(cast<AllocaInst>(I))) {
2532d7f7719eSRoman Divacky         IFI.StaticAllocas.push_back(cast<AllocaInst>(I));
2533009b1c42SEd Schouten         ++I;
253459850d08SRoman Divacky       }
2535009b1c42SEd Schouten 
2536009b1c42SEd Schouten       // Transfer all of the allocas over in a block.  Using splice means
2537009b1c42SEd Schouten       // that the instructions aren't removed from the symbol table, then
2538009b1c42SEd Schouten       // reinserted.
2539b1c73532SDimitry Andric       I.setTailBit(true);
2540e3b55780SDimitry Andric       Caller->getEntryBlock().splice(InsertPoint, &*FirstNewBlock,
2541e3b55780SDimitry Andric                                      AI->getIterator(), I);
2542009b1c42SEd Schouten     }
2543009b1c42SEd Schouten   }
2544009b1c42SEd Schouten 
2545044eb2f6SDimitry Andric   SmallVector<Value*,4> VarArgsToForward;
2546eb11fae6SDimitry Andric   SmallVector<AttributeSet, 4> VarArgsAttrs;
2547044eb2f6SDimitry Andric   for (unsigned i = CalledFunc->getFunctionType()->getNumParams();
2548c0981da4SDimitry Andric        i < CB.arg_size(); i++) {
2549cfca06d7SDimitry Andric     VarArgsToForward.push_back(CB.getArgOperand(i));
2550c0981da4SDimitry Andric     VarArgsAttrs.push_back(CB.getAttributes().getParamAttrs(i));
2551eb11fae6SDimitry Andric   }
2552044eb2f6SDimitry Andric 
255301095a5dSDimitry Andric   bool InlinedMustTailCalls = false, InlinedDeoptimizeCalls = false;
25545ca98fd9SDimitry Andric   if (InlinedFunctionInfo.ContainsCalls) {
25555ca98fd9SDimitry Andric     CallInst::TailCallKind CallSiteTailKind = CallInst::TCK_None;
2556cfca06d7SDimitry Andric     if (CallInst *CI = dyn_cast<CallInst>(&CB))
25575ca98fd9SDimitry Andric       CallSiteTailKind = CI->getTailCallKind();
25585ca98fd9SDimitry Andric 
2559eb11fae6SDimitry Andric     // For inlining purposes, the "notail" marker is the same as no marker.
2560eb11fae6SDimitry Andric     if (CallSiteTailKind == CallInst::TCK_NoTail)
2561eb11fae6SDimitry Andric       CallSiteTailKind = CallInst::TCK_None;
2562eb11fae6SDimitry Andric 
25635ca98fd9SDimitry Andric     for (Function::iterator BB = FirstNewBlock, E = Caller->end(); BB != E;
25645ca98fd9SDimitry Andric          ++BB) {
2565c0981da4SDimitry Andric       for (Instruction &I : llvm::make_early_inc_range(*BB)) {
25665ca98fd9SDimitry Andric         CallInst *CI = dyn_cast<CallInst>(&I);
25675ca98fd9SDimitry Andric         if (!CI)
25685ca98fd9SDimitry Andric           continue;
25695ca98fd9SDimitry Andric 
2570eb11fae6SDimitry Andric         // Forward varargs from inlined call site to calls to the
2571eb11fae6SDimitry Andric         // ForwardVarArgsTo function, if requested, and to musttail calls.
2572eb11fae6SDimitry Andric         if (!VarArgsToForward.empty() &&
2573eb11fae6SDimitry Andric             ((ForwardVarArgsTo &&
2574eb11fae6SDimitry Andric               CI->getCalledFunction() == ForwardVarArgsTo) ||
2575eb11fae6SDimitry Andric              CI->isMustTailCall())) {
2576eb11fae6SDimitry Andric           // Collect attributes for non-vararg parameters.
2577eb11fae6SDimitry Andric           AttributeList Attrs = CI->getAttributes();
2578eb11fae6SDimitry Andric           SmallVector<AttributeSet, 8> ArgAttrs;
2579eb11fae6SDimitry Andric           if (!Attrs.isEmpty() || !VarArgsAttrs.empty()) {
2580eb11fae6SDimitry Andric             for (unsigned ArgNo = 0;
2581eb11fae6SDimitry Andric                  ArgNo < CI->getFunctionType()->getNumParams(); ++ArgNo)
2582c0981da4SDimitry Andric               ArgAttrs.push_back(Attrs.getParamAttrs(ArgNo));
2583eb11fae6SDimitry Andric           }
2584eb11fae6SDimitry Andric 
2585eb11fae6SDimitry Andric           // Add VarArg attributes.
2586eb11fae6SDimitry Andric           ArgAttrs.append(VarArgsAttrs.begin(), VarArgsAttrs.end());
2587c0981da4SDimitry Andric           Attrs = AttributeList::get(CI->getContext(), Attrs.getFnAttrs(),
2588c0981da4SDimitry Andric                                      Attrs.getRetAttrs(), ArgAttrs);
2589eb11fae6SDimitry Andric           // Add VarArgs to existing parameters.
2590c0981da4SDimitry Andric           SmallVector<Value *, 6> Params(CI->args());
2591eb11fae6SDimitry Andric           Params.append(VarArgsToForward.begin(), VarArgsToForward.end());
2592e6d15924SDimitry Andric           CallInst *NewCI = CallInst::Create(
2593ac9a064cSDimitry Andric               CI->getFunctionType(), CI->getCalledOperand(), Params, "", CI->getIterator());
2594eb11fae6SDimitry Andric           NewCI->setDebugLoc(CI->getDebugLoc());
2595eb11fae6SDimitry Andric           NewCI->setAttributes(Attrs);
2596eb11fae6SDimitry Andric           NewCI->setCallingConv(CI->getCallingConv());
2597eb11fae6SDimitry Andric           CI->replaceAllUsesWith(NewCI);
2598eb11fae6SDimitry Andric           CI->eraseFromParent();
2599eb11fae6SDimitry Andric           CI = NewCI;
2600eb11fae6SDimitry Andric         }
2601eb11fae6SDimitry Andric 
260201095a5dSDimitry Andric         if (Function *F = CI->getCalledFunction())
260301095a5dSDimitry Andric           InlinedDeoptimizeCalls |=
260401095a5dSDimitry Andric               F->getIntrinsicID() == Intrinsic::experimental_deoptimize;
260501095a5dSDimitry Andric 
26065ca98fd9SDimitry Andric         // We need to reduce the strength of any inlined tail calls.  For
26075ca98fd9SDimitry Andric         // musttail, we have to avoid introducing potential unbounded stack
26085ca98fd9SDimitry Andric         // growth.  For example, if functions 'f' and 'g' are mutually recursive
26095ca98fd9SDimitry Andric         // with musttail, we can inline 'g' into 'f' so long as we preserve
26105ca98fd9SDimitry Andric         // musttail on the cloned call to 'f'.  If either the inlined call site
26115ca98fd9SDimitry Andric         // or the cloned call site is *not* musttail, the program already has
26125ca98fd9SDimitry Andric         // one frame of stack growth, so it's safe to remove musttail.  Here is
26135ca98fd9SDimitry Andric         // a table of example transformations:
26145ca98fd9SDimitry Andric         //
26155ca98fd9SDimitry Andric         //    f -> musttail g -> musttail f  ==>  f -> musttail f
26165ca98fd9SDimitry Andric         //    f -> musttail g ->     tail f  ==>  f ->     tail f
26175ca98fd9SDimitry Andric         //    f ->          g -> musttail f  ==>  f ->          f
26185ca98fd9SDimitry Andric         //    f ->          g ->     tail f  ==>  f ->          f
2619eb11fae6SDimitry Andric         //
2620eb11fae6SDimitry Andric         // Inlined notail calls should remain notail calls.
26215ca98fd9SDimitry Andric         CallInst::TailCallKind ChildTCK = CI->getTailCallKind();
2622044eb2f6SDimitry Andric         if (ChildTCK != CallInst::TCK_NoTail)
26235ca98fd9SDimitry Andric           ChildTCK = std::min(CallSiteTailKind, ChildTCK);
26245ca98fd9SDimitry Andric         CI->setTailCallKind(ChildTCK);
26255ca98fd9SDimitry Andric         InlinedMustTailCalls |= CI->isMustTailCall();
26265ca98fd9SDimitry Andric 
26274b4fe385SDimitry Andric         // Call sites inlined through a 'nounwind' call site should be
26284b4fe385SDimitry Andric         // 'nounwind' as well. However, avoid marking call sites explicitly
26294b4fe385SDimitry Andric         // where possible. This helps expose more opportunities for CSE after
26304b4fe385SDimitry Andric         // inlining, commonly when the callee is an intrinsic.
26314b4fe385SDimitry Andric         if (MarkNoUnwind && !CI->doesNotThrow())
26325ca98fd9SDimitry Andric           CI->setDoesNotThrow();
26335ca98fd9SDimitry Andric       }
26345ca98fd9SDimitry Andric     }
26355ca98fd9SDimitry Andric   }
26365ca98fd9SDimitry Andric 
263756fe8f14SDimitry Andric   // Leave lifetime markers for the static alloca's, scoping them to the
263856fe8f14SDimitry Andric   // function we just inlined.
2639344a3780SDimitry Andric   // We need to insert lifetime intrinsics even at O0 to avoid invalid
2640344a3780SDimitry Andric   // access caused by multithreaded coroutines. The check
2641344a3780SDimitry Andric   // `Caller->isPresplitCoroutine()` would affect AlwaysInliner at O0 only.
2642344a3780SDimitry Andric   if ((InsertLifetime || Caller->isPresplitCoroutine()) &&
2643344a3780SDimitry Andric       !IFI.StaticAllocas.empty()) {
2644b1c73532SDimitry Andric     IRBuilder<> builder(&*FirstNewBlock, FirstNewBlock->begin());
2645ac9a064cSDimitry Andric     for (AllocaInst *AI : IFI.StaticAllocas) {
2646b915e9e0SDimitry Andric       // Don't mark swifterror allocas. They can't have bitcast uses.
2647b915e9e0SDimitry Andric       if (AI->isSwiftError())
2648b915e9e0SDimitry Andric         continue;
264956fe8f14SDimitry Andric 
265056fe8f14SDimitry Andric       // If the alloca is already scoped to something smaller than the whole
265156fe8f14SDimitry Andric       // function then there's no need to add redundant, less accurate markers.
265256fe8f14SDimitry Andric       if (hasLifetimeMarkers(AI))
265356fe8f14SDimitry Andric         continue;
265456fe8f14SDimitry Andric 
26554a16efa3SDimitry Andric       // Try to determine the size of the allocation.
26565ca98fd9SDimitry Andric       ConstantInt *AllocaSize = nullptr;
26574a16efa3SDimitry Andric       if (ConstantInt *AIArraySize =
26584a16efa3SDimitry Andric           dyn_cast<ConstantInt>(AI->getArraySize())) {
2659ac9a064cSDimitry Andric         auto &DL = Caller->getDataLayout();
26604a16efa3SDimitry Andric         Type *AllocaType = AI->getAllocatedType();
2661b60736ecSDimitry Andric         TypeSize AllocaTypeSize = DL.getTypeAllocSize(AllocaType);
26624a16efa3SDimitry Andric         uint64_t AllocaArraySize = AIArraySize->getLimitedValue();
26635a5ac124SDimitry Andric 
26645a5ac124SDimitry Andric         // Don't add markers for zero-sized allocas.
26655a5ac124SDimitry Andric         if (AllocaArraySize == 0)
26665a5ac124SDimitry Andric           continue;
26675a5ac124SDimitry Andric 
26684a16efa3SDimitry Andric         // Check that array size doesn't saturate uint64_t and doesn't
26694a16efa3SDimitry Andric         // overflow when it's multiplied by type size.
2670b60736ecSDimitry Andric         if (!AllocaTypeSize.isScalable() &&
2671b60736ecSDimitry Andric             AllocaArraySize != std::numeric_limits<uint64_t>::max() &&
2672044eb2f6SDimitry Andric             std::numeric_limits<uint64_t>::max() / AllocaArraySize >=
2673e3b55780SDimitry Andric                 AllocaTypeSize.getFixedValue()) {
26744a16efa3SDimitry Andric           AllocaSize = ConstantInt::get(Type::getInt64Ty(AI->getContext()),
26754a16efa3SDimitry Andric                                         AllocaArraySize * AllocaTypeSize);
26764a16efa3SDimitry Andric         }
26774a16efa3SDimitry Andric       }
26784a16efa3SDimitry Andric 
26794a16efa3SDimitry Andric       builder.CreateLifetimeStart(AI, AllocaSize);
26805ca98fd9SDimitry Andric       for (ReturnInst *RI : Returns) {
268101095a5dSDimitry Andric         // Don't insert llvm.lifetime.end calls between a musttail or deoptimize
268201095a5dSDimitry Andric         // call and a return.  The return kills all local allocas.
268367c32a98SDimitry Andric         if (InlinedMustTailCalls &&
268467c32a98SDimitry Andric             RI->getParent()->getTerminatingMustTailCall())
26855ca98fd9SDimitry Andric           continue;
268601095a5dSDimitry Andric         if (InlinedDeoptimizeCalls &&
268701095a5dSDimitry Andric             RI->getParent()->getTerminatingDeoptimizeCall())
268801095a5dSDimitry Andric           continue;
26895ca98fd9SDimitry Andric         IRBuilder<>(RI).CreateLifetimeEnd(AI, AllocaSize);
269056fe8f14SDimitry Andric       }
269156fe8f14SDimitry Andric     }
269256fe8f14SDimitry Andric   }
269356fe8f14SDimitry Andric 
2694009b1c42SEd Schouten   // If the inlined code contained dynamic alloca instructions, wrap the inlined
2695009b1c42SEd Schouten   // code with llvm.stacksave/llvm.stackrestore intrinsics.
2696009b1c42SEd Schouten   if (InlinedFunctionInfo.ContainsDynamicAllocas) {
2697009b1c42SEd Schouten     // Insert the llvm.stacksave.
2698dd58ef01SDimitry Andric     CallInst *SavedPtr = IRBuilder<>(&*FirstNewBlock, FirstNewBlock->begin())
2699b1c73532SDimitry Andric                              .CreateStackSave("savedstack");
2700009b1c42SEd Schouten 
2701009b1c42SEd Schouten     // Insert a call to llvm.stackrestore before any return instructions in the
2702009b1c42SEd Schouten     // inlined function.
27035ca98fd9SDimitry Andric     for (ReturnInst *RI : Returns) {
270401095a5dSDimitry Andric       // Don't insert llvm.stackrestore calls between a musttail or deoptimize
270501095a5dSDimitry Andric       // call and a return.  The return will restore the stack pointer.
270667c32a98SDimitry Andric       if (InlinedMustTailCalls && RI->getParent()->getTerminatingMustTailCall())
27075ca98fd9SDimitry Andric         continue;
270801095a5dSDimitry Andric       if (InlinedDeoptimizeCalls && RI->getParent()->getTerminatingDeoptimizeCall())
270901095a5dSDimitry Andric         continue;
2710b1c73532SDimitry Andric       IRBuilder<>(RI).CreateStackRestore(SavedPtr);
2711009b1c42SEd Schouten     }
2712009b1c42SEd Schouten   }
2713009b1c42SEd Schouten 
2714dadbdfffSDimitry Andric   // If we are inlining for an invoke instruction, we must make sure to rewrite
2715dadbdfffSDimitry Andric   // any call instructions into invoke instructions.  This is sensitive to which
2716dadbdfffSDimitry Andric   // funclet pads were top-level in the inlinee, so must be done before
2717dadbdfffSDimitry Andric   // rewriting the "parent pad" links.
2718cfca06d7SDimitry Andric   if (auto *II = dyn_cast<InvokeInst>(&CB)) {
2719dadbdfffSDimitry Andric     BasicBlock *UnwindDest = II->getUnwindDest();
2720dadbdfffSDimitry Andric     Instruction *FirstNonPHI = UnwindDest->getFirstNonPHI();
2721dadbdfffSDimitry Andric     if (isa<LandingPadInst>(FirstNonPHI)) {
2722dadbdfffSDimitry Andric       HandleInlinedLandingPad(II, &*FirstNewBlock, InlinedFunctionInfo);
2723dadbdfffSDimitry Andric     } else {
2724dadbdfffSDimitry Andric       HandleInlinedEHPad(II, &*FirstNewBlock, InlinedFunctionInfo);
2725dadbdfffSDimitry Andric     }
2726dadbdfffSDimitry Andric   }
2727dadbdfffSDimitry Andric 
2728dd58ef01SDimitry Andric   // Update the lexical scopes of the new funclets and callsites.
2729dd58ef01SDimitry Andric   // Anything that had 'none' as its parent is now nested inside the callsite's
2730dd58ef01SDimitry Andric   // EHPad.
2731dd58ef01SDimitry Andric   if (CallSiteEHPad) {
2732dd58ef01SDimitry Andric     for (Function::iterator BB = FirstNewBlock->getIterator(),
2733dd58ef01SDimitry Andric                             E = Caller->end();
2734dd58ef01SDimitry Andric          BB != E; ++BB) {
273508e8dd7bSDimitry Andric       // Add bundle operands to inlined call sites.
273608e8dd7bSDimitry Andric       PropagateOperandBundles(BB, CallSiteEHPad);
2737dd58ef01SDimitry Andric 
273801095a5dSDimitry Andric       // It is problematic if the inlinee has a cleanupret which unwinds to
273901095a5dSDimitry Andric       // caller and we inline it into a call site which doesn't unwind but into
274001095a5dSDimitry Andric       // an EH pad that does.  Such an edge must be dynamically unreachable.
274101095a5dSDimitry Andric       // As such, we replace the cleanupret with unreachable.
274201095a5dSDimitry Andric       if (auto *CleanupRet = dyn_cast<CleanupReturnInst>(BB->getTerminator()))
274301095a5dSDimitry Andric         if (CleanupRet->unwindsToCaller() && EHPadForCallUnwindsLocally)
2744344a3780SDimitry Andric           changeToUnreachable(CleanupRet);
274501095a5dSDimitry Andric 
2746dd58ef01SDimitry Andric       Instruction *I = BB->getFirstNonPHI();
2747dd58ef01SDimitry Andric       if (!I->isEHPad())
2748dd58ef01SDimitry Andric         continue;
2749dd58ef01SDimitry Andric 
2750dd58ef01SDimitry Andric       if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(I)) {
2751dd58ef01SDimitry Andric         if (isa<ConstantTokenNone>(CatchSwitch->getParentPad()))
2752dd58ef01SDimitry Andric           CatchSwitch->setParentPad(CallSiteEHPad);
2753dd58ef01SDimitry Andric       } else {
2754dd58ef01SDimitry Andric         auto *FPI = cast<FuncletPadInst>(I);
2755dd58ef01SDimitry Andric         if (isa<ConstantTokenNone>(FPI->getParentPad()))
2756dd58ef01SDimitry Andric           FPI->setParentPad(CallSiteEHPad);
2757dd58ef01SDimitry Andric       }
2758dd58ef01SDimitry Andric     }
2759dd58ef01SDimitry Andric   }
2760dd58ef01SDimitry Andric 
276101095a5dSDimitry Andric   if (InlinedDeoptimizeCalls) {
276201095a5dSDimitry Andric     // We need to at least remove the deoptimizing returns from the Return set,
276301095a5dSDimitry Andric     // so that the control flow from those returns does not get merged into the
276401095a5dSDimitry Andric     // caller (but terminate it instead).  If the caller's return type does not
276501095a5dSDimitry Andric     // match the callee's return type, we also need to change the return type of
276601095a5dSDimitry Andric     // the intrinsic.
2767cfca06d7SDimitry Andric     if (Caller->getReturnType() == CB.getType()) {
2768b60736ecSDimitry Andric       llvm::erase_if(Returns, [](ReturnInst *RI) {
276901095a5dSDimitry Andric         return RI->getParent()->getTerminatingDeoptimizeCall() != nullptr;
277001095a5dSDimitry Andric       });
277101095a5dSDimitry Andric     } else {
277201095a5dSDimitry Andric       SmallVector<ReturnInst *, 8> NormalReturns;
277301095a5dSDimitry Andric       Function *NewDeoptIntrinsic = Intrinsic::getDeclaration(
277401095a5dSDimitry Andric           Caller->getParent(), Intrinsic::experimental_deoptimize,
277501095a5dSDimitry Andric           {Caller->getReturnType()});
277601095a5dSDimitry Andric 
277701095a5dSDimitry Andric       for (ReturnInst *RI : Returns) {
277801095a5dSDimitry Andric         CallInst *DeoptCall = RI->getParent()->getTerminatingDeoptimizeCall();
277901095a5dSDimitry Andric         if (!DeoptCall) {
278001095a5dSDimitry Andric           NormalReturns.push_back(RI);
278101095a5dSDimitry Andric           continue;
278201095a5dSDimitry Andric         }
278301095a5dSDimitry Andric 
278401095a5dSDimitry Andric         // The calling convention on the deoptimize call itself may be bogus,
278501095a5dSDimitry Andric         // since the code we're inlining may have undefined behavior (and may
278601095a5dSDimitry Andric         // never actually execute at runtime); but all
278701095a5dSDimitry Andric         // @llvm.experimental.deoptimize declarations have to have the same
278801095a5dSDimitry Andric         // calling convention in a well-formed module.
278901095a5dSDimitry Andric         auto CallingConv = DeoptCall->getCalledFunction()->getCallingConv();
279001095a5dSDimitry Andric         NewDeoptIntrinsic->setCallingConv(CallingConv);
279101095a5dSDimitry Andric         auto *CurBB = RI->getParent();
279201095a5dSDimitry Andric         RI->eraseFromParent();
279301095a5dSDimitry Andric 
2794b60736ecSDimitry Andric         SmallVector<Value *, 4> CallArgs(DeoptCall->args());
279501095a5dSDimitry Andric 
279601095a5dSDimitry Andric         SmallVector<OperandBundleDef, 1> OpBundles;
279701095a5dSDimitry Andric         DeoptCall->getOperandBundlesAsDefs(OpBundles);
2798344a3780SDimitry Andric         auto DeoptAttributes = DeoptCall->getAttributes();
279901095a5dSDimitry Andric         DeoptCall->eraseFromParent();
280001095a5dSDimitry Andric         assert(!OpBundles.empty() &&
280101095a5dSDimitry Andric                "Expected at least the deopt operand bundle");
280201095a5dSDimitry Andric 
280301095a5dSDimitry Andric         IRBuilder<> Builder(CurBB);
280401095a5dSDimitry Andric         CallInst *NewDeoptCall =
280501095a5dSDimitry Andric             Builder.CreateCall(NewDeoptIntrinsic, CallArgs, OpBundles);
280601095a5dSDimitry Andric         NewDeoptCall->setCallingConv(CallingConv);
2807344a3780SDimitry Andric         NewDeoptCall->setAttributes(DeoptAttributes);
280801095a5dSDimitry Andric         if (NewDeoptCall->getType()->isVoidTy())
280901095a5dSDimitry Andric           Builder.CreateRetVoid();
281001095a5dSDimitry Andric         else
281101095a5dSDimitry Andric           Builder.CreateRet(NewDeoptCall);
2812b1c73532SDimitry Andric         // Since the ret type is changed, remove the incompatible attributes.
2813b1c73532SDimitry Andric         NewDeoptCall->removeRetAttrs(
2814b1c73532SDimitry Andric             AttributeFuncs::typeIncompatible(NewDeoptCall->getType()));
281501095a5dSDimitry Andric       }
281601095a5dSDimitry Andric 
281701095a5dSDimitry Andric       // Leave behind the normal returns so we can merge control flow.
281801095a5dSDimitry Andric       std::swap(Returns, NormalReturns);
281901095a5dSDimitry Andric     }
282001095a5dSDimitry Andric   }
282101095a5dSDimitry Andric 
28225ca98fd9SDimitry Andric   // Handle any inlined musttail call sites.  In order for a new call site to be
28235ca98fd9SDimitry Andric   // musttail, the source of the clone and the inlined call site must have been
28245ca98fd9SDimitry Andric   // musttail.  Therefore it's safe to return without merging control into the
28255ca98fd9SDimitry Andric   // phi below.
28265ca98fd9SDimitry Andric   if (InlinedMustTailCalls) {
28275ca98fd9SDimitry Andric     // Check if we need to bitcast the result of any musttail calls.
28285ca98fd9SDimitry Andric     Type *NewRetTy = Caller->getReturnType();
2829cfca06d7SDimitry Andric     bool NeedBitCast = !CB.use_empty() && CB.getType() != NewRetTy;
28305ca98fd9SDimitry Andric 
28315ca98fd9SDimitry Andric     // Handle the returns preceded by musttail calls separately.
28325ca98fd9SDimitry Andric     SmallVector<ReturnInst *, 8> NormalReturns;
28335ca98fd9SDimitry Andric     for (ReturnInst *RI : Returns) {
283467c32a98SDimitry Andric       CallInst *ReturnedMustTail =
283567c32a98SDimitry Andric           RI->getParent()->getTerminatingMustTailCall();
28365ca98fd9SDimitry Andric       if (!ReturnedMustTail) {
28375ca98fd9SDimitry Andric         NormalReturns.push_back(RI);
28385ca98fd9SDimitry Andric         continue;
28395ca98fd9SDimitry Andric       }
28405ca98fd9SDimitry Andric       if (!NeedBitCast)
28415ca98fd9SDimitry Andric         continue;
28425ca98fd9SDimitry Andric 
28435ca98fd9SDimitry Andric       // Delete the old return and any preceding bitcast.
28445ca98fd9SDimitry Andric       BasicBlock *CurBB = RI->getParent();
28455ca98fd9SDimitry Andric       auto *OldCast = dyn_cast_or_null<BitCastInst>(RI->getReturnValue());
28465ca98fd9SDimitry Andric       RI->eraseFromParent();
28475ca98fd9SDimitry Andric       if (OldCast)
28485ca98fd9SDimitry Andric         OldCast->eraseFromParent();
28495ca98fd9SDimitry Andric 
28505ca98fd9SDimitry Andric       // Insert a new bitcast and return with the right type.
28515ca98fd9SDimitry Andric       IRBuilder<> Builder(CurBB);
28525ca98fd9SDimitry Andric       Builder.CreateRet(Builder.CreateBitCast(ReturnedMustTail, NewRetTy));
28535ca98fd9SDimitry Andric     }
28545ca98fd9SDimitry Andric 
28555ca98fd9SDimitry Andric     // Leave behind the normal returns so we can merge control flow.
28565ca98fd9SDimitry Andric     std::swap(Returns, NormalReturns);
28575ca98fd9SDimitry Andric   }
28585ca98fd9SDimitry Andric 
2859b915e9e0SDimitry Andric   // Now that all of the transforms on the inlined code have taken place but
2860b915e9e0SDimitry Andric   // before we splice the inlined code into the CFG and lose track of which
2861b915e9e0SDimitry Andric   // blocks were actually inlined, collect the call sites. We only do this if
2862b915e9e0SDimitry Andric   // call graph updates weren't requested, as those provide value handle based
2863344a3780SDimitry Andric   // tracking of inlined call sites instead. Calls to intrinsics are not
2864344a3780SDimitry Andric   // collected because they are not inlineable.
28657fa27ce4SDimitry Andric   if (InlinedFunctionInfo.ContainsCalls) {
2866b915e9e0SDimitry Andric     // Otherwise just collect the raw call sites that were inlined.
2867b915e9e0SDimitry Andric     for (BasicBlock &NewBB :
2868b915e9e0SDimitry Andric          make_range(FirstNewBlock->getIterator(), Caller->end()))
2869b915e9e0SDimitry Andric       for (Instruction &I : NewBB)
2870cfca06d7SDimitry Andric         if (auto *CB = dyn_cast<CallBase>(&I))
2871344a3780SDimitry Andric           if (!(CB->getCalledFunction() &&
2872344a3780SDimitry Andric                 CB->getCalledFunction()->isIntrinsic()))
2873cfca06d7SDimitry Andric             IFI.InlinedCallSites.push_back(CB);
2874b915e9e0SDimitry Andric   }
2875b915e9e0SDimitry Andric 
2876009b1c42SEd Schouten   // If we cloned in _exactly one_ basic block, and if that block ends in a
2877009b1c42SEd Schouten   // return instruction, we splice the body of the inlined callee directly into
2878009b1c42SEd Schouten   // the calling basic block.
2879009b1c42SEd Schouten   if (Returns.size() == 1 && std::distance(FirstNewBlock, Caller->end()) == 1) {
2880009b1c42SEd Schouten     // Move all of the instructions right before the call.
2881e3b55780SDimitry Andric     OrigBB->splice(CB.getIterator(), &*FirstNewBlock, FirstNewBlock->begin(),
2882e3b55780SDimitry Andric                    FirstNewBlock->end());
2883009b1c42SEd Schouten     // Remove the cloned basic block.
2884e3b55780SDimitry Andric     Caller->back().eraseFromParent();
2885009b1c42SEd Schouten 
2886009b1c42SEd Schouten     // If the call site was an invoke instruction, add a branch to the normal
2887009b1c42SEd Schouten     // destination.
2888cfca06d7SDimitry Andric     if (InvokeInst *II = dyn_cast<InvokeInst>(&CB)) {
2889ac9a064cSDimitry Andric       BranchInst *NewBr = BranchInst::Create(II->getNormalDest(), CB.getIterator());
289059d6cff9SDimitry Andric       NewBr->setDebugLoc(Returns[0]->getDebugLoc());
289159d6cff9SDimitry Andric     }
2892009b1c42SEd Schouten 
2893009b1c42SEd Schouten     // If the return instruction returned a value, replace uses of the call with
2894009b1c42SEd Schouten     // uses of the returned value.
2895cfca06d7SDimitry Andric     if (!CB.use_empty()) {
2896009b1c42SEd Schouten       ReturnInst *R = Returns[0];
2897cfca06d7SDimitry Andric       if (&CB == R->getReturnValue())
28987fa27ce4SDimitry Andric         CB.replaceAllUsesWith(PoisonValue::get(CB.getType()));
2899009b1c42SEd Schouten       else
2900cfca06d7SDimitry Andric         CB.replaceAllUsesWith(R->getReturnValue());
2901009b1c42SEd Schouten     }
2902009b1c42SEd Schouten     // Since we are now done with the Call/Invoke, we can delete it.
2903cfca06d7SDimitry Andric     CB.eraseFromParent();
2904009b1c42SEd Schouten 
2905009b1c42SEd Schouten     // Since we are now done with the return instruction, delete it also.
2906009b1c42SEd Schouten     Returns[0]->eraseFromParent();
2907009b1c42SEd Schouten 
2908e3b55780SDimitry Andric     if (MergeAttributes)
2909e3b55780SDimitry Andric       AttributeFuncs::mergeAttributesForInlining(*Caller, *CalledFunc);
2910e3b55780SDimitry Andric 
2911009b1c42SEd Schouten     // We are now done with the inlining.
2912cfca06d7SDimitry Andric     return InlineResult::success();
2913009b1c42SEd Schouten   }
2914009b1c42SEd Schouten 
2915009b1c42SEd Schouten   // Otherwise, we have the normal case, of more than one block to inline or
2916009b1c42SEd Schouten   // multiple return sites.
2917009b1c42SEd Schouten 
2918009b1c42SEd Schouten   // We want to clone the entire callee function into the hole between the
2919009b1c42SEd Schouten   // "starter" and "ender" blocks.  How we accomplish this depends on whether
2920009b1c42SEd Schouten   // this is an invoke instruction or a call instruction.
2921009b1c42SEd Schouten   BasicBlock *AfterCallBB;
29225ca98fd9SDimitry Andric   BranchInst *CreatedBranchToNormalDest = nullptr;
2923cfca06d7SDimitry Andric   if (InvokeInst *II = dyn_cast<InvokeInst>(&CB)) {
2924009b1c42SEd Schouten 
2925009b1c42SEd Schouten     // Add an unconditional branch to make this look like the CallInst case...
2926ac9a064cSDimitry Andric     CreatedBranchToNormalDest = BranchInst::Create(II->getNormalDest(), CB.getIterator());
2927009b1c42SEd Schouten 
2928009b1c42SEd Schouten     // Split the basic block.  This guarantees that no PHI nodes will have to be
2929009b1c42SEd Schouten     // updated due to new incoming edges, and make the invoke case more
2930009b1c42SEd Schouten     // symmetric to the call case.
2931dd58ef01SDimitry Andric     AfterCallBB =
2932dd58ef01SDimitry Andric         OrigBB->splitBasicBlock(CreatedBranchToNormalDest->getIterator(),
2933009b1c42SEd Schouten                                 CalledFunc->getName() + ".exit");
2934009b1c42SEd Schouten 
2935009b1c42SEd Schouten   } else { // It's a call
2936009b1c42SEd Schouten     // If this is a call instruction, we need to split the basic block that
2937009b1c42SEd Schouten     // the call lives in.
2938009b1c42SEd Schouten     //
2939cfca06d7SDimitry Andric     AfterCallBB = OrigBB->splitBasicBlock(CB.getIterator(),
2940009b1c42SEd Schouten                                           CalledFunc->getName() + ".exit");
2941009b1c42SEd Schouten   }
2942009b1c42SEd Schouten 
294371d5a254SDimitry Andric   if (IFI.CallerBFI) {
294471d5a254SDimitry Andric     // Copy original BB's block frequency to AfterCallBB
2945b1c73532SDimitry Andric     IFI.CallerBFI->setBlockFreq(AfterCallBB,
2946b1c73532SDimitry Andric                                 IFI.CallerBFI->getBlockFreq(OrigBB));
294771d5a254SDimitry Andric   }
294871d5a254SDimitry Andric 
2949009b1c42SEd Schouten   // Change the branch that used to go to AfterCallBB to branch to the first
2950009b1c42SEd Schouten   // basic block of the inlined function.
2951009b1c42SEd Schouten   //
2952d8e91e46SDimitry Andric   Instruction *Br = OrigBB->getTerminator();
2953009b1c42SEd Schouten   assert(Br && Br->getOpcode() == Instruction::Br &&
2954009b1c42SEd Schouten          "splitBasicBlock broken!");
2955dd58ef01SDimitry Andric   Br->setOperand(0, &*FirstNewBlock);
2956009b1c42SEd Schouten 
2957009b1c42SEd Schouten   // Now that the function is correct, make it a little bit nicer.  In
2958009b1c42SEd Schouten   // particular, move the basic blocks inserted from the end of the function
2959009b1c42SEd Schouten   // into the space made by splitting the source basic block.
2960e3b55780SDimitry Andric   Caller->splice(AfterCallBB->getIterator(), Caller, FirstNewBlock,
2961dd58ef01SDimitry Andric                  Caller->end());
2962009b1c42SEd Schouten 
2963009b1c42SEd Schouten   // Handle all of the return instructions that we just cloned in, and eliminate
2964009b1c42SEd Schouten   // any users of the original call/invoke instruction.
296530815c53SDimitry Andric   Type *RTy = CalledFunc->getReturnType();
2966009b1c42SEd Schouten 
29675ca98fd9SDimitry Andric   PHINode *PHI = nullptr;
2968009b1c42SEd Schouten   if (Returns.size() > 1) {
2969009b1c42SEd Schouten     // The PHI node should go at the front of the new basic block to merge all
2970009b1c42SEd Schouten     // possible incoming values.
2971cfca06d7SDimitry Andric     if (!CB.use_empty()) {
2972b1c73532SDimitry Andric       PHI = PHINode::Create(RTy, Returns.size(), CB.getName());
2973b1c73532SDimitry Andric       PHI->insertBefore(AfterCallBB->begin());
2974009b1c42SEd Schouten       // Anything that used the result of the function call should now use the
2975009b1c42SEd Schouten       // PHI node as their operand.
2976cfca06d7SDimitry Andric       CB.replaceAllUsesWith(PHI);
2977009b1c42SEd Schouten     }
2978009b1c42SEd Schouten 
2979009b1c42SEd Schouten     // Loop over all of the return instructions adding entries to the PHI node
2980009b1c42SEd Schouten     // as appropriate.
2981009b1c42SEd Schouten     if (PHI) {
2982ac9a064cSDimitry Andric       for (ReturnInst *RI : Returns) {
2983009b1c42SEd Schouten         assert(RI->getReturnValue()->getType() == PHI->getType() &&
2984009b1c42SEd Schouten                "Ret value not consistent in function!");
2985009b1c42SEd Schouten         PHI->addIncoming(RI->getReturnValue(), RI->getParent());
2986009b1c42SEd Schouten       }
298736bf506aSRoman Divacky     }
298836bf506aSRoman Divacky 
2989009b1c42SEd Schouten     // Add a branch to the merge points and remove return instructions.
299059d6cff9SDimitry Andric     DebugLoc Loc;
2991ac9a064cSDimitry Andric     for (ReturnInst *RI : Returns) {
2992ac9a064cSDimitry Andric       BranchInst *BI = BranchInst::Create(AfterCallBB, RI->getIterator());
299359d6cff9SDimitry Andric       Loc = RI->getDebugLoc();
299459d6cff9SDimitry Andric       BI->setDebugLoc(Loc);
2995009b1c42SEd Schouten       RI->eraseFromParent();
2996009b1c42SEd Schouten     }
299759d6cff9SDimitry Andric     // We need to set the debug location to *somewhere* inside the
299859d6cff9SDimitry Andric     // inlined function. The line number may be nonsensical, but the
299959d6cff9SDimitry Andric     // instruction will at least be associated with the right
300059d6cff9SDimitry Andric     // function.
300159d6cff9SDimitry Andric     if (CreatedBranchToNormalDest)
300259d6cff9SDimitry Andric       CreatedBranchToNormalDest->setDebugLoc(Loc);
3003009b1c42SEd Schouten   } else if (!Returns.empty()) {
3004009b1c42SEd Schouten     // Otherwise, if there is exactly one return value, just replace anything
3005009b1c42SEd Schouten     // using the return value of the call with the computed value.
3006cfca06d7SDimitry Andric     if (!CB.use_empty()) {
3007cfca06d7SDimitry Andric       if (&CB == Returns[0]->getReturnValue())
30087fa27ce4SDimitry Andric         CB.replaceAllUsesWith(PoisonValue::get(CB.getType()));
3009009b1c42SEd Schouten       else
3010cfca06d7SDimitry Andric         CB.replaceAllUsesWith(Returns[0]->getReturnValue());
3011009b1c42SEd Schouten     }
3012009b1c42SEd Schouten 
3013411bd29eSDimitry Andric     // Update PHI nodes that use the ReturnBB to use the AfterCallBB.
3014411bd29eSDimitry Andric     BasicBlock *ReturnBB = Returns[0]->getParent();
3015411bd29eSDimitry Andric     ReturnBB->replaceAllUsesWith(AfterCallBB);
3016411bd29eSDimitry Andric 
3017009b1c42SEd Schouten     // Splice the code from the return block into the block that it will return
3018009b1c42SEd Schouten     // to, which contains the code that was after the call.
3019e3b55780SDimitry Andric     AfterCallBB->splice(AfterCallBB->begin(), ReturnBB);
3020009b1c42SEd Schouten 
302159d6cff9SDimitry Andric     if (CreatedBranchToNormalDest)
302259d6cff9SDimitry Andric       CreatedBranchToNormalDest->setDebugLoc(Returns[0]->getDebugLoc());
302359d6cff9SDimitry Andric 
3024009b1c42SEd Schouten     // Delete the return instruction now and empty ReturnBB now.
3025009b1c42SEd Schouten     Returns[0]->eraseFromParent();
3026009b1c42SEd Schouten     ReturnBB->eraseFromParent();
3027cfca06d7SDimitry Andric   } else if (!CB.use_empty()) {
3028009b1c42SEd Schouten     // No returns, but something is using the return value of the call.  Just
3029009b1c42SEd Schouten     // nuke the result.
30304b4fe385SDimitry Andric     CB.replaceAllUsesWith(PoisonValue::get(CB.getType()));
3031009b1c42SEd Schouten   }
3032009b1c42SEd Schouten 
3033009b1c42SEd Schouten   // Since we are now done with the Call/Invoke, we can delete it.
3034cfca06d7SDimitry Andric   CB.eraseFromParent();
3035009b1c42SEd Schouten 
30365ca98fd9SDimitry Andric   // If we inlined any musttail calls and the original return is now
30375ca98fd9SDimitry Andric   // unreachable, delete it.  It can only contain a bitcast and ret.
3038b60736ecSDimitry Andric   if (InlinedMustTailCalls && pred_empty(AfterCallBB))
30395ca98fd9SDimitry Andric     AfterCallBB->eraseFromParent();
30405ca98fd9SDimitry Andric 
3041009b1c42SEd Schouten   // We should always be able to fold the entry block of the function into the
3042009b1c42SEd Schouten   // single predecessor of the block...
3043009b1c42SEd Schouten   assert(cast<BranchInst>(Br)->isUnconditional() && "splitBasicBlock broken!");
3044009b1c42SEd Schouten   BasicBlock *CalleeEntry = cast<BranchInst>(Br)->getSuccessor(0);
3045009b1c42SEd Schouten 
3046009b1c42SEd Schouten   // Splice the code entry block into calling block, right before the
3047009b1c42SEd Schouten   // unconditional branch.
3048009b1c42SEd Schouten   CalleeEntry->replaceAllUsesWith(OrigBB);  // Update PHI nodes
3049e3b55780SDimitry Andric   OrigBB->splice(Br->getIterator(), CalleeEntry);
3050009b1c42SEd Schouten 
3051009b1c42SEd Schouten   // Remove the unconditional branch.
3052e3b55780SDimitry Andric   Br->eraseFromParent();
3053009b1c42SEd Schouten 
3054009b1c42SEd Schouten   // Now we can remove the CalleeEntry block, which is now empty.
3055e3b55780SDimitry Andric   CalleeEntry->eraseFromParent();
3056009b1c42SEd Schouten 
3057cf099d11SDimitry Andric   // If we inserted a phi node, check to see if it has a single value (e.g. all
3058cf099d11SDimitry Andric   // the entries are the same or undef).  If so, remove the PHI so it doesn't
3059cf099d11SDimitry Andric   // block other optimizations.
306063faed5bSDimitry Andric   if (PHI) {
3061b915e9e0SDimitry Andric     AssumptionCache *AC =
3062cfca06d7SDimitry Andric         IFI.GetAssumptionCache ? &IFI.GetAssumptionCache(*Caller) : nullptr;
3063ac9a064cSDimitry Andric     auto &DL = Caller->getDataLayout();
3064145449b1SDimitry Andric     if (Value *V = simplifyInstruction(PHI, {DL, nullptr, nullptr, AC})) {
3065cf099d11SDimitry Andric       PHI->replaceAllUsesWith(V);
3066cf099d11SDimitry Andric       PHI->eraseFromParent();
3067cf099d11SDimitry Andric     }
306863faed5bSDimitry Andric   }
3069cf099d11SDimitry Andric 
3070e3b55780SDimitry Andric   if (MergeAttributes)
3071e3b55780SDimitry Andric     AttributeFuncs::mergeAttributesForInlining(*Caller, *CalledFunc);
3072e3b55780SDimitry Andric 
3073cfca06d7SDimitry Andric   return InlineResult::success();
3074009b1c42SEd Schouten }
3075