1 //===--- CGException.cpp - Emit LLVM Code for C++ exceptions ----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This contains code dealing with C++ exception related code generation.
12 //===----------------------------------------------------------------------===//
14 #include "CodeGenFunction.h"
16 #include "CGCleanup.h"
17 #include "CGObjCRuntime.h"
18 #include "TargetInfo.h"
19 #include "clang/AST/Mangle.h"
20 #include "clang/AST/StmtCXX.h"
21 #include "clang/AST/StmtObjC.h"
22 #include "clang/AST/StmtVisitor.h"
23 #include "clang/Basic/TargetBuiltins.h"
24 #include "llvm/IR/CallSite.h"
25 #include "llvm/IR/Intrinsics.h"
26 #include "llvm/IR/IntrinsicInst.h"
27 #include "llvm/Support/SaveAndRestore.h"
29 using namespace clang;
30 using namespace CodeGen;
32 static llvm::Constant *getFreeExceptionFn(CodeGenModule &CGM) {
33 // void __cxa_free_exception(void *thrown_exception);
35 llvm::FunctionType *FTy =
36 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
38 return CGM.CreateRuntimeFunction(FTy, "__cxa_free_exception");
41 static llvm::Constant *getUnexpectedFn(CodeGenModule &CGM) {
42 // void __cxa_call_unexpected(void *thrown_exception);
44 llvm::FunctionType *FTy =
45 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
47 return CGM.CreateRuntimeFunction(FTy, "__cxa_call_unexpected");
50 llvm::Constant *CodeGenModule::getTerminateFn() {
51 // void __terminate();
53 llvm::FunctionType *FTy =
54 llvm::FunctionType::get(VoidTy, /*IsVarArgs=*/false);
58 // In C++, use std::terminate().
59 if (getLangOpts().CPlusPlus &&
60 getTarget().getCXXABI().isItaniumFamily()) {
61 name = "_ZSt9terminatev";
62 } else if (getLangOpts().CPlusPlus &&
63 getTarget().getCXXABI().isMicrosoft()) {
64 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
65 name = "__std_terminate";
67 name = "\01?terminate@@YAXXZ";
68 } else if (getLangOpts().ObjC1 &&
69 getLangOpts().ObjCRuntime.hasTerminate())
70 name = "objc_terminate";
73 return CreateRuntimeFunction(FTy, name);
76 static llvm::Constant *getCatchallRethrowFn(CodeGenModule &CGM,
78 llvm::FunctionType *FTy =
79 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
81 return CGM.CreateRuntimeFunction(FTy, Name);
84 const EHPersonality EHPersonality::GNU_C = { "__gcc_personality_v0", nullptr };
86 EHPersonality::GNU_C_SJLJ = { "__gcc_personality_sj0", nullptr };
88 EHPersonality::GNU_C_SEH = { "__gcc_personality_seh0", nullptr };
90 EHPersonality::NeXT_ObjC = { "__objc_personality_v0", nullptr };
92 EHPersonality::GNU_CPlusPlus = { "__gxx_personality_v0", nullptr };
94 EHPersonality::GNU_CPlusPlus_SJLJ = { "__gxx_personality_sj0", nullptr };
96 EHPersonality::GNU_CPlusPlus_SEH = { "__gxx_personality_seh0", nullptr };
98 EHPersonality::GNU_ObjC = {"__gnu_objc_personality_v0", "objc_exception_throw"};
100 EHPersonality::GNU_ObjCXX = { "__gnustep_objcxx_personality_v0", nullptr };
102 EHPersonality::GNUstep_ObjC = { "__gnustep_objc_personality_v0", nullptr };
104 EHPersonality::MSVC_except_handler = { "_except_handler3", nullptr };
106 EHPersonality::MSVC_C_specific_handler = { "__C_specific_handler", nullptr };
108 EHPersonality::MSVC_CxxFrameHandler3 = { "__CxxFrameHandler3", nullptr };
110 /// On Win64, use libgcc's SEH personality function. We fall back to dwarf on
111 /// other platforms, unless the user asked for SjLj exceptions.
112 static bool useLibGCCSEHPersonality(const llvm::Triple &T) {
113 return T.isOSWindows() && T.getArch() == llvm::Triple::x86_64;
116 static const EHPersonality &getCPersonality(const llvm::Triple &T,
117 const LangOptions &L) {
118 if (L.SjLjExceptions)
119 return EHPersonality::GNU_C_SJLJ;
120 else if (useLibGCCSEHPersonality(T))
121 return EHPersonality::GNU_C_SEH;
122 return EHPersonality::GNU_C;
125 static const EHPersonality &getObjCPersonality(const llvm::Triple &T,
126 const LangOptions &L) {
127 switch (L.ObjCRuntime.getKind()) {
128 case ObjCRuntime::FragileMacOSX:
129 return getCPersonality(T, L);
130 case ObjCRuntime::MacOSX:
131 case ObjCRuntime::iOS:
132 case ObjCRuntime::WatchOS:
133 return EHPersonality::NeXT_ObjC;
134 case ObjCRuntime::GNUstep:
135 if (L.ObjCRuntime.getVersion() >= VersionTuple(1, 7))
136 return EHPersonality::GNUstep_ObjC;
138 case ObjCRuntime::GCC:
139 case ObjCRuntime::ObjFW:
140 return EHPersonality::GNU_ObjC;
142 llvm_unreachable("bad runtime kind");
145 static const EHPersonality &getCXXPersonality(const llvm::Triple &T,
146 const LangOptions &L) {
147 if (L.SjLjExceptions)
148 return EHPersonality::GNU_CPlusPlus_SJLJ;
149 else if (useLibGCCSEHPersonality(T))
150 return EHPersonality::GNU_CPlusPlus_SEH;
151 return EHPersonality::GNU_CPlusPlus;
154 /// Determines the personality function to use when both C++
155 /// and Objective-C exceptions are being caught.
156 static const EHPersonality &getObjCXXPersonality(const llvm::Triple &T,
157 const LangOptions &L) {
158 switch (L.ObjCRuntime.getKind()) {
159 // The ObjC personality defers to the C++ personality for non-ObjC
160 // handlers. Unlike the C++ case, we use the same personality
161 // function on targets using (backend-driven) SJLJ EH.
162 case ObjCRuntime::MacOSX:
163 case ObjCRuntime::iOS:
164 case ObjCRuntime::WatchOS:
165 return EHPersonality::NeXT_ObjC;
167 // In the fragile ABI, just use C++ exception handling and hope
168 // they're not doing crazy exception mixing.
169 case ObjCRuntime::FragileMacOSX:
170 return getCXXPersonality(T, L);
172 // The GCC runtime's personality function inherently doesn't support
173 // mixed EH. Use the C++ personality just to avoid returning null.
174 case ObjCRuntime::GCC:
175 case ObjCRuntime::ObjFW: // XXX: this will change soon
176 return EHPersonality::GNU_ObjC;
177 case ObjCRuntime::GNUstep:
178 return EHPersonality::GNU_ObjCXX;
180 llvm_unreachable("bad runtime kind");
183 static const EHPersonality &getSEHPersonalityMSVC(const llvm::Triple &T) {
184 if (T.getArch() == llvm::Triple::x86)
185 return EHPersonality::MSVC_except_handler;
186 return EHPersonality::MSVC_C_specific_handler;
189 const EHPersonality &EHPersonality::get(CodeGenModule &CGM,
190 const FunctionDecl *FD) {
191 const llvm::Triple &T = CGM.getTarget().getTriple();
192 const LangOptions &L = CGM.getLangOpts();
194 // Functions using SEH get an SEH personality.
195 if (FD && FD->usesSEHTry())
196 return getSEHPersonalityMSVC(T);
198 // Try to pick a personality function that is compatible with MSVC if we're
199 // not compiling Obj-C. Obj-C users better have an Obj-C runtime that supports
200 // the GCC-style personality function.
201 if (T.isWindowsMSVCEnvironment() && !L.ObjC1) {
202 if (L.SjLjExceptions)
203 return EHPersonality::GNU_CPlusPlus_SJLJ;
205 return EHPersonality::MSVC_CxxFrameHandler3;
208 if (L.CPlusPlus && L.ObjC1)
209 return getObjCXXPersonality(T, L);
210 else if (L.CPlusPlus)
211 return getCXXPersonality(T, L);
213 return getObjCPersonality(T, L);
215 return getCPersonality(T, L);
218 const EHPersonality &EHPersonality::get(CodeGenFunction &CGF) {
219 return get(CGF.CGM, dyn_cast_or_null<FunctionDecl>(CGF.CurCodeDecl));
222 static llvm::Constant *getPersonalityFn(CodeGenModule &CGM,
223 const EHPersonality &Personality) {
224 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.Int32Ty, true),
225 Personality.PersonalityFn,
226 llvm::AttributeSet(), /*Local=*/true);
229 static llvm::Constant *getOpaquePersonalityFn(CodeGenModule &CGM,
230 const EHPersonality &Personality) {
231 llvm::Constant *Fn = getPersonalityFn(CGM, Personality);
232 return llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
235 /// Check whether a landingpad instruction only uses C++ features.
236 static bool LandingPadHasOnlyCXXUses(llvm::LandingPadInst *LPI) {
237 for (unsigned I = 0, E = LPI->getNumClauses(); I != E; ++I) {
238 // Look for something that would've been returned by the ObjC
239 // runtime's GetEHType() method.
240 llvm::Value *Val = LPI->getClause(I)->stripPointerCasts();
241 if (LPI->isCatch(I)) {
242 // Check if the catch value has the ObjC prefix.
243 if (llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Val))
244 // ObjC EH selector entries are always global variables with
245 // names starting like this.
246 if (GV->getName().startswith("OBJC_EHTYPE"))
249 // Check if any of the filter values have the ObjC prefix.
250 llvm::Constant *CVal = cast<llvm::Constant>(Val);
251 for (llvm::User::op_iterator
252 II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II) {
253 if (llvm::GlobalVariable *GV =
254 cast<llvm::GlobalVariable>((*II)->stripPointerCasts()))
255 // ObjC EH selector entries are always global variables with
256 // names starting like this.
257 if (GV->getName().startswith("OBJC_EHTYPE"))
265 /// Check whether a personality function could reasonably be swapped
266 /// for a C++ personality function.
267 static bool PersonalityHasOnlyCXXUses(llvm::Constant *Fn) {
268 for (llvm::User *U : Fn->users()) {
269 // Conditionally white-list bitcasts.
270 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(U)) {
271 if (CE->getOpcode() != llvm::Instruction::BitCast) return false;
272 if (!PersonalityHasOnlyCXXUses(CE))
277 // Otherwise it must be a function.
278 llvm::Function *F = dyn_cast<llvm::Function>(U);
279 if (!F) return false;
281 for (auto BB = F->begin(), E = F->end(); BB != E; ++BB) {
282 if (BB->isLandingPad())
283 if (!LandingPadHasOnlyCXXUses(BB->getLandingPadInst()))
291 /// Try to use the C++ personality function in ObjC++. Not doing this
292 /// can cause some incompatibilities with gcc, which is more
293 /// aggressive about only using the ObjC++ personality in a function
294 /// when it really needs it.
295 void CodeGenModule::SimplifyPersonality() {
296 // If we're not in ObjC++ -fexceptions, there's nothing to do.
297 if (!LangOpts.CPlusPlus || !LangOpts.ObjC1 || !LangOpts.Exceptions)
300 // Both the problem this endeavors to fix and the way the logic
301 // above works is specific to the NeXT runtime.
302 if (!LangOpts.ObjCRuntime.isNeXTFamily())
305 const EHPersonality &ObjCXX = EHPersonality::get(*this, /*FD=*/nullptr);
306 const EHPersonality &CXX =
307 getCXXPersonality(getTarget().getTriple(), LangOpts);
311 assert(std::strcmp(ObjCXX.PersonalityFn, CXX.PersonalityFn) != 0 &&
312 "Different EHPersonalities using the same personality function.");
314 llvm::Function *Fn = getModule().getFunction(ObjCXX.PersonalityFn);
316 // Nothing to do if it's unused.
317 if (!Fn || Fn->use_empty()) return;
319 // Can't do the optimization if it has non-C++ uses.
320 if (!PersonalityHasOnlyCXXUses(Fn)) return;
322 // Create the C++ personality function and kill off the old
324 llvm::Constant *CXXFn = getPersonalityFn(*this, CXX);
326 // This can happen if the user is screwing with us.
327 if (Fn->getType() != CXXFn->getType()) return;
329 Fn->replaceAllUsesWith(CXXFn);
330 Fn->eraseFromParent();
333 /// Returns the value to inject into a selector to indicate the
334 /// presence of a catch-all.
335 static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
336 // Possibly we should use @llvm.eh.catch.all.value here.
337 return llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
341 /// A cleanup to free the exception object if its initialization
343 struct FreeException final : EHScopeStack::Cleanup {
345 FreeException(llvm::Value *exn) : exn(exn) {}
346 void Emit(CodeGenFunction &CGF, Flags flags) override {
347 CGF.EmitNounwindRuntimeCall(getFreeExceptionFn(CGF.CGM), exn);
350 } // end anonymous namespace
352 // Emits an exception expression into the given location. This
353 // differs from EmitAnyExprToMem only in that, if a final copy-ctor
354 // call is required, an exception within that copy ctor causes
355 // std::terminate to be invoked.
356 void CodeGenFunction::EmitAnyExprToExn(const Expr *e, Address addr) {
357 // Make sure the exception object is cleaned up if there's an
358 // exception during initialization.
359 pushFullExprCleanup<FreeException>(EHCleanup, addr.getPointer());
360 EHScopeStack::stable_iterator cleanup = EHStack.stable_begin();
362 // __cxa_allocate_exception returns a void*; we need to cast this
363 // to the appropriate type for the object.
364 llvm::Type *ty = ConvertTypeForMem(e->getType())->getPointerTo();
365 Address typedAddr = Builder.CreateBitCast(addr, ty);
367 // FIXME: this isn't quite right! If there's a final unelided call
368 // to a copy constructor, then according to [except.terminate]p1 we
369 // must call std::terminate() if that constructor throws, because
370 // technically that copy occurs after the exception expression is
371 // evaluated but before the exception is caught. But the best way
372 // to handle that is to teach EmitAggExpr to do the final copy
373 // differently if it can't be elided.
374 EmitAnyExprToMem(e, typedAddr, e->getType().getQualifiers(),
377 // Deactivate the cleanup block.
378 DeactivateCleanupBlock(cleanup,
379 cast<llvm::Instruction>(typedAddr.getPointer()));
382 Address CodeGenFunction::getExceptionSlot() {
384 ExceptionSlot = CreateTempAlloca(Int8PtrTy, "exn.slot");
385 return Address(ExceptionSlot, getPointerAlign());
388 Address CodeGenFunction::getEHSelectorSlot() {
390 EHSelectorSlot = CreateTempAlloca(Int32Ty, "ehselector.slot");
391 return Address(EHSelectorSlot, CharUnits::fromQuantity(4));
394 llvm::Value *CodeGenFunction::getExceptionFromSlot() {
395 return Builder.CreateLoad(getExceptionSlot(), "exn");
398 llvm::Value *CodeGenFunction::getSelectorFromSlot() {
399 return Builder.CreateLoad(getEHSelectorSlot(), "sel");
402 void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E,
403 bool KeepInsertionPoint) {
404 if (const Expr *SubExpr = E->getSubExpr()) {
405 QualType ThrowType = SubExpr->getType();
406 if (ThrowType->isObjCObjectPointerType()) {
407 const Stmt *ThrowStmt = E->getSubExpr();
408 const ObjCAtThrowStmt S(E->getExprLoc(), const_cast<Stmt *>(ThrowStmt));
409 CGM.getObjCRuntime().EmitThrowStmt(*this, S, false);
411 CGM.getCXXABI().emitThrow(*this, E);
414 CGM.getCXXABI().emitRethrow(*this, /*isNoReturn=*/true);
417 // throw is an expression, and the expression emitters expect us
418 // to leave ourselves at a valid insertion point.
419 if (KeepInsertionPoint)
420 EmitBlock(createBasicBlock("throw.cont"));
423 void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
424 if (!CGM.getLangOpts().CXXExceptions)
427 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
429 // Check if CapturedDecl is nothrow and create terminate scope for it.
430 if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
432 EHStack.pushTerminate();
436 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
440 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
441 if (isNoexceptExceptionSpec(EST)) {
442 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
443 // noexcept functions are simple terminate scopes.
444 EHStack.pushTerminate();
446 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
447 // TODO: Revisit exception specifications for the MS ABI. There is a way to
448 // encode these in an object file but MSVC doesn't do anything with it.
449 if (getTarget().getCXXABI().isMicrosoft())
451 unsigned NumExceptions = Proto->getNumExceptions();
452 EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
454 for (unsigned I = 0; I != NumExceptions; ++I) {
455 QualType Ty = Proto->getExceptionType(I);
456 QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
457 llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType,
459 Filter->setFilter(I, EHType);
464 /// Emit the dispatch block for a filter scope if necessary.
465 static void emitFilterDispatchBlock(CodeGenFunction &CGF,
466 EHFilterScope &filterScope) {
467 llvm::BasicBlock *dispatchBlock = filterScope.getCachedEHDispatchBlock();
468 if (!dispatchBlock) return;
469 if (dispatchBlock->use_empty()) {
470 delete dispatchBlock;
474 CGF.EmitBlockAfterUses(dispatchBlock);
476 // If this isn't a catch-all filter, we need to check whether we got
477 // here because the filter triggered.
478 if (filterScope.getNumFilters()) {
479 // Load the selector value.
480 llvm::Value *selector = CGF.getSelectorFromSlot();
481 llvm::BasicBlock *unexpectedBB = CGF.createBasicBlock("ehspec.unexpected");
483 llvm::Value *zero = CGF.Builder.getInt32(0);
484 llvm::Value *failsFilter =
485 CGF.Builder.CreateICmpSLT(selector, zero, "ehspec.fails");
486 CGF.Builder.CreateCondBr(failsFilter, unexpectedBB,
487 CGF.getEHResumeBlock(false));
489 CGF.EmitBlock(unexpectedBB);
492 // Call __cxa_call_unexpected. This doesn't need to be an invoke
493 // because __cxa_call_unexpected magically filters exceptions
494 // according to the last landing pad the exception was thrown
496 llvm::Value *exn = CGF.getExceptionFromSlot();
497 CGF.EmitRuntimeCall(getUnexpectedFn(CGF.CGM), exn)
498 ->setDoesNotReturn();
499 CGF.Builder.CreateUnreachable();
502 void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
503 if (!CGM.getLangOpts().CXXExceptions)
506 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
508 // Check if CapturedDecl is nothrow and pop terminate scope for it.
509 if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
511 EHStack.popTerminate();
515 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
519 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
520 if (isNoexceptExceptionSpec(EST)) {
521 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
522 EHStack.popTerminate();
524 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
525 // TODO: Revisit exception specifications for the MS ABI. There is a way to
526 // encode these in an object file but MSVC doesn't do anything with it.
527 if (getTarget().getCXXABI().isMicrosoft())
529 EHFilterScope &filterScope = cast<EHFilterScope>(*EHStack.begin());
530 emitFilterDispatchBlock(*this, filterScope);
535 void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
537 EmitStmt(S.getTryBlock());
541 void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
542 unsigned NumHandlers = S.getNumHandlers();
543 EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
545 for (unsigned I = 0; I != NumHandlers; ++I) {
546 const CXXCatchStmt *C = S.getHandler(I);
548 llvm::BasicBlock *Handler = createBasicBlock("catch");
549 if (C->getExceptionDecl()) {
550 // FIXME: Dropping the reference type on the type into makes it
551 // impossible to correctly implement catch-by-reference
552 // semantics for pointers. Unfortunately, this is what all
553 // existing compilers do, and it's not clear that the standard
554 // personality routine is capable of doing this right. See C++ DR 388:
555 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
556 Qualifiers CaughtTypeQuals;
557 QualType CaughtType = CGM.getContext().getUnqualifiedArrayType(
558 C->getCaughtType().getNonReferenceType(), CaughtTypeQuals);
560 CatchTypeInfo TypeInfo{nullptr, 0};
561 if (CaughtType->isObjCObjectPointerType())
562 TypeInfo.RTTI = CGM.getObjCRuntime().GetEHType(CaughtType);
564 TypeInfo = CGM.getCXXABI().getAddrOfCXXCatchHandlerType(
565 CaughtType, C->getCaughtType());
566 CatchScope->setHandler(I, TypeInfo, Handler);
568 // No exception decl indicates '...', a catch-all.
569 CatchScope->setHandler(I, CGM.getCXXABI().getCatchAllTypeInfo(), Handler);
575 CodeGenFunction::getEHDispatchBlock(EHScopeStack::stable_iterator si) {
576 if (EHPersonality::get(*this).usesFuncletPads())
577 return getMSVCDispatchBlock(si);
579 // The dispatch block for the end of the scope chain is a block that
580 // just resumes unwinding.
581 if (si == EHStack.stable_end())
582 return getEHResumeBlock(true);
584 // Otherwise, we should look at the actual scope.
585 EHScope &scope = *EHStack.find(si);
587 llvm::BasicBlock *dispatchBlock = scope.getCachedEHDispatchBlock();
588 if (!dispatchBlock) {
589 switch (scope.getKind()) {
590 case EHScope::Catch: {
591 // Apply a special case to a single catch-all.
592 EHCatchScope &catchScope = cast<EHCatchScope>(scope);
593 if (catchScope.getNumHandlers() == 1 &&
594 catchScope.getHandler(0).isCatchAll()) {
595 dispatchBlock = catchScope.getHandler(0).Block;
597 // Otherwise, make a dispatch block.
599 dispatchBlock = createBasicBlock("catch.dispatch");
604 case EHScope::Cleanup:
605 dispatchBlock = createBasicBlock("ehcleanup");
608 case EHScope::Filter:
609 dispatchBlock = createBasicBlock("filter.dispatch");
612 case EHScope::Terminate:
613 dispatchBlock = getTerminateHandler();
616 case EHScope::PadEnd:
617 llvm_unreachable("PadEnd unnecessary for Itanium!");
619 scope.setCachedEHDispatchBlock(dispatchBlock);
621 return dispatchBlock;
625 CodeGenFunction::getMSVCDispatchBlock(EHScopeStack::stable_iterator SI) {
626 // Returning nullptr indicates that the previous dispatch block should unwind
628 if (SI == EHStack.stable_end())
631 // Otherwise, we should look at the actual scope.
632 EHScope &EHS = *EHStack.find(SI);
634 llvm::BasicBlock *DispatchBlock = EHS.getCachedEHDispatchBlock();
636 return DispatchBlock;
638 if (EHS.getKind() == EHScope::Terminate)
639 DispatchBlock = getTerminateHandler();
641 DispatchBlock = createBasicBlock();
642 CGBuilderTy Builder(*this, DispatchBlock);
644 switch (EHS.getKind()) {
646 DispatchBlock->setName("catch.dispatch");
649 case EHScope::Cleanup:
650 DispatchBlock->setName("ehcleanup");
653 case EHScope::Filter:
654 llvm_unreachable("exception specifications not handled yet!");
656 case EHScope::Terminate:
657 DispatchBlock->setName("terminate");
660 case EHScope::PadEnd:
661 llvm_unreachable("PadEnd dispatch block missing!");
663 EHS.setCachedEHDispatchBlock(DispatchBlock);
664 return DispatchBlock;
667 /// Check whether this is a non-EH scope, i.e. a scope which doesn't
668 /// affect exception handling. Currently, the only non-EH scopes are
669 /// normal-only cleanup scopes.
670 static bool isNonEHScope(const EHScope &S) {
671 switch (S.getKind()) {
672 case EHScope::Cleanup:
673 return !cast<EHCleanupScope>(S).isEHCleanup();
674 case EHScope::Filter:
676 case EHScope::Terminate:
677 case EHScope::PadEnd:
681 llvm_unreachable("Invalid EHScope Kind!");
684 llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
685 assert(EHStack.requiresLandingPad());
686 assert(!EHStack.empty());
688 // If exceptions are disabled and SEH is not in use, then there is no invoke
689 // destination. SEH "works" even if exceptions are off. In practice, this
690 // means that C++ destructors and other EH cleanups don't run, which is
691 // consistent with MSVC's behavior.
692 const LangOptions &LO = CGM.getLangOpts();
693 if (!LO.Exceptions) {
694 if (!LO.Borland && !LO.MicrosoftExt)
696 if (!currentFunctionUsesSEHTry())
700 // CUDA device code doesn't have exceptions.
701 if (LO.CUDA && LO.CUDAIsDevice)
704 // Check the innermost scope for a cached landing pad. If this is
705 // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
706 llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
709 const EHPersonality &Personality = EHPersonality::get(*this);
711 if (!CurFn->hasPersonalityFn())
712 CurFn->setPersonalityFn(getOpaquePersonalityFn(CGM, Personality));
714 if (Personality.usesFuncletPads()) {
715 // We don't need separate landing pads in the funclet model.
716 LP = getEHDispatchBlock(EHStack.getInnermostEHScope());
718 // Build the landing pad for this scope.
719 LP = EmitLandingPad();
724 // Cache the landing pad on the innermost scope. If this is a
725 // non-EH scope, cache the landing pad on the enclosing scope, too.
726 for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
727 ir->setCachedLandingPad(LP);
728 if (!isNonEHScope(*ir)) break;
734 llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
735 assert(EHStack.requiresLandingPad());
737 EHScope &innermostEHScope = *EHStack.find(EHStack.getInnermostEHScope());
738 switch (innermostEHScope.getKind()) {
739 case EHScope::Terminate:
740 return getTerminateLandingPad();
742 case EHScope::PadEnd:
743 llvm_unreachable("PadEnd unnecessary for Itanium!");
746 case EHScope::Cleanup:
747 case EHScope::Filter:
748 if (llvm::BasicBlock *lpad = innermostEHScope.getCachedLandingPad())
752 // Save the current IR generation state.
753 CGBuilderTy::InsertPoint savedIP = Builder.saveAndClearIP();
754 auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, CurEHLocation);
756 // Create and configure the landing pad.
757 llvm::BasicBlock *lpad = createBasicBlock("lpad");
760 llvm::LandingPadInst *LPadInst = Builder.CreateLandingPad(
761 llvm::StructType::get(Int8PtrTy, Int32Ty, nullptr), 0);
763 llvm::Value *LPadExn = Builder.CreateExtractValue(LPadInst, 0);
764 Builder.CreateStore(LPadExn, getExceptionSlot());
765 llvm::Value *LPadSel = Builder.CreateExtractValue(LPadInst, 1);
766 Builder.CreateStore(LPadSel, getEHSelectorSlot());
768 // Save the exception pointer. It's safe to use a single exception
769 // pointer per function because EH cleanups can never have nested
771 // Build the landingpad instruction.
773 // Accumulate all the handlers in scope.
774 bool hasCatchAll = false;
775 bool hasCleanup = false;
776 bool hasFilter = false;
777 SmallVector<llvm::Value*, 4> filterTypes;
778 llvm::SmallPtrSet<llvm::Value*, 4> catchTypes;
779 for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end(); I != E;
782 switch (I->getKind()) {
783 case EHScope::Cleanup:
784 // If we have a cleanup, remember that.
785 hasCleanup = (hasCleanup || cast<EHCleanupScope>(*I).isEHCleanup());
788 case EHScope::Filter: {
789 assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
790 assert(!hasCatchAll && "EH filter reached after catch-all");
792 // Filter scopes get added to the landingpad in weird ways.
793 EHFilterScope &filter = cast<EHFilterScope>(*I);
796 // Add all the filter values.
797 for (unsigned i = 0, e = filter.getNumFilters(); i != e; ++i)
798 filterTypes.push_back(filter.getFilter(i));
802 case EHScope::Terminate:
803 // Terminate scopes are basically catch-alls.
804 assert(!hasCatchAll);
811 case EHScope::PadEnd:
812 llvm_unreachable("PadEnd unnecessary for Itanium!");
815 EHCatchScope &catchScope = cast<EHCatchScope>(*I);
816 for (unsigned hi = 0, he = catchScope.getNumHandlers(); hi != he; ++hi) {
817 EHCatchScope::Handler handler = catchScope.getHandler(hi);
818 assert(handler.Type.Flags == 0 &&
819 "landingpads do not support catch handler flags");
821 // If this is a catch-all, register that and abort.
822 if (!handler.Type.RTTI) {
823 assert(!hasCatchAll);
828 // Check whether we already have a handler for this type.
829 if (catchTypes.insert(handler.Type.RTTI).second)
830 // If not, add it directly to the landingpad.
831 LPadInst->addClause(handler.Type.RTTI);
836 // If we have a catch-all, add null to the landingpad.
837 assert(!(hasCatchAll && hasFilter));
839 LPadInst->addClause(getCatchAllValue(*this));
841 // If we have an EH filter, we need to add those handlers in the
842 // right place in the landingpad, which is to say, at the end.
843 } else if (hasFilter) {
844 // Create a filter expression: a constant array indicating which filter
845 // types there are. The personality routine only lands here if the filter
847 SmallVector<llvm::Constant*, 8> Filters;
848 llvm::ArrayType *AType =
849 llvm::ArrayType::get(!filterTypes.empty() ?
850 filterTypes[0]->getType() : Int8PtrTy,
853 for (unsigned i = 0, e = filterTypes.size(); i != e; ++i)
854 Filters.push_back(cast<llvm::Constant>(filterTypes[i]));
855 llvm::Constant *FilterArray = llvm::ConstantArray::get(AType, Filters);
856 LPadInst->addClause(FilterArray);
858 // Also check whether we need a cleanup.
860 LPadInst->setCleanup(true);
862 // Otherwise, signal that we at least have cleanups.
863 } else if (hasCleanup) {
864 LPadInst->setCleanup(true);
867 assert((LPadInst->getNumClauses() > 0 || LPadInst->isCleanup()) &&
868 "landingpad instruction has no clauses!");
870 // Tell the backend how to generate the landing pad.
871 Builder.CreateBr(getEHDispatchBlock(EHStack.getInnermostEHScope()));
873 // Restore the old IR generation state.
874 Builder.restoreIP(savedIP);
879 static void emitCatchPadBlock(CodeGenFunction &CGF, EHCatchScope &CatchScope) {
880 llvm::BasicBlock *DispatchBlock = CatchScope.getCachedEHDispatchBlock();
881 assert(DispatchBlock);
883 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveIP();
884 CGF.EmitBlockAfterUses(DispatchBlock);
886 llvm::Value *ParentPad = CGF.CurrentFuncletPad;
888 ParentPad = llvm::ConstantTokenNone::get(CGF.getLLVMContext());
889 llvm::BasicBlock *UnwindBB =
890 CGF.getEHDispatchBlock(CatchScope.getEnclosingEHScope());
892 unsigned NumHandlers = CatchScope.getNumHandlers();
893 llvm::CatchSwitchInst *CatchSwitch =
894 CGF.Builder.CreateCatchSwitch(ParentPad, UnwindBB, NumHandlers);
896 // Test against each of the exception types we claim to catch.
897 for (unsigned I = 0; I < NumHandlers; ++I) {
898 const EHCatchScope::Handler &Handler = CatchScope.getHandler(I);
900 CatchTypeInfo TypeInfo = Handler.Type;
902 TypeInfo.RTTI = llvm::Constant::getNullValue(CGF.VoidPtrTy);
904 CGF.Builder.SetInsertPoint(Handler.Block);
906 if (EHPersonality::get(CGF).isMSVCXXPersonality()) {
907 CGF.Builder.CreateCatchPad(
908 CatchSwitch, {TypeInfo.RTTI, CGF.Builder.getInt32(TypeInfo.Flags),
909 llvm::Constant::getNullValue(CGF.VoidPtrTy)});
911 CGF.Builder.CreateCatchPad(CatchSwitch, {TypeInfo.RTTI});
914 CatchSwitch->addHandler(Handler.Block);
916 CGF.Builder.restoreIP(SavedIP);
919 /// Emit the structure of the dispatch block for the given catch scope.
920 /// It is an invariant that the dispatch block already exists.
921 static void emitCatchDispatchBlock(CodeGenFunction &CGF,
922 EHCatchScope &catchScope) {
923 if (EHPersonality::get(CGF).usesFuncletPads())
924 return emitCatchPadBlock(CGF, catchScope);
926 llvm::BasicBlock *dispatchBlock = catchScope.getCachedEHDispatchBlock();
927 assert(dispatchBlock);
929 // If there's only a single catch-all, getEHDispatchBlock returned
930 // that catch-all as the dispatch block.
931 if (catchScope.getNumHandlers() == 1 &&
932 catchScope.getHandler(0).isCatchAll()) {
933 assert(dispatchBlock == catchScope.getHandler(0).Block);
937 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveIP();
938 CGF.EmitBlockAfterUses(dispatchBlock);
940 // Select the right handler.
941 llvm::Value *llvm_eh_typeid_for =
942 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
944 // Load the selector value.
945 llvm::Value *selector = CGF.getSelectorFromSlot();
947 // Test against each of the exception types we claim to catch.
948 for (unsigned i = 0, e = catchScope.getNumHandlers(); ; ++i) {
949 assert(i < e && "ran off end of handlers!");
950 const EHCatchScope::Handler &handler = catchScope.getHandler(i);
952 llvm::Value *typeValue = handler.Type.RTTI;
953 assert(handler.Type.Flags == 0 &&
954 "landingpads do not support catch handler flags");
955 assert(typeValue && "fell into catch-all case!");
956 typeValue = CGF.Builder.CreateBitCast(typeValue, CGF.Int8PtrTy);
958 // Figure out the next block.
960 llvm::BasicBlock *nextBlock;
962 // If this is the last handler, we're at the end, and the next
963 // block is the block for the enclosing EH scope.
965 nextBlock = CGF.getEHDispatchBlock(catchScope.getEnclosingEHScope());
968 // If the next handler is a catch-all, we're at the end, and the
969 // next block is that handler.
970 } else if (catchScope.getHandler(i+1).isCatchAll()) {
971 nextBlock = catchScope.getHandler(i+1).Block;
974 // Otherwise, we're not at the end and we need a new block.
976 nextBlock = CGF.createBasicBlock("catch.fallthrough");
980 // Figure out the catch type's index in the LSDA's type table.
981 llvm::CallInst *typeIndex =
982 CGF.Builder.CreateCall(llvm_eh_typeid_for, typeValue);
983 typeIndex->setDoesNotThrow();
985 llvm::Value *matchesTypeIndex =
986 CGF.Builder.CreateICmpEQ(selector, typeIndex, "matches");
987 CGF.Builder.CreateCondBr(matchesTypeIndex, handler.Block, nextBlock);
989 // If the next handler is a catch-all, we're completely done.
991 CGF.Builder.restoreIP(savedIP);
994 // Otherwise we need to emit and continue at that block.
995 CGF.EmitBlock(nextBlock);
999 void CodeGenFunction::popCatchScope() {
1000 EHCatchScope &catchScope = cast<EHCatchScope>(*EHStack.begin());
1001 if (catchScope.hasEHBranches())
1002 emitCatchDispatchBlock(*this, catchScope);
1006 void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
1007 unsigned NumHandlers = S.getNumHandlers();
1008 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1009 assert(CatchScope.getNumHandlers() == NumHandlers);
1011 // If the catch was not required, bail out now.
1012 if (!CatchScope.hasEHBranches()) {
1013 CatchScope.clearHandlerBlocks();
1018 // Emit the structure of the EH dispatch for this catch.
1019 emitCatchDispatchBlock(*this, CatchScope);
1021 // Copy the handler blocks off before we pop the EH stack. Emitting
1022 // the handlers might scribble on this memory.
1023 SmallVector<EHCatchScope::Handler, 8> Handlers(
1024 CatchScope.begin(), CatchScope.begin() + NumHandlers);
1028 // The fall-through block.
1029 llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
1031 // We just emitted the body of the try; jump to the continue block.
1032 if (HaveInsertPoint())
1033 Builder.CreateBr(ContBB);
1035 // Determine if we need an implicit rethrow for all these catch handlers;
1036 // see the comment below.
1037 bool doImplicitRethrow = false;
1039 doImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
1040 isa<CXXConstructorDecl>(CurCodeDecl);
1042 // Perversely, we emit the handlers backwards precisely because we
1043 // want them to appear in source order. In all of these cases, the
1044 // catch block will have exactly one predecessor, which will be a
1045 // particular block in the catch dispatch. However, in the case of
1046 // a catch-all, one of the dispatch blocks will branch to two
1047 // different handlers, and EmitBlockAfterUses will cause the second
1048 // handler to be moved before the first.
1049 for (unsigned I = NumHandlers; I != 0; --I) {
1050 llvm::BasicBlock *CatchBlock = Handlers[I-1].Block;
1051 EmitBlockAfterUses(CatchBlock);
1053 // Catch the exception if this isn't a catch-all.
1054 const CXXCatchStmt *C = S.getHandler(I-1);
1056 // Enter a cleanup scope, including the catch variable and the
1058 RunCleanupsScope CatchScope(*this);
1060 // Initialize the catch variable and set up the cleanups.
1061 SaveAndRestore<llvm::Instruction *> RestoreCurrentFuncletPad(
1063 CGM.getCXXABI().emitBeginCatch(*this, C);
1065 // Emit the PGO counter increment.
1066 incrementProfileCounter(C);
1068 // Perform the body of the catch.
1069 EmitStmt(C->getHandlerBlock());
1071 // [except.handle]p11:
1072 // The currently handled exception is rethrown if control
1073 // reaches the end of a handler of the function-try-block of a
1074 // constructor or destructor.
1076 // It is important that we only do this on fallthrough and not on
1077 // return. Note that it's illegal to put a return in a
1078 // constructor function-try-block's catch handler (p14), so this
1079 // really only applies to destructors.
1080 if (doImplicitRethrow && HaveInsertPoint()) {
1081 CGM.getCXXABI().emitRethrow(*this, /*isNoReturn*/false);
1082 Builder.CreateUnreachable();
1083 Builder.ClearInsertionPoint();
1086 // Fall out through the catch cleanups.
1087 CatchScope.ForceCleanup();
1089 // Branch out of the try.
1090 if (HaveInsertPoint())
1091 Builder.CreateBr(ContBB);
1095 incrementProfileCounter(&S);
1099 struct CallEndCatchForFinally final : EHScopeStack::Cleanup {
1100 llvm::Value *ForEHVar;
1101 llvm::Value *EndCatchFn;
1102 CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn)
1103 : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
1105 void Emit(CodeGenFunction &CGF, Flags flags) override {
1106 llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
1107 llvm::BasicBlock *CleanupContBB =
1108 CGF.createBasicBlock("finally.cleanup.cont");
1110 llvm::Value *ShouldEndCatch =
1111 CGF.Builder.CreateFlagLoad(ForEHVar, "finally.endcatch");
1112 CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1113 CGF.EmitBlock(EndCatchBB);
1114 CGF.EmitRuntimeCallOrInvoke(EndCatchFn); // catch-all, so might throw
1115 CGF.EmitBlock(CleanupContBB);
1119 struct PerformFinally final : EHScopeStack::Cleanup {
1121 llvm::Value *ForEHVar;
1122 llvm::Value *EndCatchFn;
1123 llvm::Value *RethrowFn;
1124 llvm::Value *SavedExnVar;
1126 PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
1127 llvm::Value *EndCatchFn,
1128 llvm::Value *RethrowFn, llvm::Value *SavedExnVar)
1129 : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1130 RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
1132 void Emit(CodeGenFunction &CGF, Flags flags) override {
1133 // Enter a cleanup to call the end-catch function if one was provided.
1135 CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
1136 ForEHVar, EndCatchFn);
1138 // Save the current cleanup destination in case there are
1139 // cleanups in the finally block.
1140 llvm::Value *SavedCleanupDest =
1141 CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
1142 "cleanup.dest.saved");
1144 // Emit the finally block.
1147 // If the end of the finally is reachable, check whether this was
1148 // for EH. If so, rethrow.
1149 if (CGF.HaveInsertPoint()) {
1150 llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
1151 llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
1153 llvm::Value *ShouldRethrow =
1154 CGF.Builder.CreateFlagLoad(ForEHVar, "finally.shouldthrow");
1155 CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1157 CGF.EmitBlock(RethrowBB);
1159 CGF.EmitRuntimeCallOrInvoke(RethrowFn,
1160 CGF.Builder.CreateAlignedLoad(SavedExnVar, CGF.getPointerAlign()));
1162 CGF.EmitRuntimeCallOrInvoke(RethrowFn);
1164 CGF.Builder.CreateUnreachable();
1166 CGF.EmitBlock(ContBB);
1168 // Restore the cleanup destination.
1169 CGF.Builder.CreateStore(SavedCleanupDest,
1170 CGF.getNormalCleanupDestSlot());
1173 // Leave the end-catch cleanup. As an optimization, pretend that
1174 // the fallthrough path was inaccessible; we've dynamically proven
1175 // that we're not in the EH case along that path.
1177 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1178 CGF.PopCleanupBlock();
1179 CGF.Builder.restoreIP(SavedIP);
1182 // Now make sure we actually have an insertion point or the
1183 // cleanup gods will hate us.
1184 CGF.EnsureInsertPoint();
1187 } // end anonymous namespace
1189 /// Enters a finally block for an implementation using zero-cost
1190 /// exceptions. This is mostly general, but hard-codes some
1191 /// language/ABI-specific behavior in the catch-all sections.
1192 void CodeGenFunction::FinallyInfo::enter(CodeGenFunction &CGF,
1194 llvm::Constant *beginCatchFn,
1195 llvm::Constant *endCatchFn,
1196 llvm::Constant *rethrowFn) {
1197 assert((beginCatchFn != nullptr) == (endCatchFn != nullptr) &&
1198 "begin/end catch functions not paired");
1199 assert(rethrowFn && "rethrow function is required");
1201 BeginCatchFn = beginCatchFn;
1203 // The rethrow function has one of the following two types:
1206 // In the latter case we need to pass it the exception object.
1207 // But we can't use the exception slot because the @finally might
1208 // have a landing pad (which would overwrite the exception slot).
1209 llvm::FunctionType *rethrowFnTy =
1210 cast<llvm::FunctionType>(
1211 cast<llvm::PointerType>(rethrowFn->getType())->getElementType());
1212 SavedExnVar = nullptr;
1213 if (rethrowFnTy->getNumParams())
1214 SavedExnVar = CGF.CreateTempAlloca(CGF.Int8PtrTy, "finally.exn");
1216 // A finally block is a statement which must be executed on any edge
1217 // out of a given scope. Unlike a cleanup, the finally block may
1218 // contain arbitrary control flow leading out of itself. In
1219 // addition, finally blocks should always be executed, even if there
1220 // are no catch handlers higher on the stack. Therefore, we
1221 // surround the protected scope with a combination of a normal
1222 // cleanup (to catch attempts to break out of the block via normal
1223 // control flow) and an EH catch-all (semantically "outside" any try
1224 // statement to which the finally block might have been attached).
1225 // The finally block itself is generated in the context of a cleanup
1226 // which conditionally leaves the catch-all.
1228 // Jump destination for performing the finally block on an exception
1229 // edge. We'll never actually reach this block, so unreachable is
1231 RethrowDest = CGF.getJumpDestInCurrentScope(CGF.getUnreachableBlock());
1233 // Whether the finally block is being executed for EH purposes.
1234 ForEHVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "finally.for-eh");
1235 CGF.Builder.CreateFlagStore(false, ForEHVar);
1237 // Enter a normal cleanup which will perform the @finally block.
1238 CGF.EHStack.pushCleanup<PerformFinally>(NormalCleanup, body,
1239 ForEHVar, endCatchFn,
1240 rethrowFn, SavedExnVar);
1242 // Enter a catch-all scope.
1243 llvm::BasicBlock *catchBB = CGF.createBasicBlock("finally.catchall");
1244 EHCatchScope *catchScope = CGF.EHStack.pushCatch(1);
1245 catchScope->setCatchAllHandler(0, catchBB);
1248 void CodeGenFunction::FinallyInfo::exit(CodeGenFunction &CGF) {
1249 // Leave the finally catch-all.
1250 EHCatchScope &catchScope = cast<EHCatchScope>(*CGF.EHStack.begin());
1251 llvm::BasicBlock *catchBB = catchScope.getHandler(0).Block;
1253 CGF.popCatchScope();
1255 // If there are any references to the catch-all block, emit it.
1256 if (catchBB->use_empty()) {
1259 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveAndClearIP();
1260 CGF.EmitBlock(catchBB);
1262 llvm::Value *exn = nullptr;
1264 // If there's a begin-catch function, call it.
1266 exn = CGF.getExceptionFromSlot();
1267 CGF.EmitNounwindRuntimeCall(BeginCatchFn, exn);
1270 // If we need to remember the exception pointer to rethrow later, do so.
1272 if (!exn) exn = CGF.getExceptionFromSlot();
1273 CGF.Builder.CreateAlignedStore(exn, SavedExnVar, CGF.getPointerAlign());
1276 // Tell the cleanups in the finally block that we're do this for EH.
1277 CGF.Builder.CreateFlagStore(true, ForEHVar);
1279 // Thread a jump through the finally cleanup.
1280 CGF.EmitBranchThroughCleanup(RethrowDest);
1282 CGF.Builder.restoreIP(savedIP);
1285 // Finally, leave the @finally cleanup.
1286 CGF.PopCleanupBlock();
1289 llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
1290 if (TerminateLandingPad)
1291 return TerminateLandingPad;
1293 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1295 // This will get inserted at the end of the function.
1296 TerminateLandingPad = createBasicBlock("terminate.lpad");
1297 Builder.SetInsertPoint(TerminateLandingPad);
1299 // Tell the backend that this is a landing pad.
1300 const EHPersonality &Personality = EHPersonality::get(*this);
1302 if (!CurFn->hasPersonalityFn())
1303 CurFn->setPersonalityFn(getOpaquePersonalityFn(CGM, Personality));
1305 llvm::LandingPadInst *LPadInst = Builder.CreateLandingPad(
1306 llvm::StructType::get(Int8PtrTy, Int32Ty, nullptr), 0);
1307 LPadInst->addClause(getCatchAllValue(*this));
1309 llvm::Value *Exn = nullptr;
1310 if (getLangOpts().CPlusPlus)
1311 Exn = Builder.CreateExtractValue(LPadInst, 0);
1312 llvm::CallInst *terminateCall =
1313 CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
1314 terminateCall->setDoesNotReturn();
1315 Builder.CreateUnreachable();
1317 // Restore the saved insertion state.
1318 Builder.restoreIP(SavedIP);
1320 return TerminateLandingPad;
1323 llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
1324 if (TerminateHandler)
1325 return TerminateHandler;
1327 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1329 // Set up the terminate handler. This block is inserted at the very
1330 // end of the function by FinishFunction.
1331 TerminateHandler = createBasicBlock("terminate.handler");
1332 Builder.SetInsertPoint(TerminateHandler);
1333 llvm::Value *Exn = nullptr;
1334 SaveAndRestore<llvm::Instruction *> RestoreCurrentFuncletPad(
1336 if (EHPersonality::get(*this).usesFuncletPads()) {
1337 llvm::Value *ParentPad = CurrentFuncletPad;
1339 ParentPad = llvm::ConstantTokenNone::get(CGM.getLLVMContext());
1340 CurrentFuncletPad = Builder.CreateCleanupPad(ParentPad);
1342 if (getLangOpts().CPlusPlus)
1343 Exn = getExceptionFromSlot();
1345 llvm::CallInst *terminateCall =
1346 CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
1347 terminateCall->setDoesNotReturn();
1348 Builder.CreateUnreachable();
1350 // Restore the saved insertion state.
1351 Builder.restoreIP(SavedIP);
1353 return TerminateHandler;
1356 llvm::BasicBlock *CodeGenFunction::getEHResumeBlock(bool isCleanup) {
1357 if (EHResumeBlock) return EHResumeBlock;
1359 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1361 // We emit a jump to a notional label at the outermost unwind state.
1362 EHResumeBlock = createBasicBlock("eh.resume");
1363 Builder.SetInsertPoint(EHResumeBlock);
1365 const EHPersonality &Personality = EHPersonality::get(*this);
1367 // This can always be a call because we necessarily didn't find
1368 // anything on the EH stack which needs our help.
1369 const char *RethrowName = Personality.CatchallRethrowFn;
1370 if (RethrowName != nullptr && !isCleanup) {
1371 EmitRuntimeCall(getCatchallRethrowFn(CGM, RethrowName),
1372 getExceptionFromSlot())->setDoesNotReturn();
1373 Builder.CreateUnreachable();
1374 Builder.restoreIP(SavedIP);
1375 return EHResumeBlock;
1378 // Recreate the landingpad's return value for the 'resume' instruction.
1379 llvm::Value *Exn = getExceptionFromSlot();
1380 llvm::Value *Sel = getSelectorFromSlot();
1382 llvm::Type *LPadType = llvm::StructType::get(Exn->getType(),
1383 Sel->getType(), nullptr);
1384 llvm::Value *LPadVal = llvm::UndefValue::get(LPadType);
1385 LPadVal = Builder.CreateInsertValue(LPadVal, Exn, 0, "lpad.val");
1386 LPadVal = Builder.CreateInsertValue(LPadVal, Sel, 1, "lpad.val");
1388 Builder.CreateResume(LPadVal);
1389 Builder.restoreIP(SavedIP);
1390 return EHResumeBlock;
1393 void CodeGenFunction::EmitSEHTryStmt(const SEHTryStmt &S) {
1396 JumpDest TryExit = getJumpDestInCurrentScope("__try.__leave");
1398 SEHTryEpilogueStack.push_back(&TryExit);
1399 EmitStmt(S.getTryBlock());
1400 SEHTryEpilogueStack.pop_back();
1402 if (!TryExit.getBlock()->use_empty())
1403 EmitBlock(TryExit.getBlock(), /*IsFinished=*/true);
1405 delete TryExit.getBlock();
1411 struct PerformSEHFinally final : EHScopeStack::Cleanup {
1412 llvm::Function *OutlinedFinally;
1413 PerformSEHFinally(llvm::Function *OutlinedFinally)
1414 : OutlinedFinally(OutlinedFinally) {}
1416 void Emit(CodeGenFunction &CGF, Flags F) override {
1417 ASTContext &Context = CGF.getContext();
1418 CodeGenModule &CGM = CGF.CGM;
1422 // Compute the two argument values.
1423 QualType ArgTys[2] = {Context.UnsignedCharTy, Context.VoidPtrTy};
1424 llvm::Value *LocalAddrFn = CGM.getIntrinsic(llvm::Intrinsic::localaddress);
1425 llvm::Value *FP = CGF.Builder.CreateCall(LocalAddrFn);
1426 llvm::Value *IsForEH =
1427 llvm::ConstantInt::get(CGF.ConvertType(ArgTys[0]), F.isForEHCleanup());
1428 Args.add(RValue::get(IsForEH), ArgTys[0]);
1429 Args.add(RValue::get(FP), ArgTys[1]);
1431 // Arrange a two-arg function info and type.
1432 const CGFunctionInfo &FnInfo =
1433 CGM.getTypes().arrangeBuiltinFunctionCall(Context.VoidTy, Args);
1435 auto Callee = CGCallee::forDirect(OutlinedFinally);
1436 CGF.EmitCall(FnInfo, Callee, ReturnValueSlot(), Args);
1439 } // end anonymous namespace
1442 /// Find all local variable captures in the statement.
1443 struct CaptureFinder : ConstStmtVisitor<CaptureFinder> {
1444 CodeGenFunction &ParentCGF;
1445 const VarDecl *ParentThis;
1446 llvm::SmallSetVector<const VarDecl *, 4> Captures;
1447 Address SEHCodeSlot = Address::invalid();
1448 CaptureFinder(CodeGenFunction &ParentCGF, const VarDecl *ParentThis)
1449 : ParentCGF(ParentCGF), ParentThis(ParentThis) {}
1451 // Return true if we need to do any capturing work.
1452 bool foundCaptures() {
1453 return !Captures.empty() || SEHCodeSlot.isValid();
1456 void Visit(const Stmt *S) {
1457 // See if this is a capture, then recurse.
1458 ConstStmtVisitor<CaptureFinder>::Visit(S);
1459 for (const Stmt *Child : S->children())
1464 void VisitDeclRefExpr(const DeclRefExpr *E) {
1465 // If this is already a capture, just make sure we capture 'this'.
1466 if (E->refersToEnclosingVariableOrCapture()) {
1467 Captures.insert(ParentThis);
1471 const auto *D = dyn_cast<VarDecl>(E->getDecl());
1472 if (D && D->isLocalVarDeclOrParm() && D->hasLocalStorage())
1476 void VisitCXXThisExpr(const CXXThisExpr *E) {
1477 Captures.insert(ParentThis);
1480 void VisitCallExpr(const CallExpr *E) {
1481 // We only need to add parent frame allocations for these builtins in x86.
1482 if (ParentCGF.getTarget().getTriple().getArch() != llvm::Triple::x86)
1485 unsigned ID = E->getBuiltinCallee();
1487 case Builtin::BI__exception_code:
1488 case Builtin::BI_exception_code:
1489 // This is the simple case where we are the outermost finally. All we
1490 // have to do here is make sure we escape this and recover it in the
1491 // outlined handler.
1492 if (!SEHCodeSlot.isValid())
1493 SEHCodeSlot = ParentCGF.SEHCodeSlotStack.back();
1498 } // end anonymous namespace
1500 Address CodeGenFunction::recoverAddrOfEscapedLocal(CodeGenFunction &ParentCGF,
1502 llvm::Value *ParentFP) {
1503 llvm::CallInst *RecoverCall = nullptr;
1504 CGBuilderTy Builder(*this, AllocaInsertPt);
1505 if (auto *ParentAlloca = dyn_cast<llvm::AllocaInst>(ParentVar.getPointer())) {
1506 // Mark the variable escaped if nobody else referenced it and compute the
1507 // localescape index.
1508 auto InsertPair = ParentCGF.EscapedLocals.insert(
1509 std::make_pair(ParentAlloca, ParentCGF.EscapedLocals.size()));
1510 int FrameEscapeIdx = InsertPair.first->second;
1511 // call i8* @llvm.localrecover(i8* bitcast(@parentFn), i8* %fp, i32 N)
1512 llvm::Function *FrameRecoverFn = llvm::Intrinsic::getDeclaration(
1513 &CGM.getModule(), llvm::Intrinsic::localrecover);
1514 llvm::Constant *ParentI8Fn =
1515 llvm::ConstantExpr::getBitCast(ParentCGF.CurFn, Int8PtrTy);
1516 RecoverCall = Builder.CreateCall(
1517 FrameRecoverFn, {ParentI8Fn, ParentFP,
1518 llvm::ConstantInt::get(Int32Ty, FrameEscapeIdx)});
1521 // If the parent didn't have an alloca, we're doing some nested outlining.
1522 // Just clone the existing localrecover call, but tweak the FP argument to
1523 // use our FP value. All other arguments are constants.
1524 auto *ParentRecover =
1525 cast<llvm::IntrinsicInst>(ParentVar.getPointer()->stripPointerCasts());
1526 assert(ParentRecover->getIntrinsicID() == llvm::Intrinsic::localrecover &&
1527 "expected alloca or localrecover in parent LocalDeclMap");
1528 RecoverCall = cast<llvm::CallInst>(ParentRecover->clone());
1529 RecoverCall->setArgOperand(1, ParentFP);
1530 RecoverCall->insertBefore(AllocaInsertPt);
1533 // Bitcast the variable, rename it, and insert it in the local decl map.
1534 llvm::Value *ChildVar =
1535 Builder.CreateBitCast(RecoverCall, ParentVar.getType());
1536 ChildVar->setName(ParentVar.getName());
1537 return Address(ChildVar, ParentVar.getAlignment());
1540 void CodeGenFunction::EmitCapturedLocals(CodeGenFunction &ParentCGF,
1541 const Stmt *OutlinedStmt,
1543 // Find all captures in the Stmt.
1544 CaptureFinder Finder(ParentCGF, ParentCGF.CXXABIThisDecl);
1545 Finder.Visit(OutlinedStmt);
1547 // We can exit early on x86_64 when there are no captures. We just have to
1548 // save the exception code in filters so that __exception_code() works.
1549 if (!Finder.foundCaptures() &&
1550 CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
1552 EmitSEHExceptionCodeSave(ParentCGF, nullptr, nullptr);
1556 llvm::Value *EntryFP = nullptr;
1557 CGBuilderTy Builder(CGM, AllocaInsertPt);
1558 if (IsFilter && CGM.getTarget().getTriple().getArch() == llvm::Triple::x86) {
1559 // 32-bit SEH filters need to be careful about FP recovery. The end of the
1560 // EH registration is passed in as the EBP physical register. We can
1561 // recover that with llvm.frameaddress(1).
1562 EntryFP = Builder.CreateCall(
1563 CGM.getIntrinsic(llvm::Intrinsic::frameaddress), {Builder.getInt32(1)});
1565 // Otherwise, for x64 and 32-bit finally functions, the parent FP is the
1566 // second parameter.
1567 auto AI = CurFn->arg_begin();
1572 llvm::Value *ParentFP = EntryFP;
1574 // Given whatever FP the runtime provided us in EntryFP, recover the true
1575 // frame pointer of the parent function. We only need to do this in filters,
1576 // since finally funclets recover the parent FP for us.
1577 llvm::Function *RecoverFPIntrin =
1578 CGM.getIntrinsic(llvm::Intrinsic::x86_seh_recoverfp);
1579 llvm::Constant *ParentI8Fn =
1580 llvm::ConstantExpr::getBitCast(ParentCGF.CurFn, Int8PtrTy);
1581 ParentFP = Builder.CreateCall(RecoverFPIntrin, {ParentI8Fn, EntryFP});
1584 // Create llvm.localrecover calls for all captures.
1585 for (const VarDecl *VD : Finder.Captures) {
1586 if (isa<ImplicitParamDecl>(VD)) {
1587 CGM.ErrorUnsupported(VD, "'this' captured by SEH");
1588 CXXThisValue = llvm::UndefValue::get(ConvertTypeForMem(VD->getType()));
1591 if (VD->getType()->isVariablyModifiedType()) {
1592 CGM.ErrorUnsupported(VD, "VLA captured by SEH");
1595 assert((isa<ImplicitParamDecl>(VD) || VD->isLocalVarDeclOrParm()) &&
1596 "captured non-local variable");
1598 // If this decl hasn't been declared yet, it will be declared in the
1600 auto I = ParentCGF.LocalDeclMap.find(VD);
1601 if (I == ParentCGF.LocalDeclMap.end())
1604 Address ParentVar = I->second;
1606 VD, recoverAddrOfEscapedLocal(ParentCGF, ParentVar, ParentFP));
1609 if (Finder.SEHCodeSlot.isValid()) {
1610 SEHCodeSlotStack.push_back(
1611 recoverAddrOfEscapedLocal(ParentCGF, Finder.SEHCodeSlot, ParentFP));
1615 EmitSEHExceptionCodeSave(ParentCGF, ParentFP, EntryFP);
1618 /// Arrange a function prototype that can be called by Windows exception
1619 /// handling personalities. On Win64, the prototype looks like:
1620 /// RetTy func(void *EHPtrs, void *ParentFP);
1621 void CodeGenFunction::startOutlinedSEHHelper(CodeGenFunction &ParentCGF,
1623 const Stmt *OutlinedStmt) {
1624 SourceLocation StartLoc = OutlinedStmt->getLocStart();
1626 // Get the mangled function name.
1627 SmallString<128> Name;
1629 llvm::raw_svector_ostream OS(Name);
1630 const FunctionDecl *ParentSEHFn = ParentCGF.CurSEHParent;
1631 assert(ParentSEHFn && "No CurSEHParent!");
1632 MangleContext &Mangler = CGM.getCXXABI().getMangleContext();
1634 Mangler.mangleSEHFilterExpression(ParentSEHFn, OS);
1636 Mangler.mangleSEHFinallyBlock(ParentSEHFn, OS);
1639 FunctionArgList Args;
1640 if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86 || !IsFilter) {
1641 // All SEH finally functions take two parameters. Win64 filters take two
1642 // parameters. Win32 filters take no parameters.
1644 Args.push_back(ImplicitParamDecl::Create(
1645 getContext(), nullptr, StartLoc,
1646 &getContext().Idents.get("exception_pointers"),
1647 getContext().VoidPtrTy));
1649 Args.push_back(ImplicitParamDecl::Create(
1650 getContext(), nullptr, StartLoc,
1651 &getContext().Idents.get("abnormal_termination"),
1652 getContext().UnsignedCharTy));
1654 Args.push_back(ImplicitParamDecl::Create(
1655 getContext(), nullptr, StartLoc,
1656 &getContext().Idents.get("frame_pointer"), getContext().VoidPtrTy));
1659 QualType RetTy = IsFilter ? getContext().LongTy : getContext().VoidTy;
1661 llvm::Function *ParentFn = ParentCGF.CurFn;
1662 const CGFunctionInfo &FnInfo =
1663 CGM.getTypes().arrangeBuiltinFunctionDeclaration(RetTy, Args);
1665 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
1666 llvm::Function *Fn = llvm::Function::Create(
1667 FnTy, llvm::GlobalValue::InternalLinkage, Name.str(), &CGM.getModule());
1668 // The filter is either in the same comdat as the function, or it's internal.
1669 if (llvm::Comdat *C = ParentFn->getComdat()) {
1671 } else if (ParentFn->hasWeakLinkage() || ParentFn->hasLinkOnceLinkage()) {
1672 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(ParentFn->getName());
1673 ParentFn->setComdat(C);
1676 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
1679 IsOutlinedSEHHelper = true;
1681 StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args,
1682 OutlinedStmt->getLocStart(), OutlinedStmt->getLocStart());
1683 CurSEHParent = ParentCGF.CurSEHParent;
1685 CGM.SetLLVMFunctionAttributes(nullptr, FnInfo, CurFn);
1686 EmitCapturedLocals(ParentCGF, OutlinedStmt, IsFilter);
1689 /// Create a stub filter function that will ultimately hold the code of the
1690 /// filter expression. The EH preparation passes in LLVM will outline the code
1691 /// from the main function body into this stub.
1693 CodeGenFunction::GenerateSEHFilterFunction(CodeGenFunction &ParentCGF,
1694 const SEHExceptStmt &Except) {
1695 const Expr *FilterExpr = Except.getFilterExpr();
1696 startOutlinedSEHHelper(ParentCGF, true, FilterExpr);
1698 // Emit the original filter expression, convert to i32, and return.
1699 llvm::Value *R = EmitScalarExpr(FilterExpr);
1700 R = Builder.CreateIntCast(R, ConvertType(getContext().LongTy),
1701 FilterExpr->getType()->isSignedIntegerType());
1702 Builder.CreateStore(R, ReturnValue);
1704 FinishFunction(FilterExpr->getLocEnd());
1710 CodeGenFunction::GenerateSEHFinallyFunction(CodeGenFunction &ParentCGF,
1711 const SEHFinallyStmt &Finally) {
1712 const Stmt *FinallyBlock = Finally.getBlock();
1713 startOutlinedSEHHelper(ParentCGF, false, FinallyBlock);
1715 // Emit the original filter expression, convert to i32, and return.
1716 EmitStmt(FinallyBlock);
1718 FinishFunction(FinallyBlock->getLocEnd());
1723 void CodeGenFunction::EmitSEHExceptionCodeSave(CodeGenFunction &ParentCGF,
1724 llvm::Value *ParentFP,
1725 llvm::Value *EntryFP) {
1726 // Get the pointer to the EXCEPTION_POINTERS struct. This is returned by the
1727 // __exception_info intrinsic.
1728 if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
1729 // On Win64, the info is passed as the first parameter to the filter.
1730 SEHInfo = &*CurFn->arg_begin();
1731 SEHCodeSlotStack.push_back(
1732 CreateMemTemp(getContext().IntTy, "__exception_code"));
1734 // On Win32, the EBP on entry to the filter points to the end of an
1735 // exception registration object. It contains 6 32-bit fields, and the info
1736 // pointer is stored in the second field. So, GEP 20 bytes backwards and
1737 // load the pointer.
1738 SEHInfo = Builder.CreateConstInBoundsGEP1_32(Int8Ty, EntryFP, -20);
1739 SEHInfo = Builder.CreateBitCast(SEHInfo, Int8PtrTy->getPointerTo());
1740 SEHInfo = Builder.CreateAlignedLoad(Int8PtrTy, SEHInfo, getPointerAlign());
1741 SEHCodeSlotStack.push_back(recoverAddrOfEscapedLocal(
1742 ParentCGF, ParentCGF.SEHCodeSlotStack.back(), ParentFP));
1745 // Save the exception code in the exception slot to unify exception access in
1746 // the filter function and the landing pad.
1747 // struct EXCEPTION_POINTERS {
1748 // EXCEPTION_RECORD *ExceptionRecord;
1749 // CONTEXT *ContextRecord;
1751 // int exceptioncode = exception_pointers->ExceptionRecord->ExceptionCode;
1752 llvm::Type *RecordTy = CGM.Int32Ty->getPointerTo();
1753 llvm::Type *PtrsTy = llvm::StructType::get(RecordTy, CGM.VoidPtrTy, nullptr);
1754 llvm::Value *Ptrs = Builder.CreateBitCast(SEHInfo, PtrsTy->getPointerTo());
1755 llvm::Value *Rec = Builder.CreateStructGEP(PtrsTy, Ptrs, 0);
1756 Rec = Builder.CreateAlignedLoad(Rec, getPointerAlign());
1757 llvm::Value *Code = Builder.CreateAlignedLoad(Rec, getIntAlign());
1758 assert(!SEHCodeSlotStack.empty() && "emitting EH code outside of __except");
1759 Builder.CreateStore(Code, SEHCodeSlotStack.back());
1762 llvm::Value *CodeGenFunction::EmitSEHExceptionInfo() {
1763 // Sema should diagnose calling this builtin outside of a filter context, but
1764 // don't crash if we screw up.
1766 return llvm::UndefValue::get(Int8PtrTy);
1767 assert(SEHInfo->getType() == Int8PtrTy);
1771 llvm::Value *CodeGenFunction::EmitSEHExceptionCode() {
1772 assert(!SEHCodeSlotStack.empty() && "emitting EH code outside of __except");
1773 return Builder.CreateLoad(SEHCodeSlotStack.back());
1776 llvm::Value *CodeGenFunction::EmitSEHAbnormalTermination() {
1777 // Abnormal termination is just the first parameter to the outlined finally
1779 auto AI = CurFn->arg_begin();
1780 return Builder.CreateZExt(&*AI, Int32Ty);
1783 void CodeGenFunction::EnterSEHTryStmt(const SEHTryStmt &S) {
1784 CodeGenFunction HelperCGF(CGM, /*suppressNewContext=*/true);
1785 if (const SEHFinallyStmt *Finally = S.getFinallyHandler()) {
1786 // Outline the finally block.
1787 llvm::Function *FinallyFunc =
1788 HelperCGF.GenerateSEHFinallyFunction(*this, *Finally);
1790 // Push a cleanup for __finally blocks.
1791 EHStack.pushCleanup<PerformSEHFinally>(NormalAndEHCleanup, FinallyFunc);
1795 // Otherwise, we must have an __except block.
1796 const SEHExceptStmt *Except = S.getExceptHandler();
1798 EHCatchScope *CatchScope = EHStack.pushCatch(1);
1799 SEHCodeSlotStack.push_back(
1800 CreateMemTemp(getContext().IntTy, "__exception_code"));
1802 // If the filter is known to evaluate to 1, then we can use the clause
1803 // "catch i8* null". We can't do this on x86 because the filter has to save
1804 // the exception code.
1806 CGM.EmitConstantExpr(Except->getFilterExpr(), getContext().IntTy, this);
1807 if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86 && C &&
1809 CatchScope->setCatchAllHandler(0, createBasicBlock("__except"));
1813 // In general, we have to emit an outlined filter function. Use the function
1814 // in place of the RTTI typeinfo global that C++ EH uses.
1815 llvm::Function *FilterFunc =
1816 HelperCGF.GenerateSEHFilterFunction(*this, *Except);
1817 llvm::Constant *OpaqueFunc =
1818 llvm::ConstantExpr::getBitCast(FilterFunc, Int8PtrTy);
1819 CatchScope->setHandler(0, OpaqueFunc, createBasicBlock("__except.ret"));
1822 void CodeGenFunction::ExitSEHTryStmt(const SEHTryStmt &S) {
1823 // Just pop the cleanup if it's a __finally block.
1824 if (S.getFinallyHandler()) {
1829 // Otherwise, we must have an __except block.
1830 const SEHExceptStmt *Except = S.getExceptHandler();
1831 assert(Except && "__try must have __finally xor __except");
1832 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1834 // Don't emit the __except block if the __try block lacked invokes.
1835 // TODO: Model unwind edges from instructions, either with iload / istore or
1836 // a try body function.
1837 if (!CatchScope.hasEHBranches()) {
1838 CatchScope.clearHandlerBlocks();
1840 SEHCodeSlotStack.pop_back();
1844 // The fall-through block.
1845 llvm::BasicBlock *ContBB = createBasicBlock("__try.cont");
1847 // We just emitted the body of the __try; jump to the continue block.
1848 if (HaveInsertPoint())
1849 Builder.CreateBr(ContBB);
1851 // Check if our filter function returned true.
1852 emitCatchDispatchBlock(*this, CatchScope);
1854 // Grab the block before we pop the handler.
1855 llvm::BasicBlock *CatchPadBB = CatchScope.getHandler(0).Block;
1858 EmitBlockAfterUses(CatchPadBB);
1860 // __except blocks don't get outlined into funclets, so immediately do a
1862 llvm::CatchPadInst *CPI =
1863 cast<llvm::CatchPadInst>(CatchPadBB->getFirstNonPHI());
1864 llvm::BasicBlock *ExceptBB = createBasicBlock("__except");
1865 Builder.CreateCatchRet(CPI, ExceptBB);
1866 EmitBlock(ExceptBB);
1868 // On Win64, the exception code is returned in EAX. Copy it into the slot.
1869 if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
1870 llvm::Function *SEHCodeIntrin =
1871 CGM.getIntrinsic(llvm::Intrinsic::eh_exceptioncode);
1872 llvm::Value *Code = Builder.CreateCall(SEHCodeIntrin, {CPI});
1873 Builder.CreateStore(Code, SEHCodeSlotStack.back());
1876 // Emit the __except body.
1877 EmitStmt(Except->getBlock());
1879 // End the lifetime of the exception code.
1880 SEHCodeSlotStack.pop_back();
1882 if (HaveInsertPoint())
1883 Builder.CreateBr(ContBB);
1888 void CodeGenFunction::EmitSEHLeaveStmt(const SEHLeaveStmt &S) {
1889 // If this code is reachable then emit a stop point (if generating
1890 // debug info). We have to do this ourselves because we are on the
1891 // "simple" statement path.
1892 if (HaveInsertPoint())
1895 // This must be a __leave from a __finally block, which we warn on and is UB.
1896 // Just emit unreachable.
1897 if (!isSEHTryScope()) {
1898 Builder.CreateUnreachable();
1899 Builder.ClearInsertionPoint();
1903 EmitBranchThroughCleanup(*SEHTryEpilogueStack.back());