10b57cec5SDimitry Andric //===- InlineFunction.cpp - Code to perform function inlining -------------===// 20b57cec5SDimitry Andric // 30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information. 50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 60b57cec5SDimitry Andric // 70b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 80b57cec5SDimitry Andric // 90b57cec5SDimitry Andric // This file implements inlining of a function into a call site, resolving 100b57cec5SDimitry Andric // parameters and the return value as appropriate. 110b57cec5SDimitry Andric // 120b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 130b57cec5SDimitry Andric 140b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h" 150b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h" 160b57cec5SDimitry Andric #include "llvm/ADT/SetVector.h" 170b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h" 180b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h" 190b57cec5SDimitry Andric #include "llvm/ADT/StringExtras.h" 200b57cec5SDimitry Andric #include "llvm/ADT/iterator_range.h" 210b57cec5SDimitry Andric #include "llvm/Analysis/AliasAnalysis.h" 220b57cec5SDimitry Andric #include "llvm/Analysis/AssumptionCache.h" 230b57cec5SDimitry Andric #include "llvm/Analysis/BlockFrequencyInfo.h" 240b57cec5SDimitry Andric #include "llvm/Analysis/CallGraph.h" 250b57cec5SDimitry Andric #include "llvm/Analysis/CaptureTracking.h" 260fca6ea1SDimitry Andric #include "llvm/Analysis/IndirectCallVisitor.h" 270b57cec5SDimitry Andric #include "llvm/Analysis/InstructionSimplify.h" 28bdd1243dSDimitry Andric #include "llvm/Analysis/MemoryProfileInfo.h" 29fe6060f1SDimitry Andric #include "llvm/Analysis/ObjCARCAnalysisUtils.h" 30fe6060f1SDimitry Andric #include "llvm/Analysis/ObjCARCUtil.h" 310b57cec5SDimitry Andric #include "llvm/Analysis/ProfileSummaryInfo.h" 320b57cec5SDimitry Andric #include "llvm/Analysis/ValueTracking.h" 330b57cec5SDimitry Andric #include "llvm/Analysis/VectorUtils.h" 340b57cec5SDimitry Andric #include "llvm/IR/Argument.h" 350fca6ea1SDimitry Andric #include "llvm/IR/AttributeMask.h" 360b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h" 370b57cec5SDimitry Andric #include "llvm/IR/CFG.h" 380b57cec5SDimitry Andric #include "llvm/IR/Constant.h" 390fca6ea1SDimitry Andric #include "llvm/IR/ConstantRange.h" 400b57cec5SDimitry Andric #include "llvm/IR/Constants.h" 410b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h" 421fd87a68SDimitry Andric #include "llvm/IR/DebugInfo.h" 430b57cec5SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h" 440b57cec5SDimitry Andric #include "llvm/IR/DebugLoc.h" 450b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h" 460b57cec5SDimitry Andric #include "llvm/IR/Dominators.h" 4706c3fb27SDimitry Andric #include "llvm/IR/EHPersonalities.h" 480b57cec5SDimitry Andric #include "llvm/IR/Function.h" 490b57cec5SDimitry Andric #include "llvm/IR/IRBuilder.h" 50fe6060f1SDimitry Andric #include "llvm/IR/InlineAsm.h" 510b57cec5SDimitry Andric #include "llvm/IR/InstrTypes.h" 520b57cec5SDimitry Andric #include "llvm/IR/Instruction.h" 530b57cec5SDimitry Andric #include "llvm/IR/Instructions.h" 540b57cec5SDimitry Andric #include "llvm/IR/IntrinsicInst.h" 550b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h" 560b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h" 570b57cec5SDimitry Andric #include "llvm/IR/MDBuilder.h" 580b57cec5SDimitry Andric #include "llvm/IR/Metadata.h" 590b57cec5SDimitry Andric #include "llvm/IR/Module.h" 600fca6ea1SDimitry Andric #include "llvm/IR/ProfDataUtils.h" 610b57cec5SDimitry Andric #include "llvm/IR/Type.h" 620b57cec5SDimitry Andric #include "llvm/IR/User.h" 630b57cec5SDimitry Andric #include "llvm/IR/Value.h" 640b57cec5SDimitry Andric #include "llvm/Support/Casting.h" 650b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h" 660b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h" 675ffd83dbSDimitry Andric #include "llvm/Transforms/Utils/AssumeBundleBuilder.h" 680b57cec5SDimitry Andric #include "llvm/Transforms/Utils/Cloning.h" 69fe6060f1SDimitry Andric #include "llvm/Transforms/Utils/Local.h" 700b57cec5SDimitry Andric #include "llvm/Transforms/Utils/ValueMapper.h" 710b57cec5SDimitry Andric #include <algorithm> 720b57cec5SDimitry Andric #include <cassert> 730b57cec5SDimitry Andric #include <cstdint> 740b57cec5SDimitry Andric #include <iterator> 750b57cec5SDimitry Andric #include <limits> 76bdd1243dSDimitry Andric #include <optional> 770b57cec5SDimitry Andric #include <string> 780b57cec5SDimitry Andric #include <utility> 790b57cec5SDimitry Andric #include <vector> 800b57cec5SDimitry Andric 81bdd1243dSDimitry Andric #define DEBUG_TYPE "inline-function" 82bdd1243dSDimitry Andric 830b57cec5SDimitry Andric using namespace llvm; 84bdd1243dSDimitry Andric using namespace llvm::memprof; 850b57cec5SDimitry Andric using ProfileCount = Function::ProfileCount; 860b57cec5SDimitry Andric 870b57cec5SDimitry Andric static cl::opt<bool> 880b57cec5SDimitry Andric EnableNoAliasConversion("enable-noalias-to-md-conversion", cl::init(true), 890b57cec5SDimitry Andric cl::Hidden, 900b57cec5SDimitry Andric cl::desc("Convert noalias attributes to metadata during inlining.")); 910b57cec5SDimitry Andric 92e8d8bef9SDimitry Andric static cl::opt<bool> 93e8d8bef9SDimitry Andric UseNoAliasIntrinsic("use-noalias-intrinsic-during-inlining", cl::Hidden, 9481ad6265SDimitry Andric cl::init(true), 95e8d8bef9SDimitry Andric cl::desc("Use the llvm.experimental.noalias.scope.decl " 96e8d8bef9SDimitry Andric "intrinsic during inlining.")); 97e8d8bef9SDimitry Andric 985ffd83dbSDimitry Andric // Disabled by default, because the added alignment assumptions may increase 995ffd83dbSDimitry Andric // compile-time and block optimizations. This option is not suitable for use 1005ffd83dbSDimitry Andric // with frontends that emit comprehensive parameter alignment annotations. 1010b57cec5SDimitry Andric static cl::opt<bool> 1020b57cec5SDimitry Andric PreserveAlignmentAssumptions("preserve-alignment-assumptions-during-inlining", 1035ffd83dbSDimitry Andric cl::init(false), cl::Hidden, 1040b57cec5SDimitry Andric cl::desc("Convert align attributes to assumptions during inlining.")); 1050b57cec5SDimitry Andric 1065ffd83dbSDimitry Andric static cl::opt<unsigned> InlinerAttributeWindow( 1075ffd83dbSDimitry Andric "max-inst-checked-for-throw-during-inlining", cl::Hidden, 1085ffd83dbSDimitry Andric cl::desc("the maximum number of instructions analyzed for may throw during " 1095ffd83dbSDimitry Andric "attribute inference in inlined body"), 1105ffd83dbSDimitry Andric cl::init(4)); 1110b57cec5SDimitry Andric 1120b57cec5SDimitry Andric namespace { 1130b57cec5SDimitry Andric 1140b57cec5SDimitry Andric /// A class for recording information about inlining a landing pad. 1150b57cec5SDimitry Andric class LandingPadInliningInfo { 1160b57cec5SDimitry Andric /// Destination of the invoke's unwind. 1170b57cec5SDimitry Andric BasicBlock *OuterResumeDest; 1180b57cec5SDimitry Andric 1190b57cec5SDimitry Andric /// Destination for the callee's resume. 1200b57cec5SDimitry Andric BasicBlock *InnerResumeDest = nullptr; 1210b57cec5SDimitry Andric 1220b57cec5SDimitry Andric /// LandingPadInst associated with the invoke. 1230b57cec5SDimitry Andric LandingPadInst *CallerLPad = nullptr; 1240b57cec5SDimitry Andric 1250b57cec5SDimitry Andric /// PHI for EH values from landingpad insts. 1260b57cec5SDimitry Andric PHINode *InnerEHValuesPHI = nullptr; 1270b57cec5SDimitry Andric 1280b57cec5SDimitry Andric SmallVector<Value*, 8> UnwindDestPHIValues; 1290b57cec5SDimitry Andric 1300b57cec5SDimitry Andric public: 1310b57cec5SDimitry Andric LandingPadInliningInfo(InvokeInst *II) 1320b57cec5SDimitry Andric : OuterResumeDest(II->getUnwindDest()) { 1330b57cec5SDimitry Andric // If there are PHI nodes in the unwind destination block, we need to keep 1340b57cec5SDimitry Andric // track of which values came into them from the invoke before removing 1350b57cec5SDimitry Andric // the edge from this block. 1360b57cec5SDimitry Andric BasicBlock *InvokeBB = II->getParent(); 1370b57cec5SDimitry Andric BasicBlock::iterator I = OuterResumeDest->begin(); 1380b57cec5SDimitry Andric for (; isa<PHINode>(I); ++I) { 1390b57cec5SDimitry Andric // Save the value to use for this edge. 1400b57cec5SDimitry Andric PHINode *PHI = cast<PHINode>(I); 1410b57cec5SDimitry Andric UnwindDestPHIValues.push_back(PHI->getIncomingValueForBlock(InvokeBB)); 1420b57cec5SDimitry Andric } 1430b57cec5SDimitry Andric 1440b57cec5SDimitry Andric CallerLPad = cast<LandingPadInst>(I); 1450b57cec5SDimitry Andric } 1460b57cec5SDimitry Andric 1470b57cec5SDimitry Andric /// The outer unwind destination is the target of 1480b57cec5SDimitry Andric /// unwind edges introduced for calls within the inlined function. 1490b57cec5SDimitry Andric BasicBlock *getOuterResumeDest() const { 1500b57cec5SDimitry Andric return OuterResumeDest; 1510b57cec5SDimitry Andric } 1520b57cec5SDimitry Andric 1530b57cec5SDimitry Andric BasicBlock *getInnerResumeDest(); 1540b57cec5SDimitry Andric 1550b57cec5SDimitry Andric LandingPadInst *getLandingPadInst() const { return CallerLPad; } 1560b57cec5SDimitry Andric 1570b57cec5SDimitry Andric /// Forward the 'resume' instruction to the caller's landing pad block. 1580b57cec5SDimitry Andric /// When the landing pad block has only one predecessor, this is 1590b57cec5SDimitry Andric /// a simple branch. When there is more than one predecessor, we need to 1600b57cec5SDimitry Andric /// split the landing pad block after the landingpad instruction and jump 1610b57cec5SDimitry Andric /// to there. 1620b57cec5SDimitry Andric void forwardResume(ResumeInst *RI, 1630b57cec5SDimitry Andric SmallPtrSetImpl<LandingPadInst*> &InlinedLPads); 1640b57cec5SDimitry Andric 1650b57cec5SDimitry Andric /// Add incoming-PHI values to the unwind destination block for the given 1660b57cec5SDimitry Andric /// basic block, using the values for the original invoke's source block. 1670b57cec5SDimitry Andric void addIncomingPHIValuesFor(BasicBlock *BB) const { 1680b57cec5SDimitry Andric addIncomingPHIValuesForInto(BB, OuterResumeDest); 1690b57cec5SDimitry Andric } 1700b57cec5SDimitry Andric 1710b57cec5SDimitry Andric void addIncomingPHIValuesForInto(BasicBlock *src, BasicBlock *dest) const { 1720b57cec5SDimitry Andric BasicBlock::iterator I = dest->begin(); 1730b57cec5SDimitry Andric for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) { 1740b57cec5SDimitry Andric PHINode *phi = cast<PHINode>(I); 1750b57cec5SDimitry Andric phi->addIncoming(UnwindDestPHIValues[i], src); 1760b57cec5SDimitry Andric } 1770b57cec5SDimitry Andric } 1780b57cec5SDimitry Andric }; 1790b57cec5SDimitry Andric 1800b57cec5SDimitry Andric } // end anonymous namespace 1810b57cec5SDimitry Andric 1820b57cec5SDimitry Andric /// Get or create a target for the branch from ResumeInsts. 1830b57cec5SDimitry Andric BasicBlock *LandingPadInliningInfo::getInnerResumeDest() { 1840b57cec5SDimitry Andric if (InnerResumeDest) return InnerResumeDest; 1850b57cec5SDimitry Andric 1860b57cec5SDimitry Andric // Split the landing pad. 1870b57cec5SDimitry Andric BasicBlock::iterator SplitPoint = ++CallerLPad->getIterator(); 1880b57cec5SDimitry Andric InnerResumeDest = 1890b57cec5SDimitry Andric OuterResumeDest->splitBasicBlock(SplitPoint, 1900b57cec5SDimitry Andric OuterResumeDest->getName() + ".body"); 1910b57cec5SDimitry Andric 1920b57cec5SDimitry Andric // The number of incoming edges we expect to the inner landing pad. 1930b57cec5SDimitry Andric const unsigned PHICapacity = 2; 1940b57cec5SDimitry Andric 1950b57cec5SDimitry Andric // Create corresponding new PHIs for all the PHIs in the outer landing pad. 1965f757f3fSDimitry Andric BasicBlock::iterator InsertPoint = InnerResumeDest->begin(); 1970b57cec5SDimitry Andric BasicBlock::iterator I = OuterResumeDest->begin(); 1980b57cec5SDimitry Andric for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) { 1990b57cec5SDimitry Andric PHINode *OuterPHI = cast<PHINode>(I); 2000b57cec5SDimitry Andric PHINode *InnerPHI = PHINode::Create(OuterPHI->getType(), PHICapacity, 2015f757f3fSDimitry Andric OuterPHI->getName() + ".lpad-body"); 2025f757f3fSDimitry Andric InnerPHI->insertBefore(InsertPoint); 2030b57cec5SDimitry Andric OuterPHI->replaceAllUsesWith(InnerPHI); 2040b57cec5SDimitry Andric InnerPHI->addIncoming(OuterPHI, OuterResumeDest); 2050b57cec5SDimitry Andric } 2060b57cec5SDimitry Andric 2070b57cec5SDimitry Andric // Create a PHI for the exception values. 2085f757f3fSDimitry Andric InnerEHValuesPHI = 2095f757f3fSDimitry Andric PHINode::Create(CallerLPad->getType(), PHICapacity, "eh.lpad-body"); 2105f757f3fSDimitry Andric InnerEHValuesPHI->insertBefore(InsertPoint); 2110b57cec5SDimitry Andric CallerLPad->replaceAllUsesWith(InnerEHValuesPHI); 2120b57cec5SDimitry Andric InnerEHValuesPHI->addIncoming(CallerLPad, OuterResumeDest); 2130b57cec5SDimitry Andric 2140b57cec5SDimitry Andric // All done. 2150b57cec5SDimitry Andric return InnerResumeDest; 2160b57cec5SDimitry Andric } 2170b57cec5SDimitry Andric 2180b57cec5SDimitry Andric /// Forward the 'resume' instruction to the caller's landing pad block. 2190b57cec5SDimitry Andric /// When the landing pad block has only one predecessor, this is a simple 2200b57cec5SDimitry Andric /// branch. When there is more than one predecessor, we need to split the 2210b57cec5SDimitry Andric /// landing pad block after the landingpad instruction and jump to there. 2220b57cec5SDimitry Andric void LandingPadInliningInfo::forwardResume( 2230b57cec5SDimitry Andric ResumeInst *RI, SmallPtrSetImpl<LandingPadInst *> &InlinedLPads) { 2240b57cec5SDimitry Andric BasicBlock *Dest = getInnerResumeDest(); 2250b57cec5SDimitry Andric BasicBlock *Src = RI->getParent(); 2260b57cec5SDimitry Andric 2270b57cec5SDimitry Andric BranchInst::Create(Dest, Src); 2280b57cec5SDimitry Andric 2290b57cec5SDimitry Andric // Update the PHIs in the destination. They were inserted in an order which 2300b57cec5SDimitry Andric // makes this work. 2310b57cec5SDimitry Andric addIncomingPHIValuesForInto(Src, Dest); 2320b57cec5SDimitry Andric 2330b57cec5SDimitry Andric InnerEHValuesPHI->addIncoming(RI->getOperand(0), Src); 2340b57cec5SDimitry Andric RI->eraseFromParent(); 2350b57cec5SDimitry Andric } 2360b57cec5SDimitry Andric 2370b57cec5SDimitry Andric /// Helper for getUnwindDestToken/getUnwindDestTokenHelper. 2380b57cec5SDimitry Andric static Value *getParentPad(Value *EHPad) { 2390b57cec5SDimitry Andric if (auto *FPI = dyn_cast<FuncletPadInst>(EHPad)) 2400b57cec5SDimitry Andric return FPI->getParentPad(); 2410b57cec5SDimitry Andric return cast<CatchSwitchInst>(EHPad)->getParentPad(); 2420b57cec5SDimitry Andric } 2430b57cec5SDimitry Andric 2440b57cec5SDimitry Andric using UnwindDestMemoTy = DenseMap<Instruction *, Value *>; 2450b57cec5SDimitry Andric 2460b57cec5SDimitry Andric /// Helper for getUnwindDestToken that does the descendant-ward part of 2470b57cec5SDimitry Andric /// the search. 2480b57cec5SDimitry Andric static Value *getUnwindDestTokenHelper(Instruction *EHPad, 2490b57cec5SDimitry Andric UnwindDestMemoTy &MemoMap) { 2500b57cec5SDimitry Andric SmallVector<Instruction *, 8> Worklist(1, EHPad); 2510b57cec5SDimitry Andric 2520b57cec5SDimitry Andric while (!Worklist.empty()) { 2530b57cec5SDimitry Andric Instruction *CurrentPad = Worklist.pop_back_val(); 2540b57cec5SDimitry Andric // We only put pads on the worklist that aren't in the MemoMap. When 2550b57cec5SDimitry Andric // we find an unwind dest for a pad we may update its ancestors, but 2560b57cec5SDimitry Andric // the queue only ever contains uncles/great-uncles/etc. of CurrentPad, 2570b57cec5SDimitry Andric // so they should never get updated while queued on the worklist. 2580b57cec5SDimitry Andric assert(!MemoMap.count(CurrentPad)); 2590b57cec5SDimitry Andric Value *UnwindDestToken = nullptr; 2600b57cec5SDimitry Andric if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(CurrentPad)) { 2610b57cec5SDimitry Andric if (CatchSwitch->hasUnwindDest()) { 2620b57cec5SDimitry Andric UnwindDestToken = CatchSwitch->getUnwindDest()->getFirstNonPHI(); 2630b57cec5SDimitry Andric } else { 2640b57cec5SDimitry Andric // Catchswitch doesn't have a 'nounwind' variant, and one might be 2650b57cec5SDimitry Andric // annotated as "unwinds to caller" when really it's nounwind (see 2660b57cec5SDimitry Andric // e.g. SimplifyCFGOpt::SimplifyUnreachable), so we can't infer the 2670b57cec5SDimitry Andric // parent's unwind dest from this. We can check its catchpads' 2680b57cec5SDimitry Andric // descendants, since they might include a cleanuppad with an 2690b57cec5SDimitry Andric // "unwinds to caller" cleanupret, which can be trusted. 2700b57cec5SDimitry Andric for (auto HI = CatchSwitch->handler_begin(), 2710b57cec5SDimitry Andric HE = CatchSwitch->handler_end(); 2720b57cec5SDimitry Andric HI != HE && !UnwindDestToken; ++HI) { 2730b57cec5SDimitry Andric BasicBlock *HandlerBlock = *HI; 2740b57cec5SDimitry Andric auto *CatchPad = cast<CatchPadInst>(HandlerBlock->getFirstNonPHI()); 2750b57cec5SDimitry Andric for (User *Child : CatchPad->users()) { 2760b57cec5SDimitry Andric // Intentionally ignore invokes here -- since the catchswitch is 2770b57cec5SDimitry Andric // marked "unwind to caller", it would be a verifier error if it 2780b57cec5SDimitry Andric // contained an invoke which unwinds out of it, so any invoke we'd 2790b57cec5SDimitry Andric // encounter must unwind to some child of the catch. 2800b57cec5SDimitry Andric if (!isa<CleanupPadInst>(Child) && !isa<CatchSwitchInst>(Child)) 2810b57cec5SDimitry Andric continue; 2820b57cec5SDimitry Andric 2830b57cec5SDimitry Andric Instruction *ChildPad = cast<Instruction>(Child); 2840b57cec5SDimitry Andric auto Memo = MemoMap.find(ChildPad); 2850b57cec5SDimitry Andric if (Memo == MemoMap.end()) { 2860b57cec5SDimitry Andric // Haven't figured out this child pad yet; queue it. 2870b57cec5SDimitry Andric Worklist.push_back(ChildPad); 2880b57cec5SDimitry Andric continue; 2890b57cec5SDimitry Andric } 2900b57cec5SDimitry Andric // We've already checked this child, but might have found that 2910b57cec5SDimitry Andric // it offers no proof either way. 2920b57cec5SDimitry Andric Value *ChildUnwindDestToken = Memo->second; 2930b57cec5SDimitry Andric if (!ChildUnwindDestToken) 2940b57cec5SDimitry Andric continue; 2950b57cec5SDimitry Andric // We already know the child's unwind dest, which can either 2960b57cec5SDimitry Andric // be ConstantTokenNone to indicate unwind to caller, or can 2970b57cec5SDimitry Andric // be another child of the catchpad. Only the former indicates 2980b57cec5SDimitry Andric // the unwind dest of the catchswitch. 2990b57cec5SDimitry Andric if (isa<ConstantTokenNone>(ChildUnwindDestToken)) { 3000b57cec5SDimitry Andric UnwindDestToken = ChildUnwindDestToken; 3010b57cec5SDimitry Andric break; 3020b57cec5SDimitry Andric } 3030b57cec5SDimitry Andric assert(getParentPad(ChildUnwindDestToken) == CatchPad); 3040b57cec5SDimitry Andric } 3050b57cec5SDimitry Andric } 3060b57cec5SDimitry Andric } 3070b57cec5SDimitry Andric } else { 3080b57cec5SDimitry Andric auto *CleanupPad = cast<CleanupPadInst>(CurrentPad); 3090b57cec5SDimitry Andric for (User *U : CleanupPad->users()) { 3100b57cec5SDimitry Andric if (auto *CleanupRet = dyn_cast<CleanupReturnInst>(U)) { 3110b57cec5SDimitry Andric if (BasicBlock *RetUnwindDest = CleanupRet->getUnwindDest()) 3120b57cec5SDimitry Andric UnwindDestToken = RetUnwindDest->getFirstNonPHI(); 3130b57cec5SDimitry Andric else 3140b57cec5SDimitry Andric UnwindDestToken = ConstantTokenNone::get(CleanupPad->getContext()); 3150b57cec5SDimitry Andric break; 3160b57cec5SDimitry Andric } 3170b57cec5SDimitry Andric Value *ChildUnwindDestToken; 3180b57cec5SDimitry Andric if (auto *Invoke = dyn_cast<InvokeInst>(U)) { 3190b57cec5SDimitry Andric ChildUnwindDestToken = Invoke->getUnwindDest()->getFirstNonPHI(); 3200b57cec5SDimitry Andric } else if (isa<CleanupPadInst>(U) || isa<CatchSwitchInst>(U)) { 3210b57cec5SDimitry Andric Instruction *ChildPad = cast<Instruction>(U); 3220b57cec5SDimitry Andric auto Memo = MemoMap.find(ChildPad); 3230b57cec5SDimitry Andric if (Memo == MemoMap.end()) { 3240b57cec5SDimitry Andric // Haven't resolved this child yet; queue it and keep searching. 3250b57cec5SDimitry Andric Worklist.push_back(ChildPad); 3260b57cec5SDimitry Andric continue; 3270b57cec5SDimitry Andric } 3280b57cec5SDimitry Andric // We've checked this child, but still need to ignore it if it 3290b57cec5SDimitry Andric // had no proof either way. 3300b57cec5SDimitry Andric ChildUnwindDestToken = Memo->second; 3310b57cec5SDimitry Andric if (!ChildUnwindDestToken) 3320b57cec5SDimitry Andric continue; 3330b57cec5SDimitry Andric } else { 3340b57cec5SDimitry Andric // Not a relevant user of the cleanuppad 3350b57cec5SDimitry Andric continue; 3360b57cec5SDimitry Andric } 3370b57cec5SDimitry Andric // In a well-formed program, the child/invoke must either unwind to 3380b57cec5SDimitry Andric // an(other) child of the cleanup, or exit the cleanup. In the 3390b57cec5SDimitry Andric // first case, continue searching. 3400b57cec5SDimitry Andric if (isa<Instruction>(ChildUnwindDestToken) && 3410b57cec5SDimitry Andric getParentPad(ChildUnwindDestToken) == CleanupPad) 3420b57cec5SDimitry Andric continue; 3430b57cec5SDimitry Andric UnwindDestToken = ChildUnwindDestToken; 3440b57cec5SDimitry Andric break; 3450b57cec5SDimitry Andric } 3460b57cec5SDimitry Andric } 3470b57cec5SDimitry Andric // If we haven't found an unwind dest for CurrentPad, we may have queued its 3480b57cec5SDimitry Andric // children, so move on to the next in the worklist. 3490b57cec5SDimitry Andric if (!UnwindDestToken) 3500b57cec5SDimitry Andric continue; 3510b57cec5SDimitry Andric 3520b57cec5SDimitry Andric // Now we know that CurrentPad unwinds to UnwindDestToken. It also exits 3530b57cec5SDimitry Andric // any ancestors of CurrentPad up to but not including UnwindDestToken's 3540b57cec5SDimitry Andric // parent pad. Record this in the memo map, and check to see if the 3550b57cec5SDimitry Andric // original EHPad being queried is one of the ones exited. 3560b57cec5SDimitry Andric Value *UnwindParent; 3570b57cec5SDimitry Andric if (auto *UnwindPad = dyn_cast<Instruction>(UnwindDestToken)) 3580b57cec5SDimitry Andric UnwindParent = getParentPad(UnwindPad); 3590b57cec5SDimitry Andric else 3600b57cec5SDimitry Andric UnwindParent = nullptr; 3610b57cec5SDimitry Andric bool ExitedOriginalPad = false; 3620b57cec5SDimitry Andric for (Instruction *ExitedPad = CurrentPad; 3630b57cec5SDimitry Andric ExitedPad && ExitedPad != UnwindParent; 3640b57cec5SDimitry Andric ExitedPad = dyn_cast<Instruction>(getParentPad(ExitedPad))) { 3650b57cec5SDimitry Andric // Skip over catchpads since they just follow their catchswitches. 3660b57cec5SDimitry Andric if (isa<CatchPadInst>(ExitedPad)) 3670b57cec5SDimitry Andric continue; 3680b57cec5SDimitry Andric MemoMap[ExitedPad] = UnwindDestToken; 3690b57cec5SDimitry Andric ExitedOriginalPad |= (ExitedPad == EHPad); 3700b57cec5SDimitry Andric } 3710b57cec5SDimitry Andric 3720b57cec5SDimitry Andric if (ExitedOriginalPad) 3730b57cec5SDimitry Andric return UnwindDestToken; 3740b57cec5SDimitry Andric 3750b57cec5SDimitry Andric // Continue the search. 3760b57cec5SDimitry Andric } 3770b57cec5SDimitry Andric 3780b57cec5SDimitry Andric // No definitive information is contained within this funclet. 3790b57cec5SDimitry Andric return nullptr; 3800b57cec5SDimitry Andric } 3810b57cec5SDimitry Andric 3820b57cec5SDimitry Andric /// Given an EH pad, find where it unwinds. If it unwinds to an EH pad, 3830b57cec5SDimitry Andric /// return that pad instruction. If it unwinds to caller, return 3840b57cec5SDimitry Andric /// ConstantTokenNone. If it does not have a definitive unwind destination, 3850b57cec5SDimitry Andric /// return nullptr. 3860b57cec5SDimitry Andric /// 3870b57cec5SDimitry Andric /// This routine gets invoked for calls in funclets in inlinees when inlining 3880b57cec5SDimitry Andric /// an invoke. Since many funclets don't have calls inside them, it's queried 3890b57cec5SDimitry Andric /// on-demand rather than building a map of pads to unwind dests up front. 3900b57cec5SDimitry Andric /// Determining a funclet's unwind dest may require recursively searching its 3910b57cec5SDimitry Andric /// descendants, and also ancestors and cousins if the descendants don't provide 3920b57cec5SDimitry Andric /// an answer. Since most funclets will have their unwind dest immediately 3930b57cec5SDimitry Andric /// available as the unwind dest of a catchswitch or cleanupret, this routine 3940b57cec5SDimitry Andric /// searches top-down from the given pad and then up. To avoid worst-case 3950b57cec5SDimitry Andric /// quadratic run-time given that approach, it uses a memo map to avoid 3960b57cec5SDimitry Andric /// re-processing funclet trees. The callers that rewrite the IR as they go 3970b57cec5SDimitry Andric /// take advantage of this, for correctness, by checking/forcing rewritten 3980b57cec5SDimitry Andric /// pads' entries to match the original callee view. 3990b57cec5SDimitry Andric static Value *getUnwindDestToken(Instruction *EHPad, 4000b57cec5SDimitry Andric UnwindDestMemoTy &MemoMap) { 4010b57cec5SDimitry Andric // Catchpads unwind to the same place as their catchswitch; 4020b57cec5SDimitry Andric // redirct any queries on catchpads so the code below can 4030b57cec5SDimitry Andric // deal with just catchswitches and cleanuppads. 4040b57cec5SDimitry Andric if (auto *CPI = dyn_cast<CatchPadInst>(EHPad)) 4050b57cec5SDimitry Andric EHPad = CPI->getCatchSwitch(); 4060b57cec5SDimitry Andric 4070b57cec5SDimitry Andric // Check if we've already determined the unwind dest for this pad. 4080b57cec5SDimitry Andric auto Memo = MemoMap.find(EHPad); 4090b57cec5SDimitry Andric if (Memo != MemoMap.end()) 4100b57cec5SDimitry Andric return Memo->second; 4110b57cec5SDimitry Andric 4120b57cec5SDimitry Andric // Search EHPad and, if necessary, its descendants. 4130b57cec5SDimitry Andric Value *UnwindDestToken = getUnwindDestTokenHelper(EHPad, MemoMap); 4140b57cec5SDimitry Andric assert((UnwindDestToken == nullptr) != (MemoMap.count(EHPad) != 0)); 4150b57cec5SDimitry Andric if (UnwindDestToken) 4160b57cec5SDimitry Andric return UnwindDestToken; 4170b57cec5SDimitry Andric 4180b57cec5SDimitry Andric // No information is available for this EHPad from itself or any of its 4190b57cec5SDimitry Andric // descendants. An unwind all the way out to a pad in the caller would 4200b57cec5SDimitry Andric // need also to agree with the unwind dest of the parent funclet, so 4210b57cec5SDimitry Andric // search up the chain to try to find a funclet with information. Put 4220b57cec5SDimitry Andric // null entries in the memo map to avoid re-processing as we go up. 4230b57cec5SDimitry Andric MemoMap[EHPad] = nullptr; 4240b57cec5SDimitry Andric #ifndef NDEBUG 4250b57cec5SDimitry Andric SmallPtrSet<Instruction *, 4> TempMemos; 4260b57cec5SDimitry Andric TempMemos.insert(EHPad); 4270b57cec5SDimitry Andric #endif 4280b57cec5SDimitry Andric Instruction *LastUselessPad = EHPad; 4290b57cec5SDimitry Andric Value *AncestorToken; 4300b57cec5SDimitry Andric for (AncestorToken = getParentPad(EHPad); 4310b57cec5SDimitry Andric auto *AncestorPad = dyn_cast<Instruction>(AncestorToken); 4320b57cec5SDimitry Andric AncestorToken = getParentPad(AncestorToken)) { 4330b57cec5SDimitry Andric // Skip over catchpads since they just follow their catchswitches. 4340b57cec5SDimitry Andric if (isa<CatchPadInst>(AncestorPad)) 4350b57cec5SDimitry Andric continue; 4360b57cec5SDimitry Andric // If the MemoMap had an entry mapping AncestorPad to nullptr, since we 4370b57cec5SDimitry Andric // haven't yet called getUnwindDestTokenHelper for AncestorPad in this 4380b57cec5SDimitry Andric // call to getUnwindDestToken, that would mean that AncestorPad had no 4390b57cec5SDimitry Andric // information in itself, its descendants, or its ancestors. If that 4400b57cec5SDimitry Andric // were the case, then we should also have recorded the lack of information 4410b57cec5SDimitry Andric // for the descendant that we're coming from. So assert that we don't 4420b57cec5SDimitry Andric // find a null entry in the MemoMap for AncestorPad. 4430b57cec5SDimitry Andric assert(!MemoMap.count(AncestorPad) || MemoMap[AncestorPad]); 4440b57cec5SDimitry Andric auto AncestorMemo = MemoMap.find(AncestorPad); 4450b57cec5SDimitry Andric if (AncestorMemo == MemoMap.end()) { 4460b57cec5SDimitry Andric UnwindDestToken = getUnwindDestTokenHelper(AncestorPad, MemoMap); 4470b57cec5SDimitry Andric } else { 4480b57cec5SDimitry Andric UnwindDestToken = AncestorMemo->second; 4490b57cec5SDimitry Andric } 4500b57cec5SDimitry Andric if (UnwindDestToken) 4510b57cec5SDimitry Andric break; 4520b57cec5SDimitry Andric LastUselessPad = AncestorPad; 4530b57cec5SDimitry Andric MemoMap[LastUselessPad] = nullptr; 4540b57cec5SDimitry Andric #ifndef NDEBUG 4550b57cec5SDimitry Andric TempMemos.insert(LastUselessPad); 4560b57cec5SDimitry Andric #endif 4570b57cec5SDimitry Andric } 4580b57cec5SDimitry Andric 4590b57cec5SDimitry Andric // We know that getUnwindDestTokenHelper was called on LastUselessPad and 4600b57cec5SDimitry Andric // returned nullptr (and likewise for EHPad and any of its ancestors up to 4610b57cec5SDimitry Andric // LastUselessPad), so LastUselessPad has no information from below. Since 4620b57cec5SDimitry Andric // getUnwindDestTokenHelper must investigate all downward paths through 4630b57cec5SDimitry Andric // no-information nodes to prove that a node has no information like this, 4640b57cec5SDimitry Andric // and since any time it finds information it records it in the MemoMap for 4650b57cec5SDimitry Andric // not just the immediately-containing funclet but also any ancestors also 4660b57cec5SDimitry Andric // exited, it must be the case that, walking downward from LastUselessPad, 4670b57cec5SDimitry Andric // visiting just those nodes which have not been mapped to an unwind dest 4680b57cec5SDimitry Andric // by getUnwindDestTokenHelper (the nullptr TempMemos notwithstanding, since 4690b57cec5SDimitry Andric // they are just used to keep getUnwindDestTokenHelper from repeating work), 4700b57cec5SDimitry Andric // any node visited must have been exhaustively searched with no information 4710b57cec5SDimitry Andric // for it found. 4720b57cec5SDimitry Andric SmallVector<Instruction *, 8> Worklist(1, LastUselessPad); 4730b57cec5SDimitry Andric while (!Worklist.empty()) { 4740b57cec5SDimitry Andric Instruction *UselessPad = Worklist.pop_back_val(); 4750b57cec5SDimitry Andric auto Memo = MemoMap.find(UselessPad); 4760b57cec5SDimitry Andric if (Memo != MemoMap.end() && Memo->second) { 4770b57cec5SDimitry Andric // Here the name 'UselessPad' is a bit of a misnomer, because we've found 4780b57cec5SDimitry Andric // that it is a funclet that does have information about unwinding to 4790b57cec5SDimitry Andric // a particular destination; its parent was a useless pad. 4800b57cec5SDimitry Andric // Since its parent has no information, the unwind edge must not escape 4810b57cec5SDimitry Andric // the parent, and must target a sibling of this pad. This local unwind 4820b57cec5SDimitry Andric // gives us no information about EHPad. Leave it and the subtree rooted 4830b57cec5SDimitry Andric // at it alone. 4840b57cec5SDimitry Andric assert(getParentPad(Memo->second) == getParentPad(UselessPad)); 4850b57cec5SDimitry Andric continue; 4860b57cec5SDimitry Andric } 4870b57cec5SDimitry Andric // We know we don't have information for UselesPad. If it has an entry in 4880b57cec5SDimitry Andric // the MemoMap (mapping it to nullptr), it must be one of the TempMemos 4890b57cec5SDimitry Andric // added on this invocation of getUnwindDestToken; if a previous invocation 4900b57cec5SDimitry Andric // recorded nullptr, it would have had to prove that the ancestors of 4910b57cec5SDimitry Andric // UselessPad, which include LastUselessPad, had no information, and that 4920b57cec5SDimitry Andric // in turn would have required proving that the descendants of 4930b57cec5SDimitry Andric // LastUselesPad, which include EHPad, have no information about 4940b57cec5SDimitry Andric // LastUselessPad, which would imply that EHPad was mapped to nullptr in 4950b57cec5SDimitry Andric // the MemoMap on that invocation, which isn't the case if we got here. 4960b57cec5SDimitry Andric assert(!MemoMap.count(UselessPad) || TempMemos.count(UselessPad)); 4970b57cec5SDimitry Andric // Assert as we enumerate users that 'UselessPad' doesn't have any unwind 4980b57cec5SDimitry Andric // information that we'd be contradicting by making a map entry for it 4990b57cec5SDimitry Andric // (which is something that getUnwindDestTokenHelper must have proved for 5000b57cec5SDimitry Andric // us to get here). Just assert on is direct users here; the checks in 5010b57cec5SDimitry Andric // this downward walk at its descendants will verify that they don't have 5020b57cec5SDimitry Andric // any unwind edges that exit 'UselessPad' either (i.e. they either have no 5030b57cec5SDimitry Andric // unwind edges or unwind to a sibling). 5040b57cec5SDimitry Andric MemoMap[UselessPad] = UnwindDestToken; 5050b57cec5SDimitry Andric if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(UselessPad)) { 5060b57cec5SDimitry Andric assert(CatchSwitch->getUnwindDest() == nullptr && "Expected useless pad"); 5070b57cec5SDimitry Andric for (BasicBlock *HandlerBlock : CatchSwitch->handlers()) { 5080b57cec5SDimitry Andric auto *CatchPad = HandlerBlock->getFirstNonPHI(); 5090b57cec5SDimitry Andric for (User *U : CatchPad->users()) { 5100b57cec5SDimitry Andric assert( 5110b57cec5SDimitry Andric (!isa<InvokeInst>(U) || 5120b57cec5SDimitry Andric (getParentPad( 5130b57cec5SDimitry Andric cast<InvokeInst>(U)->getUnwindDest()->getFirstNonPHI()) == 5140b57cec5SDimitry Andric CatchPad)) && 5150b57cec5SDimitry Andric "Expected useless pad"); 5160b57cec5SDimitry Andric if (isa<CatchSwitchInst>(U) || isa<CleanupPadInst>(U)) 5170b57cec5SDimitry Andric Worklist.push_back(cast<Instruction>(U)); 5180b57cec5SDimitry Andric } 5190b57cec5SDimitry Andric } 5200b57cec5SDimitry Andric } else { 5210b57cec5SDimitry Andric assert(isa<CleanupPadInst>(UselessPad)); 5220b57cec5SDimitry Andric for (User *U : UselessPad->users()) { 5230b57cec5SDimitry Andric assert(!isa<CleanupReturnInst>(U) && "Expected useless pad"); 5240b57cec5SDimitry Andric assert((!isa<InvokeInst>(U) || 5250b57cec5SDimitry Andric (getParentPad( 5260b57cec5SDimitry Andric cast<InvokeInst>(U)->getUnwindDest()->getFirstNonPHI()) == 5270b57cec5SDimitry Andric UselessPad)) && 5280b57cec5SDimitry Andric "Expected useless pad"); 5290b57cec5SDimitry Andric if (isa<CatchSwitchInst>(U) || isa<CleanupPadInst>(U)) 5300b57cec5SDimitry Andric Worklist.push_back(cast<Instruction>(U)); 5310b57cec5SDimitry Andric } 5320b57cec5SDimitry Andric } 5330b57cec5SDimitry Andric } 5340b57cec5SDimitry Andric 5350b57cec5SDimitry Andric return UnwindDestToken; 5360b57cec5SDimitry Andric } 5370b57cec5SDimitry Andric 5380b57cec5SDimitry Andric /// When we inline a basic block into an invoke, 5390b57cec5SDimitry Andric /// we have to turn all of the calls that can throw into invokes. 5400b57cec5SDimitry Andric /// This function analyze BB to see if there are any calls, and if so, 5410b57cec5SDimitry Andric /// it rewrites them to be invokes that jump to InvokeDest and fills in the PHI 5420b57cec5SDimitry Andric /// nodes in that block with the values specified in InvokeDestPHIValues. 5430b57cec5SDimitry Andric static BasicBlock *HandleCallsInBlockInlinedThroughInvoke( 5440b57cec5SDimitry Andric BasicBlock *BB, BasicBlock *UnwindEdge, 5450b57cec5SDimitry Andric UnwindDestMemoTy *FuncletUnwindMap = nullptr) { 546349cc55cSDimitry Andric for (Instruction &I : llvm::make_early_inc_range(*BB)) { 5470b57cec5SDimitry Andric // We only need to check for function calls: inlined invoke 5480b57cec5SDimitry Andric // instructions require no special handling. 549349cc55cSDimitry Andric CallInst *CI = dyn_cast<CallInst>(&I); 5500b57cec5SDimitry Andric 551fe6060f1SDimitry Andric if (!CI || CI->doesNotThrow()) 5520b57cec5SDimitry Andric continue; 5530b57cec5SDimitry Andric 5540b57cec5SDimitry Andric // We do not need to (and in fact, cannot) convert possibly throwing calls 5550b57cec5SDimitry Andric // to @llvm.experimental_deoptimize (resp. @llvm.experimental.guard) into 5560b57cec5SDimitry Andric // invokes. The caller's "segment" of the deoptimization continuation 5570b57cec5SDimitry Andric // attached to the newly inlined @llvm.experimental_deoptimize 5580b57cec5SDimitry Andric // (resp. @llvm.experimental.guard) call should contain the exception 5590b57cec5SDimitry Andric // handling logic, if any. 5600b57cec5SDimitry Andric if (auto *F = CI->getCalledFunction()) 5610b57cec5SDimitry Andric if (F->getIntrinsicID() == Intrinsic::experimental_deoptimize || 5620b57cec5SDimitry Andric F->getIntrinsicID() == Intrinsic::experimental_guard) 5630b57cec5SDimitry Andric continue; 5640b57cec5SDimitry Andric 5650b57cec5SDimitry Andric if (auto FuncletBundle = CI->getOperandBundle(LLVMContext::OB_funclet)) { 5660b57cec5SDimitry Andric // This call is nested inside a funclet. If that funclet has an unwind 5670b57cec5SDimitry Andric // destination within the inlinee, then unwinding out of this call would 5680b57cec5SDimitry Andric // be UB. Rewriting this call to an invoke which targets the inlined 5690b57cec5SDimitry Andric // invoke's unwind dest would give the call's parent funclet multiple 5700b57cec5SDimitry Andric // unwind destinations, which is something that subsequent EH table 5710b57cec5SDimitry Andric // generation can't handle and that the veirifer rejects. So when we 5720b57cec5SDimitry Andric // see such a call, leave it as a call. 5730b57cec5SDimitry Andric auto *FuncletPad = cast<Instruction>(FuncletBundle->Inputs[0]); 5740b57cec5SDimitry Andric Value *UnwindDestToken = 5750b57cec5SDimitry Andric getUnwindDestToken(FuncletPad, *FuncletUnwindMap); 5760b57cec5SDimitry Andric if (UnwindDestToken && !isa<ConstantTokenNone>(UnwindDestToken)) 5770b57cec5SDimitry Andric continue; 5780b57cec5SDimitry Andric #ifndef NDEBUG 5790b57cec5SDimitry Andric Instruction *MemoKey; 5800b57cec5SDimitry Andric if (auto *CatchPad = dyn_cast<CatchPadInst>(FuncletPad)) 5810b57cec5SDimitry Andric MemoKey = CatchPad->getCatchSwitch(); 5820b57cec5SDimitry Andric else 5830b57cec5SDimitry Andric MemoKey = FuncletPad; 5840b57cec5SDimitry Andric assert(FuncletUnwindMap->count(MemoKey) && 5850b57cec5SDimitry Andric (*FuncletUnwindMap)[MemoKey] == UnwindDestToken && 5860b57cec5SDimitry Andric "must get memoized to avoid confusing later searches"); 5870b57cec5SDimitry Andric #endif // NDEBUG 5880b57cec5SDimitry Andric } 5890b57cec5SDimitry Andric 5900b57cec5SDimitry Andric changeToInvokeAndSplitBasicBlock(CI, UnwindEdge); 5910b57cec5SDimitry Andric return BB; 5920b57cec5SDimitry Andric } 5930b57cec5SDimitry Andric return nullptr; 5940b57cec5SDimitry Andric } 5950b57cec5SDimitry Andric 5960b57cec5SDimitry Andric /// If we inlined an invoke site, we need to convert calls 5970b57cec5SDimitry Andric /// in the body of the inlined function into invokes. 5980b57cec5SDimitry Andric /// 5990b57cec5SDimitry Andric /// II is the invoke instruction being inlined. FirstNewBlock is the first 6000b57cec5SDimitry Andric /// block of the inlined code (the last block is the end of the function), 6010b57cec5SDimitry Andric /// and InlineCodeInfo is information about the code that got inlined. 6020b57cec5SDimitry Andric static void HandleInlinedLandingPad(InvokeInst *II, BasicBlock *FirstNewBlock, 6030b57cec5SDimitry Andric ClonedCodeInfo &InlinedCodeInfo) { 6040b57cec5SDimitry Andric BasicBlock *InvokeDest = II->getUnwindDest(); 6050b57cec5SDimitry Andric 6060b57cec5SDimitry Andric Function *Caller = FirstNewBlock->getParent(); 6070b57cec5SDimitry Andric 6080b57cec5SDimitry Andric // The inlined code is currently at the end of the function, scan from the 6090b57cec5SDimitry Andric // start of the inlined code to its end, checking for stuff we need to 6100b57cec5SDimitry Andric // rewrite. 6110b57cec5SDimitry Andric LandingPadInliningInfo Invoke(II); 6120b57cec5SDimitry Andric 6130b57cec5SDimitry Andric // Get all of the inlined landing pad instructions. 6140b57cec5SDimitry Andric SmallPtrSet<LandingPadInst*, 16> InlinedLPads; 6150b57cec5SDimitry Andric for (Function::iterator I = FirstNewBlock->getIterator(), E = Caller->end(); 6160b57cec5SDimitry Andric I != E; ++I) 6170b57cec5SDimitry Andric if (InvokeInst *II = dyn_cast<InvokeInst>(I->getTerminator())) 6180b57cec5SDimitry Andric InlinedLPads.insert(II->getLandingPadInst()); 6190b57cec5SDimitry Andric 6200b57cec5SDimitry Andric // Append the clauses from the outer landing pad instruction into the inlined 6210b57cec5SDimitry Andric // landing pad instructions. 6220b57cec5SDimitry Andric LandingPadInst *OuterLPad = Invoke.getLandingPadInst(); 6230b57cec5SDimitry Andric for (LandingPadInst *InlinedLPad : InlinedLPads) { 6240b57cec5SDimitry Andric unsigned OuterNum = OuterLPad->getNumClauses(); 6250b57cec5SDimitry Andric InlinedLPad->reserveClauses(OuterNum); 6260b57cec5SDimitry Andric for (unsigned OuterIdx = 0; OuterIdx != OuterNum; ++OuterIdx) 6270b57cec5SDimitry Andric InlinedLPad->addClause(OuterLPad->getClause(OuterIdx)); 6280b57cec5SDimitry Andric if (OuterLPad->isCleanup()) 6290b57cec5SDimitry Andric InlinedLPad->setCleanup(true); 6300b57cec5SDimitry Andric } 6310b57cec5SDimitry Andric 6320b57cec5SDimitry Andric for (Function::iterator BB = FirstNewBlock->getIterator(), E = Caller->end(); 6330b57cec5SDimitry Andric BB != E; ++BB) { 6340b57cec5SDimitry Andric if (InlinedCodeInfo.ContainsCalls) 6350b57cec5SDimitry Andric if (BasicBlock *NewBB = HandleCallsInBlockInlinedThroughInvoke( 6360b57cec5SDimitry Andric &*BB, Invoke.getOuterResumeDest())) 6370b57cec5SDimitry Andric // Update any PHI nodes in the exceptional block to indicate that there 6380b57cec5SDimitry Andric // is now a new entry in them. 6390b57cec5SDimitry Andric Invoke.addIncomingPHIValuesFor(NewBB); 6400b57cec5SDimitry Andric 6410b57cec5SDimitry Andric // Forward any resumes that are remaining here. 6420b57cec5SDimitry Andric if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator())) 6430b57cec5SDimitry Andric Invoke.forwardResume(RI, InlinedLPads); 6440b57cec5SDimitry Andric } 6450b57cec5SDimitry Andric 6460b57cec5SDimitry Andric // Now that everything is happy, we have one final detail. The PHI nodes in 6470b57cec5SDimitry Andric // the exception destination block still have entries due to the original 6480b57cec5SDimitry Andric // invoke instruction. Eliminate these entries (which might even delete the 6490b57cec5SDimitry Andric // PHI node) now. 6500b57cec5SDimitry Andric InvokeDest->removePredecessor(II->getParent()); 6510b57cec5SDimitry Andric } 6520b57cec5SDimitry Andric 6530b57cec5SDimitry Andric /// If we inlined an invoke site, we need to convert calls 6540b57cec5SDimitry Andric /// in the body of the inlined function into invokes. 6550b57cec5SDimitry Andric /// 6560b57cec5SDimitry Andric /// II is the invoke instruction being inlined. FirstNewBlock is the first 6570b57cec5SDimitry Andric /// block of the inlined code (the last block is the end of the function), 6580b57cec5SDimitry Andric /// and InlineCodeInfo is information about the code that got inlined. 6590b57cec5SDimitry Andric static void HandleInlinedEHPad(InvokeInst *II, BasicBlock *FirstNewBlock, 6600b57cec5SDimitry Andric ClonedCodeInfo &InlinedCodeInfo) { 6610b57cec5SDimitry Andric BasicBlock *UnwindDest = II->getUnwindDest(); 6620b57cec5SDimitry Andric Function *Caller = FirstNewBlock->getParent(); 6630b57cec5SDimitry Andric 6640b57cec5SDimitry Andric assert(UnwindDest->getFirstNonPHI()->isEHPad() && "unexpected BasicBlock!"); 6650b57cec5SDimitry Andric 6660b57cec5SDimitry Andric // If there are PHI nodes in the unwind destination block, we need to keep 6670b57cec5SDimitry Andric // track of which values came into them from the invoke before removing the 6680b57cec5SDimitry Andric // edge from this block. 6690b57cec5SDimitry Andric SmallVector<Value *, 8> UnwindDestPHIValues; 6700b57cec5SDimitry Andric BasicBlock *InvokeBB = II->getParent(); 6711fd87a68SDimitry Andric for (PHINode &PHI : UnwindDest->phis()) { 6720b57cec5SDimitry Andric // Save the value to use for this edge. 6731fd87a68SDimitry Andric UnwindDestPHIValues.push_back(PHI.getIncomingValueForBlock(InvokeBB)); 6740b57cec5SDimitry Andric } 6750b57cec5SDimitry Andric 6760b57cec5SDimitry Andric // Add incoming-PHI values to the unwind destination block for the given basic 6770b57cec5SDimitry Andric // block, using the values for the original invoke's source block. 6780b57cec5SDimitry Andric auto UpdatePHINodes = [&](BasicBlock *Src) { 6790b57cec5SDimitry Andric BasicBlock::iterator I = UnwindDest->begin(); 6800b57cec5SDimitry Andric for (Value *V : UnwindDestPHIValues) { 6810b57cec5SDimitry Andric PHINode *PHI = cast<PHINode>(I); 6820b57cec5SDimitry Andric PHI->addIncoming(V, Src); 6830b57cec5SDimitry Andric ++I; 6840b57cec5SDimitry Andric } 6850b57cec5SDimitry Andric }; 6860b57cec5SDimitry Andric 6870b57cec5SDimitry Andric // This connects all the instructions which 'unwind to caller' to the invoke 6880b57cec5SDimitry Andric // destination. 6890b57cec5SDimitry Andric UnwindDestMemoTy FuncletUnwindMap; 6900b57cec5SDimitry Andric for (Function::iterator BB = FirstNewBlock->getIterator(), E = Caller->end(); 6910b57cec5SDimitry Andric BB != E; ++BB) { 6920b57cec5SDimitry Andric if (auto *CRI = dyn_cast<CleanupReturnInst>(BB->getTerminator())) { 6930b57cec5SDimitry Andric if (CRI->unwindsToCaller()) { 6940b57cec5SDimitry Andric auto *CleanupPad = CRI->getCleanupPad(); 6950fca6ea1SDimitry Andric CleanupReturnInst::Create(CleanupPad, UnwindDest, CRI->getIterator()); 6960b57cec5SDimitry Andric CRI->eraseFromParent(); 6970b57cec5SDimitry Andric UpdatePHINodes(&*BB); 6980b57cec5SDimitry Andric // Finding a cleanupret with an unwind destination would confuse 6990b57cec5SDimitry Andric // subsequent calls to getUnwindDestToken, so map the cleanuppad 7000b57cec5SDimitry Andric // to short-circuit any such calls and recognize this as an "unwind 7010b57cec5SDimitry Andric // to caller" cleanup. 7020b57cec5SDimitry Andric assert(!FuncletUnwindMap.count(CleanupPad) || 7030b57cec5SDimitry Andric isa<ConstantTokenNone>(FuncletUnwindMap[CleanupPad])); 7040b57cec5SDimitry Andric FuncletUnwindMap[CleanupPad] = 7050b57cec5SDimitry Andric ConstantTokenNone::get(Caller->getContext()); 7060b57cec5SDimitry Andric } 7070b57cec5SDimitry Andric } 7080b57cec5SDimitry Andric 7090b57cec5SDimitry Andric Instruction *I = BB->getFirstNonPHI(); 7100b57cec5SDimitry Andric if (!I->isEHPad()) 7110b57cec5SDimitry Andric continue; 7120b57cec5SDimitry Andric 7130b57cec5SDimitry Andric Instruction *Replacement = nullptr; 7140b57cec5SDimitry Andric if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(I)) { 7150b57cec5SDimitry Andric if (CatchSwitch->unwindsToCaller()) { 7160b57cec5SDimitry Andric Value *UnwindDestToken; 7170b57cec5SDimitry Andric if (auto *ParentPad = 7180b57cec5SDimitry Andric dyn_cast<Instruction>(CatchSwitch->getParentPad())) { 7190b57cec5SDimitry Andric // This catchswitch is nested inside another funclet. If that 7200b57cec5SDimitry Andric // funclet has an unwind destination within the inlinee, then 7210b57cec5SDimitry Andric // unwinding out of this catchswitch would be UB. Rewriting this 7220b57cec5SDimitry Andric // catchswitch to unwind to the inlined invoke's unwind dest would 7230b57cec5SDimitry Andric // give the parent funclet multiple unwind destinations, which is 7240b57cec5SDimitry Andric // something that subsequent EH table generation can't handle and 7250b57cec5SDimitry Andric // that the veirifer rejects. So when we see such a call, leave it 7260b57cec5SDimitry Andric // as "unwind to caller". 7270b57cec5SDimitry Andric UnwindDestToken = getUnwindDestToken(ParentPad, FuncletUnwindMap); 7280b57cec5SDimitry Andric if (UnwindDestToken && !isa<ConstantTokenNone>(UnwindDestToken)) 7290b57cec5SDimitry Andric continue; 7300b57cec5SDimitry Andric } else { 7310b57cec5SDimitry Andric // This catchswitch has no parent to inherit constraints from, and 7320b57cec5SDimitry Andric // none of its descendants can have an unwind edge that exits it and 7330b57cec5SDimitry Andric // targets another funclet in the inlinee. It may or may not have a 7340b57cec5SDimitry Andric // descendant that definitively has an unwind to caller. In either 7350b57cec5SDimitry Andric // case, we'll have to assume that any unwinds out of it may need to 7360b57cec5SDimitry Andric // be routed to the caller, so treat it as though it has a definitive 7370b57cec5SDimitry Andric // unwind to caller. 7380b57cec5SDimitry Andric UnwindDestToken = ConstantTokenNone::get(Caller->getContext()); 7390b57cec5SDimitry Andric } 7400b57cec5SDimitry Andric auto *NewCatchSwitch = CatchSwitchInst::Create( 7410b57cec5SDimitry Andric CatchSwitch->getParentPad(), UnwindDest, 7420b57cec5SDimitry Andric CatchSwitch->getNumHandlers(), CatchSwitch->getName(), 7430fca6ea1SDimitry Andric CatchSwitch->getIterator()); 7440b57cec5SDimitry Andric for (BasicBlock *PadBB : CatchSwitch->handlers()) 7450b57cec5SDimitry Andric NewCatchSwitch->addHandler(PadBB); 7460b57cec5SDimitry Andric // Propagate info for the old catchswitch over to the new one in 7470b57cec5SDimitry Andric // the unwind map. This also serves to short-circuit any subsequent 7480b57cec5SDimitry Andric // checks for the unwind dest of this catchswitch, which would get 7490b57cec5SDimitry Andric // confused if they found the outer handler in the callee. 7500b57cec5SDimitry Andric FuncletUnwindMap[NewCatchSwitch] = UnwindDestToken; 7510b57cec5SDimitry Andric Replacement = NewCatchSwitch; 7520b57cec5SDimitry Andric } 7530b57cec5SDimitry Andric } else if (!isa<FuncletPadInst>(I)) { 7540b57cec5SDimitry Andric llvm_unreachable("unexpected EHPad!"); 7550b57cec5SDimitry Andric } 7560b57cec5SDimitry Andric 7570b57cec5SDimitry Andric if (Replacement) { 7580b57cec5SDimitry Andric Replacement->takeName(I); 7590b57cec5SDimitry Andric I->replaceAllUsesWith(Replacement); 7600b57cec5SDimitry Andric I->eraseFromParent(); 7610b57cec5SDimitry Andric UpdatePHINodes(&*BB); 7620b57cec5SDimitry Andric } 7630b57cec5SDimitry Andric } 7640b57cec5SDimitry Andric 7650b57cec5SDimitry Andric if (InlinedCodeInfo.ContainsCalls) 7660b57cec5SDimitry Andric for (Function::iterator BB = FirstNewBlock->getIterator(), 7670b57cec5SDimitry Andric E = Caller->end(); 7680b57cec5SDimitry Andric BB != E; ++BB) 7690b57cec5SDimitry Andric if (BasicBlock *NewBB = HandleCallsInBlockInlinedThroughInvoke( 7700b57cec5SDimitry Andric &*BB, UnwindDest, &FuncletUnwindMap)) 7710b57cec5SDimitry Andric // Update any PHI nodes in the exceptional block to indicate that there 7720b57cec5SDimitry Andric // is now a new entry in them. 7730b57cec5SDimitry Andric UpdatePHINodes(NewBB); 7740b57cec5SDimitry Andric 7750b57cec5SDimitry Andric // Now that everything is happy, we have one final detail. The PHI nodes in 7760b57cec5SDimitry Andric // the exception destination block still have entries due to the original 7770b57cec5SDimitry Andric // invoke instruction. Eliminate these entries (which might even delete the 7780b57cec5SDimitry Andric // PHI node) now. 7790b57cec5SDimitry Andric UnwindDest->removePredecessor(InvokeBB); 7800b57cec5SDimitry Andric } 7810b57cec5SDimitry Andric 782bdd1243dSDimitry Andric static bool haveCommonPrefix(MDNode *MIBStackContext, 783bdd1243dSDimitry Andric MDNode *CallsiteStackContext) { 784bdd1243dSDimitry Andric assert(MIBStackContext->getNumOperands() > 0 && 785bdd1243dSDimitry Andric CallsiteStackContext->getNumOperands() > 0); 786bdd1243dSDimitry Andric // Because of the context trimming performed during matching, the callsite 787bdd1243dSDimitry Andric // context could have more stack ids than the MIB. We match up to the end of 788bdd1243dSDimitry Andric // the shortest stack context. 789bdd1243dSDimitry Andric for (auto MIBStackIter = MIBStackContext->op_begin(), 790bdd1243dSDimitry Andric CallsiteStackIter = CallsiteStackContext->op_begin(); 791bdd1243dSDimitry Andric MIBStackIter != MIBStackContext->op_end() && 792bdd1243dSDimitry Andric CallsiteStackIter != CallsiteStackContext->op_end(); 793bdd1243dSDimitry Andric MIBStackIter++, CallsiteStackIter++) { 794bdd1243dSDimitry Andric auto *Val1 = mdconst::dyn_extract<ConstantInt>(*MIBStackIter); 795bdd1243dSDimitry Andric auto *Val2 = mdconst::dyn_extract<ConstantInt>(*CallsiteStackIter); 796bdd1243dSDimitry Andric assert(Val1 && Val2); 797bdd1243dSDimitry Andric if (Val1->getZExtValue() != Val2->getZExtValue()) 798bdd1243dSDimitry Andric return false; 799bdd1243dSDimitry Andric } 800bdd1243dSDimitry Andric return true; 801bdd1243dSDimitry Andric } 802bdd1243dSDimitry Andric 803bdd1243dSDimitry Andric static void removeMemProfMetadata(CallBase *Call) { 804bdd1243dSDimitry Andric Call->setMetadata(LLVMContext::MD_memprof, nullptr); 805bdd1243dSDimitry Andric } 806bdd1243dSDimitry Andric 807bdd1243dSDimitry Andric static void removeCallsiteMetadata(CallBase *Call) { 808bdd1243dSDimitry Andric Call->setMetadata(LLVMContext::MD_callsite, nullptr); 809bdd1243dSDimitry Andric } 810bdd1243dSDimitry Andric 811bdd1243dSDimitry Andric static void updateMemprofMetadata(CallBase *CI, 812bdd1243dSDimitry Andric const std::vector<Metadata *> &MIBList) { 813bdd1243dSDimitry Andric assert(!MIBList.empty()); 814bdd1243dSDimitry Andric // Remove existing memprof, which will either be replaced or may not be needed 815bdd1243dSDimitry Andric // if we are able to use a single allocation type function attribute. 816bdd1243dSDimitry Andric removeMemProfMetadata(CI); 817bdd1243dSDimitry Andric CallStackTrie CallStack; 818bdd1243dSDimitry Andric for (Metadata *MIB : MIBList) 819bdd1243dSDimitry Andric CallStack.addCallStack(cast<MDNode>(MIB)); 820bdd1243dSDimitry Andric bool MemprofMDAttached = CallStack.buildAndAttachMIBMetadata(CI); 821bdd1243dSDimitry Andric assert(MemprofMDAttached == CI->hasMetadata(LLVMContext::MD_memprof)); 822bdd1243dSDimitry Andric if (!MemprofMDAttached) 823bdd1243dSDimitry Andric // If we used a function attribute remove the callsite metadata as well. 824bdd1243dSDimitry Andric removeCallsiteMetadata(CI); 825bdd1243dSDimitry Andric } 826bdd1243dSDimitry Andric 827bdd1243dSDimitry Andric // Update the metadata on the inlined copy ClonedCall of a call OrigCall in the 828bdd1243dSDimitry Andric // inlined callee body, based on the callsite metadata InlinedCallsiteMD from 829bdd1243dSDimitry Andric // the call that was inlined. 830bdd1243dSDimitry Andric static void propagateMemProfHelper(const CallBase *OrigCall, 831bdd1243dSDimitry Andric CallBase *ClonedCall, 832bdd1243dSDimitry Andric MDNode *InlinedCallsiteMD) { 833bdd1243dSDimitry Andric MDNode *OrigCallsiteMD = ClonedCall->getMetadata(LLVMContext::MD_callsite); 834bdd1243dSDimitry Andric MDNode *ClonedCallsiteMD = nullptr; 835bdd1243dSDimitry Andric // Check if the call originally had callsite metadata, and update it for the 836bdd1243dSDimitry Andric // new call in the inlined body. 837bdd1243dSDimitry Andric if (OrigCallsiteMD) { 838bdd1243dSDimitry Andric // The cloned call's context is now the concatenation of the original call's 839bdd1243dSDimitry Andric // callsite metadata and the callsite metadata on the call where it was 840bdd1243dSDimitry Andric // inlined. 841bdd1243dSDimitry Andric ClonedCallsiteMD = MDNode::concatenate(OrigCallsiteMD, InlinedCallsiteMD); 842bdd1243dSDimitry Andric ClonedCall->setMetadata(LLVMContext::MD_callsite, ClonedCallsiteMD); 843bdd1243dSDimitry Andric } 844bdd1243dSDimitry Andric 845bdd1243dSDimitry Andric // Update any memprof metadata on the cloned call. 846bdd1243dSDimitry Andric MDNode *OrigMemProfMD = ClonedCall->getMetadata(LLVMContext::MD_memprof); 847bdd1243dSDimitry Andric if (!OrigMemProfMD) 848bdd1243dSDimitry Andric return; 849bdd1243dSDimitry Andric // We currently expect that allocations with memprof metadata also have 850bdd1243dSDimitry Andric // callsite metadata for the allocation's part of the context. 851bdd1243dSDimitry Andric assert(OrigCallsiteMD); 852bdd1243dSDimitry Andric 853bdd1243dSDimitry Andric // New call's MIB list. 854bdd1243dSDimitry Andric std::vector<Metadata *> NewMIBList; 855bdd1243dSDimitry Andric 856bdd1243dSDimitry Andric // For each MIB metadata, check if its call stack context starts with the 857bdd1243dSDimitry Andric // new clone's callsite metadata. If so, that MIB goes onto the cloned call in 858bdd1243dSDimitry Andric // the inlined body. If not, it stays on the out-of-line original call. 859bdd1243dSDimitry Andric for (auto &MIBOp : OrigMemProfMD->operands()) { 860bdd1243dSDimitry Andric MDNode *MIB = dyn_cast<MDNode>(MIBOp); 861bdd1243dSDimitry Andric // Stack is first operand of MIB. 862bdd1243dSDimitry Andric MDNode *StackMD = getMIBStackNode(MIB); 863bdd1243dSDimitry Andric assert(StackMD); 864bdd1243dSDimitry Andric // See if the new cloned callsite context matches this profiled context. 865bdd1243dSDimitry Andric if (haveCommonPrefix(StackMD, ClonedCallsiteMD)) 866bdd1243dSDimitry Andric // Add it to the cloned call's MIB list. 867bdd1243dSDimitry Andric NewMIBList.push_back(MIB); 868bdd1243dSDimitry Andric } 869bdd1243dSDimitry Andric if (NewMIBList.empty()) { 870bdd1243dSDimitry Andric removeMemProfMetadata(ClonedCall); 871bdd1243dSDimitry Andric removeCallsiteMetadata(ClonedCall); 872bdd1243dSDimitry Andric return; 873bdd1243dSDimitry Andric } 874bdd1243dSDimitry Andric if (NewMIBList.size() < OrigMemProfMD->getNumOperands()) 875bdd1243dSDimitry Andric updateMemprofMetadata(ClonedCall, NewMIBList); 876bdd1243dSDimitry Andric } 877bdd1243dSDimitry Andric 878bdd1243dSDimitry Andric // Update memprof related metadata (!memprof and !callsite) based on the 879bdd1243dSDimitry Andric // inlining of Callee into the callsite at CB. The updates include merging the 880bdd1243dSDimitry Andric // inlined callee's callsite metadata with that of the inlined call, 881bdd1243dSDimitry Andric // and moving the subset of any memprof contexts to the inlined callee 882bdd1243dSDimitry Andric // allocations if they match the new inlined call stack. 883bdd1243dSDimitry Andric static void 884bdd1243dSDimitry Andric propagateMemProfMetadata(Function *Callee, CallBase &CB, 885bdd1243dSDimitry Andric bool ContainsMemProfMetadata, 886bdd1243dSDimitry Andric const ValueMap<const Value *, WeakTrackingVH> &VMap) { 887bdd1243dSDimitry Andric MDNode *CallsiteMD = CB.getMetadata(LLVMContext::MD_callsite); 888bdd1243dSDimitry Andric // Only need to update if the inlined callsite had callsite metadata, or if 889bdd1243dSDimitry Andric // there was any memprof metadata inlined. 890bdd1243dSDimitry Andric if (!CallsiteMD && !ContainsMemProfMetadata) 891bdd1243dSDimitry Andric return; 892bdd1243dSDimitry Andric 893bdd1243dSDimitry Andric // Propagate metadata onto the cloned calls in the inlined callee. 894bdd1243dSDimitry Andric for (const auto &Entry : VMap) { 895bdd1243dSDimitry Andric // See if this is a call that has been inlined and remapped, and not 896bdd1243dSDimitry Andric // simplified away in the process. 897bdd1243dSDimitry Andric auto *OrigCall = dyn_cast_or_null<CallBase>(Entry.first); 898bdd1243dSDimitry Andric auto *ClonedCall = dyn_cast_or_null<CallBase>(Entry.second); 899bdd1243dSDimitry Andric if (!OrigCall || !ClonedCall) 900bdd1243dSDimitry Andric continue; 901bdd1243dSDimitry Andric // If the inlined callsite did not have any callsite metadata, then it isn't 902bdd1243dSDimitry Andric // involved in any profiled call contexts, and we can remove any memprof 903bdd1243dSDimitry Andric // metadata on the cloned call. 904bdd1243dSDimitry Andric if (!CallsiteMD) { 905bdd1243dSDimitry Andric removeMemProfMetadata(ClonedCall); 906bdd1243dSDimitry Andric removeCallsiteMetadata(ClonedCall); 907bdd1243dSDimitry Andric continue; 908bdd1243dSDimitry Andric } 909bdd1243dSDimitry Andric propagateMemProfHelper(OrigCall, ClonedCall, CallsiteMD); 910bdd1243dSDimitry Andric } 911bdd1243dSDimitry Andric } 912bdd1243dSDimitry Andric 913e8d8bef9SDimitry Andric /// When inlining a call site that has !llvm.mem.parallel_loop_access, 914e8d8bef9SDimitry Andric /// !llvm.access.group, !alias.scope or !noalias metadata, that metadata should 915e8d8bef9SDimitry Andric /// be propagated to all memory-accessing cloned instructions. 91623408297SDimitry Andric static void PropagateCallSiteMetadata(CallBase &CB, Function::iterator FStart, 91723408297SDimitry Andric Function::iterator FEnd) { 918e8d8bef9SDimitry Andric MDNode *MemParallelLoopAccess = 919e8d8bef9SDimitry Andric CB.getMetadata(LLVMContext::MD_mem_parallel_loop_access); 920e8d8bef9SDimitry Andric MDNode *AccessGroup = CB.getMetadata(LLVMContext::MD_access_group); 921e8d8bef9SDimitry Andric MDNode *AliasScope = CB.getMetadata(LLVMContext::MD_alias_scope); 922e8d8bef9SDimitry Andric MDNode *NoAlias = CB.getMetadata(LLVMContext::MD_noalias); 923e8d8bef9SDimitry Andric if (!MemParallelLoopAccess && !AccessGroup && !AliasScope && !NoAlias) 9240b57cec5SDimitry Andric return; 9250b57cec5SDimitry Andric 92623408297SDimitry Andric for (BasicBlock &BB : make_range(FStart, FEnd)) { 92723408297SDimitry Andric for (Instruction &I : BB) { 928e8d8bef9SDimitry Andric // This metadata is only relevant for instructions that access memory. 92923408297SDimitry Andric if (!I.mayReadOrWriteMemory()) 930e8d8bef9SDimitry Andric continue; 931e8d8bef9SDimitry Andric 932e8d8bef9SDimitry Andric if (MemParallelLoopAccess) { 933e8d8bef9SDimitry Andric // TODO: This probably should not overwrite MemParalleLoopAccess. 934e8d8bef9SDimitry Andric MemParallelLoopAccess = MDNode::concatenate( 93523408297SDimitry Andric I.getMetadata(LLVMContext::MD_mem_parallel_loop_access), 936e8d8bef9SDimitry Andric MemParallelLoopAccess); 93723408297SDimitry Andric I.setMetadata(LLVMContext::MD_mem_parallel_loop_access, 938e8d8bef9SDimitry Andric MemParallelLoopAccess); 939e8d8bef9SDimitry Andric } 940e8d8bef9SDimitry Andric 941e8d8bef9SDimitry Andric if (AccessGroup) 94223408297SDimitry Andric I.setMetadata(LLVMContext::MD_access_group, uniteAccessGroups( 94323408297SDimitry Andric I.getMetadata(LLVMContext::MD_access_group), AccessGroup)); 944e8d8bef9SDimitry Andric 945e8d8bef9SDimitry Andric if (AliasScope) 94623408297SDimitry Andric I.setMetadata(LLVMContext::MD_alias_scope, MDNode::concatenate( 94723408297SDimitry Andric I.getMetadata(LLVMContext::MD_alias_scope), AliasScope)); 948e8d8bef9SDimitry Andric 949e8d8bef9SDimitry Andric if (NoAlias) 95023408297SDimitry Andric I.setMetadata(LLVMContext::MD_noalias, MDNode::concatenate( 95123408297SDimitry Andric I.getMetadata(LLVMContext::MD_noalias), NoAlias)); 95223408297SDimitry Andric } 9530b57cec5SDimitry Andric } 9540b57cec5SDimitry Andric } 9550b57cec5SDimitry Andric 956972a253aSDimitry Andric /// Bundle operands of the inlined function must be added to inlined call sites. 957972a253aSDimitry Andric static void PropagateOperandBundles(Function::iterator InlinedBB, 958972a253aSDimitry Andric Instruction *CallSiteEHPad) { 959972a253aSDimitry Andric for (Instruction &II : llvm::make_early_inc_range(*InlinedBB)) { 960972a253aSDimitry Andric CallBase *I = dyn_cast<CallBase>(&II); 961972a253aSDimitry Andric if (!I) 962972a253aSDimitry Andric continue; 963972a253aSDimitry Andric // Skip call sites which already have a "funclet" bundle. 964972a253aSDimitry Andric if (I->getOperandBundle(LLVMContext::OB_funclet)) 965972a253aSDimitry Andric continue; 966972a253aSDimitry Andric // Skip call sites which are nounwind intrinsics (as long as they don't 967972a253aSDimitry Andric // lower into regular function calls in the course of IR transformations). 968972a253aSDimitry Andric auto *CalledFn = 969972a253aSDimitry Andric dyn_cast<Function>(I->getCalledOperand()->stripPointerCasts()); 970972a253aSDimitry Andric if (CalledFn && CalledFn->isIntrinsic() && I->doesNotThrow() && 971972a253aSDimitry Andric !IntrinsicInst::mayLowerToFunctionCall(CalledFn->getIntrinsicID())) 972972a253aSDimitry Andric continue; 973972a253aSDimitry Andric 974972a253aSDimitry Andric SmallVector<OperandBundleDef, 1> OpBundles; 975972a253aSDimitry Andric I->getOperandBundlesAsDefs(OpBundles); 976972a253aSDimitry Andric OpBundles.emplace_back("funclet", CallSiteEHPad); 977972a253aSDimitry Andric 9780fca6ea1SDimitry Andric Instruction *NewInst = CallBase::Create(I, OpBundles, I->getIterator()); 979972a253aSDimitry Andric NewInst->takeName(I); 980972a253aSDimitry Andric I->replaceAllUsesWith(NewInst); 981972a253aSDimitry Andric I->eraseFromParent(); 982972a253aSDimitry Andric } 983972a253aSDimitry Andric } 984972a253aSDimitry Andric 985349cc55cSDimitry Andric namespace { 986e8d8bef9SDimitry Andric /// Utility for cloning !noalias and !alias.scope metadata. When a code region 987e8d8bef9SDimitry Andric /// using scoped alias metadata is inlined, the aliasing relationships may not 988e8d8bef9SDimitry Andric /// hold between the two version. It is necessary to create a deep clone of the 989e8d8bef9SDimitry Andric /// metadata, putting the two versions in separate scope domains. 990e8d8bef9SDimitry Andric class ScopedAliasMetadataDeepCloner { 991e8d8bef9SDimitry Andric using MetadataMap = DenseMap<const MDNode *, TrackingMDNodeRef>; 9920b57cec5SDimitry Andric SetVector<const MDNode *> MD; 993e8d8bef9SDimitry Andric MetadataMap MDMap; 994e8d8bef9SDimitry Andric void addRecursiveMetadataUses(); 9950b57cec5SDimitry Andric 996e8d8bef9SDimitry Andric public: 997e8d8bef9SDimitry Andric ScopedAliasMetadataDeepCloner(const Function *F); 9980b57cec5SDimitry Andric 999e8d8bef9SDimitry Andric /// Create a new clone of the scoped alias metadata, which will be used by 1000e8d8bef9SDimitry Andric /// subsequent remap() calls. 1001e8d8bef9SDimitry Andric void clone(); 1002e8d8bef9SDimitry Andric 100323408297SDimitry Andric /// Remap instructions in the given range from the original to the cloned 1004e8d8bef9SDimitry Andric /// metadata. 100523408297SDimitry Andric void remap(Function::iterator FStart, Function::iterator FEnd); 1006e8d8bef9SDimitry Andric }; 1007349cc55cSDimitry Andric } // namespace 1008e8d8bef9SDimitry Andric 1009e8d8bef9SDimitry Andric ScopedAliasMetadataDeepCloner::ScopedAliasMetadataDeepCloner( 1010e8d8bef9SDimitry Andric const Function *F) { 1011e8d8bef9SDimitry Andric for (const BasicBlock &BB : *F) { 1012e8d8bef9SDimitry Andric for (const Instruction &I : BB) { 1013e8d8bef9SDimitry Andric if (const MDNode *M = I.getMetadata(LLVMContext::MD_alias_scope)) 10140b57cec5SDimitry Andric MD.insert(M); 1015e8d8bef9SDimitry Andric if (const MDNode *M = I.getMetadata(LLVMContext::MD_noalias)) 10160b57cec5SDimitry Andric MD.insert(M); 1017e8d8bef9SDimitry Andric 1018e8d8bef9SDimitry Andric // We also need to clone the metadata in noalias intrinsics. 1019e8d8bef9SDimitry Andric if (const auto *Decl = dyn_cast<NoAliasScopeDeclInst>(&I)) 1020e8d8bef9SDimitry Andric MD.insert(Decl->getScopeList()); 1021e8d8bef9SDimitry Andric } 1022e8d8bef9SDimitry Andric } 1023e8d8bef9SDimitry Andric addRecursiveMetadataUses(); 10240b57cec5SDimitry Andric } 10250b57cec5SDimitry Andric 1026e8d8bef9SDimitry Andric void ScopedAliasMetadataDeepCloner::addRecursiveMetadataUses() { 10270b57cec5SDimitry Andric SmallVector<const Metadata *, 16> Queue(MD.begin(), MD.end()); 10280b57cec5SDimitry Andric while (!Queue.empty()) { 10290b57cec5SDimitry Andric const MDNode *M = cast<MDNode>(Queue.pop_back_val()); 1030e8d8bef9SDimitry Andric for (const Metadata *Op : M->operands()) 1031e8d8bef9SDimitry Andric if (const MDNode *OpMD = dyn_cast<MDNode>(Op)) 1032e8d8bef9SDimitry Andric if (MD.insert(OpMD)) 1033e8d8bef9SDimitry Andric Queue.push_back(OpMD); 1034e8d8bef9SDimitry Andric } 10350b57cec5SDimitry Andric } 10360b57cec5SDimitry Andric 1037e8d8bef9SDimitry Andric void ScopedAliasMetadataDeepCloner::clone() { 1038e8d8bef9SDimitry Andric assert(MDMap.empty() && "clone() already called ?"); 1039e8d8bef9SDimitry Andric 10400b57cec5SDimitry Andric SmallVector<TempMDTuple, 16> DummyNodes; 10410b57cec5SDimitry Andric for (const MDNode *I : MD) { 1042bdd1243dSDimitry Andric DummyNodes.push_back(MDTuple::getTemporary(I->getContext(), std::nullopt)); 10430b57cec5SDimitry Andric MDMap[I].reset(DummyNodes.back().get()); 10440b57cec5SDimitry Andric } 10450b57cec5SDimitry Andric 10460b57cec5SDimitry Andric // Create new metadata nodes to replace the dummy nodes, replacing old 10470b57cec5SDimitry Andric // metadata references with either a dummy node or an already-created new 10480b57cec5SDimitry Andric // node. 10490b57cec5SDimitry Andric SmallVector<Metadata *, 4> NewOps; 1050e8d8bef9SDimitry Andric for (const MDNode *I : MD) { 1051e8d8bef9SDimitry Andric for (const Metadata *Op : I->operands()) { 1052e8d8bef9SDimitry Andric if (const MDNode *M = dyn_cast<MDNode>(Op)) 10530b57cec5SDimitry Andric NewOps.push_back(MDMap[M]); 10540b57cec5SDimitry Andric else 1055e8d8bef9SDimitry Andric NewOps.push_back(const_cast<Metadata *>(Op)); 10560b57cec5SDimitry Andric } 10570b57cec5SDimitry Andric 1058e8d8bef9SDimitry Andric MDNode *NewM = MDNode::get(I->getContext(), NewOps); 10590b57cec5SDimitry Andric MDTuple *TempM = cast<MDTuple>(MDMap[I]); 10600b57cec5SDimitry Andric assert(TempM->isTemporary() && "Expected temporary node"); 10610b57cec5SDimitry Andric 10620b57cec5SDimitry Andric TempM->replaceAllUsesWith(NewM); 1063e8d8bef9SDimitry Andric NewOps.clear(); 1064e8d8bef9SDimitry Andric } 10650b57cec5SDimitry Andric } 10660b57cec5SDimitry Andric 106723408297SDimitry Andric void ScopedAliasMetadataDeepCloner::remap(Function::iterator FStart, 106823408297SDimitry Andric Function::iterator FEnd) { 1069e8d8bef9SDimitry Andric if (MDMap.empty()) 1070e8d8bef9SDimitry Andric return; // Nothing to do. 1071e8d8bef9SDimitry Andric 107223408297SDimitry Andric for (BasicBlock &BB : make_range(FStart, FEnd)) { 107323408297SDimitry Andric for (Instruction &I : BB) { 107423408297SDimitry Andric // TODO: The null checks for the MDMap.lookup() results should no longer 107523408297SDimitry Andric // be necessary. 107623408297SDimitry Andric if (MDNode *M = I.getMetadata(LLVMContext::MD_alias_scope)) 1077d409305fSDimitry Andric if (MDNode *MNew = MDMap.lookup(M)) 107823408297SDimitry Andric I.setMetadata(LLVMContext::MD_alias_scope, MNew); 10790b57cec5SDimitry Andric 108023408297SDimitry Andric if (MDNode *M = I.getMetadata(LLVMContext::MD_noalias)) 1081d409305fSDimitry Andric if (MDNode *MNew = MDMap.lookup(M)) 108223408297SDimitry Andric I.setMetadata(LLVMContext::MD_noalias, MNew); 1083e8d8bef9SDimitry Andric 108423408297SDimitry Andric if (auto *Decl = dyn_cast<NoAliasScopeDeclInst>(&I)) 1085d409305fSDimitry Andric if (MDNode *MNew = MDMap.lookup(Decl->getScopeList())) 1086d409305fSDimitry Andric Decl->setScopeList(MNew); 10870b57cec5SDimitry Andric } 10880b57cec5SDimitry Andric } 108923408297SDimitry Andric } 10900b57cec5SDimitry Andric 10910b57cec5SDimitry Andric /// If the inlined function has noalias arguments, 10920b57cec5SDimitry Andric /// then add new alias scopes for each noalias argument, tag the mapped noalias 10930b57cec5SDimitry Andric /// parameters with noalias metadata specifying the new scope, and tag all 10940b57cec5SDimitry Andric /// non-derived loads, stores and memory intrinsics with the new alias scopes. 10955ffd83dbSDimitry Andric static void AddAliasScopeMetadata(CallBase &CB, ValueToValueMapTy &VMap, 1096fe6060f1SDimitry Andric const DataLayout &DL, AAResults *CalleeAAR, 1097fe6060f1SDimitry Andric ClonedCodeInfo &InlinedFunctionInfo) { 10980b57cec5SDimitry Andric if (!EnableNoAliasConversion) 10990b57cec5SDimitry Andric return; 11000b57cec5SDimitry Andric 11015ffd83dbSDimitry Andric const Function *CalledFunc = CB.getCalledFunction(); 11020b57cec5SDimitry Andric SmallVector<const Argument *, 4> NoAliasArgs; 11030b57cec5SDimitry Andric 11040b57cec5SDimitry Andric for (const Argument &Arg : CalledFunc->args()) 11055ffd83dbSDimitry Andric if (CB.paramHasAttr(Arg.getArgNo(), Attribute::NoAlias) && !Arg.use_empty()) 11060b57cec5SDimitry Andric NoAliasArgs.push_back(&Arg); 11070b57cec5SDimitry Andric 11080b57cec5SDimitry Andric if (NoAliasArgs.empty()) 11090b57cec5SDimitry Andric return; 11100b57cec5SDimitry Andric 11110b57cec5SDimitry Andric // To do a good job, if a noalias variable is captured, we need to know if 11120b57cec5SDimitry Andric // the capture point dominates the particular use we're considering. 11130b57cec5SDimitry Andric DominatorTree DT; 11140b57cec5SDimitry Andric DT.recalculate(const_cast<Function&>(*CalledFunc)); 11150b57cec5SDimitry Andric 11160b57cec5SDimitry Andric // noalias indicates that pointer values based on the argument do not alias 11170b57cec5SDimitry Andric // pointer values which are not based on it. So we add a new "scope" for each 11180b57cec5SDimitry Andric // noalias function argument. Accesses using pointers based on that argument 11190b57cec5SDimitry Andric // become part of that alias scope, accesses using pointers not based on that 11200b57cec5SDimitry Andric // argument are tagged as noalias with that scope. 11210b57cec5SDimitry Andric 11220b57cec5SDimitry Andric DenseMap<const Argument *, MDNode *> NewScopes; 11230b57cec5SDimitry Andric MDBuilder MDB(CalledFunc->getContext()); 11240b57cec5SDimitry Andric 11250b57cec5SDimitry Andric // Create a new scope domain for this function. 11260b57cec5SDimitry Andric MDNode *NewDomain = 11270b57cec5SDimitry Andric MDB.createAnonymousAliasScopeDomain(CalledFunc->getName()); 11280b57cec5SDimitry Andric for (unsigned i = 0, e = NoAliasArgs.size(); i != e; ++i) { 11290b57cec5SDimitry Andric const Argument *A = NoAliasArgs[i]; 11300b57cec5SDimitry Andric 11315ffd83dbSDimitry Andric std::string Name = std::string(CalledFunc->getName()); 11320b57cec5SDimitry Andric if (A->hasName()) { 11330b57cec5SDimitry Andric Name += ": %"; 11340b57cec5SDimitry Andric Name += A->getName(); 11350b57cec5SDimitry Andric } else { 11360b57cec5SDimitry Andric Name += ": argument "; 11370b57cec5SDimitry Andric Name += utostr(i); 11380b57cec5SDimitry Andric } 11390b57cec5SDimitry Andric 11400b57cec5SDimitry Andric // Note: We always create a new anonymous root here. This is true regardless 11410b57cec5SDimitry Andric // of the linkage of the callee because the aliasing "scope" is not just a 11420b57cec5SDimitry Andric // property of the callee, but also all control dependencies in the caller. 11430b57cec5SDimitry Andric MDNode *NewScope = MDB.createAnonymousAliasScope(NewDomain, Name); 11440b57cec5SDimitry Andric NewScopes.insert(std::make_pair(A, NewScope)); 1145e8d8bef9SDimitry Andric 1146e8d8bef9SDimitry Andric if (UseNoAliasIntrinsic) { 1147e8d8bef9SDimitry Andric // Introduce a llvm.experimental.noalias.scope.decl for the noalias 1148e8d8bef9SDimitry Andric // argument. 1149e8d8bef9SDimitry Andric MDNode *AScopeList = MDNode::get(CalledFunc->getContext(), NewScope); 1150e8d8bef9SDimitry Andric auto *NoAliasDecl = 1151e8d8bef9SDimitry Andric IRBuilder<>(&CB).CreateNoAliasScopeDeclaration(AScopeList); 1152e8d8bef9SDimitry Andric // Ignore the result for now. The result will be used when the 1153e8d8bef9SDimitry Andric // llvm.noalias intrinsic is introduced. 1154e8d8bef9SDimitry Andric (void)NoAliasDecl; 1155e8d8bef9SDimitry Andric } 11560b57cec5SDimitry Andric } 11570b57cec5SDimitry Andric 11580b57cec5SDimitry Andric // Iterate over all new instructions in the map; for all memory-access 11590b57cec5SDimitry Andric // instructions, add the alias scope metadata. 11600b57cec5SDimitry Andric for (ValueToValueMapTy::iterator VMI = VMap.begin(), VMIE = VMap.end(); 11610b57cec5SDimitry Andric VMI != VMIE; ++VMI) { 11620b57cec5SDimitry Andric if (const Instruction *I = dyn_cast<Instruction>(VMI->first)) { 11630b57cec5SDimitry Andric if (!VMI->second) 11640b57cec5SDimitry Andric continue; 11650b57cec5SDimitry Andric 11660b57cec5SDimitry Andric Instruction *NI = dyn_cast<Instruction>(VMI->second); 1167fe6060f1SDimitry Andric if (!NI || InlinedFunctionInfo.isSimplified(I, NI)) 11680b57cec5SDimitry Andric continue; 11690b57cec5SDimitry Andric 11700b57cec5SDimitry Andric bool IsArgMemOnlyCall = false, IsFuncCall = false; 11710b57cec5SDimitry Andric SmallVector<const Value *, 2> PtrArgs; 11720b57cec5SDimitry Andric 11730b57cec5SDimitry Andric if (const LoadInst *LI = dyn_cast<LoadInst>(I)) 11740b57cec5SDimitry Andric PtrArgs.push_back(LI->getPointerOperand()); 11750b57cec5SDimitry Andric else if (const StoreInst *SI = dyn_cast<StoreInst>(I)) 11760b57cec5SDimitry Andric PtrArgs.push_back(SI->getPointerOperand()); 11770b57cec5SDimitry Andric else if (const VAArgInst *VAAI = dyn_cast<VAArgInst>(I)) 11780b57cec5SDimitry Andric PtrArgs.push_back(VAAI->getPointerOperand()); 11790b57cec5SDimitry Andric else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I)) 11800b57cec5SDimitry Andric PtrArgs.push_back(CXI->getPointerOperand()); 11810b57cec5SDimitry Andric else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I)) 11820b57cec5SDimitry Andric PtrArgs.push_back(RMWI->getPointerOperand()); 11830b57cec5SDimitry Andric else if (const auto *Call = dyn_cast<CallBase>(I)) { 11840b57cec5SDimitry Andric // If we know that the call does not access memory, then we'll still 11850b57cec5SDimitry Andric // know that about the inlined clone of this call site, and we don't 11860b57cec5SDimitry Andric // need to add metadata. 11870b57cec5SDimitry Andric if (Call->doesNotAccessMemory()) 11880b57cec5SDimitry Andric continue; 11890b57cec5SDimitry Andric 11900b57cec5SDimitry Andric IsFuncCall = true; 11910b57cec5SDimitry Andric if (CalleeAAR) { 1192bdd1243dSDimitry Andric MemoryEffects ME = CalleeAAR->getMemoryEffects(Call); 1193fe6060f1SDimitry Andric 1194fe6060f1SDimitry Andric // We'll retain this knowledge without additional metadata. 1195bdd1243dSDimitry Andric if (ME.onlyAccessesInaccessibleMem()) 1196fe6060f1SDimitry Andric continue; 1197fe6060f1SDimitry Andric 1198bdd1243dSDimitry Andric if (ME.onlyAccessesArgPointees()) 11990b57cec5SDimitry Andric IsArgMemOnlyCall = true; 12000b57cec5SDimitry Andric } 12010b57cec5SDimitry Andric 12020b57cec5SDimitry Andric for (Value *Arg : Call->args()) { 120381ad6265SDimitry Andric // Only care about pointer arguments. If a noalias argument is 120481ad6265SDimitry Andric // accessed through a non-pointer argument, it must be captured 120581ad6265SDimitry Andric // first (e.g. via ptrtoint), and we protect against captures below. 120681ad6265SDimitry Andric if (!Arg->getType()->isPointerTy()) 12070b57cec5SDimitry Andric continue; 12080b57cec5SDimitry Andric 12090b57cec5SDimitry Andric PtrArgs.push_back(Arg); 12100b57cec5SDimitry Andric } 12110b57cec5SDimitry Andric } 12120b57cec5SDimitry Andric 12130b57cec5SDimitry Andric // If we found no pointers, then this instruction is not suitable for 12140b57cec5SDimitry Andric // pairing with an instruction to receive aliasing metadata. 12150b57cec5SDimitry Andric // However, if this is a call, this we might just alias with none of the 12160b57cec5SDimitry Andric // noalias arguments. 12170b57cec5SDimitry Andric if (PtrArgs.empty() && !IsFuncCall) 12180b57cec5SDimitry Andric continue; 12190b57cec5SDimitry Andric 12200b57cec5SDimitry Andric // It is possible that there is only one underlying object, but you 12210b57cec5SDimitry Andric // need to go through several PHIs to see it, and thus could be 12220b57cec5SDimitry Andric // repeated in the Objects list. 12230b57cec5SDimitry Andric SmallPtrSet<const Value *, 4> ObjSet; 12240b57cec5SDimitry Andric SmallVector<Metadata *, 4> Scopes, NoAliases; 12250b57cec5SDimitry Andric 12260b57cec5SDimitry Andric for (const Value *V : PtrArgs) { 12270b57cec5SDimitry Andric SmallVector<const Value *, 4> Objects; 1228e8d8bef9SDimitry Andric getUnderlyingObjects(V, Objects, /* LI = */ nullptr); 12290b57cec5SDimitry Andric 12300b57cec5SDimitry Andric for (const Value *O : Objects) 12310b57cec5SDimitry Andric ObjSet.insert(O); 12320b57cec5SDimitry Andric } 12330b57cec5SDimitry Andric 12340b57cec5SDimitry Andric // Figure out if we're derived from anything that is not a noalias 12350b57cec5SDimitry Andric // argument. 123681ad6265SDimitry Andric bool RequiresNoCaptureBefore = false, UsesAliasingPtr = false, 123781ad6265SDimitry Andric UsesUnknownObject = false; 12380b57cec5SDimitry Andric for (const Value *V : ObjSet) { 12390b57cec5SDimitry Andric // Is this value a constant that cannot be derived from any pointer 12400b57cec5SDimitry Andric // value (we need to exclude constant expressions, for example, that 12410b57cec5SDimitry Andric // are formed from arithmetic on global symbols). 12420b57cec5SDimitry Andric bool IsNonPtrConst = isa<ConstantInt>(V) || isa<ConstantFP>(V) || 12430b57cec5SDimitry Andric isa<ConstantPointerNull>(V) || 12440b57cec5SDimitry Andric isa<ConstantDataVector>(V) || isa<UndefValue>(V); 12450b57cec5SDimitry Andric if (IsNonPtrConst) 12460b57cec5SDimitry Andric continue; 12470b57cec5SDimitry Andric 12480b57cec5SDimitry Andric // If this is anything other than a noalias argument, then we cannot 12490b57cec5SDimitry Andric // completely describe the aliasing properties using alias.scope 12500b57cec5SDimitry Andric // metadata (and, thus, won't add any). 12510b57cec5SDimitry Andric if (const Argument *A = dyn_cast<Argument>(V)) { 12525ffd83dbSDimitry Andric if (!CB.paramHasAttr(A->getArgNo(), Attribute::NoAlias)) 12530b57cec5SDimitry Andric UsesAliasingPtr = true; 12540b57cec5SDimitry Andric } else { 12550b57cec5SDimitry Andric UsesAliasingPtr = true; 12560b57cec5SDimitry Andric } 12570b57cec5SDimitry Andric 125881ad6265SDimitry Andric if (isEscapeSource(V)) { 125981ad6265SDimitry Andric // An escape source can only alias with a noalias argument if it has 126081ad6265SDimitry Andric // been captured beforehand. 126181ad6265SDimitry Andric RequiresNoCaptureBefore = true; 126281ad6265SDimitry Andric } else if (!isa<Argument>(V) && !isIdentifiedObject(V)) { 126381ad6265SDimitry Andric // If this is neither an escape source, nor some identified object 126481ad6265SDimitry Andric // (which cannot directly alias a noalias argument), nor some other 126581ad6265SDimitry Andric // argument (which, by definition, also cannot alias a noalias 126681ad6265SDimitry Andric // argument), conservatively do not make any assumptions. 126781ad6265SDimitry Andric UsesUnknownObject = true; 12680b57cec5SDimitry Andric } 126981ad6265SDimitry Andric } 127081ad6265SDimitry Andric 127181ad6265SDimitry Andric // Nothing we can do if the used underlying object cannot be reliably 127281ad6265SDimitry Andric // determined. 127381ad6265SDimitry Andric if (UsesUnknownObject) 127481ad6265SDimitry Andric continue; 12750b57cec5SDimitry Andric 12760b57cec5SDimitry Andric // A function call can always get captured noalias pointers (via other 12770b57cec5SDimitry Andric // parameters, globals, etc.). 12780b57cec5SDimitry Andric if (IsFuncCall && !IsArgMemOnlyCall) 127981ad6265SDimitry Andric RequiresNoCaptureBefore = true; 12800b57cec5SDimitry Andric 12810b57cec5SDimitry Andric // First, we want to figure out all of the sets with which we definitely 12820b57cec5SDimitry Andric // don't alias. Iterate over all noalias set, and add those for which: 12830b57cec5SDimitry Andric // 1. The noalias argument is not in the set of objects from which we 12840b57cec5SDimitry Andric // definitely derive. 12850b57cec5SDimitry Andric // 2. The noalias argument has not yet been captured. 12860b57cec5SDimitry Andric // An arbitrary function that might load pointers could see captured 12870b57cec5SDimitry Andric // noalias arguments via other noalias arguments or globals, and so we 12880b57cec5SDimitry Andric // must always check for prior capture. 12890b57cec5SDimitry Andric for (const Argument *A : NoAliasArgs) { 129081ad6265SDimitry Andric if (ObjSet.contains(A)) 129181ad6265SDimitry Andric continue; // May be based on a noalias argument. 129281ad6265SDimitry Andric 129381ad6265SDimitry Andric // It might be tempting to skip the PointerMayBeCapturedBefore check if 129481ad6265SDimitry Andric // A->hasNoCaptureAttr() is true, but this is incorrect because 129581ad6265SDimitry Andric // nocapture only guarantees that no copies outlive the function, not 12960b57cec5SDimitry Andric // that the value cannot be locally captured. 129781ad6265SDimitry Andric if (!RequiresNoCaptureBefore || 129881ad6265SDimitry Andric !PointerMayBeCapturedBefore(A, /* ReturnCaptures */ false, 129981ad6265SDimitry Andric /* StoreCaptures */ false, I, &DT)) 13000b57cec5SDimitry Andric NoAliases.push_back(NewScopes[A]); 13010b57cec5SDimitry Andric } 13020b57cec5SDimitry Andric 13030b57cec5SDimitry Andric if (!NoAliases.empty()) 13040b57cec5SDimitry Andric NI->setMetadata(LLVMContext::MD_noalias, 13050b57cec5SDimitry Andric MDNode::concatenate( 13060b57cec5SDimitry Andric NI->getMetadata(LLVMContext::MD_noalias), 13070b57cec5SDimitry Andric MDNode::get(CalledFunc->getContext(), NoAliases))); 13080b57cec5SDimitry Andric 13090b57cec5SDimitry Andric // Next, we want to figure out all of the sets to which we might belong. 13100b57cec5SDimitry Andric // We might belong to a set if the noalias argument is in the set of 13110b57cec5SDimitry Andric // underlying objects. If there is some non-noalias argument in our list 13120b57cec5SDimitry Andric // of underlying objects, then we cannot add a scope because the fact 13130b57cec5SDimitry Andric // that some access does not alias with any set of our noalias arguments 13140b57cec5SDimitry Andric // cannot itself guarantee that it does not alias with this access 13150b57cec5SDimitry Andric // (because there is some pointer of unknown origin involved and the 13160b57cec5SDimitry Andric // other access might also depend on this pointer). We also cannot add 13170b57cec5SDimitry Andric // scopes to arbitrary functions unless we know they don't access any 13180b57cec5SDimitry Andric // non-parameter pointer-values. 13190b57cec5SDimitry Andric bool CanAddScopes = !UsesAliasingPtr; 13200b57cec5SDimitry Andric if (CanAddScopes && IsFuncCall) 13210b57cec5SDimitry Andric CanAddScopes = IsArgMemOnlyCall; 13220b57cec5SDimitry Andric 13230b57cec5SDimitry Andric if (CanAddScopes) 13240b57cec5SDimitry Andric for (const Argument *A : NoAliasArgs) { 13250b57cec5SDimitry Andric if (ObjSet.count(A)) 13260b57cec5SDimitry Andric Scopes.push_back(NewScopes[A]); 13270b57cec5SDimitry Andric } 13280b57cec5SDimitry Andric 13290b57cec5SDimitry Andric if (!Scopes.empty()) 13300b57cec5SDimitry Andric NI->setMetadata( 13310b57cec5SDimitry Andric LLVMContext::MD_alias_scope, 13320b57cec5SDimitry Andric MDNode::concatenate(NI->getMetadata(LLVMContext::MD_alias_scope), 13330b57cec5SDimitry Andric MDNode::get(CalledFunc->getContext(), Scopes))); 13340b57cec5SDimitry Andric } 13350b57cec5SDimitry Andric } 13360b57cec5SDimitry Andric } 13370b57cec5SDimitry Andric 13385f757f3fSDimitry Andric static bool MayContainThrowingOrExitingCallAfterCB(CallBase *Begin, 13395f757f3fSDimitry Andric ReturnInst *End) { 13405ffd83dbSDimitry Andric 13415ffd83dbSDimitry Andric assert(Begin->getParent() == End->getParent() && 13425ffd83dbSDimitry Andric "Expected to be in same basic block!"); 13435f757f3fSDimitry Andric auto BeginIt = Begin->getIterator(); 13445f757f3fSDimitry Andric assert(BeginIt != End->getIterator() && "Non-empty BB has empty iterator"); 1345349cc55cSDimitry Andric return !llvm::isGuaranteedToTransferExecutionToSuccessor( 13465f757f3fSDimitry Andric ++BeginIt, End->getIterator(), InlinerAttributeWindow + 1); 13475ffd83dbSDimitry Andric } 13485ffd83dbSDimitry Andric 13490fca6ea1SDimitry Andric // Add attributes from CB params and Fn attributes that can always be propagated 13500fca6ea1SDimitry Andric // to the corresponding argument / inner callbases. 13510fca6ea1SDimitry Andric static void AddParamAndFnBasicAttributes(const CallBase &CB, 13526e516c87SDimitry Andric ValueToValueMapTy &VMap, 13536e516c87SDimitry Andric ClonedCodeInfo &InlinedFunctionInfo) { 13540fca6ea1SDimitry Andric auto *CalledFunction = CB.getCalledFunction(); 13550fca6ea1SDimitry Andric auto &Context = CalledFunction->getContext(); 13560fca6ea1SDimitry Andric 13570fca6ea1SDimitry Andric // Collect valid attributes for all params. 13580fca6ea1SDimitry Andric SmallVector<AttrBuilder> ValidParamAttrs; 13590fca6ea1SDimitry Andric bool HasAttrToPropagate = false; 13600fca6ea1SDimitry Andric 13610fca6ea1SDimitry Andric for (unsigned I = 0, E = CB.arg_size(); I < E; ++I) { 13620fca6ea1SDimitry Andric ValidParamAttrs.emplace_back(AttrBuilder{CB.getContext()}); 13630fca6ea1SDimitry Andric // Access attributes can be propagated to any param with the same underlying 13640fca6ea1SDimitry Andric // object as the argument. 13650fca6ea1SDimitry Andric if (CB.paramHasAttr(I, Attribute::ReadNone)) 13660fca6ea1SDimitry Andric ValidParamAttrs.back().addAttribute(Attribute::ReadNone); 13670fca6ea1SDimitry Andric if (CB.paramHasAttr(I, Attribute::ReadOnly)) 13680fca6ea1SDimitry Andric ValidParamAttrs.back().addAttribute(Attribute::ReadOnly); 13690fca6ea1SDimitry Andric HasAttrToPropagate |= ValidParamAttrs.back().hasAttributes(); 13700fca6ea1SDimitry Andric } 13710fca6ea1SDimitry Andric 13720fca6ea1SDimitry Andric // Won't be able to propagate anything. 13730fca6ea1SDimitry Andric if (!HasAttrToPropagate) 13740fca6ea1SDimitry Andric return; 13750fca6ea1SDimitry Andric 13760fca6ea1SDimitry Andric for (BasicBlock &BB : *CalledFunction) { 13770fca6ea1SDimitry Andric for (Instruction &Ins : BB) { 13780fca6ea1SDimitry Andric const auto *InnerCB = dyn_cast<CallBase>(&Ins); 13790fca6ea1SDimitry Andric if (!InnerCB) 13800fca6ea1SDimitry Andric continue; 13810fca6ea1SDimitry Andric auto *NewInnerCB = dyn_cast_or_null<CallBase>(VMap.lookup(InnerCB)); 13820fca6ea1SDimitry Andric if (!NewInnerCB) 13830fca6ea1SDimitry Andric continue; 13846e516c87SDimitry Andric // The InnerCB might have be simplified during the inlining 13856e516c87SDimitry Andric // process which can make propagation incorrect. 13866e516c87SDimitry Andric if (InlinedFunctionInfo.isSimplified(InnerCB, NewInnerCB)) 13876e516c87SDimitry Andric continue; 13886e516c87SDimitry Andric 13890fca6ea1SDimitry Andric AttributeList AL = NewInnerCB->getAttributes(); 13900fca6ea1SDimitry Andric for (unsigned I = 0, E = InnerCB->arg_size(); I < E; ++I) { 13910fca6ea1SDimitry Andric // Check if the underlying value for the parameter is an argument. 13920fca6ea1SDimitry Andric const Value *UnderlyingV = 13930fca6ea1SDimitry Andric getUnderlyingObject(InnerCB->getArgOperand(I)); 13940fca6ea1SDimitry Andric const Argument *Arg = dyn_cast<Argument>(UnderlyingV); 13950fca6ea1SDimitry Andric if (!Arg) 13960fca6ea1SDimitry Andric continue; 13970fca6ea1SDimitry Andric 1398*d686ce93SDimitry Andric if (NewInnerCB->paramHasAttr(I, Attribute::ByVal)) 13990fca6ea1SDimitry Andric // It's unsound to propagate memory attributes to byval arguments. 14000fca6ea1SDimitry Andric // Even if CalledFunction doesn't e.g. write to the argument, 14010fca6ea1SDimitry Andric // the call to NewInnerCB may write to its by-value copy. 14020fca6ea1SDimitry Andric continue; 14030fca6ea1SDimitry Andric 14040fca6ea1SDimitry Andric unsigned ArgNo = Arg->getArgNo(); 14050fca6ea1SDimitry Andric // If so, propagate its access attributes. 14060fca6ea1SDimitry Andric AL = AL.addParamAttributes(Context, I, ValidParamAttrs[ArgNo]); 14070fca6ea1SDimitry Andric // We can have conflicting attributes from the inner callsite and 14080fca6ea1SDimitry Andric // to-be-inlined callsite. In that case, choose the most 14090fca6ea1SDimitry Andric // restrictive. 14100fca6ea1SDimitry Andric 14110fca6ea1SDimitry Andric // readonly + writeonly means we can never deref so make readnone. 14120fca6ea1SDimitry Andric if (AL.hasParamAttr(I, Attribute::ReadOnly) && 14130fca6ea1SDimitry Andric AL.hasParamAttr(I, Attribute::WriteOnly)) 14140fca6ea1SDimitry Andric AL = AL.addParamAttribute(Context, I, Attribute::ReadNone); 14150fca6ea1SDimitry Andric 14160fca6ea1SDimitry Andric // If have readnone, need to clear readonly/writeonly 14170fca6ea1SDimitry Andric if (AL.hasParamAttr(I, Attribute::ReadNone)) { 14180fca6ea1SDimitry Andric AL = AL.removeParamAttribute(Context, I, Attribute::ReadOnly); 14190fca6ea1SDimitry Andric AL = AL.removeParamAttribute(Context, I, Attribute::WriteOnly); 14200fca6ea1SDimitry Andric } 14210fca6ea1SDimitry Andric 14220fca6ea1SDimitry Andric // Writable cannot exist in conjunction w/ readonly/readnone 14230fca6ea1SDimitry Andric if (AL.hasParamAttr(I, Attribute::ReadOnly) || 14240fca6ea1SDimitry Andric AL.hasParamAttr(I, Attribute::ReadNone)) 14250fca6ea1SDimitry Andric AL = AL.removeParamAttribute(Context, I, Attribute::Writable); 14260fca6ea1SDimitry Andric } 14270fca6ea1SDimitry Andric NewInnerCB->setAttributes(AL); 14280fca6ea1SDimitry Andric } 14290fca6ea1SDimitry Andric } 14300fca6ea1SDimitry Andric } 14310fca6ea1SDimitry Andric 14325ffd83dbSDimitry Andric // Only allow these white listed attributes to be propagated back to the 14335ffd83dbSDimitry Andric // callee. This is because other attributes may only be valid on the call 14345ffd83dbSDimitry Andric // itself, i.e. attributes such as signext and zeroext. 14355f757f3fSDimitry Andric 14365f757f3fSDimitry Andric // Attributes that are always okay to propagate as if they are violated its 14375f757f3fSDimitry Andric // immediate UB. 14385f757f3fSDimitry Andric static AttrBuilder IdentifyValidUBGeneratingAttributes(CallBase &CB) { 14395f757f3fSDimitry Andric AttrBuilder Valid(CB.getContext()); 14405f757f3fSDimitry Andric if (auto DerefBytes = CB.getRetDereferenceableBytes()) 14415ffd83dbSDimitry Andric Valid.addDereferenceableAttr(DerefBytes); 14425f757f3fSDimitry Andric if (auto DerefOrNullBytes = CB.getRetDereferenceableOrNullBytes()) 14435ffd83dbSDimitry Andric Valid.addDereferenceableOrNullAttr(DerefOrNullBytes); 14445f757f3fSDimitry Andric if (CB.hasRetAttr(Attribute::NoAlias)) 14455ffd83dbSDimitry Andric Valid.addAttribute(Attribute::NoAlias); 14465f757f3fSDimitry Andric if (CB.hasRetAttr(Attribute::NoUndef)) 14475f757f3fSDimitry Andric Valid.addAttribute(Attribute::NoUndef); 14485f757f3fSDimitry Andric return Valid; 14495f757f3fSDimitry Andric } 14505f757f3fSDimitry Andric 14515f757f3fSDimitry Andric // Attributes that need additional checks as propagating them may change 14525f757f3fSDimitry Andric // behavior or cause new UB. 14535f757f3fSDimitry Andric static AttrBuilder IdentifyValidPoisonGeneratingAttributes(CallBase &CB) { 14545f757f3fSDimitry Andric AttrBuilder Valid(CB.getContext()); 14555f757f3fSDimitry Andric if (CB.hasRetAttr(Attribute::NonNull)) 14565ffd83dbSDimitry Andric Valid.addAttribute(Attribute::NonNull); 14575f757f3fSDimitry Andric if (CB.hasRetAttr(Attribute::Alignment)) 14585f757f3fSDimitry Andric Valid.addAlignmentAttr(CB.getRetAlign()); 14590fca6ea1SDimitry Andric if (std::optional<ConstantRange> Range = CB.getRange()) 14600fca6ea1SDimitry Andric Valid.addRangeAttr(*Range); 14615ffd83dbSDimitry Andric return Valid; 14625ffd83dbSDimitry Andric } 14635ffd83dbSDimitry Andric 14646e516c87SDimitry Andric static void AddReturnAttributes(CallBase &CB, ValueToValueMapTy &VMap, 14656e516c87SDimitry Andric ClonedCodeInfo &InlinedFunctionInfo) { 14665f757f3fSDimitry Andric AttrBuilder ValidUB = IdentifyValidUBGeneratingAttributes(CB); 14675f757f3fSDimitry Andric AttrBuilder ValidPG = IdentifyValidPoisonGeneratingAttributes(CB); 14685f757f3fSDimitry Andric if (!ValidUB.hasAttributes() && !ValidPG.hasAttributes()) 14695ffd83dbSDimitry Andric return; 14705ffd83dbSDimitry Andric auto *CalledFunction = CB.getCalledFunction(); 14715ffd83dbSDimitry Andric auto &Context = CalledFunction->getContext(); 14725ffd83dbSDimitry Andric 14735ffd83dbSDimitry Andric for (auto &BB : *CalledFunction) { 14745ffd83dbSDimitry Andric auto *RI = dyn_cast<ReturnInst>(BB.getTerminator()); 14755ffd83dbSDimitry Andric if (!RI || !isa<CallBase>(RI->getOperand(0))) 14765ffd83dbSDimitry Andric continue; 14775ffd83dbSDimitry Andric auto *RetVal = cast<CallBase>(RI->getOperand(0)); 14784824e7fdSDimitry Andric // Check that the cloned RetVal exists and is a call, otherwise we cannot 14794824e7fdSDimitry Andric // add the attributes on the cloned RetVal. Simplification during inlining 14804824e7fdSDimitry Andric // could have transformed the cloned instruction. 14815ffd83dbSDimitry Andric auto *NewRetVal = dyn_cast_or_null<CallBase>(VMap.lookup(RetVal)); 14825ffd83dbSDimitry Andric if (!NewRetVal) 14835ffd83dbSDimitry Andric continue; 14846e516c87SDimitry Andric 14856e516c87SDimitry Andric // The RetVal might have be simplified during the inlining 14866e516c87SDimitry Andric // process which can make propagation incorrect. 14876e516c87SDimitry Andric if (InlinedFunctionInfo.isSimplified(RetVal, NewRetVal)) 14886e516c87SDimitry Andric continue; 14895ffd83dbSDimitry Andric // Backward propagation of attributes to the returned value may be incorrect 14905ffd83dbSDimitry Andric // if it is control flow dependent. 14915ffd83dbSDimitry Andric // Consider: 14925ffd83dbSDimitry Andric // @callee { 14935ffd83dbSDimitry Andric // %rv = call @foo() 14945ffd83dbSDimitry Andric // %rv2 = call @bar() 14955ffd83dbSDimitry Andric // if (%rv2 != null) 14965ffd83dbSDimitry Andric // return %rv2 14975ffd83dbSDimitry Andric // if (%rv == null) 14985ffd83dbSDimitry Andric // exit() 14995ffd83dbSDimitry Andric // return %rv 15005ffd83dbSDimitry Andric // } 15015ffd83dbSDimitry Andric // caller() { 15025ffd83dbSDimitry Andric // %val = call nonnull @callee() 15035ffd83dbSDimitry Andric // } 15045ffd83dbSDimitry Andric // Here we cannot add the nonnull attribute on either foo or bar. So, we 15055ffd83dbSDimitry Andric // limit the check to both RetVal and RI are in the same basic block and 15065ffd83dbSDimitry Andric // there are no throwing/exiting instructions between these instructions. 15075ffd83dbSDimitry Andric if (RI->getParent() != RetVal->getParent() || 15085f757f3fSDimitry Andric MayContainThrowingOrExitingCallAfterCB(RetVal, RI)) 15095ffd83dbSDimitry Andric continue; 15105ffd83dbSDimitry Andric // Add to the existing attributes of NewRetVal, i.e. the cloned call 15115ffd83dbSDimitry Andric // instruction. 15125ffd83dbSDimitry Andric // NB! When we have the same attribute already existing on NewRetVal, but 15135ffd83dbSDimitry Andric // with a differing value, the AttributeList's merge API honours the already 15145ffd83dbSDimitry Andric // existing attribute value (i.e. attributes such as dereferenceable, 15155ffd83dbSDimitry Andric // dereferenceable_or_null etc). See AttrBuilder::merge for more details. 15165ffd83dbSDimitry Andric AttributeList AL = NewRetVal->getAttributes(); 15175f757f3fSDimitry Andric if (ValidUB.getDereferenceableBytes() < AL.getRetDereferenceableBytes()) 15185f757f3fSDimitry Andric ValidUB.removeAttribute(Attribute::Dereferenceable); 15195f757f3fSDimitry Andric if (ValidUB.getDereferenceableOrNullBytes() < 15205f757f3fSDimitry Andric AL.getRetDereferenceableOrNullBytes()) 15215f757f3fSDimitry Andric ValidUB.removeAttribute(Attribute::DereferenceableOrNull); 15225f757f3fSDimitry Andric AttributeList NewAL = AL.addRetAttributes(Context, ValidUB); 15235f757f3fSDimitry Andric // Attributes that may generate poison returns are a bit tricky. If we 15245f757f3fSDimitry Andric // propagate them, other uses of the callsite might have their behavior 15255f757f3fSDimitry Andric // change or cause UB (if they have noundef) b.c of the new potential 15265f757f3fSDimitry Andric // poison. 15275f757f3fSDimitry Andric // Take the following three cases: 15285f757f3fSDimitry Andric // 15295f757f3fSDimitry Andric // 1) 15305f757f3fSDimitry Andric // define nonnull ptr @foo() { 15315f757f3fSDimitry Andric // %p = call ptr @bar() 15325f757f3fSDimitry Andric // call void @use(ptr %p) willreturn nounwind 15335f757f3fSDimitry Andric // ret ptr %p 15345f757f3fSDimitry Andric // } 15355f757f3fSDimitry Andric // 15365f757f3fSDimitry Andric // 2) 15375f757f3fSDimitry Andric // define noundef nonnull ptr @foo() { 15385f757f3fSDimitry Andric // %p = call ptr @bar() 15395f757f3fSDimitry Andric // call void @use(ptr %p) willreturn nounwind 15405f757f3fSDimitry Andric // ret ptr %p 15415f757f3fSDimitry Andric // } 15425f757f3fSDimitry Andric // 15435f757f3fSDimitry Andric // 3) 15445f757f3fSDimitry Andric // define nonnull ptr @foo() { 15455f757f3fSDimitry Andric // %p = call noundef ptr @bar() 15465f757f3fSDimitry Andric // ret ptr %p 15475f757f3fSDimitry Andric // } 15485f757f3fSDimitry Andric // 15495f757f3fSDimitry Andric // In case 1, we can't propagate nonnull because poison value in @use may 15505f757f3fSDimitry Andric // change behavior or trigger UB. 15515f757f3fSDimitry Andric // In case 2, we don't need to be concerned about propagating nonnull, as 15525f757f3fSDimitry Andric // any new poison at @use will trigger UB anyways. 15535f757f3fSDimitry Andric // In case 3, we can never propagate nonnull because it may create UB due to 15545f757f3fSDimitry Andric // the noundef on @bar. 15555f757f3fSDimitry Andric if (ValidPG.getAlignment().valueOrOne() < AL.getRetAlignment().valueOrOne()) 15565f757f3fSDimitry Andric ValidPG.removeAttribute(Attribute::Alignment); 15575f757f3fSDimitry Andric if (ValidPG.hasAttributes()) { 15580fca6ea1SDimitry Andric Attribute CBRange = ValidPG.getAttribute(Attribute::Range); 15590fca6ea1SDimitry Andric if (CBRange.isValid()) { 15600fca6ea1SDimitry Andric Attribute NewRange = AL.getRetAttr(Attribute::Range); 15610fca6ea1SDimitry Andric if (NewRange.isValid()) { 15620fca6ea1SDimitry Andric ValidPG.addRangeAttr( 15630fca6ea1SDimitry Andric CBRange.getRange().intersectWith(NewRange.getRange())); 15640fca6ea1SDimitry Andric } 15650fca6ea1SDimitry Andric } 15665f757f3fSDimitry Andric // Three checks. 15675f757f3fSDimitry Andric // If the callsite has `noundef`, then a poison due to violating the 15685f757f3fSDimitry Andric // return attribute will create UB anyways so we can always propagate. 15695f757f3fSDimitry Andric // Otherwise, if the return value (callee to be inlined) has `noundef`, we 15705f757f3fSDimitry Andric // can't propagate as a new poison return will cause UB. 15715f757f3fSDimitry Andric // Finally, check if the return value has no uses whose behavior may 15725f757f3fSDimitry Andric // change/may cause UB if we potentially return poison. At the moment this 15735f757f3fSDimitry Andric // is implemented overly conservatively with a single-use check. 15745f757f3fSDimitry Andric // TODO: Update the single-use check to iterate through uses and only bail 15755f757f3fSDimitry Andric // if we have a potentially dangerous use. 15765f757f3fSDimitry Andric 15775f757f3fSDimitry Andric if (CB.hasRetAttr(Attribute::NoUndef) || 15785f757f3fSDimitry Andric (RetVal->hasOneUse() && !RetVal->hasRetAttr(Attribute::NoUndef))) 15795f757f3fSDimitry Andric NewAL = NewAL.addRetAttributes(Context, ValidPG); 15805f757f3fSDimitry Andric } 15815ffd83dbSDimitry Andric NewRetVal->setAttributes(NewAL); 15825ffd83dbSDimitry Andric } 15835ffd83dbSDimitry Andric } 15845ffd83dbSDimitry Andric 15850b57cec5SDimitry Andric /// If the inlined function has non-byval align arguments, then 15860b57cec5SDimitry Andric /// add @llvm.assume-based alignment assumptions to preserve this information. 15875ffd83dbSDimitry Andric static void AddAlignmentAssumptions(CallBase &CB, InlineFunctionInfo &IFI) { 15880b57cec5SDimitry Andric if (!PreserveAlignmentAssumptions || !IFI.GetAssumptionCache) 15890b57cec5SDimitry Andric return; 15900b57cec5SDimitry Andric 15915ffd83dbSDimitry Andric AssumptionCache *AC = &IFI.GetAssumptionCache(*CB.getCaller()); 15920fca6ea1SDimitry Andric auto &DL = CB.getDataLayout(); 15930b57cec5SDimitry Andric 15940b57cec5SDimitry Andric // To avoid inserting redundant assumptions, we should check for assumptions 15950b57cec5SDimitry Andric // already in the caller. To do this, we might need a DT of the caller. 15960b57cec5SDimitry Andric DominatorTree DT; 15970b57cec5SDimitry Andric bool DTCalculated = false; 15980b57cec5SDimitry Andric 15995ffd83dbSDimitry Andric Function *CalledFunc = CB.getCalledFunction(); 16000b57cec5SDimitry Andric for (Argument &Arg : CalledFunc->args()) { 1601bdd1243dSDimitry Andric if (!Arg.getType()->isPointerTy() || Arg.hasPassPointeeByValueCopyAttr() || 1602bdd1243dSDimitry Andric Arg.hasNUses(0)) 1603bdd1243dSDimitry Andric continue; 1604bdd1243dSDimitry Andric MaybeAlign Alignment = Arg.getParamAlign(); 1605bdd1243dSDimitry Andric if (!Alignment) 1606bdd1243dSDimitry Andric continue; 1607bdd1243dSDimitry Andric 16080b57cec5SDimitry Andric if (!DTCalculated) { 16095ffd83dbSDimitry Andric DT.recalculate(*CB.getCaller()); 16100b57cec5SDimitry Andric DTCalculated = true; 16110b57cec5SDimitry Andric } 16120b57cec5SDimitry Andric // If we can already prove the asserted alignment in the context of the 16130b57cec5SDimitry Andric // caller, then don't bother inserting the assumption. 16145ffd83dbSDimitry Andric Value *ArgVal = CB.getArgOperand(Arg.getArgNo()); 1615bdd1243dSDimitry Andric if (getKnownAlignment(ArgVal, DL, &CB, AC, &DT) >= *Alignment) 16160b57cec5SDimitry Andric continue; 16170b57cec5SDimitry Andric 1618bdd1243dSDimitry Andric CallInst *NewAsmp = IRBuilder<>(&CB).CreateAlignmentAssumption( 1619bdd1243dSDimitry Andric DL, ArgVal, Alignment->value()); 1620fe6060f1SDimitry Andric AC->registerAssumption(cast<AssumeInst>(NewAsmp)); 16210b57cec5SDimitry Andric } 16220b57cec5SDimitry Andric } 16230b57cec5SDimitry Andric 1624349cc55cSDimitry Andric static void HandleByValArgumentInit(Type *ByValType, Value *Dst, Value *Src, 1625349cc55cSDimitry Andric Module *M, BasicBlock *InsertBlock, 162606c3fb27SDimitry Andric InlineFunctionInfo &IFI, 162706c3fb27SDimitry Andric Function *CalledFunc) { 16280b57cec5SDimitry Andric IRBuilder<> Builder(InsertBlock, InsertBlock->begin()); 16290b57cec5SDimitry Andric 1630349cc55cSDimitry Andric Value *Size = 1631349cc55cSDimitry Andric Builder.getInt64(M->getDataLayout().getTypeStoreSize(ByValType)); 16320b57cec5SDimitry Andric 16330b57cec5SDimitry Andric // Always generate a memcpy of alignment 1 here because we don't know 16340b57cec5SDimitry Andric // the alignment of the src pointer. Other optimizations can infer 16350b57cec5SDimitry Andric // better alignment. 163606c3fb27SDimitry Andric CallInst *CI = Builder.CreateMemCpy(Dst, /*DstAlign*/ Align(1), Src, 16375ffd83dbSDimitry Andric /*SrcAlign*/ Align(1), Size); 163806c3fb27SDimitry Andric 163906c3fb27SDimitry Andric // The verifier requires that all calls of debug-info-bearing functions 164006c3fb27SDimitry Andric // from debug-info-bearing functions have a debug location (for inlining 164106c3fb27SDimitry Andric // purposes). Assign a dummy location to satisfy the constraint. 164206c3fb27SDimitry Andric if (!CI->getDebugLoc() && InsertBlock->getParent()->getSubprogram()) 164306c3fb27SDimitry Andric if (DISubprogram *SP = CalledFunc->getSubprogram()) 164406c3fb27SDimitry Andric CI->setDebugLoc(DILocation::get(SP->getContext(), 0, 0, SP)); 16450b57cec5SDimitry Andric } 16460b57cec5SDimitry Andric 16470b57cec5SDimitry Andric /// When inlining a call site that has a byval argument, 16480b57cec5SDimitry Andric /// we have to make the implicit memcpy explicit by adding it. 1649349cc55cSDimitry Andric static Value *HandleByValArgument(Type *ByValType, Value *Arg, 1650349cc55cSDimitry Andric Instruction *TheCall, 16510b57cec5SDimitry Andric const Function *CalledFunc, 16520b57cec5SDimitry Andric InlineFunctionInfo &IFI, 1653bdd1243dSDimitry Andric MaybeAlign ByValAlignment) { 16540b57cec5SDimitry Andric Function *Caller = TheCall->getFunction(); 16550fca6ea1SDimitry Andric const DataLayout &DL = Caller->getDataLayout(); 16560b57cec5SDimitry Andric 16570b57cec5SDimitry Andric // If the called function is readonly, then it could not mutate the caller's 16580b57cec5SDimitry Andric // copy of the byval'd memory. In this case, it is safe to elide the copy and 16590b57cec5SDimitry Andric // temporary. 16600b57cec5SDimitry Andric if (CalledFunc->onlyReadsMemory()) { 16610b57cec5SDimitry Andric // If the byval argument has a specified alignment that is greater than the 16620b57cec5SDimitry Andric // passed in pointer, then we either have to round up the input pointer or 16630b57cec5SDimitry Andric // give up on this transformation. 1664bdd1243dSDimitry Andric if (ByValAlignment.valueOrOne() == 1) 16650b57cec5SDimitry Andric return Arg; 16660b57cec5SDimitry Andric 16670b57cec5SDimitry Andric AssumptionCache *AC = 16685ffd83dbSDimitry Andric IFI.GetAssumptionCache ? &IFI.GetAssumptionCache(*Caller) : nullptr; 16690b57cec5SDimitry Andric 16700b57cec5SDimitry Andric // If the pointer is already known to be sufficiently aligned, or if we can 16710b57cec5SDimitry Andric // round it up to a larger alignment, then we don't need a temporary. 1672bdd1243dSDimitry Andric if (getOrEnforceKnownAlignment(Arg, *ByValAlignment, DL, TheCall, AC) >= 1673bdd1243dSDimitry Andric *ByValAlignment) 16740b57cec5SDimitry Andric return Arg; 16750b57cec5SDimitry Andric 16760b57cec5SDimitry Andric // Otherwise, we have to make a memcpy to get a safe alignment. This is bad 16770b57cec5SDimitry Andric // for code quality, but rarely happens and is required for correctness. 16780b57cec5SDimitry Andric } 16790b57cec5SDimitry Andric 16800b57cec5SDimitry Andric // Create the alloca. If we have DataLayout, use nice alignment. 1681bdd1243dSDimitry Andric Align Alignment = DL.getPrefTypeAlign(ByValType); 16820b57cec5SDimitry Andric 16830b57cec5SDimitry Andric // If the byval had an alignment specified, we *must* use at least that 16840b57cec5SDimitry Andric // alignment, as it is required by the byval argument (and uses of the 16850b57cec5SDimitry Andric // pointer inside the callee). 1686bdd1243dSDimitry Andric if (ByValAlignment) 1687bdd1243dSDimitry Andric Alignment = std::max(Alignment, *ByValAlignment); 16880b57cec5SDimitry Andric 16890fca6ea1SDimitry Andric AllocaInst *NewAlloca = 16900fca6ea1SDimitry Andric new AllocaInst(ByValType, Arg->getType()->getPointerAddressSpace(), 16915f757f3fSDimitry Andric nullptr, Alignment, Arg->getName()); 16925f757f3fSDimitry Andric NewAlloca->insertBefore(Caller->begin()->begin()); 16935f757f3fSDimitry Andric IFI.StaticAllocas.push_back(NewAlloca); 16940b57cec5SDimitry Andric 16950b57cec5SDimitry Andric // Uses of the argument in the function should use our new alloca 16960b57cec5SDimitry Andric // instead. 16970b57cec5SDimitry Andric return NewAlloca; 16980b57cec5SDimitry Andric } 16990b57cec5SDimitry Andric 17000b57cec5SDimitry Andric // Check whether this Value is used by a lifetime intrinsic. 17010b57cec5SDimitry Andric static bool isUsedByLifetimeMarker(Value *V) { 17020b57cec5SDimitry Andric for (User *U : V->users()) 17030b57cec5SDimitry Andric if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) 17040b57cec5SDimitry Andric if (II->isLifetimeStartOrEnd()) 17050b57cec5SDimitry Andric return true; 17060b57cec5SDimitry Andric return false; 17070b57cec5SDimitry Andric } 17080b57cec5SDimitry Andric 17090b57cec5SDimitry Andric // Check whether the given alloca already has 17100b57cec5SDimitry Andric // lifetime.start or lifetime.end intrinsics. 17110b57cec5SDimitry Andric static bool hasLifetimeMarkers(AllocaInst *AI) { 17120b57cec5SDimitry Andric Type *Ty = AI->getType(); 17135f757f3fSDimitry Andric Type *Int8PtrTy = 17145f757f3fSDimitry Andric PointerType::get(Ty->getContext(), Ty->getPointerAddressSpace()); 17150b57cec5SDimitry Andric if (Ty == Int8PtrTy) 17160b57cec5SDimitry Andric return isUsedByLifetimeMarker(AI); 17170b57cec5SDimitry Andric 17180b57cec5SDimitry Andric // Do a scan to find all the casts to i8*. 17190b57cec5SDimitry Andric for (User *U : AI->users()) { 17200b57cec5SDimitry Andric if (U->getType() != Int8PtrTy) continue; 17210b57cec5SDimitry Andric if (U->stripPointerCasts() != AI) continue; 17220b57cec5SDimitry Andric if (isUsedByLifetimeMarker(U)) 17230b57cec5SDimitry Andric return true; 17240b57cec5SDimitry Andric } 17250b57cec5SDimitry Andric return false; 17260b57cec5SDimitry Andric } 17270b57cec5SDimitry Andric 17280b57cec5SDimitry Andric /// Return the result of AI->isStaticAlloca() if AI were moved to the entry 17290b57cec5SDimitry Andric /// block. Allocas used in inalloca calls and allocas of dynamic array size 17300b57cec5SDimitry Andric /// cannot be static. 17310b57cec5SDimitry Andric static bool allocaWouldBeStaticInEntry(const AllocaInst *AI ) { 17320b57cec5SDimitry Andric return isa<Constant>(AI->getArraySize()) && !AI->isUsedWithInAlloca(); 17330b57cec5SDimitry Andric } 17340b57cec5SDimitry Andric 17350b57cec5SDimitry Andric /// Returns a DebugLoc for a new DILocation which is a clone of \p OrigDL 17360b57cec5SDimitry Andric /// inlined at \p InlinedAt. \p IANodes is an inlined-at cache. 17370b57cec5SDimitry Andric static DebugLoc inlineDebugLoc(DebugLoc OrigDL, DILocation *InlinedAt, 17380b57cec5SDimitry Andric LLVMContext &Ctx, 17390b57cec5SDimitry Andric DenseMap<const MDNode *, MDNode *> &IANodes) { 17400b57cec5SDimitry Andric auto IA = DebugLoc::appendInlinedAt(OrigDL, InlinedAt, Ctx, IANodes); 1741e8d8bef9SDimitry Andric return DILocation::get(Ctx, OrigDL.getLine(), OrigDL.getCol(), 1742e8d8bef9SDimitry Andric OrigDL.getScope(), IA); 17430b57cec5SDimitry Andric } 17440b57cec5SDimitry Andric 17450b57cec5SDimitry Andric /// Update inlined instructions' line numbers to 17460b57cec5SDimitry Andric /// to encode location where these instructions are inlined. 17470b57cec5SDimitry Andric static void fixupLineNumbers(Function *Fn, Function::iterator FI, 17480b57cec5SDimitry Andric Instruction *TheCall, bool CalleeHasDebugInfo) { 17490b57cec5SDimitry Andric const DebugLoc &TheCallDL = TheCall->getDebugLoc(); 17500b57cec5SDimitry Andric if (!TheCallDL) 17510b57cec5SDimitry Andric return; 17520b57cec5SDimitry Andric 17530b57cec5SDimitry Andric auto &Ctx = Fn->getContext(); 17540b57cec5SDimitry Andric DILocation *InlinedAtNode = TheCallDL; 17550b57cec5SDimitry Andric 17560b57cec5SDimitry Andric // Create a unique call site, not to be confused with any other call from the 17570b57cec5SDimitry Andric // same location. 17580b57cec5SDimitry Andric InlinedAtNode = DILocation::getDistinct( 17590b57cec5SDimitry Andric Ctx, InlinedAtNode->getLine(), InlinedAtNode->getColumn(), 17600b57cec5SDimitry Andric InlinedAtNode->getScope(), InlinedAtNode->getInlinedAt()); 17610b57cec5SDimitry Andric 17620b57cec5SDimitry Andric // Cache the inlined-at nodes as they're built so they are reused, without 17630b57cec5SDimitry Andric // this every instruction's inlined-at chain would become distinct from each 17640b57cec5SDimitry Andric // other. 17650b57cec5SDimitry Andric DenseMap<const MDNode *, MDNode *> IANodes; 17660b57cec5SDimitry Andric 1767480093f4SDimitry Andric // Check if we are not generating inline line tables and want to use 1768480093f4SDimitry Andric // the call site location instead. 1769480093f4SDimitry Andric bool NoInlineLineTables = Fn->hasFnAttribute("no-inline-line-tables"); 1770480093f4SDimitry Andric 17715f757f3fSDimitry Andric // Helper-util for updating the metadata attached to an instruction. 17725f757f3fSDimitry Andric auto UpdateInst = [&](Instruction &I) { 17730b57cec5SDimitry Andric // Loop metadata needs to be updated so that the start and end locs 17740b57cec5SDimitry Andric // reference inlined-at locations. 1775fe6060f1SDimitry Andric auto updateLoopInfoLoc = [&Ctx, &InlinedAtNode, 1776fe6060f1SDimitry Andric &IANodes](Metadata *MD) -> Metadata * { 1777fe6060f1SDimitry Andric if (auto *Loc = dyn_cast_or_null<DILocation>(MD)) 1778fe6060f1SDimitry Andric return inlineDebugLoc(Loc, InlinedAtNode, Ctx, IANodes).get(); 1779fe6060f1SDimitry Andric return MD; 17805ffd83dbSDimitry Andric }; 17815f757f3fSDimitry Andric updateLoopMetadataDebugLocations(I, updateLoopInfoLoc); 17820b57cec5SDimitry Andric 1783480093f4SDimitry Andric if (!NoInlineLineTables) 17845f757f3fSDimitry Andric if (DebugLoc DL = I.getDebugLoc()) { 17850b57cec5SDimitry Andric DebugLoc IDL = 17865f757f3fSDimitry Andric inlineDebugLoc(DL, InlinedAtNode, I.getContext(), IANodes); 17875f757f3fSDimitry Andric I.setDebugLoc(IDL); 17885f757f3fSDimitry Andric return; 17890b57cec5SDimitry Andric } 17900b57cec5SDimitry Andric 1791480093f4SDimitry Andric if (CalleeHasDebugInfo && !NoInlineLineTables) 17925f757f3fSDimitry Andric return; 17930b57cec5SDimitry Andric 1794480093f4SDimitry Andric // If the inlined instruction has no line number, or if inline info 1795480093f4SDimitry Andric // is not being generated, make it look as if it originates from the call 1796480093f4SDimitry Andric // location. This is important for ((__always_inline, __nodebug__)) 1797480093f4SDimitry Andric // functions which must use caller location for all instructions in their 1798480093f4SDimitry Andric // function body. 17990b57cec5SDimitry Andric 18000b57cec5SDimitry Andric // Don't update static allocas, as they may get moved later. 18015f757f3fSDimitry Andric if (auto *AI = dyn_cast<AllocaInst>(&I)) 18020b57cec5SDimitry Andric if (allocaWouldBeStaticInEntry(AI)) 18035f757f3fSDimitry Andric return; 18040b57cec5SDimitry Andric 180506c3fb27SDimitry Andric // Do not force a debug loc for pseudo probes, since they do not need to 180606c3fb27SDimitry Andric // be debuggable, and also they are expected to have a zero/null dwarf 180706c3fb27SDimitry Andric // discriminator at this point which could be violated otherwise. 18085f757f3fSDimitry Andric if (isa<PseudoProbeInst>(I)) 18095f757f3fSDimitry Andric return; 181006c3fb27SDimitry Andric 18115f757f3fSDimitry Andric I.setDebugLoc(TheCallDL); 18125f757f3fSDimitry Andric }; 18135f757f3fSDimitry Andric 18145f757f3fSDimitry Andric // Helper-util for updating debug-info records attached to instructions. 18150fca6ea1SDimitry Andric auto UpdateDVR = [&](DbgRecord *DVR) { 18160fca6ea1SDimitry Andric assert(DVR->getDebugLoc() && "Debug Value must have debug loc"); 18175f757f3fSDimitry Andric if (NoInlineLineTables) { 18180fca6ea1SDimitry Andric DVR->setDebugLoc(TheCallDL); 18195f757f3fSDimitry Andric return; 18205f757f3fSDimitry Andric } 18210fca6ea1SDimitry Andric DebugLoc DL = DVR->getDebugLoc(); 18225f757f3fSDimitry Andric DebugLoc IDL = 18235f757f3fSDimitry Andric inlineDebugLoc(DL, InlinedAtNode, 18240fca6ea1SDimitry Andric DVR->getMarker()->getParent()->getContext(), IANodes); 18250fca6ea1SDimitry Andric DVR->setDebugLoc(IDL); 18265f757f3fSDimitry Andric }; 18275f757f3fSDimitry Andric 18285f757f3fSDimitry Andric // Iterate over all instructions, updating metadata and debug-info records. 18295f757f3fSDimitry Andric for (; FI != Fn->end(); ++FI) { 18300fca6ea1SDimitry Andric for (Instruction &I : *FI) { 18310fca6ea1SDimitry Andric UpdateInst(I); 18320fca6ea1SDimitry Andric for (DbgRecord &DVR : I.getDbgRecordRange()) { 18330fca6ea1SDimitry Andric UpdateDVR(&DVR); 18345f757f3fSDimitry Andric } 18350b57cec5SDimitry Andric } 1836480093f4SDimitry Andric 1837480093f4SDimitry Andric // Remove debug info intrinsics if we're not keeping inline info. 1838480093f4SDimitry Andric if (NoInlineLineTables) { 1839480093f4SDimitry Andric BasicBlock::iterator BI = FI->begin(); 1840480093f4SDimitry Andric while (BI != FI->end()) { 1841480093f4SDimitry Andric if (isa<DbgInfoIntrinsic>(BI)) { 1842480093f4SDimitry Andric BI = BI->eraseFromParent(); 1843480093f4SDimitry Andric continue; 18445f757f3fSDimitry Andric } else { 18450fca6ea1SDimitry Andric BI->dropDbgRecords(); 1846480093f4SDimitry Andric } 1847480093f4SDimitry Andric ++BI; 1848480093f4SDimitry Andric } 1849480093f4SDimitry Andric } 18500b57cec5SDimitry Andric } 18510b57cec5SDimitry Andric } 18520b57cec5SDimitry Andric 1853bdd1243dSDimitry Andric #undef DEBUG_TYPE 1854bdd1243dSDimitry Andric #define DEBUG_TYPE "assignment-tracking" 1855bdd1243dSDimitry Andric /// Find Alloca and linked DbgAssignIntrinsic for locals escaped by \p CB. 1856bdd1243dSDimitry Andric static at::StorageToVarsMap collectEscapedLocals(const DataLayout &DL, 1857bdd1243dSDimitry Andric const CallBase &CB) { 1858bdd1243dSDimitry Andric at::StorageToVarsMap EscapedLocals; 1859bdd1243dSDimitry Andric SmallPtrSet<const Value *, 4> SeenBases; 1860bdd1243dSDimitry Andric 1861bdd1243dSDimitry Andric LLVM_DEBUG( 1862bdd1243dSDimitry Andric errs() << "# Finding caller local variables escaped by callee\n"); 1863bdd1243dSDimitry Andric for (const Value *Arg : CB.args()) { 1864bdd1243dSDimitry Andric LLVM_DEBUG(errs() << "INSPECT: " << *Arg << "\n"); 1865bdd1243dSDimitry Andric if (!Arg->getType()->isPointerTy()) { 1866bdd1243dSDimitry Andric LLVM_DEBUG(errs() << " | SKIP: Not a pointer\n"); 1867bdd1243dSDimitry Andric continue; 1868bdd1243dSDimitry Andric } 1869bdd1243dSDimitry Andric 1870bdd1243dSDimitry Andric const Instruction *I = dyn_cast<Instruction>(Arg); 1871bdd1243dSDimitry Andric if (!I) { 1872bdd1243dSDimitry Andric LLVM_DEBUG(errs() << " | SKIP: Not result of instruction\n"); 1873bdd1243dSDimitry Andric continue; 1874bdd1243dSDimitry Andric } 1875bdd1243dSDimitry Andric 1876bdd1243dSDimitry Andric // Walk back to the base storage. 1877bdd1243dSDimitry Andric assert(Arg->getType()->isPtrOrPtrVectorTy()); 1878bdd1243dSDimitry Andric APInt TmpOffset(DL.getIndexTypeSizeInBits(Arg->getType()), 0, false); 1879bdd1243dSDimitry Andric const AllocaInst *Base = dyn_cast<AllocaInst>( 1880bdd1243dSDimitry Andric Arg->stripAndAccumulateConstantOffsets(DL, TmpOffset, true)); 1881bdd1243dSDimitry Andric if (!Base) { 1882bdd1243dSDimitry Andric LLVM_DEBUG(errs() << " | SKIP: Couldn't walk back to base storage\n"); 1883bdd1243dSDimitry Andric continue; 1884bdd1243dSDimitry Andric } 1885bdd1243dSDimitry Andric 1886bdd1243dSDimitry Andric assert(Base); 1887bdd1243dSDimitry Andric LLVM_DEBUG(errs() << " | BASE: " << *Base << "\n"); 1888bdd1243dSDimitry Andric // We only need to process each base address once - skip any duplicates. 1889bdd1243dSDimitry Andric if (!SeenBases.insert(Base).second) 1890bdd1243dSDimitry Andric continue; 1891bdd1243dSDimitry Andric 1892bdd1243dSDimitry Andric // Find all local variables associated with the backing storage. 18937a6dacacSDimitry Andric auto CollectAssignsForStorage = [&](auto *DbgAssign) { 1894bdd1243dSDimitry Andric // Skip variables from inlined functions - they are not local variables. 18957a6dacacSDimitry Andric if (DbgAssign->getDebugLoc().getInlinedAt()) 18967a6dacacSDimitry Andric return; 18977a6dacacSDimitry Andric LLVM_DEBUG(errs() << " > DEF : " << *DbgAssign << "\n"); 18987a6dacacSDimitry Andric EscapedLocals[Base].insert(at::VarRecord(DbgAssign)); 18997a6dacacSDimitry Andric }; 19007a6dacacSDimitry Andric for_each(at::getAssignmentMarkers(Base), CollectAssignsForStorage); 19010fca6ea1SDimitry Andric for_each(at::getDVRAssignmentMarkers(Base), CollectAssignsForStorage); 1902bdd1243dSDimitry Andric } 1903bdd1243dSDimitry Andric return EscapedLocals; 1904bdd1243dSDimitry Andric } 1905bdd1243dSDimitry Andric 1906bdd1243dSDimitry Andric static void trackInlinedStores(Function::iterator Start, Function::iterator End, 1907bdd1243dSDimitry Andric const CallBase &CB) { 1908bdd1243dSDimitry Andric LLVM_DEBUG(errs() << "trackInlinedStores into " 1909bdd1243dSDimitry Andric << Start->getParent()->getName() << " from " 1910bdd1243dSDimitry Andric << CB.getCalledFunction()->getName() << "\n"); 1911bdd1243dSDimitry Andric std::unique_ptr<DataLayout> DL = std::make_unique<DataLayout>(CB.getModule()); 1912bdd1243dSDimitry Andric at::trackAssignments(Start, End, collectEscapedLocals(*DL, CB), *DL); 1913bdd1243dSDimitry Andric } 1914bdd1243dSDimitry Andric 1915bdd1243dSDimitry Andric /// Update inlined instructions' DIAssignID metadata. We need to do this 1916bdd1243dSDimitry Andric /// otherwise a function inlined more than once into the same function 1917bdd1243dSDimitry Andric /// will cause DIAssignID to be shared by many instructions. 1918bdd1243dSDimitry Andric static void fixupAssignments(Function::iterator Start, Function::iterator End) { 1919bdd1243dSDimitry Andric DenseMap<DIAssignID *, DIAssignID *> Map; 1920bdd1243dSDimitry Andric // Loop over all the inlined instructions. If we find a DIAssignID 1921bdd1243dSDimitry Andric // attachment or use, replace it with a new version. 1922bdd1243dSDimitry Andric for (auto BBI = Start; BBI != End; ++BBI) { 19230fca6ea1SDimitry Andric for (Instruction &I : *BBI) 19240fca6ea1SDimitry Andric at::remapAssignID(Map, I); 1925bdd1243dSDimitry Andric } 1926bdd1243dSDimitry Andric } 1927bdd1243dSDimitry Andric #undef DEBUG_TYPE 1928bdd1243dSDimitry Andric #define DEBUG_TYPE "inline-function" 1929bdd1243dSDimitry Andric 19300b57cec5SDimitry Andric /// Update the block frequencies of the caller after a callee has been inlined. 19310b57cec5SDimitry Andric /// 19320b57cec5SDimitry Andric /// Each block cloned into the caller has its block frequency scaled by the 19330b57cec5SDimitry Andric /// ratio of CallSiteFreq/CalleeEntryFreq. This ensures that the cloned copy of 19340b57cec5SDimitry Andric /// callee's entry block gets the same frequency as the callsite block and the 19350b57cec5SDimitry Andric /// relative frequencies of all cloned blocks remain the same after cloning. 19360b57cec5SDimitry Andric static void updateCallerBFI(BasicBlock *CallSiteBlock, 19370b57cec5SDimitry Andric const ValueToValueMapTy &VMap, 19380b57cec5SDimitry Andric BlockFrequencyInfo *CallerBFI, 19390b57cec5SDimitry Andric BlockFrequencyInfo *CalleeBFI, 19400b57cec5SDimitry Andric const BasicBlock &CalleeEntryBlock) { 19410b57cec5SDimitry Andric SmallPtrSet<BasicBlock *, 16> ClonedBBs; 1942480093f4SDimitry Andric for (auto Entry : VMap) { 19430b57cec5SDimitry Andric if (!isa<BasicBlock>(Entry.first) || !Entry.second) 19440b57cec5SDimitry Andric continue; 19450b57cec5SDimitry Andric auto *OrigBB = cast<BasicBlock>(Entry.first); 19460b57cec5SDimitry Andric auto *ClonedBB = cast<BasicBlock>(Entry.second); 19475f757f3fSDimitry Andric BlockFrequency Freq = CalleeBFI->getBlockFreq(OrigBB); 19480b57cec5SDimitry Andric if (!ClonedBBs.insert(ClonedBB).second) { 19490b57cec5SDimitry Andric // Multiple blocks in the callee might get mapped to one cloned block in 19500b57cec5SDimitry Andric // the caller since we prune the callee as we clone it. When that happens, 19510b57cec5SDimitry Andric // we want to use the maximum among the original blocks' frequencies. 19525f757f3fSDimitry Andric BlockFrequency NewFreq = CallerBFI->getBlockFreq(ClonedBB); 19530b57cec5SDimitry Andric if (NewFreq > Freq) 19540b57cec5SDimitry Andric Freq = NewFreq; 19550b57cec5SDimitry Andric } 19560b57cec5SDimitry Andric CallerBFI->setBlockFreq(ClonedBB, Freq); 19570b57cec5SDimitry Andric } 19580b57cec5SDimitry Andric BasicBlock *EntryClone = cast<BasicBlock>(VMap.lookup(&CalleeEntryBlock)); 19590b57cec5SDimitry Andric CallerBFI->setBlockFreqAndScale( 19605f757f3fSDimitry Andric EntryClone, CallerBFI->getBlockFreq(CallSiteBlock), ClonedBBs); 19610b57cec5SDimitry Andric } 19620b57cec5SDimitry Andric 19630b57cec5SDimitry Andric /// Update the branch metadata for cloned call instructions. 19640b57cec5SDimitry Andric static void updateCallProfile(Function *Callee, const ValueToValueMapTy &VMap, 19650b57cec5SDimitry Andric const ProfileCount &CalleeEntryCount, 19665ffd83dbSDimitry Andric const CallBase &TheCall, ProfileSummaryInfo *PSI, 19670b57cec5SDimitry Andric BlockFrequencyInfo *CallerBFI) { 1968349cc55cSDimitry Andric if (CalleeEntryCount.isSynthetic() || CalleeEntryCount.getCount() < 1) 19690b57cec5SDimitry Andric return; 1970bdd1243dSDimitry Andric auto CallSiteCount = 1971bdd1243dSDimitry Andric PSI ? PSI->getProfileCount(TheCall, CallerBFI) : std::nullopt; 19720b57cec5SDimitry Andric int64_t CallCount = 197381ad6265SDimitry Andric std::min(CallSiteCount.value_or(0), CalleeEntryCount.getCount()); 19740b57cec5SDimitry Andric updateProfileCallee(Callee, -CallCount, &VMap); 19750b57cec5SDimitry Andric } 19760b57cec5SDimitry Andric 19770b57cec5SDimitry Andric void llvm::updateProfileCallee( 1978349cc55cSDimitry Andric Function *Callee, int64_t EntryDelta, 19790b57cec5SDimitry Andric const ValueMap<const Value *, WeakTrackingVH> *VMap) { 19800b57cec5SDimitry Andric auto CalleeCount = Callee->getEntryCount(); 198181ad6265SDimitry Andric if (!CalleeCount) 19820b57cec5SDimitry Andric return; 19830b57cec5SDimitry Andric 1984349cc55cSDimitry Andric const uint64_t PriorEntryCount = CalleeCount->getCount(); 19850b57cec5SDimitry Andric 19860b57cec5SDimitry Andric // Since CallSiteCount is an estimate, it could exceed the original callee 19870b57cec5SDimitry Andric // count and has to be set to 0 so guard against underflow. 1988349cc55cSDimitry Andric const uint64_t NewEntryCount = 1989349cc55cSDimitry Andric (EntryDelta < 0 && static_cast<uint64_t>(-EntryDelta) > PriorEntryCount) 1990349cc55cSDimitry Andric ? 0 1991349cc55cSDimitry Andric : PriorEntryCount + EntryDelta; 19920b57cec5SDimitry Andric 19930fca6ea1SDimitry Andric auto updateVTableProfWeight = [](CallBase *CB, const uint64_t NewEntryCount, 19940fca6ea1SDimitry Andric const uint64_t PriorEntryCount) { 19950fca6ea1SDimitry Andric Instruction *VPtr = PGOIndirectCallVisitor::tryGetVTableInstruction(CB); 19960fca6ea1SDimitry Andric if (VPtr) 19970fca6ea1SDimitry Andric scaleProfData(*VPtr, NewEntryCount, PriorEntryCount); 19980fca6ea1SDimitry Andric }; 19990fca6ea1SDimitry Andric 20000b57cec5SDimitry Andric // During inlining ? 20010b57cec5SDimitry Andric if (VMap) { 2002349cc55cSDimitry Andric uint64_t CloneEntryCount = PriorEntryCount - NewEntryCount; 20030fca6ea1SDimitry Andric for (auto Entry : *VMap) { 20040b57cec5SDimitry Andric if (isa<CallInst>(Entry.first)) 20050fca6ea1SDimitry Andric if (auto *CI = dyn_cast_or_null<CallInst>(Entry.second)) { 2006349cc55cSDimitry Andric CI->updateProfWeight(CloneEntryCount, PriorEntryCount); 20070fca6ea1SDimitry Andric updateVTableProfWeight(CI, CloneEntryCount, PriorEntryCount); 20080fca6ea1SDimitry Andric } 20090fca6ea1SDimitry Andric 20100fca6ea1SDimitry Andric if (isa<InvokeInst>(Entry.first)) 20110fca6ea1SDimitry Andric if (auto *II = dyn_cast_or_null<InvokeInst>(Entry.second)) { 20120fca6ea1SDimitry Andric II->updateProfWeight(CloneEntryCount, PriorEntryCount); 20130fca6ea1SDimitry Andric updateVTableProfWeight(II, CloneEntryCount, PriorEntryCount); 20140fca6ea1SDimitry Andric } 20150fca6ea1SDimitry Andric } 20160b57cec5SDimitry Andric } 2017480093f4SDimitry Andric 2018349cc55cSDimitry Andric if (EntryDelta) { 2019349cc55cSDimitry Andric Callee->setEntryCount(NewEntryCount); 2020480093f4SDimitry Andric 20210b57cec5SDimitry Andric for (BasicBlock &BB : *Callee) 20220b57cec5SDimitry Andric // No need to update the callsite if it is pruned during inlining. 20230b57cec5SDimitry Andric if (!VMap || VMap->count(&BB)) 20240fca6ea1SDimitry Andric for (Instruction &I : BB) { 20250fca6ea1SDimitry Andric if (CallInst *CI = dyn_cast<CallInst>(&I)) { 2026349cc55cSDimitry Andric CI->updateProfWeight(NewEntryCount, PriorEntryCount); 20270fca6ea1SDimitry Andric updateVTableProfWeight(CI, NewEntryCount, PriorEntryCount); 20280fca6ea1SDimitry Andric } 20290fca6ea1SDimitry Andric if (InvokeInst *II = dyn_cast<InvokeInst>(&I)) { 20300fca6ea1SDimitry Andric II->updateProfWeight(NewEntryCount, PriorEntryCount); 20310fca6ea1SDimitry Andric updateVTableProfWeight(II, NewEntryCount, PriorEntryCount); 20320fca6ea1SDimitry Andric } 20330fca6ea1SDimitry Andric } 20340b57cec5SDimitry Andric } 2035480093f4SDimitry Andric } 20360b57cec5SDimitry Andric 2037fe6060f1SDimitry Andric /// An operand bundle "clang.arc.attachedcall" on a call indicates the call 2038fe6060f1SDimitry Andric /// result is implicitly consumed by a call to retainRV or claimRV immediately 2039fe6060f1SDimitry Andric /// after the call. This function inlines the retainRV/claimRV calls. 2040fe6060f1SDimitry Andric /// 2041fe6060f1SDimitry Andric /// There are three cases to consider: 2042fe6060f1SDimitry Andric /// 2043fe6060f1SDimitry Andric /// 1. If there is a call to autoreleaseRV that takes a pointer to the returned 2044fe6060f1SDimitry Andric /// object in the callee return block, the autoreleaseRV call and the 2045fe6060f1SDimitry Andric /// retainRV/claimRV call in the caller cancel out. If the call in the caller 2046fe6060f1SDimitry Andric /// is a claimRV call, a call to objc_release is emitted. 2047fe6060f1SDimitry Andric /// 2048fe6060f1SDimitry Andric /// 2. If there is a call in the callee return block that doesn't have operand 2049fe6060f1SDimitry Andric /// bundle "clang.arc.attachedcall", the operand bundle on the original call 2050fe6060f1SDimitry Andric /// is transferred to the call in the callee. 2051fe6060f1SDimitry Andric /// 2052fe6060f1SDimitry Andric /// 3. Otherwise, a call to objc_retain is inserted if the call in the caller is 2053fe6060f1SDimitry Andric /// a retainRV call. 2054fe6060f1SDimitry Andric static void 2055349cc55cSDimitry Andric inlineRetainOrClaimRVCalls(CallBase &CB, objcarc::ARCInstKind RVCallKind, 2056fe6060f1SDimitry Andric const SmallVectorImpl<ReturnInst *> &Returns) { 2057fe6060f1SDimitry Andric Module *Mod = CB.getModule(); 2058349cc55cSDimitry Andric assert(objcarc::isRetainOrClaimRV(RVCallKind) && "unexpected ARC function"); 2059349cc55cSDimitry Andric bool IsRetainRV = RVCallKind == objcarc::ARCInstKind::RetainRV, 206004eeddc0SDimitry Andric IsUnsafeClaimRV = !IsRetainRV; 2061fe6060f1SDimitry Andric 2062fe6060f1SDimitry Andric for (auto *RI : Returns) { 2063fe6060f1SDimitry Andric Value *RetOpnd = objcarc::GetRCIdentityRoot(RI->getOperand(0)); 2064fe6060f1SDimitry Andric bool InsertRetainCall = IsRetainRV; 2065fe6060f1SDimitry Andric IRBuilder<> Builder(RI->getContext()); 2066fe6060f1SDimitry Andric 2067fe6060f1SDimitry Andric // Walk backwards through the basic block looking for either a matching 2068fe6060f1SDimitry Andric // autoreleaseRV call or an unannotated call. 2069349cc55cSDimitry Andric auto InstRange = llvm::make_range(++(RI->getIterator().getReverse()), 2070349cc55cSDimitry Andric RI->getParent()->rend()); 2071349cc55cSDimitry Andric for (Instruction &I : llvm::make_early_inc_range(InstRange)) { 2072fe6060f1SDimitry Andric // Ignore casts. 2073349cc55cSDimitry Andric if (isa<CastInst>(I)) 2074fe6060f1SDimitry Andric continue; 2075fe6060f1SDimitry Andric 2076349cc55cSDimitry Andric if (auto *II = dyn_cast<IntrinsicInst>(&I)) { 2077349cc55cSDimitry Andric if (II->getIntrinsicID() != Intrinsic::objc_autoreleaseReturnValue || 2078349cc55cSDimitry Andric !II->hasNUses(0) || 2079349cc55cSDimitry Andric objcarc::GetRCIdentityRoot(II->getOperand(0)) != RetOpnd) 2080349cc55cSDimitry Andric break; 2081349cc55cSDimitry Andric 2082fe6060f1SDimitry Andric // If we've found a matching authoreleaseRV call: 2083fe6060f1SDimitry Andric // - If claimRV is attached to the call, insert a call to objc_release 2084fe6060f1SDimitry Andric // and erase the autoreleaseRV call. 2085fe6060f1SDimitry Andric // - If retainRV is attached to the call, just erase the autoreleaseRV 2086fe6060f1SDimitry Andric // call. 208704eeddc0SDimitry Andric if (IsUnsafeClaimRV) { 2088fe6060f1SDimitry Andric Builder.SetInsertPoint(II); 2089fe6060f1SDimitry Andric Function *IFn = 2090fe6060f1SDimitry Andric Intrinsic::getDeclaration(Mod, Intrinsic::objc_release); 20915f757f3fSDimitry Andric Builder.CreateCall(IFn, RetOpnd, ""); 2092fe6060f1SDimitry Andric } 2093fe6060f1SDimitry Andric II->eraseFromParent(); 2094fe6060f1SDimitry Andric InsertRetainCall = false; 2095349cc55cSDimitry Andric break; 2096fe6060f1SDimitry Andric } 2097349cc55cSDimitry Andric 2098349cc55cSDimitry Andric auto *CI = dyn_cast<CallInst>(&I); 2099349cc55cSDimitry Andric 2100349cc55cSDimitry Andric if (!CI) 2101349cc55cSDimitry Andric break; 2102349cc55cSDimitry Andric 2103349cc55cSDimitry Andric if (objcarc::GetRCIdentityRoot(CI) != RetOpnd || 2104349cc55cSDimitry Andric objcarc::hasAttachedCallOpBundle(CI)) 2105349cc55cSDimitry Andric break; 2106349cc55cSDimitry Andric 2107fe6060f1SDimitry Andric // If we've found an unannotated call that defines RetOpnd, add a 2108fe6060f1SDimitry Andric // "clang.arc.attachedcall" operand bundle. 2109349cc55cSDimitry Andric Value *BundleArgs[] = {*objcarc::getAttachedARCFunction(&CB)}; 2110fe6060f1SDimitry Andric OperandBundleDef OB("clang.arc.attachedcall", BundleArgs); 2111fe6060f1SDimitry Andric auto *NewCall = CallBase::addOperandBundle( 21120fca6ea1SDimitry Andric CI, LLVMContext::OB_clang_arc_attachedcall, OB, CI->getIterator()); 2113fe6060f1SDimitry Andric NewCall->copyMetadata(*CI); 2114fe6060f1SDimitry Andric CI->replaceAllUsesWith(NewCall); 2115fe6060f1SDimitry Andric CI->eraseFromParent(); 2116fe6060f1SDimitry Andric InsertRetainCall = false; 2117fe6060f1SDimitry Andric break; 2118fe6060f1SDimitry Andric } 2119fe6060f1SDimitry Andric 2120fe6060f1SDimitry Andric if (InsertRetainCall) { 2121fe6060f1SDimitry Andric // The retainRV is attached to the call and we've failed to find a 2122fe6060f1SDimitry Andric // matching autoreleaseRV or an annotated call in the callee. Emit a call 2123fe6060f1SDimitry Andric // to objc_retain. 2124fe6060f1SDimitry Andric Builder.SetInsertPoint(RI); 2125fe6060f1SDimitry Andric Function *IFn = Intrinsic::getDeclaration(Mod, Intrinsic::objc_retain); 21265f757f3fSDimitry Andric Builder.CreateCall(IFn, RetOpnd, ""); 2127fe6060f1SDimitry Andric } 2128fe6060f1SDimitry Andric } 2129fe6060f1SDimitry Andric } 2130fe6060f1SDimitry Andric 21310b57cec5SDimitry Andric /// This function inlines the called function into the basic block of the 21320b57cec5SDimitry Andric /// caller. This returns false if it is not possible to inline this call. 21330b57cec5SDimitry Andric /// The program is still in a well defined state if this occurs though. 21340b57cec5SDimitry Andric /// 21350b57cec5SDimitry Andric /// Note that this only does one level of inlining. For example, if the 21360b57cec5SDimitry Andric /// instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now 21370b57cec5SDimitry Andric /// exists in the instruction stream. Similarly this will inline a recursive 21380b57cec5SDimitry Andric /// function by one level. 21395ffd83dbSDimitry Andric llvm::InlineResult llvm::InlineFunction(CallBase &CB, InlineFunctionInfo &IFI, 2140bdd1243dSDimitry Andric bool MergeAttributes, 21410b57cec5SDimitry Andric AAResults *CalleeAAR, 21420b57cec5SDimitry Andric bool InsertLifetime, 21430b57cec5SDimitry Andric Function *ForwardVarArgsTo) { 21445ffd83dbSDimitry Andric assert(CB.getParent() && CB.getFunction() && "Instruction not in function!"); 21450b57cec5SDimitry Andric 21460b57cec5SDimitry Andric // FIXME: we don't inline callbr yet. 21475ffd83dbSDimitry Andric if (isa<CallBrInst>(CB)) 21485ffd83dbSDimitry Andric return InlineResult::failure("We don't inline callbr yet."); 21490b57cec5SDimitry Andric 21500b57cec5SDimitry Andric // If IFI has any state in it, zap it before we fill it in. 21510b57cec5SDimitry Andric IFI.reset(); 21520b57cec5SDimitry Andric 21535ffd83dbSDimitry Andric Function *CalledFunc = CB.getCalledFunction(); 21540b57cec5SDimitry Andric if (!CalledFunc || // Can't inline external function or indirect 21550b57cec5SDimitry Andric CalledFunc->isDeclaration()) // call! 21565ffd83dbSDimitry Andric return InlineResult::failure("external or indirect"); 21570b57cec5SDimitry Andric 21580b57cec5SDimitry Andric // The inliner does not know how to inline through calls with operand bundles 21590b57cec5SDimitry Andric // in general ... 21605f757f3fSDimitry Andric Value *ConvergenceControlToken = nullptr; 21615ffd83dbSDimitry Andric if (CB.hasOperandBundles()) { 21625ffd83dbSDimitry Andric for (int i = 0, e = CB.getNumOperandBundles(); i != e; ++i) { 21635f757f3fSDimitry Andric auto OBUse = CB.getOperandBundleAt(i); 21645f757f3fSDimitry Andric uint32_t Tag = OBUse.getTagID(); 21650b57cec5SDimitry Andric // ... but it knows how to inline through "deopt" operand bundles ... 21660b57cec5SDimitry Andric if (Tag == LLVMContext::OB_deopt) 21670b57cec5SDimitry Andric continue; 21680b57cec5SDimitry Andric // ... and "funclet" operand bundles. 21690b57cec5SDimitry Andric if (Tag == LLVMContext::OB_funclet) 21700b57cec5SDimitry Andric continue; 2171fe6060f1SDimitry Andric if (Tag == LLVMContext::OB_clang_arc_attachedcall) 2172fe6060f1SDimitry Andric continue; 2173bdd1243dSDimitry Andric if (Tag == LLVMContext::OB_kcfi) 2174bdd1243dSDimitry Andric continue; 21755f757f3fSDimitry Andric if (Tag == LLVMContext::OB_convergencectrl) { 21765f757f3fSDimitry Andric ConvergenceControlToken = OBUse.Inputs[0].get(); 21775f757f3fSDimitry Andric continue; 21785f757f3fSDimitry Andric } 21790b57cec5SDimitry Andric 21805ffd83dbSDimitry Andric return InlineResult::failure("unsupported operand bundle"); 21810b57cec5SDimitry Andric } 21820b57cec5SDimitry Andric } 21830b57cec5SDimitry Andric 21845f757f3fSDimitry Andric // FIXME: The check below is redundant and incomplete. According to spec, if a 21855f757f3fSDimitry Andric // convergent call is missing a token, then the caller is using uncontrolled 21865f757f3fSDimitry Andric // convergence. If the callee has an entry intrinsic, then the callee is using 21875f757f3fSDimitry Andric // controlled convergence, and the call cannot be inlined. A proper 21885f757f3fSDimitry Andric // implemenation of this check requires a whole new analysis that identifies 21895f757f3fSDimitry Andric // convergence in every function. For now, we skip that and just do this one 21905f757f3fSDimitry Andric // cursory check. The underlying assumption is that in a compiler flow that 21915f757f3fSDimitry Andric // fully implements convergence control tokens, there is no mixing of 21925f757f3fSDimitry Andric // controlled and uncontrolled convergent operations in the whole program. 21935f757f3fSDimitry Andric if (CB.isConvergent()) { 21945f757f3fSDimitry Andric auto *I = CalledFunc->getEntryBlock().getFirstNonPHI(); 21955f757f3fSDimitry Andric if (auto *IntrinsicCall = dyn_cast<IntrinsicInst>(I)) { 21965f757f3fSDimitry Andric if (IntrinsicCall->getIntrinsicID() == 21975f757f3fSDimitry Andric Intrinsic::experimental_convergence_entry) { 21985f757f3fSDimitry Andric if (!ConvergenceControlToken) { 21995f757f3fSDimitry Andric return InlineResult::failure( 22005f757f3fSDimitry Andric "convergent call needs convergencectrl operand"); 22015f757f3fSDimitry Andric } 22025f757f3fSDimitry Andric } 22035f757f3fSDimitry Andric } 22045f757f3fSDimitry Andric } 22055f757f3fSDimitry Andric 22060b57cec5SDimitry Andric // If the call to the callee cannot throw, set the 'nounwind' flag on any 22070b57cec5SDimitry Andric // calls that we inline. 22085ffd83dbSDimitry Andric bool MarkNoUnwind = CB.doesNotThrow(); 22090b57cec5SDimitry Andric 22105ffd83dbSDimitry Andric BasicBlock *OrigBB = CB.getParent(); 22110b57cec5SDimitry Andric Function *Caller = OrigBB->getParent(); 22120b57cec5SDimitry Andric 22130b57cec5SDimitry Andric // GC poses two hazards to inlining, which only occur when the callee has GC: 22140b57cec5SDimitry Andric // 1. If the caller has no GC, then the callee's GC must be propagated to the 22150b57cec5SDimitry Andric // caller. 22160b57cec5SDimitry Andric // 2. If the caller has a differing GC, it is invalid to inline. 22170b57cec5SDimitry Andric if (CalledFunc->hasGC()) { 22180b57cec5SDimitry Andric if (!Caller->hasGC()) 22190b57cec5SDimitry Andric Caller->setGC(CalledFunc->getGC()); 22200b57cec5SDimitry Andric else if (CalledFunc->getGC() != Caller->getGC()) 22215ffd83dbSDimitry Andric return InlineResult::failure("incompatible GC"); 22220b57cec5SDimitry Andric } 22230b57cec5SDimitry Andric 22240b57cec5SDimitry Andric // Get the personality function from the callee if it contains a landing pad. 22250b57cec5SDimitry Andric Constant *CalledPersonality = 22260b57cec5SDimitry Andric CalledFunc->hasPersonalityFn() 22270b57cec5SDimitry Andric ? CalledFunc->getPersonalityFn()->stripPointerCasts() 22280b57cec5SDimitry Andric : nullptr; 22290b57cec5SDimitry Andric 22300b57cec5SDimitry Andric // Find the personality function used by the landing pads of the caller. If it 22310b57cec5SDimitry Andric // exists, then check to see that it matches the personality function used in 22320b57cec5SDimitry Andric // the callee. 22330b57cec5SDimitry Andric Constant *CallerPersonality = 22340b57cec5SDimitry Andric Caller->hasPersonalityFn() 22350b57cec5SDimitry Andric ? Caller->getPersonalityFn()->stripPointerCasts() 22360b57cec5SDimitry Andric : nullptr; 22370b57cec5SDimitry Andric if (CalledPersonality) { 22380b57cec5SDimitry Andric if (!CallerPersonality) 22390b57cec5SDimitry Andric Caller->setPersonalityFn(CalledPersonality); 22400b57cec5SDimitry Andric // If the personality functions match, then we can perform the 22410b57cec5SDimitry Andric // inlining. Otherwise, we can't inline. 22420b57cec5SDimitry Andric // TODO: This isn't 100% true. Some personality functions are proper 22430b57cec5SDimitry Andric // supersets of others and can be used in place of the other. 22440b57cec5SDimitry Andric else if (CalledPersonality != CallerPersonality) 22455ffd83dbSDimitry Andric return InlineResult::failure("incompatible personality"); 22460b57cec5SDimitry Andric } 22470b57cec5SDimitry Andric 22480b57cec5SDimitry Andric // We need to figure out which funclet the callsite was in so that we may 22490b57cec5SDimitry Andric // properly nest the callee. 22500b57cec5SDimitry Andric Instruction *CallSiteEHPad = nullptr; 22510b57cec5SDimitry Andric if (CallerPersonality) { 22520b57cec5SDimitry Andric EHPersonality Personality = classifyEHPersonality(CallerPersonality); 22530b57cec5SDimitry Andric if (isScopedEHPersonality(Personality)) { 2254bdd1243dSDimitry Andric std::optional<OperandBundleUse> ParentFunclet = 22555ffd83dbSDimitry Andric CB.getOperandBundle(LLVMContext::OB_funclet); 22560b57cec5SDimitry Andric if (ParentFunclet) 22570b57cec5SDimitry Andric CallSiteEHPad = cast<FuncletPadInst>(ParentFunclet->Inputs.front()); 22580b57cec5SDimitry Andric 22590b57cec5SDimitry Andric // OK, the inlining site is legal. What about the target function? 22600b57cec5SDimitry Andric 22610b57cec5SDimitry Andric if (CallSiteEHPad) { 22620b57cec5SDimitry Andric if (Personality == EHPersonality::MSVC_CXX) { 22630b57cec5SDimitry Andric // The MSVC personality cannot tolerate catches getting inlined into 22640b57cec5SDimitry Andric // cleanup funclets. 22650b57cec5SDimitry Andric if (isa<CleanupPadInst>(CallSiteEHPad)) { 22660b57cec5SDimitry Andric // Ok, the call site is within a cleanuppad. Let's check the callee 22670b57cec5SDimitry Andric // for catchpads. 22680b57cec5SDimitry Andric for (const BasicBlock &CalledBB : *CalledFunc) { 22690b57cec5SDimitry Andric if (isa<CatchSwitchInst>(CalledBB.getFirstNonPHI())) 22705ffd83dbSDimitry Andric return InlineResult::failure("catch in cleanup funclet"); 22710b57cec5SDimitry Andric } 22720b57cec5SDimitry Andric } 22730b57cec5SDimitry Andric } else if (isAsynchronousEHPersonality(Personality)) { 22740b57cec5SDimitry Andric // SEH is even less tolerant, there may not be any sort of exceptional 22750b57cec5SDimitry Andric // funclet in the callee. 22760b57cec5SDimitry Andric for (const BasicBlock &CalledBB : *CalledFunc) { 22770b57cec5SDimitry Andric if (CalledBB.isEHPad()) 22785ffd83dbSDimitry Andric return InlineResult::failure("SEH in cleanup funclet"); 22790b57cec5SDimitry Andric } 22800b57cec5SDimitry Andric } 22810b57cec5SDimitry Andric } 22820b57cec5SDimitry Andric } 22830b57cec5SDimitry Andric } 22840b57cec5SDimitry Andric 22850b57cec5SDimitry Andric // Determine if we are dealing with a call in an EHPad which does not unwind 22860b57cec5SDimitry Andric // to caller. 22870b57cec5SDimitry Andric bool EHPadForCallUnwindsLocally = false; 22885ffd83dbSDimitry Andric if (CallSiteEHPad && isa<CallInst>(CB)) { 22890b57cec5SDimitry Andric UnwindDestMemoTy FuncletUnwindMap; 22900b57cec5SDimitry Andric Value *CallSiteUnwindDestToken = 22910b57cec5SDimitry Andric getUnwindDestToken(CallSiteEHPad, FuncletUnwindMap); 22920b57cec5SDimitry Andric 22930b57cec5SDimitry Andric EHPadForCallUnwindsLocally = 22940b57cec5SDimitry Andric CallSiteUnwindDestToken && 22950b57cec5SDimitry Andric !isa<ConstantTokenNone>(CallSiteUnwindDestToken); 22960b57cec5SDimitry Andric } 22970b57cec5SDimitry Andric 22980b57cec5SDimitry Andric // Get an iterator to the last basic block in the function, which will have 22990b57cec5SDimitry Andric // the new function inlined after it. 23000b57cec5SDimitry Andric Function::iterator LastBlock = --Caller->end(); 23010b57cec5SDimitry Andric 23020b57cec5SDimitry Andric // Make sure to capture all of the return instructions from the cloned 23030b57cec5SDimitry Andric // function. 23040b57cec5SDimitry Andric SmallVector<ReturnInst*, 8> Returns; 23050b57cec5SDimitry Andric ClonedCodeInfo InlinedFunctionInfo; 23060b57cec5SDimitry Andric Function::iterator FirstNewBlock; 23070b57cec5SDimitry Andric 23080b57cec5SDimitry Andric { // Scope to destroy VMap after cloning. 23090b57cec5SDimitry Andric ValueToValueMapTy VMap; 2310349cc55cSDimitry Andric struct ByValInit { 2311349cc55cSDimitry Andric Value *Dst; 2312349cc55cSDimitry Andric Value *Src; 2313349cc55cSDimitry Andric Type *Ty; 2314349cc55cSDimitry Andric }; 23150b57cec5SDimitry Andric // Keep a list of pair (dst, src) to emit byval initializations. 2316349cc55cSDimitry Andric SmallVector<ByValInit, 4> ByValInits; 23170b57cec5SDimitry Andric 2318e8d8bef9SDimitry Andric // When inlining a function that contains noalias scope metadata, 2319e8d8bef9SDimitry Andric // this metadata needs to be cloned so that the inlined blocks 2320e8d8bef9SDimitry Andric // have different "unique scopes" at every call site. 2321e8d8bef9SDimitry Andric // Track the metadata that must be cloned. Do this before other changes to 2322e8d8bef9SDimitry Andric // the function, so that we do not get in trouble when inlining caller == 2323e8d8bef9SDimitry Andric // callee. 2324e8d8bef9SDimitry Andric ScopedAliasMetadataDeepCloner SAMetadataCloner(CB.getCalledFunction()); 2325e8d8bef9SDimitry Andric 23260fca6ea1SDimitry Andric auto &DL = Caller->getDataLayout(); 23270b57cec5SDimitry Andric 23280b57cec5SDimitry Andric // Calculate the vector of arguments to pass into the function cloner, which 23290b57cec5SDimitry Andric // matches up the formal to the actual argument values. 23305ffd83dbSDimitry Andric auto AI = CB.arg_begin(); 23310b57cec5SDimitry Andric unsigned ArgNo = 0; 23320b57cec5SDimitry Andric for (Function::arg_iterator I = CalledFunc->arg_begin(), 23330b57cec5SDimitry Andric E = CalledFunc->arg_end(); I != E; ++I, ++AI, ++ArgNo) { 23340b57cec5SDimitry Andric Value *ActualArg = *AI; 23350b57cec5SDimitry Andric 23360b57cec5SDimitry Andric // When byval arguments actually inlined, we need to make the copy implied 23370b57cec5SDimitry Andric // by them explicit. However, we don't do this if the callee is readonly 23380b57cec5SDimitry Andric // or readnone, because the copy would be unneeded: the callee doesn't 23390b57cec5SDimitry Andric // modify the struct. 23405ffd83dbSDimitry Andric if (CB.isByValArgument(ArgNo)) { 2341349cc55cSDimitry Andric ActualArg = HandleByValArgument(CB.getParamByValType(ArgNo), ActualArg, 2342349cc55cSDimitry Andric &CB, CalledFunc, IFI, 2343bdd1243dSDimitry Andric CalledFunc->getParamAlign(ArgNo)); 23440b57cec5SDimitry Andric if (ActualArg != *AI) 2345349cc55cSDimitry Andric ByValInits.push_back( 2346349cc55cSDimitry Andric {ActualArg, (Value *)*AI, CB.getParamByValType(ArgNo)}); 23470b57cec5SDimitry Andric } 23480b57cec5SDimitry Andric 23490b57cec5SDimitry Andric VMap[&*I] = ActualArg; 23500b57cec5SDimitry Andric } 23510b57cec5SDimitry Andric 23525ffd83dbSDimitry Andric // TODO: Remove this when users have been updated to the assume bundles. 23530b57cec5SDimitry Andric // Add alignment assumptions if necessary. We do this before the inlined 23540b57cec5SDimitry Andric // instructions are actually cloned into the caller so that we can easily 23550b57cec5SDimitry Andric // check what will be known at the start of the inlined code. 23565ffd83dbSDimitry Andric AddAlignmentAssumptions(CB, IFI); 23575ffd83dbSDimitry Andric 23585ffd83dbSDimitry Andric AssumptionCache *AC = 23595ffd83dbSDimitry Andric IFI.GetAssumptionCache ? &IFI.GetAssumptionCache(*Caller) : nullptr; 23605ffd83dbSDimitry Andric 23615ffd83dbSDimitry Andric /// Preserve all attributes on of the call and its parameters. 23625ffd83dbSDimitry Andric salvageKnowledge(&CB, AC); 23630b57cec5SDimitry Andric 23640b57cec5SDimitry Andric // We want the inliner to prune the code as it copies. We would LOVE to 23650b57cec5SDimitry Andric // have no dead or constant instructions leftover after inlining occurs 23660b57cec5SDimitry Andric // (which can happen, e.g., because an argument was constant), but we'll be 23670b57cec5SDimitry Andric // happy with whatever the cloner can do. 23680b57cec5SDimitry Andric CloneAndPruneFunctionInto(Caller, CalledFunc, VMap, 23690b57cec5SDimitry Andric /*ModuleLevelChanges=*/false, Returns, ".i", 2370fe6060f1SDimitry Andric &InlinedFunctionInfo); 23710b57cec5SDimitry Andric // Remember the first block that is newly cloned over. 23720b57cec5SDimitry Andric FirstNewBlock = LastBlock; ++FirstNewBlock; 23730b57cec5SDimitry Andric 2374fe6060f1SDimitry Andric // Insert retainRV/clainRV runtime calls. 2375349cc55cSDimitry Andric objcarc::ARCInstKind RVCallKind = objcarc::getAttachedARCFunctionKind(&CB); 2376349cc55cSDimitry Andric if (RVCallKind != objcarc::ARCInstKind::None) 2377349cc55cSDimitry Andric inlineRetainOrClaimRVCalls(CB, RVCallKind, Returns); 2378fe6060f1SDimitry Andric 2379fe6060f1SDimitry Andric // Updated caller/callee profiles only when requested. For sample loader 2380fe6060f1SDimitry Andric // inlining, the context-sensitive inlinee profile doesn't need to be 2381fe6060f1SDimitry Andric // subtracted from callee profile, and the inlined clone also doesn't need 2382fe6060f1SDimitry Andric // to be scaled based on call site count. 2383fe6060f1SDimitry Andric if (IFI.UpdateProfile) { 23840b57cec5SDimitry Andric if (IFI.CallerBFI != nullptr && IFI.CalleeBFI != nullptr) 23850b57cec5SDimitry Andric // Update the BFI of blocks cloned into the caller. 23860b57cec5SDimitry Andric updateCallerBFI(OrigBB, VMap, IFI.CallerBFI, IFI.CalleeBFI, 23870b57cec5SDimitry Andric CalledFunc->front()); 23880b57cec5SDimitry Andric 2389349cc55cSDimitry Andric if (auto Profile = CalledFunc->getEntryCount()) 2390349cc55cSDimitry Andric updateCallProfile(CalledFunc, VMap, *Profile, CB, IFI.PSI, 2391349cc55cSDimitry Andric IFI.CallerBFI); 2392fe6060f1SDimitry Andric } 23930b57cec5SDimitry Andric 23940b57cec5SDimitry Andric // Inject byval arguments initialization. 2395349cc55cSDimitry Andric for (ByValInit &Init : ByValInits) 2396349cc55cSDimitry Andric HandleByValArgumentInit(Init.Ty, Init.Dst, Init.Src, Caller->getParent(), 239706c3fb27SDimitry Andric &*FirstNewBlock, IFI, CalledFunc); 23980b57cec5SDimitry Andric 2399bdd1243dSDimitry Andric std::optional<OperandBundleUse> ParentDeopt = 24005ffd83dbSDimitry Andric CB.getOperandBundle(LLVMContext::OB_deopt); 24010b57cec5SDimitry Andric if (ParentDeopt) { 24020b57cec5SDimitry Andric SmallVector<OperandBundleDef, 2> OpDefs; 24030b57cec5SDimitry Andric 24040b57cec5SDimitry Andric for (auto &VH : InlinedFunctionInfo.OperandBundleCallSites) { 24055ffd83dbSDimitry Andric CallBase *ICS = dyn_cast_or_null<CallBase>(VH); 24065ffd83dbSDimitry Andric if (!ICS) 24075ffd83dbSDimitry Andric continue; // instruction was DCE'd or RAUW'ed to undef 24080b57cec5SDimitry Andric 24090b57cec5SDimitry Andric OpDefs.clear(); 24100b57cec5SDimitry Andric 24115ffd83dbSDimitry Andric OpDefs.reserve(ICS->getNumOperandBundles()); 24120b57cec5SDimitry Andric 24135ffd83dbSDimitry Andric for (unsigned COBi = 0, COBe = ICS->getNumOperandBundles(); COBi < COBe; 24145ffd83dbSDimitry Andric ++COBi) { 24155ffd83dbSDimitry Andric auto ChildOB = ICS->getOperandBundleAt(COBi); 24160b57cec5SDimitry Andric if (ChildOB.getTagID() != LLVMContext::OB_deopt) { 24170b57cec5SDimitry Andric // If the inlined call has other operand bundles, let them be 24180b57cec5SDimitry Andric OpDefs.emplace_back(ChildOB); 24190b57cec5SDimitry Andric continue; 24200b57cec5SDimitry Andric } 24210b57cec5SDimitry Andric 24220b57cec5SDimitry Andric // It may be useful to separate this logic (of handling operand 24230b57cec5SDimitry Andric // bundles) out to a separate "policy" component if this gets crowded. 24240b57cec5SDimitry Andric // Prepend the parent's deoptimization continuation to the newly 24250b57cec5SDimitry Andric // inlined call's deoptimization continuation. 24260b57cec5SDimitry Andric std::vector<Value *> MergedDeoptArgs; 24270b57cec5SDimitry Andric MergedDeoptArgs.reserve(ParentDeopt->Inputs.size() + 24280b57cec5SDimitry Andric ChildOB.Inputs.size()); 24290b57cec5SDimitry Andric 2430e8d8bef9SDimitry Andric llvm::append_range(MergedDeoptArgs, ParentDeopt->Inputs); 2431e8d8bef9SDimitry Andric llvm::append_range(MergedDeoptArgs, ChildOB.Inputs); 24320b57cec5SDimitry Andric 24330b57cec5SDimitry Andric OpDefs.emplace_back("deopt", std::move(MergedDeoptArgs)); 24340b57cec5SDimitry Andric } 24350b57cec5SDimitry Andric 24360fca6ea1SDimitry Andric Instruction *NewI = CallBase::Create(ICS, OpDefs, ICS->getIterator()); 24370b57cec5SDimitry Andric 24380b57cec5SDimitry Andric // Note: the RAUW does the appropriate fixup in VMap, so we need to do 24390b57cec5SDimitry Andric // this even if the call returns void. 24405ffd83dbSDimitry Andric ICS->replaceAllUsesWith(NewI); 24410b57cec5SDimitry Andric 24420b57cec5SDimitry Andric VH = nullptr; 24435ffd83dbSDimitry Andric ICS->eraseFromParent(); 24440b57cec5SDimitry Andric } 24450b57cec5SDimitry Andric } 24460b57cec5SDimitry Andric 24470b57cec5SDimitry Andric // For 'nodebug' functions, the associated DISubprogram is always null. 24480b57cec5SDimitry Andric // Conservatively avoid propagating the callsite debug location to 24490b57cec5SDimitry Andric // instructions inlined from a function whose DISubprogram is not null. 24505ffd83dbSDimitry Andric fixupLineNumbers(Caller, FirstNewBlock, &CB, 24510b57cec5SDimitry Andric CalledFunc->getSubprogram() != nullptr); 24520b57cec5SDimitry Andric 2453bdd1243dSDimitry Andric if (isAssignmentTrackingEnabled(*Caller->getParent())) { 2454bdd1243dSDimitry Andric // Interpret inlined stores to caller-local variables as assignments. 2455bdd1243dSDimitry Andric trackInlinedStores(FirstNewBlock, Caller->end(), CB); 2456bdd1243dSDimitry Andric 2457bdd1243dSDimitry Andric // Update DIAssignID metadata attachments and uses so that they are 2458bdd1243dSDimitry Andric // unique to this inlined instance. 2459bdd1243dSDimitry Andric fixupAssignments(FirstNewBlock, Caller->end()); 2460bdd1243dSDimitry Andric } 2461bdd1243dSDimitry Andric 2462e8d8bef9SDimitry Andric // Now clone the inlined noalias scope metadata. 2463e8d8bef9SDimitry Andric SAMetadataCloner.clone(); 246423408297SDimitry Andric SAMetadataCloner.remap(FirstNewBlock, Caller->end()); 24650b57cec5SDimitry Andric 24660b57cec5SDimitry Andric // Add noalias metadata if necessary. 2467fe6060f1SDimitry Andric AddAliasScopeMetadata(CB, VMap, DL, CalleeAAR, InlinedFunctionInfo); 24685ffd83dbSDimitry Andric 24695ffd83dbSDimitry Andric // Clone return attributes on the callsite into the calls within the inlined 24705ffd83dbSDimitry Andric // function which feed into its return value. 24716e516c87SDimitry Andric AddReturnAttributes(CB, VMap, InlinedFunctionInfo); 24720b57cec5SDimitry Andric 24730fca6ea1SDimitry Andric // Clone attributes on the params of the callsite to calls within the 24740fca6ea1SDimitry Andric // inlined function which use the same param. 24756e516c87SDimitry Andric AddParamAndFnBasicAttributes(CB, VMap, InlinedFunctionInfo); 24760fca6ea1SDimitry Andric 2477bdd1243dSDimitry Andric propagateMemProfMetadata(CalledFunc, CB, 2478bdd1243dSDimitry Andric InlinedFunctionInfo.ContainsMemProfMetadata, VMap); 2479bdd1243dSDimitry Andric 2480e8d8bef9SDimitry Andric // Propagate metadata on the callsite if necessary. 248123408297SDimitry Andric PropagateCallSiteMetadata(CB, FirstNewBlock, Caller->end()); 24820b57cec5SDimitry Andric 24830b57cec5SDimitry Andric // Register any cloned assumptions. 24840b57cec5SDimitry Andric if (IFI.GetAssumptionCache) 24850b57cec5SDimitry Andric for (BasicBlock &NewBlock : 24860b57cec5SDimitry Andric make_range(FirstNewBlock->getIterator(), Caller->end())) 24875ffd83dbSDimitry Andric for (Instruction &I : NewBlock) 248806c3fb27SDimitry Andric if (auto *II = dyn_cast<AssumeInst>(&I)) 24895ffd83dbSDimitry Andric IFI.GetAssumptionCache(*Caller).registerAssumption(II); 24900b57cec5SDimitry Andric } 24910b57cec5SDimitry Andric 24925f757f3fSDimitry Andric if (ConvergenceControlToken) { 24935f757f3fSDimitry Andric auto *I = FirstNewBlock->getFirstNonPHI(); 24945f757f3fSDimitry Andric if (auto *IntrinsicCall = dyn_cast<IntrinsicInst>(I)) { 24955f757f3fSDimitry Andric if (IntrinsicCall->getIntrinsicID() == 24965f757f3fSDimitry Andric Intrinsic::experimental_convergence_entry) { 24975f757f3fSDimitry Andric IntrinsicCall->replaceAllUsesWith(ConvergenceControlToken); 24985f757f3fSDimitry Andric IntrinsicCall->eraseFromParent(); 24995f757f3fSDimitry Andric } 25005f757f3fSDimitry Andric } 25015f757f3fSDimitry Andric } 25025f757f3fSDimitry Andric 25030b57cec5SDimitry Andric // If there are any alloca instructions in the block that used to be the entry 25040b57cec5SDimitry Andric // block for the callee, move them to the entry block of the caller. First 25050b57cec5SDimitry Andric // calculate which instruction they should be inserted before. We insert the 25060b57cec5SDimitry Andric // instructions at the end of the current alloca list. 25070b57cec5SDimitry Andric { 25080b57cec5SDimitry Andric BasicBlock::iterator InsertPoint = Caller->begin()->begin(); 25090b57cec5SDimitry Andric for (BasicBlock::iterator I = FirstNewBlock->begin(), 25100b57cec5SDimitry Andric E = FirstNewBlock->end(); I != E; ) { 25110b57cec5SDimitry Andric AllocaInst *AI = dyn_cast<AllocaInst>(I++); 25120b57cec5SDimitry Andric if (!AI) continue; 25130b57cec5SDimitry Andric 25140b57cec5SDimitry Andric // If the alloca is now dead, remove it. This often occurs due to code 25150b57cec5SDimitry Andric // specialization. 25160b57cec5SDimitry Andric if (AI->use_empty()) { 25170b57cec5SDimitry Andric AI->eraseFromParent(); 25180b57cec5SDimitry Andric continue; 25190b57cec5SDimitry Andric } 25200b57cec5SDimitry Andric 25210b57cec5SDimitry Andric if (!allocaWouldBeStaticInEntry(AI)) 25220b57cec5SDimitry Andric continue; 25230b57cec5SDimitry Andric 25240b57cec5SDimitry Andric // Keep track of the static allocas that we inline into the caller. 25250b57cec5SDimitry Andric IFI.StaticAllocas.push_back(AI); 25260b57cec5SDimitry Andric 25270b57cec5SDimitry Andric // Scan for the block of allocas that we can move over, and move them 25280b57cec5SDimitry Andric // all at once. 25290b57cec5SDimitry Andric while (isa<AllocaInst>(I) && 2530480093f4SDimitry Andric !cast<AllocaInst>(I)->use_empty() && 25310b57cec5SDimitry Andric allocaWouldBeStaticInEntry(cast<AllocaInst>(I))) { 25320b57cec5SDimitry Andric IFI.StaticAllocas.push_back(cast<AllocaInst>(I)); 25330b57cec5SDimitry Andric ++I; 25340b57cec5SDimitry Andric } 25350b57cec5SDimitry Andric 25360b57cec5SDimitry Andric // Transfer all of the allocas over in a block. Using splice means 25370b57cec5SDimitry Andric // that the instructions aren't removed from the symbol table, then 25380b57cec5SDimitry Andric // reinserted. 25395f757f3fSDimitry Andric I.setTailBit(true); 2540bdd1243dSDimitry Andric Caller->getEntryBlock().splice(InsertPoint, &*FirstNewBlock, 2541bdd1243dSDimitry Andric AI->getIterator(), I); 25420b57cec5SDimitry Andric } 25430b57cec5SDimitry Andric } 25440b57cec5SDimitry Andric 25450b57cec5SDimitry Andric SmallVector<Value*,4> VarArgsToForward; 25460b57cec5SDimitry Andric SmallVector<AttributeSet, 4> VarArgsAttrs; 25470b57cec5SDimitry Andric for (unsigned i = CalledFunc->getFunctionType()->getNumParams(); 2548349cc55cSDimitry Andric i < CB.arg_size(); i++) { 25495ffd83dbSDimitry Andric VarArgsToForward.push_back(CB.getArgOperand(i)); 2550349cc55cSDimitry Andric VarArgsAttrs.push_back(CB.getAttributes().getParamAttrs(i)); 25510b57cec5SDimitry Andric } 25520b57cec5SDimitry Andric 25530b57cec5SDimitry Andric bool InlinedMustTailCalls = false, InlinedDeoptimizeCalls = false; 25540b57cec5SDimitry Andric if (InlinedFunctionInfo.ContainsCalls) { 25550b57cec5SDimitry Andric CallInst::TailCallKind CallSiteTailKind = CallInst::TCK_None; 25565ffd83dbSDimitry Andric if (CallInst *CI = dyn_cast<CallInst>(&CB)) 25570b57cec5SDimitry Andric CallSiteTailKind = CI->getTailCallKind(); 25580b57cec5SDimitry Andric 25590b57cec5SDimitry Andric // For inlining purposes, the "notail" marker is the same as no marker. 25600b57cec5SDimitry Andric if (CallSiteTailKind == CallInst::TCK_NoTail) 25610b57cec5SDimitry Andric CallSiteTailKind = CallInst::TCK_None; 25620b57cec5SDimitry Andric 25630b57cec5SDimitry Andric for (Function::iterator BB = FirstNewBlock, E = Caller->end(); BB != E; 25640b57cec5SDimitry Andric ++BB) { 2565349cc55cSDimitry Andric for (Instruction &I : llvm::make_early_inc_range(*BB)) { 25660b57cec5SDimitry Andric CallInst *CI = dyn_cast<CallInst>(&I); 25670b57cec5SDimitry Andric if (!CI) 25680b57cec5SDimitry Andric continue; 25690b57cec5SDimitry Andric 25700b57cec5SDimitry Andric // Forward varargs from inlined call site to calls to the 25710b57cec5SDimitry Andric // ForwardVarArgsTo function, if requested, and to musttail calls. 25720b57cec5SDimitry Andric if (!VarArgsToForward.empty() && 25730b57cec5SDimitry Andric ((ForwardVarArgsTo && 25740b57cec5SDimitry Andric CI->getCalledFunction() == ForwardVarArgsTo) || 25750b57cec5SDimitry Andric CI->isMustTailCall())) { 25760b57cec5SDimitry Andric // Collect attributes for non-vararg parameters. 25770b57cec5SDimitry Andric AttributeList Attrs = CI->getAttributes(); 25780b57cec5SDimitry Andric SmallVector<AttributeSet, 8> ArgAttrs; 25790b57cec5SDimitry Andric if (!Attrs.isEmpty() || !VarArgsAttrs.empty()) { 25800b57cec5SDimitry Andric for (unsigned ArgNo = 0; 25810b57cec5SDimitry Andric ArgNo < CI->getFunctionType()->getNumParams(); ++ArgNo) 2582349cc55cSDimitry Andric ArgAttrs.push_back(Attrs.getParamAttrs(ArgNo)); 25830b57cec5SDimitry Andric } 25840b57cec5SDimitry Andric 25850b57cec5SDimitry Andric // Add VarArg attributes. 25860b57cec5SDimitry Andric ArgAttrs.append(VarArgsAttrs.begin(), VarArgsAttrs.end()); 2587349cc55cSDimitry Andric Attrs = AttributeList::get(CI->getContext(), Attrs.getFnAttrs(), 2588349cc55cSDimitry Andric Attrs.getRetAttrs(), ArgAttrs); 25890b57cec5SDimitry Andric // Add VarArgs to existing parameters. 2590349cc55cSDimitry Andric SmallVector<Value *, 6> Params(CI->args()); 25910b57cec5SDimitry Andric Params.append(VarArgsToForward.begin(), VarArgsToForward.end()); 25920b57cec5SDimitry Andric CallInst *NewCI = CallInst::Create( 25930fca6ea1SDimitry Andric CI->getFunctionType(), CI->getCalledOperand(), Params, "", CI->getIterator()); 25940b57cec5SDimitry Andric NewCI->setDebugLoc(CI->getDebugLoc()); 25950b57cec5SDimitry Andric NewCI->setAttributes(Attrs); 25960b57cec5SDimitry Andric NewCI->setCallingConv(CI->getCallingConv()); 25970b57cec5SDimitry Andric CI->replaceAllUsesWith(NewCI); 25980b57cec5SDimitry Andric CI->eraseFromParent(); 25990b57cec5SDimitry Andric CI = NewCI; 26000b57cec5SDimitry Andric } 26010b57cec5SDimitry Andric 26020b57cec5SDimitry Andric if (Function *F = CI->getCalledFunction()) 26030b57cec5SDimitry Andric InlinedDeoptimizeCalls |= 26040b57cec5SDimitry Andric F->getIntrinsicID() == Intrinsic::experimental_deoptimize; 26050b57cec5SDimitry Andric 26060b57cec5SDimitry Andric // We need to reduce the strength of any inlined tail calls. For 26070b57cec5SDimitry Andric // musttail, we have to avoid introducing potential unbounded stack 26080b57cec5SDimitry Andric // growth. For example, if functions 'f' and 'g' are mutually recursive 26090b57cec5SDimitry Andric // with musttail, we can inline 'g' into 'f' so long as we preserve 26100b57cec5SDimitry Andric // musttail on the cloned call to 'f'. If either the inlined call site 26110b57cec5SDimitry Andric // or the cloned call site is *not* musttail, the program already has 26120b57cec5SDimitry Andric // one frame of stack growth, so it's safe to remove musttail. Here is 26130b57cec5SDimitry Andric // a table of example transformations: 26140b57cec5SDimitry Andric // 26150b57cec5SDimitry Andric // f -> musttail g -> musttail f ==> f -> musttail f 26160b57cec5SDimitry Andric // f -> musttail g -> tail f ==> f -> tail f 26170b57cec5SDimitry Andric // f -> g -> musttail f ==> f -> f 26180b57cec5SDimitry Andric // f -> g -> tail f ==> f -> f 26190b57cec5SDimitry Andric // 26200b57cec5SDimitry Andric // Inlined notail calls should remain notail calls. 26210b57cec5SDimitry Andric CallInst::TailCallKind ChildTCK = CI->getTailCallKind(); 26220b57cec5SDimitry Andric if (ChildTCK != CallInst::TCK_NoTail) 26230b57cec5SDimitry Andric ChildTCK = std::min(CallSiteTailKind, ChildTCK); 26240b57cec5SDimitry Andric CI->setTailCallKind(ChildTCK); 26250b57cec5SDimitry Andric InlinedMustTailCalls |= CI->isMustTailCall(); 26260b57cec5SDimitry Andric 2627fcaf7f86SDimitry Andric // Call sites inlined through a 'nounwind' call site should be 2628fcaf7f86SDimitry Andric // 'nounwind' as well. However, avoid marking call sites explicitly 2629fcaf7f86SDimitry Andric // where possible. This helps expose more opportunities for CSE after 2630fcaf7f86SDimitry Andric // inlining, commonly when the callee is an intrinsic. 2631fcaf7f86SDimitry Andric if (MarkNoUnwind && !CI->doesNotThrow()) 26320b57cec5SDimitry Andric CI->setDoesNotThrow(); 26330b57cec5SDimitry Andric } 26340b57cec5SDimitry Andric } 26350b57cec5SDimitry Andric } 26360b57cec5SDimitry Andric 26370b57cec5SDimitry Andric // Leave lifetime markers for the static alloca's, scoping them to the 26380b57cec5SDimitry Andric // function we just inlined. 2639fe6060f1SDimitry Andric // We need to insert lifetime intrinsics even at O0 to avoid invalid 2640fe6060f1SDimitry Andric // access caused by multithreaded coroutines. The check 2641fe6060f1SDimitry Andric // `Caller->isPresplitCoroutine()` would affect AlwaysInliner at O0 only. 2642fe6060f1SDimitry Andric if ((InsertLifetime || Caller->isPresplitCoroutine()) && 2643fe6060f1SDimitry Andric !IFI.StaticAllocas.empty()) { 26445f757f3fSDimitry Andric IRBuilder<> builder(&*FirstNewBlock, FirstNewBlock->begin()); 26450fca6ea1SDimitry Andric for (AllocaInst *AI : IFI.StaticAllocas) { 26460b57cec5SDimitry Andric // Don't mark swifterror allocas. They can't have bitcast uses. 26470b57cec5SDimitry Andric if (AI->isSwiftError()) 26480b57cec5SDimitry Andric continue; 26490b57cec5SDimitry Andric 26500b57cec5SDimitry Andric // If the alloca is already scoped to something smaller than the whole 26510b57cec5SDimitry Andric // function then there's no need to add redundant, less accurate markers. 26520b57cec5SDimitry Andric if (hasLifetimeMarkers(AI)) 26530b57cec5SDimitry Andric continue; 26540b57cec5SDimitry Andric 26550b57cec5SDimitry Andric // Try to determine the size of the allocation. 26560b57cec5SDimitry Andric ConstantInt *AllocaSize = nullptr; 26570b57cec5SDimitry Andric if (ConstantInt *AIArraySize = 26580b57cec5SDimitry Andric dyn_cast<ConstantInt>(AI->getArraySize())) { 26590fca6ea1SDimitry Andric auto &DL = Caller->getDataLayout(); 26600b57cec5SDimitry Andric Type *AllocaType = AI->getAllocatedType(); 2661e8d8bef9SDimitry Andric TypeSize AllocaTypeSize = DL.getTypeAllocSize(AllocaType); 26620b57cec5SDimitry Andric uint64_t AllocaArraySize = AIArraySize->getLimitedValue(); 26630b57cec5SDimitry Andric 26640b57cec5SDimitry Andric // Don't add markers for zero-sized allocas. 26650b57cec5SDimitry Andric if (AllocaArraySize == 0) 26660b57cec5SDimitry Andric continue; 26670b57cec5SDimitry Andric 26680b57cec5SDimitry Andric // Check that array size doesn't saturate uint64_t and doesn't 26690b57cec5SDimitry Andric // overflow when it's multiplied by type size. 2670e8d8bef9SDimitry Andric if (!AllocaTypeSize.isScalable() && 2671e8d8bef9SDimitry Andric AllocaArraySize != std::numeric_limits<uint64_t>::max() && 26720b57cec5SDimitry Andric std::numeric_limits<uint64_t>::max() / AllocaArraySize >= 2673bdd1243dSDimitry Andric AllocaTypeSize.getFixedValue()) { 26740b57cec5SDimitry Andric AllocaSize = ConstantInt::get(Type::getInt64Ty(AI->getContext()), 26750b57cec5SDimitry Andric AllocaArraySize * AllocaTypeSize); 26760b57cec5SDimitry Andric } 26770b57cec5SDimitry Andric } 26780b57cec5SDimitry Andric 26790b57cec5SDimitry Andric builder.CreateLifetimeStart(AI, AllocaSize); 26800b57cec5SDimitry Andric for (ReturnInst *RI : Returns) { 26810b57cec5SDimitry Andric // Don't insert llvm.lifetime.end calls between a musttail or deoptimize 26820b57cec5SDimitry Andric // call and a return. The return kills all local allocas. 26830b57cec5SDimitry Andric if (InlinedMustTailCalls && 26840b57cec5SDimitry Andric RI->getParent()->getTerminatingMustTailCall()) 26850b57cec5SDimitry Andric continue; 26860b57cec5SDimitry Andric if (InlinedDeoptimizeCalls && 26870b57cec5SDimitry Andric RI->getParent()->getTerminatingDeoptimizeCall()) 26880b57cec5SDimitry Andric continue; 26890b57cec5SDimitry Andric IRBuilder<>(RI).CreateLifetimeEnd(AI, AllocaSize); 26900b57cec5SDimitry Andric } 26910b57cec5SDimitry Andric } 26920b57cec5SDimitry Andric } 26930b57cec5SDimitry Andric 26940b57cec5SDimitry Andric // If the inlined code contained dynamic alloca instructions, wrap the inlined 26950b57cec5SDimitry Andric // code with llvm.stacksave/llvm.stackrestore intrinsics. 26960b57cec5SDimitry Andric if (InlinedFunctionInfo.ContainsDynamicAllocas) { 26970b57cec5SDimitry Andric // Insert the llvm.stacksave. 26980b57cec5SDimitry Andric CallInst *SavedPtr = IRBuilder<>(&*FirstNewBlock, FirstNewBlock->begin()) 26995f757f3fSDimitry Andric .CreateStackSave("savedstack"); 27000b57cec5SDimitry Andric 27010b57cec5SDimitry Andric // Insert a call to llvm.stackrestore before any return instructions in the 27020b57cec5SDimitry Andric // inlined function. 27030b57cec5SDimitry Andric for (ReturnInst *RI : Returns) { 27040b57cec5SDimitry Andric // Don't insert llvm.stackrestore calls between a musttail or deoptimize 27050b57cec5SDimitry Andric // call and a return. The return will restore the stack pointer. 27060b57cec5SDimitry Andric if (InlinedMustTailCalls && RI->getParent()->getTerminatingMustTailCall()) 27070b57cec5SDimitry Andric continue; 27080b57cec5SDimitry Andric if (InlinedDeoptimizeCalls && RI->getParent()->getTerminatingDeoptimizeCall()) 27090b57cec5SDimitry Andric continue; 27105f757f3fSDimitry Andric IRBuilder<>(RI).CreateStackRestore(SavedPtr); 27110b57cec5SDimitry Andric } 27120b57cec5SDimitry Andric } 27130b57cec5SDimitry Andric 27140b57cec5SDimitry Andric // If we are inlining for an invoke instruction, we must make sure to rewrite 27150b57cec5SDimitry Andric // any call instructions into invoke instructions. This is sensitive to which 27160b57cec5SDimitry Andric // funclet pads were top-level in the inlinee, so must be done before 27170b57cec5SDimitry Andric // rewriting the "parent pad" links. 27185ffd83dbSDimitry Andric if (auto *II = dyn_cast<InvokeInst>(&CB)) { 27190b57cec5SDimitry Andric BasicBlock *UnwindDest = II->getUnwindDest(); 27200b57cec5SDimitry Andric Instruction *FirstNonPHI = UnwindDest->getFirstNonPHI(); 27210b57cec5SDimitry Andric if (isa<LandingPadInst>(FirstNonPHI)) { 27220b57cec5SDimitry Andric HandleInlinedLandingPad(II, &*FirstNewBlock, InlinedFunctionInfo); 27230b57cec5SDimitry Andric } else { 27240b57cec5SDimitry Andric HandleInlinedEHPad(II, &*FirstNewBlock, InlinedFunctionInfo); 27250b57cec5SDimitry Andric } 27260b57cec5SDimitry Andric } 27270b57cec5SDimitry Andric 27280b57cec5SDimitry Andric // Update the lexical scopes of the new funclets and callsites. 27290b57cec5SDimitry Andric // Anything that had 'none' as its parent is now nested inside the callsite's 27300b57cec5SDimitry Andric // EHPad. 27310b57cec5SDimitry Andric if (CallSiteEHPad) { 27320b57cec5SDimitry Andric for (Function::iterator BB = FirstNewBlock->getIterator(), 27330b57cec5SDimitry Andric E = Caller->end(); 27340b57cec5SDimitry Andric BB != E; ++BB) { 2735972a253aSDimitry Andric // Add bundle operands to inlined call sites. 2736972a253aSDimitry Andric PropagateOperandBundles(BB, CallSiteEHPad); 27370b57cec5SDimitry Andric 27380b57cec5SDimitry Andric // It is problematic if the inlinee has a cleanupret which unwinds to 27390b57cec5SDimitry Andric // caller and we inline it into a call site which doesn't unwind but into 27400b57cec5SDimitry Andric // an EH pad that does. Such an edge must be dynamically unreachable. 27410b57cec5SDimitry Andric // As such, we replace the cleanupret with unreachable. 27420b57cec5SDimitry Andric if (auto *CleanupRet = dyn_cast<CleanupReturnInst>(BB->getTerminator())) 27430b57cec5SDimitry Andric if (CleanupRet->unwindsToCaller() && EHPadForCallUnwindsLocally) 2744fe6060f1SDimitry Andric changeToUnreachable(CleanupRet); 27450b57cec5SDimitry Andric 27460b57cec5SDimitry Andric Instruction *I = BB->getFirstNonPHI(); 27470b57cec5SDimitry Andric if (!I->isEHPad()) 27480b57cec5SDimitry Andric continue; 27490b57cec5SDimitry Andric 27500b57cec5SDimitry Andric if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(I)) { 27510b57cec5SDimitry Andric if (isa<ConstantTokenNone>(CatchSwitch->getParentPad())) 27520b57cec5SDimitry Andric CatchSwitch->setParentPad(CallSiteEHPad); 27530b57cec5SDimitry Andric } else { 27540b57cec5SDimitry Andric auto *FPI = cast<FuncletPadInst>(I); 27550b57cec5SDimitry Andric if (isa<ConstantTokenNone>(FPI->getParentPad())) 27560b57cec5SDimitry Andric FPI->setParentPad(CallSiteEHPad); 27570b57cec5SDimitry Andric } 27580b57cec5SDimitry Andric } 27590b57cec5SDimitry Andric } 27600b57cec5SDimitry Andric 27610b57cec5SDimitry Andric if (InlinedDeoptimizeCalls) { 27620b57cec5SDimitry Andric // We need to at least remove the deoptimizing returns from the Return set, 27630b57cec5SDimitry Andric // so that the control flow from those returns does not get merged into the 27640b57cec5SDimitry Andric // caller (but terminate it instead). If the caller's return type does not 27650b57cec5SDimitry Andric // match the callee's return type, we also need to change the return type of 27660b57cec5SDimitry Andric // the intrinsic. 27675ffd83dbSDimitry Andric if (Caller->getReturnType() == CB.getType()) { 2768e8d8bef9SDimitry Andric llvm::erase_if(Returns, [](ReturnInst *RI) { 27690b57cec5SDimitry Andric return RI->getParent()->getTerminatingDeoptimizeCall() != nullptr; 27700b57cec5SDimitry Andric }); 27710b57cec5SDimitry Andric } else { 27720b57cec5SDimitry Andric SmallVector<ReturnInst *, 8> NormalReturns; 27730b57cec5SDimitry Andric Function *NewDeoptIntrinsic = Intrinsic::getDeclaration( 27740b57cec5SDimitry Andric Caller->getParent(), Intrinsic::experimental_deoptimize, 27750b57cec5SDimitry Andric {Caller->getReturnType()}); 27760b57cec5SDimitry Andric 27770b57cec5SDimitry Andric for (ReturnInst *RI : Returns) { 27780b57cec5SDimitry Andric CallInst *DeoptCall = RI->getParent()->getTerminatingDeoptimizeCall(); 27790b57cec5SDimitry Andric if (!DeoptCall) { 27800b57cec5SDimitry Andric NormalReturns.push_back(RI); 27810b57cec5SDimitry Andric continue; 27820b57cec5SDimitry Andric } 27830b57cec5SDimitry Andric 27840b57cec5SDimitry Andric // The calling convention on the deoptimize call itself may be bogus, 27850b57cec5SDimitry Andric // since the code we're inlining may have undefined behavior (and may 27860b57cec5SDimitry Andric // never actually execute at runtime); but all 27870b57cec5SDimitry Andric // @llvm.experimental.deoptimize declarations have to have the same 27880b57cec5SDimitry Andric // calling convention in a well-formed module. 27890b57cec5SDimitry Andric auto CallingConv = DeoptCall->getCalledFunction()->getCallingConv(); 27900b57cec5SDimitry Andric NewDeoptIntrinsic->setCallingConv(CallingConv); 27910b57cec5SDimitry Andric auto *CurBB = RI->getParent(); 27920b57cec5SDimitry Andric RI->eraseFromParent(); 27930b57cec5SDimitry Andric 2794e8d8bef9SDimitry Andric SmallVector<Value *, 4> CallArgs(DeoptCall->args()); 27950b57cec5SDimitry Andric 27960b57cec5SDimitry Andric SmallVector<OperandBundleDef, 1> OpBundles; 27970b57cec5SDimitry Andric DeoptCall->getOperandBundlesAsDefs(OpBundles); 2798fe6060f1SDimitry Andric auto DeoptAttributes = DeoptCall->getAttributes(); 27990b57cec5SDimitry Andric DeoptCall->eraseFromParent(); 28000b57cec5SDimitry Andric assert(!OpBundles.empty() && 28010b57cec5SDimitry Andric "Expected at least the deopt operand bundle"); 28020b57cec5SDimitry Andric 28030b57cec5SDimitry Andric IRBuilder<> Builder(CurBB); 28040b57cec5SDimitry Andric CallInst *NewDeoptCall = 28050b57cec5SDimitry Andric Builder.CreateCall(NewDeoptIntrinsic, CallArgs, OpBundles); 28060b57cec5SDimitry Andric NewDeoptCall->setCallingConv(CallingConv); 2807fe6060f1SDimitry Andric NewDeoptCall->setAttributes(DeoptAttributes); 28080b57cec5SDimitry Andric if (NewDeoptCall->getType()->isVoidTy()) 28090b57cec5SDimitry Andric Builder.CreateRetVoid(); 28100b57cec5SDimitry Andric else 28110b57cec5SDimitry Andric Builder.CreateRet(NewDeoptCall); 28125f757f3fSDimitry Andric // Since the ret type is changed, remove the incompatible attributes. 28135f757f3fSDimitry Andric NewDeoptCall->removeRetAttrs( 28145f757f3fSDimitry Andric AttributeFuncs::typeIncompatible(NewDeoptCall->getType())); 28150b57cec5SDimitry Andric } 28160b57cec5SDimitry Andric 28170b57cec5SDimitry Andric // Leave behind the normal returns so we can merge control flow. 28180b57cec5SDimitry Andric std::swap(Returns, NormalReturns); 28190b57cec5SDimitry Andric } 28200b57cec5SDimitry Andric } 28210b57cec5SDimitry Andric 28220b57cec5SDimitry Andric // Handle any inlined musttail call sites. In order for a new call site to be 28230b57cec5SDimitry Andric // musttail, the source of the clone and the inlined call site must have been 28240b57cec5SDimitry Andric // musttail. Therefore it's safe to return without merging control into the 28250b57cec5SDimitry Andric // phi below. 28260b57cec5SDimitry Andric if (InlinedMustTailCalls) { 28270b57cec5SDimitry Andric // Check if we need to bitcast the result of any musttail calls. 28280b57cec5SDimitry Andric Type *NewRetTy = Caller->getReturnType(); 28295ffd83dbSDimitry Andric bool NeedBitCast = !CB.use_empty() && CB.getType() != NewRetTy; 28300b57cec5SDimitry Andric 28310b57cec5SDimitry Andric // Handle the returns preceded by musttail calls separately. 28320b57cec5SDimitry Andric SmallVector<ReturnInst *, 8> NormalReturns; 28330b57cec5SDimitry Andric for (ReturnInst *RI : Returns) { 28340b57cec5SDimitry Andric CallInst *ReturnedMustTail = 28350b57cec5SDimitry Andric RI->getParent()->getTerminatingMustTailCall(); 28360b57cec5SDimitry Andric if (!ReturnedMustTail) { 28370b57cec5SDimitry Andric NormalReturns.push_back(RI); 28380b57cec5SDimitry Andric continue; 28390b57cec5SDimitry Andric } 28400b57cec5SDimitry Andric if (!NeedBitCast) 28410b57cec5SDimitry Andric continue; 28420b57cec5SDimitry Andric 28430b57cec5SDimitry Andric // Delete the old return and any preceding bitcast. 28440b57cec5SDimitry Andric BasicBlock *CurBB = RI->getParent(); 28450b57cec5SDimitry Andric auto *OldCast = dyn_cast_or_null<BitCastInst>(RI->getReturnValue()); 28460b57cec5SDimitry Andric RI->eraseFromParent(); 28470b57cec5SDimitry Andric if (OldCast) 28480b57cec5SDimitry Andric OldCast->eraseFromParent(); 28490b57cec5SDimitry Andric 28500b57cec5SDimitry Andric // Insert a new bitcast and return with the right type. 28510b57cec5SDimitry Andric IRBuilder<> Builder(CurBB); 28520b57cec5SDimitry Andric Builder.CreateRet(Builder.CreateBitCast(ReturnedMustTail, NewRetTy)); 28530b57cec5SDimitry Andric } 28540b57cec5SDimitry Andric 28550b57cec5SDimitry Andric // Leave behind the normal returns so we can merge control flow. 28560b57cec5SDimitry Andric std::swap(Returns, NormalReturns); 28570b57cec5SDimitry Andric } 28580b57cec5SDimitry Andric 28590b57cec5SDimitry Andric // Now that all of the transforms on the inlined code have taken place but 28600b57cec5SDimitry Andric // before we splice the inlined code into the CFG and lose track of which 28610b57cec5SDimitry Andric // blocks were actually inlined, collect the call sites. We only do this if 28620b57cec5SDimitry Andric // call graph updates weren't requested, as those provide value handle based 2863fe6060f1SDimitry Andric // tracking of inlined call sites instead. Calls to intrinsics are not 2864fe6060f1SDimitry Andric // collected because they are not inlineable. 286506c3fb27SDimitry Andric if (InlinedFunctionInfo.ContainsCalls) { 28660b57cec5SDimitry Andric // Otherwise just collect the raw call sites that were inlined. 28670b57cec5SDimitry Andric for (BasicBlock &NewBB : 28680b57cec5SDimitry Andric make_range(FirstNewBlock->getIterator(), Caller->end())) 28690b57cec5SDimitry Andric for (Instruction &I : NewBB) 28705ffd83dbSDimitry Andric if (auto *CB = dyn_cast<CallBase>(&I)) 2871fe6060f1SDimitry Andric if (!(CB->getCalledFunction() && 2872fe6060f1SDimitry Andric CB->getCalledFunction()->isIntrinsic())) 28735ffd83dbSDimitry Andric IFI.InlinedCallSites.push_back(CB); 28740b57cec5SDimitry Andric } 28750b57cec5SDimitry Andric 28760b57cec5SDimitry Andric // If we cloned in _exactly one_ basic block, and if that block ends in a 28770b57cec5SDimitry Andric // return instruction, we splice the body of the inlined callee directly into 28780b57cec5SDimitry Andric // the calling basic block. 28790b57cec5SDimitry Andric if (Returns.size() == 1 && std::distance(FirstNewBlock, Caller->end()) == 1) { 28800b57cec5SDimitry Andric // Move all of the instructions right before the call. 2881bdd1243dSDimitry Andric OrigBB->splice(CB.getIterator(), &*FirstNewBlock, FirstNewBlock->begin(), 2882bdd1243dSDimitry Andric FirstNewBlock->end()); 28830b57cec5SDimitry Andric // Remove the cloned basic block. 2884bdd1243dSDimitry Andric Caller->back().eraseFromParent(); 28850b57cec5SDimitry Andric 28860b57cec5SDimitry Andric // If the call site was an invoke instruction, add a branch to the normal 28870b57cec5SDimitry Andric // destination. 28885ffd83dbSDimitry Andric if (InvokeInst *II = dyn_cast<InvokeInst>(&CB)) { 28890fca6ea1SDimitry Andric BranchInst *NewBr = BranchInst::Create(II->getNormalDest(), CB.getIterator()); 28900b57cec5SDimitry Andric NewBr->setDebugLoc(Returns[0]->getDebugLoc()); 28910b57cec5SDimitry Andric } 28920b57cec5SDimitry Andric 28930b57cec5SDimitry Andric // If the return instruction returned a value, replace uses of the call with 28940b57cec5SDimitry Andric // uses of the returned value. 28955ffd83dbSDimitry Andric if (!CB.use_empty()) { 28960b57cec5SDimitry Andric ReturnInst *R = Returns[0]; 28975ffd83dbSDimitry Andric if (&CB == R->getReturnValue()) 289806c3fb27SDimitry Andric CB.replaceAllUsesWith(PoisonValue::get(CB.getType())); 28990b57cec5SDimitry Andric else 29005ffd83dbSDimitry Andric CB.replaceAllUsesWith(R->getReturnValue()); 29010b57cec5SDimitry Andric } 29020b57cec5SDimitry Andric // Since we are now done with the Call/Invoke, we can delete it. 29035ffd83dbSDimitry Andric CB.eraseFromParent(); 29040b57cec5SDimitry Andric 29050b57cec5SDimitry Andric // Since we are now done with the return instruction, delete it also. 29060b57cec5SDimitry Andric Returns[0]->eraseFromParent(); 29070b57cec5SDimitry Andric 2908bdd1243dSDimitry Andric if (MergeAttributes) 2909bdd1243dSDimitry Andric AttributeFuncs::mergeAttributesForInlining(*Caller, *CalledFunc); 2910bdd1243dSDimitry Andric 29110b57cec5SDimitry Andric // We are now done with the inlining. 29125ffd83dbSDimitry Andric return InlineResult::success(); 29130b57cec5SDimitry Andric } 29140b57cec5SDimitry Andric 29150b57cec5SDimitry Andric // Otherwise, we have the normal case, of more than one block to inline or 29160b57cec5SDimitry Andric // multiple return sites. 29170b57cec5SDimitry Andric 29180b57cec5SDimitry Andric // We want to clone the entire callee function into the hole between the 29190b57cec5SDimitry Andric // "starter" and "ender" blocks. How we accomplish this depends on whether 29200b57cec5SDimitry Andric // this is an invoke instruction or a call instruction. 29210b57cec5SDimitry Andric BasicBlock *AfterCallBB; 29220b57cec5SDimitry Andric BranchInst *CreatedBranchToNormalDest = nullptr; 29235ffd83dbSDimitry Andric if (InvokeInst *II = dyn_cast<InvokeInst>(&CB)) { 29240b57cec5SDimitry Andric 29250b57cec5SDimitry Andric // Add an unconditional branch to make this look like the CallInst case... 29260fca6ea1SDimitry Andric CreatedBranchToNormalDest = BranchInst::Create(II->getNormalDest(), CB.getIterator()); 29270b57cec5SDimitry Andric 29280b57cec5SDimitry Andric // Split the basic block. This guarantees that no PHI nodes will have to be 29290b57cec5SDimitry Andric // updated due to new incoming edges, and make the invoke case more 29300b57cec5SDimitry Andric // symmetric to the call case. 29310b57cec5SDimitry Andric AfterCallBB = 29320b57cec5SDimitry Andric OrigBB->splitBasicBlock(CreatedBranchToNormalDest->getIterator(), 29330b57cec5SDimitry Andric CalledFunc->getName() + ".exit"); 29340b57cec5SDimitry Andric 29350b57cec5SDimitry Andric } else { // It's a call 29360b57cec5SDimitry Andric // If this is a call instruction, we need to split the basic block that 29370b57cec5SDimitry Andric // the call lives in. 29380b57cec5SDimitry Andric // 29395ffd83dbSDimitry Andric AfterCallBB = OrigBB->splitBasicBlock(CB.getIterator(), 29400b57cec5SDimitry Andric CalledFunc->getName() + ".exit"); 29410b57cec5SDimitry Andric } 29420b57cec5SDimitry Andric 29430b57cec5SDimitry Andric if (IFI.CallerBFI) { 29440b57cec5SDimitry Andric // Copy original BB's block frequency to AfterCallBB 29455f757f3fSDimitry Andric IFI.CallerBFI->setBlockFreq(AfterCallBB, 29465f757f3fSDimitry Andric IFI.CallerBFI->getBlockFreq(OrigBB)); 29470b57cec5SDimitry Andric } 29480b57cec5SDimitry Andric 29490b57cec5SDimitry Andric // Change the branch that used to go to AfterCallBB to branch to the first 29500b57cec5SDimitry Andric // basic block of the inlined function. 29510b57cec5SDimitry Andric // 29520b57cec5SDimitry Andric Instruction *Br = OrigBB->getTerminator(); 29530b57cec5SDimitry Andric assert(Br && Br->getOpcode() == Instruction::Br && 29540b57cec5SDimitry Andric "splitBasicBlock broken!"); 29550b57cec5SDimitry Andric Br->setOperand(0, &*FirstNewBlock); 29560b57cec5SDimitry Andric 29570b57cec5SDimitry Andric // Now that the function is correct, make it a little bit nicer. In 29580b57cec5SDimitry Andric // particular, move the basic blocks inserted from the end of the function 29590b57cec5SDimitry Andric // into the space made by splitting the source basic block. 2960bdd1243dSDimitry Andric Caller->splice(AfterCallBB->getIterator(), Caller, FirstNewBlock, 29610b57cec5SDimitry Andric Caller->end()); 29620b57cec5SDimitry Andric 29630b57cec5SDimitry Andric // Handle all of the return instructions that we just cloned in, and eliminate 29640b57cec5SDimitry Andric // any users of the original call/invoke instruction. 29650b57cec5SDimitry Andric Type *RTy = CalledFunc->getReturnType(); 29660b57cec5SDimitry Andric 29670b57cec5SDimitry Andric PHINode *PHI = nullptr; 29680b57cec5SDimitry Andric if (Returns.size() > 1) { 29690b57cec5SDimitry Andric // The PHI node should go at the front of the new basic block to merge all 29700b57cec5SDimitry Andric // possible incoming values. 29715ffd83dbSDimitry Andric if (!CB.use_empty()) { 29725f757f3fSDimitry Andric PHI = PHINode::Create(RTy, Returns.size(), CB.getName()); 29735f757f3fSDimitry Andric PHI->insertBefore(AfterCallBB->begin()); 29740b57cec5SDimitry Andric // Anything that used the result of the function call should now use the 29750b57cec5SDimitry Andric // PHI node as their operand. 29765ffd83dbSDimitry Andric CB.replaceAllUsesWith(PHI); 29770b57cec5SDimitry Andric } 29780b57cec5SDimitry Andric 29790b57cec5SDimitry Andric // Loop over all of the return instructions adding entries to the PHI node 29800b57cec5SDimitry Andric // as appropriate. 29810b57cec5SDimitry Andric if (PHI) { 29820fca6ea1SDimitry Andric for (ReturnInst *RI : Returns) { 29830b57cec5SDimitry Andric assert(RI->getReturnValue()->getType() == PHI->getType() && 29840b57cec5SDimitry Andric "Ret value not consistent in function!"); 29850b57cec5SDimitry Andric PHI->addIncoming(RI->getReturnValue(), RI->getParent()); 29860b57cec5SDimitry Andric } 29870b57cec5SDimitry Andric } 29880b57cec5SDimitry Andric 29890b57cec5SDimitry Andric // Add a branch to the merge points and remove return instructions. 29900b57cec5SDimitry Andric DebugLoc Loc; 29910fca6ea1SDimitry Andric for (ReturnInst *RI : Returns) { 29920fca6ea1SDimitry Andric BranchInst *BI = BranchInst::Create(AfterCallBB, RI->getIterator()); 29930b57cec5SDimitry Andric Loc = RI->getDebugLoc(); 29940b57cec5SDimitry Andric BI->setDebugLoc(Loc); 29950b57cec5SDimitry Andric RI->eraseFromParent(); 29960b57cec5SDimitry Andric } 29970b57cec5SDimitry Andric // We need to set the debug location to *somewhere* inside the 29980b57cec5SDimitry Andric // inlined function. The line number may be nonsensical, but the 29990b57cec5SDimitry Andric // instruction will at least be associated with the right 30000b57cec5SDimitry Andric // function. 30010b57cec5SDimitry Andric if (CreatedBranchToNormalDest) 30020b57cec5SDimitry Andric CreatedBranchToNormalDest->setDebugLoc(Loc); 30030b57cec5SDimitry Andric } else if (!Returns.empty()) { 30040b57cec5SDimitry Andric // Otherwise, if there is exactly one return value, just replace anything 30050b57cec5SDimitry Andric // using the return value of the call with the computed value. 30065ffd83dbSDimitry Andric if (!CB.use_empty()) { 30075ffd83dbSDimitry Andric if (&CB == Returns[0]->getReturnValue()) 300806c3fb27SDimitry Andric CB.replaceAllUsesWith(PoisonValue::get(CB.getType())); 30090b57cec5SDimitry Andric else 30105ffd83dbSDimitry Andric CB.replaceAllUsesWith(Returns[0]->getReturnValue()); 30110b57cec5SDimitry Andric } 30120b57cec5SDimitry Andric 30130b57cec5SDimitry Andric // Update PHI nodes that use the ReturnBB to use the AfterCallBB. 30140b57cec5SDimitry Andric BasicBlock *ReturnBB = Returns[0]->getParent(); 30150b57cec5SDimitry Andric ReturnBB->replaceAllUsesWith(AfterCallBB); 30160b57cec5SDimitry Andric 30170b57cec5SDimitry Andric // Splice the code from the return block into the block that it will return 30180b57cec5SDimitry Andric // to, which contains the code that was after the call. 3019bdd1243dSDimitry Andric AfterCallBB->splice(AfterCallBB->begin(), ReturnBB); 30200b57cec5SDimitry Andric 30210b57cec5SDimitry Andric if (CreatedBranchToNormalDest) 30220b57cec5SDimitry Andric CreatedBranchToNormalDest->setDebugLoc(Returns[0]->getDebugLoc()); 30230b57cec5SDimitry Andric 30240b57cec5SDimitry Andric // Delete the return instruction now and empty ReturnBB now. 30250b57cec5SDimitry Andric Returns[0]->eraseFromParent(); 30260b57cec5SDimitry Andric ReturnBB->eraseFromParent(); 30275ffd83dbSDimitry Andric } else if (!CB.use_empty()) { 30280b57cec5SDimitry Andric // No returns, but something is using the return value of the call. Just 30290b57cec5SDimitry Andric // nuke the result. 3030fcaf7f86SDimitry Andric CB.replaceAllUsesWith(PoisonValue::get(CB.getType())); 30310b57cec5SDimitry Andric } 30320b57cec5SDimitry Andric 30330b57cec5SDimitry Andric // Since we are now done with the Call/Invoke, we can delete it. 30345ffd83dbSDimitry Andric CB.eraseFromParent(); 30350b57cec5SDimitry Andric 30360b57cec5SDimitry Andric // If we inlined any musttail calls and the original return is now 30370b57cec5SDimitry Andric // unreachable, delete it. It can only contain a bitcast and ret. 3038e8d8bef9SDimitry Andric if (InlinedMustTailCalls && pred_empty(AfterCallBB)) 30390b57cec5SDimitry Andric AfterCallBB->eraseFromParent(); 30400b57cec5SDimitry Andric 30410b57cec5SDimitry Andric // We should always be able to fold the entry block of the function into the 30420b57cec5SDimitry Andric // single predecessor of the block... 30430b57cec5SDimitry Andric assert(cast<BranchInst>(Br)->isUnconditional() && "splitBasicBlock broken!"); 30440b57cec5SDimitry Andric BasicBlock *CalleeEntry = cast<BranchInst>(Br)->getSuccessor(0); 30450b57cec5SDimitry Andric 30460b57cec5SDimitry Andric // Splice the code entry block into calling block, right before the 30470b57cec5SDimitry Andric // unconditional branch. 30480b57cec5SDimitry Andric CalleeEntry->replaceAllUsesWith(OrigBB); // Update PHI nodes 3049bdd1243dSDimitry Andric OrigBB->splice(Br->getIterator(), CalleeEntry); 30500b57cec5SDimitry Andric 30510b57cec5SDimitry Andric // Remove the unconditional branch. 3052bdd1243dSDimitry Andric Br->eraseFromParent(); 30530b57cec5SDimitry Andric 30540b57cec5SDimitry Andric // Now we can remove the CalleeEntry block, which is now empty. 3055bdd1243dSDimitry Andric CalleeEntry->eraseFromParent(); 30560b57cec5SDimitry Andric 30570b57cec5SDimitry Andric // If we inserted a phi node, check to see if it has a single value (e.g. all 30580b57cec5SDimitry Andric // the entries are the same or undef). If so, remove the PHI so it doesn't 30590b57cec5SDimitry Andric // block other optimizations. 30600b57cec5SDimitry Andric if (PHI) { 30610b57cec5SDimitry Andric AssumptionCache *AC = 30625ffd83dbSDimitry Andric IFI.GetAssumptionCache ? &IFI.GetAssumptionCache(*Caller) : nullptr; 30630fca6ea1SDimitry Andric auto &DL = Caller->getDataLayout(); 306481ad6265SDimitry Andric if (Value *V = simplifyInstruction(PHI, {DL, nullptr, nullptr, AC})) { 30650b57cec5SDimitry Andric PHI->replaceAllUsesWith(V); 30660b57cec5SDimitry Andric PHI->eraseFromParent(); 30670b57cec5SDimitry Andric } 30680b57cec5SDimitry Andric } 30690b57cec5SDimitry Andric 3070bdd1243dSDimitry Andric if (MergeAttributes) 3071bdd1243dSDimitry Andric AttributeFuncs::mergeAttributesForInlining(*Caller, *CalledFunc); 3072bdd1243dSDimitry Andric 30735ffd83dbSDimitry Andric return InlineResult::success(); 30740b57cec5SDimitry Andric } 3075