blob: 53fafab3e0e6835f3cff5ef29d7785dc508c0d95 [file] [log] [blame]
Hans Wennborgdcfba332015-10-06 23:40:43 +00001//===--- CGException.cpp - Emit LLVM Code for C++ exceptions ----*- C++ -*-===//
Anders Carlsson4b08db72009-10-30 01:42:31 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Anders Carlsson4b08db72009-10-30 01:42:31 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This contains code dealing with C++ exception related code generation.
10//
11//===----------------------------------------------------------------------===//
12
David Majnemer442d0a22014-11-25 07:20:20 +000013#include "CGCXXABI.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000014#include "CGCleanup.h"
Benjamin Kramer793bd552012-02-08 12:41:24 +000015#include "CGObjCRuntime.h"
Reid Kleckner5d986952019-12-11 07:55:26 -080016#include "CodeGenFunction.h"
John McCallde0fe072017-08-15 21:42:52 +000017#include "ConstantEmitter.h"
John McCall5add20c2010-07-20 22:17:55 +000018#include "TargetInfo.h"
Reid Kleckner1d59f992015-01-22 01:36:17 +000019#include "clang/AST/Mangle.h"
Benjamin Kramer793bd552012-02-08 12:41:24 +000020#include "clang/AST/StmtCXX.h"
Chandler Carruth4b417452013-01-19 08:09:44 +000021#include "clang/AST/StmtObjC.h"
Reid Kleckner31a1bb02015-04-08 22:23:48 +000022#include "clang/AST/StmtVisitor.h"
Reid Kleckner9fe7f232015-07-07 00:36:30 +000023#include "clang/Basic/TargetBuiltins.h"
Reid Kleckner31a1bb02015-04-08 22:23:48 +000024#include "llvm/IR/IntrinsicInst.h"
Reid Kleckner5d986952019-12-11 07:55:26 -080025#include "llvm/IR/Intrinsics.h"
26#include "llvm/IR/IntrinsicsWebAssembly.h"
Reid Klecknerebaf28d2015-04-14 20:59:00 +000027#include "llvm/Support/SaveAndRestore.h"
John McCallbd309292010-07-06 01:34:17 +000028
Anders Carlsson4b08db72009-10-30 01:42:31 +000029using namespace clang;
30using namespace CodeGen;
31
James Y Knight9871db02019-02-05 16:42:33 +000032static llvm::FunctionCallee getFreeExceptionFn(CodeGenModule &CGM) {
Mike Stump33270212009-12-02 07:41:41 +000033 // void __cxa_free_exception(void *thrown_exception);
Mike Stump75546b82009-12-10 00:06:18 +000034
Chris Lattner2192fe52011-07-18 04:24:23 +000035 llvm::FunctionType *FTy =
Rui Ueyama49a3ad22019-07-16 04:46:31 +000036 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*isVarArg=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000037
John McCall2c33ba82013-02-12 03:51:38 +000038 return CGM.CreateRuntimeFunction(FTy, "__cxa_free_exception");
Mike Stump33270212009-12-02 07:41:41 +000039}
40
James Y Knight9871db02019-02-05 16:42:33 +000041static llvm::FunctionCallee getUnexpectedFn(CodeGenModule &CGM) {
Richard Smith2f7aa192013-06-20 23:03:35 +000042 // void __cxa_call_unexpected(void *thrown_exception);
Mike Stump1d849212009-12-07 23:38:24 +000043
Chris Lattner2192fe52011-07-18 04:24:23 +000044 llvm::FunctionType *FTy =
Rui Ueyama49a3ad22019-07-16 04:46:31 +000045 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*isVarArg=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000046
John McCall2c33ba82013-02-12 03:51:38 +000047 return CGM.CreateRuntimeFunction(FTy, "__cxa_call_unexpected");
Mike Stump1d849212009-12-07 23:38:24 +000048}
49
James Y Knight9871db02019-02-05 16:42:33 +000050llvm::FunctionCallee CodeGenModule::getTerminateFn() {
Mike Stump33270212009-12-02 07:41:41 +000051 // void __terminate();
52
Chris Lattner2192fe52011-07-18 04:24:23 +000053 llvm::FunctionType *FTy =
Rui Ueyama49a3ad22019-07-16 04:46:31 +000054 llvm::FunctionType::get(VoidTy, /*isVarArg=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000055
Chris Lattner0e62c1c2011-07-23 10:55:15 +000056 StringRef name;
John McCall9de19782011-07-06 01:22:26 +000057
58 // In C++, use std::terminate().
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000059 if (getLangOpts().CPlusPlus &&
60 getTarget().getCXXABI().isItaniumFamily()) {
Reid Kleckner1d59f992015-01-22 01:36:17 +000061 name = "_ZSt9terminatev";
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000062 } else if (getLangOpts().CPlusPlus &&
63 getTarget().getCXXABI().isMicrosoft()) {
David Majnemerb710a932015-05-11 03:57:49 +000064 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
David Majnemerfb6ffca2015-05-10 21:38:26 +000065 name = "__std_terminate";
66 else
Reid Klecknerfb931542018-03-16 20:36:49 +000067 name = "?terminate@@YAXXZ";
Erik Pilkingtonfa983902018-10-30 20:31:30 +000068 } else if (getLangOpts().ObjC &&
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000069 getLangOpts().ObjCRuntime.hasTerminate())
John McCall9de19782011-07-06 01:22:26 +000070 name = "objc_terminate";
71 else
72 name = "abort";
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000073 return CreateRuntimeFunction(FTy, name);
David Chisnallf9c42252010-05-17 13:49:20 +000074}
75
James Y Knight9871db02019-02-05 16:42:33 +000076static llvm::FunctionCallee getCatchallRethrowFn(CodeGenModule &CGM,
77 StringRef Name) {
Chris Lattner2192fe52011-07-18 04:24:23 +000078 llvm::FunctionType *FTy =
Rui Ueyama49a3ad22019-07-16 04:46:31 +000079 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*isVarArg=*/false);
John McCall36ea3722010-07-17 00:43:08 +000080
John McCall2c33ba82013-02-12 03:51:38 +000081 return CGM.CreateRuntimeFunction(FTy, Name);
John McCallbd309292010-07-06 01:34:17 +000082}
83
Craig Topper8a13c412014-05-21 05:09:00 +000084const EHPersonality EHPersonality::GNU_C = { "__gcc_personality_v0", nullptr };
Benjamin Kramer793bd552012-02-08 12:41:24 +000085const EHPersonality
Craig Topper8a13c412014-05-21 05:09:00 +000086EHPersonality::GNU_C_SJLJ = { "__gcc_personality_sj0", nullptr };
87const EHPersonality
Reid Kleckner8f45c9c2014-09-15 17:19:16 +000088EHPersonality::GNU_C_SEH = { "__gcc_personality_seh0", nullptr };
89const EHPersonality
Craig Topper8a13c412014-05-21 05:09:00 +000090EHPersonality::NeXT_ObjC = { "__objc_personality_v0", nullptr };
91const EHPersonality
92EHPersonality::GNU_CPlusPlus = { "__gxx_personality_v0", nullptr };
93const EHPersonality
94EHPersonality::GNU_CPlusPlus_SJLJ = { "__gxx_personality_sj0", nullptr };
Benjamin Kramer793bd552012-02-08 12:41:24 +000095const EHPersonality
Reid Kleckner8f45c9c2014-09-15 17:19:16 +000096EHPersonality::GNU_CPlusPlus_SEH = { "__gxx_personality_seh0", nullptr };
97const EHPersonality
Benjamin Kramer793bd552012-02-08 12:41:24 +000098EHPersonality::GNU_ObjC = {"__gnu_objc_personality_v0", "objc_exception_throw"};
99const EHPersonality
Benjamin Kramer796c1d92017-01-08 22:58:07 +0000100EHPersonality::GNU_ObjC_SJLJ = {"__gnu_objc_personality_sj0", "objc_exception_throw"};
101const EHPersonality
102EHPersonality::GNU_ObjC_SEH = {"__gnu_objc_personality_seh0", "objc_exception_throw"};
103const EHPersonality
Craig Topper8a13c412014-05-21 05:09:00 +0000104EHPersonality::GNU_ObjCXX = { "__gnustep_objcxx_personality_v0", nullptr };
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000105const EHPersonality
Craig Topper8a13c412014-05-21 05:09:00 +0000106EHPersonality::GNUstep_ObjC = { "__gnustep_objc_personality_v0", nullptr };
Reid Kleckner1d59f992015-01-22 01:36:17 +0000107const EHPersonality
108EHPersonality::MSVC_except_handler = { "_except_handler3", nullptr };
109const EHPersonality
110EHPersonality::MSVC_C_specific_handler = { "__C_specific_handler", nullptr };
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000111const EHPersonality
112EHPersonality::MSVC_CxxFrameHandler3 = { "__CxxFrameHandler3", nullptr };
Heejin Ahnc6479192018-05-31 22:18:13 +0000113const EHPersonality
114EHPersonality::GNU_Wasm_CPlusPlus = { "__gxx_wasm_personality_v0", nullptr };
John McCall36ea3722010-07-17 00:43:08 +0000115
Heejin Ahn00831792018-06-04 18:23:00 +0000116static const EHPersonality &getCPersonality(const TargetInfo &Target,
Reid Klecknere070b992014-11-14 02:01:10 +0000117 const LangOptions &L) {
Heejin Ahn00831792018-06-04 18:23:00 +0000118 const llvm::Triple &T = Target.getTriple();
Shoaib Meenaia5fc6032018-06-08 00:41:01 +0000119 if (T.isWindowsMSVCEnvironment())
120 return EHPersonality::MSVC_CxxFrameHandler3;
John McCall2faab302010-11-07 02:35:25 +0000121 if (L.SjLjExceptions)
122 return EHPersonality::GNU_C_SJLJ;
Saleem Abdulrasool3e701322018-03-09 07:06:42 +0000123 if (L.DWARFExceptions)
124 return EHPersonality::GNU_C;
Martell Malonec950c652017-11-29 07:25:12 +0000125 if (L.SEHExceptions)
Reid Kleckner8f45c9c2014-09-15 17:19:16 +0000126 return EHPersonality::GNU_C_SEH;
John McCall36ea3722010-07-17 00:43:08 +0000127 return EHPersonality::GNU_C;
128}
129
Heejin Ahn00831792018-06-04 18:23:00 +0000130static const EHPersonality &getObjCPersonality(const TargetInfo &Target,
Reid Klecknere070b992014-11-14 02:01:10 +0000131 const LangOptions &L) {
Heejin Ahn00831792018-06-04 18:23:00 +0000132 const llvm::Triple &T = Target.getTriple();
Shoaib Meenaia5fc6032018-06-08 00:41:01 +0000133 if (T.isWindowsMSVCEnvironment())
134 return EHPersonality::MSVC_CxxFrameHandler3;
135
John McCall5fb5df92012-06-20 06:18:46 +0000136 switch (L.ObjCRuntime.getKind()) {
137 case ObjCRuntime::FragileMacOSX:
Heejin Ahn00831792018-06-04 18:23:00 +0000138 return getCPersonality(Target, L);
John McCall5fb5df92012-06-20 06:18:46 +0000139 case ObjCRuntime::MacOSX:
140 case ObjCRuntime::iOS:
Tim Northover756447a2015-10-30 16:30:36 +0000141 case ObjCRuntime::WatchOS:
John McCall5fb5df92012-06-20 06:18:46 +0000142 return EHPersonality::NeXT_ObjC;
David Chisnallb601c962012-07-03 20:49:52 +0000143 case ObjCRuntime::GNUstep:
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000144 if (L.ObjCRuntime.getVersion() >= VersionTuple(1, 7))
145 return EHPersonality::GNUstep_ObjC;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +0000146 LLVM_FALLTHROUGH;
David Chisnallb601c962012-07-03 20:49:52 +0000147 case ObjCRuntime::GCC:
John McCall775086e2012-07-12 02:07:58 +0000148 case ObjCRuntime::ObjFW:
Benjamin Kramer796c1d92017-01-08 22:58:07 +0000149 if (L.SjLjExceptions)
150 return EHPersonality::GNU_ObjC_SJLJ;
Martell Malonec950c652017-11-29 07:25:12 +0000151 if (L.SEHExceptions)
Benjamin Kramer796c1d92017-01-08 22:58:07 +0000152 return EHPersonality::GNU_ObjC_SEH;
John McCall36ea3722010-07-17 00:43:08 +0000153 return EHPersonality::GNU_ObjC;
John McCallbd309292010-07-06 01:34:17 +0000154 }
John McCall5fb5df92012-06-20 06:18:46 +0000155 llvm_unreachable("bad runtime kind");
John McCallbd309292010-07-06 01:34:17 +0000156}
157
Heejin Ahn00831792018-06-04 18:23:00 +0000158static const EHPersonality &getCXXPersonality(const TargetInfo &Target,
159 const LangOptions &L) {
160 const llvm::Triple &T = Target.getTriple();
Shoaib Meenaia5fc6032018-06-08 00:41:01 +0000161 if (T.isWindowsMSVCEnvironment())
162 return EHPersonality::MSVC_CxxFrameHandler3;
John McCall36ea3722010-07-17 00:43:08 +0000163 if (L.SjLjExceptions)
164 return EHPersonality::GNU_CPlusPlus_SJLJ;
Saleem Abdulrasool3e701322018-03-09 07:06:42 +0000165 if (L.DWARFExceptions)
166 return EHPersonality::GNU_CPlusPlus;
Martell Malonec950c652017-11-29 07:25:12 +0000167 if (L.SEHExceptions)
Reid Kleckner8f45c9c2014-09-15 17:19:16 +0000168 return EHPersonality::GNU_CPlusPlus_SEH;
Heejin Ahne8b2b882019-09-12 04:01:37 +0000169 if (L.WasmExceptions)
Heejin Ahnc6479192018-05-31 22:18:13 +0000170 return EHPersonality::GNU_Wasm_CPlusPlus;
Reid Klecknere070b992014-11-14 02:01:10 +0000171 return EHPersonality::GNU_CPlusPlus;
John McCallbd309292010-07-06 01:34:17 +0000172}
173
174/// Determines the personality function to use when both C++
175/// and Objective-C exceptions are being caught.
Heejin Ahn00831792018-06-04 18:23:00 +0000176static const EHPersonality &getObjCXXPersonality(const TargetInfo &Target,
177 const LangOptions &L) {
Shoaib Meenaia5fc6032018-06-08 00:41:01 +0000178 if (Target.getTriple().isWindowsMSVCEnvironment())
179 return EHPersonality::MSVC_CxxFrameHandler3;
180
John McCall5fb5df92012-06-20 06:18:46 +0000181 switch (L.ObjCRuntime.getKind()) {
Saleem Abdulrasool8f6d9442017-11-02 00:25:40 +0000182 // In the fragile ABI, just use C++ exception handling and hope
183 // they're not doing crazy exception mixing.
184 case ObjCRuntime::FragileMacOSX:
Heejin Ahn00831792018-06-04 18:23:00 +0000185 return getCXXPersonality(Target, L);
Saleem Abdulrasool8f6d9442017-11-02 00:25:40 +0000186
John McCallbd309292010-07-06 01:34:17 +0000187 // The ObjC personality defers to the C++ personality for non-ObjC
188 // handlers. Unlike the C++ case, we use the same personality
189 // function on targets using (backend-driven) SJLJ EH.
John McCall5fb5df92012-06-20 06:18:46 +0000190 case ObjCRuntime::MacOSX:
191 case ObjCRuntime::iOS:
Tim Northover756447a2015-10-30 16:30:36 +0000192 case ObjCRuntime::WatchOS:
Heejin Ahn00831792018-06-04 18:23:00 +0000193 return getObjCPersonality(Target, L);
John McCallbd309292010-07-06 01:34:17 +0000194
Saleem Abdulrasool8f6d9442017-11-02 00:25:40 +0000195 case ObjCRuntime::GNUstep:
196 return EHPersonality::GNU_ObjCXX;
David Chisnallf9c42252010-05-17 13:49:20 +0000197
David Chisnallb601c962012-07-03 20:49:52 +0000198 // The GCC runtime's personality function inherently doesn't support
Saleem Abdulrasool8f6d9442017-11-02 00:25:40 +0000199 // mixed EH. Use the ObjC personality just to avoid returning null.
David Chisnallb601c962012-07-03 20:49:52 +0000200 case ObjCRuntime::GCC:
Benjamin Kramer9851cb72017-04-01 17:59:01 +0000201 case ObjCRuntime::ObjFW:
Heejin Ahn00831792018-06-04 18:23:00 +0000202 return getObjCPersonality(Target, L);
John McCall5fb5df92012-06-20 06:18:46 +0000203 }
204 llvm_unreachable("bad runtime kind");
John McCallbd309292010-07-06 01:34:17 +0000205}
206
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000207static const EHPersonality &getSEHPersonalityMSVC(const llvm::Triple &T) {
Reid Kleckner1d59f992015-01-22 01:36:17 +0000208 if (T.getArch() == llvm::Triple::x86)
209 return EHPersonality::MSVC_except_handler;
210 return EHPersonality::MSVC_C_specific_handler;
211}
212
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000213const EHPersonality &EHPersonality::get(CodeGenModule &CGM,
214 const FunctionDecl *FD) {
Reid Klecknere070b992014-11-14 02:01:10 +0000215 const llvm::Triple &T = CGM.getTarget().getTriple();
216 const LangOptions &L = CGM.getLangOpts();
Heejin Ahn1eb074d2018-06-01 01:01:37 +0000217 const TargetInfo &Target = CGM.getTarget();
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000218
Reid Kleckner01485652015-09-17 17:04:13 +0000219 // Functions using SEH get an SEH personality.
220 if (FD && FD->usesSEHTry())
221 return getSEHPersonalityMSVC(T);
222
Erik Pilkingtonfa983902018-10-30 20:31:30 +0000223 if (L.ObjC)
Heejin Ahn00831792018-06-04 18:23:00 +0000224 return L.CPlusPlus ? getObjCXXPersonality(Target, L)
225 : getObjCPersonality(Target, L);
226 return L.CPlusPlus ? getCXXPersonality(Target, L)
227 : getCPersonality(Target, L);
John McCall36ea3722010-07-17 00:43:08 +0000228}
John McCallbd309292010-07-06 01:34:17 +0000229
David Majnemerc28d46e2015-07-22 23:46:21 +0000230const EHPersonality &EHPersonality::get(CodeGenFunction &CGF) {
Reid Kleckner65fa8692017-10-13 16:55:14 +0000231 const auto *FD = CGF.CurCodeDecl;
232 // For outlined finallys and filters, use the SEH personality in case they
233 // contain more SEH. This mostly only affects finallys. Filters could
234 // hypothetically use gnu statement expressions to sneak in nested SEH.
235 FD = FD ? FD : CGF.CurSEHParent;
236 return get(CGF.CGM, dyn_cast_or_null<FunctionDecl>(FD));
David Majnemerc28d46e2015-07-22 23:46:21 +0000237}
238
James Y Knight9871db02019-02-05 16:42:33 +0000239static llvm::FunctionCallee getPersonalityFn(CodeGenModule &CGM,
240 const EHPersonality &Personality) {
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +0000241 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.Int32Ty, true),
242 Personality.PersonalityFn,
Reid Klecknerde864822017-03-21 16:57:30 +0000243 llvm::AttributeList(), /*Local=*/true);
John McCall0bdb1fd2010-09-16 06:16:50 +0000244}
245
246static llvm::Constant *getOpaquePersonalityFn(CodeGenModule &CGM,
247 const EHPersonality &Personality) {
James Y Knight9871db02019-02-05 16:42:33 +0000248 llvm::FunctionCallee Fn = getPersonalityFn(CGM, Personality);
Dylan McKay02bbe412018-11-09 19:42:05 +0000249 llvm::PointerType* Int8PtrTy = llvm::PointerType::get(
250 llvm::Type::getInt8Ty(CGM.getLLVMContext()),
251 CGM.getDataLayout().getProgramAddressSpace());
252
James Y Knight9871db02019-02-05 16:42:33 +0000253 return llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(Fn.getCallee()),
254 Int8PtrTy);
John McCall0bdb1fd2010-09-16 06:16:50 +0000255}
256
Vedant Kumardb609472015-09-11 15:40:05 +0000257/// Check whether a landingpad instruction only uses C++ features.
258static bool LandingPadHasOnlyCXXUses(llvm::LandingPadInst *LPI) {
259 for (unsigned I = 0, E = LPI->getNumClauses(); I != E; ++I) {
260 // Look for something that would've been returned by the ObjC
261 // runtime's GetEHType() method.
262 llvm::Value *Val = LPI->getClause(I)->stripPointerCasts();
263 if (LPI->isCatch(I)) {
264 // Check if the catch value has the ObjC prefix.
265 if (llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Val))
266 // ObjC EH selector entries are always global variables with
267 // names starting like this.
268 if (GV->getName().startswith("OBJC_EHTYPE"))
269 return false;
270 } else {
271 // Check if any of the filter values have the ObjC prefix.
272 llvm::Constant *CVal = cast<llvm::Constant>(Val);
273 for (llvm::User::op_iterator
274 II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II) {
275 if (llvm::GlobalVariable *GV =
276 cast<llvm::GlobalVariable>((*II)->stripPointerCasts()))
277 // ObjC EH selector entries are always global variables with
278 // names starting like this.
279 if (GV->getName().startswith("OBJC_EHTYPE"))
280 return false;
281 }
282 }
283 }
284 return true;
285}
286
John McCall0bdb1fd2010-09-16 06:16:50 +0000287/// Check whether a personality function could reasonably be swapped
288/// for a C++ personality function.
289static bool PersonalityHasOnlyCXXUses(llvm::Constant *Fn) {
Chandler Carruth4d01fff2014-03-09 03:16:50 +0000290 for (llvm::User *U : Fn->users()) {
John McCall0bdb1fd2010-09-16 06:16:50 +0000291 // Conditionally white-list bitcasts.
Chandler Carruth4d01fff2014-03-09 03:16:50 +0000292 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(U)) {
John McCall0bdb1fd2010-09-16 06:16:50 +0000293 if (CE->getOpcode() != llvm::Instruction::BitCast) return false;
294 if (!PersonalityHasOnlyCXXUses(CE))
295 return false;
296 continue;
297 }
298
Vedant Kumardb609472015-09-11 15:40:05 +0000299 // Otherwise it must be a function.
300 llvm::Function *F = dyn_cast<llvm::Function>(U);
301 if (!F) return false;
John McCall0bdb1fd2010-09-16 06:16:50 +0000302
Vedant Kumardb609472015-09-11 15:40:05 +0000303 for (auto BB = F->begin(), E = F->end(); BB != E; ++BB) {
304 if (BB->isLandingPad())
305 if (!LandingPadHasOnlyCXXUses(BB->getLandingPadInst()))
306 return false;
John McCall0bdb1fd2010-09-16 06:16:50 +0000307 }
308 }
309
310 return true;
311}
312
313/// Try to use the C++ personality function in ObjC++. Not doing this
314/// can cause some incompatibilities with gcc, which is more
315/// aggressive about only using the ObjC++ personality in a function
316/// when it really needs it.
317void CodeGenModule::SimplifyPersonality() {
John McCall0bdb1fd2010-09-16 06:16:50 +0000318 // If we're not in ObjC++ -fexceptions, there's nothing to do.
Erik Pilkingtonfa983902018-10-30 20:31:30 +0000319 if (!LangOpts.CPlusPlus || !LangOpts.ObjC || !LangOpts.Exceptions)
John McCall0bdb1fd2010-09-16 06:16:50 +0000320 return;
321
John McCall3c223932012-11-14 17:48:31 +0000322 // Both the problem this endeavors to fix and the way the logic
323 // above works is specific to the NeXT runtime.
324 if (!LangOpts.ObjCRuntime.isNeXTFamily())
325 return;
326
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000327 const EHPersonality &ObjCXX = EHPersonality::get(*this, /*FD=*/nullptr);
Heejin Ahn00831792018-06-04 18:23:00 +0000328 const EHPersonality &CXX = getCXXPersonality(getTarget(), LangOpts);
Benjamin Kramer793bd552012-02-08 12:41:24 +0000329 if (&ObjCXX == &CXX)
John McCall0bdb1fd2010-09-16 06:16:50 +0000330 return;
331
Benjamin Kramer793bd552012-02-08 12:41:24 +0000332 assert(std::strcmp(ObjCXX.PersonalityFn, CXX.PersonalityFn) != 0 &&
333 "Different EHPersonalities using the same personality function.");
334
335 llvm::Function *Fn = getModule().getFunction(ObjCXX.PersonalityFn);
John McCall0bdb1fd2010-09-16 06:16:50 +0000336
337 // Nothing to do if it's unused.
338 if (!Fn || Fn->use_empty()) return;
Fangrui Song6907ce22018-07-30 19:24:48 +0000339
John McCall0bdb1fd2010-09-16 06:16:50 +0000340 // Can't do the optimization if it has non-C++ uses.
341 if (!PersonalityHasOnlyCXXUses(Fn)) return;
342
343 // Create the C++ personality function and kill off the old
344 // function.
James Y Knight9871db02019-02-05 16:42:33 +0000345 llvm::FunctionCallee CXXFn = getPersonalityFn(*this, CXX);
John McCall0bdb1fd2010-09-16 06:16:50 +0000346
347 // This can happen if the user is screwing with us.
James Y Knight9871db02019-02-05 16:42:33 +0000348 if (Fn->getType() != CXXFn.getCallee()->getType())
349 return;
John McCall0bdb1fd2010-09-16 06:16:50 +0000350
James Y Knight9871db02019-02-05 16:42:33 +0000351 Fn->replaceAllUsesWith(CXXFn.getCallee());
John McCall0bdb1fd2010-09-16 06:16:50 +0000352 Fn->eraseFromParent();
John McCallbd309292010-07-06 01:34:17 +0000353}
354
355/// Returns the value to inject into a selector to indicate the
356/// presence of a catch-all.
357static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
358 // Possibly we should use @llvm.eh.catch.all.value here.
John McCallad7c5c12011-02-08 08:22:06 +0000359 return llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
John McCallbd309292010-07-06 01:34:17 +0000360}
361
John McCallbb026012010-07-13 21:17:51 +0000362namespace {
363 /// A cleanup to free the exception object if its initialization
364 /// throws.
David Blaikie7e70d682015-08-18 22:40:54 +0000365 struct FreeException final : EHScopeStack::Cleanup {
John McCall5fcf8da2011-07-12 00:15:30 +0000366 llvm::Value *exn;
367 FreeException(llvm::Value *exn) : exn(exn) {}
Craig Topper4f12f102014-03-12 06:41:41 +0000368 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +0000369 CGF.EmitNounwindRuntimeCall(getFreeExceptionFn(CGF.CGM), exn);
John McCallbb026012010-07-13 21:17:51 +0000370 }
371 };
Hans Wennborgdcfba332015-10-06 23:40:43 +0000372} // end anonymous namespace
John McCallbb026012010-07-13 21:17:51 +0000373
John McCall2e6567a2010-04-22 01:10:34 +0000374// Emits an exception expression into the given location. This
375// differs from EmitAnyExprToMem only in that, if a final copy-ctor
376// call is required, an exception within that copy ctor causes
377// std::terminate to be invoked.
John McCall7f416cc2015-09-08 08:05:57 +0000378void CodeGenFunction::EmitAnyExprToExn(const Expr *e, Address addr) {
John McCallbd309292010-07-06 01:34:17 +0000379 // Make sure the exception object is cleaned up if there's an
380 // exception during initialization.
John McCall7f416cc2015-09-08 08:05:57 +0000381 pushFullExprCleanup<FreeException>(EHCleanup, addr.getPointer());
David Majnemer7c237072015-03-05 00:46:22 +0000382 EHScopeStack::stable_iterator cleanup = EHStack.stable_begin();
John McCall2e6567a2010-04-22 01:10:34 +0000383
384 // __cxa_allocate_exception returns a void*; we need to cast this
385 // to the appropriate type for the object.
David Majnemer7c237072015-03-05 00:46:22 +0000386 llvm::Type *ty = ConvertTypeForMem(e->getType())->getPointerTo();
John McCall7f416cc2015-09-08 08:05:57 +0000387 Address typedAddr = Builder.CreateBitCast(addr, ty);
John McCall2e6567a2010-04-22 01:10:34 +0000388
389 // FIXME: this isn't quite right! If there's a final unelided call
390 // to a copy constructor, then according to [except.terminate]p1 we
391 // must call std::terminate() if that constructor throws, because
392 // technically that copy occurs after the exception expression is
393 // evaluated but before the exception is caught. But the best way
394 // to handle that is to teach EmitAggExpr to do the final copy
395 // differently if it can't be elided.
David Majnemer7c237072015-03-05 00:46:22 +0000396 EmitAnyExprToMem(e, typedAddr, e->getType().getQualifiers(),
397 /*IsInit*/ true);
John McCall2e6567a2010-04-22 01:10:34 +0000398
John McCalle4df6c82011-01-28 08:37:24 +0000399 // Deactivate the cleanup block.
John McCall7f416cc2015-09-08 08:05:57 +0000400 DeactivateCleanupBlock(cleanup,
401 cast<llvm::Instruction>(typedAddr.getPointer()));
Mike Stump54066142009-12-01 03:41:18 +0000402}
403
John McCall7f416cc2015-09-08 08:05:57 +0000404Address CodeGenFunction::getExceptionSlot() {
John McCall9b382dd2011-05-28 21:13:02 +0000405 if (!ExceptionSlot)
406 ExceptionSlot = CreateTempAlloca(Int8PtrTy, "exn.slot");
John McCall7f416cc2015-09-08 08:05:57 +0000407 return Address(ExceptionSlot, getPointerAlign());
Mike Stump54066142009-12-01 03:41:18 +0000408}
409
John McCall7f416cc2015-09-08 08:05:57 +0000410Address CodeGenFunction::getEHSelectorSlot() {
John McCall9b382dd2011-05-28 21:13:02 +0000411 if (!EHSelectorSlot)
412 EHSelectorSlot = CreateTempAlloca(Int32Ty, "ehselector.slot");
John McCall7f416cc2015-09-08 08:05:57 +0000413 return Address(EHSelectorSlot, CharUnits::fromQuantity(4));
John McCall9b382dd2011-05-28 21:13:02 +0000414}
415
Bill Wendling79a70e42011-09-15 18:57:19 +0000416llvm::Value *CodeGenFunction::getExceptionFromSlot() {
417 return Builder.CreateLoad(getExceptionSlot(), "exn");
418}
419
420llvm::Value *CodeGenFunction::getSelectorFromSlot() {
421 return Builder.CreateLoad(getEHSelectorSlot(), "sel");
422}
423
Richard Smithea852322013-05-07 21:53:22 +0000424void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E,
425 bool KeepInsertionPoint) {
David Majnemer7c237072015-03-05 00:46:22 +0000426 if (const Expr *SubExpr = E->getSubExpr()) {
427 QualType ThrowType = SubExpr->getType();
428 if (ThrowType->isObjCObjectPointerType()) {
429 const Stmt *ThrowStmt = E->getSubExpr();
430 const ObjCAtThrowStmt S(E->getExprLoc(), const_cast<Stmt *>(ThrowStmt));
431 CGM.getObjCRuntime().EmitThrowStmt(*this, S, false);
432 } else {
433 CGM.getCXXABI().emitThrow(*this, E);
John McCall2e6567a2010-04-22 01:10:34 +0000434 }
David Majnemer7c237072015-03-05 00:46:22 +0000435 } else {
436 CGM.getCXXABI().emitRethrow(*this, /*isNoReturn=*/true);
John McCall2e6567a2010-04-22 01:10:34 +0000437 }
Mike Stump75546b82009-12-10 00:06:18 +0000438
John McCall20f6ab82011-01-12 03:41:02 +0000439 // throw is an expression, and the expression emitters expect us
440 // to leave ourselves at a valid insertion point.
Richard Smithea852322013-05-07 21:53:22 +0000441 if (KeepInsertionPoint)
442 EmitBlock(createBasicBlock("throw.cont"));
Anders Carlsson4b08db72009-10-30 01:42:31 +0000443}
Mike Stump58ef18b2009-11-20 23:44:51 +0000444
Mike Stump1d849212009-12-07 23:38:24 +0000445void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000446 if (!CGM.getLangOpts().CXXExceptions)
Anders Carlsson9878f9f2010-02-06 23:59:05 +0000447 return;
Fangrui Song6907ce22018-07-30 19:24:48 +0000448
Mike Stump1d849212009-12-07 23:38:24 +0000449 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
Craig Topper8a13c412014-05-21 05:09:00 +0000450 if (!FD) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000451 // Check if CapturedDecl is nothrow and create terminate scope for it.
452 if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
453 if (CD->isNothrow())
454 EHStack.pushTerminate();
455 }
Mike Stump1d849212009-12-07 23:38:24 +0000456 return;
Alexey Bataev9959db52014-05-06 10:08:46 +0000457 }
Mike Stump1d849212009-12-07 23:38:24 +0000458 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
Craig Topper8a13c412014-05-21 05:09:00 +0000459 if (!Proto)
Mike Stump1d849212009-12-07 23:38:24 +0000460 return;
461
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000462 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
Richard Smitheaf11ad2018-05-03 03:58:32 +0000463 if (isNoexceptExceptionSpec(EST) && Proto->canThrow() == CT_Cannot) {
464 // noexcept functions are simple terminate scopes.
465 EHStack.pushTerminate();
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000466 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
David Majnemer1f192e22015-04-01 04:45:52 +0000467 // TODO: Revisit exception specifications for the MS ABI. There is a way to
468 // encode these in an object file but MSVC doesn't do anything with it.
469 if (getTarget().getCXXABI().isMicrosoft())
470 return;
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000471 unsigned NumExceptions = Proto->getNumExceptions();
472 EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
Mike Stump1d849212009-12-07 23:38:24 +0000473
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000474 for (unsigned I = 0; I != NumExceptions; ++I) {
475 QualType Ty = Proto->getExceptionType(I);
476 QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
477 llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType,
478 /*ForEH=*/true);
479 Filter->setFilter(I, EHType);
480 }
Mike Stump1d849212009-12-07 23:38:24 +0000481 }
Mike Stump1d849212009-12-07 23:38:24 +0000482}
483
John McCall8e4c74b2011-08-11 02:22:43 +0000484/// Emit the dispatch block for a filter scope if necessary.
485static void emitFilterDispatchBlock(CodeGenFunction &CGF,
486 EHFilterScope &filterScope) {
487 llvm::BasicBlock *dispatchBlock = filterScope.getCachedEHDispatchBlock();
488 if (!dispatchBlock) return;
489 if (dispatchBlock->use_empty()) {
490 delete dispatchBlock;
491 return;
492 }
493
John McCall8e4c74b2011-08-11 02:22:43 +0000494 CGF.EmitBlockAfterUses(dispatchBlock);
495
496 // If this isn't a catch-all filter, we need to check whether we got
497 // here because the filter triggered.
498 if (filterScope.getNumFilters()) {
499 // Load the selector value.
Bill Wendling79a70e42011-09-15 18:57:19 +0000500 llvm::Value *selector = CGF.getSelectorFromSlot();
John McCall8e4c74b2011-08-11 02:22:43 +0000501 llvm::BasicBlock *unexpectedBB = CGF.createBasicBlock("ehspec.unexpected");
502
503 llvm::Value *zero = CGF.Builder.getInt32(0);
504 llvm::Value *failsFilter =
Nico Weber1bebad12015-02-11 22:33:32 +0000505 CGF.Builder.CreateICmpSLT(selector, zero, "ehspec.fails");
506 CGF.Builder.CreateCondBr(failsFilter, unexpectedBB,
507 CGF.getEHResumeBlock(false));
John McCall8e4c74b2011-08-11 02:22:43 +0000508
509 CGF.EmitBlock(unexpectedBB);
510 }
511
512 // Call __cxa_call_unexpected. This doesn't need to be an invoke
513 // because __cxa_call_unexpected magically filters exceptions
514 // according to the last landing pad the exception was thrown
515 // into. Seriously.
Bill Wendling79a70e42011-09-15 18:57:19 +0000516 llvm::Value *exn = CGF.getExceptionFromSlot();
John McCall882987f2013-02-28 19:01:20 +0000517 CGF.EmitRuntimeCall(getUnexpectedFn(CGF.CGM), exn)
John McCall8e4c74b2011-08-11 02:22:43 +0000518 ->setDoesNotReturn();
519 CGF.Builder.CreateUnreachable();
520}
521
Mike Stump1d849212009-12-07 23:38:24 +0000522void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000523 if (!CGM.getLangOpts().CXXExceptions)
Anders Carlsson9878f9f2010-02-06 23:59:05 +0000524 return;
Fangrui Song6907ce22018-07-30 19:24:48 +0000525
Mike Stump1d849212009-12-07 23:38:24 +0000526 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
Craig Topper8a13c412014-05-21 05:09:00 +0000527 if (!FD) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000528 // Check if CapturedDecl is nothrow and pop terminate scope for it.
529 if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
530 if (CD->isNothrow())
531 EHStack.popTerminate();
532 }
Mike Stump1d849212009-12-07 23:38:24 +0000533 return;
Alexey Bataev9959db52014-05-06 10:08:46 +0000534 }
Mike Stump1d849212009-12-07 23:38:24 +0000535 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
Craig Topper8a13c412014-05-21 05:09:00 +0000536 if (!Proto)
Mike Stump1d849212009-12-07 23:38:24 +0000537 return;
538
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000539 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
Richard Smitheaf11ad2018-05-03 03:58:32 +0000540 if (isNoexceptExceptionSpec(EST) && Proto->canThrow() == CT_Cannot) {
541 EHStack.popTerminate();
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000542 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
David Majnemer1f192e22015-04-01 04:45:52 +0000543 // TODO: Revisit exception specifications for the MS ABI. There is a way to
544 // encode these in an object file but MSVC doesn't do anything with it.
545 if (getTarget().getCXXABI().isMicrosoft())
546 return;
John McCall8e4c74b2011-08-11 02:22:43 +0000547 EHFilterScope &filterScope = cast<EHFilterScope>(*EHStack.begin());
548 emitFilterDispatchBlock(*this, filterScope);
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000549 EHStack.popFilter();
550 }
Mike Stump1d849212009-12-07 23:38:24 +0000551}
552
Mike Stump58ef18b2009-11-20 23:44:51 +0000553void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
John McCallb609d3f2010-07-07 06:56:46 +0000554 EnterCXXTryStmt(S);
John McCallb81884d2010-02-19 09:25:03 +0000555 EmitStmt(S.getTryBlock());
John McCallb609d3f2010-07-07 06:56:46 +0000556 ExitCXXTryStmt(S);
John McCallb81884d2010-02-19 09:25:03 +0000557}
558
John McCallb609d3f2010-07-07 06:56:46 +0000559void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallbd309292010-07-06 01:34:17 +0000560 unsigned NumHandlers = S.getNumHandlers();
561 EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
John McCallb81884d2010-02-19 09:25:03 +0000562
John McCallbd309292010-07-06 01:34:17 +0000563 for (unsigned I = 0; I != NumHandlers; ++I) {
564 const CXXCatchStmt *C = S.getHandler(I);
John McCallb81884d2010-02-19 09:25:03 +0000565
John McCallbd309292010-07-06 01:34:17 +0000566 llvm::BasicBlock *Handler = createBasicBlock("catch");
567 if (C->getExceptionDecl()) {
568 // FIXME: Dropping the reference type on the type into makes it
569 // impossible to correctly implement catch-by-reference
570 // semantics for pointers. Unfortunately, this is what all
571 // existing compilers do, and it's not clear that the standard
572 // personality routine is capable of doing this right. See C++ DR 388:
573 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
David Majnemer571162a2014-10-12 06:58:22 +0000574 Qualifiers CaughtTypeQuals;
575 QualType CaughtType = CGM.getContext().getUnqualifiedArrayType(
576 C->getCaughtType().getNonReferenceType(), CaughtTypeQuals);
John McCall2ca705e2010-07-24 00:37:23 +0000577
Reid Kleckner10aa7702015-09-16 20:15:55 +0000578 CatchTypeInfo TypeInfo{nullptr, 0};
John McCall2ca705e2010-07-24 00:37:23 +0000579 if (CaughtType->isObjCObjectPointerType())
Reid Kleckner10aa7702015-09-16 20:15:55 +0000580 TypeInfo.RTTI = CGM.getObjCRuntime().GetEHType(CaughtType);
John McCall2ca705e2010-07-24 00:37:23 +0000581 else
Reid Kleckner10aa7702015-09-16 20:15:55 +0000582 TypeInfo = CGM.getCXXABI().getAddrOfCXXCatchHandlerType(
583 CaughtType, C->getCaughtType());
John McCallbd309292010-07-06 01:34:17 +0000584 CatchScope->setHandler(I, TypeInfo, Handler);
585 } else {
586 // No exception decl indicates '...', a catch-all.
Reid Kleckner10aa7702015-09-16 20:15:55 +0000587 CatchScope->setHandler(I, CGM.getCXXABI().getCatchAllTypeInfo(), Handler);
John McCallbd309292010-07-06 01:34:17 +0000588 }
589 }
John McCallbd309292010-07-06 01:34:17 +0000590}
591
John McCall8e4c74b2011-08-11 02:22:43 +0000592llvm::BasicBlock *
593CodeGenFunction::getEHDispatchBlock(EHScopeStack::stable_iterator si) {
Reid Kleckner129552b2015-10-08 01:13:52 +0000594 if (EHPersonality::get(*this).usesFuncletPads())
Heejin Ahnc6479192018-05-31 22:18:13 +0000595 return getFuncletEHDispatchBlock(si);
David Majnemerdbf10452015-07-31 17:58:45 +0000596
John McCall8e4c74b2011-08-11 02:22:43 +0000597 // The dispatch block for the end of the scope chain is a block that
598 // just resumes unwinding.
599 if (si == EHStack.stable_end())
David Chisnall9a837be2012-11-07 16:50:40 +0000600 return getEHResumeBlock(true);
John McCall8e4c74b2011-08-11 02:22:43 +0000601
602 // Otherwise, we should look at the actual scope.
603 EHScope &scope = *EHStack.find(si);
604
605 llvm::BasicBlock *dispatchBlock = scope.getCachedEHDispatchBlock();
606 if (!dispatchBlock) {
607 switch (scope.getKind()) {
608 case EHScope::Catch: {
609 // Apply a special case to a single catch-all.
610 EHCatchScope &catchScope = cast<EHCatchScope>(scope);
611 if (catchScope.getNumHandlers() == 1 &&
612 catchScope.getHandler(0).isCatchAll()) {
613 dispatchBlock = catchScope.getHandler(0).Block;
614
615 // Otherwise, make a dispatch block.
616 } else {
617 dispatchBlock = createBasicBlock("catch.dispatch");
618 }
619 break;
620 }
621
622 case EHScope::Cleanup:
623 dispatchBlock = createBasicBlock("ehcleanup");
624 break;
625
626 case EHScope::Filter:
627 dispatchBlock = createBasicBlock("filter.dispatch");
628 break;
629
630 case EHScope::Terminate:
631 dispatchBlock = getTerminateHandler();
632 break;
David Majnemerdbf10452015-07-31 17:58:45 +0000633
Reid Kleckner2586aac2015-09-10 22:11:13 +0000634 case EHScope::PadEnd:
635 llvm_unreachable("PadEnd unnecessary for Itanium!");
John McCall8e4c74b2011-08-11 02:22:43 +0000636 }
637 scope.setCachedEHDispatchBlock(dispatchBlock);
638 }
639 return dispatchBlock;
640}
641
David Majnemerdbf10452015-07-31 17:58:45 +0000642llvm::BasicBlock *
Heejin Ahnc6479192018-05-31 22:18:13 +0000643CodeGenFunction::getFuncletEHDispatchBlock(EHScopeStack::stable_iterator SI) {
David Majnemerdbf10452015-07-31 17:58:45 +0000644 // Returning nullptr indicates that the previous dispatch block should unwind
645 // to caller.
646 if (SI == EHStack.stable_end())
647 return nullptr;
648
649 // Otherwise, we should look at the actual scope.
650 EHScope &EHS = *EHStack.find(SI);
651
652 llvm::BasicBlock *DispatchBlock = EHS.getCachedEHDispatchBlock();
653 if (DispatchBlock)
654 return DispatchBlock;
655
656 if (EHS.getKind() == EHScope::Terminate)
Reid Kleckner06f19a02018-01-02 21:34:16 +0000657 DispatchBlock = getTerminateFunclet();
David Majnemerdbf10452015-07-31 17:58:45 +0000658 else
659 DispatchBlock = createBasicBlock();
John McCall7f416cc2015-09-08 08:05:57 +0000660 CGBuilderTy Builder(*this, DispatchBlock);
David Majnemerdbf10452015-07-31 17:58:45 +0000661
662 switch (EHS.getKind()) {
663 case EHScope::Catch:
664 DispatchBlock->setName("catch.dispatch");
665 break;
666
667 case EHScope::Cleanup:
668 DispatchBlock->setName("ehcleanup");
669 break;
670
671 case EHScope::Filter:
672 llvm_unreachable("exception specifications not handled yet!");
673
674 case EHScope::Terminate:
675 DispatchBlock->setName("terminate");
676 break;
677
Reid Kleckner2586aac2015-09-10 22:11:13 +0000678 case EHScope::PadEnd:
679 llvm_unreachable("PadEnd dispatch block missing!");
David Majnemerdbf10452015-07-31 17:58:45 +0000680 }
681 EHS.setCachedEHDispatchBlock(DispatchBlock);
682 return DispatchBlock;
683}
684
John McCallbd309292010-07-06 01:34:17 +0000685/// Check whether this is a non-EH scope, i.e. a scope which doesn't
686/// affect exception handling. Currently, the only non-EH scopes are
687/// normal-only cleanup scopes.
688static bool isNonEHScope(const EHScope &S) {
John McCall2b7fc382010-07-13 20:32:21 +0000689 switch (S.getKind()) {
John McCallcda666c2010-07-21 07:22:38 +0000690 case EHScope::Cleanup:
691 return !cast<EHCleanupScope>(S).isEHCleanup();
John McCall2b7fc382010-07-13 20:32:21 +0000692 case EHScope::Filter:
693 case EHScope::Catch:
694 case EHScope::Terminate:
Reid Kleckner2586aac2015-09-10 22:11:13 +0000695 case EHScope::PadEnd:
John McCall2b7fc382010-07-13 20:32:21 +0000696 return false;
697 }
698
David Blaikiee4d798f2012-01-20 21:50:17 +0000699 llvm_unreachable("Invalid EHScope Kind!");
John McCallbd309292010-07-06 01:34:17 +0000700}
701
702llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
703 assert(EHStack.requiresLandingPad());
704 assert(!EHStack.empty());
705
Reid Kleckner8f1b1f52016-03-01 19:51:48 +0000706 // If exceptions are disabled and SEH is not in use, then there is no invoke
707 // destination. SEH "works" even if exceptions are off. In practice, this
708 // means that C++ destructors and other EH cleanups don't run, which is
709 // consistent with MSVC's behavior.
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000710 const LangOptions &LO = CGM.getLangOpts();
711 if (!LO.Exceptions) {
712 if (!LO.Borland && !LO.MicrosoftExt)
713 return nullptr;
Reid Klecknere7b3f7c2015-02-11 00:00:21 +0000714 if (!currentFunctionUsesSEHTry())
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000715 return nullptr;
716 }
John McCall2b7fc382010-07-13 20:32:21 +0000717
Justin Lebar3e6449b2016-10-04 23:41:49 +0000718 // CUDA device code doesn't have exceptions.
719 if (LO.CUDA && LO.CUDAIsDevice)
720 return nullptr;
721
John McCallbd309292010-07-06 01:34:17 +0000722 // Check the innermost scope for a cached landing pad. If this is
723 // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
724 llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
725 if (LP) return LP;
726
David Majnemerdbf10452015-07-31 17:58:45 +0000727 const EHPersonality &Personality = EHPersonality::get(*this);
728
729 if (!CurFn->hasPersonalityFn())
730 CurFn->setPersonalityFn(getOpaquePersonalityFn(CGM, Personality));
731
Reid Kleckner129552b2015-10-08 01:13:52 +0000732 if (Personality.usesFuncletPads()) {
733 // We don't need separate landing pads in the funclet model.
David Majnemerdbf10452015-07-31 17:58:45 +0000734 LP = getEHDispatchBlock(EHStack.getInnermostEHScope());
735 } else {
736 // Build the landing pad for this scope.
737 LP = EmitLandingPad();
738 }
739
John McCallbd309292010-07-06 01:34:17 +0000740 assert(LP);
741
742 // Cache the landing pad on the innermost scope. If this is a
743 // non-EH scope, cache the landing pad on the enclosing scope, too.
744 for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
745 ir->setCachedLandingPad(LP);
746 if (!isNonEHScope(*ir)) break;
747 }
748
749 return LP;
750}
751
752llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
753 assert(EHStack.requiresLandingPad());
754
John McCall8e4c74b2011-08-11 02:22:43 +0000755 EHScope &innermostEHScope = *EHStack.find(EHStack.getInnermostEHScope());
756 switch (innermostEHScope.getKind()) {
757 case EHScope::Terminate:
758 return getTerminateLandingPad();
John McCallbd309292010-07-06 01:34:17 +0000759
Reid Kleckner2586aac2015-09-10 22:11:13 +0000760 case EHScope::PadEnd:
761 llvm_unreachable("PadEnd unnecessary for Itanium!");
David Majnemerdbf10452015-07-31 17:58:45 +0000762
John McCall8e4c74b2011-08-11 02:22:43 +0000763 case EHScope::Catch:
764 case EHScope::Cleanup:
765 case EHScope::Filter:
766 if (llvm::BasicBlock *lpad = innermostEHScope.getCachedLandingPad())
767 return lpad;
John McCallbd309292010-07-06 01:34:17 +0000768 }
769
770 // Save the current IR generation state.
John McCall8e4c74b2011-08-11 02:22:43 +0000771 CGBuilderTy::InsertPoint savedIP = Builder.saveAndClearIP();
Calixte Denizetfcd661d2018-09-24 18:24:18 +0000772 auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, CurEHLocation);
John McCallbd309292010-07-06 01:34:17 +0000773
774 // Create and configure the landing pad.
John McCall8e4c74b2011-08-11 02:22:43 +0000775 llvm::BasicBlock *lpad = createBasicBlock("lpad");
776 EmitBlock(lpad);
John McCallbd309292010-07-06 01:34:17 +0000777
Serge Guelton1d993272017-05-09 19:31:30 +0000778 llvm::LandingPadInst *LPadInst =
779 Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty), 0);
Bill Wendlingf0724e82011-09-19 20:31:14 +0000780
781 llvm::Value *LPadExn = Builder.CreateExtractValue(LPadInst, 0);
782 Builder.CreateStore(LPadExn, getExceptionSlot());
783 llvm::Value *LPadSel = Builder.CreateExtractValue(LPadInst, 1);
784 Builder.CreateStore(LPadSel, getEHSelectorSlot());
785
John McCallbd309292010-07-06 01:34:17 +0000786 // Save the exception pointer. It's safe to use a single exception
787 // pointer per function because EH cleanups can never have nested
788 // try/catches.
Bill Wendlingf0724e82011-09-19 20:31:14 +0000789 // Build the landingpad instruction.
John McCallbd309292010-07-06 01:34:17 +0000790
791 // Accumulate all the handlers in scope.
John McCall8e4c74b2011-08-11 02:22:43 +0000792 bool hasCatchAll = false;
793 bool hasCleanup = false;
794 bool hasFilter = false;
795 SmallVector<llvm::Value*, 4> filterTypes;
796 llvm::SmallPtrSet<llvm::Value*, 4> catchTypes;
Nico Webere68b9f32015-02-25 16:25:00 +0000797 for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end(); I != E;
798 ++I) {
John McCallbd309292010-07-06 01:34:17 +0000799
800 switch (I->getKind()) {
John McCallcda666c2010-07-21 07:22:38 +0000801 case EHScope::Cleanup:
John McCall8e4c74b2011-08-11 02:22:43 +0000802 // If we have a cleanup, remember that.
803 hasCleanup = (hasCleanup || cast<EHCleanupScope>(*I).isEHCleanup());
John McCall2b7fc382010-07-13 20:32:21 +0000804 continue;
805
John McCallbd309292010-07-06 01:34:17 +0000806 case EHScope::Filter: {
807 assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
John McCall8e4c74b2011-08-11 02:22:43 +0000808 assert(!hasCatchAll && "EH filter reached after catch-all");
John McCallbd309292010-07-06 01:34:17 +0000809
Bill Wendlingf0724e82011-09-19 20:31:14 +0000810 // Filter scopes get added to the landingpad in weird ways.
John McCall8e4c74b2011-08-11 02:22:43 +0000811 EHFilterScope &filter = cast<EHFilterScope>(*I);
812 hasFilter = true;
John McCallbd309292010-07-06 01:34:17 +0000813
Bill Wendling8c4b7162011-09-22 20:32:54 +0000814 // Add all the filter values.
815 for (unsigned i = 0, e = filter.getNumFilters(); i != e; ++i)
816 filterTypes.push_back(filter.getFilter(i));
John McCallbd309292010-07-06 01:34:17 +0000817 goto done;
818 }
819
820 case EHScope::Terminate:
821 // Terminate scopes are basically catch-alls.
John McCall8e4c74b2011-08-11 02:22:43 +0000822 assert(!hasCatchAll);
823 hasCatchAll = true;
John McCallbd309292010-07-06 01:34:17 +0000824 goto done;
825
826 case EHScope::Catch:
827 break;
David Majnemerdbf10452015-07-31 17:58:45 +0000828
Reid Kleckner2586aac2015-09-10 22:11:13 +0000829 case EHScope::PadEnd:
830 llvm_unreachable("PadEnd unnecessary for Itanium!");
John McCallbd309292010-07-06 01:34:17 +0000831 }
832
John McCall8e4c74b2011-08-11 02:22:43 +0000833 EHCatchScope &catchScope = cast<EHCatchScope>(*I);
834 for (unsigned hi = 0, he = catchScope.getNumHandlers(); hi != he; ++hi) {
835 EHCatchScope::Handler handler = catchScope.getHandler(hi);
Reid Kleckner10aa7702015-09-16 20:15:55 +0000836 assert(handler.Type.Flags == 0 &&
837 "landingpads do not support catch handler flags");
John McCallbd309292010-07-06 01:34:17 +0000838
John McCall8e4c74b2011-08-11 02:22:43 +0000839 // If this is a catch-all, register that and abort.
Reid Kleckner10aa7702015-09-16 20:15:55 +0000840 if (!handler.Type.RTTI) {
John McCall8e4c74b2011-08-11 02:22:43 +0000841 assert(!hasCatchAll);
842 hasCatchAll = true;
843 goto done;
John McCallbd309292010-07-06 01:34:17 +0000844 }
845
846 // Check whether we already have a handler for this type.
Reid Kleckner10aa7702015-09-16 20:15:55 +0000847 if (catchTypes.insert(handler.Type.RTTI).second)
Bill Wendlingf0724e82011-09-19 20:31:14 +0000848 // If not, add it directly to the landingpad.
Reid Kleckner10aa7702015-09-16 20:15:55 +0000849 LPadInst->addClause(handler.Type.RTTI);
John McCallbd309292010-07-06 01:34:17 +0000850 }
John McCallbd309292010-07-06 01:34:17 +0000851 }
852
853 done:
Bill Wendlingf0724e82011-09-19 20:31:14 +0000854 // If we have a catch-all, add null to the landingpad.
John McCall8e4c74b2011-08-11 02:22:43 +0000855 assert(!(hasCatchAll && hasFilter));
856 if (hasCatchAll) {
Bill Wendlingf0724e82011-09-19 20:31:14 +0000857 LPadInst->addClause(getCatchAllValue(*this));
John McCallbd309292010-07-06 01:34:17 +0000858
859 // If we have an EH filter, we need to add those handlers in the
Bill Wendlingf0724e82011-09-19 20:31:14 +0000860 // right place in the landingpad, which is to say, at the end.
John McCall8e4c74b2011-08-11 02:22:43 +0000861 } else if (hasFilter) {
Bill Wendling58e58fe2011-09-19 22:08:36 +0000862 // Create a filter expression: a constant array indicating which filter
863 // types there are. The personality routine only lands here if the filter
864 // doesn't match.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000865 SmallVector<llvm::Constant*, 8> Filters;
Bill Wendlingf0724e82011-09-19 20:31:14 +0000866 llvm::ArrayType *AType =
867 llvm::ArrayType::get(!filterTypes.empty() ?
868 filterTypes[0]->getType() : Int8PtrTy,
869 filterTypes.size());
870
871 for (unsigned i = 0, e = filterTypes.size(); i != e; ++i)
872 Filters.push_back(cast<llvm::Constant>(filterTypes[i]));
873 llvm::Constant *FilterArray = llvm::ConstantArray::get(AType, Filters);
874 LPadInst->addClause(FilterArray);
John McCallbd309292010-07-06 01:34:17 +0000875
876 // Also check whether we need a cleanup.
Bill Wendlingf0724e82011-09-19 20:31:14 +0000877 if (hasCleanup)
878 LPadInst->setCleanup(true);
John McCallbd309292010-07-06 01:34:17 +0000879
880 // Otherwise, signal that we at least have cleanups.
Logan Chiene9c8ccb2014-07-01 11:47:10 +0000881 } else if (hasCleanup) {
882 LPadInst->setCleanup(true);
John McCallbd309292010-07-06 01:34:17 +0000883 }
884
Bill Wendlingf0724e82011-09-19 20:31:14 +0000885 assert((LPadInst->getNumClauses() > 0 || LPadInst->isCleanup()) &&
886 "landingpad instruction has no clauses!");
John McCallbd309292010-07-06 01:34:17 +0000887
888 // Tell the backend how to generate the landing pad.
John McCall8e4c74b2011-08-11 02:22:43 +0000889 Builder.CreateBr(getEHDispatchBlock(EHStack.getInnermostEHScope()));
John McCallbd309292010-07-06 01:34:17 +0000890
891 // Restore the old IR generation state.
John McCall8e4c74b2011-08-11 02:22:43 +0000892 Builder.restoreIP(savedIP);
John McCallbd309292010-07-06 01:34:17 +0000893
John McCall8e4c74b2011-08-11 02:22:43 +0000894 return lpad;
John McCallbd309292010-07-06 01:34:17 +0000895}
896
David Majnemer4e52d6f2015-12-12 05:39:21 +0000897static void emitCatchPadBlock(CodeGenFunction &CGF, EHCatchScope &CatchScope) {
David Majnemerdbf10452015-07-31 17:58:45 +0000898 llvm::BasicBlock *DispatchBlock = CatchScope.getCachedEHDispatchBlock();
899 assert(DispatchBlock);
900
901 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveIP();
902 CGF.EmitBlockAfterUses(DispatchBlock);
903
David Majnemer4e52d6f2015-12-12 05:39:21 +0000904 llvm::Value *ParentPad = CGF.CurrentFuncletPad;
905 if (!ParentPad)
906 ParentPad = llvm::ConstantTokenNone::get(CGF.getLLVMContext());
907 llvm::BasicBlock *UnwindBB =
908 CGF.getEHDispatchBlock(CatchScope.getEnclosingEHScope());
909
910 unsigned NumHandlers = CatchScope.getNumHandlers();
911 llvm::CatchSwitchInst *CatchSwitch =
912 CGF.Builder.CreateCatchSwitch(ParentPad, UnwindBB, NumHandlers);
David Majnemerdbf10452015-07-31 17:58:45 +0000913
914 // Test against each of the exception types we claim to catch.
David Majnemer4e52d6f2015-12-12 05:39:21 +0000915 for (unsigned I = 0; I < NumHandlers; ++I) {
David Majnemerdbf10452015-07-31 17:58:45 +0000916 const EHCatchScope::Handler &Handler = CatchScope.getHandler(I);
917
Reid Kleckner10aa7702015-09-16 20:15:55 +0000918 CatchTypeInfo TypeInfo = Handler.Type;
919 if (!TypeInfo.RTTI)
920 TypeInfo.RTTI = llvm::Constant::getNullValue(CGF.VoidPtrTy);
David Majnemerdbf10452015-07-31 17:58:45 +0000921
David Majnemer4e52d6f2015-12-12 05:39:21 +0000922 CGF.Builder.SetInsertPoint(Handler.Block);
David Majnemerdbf10452015-07-31 17:58:45 +0000923
924 if (EHPersonality::get(CGF).isMSVCXXPersonality()) {
David Majnemer4e52d6f2015-12-12 05:39:21 +0000925 CGF.Builder.CreateCatchPad(
926 CatchSwitch, {TypeInfo.RTTI, CGF.Builder.getInt32(TypeInfo.Flags),
927 llvm::Constant::getNullValue(CGF.VoidPtrTy)});
David Majnemerdbf10452015-07-31 17:58:45 +0000928 } else {
David Majnemer4e52d6f2015-12-12 05:39:21 +0000929 CGF.Builder.CreateCatchPad(CatchSwitch, {TypeInfo.RTTI});
David Majnemerdbf10452015-07-31 17:58:45 +0000930 }
931
David Majnemer4e52d6f2015-12-12 05:39:21 +0000932 CatchSwitch->addHandler(Handler.Block);
David Majnemerdbf10452015-07-31 17:58:45 +0000933 }
934 CGF.Builder.restoreIP(SavedIP);
David Majnemerdbf10452015-07-31 17:58:45 +0000935}
936
Heejin Ahnc6479192018-05-31 22:18:13 +0000937// Wasm uses Windows-style EH instructions, but it merges all catch clauses into
938// one big catchpad, within which we use Itanium's landingpad-style selector
939// comparison instructions.
940static void emitWasmCatchPadBlock(CodeGenFunction &CGF,
941 EHCatchScope &CatchScope) {
942 llvm::BasicBlock *DispatchBlock = CatchScope.getCachedEHDispatchBlock();
943 assert(DispatchBlock);
944
945 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveIP();
946 CGF.EmitBlockAfterUses(DispatchBlock);
947
948 llvm::Value *ParentPad = CGF.CurrentFuncletPad;
949 if (!ParentPad)
950 ParentPad = llvm::ConstantTokenNone::get(CGF.getLLVMContext());
951 llvm::BasicBlock *UnwindBB =
952 CGF.getEHDispatchBlock(CatchScope.getEnclosingEHScope());
953
954 unsigned NumHandlers = CatchScope.getNumHandlers();
955 llvm::CatchSwitchInst *CatchSwitch =
956 CGF.Builder.CreateCatchSwitch(ParentPad, UnwindBB, NumHandlers);
957
958 // We don't use a landingpad instruction, so generate intrinsic calls to
959 // provide exception and selector values.
960 llvm::BasicBlock *WasmCatchStartBlock = CGF.createBasicBlock("catch.start");
961 CatchSwitch->addHandler(WasmCatchStartBlock);
962 CGF.EmitBlockAfterUses(WasmCatchStartBlock);
963
964 // Create a catchpad instruction.
965 SmallVector<llvm::Value *, 4> CatchTypes;
966 for (unsigned I = 0, E = NumHandlers; I < E; ++I) {
967 const EHCatchScope::Handler &Handler = CatchScope.getHandler(I);
968 CatchTypeInfo TypeInfo = Handler.Type;
969 if (!TypeInfo.RTTI)
970 TypeInfo.RTTI = llvm::Constant::getNullValue(CGF.VoidPtrTy);
971 CatchTypes.push_back(TypeInfo.RTTI);
972 }
973 auto *CPI = CGF.Builder.CreateCatchPad(CatchSwitch, CatchTypes);
974
975 // Create calls to wasm.get.exception and wasm.get.ehselector intrinsics.
976 // Before they are lowered appropriately later, they provide values for the
977 // exception and selector.
James Y Knight8799cae2019-02-03 21:53:49 +0000978 llvm::Function *GetExnFn =
Heejin Ahnc6479192018-05-31 22:18:13 +0000979 CGF.CGM.getIntrinsic(llvm::Intrinsic::wasm_get_exception);
James Y Knight8799cae2019-02-03 21:53:49 +0000980 llvm::Function *GetSelectorFn =
Heejin Ahnc6479192018-05-31 22:18:13 +0000981 CGF.CGM.getIntrinsic(llvm::Intrinsic::wasm_get_ehselector);
982 llvm::CallInst *Exn = CGF.Builder.CreateCall(GetExnFn, CPI);
983 CGF.Builder.CreateStore(Exn, CGF.getExceptionSlot());
984 llvm::CallInst *Selector = CGF.Builder.CreateCall(GetSelectorFn, CPI);
985
James Y Knight8799cae2019-02-03 21:53:49 +0000986 llvm::Function *TypeIDFn = CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
Heejin Ahnc6479192018-05-31 22:18:13 +0000987
988 // If there's only a single catch-all, branch directly to its handler.
989 if (CatchScope.getNumHandlers() == 1 &&
990 CatchScope.getHandler(0).isCatchAll()) {
991 CGF.Builder.CreateBr(CatchScope.getHandler(0).Block);
992 CGF.Builder.restoreIP(SavedIP);
993 return;
994 }
995
996 // Test against each of the exception types we claim to catch.
997 for (unsigned I = 0, E = NumHandlers;; ++I) {
998 assert(I < E && "ran off end of handlers!");
999 const EHCatchScope::Handler &Handler = CatchScope.getHandler(I);
1000 CatchTypeInfo TypeInfo = Handler.Type;
1001 if (!TypeInfo.RTTI)
1002 TypeInfo.RTTI = llvm::Constant::getNullValue(CGF.VoidPtrTy);
1003
1004 // Figure out the next block.
1005 llvm::BasicBlock *NextBlock;
1006
1007 bool EmitNextBlock = false, NextIsEnd = false;
1008
1009 // If this is the last handler, we're at the end, and the next block is a
1010 // block that contains a call to the rethrow function, so we can unwind to
1011 // the enclosing EH scope. The call itself will be generated later.
1012 if (I + 1 == E) {
1013 NextBlock = CGF.createBasicBlock("rethrow");
1014 EmitNextBlock = true;
1015 NextIsEnd = true;
1016
1017 // If the next handler is a catch-all, we're at the end, and the
1018 // next block is that handler.
1019 } else if (CatchScope.getHandler(I + 1).isCatchAll()) {
1020 NextBlock = CatchScope.getHandler(I + 1).Block;
1021 NextIsEnd = true;
1022
1023 // Otherwise, we're not at the end and we need a new block.
1024 } else {
1025 NextBlock = CGF.createBasicBlock("catch.fallthrough");
1026 EmitNextBlock = true;
1027 }
1028
1029 // Figure out the catch type's index in the LSDA's type table.
1030 llvm::CallInst *TypeIndex = CGF.Builder.CreateCall(TypeIDFn, TypeInfo.RTTI);
1031 TypeIndex->setDoesNotThrow();
1032
1033 llvm::Value *MatchesTypeIndex =
1034 CGF.Builder.CreateICmpEQ(Selector, TypeIndex, "matches");
1035 CGF.Builder.CreateCondBr(MatchesTypeIndex, Handler.Block, NextBlock);
1036
1037 if (EmitNextBlock)
1038 CGF.EmitBlock(NextBlock);
1039 if (NextIsEnd)
1040 break;
1041 }
1042
1043 CGF.Builder.restoreIP(SavedIP);
1044}
1045
John McCall8e4c74b2011-08-11 02:22:43 +00001046/// Emit the structure of the dispatch block for the given catch scope.
1047/// It is an invariant that the dispatch block already exists.
David Majnemer4e52d6f2015-12-12 05:39:21 +00001048static void emitCatchDispatchBlock(CodeGenFunction &CGF,
1049 EHCatchScope &catchScope) {
Heejin Ahnc6479192018-05-31 22:18:13 +00001050 if (EHPersonality::get(CGF).isWasmPersonality())
1051 return emitWasmCatchPadBlock(CGF, catchScope);
Reid Kleckner129552b2015-10-08 01:13:52 +00001052 if (EHPersonality::get(CGF).usesFuncletPads())
1053 return emitCatchPadBlock(CGF, catchScope);
David Majnemerdbf10452015-07-31 17:58:45 +00001054
John McCall8e4c74b2011-08-11 02:22:43 +00001055 llvm::BasicBlock *dispatchBlock = catchScope.getCachedEHDispatchBlock();
1056 assert(dispatchBlock);
1057
1058 // If there's only a single catch-all, getEHDispatchBlock returned
1059 // that catch-all as the dispatch block.
1060 if (catchScope.getNumHandlers() == 1 &&
1061 catchScope.getHandler(0).isCatchAll()) {
1062 assert(dispatchBlock == catchScope.getHandler(0).Block);
David Majnemer4e52d6f2015-12-12 05:39:21 +00001063 return;
John McCall8e4c74b2011-08-11 02:22:43 +00001064 }
1065
1066 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveIP();
1067 CGF.EmitBlockAfterUses(dispatchBlock);
1068
1069 // Select the right handler.
James Y Knight8799cae2019-02-03 21:53:49 +00001070 llvm::Function *llvm_eh_typeid_for =
John McCall8e4c74b2011-08-11 02:22:43 +00001071 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
1072
1073 // Load the selector value.
Bill Wendling79a70e42011-09-15 18:57:19 +00001074 llvm::Value *selector = CGF.getSelectorFromSlot();
John McCall8e4c74b2011-08-11 02:22:43 +00001075
1076 // Test against each of the exception types we claim to catch.
1077 for (unsigned i = 0, e = catchScope.getNumHandlers(); ; ++i) {
1078 assert(i < e && "ran off end of handlers!");
1079 const EHCatchScope::Handler &handler = catchScope.getHandler(i);
1080
Reid Kleckner10aa7702015-09-16 20:15:55 +00001081 llvm::Value *typeValue = handler.Type.RTTI;
1082 assert(handler.Type.Flags == 0 &&
1083 "landingpads do not support catch handler flags");
John McCall8e4c74b2011-08-11 02:22:43 +00001084 assert(typeValue && "fell into catch-all case!");
1085 typeValue = CGF.Builder.CreateBitCast(typeValue, CGF.Int8PtrTy);
1086
1087 // Figure out the next block.
1088 bool nextIsEnd;
1089 llvm::BasicBlock *nextBlock;
1090
1091 // If this is the last handler, we're at the end, and the next
1092 // block is the block for the enclosing EH scope.
1093 if (i + 1 == e) {
1094 nextBlock = CGF.getEHDispatchBlock(catchScope.getEnclosingEHScope());
1095 nextIsEnd = true;
1096
1097 // If the next handler is a catch-all, we're at the end, and the
1098 // next block is that handler.
1099 } else if (catchScope.getHandler(i+1).isCatchAll()) {
1100 nextBlock = catchScope.getHandler(i+1).Block;
1101 nextIsEnd = true;
1102
1103 // Otherwise, we're not at the end and we need a new block.
1104 } else {
1105 nextBlock = CGF.createBasicBlock("catch.fallthrough");
1106 nextIsEnd = false;
1107 }
1108
1109 // Figure out the catch type's index in the LSDA's type table.
1110 llvm::CallInst *typeIndex =
1111 CGF.Builder.CreateCall(llvm_eh_typeid_for, typeValue);
1112 typeIndex->setDoesNotThrow();
1113
1114 llvm::Value *matchesTypeIndex =
1115 CGF.Builder.CreateICmpEQ(selector, typeIndex, "matches");
1116 CGF.Builder.CreateCondBr(matchesTypeIndex, handler.Block, nextBlock);
1117
1118 // If the next handler is a catch-all, we're completely done.
1119 if (nextIsEnd) {
1120 CGF.Builder.restoreIP(savedIP);
David Majnemer4e52d6f2015-12-12 05:39:21 +00001121 return;
John McCall8e4c74b2011-08-11 02:22:43 +00001122 }
Ahmed Charles289896d2012-02-19 11:57:29 +00001123 // Otherwise we need to emit and continue at that block.
1124 CGF.EmitBlock(nextBlock);
John McCall8e4c74b2011-08-11 02:22:43 +00001125 }
John McCall8e4c74b2011-08-11 02:22:43 +00001126}
1127
1128void CodeGenFunction::popCatchScope() {
1129 EHCatchScope &catchScope = cast<EHCatchScope>(*EHStack.begin());
1130 if (catchScope.hasEHBranches())
1131 emitCatchDispatchBlock(*this, catchScope);
1132 EHStack.popCatch();
1133}
1134
John McCallb609d3f2010-07-07 06:56:46 +00001135void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallbd309292010-07-06 01:34:17 +00001136 unsigned NumHandlers = S.getNumHandlers();
1137 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1138 assert(CatchScope.getNumHandlers() == NumHandlers);
Heejin Ahnc6479192018-05-31 22:18:13 +00001139 llvm::BasicBlock *DispatchBlock = CatchScope.getCachedEHDispatchBlock();
Mike Stump58ef18b2009-11-20 23:44:51 +00001140
John McCall8e4c74b2011-08-11 02:22:43 +00001141 // If the catch was not required, bail out now.
1142 if (!CatchScope.hasEHBranches()) {
Kostya Serebryanyba4aced2014-01-09 09:22:32 +00001143 CatchScope.clearHandlerBlocks();
John McCall8e4c74b2011-08-11 02:22:43 +00001144 EHStack.popCatch();
1145 return;
1146 }
1147
1148 // Emit the structure of the EH dispatch for this catch.
David Majnemer4e52d6f2015-12-12 05:39:21 +00001149 emitCatchDispatchBlock(*this, CatchScope);
John McCall8e4c74b2011-08-11 02:22:43 +00001150
John McCallbd309292010-07-06 01:34:17 +00001151 // Copy the handler blocks off before we pop the EH stack. Emitting
1152 // the handlers might scribble on this memory.
Benjamin Kramerda32cf82015-08-04 15:38:49 +00001153 SmallVector<EHCatchScope::Handler, 8> Handlers(
1154 CatchScope.begin(), CatchScope.begin() + NumHandlers);
John McCall8e4c74b2011-08-11 02:22:43 +00001155
John McCallbd309292010-07-06 01:34:17 +00001156 EHStack.popCatch();
Mike Stump58ef18b2009-11-20 23:44:51 +00001157
John McCallbd309292010-07-06 01:34:17 +00001158 // The fall-through block.
1159 llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
Mike Stump58ef18b2009-11-20 23:44:51 +00001160
John McCallbd309292010-07-06 01:34:17 +00001161 // We just emitted the body of the try; jump to the continue block.
1162 if (HaveInsertPoint())
1163 Builder.CreateBr(ContBB);
Mike Stump97329152009-12-02 19:53:57 +00001164
John McCalld8d00be2012-06-15 05:27:05 +00001165 // Determine if we need an implicit rethrow for all these catch handlers;
1166 // see the comment below.
1167 bool doImplicitRethrow = false;
John McCallb609d3f2010-07-07 06:56:46 +00001168 if (IsFnTryBlock)
John McCalld8d00be2012-06-15 05:27:05 +00001169 doImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
1170 isa<CXXConstructorDecl>(CurCodeDecl);
John McCallb609d3f2010-07-07 06:56:46 +00001171
Heejin Ahnc6479192018-05-31 22:18:13 +00001172 // Wasm uses Windows-style EH instructions, but merges all catch clauses into
1173 // one big catchpad. So we save the old funclet pad here before we traverse
1174 // each catch handler.
1175 SaveAndRestore<llvm::Instruction *> RestoreCurrentFuncletPad(
1176 CurrentFuncletPad);
1177 llvm::BasicBlock *WasmCatchStartBlock = nullptr;
1178 if (EHPersonality::get(*this).isWasmPersonality()) {
1179 auto *CatchSwitch =
1180 cast<llvm::CatchSwitchInst>(DispatchBlock->getFirstNonPHI());
1181 WasmCatchStartBlock = CatchSwitch->hasUnwindDest()
1182 ? CatchSwitch->getSuccessor(1)
1183 : CatchSwitch->getSuccessor(0);
1184 auto *CPI = cast<llvm::CatchPadInst>(WasmCatchStartBlock->getFirstNonPHI());
1185 CurrentFuncletPad = CPI;
1186 }
1187
John McCall8e4c74b2011-08-11 02:22:43 +00001188 // Perversely, we emit the handlers backwards precisely because we
1189 // want them to appear in source order. In all of these cases, the
1190 // catch block will have exactly one predecessor, which will be a
1191 // particular block in the catch dispatch. However, in the case of
1192 // a catch-all, one of the dispatch blocks will branch to two
1193 // different handlers, and EmitBlockAfterUses will cause the second
1194 // handler to be moved before the first.
Heejin Ahnc6479192018-05-31 22:18:13 +00001195 bool HasCatchAll = false;
John McCall8e4c74b2011-08-11 02:22:43 +00001196 for (unsigned I = NumHandlers; I != 0; --I) {
Heejin Ahnc6479192018-05-31 22:18:13 +00001197 HasCatchAll |= Handlers[I - 1].isCatchAll();
John McCall8e4c74b2011-08-11 02:22:43 +00001198 llvm::BasicBlock *CatchBlock = Handlers[I-1].Block;
1199 EmitBlockAfterUses(CatchBlock);
Mike Stump75546b82009-12-10 00:06:18 +00001200
John McCallbd309292010-07-06 01:34:17 +00001201 // Catch the exception if this isn't a catch-all.
John McCall8e4c74b2011-08-11 02:22:43 +00001202 const CXXCatchStmt *C = S.getHandler(I-1);
Mike Stump58ef18b2009-11-20 23:44:51 +00001203
John McCallbd309292010-07-06 01:34:17 +00001204 // Enter a cleanup scope, including the catch variable and the
1205 // end-catch.
1206 RunCleanupsScope CatchScope(*this);
Mike Stump58ef18b2009-11-20 23:44:51 +00001207
John McCallbd309292010-07-06 01:34:17 +00001208 // Initialize the catch variable and set up the cleanups.
David Majnemer4e52d6f2015-12-12 05:39:21 +00001209 SaveAndRestore<llvm::Instruction *> RestoreCurrentFuncletPad(
1210 CurrentFuncletPad);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00001211 CGM.getCXXABI().emitBeginCatch(*this, C);
John McCallbd309292010-07-06 01:34:17 +00001212
Justin Bognerea278c32014-01-07 00:20:28 +00001213 // Emit the PGO counter increment.
Justin Bogner66242d62015-04-23 23:06:47 +00001214 incrementProfileCounter(C);
Justin Bogneref512b92014-01-06 22:27:43 +00001215
John McCallbd309292010-07-06 01:34:17 +00001216 // Perform the body of the catch.
1217 EmitStmt(C->getHandlerBlock());
1218
John McCalld8d00be2012-06-15 05:27:05 +00001219 // [except.handle]p11:
1220 // The currently handled exception is rethrown if control
1221 // reaches the end of a handler of the function-try-block of a
1222 // constructor or destructor.
1223
1224 // It is important that we only do this on fallthrough and not on
1225 // return. Note that it's illegal to put a return in a
1226 // constructor function-try-block's catch handler (p14), so this
1227 // really only applies to destructors.
1228 if (doImplicitRethrow && HaveInsertPoint()) {
David Majnemer442d0a22014-11-25 07:20:20 +00001229 CGM.getCXXABI().emitRethrow(*this, /*isNoReturn*/false);
John McCalld8d00be2012-06-15 05:27:05 +00001230 Builder.CreateUnreachable();
1231 Builder.ClearInsertionPoint();
1232 }
1233
John McCallbd309292010-07-06 01:34:17 +00001234 // Fall out through the catch cleanups.
1235 CatchScope.ForceCleanup();
1236
1237 // Branch out of the try.
1238 if (HaveInsertPoint())
1239 Builder.CreateBr(ContBB);
Mike Stump58ef18b2009-11-20 23:44:51 +00001240 }
1241
Heejin Ahnc6479192018-05-31 22:18:13 +00001242 // Because in wasm we merge all catch clauses into one big catchpad, in case
1243 // none of the types in catch handlers matches after we test against each of
1244 // them, we should unwind to the next EH enclosing scope. We generate a call
1245 // to rethrow function here to do that.
1246 if (EHPersonality::get(*this).isWasmPersonality() && !HasCatchAll) {
1247 assert(WasmCatchStartBlock);
1248 // Navigate for the "rethrow" block we created in emitWasmCatchPadBlock().
1249 // Wasm uses landingpad-style conditional branches to compare selectors, so
1250 // we follow the false destination for each of the cond branches to reach
1251 // the rethrow block.
1252 llvm::BasicBlock *RethrowBlock = WasmCatchStartBlock;
Chandler Carruthe303c872018-10-15 10:42:50 +00001253 while (llvm::Instruction *TI = RethrowBlock->getTerminator()) {
Heejin Ahnc6479192018-05-31 22:18:13 +00001254 auto *BI = cast<llvm::BranchInst>(TI);
1255 assert(BI->isConditional());
1256 RethrowBlock = BI->getSuccessor(1);
1257 }
1258 assert(RethrowBlock != WasmCatchStartBlock && RethrowBlock->empty());
1259 Builder.SetInsertPoint(RethrowBlock);
Heejin Ahn7e66a502019-03-16 05:39:12 +00001260 llvm::Function *RethrowInCatchFn =
1261 CGM.getIntrinsic(llvm::Intrinsic::wasm_rethrow_in_catch);
1262 EmitNoreturnRuntimeCallOrInvoke(RethrowInCatchFn, {});
Heejin Ahnc6479192018-05-31 22:18:13 +00001263 }
1264
John McCallbd309292010-07-06 01:34:17 +00001265 EmitBlock(ContBB);
Justin Bogner66242d62015-04-23 23:06:47 +00001266 incrementProfileCounter(&S);
Mike Stump58ef18b2009-11-20 23:44:51 +00001267}
Mike Stumpaff69af2009-12-09 03:35:49 +00001268
John McCall1e670402010-07-21 00:52:03 +00001269namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001270 struct CallEndCatchForFinally final : EHScopeStack::Cleanup {
John McCall1e670402010-07-21 00:52:03 +00001271 llvm::Value *ForEHVar;
James Y Knight9871db02019-02-05 16:42:33 +00001272 llvm::FunctionCallee EndCatchFn;
1273 CallEndCatchForFinally(llvm::Value *ForEHVar,
1274 llvm::FunctionCallee EndCatchFn)
1275 : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
John McCall1e670402010-07-21 00:52:03 +00001276
Craig Topper4f12f102014-03-12 06:41:41 +00001277 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall1e670402010-07-21 00:52:03 +00001278 llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
1279 llvm::BasicBlock *CleanupContBB =
1280 CGF.createBasicBlock("finally.cleanup.cont");
1281
1282 llvm::Value *ShouldEndCatch =
John McCall7f416cc2015-09-08 08:05:57 +00001283 CGF.Builder.CreateFlagLoad(ForEHVar, "finally.endcatch");
John McCall1e670402010-07-21 00:52:03 +00001284 CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1285 CGF.EmitBlock(EndCatchBB);
John McCall882987f2013-02-28 19:01:20 +00001286 CGF.EmitRuntimeCallOrInvoke(EndCatchFn); // catch-all, so might throw
John McCall1e670402010-07-21 00:52:03 +00001287 CGF.EmitBlock(CleanupContBB);
1288 }
1289 };
John McCall906da4b2010-07-21 05:47:49 +00001290
David Blaikie7e70d682015-08-18 22:40:54 +00001291 struct PerformFinally final : EHScopeStack::Cleanup {
John McCall906da4b2010-07-21 05:47:49 +00001292 const Stmt *Body;
1293 llvm::Value *ForEHVar;
James Y Knight9871db02019-02-05 16:42:33 +00001294 llvm::FunctionCallee EndCatchFn;
1295 llvm::FunctionCallee RethrowFn;
John McCall906da4b2010-07-21 05:47:49 +00001296 llvm::Value *SavedExnVar;
1297
1298 PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
James Y Knight9871db02019-02-05 16:42:33 +00001299 llvm::FunctionCallee EndCatchFn,
1300 llvm::FunctionCallee RethrowFn, llvm::Value *SavedExnVar)
1301 : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1302 RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
John McCall906da4b2010-07-21 05:47:49 +00001303
Craig Topper4f12f102014-03-12 06:41:41 +00001304 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall906da4b2010-07-21 05:47:49 +00001305 // Enter a cleanup to call the end-catch function if one was provided.
1306 if (EndCatchFn)
John McCallcda666c2010-07-21 07:22:38 +00001307 CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
1308 ForEHVar, EndCatchFn);
John McCall906da4b2010-07-21 05:47:49 +00001309
John McCallcebe0ca2010-08-11 00:16:14 +00001310 // Save the current cleanup destination in case there are
1311 // cleanups in the finally block.
1312 llvm::Value *SavedCleanupDest =
1313 CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
1314 "cleanup.dest.saved");
1315
John McCall906da4b2010-07-21 05:47:49 +00001316 // Emit the finally block.
1317 CGF.EmitStmt(Body);
1318
1319 // If the end of the finally is reachable, check whether this was
1320 // for EH. If so, rethrow.
1321 if (CGF.HaveInsertPoint()) {
1322 llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
1323 llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
1324
1325 llvm::Value *ShouldRethrow =
John McCall7f416cc2015-09-08 08:05:57 +00001326 CGF.Builder.CreateFlagLoad(ForEHVar, "finally.shouldthrow");
John McCall906da4b2010-07-21 05:47:49 +00001327 CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1328
1329 CGF.EmitBlock(RethrowBB);
1330 if (SavedExnVar) {
John McCall882987f2013-02-28 19:01:20 +00001331 CGF.EmitRuntimeCallOrInvoke(RethrowFn,
John McCall7f416cc2015-09-08 08:05:57 +00001332 CGF.Builder.CreateAlignedLoad(SavedExnVar, CGF.getPointerAlign()));
John McCall906da4b2010-07-21 05:47:49 +00001333 } else {
John McCall882987f2013-02-28 19:01:20 +00001334 CGF.EmitRuntimeCallOrInvoke(RethrowFn);
John McCall906da4b2010-07-21 05:47:49 +00001335 }
1336 CGF.Builder.CreateUnreachable();
1337
1338 CGF.EmitBlock(ContBB);
John McCallcebe0ca2010-08-11 00:16:14 +00001339
1340 // Restore the cleanup destination.
1341 CGF.Builder.CreateStore(SavedCleanupDest,
1342 CGF.getNormalCleanupDestSlot());
John McCall906da4b2010-07-21 05:47:49 +00001343 }
1344
1345 // Leave the end-catch cleanup. As an optimization, pretend that
1346 // the fallthrough path was inaccessible; we've dynamically proven
1347 // that we're not in the EH case along that path.
1348 if (EndCatchFn) {
1349 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1350 CGF.PopCleanupBlock();
1351 CGF.Builder.restoreIP(SavedIP);
1352 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001353
John McCall906da4b2010-07-21 05:47:49 +00001354 // Now make sure we actually have an insertion point or the
1355 // cleanup gods will hate us.
1356 CGF.EnsureInsertPoint();
1357 }
1358 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00001359} // end anonymous namespace
John McCall1e670402010-07-21 00:52:03 +00001360
John McCallbd309292010-07-06 01:34:17 +00001361/// Enters a finally block for an implementation using zero-cost
1362/// exceptions. This is mostly general, but hard-codes some
1363/// language/ABI-specific behavior in the catch-all sections.
James Y Knight9871db02019-02-05 16:42:33 +00001364void CodeGenFunction::FinallyInfo::enter(CodeGenFunction &CGF, const Stmt *body,
1365 llvm::FunctionCallee beginCatchFn,
1366 llvm::FunctionCallee endCatchFn,
1367 llvm::FunctionCallee rethrowFn) {
1368 assert((!!beginCatchFn) == (!!endCatchFn) &&
John McCallbd309292010-07-06 01:34:17 +00001369 "begin/end catch functions not paired");
John McCall6b0feb72011-06-22 02:32:12 +00001370 assert(rethrowFn && "rethrow function is required");
1371
1372 BeginCatchFn = beginCatchFn;
Mike Stumpaff69af2009-12-09 03:35:49 +00001373
John McCallbd309292010-07-06 01:34:17 +00001374 // The rethrow function has one of the following two types:
1375 // void (*)()
1376 // void (*)(void*)
1377 // In the latter case we need to pass it the exception object.
1378 // But we can't use the exception slot because the @finally might
1379 // have a landing pad (which would overwrite the exception slot).
James Y Knight9871db02019-02-05 16:42:33 +00001380 llvm::FunctionType *rethrowFnTy = rethrowFn.getFunctionType();
Craig Topper8a13c412014-05-21 05:09:00 +00001381 SavedExnVar = nullptr;
John McCall6b0feb72011-06-22 02:32:12 +00001382 if (rethrowFnTy->getNumParams())
1383 SavedExnVar = CGF.CreateTempAlloca(CGF.Int8PtrTy, "finally.exn");
Mike Stumpaff69af2009-12-09 03:35:49 +00001384
John McCallbd309292010-07-06 01:34:17 +00001385 // A finally block is a statement which must be executed on any edge
1386 // out of a given scope. Unlike a cleanup, the finally block may
1387 // contain arbitrary control flow leading out of itself. In
1388 // addition, finally blocks should always be executed, even if there
1389 // are no catch handlers higher on the stack. Therefore, we
1390 // surround the protected scope with a combination of a normal
1391 // cleanup (to catch attempts to break out of the block via normal
1392 // control flow) and an EH catch-all (semantically "outside" any try
1393 // statement to which the finally block might have been attached).
1394 // The finally block itself is generated in the context of a cleanup
1395 // which conditionally leaves the catch-all.
John McCall21886962010-04-21 10:05:39 +00001396
John McCallbd309292010-07-06 01:34:17 +00001397 // Jump destination for performing the finally block on an exception
1398 // edge. We'll never actually reach this block, so unreachable is
1399 // fine.
John McCall6b0feb72011-06-22 02:32:12 +00001400 RethrowDest = CGF.getJumpDestInCurrentScope(CGF.getUnreachableBlock());
John McCall21886962010-04-21 10:05:39 +00001401
John McCallbd309292010-07-06 01:34:17 +00001402 // Whether the finally block is being executed for EH purposes.
John McCall6b0feb72011-06-22 02:32:12 +00001403 ForEHVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "finally.for-eh");
John McCall7f416cc2015-09-08 08:05:57 +00001404 CGF.Builder.CreateFlagStore(false, ForEHVar);
Mike Stumpaff69af2009-12-09 03:35:49 +00001405
John McCallbd309292010-07-06 01:34:17 +00001406 // Enter a normal cleanup which will perform the @finally block.
John McCall6b0feb72011-06-22 02:32:12 +00001407 CGF.EHStack.pushCleanup<PerformFinally>(NormalCleanup, body,
1408 ForEHVar, endCatchFn,
1409 rethrowFn, SavedExnVar);
John McCallbd309292010-07-06 01:34:17 +00001410
1411 // Enter a catch-all scope.
John McCall6b0feb72011-06-22 02:32:12 +00001412 llvm::BasicBlock *catchBB = CGF.createBasicBlock("finally.catchall");
1413 EHCatchScope *catchScope = CGF.EHStack.pushCatch(1);
1414 catchScope->setCatchAllHandler(0, catchBB);
John McCallbd309292010-07-06 01:34:17 +00001415}
1416
John McCall6b0feb72011-06-22 02:32:12 +00001417void CodeGenFunction::FinallyInfo::exit(CodeGenFunction &CGF) {
John McCallbd309292010-07-06 01:34:17 +00001418 // Leave the finally catch-all.
John McCall6b0feb72011-06-22 02:32:12 +00001419 EHCatchScope &catchScope = cast<EHCatchScope>(*CGF.EHStack.begin());
1420 llvm::BasicBlock *catchBB = catchScope.getHandler(0).Block;
John McCall8e4c74b2011-08-11 02:22:43 +00001421
1422 CGF.popCatchScope();
John McCallbd309292010-07-06 01:34:17 +00001423
John McCall6b0feb72011-06-22 02:32:12 +00001424 // If there are any references to the catch-all block, emit it.
1425 if (catchBB->use_empty()) {
1426 delete catchBB;
1427 } else {
1428 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveAndClearIP();
1429 CGF.EmitBlock(catchBB);
John McCallbd309292010-07-06 01:34:17 +00001430
Craig Topper8a13c412014-05-21 05:09:00 +00001431 llvm::Value *exn = nullptr;
John McCallbd309292010-07-06 01:34:17 +00001432
John McCall6b0feb72011-06-22 02:32:12 +00001433 // If there's a begin-catch function, call it.
1434 if (BeginCatchFn) {
Bill Wendling79a70e42011-09-15 18:57:19 +00001435 exn = CGF.getExceptionFromSlot();
John McCall882987f2013-02-28 19:01:20 +00001436 CGF.EmitNounwindRuntimeCall(BeginCatchFn, exn);
John McCall6b0feb72011-06-22 02:32:12 +00001437 }
1438
1439 // If we need to remember the exception pointer to rethrow later, do so.
1440 if (SavedExnVar) {
Bill Wendling79a70e42011-09-15 18:57:19 +00001441 if (!exn) exn = CGF.getExceptionFromSlot();
John McCall7f416cc2015-09-08 08:05:57 +00001442 CGF.Builder.CreateAlignedStore(exn, SavedExnVar, CGF.getPointerAlign());
John McCall6b0feb72011-06-22 02:32:12 +00001443 }
1444
1445 // Tell the cleanups in the finally block that we're do this for EH.
John McCall7f416cc2015-09-08 08:05:57 +00001446 CGF.Builder.CreateFlagStore(true, ForEHVar);
John McCall6b0feb72011-06-22 02:32:12 +00001447
1448 // Thread a jump through the finally cleanup.
1449 CGF.EmitBranchThroughCleanup(RethrowDest);
1450
1451 CGF.Builder.restoreIP(savedIP);
1452 }
1453
1454 // Finally, leave the @finally cleanup.
1455 CGF.PopCleanupBlock();
John McCallbd309292010-07-06 01:34:17 +00001456}
1457
1458llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
1459 if (TerminateLandingPad)
1460 return TerminateLandingPad;
1461
1462 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1463
1464 // This will get inserted at the end of the function.
1465 TerminateLandingPad = createBasicBlock("terminate.lpad");
1466 Builder.SetInsertPoint(TerminateLandingPad);
1467
1468 // Tell the backend that this is a landing pad.
Reid Klecknerdeeddec2015-02-05 18:56:03 +00001469 const EHPersonality &Personality = EHPersonality::get(*this);
David Majnemerfcbdb6e2015-06-17 20:53:19 +00001470
1471 if (!CurFn->hasPersonalityFn())
1472 CurFn->setPersonalityFn(getOpaquePersonalityFn(CGM, Personality));
1473
Serge Guelton1d993272017-05-09 19:31:30 +00001474 llvm::LandingPadInst *LPadInst =
1475 Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty), 0);
Bill Wendlingf0724e82011-09-19 20:31:14 +00001476 LPadInst->addClause(getCatchAllValue(*this));
John McCallbd309292010-07-06 01:34:17 +00001477
Hans Wennborgdcfba332015-10-06 23:40:43 +00001478 llvm::Value *Exn = nullptr;
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00001479 if (getLangOpts().CPlusPlus)
1480 Exn = Builder.CreateExtractValue(LPadInst, 0);
1481 llvm::CallInst *terminateCall =
1482 CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
John McCalle142ad52013-02-12 03:51:46 +00001483 terminateCall->setDoesNotReturn();
John McCallad7c5c12011-02-08 08:22:06 +00001484 Builder.CreateUnreachable();
Mike Stumpaff69af2009-12-09 03:35:49 +00001485
John McCallbd309292010-07-06 01:34:17 +00001486 // Restore the saved insertion state.
1487 Builder.restoreIP(SavedIP);
John McCalldac3ea62010-04-30 00:06:43 +00001488
John McCallbd309292010-07-06 01:34:17 +00001489 return TerminateLandingPad;
Mike Stumpaff69af2009-12-09 03:35:49 +00001490}
Mike Stump2b488872009-12-09 22:59:31 +00001491
1492llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
Mike Stumpf5cbb082009-12-10 00:02:42 +00001493 if (TerminateHandler)
1494 return TerminateHandler;
1495
John McCallbd309292010-07-06 01:34:17 +00001496 // Set up the terminate handler. This block is inserted at the very
1497 // end of the function by FinishFunction.
Mike Stumpf5cbb082009-12-10 00:02:42 +00001498 TerminateHandler = createBasicBlock("terminate.handler");
Reid Kleckner06f19a02018-01-02 21:34:16 +00001499 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
John McCallbd309292010-07-06 01:34:17 +00001500 Builder.SetInsertPoint(TerminateHandler);
Reid Kleckner06f19a02018-01-02 21:34:16 +00001501
David Majnemerfeeefb22015-12-14 18:34:18 +00001502 llvm::Value *Exn = nullptr;
Reid Kleckner06f19a02018-01-02 21:34:16 +00001503 if (getLangOpts().CPlusPlus)
1504 Exn = getExceptionFromSlot();
David Majnemerfeeefb22015-12-14 18:34:18 +00001505 llvm::CallInst *terminateCall =
1506 CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
1507 terminateCall->setDoesNotReturn();
1508 Builder.CreateUnreachable();
Mike Stump2b488872009-12-09 22:59:31 +00001509
John McCall21886962010-04-21 10:05:39 +00001510 // Restore the saved insertion state.
John McCallbd309292010-07-06 01:34:17 +00001511 Builder.restoreIP(SavedIP);
Mike Stump25b20fc2009-12-09 23:31:35 +00001512
Mike Stump2b488872009-12-09 22:59:31 +00001513 return TerminateHandler;
1514}
John McCallbd309292010-07-06 01:34:17 +00001515
Reid Kleckner06f19a02018-01-02 21:34:16 +00001516llvm::BasicBlock *CodeGenFunction::getTerminateFunclet() {
1517 assert(EHPersonality::get(*this).usesFuncletPads() &&
1518 "use getTerminateLandingPad for non-funclet EH");
1519
1520 llvm::BasicBlock *&TerminateFunclet = TerminateFunclets[CurrentFuncletPad];
1521 if (TerminateFunclet)
1522 return TerminateFunclet;
1523
1524 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1525
1526 // Set up the terminate handler. This block is inserted at the very
1527 // end of the function by FinishFunction.
1528 TerminateFunclet = createBasicBlock("terminate.handler");
1529 Builder.SetInsertPoint(TerminateFunclet);
1530
1531 // Create the cleanuppad using the current parent pad as its token. Use 'none'
1532 // if this is a top-level terminate scope, which is the common case.
1533 SaveAndRestore<llvm::Instruction *> RestoreCurrentFuncletPad(
1534 CurrentFuncletPad);
1535 llvm::Value *ParentPad = CurrentFuncletPad;
1536 if (!ParentPad)
1537 ParentPad = llvm::ConstantTokenNone::get(CGM.getLLVMContext());
1538 CurrentFuncletPad = Builder.CreateCleanupPad(ParentPad);
1539
1540 // Emit the __std_terminate call.
Heejin Ahnc6479192018-05-31 22:18:13 +00001541 llvm::Value *Exn = nullptr;
1542 // In case of wasm personality, we need to pass the exception value to
1543 // __clang_call_terminate function.
1544 if (getLangOpts().CPlusPlus &&
1545 EHPersonality::get(*this).isWasmPersonality()) {
James Y Knight8799cae2019-02-03 21:53:49 +00001546 llvm::Function *GetExnFn =
Heejin Ahnc6479192018-05-31 22:18:13 +00001547 CGM.getIntrinsic(llvm::Intrinsic::wasm_get_exception);
1548 Exn = Builder.CreateCall(GetExnFn, CurrentFuncletPad);
1549 }
Reid Kleckner06f19a02018-01-02 21:34:16 +00001550 llvm::CallInst *terminateCall =
Heejin Ahnc6479192018-05-31 22:18:13 +00001551 CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
Reid Kleckner06f19a02018-01-02 21:34:16 +00001552 terminateCall->setDoesNotReturn();
1553 Builder.CreateUnreachable();
1554
1555 // Restore the saved insertion state.
1556 Builder.restoreIP(SavedIP);
1557
1558 return TerminateFunclet;
1559}
1560
David Chisnall9a837be2012-11-07 16:50:40 +00001561llvm::BasicBlock *CodeGenFunction::getEHResumeBlock(bool isCleanup) {
John McCall8e4c74b2011-08-11 02:22:43 +00001562 if (EHResumeBlock) return EHResumeBlock;
John McCallad5d61e2010-07-23 21:56:41 +00001563
1564 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1565
1566 // We emit a jump to a notional label at the outermost unwind state.
John McCall8e4c74b2011-08-11 02:22:43 +00001567 EHResumeBlock = createBasicBlock("eh.resume");
1568 Builder.SetInsertPoint(EHResumeBlock);
John McCallad5d61e2010-07-23 21:56:41 +00001569
Reid Klecknerdeeddec2015-02-05 18:56:03 +00001570 const EHPersonality &Personality = EHPersonality::get(*this);
John McCallad5d61e2010-07-23 21:56:41 +00001571
1572 // This can always be a call because we necessarily didn't find
1573 // anything on the EH stack which needs our help.
Benjamin Kramer793bd552012-02-08 12:41:24 +00001574 const char *RethrowName = Personality.CatchallRethrowFn;
Craig Topper8a13c412014-05-21 05:09:00 +00001575 if (RethrowName != nullptr && !isCleanup) {
John McCall882987f2013-02-28 19:01:20 +00001576 EmitRuntimeCall(getCatchallRethrowFn(CGM, RethrowName),
Nico Weberff62a6a2015-02-26 22:34:33 +00001577 getExceptionFromSlot())->setDoesNotReturn();
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001578 Builder.CreateUnreachable();
1579 Builder.restoreIP(SavedIP);
1580 return EHResumeBlock;
John McCall9b382dd2011-05-28 21:13:02 +00001581 }
1582
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001583 // Recreate the landingpad's return value for the 'resume' instruction.
1584 llvm::Value *Exn = getExceptionFromSlot();
1585 llvm::Value *Sel = getSelectorFromSlot();
John McCallad5d61e2010-07-23 21:56:41 +00001586
Serge Guelton1d993272017-05-09 19:31:30 +00001587 llvm::Type *LPadType = llvm::StructType::get(Exn->getType(), Sel->getType());
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001588 llvm::Value *LPadVal = llvm::UndefValue::get(LPadType);
1589 LPadVal = Builder.CreateInsertValue(LPadVal, Exn, 0, "lpad.val");
1590 LPadVal = Builder.CreateInsertValue(LPadVal, Sel, 1, "lpad.val");
1591
1592 Builder.CreateResume(LPadVal);
John McCallad5d61e2010-07-23 21:56:41 +00001593 Builder.restoreIP(SavedIP);
John McCall8e4c74b2011-08-11 02:22:43 +00001594 return EHResumeBlock;
John McCallad5d61e2010-07-23 21:56:41 +00001595}
Reid Kleckner543a16c2013-09-16 21:46:30 +00001596
1597void CodeGenFunction::EmitSEHTryStmt(const SEHTryStmt &S) {
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001598 EnterSEHTryStmt(S);
Reid Klecknera5930002015-02-11 21:40:48 +00001599 {
Nico Weber5779f842015-02-12 23:16:11 +00001600 JumpDest TryExit = getJumpDestInCurrentScope("__try.__leave");
Nico Weber5779f842015-02-12 23:16:11 +00001601
Reid Kleckner11c033e2015-02-12 23:40:45 +00001602 SEHTryEpilogueStack.push_back(&TryExit);
Reid Klecknera5930002015-02-11 21:40:48 +00001603 EmitStmt(S.getTryBlock());
Reid Kleckner11c033e2015-02-12 23:40:45 +00001604 SEHTryEpilogueStack.pop_back();
Nico Weber5779f842015-02-12 23:16:11 +00001605
1606 if (!TryExit.getBlock()->use_empty())
1607 EmitBlock(TryExit.getBlock(), /*IsFinished=*/true);
1608 else
1609 delete TryExit.getBlock();
Reid Klecknera5930002015-02-11 21:40:48 +00001610 }
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001611 ExitSEHTryStmt(S);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001612}
1613
1614namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001615struct PerformSEHFinally final : EHScopeStack::Cleanup {
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001616 llvm::Function *OutlinedFinally;
Reid Kleckner55391522015-10-08 21:14:56 +00001617 PerformSEHFinally(llvm::Function *OutlinedFinally)
1618 : OutlinedFinally(OutlinedFinally) {}
Reid Kleckneraca01db2015-02-04 22:37:07 +00001619
Reid Kleckner1d59f992015-01-22 01:36:17 +00001620 void Emit(CodeGenFunction &CGF, Flags F) override {
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001621 ASTContext &Context = CGF.getContext();
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001622 CodeGenModule &CGM = CGF.CGM;
Reid Kleckner65870442015-06-09 17:47:50 +00001623
Reid Klecknerd0d9a1f2015-07-01 17:10:10 +00001624 CallArgList Args;
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001625
1626 // Compute the two argument values.
1627 QualType ArgTys[2] = {Context.UnsignedCharTy, Context.VoidPtrTy};
Sanjin Sijariccfa2a2a2019-01-16 07:39:44 +00001628 llvm::Value *FP = nullptr;
1629 // If CFG.IsOutlinedSEHHelper is true, then we are within a finally block.
1630 if (CGF.IsOutlinedSEHHelper) {
1631 FP = &CGF.CurFn->arg_begin()[1];
1632 } else {
James Y Knight8799cae2019-02-03 21:53:49 +00001633 llvm::Function *LocalAddrFn =
Sanjin Sijariccfa2a2a2019-01-16 07:39:44 +00001634 CGM.getIntrinsic(llvm::Intrinsic::localaddress);
1635 FP = CGF.Builder.CreateCall(LocalAddrFn);
1636 }
1637
Reid Klecknereb11c412015-07-01 21:00:00 +00001638 llvm::Value *IsForEH =
1639 llvm::ConstantInt::get(CGF.ConvertType(ArgTys[0]), F.isForEHCleanup());
1640 Args.add(RValue::get(IsForEH), ArgTys[0]);
1641 Args.add(RValue::get(FP), ArgTys[1]);
Reid Klecknerd0d9a1f2015-07-01 17:10:10 +00001642
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001643 // Arrange a two-arg function info and type.
Reid Klecknereb11c412015-07-01 21:00:00 +00001644 const CGFunctionInfo &FnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00001645 CGM.getTypes().arrangeBuiltinFunctionCall(Context.VoidTy, Args);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001646
John McCallb92ab1a2016-10-26 23:46:34 +00001647 auto Callee = CGCallee::forDirect(OutlinedFinally);
1648 CGF.EmitCall(FnInfo, Callee, ReturnValueSlot(), Args);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001649 }
1650};
Hans Wennborgdcfba332015-10-06 23:40:43 +00001651} // end anonymous namespace
Reid Kleckner1d59f992015-01-22 01:36:17 +00001652
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001653namespace {
1654/// Find all local variable captures in the statement.
1655struct CaptureFinder : ConstStmtVisitor<CaptureFinder> {
1656 CodeGenFunction &ParentCGF;
1657 const VarDecl *ParentThis;
John McCall0a490152015-09-08 21:15:22 +00001658 llvm::SmallSetVector<const VarDecl *, 4> Captures;
John McCall7f416cc2015-09-08 08:05:57 +00001659 Address SEHCodeSlot = Address::invalid();
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001660 CaptureFinder(CodeGenFunction &ParentCGF, const VarDecl *ParentThis)
1661 : ParentCGF(ParentCGF), ParentThis(ParentThis) {}
1662
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001663 // Return true if we need to do any capturing work.
1664 bool foundCaptures() {
John McCall7f416cc2015-09-08 08:05:57 +00001665 return !Captures.empty() || SEHCodeSlot.isValid();
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001666 }
1667
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001668 void Visit(const Stmt *S) {
1669 // See if this is a capture, then recurse.
1670 ConstStmtVisitor<CaptureFinder>::Visit(S);
1671 for (const Stmt *Child : S->children())
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001672 if (Child)
1673 Visit(Child);
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001674 }
1675
1676 void VisitDeclRefExpr(const DeclRefExpr *E) {
1677 // If this is already a capture, just make sure we capture 'this'.
1678 if (E->refersToEnclosingVariableOrCapture()) {
John McCall0a490152015-09-08 21:15:22 +00001679 Captures.insert(ParentThis);
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001680 return;
1681 }
1682
1683 const auto *D = dyn_cast<VarDecl>(E->getDecl());
1684 if (D && D->isLocalVarDeclOrParm() && D->hasLocalStorage())
John McCall0a490152015-09-08 21:15:22 +00001685 Captures.insert(D);
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001686 }
1687
1688 void VisitCXXThisExpr(const CXXThisExpr *E) {
John McCall0a490152015-09-08 21:15:22 +00001689 Captures.insert(ParentThis);
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001690 }
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001691
1692 void VisitCallExpr(const CallExpr *E) {
1693 // We only need to add parent frame allocations for these builtins in x86.
1694 if (ParentCGF.getTarget().getTriple().getArch() != llvm::Triple::x86)
1695 return;
1696
1697 unsigned ID = E->getBuiltinCallee();
1698 switch (ID) {
1699 case Builtin::BI__exception_code:
1700 case Builtin::BI_exception_code:
1701 // This is the simple case where we are the outermost finally. All we
1702 // have to do here is make sure we escape this and recover it in the
1703 // outlined handler.
John McCall7f416cc2015-09-08 08:05:57 +00001704 if (!SEHCodeSlot.isValid())
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001705 SEHCodeSlot = ParentCGF.SEHCodeSlotStack.back();
1706 break;
1707 }
1708 }
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001709};
Hans Wennborgdcfba332015-10-06 23:40:43 +00001710} // end anonymous namespace
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001711
Reid Kleckner39329d57b2015-12-16 00:26:37 +00001712Address CodeGenFunction::recoverAddrOfEscapedLocal(CodeGenFunction &ParentCGF,
1713 Address ParentVar,
1714 llvm::Value *ParentFP) {
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001715 llvm::CallInst *RecoverCall = nullptr;
John McCall7f416cc2015-09-08 08:05:57 +00001716 CGBuilderTy Builder(*this, AllocaInsertPt);
1717 if (auto *ParentAlloca = dyn_cast<llvm::AllocaInst>(ParentVar.getPointer())) {
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001718 // Mark the variable escaped if nobody else referenced it and compute the
Reid Kleckner98cb8ba2015-07-07 22:26:07 +00001719 // localescape index.
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001720 auto InsertPair = ParentCGF.EscapedLocals.insert(
1721 std::make_pair(ParentAlloca, ParentCGF.EscapedLocals.size()));
1722 int FrameEscapeIdx = InsertPair.first->second;
Reid Kleckner98cb8ba2015-07-07 22:26:07 +00001723 // call i8* @llvm.localrecover(i8* bitcast(@parentFn), i8* %fp, i32 N)
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001724 llvm::Function *FrameRecoverFn = llvm::Intrinsic::getDeclaration(
Reid Kleckner98cb8ba2015-07-07 22:26:07 +00001725 &CGM.getModule(), llvm::Intrinsic::localrecover);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001726 llvm::Constant *ParentI8Fn =
1727 llvm::ConstantExpr::getBitCast(ParentCGF.CurFn, Int8PtrTy);
1728 RecoverCall = Builder.CreateCall(
1729 FrameRecoverFn, {ParentI8Fn, ParentFP,
1730 llvm::ConstantInt::get(Int32Ty, FrameEscapeIdx)});
1731
1732 } else {
1733 // If the parent didn't have an alloca, we're doing some nested outlining.
Reid Kleckner98cb8ba2015-07-07 22:26:07 +00001734 // Just clone the existing localrecover call, but tweak the FP argument to
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001735 // use our FP value. All other arguments are constants.
1736 auto *ParentRecover =
John McCall7f416cc2015-09-08 08:05:57 +00001737 cast<llvm::IntrinsicInst>(ParentVar.getPointer()->stripPointerCasts());
Reid Kleckner98cb8ba2015-07-07 22:26:07 +00001738 assert(ParentRecover->getIntrinsicID() == llvm::Intrinsic::localrecover &&
1739 "expected alloca or localrecover in parent LocalDeclMap");
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001740 RecoverCall = cast<llvm::CallInst>(ParentRecover->clone());
1741 RecoverCall->setArgOperand(1, ParentFP);
1742 RecoverCall->insertBefore(AllocaInsertPt);
1743 }
1744
1745 // Bitcast the variable, rename it, and insert it in the local decl map.
1746 llvm::Value *ChildVar =
John McCall7f416cc2015-09-08 08:05:57 +00001747 Builder.CreateBitCast(RecoverCall, ParentVar.getType());
1748 ChildVar->setName(ParentVar.getName());
1749 return Address(ChildVar, ParentVar.getAlignment());
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001750}
1751
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001752void CodeGenFunction::EmitCapturedLocals(CodeGenFunction &ParentCGF,
Reid Kleckner0b9bbbf2015-06-09 17:49:42 +00001753 const Stmt *OutlinedStmt,
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001754 bool IsFilter) {
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001755 // Find all captures in the Stmt.
1756 CaptureFinder Finder(ParentCGF, ParentCGF.CXXABIThisDecl);
1757 Finder.Visit(OutlinedStmt);
1758
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001759 // We can exit early on x86_64 when there are no captures. We just have to
1760 // save the exception code in filters so that __exception_code() works.
1761 if (!Finder.foundCaptures() &&
1762 CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
1763 if (IsFilter)
1764 EmitSEHExceptionCodeSave(ParentCGF, nullptr, nullptr);
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001765 return;
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001766 }
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001767
Reid Kleckner39329d57b2015-12-16 00:26:37 +00001768 llvm::Value *EntryFP = nullptr;
1769 CGBuilderTy Builder(CGM, AllocaInsertPt);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001770 if (IsFilter && CGM.getTarget().getTriple().getArch() == llvm::Triple::x86) {
1771 // 32-bit SEH filters need to be careful about FP recovery. The end of the
1772 // EH registration is passed in as the EBP physical register. We can
Reid Kleckner39329d57b2015-12-16 00:26:37 +00001773 // recover that with llvm.frameaddress(1).
1774 EntryFP = Builder.CreateCall(
Christudasan Devadasan8c5e6fa2019-07-22 12:50:30 +00001775 CGM.getIntrinsic(llvm::Intrinsic::frameaddress, AllocaInt8PtrTy),
1776 {Builder.getInt32(1)});
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001777 } else {
1778 // Otherwise, for x64 and 32-bit finally functions, the parent FP is the
1779 // second parameter.
1780 auto AI = CurFn->arg_begin();
1781 ++AI;
Reid Kleckner39329d57b2015-12-16 00:26:37 +00001782 EntryFP = &*AI;
1783 }
1784
1785 llvm::Value *ParentFP = EntryFP;
1786 if (IsFilter) {
1787 // Given whatever FP the runtime provided us in EntryFP, recover the true
1788 // frame pointer of the parent function. We only need to do this in filters,
1789 // since finally funclets recover the parent FP for us.
1790 llvm::Function *RecoverFPIntrin =
Eli Friedmanc4c43b22019-01-16 00:50:44 +00001791 CGM.getIntrinsic(llvm::Intrinsic::eh_recoverfp);
Reid Kleckner39329d57b2015-12-16 00:26:37 +00001792 llvm::Constant *ParentI8Fn =
1793 llvm::ConstantExpr::getBitCast(ParentCGF.CurFn, Int8PtrTy);
1794 ParentFP = Builder.CreateCall(RecoverFPIntrin, {ParentI8Fn, EntryFP});
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001795 }
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001796
Reid Kleckner98cb8ba2015-07-07 22:26:07 +00001797 // Create llvm.localrecover calls for all captures.
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001798 for (const VarDecl *VD : Finder.Captures) {
1799 if (isa<ImplicitParamDecl>(VD)) {
1800 CGM.ErrorUnsupported(VD, "'this' captured by SEH");
1801 CXXThisValue = llvm::UndefValue::get(ConvertTypeForMem(VD->getType()));
1802 continue;
1803 }
1804 if (VD->getType()->isVariablyModifiedType()) {
1805 CGM.ErrorUnsupported(VD, "VLA captured by SEH");
1806 continue;
1807 }
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001808 assert((isa<ImplicitParamDecl>(VD) || VD->isLocalVarDeclOrParm()) &&
1809 "captured non-local variable");
1810
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001811 // If this decl hasn't been declared yet, it will be declared in the
1812 // OutlinedStmt.
1813 auto I = ParentCGF.LocalDeclMap.find(VD);
1814 if (I == ParentCGF.LocalDeclMap.end())
1815 continue;
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001816
John McCall7f416cc2015-09-08 08:05:57 +00001817 Address ParentVar = I->second;
Reid Kleckner39329d57b2015-12-16 00:26:37 +00001818 setAddrOfLocalVar(
1819 VD, recoverAddrOfEscapedLocal(ParentCGF, ParentVar, ParentFP));
Nico Webere4f974c2015-07-02 06:10:53 +00001820 }
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001821
John McCall7f416cc2015-09-08 08:05:57 +00001822 if (Finder.SEHCodeSlot.isValid()) {
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001823 SEHCodeSlotStack.push_back(
1824 recoverAddrOfEscapedLocal(ParentCGF, Finder.SEHCodeSlot, ParentFP));
1825 }
1826
1827 if (IsFilter)
Reid Kleckner39329d57b2015-12-16 00:26:37 +00001828 EmitSEHExceptionCodeSave(ParentCGF, ParentFP, EntryFP);
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001829}
1830
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001831/// Arrange a function prototype that can be called by Windows exception
1832/// handling personalities. On Win64, the prototype looks like:
1833/// RetTy func(void *EHPtrs, void *ParentFP);
1834void CodeGenFunction::startOutlinedSEHHelper(CodeGenFunction &ParentCGF,
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001835 bool IsFilter,
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001836 const Stmt *OutlinedStmt) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001837 SourceLocation StartLoc = OutlinedStmt->getBeginLoc();
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001838
1839 // Get the mangled function name.
1840 SmallString<128> Name;
1841 {
1842 llvm::raw_svector_ostream OS(Name);
David Chisnall93ce0182018-08-10 12:53:13 +00001843 const NamedDecl *ParentSEHFn = ParentCGF.CurSEHParent;
David Majnemer25eb1652016-03-01 19:42:53 +00001844 assert(ParentSEHFn && "No CurSEHParent!");
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001845 MangleContext &Mangler = CGM.getCXXABI().getMangleContext();
1846 if (IsFilter)
David Majnemer25eb1652016-03-01 19:42:53 +00001847 Mangler.mangleSEHFilterExpression(ParentSEHFn, OS);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001848 else
David Majnemer25eb1652016-03-01 19:42:53 +00001849 Mangler.mangleSEHFinallyBlock(ParentSEHFn, OS);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001850 }
1851
1852 FunctionArgList Args;
1853 if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86 || !IsFilter) {
1854 // All SEH finally functions take two parameters. Win64 filters take two
1855 // parameters. Win32 filters take no parameters.
1856 if (IsFilter) {
1857 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00001858 getContext(), /*DC=*/nullptr, StartLoc,
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001859 &getContext().Idents.get("exception_pointers"),
Alexey Bataev56223232017-06-09 13:40:18 +00001860 getContext().VoidPtrTy, ImplicitParamDecl::Other));
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001861 } else {
1862 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00001863 getContext(), /*DC=*/nullptr, StartLoc,
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001864 &getContext().Idents.get("abnormal_termination"),
Alexey Bataev56223232017-06-09 13:40:18 +00001865 getContext().UnsignedCharTy, ImplicitParamDecl::Other));
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001866 }
1867 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00001868 getContext(), /*DC=*/nullptr, StartLoc,
1869 &getContext().Idents.get("frame_pointer"), getContext().VoidPtrTy,
1870 ImplicitParamDecl::Other));
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001871 }
1872
1873 QualType RetTy = IsFilter ? getContext().LongTy : getContext().VoidTy;
1874
John McCallc56a8b32016-03-11 04:30:31 +00001875 const CGFunctionInfo &FnInfo =
1876 CGM.getTypes().arrangeBuiltinFunctionDeclaration(RetTy, Args);
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001877
Reid Kleckner1d59f992015-01-22 01:36:17 +00001878 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001879 llvm::Function *Fn = llvm::Function::Create(
1880 FnTy, llvm::GlobalValue::InternalLinkage, Name.str(), &CGM.getModule());
Reid Kleckner1d59f992015-01-22 01:36:17 +00001881
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001882 IsOutlinedSEHHelper = true;
Nico Weberf2a39a72015-04-13 20:03:03 +00001883
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001884 StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001885 OutlinedStmt->getBeginLoc(), OutlinedStmt->getBeginLoc());
David Majnemer25eb1652016-03-01 19:42:53 +00001886 CurSEHParent = ParentCGF.CurSEHParent;
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001887
Erich Keanede6480a32018-11-13 15:48:08 +00001888 CGM.SetLLVMFunctionAttributes(GlobalDecl(), FnInfo, CurFn);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001889 EmitCapturedLocals(ParentCGF, OutlinedStmt, IsFilter);
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001890}
1891
1892/// Create a stub filter function that will ultimately hold the code of the
1893/// filter expression. The EH preparation passes in LLVM will outline the code
1894/// from the main function body into this stub.
1895llvm::Function *
1896CodeGenFunction::GenerateSEHFilterFunction(CodeGenFunction &ParentCGF,
1897 const SEHExceptStmt &Except) {
1898 const Expr *FilterExpr = Except.getFilterExpr();
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001899 startOutlinedSEHHelper(ParentCGF, true, FilterExpr);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001900
1901 // Emit the original filter expression, convert to i32, and return.
1902 llvm::Value *R = EmitScalarExpr(FilterExpr);
David Majnemer2ccba832015-04-17 06:57:25 +00001903 R = Builder.CreateIntCast(R, ConvertType(getContext().LongTy),
Reid Kleckner1d59f992015-01-22 01:36:17 +00001904 FilterExpr->getType()->isSignedIntegerType());
1905 Builder.CreateStore(R, ReturnValue);
1906
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001907 FinishFunction(FilterExpr->getEndLoc());
Reid Kleckner1d59f992015-01-22 01:36:17 +00001908
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001909 return CurFn;
1910}
1911
1912llvm::Function *
1913CodeGenFunction::GenerateSEHFinallyFunction(CodeGenFunction &ParentCGF,
1914 const SEHFinallyStmt &Finally) {
1915 const Stmt *FinallyBlock = Finally.getBlock();
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001916 startOutlinedSEHHelper(ParentCGF, false, FinallyBlock);
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001917
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001918 // Emit the original filter expression, convert to i32, and return.
1919 EmitStmt(FinallyBlock);
1920
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001921 FinishFunction(FinallyBlock->getEndLoc());
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001922
1923 return CurFn;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001924}
1925
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001926void CodeGenFunction::EmitSEHExceptionCodeSave(CodeGenFunction &ParentCGF,
1927 llvm::Value *ParentFP,
Reid Kleckner39329d57b2015-12-16 00:26:37 +00001928 llvm::Value *EntryFP) {
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001929 // Get the pointer to the EXCEPTION_POINTERS struct. This is returned by the
1930 // __exception_info intrinsic.
1931 if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
1932 // On Win64, the info is passed as the first parameter to the filter.
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00001933 SEHInfo = &*CurFn->arg_begin();
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001934 SEHCodeSlotStack.push_back(
1935 CreateMemTemp(getContext().IntTy, "__exception_code"));
1936 } else {
1937 // On Win32, the EBP on entry to the filter points to the end of an
1938 // exception registration object. It contains 6 32-bit fields, and the info
1939 // pointer is stored in the second field. So, GEP 20 bytes backwards and
1940 // load the pointer.
Reid Kleckner39329d57b2015-12-16 00:26:37 +00001941 SEHInfo = Builder.CreateConstInBoundsGEP1_32(Int8Ty, EntryFP, -20);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001942 SEHInfo = Builder.CreateBitCast(SEHInfo, Int8PtrTy->getPointerTo());
John McCall7f416cc2015-09-08 08:05:57 +00001943 SEHInfo = Builder.CreateAlignedLoad(Int8PtrTy, SEHInfo, getPointerAlign());
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001944 SEHCodeSlotStack.push_back(recoverAddrOfEscapedLocal(
1945 ParentCGF, ParentCGF.SEHCodeSlotStack.back(), ParentFP));
1946 }
1947
Reid Kleckner1d59f992015-01-22 01:36:17 +00001948 // Save the exception code in the exception slot to unify exception access in
1949 // the filter function and the landing pad.
1950 // struct EXCEPTION_POINTERS {
1951 // EXCEPTION_RECORD *ExceptionRecord;
1952 // CONTEXT *ContextRecord;
1953 // };
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001954 // int exceptioncode = exception_pointers->ExceptionRecord->ExceptionCode;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001955 llvm::Type *RecordTy = CGM.Int32Ty->getPointerTo();
Serge Guelton1d993272017-05-09 19:31:30 +00001956 llvm::Type *PtrsTy = llvm::StructType::get(RecordTy, CGM.VoidPtrTy);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001957 llvm::Value *Ptrs = Builder.CreateBitCast(SEHInfo, PtrsTy->getPointerTo());
David Blaikie1ed728c2015-04-05 22:45:47 +00001958 llvm::Value *Rec = Builder.CreateStructGEP(PtrsTy, Ptrs, 0);
John McCall7f416cc2015-09-08 08:05:57 +00001959 Rec = Builder.CreateAlignedLoad(Rec, getPointerAlign());
1960 llvm::Value *Code = Builder.CreateAlignedLoad(Rec, getIntAlign());
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001961 assert(!SEHCodeSlotStack.empty() && "emitting EH code outside of __except");
1962 Builder.CreateStore(Code, SEHCodeSlotStack.back());
Reid Kleckner1d59f992015-01-22 01:36:17 +00001963}
1964
1965llvm::Value *CodeGenFunction::EmitSEHExceptionInfo() {
1966 // Sema should diagnose calling this builtin outside of a filter context, but
1967 // don't crash if we screw up.
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001968 if (!SEHInfo)
Reid Kleckner1d59f992015-01-22 01:36:17 +00001969 return llvm::UndefValue::get(Int8PtrTy);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001970 assert(SEHInfo->getType() == Int8PtrTy);
1971 return SEHInfo;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001972}
1973
1974llvm::Value *CodeGenFunction::EmitSEHExceptionCode() {
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001975 assert(!SEHCodeSlotStack.empty() && "emitting EH code outside of __except");
John McCall7f416cc2015-09-08 08:05:57 +00001976 return Builder.CreateLoad(SEHCodeSlotStack.back());
Reid Kleckner1d59f992015-01-22 01:36:17 +00001977}
1978
Reid Kleckneraca01db2015-02-04 22:37:07 +00001979llvm::Value *CodeGenFunction::EmitSEHAbnormalTermination() {
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001980 // Abnormal termination is just the first parameter to the outlined finally
1981 // helper.
1982 auto AI = CurFn->arg_begin();
1983 return Builder.CreateZExt(&*AI, Int32Ty);
Reid Kleckneraca01db2015-02-04 22:37:07 +00001984}
1985
David Chisnall93ce0182018-08-10 12:53:13 +00001986void CodeGenFunction::pushSEHCleanup(CleanupKind Kind,
1987 llvm::Function *FinallyFunc) {
1988 EHStack.pushCleanup<PerformSEHFinally>(Kind, FinallyFunc);
1989}
1990
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001991void CodeGenFunction::EnterSEHTryStmt(const SEHTryStmt &S) {
1992 CodeGenFunction HelperCGF(CGM, /*suppressNewContext=*/true);
1993 if (const SEHFinallyStmt *Finally = S.getFinallyHandler()) {
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001994 // Outline the finally block.
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001995 llvm::Function *FinallyFunc =
1996 HelperCGF.GenerateSEHFinallyFunction(*this, *Finally);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001997
1998 // Push a cleanup for __finally blocks.
Reid Kleckner55391522015-10-08 21:14:56 +00001999 EHStack.pushCleanup<PerformSEHFinally>(NormalAndEHCleanup, FinallyFunc);
Reid Kleckner1d59f992015-01-22 01:36:17 +00002000 return;
2001 }
2002
2003 // Otherwise, we must have an __except block.
Reid Klecknerebaf28d2015-04-14 20:59:00 +00002004 const SEHExceptStmt *Except = S.getExceptHandler();
Reid Kleckner1d59f992015-01-22 01:36:17 +00002005 assert(Except);
2006 EHCatchScope *CatchScope = EHStack.pushCatch(1);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00002007 SEHCodeSlotStack.push_back(
2008 CreateMemTemp(getContext().IntTy, "__exception_code"));
Reid Kleckner2a2e1562015-01-22 02:25:56 +00002009
Reid Kleckner9fe7f232015-07-07 00:36:30 +00002010 // If the filter is known to evaluate to 1, then we can use the clause
2011 // "catch i8* null". We can't do this on x86 because the filter has to save
2012 // the exception code.
Reid Kleckner2a2e1562015-01-22 02:25:56 +00002013 llvm::Constant *C =
John McCallde0fe072017-08-15 21:42:52 +00002014 ConstantEmitter(*this).tryEmitAbstract(Except->getFilterExpr(),
2015 getContext().IntTy);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00002016 if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86 && C &&
2017 C->isOneValue()) {
Reid Kleckner2a2e1562015-01-22 02:25:56 +00002018 CatchScope->setCatchAllHandler(0, createBasicBlock("__except"));
2019 return;
2020 }
2021
2022 // In general, we have to emit an outlined filter function. Use the function
2023 // in place of the RTTI typeinfo global that C++ EH uses.
Reid Kleckner1d59f992015-01-22 01:36:17 +00002024 llvm::Function *FilterFunc =
Reid Klecknerebaf28d2015-04-14 20:59:00 +00002025 HelperCGF.GenerateSEHFilterFunction(*this, *Except);
Reid Kleckner1d59f992015-01-22 01:36:17 +00002026 llvm::Constant *OpaqueFunc =
2027 llvm::ConstantExpr::getBitCast(FilterFunc, Int8PtrTy);
Reid Kleckner8be18472015-09-16 21:06:09 +00002028 CatchScope->setHandler(0, OpaqueFunc, createBasicBlock("__except.ret"));
Reid Kleckner1d59f992015-01-22 01:36:17 +00002029}
2030
Reid Klecknerebaf28d2015-04-14 20:59:00 +00002031void CodeGenFunction::ExitSEHTryStmt(const SEHTryStmt &S) {
Reid Kleckner1d59f992015-01-22 01:36:17 +00002032 // Just pop the cleanup if it's a __finally block.
Reid Klecknerebaf28d2015-04-14 20:59:00 +00002033 if (S.getFinallyHandler()) {
Reid Kleckner1d59f992015-01-22 01:36:17 +00002034 PopCleanupBlock();
2035 return;
2036 }
2037
2038 // Otherwise, we must have an __except block.
Reid Kleckneraca01db2015-02-04 22:37:07 +00002039 const SEHExceptStmt *Except = S.getExceptHandler();
Reid Kleckner1d59f992015-01-22 01:36:17 +00002040 assert(Except && "__try must have __finally xor __except");
2041 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
2042
2043 // Don't emit the __except block if the __try block lacked invokes.
2044 // TODO: Model unwind edges from instructions, either with iload / istore or
2045 // a try body function.
2046 if (!CatchScope.hasEHBranches()) {
2047 CatchScope.clearHandlerBlocks();
2048 EHStack.popCatch();
Reid Kleckner9fe7f232015-07-07 00:36:30 +00002049 SEHCodeSlotStack.pop_back();
Reid Kleckner1d59f992015-01-22 01:36:17 +00002050 return;
2051 }
2052
2053 // The fall-through block.
2054 llvm::BasicBlock *ContBB = createBasicBlock("__try.cont");
2055
2056 // We just emitted the body of the __try; jump to the continue block.
2057 if (HaveInsertPoint())
2058 Builder.CreateBr(ContBB);
2059
2060 // Check if our filter function returned true.
2061 emitCatchDispatchBlock(*this, CatchScope);
2062
2063 // Grab the block before we pop the handler.
David Majnemer4e52d6f2015-12-12 05:39:21 +00002064 llvm::BasicBlock *CatchPadBB = CatchScope.getHandler(0).Block;
Reid Kleckner1d59f992015-01-22 01:36:17 +00002065 EHStack.popCatch();
2066
David Majnemer4e52d6f2015-12-12 05:39:21 +00002067 EmitBlockAfterUses(CatchPadBB);
Reid Kleckner1d59f992015-01-22 01:36:17 +00002068
Reid Kleckner129552b2015-10-08 01:13:52 +00002069 // __except blocks don't get outlined into funclets, so immediately do a
2070 // catchret.
Reid Kleckner129552b2015-10-08 01:13:52 +00002071 llvm::CatchPadInst *CPI =
2072 cast<llvm::CatchPadInst>(CatchPadBB->getFirstNonPHI());
David Majnemer4e52d6f2015-12-12 05:39:21 +00002073 llvm::BasicBlock *ExceptBB = createBasicBlock("__except");
Reid Kleckner129552b2015-10-08 01:13:52 +00002074 Builder.CreateCatchRet(CPI, ExceptBB);
2075 EmitBlock(ExceptBB);
2076
2077 // On Win64, the exception code is returned in EAX. Copy it into the slot.
2078 if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
2079 llvm::Function *SEHCodeIntrin =
2080 CGM.getIntrinsic(llvm::Intrinsic::eh_exceptioncode);
2081 llvm::Value *Code = Builder.CreateCall(SEHCodeIntrin, {CPI});
2082 Builder.CreateStore(Code, SEHCodeSlotStack.back());
Reid Kleckner9fe7f232015-07-07 00:36:30 +00002083 }
2084
Reid Kleckner1d59f992015-01-22 01:36:17 +00002085 // Emit the __except body.
2086 EmitStmt(Except->getBlock());
2087
Reid Kleckner9fe7f232015-07-07 00:36:30 +00002088 // End the lifetime of the exception code.
2089 SEHCodeSlotStack.pop_back();
2090
Reid Kleckner3a417c32015-01-30 22:16:45 +00002091 if (HaveInsertPoint())
2092 Builder.CreateBr(ContBB);
Reid Kleckner1d59f992015-01-22 01:36:17 +00002093
2094 EmitBlock(ContBB);
Reid Kleckner543a16c2013-09-16 21:46:30 +00002095}
Nico Weber9b982072014-07-07 00:12:30 +00002096
2097void CodeGenFunction::EmitSEHLeaveStmt(const SEHLeaveStmt &S) {
Nico Weber5779f842015-02-12 23:16:11 +00002098 // If this code is reachable then emit a stop point (if generating
2099 // debug info). We have to do this ourselves because we are on the
2100 // "simple" statement path.
2101 if (HaveInsertPoint())
2102 EmitStopPoint(&S);
2103
Reid Klecknerebaf28d2015-04-14 20:59:00 +00002104 // This must be a __leave from a __finally block, which we warn on and is UB.
2105 // Just emit unreachable.
2106 if (!isSEHTryScope()) {
2107 Builder.CreateUnreachable();
2108 Builder.ClearInsertionPoint();
2109 return;
2110 }
2111
Nico Weber5779f842015-02-12 23:16:11 +00002112 EmitBranchThroughCleanup(*SEHTryEpilogueStack.back());
Nico Weber9b982072014-07-07 00:12:30 +00002113}