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