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