LCOV - code coverage report
Current view: top level - lib/CodeGen - SjLjEHPrepare.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 207 220 94.1 %
Date: 2017-09-14 15:23:50 Functions: 15 17 88.2 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : //===- SjLjEHPrepare.cpp - Eliminate Invoke & Unwind instructions ---------===//
       2             : //
       3             : //                     The LLVM Compiler Infrastructure
       4             : //
       5             : // This file is distributed under the University of Illinois Open Source
       6             : // License. See LICENSE.TXT for details.
       7             : //
       8             : //===----------------------------------------------------------------------===//
       9             : //
      10             : // This transformation is designed for use by code generators which use SjLj
      11             : // based exception handling.
      12             : //
      13             : //===----------------------------------------------------------------------===//
      14             : 
      15             : #include "llvm/ADT/SetVector.h"
      16             : #include "llvm/ADT/SmallPtrSet.h"
      17             : #include "llvm/ADT/SmallVector.h"
      18             : #include "llvm/ADT/Statistic.h"
      19             : #include "llvm/CodeGen/Passes.h"
      20             : #include "llvm/IR/Constants.h"
      21             : #include "llvm/IR/DataLayout.h"
      22             : #include "llvm/IR/DerivedTypes.h"
      23             : #include "llvm/IR/IRBuilder.h"
      24             : #include "llvm/IR/Instructions.h"
      25             : #include "llvm/IR/Intrinsics.h"
      26             : #include "llvm/IR/Module.h"
      27             : #include "llvm/Pass.h"
      28             : #include "llvm/Support/Debug.h"
      29             : #include "llvm/Support/raw_ostream.h"
      30             : #include "llvm/Transforms/Utils/Local.h"
      31             : using namespace llvm;
      32             : 
      33             : #define DEBUG_TYPE "sjljehprepare"
      34             : 
      35             : STATISTIC(NumInvokes, "Number of invokes replaced");
      36             : STATISTIC(NumSpilled, "Number of registers live across unwind edges");
      37             : 
      38             : namespace {
      39        1402 : class SjLjEHPrepare : public FunctionPass {
      40             :   Type *doubleUnderDataTy;
      41             :   Type *doubleUnderJBufTy;
      42             :   Type *FunctionContextTy;
      43             :   Constant *RegisterFn;
      44             :   Constant *UnregisterFn;
      45             :   Constant *BuiltinSetupDispatchFn;
      46             :   Constant *FrameAddrFn;
      47             :   Constant *StackAddrFn;
      48             :   Constant *StackRestoreFn;
      49             :   Constant *LSDAAddrFn;
      50             :   Constant *CallSiteFn;
      51             :   Constant *FuncCtxFn;
      52             :   AllocaInst *FuncCtx;
      53             : 
      54             : public:
      55             :   static char ID; // Pass identification, replacement for typeid
      56        1406 :   explicit SjLjEHPrepare() : FunctionPass(ID) {}
      57             :   bool doInitialization(Module &M) override;
      58             :   bool runOnFunction(Function &F) override;
      59             : 
      60         700 :   void getAnalysisUsage(AnalysisUsage &AU) const override {}
      61           0 :   StringRef getPassName() const override {
      62           0 :     return "SJLJ Exception Handling preparation";
      63             :   }
      64             : 
      65             : private:
      66             :   bool setupEntryBlockAndCallSites(Function &F);
      67             :   bool undoSwiftErrorSelect(Function &F);
      68             :   void substituteLPadValues(LandingPadInst *LPI, Value *ExnVal, Value *SelVal);
      69             :   Value *setupFunctionContext(Function &F, ArrayRef<LandingPadInst *> LPads);
      70             :   void lowerIncomingArguments(Function &F);
      71             :   void lowerAcrossUnwindEdges(Function &F, ArrayRef<InvokeInst *> Invokes);
      72             :   void insertCallSiteStore(Instruction *I, int Number);
      73             : };
      74             : } // end anonymous namespace
      75             : 
      76             : char SjLjEHPrepare::ID = 0;
      77       45740 : INITIALIZE_PASS(SjLjEHPrepare, DEBUG_TYPE, "Prepare SjLj exceptions",
      78             :                 false, false)
      79             : 
      80             : // Public Interface To the SjLjEHPrepare pass.
      81        1402 : FunctionPass *llvm::createSjLjEHPreparePass() { return new SjLjEHPrepare(); }
      82             : // doInitialization - Set up decalarations and types needed to process
      83             : // exceptions.
      84         700 : bool SjLjEHPrepare::doInitialization(Module &M) {
      85             :   // Build the function context structure.
      86             :   // builtin_setjmp uses a five word jbuf
      87         700 :   Type *VoidPtrTy = Type::getInt8PtrTy(M.getContext());
      88         700 :   Type *Int32Ty = Type::getInt32Ty(M.getContext());
      89         700 :   doubleUnderDataTy = ArrayType::get(Int32Ty, 4);
      90         700 :   doubleUnderJBufTy = ArrayType::get(VoidPtrTy, 5);
      91         700 :   FunctionContextTy = StructType::get(VoidPtrTy,         // __prev
      92             :                                       Int32Ty,           // call_site
      93             :                                       doubleUnderDataTy, // __data
      94             :                                       VoidPtrTy,         // __personality
      95             :                                       VoidPtrTy,         // __lsda
      96             :                                       doubleUnderJBufTy  // __jbuf
      97             :                                       );
      98             : 
      99         700 :   return true;
     100             : }
     101             : 
     102             : /// insertCallSiteStore - Insert a store of the call-site value to the
     103             : /// function context
     104         926 : void SjLjEHPrepare::insertCallSiteStore(Instruction *I, int Number) {
     105        1852 :   IRBuilder<> Builder(I);
     106             : 
     107             :   // Get a reference to the call_site field.
     108         926 :   Type *Int32Ty = Type::getInt32Ty(I->getContext());
     109         926 :   Value *Zero = ConstantInt::get(Int32Ty, 0);
     110         926 :   Value *One = ConstantInt::get(Int32Ty, 1);
     111         926 :   Value *Idxs[2] = { Zero, One };
     112             :   Value *CallSite =
     113        1852 :       Builder.CreateGEP(FunctionContextTy, FuncCtx, Idxs, "call_site");
     114             : 
     115             :   // Insert a store of the call-site number
     116             :   ConstantInt *CallSiteNoC =
     117         926 :       ConstantInt::get(Type::getInt32Ty(I->getContext()), Number);
     118         926 :   Builder.CreateStore(CallSiteNoC, CallSite, true /*volatile*/);
     119         926 : }
     120             : 
     121             : /// MarkBlocksLiveIn - Insert BB and all of its predecessors into LiveBBs until
     122             : /// we reach blocks we've already seen.
     123         607 : static void MarkBlocksLiveIn(BasicBlock *BB,
     124             :                              SmallPtrSetImpl<BasicBlock *> &LiveBBs) {
     125         607 :   if (!LiveBBs.insert(BB).second)
     126         322 :     return; // already been here.
     127             : 
     128         570 :   df_iterator_default_set<BasicBlock*> Visited;
     129             : 
     130        8839 :   for (BasicBlock *B : inverse_depth_first_ext(BB, Visited))
     131        3707 :     LiveBBs.insert(B);
     132             : 
     133             : }
     134             : 
     135             : /// substituteLPadValues - Substitute the values returned by the landingpad
     136             : /// instruction with those returned by the personality function.
     137         123 : void SjLjEHPrepare::substituteLPadValues(LandingPadInst *LPI, Value *ExnVal,
     138             :                                          Value *SelVal) {
     139         376 :   SmallVector<Value *, 8> UseWorkList(LPI->user_begin(), LPI->user_end());
     140         324 :   while (!UseWorkList.empty()) {
     141         201 :     Value *Val = UseWorkList.pop_back_val();
     142         194 :     auto *EVI = dyn_cast<ExtractValueInst>(Val);
     143           7 :     if (!EVI)
     144             :       continue;
     145         194 :     if (EVI->getNumIndices() != 1)
     146             :       continue;
     147         194 :     if (*EVI->idx_begin() == 0)
     148         101 :       EVI->replaceAllUsesWith(ExnVal);
     149          93 :     else if (*EVI->idx_begin() == 1)
     150          93 :       EVI->replaceAllUsesWith(SelVal);
     151         388 :     if (EVI->use_empty())
     152         194 :       EVI->eraseFromParent();
     153             :   }
     154             : 
     155         246 :   if (LPI->use_empty())
     156         116 :     return;
     157             : 
     158             :   // There are still some uses of LPI. Construct an aggregate with the exception
     159             :   // values and replace the LPI with that aggregate.
     160           7 :   Type *LPadType = LPI->getType();
     161           7 :   Value *LPadVal = UndefValue::get(LPadType);
     162           7 :   auto *SelI = cast<Instruction>(SelVal);
     163          28 :   IRBuilder<> Builder(SelI->getParent(), std::next(SelI->getIterator()));
     164          14 :   LPadVal = Builder.CreateInsertValue(LPadVal, ExnVal, 0, "lpad.val");
     165          14 :   LPadVal = Builder.CreateInsertValue(LPadVal, SelVal, 1, "lpad.val");
     166             : 
     167           7 :   LPI->replaceAllUsesWith(LPadVal);
     168             : }
     169             : 
     170             : /// setupFunctionContext - Allocate the function context on the stack and fill
     171             : /// it with all of the data that we know at this point.
     172          31 : Value *SjLjEHPrepare::setupFunctionContext(Function &F,
     173             :                                            ArrayRef<LandingPadInst *> LPads) {
     174          31 :   BasicBlock *EntryBB = &F.front();
     175             : 
     176             :   // Create an alloca for the incoming jump buffer ptr and the new jump buffer
     177             :   // that needs to be restored on all exits from the function. This is an alloca
     178             :   // because the value needs to be added to the global context list.
     179          31 :   auto &DL = F.getParent()->getDataLayout();
     180          31 :   unsigned Align = DL.getPrefTypeAlignment(FunctionContextTy);
     181          93 :   FuncCtx = new AllocaInst(FunctionContextTy, DL.getAllocaAddrSpace(),
     182          62 :                            nullptr, Align, "fn_context", &EntryBB->front());
     183             : 
     184             :   // Fill in the function context structure.
     185         185 :   for (LandingPadInst *LPI : LPads) {
     186             :     IRBuilder<> Builder(LPI->getParent(),
     187         369 :                         LPI->getParent()->getFirstInsertionPt());
     188             : 
     189             :     // Reference the __data field.
     190             :     Value *FCData =
     191         123 :         Builder.CreateConstGEP2_32(FunctionContextTy, FuncCtx, 0, 2, "__data");
     192             : 
     193             :     // The exception values come back in context->__data[0].
     194         246 :     Value *ExceptionAddr = Builder.CreateConstGEP2_32(doubleUnderDataTy, FCData,
     195         123 :                                                       0, 0, "exception_gep");
     196         123 :     Value *ExnVal = Builder.CreateLoad(ExceptionAddr, true, "exn_val");
     197         369 :     ExnVal = Builder.CreateIntToPtr(ExnVal, Builder.getInt8PtrTy());
     198             : 
     199         246 :     Value *SelectorAddr = Builder.CreateConstGEP2_32(doubleUnderDataTy, FCData,
     200         123 :                                                      0, 1, "exn_selector_gep");
     201         123 :     Value *SelVal = Builder.CreateLoad(SelectorAddr, true, "exn_selector_val");
     202             : 
     203         123 :     substituteLPadValues(LPI, ExnVal, SelVal);
     204             :   }
     205             : 
     206             :   // Personality function
     207          93 :   IRBuilder<> Builder(EntryBB->getTerminator());
     208          31 :   Value *PersonalityFn = F.getPersonalityFn();
     209          93 :   Value *PersonalityFieldPtr = Builder.CreateConstGEP2_32(
     210          62 :       FunctionContextTy, FuncCtx, 0, 3, "pers_fn_gep");
     211          62 :   Builder.CreateStore(
     212          62 :       Builder.CreateBitCast(PersonalityFn, Builder.getInt8PtrTy()),
     213             :       PersonalityFieldPtr, /*isVolatile=*/true);
     214             : 
     215             :   // LSDA address
     216          62 :   Value *LSDA = Builder.CreateCall(LSDAAddrFn, {}, "lsda_addr");
     217             :   Value *LSDAFieldPtr =
     218          31 :       Builder.CreateConstGEP2_32(FunctionContextTy, FuncCtx, 0, 4, "lsda_gep");
     219          31 :   Builder.CreateStore(LSDA, LSDAFieldPtr, /*isVolatile=*/true);
     220             : 
     221          62 :   return FuncCtx;
     222             : }
     223             : 
     224             : /// lowerIncomingArguments - To avoid having to handle incoming arguments
     225             : /// specially, we lower each arg to a copy instruction in the entry block. This
     226             : /// ensures that the argument value itself cannot be live out of the entry
     227             : /// block.
     228          31 : void SjLjEHPrepare::lowerIncomingArguments(Function &F) {
     229          93 :   BasicBlock::iterator AfterAllocaInsPt = F.begin()->begin();
     230        1505 :   while (isa<AllocaInst>(AfterAllocaInsPt) &&
     231         737 :          cast<AllocaInst>(AfterAllocaInsPt)->isStaticAlloca())
     232             :     ++AfterAllocaInsPt;
     233             :   assert(AfterAllocaInsPt != F.front().end());
     234             : 
     235          68 :   for (auto &AI : F.args()) {
     236          37 :     Type *Ty = AI.getType();
     237             : 
     238             :     // Use 'select i8 true, %arg, undef' to simulate a 'no-op' instruction.
     239          37 :     Value *TrueValue = ConstantInt::getTrue(F.getContext());
     240          37 :     Value *UndefValue = UndefValue::get(Ty);
     241          37 :     Instruction *SI = SelectInst::Create(
     242         111 :         TrueValue, &AI, UndefValue, AI.getName() + ".tmp", &*AfterAllocaInsPt);
     243          37 :     AI.replaceAllUsesWith(SI);
     244             : 
     245             :     // Reset the operand, because it  was clobbered by the RAUW above.
     246          37 :     SI->setOperand(1, &AI);
     247             :   }
     248          31 : }
     249             : 
     250             : /// lowerAcrossUnwindEdges - Find all variables which are alive across an unwind
     251             : /// edge and spill them.
     252          31 : void SjLjEHPrepare::lowerAcrossUnwindEdges(Function &F,
     253             :                                            ArrayRef<InvokeInst *> Invokes) {
     254             :   // Finally, scan the code looking for instructions with bad live ranges.
     255         428 :   for (BasicBlock &BB : F) {
     256        6209 :     for (Instruction &Inst : BB) {
     257             :       // Ignore obvious cases we don't have to handle. In particular, most
     258             :       // instructions either have no uses or only have a single use inside the
     259             :       // current block. Ignore them quickly.
     260       10408 :       if (Inst.use_empty())
     261        4904 :         continue;
     262       10513 :       if (Inst.hasOneUse() &&
     263        9505 :           cast<Instruction>(Inst.user_back())->getParent() == &BB &&
     264        2107 :           !isa<PHINode>(Inst.user_back()))
     265             :         continue;
     266             : 
     267             :       // If this is an alloca in the entry block, it's not a real register
     268             :       // value.
     269         731 :       if (auto *AI = dyn_cast<AllocaInst>(&Inst))
     270         731 :         if (AI->isStaticAlloca())
     271             :           continue;
     272             : 
     273             :       // Avoid iterator invalidation by copying users to a temporary vector.
     274         600 :       SmallVector<Instruction *, 16> Users;
     275        2944 :       for (User *U : Inst.users()) {
     276        1022 :         Instruction *UI = cast<Instruction>(U);
     277        1443 :         if (UI->getParent() != &BB || isa<PHINode>(UI))
     278         601 :           Users.push_back(UI);
     279             :       }
     280             : 
     281             :       // Find all of the blocks that this value is live in.
     282         600 :       SmallPtrSet<BasicBlock *, 32> LiveBBs;
     283         300 :       LiveBBs.insert(&BB);
     284         901 :       while (!Users.empty()) {
     285         601 :         Instruction *U = Users.pop_back_val();
     286             : 
     287        1202 :         if (!isa<PHINode>(U)) {
     288         580 :           MarkBlocksLiveIn(U->getParent(), LiveBBs);
     289             :         } else {
     290             :           // Uses for a PHI node occur in their predecessor block.
     291          42 :           PHINode *PN = cast<PHINode>(U);
     292          95 :           for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
     293          53 :             if (PN->getIncomingValue(i) == &Inst)
     294          27 :               MarkBlocksLiveIn(PN->getIncomingBlock(i), LiveBBs);
     295             :         }
     296             :       }
     297             : 
     298             :       // Now that we know all of the blocks that this thing is live in, see if
     299             :       // it includes any of the unwind locations.
     300         300 :       bool NeedsSpill = false;
     301        7431 :       for (InvokeInst *Invoke : Invokes) {
     302        6922 :         BasicBlock *UnwindBlock = Invoke->getUnwindDest();
     303        6922 :         if (UnwindBlock != &BB && LiveBBs.count(UnwindBlock)) {
     304             :           DEBUG(dbgs() << "SJLJ Spill: " << Inst << " around "
     305             :                        << UnwindBlock->getName() << "\n");
     306             :           NeedsSpill = true;
     307             :           break;
     308             :         }
     309             :       }
     310             : 
     311             :       // If we decided we need a spill, do it.
     312             :       // FIXME: Spilling this way is overkill, as it forces all uses of
     313             :       // the value to be reloaded from the stack slot, even those that aren't
     314             :       // in the unwind blocks. We should be more selective.
     315         300 :       if (NeedsSpill) {
     316          91 :         DemoteRegToStack(Inst, true);
     317             :         ++NumSpilled;
     318             :       }
     319             :     }
     320             :   }
     321             : 
     322             :   // Go through the landing pads and remove any PHIs there.
     323         229 :   for (InvokeInst *Invoke : Invokes) {
     324         167 :     BasicBlock *UnwindBlock = Invoke->getUnwindDest();
     325         167 :     LandingPadInst *LPI = UnwindBlock->getLandingPadInst();
     326             : 
     327             :     // Place PHIs into a set to avoid invalidating the iterator.
     328         167 :     SmallPtrSet<PHINode *, 8> PHIsToDemote;
     329         334 :     for (BasicBlock::iterator PN = UnwindBlock->begin(); isa<PHINode>(PN); ++PN)
     330           0 :       PHIsToDemote.insert(cast<PHINode>(PN));
     331         167 :     if (PHIsToDemote.empty())
     332         167 :       continue;
     333             : 
     334             :     // Demote the PHIs to the stack.
     335           0 :     for (PHINode *PN : PHIsToDemote)
     336           0 :       DemotePHIToStack(PN);
     337             : 
     338             :     // Move the landingpad instruction back to the top of the landing pad block.
     339           0 :     LPI->moveBefore(&UnwindBlock->front());
     340             :   }
     341          31 : }
     342             : 
     343             : /// setupEntryBlockAndCallSites - Setup the entry block by creating and filling
     344             : /// the function context and marking the call sites with the appropriate
     345             : /// values. These values are used by the DWARF EH emitter.
     346        2250 : bool SjLjEHPrepare::setupEntryBlockAndCallSites(Function &F) {
     347        4500 :   SmallVector<ReturnInst *, 16> Returns;
     348        4500 :   SmallVector<InvokeInst *, 16> Invokes;
     349        4500 :   SmallSetVector<LandingPadInst *, 16> LPads;
     350             : 
     351             :   // Look through the terminators of the basic blocks to find invokes.
     352       10952 :   for (BasicBlock &BB : F)
     353        8404 :     if (auto *II = dyn_cast<InvokeInst>(BB.getTerminator())) {
     354         332 :       if (Function *Callee = II->getCalledFunction())
     355         165 :         if (Callee->getIntrinsicID() == Intrinsic::donothing) {
     356             :           // Remove the NOP invoke.
     357           0 :           BranchInst::Create(II->getNormalDest(), II);
     358           0 :           II->eraseFromParent();
     359           0 :           continue;
     360             :         }
     361             : 
     362         167 :       Invokes.push_back(II);
     363         501 :       LPads.insert(II->getUnwindDest()->getLandingPadInst());
     364        8070 :     } else if (auto *RI = dyn_cast<ReturnInst>(BB.getTerminator())) {
     365        2294 :       Returns.push_back(RI);
     366             :     }
     367             : 
     368        2250 :   if (Invokes.empty())
     369             :     return false;
     370             : 
     371          31 :   NumInvokes += Invokes.size();
     372             : 
     373          31 :   lowerIncomingArguments(F);
     374          31 :   lowerAcrossUnwindEdges(F, Invokes);
     375             : 
     376             :   Value *FuncCtx =
     377          93 :       setupFunctionContext(F, makeArrayRef(LPads.begin(), LPads.end()));
     378          31 :   BasicBlock *EntryBB = &F.front();
     379          62 :   IRBuilder<> Builder(EntryBB->getTerminator());
     380             : 
     381             :   // Get a reference to the jump buffer.
     382             :   Value *JBufPtr =
     383          31 :       Builder.CreateConstGEP2_32(FunctionContextTy, FuncCtx, 0, 5, "jbuf_gep");
     384             : 
     385             :   // Save the frame pointer.
     386          62 :   Value *FramePtr = Builder.CreateConstGEP2_32(doubleUnderJBufTy, JBufPtr, 0, 0,
     387          31 :                                                "jbuf_fp_gep");
     388             : 
     389          62 :   Value *Val = Builder.CreateCall(FrameAddrFn, Builder.getInt32(0), "fp");
     390          31 :   Builder.CreateStore(Val, FramePtr, /*isVolatile=*/true);
     391             : 
     392             :   // Save the stack pointer.
     393          62 :   Value *StackPtr = Builder.CreateConstGEP2_32(doubleUnderJBufTy, JBufPtr, 0, 2,
     394          31 :                                                "jbuf_sp_gep");
     395             : 
     396          62 :   Val = Builder.CreateCall(StackAddrFn, {}, "sp");
     397          31 :   Builder.CreateStore(Val, StackPtr, /*isVolatile=*/true);
     398             : 
     399             :   // Call the setup_dispatch instrinsic. It fills in the rest of the jmpbuf.
     400          62 :   Builder.CreateCall(BuiltinSetupDispatchFn, {});
     401             : 
     402             :   // Store a pointer to the function context so that the back-end will know
     403             :   // where to look for it.
     404          93 :   Value *FuncCtxArg = Builder.CreateBitCast(FuncCtx, Builder.getInt8PtrTy());
     405          62 :   Builder.CreateCall(FuncCtxFn, FuncCtxArg);
     406             : 
     407             :   // At this point, we are all set up, update the invoke instructions to mark
     408             :   // their call_site values.
     409         229 :   for (unsigned I = 0, E = Invokes.size(); I != E; ++I) {
     410         334 :     insertCallSiteStore(Invokes[I], I + 1);
     411             : 
     412             :     ConstantInt *CallSiteNum =
     413         167 :         ConstantInt::get(Type::getInt32Ty(F.getContext()), I + 1);
     414             : 
     415             :     // Record the call site value for the back end so it stays associated with
     416             :     // the invoke.
     417         668 :     CallInst::Create(CallSiteFn, CallSiteNum, "", Invokes[I]);
     418             :   }
     419             : 
     420             :   // Mark call instructions that aren't nounwind as no-action (call_site ==
     421             :   // -1). Skip the entry block, as prior to then, no function context has been
     422             :   // created for this function and any unexpected exceptions thrown will go
     423             :   // directly to the caller's context, which is what we want anyway, so no need
     424             :   // to do anything here.
     425         428 :   for (BasicBlock &BB : F) {
     426         335 :     if (&BB == &F.front())
     427          31 :       continue;
     428        6170 :     for (Instruction &I : BB)
     429        5258 :       if (I.mayThrow())
     430         759 :         insertCallSiteStore(&I, -1);
     431             :   }
     432             : 
     433             :   // Register the function context and make sure it's known to not throw
     434             :   CallInst *Register =
     435          93 :       CallInst::Create(RegisterFn, FuncCtx, "", EntryBB->getTerminator());
     436          31 :   Register->setDoesNotThrow();
     437             : 
     438             :   // Following any allocas not in the entry block, update the saved SP in the
     439             :   // jmpbuf to the new value.
     440         428 :   for (BasicBlock &BB : F) {
     441         335 :     if (&BB == &F.front())
     442          31 :       continue;
     443        7688 :     for (Instruction &I : BB) {
     444        1198 :       if (auto *CI = dyn_cast<CallInst>(&I)) {
     445        1198 :         if (CI->getCalledFunction() != StackRestoreFn)
     446        1198 :           continue;
     447       11156 :       } else if (!isa<AllocaInst>(&I)) {
     448        5578 :         continue;
     449             :       }
     450           0 :       Instruction *StackAddr = CallInst::Create(StackAddrFn, "sp");
     451           0 :       StackAddr->insertAfter(&I);
     452           0 :       Instruction *StoreStackAddr = new StoreInst(StackAddr, StackPtr, true);
     453           0 :       StoreStackAddr->insertAfter(StackAddr);
     454             :     }
     455             :   }
     456             : 
     457             :   // Finally, for any returns from this function, if this function contains an
     458             :   // invoke, add a call to unregister the function context.
     459         116 :   for (ReturnInst *Return : Returns)
     460          46 :     CallInst::Create(UnregisterFn, FuncCtx, "", Return);
     461             : 
     462          31 :   return true;
     463             : }
     464             : 
     465          31 : bool SjLjEHPrepare::undoSwiftErrorSelect(Function &F) {
     466             :   // We have inserted dummy copies 'select true, arg, undef' in the entry block
     467             :   // for arguments to simplify this pass.
     468             :   // swifterror arguments cannot be used in this way. Undo the select for the
     469             :   // swifterror argument.
     470          67 :   for (auto &AI : F.args()) {
     471          37 :     if (AI.isSwiftError()) {
     472             :       assert(AI.hasOneUse() && "Must have converted the argument to a select");
     473           4 :       auto *Select = dyn_cast<SelectInst>(AI.use_begin()->getUser());
     474             :       assert(Select && "There must be single select user");
     475           2 :       auto *OrigSwiftError = cast<Argument>(Select->getTrueValue());
     476           1 :       Select->replaceAllUsesWith(OrigSwiftError);
     477           1 :       Select->eraseFromParent();
     478             :       return true;
     479             :     }
     480             :   }
     481             :   return false;
     482             : }
     483             : 
     484        2250 : bool SjLjEHPrepare::runOnFunction(Function &F) {
     485        2250 :   Module &M = *F.getParent();
     486        6750 :   RegisterFn = M.getOrInsertFunction(
     487             :       "_Unwind_SjLj_Register", Type::getVoidTy(M.getContext()),
     488             :       PointerType::getUnqual(FunctionContextTy));
     489        6750 :   UnregisterFn = M.getOrInsertFunction(
     490             :       "_Unwind_SjLj_Unregister", Type::getVoidTy(M.getContext()),
     491             :       PointerType::getUnqual(FunctionContextTy));
     492        2250 :   FrameAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::frameaddress);
     493        2250 :   StackAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::stacksave);
     494        2250 :   StackRestoreFn = Intrinsic::getDeclaration(&M, Intrinsic::stackrestore);
     495        2250 :   BuiltinSetupDispatchFn =
     496        4500 :     Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_setup_dispatch);
     497        2250 :   LSDAAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_lsda);
     498        2250 :   CallSiteFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_callsite);
     499        2250 :   FuncCtxFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_functioncontext);
     500             : 
     501        2250 :   bool Res = setupEntryBlockAndCallSites(F);
     502        2250 :   if (Res)
     503          31 :     Res |= undoSwiftErrorSelect(F);
     504        2250 :   return Res;
     505             : }

Generated by: LCOV version 1.13