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_ObjC_SJLJ = {"__gnu_objc_personality_sj0", "objc_exception_throw"};
102 EHPersonality::GNU_ObjC_SEH = {"__gnu_objc_personality_seh0", "objc_exception_throw"};
104 EHPersonality::GNU_ObjCXX = { "__gnustep_objcxx_personality_v0", nullptr };
106 EHPersonality::GNUstep_ObjC = { "__gnustep_objc_personality_v0", nullptr };
108 EHPersonality::MSVC_except_handler = { "_except_handler3", nullptr };
110 EHPersonality::MSVC_C_specific_handler = { "__C_specific_handler", nullptr };
112 EHPersonality::MSVC_CxxFrameHandler3 = { "__CxxFrameHandler3", nullptr };
114 /// On Win64, use libgcc's SEH personality function. We fall back to dwarf on
115 /// other platforms, unless the user asked for SjLj exceptions.
116 static bool useLibGCCSEHPersonality(const llvm::Triple &T) {
117 return T.isOSWindows() && T.getArch() == llvm::Triple::x86_64;
120 static const EHPersonality &getCPersonality(const llvm::Triple &T,
121 const LangOptions &L) {
122 if (L.SjLjExceptions)
123 return EHPersonality::GNU_C_SJLJ;
124 else if (useLibGCCSEHPersonality(T))
125 return EHPersonality::GNU_C_SEH;
126 return EHPersonality::GNU_C;
129 static const EHPersonality &getObjCPersonality(const llvm::Triple &T,
130 const LangOptions &L) {
131 switch (L.ObjCRuntime.getKind()) {
132 case ObjCRuntime::FragileMacOSX:
133 return getCPersonality(T, L);
134 case ObjCRuntime::MacOSX:
135 case ObjCRuntime::iOS:
136 case ObjCRuntime::WatchOS:
137 return EHPersonality::NeXT_ObjC;
138 case ObjCRuntime::GNUstep:
139 if (L.ObjCRuntime.getVersion() >= VersionTuple(1, 7))
140 return EHPersonality::GNUstep_ObjC;
142 case ObjCRuntime::GCC:
143 case ObjCRuntime::ObjFW:
144 if (L.SjLjExceptions)
145 return EHPersonality::GNU_ObjC_SJLJ;
146 else if (useLibGCCSEHPersonality(T))
147 return EHPersonality::GNU_ObjC_SEH;
148 return EHPersonality::GNU_ObjC;
150 llvm_unreachable("bad runtime kind");
153 static const EHPersonality &getCXXPersonality(const llvm::Triple &T,
154 const LangOptions &L) {
155 if (L.SjLjExceptions)
156 return EHPersonality::GNU_CPlusPlus_SJLJ;
157 else if (useLibGCCSEHPersonality(T))
158 return EHPersonality::GNU_CPlusPlus_SEH;
159 return EHPersonality::GNU_CPlusPlus;
162 /// Determines the personality function to use when both C++
163 /// and Objective-C exceptions are being caught.
164 static const EHPersonality &getObjCXXPersonality(const llvm::Triple &T,
165 const LangOptions &L) {
166 switch (L.ObjCRuntime.getKind()) {
167 // The ObjC personality defers to the C++ personality for non-ObjC
168 // handlers. Unlike the C++ case, we use the same personality
169 // function on targets using (backend-driven) SJLJ EH.
170 case ObjCRuntime::MacOSX:
171 case ObjCRuntime::iOS:
172 case ObjCRuntime::WatchOS:
173 return EHPersonality::NeXT_ObjC;
175 // In the fragile ABI, just use C++ exception handling and hope
176 // they're not doing crazy exception mixing.
177 case ObjCRuntime::FragileMacOSX:
178 return getCXXPersonality(T, L);
180 // The GCC runtime's personality function inherently doesn't support
181 // mixed EH. Use the C++ personality just to avoid returning null.
182 case ObjCRuntime::GCC:
183 case ObjCRuntime::ObjFW: // XXX: this will change soon
184 return EHPersonality::GNU_ObjC;
185 case ObjCRuntime::GNUstep:
186 return EHPersonality::GNU_ObjCXX;
188 llvm_unreachable("bad runtime kind");
191 static const EHPersonality &getSEHPersonalityMSVC(const llvm::Triple &T) {
192 if (T.getArch() == llvm::Triple::x86)
193 return EHPersonality::MSVC_except_handler;
194 return EHPersonality::MSVC_C_specific_handler;
197 const EHPersonality &EHPersonality::get(CodeGenModule &CGM,
198 const FunctionDecl *FD) {
199 const llvm::Triple &T = CGM.getTarget().getTriple();
200 const LangOptions &L = CGM.getLangOpts();
202 // Functions using SEH get an SEH personality.
203 if (FD && FD->usesSEHTry())
204 return getSEHPersonalityMSVC(T);
206 // Try to pick a personality function that is compatible with MSVC if we're
207 // not compiling Obj-C. Obj-C users better have an Obj-C runtime that supports
208 // the GCC-style personality function.
209 if (T.isWindowsMSVCEnvironment() && !L.ObjC1) {
210 if (L.SjLjExceptions)
211 return EHPersonality::GNU_CPlusPlus_SJLJ;
213 return EHPersonality::MSVC_CxxFrameHandler3;
216 if (L.CPlusPlus && L.ObjC1)
217 return getObjCXXPersonality(T, L);
218 else if (L.CPlusPlus)
219 return getCXXPersonality(T, L);
221 return getObjCPersonality(T, L);
223 return getCPersonality(T, L);
226 const EHPersonality &EHPersonality::get(CodeGenFunction &CGF) {
227 return get(CGF.CGM, dyn_cast_or_null<FunctionDecl>(CGF.CurCodeDecl));
230 static llvm::Constant *getPersonalityFn(CodeGenModule &CGM,
231 const EHPersonality &Personality) {
232 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.Int32Ty, true),
233 Personality.PersonalityFn,
234 llvm::AttributeSet(), /*Local=*/true);
237 static llvm::Constant *getOpaquePersonalityFn(CodeGenModule &CGM,
238 const EHPersonality &Personality) {
239 llvm::Constant *Fn = getPersonalityFn(CGM, Personality);
240 return llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
243 /// Check whether a landingpad instruction only uses C++ features.
244 static bool LandingPadHasOnlyCXXUses(llvm::LandingPadInst *LPI) {
245 for (unsigned I = 0, E = LPI->getNumClauses(); I != E; ++I) {
246 // Look for something that would've been returned by the ObjC
247 // runtime's GetEHType() method.
248 llvm::Value *Val = LPI->getClause(I)->stripPointerCasts();
249 if (LPI->isCatch(I)) {
250 // Check if the catch value has the ObjC prefix.
251 if (llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Val))
252 // ObjC EH selector entries are always global variables with
253 // names starting like this.
254 if (GV->getName().startswith("OBJC_EHTYPE"))
257 // Check if any of the filter values have the ObjC prefix.
258 llvm::Constant *CVal = cast<llvm::Constant>(Val);
259 for (llvm::User::op_iterator
260 II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II) {
261 if (llvm::GlobalVariable *GV =
262 cast<llvm::GlobalVariable>((*II)->stripPointerCasts()))
263 // ObjC EH selector entries are always global variables with
264 // names starting like this.
265 if (GV->getName().startswith("OBJC_EHTYPE"))
273 /// Check whether a personality function could reasonably be swapped
274 /// for a C++ personality function.
275 static bool PersonalityHasOnlyCXXUses(llvm::Constant *Fn) {
276 for (llvm::User *U : Fn->users()) {
277 // Conditionally white-list bitcasts.
278 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(U)) {
279 if (CE->getOpcode() != llvm::Instruction::BitCast) return false;
280 if (!PersonalityHasOnlyCXXUses(CE))
285 // Otherwise it must be a function.
286 llvm::Function *F = dyn_cast<llvm::Function>(U);
287 if (!F) return false;
289 for (auto BB = F->begin(), E = F->end(); BB != E; ++BB) {
290 if (BB->isLandingPad())
291 if (!LandingPadHasOnlyCXXUses(BB->getLandingPadInst()))
299 /// Try to use the C++ personality function in ObjC++. Not doing this
300 /// can cause some incompatibilities with gcc, which is more
301 /// aggressive about only using the ObjC++ personality in a function
302 /// when it really needs it.
303 void CodeGenModule::SimplifyPersonality() {
304 // If we're not in ObjC++ -fexceptions, there's nothing to do.
305 if (!LangOpts.CPlusPlus || !LangOpts.ObjC1 || !LangOpts.Exceptions)
308 // Both the problem this endeavors to fix and the way the logic
309 // above works is specific to the NeXT runtime.
310 if (!LangOpts.ObjCRuntime.isNeXTFamily())
313 const EHPersonality &ObjCXX = EHPersonality::get(*this, /*FD=*/nullptr);
314 const EHPersonality &CXX =
315 getCXXPersonality(getTarget().getTriple(), LangOpts);
319 assert(std::strcmp(ObjCXX.PersonalityFn, CXX.PersonalityFn) != 0 &&
320 "Different EHPersonalities using the same personality function.");
322 llvm::Function *Fn = getModule().getFunction(ObjCXX.PersonalityFn);
324 // Nothing to do if it's unused.
325 if (!Fn || Fn->use_empty()) return;
327 // Can't do the optimization if it has non-C++ uses.
328 if (!PersonalityHasOnlyCXXUses(Fn)) return;
330 // Create the C++ personality function and kill off the old
332 llvm::Constant *CXXFn = getPersonalityFn(*this, CXX);
334 // This can happen if the user is screwing with us.
335 if (Fn->getType() != CXXFn->getType()) return;
337 Fn->replaceAllUsesWith(CXXFn);
338 Fn->eraseFromParent();
341 /// Returns the value to inject into a selector to indicate the
342 /// presence of a catch-all.
343 static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
344 // Possibly we should use @llvm.eh.catch.all.value here.
345 return llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
349 /// A cleanup to free the exception object if its initialization
351 struct FreeException final : EHScopeStack::Cleanup {
353 FreeException(llvm::Value *exn) : exn(exn) {}
354 void Emit(CodeGenFunction &CGF, Flags flags) override {
355 CGF.EmitNounwindRuntimeCall(getFreeExceptionFn(CGF.CGM), exn);
358 } // end anonymous namespace
360 // Emits an exception expression into the given location. This
361 // differs from EmitAnyExprToMem only in that, if a final copy-ctor
362 // call is required, an exception within that copy ctor causes
363 // std::terminate to be invoked.
364 void CodeGenFunction::EmitAnyExprToExn(const Expr *e, Address addr) {
365 // Make sure the exception object is cleaned up if there's an
366 // exception during initialization.
367 pushFullExprCleanup<FreeException>(EHCleanup, addr.getPointer());
368 EHScopeStack::stable_iterator cleanup = EHStack.stable_begin();
370 // __cxa_allocate_exception returns a void*; we need to cast this
371 // to the appropriate type for the object.
372 llvm::Type *ty = ConvertTypeForMem(e->getType())->getPointerTo();
373 Address typedAddr = Builder.CreateBitCast(addr, ty);
375 // FIXME: this isn't quite right! If there's a final unelided call
376 // to a copy constructor, then according to [except.terminate]p1 we
377 // must call std::terminate() if that constructor throws, because
378 // technically that copy occurs after the exception expression is
379 // evaluated but before the exception is caught. But the best way
380 // to handle that is to teach EmitAggExpr to do the final copy
381 // differently if it can't be elided.
382 EmitAnyExprToMem(e, typedAddr, e->getType().getQualifiers(),
385 // Deactivate the cleanup block.
386 DeactivateCleanupBlock(cleanup,
387 cast<llvm::Instruction>(typedAddr.getPointer()));
390 Address CodeGenFunction::getExceptionSlot() {
392 ExceptionSlot = CreateTempAlloca(Int8PtrTy, "exn.slot");
393 return Address(ExceptionSlot, getPointerAlign());
396 Address CodeGenFunction::getEHSelectorSlot() {
398 EHSelectorSlot = CreateTempAlloca(Int32Ty, "ehselector.slot");
399 return Address(EHSelectorSlot, CharUnits::fromQuantity(4));
402 llvm::Value *CodeGenFunction::getExceptionFromSlot() {
403 return Builder.CreateLoad(getExceptionSlot(), "exn");
406 llvm::Value *CodeGenFunction::getSelectorFromSlot() {
407 return Builder.CreateLoad(getEHSelectorSlot(), "sel");
410 void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E,
411 bool KeepInsertionPoint) {
412 if (const Expr *SubExpr = E->getSubExpr()) {
413 QualType ThrowType = SubExpr->getType();
414 if (ThrowType->isObjCObjectPointerType()) {
415 const Stmt *ThrowStmt = E->getSubExpr();
416 const ObjCAtThrowStmt S(E->getExprLoc(), const_cast<Stmt *>(ThrowStmt));
417 CGM.getObjCRuntime().EmitThrowStmt(*this, S, false);
419 CGM.getCXXABI().emitThrow(*this, E);
422 CGM.getCXXABI().emitRethrow(*this, /*isNoReturn=*/true);
425 // throw is an expression, and the expression emitters expect us
426 // to leave ourselves at a valid insertion point.
427 if (KeepInsertionPoint)
428 EmitBlock(createBasicBlock("throw.cont"));
431 void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
432 if (!CGM.getLangOpts().CXXExceptions)
435 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
437 // Check if CapturedDecl is nothrow and create terminate scope for it.
438 if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
440 EHStack.pushTerminate();
444 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
448 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
449 if (isNoexceptExceptionSpec(EST)) {
450 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
451 // noexcept functions are simple terminate scopes.
452 EHStack.pushTerminate();
454 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
455 // TODO: Revisit exception specifications for the MS ABI. There is a way to
456 // encode these in an object file but MSVC doesn't do anything with it.
457 if (getTarget().getCXXABI().isMicrosoft())
459 unsigned NumExceptions = Proto->getNumExceptions();
460 EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
462 for (unsigned I = 0; I != NumExceptions; ++I) {
463 QualType Ty = Proto->getExceptionType(I);
464 QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
465 llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType,
467 Filter->setFilter(I, EHType);
472 /// Emit the dispatch block for a filter scope if necessary.
473 static void emitFilterDispatchBlock(CodeGenFunction &CGF,
474 EHFilterScope &filterScope) {
475 llvm::BasicBlock *dispatchBlock = filterScope.getCachedEHDispatchBlock();
476 if (!dispatchBlock) return;
477 if (dispatchBlock->use_empty()) {
478 delete dispatchBlock;
482 CGF.EmitBlockAfterUses(dispatchBlock);
484 // If this isn't a catch-all filter, we need to check whether we got
485 // here because the filter triggered.
486 if (filterScope.getNumFilters()) {
487 // Load the selector value.
488 llvm::Value *selector = CGF.getSelectorFromSlot();
489 llvm::BasicBlock *unexpectedBB = CGF.createBasicBlock("ehspec.unexpected");
491 llvm::Value *zero = CGF.Builder.getInt32(0);
492 llvm::Value *failsFilter =
493 CGF.Builder.CreateICmpSLT(selector, zero, "ehspec.fails");
494 CGF.Builder.CreateCondBr(failsFilter, unexpectedBB,
495 CGF.getEHResumeBlock(false));
497 CGF.EmitBlock(unexpectedBB);
500 // Call __cxa_call_unexpected. This doesn't need to be an invoke
501 // because __cxa_call_unexpected magically filters exceptions
502 // according to the last landing pad the exception was thrown
504 llvm::Value *exn = CGF.getExceptionFromSlot();
505 CGF.EmitRuntimeCall(getUnexpectedFn(CGF.CGM), exn)
506 ->setDoesNotReturn();
507 CGF.Builder.CreateUnreachable();
510 void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
511 if (!CGM.getLangOpts().CXXExceptions)
514 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
516 // Check if CapturedDecl is nothrow and pop terminate scope for it.
517 if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
519 EHStack.popTerminate();
523 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
527 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
528 if (isNoexceptExceptionSpec(EST)) {
529 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
530 EHStack.popTerminate();
532 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
533 // TODO: Revisit exception specifications for the MS ABI. There is a way to
534 // encode these in an object file but MSVC doesn't do anything with it.
535 if (getTarget().getCXXABI().isMicrosoft())
537 EHFilterScope &filterScope = cast<EHFilterScope>(*EHStack.begin());
538 emitFilterDispatchBlock(*this, filterScope);
543 void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
545 EmitStmt(S.getTryBlock());
549 void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
550 unsigned NumHandlers = S.getNumHandlers();
551 EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
553 for (unsigned I = 0; I != NumHandlers; ++I) {
554 const CXXCatchStmt *C = S.getHandler(I);
556 llvm::BasicBlock *Handler = createBasicBlock("catch");
557 if (C->getExceptionDecl()) {
558 // FIXME: Dropping the reference type on the type into makes it
559 // impossible to correctly implement catch-by-reference
560 // semantics for pointers. Unfortunately, this is what all
561 // existing compilers do, and it's not clear that the standard
562 // personality routine is capable of doing this right. See C++ DR 388:
563 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
564 Qualifiers CaughtTypeQuals;
565 QualType CaughtType = CGM.getContext().getUnqualifiedArrayType(
566 C->getCaughtType().getNonReferenceType(), CaughtTypeQuals);
568 CatchTypeInfo TypeInfo{nullptr, 0};
569 if (CaughtType->isObjCObjectPointerType())
570 TypeInfo.RTTI = CGM.getObjCRuntime().GetEHType(CaughtType);
572 TypeInfo = CGM.getCXXABI().getAddrOfCXXCatchHandlerType(
573 CaughtType, C->getCaughtType());
574 CatchScope->setHandler(I, TypeInfo, Handler);
576 // No exception decl indicates '...', a catch-all.
577 CatchScope->setHandler(I, CGM.getCXXABI().getCatchAllTypeInfo(), Handler);
583 CodeGenFunction::getEHDispatchBlock(EHScopeStack::stable_iterator si) {
584 if (EHPersonality::get(*this).usesFuncletPads())
585 return getMSVCDispatchBlock(si);
587 // The dispatch block for the end of the scope chain is a block that
588 // just resumes unwinding.
589 if (si == EHStack.stable_end())
590 return getEHResumeBlock(true);
592 // Otherwise, we should look at the actual scope.
593 EHScope &scope = *EHStack.find(si);
595 llvm::BasicBlock *dispatchBlock = scope.getCachedEHDispatchBlock();
596 if (!dispatchBlock) {
597 switch (scope.getKind()) {
598 case EHScope::Catch: {
599 // Apply a special case to a single catch-all.
600 EHCatchScope &catchScope = cast<EHCatchScope>(scope);
601 if (catchScope.getNumHandlers() == 1 &&
602 catchScope.getHandler(0).isCatchAll()) {
603 dispatchBlock = catchScope.getHandler(0).Block;
605 // Otherwise, make a dispatch block.
607 dispatchBlock = createBasicBlock("catch.dispatch");
612 case EHScope::Cleanup:
613 dispatchBlock = createBasicBlock("ehcleanup");
616 case EHScope::Filter:
617 dispatchBlock = createBasicBlock("filter.dispatch");
620 case EHScope::Terminate:
621 dispatchBlock = getTerminateHandler();
624 case EHScope::PadEnd:
625 llvm_unreachable("PadEnd unnecessary for Itanium!");
627 scope.setCachedEHDispatchBlock(dispatchBlock);
629 return dispatchBlock;
633 CodeGenFunction::getMSVCDispatchBlock(EHScopeStack::stable_iterator SI) {
634 // Returning nullptr indicates that the previous dispatch block should unwind
636 if (SI == EHStack.stable_end())
639 // Otherwise, we should look at the actual scope.
640 EHScope &EHS = *EHStack.find(SI);
642 llvm::BasicBlock *DispatchBlock = EHS.getCachedEHDispatchBlock();
644 return DispatchBlock;
646 if (EHS.getKind() == EHScope::Terminate)
647 DispatchBlock = getTerminateHandler();
649 DispatchBlock = createBasicBlock();
650 CGBuilderTy Builder(*this, DispatchBlock);
652 switch (EHS.getKind()) {
654 DispatchBlock->setName("catch.dispatch");
657 case EHScope::Cleanup:
658 DispatchBlock->setName("ehcleanup");
661 case EHScope::Filter:
662 llvm_unreachable("exception specifications not handled yet!");
664 case EHScope::Terminate:
665 DispatchBlock->setName("terminate");
668 case EHScope::PadEnd:
669 llvm_unreachable("PadEnd dispatch block missing!");
671 EHS.setCachedEHDispatchBlock(DispatchBlock);
672 return DispatchBlock;
675 /// Check whether this is a non-EH scope, i.e. a scope which doesn't
676 /// affect exception handling. Currently, the only non-EH scopes are
677 /// normal-only cleanup scopes.
678 static bool isNonEHScope(const EHScope &S) {
679 switch (S.getKind()) {
680 case EHScope::Cleanup:
681 return !cast<EHCleanupScope>(S).isEHCleanup();
682 case EHScope::Filter:
684 case EHScope::Terminate:
685 case EHScope::PadEnd:
689 llvm_unreachable("Invalid EHScope Kind!");
692 llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
693 assert(EHStack.requiresLandingPad());
694 assert(!EHStack.empty());
696 // If exceptions are disabled and SEH is not in use, then there is no invoke
697 // destination. SEH "works" even if exceptions are off. In practice, this
698 // means that C++ destructors and other EH cleanups don't run, which is
699 // consistent with MSVC's behavior.
700 const LangOptions &LO = CGM.getLangOpts();
701 if (!LO.Exceptions) {
702 if (!LO.Borland && !LO.MicrosoftExt)
704 if (!currentFunctionUsesSEHTry())
708 // CUDA device code doesn't have exceptions.
709 if (LO.CUDA && LO.CUDAIsDevice)
712 // Check the innermost scope for a cached landing pad. If this is
713 // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
714 llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
717 const EHPersonality &Personality = EHPersonality::get(*this);
719 if (!CurFn->hasPersonalityFn())
720 CurFn->setPersonalityFn(getOpaquePersonalityFn(CGM, Personality));
722 if (Personality.usesFuncletPads()) {
723 // We don't need separate landing pads in the funclet model.
724 LP = getEHDispatchBlock(EHStack.getInnermostEHScope());
726 // Build the landing pad for this scope.
727 LP = EmitLandingPad();
732 // Cache the landing pad on the innermost scope. If this is a
733 // non-EH scope, cache the landing pad on the enclosing scope, too.
734 for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
735 ir->setCachedLandingPad(LP);
736 if (!isNonEHScope(*ir)) break;
742 llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
743 assert(EHStack.requiresLandingPad());
745 EHScope &innermostEHScope = *EHStack.find(EHStack.getInnermostEHScope());
746 switch (innermostEHScope.getKind()) {
747 case EHScope::Terminate:
748 return getTerminateLandingPad();
750 case EHScope::PadEnd:
751 llvm_unreachable("PadEnd unnecessary for Itanium!");
754 case EHScope::Cleanup:
755 case EHScope::Filter:
756 if (llvm::BasicBlock *lpad = innermostEHScope.getCachedLandingPad())
760 // Save the current IR generation state.
761 CGBuilderTy::InsertPoint savedIP = Builder.saveAndClearIP();
762 auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, CurEHLocation);
764 // Create and configure the landing pad.
765 llvm::BasicBlock *lpad = createBasicBlock("lpad");
768 llvm::LandingPadInst *LPadInst = Builder.CreateLandingPad(
769 llvm::StructType::get(Int8PtrTy, Int32Ty, nullptr), 0);
771 llvm::Value *LPadExn = Builder.CreateExtractValue(LPadInst, 0);
772 Builder.CreateStore(LPadExn, getExceptionSlot());
773 llvm::Value *LPadSel = Builder.CreateExtractValue(LPadInst, 1);
774 Builder.CreateStore(LPadSel, getEHSelectorSlot());
776 // Save the exception pointer. It's safe to use a single exception
777 // pointer per function because EH cleanups can never have nested
779 // Build the landingpad instruction.
781 // Accumulate all the handlers in scope.
782 bool hasCatchAll = false;
783 bool hasCleanup = false;
784 bool hasFilter = false;
785 SmallVector<llvm::Value*, 4> filterTypes;
786 llvm::SmallPtrSet<llvm::Value*, 4> catchTypes;
787 for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end(); I != E;
790 switch (I->getKind()) {
791 case EHScope::Cleanup:
792 // If we have a cleanup, remember that.
793 hasCleanup = (hasCleanup || cast<EHCleanupScope>(*I).isEHCleanup());
796 case EHScope::Filter: {
797 assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
798 assert(!hasCatchAll && "EH filter reached after catch-all");
800 // Filter scopes get added to the landingpad in weird ways.
801 EHFilterScope &filter = cast<EHFilterScope>(*I);
804 // Add all the filter values.
805 for (unsigned i = 0, e = filter.getNumFilters(); i != e; ++i)
806 filterTypes.push_back(filter.getFilter(i));
810 case EHScope::Terminate:
811 // Terminate scopes are basically catch-alls.
812 assert(!hasCatchAll);
819 case EHScope::PadEnd:
820 llvm_unreachable("PadEnd unnecessary for Itanium!");
823 EHCatchScope &catchScope = cast<EHCatchScope>(*I);
824 for (unsigned hi = 0, he = catchScope.getNumHandlers(); hi != he; ++hi) {
825 EHCatchScope::Handler handler = catchScope.getHandler(hi);
826 assert(handler.Type.Flags == 0 &&
827 "landingpads do not support catch handler flags");
829 // If this is a catch-all, register that and abort.
830 if (!handler.Type.RTTI) {
831 assert(!hasCatchAll);
836 // Check whether we already have a handler for this type.
837 if (catchTypes.insert(handler.Type.RTTI).second)
838 // If not, add it directly to the landingpad.
839 LPadInst->addClause(handler.Type.RTTI);
844 // If we have a catch-all, add null to the landingpad.
845 assert(!(hasCatchAll && hasFilter));
847 LPadInst->addClause(getCatchAllValue(*this));
849 // If we have an EH filter, we need to add those handlers in the
850 // right place in the landingpad, which is to say, at the end.
851 } else if (hasFilter) {
852 // Create a filter expression: a constant array indicating which filter
853 // types there are. The personality routine only lands here if the filter
855 SmallVector<llvm::Constant*, 8> Filters;
856 llvm::ArrayType *AType =
857 llvm::ArrayType::get(!filterTypes.empty() ?
858 filterTypes[0]->getType() : Int8PtrTy,
861 for (unsigned i = 0, e = filterTypes.size(); i != e; ++i)
862 Filters.push_back(cast<llvm::Constant>(filterTypes[i]));
863 llvm::Constant *FilterArray = llvm::ConstantArray::get(AType, Filters);
864 LPadInst->addClause(FilterArray);
866 // Also check whether we need a cleanup.
868 LPadInst->setCleanup(true);
870 // Otherwise, signal that we at least have cleanups.
871 } else if (hasCleanup) {
872 LPadInst->setCleanup(true);
875 assert((LPadInst->getNumClauses() > 0 || LPadInst->isCleanup()) &&
876 "landingpad instruction has no clauses!");
878 // Tell the backend how to generate the landing pad.
879 Builder.CreateBr(getEHDispatchBlock(EHStack.getInnermostEHScope()));
881 // Restore the old IR generation state.
882 Builder.restoreIP(savedIP);
887 static void emitCatchPadBlock(CodeGenFunction &CGF, EHCatchScope &CatchScope) {
888 llvm::BasicBlock *DispatchBlock = CatchScope.getCachedEHDispatchBlock();
889 assert(DispatchBlock);
891 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveIP();
892 CGF.EmitBlockAfterUses(DispatchBlock);
894 llvm::Value *ParentPad = CGF.CurrentFuncletPad;
896 ParentPad = llvm::ConstantTokenNone::get(CGF.getLLVMContext());
897 llvm::BasicBlock *UnwindBB =
898 CGF.getEHDispatchBlock(CatchScope.getEnclosingEHScope());
900 unsigned NumHandlers = CatchScope.getNumHandlers();
901 llvm::CatchSwitchInst *CatchSwitch =
902 CGF.Builder.CreateCatchSwitch(ParentPad, UnwindBB, NumHandlers);
904 // Test against each of the exception types we claim to catch.
905 for (unsigned I = 0; I < NumHandlers; ++I) {
906 const EHCatchScope::Handler &Handler = CatchScope.getHandler(I);
908 CatchTypeInfo TypeInfo = Handler.Type;
910 TypeInfo.RTTI = llvm::Constant::getNullValue(CGF.VoidPtrTy);
912 CGF.Builder.SetInsertPoint(Handler.Block);
914 if (EHPersonality::get(CGF).isMSVCXXPersonality()) {
915 CGF.Builder.CreateCatchPad(
916 CatchSwitch, {TypeInfo.RTTI, CGF.Builder.getInt32(TypeInfo.Flags),
917 llvm::Constant::getNullValue(CGF.VoidPtrTy)});
919 CGF.Builder.CreateCatchPad(CatchSwitch, {TypeInfo.RTTI});
922 CatchSwitch->addHandler(Handler.Block);
924 CGF.Builder.restoreIP(SavedIP);
927 /// Emit the structure of the dispatch block for the given catch scope.
928 /// It is an invariant that the dispatch block already exists.
929 static void emitCatchDispatchBlock(CodeGenFunction &CGF,
930 EHCatchScope &catchScope) {
931 if (EHPersonality::get(CGF).usesFuncletPads())
932 return emitCatchPadBlock(CGF, catchScope);
934 llvm::BasicBlock *dispatchBlock = catchScope.getCachedEHDispatchBlock();
935 assert(dispatchBlock);
937 // If there's only a single catch-all, getEHDispatchBlock returned
938 // that catch-all as the dispatch block.
939 if (catchScope.getNumHandlers() == 1 &&
940 catchScope.getHandler(0).isCatchAll()) {
941 assert(dispatchBlock == catchScope.getHandler(0).Block);
945 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveIP();
946 CGF.EmitBlockAfterUses(dispatchBlock);
948 // Select the right handler.
949 llvm::Value *llvm_eh_typeid_for =
950 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
952 // Load the selector value.
953 llvm::Value *selector = CGF.getSelectorFromSlot();
955 // Test against each of the exception types we claim to catch.
956 for (unsigned i = 0, e = catchScope.getNumHandlers(); ; ++i) {
957 assert(i < e && "ran off end of handlers!");
958 const EHCatchScope::Handler &handler = catchScope.getHandler(i);
960 llvm::Value *typeValue = handler.Type.RTTI;
961 assert(handler.Type.Flags == 0 &&
962 "landingpads do not support catch handler flags");
963 assert(typeValue && "fell into catch-all case!");
964 typeValue = CGF.Builder.CreateBitCast(typeValue, CGF.Int8PtrTy);
966 // Figure out the next block.
968 llvm::BasicBlock *nextBlock;
970 // If this is the last handler, we're at the end, and the next
971 // block is the block for the enclosing EH scope.
973 nextBlock = CGF.getEHDispatchBlock(catchScope.getEnclosingEHScope());
976 // If the next handler is a catch-all, we're at the end, and the
977 // next block is that handler.
978 } else if (catchScope.getHandler(i+1).isCatchAll()) {
979 nextBlock = catchScope.getHandler(i+1).Block;
982 // Otherwise, we're not at the end and we need a new block.
984 nextBlock = CGF.createBasicBlock("catch.fallthrough");
988 // Figure out the catch type's index in the LSDA's type table.
989 llvm::CallInst *typeIndex =
990 CGF.Builder.CreateCall(llvm_eh_typeid_for, typeValue);
991 typeIndex->setDoesNotThrow();
993 llvm::Value *matchesTypeIndex =
994 CGF.Builder.CreateICmpEQ(selector, typeIndex, "matches");
995 CGF.Builder.CreateCondBr(matchesTypeIndex, handler.Block, nextBlock);
997 // If the next handler is a catch-all, we're completely done.
999 CGF.Builder.restoreIP(savedIP);
1002 // Otherwise we need to emit and continue at that block.
1003 CGF.EmitBlock(nextBlock);
1007 void CodeGenFunction::popCatchScope() {
1008 EHCatchScope &catchScope = cast<EHCatchScope>(*EHStack.begin());
1009 if (catchScope.hasEHBranches())
1010 emitCatchDispatchBlock(*this, catchScope);
1014 void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
1015 unsigned NumHandlers = S.getNumHandlers();
1016 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1017 assert(CatchScope.getNumHandlers() == NumHandlers);
1019 // If the catch was not required, bail out now.
1020 if (!CatchScope.hasEHBranches()) {
1021 CatchScope.clearHandlerBlocks();
1026 // Emit the structure of the EH dispatch for this catch.
1027 emitCatchDispatchBlock(*this, CatchScope);
1029 // Copy the handler blocks off before we pop the EH stack. Emitting
1030 // the handlers might scribble on this memory.
1031 SmallVector<EHCatchScope::Handler, 8> Handlers(
1032 CatchScope.begin(), CatchScope.begin() + NumHandlers);
1036 // The fall-through block.
1037 llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
1039 // We just emitted the body of the try; jump to the continue block.
1040 if (HaveInsertPoint())
1041 Builder.CreateBr(ContBB);
1043 // Determine if we need an implicit rethrow for all these catch handlers;
1044 // see the comment below.
1045 bool doImplicitRethrow = false;
1047 doImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
1048 isa<CXXConstructorDecl>(CurCodeDecl);
1050 // Perversely, we emit the handlers backwards precisely because we
1051 // want them to appear in source order. In all of these cases, the
1052 // catch block will have exactly one predecessor, which will be a
1053 // particular block in the catch dispatch. However, in the case of
1054 // a catch-all, one of the dispatch blocks will branch to two
1055 // different handlers, and EmitBlockAfterUses will cause the second
1056 // handler to be moved before the first.
1057 for (unsigned I = NumHandlers; I != 0; --I) {
1058 llvm::BasicBlock *CatchBlock = Handlers[I-1].Block;
1059 EmitBlockAfterUses(CatchBlock);
1061 // Catch the exception if this isn't a catch-all.
1062 const CXXCatchStmt *C = S.getHandler(I-1);
1064 // Enter a cleanup scope, including the catch variable and the
1066 RunCleanupsScope CatchScope(*this);
1068 // Initialize the catch variable and set up the cleanups.
1069 SaveAndRestore<llvm::Instruction *> RestoreCurrentFuncletPad(
1071 CGM.getCXXABI().emitBeginCatch(*this, C);
1073 // Emit the PGO counter increment.
1074 incrementProfileCounter(C);
1076 // Perform the body of the catch.
1077 EmitStmt(C->getHandlerBlock());
1079 // [except.handle]p11:
1080 // The currently handled exception is rethrown if control
1081 // reaches the end of a handler of the function-try-block of a
1082 // constructor or destructor.
1084 // It is important that we only do this on fallthrough and not on
1085 // return. Note that it's illegal to put a return in a
1086 // constructor function-try-block's catch handler (p14), so this
1087 // really only applies to destructors.
1088 if (doImplicitRethrow && HaveInsertPoint()) {
1089 CGM.getCXXABI().emitRethrow(*this, /*isNoReturn*/false);
1090 Builder.CreateUnreachable();
1091 Builder.ClearInsertionPoint();
1094 // Fall out through the catch cleanups.
1095 CatchScope.ForceCleanup();
1097 // Branch out of the try.
1098 if (HaveInsertPoint())
1099 Builder.CreateBr(ContBB);
1103 incrementProfileCounter(&S);
1107 struct CallEndCatchForFinally final : EHScopeStack::Cleanup {
1108 llvm::Value *ForEHVar;
1109 llvm::Value *EndCatchFn;
1110 CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn)
1111 : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
1113 void Emit(CodeGenFunction &CGF, Flags flags) override {
1114 llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
1115 llvm::BasicBlock *CleanupContBB =
1116 CGF.createBasicBlock("finally.cleanup.cont");
1118 llvm::Value *ShouldEndCatch =
1119 CGF.Builder.CreateFlagLoad(ForEHVar, "finally.endcatch");
1120 CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1121 CGF.EmitBlock(EndCatchBB);
1122 CGF.EmitRuntimeCallOrInvoke(EndCatchFn); // catch-all, so might throw
1123 CGF.EmitBlock(CleanupContBB);
1127 struct PerformFinally final : EHScopeStack::Cleanup {
1129 llvm::Value *ForEHVar;
1130 llvm::Value *EndCatchFn;
1131 llvm::Value *RethrowFn;
1132 llvm::Value *SavedExnVar;
1134 PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
1135 llvm::Value *EndCatchFn,
1136 llvm::Value *RethrowFn, llvm::Value *SavedExnVar)
1137 : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1138 RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
1140 void Emit(CodeGenFunction &CGF, Flags flags) override {
1141 // Enter a cleanup to call the end-catch function if one was provided.
1143 CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
1144 ForEHVar, EndCatchFn);
1146 // Save the current cleanup destination in case there are
1147 // cleanups in the finally block.
1148 llvm::Value *SavedCleanupDest =
1149 CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
1150 "cleanup.dest.saved");
1152 // Emit the finally block.
1155 // If the end of the finally is reachable, check whether this was
1156 // for EH. If so, rethrow.
1157 if (CGF.HaveInsertPoint()) {
1158 llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
1159 llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
1161 llvm::Value *ShouldRethrow =
1162 CGF.Builder.CreateFlagLoad(ForEHVar, "finally.shouldthrow");
1163 CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1165 CGF.EmitBlock(RethrowBB);
1167 CGF.EmitRuntimeCallOrInvoke(RethrowFn,
1168 CGF.Builder.CreateAlignedLoad(SavedExnVar, CGF.getPointerAlign()));
1170 CGF.EmitRuntimeCallOrInvoke(RethrowFn);
1172 CGF.Builder.CreateUnreachable();
1174 CGF.EmitBlock(ContBB);
1176 // Restore the cleanup destination.
1177 CGF.Builder.CreateStore(SavedCleanupDest,
1178 CGF.getNormalCleanupDestSlot());
1181 // Leave the end-catch cleanup. As an optimization, pretend that
1182 // the fallthrough path was inaccessible; we've dynamically proven
1183 // that we're not in the EH case along that path.
1185 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1186 CGF.PopCleanupBlock();
1187 CGF.Builder.restoreIP(SavedIP);
1190 // Now make sure we actually have an insertion point or the
1191 // cleanup gods will hate us.
1192 CGF.EnsureInsertPoint();
1195 } // end anonymous namespace
1197 /// Enters a finally block for an implementation using zero-cost
1198 /// exceptions. This is mostly general, but hard-codes some
1199 /// language/ABI-specific behavior in the catch-all sections.
1200 void CodeGenFunction::FinallyInfo::enter(CodeGenFunction &CGF,
1202 llvm::Constant *beginCatchFn,
1203 llvm::Constant *endCatchFn,
1204 llvm::Constant *rethrowFn) {
1205 assert((beginCatchFn != nullptr) == (endCatchFn != nullptr) &&
1206 "begin/end catch functions not paired");
1207 assert(rethrowFn && "rethrow function is required");
1209 BeginCatchFn = beginCatchFn;
1211 // The rethrow function has one of the following two types:
1214 // In the latter case we need to pass it the exception object.
1215 // But we can't use the exception slot because the @finally might
1216 // have a landing pad (which would overwrite the exception slot).
1217 llvm::FunctionType *rethrowFnTy =
1218 cast<llvm::FunctionType>(
1219 cast<llvm::PointerType>(rethrowFn->getType())->getElementType());
1220 SavedExnVar = nullptr;
1221 if (rethrowFnTy->getNumParams())
1222 SavedExnVar = CGF.CreateTempAlloca(CGF.Int8PtrTy, "finally.exn");
1224 // A finally block is a statement which must be executed on any edge
1225 // out of a given scope. Unlike a cleanup, the finally block may
1226 // contain arbitrary control flow leading out of itself. In
1227 // addition, finally blocks should always be executed, even if there
1228 // are no catch handlers higher on the stack. Therefore, we
1229 // surround the protected scope with a combination of a normal
1230 // cleanup (to catch attempts to break out of the block via normal
1231 // control flow) and an EH catch-all (semantically "outside" any try
1232 // statement to which the finally block might have been attached).
1233 // The finally block itself is generated in the context of a cleanup
1234 // which conditionally leaves the catch-all.
1236 // Jump destination for performing the finally block on an exception
1237 // edge. We'll never actually reach this block, so unreachable is
1239 RethrowDest = CGF.getJumpDestInCurrentScope(CGF.getUnreachableBlock());
1241 // Whether the finally block is being executed for EH purposes.
1242 ForEHVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "finally.for-eh");
1243 CGF.Builder.CreateFlagStore(false, ForEHVar);
1245 // Enter a normal cleanup which will perform the @finally block.
1246 CGF.EHStack.pushCleanup<PerformFinally>(NormalCleanup, body,
1247 ForEHVar, endCatchFn,
1248 rethrowFn, SavedExnVar);
1250 // Enter a catch-all scope.
1251 llvm::BasicBlock *catchBB = CGF.createBasicBlock("finally.catchall");
1252 EHCatchScope *catchScope = CGF.EHStack.pushCatch(1);
1253 catchScope->setCatchAllHandler(0, catchBB);
1256 void CodeGenFunction::FinallyInfo::exit(CodeGenFunction &CGF) {
1257 // Leave the finally catch-all.
1258 EHCatchScope &catchScope = cast<EHCatchScope>(*CGF.EHStack.begin());
1259 llvm::BasicBlock *catchBB = catchScope.getHandler(0).Block;
1261 CGF.popCatchScope();
1263 // If there are any references to the catch-all block, emit it.
1264 if (catchBB->use_empty()) {
1267 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveAndClearIP();
1268 CGF.EmitBlock(catchBB);
1270 llvm::Value *exn = nullptr;
1272 // If there's a begin-catch function, call it.
1274 exn = CGF.getExceptionFromSlot();
1275 CGF.EmitNounwindRuntimeCall(BeginCatchFn, exn);
1278 // If we need to remember the exception pointer to rethrow later, do so.
1280 if (!exn) exn = CGF.getExceptionFromSlot();
1281 CGF.Builder.CreateAlignedStore(exn, SavedExnVar, CGF.getPointerAlign());
1284 // Tell the cleanups in the finally block that we're do this for EH.
1285 CGF.Builder.CreateFlagStore(true, ForEHVar);
1287 // Thread a jump through the finally cleanup.
1288 CGF.EmitBranchThroughCleanup(RethrowDest);
1290 CGF.Builder.restoreIP(savedIP);
1293 // Finally, leave the @finally cleanup.
1294 CGF.PopCleanupBlock();
1297 llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
1298 if (TerminateLandingPad)
1299 return TerminateLandingPad;
1301 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1303 // This will get inserted at the end of the function.
1304 TerminateLandingPad = createBasicBlock("terminate.lpad");
1305 Builder.SetInsertPoint(TerminateLandingPad);
1307 // Tell the backend that this is a landing pad.
1308 const EHPersonality &Personality = EHPersonality::get(*this);
1310 if (!CurFn->hasPersonalityFn())
1311 CurFn->setPersonalityFn(getOpaquePersonalityFn(CGM, Personality));
1313 llvm::LandingPadInst *LPadInst = Builder.CreateLandingPad(
1314 llvm::StructType::get(Int8PtrTy, Int32Ty, nullptr), 0);
1315 LPadInst->addClause(getCatchAllValue(*this));
1317 llvm::Value *Exn = nullptr;
1318 if (getLangOpts().CPlusPlus)
1319 Exn = Builder.CreateExtractValue(LPadInst, 0);
1320 llvm::CallInst *terminateCall =
1321 CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
1322 terminateCall->setDoesNotReturn();
1323 Builder.CreateUnreachable();
1325 // Restore the saved insertion state.
1326 Builder.restoreIP(SavedIP);
1328 return TerminateLandingPad;
1331 llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
1332 if (TerminateHandler)
1333 return TerminateHandler;
1335 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1337 // Set up the terminate handler. This block is inserted at the very
1338 // end of the function by FinishFunction.
1339 TerminateHandler = createBasicBlock("terminate.handler");
1340 Builder.SetInsertPoint(TerminateHandler);
1341 llvm::Value *Exn = nullptr;
1342 SaveAndRestore<llvm::Instruction *> RestoreCurrentFuncletPad(
1344 if (EHPersonality::get(*this).usesFuncletPads()) {
1345 llvm::Value *ParentPad = CurrentFuncletPad;
1347 ParentPad = llvm::ConstantTokenNone::get(CGM.getLLVMContext());
1348 CurrentFuncletPad = Builder.CreateCleanupPad(ParentPad);
1350 if (getLangOpts().CPlusPlus)
1351 Exn = getExceptionFromSlot();
1353 llvm::CallInst *terminateCall =
1354 CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
1355 terminateCall->setDoesNotReturn();
1356 Builder.CreateUnreachable();
1358 // Restore the saved insertion state.
1359 Builder.restoreIP(SavedIP);
1361 return TerminateHandler;
1364 llvm::BasicBlock *CodeGenFunction::getEHResumeBlock(bool isCleanup) {
1365 if (EHResumeBlock) return EHResumeBlock;
1367 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1369 // We emit a jump to a notional label at the outermost unwind state.
1370 EHResumeBlock = createBasicBlock("eh.resume");
1371 Builder.SetInsertPoint(EHResumeBlock);
1373 const EHPersonality &Personality = EHPersonality::get(*this);
1375 // This can always be a call because we necessarily didn't find
1376 // anything on the EH stack which needs our help.
1377 const char *RethrowName = Personality.CatchallRethrowFn;
1378 if (RethrowName != nullptr && !isCleanup) {
1379 EmitRuntimeCall(getCatchallRethrowFn(CGM, RethrowName),
1380 getExceptionFromSlot())->setDoesNotReturn();
1381 Builder.CreateUnreachable();
1382 Builder.restoreIP(SavedIP);
1383 return EHResumeBlock;
1386 // Recreate the landingpad's return value for the 'resume' instruction.
1387 llvm::Value *Exn = getExceptionFromSlot();
1388 llvm::Value *Sel = getSelectorFromSlot();
1390 llvm::Type *LPadType = llvm::StructType::get(Exn->getType(),
1391 Sel->getType(), nullptr);
1392 llvm::Value *LPadVal = llvm::UndefValue::get(LPadType);
1393 LPadVal = Builder.CreateInsertValue(LPadVal, Exn, 0, "lpad.val");
1394 LPadVal = Builder.CreateInsertValue(LPadVal, Sel, 1, "lpad.val");
1396 Builder.CreateResume(LPadVal);
1397 Builder.restoreIP(SavedIP);
1398 return EHResumeBlock;
1401 void CodeGenFunction::EmitSEHTryStmt(const SEHTryStmt &S) {
1404 JumpDest TryExit = getJumpDestInCurrentScope("__try.__leave");
1406 SEHTryEpilogueStack.push_back(&TryExit);
1407 EmitStmt(S.getTryBlock());
1408 SEHTryEpilogueStack.pop_back();
1410 if (!TryExit.getBlock()->use_empty())
1411 EmitBlock(TryExit.getBlock(), /*IsFinished=*/true);
1413 delete TryExit.getBlock();
1419 struct PerformSEHFinally final : EHScopeStack::Cleanup {
1420 llvm::Function *OutlinedFinally;
1421 PerformSEHFinally(llvm::Function *OutlinedFinally)
1422 : OutlinedFinally(OutlinedFinally) {}
1424 void Emit(CodeGenFunction &CGF, Flags F) override {
1425 ASTContext &Context = CGF.getContext();
1426 CodeGenModule &CGM = CGF.CGM;
1430 // Compute the two argument values.
1431 QualType ArgTys[2] = {Context.UnsignedCharTy, Context.VoidPtrTy};
1432 llvm::Value *LocalAddrFn = CGM.getIntrinsic(llvm::Intrinsic::localaddress);
1433 llvm::Value *FP = CGF.Builder.CreateCall(LocalAddrFn);
1434 llvm::Value *IsForEH =
1435 llvm::ConstantInt::get(CGF.ConvertType(ArgTys[0]), F.isForEHCleanup());
1436 Args.add(RValue::get(IsForEH), ArgTys[0]);
1437 Args.add(RValue::get(FP), ArgTys[1]);
1439 // Arrange a two-arg function info and type.
1440 const CGFunctionInfo &FnInfo =
1441 CGM.getTypes().arrangeBuiltinFunctionCall(Context.VoidTy, Args);
1443 auto Callee = CGCallee::forDirect(OutlinedFinally);
1444 CGF.EmitCall(FnInfo, Callee, ReturnValueSlot(), Args);
1447 } // end anonymous namespace
1450 /// Find all local variable captures in the statement.
1451 struct CaptureFinder : ConstStmtVisitor<CaptureFinder> {
1452 CodeGenFunction &ParentCGF;
1453 const VarDecl *ParentThis;
1454 llvm::SmallSetVector<const VarDecl *, 4> Captures;
1455 Address SEHCodeSlot = Address::invalid();
1456 CaptureFinder(CodeGenFunction &ParentCGF, const VarDecl *ParentThis)
1457 : ParentCGF(ParentCGF), ParentThis(ParentThis) {}
1459 // Return true if we need to do any capturing work.
1460 bool foundCaptures() {
1461 return !Captures.empty() || SEHCodeSlot.isValid();
1464 void Visit(const Stmt *S) {
1465 // See if this is a capture, then recurse.
1466 ConstStmtVisitor<CaptureFinder>::Visit(S);
1467 for (const Stmt *Child : S->children())
1472 void VisitDeclRefExpr(const DeclRefExpr *E) {
1473 // If this is already a capture, just make sure we capture 'this'.
1474 if (E->refersToEnclosingVariableOrCapture()) {
1475 Captures.insert(ParentThis);
1479 const auto *D = dyn_cast<VarDecl>(E->getDecl());
1480 if (D && D->isLocalVarDeclOrParm() && D->hasLocalStorage())
1484 void VisitCXXThisExpr(const CXXThisExpr *E) {
1485 Captures.insert(ParentThis);
1488 void VisitCallExpr(const CallExpr *E) {
1489 // We only need to add parent frame allocations for these builtins in x86.
1490 if (ParentCGF.getTarget().getTriple().getArch() != llvm::Triple::x86)
1493 unsigned ID = E->getBuiltinCallee();
1495 case Builtin::BI__exception_code:
1496 case Builtin::BI_exception_code:
1497 // This is the simple case where we are the outermost finally. All we
1498 // have to do here is make sure we escape this and recover it in the
1499 // outlined handler.
1500 if (!SEHCodeSlot.isValid())
1501 SEHCodeSlot = ParentCGF.SEHCodeSlotStack.back();
1506 } // end anonymous namespace
1508 Address CodeGenFunction::recoverAddrOfEscapedLocal(CodeGenFunction &ParentCGF,
1510 llvm::Value *ParentFP) {
1511 llvm::CallInst *RecoverCall = nullptr;
1512 CGBuilderTy Builder(*this, AllocaInsertPt);
1513 if (auto *ParentAlloca = dyn_cast<llvm::AllocaInst>(ParentVar.getPointer())) {
1514 // Mark the variable escaped if nobody else referenced it and compute the
1515 // localescape index.
1516 auto InsertPair = ParentCGF.EscapedLocals.insert(
1517 std::make_pair(ParentAlloca, ParentCGF.EscapedLocals.size()));
1518 int FrameEscapeIdx = InsertPair.first->second;
1519 // call i8* @llvm.localrecover(i8* bitcast(@parentFn), i8* %fp, i32 N)
1520 llvm::Function *FrameRecoverFn = llvm::Intrinsic::getDeclaration(
1521 &CGM.getModule(), llvm::Intrinsic::localrecover);
1522 llvm::Constant *ParentI8Fn =
1523 llvm::ConstantExpr::getBitCast(ParentCGF.CurFn, Int8PtrTy);
1524 RecoverCall = Builder.CreateCall(
1525 FrameRecoverFn, {ParentI8Fn, ParentFP,
1526 llvm::ConstantInt::get(Int32Ty, FrameEscapeIdx)});
1529 // If the parent didn't have an alloca, we're doing some nested outlining.
1530 // Just clone the existing localrecover call, but tweak the FP argument to
1531 // use our FP value. All other arguments are constants.
1532 auto *ParentRecover =
1533 cast<llvm::IntrinsicInst>(ParentVar.getPointer()->stripPointerCasts());
1534 assert(ParentRecover->getIntrinsicID() == llvm::Intrinsic::localrecover &&
1535 "expected alloca or localrecover in parent LocalDeclMap");
1536 RecoverCall = cast<llvm::CallInst>(ParentRecover->clone());
1537 RecoverCall->setArgOperand(1, ParentFP);
1538 RecoverCall->insertBefore(AllocaInsertPt);
1541 // Bitcast the variable, rename it, and insert it in the local decl map.
1542 llvm::Value *ChildVar =
1543 Builder.CreateBitCast(RecoverCall, ParentVar.getType());
1544 ChildVar->setName(ParentVar.getName());
1545 return Address(ChildVar, ParentVar.getAlignment());
1548 void CodeGenFunction::EmitCapturedLocals(CodeGenFunction &ParentCGF,
1549 const Stmt *OutlinedStmt,
1551 // Find all captures in the Stmt.
1552 CaptureFinder Finder(ParentCGF, ParentCGF.CXXABIThisDecl);
1553 Finder.Visit(OutlinedStmt);
1555 // We can exit early on x86_64 when there are no captures. We just have to
1556 // save the exception code in filters so that __exception_code() works.
1557 if (!Finder.foundCaptures() &&
1558 CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
1560 EmitSEHExceptionCodeSave(ParentCGF, nullptr, nullptr);
1564 llvm::Value *EntryFP = nullptr;
1565 CGBuilderTy Builder(CGM, AllocaInsertPt);
1566 if (IsFilter && CGM.getTarget().getTriple().getArch() == llvm::Triple::x86) {
1567 // 32-bit SEH filters need to be careful about FP recovery. The end of the
1568 // EH registration is passed in as the EBP physical register. We can
1569 // recover that with llvm.frameaddress(1).
1570 EntryFP = Builder.CreateCall(
1571 CGM.getIntrinsic(llvm::Intrinsic::frameaddress), {Builder.getInt32(1)});
1573 // Otherwise, for x64 and 32-bit finally functions, the parent FP is the
1574 // second parameter.
1575 auto AI = CurFn->arg_begin();
1580 llvm::Value *ParentFP = EntryFP;
1582 // Given whatever FP the runtime provided us in EntryFP, recover the true
1583 // frame pointer of the parent function. We only need to do this in filters,
1584 // since finally funclets recover the parent FP for us.
1585 llvm::Function *RecoverFPIntrin =
1586 CGM.getIntrinsic(llvm::Intrinsic::x86_seh_recoverfp);
1587 llvm::Constant *ParentI8Fn =
1588 llvm::ConstantExpr::getBitCast(ParentCGF.CurFn, Int8PtrTy);
1589 ParentFP = Builder.CreateCall(RecoverFPIntrin, {ParentI8Fn, EntryFP});
1592 // Create llvm.localrecover calls for all captures.
1593 for (const VarDecl *VD : Finder.Captures) {
1594 if (isa<ImplicitParamDecl>(VD)) {
1595 CGM.ErrorUnsupported(VD, "'this' captured by SEH");
1596 CXXThisValue = llvm::UndefValue::get(ConvertTypeForMem(VD->getType()));
1599 if (VD->getType()->isVariablyModifiedType()) {
1600 CGM.ErrorUnsupported(VD, "VLA captured by SEH");
1603 assert((isa<ImplicitParamDecl>(VD) || VD->isLocalVarDeclOrParm()) &&
1604 "captured non-local variable");
1606 // If this decl hasn't been declared yet, it will be declared in the
1608 auto I = ParentCGF.LocalDeclMap.find(VD);
1609 if (I == ParentCGF.LocalDeclMap.end())
1612 Address ParentVar = I->second;
1614 VD, recoverAddrOfEscapedLocal(ParentCGF, ParentVar, ParentFP));
1617 if (Finder.SEHCodeSlot.isValid()) {
1618 SEHCodeSlotStack.push_back(
1619 recoverAddrOfEscapedLocal(ParentCGF, Finder.SEHCodeSlot, ParentFP));
1623 EmitSEHExceptionCodeSave(ParentCGF, ParentFP, EntryFP);
1626 /// Arrange a function prototype that can be called by Windows exception
1627 /// handling personalities. On Win64, the prototype looks like:
1628 /// RetTy func(void *EHPtrs, void *ParentFP);
1629 void CodeGenFunction::startOutlinedSEHHelper(CodeGenFunction &ParentCGF,
1631 const Stmt *OutlinedStmt) {
1632 SourceLocation StartLoc = OutlinedStmt->getLocStart();
1634 // Get the mangled function name.
1635 SmallString<128> Name;
1637 llvm::raw_svector_ostream OS(Name);
1638 const FunctionDecl *ParentSEHFn = ParentCGF.CurSEHParent;
1639 assert(ParentSEHFn && "No CurSEHParent!");
1640 MangleContext &Mangler = CGM.getCXXABI().getMangleContext();
1642 Mangler.mangleSEHFilterExpression(ParentSEHFn, OS);
1644 Mangler.mangleSEHFinallyBlock(ParentSEHFn, OS);
1647 FunctionArgList Args;
1648 if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86 || !IsFilter) {
1649 // All SEH finally functions take two parameters. Win64 filters take two
1650 // parameters. Win32 filters take no parameters.
1652 Args.push_back(ImplicitParamDecl::Create(
1653 getContext(), nullptr, StartLoc,
1654 &getContext().Idents.get("exception_pointers"),
1655 getContext().VoidPtrTy));
1657 Args.push_back(ImplicitParamDecl::Create(
1658 getContext(), nullptr, StartLoc,
1659 &getContext().Idents.get("abnormal_termination"),
1660 getContext().UnsignedCharTy));
1662 Args.push_back(ImplicitParamDecl::Create(
1663 getContext(), nullptr, StartLoc,
1664 &getContext().Idents.get("frame_pointer"), getContext().VoidPtrTy));
1667 QualType RetTy = IsFilter ? getContext().LongTy : getContext().VoidTy;
1669 llvm::Function *ParentFn = ParentCGF.CurFn;
1670 const CGFunctionInfo &FnInfo =
1671 CGM.getTypes().arrangeBuiltinFunctionDeclaration(RetTy, Args);
1673 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
1674 llvm::Function *Fn = llvm::Function::Create(
1675 FnTy, llvm::GlobalValue::InternalLinkage, Name.str(), &CGM.getModule());
1676 // The filter is either in the same comdat as the function, or it's internal.
1677 if (llvm::Comdat *C = ParentFn->getComdat()) {
1679 } else if (ParentFn->hasWeakLinkage() || ParentFn->hasLinkOnceLinkage()) {
1680 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(ParentFn->getName());
1681 ParentFn->setComdat(C);
1684 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
1687 IsOutlinedSEHHelper = true;
1689 StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args,
1690 OutlinedStmt->getLocStart(), OutlinedStmt->getLocStart());
1691 CurSEHParent = ParentCGF.CurSEHParent;
1693 CGM.SetLLVMFunctionAttributes(nullptr, FnInfo, CurFn);
1694 EmitCapturedLocals(ParentCGF, OutlinedStmt, IsFilter);
1697 /// Create a stub filter function that will ultimately hold the code of the
1698 /// filter expression. The EH preparation passes in LLVM will outline the code
1699 /// from the main function body into this stub.
1701 CodeGenFunction::GenerateSEHFilterFunction(CodeGenFunction &ParentCGF,
1702 const SEHExceptStmt &Except) {
1703 const Expr *FilterExpr = Except.getFilterExpr();
1704 startOutlinedSEHHelper(ParentCGF, true, FilterExpr);
1706 // Emit the original filter expression, convert to i32, and return.
1707 llvm::Value *R = EmitScalarExpr(FilterExpr);
1708 R = Builder.CreateIntCast(R, ConvertType(getContext().LongTy),
1709 FilterExpr->getType()->isSignedIntegerType());
1710 Builder.CreateStore(R, ReturnValue);
1712 FinishFunction(FilterExpr->getLocEnd());
1718 CodeGenFunction::GenerateSEHFinallyFunction(CodeGenFunction &ParentCGF,
1719 const SEHFinallyStmt &Finally) {
1720 const Stmt *FinallyBlock = Finally.getBlock();
1721 startOutlinedSEHHelper(ParentCGF, false, FinallyBlock);
1723 // Emit the original filter expression, convert to i32, and return.
1724 EmitStmt(FinallyBlock);
1726 FinishFunction(FinallyBlock->getLocEnd());
1731 void CodeGenFunction::EmitSEHExceptionCodeSave(CodeGenFunction &ParentCGF,
1732 llvm::Value *ParentFP,
1733 llvm::Value *EntryFP) {
1734 // Get the pointer to the EXCEPTION_POINTERS struct. This is returned by the
1735 // __exception_info intrinsic.
1736 if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
1737 // On Win64, the info is passed as the first parameter to the filter.
1738 SEHInfo = &*CurFn->arg_begin();
1739 SEHCodeSlotStack.push_back(
1740 CreateMemTemp(getContext().IntTy, "__exception_code"));
1742 // On Win32, the EBP on entry to the filter points to the end of an
1743 // exception registration object. It contains 6 32-bit fields, and the info
1744 // pointer is stored in the second field. So, GEP 20 bytes backwards and
1745 // load the pointer.
1746 SEHInfo = Builder.CreateConstInBoundsGEP1_32(Int8Ty, EntryFP, -20);
1747 SEHInfo = Builder.CreateBitCast(SEHInfo, Int8PtrTy->getPointerTo());
1748 SEHInfo = Builder.CreateAlignedLoad(Int8PtrTy, SEHInfo, getPointerAlign());
1749 SEHCodeSlotStack.push_back(recoverAddrOfEscapedLocal(
1750 ParentCGF, ParentCGF.SEHCodeSlotStack.back(), ParentFP));
1753 // Save the exception code in the exception slot to unify exception access in
1754 // the filter function and the landing pad.
1755 // struct EXCEPTION_POINTERS {
1756 // EXCEPTION_RECORD *ExceptionRecord;
1757 // CONTEXT *ContextRecord;
1759 // int exceptioncode = exception_pointers->ExceptionRecord->ExceptionCode;
1760 llvm::Type *RecordTy = CGM.Int32Ty->getPointerTo();
1761 llvm::Type *PtrsTy = llvm::StructType::get(RecordTy, CGM.VoidPtrTy, nullptr);
1762 llvm::Value *Ptrs = Builder.CreateBitCast(SEHInfo, PtrsTy->getPointerTo());
1763 llvm::Value *Rec = Builder.CreateStructGEP(PtrsTy, Ptrs, 0);
1764 Rec = Builder.CreateAlignedLoad(Rec, getPointerAlign());
1765 llvm::Value *Code = Builder.CreateAlignedLoad(Rec, getIntAlign());
1766 assert(!SEHCodeSlotStack.empty() && "emitting EH code outside of __except");
1767 Builder.CreateStore(Code, SEHCodeSlotStack.back());
1770 llvm::Value *CodeGenFunction::EmitSEHExceptionInfo() {
1771 // Sema should diagnose calling this builtin outside of a filter context, but
1772 // don't crash if we screw up.
1774 return llvm::UndefValue::get(Int8PtrTy);
1775 assert(SEHInfo->getType() == Int8PtrTy);
1779 llvm::Value *CodeGenFunction::EmitSEHExceptionCode() {
1780 assert(!SEHCodeSlotStack.empty() && "emitting EH code outside of __except");
1781 return Builder.CreateLoad(SEHCodeSlotStack.back());
1784 llvm::Value *CodeGenFunction::EmitSEHAbnormalTermination() {
1785 // Abnormal termination is just the first parameter to the outlined finally
1787 auto AI = CurFn->arg_begin();
1788 return Builder.CreateZExt(&*AI, Int32Ty);
1791 void CodeGenFunction::EnterSEHTryStmt(const SEHTryStmt &S) {
1792 CodeGenFunction HelperCGF(CGM, /*suppressNewContext=*/true);
1793 if (const SEHFinallyStmt *Finally = S.getFinallyHandler()) {
1794 // Outline the finally block.
1795 llvm::Function *FinallyFunc =
1796 HelperCGF.GenerateSEHFinallyFunction(*this, *Finally);
1798 // Push a cleanup for __finally blocks.
1799 EHStack.pushCleanup<PerformSEHFinally>(NormalAndEHCleanup, FinallyFunc);
1803 // Otherwise, we must have an __except block.
1804 const SEHExceptStmt *Except = S.getExceptHandler();
1806 EHCatchScope *CatchScope = EHStack.pushCatch(1);
1807 SEHCodeSlotStack.push_back(
1808 CreateMemTemp(getContext().IntTy, "__exception_code"));
1810 // If the filter is known to evaluate to 1, then we can use the clause
1811 // "catch i8* null". We can't do this on x86 because the filter has to save
1812 // the exception code.
1814 CGM.EmitConstantExpr(Except->getFilterExpr(), getContext().IntTy, this);
1815 if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86 && C &&
1817 CatchScope->setCatchAllHandler(0, createBasicBlock("__except"));
1821 // In general, we have to emit an outlined filter function. Use the function
1822 // in place of the RTTI typeinfo global that C++ EH uses.
1823 llvm::Function *FilterFunc =
1824 HelperCGF.GenerateSEHFilterFunction(*this, *Except);
1825 llvm::Constant *OpaqueFunc =
1826 llvm::ConstantExpr::getBitCast(FilterFunc, Int8PtrTy);
1827 CatchScope->setHandler(0, OpaqueFunc, createBasicBlock("__except.ret"));
1830 void CodeGenFunction::ExitSEHTryStmt(const SEHTryStmt &S) {
1831 // Just pop the cleanup if it's a __finally block.
1832 if (S.getFinallyHandler()) {
1837 // Otherwise, we must have an __except block.
1838 const SEHExceptStmt *Except = S.getExceptHandler();
1839 assert(Except && "__try must have __finally xor __except");
1840 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1842 // Don't emit the __except block if the __try block lacked invokes.
1843 // TODO: Model unwind edges from instructions, either with iload / istore or
1844 // a try body function.
1845 if (!CatchScope.hasEHBranches()) {
1846 CatchScope.clearHandlerBlocks();
1848 SEHCodeSlotStack.pop_back();
1852 // The fall-through block.
1853 llvm::BasicBlock *ContBB = createBasicBlock("__try.cont");
1855 // We just emitted the body of the __try; jump to the continue block.
1856 if (HaveInsertPoint())
1857 Builder.CreateBr(ContBB);
1859 // Check if our filter function returned true.
1860 emitCatchDispatchBlock(*this, CatchScope);
1862 // Grab the block before we pop the handler.
1863 llvm::BasicBlock *CatchPadBB = CatchScope.getHandler(0).Block;
1866 EmitBlockAfterUses(CatchPadBB);
1868 // __except blocks don't get outlined into funclets, so immediately do a
1870 llvm::CatchPadInst *CPI =
1871 cast<llvm::CatchPadInst>(CatchPadBB->getFirstNonPHI());
1872 llvm::BasicBlock *ExceptBB = createBasicBlock("__except");
1873 Builder.CreateCatchRet(CPI, ExceptBB);
1874 EmitBlock(ExceptBB);
1876 // On Win64, the exception code is returned in EAX. Copy it into the slot.
1877 if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
1878 llvm::Function *SEHCodeIntrin =
1879 CGM.getIntrinsic(llvm::Intrinsic::eh_exceptioncode);
1880 llvm::Value *Code = Builder.CreateCall(SEHCodeIntrin, {CPI});
1881 Builder.CreateStore(Code, SEHCodeSlotStack.back());
1884 // Emit the __except body.
1885 EmitStmt(Except->getBlock());
1887 // End the lifetime of the exception code.
1888 SEHCodeSlotStack.pop_back();
1890 if (HaveInsertPoint())
1891 Builder.CreateBr(ContBB);
1896 void CodeGenFunction::EmitSEHLeaveStmt(const SEHLeaveStmt &S) {
1897 // If this code is reachable then emit a stop point (if generating
1898 // debug info). We have to do this ourselves because we are on the
1899 // "simple" statement path.
1900 if (HaveInsertPoint())
1903 // This must be a __leave from a __finally block, which we warn on and is UB.
1904 // Just emit unreachable.
1905 if (!isSEHTryScope()) {
1906 Builder.CreateUnreachable();
1907 Builder.ClearInsertionPoint();
1911 EmitBranchThroughCleanup(*SEHTryEpilogueStack.back());