1 //===--- CGException.cpp - Emit LLVM Code for C++ exceptions ----*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This contains code dealing with C++ exception related code generation.
11 //===----------------------------------------------------------------------===//
14 #include "CGCleanup.h"
15 #include "CGObjCRuntime.h"
16 #include "CodeGenFunction.h"
17 #include "ConstantEmitter.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/DiagnosticSema.h"
24 #include "clang/Basic/TargetBuiltins.h"
25 #include "llvm/IR/IntrinsicInst.h"
26 #include "llvm/IR/Intrinsics.h"
27 #include "llvm/IR/IntrinsicsWebAssembly.h"
28 #include "llvm/Support/SaveAndRestore.h"
30 using namespace clang
;
31 using namespace CodeGen
;
33 static llvm::FunctionCallee
getFreeExceptionFn(CodeGenModule
&CGM
) {
34 // void __cxa_free_exception(void *thrown_exception);
36 llvm::FunctionType
*FTy
=
37 llvm::FunctionType::get(CGM
.VoidTy
, CGM
.Int8PtrTy
, /*isVarArg=*/false);
39 return CGM
.CreateRuntimeFunction(FTy
, "__cxa_free_exception");
42 static llvm::FunctionCallee
getSehTryBeginFn(CodeGenModule
&CGM
) {
43 llvm::FunctionType
*FTy
=
44 llvm::FunctionType::get(CGM
.VoidTy
, /*isVarArg=*/false);
45 return CGM
.CreateRuntimeFunction(FTy
, "llvm.seh.try.begin");
48 static llvm::FunctionCallee
getSehTryEndFn(CodeGenModule
&CGM
) {
49 llvm::FunctionType
*FTy
=
50 llvm::FunctionType::get(CGM
.VoidTy
, /*isVarArg=*/false);
51 return CGM
.CreateRuntimeFunction(FTy
, "llvm.seh.try.end");
54 static llvm::FunctionCallee
getUnexpectedFn(CodeGenModule
&CGM
) {
55 // void __cxa_call_unexpected(void *thrown_exception);
57 llvm::FunctionType
*FTy
=
58 llvm::FunctionType::get(CGM
.VoidTy
, CGM
.Int8PtrTy
, /*isVarArg=*/false);
60 return CGM
.CreateRuntimeFunction(FTy
, "__cxa_call_unexpected");
63 llvm::FunctionCallee
CodeGenModule::getTerminateFn() {
64 // void __terminate();
66 llvm::FunctionType
*FTy
=
67 llvm::FunctionType::get(VoidTy
, /*isVarArg=*/false);
71 // In C++, use std::terminate().
72 if (getLangOpts().CPlusPlus
&&
73 getTarget().getCXXABI().isItaniumFamily()) {
74 name
= "_ZSt9terminatev";
75 } else if (getLangOpts().CPlusPlus
&&
76 getTarget().getCXXABI().isMicrosoft()) {
77 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015
))
78 name
= "__std_terminate";
80 name
= "?terminate@@YAXXZ";
81 } else if (getLangOpts().ObjC
&&
82 getLangOpts().ObjCRuntime
.hasTerminate())
83 name
= "objc_terminate";
86 return CreateRuntimeFunction(FTy
, name
);
89 static llvm::FunctionCallee
getCatchallRethrowFn(CodeGenModule
&CGM
,
91 llvm::FunctionType
*FTy
=
92 llvm::FunctionType::get(CGM
.VoidTy
, CGM
.Int8PtrTy
, /*isVarArg=*/false);
94 return CGM
.CreateRuntimeFunction(FTy
, Name
);
97 const EHPersonality
EHPersonality::GNU_C
= { "__gcc_personality_v0", nullptr };
99 EHPersonality::GNU_C_SJLJ
= { "__gcc_personality_sj0", nullptr };
101 EHPersonality::GNU_C_SEH
= { "__gcc_personality_seh0", nullptr };
103 EHPersonality::NeXT_ObjC
= { "__objc_personality_v0", nullptr };
105 EHPersonality::GNU_CPlusPlus
= { "__gxx_personality_v0", nullptr };
107 EHPersonality::GNU_CPlusPlus_SJLJ
= { "__gxx_personality_sj0", nullptr };
109 EHPersonality::GNU_CPlusPlus_SEH
= { "__gxx_personality_seh0", nullptr };
111 EHPersonality::GNU_ObjC
= {"__gnu_objc_personality_v0", "objc_exception_throw"};
113 EHPersonality::GNU_ObjC_SJLJ
= {"__gnu_objc_personality_sj0", "objc_exception_throw"};
115 EHPersonality::GNU_ObjC_SEH
= {"__gnu_objc_personality_seh0", "objc_exception_throw"};
117 EHPersonality::GNU_ObjCXX
= { "__gnustep_objcxx_personality_v0", nullptr };
119 EHPersonality::GNUstep_ObjC
= { "__gnustep_objc_personality_v0", nullptr };
121 EHPersonality::MSVC_except_handler
= { "_except_handler3", nullptr };
123 EHPersonality::MSVC_C_specific_handler
= { "__C_specific_handler", nullptr };
125 EHPersonality::MSVC_CxxFrameHandler3
= { "__CxxFrameHandler3", nullptr };
127 EHPersonality::GNU_Wasm_CPlusPlus
= { "__gxx_wasm_personality_v0", nullptr };
128 const EHPersonality
EHPersonality::XL_CPlusPlus
= {"__xlcxx_personality_v1",
131 static const EHPersonality
&getCPersonality(const TargetInfo
&Target
,
132 const LangOptions
&L
) {
133 const llvm::Triple
&T
= Target
.getTriple();
134 if (T
.isWindowsMSVCEnvironment())
135 return EHPersonality::MSVC_CxxFrameHandler3
;
136 if (L
.hasSjLjExceptions())
137 return EHPersonality::GNU_C_SJLJ
;
138 if (L
.hasDWARFExceptions())
139 return EHPersonality::GNU_C
;
140 if (L
.hasSEHExceptions())
141 return EHPersonality::GNU_C_SEH
;
142 return EHPersonality::GNU_C
;
145 static const EHPersonality
&getObjCPersonality(const TargetInfo
&Target
,
146 const LangOptions
&L
) {
147 const llvm::Triple
&T
= Target
.getTriple();
148 if (T
.isWindowsMSVCEnvironment())
149 return EHPersonality::MSVC_CxxFrameHandler3
;
151 switch (L
.ObjCRuntime
.getKind()) {
152 case ObjCRuntime::FragileMacOSX
:
153 return getCPersonality(Target
, L
);
154 case ObjCRuntime::MacOSX
:
155 case ObjCRuntime::iOS
:
156 case ObjCRuntime::WatchOS
:
157 return EHPersonality::NeXT_ObjC
;
158 case ObjCRuntime::GNUstep
:
159 if (L
.ObjCRuntime
.getVersion() >= VersionTuple(1, 7))
160 return EHPersonality::GNUstep_ObjC
;
162 case ObjCRuntime::GCC
:
163 case ObjCRuntime::ObjFW
:
164 if (L
.hasSjLjExceptions())
165 return EHPersonality::GNU_ObjC_SJLJ
;
166 if (L
.hasSEHExceptions())
167 return EHPersonality::GNU_ObjC_SEH
;
168 return EHPersonality::GNU_ObjC
;
170 llvm_unreachable("bad runtime kind");
173 static const EHPersonality
&getCXXPersonality(const TargetInfo
&Target
,
174 const LangOptions
&L
) {
175 const llvm::Triple
&T
= Target
.getTriple();
176 if (T
.isWindowsMSVCEnvironment())
177 return EHPersonality::MSVC_CxxFrameHandler3
;
179 return EHPersonality::XL_CPlusPlus
;
180 if (L
.hasSjLjExceptions())
181 return EHPersonality::GNU_CPlusPlus_SJLJ
;
182 if (L
.hasDWARFExceptions())
183 return EHPersonality::GNU_CPlusPlus
;
184 if (L
.hasSEHExceptions())
185 return EHPersonality::GNU_CPlusPlus_SEH
;
186 if (L
.hasWasmExceptions())
187 return EHPersonality::GNU_Wasm_CPlusPlus
;
188 return EHPersonality::GNU_CPlusPlus
;
191 /// Determines the personality function to use when both C++
192 /// and Objective-C exceptions are being caught.
193 static const EHPersonality
&getObjCXXPersonality(const TargetInfo
&Target
,
194 const LangOptions
&L
) {
195 if (Target
.getTriple().isWindowsMSVCEnvironment())
196 return EHPersonality::MSVC_CxxFrameHandler3
;
198 switch (L
.ObjCRuntime
.getKind()) {
199 // In the fragile ABI, just use C++ exception handling and hope
200 // they're not doing crazy exception mixing.
201 case ObjCRuntime::FragileMacOSX
:
202 return getCXXPersonality(Target
, L
);
204 // The ObjC personality defers to the C++ personality for non-ObjC
205 // handlers. Unlike the C++ case, we use the same personality
206 // function on targets using (backend-driven) SJLJ EH.
207 case ObjCRuntime::MacOSX
:
208 case ObjCRuntime::iOS
:
209 case ObjCRuntime::WatchOS
:
210 return getObjCPersonality(Target
, L
);
212 case ObjCRuntime::GNUstep
:
213 return EHPersonality::GNU_ObjCXX
;
215 // The GCC runtime's personality function inherently doesn't support
216 // mixed EH. Use the ObjC personality just to avoid returning null.
217 case ObjCRuntime::GCC
:
218 case ObjCRuntime::ObjFW
:
219 return getObjCPersonality(Target
, L
);
221 llvm_unreachable("bad runtime kind");
224 static const EHPersonality
&getSEHPersonalityMSVC(const llvm::Triple
&T
) {
225 if (T
.getArch() == llvm::Triple::x86
)
226 return EHPersonality::MSVC_except_handler
;
227 return EHPersonality::MSVC_C_specific_handler
;
230 const EHPersonality
&EHPersonality::get(CodeGenModule
&CGM
,
231 const FunctionDecl
*FD
) {
232 const llvm::Triple
&T
= CGM
.getTarget().getTriple();
233 const LangOptions
&L
= CGM
.getLangOpts();
234 const TargetInfo
&Target
= CGM
.getTarget();
236 // Functions using SEH get an SEH personality.
237 if (FD
&& FD
->usesSEHTry())
238 return getSEHPersonalityMSVC(T
);
241 return L
.CPlusPlus
? getObjCXXPersonality(Target
, L
)
242 : getObjCPersonality(Target
, L
);
243 return L
.CPlusPlus
? getCXXPersonality(Target
, L
)
244 : getCPersonality(Target
, L
);
247 const EHPersonality
&EHPersonality::get(CodeGenFunction
&CGF
) {
248 const auto *FD
= CGF
.CurCodeDecl
;
249 // For outlined finallys and filters, use the SEH personality in case they
250 // contain more SEH. This mostly only affects finallys. Filters could
251 // hypothetically use gnu statement expressions to sneak in nested SEH.
252 FD
= FD
? FD
: CGF
.CurSEHParent
.getDecl();
253 return get(CGF
.CGM
, dyn_cast_or_null
<FunctionDecl
>(FD
));
256 static llvm::FunctionCallee
getPersonalityFn(CodeGenModule
&CGM
,
257 const EHPersonality
&Personality
) {
258 return CGM
.CreateRuntimeFunction(llvm::FunctionType::get(CGM
.Int32Ty
, true),
259 Personality
.PersonalityFn
,
260 llvm::AttributeList(), /*Local=*/true);
263 static llvm::Constant
*getOpaquePersonalityFn(CodeGenModule
&CGM
,
264 const EHPersonality
&Personality
) {
265 llvm::FunctionCallee Fn
= getPersonalityFn(CGM
, Personality
);
266 llvm::PointerType
* Int8PtrTy
= llvm::PointerType::get(
267 llvm::Type::getInt8Ty(CGM
.getLLVMContext()),
268 CGM
.getDataLayout().getProgramAddressSpace());
270 return llvm::ConstantExpr::getBitCast(cast
<llvm::Constant
>(Fn
.getCallee()),
274 /// Check whether a landingpad instruction only uses C++ features.
275 static bool LandingPadHasOnlyCXXUses(llvm::LandingPadInst
*LPI
) {
276 for (unsigned I
= 0, E
= LPI
->getNumClauses(); I
!= E
; ++I
) {
277 // Look for something that would've been returned by the ObjC
278 // runtime's GetEHType() method.
279 llvm::Value
*Val
= LPI
->getClause(I
)->stripPointerCasts();
280 if (LPI
->isCatch(I
)) {
281 // Check if the catch value has the ObjC prefix.
282 if (llvm::GlobalVariable
*GV
= dyn_cast
<llvm::GlobalVariable
>(Val
))
283 // ObjC EH selector entries are always global variables with
284 // names starting like this.
285 if (GV
->getName().startswith("OBJC_EHTYPE"))
288 // Check if any of the filter values have the ObjC prefix.
289 llvm::Constant
*CVal
= cast
<llvm::Constant
>(Val
);
290 for (llvm::User::op_iterator
291 II
= CVal
->op_begin(), IE
= CVal
->op_end(); II
!= IE
; ++II
) {
292 if (llvm::GlobalVariable
*GV
=
293 cast
<llvm::GlobalVariable
>((*II
)->stripPointerCasts()))
294 // ObjC EH selector entries are always global variables with
295 // names starting like this.
296 if (GV
->getName().startswith("OBJC_EHTYPE"))
304 /// Check whether a personality function could reasonably be swapped
305 /// for a C++ personality function.
306 static bool PersonalityHasOnlyCXXUses(llvm::Constant
*Fn
) {
307 for (llvm::User
*U
: Fn
->users()) {
308 // Conditionally white-list bitcasts.
309 if (llvm::ConstantExpr
*CE
= dyn_cast
<llvm::ConstantExpr
>(U
)) {
310 if (CE
->getOpcode() != llvm::Instruction::BitCast
) return false;
311 if (!PersonalityHasOnlyCXXUses(CE
))
316 // Otherwise it must be a function.
317 llvm::Function
*F
= dyn_cast
<llvm::Function
>(U
);
318 if (!F
) return false;
320 for (auto BB
= F
->begin(), E
= F
->end(); BB
!= E
; ++BB
) {
321 if (BB
->isLandingPad())
322 if (!LandingPadHasOnlyCXXUses(BB
->getLandingPadInst()))
330 /// Try to use the C++ personality function in ObjC++. Not doing this
331 /// can cause some incompatibilities with gcc, which is more
332 /// aggressive about only using the ObjC++ personality in a function
333 /// when it really needs it.
334 void CodeGenModule::SimplifyPersonality() {
335 // If we're not in ObjC++ -fexceptions, there's nothing to do.
336 if (!LangOpts
.CPlusPlus
|| !LangOpts
.ObjC
|| !LangOpts
.Exceptions
)
339 // Both the problem this endeavors to fix and the way the logic
340 // above works is specific to the NeXT runtime.
341 if (!LangOpts
.ObjCRuntime
.isNeXTFamily())
344 const EHPersonality
&ObjCXX
= EHPersonality::get(*this, /*FD=*/nullptr);
345 const EHPersonality
&CXX
= getCXXPersonality(getTarget(), LangOpts
);
349 assert(std::strcmp(ObjCXX
.PersonalityFn
, CXX
.PersonalityFn
) != 0 &&
350 "Different EHPersonalities using the same personality function.");
352 llvm::Function
*Fn
= getModule().getFunction(ObjCXX
.PersonalityFn
);
354 // Nothing to do if it's unused.
355 if (!Fn
|| Fn
->use_empty()) return;
357 // Can't do the optimization if it has non-C++ uses.
358 if (!PersonalityHasOnlyCXXUses(Fn
)) return;
360 // Create the C++ personality function and kill off the old
362 llvm::FunctionCallee CXXFn
= getPersonalityFn(*this, CXX
);
364 // This can happen if the user is screwing with us.
365 if (Fn
->getType() != CXXFn
.getCallee()->getType())
368 Fn
->replaceAllUsesWith(CXXFn
.getCallee());
369 Fn
->eraseFromParent();
372 /// Returns the value to inject into a selector to indicate the
373 /// presence of a catch-all.
374 static llvm::Constant
*getCatchAllValue(CodeGenFunction
&CGF
) {
375 // Possibly we should use @llvm.eh.catch.all.value here.
376 return llvm::ConstantPointerNull::get(CGF
.Int8PtrTy
);
380 /// A cleanup to free the exception object if its initialization
382 struct FreeException final
: EHScopeStack::Cleanup
{
384 FreeException(llvm::Value
*exn
) : exn(exn
) {}
385 void Emit(CodeGenFunction
&CGF
, Flags flags
) override
{
386 CGF
.EmitNounwindRuntimeCall(getFreeExceptionFn(CGF
.CGM
), exn
);
389 } // end anonymous namespace
391 // Emits an exception expression into the given location. This
392 // differs from EmitAnyExprToMem only in that, if a final copy-ctor
393 // call is required, an exception within that copy ctor causes
394 // std::terminate to be invoked.
395 void CodeGenFunction::EmitAnyExprToExn(const Expr
*e
, Address addr
) {
396 // Make sure the exception object is cleaned up if there's an
397 // exception during initialization.
398 pushFullExprCleanup
<FreeException
>(EHCleanup
, addr
.getPointer());
399 EHScopeStack::stable_iterator cleanup
= EHStack
.stable_begin();
401 // __cxa_allocate_exception returns a void*; we need to cast this
402 // to the appropriate type for the object.
403 llvm::Type
*ty
= ConvertTypeForMem(e
->getType());
404 Address typedAddr
= addr
.withElementType(ty
);
406 // FIXME: this isn't quite right! If there's a final unelided call
407 // to a copy constructor, then according to [except.terminate]p1 we
408 // must call std::terminate() if that constructor throws, because
409 // technically that copy occurs after the exception expression is
410 // evaluated but before the exception is caught. But the best way
411 // to handle that is to teach EmitAggExpr to do the final copy
412 // differently if it can't be elided.
413 EmitAnyExprToMem(e
, typedAddr
, e
->getType().getQualifiers(),
416 // Deactivate the cleanup block.
417 DeactivateCleanupBlock(cleanup
,
418 cast
<llvm::Instruction
>(typedAddr
.getPointer()));
421 Address
CodeGenFunction::getExceptionSlot() {
423 ExceptionSlot
= CreateTempAlloca(Int8PtrTy
, "exn.slot");
424 return Address(ExceptionSlot
, Int8PtrTy
, getPointerAlign());
427 Address
CodeGenFunction::getEHSelectorSlot() {
429 EHSelectorSlot
= CreateTempAlloca(Int32Ty
, "ehselector.slot");
430 return Address(EHSelectorSlot
, Int32Ty
, CharUnits::fromQuantity(4));
433 llvm::Value
*CodeGenFunction::getExceptionFromSlot() {
434 return Builder
.CreateLoad(getExceptionSlot(), "exn");
437 llvm::Value
*CodeGenFunction::getSelectorFromSlot() {
438 return Builder
.CreateLoad(getEHSelectorSlot(), "sel");
441 void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr
*E
,
442 bool KeepInsertionPoint
) {
443 // If the exception is being emitted in an OpenMP target region,
444 // and the target is a GPU, we do not support exception handling.
445 // Therefore, we emit a trap which will abort the program, and
446 // prompt a warning indicating that a trap will be emitted.
447 const llvm::Triple
&T
= Target
.getTriple();
448 if (CGM
.getLangOpts().OpenMPIsTargetDevice
&& (T
.isNVPTX() || T
.isAMDGCN())) {
449 EmitTrapCall(llvm::Intrinsic::trap
);
452 if (const Expr
*SubExpr
= E
->getSubExpr()) {
453 QualType ThrowType
= SubExpr
->getType();
454 if (ThrowType
->isObjCObjectPointerType()) {
455 const Stmt
*ThrowStmt
= E
->getSubExpr();
456 const ObjCAtThrowStmt
S(E
->getExprLoc(), const_cast<Stmt
*>(ThrowStmt
));
457 CGM
.getObjCRuntime().EmitThrowStmt(*this, S
, false);
459 CGM
.getCXXABI().emitThrow(*this, E
);
462 CGM
.getCXXABI().emitRethrow(*this, /*isNoReturn=*/true);
465 // throw is an expression, and the expression emitters expect us
466 // to leave ourselves at a valid insertion point.
467 if (KeepInsertionPoint
)
468 EmitBlock(createBasicBlock("throw.cont"));
471 void CodeGenFunction::EmitStartEHSpec(const Decl
*D
) {
472 if (!CGM
.getLangOpts().CXXExceptions
)
475 const FunctionDecl
* FD
= dyn_cast_or_null
<FunctionDecl
>(D
);
477 // Check if CapturedDecl is nothrow and create terminate scope for it.
478 if (const CapturedDecl
* CD
= dyn_cast_or_null
<CapturedDecl
>(D
)) {
480 EHStack
.pushTerminate();
484 const FunctionProtoType
*Proto
= FD
->getType()->getAs
<FunctionProtoType
>();
488 ExceptionSpecificationType EST
= Proto
->getExceptionSpecType();
489 // In C++17 and later, 'throw()' aka EST_DynamicNone is treated the same way
490 // as noexcept. In earlier standards, it is handled in this block, along with
492 if (EST
== EST_Dynamic
||
493 (EST
== EST_DynamicNone
&& !getLangOpts().CPlusPlus17
)) {
494 // TODO: Revisit exception specifications for the MS ABI. There is a way to
495 // encode these in an object file but MSVC doesn't do anything with it.
496 if (getTarget().getCXXABI().isMicrosoft())
498 // In Wasm EH we currently treat 'throw()' in the same way as 'noexcept'. In
499 // case of throw with types, we ignore it and print a warning for now.
500 // TODO Correctly handle exception specification in Wasm EH
501 if (CGM
.getLangOpts().hasWasmExceptions()) {
502 if (EST
== EST_DynamicNone
)
503 EHStack
.pushTerminate();
505 CGM
.getDiags().Report(D
->getLocation(),
506 diag::warn_wasm_dynamic_exception_spec_ignored
)
507 << FD
->getExceptionSpecSourceRange();
510 // Currently Emscripten EH only handles 'throw()' but not 'throw' with
511 // types. 'throw()' handling will be done in JS glue code so we don't need
512 // to do anything in that case. Just print a warning message in case of
514 // TODO Correctly handle exception specification in Emscripten EH
515 if (getTarget().getCXXABI() == TargetCXXABI::WebAssembly
&&
516 CGM
.getLangOpts().getExceptionHandling() ==
517 LangOptions::ExceptionHandlingKind::None
&&
519 CGM
.getDiags().Report(D
->getLocation(),
520 diag::warn_wasm_dynamic_exception_spec_ignored
)
521 << FD
->getExceptionSpecSourceRange();
523 unsigned NumExceptions
= Proto
->getNumExceptions();
524 EHFilterScope
*Filter
= EHStack
.pushFilter(NumExceptions
);
526 for (unsigned I
= 0; I
!= NumExceptions
; ++I
) {
527 QualType Ty
= Proto
->getExceptionType(I
);
528 QualType ExceptType
= Ty
.getNonReferenceType().getUnqualifiedType();
529 llvm::Value
*EHType
= CGM
.GetAddrOfRTTIDescriptor(ExceptType
,
531 Filter
->setFilter(I
, EHType
);
533 } else if (Proto
->canThrow() == CT_Cannot
) {
534 // noexcept functions are simple terminate scopes.
535 if (!getLangOpts().EHAsynch
) // -EHa: HW exception still can occur
536 EHStack
.pushTerminate();
540 /// Emit the dispatch block for a filter scope if necessary.
541 static void emitFilterDispatchBlock(CodeGenFunction
&CGF
,
542 EHFilterScope
&filterScope
) {
543 llvm::BasicBlock
*dispatchBlock
= filterScope
.getCachedEHDispatchBlock();
544 if (!dispatchBlock
) return;
545 if (dispatchBlock
->use_empty()) {
546 delete dispatchBlock
;
550 CGF
.EmitBlockAfterUses(dispatchBlock
);
552 // If this isn't a catch-all filter, we need to check whether we got
553 // here because the filter triggered.
554 if (filterScope
.getNumFilters()) {
555 // Load the selector value.
556 llvm::Value
*selector
= CGF
.getSelectorFromSlot();
557 llvm::BasicBlock
*unexpectedBB
= CGF
.createBasicBlock("ehspec.unexpected");
559 llvm::Value
*zero
= CGF
.Builder
.getInt32(0);
560 llvm::Value
*failsFilter
=
561 CGF
.Builder
.CreateICmpSLT(selector
, zero
, "ehspec.fails");
562 CGF
.Builder
.CreateCondBr(failsFilter
, unexpectedBB
,
563 CGF
.getEHResumeBlock(false));
565 CGF
.EmitBlock(unexpectedBB
);
568 // Call __cxa_call_unexpected. This doesn't need to be an invoke
569 // because __cxa_call_unexpected magically filters exceptions
570 // according to the last landing pad the exception was thrown
572 llvm::Value
*exn
= CGF
.getExceptionFromSlot();
573 CGF
.EmitRuntimeCall(getUnexpectedFn(CGF
.CGM
), exn
)
574 ->setDoesNotReturn();
575 CGF
.Builder
.CreateUnreachable();
578 void CodeGenFunction::EmitEndEHSpec(const Decl
*D
) {
579 if (!CGM
.getLangOpts().CXXExceptions
)
582 const FunctionDecl
* FD
= dyn_cast_or_null
<FunctionDecl
>(D
);
584 // Check if CapturedDecl is nothrow and pop terminate scope for it.
585 if (const CapturedDecl
* CD
= dyn_cast_or_null
<CapturedDecl
>(D
)) {
586 if (CD
->isNothrow() && !EHStack
.empty())
587 EHStack
.popTerminate();
591 const FunctionProtoType
*Proto
= FD
->getType()->getAs
<FunctionProtoType
>();
595 ExceptionSpecificationType EST
= Proto
->getExceptionSpecType();
596 if (EST
== EST_Dynamic
||
597 (EST
== EST_DynamicNone
&& !getLangOpts().CPlusPlus17
)) {
598 // TODO: Revisit exception specifications for the MS ABI. There is a way to
599 // encode these in an object file but MSVC doesn't do anything with it.
600 if (getTarget().getCXXABI().isMicrosoft())
602 // In wasm we currently treat 'throw()' in the same way as 'noexcept'. In
603 // case of throw with types, we ignore it and print a warning for now.
604 // TODO Correctly handle exception specification in wasm
605 if (CGM
.getLangOpts().hasWasmExceptions()) {
606 if (EST
== EST_DynamicNone
)
607 EHStack
.popTerminate();
610 EHFilterScope
&filterScope
= cast
<EHFilterScope
>(*EHStack
.begin());
611 emitFilterDispatchBlock(*this, filterScope
);
613 } else if (Proto
->canThrow() == CT_Cannot
&&
614 /* possible empty when under async exceptions */
616 EHStack
.popTerminate();
620 void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt
&S
) {
621 const llvm::Triple
&T
= Target
.getTriple();
622 // If we encounter a try statement on in an OpenMP target region offloaded to
623 // a GPU, we treat it as a basic block.
624 const bool IsTargetDevice
=
625 (CGM
.getLangOpts().OpenMPIsTargetDevice
&& (T
.isNVPTX() || T
.isAMDGCN()));
628 EmitStmt(S
.getTryBlock());
633 void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt
&S
, bool IsFnTryBlock
) {
634 unsigned NumHandlers
= S
.getNumHandlers();
635 EHCatchScope
*CatchScope
= EHStack
.pushCatch(NumHandlers
);
637 for (unsigned I
= 0; I
!= NumHandlers
; ++I
) {
638 const CXXCatchStmt
*C
= S
.getHandler(I
);
640 llvm::BasicBlock
*Handler
= createBasicBlock("catch");
641 if (C
->getExceptionDecl()) {
642 // FIXME: Dropping the reference type on the type into makes it
643 // impossible to correctly implement catch-by-reference
644 // semantics for pointers. Unfortunately, this is what all
645 // existing compilers do, and it's not clear that the standard
646 // personality routine is capable of doing this right. See C++ DR 388:
647 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
648 Qualifiers CaughtTypeQuals
;
649 QualType CaughtType
= CGM
.getContext().getUnqualifiedArrayType(
650 C
->getCaughtType().getNonReferenceType(), CaughtTypeQuals
);
652 CatchTypeInfo TypeInfo
{nullptr, 0};
653 if (CaughtType
->isObjCObjectPointerType())
654 TypeInfo
.RTTI
= CGM
.getObjCRuntime().GetEHType(CaughtType
);
656 TypeInfo
= CGM
.getCXXABI().getAddrOfCXXCatchHandlerType(
657 CaughtType
, C
->getCaughtType());
658 CatchScope
->setHandler(I
, TypeInfo
, Handler
);
660 // No exception decl indicates '...', a catch-all.
661 CatchScope
->setHandler(I
, CGM
.getCXXABI().getCatchAllTypeInfo(), Handler
);
662 // Under async exceptions, catch(...) need to catch HW exception too
663 // Mark scope with SehTryBegin as a SEH __try scope
664 if (getLangOpts().EHAsynch
)
665 EmitSehTryScopeBegin();
671 CodeGenFunction::getEHDispatchBlock(EHScopeStack::stable_iterator si
) {
672 if (EHPersonality::get(*this).usesFuncletPads())
673 return getFuncletEHDispatchBlock(si
);
675 // The dispatch block for the end of the scope chain is a block that
676 // just resumes unwinding.
677 if (si
== EHStack
.stable_end())
678 return getEHResumeBlock(true);
680 // Otherwise, we should look at the actual scope.
681 EHScope
&scope
= *EHStack
.find(si
);
683 llvm::BasicBlock
*dispatchBlock
= scope
.getCachedEHDispatchBlock();
684 if (!dispatchBlock
) {
685 switch (scope
.getKind()) {
686 case EHScope::Catch
: {
687 // Apply a special case to a single catch-all.
688 EHCatchScope
&catchScope
= cast
<EHCatchScope
>(scope
);
689 if (catchScope
.getNumHandlers() == 1 &&
690 catchScope
.getHandler(0).isCatchAll()) {
691 dispatchBlock
= catchScope
.getHandler(0).Block
;
693 // Otherwise, make a dispatch block.
695 dispatchBlock
= createBasicBlock("catch.dispatch");
700 case EHScope::Cleanup
:
701 dispatchBlock
= createBasicBlock("ehcleanup");
704 case EHScope::Filter
:
705 dispatchBlock
= createBasicBlock("filter.dispatch");
708 case EHScope::Terminate
:
709 dispatchBlock
= getTerminateHandler();
712 scope
.setCachedEHDispatchBlock(dispatchBlock
);
714 return dispatchBlock
;
718 CodeGenFunction::getFuncletEHDispatchBlock(EHScopeStack::stable_iterator SI
) {
719 // Returning nullptr indicates that the previous dispatch block should unwind
721 if (SI
== EHStack
.stable_end())
724 // Otherwise, we should look at the actual scope.
725 EHScope
&EHS
= *EHStack
.find(SI
);
727 llvm::BasicBlock
*DispatchBlock
= EHS
.getCachedEHDispatchBlock();
729 return DispatchBlock
;
731 if (EHS
.getKind() == EHScope::Terminate
)
732 DispatchBlock
= getTerminateFunclet();
734 DispatchBlock
= createBasicBlock();
735 CGBuilderTy
Builder(*this, DispatchBlock
);
737 switch (EHS
.getKind()) {
739 DispatchBlock
->setName("catch.dispatch");
742 case EHScope::Cleanup
:
743 DispatchBlock
->setName("ehcleanup");
746 case EHScope::Filter
:
747 llvm_unreachable("exception specifications not handled yet!");
749 case EHScope::Terminate
:
750 DispatchBlock
->setName("terminate");
753 EHS
.setCachedEHDispatchBlock(DispatchBlock
);
754 return DispatchBlock
;
757 /// Check whether this is a non-EH scope, i.e. a scope which doesn't
758 /// affect exception handling. Currently, the only non-EH scopes are
759 /// normal-only cleanup scopes.
760 static bool isNonEHScope(const EHScope
&S
) {
761 switch (S
.getKind()) {
762 case EHScope::Cleanup
:
763 return !cast
<EHCleanupScope
>(S
).isEHCleanup();
764 case EHScope::Filter
:
766 case EHScope::Terminate
:
770 llvm_unreachable("Invalid EHScope Kind!");
773 llvm::BasicBlock
*CodeGenFunction::getInvokeDestImpl() {
774 assert(EHStack
.requiresLandingPad());
775 assert(!EHStack
.empty());
777 // If exceptions are disabled/ignored and SEH is not in use, then there is no
778 // invoke destination. SEH "works" even if exceptions are off. In practice,
779 // this means that C++ destructors and other EH cleanups don't run, which is
780 // consistent with MSVC's behavior, except in the presence of -EHa
781 const LangOptions
&LO
= CGM
.getLangOpts();
782 if (!LO
.Exceptions
|| LO
.IgnoreExceptions
) {
783 if (!LO
.Borland
&& !LO
.MicrosoftExt
)
785 if (!currentFunctionUsesSEHTry())
789 // CUDA device code doesn't have exceptions.
790 if (LO
.CUDA
&& LO
.CUDAIsDevice
)
793 // Check the innermost scope for a cached landing pad. If this is
794 // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
795 llvm::BasicBlock
*LP
= EHStack
.begin()->getCachedLandingPad();
798 const EHPersonality
&Personality
= EHPersonality::get(*this);
800 if (!CurFn
->hasPersonalityFn())
801 CurFn
->setPersonalityFn(getOpaquePersonalityFn(CGM
, Personality
));
803 if (Personality
.usesFuncletPads()) {
804 // We don't need separate landing pads in the funclet model.
805 LP
= getEHDispatchBlock(EHStack
.getInnermostEHScope());
807 // Build the landing pad for this scope.
808 LP
= EmitLandingPad();
813 // Cache the landing pad on the innermost scope. If this is a
814 // non-EH scope, cache the landing pad on the enclosing scope, too.
815 for (EHScopeStack::iterator ir
= EHStack
.begin(); true; ++ir
) {
816 ir
->setCachedLandingPad(LP
);
817 if (!isNonEHScope(*ir
)) break;
823 llvm::BasicBlock
*CodeGenFunction::EmitLandingPad() {
824 assert(EHStack
.requiresLandingPad());
825 assert(!CGM
.getLangOpts().IgnoreExceptions
&&
826 "LandingPad should not be emitted when -fignore-exceptions are in "
828 EHScope
&innermostEHScope
= *EHStack
.find(EHStack
.getInnermostEHScope());
829 switch (innermostEHScope
.getKind()) {
830 case EHScope::Terminate
:
831 return getTerminateLandingPad();
834 case EHScope::Cleanup
:
835 case EHScope::Filter
:
836 if (llvm::BasicBlock
*lpad
= innermostEHScope
.getCachedLandingPad())
840 // Save the current IR generation state.
841 CGBuilderTy::InsertPoint savedIP
= Builder
.saveAndClearIP();
842 auto DL
= ApplyDebugLocation::CreateDefaultArtificial(*this, CurEHLocation
);
844 // Create and configure the landing pad.
845 llvm::BasicBlock
*lpad
= createBasicBlock("lpad");
848 llvm::LandingPadInst
*LPadInst
=
849 Builder
.CreateLandingPad(llvm::StructType::get(Int8PtrTy
, Int32Ty
), 0);
851 llvm::Value
*LPadExn
= Builder
.CreateExtractValue(LPadInst
, 0);
852 Builder
.CreateStore(LPadExn
, getExceptionSlot());
853 llvm::Value
*LPadSel
= Builder
.CreateExtractValue(LPadInst
, 1);
854 Builder
.CreateStore(LPadSel
, getEHSelectorSlot());
856 // Save the exception pointer. It's safe to use a single exception
857 // pointer per function because EH cleanups can never have nested
859 // Build the landingpad instruction.
861 // Accumulate all the handlers in scope.
862 bool hasCatchAll
= false;
863 bool hasCleanup
= false;
864 bool hasFilter
= false;
865 SmallVector
<llvm::Value
*, 4> filterTypes
;
866 llvm::SmallPtrSet
<llvm::Value
*, 4> catchTypes
;
867 for (EHScopeStack::iterator I
= EHStack
.begin(), E
= EHStack
.end(); I
!= E
;
870 switch (I
->getKind()) {
871 case EHScope::Cleanup
:
872 // If we have a cleanup, remember that.
873 hasCleanup
= (hasCleanup
|| cast
<EHCleanupScope
>(*I
).isEHCleanup());
876 case EHScope::Filter
: {
877 assert(I
.next() == EHStack
.end() && "EH filter is not end of EH stack");
878 assert(!hasCatchAll
&& "EH filter reached after catch-all");
880 // Filter scopes get added to the landingpad in weird ways.
881 EHFilterScope
&filter
= cast
<EHFilterScope
>(*I
);
884 // Add all the filter values.
885 for (unsigned i
= 0, e
= filter
.getNumFilters(); i
!= e
; ++i
)
886 filterTypes
.push_back(filter
.getFilter(i
));
890 case EHScope::Terminate
:
891 // Terminate scopes are basically catch-alls.
892 assert(!hasCatchAll
);
900 EHCatchScope
&catchScope
= cast
<EHCatchScope
>(*I
);
901 for (unsigned hi
= 0, he
= catchScope
.getNumHandlers(); hi
!= he
; ++hi
) {
902 EHCatchScope::Handler handler
= catchScope
.getHandler(hi
);
903 assert(handler
.Type
.Flags
== 0 &&
904 "landingpads do not support catch handler flags");
906 // If this is a catch-all, register that and abort.
907 if (!handler
.Type
.RTTI
) {
908 assert(!hasCatchAll
);
913 // Check whether we already have a handler for this type.
914 if (catchTypes
.insert(handler
.Type
.RTTI
).second
)
915 // If not, add it directly to the landingpad.
916 LPadInst
->addClause(handler
.Type
.RTTI
);
921 // If we have a catch-all, add null to the landingpad.
922 assert(!(hasCatchAll
&& hasFilter
));
924 LPadInst
->addClause(getCatchAllValue(*this));
926 // If we have an EH filter, we need to add those handlers in the
927 // right place in the landingpad, which is to say, at the end.
928 } else if (hasFilter
) {
929 // Create a filter expression: a constant array indicating which filter
930 // types there are. The personality routine only lands here if the filter
932 SmallVector
<llvm::Constant
*, 8> Filters
;
933 llvm::ArrayType
*AType
=
934 llvm::ArrayType::get(!filterTypes
.empty() ?
935 filterTypes
[0]->getType() : Int8PtrTy
,
938 for (unsigned i
= 0, e
= filterTypes
.size(); i
!= e
; ++i
)
939 Filters
.push_back(cast
<llvm::Constant
>(filterTypes
[i
]));
940 llvm::Constant
*FilterArray
= llvm::ConstantArray::get(AType
, Filters
);
941 LPadInst
->addClause(FilterArray
);
943 // Also check whether we need a cleanup.
945 LPadInst
->setCleanup(true);
947 // Otherwise, signal that we at least have cleanups.
948 } else if (hasCleanup
) {
949 LPadInst
->setCleanup(true);
952 assert((LPadInst
->getNumClauses() > 0 || LPadInst
->isCleanup()) &&
953 "landingpad instruction has no clauses!");
955 // Tell the backend how to generate the landing pad.
956 Builder
.CreateBr(getEHDispatchBlock(EHStack
.getInnermostEHScope()));
958 // Restore the old IR generation state.
959 Builder
.restoreIP(savedIP
);
964 static void emitCatchPadBlock(CodeGenFunction
&CGF
, EHCatchScope
&CatchScope
) {
965 llvm::BasicBlock
*DispatchBlock
= CatchScope
.getCachedEHDispatchBlock();
966 assert(DispatchBlock
);
968 CGBuilderTy::InsertPoint SavedIP
= CGF
.Builder
.saveIP();
969 CGF
.EmitBlockAfterUses(DispatchBlock
);
971 llvm::Value
*ParentPad
= CGF
.CurrentFuncletPad
;
973 ParentPad
= llvm::ConstantTokenNone::get(CGF
.getLLVMContext());
974 llvm::BasicBlock
*UnwindBB
=
975 CGF
.getEHDispatchBlock(CatchScope
.getEnclosingEHScope());
977 unsigned NumHandlers
= CatchScope
.getNumHandlers();
978 llvm::CatchSwitchInst
*CatchSwitch
=
979 CGF
.Builder
.CreateCatchSwitch(ParentPad
, UnwindBB
, NumHandlers
);
981 // Test against each of the exception types we claim to catch.
982 for (unsigned I
= 0; I
< NumHandlers
; ++I
) {
983 const EHCatchScope::Handler
&Handler
= CatchScope
.getHandler(I
);
985 CatchTypeInfo TypeInfo
= Handler
.Type
;
987 TypeInfo
.RTTI
= llvm::Constant::getNullValue(CGF
.VoidPtrTy
);
989 CGF
.Builder
.SetInsertPoint(Handler
.Block
);
991 if (EHPersonality::get(CGF
).isMSVCXXPersonality()) {
992 CGF
.Builder
.CreateCatchPad(
993 CatchSwitch
, {TypeInfo
.RTTI
, CGF
.Builder
.getInt32(TypeInfo
.Flags
),
994 llvm::Constant::getNullValue(CGF
.VoidPtrTy
)});
996 CGF
.Builder
.CreateCatchPad(CatchSwitch
, {TypeInfo
.RTTI
});
999 CatchSwitch
->addHandler(Handler
.Block
);
1001 CGF
.Builder
.restoreIP(SavedIP
);
1004 // Wasm uses Windows-style EH instructions, but it merges all catch clauses into
1005 // one big catchpad, within which we use Itanium's landingpad-style selector
1006 // comparison instructions.
1007 static void emitWasmCatchPadBlock(CodeGenFunction
&CGF
,
1008 EHCatchScope
&CatchScope
) {
1009 llvm::BasicBlock
*DispatchBlock
= CatchScope
.getCachedEHDispatchBlock();
1010 assert(DispatchBlock
);
1012 CGBuilderTy::InsertPoint SavedIP
= CGF
.Builder
.saveIP();
1013 CGF
.EmitBlockAfterUses(DispatchBlock
);
1015 llvm::Value
*ParentPad
= CGF
.CurrentFuncletPad
;
1017 ParentPad
= llvm::ConstantTokenNone::get(CGF
.getLLVMContext());
1018 llvm::BasicBlock
*UnwindBB
=
1019 CGF
.getEHDispatchBlock(CatchScope
.getEnclosingEHScope());
1021 unsigned NumHandlers
= CatchScope
.getNumHandlers();
1022 llvm::CatchSwitchInst
*CatchSwitch
=
1023 CGF
.Builder
.CreateCatchSwitch(ParentPad
, UnwindBB
, NumHandlers
);
1025 // We don't use a landingpad instruction, so generate intrinsic calls to
1026 // provide exception and selector values.
1027 llvm::BasicBlock
*WasmCatchStartBlock
= CGF
.createBasicBlock("catch.start");
1028 CatchSwitch
->addHandler(WasmCatchStartBlock
);
1029 CGF
.EmitBlockAfterUses(WasmCatchStartBlock
);
1031 // Create a catchpad instruction.
1032 SmallVector
<llvm::Value
*, 4> CatchTypes
;
1033 for (unsigned I
= 0, E
= NumHandlers
; I
< E
; ++I
) {
1034 const EHCatchScope::Handler
&Handler
= CatchScope
.getHandler(I
);
1035 CatchTypeInfo TypeInfo
= Handler
.Type
;
1037 TypeInfo
.RTTI
= llvm::Constant::getNullValue(CGF
.VoidPtrTy
);
1038 CatchTypes
.push_back(TypeInfo
.RTTI
);
1040 auto *CPI
= CGF
.Builder
.CreateCatchPad(CatchSwitch
, CatchTypes
);
1042 // Create calls to wasm.get.exception and wasm.get.ehselector intrinsics.
1043 // Before they are lowered appropriately later, they provide values for the
1044 // exception and selector.
1045 llvm::Function
*GetExnFn
=
1046 CGF
.CGM
.getIntrinsic(llvm::Intrinsic::wasm_get_exception
);
1047 llvm::Function
*GetSelectorFn
=
1048 CGF
.CGM
.getIntrinsic(llvm::Intrinsic::wasm_get_ehselector
);
1049 llvm::CallInst
*Exn
= CGF
.Builder
.CreateCall(GetExnFn
, CPI
);
1050 CGF
.Builder
.CreateStore(Exn
, CGF
.getExceptionSlot());
1051 llvm::CallInst
*Selector
= CGF
.Builder
.CreateCall(GetSelectorFn
, CPI
);
1053 llvm::Function
*TypeIDFn
= CGF
.CGM
.getIntrinsic(llvm::Intrinsic::eh_typeid_for
);
1055 // If there's only a single catch-all, branch directly to its handler.
1056 if (CatchScope
.getNumHandlers() == 1 &&
1057 CatchScope
.getHandler(0).isCatchAll()) {
1058 CGF
.Builder
.CreateBr(CatchScope
.getHandler(0).Block
);
1059 CGF
.Builder
.restoreIP(SavedIP
);
1063 // Test against each of the exception types we claim to catch.
1064 for (unsigned I
= 0, E
= NumHandlers
;; ++I
) {
1065 assert(I
< E
&& "ran off end of handlers!");
1066 const EHCatchScope::Handler
&Handler
= CatchScope
.getHandler(I
);
1067 CatchTypeInfo TypeInfo
= Handler
.Type
;
1069 TypeInfo
.RTTI
= llvm::Constant::getNullValue(CGF
.VoidPtrTy
);
1071 // Figure out the next block.
1072 llvm::BasicBlock
*NextBlock
;
1074 bool EmitNextBlock
= false, NextIsEnd
= false;
1076 // If this is the last handler, we're at the end, and the next block is a
1077 // block that contains a call to the rethrow function, so we can unwind to
1078 // the enclosing EH scope. The call itself will be generated later.
1080 NextBlock
= CGF
.createBasicBlock("rethrow");
1081 EmitNextBlock
= true;
1084 // If the next handler is a catch-all, we're at the end, and the
1085 // next block is that handler.
1086 } else if (CatchScope
.getHandler(I
+ 1).isCatchAll()) {
1087 NextBlock
= CatchScope
.getHandler(I
+ 1).Block
;
1090 // Otherwise, we're not at the end and we need a new block.
1092 NextBlock
= CGF
.createBasicBlock("catch.fallthrough");
1093 EmitNextBlock
= true;
1096 // Figure out the catch type's index in the LSDA's type table.
1097 llvm::CallInst
*TypeIndex
= CGF
.Builder
.CreateCall(TypeIDFn
, TypeInfo
.RTTI
);
1098 TypeIndex
->setDoesNotThrow();
1100 llvm::Value
*MatchesTypeIndex
=
1101 CGF
.Builder
.CreateICmpEQ(Selector
, TypeIndex
, "matches");
1102 CGF
.Builder
.CreateCondBr(MatchesTypeIndex
, Handler
.Block
, NextBlock
);
1105 CGF
.EmitBlock(NextBlock
);
1110 CGF
.Builder
.restoreIP(SavedIP
);
1113 /// Emit the structure of the dispatch block for the given catch scope.
1114 /// It is an invariant that the dispatch block already exists.
1115 static void emitCatchDispatchBlock(CodeGenFunction
&CGF
,
1116 EHCatchScope
&catchScope
) {
1117 if (EHPersonality::get(CGF
).isWasmPersonality())
1118 return emitWasmCatchPadBlock(CGF
, catchScope
);
1119 if (EHPersonality::get(CGF
).usesFuncletPads())
1120 return emitCatchPadBlock(CGF
, catchScope
);
1122 llvm::BasicBlock
*dispatchBlock
= catchScope
.getCachedEHDispatchBlock();
1123 assert(dispatchBlock
);
1125 // If there's only a single catch-all, getEHDispatchBlock returned
1126 // that catch-all as the dispatch block.
1127 if (catchScope
.getNumHandlers() == 1 &&
1128 catchScope
.getHandler(0).isCatchAll()) {
1129 assert(dispatchBlock
== catchScope
.getHandler(0).Block
);
1133 CGBuilderTy::InsertPoint savedIP
= CGF
.Builder
.saveIP();
1134 CGF
.EmitBlockAfterUses(dispatchBlock
);
1136 // Select the right handler.
1137 llvm::Function
*llvm_eh_typeid_for
=
1138 CGF
.CGM
.getIntrinsic(llvm::Intrinsic::eh_typeid_for
);
1139 llvm::Type
*argTy
= llvm_eh_typeid_for
->getArg(0)->getType();
1140 LangAS globAS
= CGF
.CGM
.GetGlobalVarAddressSpace(nullptr);
1142 // Load the selector value.
1143 llvm::Value
*selector
= CGF
.getSelectorFromSlot();
1145 // Test against each of the exception types we claim to catch.
1146 for (unsigned i
= 0, e
= catchScope
.getNumHandlers(); ; ++i
) {
1147 assert(i
< e
&& "ran off end of handlers!");
1148 const EHCatchScope::Handler
&handler
= catchScope
.getHandler(i
);
1150 llvm::Value
*typeValue
= handler
.Type
.RTTI
;
1151 assert(handler
.Type
.Flags
== 0 &&
1152 "landingpads do not support catch handler flags");
1153 assert(typeValue
&& "fell into catch-all case!");
1154 // With opaque ptrs, only the address space can be a mismatch.
1155 if (typeValue
->getType() != argTy
)
1157 CGF
.getTargetHooks().performAddrSpaceCast(CGF
, typeValue
, globAS
,
1158 LangAS::Default
, argTy
);
1160 // Figure out the next block.
1162 llvm::BasicBlock
*nextBlock
;
1164 // If this is the last handler, we're at the end, and the next
1165 // block is the block for the enclosing EH scope.
1167 nextBlock
= CGF
.getEHDispatchBlock(catchScope
.getEnclosingEHScope());
1170 // If the next handler is a catch-all, we're at the end, and the
1171 // next block is that handler.
1172 } else if (catchScope
.getHandler(i
+1).isCatchAll()) {
1173 nextBlock
= catchScope
.getHandler(i
+1).Block
;
1176 // Otherwise, we're not at the end and we need a new block.
1178 nextBlock
= CGF
.createBasicBlock("catch.fallthrough");
1182 // Figure out the catch type's index in the LSDA's type table.
1183 llvm::CallInst
*typeIndex
=
1184 CGF
.Builder
.CreateCall(llvm_eh_typeid_for
, typeValue
);
1185 typeIndex
->setDoesNotThrow();
1187 llvm::Value
*matchesTypeIndex
=
1188 CGF
.Builder
.CreateICmpEQ(selector
, typeIndex
, "matches");
1189 CGF
.Builder
.CreateCondBr(matchesTypeIndex
, handler
.Block
, nextBlock
);
1191 // If the next handler is a catch-all, we're completely done.
1193 CGF
.Builder
.restoreIP(savedIP
);
1196 // Otherwise we need to emit and continue at that block.
1197 CGF
.EmitBlock(nextBlock
);
1201 void CodeGenFunction::popCatchScope() {
1202 EHCatchScope
&catchScope
= cast
<EHCatchScope
>(*EHStack
.begin());
1203 if (catchScope
.hasEHBranches())
1204 emitCatchDispatchBlock(*this, catchScope
);
1208 void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt
&S
, bool IsFnTryBlock
) {
1209 unsigned NumHandlers
= S
.getNumHandlers();
1210 EHCatchScope
&CatchScope
= cast
<EHCatchScope
>(*EHStack
.begin());
1211 assert(CatchScope
.getNumHandlers() == NumHandlers
);
1212 llvm::BasicBlock
*DispatchBlock
= CatchScope
.getCachedEHDispatchBlock();
1214 // If the catch was not required, bail out now.
1215 if (!CatchScope
.hasEHBranches()) {
1216 CatchScope
.clearHandlerBlocks();
1221 // Emit the structure of the EH dispatch for this catch.
1222 emitCatchDispatchBlock(*this, CatchScope
);
1224 // Copy the handler blocks off before we pop the EH stack. Emitting
1225 // the handlers might scribble on this memory.
1226 SmallVector
<EHCatchScope::Handler
, 8> Handlers(
1227 CatchScope
.begin(), CatchScope
.begin() + NumHandlers
);
1231 // The fall-through block.
1232 llvm::BasicBlock
*ContBB
= createBasicBlock("try.cont");
1234 // We just emitted the body of the try; jump to the continue block.
1235 if (HaveInsertPoint())
1236 Builder
.CreateBr(ContBB
);
1238 // Determine if we need an implicit rethrow for all these catch handlers;
1239 // see the comment below.
1240 bool doImplicitRethrow
= false;
1242 doImplicitRethrow
= isa
<CXXDestructorDecl
>(CurCodeDecl
) ||
1243 isa
<CXXConstructorDecl
>(CurCodeDecl
);
1245 // Wasm uses Windows-style EH instructions, but merges all catch clauses into
1246 // one big catchpad. So we save the old funclet pad here before we traverse
1247 // each catch handler.
1248 SaveAndRestore
RestoreCurrentFuncletPad(CurrentFuncletPad
);
1249 llvm::BasicBlock
*WasmCatchStartBlock
= nullptr;
1250 if (EHPersonality::get(*this).isWasmPersonality()) {
1252 cast
<llvm::CatchSwitchInst
>(DispatchBlock
->getFirstNonPHI());
1253 WasmCatchStartBlock
= CatchSwitch
->hasUnwindDest()
1254 ? CatchSwitch
->getSuccessor(1)
1255 : CatchSwitch
->getSuccessor(0);
1256 auto *CPI
= cast
<llvm::CatchPadInst
>(WasmCatchStartBlock
->getFirstNonPHI());
1257 CurrentFuncletPad
= CPI
;
1260 // Perversely, we emit the handlers backwards precisely because we
1261 // want them to appear in source order. In all of these cases, the
1262 // catch block will have exactly one predecessor, which will be a
1263 // particular block in the catch dispatch. However, in the case of
1264 // a catch-all, one of the dispatch blocks will branch to two
1265 // different handlers, and EmitBlockAfterUses will cause the second
1266 // handler to be moved before the first.
1267 bool HasCatchAll
= false;
1268 for (unsigned I
= NumHandlers
; I
!= 0; --I
) {
1269 HasCatchAll
|= Handlers
[I
- 1].isCatchAll();
1270 llvm::BasicBlock
*CatchBlock
= Handlers
[I
-1].Block
;
1271 EmitBlockAfterUses(CatchBlock
);
1273 // Catch the exception if this isn't a catch-all.
1274 const CXXCatchStmt
*C
= S
.getHandler(I
-1);
1276 // Enter a cleanup scope, including the catch variable and the
1278 RunCleanupsScope
CatchScope(*this);
1280 // Initialize the catch variable and set up the cleanups.
1281 SaveAndRestore
RestoreCurrentFuncletPad(CurrentFuncletPad
);
1282 CGM
.getCXXABI().emitBeginCatch(*this, C
);
1284 // Emit the PGO counter increment.
1285 incrementProfileCounter(C
);
1287 // Perform the body of the catch.
1288 EmitStmt(C
->getHandlerBlock());
1290 // [except.handle]p11:
1291 // The currently handled exception is rethrown if control
1292 // reaches the end of a handler of the function-try-block of a
1293 // constructor or destructor.
1295 // It is important that we only do this on fallthrough and not on
1296 // return. Note that it's illegal to put a return in a
1297 // constructor function-try-block's catch handler (p14), so this
1298 // really only applies to destructors.
1299 if (doImplicitRethrow
&& HaveInsertPoint()) {
1300 CGM
.getCXXABI().emitRethrow(*this, /*isNoReturn*/false);
1301 Builder
.CreateUnreachable();
1302 Builder
.ClearInsertionPoint();
1305 // Fall out through the catch cleanups.
1306 CatchScope
.ForceCleanup();
1308 // Branch out of the try.
1309 if (HaveInsertPoint())
1310 Builder
.CreateBr(ContBB
);
1313 // Because in wasm we merge all catch clauses into one big catchpad, in case
1314 // none of the types in catch handlers matches after we test against each of
1315 // them, we should unwind to the next EH enclosing scope. We generate a call
1316 // to rethrow function here to do that.
1317 if (EHPersonality::get(*this).isWasmPersonality() && !HasCatchAll
) {
1318 assert(WasmCatchStartBlock
);
1319 // Navigate for the "rethrow" block we created in emitWasmCatchPadBlock().
1320 // Wasm uses landingpad-style conditional branches to compare selectors, so
1321 // we follow the false destination for each of the cond branches to reach
1322 // the rethrow block.
1323 llvm::BasicBlock
*RethrowBlock
= WasmCatchStartBlock
;
1324 while (llvm::Instruction
*TI
= RethrowBlock
->getTerminator()) {
1325 auto *BI
= cast
<llvm::BranchInst
>(TI
);
1326 assert(BI
->isConditional());
1327 RethrowBlock
= BI
->getSuccessor(1);
1329 assert(RethrowBlock
!= WasmCatchStartBlock
&& RethrowBlock
->empty());
1330 Builder
.SetInsertPoint(RethrowBlock
);
1331 llvm::Function
*RethrowInCatchFn
=
1332 CGM
.getIntrinsic(llvm::Intrinsic::wasm_rethrow
);
1333 EmitNoreturnRuntimeCallOrInvoke(RethrowInCatchFn
, {});
1337 incrementProfileCounter(&S
);
1341 struct CallEndCatchForFinally final
: EHScopeStack::Cleanup
{
1342 llvm::Value
*ForEHVar
;
1343 llvm::FunctionCallee EndCatchFn
;
1344 CallEndCatchForFinally(llvm::Value
*ForEHVar
,
1345 llvm::FunctionCallee EndCatchFn
)
1346 : ForEHVar(ForEHVar
), EndCatchFn(EndCatchFn
) {}
1348 void Emit(CodeGenFunction
&CGF
, Flags flags
) override
{
1349 llvm::BasicBlock
*EndCatchBB
= CGF
.createBasicBlock("finally.endcatch");
1350 llvm::BasicBlock
*CleanupContBB
=
1351 CGF
.createBasicBlock("finally.cleanup.cont");
1353 llvm::Value
*ShouldEndCatch
=
1354 CGF
.Builder
.CreateFlagLoad(ForEHVar
, "finally.endcatch");
1355 CGF
.Builder
.CreateCondBr(ShouldEndCatch
, EndCatchBB
, CleanupContBB
);
1356 CGF
.EmitBlock(EndCatchBB
);
1357 CGF
.EmitRuntimeCallOrInvoke(EndCatchFn
); // catch-all, so might throw
1358 CGF
.EmitBlock(CleanupContBB
);
1362 struct PerformFinally final
: EHScopeStack::Cleanup
{
1364 llvm::Value
*ForEHVar
;
1365 llvm::FunctionCallee EndCatchFn
;
1366 llvm::FunctionCallee RethrowFn
;
1367 llvm::Value
*SavedExnVar
;
1369 PerformFinally(const Stmt
*Body
, llvm::Value
*ForEHVar
,
1370 llvm::FunctionCallee EndCatchFn
,
1371 llvm::FunctionCallee RethrowFn
, llvm::Value
*SavedExnVar
)
1372 : Body(Body
), ForEHVar(ForEHVar
), EndCatchFn(EndCatchFn
),
1373 RethrowFn(RethrowFn
), SavedExnVar(SavedExnVar
) {}
1375 void Emit(CodeGenFunction
&CGF
, Flags flags
) override
{
1376 // Enter a cleanup to call the end-catch function if one was provided.
1378 CGF
.EHStack
.pushCleanup
<CallEndCatchForFinally
>(NormalAndEHCleanup
,
1379 ForEHVar
, EndCatchFn
);
1381 // Save the current cleanup destination in case there are
1382 // cleanups in the finally block.
1383 llvm::Value
*SavedCleanupDest
=
1384 CGF
.Builder
.CreateLoad(CGF
.getNormalCleanupDestSlot(),
1385 "cleanup.dest.saved");
1387 // Emit the finally block.
1390 // If the end of the finally is reachable, check whether this was
1391 // for EH. If so, rethrow.
1392 if (CGF
.HaveInsertPoint()) {
1393 llvm::BasicBlock
*RethrowBB
= CGF
.createBasicBlock("finally.rethrow");
1394 llvm::BasicBlock
*ContBB
= CGF
.createBasicBlock("finally.cont");
1396 llvm::Value
*ShouldRethrow
=
1397 CGF
.Builder
.CreateFlagLoad(ForEHVar
, "finally.shouldthrow");
1398 CGF
.Builder
.CreateCondBr(ShouldRethrow
, RethrowBB
, ContBB
);
1400 CGF
.EmitBlock(RethrowBB
);
1402 CGF
.EmitRuntimeCallOrInvoke(RethrowFn
,
1403 CGF
.Builder
.CreateAlignedLoad(CGF
.Int8PtrTy
, SavedExnVar
,
1404 CGF
.getPointerAlign()));
1406 CGF
.EmitRuntimeCallOrInvoke(RethrowFn
);
1408 CGF
.Builder
.CreateUnreachable();
1410 CGF
.EmitBlock(ContBB
);
1412 // Restore the cleanup destination.
1413 CGF
.Builder
.CreateStore(SavedCleanupDest
,
1414 CGF
.getNormalCleanupDestSlot());
1417 // Leave the end-catch cleanup. As an optimization, pretend that
1418 // the fallthrough path was inaccessible; we've dynamically proven
1419 // that we're not in the EH case along that path.
1421 CGBuilderTy::InsertPoint SavedIP
= CGF
.Builder
.saveAndClearIP();
1422 CGF
.PopCleanupBlock();
1423 CGF
.Builder
.restoreIP(SavedIP
);
1426 // Now make sure we actually have an insertion point or the
1427 // cleanup gods will hate us.
1428 CGF
.EnsureInsertPoint();
1431 } // end anonymous namespace
1433 /// Enters a finally block for an implementation using zero-cost
1434 /// exceptions. This is mostly general, but hard-codes some
1435 /// language/ABI-specific behavior in the catch-all sections.
1436 void CodeGenFunction::FinallyInfo::enter(CodeGenFunction
&CGF
, const Stmt
*body
,
1437 llvm::FunctionCallee beginCatchFn
,
1438 llvm::FunctionCallee endCatchFn
,
1439 llvm::FunctionCallee rethrowFn
) {
1440 assert((!!beginCatchFn
) == (!!endCatchFn
) &&
1441 "begin/end catch functions not paired");
1442 assert(rethrowFn
&& "rethrow function is required");
1444 BeginCatchFn
= beginCatchFn
;
1446 // The rethrow function has one of the following two types:
1449 // In the latter case we need to pass it the exception object.
1450 // But we can't use the exception slot because the @finally might
1451 // have a landing pad (which would overwrite the exception slot).
1452 llvm::FunctionType
*rethrowFnTy
= rethrowFn
.getFunctionType();
1453 SavedExnVar
= nullptr;
1454 if (rethrowFnTy
->getNumParams())
1455 SavedExnVar
= CGF
.CreateTempAlloca(CGF
.Int8PtrTy
, "finally.exn");
1457 // A finally block is a statement which must be executed on any edge
1458 // out of a given scope. Unlike a cleanup, the finally block may
1459 // contain arbitrary control flow leading out of itself. In
1460 // addition, finally blocks should always be executed, even if there
1461 // are no catch handlers higher on the stack. Therefore, we
1462 // surround the protected scope with a combination of a normal
1463 // cleanup (to catch attempts to break out of the block via normal
1464 // control flow) and an EH catch-all (semantically "outside" any try
1465 // statement to which the finally block might have been attached).
1466 // The finally block itself is generated in the context of a cleanup
1467 // which conditionally leaves the catch-all.
1469 // Jump destination for performing the finally block on an exception
1470 // edge. We'll never actually reach this block, so unreachable is
1472 RethrowDest
= CGF
.getJumpDestInCurrentScope(CGF
.getUnreachableBlock());
1474 // Whether the finally block is being executed for EH purposes.
1475 ForEHVar
= CGF
.CreateTempAlloca(CGF
.Builder
.getInt1Ty(), "finally.for-eh");
1476 CGF
.Builder
.CreateFlagStore(false, ForEHVar
);
1478 // Enter a normal cleanup which will perform the @finally block.
1479 CGF
.EHStack
.pushCleanup
<PerformFinally
>(NormalCleanup
, body
,
1480 ForEHVar
, endCatchFn
,
1481 rethrowFn
, SavedExnVar
);
1483 // Enter a catch-all scope.
1484 llvm::BasicBlock
*catchBB
= CGF
.createBasicBlock("finally.catchall");
1485 EHCatchScope
*catchScope
= CGF
.EHStack
.pushCatch(1);
1486 catchScope
->setCatchAllHandler(0, catchBB
);
1489 void CodeGenFunction::FinallyInfo::exit(CodeGenFunction
&CGF
) {
1490 // Leave the finally catch-all.
1491 EHCatchScope
&catchScope
= cast
<EHCatchScope
>(*CGF
.EHStack
.begin());
1492 llvm::BasicBlock
*catchBB
= catchScope
.getHandler(0).Block
;
1494 CGF
.popCatchScope();
1496 // If there are any references to the catch-all block, emit it.
1497 if (catchBB
->use_empty()) {
1500 CGBuilderTy::InsertPoint savedIP
= CGF
.Builder
.saveAndClearIP();
1501 CGF
.EmitBlock(catchBB
);
1503 llvm::Value
*exn
= nullptr;
1505 // If there's a begin-catch function, call it.
1507 exn
= CGF
.getExceptionFromSlot();
1508 CGF
.EmitNounwindRuntimeCall(BeginCatchFn
, exn
);
1511 // If we need to remember the exception pointer to rethrow later, do so.
1513 if (!exn
) exn
= CGF
.getExceptionFromSlot();
1514 CGF
.Builder
.CreateAlignedStore(exn
, SavedExnVar
, CGF
.getPointerAlign());
1517 // Tell the cleanups in the finally block that we're do this for EH.
1518 CGF
.Builder
.CreateFlagStore(true, ForEHVar
);
1520 // Thread a jump through the finally cleanup.
1521 CGF
.EmitBranchThroughCleanup(RethrowDest
);
1523 CGF
.Builder
.restoreIP(savedIP
);
1526 // Finally, leave the @finally cleanup.
1527 CGF
.PopCleanupBlock();
1530 llvm::BasicBlock
*CodeGenFunction::getTerminateLandingPad() {
1531 if (TerminateLandingPad
)
1532 return TerminateLandingPad
;
1534 CGBuilderTy::InsertPoint SavedIP
= Builder
.saveAndClearIP();
1536 // This will get inserted at the end of the function.
1537 TerminateLandingPad
= createBasicBlock("terminate.lpad");
1538 Builder
.SetInsertPoint(TerminateLandingPad
);
1540 // Tell the backend that this is a landing pad.
1541 const EHPersonality
&Personality
= EHPersonality::get(*this);
1543 if (!CurFn
->hasPersonalityFn())
1544 CurFn
->setPersonalityFn(getOpaquePersonalityFn(CGM
, Personality
));
1546 llvm::LandingPadInst
*LPadInst
=
1547 Builder
.CreateLandingPad(llvm::StructType::get(Int8PtrTy
, Int32Ty
), 0);
1548 LPadInst
->addClause(getCatchAllValue(*this));
1550 llvm::Value
*Exn
= nullptr;
1551 if (getLangOpts().CPlusPlus
)
1552 Exn
= Builder
.CreateExtractValue(LPadInst
, 0);
1553 llvm::CallInst
*terminateCall
=
1554 CGM
.getCXXABI().emitTerminateForUnexpectedException(*this, Exn
);
1555 terminateCall
->setDoesNotReturn();
1556 Builder
.CreateUnreachable();
1558 // Restore the saved insertion state.
1559 Builder
.restoreIP(SavedIP
);
1561 return TerminateLandingPad
;
1564 llvm::BasicBlock
*CodeGenFunction::getTerminateHandler() {
1565 if (TerminateHandler
)
1566 return TerminateHandler
;
1568 // Set up the terminate handler. This block is inserted at the very
1569 // end of the function by FinishFunction.
1570 TerminateHandler
= createBasicBlock("terminate.handler");
1571 CGBuilderTy::InsertPoint SavedIP
= Builder
.saveAndClearIP();
1572 Builder
.SetInsertPoint(TerminateHandler
);
1574 llvm::Value
*Exn
= nullptr;
1575 if (getLangOpts().CPlusPlus
)
1576 Exn
= getExceptionFromSlot();
1577 llvm::CallInst
*terminateCall
=
1578 CGM
.getCXXABI().emitTerminateForUnexpectedException(*this, Exn
);
1579 terminateCall
->setDoesNotReturn();
1580 Builder
.CreateUnreachable();
1582 // Restore the saved insertion state.
1583 Builder
.restoreIP(SavedIP
);
1585 return TerminateHandler
;
1588 llvm::BasicBlock
*CodeGenFunction::getTerminateFunclet() {
1589 assert(EHPersonality::get(*this).usesFuncletPads() &&
1590 "use getTerminateLandingPad for non-funclet EH");
1592 llvm::BasicBlock
*&TerminateFunclet
= TerminateFunclets
[CurrentFuncletPad
];
1593 if (TerminateFunclet
)
1594 return TerminateFunclet
;
1596 CGBuilderTy::InsertPoint SavedIP
= Builder
.saveAndClearIP();
1598 // Set up the terminate handler. This block is inserted at the very
1599 // end of the function by FinishFunction.
1600 TerminateFunclet
= createBasicBlock("terminate.handler");
1601 Builder
.SetInsertPoint(TerminateFunclet
);
1603 // Create the cleanuppad using the current parent pad as its token. Use 'none'
1604 // if this is a top-level terminate scope, which is the common case.
1605 SaveAndRestore
RestoreCurrentFuncletPad(CurrentFuncletPad
);
1606 llvm::Value
*ParentPad
= CurrentFuncletPad
;
1608 ParentPad
= llvm::ConstantTokenNone::get(CGM
.getLLVMContext());
1609 CurrentFuncletPad
= Builder
.CreateCleanupPad(ParentPad
);
1611 // Emit the __std_terminate call.
1612 llvm::CallInst
*terminateCall
=
1613 CGM
.getCXXABI().emitTerminateForUnexpectedException(*this, nullptr);
1614 terminateCall
->setDoesNotReturn();
1615 Builder
.CreateUnreachable();
1617 // Restore the saved insertion state.
1618 Builder
.restoreIP(SavedIP
);
1620 return TerminateFunclet
;
1623 llvm::BasicBlock
*CodeGenFunction::getEHResumeBlock(bool isCleanup
) {
1624 if (EHResumeBlock
) return EHResumeBlock
;
1626 CGBuilderTy::InsertPoint SavedIP
= Builder
.saveIP();
1628 // We emit a jump to a notional label at the outermost unwind state.
1629 EHResumeBlock
= createBasicBlock("eh.resume");
1630 Builder
.SetInsertPoint(EHResumeBlock
);
1632 const EHPersonality
&Personality
= EHPersonality::get(*this);
1634 // This can always be a call because we necessarily didn't find
1635 // anything on the EH stack which needs our help.
1636 const char *RethrowName
= Personality
.CatchallRethrowFn
;
1637 if (RethrowName
!= nullptr && !isCleanup
) {
1638 EmitRuntimeCall(getCatchallRethrowFn(CGM
, RethrowName
),
1639 getExceptionFromSlot())->setDoesNotReturn();
1640 Builder
.CreateUnreachable();
1641 Builder
.restoreIP(SavedIP
);
1642 return EHResumeBlock
;
1645 // Recreate the landingpad's return value for the 'resume' instruction.
1646 llvm::Value
*Exn
= getExceptionFromSlot();
1647 llvm::Value
*Sel
= getSelectorFromSlot();
1649 llvm::Type
*LPadType
= llvm::StructType::get(Exn
->getType(), Sel
->getType());
1650 llvm::Value
*LPadVal
= llvm::PoisonValue::get(LPadType
);
1651 LPadVal
= Builder
.CreateInsertValue(LPadVal
, Exn
, 0, "lpad.val");
1652 LPadVal
= Builder
.CreateInsertValue(LPadVal
, Sel
, 1, "lpad.val");
1654 Builder
.CreateResume(LPadVal
);
1655 Builder
.restoreIP(SavedIP
);
1656 return EHResumeBlock
;
1659 void CodeGenFunction::EmitSEHTryStmt(const SEHTryStmt
&S
) {
1662 JumpDest TryExit
= getJumpDestInCurrentScope("__try.__leave");
1664 SEHTryEpilogueStack
.push_back(&TryExit
);
1666 llvm::BasicBlock
*TryBB
= nullptr;
1667 // IsEHa: emit an invoke to _seh_try_begin() runtime for -EHa
1668 if (getLangOpts().EHAsynch
) {
1669 EmitRuntimeCallOrInvoke(getSehTryBeginFn(CGM
));
1670 if (SEHTryEpilogueStack
.size() == 1) // outermost only
1671 TryBB
= Builder
.GetInsertBlock();
1674 EmitStmt(S
.getTryBlock());
1676 // Volatilize all blocks in Try, till current insert point
1678 llvm::SmallPtrSet
<llvm::BasicBlock
*, 10> Visited
;
1679 VolatilizeTryBlocks(TryBB
, Visited
);
1682 SEHTryEpilogueStack
.pop_back();
1684 if (!TryExit
.getBlock()->use_empty())
1685 EmitBlock(TryExit
.getBlock(), /*IsFinished=*/true);
1687 delete TryExit
.getBlock();
1692 // Recursively walk through blocks in a _try
1693 // and make all memory instructions volatile
1694 void CodeGenFunction::VolatilizeTryBlocks(
1695 llvm::BasicBlock
*BB
, llvm::SmallPtrSet
<llvm::BasicBlock
*, 10> &V
) {
1696 if (BB
== SEHTryEpilogueStack
.back()->getBlock() /* end of Try */ ||
1697 !V
.insert(BB
).second
/* already visited */ ||
1698 !BB
->getParent() /* not emitted */ || BB
->empty())
1701 if (!BB
->isEHPad()) {
1702 for (llvm::BasicBlock::iterator J
= BB
->begin(), JE
= BB
->end(); J
!= JE
;
1704 if (auto LI
= dyn_cast
<llvm::LoadInst
>(J
)) {
1705 LI
->setVolatile(true);
1706 } else if (auto SI
= dyn_cast
<llvm::StoreInst
>(J
)) {
1707 SI
->setVolatile(true);
1708 } else if (auto* MCI
= dyn_cast
<llvm::MemIntrinsic
>(J
)) {
1709 MCI
->setVolatile(llvm::ConstantInt::get(Builder
.getInt1Ty(), 1));
1713 const llvm::Instruction
*TI
= BB
->getTerminator();
1715 unsigned N
= TI
->getNumSuccessors();
1716 for (unsigned I
= 0; I
< N
; I
++)
1717 VolatilizeTryBlocks(TI
->getSuccessor(I
), V
);
1722 struct PerformSEHFinally final
: EHScopeStack::Cleanup
{
1723 llvm::Function
*OutlinedFinally
;
1724 PerformSEHFinally(llvm::Function
*OutlinedFinally
)
1725 : OutlinedFinally(OutlinedFinally
) {}
1727 void Emit(CodeGenFunction
&CGF
, Flags F
) override
{
1728 ASTContext
&Context
= CGF
.getContext();
1729 CodeGenModule
&CGM
= CGF
.CGM
;
1733 // Compute the two argument values.
1734 QualType ArgTys
[2] = {Context
.UnsignedCharTy
, Context
.VoidPtrTy
};
1735 llvm::Value
*FP
= nullptr;
1736 // If CFG.IsOutlinedSEHHelper is true, then we are within a finally block.
1737 if (CGF
.IsOutlinedSEHHelper
) {
1738 FP
= &CGF
.CurFn
->arg_begin()[1];
1740 llvm::Function
*LocalAddrFn
=
1741 CGM
.getIntrinsic(llvm::Intrinsic::localaddress
);
1742 FP
= CGF
.Builder
.CreateCall(LocalAddrFn
);
1745 llvm::Value
*IsForEH
=
1746 llvm::ConstantInt::get(CGF
.ConvertType(ArgTys
[0]), F
.isForEHCleanup());
1748 // Except _leave and fall-through at the end, all other exits in a _try
1749 // (return/goto/continue/break) are considered as abnormal terminations
1750 // since _leave/fall-through is always Indexed 0,
1751 // just use NormalCleanupDestSlot (>= 1 for goto/return/..),
1752 // as 1st Arg to indicate abnormal termination
1753 if (!F
.isForEHCleanup() && F
.hasExitSwitch()) {
1754 Address Addr
= CGF
.getNormalCleanupDestSlot();
1755 llvm::Value
*Load
= CGF
.Builder
.CreateLoad(Addr
, "cleanup.dest");
1756 llvm::Value
*Zero
= llvm::Constant::getNullValue(CGM
.Int32Ty
);
1757 IsForEH
= CGF
.Builder
.CreateICmpNE(Load
, Zero
);
1760 Args
.add(RValue::get(IsForEH
), ArgTys
[0]);
1761 Args
.add(RValue::get(FP
), ArgTys
[1]);
1763 // Arrange a two-arg function info and type.
1764 const CGFunctionInfo
&FnInfo
=
1765 CGM
.getTypes().arrangeBuiltinFunctionCall(Context
.VoidTy
, Args
);
1767 auto Callee
= CGCallee::forDirect(OutlinedFinally
);
1768 CGF
.EmitCall(FnInfo
, Callee
, ReturnValueSlot(), Args
);
1771 } // end anonymous namespace
1774 /// Find all local variable captures in the statement.
1775 struct CaptureFinder
: ConstStmtVisitor
<CaptureFinder
> {
1776 CodeGenFunction
&ParentCGF
;
1777 const VarDecl
*ParentThis
;
1778 llvm::SmallSetVector
<const VarDecl
*, 4> Captures
;
1779 Address SEHCodeSlot
= Address::invalid();
1780 CaptureFinder(CodeGenFunction
&ParentCGF
, const VarDecl
*ParentThis
)
1781 : ParentCGF(ParentCGF
), ParentThis(ParentThis
) {}
1783 // Return true if we need to do any capturing work.
1784 bool foundCaptures() {
1785 return !Captures
.empty() || SEHCodeSlot
.isValid();
1788 void Visit(const Stmt
*S
) {
1789 // See if this is a capture, then recurse.
1790 ConstStmtVisitor
<CaptureFinder
>::Visit(S
);
1791 for (const Stmt
*Child
: S
->children())
1796 void VisitDeclRefExpr(const DeclRefExpr
*E
) {
1797 // If this is already a capture, just make sure we capture 'this'.
1798 if (E
->refersToEnclosingVariableOrCapture())
1799 Captures
.insert(ParentThis
);
1801 const auto *D
= dyn_cast
<VarDecl
>(E
->getDecl());
1802 if (D
&& D
->isLocalVarDeclOrParm() && D
->hasLocalStorage())
1806 void VisitCXXThisExpr(const CXXThisExpr
*E
) {
1807 Captures
.insert(ParentThis
);
1810 void VisitCallExpr(const CallExpr
*E
) {
1811 // We only need to add parent frame allocations for these builtins in x86.
1812 if (ParentCGF
.getTarget().getTriple().getArch() != llvm::Triple::x86
)
1815 unsigned ID
= E
->getBuiltinCallee();
1817 case Builtin::BI__exception_code
:
1818 case Builtin::BI_exception_code
:
1819 // This is the simple case where we are the outermost finally. All we
1820 // have to do here is make sure we escape this and recover it in the
1821 // outlined handler.
1822 if (!SEHCodeSlot
.isValid())
1823 SEHCodeSlot
= ParentCGF
.SEHCodeSlotStack
.back();
1828 } // end anonymous namespace
1830 Address
CodeGenFunction::recoverAddrOfEscapedLocal(CodeGenFunction
&ParentCGF
,
1832 llvm::Value
*ParentFP
) {
1833 llvm::CallInst
*RecoverCall
= nullptr;
1834 CGBuilderTy
Builder(*this, AllocaInsertPt
);
1835 if (auto *ParentAlloca
= dyn_cast
<llvm::AllocaInst
>(ParentVar
.getPointer())) {
1836 // Mark the variable escaped if nobody else referenced it and compute the
1837 // localescape index.
1838 auto InsertPair
= ParentCGF
.EscapedLocals
.insert(
1839 std::make_pair(ParentAlloca
, ParentCGF
.EscapedLocals
.size()));
1840 int FrameEscapeIdx
= InsertPair
.first
->second
;
1841 // call i8* @llvm.localrecover(i8* bitcast(@parentFn), i8* %fp, i32 N)
1842 llvm::Function
*FrameRecoverFn
= llvm::Intrinsic::getDeclaration(
1843 &CGM
.getModule(), llvm::Intrinsic::localrecover
);
1844 llvm::Constant
*ParentI8Fn
=
1845 llvm::ConstantExpr::getBitCast(ParentCGF
.CurFn
, Int8PtrTy
);
1846 RecoverCall
= Builder
.CreateCall(
1847 FrameRecoverFn
, {ParentI8Fn
, ParentFP
,
1848 llvm::ConstantInt::get(Int32Ty
, FrameEscapeIdx
)});
1851 // If the parent didn't have an alloca, we're doing some nested outlining.
1852 // Just clone the existing localrecover call, but tweak the FP argument to
1853 // use our FP value. All other arguments are constants.
1854 auto *ParentRecover
=
1855 cast
<llvm::IntrinsicInst
>(ParentVar
.getPointer()->stripPointerCasts());
1856 assert(ParentRecover
->getIntrinsicID() == llvm::Intrinsic::localrecover
&&
1857 "expected alloca or localrecover in parent LocalDeclMap");
1858 RecoverCall
= cast
<llvm::CallInst
>(ParentRecover
->clone());
1859 RecoverCall
->setArgOperand(1, ParentFP
);
1860 RecoverCall
->insertBefore(AllocaInsertPt
);
1863 // Bitcast the variable, rename it, and insert it in the local decl map.
1864 llvm::Value
*ChildVar
=
1865 Builder
.CreateBitCast(RecoverCall
, ParentVar
.getType());
1866 ChildVar
->setName(ParentVar
.getName());
1867 return ParentVar
.withPointer(ChildVar
, KnownNonNull
);
1870 void CodeGenFunction::EmitCapturedLocals(CodeGenFunction
&ParentCGF
,
1871 const Stmt
*OutlinedStmt
,
1873 // Find all captures in the Stmt.
1874 CaptureFinder
Finder(ParentCGF
, ParentCGF
.CXXABIThisDecl
);
1875 Finder
.Visit(OutlinedStmt
);
1877 // We can exit early on x86_64 when there are no captures. We just have to
1878 // save the exception code in filters so that __exception_code() works.
1879 if (!Finder
.foundCaptures() &&
1880 CGM
.getTarget().getTriple().getArch() != llvm::Triple::x86
) {
1882 EmitSEHExceptionCodeSave(ParentCGF
, nullptr, nullptr);
1886 llvm::Value
*EntryFP
= nullptr;
1887 CGBuilderTy
Builder(CGM
, AllocaInsertPt
);
1888 if (IsFilter
&& CGM
.getTarget().getTriple().getArch() == llvm::Triple::x86
) {
1889 // 32-bit SEH filters need to be careful about FP recovery. The end of the
1890 // EH registration is passed in as the EBP physical register. We can
1891 // recover that with llvm.frameaddress(1).
1892 EntryFP
= Builder
.CreateCall(
1893 CGM
.getIntrinsic(llvm::Intrinsic::frameaddress
, AllocaInt8PtrTy
),
1894 {Builder
.getInt32(1)});
1896 // Otherwise, for x64 and 32-bit finally functions, the parent FP is the
1897 // second parameter.
1898 auto AI
= CurFn
->arg_begin();
1903 llvm::Value
*ParentFP
= EntryFP
;
1905 // Given whatever FP the runtime provided us in EntryFP, recover the true
1906 // frame pointer of the parent function. We only need to do this in filters,
1907 // since finally funclets recover the parent FP for us.
1908 llvm::Function
*RecoverFPIntrin
=
1909 CGM
.getIntrinsic(llvm::Intrinsic::eh_recoverfp
);
1910 llvm::Constant
*ParentI8Fn
=
1911 llvm::ConstantExpr::getBitCast(ParentCGF
.CurFn
, Int8PtrTy
);
1912 ParentFP
= Builder
.CreateCall(RecoverFPIntrin
, {ParentI8Fn
, EntryFP
});
1914 // if the parent is a _finally, the passed-in ParentFP is the FP
1915 // of parent _finally, not Establisher's FP (FP of outermost function).
1916 // Establkisher FP is 2nd paramenter passed into parent _finally.
1917 // Fortunately, it's always saved in parent's frame. The following
1918 // code retrieves it, and escapes it so that spill instruction won't be
1920 if (ParentCGF
.ParentCGF
!= nullptr) {
1921 // Locate and escape Parent's frame_pointer.addr alloca
1922 // Depending on target, should be 1st/2nd one in LocalDeclMap.
1923 // Let's just scan for ImplicitParamDecl with VoidPtrTy.
1924 llvm::AllocaInst
*FramePtrAddrAlloca
= nullptr;
1925 for (auto &I
: ParentCGF
.LocalDeclMap
) {
1926 const VarDecl
*D
= cast
<VarDecl
>(I
.first
);
1927 if (isa
<ImplicitParamDecl
>(D
) &&
1928 D
->getType() == getContext().VoidPtrTy
) {
1929 assert(D
->getName().startswith("frame_pointer"));
1930 FramePtrAddrAlloca
= cast
<llvm::AllocaInst
>(I
.second
.getPointer());
1934 assert(FramePtrAddrAlloca
);
1935 auto InsertPair
= ParentCGF
.EscapedLocals
.insert(
1936 std::make_pair(FramePtrAddrAlloca
, ParentCGF
.EscapedLocals
.size()));
1937 int FrameEscapeIdx
= InsertPair
.first
->second
;
1939 // an example of a filter's prolog::
1940 // %0 = call i8* @llvm.eh.recoverfp(bitcast(@"?fin$0@0@main@@"),..)
1941 // %1 = call i8* @llvm.localrecover(bitcast(@"?fin$0@0@main@@"),..)
1942 // %2 = bitcast i8* %1 to i8**
1943 // %3 = load i8*, i8* *%2, align 8
1944 // ==> %3 is the frame-pointer of outermost host function
1945 llvm::Function
*FrameRecoverFn
= llvm::Intrinsic::getDeclaration(
1946 &CGM
.getModule(), llvm::Intrinsic::localrecover
);
1947 llvm::Constant
*ParentI8Fn
=
1948 llvm::ConstantExpr::getBitCast(ParentCGF
.CurFn
, Int8PtrTy
);
1949 ParentFP
= Builder
.CreateCall(
1950 FrameRecoverFn
, {ParentI8Fn
, ParentFP
,
1951 llvm::ConstantInt::get(Int32Ty
, FrameEscapeIdx
)});
1952 ParentFP
= Builder
.CreateBitCast(ParentFP
, CGM
.VoidPtrPtrTy
);
1953 ParentFP
= Builder
.CreateLoad(
1954 Address(ParentFP
, CGM
.VoidPtrTy
, getPointerAlign()));
1958 // Create llvm.localrecover calls for all captures.
1959 for (const VarDecl
*VD
: Finder
.Captures
) {
1960 if (VD
->getType()->isVariablyModifiedType()) {
1961 CGM
.ErrorUnsupported(VD
, "VLA captured by SEH");
1964 assert((isa
<ImplicitParamDecl
>(VD
) || VD
->isLocalVarDeclOrParm()) &&
1965 "captured non-local variable");
1967 auto L
= ParentCGF
.LambdaCaptureFields
.find(VD
);
1968 if (L
!= ParentCGF
.LambdaCaptureFields
.end()) {
1969 LambdaCaptureFields
[VD
] = L
->second
;
1973 // If this decl hasn't been declared yet, it will be declared in the
1975 auto I
= ParentCGF
.LocalDeclMap
.find(VD
);
1976 if (I
== ParentCGF
.LocalDeclMap
.end())
1979 Address ParentVar
= I
->second
;
1981 recoverAddrOfEscapedLocal(ParentCGF
, ParentVar
, ParentFP
);
1982 setAddrOfLocalVar(VD
, Recovered
);
1984 if (isa
<ImplicitParamDecl
>(VD
)) {
1985 CXXABIThisAlignment
= ParentCGF
.CXXABIThisAlignment
;
1986 CXXThisAlignment
= ParentCGF
.CXXThisAlignment
;
1987 CXXABIThisValue
= Builder
.CreateLoad(Recovered
, "this");
1988 if (ParentCGF
.LambdaThisCaptureField
) {
1989 LambdaThisCaptureField
= ParentCGF
.LambdaThisCaptureField
;
1990 // We are in a lambda function where "this" is captured so the
1991 // CXXThisValue need to be loaded from the lambda capture
1992 LValue ThisFieldLValue
=
1993 EmitLValueForLambdaField(LambdaThisCaptureField
);
1994 if (!LambdaThisCaptureField
->getType()->isPointerType()) {
1995 CXXThisValue
= ThisFieldLValue
.getAddress(*this).getPointer();
1997 CXXThisValue
= EmitLoadOfLValue(ThisFieldLValue
, SourceLocation())
2001 CXXThisValue
= CXXABIThisValue
;
2006 if (Finder
.SEHCodeSlot
.isValid()) {
2007 SEHCodeSlotStack
.push_back(
2008 recoverAddrOfEscapedLocal(ParentCGF
, Finder
.SEHCodeSlot
, ParentFP
));
2012 EmitSEHExceptionCodeSave(ParentCGF
, ParentFP
, EntryFP
);
2015 /// Arrange a function prototype that can be called by Windows exception
2016 /// handling personalities. On Win64, the prototype looks like:
2017 /// RetTy func(void *EHPtrs, void *ParentFP);
2018 void CodeGenFunction::startOutlinedSEHHelper(CodeGenFunction
&ParentCGF
,
2020 const Stmt
*OutlinedStmt
) {
2021 SourceLocation StartLoc
= OutlinedStmt
->getBeginLoc();
2023 // Get the mangled function name.
2024 SmallString
<128> Name
;
2026 llvm::raw_svector_ostream
OS(Name
);
2027 GlobalDecl ParentSEHFn
= ParentCGF
.CurSEHParent
;
2028 assert(ParentSEHFn
&& "No CurSEHParent!");
2029 MangleContext
&Mangler
= CGM
.getCXXABI().getMangleContext();
2031 Mangler
.mangleSEHFilterExpression(ParentSEHFn
, OS
);
2033 Mangler
.mangleSEHFinallyBlock(ParentSEHFn
, OS
);
2036 FunctionArgList Args
;
2037 if (CGM
.getTarget().getTriple().getArch() != llvm::Triple::x86
|| !IsFilter
) {
2038 // All SEH finally functions take two parameters. Win64 filters take two
2039 // parameters. Win32 filters take no parameters.
2041 Args
.push_back(ImplicitParamDecl::Create(
2042 getContext(), /*DC=*/nullptr, StartLoc
,
2043 &getContext().Idents
.get("exception_pointers"),
2044 getContext().VoidPtrTy
, ImplicitParamDecl::Other
));
2046 Args
.push_back(ImplicitParamDecl::Create(
2047 getContext(), /*DC=*/nullptr, StartLoc
,
2048 &getContext().Idents
.get("abnormal_termination"),
2049 getContext().UnsignedCharTy
, ImplicitParamDecl::Other
));
2051 Args
.push_back(ImplicitParamDecl::Create(
2052 getContext(), /*DC=*/nullptr, StartLoc
,
2053 &getContext().Idents
.get("frame_pointer"), getContext().VoidPtrTy
,
2054 ImplicitParamDecl::Other
));
2057 QualType RetTy
= IsFilter
? getContext().LongTy
: getContext().VoidTy
;
2059 const CGFunctionInfo
&FnInfo
=
2060 CGM
.getTypes().arrangeBuiltinFunctionDeclaration(RetTy
, Args
);
2062 llvm::FunctionType
*FnTy
= CGM
.getTypes().GetFunctionType(FnInfo
);
2063 llvm::Function
*Fn
= llvm::Function::Create(
2064 FnTy
, llvm::GlobalValue::InternalLinkage
, Name
.str(), &CGM
.getModule());
2066 IsOutlinedSEHHelper
= true;
2068 StartFunction(GlobalDecl(), RetTy
, Fn
, FnInfo
, Args
,
2069 OutlinedStmt
->getBeginLoc(), OutlinedStmt
->getBeginLoc());
2070 CurSEHParent
= ParentCGF
.CurSEHParent
;
2072 CGM
.SetInternalFunctionAttributes(GlobalDecl(), CurFn
, FnInfo
);
2073 EmitCapturedLocals(ParentCGF
, OutlinedStmt
, IsFilter
);
2076 /// Create a stub filter function that will ultimately hold the code of the
2077 /// filter expression. The EH preparation passes in LLVM will outline the code
2078 /// from the main function body into this stub.
2080 CodeGenFunction::GenerateSEHFilterFunction(CodeGenFunction
&ParentCGF
,
2081 const SEHExceptStmt
&Except
) {
2082 const Expr
*FilterExpr
= Except
.getFilterExpr();
2083 startOutlinedSEHHelper(ParentCGF
, true, FilterExpr
);
2085 // Emit the original filter expression, convert to i32, and return.
2086 llvm::Value
*R
= EmitScalarExpr(FilterExpr
);
2087 R
= Builder
.CreateIntCast(R
, ConvertType(getContext().LongTy
),
2088 FilterExpr
->getType()->isSignedIntegerType());
2089 Builder
.CreateStore(R
, ReturnValue
);
2091 FinishFunction(FilterExpr
->getEndLoc());
2097 CodeGenFunction::GenerateSEHFinallyFunction(CodeGenFunction
&ParentCGF
,
2098 const SEHFinallyStmt
&Finally
) {
2099 const Stmt
*FinallyBlock
= Finally
.getBlock();
2100 startOutlinedSEHHelper(ParentCGF
, false, FinallyBlock
);
2102 // Emit the original filter expression, convert to i32, and return.
2103 EmitStmt(FinallyBlock
);
2105 FinishFunction(FinallyBlock
->getEndLoc());
2110 void CodeGenFunction::EmitSEHExceptionCodeSave(CodeGenFunction
&ParentCGF
,
2111 llvm::Value
*ParentFP
,
2112 llvm::Value
*EntryFP
) {
2113 // Get the pointer to the EXCEPTION_POINTERS struct. This is returned by the
2114 // __exception_info intrinsic.
2115 if (CGM
.getTarget().getTriple().getArch() != llvm::Triple::x86
) {
2116 // On Win64, the info is passed as the first parameter to the filter.
2117 SEHInfo
= &*CurFn
->arg_begin();
2118 SEHCodeSlotStack
.push_back(
2119 CreateMemTemp(getContext().IntTy
, "__exception_code"));
2121 // On Win32, the EBP on entry to the filter points to the end of an
2122 // exception registration object. It contains 6 32-bit fields, and the info
2123 // pointer is stored in the second field. So, GEP 20 bytes backwards and
2124 // load the pointer.
2125 SEHInfo
= Builder
.CreateConstInBoundsGEP1_32(Int8Ty
, EntryFP
, -20);
2126 SEHInfo
= Builder
.CreateAlignedLoad(Int8PtrTy
, SEHInfo
, getPointerAlign());
2127 SEHCodeSlotStack
.push_back(recoverAddrOfEscapedLocal(
2128 ParentCGF
, ParentCGF
.SEHCodeSlotStack
.back(), ParentFP
));
2131 // Save the exception code in the exception slot to unify exception access in
2132 // the filter function and the landing pad.
2133 // struct EXCEPTION_POINTERS {
2134 // EXCEPTION_RECORD *ExceptionRecord;
2135 // CONTEXT *ContextRecord;
2137 // int exceptioncode = exception_pointers->ExceptionRecord->ExceptionCode;
2138 llvm::Type
*RecordTy
= llvm::PointerType::getUnqual(getLLVMContext());
2139 llvm::Type
*PtrsTy
= llvm::StructType::get(RecordTy
, CGM
.VoidPtrTy
);
2140 llvm::Value
*Rec
= Builder
.CreateStructGEP(PtrsTy
, SEHInfo
, 0);
2141 Rec
= Builder
.CreateAlignedLoad(RecordTy
, Rec
, getPointerAlign());
2142 llvm::Value
*Code
= Builder
.CreateAlignedLoad(Int32Ty
, Rec
, getIntAlign());
2143 assert(!SEHCodeSlotStack
.empty() && "emitting EH code outside of __except");
2144 Builder
.CreateStore(Code
, SEHCodeSlotStack
.back());
2147 llvm::Value
*CodeGenFunction::EmitSEHExceptionInfo() {
2148 // Sema should diagnose calling this builtin outside of a filter context, but
2149 // don't crash if we screw up.
2151 return llvm::UndefValue::get(Int8PtrTy
);
2152 assert(SEHInfo
->getType() == Int8PtrTy
);
2156 llvm::Value
*CodeGenFunction::EmitSEHExceptionCode() {
2157 assert(!SEHCodeSlotStack
.empty() && "emitting EH code outside of __except");
2158 return Builder
.CreateLoad(SEHCodeSlotStack
.back());
2161 llvm::Value
*CodeGenFunction::EmitSEHAbnormalTermination() {
2162 // Abnormal termination is just the first parameter to the outlined finally
2164 auto AI
= CurFn
->arg_begin();
2165 return Builder
.CreateZExt(&*AI
, Int32Ty
);
2168 void CodeGenFunction::pushSEHCleanup(CleanupKind Kind
,
2169 llvm::Function
*FinallyFunc
) {
2170 EHStack
.pushCleanup
<PerformSEHFinally
>(Kind
, FinallyFunc
);
2173 void CodeGenFunction::EnterSEHTryStmt(const SEHTryStmt
&S
) {
2174 CodeGenFunction
HelperCGF(CGM
, /*suppressNewContext=*/true);
2175 HelperCGF
.ParentCGF
= this;
2176 if (const SEHFinallyStmt
*Finally
= S
.getFinallyHandler()) {
2177 // Outline the finally block.
2178 llvm::Function
*FinallyFunc
=
2179 HelperCGF
.GenerateSEHFinallyFunction(*this, *Finally
);
2181 // Push a cleanup for __finally blocks.
2182 EHStack
.pushCleanup
<PerformSEHFinally
>(NormalAndEHCleanup
, FinallyFunc
);
2186 // Otherwise, we must have an __except block.
2187 const SEHExceptStmt
*Except
= S
.getExceptHandler();
2189 EHCatchScope
*CatchScope
= EHStack
.pushCatch(1);
2190 SEHCodeSlotStack
.push_back(
2191 CreateMemTemp(getContext().IntTy
, "__exception_code"));
2193 // If the filter is known to evaluate to 1, then we can use the clause
2194 // "catch i8* null". We can't do this on x86 because the filter has to save
2195 // the exception code.
2197 ConstantEmitter(*this).tryEmitAbstract(Except
->getFilterExpr(),
2198 getContext().IntTy
);
2199 if (CGM
.getTarget().getTriple().getArch() != llvm::Triple::x86
&& C
&&
2201 CatchScope
->setCatchAllHandler(0, createBasicBlock("__except"));
2205 // In general, we have to emit an outlined filter function. Use the function
2206 // in place of the RTTI typeinfo global that C++ EH uses.
2207 llvm::Function
*FilterFunc
=
2208 HelperCGF
.GenerateSEHFilterFunction(*this, *Except
);
2209 llvm::Constant
*OpaqueFunc
=
2210 llvm::ConstantExpr::getBitCast(FilterFunc
, Int8PtrTy
);
2211 CatchScope
->setHandler(0, OpaqueFunc
, createBasicBlock("__except.ret"));
2214 void CodeGenFunction::ExitSEHTryStmt(const SEHTryStmt
&S
) {
2215 // Just pop the cleanup if it's a __finally block.
2216 if (S
.getFinallyHandler()) {
2221 // IsEHa: emit an invoke _seh_try_end() to mark end of FT flow
2222 if (getLangOpts().EHAsynch
&& Builder
.GetInsertBlock()) {
2223 llvm::FunctionCallee SehTryEnd
= getSehTryEndFn(CGM
);
2224 EmitRuntimeCallOrInvoke(SehTryEnd
);
2227 // Otherwise, we must have an __except block.
2228 const SEHExceptStmt
*Except
= S
.getExceptHandler();
2229 assert(Except
&& "__try must have __finally xor __except");
2230 EHCatchScope
&CatchScope
= cast
<EHCatchScope
>(*EHStack
.begin());
2232 // Don't emit the __except block if the __try block lacked invokes.
2233 // TODO: Model unwind edges from instructions, either with iload / istore or
2234 // a try body function.
2235 if (!CatchScope
.hasEHBranches()) {
2236 CatchScope
.clearHandlerBlocks();
2238 SEHCodeSlotStack
.pop_back();
2242 // The fall-through block.
2243 llvm::BasicBlock
*ContBB
= createBasicBlock("__try.cont");
2245 // We just emitted the body of the __try; jump to the continue block.
2246 if (HaveInsertPoint())
2247 Builder
.CreateBr(ContBB
);
2249 // Check if our filter function returned true.
2250 emitCatchDispatchBlock(*this, CatchScope
);
2252 // Grab the block before we pop the handler.
2253 llvm::BasicBlock
*CatchPadBB
= CatchScope
.getHandler(0).Block
;
2256 EmitBlockAfterUses(CatchPadBB
);
2258 // __except blocks don't get outlined into funclets, so immediately do a
2260 llvm::CatchPadInst
*CPI
=
2261 cast
<llvm::CatchPadInst
>(CatchPadBB
->getFirstNonPHI());
2262 llvm::BasicBlock
*ExceptBB
= createBasicBlock("__except");
2263 Builder
.CreateCatchRet(CPI
, ExceptBB
);
2264 EmitBlock(ExceptBB
);
2266 // On Win64, the exception code is returned in EAX. Copy it into the slot.
2267 if (CGM
.getTarget().getTriple().getArch() != llvm::Triple::x86
) {
2268 llvm::Function
*SEHCodeIntrin
=
2269 CGM
.getIntrinsic(llvm::Intrinsic::eh_exceptioncode
);
2270 llvm::Value
*Code
= Builder
.CreateCall(SEHCodeIntrin
, {CPI
});
2271 Builder
.CreateStore(Code
, SEHCodeSlotStack
.back());
2274 // Emit the __except body.
2275 EmitStmt(Except
->getBlock());
2277 // End the lifetime of the exception code.
2278 SEHCodeSlotStack
.pop_back();
2280 if (HaveInsertPoint())
2281 Builder
.CreateBr(ContBB
);
2286 void CodeGenFunction::EmitSEHLeaveStmt(const SEHLeaveStmt
&S
) {
2287 // If this code is reachable then emit a stop point (if generating
2288 // debug info). We have to do this ourselves because we are on the
2289 // "simple" statement path.
2290 if (HaveInsertPoint())
2293 // This must be a __leave from a __finally block, which we warn on and is UB.
2294 // Just emit unreachable.
2295 if (!isSEHTryScope()) {
2296 Builder
.CreateUnreachable();
2297 Builder
.ClearInsertionPoint();
2301 EmitBranchThroughCleanup(*SEHTryEpilogueStack
.back());