blob: 3b7a88a0b76938084485ed5a1232b584dd1c8788 [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
13#include "CodeGenFunction.h"
David Majnemer442d0a22014-11-25 07:20:20 +000014#include "CGCXXABI.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000015#include "CGCleanup.h"
Benjamin Kramer793bd552012-02-08 12:41:24 +000016#include "CGObjCRuntime.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"
Chandler Carruthffd55512013-01-02 11:45:17 +000024#include "llvm/IR/Intrinsics.h"
Reid Kleckner31a1bb02015-04-08 22:23:48 +000025#include "llvm/IR/IntrinsicInst.h"
Reid Klecknerebaf28d2015-04-14 20:59:00 +000026#include "llvm/Support/SaveAndRestore.h"
John McCallbd309292010-07-06 01:34:17 +000027
Anders Carlsson4b08db72009-10-30 01:42:31 +000028using namespace clang;
29using namespace CodeGen;
30
James Y Knight9871db02019-02-05 16:42:33 +000031static llvm::FunctionCallee getFreeExceptionFn(CodeGenModule &CGM) {
Mike Stump33270212009-12-02 07:41:41 +000032 // void __cxa_free_exception(void *thrown_exception);
Mike Stump75546b82009-12-10 00:06:18 +000033
Chris Lattner2192fe52011-07-18 04:24:23 +000034 llvm::FunctionType *FTy =
Rui Ueyama49a3ad22019-07-16 04:46:31 +000035 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*isVarArg=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000036
John McCall2c33ba82013-02-12 03:51:38 +000037 return CGM.CreateRuntimeFunction(FTy, "__cxa_free_exception");
Mike Stump33270212009-12-02 07:41:41 +000038}
39
James Y Knight9871db02019-02-05 16:42:33 +000040static llvm::FunctionCallee getUnexpectedFn(CodeGenModule &CGM) {
Richard Smith2f7aa192013-06-20 23:03:35 +000041 // void __cxa_call_unexpected(void *thrown_exception);
Mike Stump1d849212009-12-07 23:38:24 +000042
Chris Lattner2192fe52011-07-18 04:24:23 +000043 llvm::FunctionType *FTy =
Rui Ueyama49a3ad22019-07-16 04:46:31 +000044 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*isVarArg=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000045
John McCall2c33ba82013-02-12 03:51:38 +000046 return CGM.CreateRuntimeFunction(FTy, "__cxa_call_unexpected");
Mike Stump1d849212009-12-07 23:38:24 +000047}
48
James Y Knight9871db02019-02-05 16:42:33 +000049llvm::FunctionCallee CodeGenModule::getTerminateFn() {
Mike Stump33270212009-12-02 07:41:41 +000050 // void __terminate();
51
Chris Lattner2192fe52011-07-18 04:24:23 +000052 llvm::FunctionType *FTy =
Rui Ueyama49a3ad22019-07-16 04:46:31 +000053 llvm::FunctionType::get(VoidTy, /*isVarArg=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000054
Chris Lattner0e62c1c2011-07-23 10:55:15 +000055 StringRef name;
John McCall9de19782011-07-06 01:22:26 +000056
57 // In C++, use std::terminate().
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000058 if (getLangOpts().CPlusPlus &&
59 getTarget().getCXXABI().isItaniumFamily()) {
Reid Kleckner1d59f992015-01-22 01:36:17 +000060 name = "_ZSt9terminatev";
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000061 } else if (getLangOpts().CPlusPlus &&
62 getTarget().getCXXABI().isMicrosoft()) {
David Majnemerb710a932015-05-11 03:57:49 +000063 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
David Majnemerfb6ffca2015-05-10 21:38:26 +000064 name = "__std_terminate";
65 else
Reid Klecknerfb931542018-03-16 20:36:49 +000066 name = "?terminate@@YAXXZ";
Erik Pilkingtonfa983902018-10-30 20:31:30 +000067 } else if (getLangOpts().ObjC &&
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000068 getLangOpts().ObjCRuntime.hasTerminate())
John McCall9de19782011-07-06 01:22:26 +000069 name = "objc_terminate";
70 else
71 name = "abort";
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000072 return CreateRuntimeFunction(FTy, name);
David Chisnallf9c42252010-05-17 13:49:20 +000073}
74
James Y Knight9871db02019-02-05 16:42:33 +000075static llvm::FunctionCallee getCatchallRethrowFn(CodeGenModule &CGM,
76 StringRef Name) {
Chris Lattner2192fe52011-07-18 04:24:23 +000077 llvm::FunctionType *FTy =
Rui Ueyama49a3ad22019-07-16 04:46:31 +000078 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*isVarArg=*/false);
John McCall36ea3722010-07-17 00:43:08 +000079
John McCall2c33ba82013-02-12 03:51:38 +000080 return CGM.CreateRuntimeFunction(FTy, Name);
John McCallbd309292010-07-06 01:34:17 +000081}
82
Craig Topper8a13c412014-05-21 05:09:00 +000083const EHPersonality EHPersonality::GNU_C = { "__gcc_personality_v0", nullptr };
Benjamin Kramer793bd552012-02-08 12:41:24 +000084const EHPersonality
Craig Topper8a13c412014-05-21 05:09:00 +000085EHPersonality::GNU_C_SJLJ = { "__gcc_personality_sj0", nullptr };
86const EHPersonality
Reid Kleckner8f45c9c2014-09-15 17:19:16 +000087EHPersonality::GNU_C_SEH = { "__gcc_personality_seh0", nullptr };
88const EHPersonality
Craig Topper8a13c412014-05-21 05:09:00 +000089EHPersonality::NeXT_ObjC = { "__objc_personality_v0", nullptr };
90const EHPersonality
91EHPersonality::GNU_CPlusPlus = { "__gxx_personality_v0", nullptr };
92const EHPersonality
93EHPersonality::GNU_CPlusPlus_SJLJ = { "__gxx_personality_sj0", nullptr };
Benjamin Kramer793bd552012-02-08 12:41:24 +000094const EHPersonality
Reid Kleckner8f45c9c2014-09-15 17:19:16 +000095EHPersonality::GNU_CPlusPlus_SEH = { "__gxx_personality_seh0", nullptr };
96const EHPersonality
Benjamin Kramer793bd552012-02-08 12:41:24 +000097EHPersonality::GNU_ObjC = {"__gnu_objc_personality_v0", "objc_exception_throw"};
98const EHPersonality
Benjamin Kramer796c1d92017-01-08 22:58:07 +000099EHPersonality::GNU_ObjC_SJLJ = {"__gnu_objc_personality_sj0", "objc_exception_throw"};
100const EHPersonality
101EHPersonality::GNU_ObjC_SEH = {"__gnu_objc_personality_seh0", "objc_exception_throw"};
102const EHPersonality
Craig Topper8a13c412014-05-21 05:09:00 +0000103EHPersonality::GNU_ObjCXX = { "__gnustep_objcxx_personality_v0", nullptr };
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000104const EHPersonality
Craig Topper8a13c412014-05-21 05:09:00 +0000105EHPersonality::GNUstep_ObjC = { "__gnustep_objc_personality_v0", nullptr };
Reid Kleckner1d59f992015-01-22 01:36:17 +0000106const EHPersonality
107EHPersonality::MSVC_except_handler = { "_except_handler3", nullptr };
108const EHPersonality
109EHPersonality::MSVC_C_specific_handler = { "__C_specific_handler", nullptr };
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000110const EHPersonality
111EHPersonality::MSVC_CxxFrameHandler3 = { "__CxxFrameHandler3", nullptr };
Heejin Ahnc6479192018-05-31 22:18:13 +0000112const EHPersonality
113EHPersonality::GNU_Wasm_CPlusPlus = { "__gxx_wasm_personality_v0", nullptr };
John McCall36ea3722010-07-17 00:43:08 +0000114
Heejin Ahn00831792018-06-04 18:23:00 +0000115static const EHPersonality &getCPersonality(const TargetInfo &Target,
Reid Klecknere070b992014-11-14 02:01:10 +0000116 const LangOptions &L) {
Heejin Ahn00831792018-06-04 18:23:00 +0000117 const llvm::Triple &T = Target.getTriple();
Shoaib Meenaia5fc6032018-06-08 00:41:01 +0000118 if (T.isWindowsMSVCEnvironment())
119 return EHPersonality::MSVC_CxxFrameHandler3;
John McCall2faab302010-11-07 02:35:25 +0000120 if (L.SjLjExceptions)
121 return EHPersonality::GNU_C_SJLJ;
Saleem Abdulrasool3e701322018-03-09 07:06:42 +0000122 if (L.DWARFExceptions)
123 return EHPersonality::GNU_C;
Martell Malonec950c652017-11-29 07:25:12 +0000124 if (L.SEHExceptions)
Reid Kleckner8f45c9c2014-09-15 17:19:16 +0000125 return EHPersonality::GNU_C_SEH;
John McCall36ea3722010-07-17 00:43:08 +0000126 return EHPersonality::GNU_C;
127}
128
Heejin Ahn00831792018-06-04 18:23:00 +0000129static const EHPersonality &getObjCPersonality(const TargetInfo &Target,
Reid Klecknere070b992014-11-14 02:01:10 +0000130 const LangOptions &L) {
Heejin Ahn00831792018-06-04 18:23:00 +0000131 const llvm::Triple &T = Target.getTriple();
Shoaib Meenaia5fc6032018-06-08 00:41:01 +0000132 if (T.isWindowsMSVCEnvironment())
133 return EHPersonality::MSVC_CxxFrameHandler3;
134
John McCall5fb5df92012-06-20 06:18:46 +0000135 switch (L.ObjCRuntime.getKind()) {
136 case ObjCRuntime::FragileMacOSX:
Heejin Ahn00831792018-06-04 18:23:00 +0000137 return getCPersonality(Target, L);
John McCall5fb5df92012-06-20 06:18:46 +0000138 case ObjCRuntime::MacOSX:
139 case ObjCRuntime::iOS:
Tim Northover756447a2015-10-30 16:30:36 +0000140 case ObjCRuntime::WatchOS:
John McCall5fb5df92012-06-20 06:18:46 +0000141 return EHPersonality::NeXT_ObjC;
David Chisnallb601c962012-07-03 20:49:52 +0000142 case ObjCRuntime::GNUstep:
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000143 if (L.ObjCRuntime.getVersion() >= VersionTuple(1, 7))
144 return EHPersonality::GNUstep_ObjC;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +0000145 LLVM_FALLTHROUGH;
David Chisnallb601c962012-07-03 20:49:52 +0000146 case ObjCRuntime::GCC:
John McCall775086e2012-07-12 02:07:58 +0000147 case ObjCRuntime::ObjFW:
Benjamin Kramer796c1d92017-01-08 22:58:07 +0000148 if (L.SjLjExceptions)
149 return EHPersonality::GNU_ObjC_SJLJ;
Martell Malonec950c652017-11-29 07:25:12 +0000150 if (L.SEHExceptions)
Benjamin Kramer796c1d92017-01-08 22:58:07 +0000151 return EHPersonality::GNU_ObjC_SEH;
John McCall36ea3722010-07-17 00:43:08 +0000152 return EHPersonality::GNU_ObjC;
John McCallbd309292010-07-06 01:34:17 +0000153 }
John McCall5fb5df92012-06-20 06:18:46 +0000154 llvm_unreachable("bad runtime kind");
John McCallbd309292010-07-06 01:34:17 +0000155}
156
Heejin Ahn00831792018-06-04 18:23:00 +0000157static const EHPersonality &getCXXPersonality(const TargetInfo &Target,
158 const LangOptions &L) {
159 const llvm::Triple &T = Target.getTriple();
Shoaib Meenaia5fc6032018-06-08 00:41:01 +0000160 if (T.isWindowsMSVCEnvironment())
161 return EHPersonality::MSVC_CxxFrameHandler3;
John McCall36ea3722010-07-17 00:43:08 +0000162 if (L.SjLjExceptions)
163 return EHPersonality::GNU_CPlusPlus_SJLJ;
Saleem Abdulrasool3e701322018-03-09 07:06:42 +0000164 if (L.DWARFExceptions)
165 return EHPersonality::GNU_CPlusPlus;
Martell Malonec950c652017-11-29 07:25:12 +0000166 if (L.SEHExceptions)
Reid Kleckner8f45c9c2014-09-15 17:19:16 +0000167 return EHPersonality::GNU_CPlusPlus_SEH;
Heejin Ahn1eb074d2018-06-01 01:01:37 +0000168 // Wasm EH is a non-MVP feature for now.
169 if (Target.hasFeature("exception-handling") &&
170 (T.getArch() == llvm::Triple::wasm32 ||
171 T.getArch() == llvm::Triple::wasm64))
Heejin Ahnc6479192018-05-31 22:18:13 +0000172 return EHPersonality::GNU_Wasm_CPlusPlus;
Reid Klecknere070b992014-11-14 02:01:10 +0000173 return EHPersonality::GNU_CPlusPlus;
John McCallbd309292010-07-06 01:34:17 +0000174}
175
176/// Determines the personality function to use when both C++
177/// and Objective-C exceptions are being caught.
Heejin Ahn00831792018-06-04 18:23:00 +0000178static const EHPersonality &getObjCXXPersonality(const TargetInfo &Target,
179 const LangOptions &L) {
Shoaib Meenaia5fc6032018-06-08 00:41:01 +0000180 if (Target.getTriple().isWindowsMSVCEnvironment())
181 return EHPersonality::MSVC_CxxFrameHandler3;
182
John McCall5fb5df92012-06-20 06:18:46 +0000183 switch (L.ObjCRuntime.getKind()) {
Saleem Abdulrasool8f6d9442017-11-02 00:25:40 +0000184 // In the fragile ABI, just use C++ exception handling and hope
185 // they're not doing crazy exception mixing.
186 case ObjCRuntime::FragileMacOSX:
Heejin Ahn00831792018-06-04 18:23:00 +0000187 return getCXXPersonality(Target, L);
Saleem Abdulrasool8f6d9442017-11-02 00:25:40 +0000188
John McCallbd309292010-07-06 01:34:17 +0000189 // The ObjC personality defers to the C++ personality for non-ObjC
190 // handlers. Unlike the C++ case, we use the same personality
191 // function on targets using (backend-driven) SJLJ EH.
John McCall5fb5df92012-06-20 06:18:46 +0000192 case ObjCRuntime::MacOSX:
193 case ObjCRuntime::iOS:
Tim Northover756447a2015-10-30 16:30:36 +0000194 case ObjCRuntime::WatchOS:
Heejin Ahn00831792018-06-04 18:23:00 +0000195 return getObjCPersonality(Target, L);
John McCallbd309292010-07-06 01:34:17 +0000196
Saleem Abdulrasool8f6d9442017-11-02 00:25:40 +0000197 case ObjCRuntime::GNUstep:
198 return EHPersonality::GNU_ObjCXX;
David Chisnallf9c42252010-05-17 13:49:20 +0000199
David Chisnallb601c962012-07-03 20:49:52 +0000200 // The GCC runtime's personality function inherently doesn't support
Saleem Abdulrasool8f6d9442017-11-02 00:25:40 +0000201 // mixed EH. Use the ObjC personality just to avoid returning null.
David Chisnallb601c962012-07-03 20:49:52 +0000202 case ObjCRuntime::GCC:
Benjamin Kramer9851cb72017-04-01 17:59:01 +0000203 case ObjCRuntime::ObjFW:
Heejin Ahn00831792018-06-04 18:23:00 +0000204 return getObjCPersonality(Target, L);
John McCall5fb5df92012-06-20 06:18:46 +0000205 }
206 llvm_unreachable("bad runtime kind");
John McCallbd309292010-07-06 01:34:17 +0000207}
208
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000209static const EHPersonality &getSEHPersonalityMSVC(const llvm::Triple &T) {
Reid Kleckner1d59f992015-01-22 01:36:17 +0000210 if (T.getArch() == llvm::Triple::x86)
211 return EHPersonality::MSVC_except_handler;
212 return EHPersonality::MSVC_C_specific_handler;
213}
214
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000215const EHPersonality &EHPersonality::get(CodeGenModule &CGM,
216 const FunctionDecl *FD) {
Reid Klecknere070b992014-11-14 02:01:10 +0000217 const llvm::Triple &T = CGM.getTarget().getTriple();
218 const LangOptions &L = CGM.getLangOpts();
Heejin Ahn1eb074d2018-06-01 01:01:37 +0000219 const TargetInfo &Target = CGM.getTarget();
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000220
Reid Kleckner01485652015-09-17 17:04:13 +0000221 // Functions using SEH get an SEH personality.
222 if (FD && FD->usesSEHTry())
223 return getSEHPersonalityMSVC(T);
224
Erik Pilkingtonfa983902018-10-30 20:31:30 +0000225 if (L.ObjC)
Heejin Ahn00831792018-06-04 18:23:00 +0000226 return L.CPlusPlus ? getObjCXXPersonality(Target, L)
227 : getObjCPersonality(Target, L);
228 return L.CPlusPlus ? getCXXPersonality(Target, L)
229 : getCPersonality(Target, L);
John McCall36ea3722010-07-17 00:43:08 +0000230}
John McCallbd309292010-07-06 01:34:17 +0000231
David Majnemerc28d46e2015-07-22 23:46:21 +0000232const EHPersonality &EHPersonality::get(CodeGenFunction &CGF) {
Reid Kleckner65fa8692017-10-13 16:55:14 +0000233 const auto *FD = CGF.CurCodeDecl;
234 // For outlined finallys and filters, use the SEH personality in case they
235 // contain more SEH. This mostly only affects finallys. Filters could
236 // hypothetically use gnu statement expressions to sneak in nested SEH.
237 FD = FD ? FD : CGF.CurSEHParent;
238 return get(CGF.CGM, dyn_cast_or_null<FunctionDecl>(FD));
David Majnemerc28d46e2015-07-22 23:46:21 +0000239}
240
James Y Knight9871db02019-02-05 16:42:33 +0000241static llvm::FunctionCallee getPersonalityFn(CodeGenModule &CGM,
242 const EHPersonality &Personality) {
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +0000243 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.Int32Ty, true),
244 Personality.PersonalityFn,
Reid Klecknerde864822017-03-21 16:57:30 +0000245 llvm::AttributeList(), /*Local=*/true);
John McCall0bdb1fd2010-09-16 06:16:50 +0000246}
247
248static llvm::Constant *getOpaquePersonalityFn(CodeGenModule &CGM,
249 const EHPersonality &Personality) {
James Y Knight9871db02019-02-05 16:42:33 +0000250 llvm::FunctionCallee Fn = getPersonalityFn(CGM, Personality);
Dylan McKay02bbe412018-11-09 19:42:05 +0000251 llvm::PointerType* Int8PtrTy = llvm::PointerType::get(
252 llvm::Type::getInt8Ty(CGM.getLLVMContext()),
253 CGM.getDataLayout().getProgramAddressSpace());
254
James Y Knight9871db02019-02-05 16:42:33 +0000255 return llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(Fn.getCallee()),
256 Int8PtrTy);
John McCall0bdb1fd2010-09-16 06:16:50 +0000257}
258
Vedant Kumardb609472015-09-11 15:40:05 +0000259/// Check whether a landingpad instruction only uses C++ features.
260static bool LandingPadHasOnlyCXXUses(llvm::LandingPadInst *LPI) {
261 for (unsigned I = 0, E = LPI->getNumClauses(); I != E; ++I) {
262 // Look for something that would've been returned by the ObjC
263 // runtime's GetEHType() method.
264 llvm::Value *Val = LPI->getClause(I)->stripPointerCasts();
265 if (LPI->isCatch(I)) {
266 // Check if the catch value has the ObjC prefix.
267 if (llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Val))
268 // ObjC EH selector entries are always global variables with
269 // names starting like this.
270 if (GV->getName().startswith("OBJC_EHTYPE"))
271 return false;
272 } else {
273 // Check if any of the filter values have the ObjC prefix.
274 llvm::Constant *CVal = cast<llvm::Constant>(Val);
275 for (llvm::User::op_iterator
276 II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II) {
277 if (llvm::GlobalVariable *GV =
278 cast<llvm::GlobalVariable>((*II)->stripPointerCasts()))
279 // ObjC EH selector entries are always global variables with
280 // names starting like this.
281 if (GV->getName().startswith("OBJC_EHTYPE"))
282 return false;
283 }
284 }
285 }
286 return true;
287}
288
John McCall0bdb1fd2010-09-16 06:16:50 +0000289/// Check whether a personality function could reasonably be swapped
290/// for a C++ personality function.
291static bool PersonalityHasOnlyCXXUses(llvm::Constant *Fn) {
Chandler Carruth4d01fff2014-03-09 03:16:50 +0000292 for (llvm::User *U : Fn->users()) {
John McCall0bdb1fd2010-09-16 06:16:50 +0000293 // Conditionally white-list bitcasts.
Chandler Carruth4d01fff2014-03-09 03:16:50 +0000294 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(U)) {
John McCall0bdb1fd2010-09-16 06:16:50 +0000295 if (CE->getOpcode() != llvm::Instruction::BitCast) return false;
296 if (!PersonalityHasOnlyCXXUses(CE))
297 return false;
298 continue;
299 }
300
Vedant Kumardb609472015-09-11 15:40:05 +0000301 // Otherwise it must be a function.
302 llvm::Function *F = dyn_cast<llvm::Function>(U);
303 if (!F) return false;
John McCall0bdb1fd2010-09-16 06:16:50 +0000304
Vedant Kumardb609472015-09-11 15:40:05 +0000305 for (auto BB = F->begin(), E = F->end(); BB != E; ++BB) {
306 if (BB->isLandingPad())
307 if (!LandingPadHasOnlyCXXUses(BB->getLandingPadInst()))
308 return false;
John McCall0bdb1fd2010-09-16 06:16:50 +0000309 }
310 }
311
312 return true;
313}
314
315/// Try to use the C++ personality function in ObjC++. Not doing this
316/// can cause some incompatibilities with gcc, which is more
317/// aggressive about only using the ObjC++ personality in a function
318/// when it really needs it.
319void CodeGenModule::SimplifyPersonality() {
John McCall0bdb1fd2010-09-16 06:16:50 +0000320 // If we're not in ObjC++ -fexceptions, there's nothing to do.
Erik Pilkingtonfa983902018-10-30 20:31:30 +0000321 if (!LangOpts.CPlusPlus || !LangOpts.ObjC || !LangOpts.Exceptions)
John McCall0bdb1fd2010-09-16 06:16:50 +0000322 return;
323
John McCall3c223932012-11-14 17:48:31 +0000324 // Both the problem this endeavors to fix and the way the logic
325 // above works is specific to the NeXT runtime.
326 if (!LangOpts.ObjCRuntime.isNeXTFamily())
327 return;
328
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000329 const EHPersonality &ObjCXX = EHPersonality::get(*this, /*FD=*/nullptr);
Heejin Ahn00831792018-06-04 18:23:00 +0000330 const EHPersonality &CXX = getCXXPersonality(getTarget(), LangOpts);
Benjamin Kramer793bd552012-02-08 12:41:24 +0000331 if (&ObjCXX == &CXX)
John McCall0bdb1fd2010-09-16 06:16:50 +0000332 return;
333
Benjamin Kramer793bd552012-02-08 12:41:24 +0000334 assert(std::strcmp(ObjCXX.PersonalityFn, CXX.PersonalityFn) != 0 &&
335 "Different EHPersonalities using the same personality function.");
336
337 llvm::Function *Fn = getModule().getFunction(ObjCXX.PersonalityFn);
John McCall0bdb1fd2010-09-16 06:16:50 +0000338
339 // Nothing to do if it's unused.
340 if (!Fn || Fn->use_empty()) return;
Fangrui Song6907ce22018-07-30 19:24:48 +0000341
John McCall0bdb1fd2010-09-16 06:16:50 +0000342 // Can't do the optimization if it has non-C++ uses.
343 if (!PersonalityHasOnlyCXXUses(Fn)) return;
344
345 // Create the C++ personality function and kill off the old
346 // function.
James Y Knight9871db02019-02-05 16:42:33 +0000347 llvm::FunctionCallee CXXFn = getPersonalityFn(*this, CXX);
John McCall0bdb1fd2010-09-16 06:16:50 +0000348
349 // This can happen if the user is screwing with us.
James Y Knight9871db02019-02-05 16:42:33 +0000350 if (Fn->getType() != CXXFn.getCallee()->getType())
351 return;
John McCall0bdb1fd2010-09-16 06:16:50 +0000352
James Y Knight9871db02019-02-05 16:42:33 +0000353 Fn->replaceAllUsesWith(CXXFn.getCallee());
John McCall0bdb1fd2010-09-16 06:16:50 +0000354 Fn->eraseFromParent();
John McCallbd309292010-07-06 01:34:17 +0000355}
356
357/// Returns the value to inject into a selector to indicate the
358/// presence of a catch-all.
359static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
360 // Possibly we should use @llvm.eh.catch.all.value here.
John McCallad7c5c12011-02-08 08:22:06 +0000361 return llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
John McCallbd309292010-07-06 01:34:17 +0000362}
363
John McCallbb026012010-07-13 21:17:51 +0000364namespace {
365 /// A cleanup to free the exception object if its initialization
366 /// throws.
David Blaikie7e70d682015-08-18 22:40:54 +0000367 struct FreeException final : EHScopeStack::Cleanup {
John McCall5fcf8da2011-07-12 00:15:30 +0000368 llvm::Value *exn;
369 FreeException(llvm::Value *exn) : exn(exn) {}
Craig Topper4f12f102014-03-12 06:41:41 +0000370 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +0000371 CGF.EmitNounwindRuntimeCall(getFreeExceptionFn(CGF.CGM), exn);
John McCallbb026012010-07-13 21:17:51 +0000372 }
373 };
Hans Wennborgdcfba332015-10-06 23:40:43 +0000374} // end anonymous namespace
John McCallbb026012010-07-13 21:17:51 +0000375
John McCall2e6567a2010-04-22 01:10:34 +0000376// Emits an exception expression into the given location. This
377// differs from EmitAnyExprToMem only in that, if a final copy-ctor
378// call is required, an exception within that copy ctor causes
379// std::terminate to be invoked.
John McCall7f416cc2015-09-08 08:05:57 +0000380void CodeGenFunction::EmitAnyExprToExn(const Expr *e, Address addr) {
John McCallbd309292010-07-06 01:34:17 +0000381 // Make sure the exception object is cleaned up if there's an
382 // exception during initialization.
John McCall7f416cc2015-09-08 08:05:57 +0000383 pushFullExprCleanup<FreeException>(EHCleanup, addr.getPointer());
David Majnemer7c237072015-03-05 00:46:22 +0000384 EHScopeStack::stable_iterator cleanup = EHStack.stable_begin();
John McCall2e6567a2010-04-22 01:10:34 +0000385
386 // __cxa_allocate_exception returns a void*; we need to cast this
387 // to the appropriate type for the object.
David Majnemer7c237072015-03-05 00:46:22 +0000388 llvm::Type *ty = ConvertTypeForMem(e->getType())->getPointerTo();
John McCall7f416cc2015-09-08 08:05:57 +0000389 Address typedAddr = Builder.CreateBitCast(addr, ty);
John McCall2e6567a2010-04-22 01:10:34 +0000390
391 // FIXME: this isn't quite right! If there's a final unelided call
392 // to a copy constructor, then according to [except.terminate]p1 we
393 // must call std::terminate() if that constructor throws, because
394 // technically that copy occurs after the exception expression is
395 // evaluated but before the exception is caught. But the best way
396 // to handle that is to teach EmitAggExpr to do the final copy
397 // differently if it can't be elided.
David Majnemer7c237072015-03-05 00:46:22 +0000398 EmitAnyExprToMem(e, typedAddr, e->getType().getQualifiers(),
399 /*IsInit*/ true);
John McCall2e6567a2010-04-22 01:10:34 +0000400
John McCalle4df6c82011-01-28 08:37:24 +0000401 // Deactivate the cleanup block.
John McCall7f416cc2015-09-08 08:05:57 +0000402 DeactivateCleanupBlock(cleanup,
403 cast<llvm::Instruction>(typedAddr.getPointer()));
Mike Stump54066142009-12-01 03:41:18 +0000404}
405
John McCall7f416cc2015-09-08 08:05:57 +0000406Address CodeGenFunction::getExceptionSlot() {
John McCall9b382dd2011-05-28 21:13:02 +0000407 if (!ExceptionSlot)
408 ExceptionSlot = CreateTempAlloca(Int8PtrTy, "exn.slot");
John McCall7f416cc2015-09-08 08:05:57 +0000409 return Address(ExceptionSlot, getPointerAlign());
Mike Stump54066142009-12-01 03:41:18 +0000410}
411
John McCall7f416cc2015-09-08 08:05:57 +0000412Address CodeGenFunction::getEHSelectorSlot() {
John McCall9b382dd2011-05-28 21:13:02 +0000413 if (!EHSelectorSlot)
414 EHSelectorSlot = CreateTempAlloca(Int32Ty, "ehselector.slot");
John McCall7f416cc2015-09-08 08:05:57 +0000415 return Address(EHSelectorSlot, CharUnits::fromQuantity(4));
John McCall9b382dd2011-05-28 21:13:02 +0000416}
417
Bill Wendling79a70e42011-09-15 18:57:19 +0000418llvm::Value *CodeGenFunction::getExceptionFromSlot() {
419 return Builder.CreateLoad(getExceptionSlot(), "exn");
420}
421
422llvm::Value *CodeGenFunction::getSelectorFromSlot() {
423 return Builder.CreateLoad(getEHSelectorSlot(), "sel");
424}
425
Richard Smithea852322013-05-07 21:53:22 +0000426void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E,
427 bool KeepInsertionPoint) {
David Majnemer7c237072015-03-05 00:46:22 +0000428 if (const Expr *SubExpr = E->getSubExpr()) {
429 QualType ThrowType = SubExpr->getType();
430 if (ThrowType->isObjCObjectPointerType()) {
431 const Stmt *ThrowStmt = E->getSubExpr();
432 const ObjCAtThrowStmt S(E->getExprLoc(), const_cast<Stmt *>(ThrowStmt));
433 CGM.getObjCRuntime().EmitThrowStmt(*this, S, false);
434 } else {
435 CGM.getCXXABI().emitThrow(*this, E);
John McCall2e6567a2010-04-22 01:10:34 +0000436 }
David Majnemer7c237072015-03-05 00:46:22 +0000437 } else {
438 CGM.getCXXABI().emitRethrow(*this, /*isNoReturn=*/true);
John McCall2e6567a2010-04-22 01:10:34 +0000439 }
Mike Stump75546b82009-12-10 00:06:18 +0000440
John McCall20f6ab82011-01-12 03:41:02 +0000441 // throw is an expression, and the expression emitters expect us
442 // to leave ourselves at a valid insertion point.
Richard Smithea852322013-05-07 21:53:22 +0000443 if (KeepInsertionPoint)
444 EmitBlock(createBasicBlock("throw.cont"));
Anders Carlsson4b08db72009-10-30 01:42:31 +0000445}
Mike Stump58ef18b2009-11-20 23:44:51 +0000446
Mike Stump1d849212009-12-07 23:38:24 +0000447void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000448 if (!CGM.getLangOpts().CXXExceptions)
Anders Carlsson9878f9f2010-02-06 23:59:05 +0000449 return;
Fangrui Song6907ce22018-07-30 19:24:48 +0000450
Mike Stump1d849212009-12-07 23:38:24 +0000451 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
Craig Topper8a13c412014-05-21 05:09:00 +0000452 if (!FD) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000453 // Check if CapturedDecl is nothrow and create terminate scope for it.
454 if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
455 if (CD->isNothrow())
456 EHStack.pushTerminate();
457 }
Mike Stump1d849212009-12-07 23:38:24 +0000458 return;
Alexey Bataev9959db52014-05-06 10:08:46 +0000459 }
Mike Stump1d849212009-12-07 23:38:24 +0000460 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
Craig Topper8a13c412014-05-21 05:09:00 +0000461 if (!Proto)
Mike Stump1d849212009-12-07 23:38:24 +0000462 return;
463
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000464 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
Richard Smitheaf11ad2018-05-03 03:58:32 +0000465 if (isNoexceptExceptionSpec(EST) && Proto->canThrow() == CT_Cannot) {
466 // noexcept functions are simple terminate scopes.
467 EHStack.pushTerminate();
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000468 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
David Majnemer1f192e22015-04-01 04:45:52 +0000469 // TODO: Revisit exception specifications for the MS ABI. There is a way to
470 // encode these in an object file but MSVC doesn't do anything with it.
471 if (getTarget().getCXXABI().isMicrosoft())
472 return;
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000473 unsigned NumExceptions = Proto->getNumExceptions();
474 EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
Mike Stump1d849212009-12-07 23:38:24 +0000475
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000476 for (unsigned I = 0; I != NumExceptions; ++I) {
477 QualType Ty = Proto->getExceptionType(I);
478 QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
479 llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType,
480 /*ForEH=*/true);
481 Filter->setFilter(I, EHType);
482 }
Mike Stump1d849212009-12-07 23:38:24 +0000483 }
Mike Stump1d849212009-12-07 23:38:24 +0000484}
485
John McCall8e4c74b2011-08-11 02:22:43 +0000486/// Emit the dispatch block for a filter scope if necessary.
487static void emitFilterDispatchBlock(CodeGenFunction &CGF,
488 EHFilterScope &filterScope) {
489 llvm::BasicBlock *dispatchBlock = filterScope.getCachedEHDispatchBlock();
490 if (!dispatchBlock) return;
491 if (dispatchBlock->use_empty()) {
492 delete dispatchBlock;
493 return;
494 }
495
John McCall8e4c74b2011-08-11 02:22:43 +0000496 CGF.EmitBlockAfterUses(dispatchBlock);
497
498 // If this isn't a catch-all filter, we need to check whether we got
499 // here because the filter triggered.
500 if (filterScope.getNumFilters()) {
501 // Load the selector value.
Bill Wendling79a70e42011-09-15 18:57:19 +0000502 llvm::Value *selector = CGF.getSelectorFromSlot();
John McCall8e4c74b2011-08-11 02:22:43 +0000503 llvm::BasicBlock *unexpectedBB = CGF.createBasicBlock("ehspec.unexpected");
504
505 llvm::Value *zero = CGF.Builder.getInt32(0);
506 llvm::Value *failsFilter =
Nico Weber1bebad12015-02-11 22:33:32 +0000507 CGF.Builder.CreateICmpSLT(selector, zero, "ehspec.fails");
508 CGF.Builder.CreateCondBr(failsFilter, unexpectedBB,
509 CGF.getEHResumeBlock(false));
John McCall8e4c74b2011-08-11 02:22:43 +0000510
511 CGF.EmitBlock(unexpectedBB);
512 }
513
514 // Call __cxa_call_unexpected. This doesn't need to be an invoke
515 // because __cxa_call_unexpected magically filters exceptions
516 // according to the last landing pad the exception was thrown
517 // into. Seriously.
Bill Wendling79a70e42011-09-15 18:57:19 +0000518 llvm::Value *exn = CGF.getExceptionFromSlot();
John McCall882987f2013-02-28 19:01:20 +0000519 CGF.EmitRuntimeCall(getUnexpectedFn(CGF.CGM), exn)
John McCall8e4c74b2011-08-11 02:22:43 +0000520 ->setDoesNotReturn();
521 CGF.Builder.CreateUnreachable();
522}
523
Mike Stump1d849212009-12-07 23:38:24 +0000524void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000525 if (!CGM.getLangOpts().CXXExceptions)
Anders Carlsson9878f9f2010-02-06 23:59:05 +0000526 return;
Fangrui Song6907ce22018-07-30 19:24:48 +0000527
Mike Stump1d849212009-12-07 23:38:24 +0000528 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
Craig Topper8a13c412014-05-21 05:09:00 +0000529 if (!FD) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000530 // Check if CapturedDecl is nothrow and pop terminate scope for it.
531 if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
532 if (CD->isNothrow())
533 EHStack.popTerminate();
534 }
Mike Stump1d849212009-12-07 23:38:24 +0000535 return;
Alexey Bataev9959db52014-05-06 10:08:46 +0000536 }
Mike Stump1d849212009-12-07 23:38:24 +0000537 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
Craig Topper8a13c412014-05-21 05:09:00 +0000538 if (!Proto)
Mike Stump1d849212009-12-07 23:38:24 +0000539 return;
540
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000541 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
Richard Smitheaf11ad2018-05-03 03:58:32 +0000542 if (isNoexceptExceptionSpec(EST) && Proto->canThrow() == CT_Cannot) {
543 EHStack.popTerminate();
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000544 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
David Majnemer1f192e22015-04-01 04:45:52 +0000545 // TODO: Revisit exception specifications for the MS ABI. There is a way to
546 // encode these in an object file but MSVC doesn't do anything with it.
547 if (getTarget().getCXXABI().isMicrosoft())
548 return;
John McCall8e4c74b2011-08-11 02:22:43 +0000549 EHFilterScope &filterScope = cast<EHFilterScope>(*EHStack.begin());
550 emitFilterDispatchBlock(*this, filterScope);
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000551 EHStack.popFilter();
552 }
Mike Stump1d849212009-12-07 23:38:24 +0000553}
554
Mike Stump58ef18b2009-11-20 23:44:51 +0000555void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
John McCallb609d3f2010-07-07 06:56:46 +0000556 EnterCXXTryStmt(S);
John McCallb81884d2010-02-19 09:25:03 +0000557 EmitStmt(S.getTryBlock());
John McCallb609d3f2010-07-07 06:56:46 +0000558 ExitCXXTryStmt(S);
John McCallb81884d2010-02-19 09:25:03 +0000559}
560
John McCallb609d3f2010-07-07 06:56:46 +0000561void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallbd309292010-07-06 01:34:17 +0000562 unsigned NumHandlers = S.getNumHandlers();
563 EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
John McCallb81884d2010-02-19 09:25:03 +0000564
John McCallbd309292010-07-06 01:34:17 +0000565 for (unsigned I = 0; I != NumHandlers; ++I) {
566 const CXXCatchStmt *C = S.getHandler(I);
John McCallb81884d2010-02-19 09:25:03 +0000567
John McCallbd309292010-07-06 01:34:17 +0000568 llvm::BasicBlock *Handler = createBasicBlock("catch");
569 if (C->getExceptionDecl()) {
570 // FIXME: Dropping the reference type on the type into makes it
571 // impossible to correctly implement catch-by-reference
572 // semantics for pointers. Unfortunately, this is what all
573 // existing compilers do, and it's not clear that the standard
574 // personality routine is capable of doing this right. See C++ DR 388:
575 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
David Majnemer571162a2014-10-12 06:58:22 +0000576 Qualifiers CaughtTypeQuals;
577 QualType CaughtType = CGM.getContext().getUnqualifiedArrayType(
578 C->getCaughtType().getNonReferenceType(), CaughtTypeQuals);
John McCall2ca705e2010-07-24 00:37:23 +0000579
Reid Kleckner10aa7702015-09-16 20:15:55 +0000580 CatchTypeInfo TypeInfo{nullptr, 0};
John McCall2ca705e2010-07-24 00:37:23 +0000581 if (CaughtType->isObjCObjectPointerType())
Reid Kleckner10aa7702015-09-16 20:15:55 +0000582 TypeInfo.RTTI = CGM.getObjCRuntime().GetEHType(CaughtType);
John McCall2ca705e2010-07-24 00:37:23 +0000583 else
Reid Kleckner10aa7702015-09-16 20:15:55 +0000584 TypeInfo = CGM.getCXXABI().getAddrOfCXXCatchHandlerType(
585 CaughtType, C->getCaughtType());
John McCallbd309292010-07-06 01:34:17 +0000586 CatchScope->setHandler(I, TypeInfo, Handler);
587 } else {
588 // No exception decl indicates '...', a catch-all.
Reid Kleckner10aa7702015-09-16 20:15:55 +0000589 CatchScope->setHandler(I, CGM.getCXXABI().getCatchAllTypeInfo(), Handler);
John McCallbd309292010-07-06 01:34:17 +0000590 }
591 }
John McCallbd309292010-07-06 01:34:17 +0000592}
593
John McCall8e4c74b2011-08-11 02:22:43 +0000594llvm::BasicBlock *
595CodeGenFunction::getEHDispatchBlock(EHScopeStack::stable_iterator si) {
Reid Kleckner129552b2015-10-08 01:13:52 +0000596 if (EHPersonality::get(*this).usesFuncletPads())
Heejin Ahnc6479192018-05-31 22:18:13 +0000597 return getFuncletEHDispatchBlock(si);
David Majnemerdbf10452015-07-31 17:58:45 +0000598
John McCall8e4c74b2011-08-11 02:22:43 +0000599 // The dispatch block for the end of the scope chain is a block that
600 // just resumes unwinding.
601 if (si == EHStack.stable_end())
David Chisnall9a837be2012-11-07 16:50:40 +0000602 return getEHResumeBlock(true);
John McCall8e4c74b2011-08-11 02:22:43 +0000603
604 // Otherwise, we should look at the actual scope.
605 EHScope &scope = *EHStack.find(si);
606
607 llvm::BasicBlock *dispatchBlock = scope.getCachedEHDispatchBlock();
608 if (!dispatchBlock) {
609 switch (scope.getKind()) {
610 case EHScope::Catch: {
611 // Apply a special case to a single catch-all.
612 EHCatchScope &catchScope = cast<EHCatchScope>(scope);
613 if (catchScope.getNumHandlers() == 1 &&
614 catchScope.getHandler(0).isCatchAll()) {
615 dispatchBlock = catchScope.getHandler(0).Block;
616
617 // Otherwise, make a dispatch block.
618 } else {
619 dispatchBlock = createBasicBlock("catch.dispatch");
620 }
621 break;
622 }
623
624 case EHScope::Cleanup:
625 dispatchBlock = createBasicBlock("ehcleanup");
626 break;
627
628 case EHScope::Filter:
629 dispatchBlock = createBasicBlock("filter.dispatch");
630 break;
631
632 case EHScope::Terminate:
633 dispatchBlock = getTerminateHandler();
634 break;
David Majnemerdbf10452015-07-31 17:58:45 +0000635
Reid Kleckner2586aac2015-09-10 22:11:13 +0000636 case EHScope::PadEnd:
637 llvm_unreachable("PadEnd unnecessary for Itanium!");
John McCall8e4c74b2011-08-11 02:22:43 +0000638 }
639 scope.setCachedEHDispatchBlock(dispatchBlock);
640 }
641 return dispatchBlock;
642}
643
David Majnemerdbf10452015-07-31 17:58:45 +0000644llvm::BasicBlock *
Heejin Ahnc6479192018-05-31 22:18:13 +0000645CodeGenFunction::getFuncletEHDispatchBlock(EHScopeStack::stable_iterator SI) {
David Majnemerdbf10452015-07-31 17:58:45 +0000646 // Returning nullptr indicates that the previous dispatch block should unwind
647 // to caller.
648 if (SI == EHStack.stable_end())
649 return nullptr;
650
651 // Otherwise, we should look at the actual scope.
652 EHScope &EHS = *EHStack.find(SI);
653
654 llvm::BasicBlock *DispatchBlock = EHS.getCachedEHDispatchBlock();
655 if (DispatchBlock)
656 return DispatchBlock;
657
658 if (EHS.getKind() == EHScope::Terminate)
Reid Kleckner06f19a02018-01-02 21:34:16 +0000659 DispatchBlock = getTerminateFunclet();
David Majnemerdbf10452015-07-31 17:58:45 +0000660 else
661 DispatchBlock = createBasicBlock();
John McCall7f416cc2015-09-08 08:05:57 +0000662 CGBuilderTy Builder(*this, DispatchBlock);
David Majnemerdbf10452015-07-31 17:58:45 +0000663
664 switch (EHS.getKind()) {
665 case EHScope::Catch:
666 DispatchBlock->setName("catch.dispatch");
667 break;
668
669 case EHScope::Cleanup:
670 DispatchBlock->setName("ehcleanup");
671 break;
672
673 case EHScope::Filter:
674 llvm_unreachable("exception specifications not handled yet!");
675
676 case EHScope::Terminate:
677 DispatchBlock->setName("terminate");
678 break;
679
Reid Kleckner2586aac2015-09-10 22:11:13 +0000680 case EHScope::PadEnd:
681 llvm_unreachable("PadEnd dispatch block missing!");
David Majnemerdbf10452015-07-31 17:58:45 +0000682 }
683 EHS.setCachedEHDispatchBlock(DispatchBlock);
684 return DispatchBlock;
685}
686
John McCallbd309292010-07-06 01:34:17 +0000687/// Check whether this is a non-EH scope, i.e. a scope which doesn't
688/// affect exception handling. Currently, the only non-EH scopes are
689/// normal-only cleanup scopes.
690static bool isNonEHScope(const EHScope &S) {
John McCall2b7fc382010-07-13 20:32:21 +0000691 switch (S.getKind()) {
John McCallcda666c2010-07-21 07:22:38 +0000692 case EHScope::Cleanup:
693 return !cast<EHCleanupScope>(S).isEHCleanup();
John McCall2b7fc382010-07-13 20:32:21 +0000694 case EHScope::Filter:
695 case EHScope::Catch:
696 case EHScope::Terminate:
Reid Kleckner2586aac2015-09-10 22:11:13 +0000697 case EHScope::PadEnd:
John McCall2b7fc382010-07-13 20:32:21 +0000698 return false;
699 }
700
David Blaikiee4d798f2012-01-20 21:50:17 +0000701 llvm_unreachable("Invalid EHScope Kind!");
John McCallbd309292010-07-06 01:34:17 +0000702}
703
704llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
705 assert(EHStack.requiresLandingPad());
706 assert(!EHStack.empty());
707
Reid Kleckner8f1b1f52016-03-01 19:51:48 +0000708 // If exceptions are disabled and SEH is not in use, then there is no invoke
709 // destination. SEH "works" even if exceptions are off. In practice, this
710 // means that C++ destructors and other EH cleanups don't run, which is
711 // consistent with MSVC's behavior.
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000712 const LangOptions &LO = CGM.getLangOpts();
713 if (!LO.Exceptions) {
714 if (!LO.Borland && !LO.MicrosoftExt)
715 return nullptr;
Reid Klecknere7b3f7c2015-02-11 00:00:21 +0000716 if (!currentFunctionUsesSEHTry())
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000717 return nullptr;
718 }
John McCall2b7fc382010-07-13 20:32:21 +0000719
Justin Lebar3e6449b2016-10-04 23:41:49 +0000720 // CUDA device code doesn't have exceptions.
721 if (LO.CUDA && LO.CUDAIsDevice)
722 return nullptr;
723
John McCallbd309292010-07-06 01:34:17 +0000724 // Check the innermost scope for a cached landing pad. If this is
725 // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
726 llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
727 if (LP) return LP;
728
David Majnemerdbf10452015-07-31 17:58:45 +0000729 const EHPersonality &Personality = EHPersonality::get(*this);
730
731 if (!CurFn->hasPersonalityFn())
732 CurFn->setPersonalityFn(getOpaquePersonalityFn(CGM, Personality));
733
Reid Kleckner129552b2015-10-08 01:13:52 +0000734 if (Personality.usesFuncletPads()) {
735 // We don't need separate landing pads in the funclet model.
David Majnemerdbf10452015-07-31 17:58:45 +0000736 LP = getEHDispatchBlock(EHStack.getInnermostEHScope());
737 } else {
738 // Build the landing pad for this scope.
739 LP = EmitLandingPad();
740 }
741
John McCallbd309292010-07-06 01:34:17 +0000742 assert(LP);
743
744 // Cache the landing pad on the innermost scope. If this is a
745 // non-EH scope, cache the landing pad on the enclosing scope, too.
746 for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
747 ir->setCachedLandingPad(LP);
748 if (!isNonEHScope(*ir)) break;
749 }
750
751 return LP;
752}
753
754llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
755 assert(EHStack.requiresLandingPad());
756
John McCall8e4c74b2011-08-11 02:22:43 +0000757 EHScope &innermostEHScope = *EHStack.find(EHStack.getInnermostEHScope());
758 switch (innermostEHScope.getKind()) {
759 case EHScope::Terminate:
760 return getTerminateLandingPad();
John McCallbd309292010-07-06 01:34:17 +0000761
Reid Kleckner2586aac2015-09-10 22:11:13 +0000762 case EHScope::PadEnd:
763 llvm_unreachable("PadEnd unnecessary for Itanium!");
David Majnemerdbf10452015-07-31 17:58:45 +0000764
John McCall8e4c74b2011-08-11 02:22:43 +0000765 case EHScope::Catch:
766 case EHScope::Cleanup:
767 case EHScope::Filter:
768 if (llvm::BasicBlock *lpad = innermostEHScope.getCachedLandingPad())
769 return lpad;
John McCallbd309292010-07-06 01:34:17 +0000770 }
771
772 // Save the current IR generation state.
John McCall8e4c74b2011-08-11 02:22:43 +0000773 CGBuilderTy::InsertPoint savedIP = Builder.saveAndClearIP();
Calixte Denizetfcd661d2018-09-24 18:24:18 +0000774 auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, CurEHLocation);
John McCallbd309292010-07-06 01:34:17 +0000775
776 // Create and configure the landing pad.
John McCall8e4c74b2011-08-11 02:22:43 +0000777 llvm::BasicBlock *lpad = createBasicBlock("lpad");
778 EmitBlock(lpad);
John McCallbd309292010-07-06 01:34:17 +0000779
Serge Guelton1d993272017-05-09 19:31:30 +0000780 llvm::LandingPadInst *LPadInst =
781 Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty), 0);
Bill Wendlingf0724e82011-09-19 20:31:14 +0000782
783 llvm::Value *LPadExn = Builder.CreateExtractValue(LPadInst, 0);
784 Builder.CreateStore(LPadExn, getExceptionSlot());
785 llvm::Value *LPadSel = Builder.CreateExtractValue(LPadInst, 1);
786 Builder.CreateStore(LPadSel, getEHSelectorSlot());
787
John McCallbd309292010-07-06 01:34:17 +0000788 // Save the exception pointer. It's safe to use a single exception
789 // pointer per function because EH cleanups can never have nested
790 // try/catches.
Bill Wendlingf0724e82011-09-19 20:31:14 +0000791 // Build the landingpad instruction.
John McCallbd309292010-07-06 01:34:17 +0000792
793 // Accumulate all the handlers in scope.
John McCall8e4c74b2011-08-11 02:22:43 +0000794 bool hasCatchAll = false;
795 bool hasCleanup = false;
796 bool hasFilter = false;
797 SmallVector<llvm::Value*, 4> filterTypes;
798 llvm::SmallPtrSet<llvm::Value*, 4> catchTypes;
Nico Webere68b9f32015-02-25 16:25:00 +0000799 for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end(); I != E;
800 ++I) {
John McCallbd309292010-07-06 01:34:17 +0000801
802 switch (I->getKind()) {
John McCallcda666c2010-07-21 07:22:38 +0000803 case EHScope::Cleanup:
John McCall8e4c74b2011-08-11 02:22:43 +0000804 // If we have a cleanup, remember that.
805 hasCleanup = (hasCleanup || cast<EHCleanupScope>(*I).isEHCleanup());
John McCall2b7fc382010-07-13 20:32:21 +0000806 continue;
807
John McCallbd309292010-07-06 01:34:17 +0000808 case EHScope::Filter: {
809 assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
John McCall8e4c74b2011-08-11 02:22:43 +0000810 assert(!hasCatchAll && "EH filter reached after catch-all");
John McCallbd309292010-07-06 01:34:17 +0000811
Bill Wendlingf0724e82011-09-19 20:31:14 +0000812 // Filter scopes get added to the landingpad in weird ways.
John McCall8e4c74b2011-08-11 02:22:43 +0000813 EHFilterScope &filter = cast<EHFilterScope>(*I);
814 hasFilter = true;
John McCallbd309292010-07-06 01:34:17 +0000815
Bill Wendling8c4b7162011-09-22 20:32:54 +0000816 // Add all the filter values.
817 for (unsigned i = 0, e = filter.getNumFilters(); i != e; ++i)
818 filterTypes.push_back(filter.getFilter(i));
John McCallbd309292010-07-06 01:34:17 +0000819 goto done;
820 }
821
822 case EHScope::Terminate:
823 // Terminate scopes are basically catch-alls.
John McCall8e4c74b2011-08-11 02:22:43 +0000824 assert(!hasCatchAll);
825 hasCatchAll = true;
John McCallbd309292010-07-06 01:34:17 +0000826 goto done;
827
828 case EHScope::Catch:
829 break;
David Majnemerdbf10452015-07-31 17:58:45 +0000830
Reid Kleckner2586aac2015-09-10 22:11:13 +0000831 case EHScope::PadEnd:
832 llvm_unreachable("PadEnd unnecessary for Itanium!");
John McCallbd309292010-07-06 01:34:17 +0000833 }
834
John McCall8e4c74b2011-08-11 02:22:43 +0000835 EHCatchScope &catchScope = cast<EHCatchScope>(*I);
836 for (unsigned hi = 0, he = catchScope.getNumHandlers(); hi != he; ++hi) {
837 EHCatchScope::Handler handler = catchScope.getHandler(hi);
Reid Kleckner10aa7702015-09-16 20:15:55 +0000838 assert(handler.Type.Flags == 0 &&
839 "landingpads do not support catch handler flags");
John McCallbd309292010-07-06 01:34:17 +0000840
John McCall8e4c74b2011-08-11 02:22:43 +0000841 // If this is a catch-all, register that and abort.
Reid Kleckner10aa7702015-09-16 20:15:55 +0000842 if (!handler.Type.RTTI) {
John McCall8e4c74b2011-08-11 02:22:43 +0000843 assert(!hasCatchAll);
844 hasCatchAll = true;
845 goto done;
John McCallbd309292010-07-06 01:34:17 +0000846 }
847
848 // Check whether we already have a handler for this type.
Reid Kleckner10aa7702015-09-16 20:15:55 +0000849 if (catchTypes.insert(handler.Type.RTTI).second)
Bill Wendlingf0724e82011-09-19 20:31:14 +0000850 // If not, add it directly to the landingpad.
Reid Kleckner10aa7702015-09-16 20:15:55 +0000851 LPadInst->addClause(handler.Type.RTTI);
John McCallbd309292010-07-06 01:34:17 +0000852 }
John McCallbd309292010-07-06 01:34:17 +0000853 }
854
855 done:
Bill Wendlingf0724e82011-09-19 20:31:14 +0000856 // If we have a catch-all, add null to the landingpad.
John McCall8e4c74b2011-08-11 02:22:43 +0000857 assert(!(hasCatchAll && hasFilter));
858 if (hasCatchAll) {
Bill Wendlingf0724e82011-09-19 20:31:14 +0000859 LPadInst->addClause(getCatchAllValue(*this));
John McCallbd309292010-07-06 01:34:17 +0000860
861 // If we have an EH filter, we need to add those handlers in the
Bill Wendlingf0724e82011-09-19 20:31:14 +0000862 // right place in the landingpad, which is to say, at the end.
John McCall8e4c74b2011-08-11 02:22:43 +0000863 } else if (hasFilter) {
Bill Wendling58e58fe2011-09-19 22:08:36 +0000864 // Create a filter expression: a constant array indicating which filter
865 // types there are. The personality routine only lands here if the filter
866 // doesn't match.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000867 SmallVector<llvm::Constant*, 8> Filters;
Bill Wendlingf0724e82011-09-19 20:31:14 +0000868 llvm::ArrayType *AType =
869 llvm::ArrayType::get(!filterTypes.empty() ?
870 filterTypes[0]->getType() : Int8PtrTy,
871 filterTypes.size());
872
873 for (unsigned i = 0, e = filterTypes.size(); i != e; ++i)
874 Filters.push_back(cast<llvm::Constant>(filterTypes[i]));
875 llvm::Constant *FilterArray = llvm::ConstantArray::get(AType, Filters);
876 LPadInst->addClause(FilterArray);
John McCallbd309292010-07-06 01:34:17 +0000877
878 // Also check whether we need a cleanup.
Bill Wendlingf0724e82011-09-19 20:31:14 +0000879 if (hasCleanup)
880 LPadInst->setCleanup(true);
John McCallbd309292010-07-06 01:34:17 +0000881
882 // Otherwise, signal that we at least have cleanups.
Logan Chiene9c8ccb2014-07-01 11:47:10 +0000883 } else if (hasCleanup) {
884 LPadInst->setCleanup(true);
John McCallbd309292010-07-06 01:34:17 +0000885 }
886
Bill Wendlingf0724e82011-09-19 20:31:14 +0000887 assert((LPadInst->getNumClauses() > 0 || LPadInst->isCleanup()) &&
888 "landingpad instruction has no clauses!");
John McCallbd309292010-07-06 01:34:17 +0000889
890 // Tell the backend how to generate the landing pad.
John McCall8e4c74b2011-08-11 02:22:43 +0000891 Builder.CreateBr(getEHDispatchBlock(EHStack.getInnermostEHScope()));
John McCallbd309292010-07-06 01:34:17 +0000892
893 // Restore the old IR generation state.
John McCall8e4c74b2011-08-11 02:22:43 +0000894 Builder.restoreIP(savedIP);
John McCallbd309292010-07-06 01:34:17 +0000895
John McCall8e4c74b2011-08-11 02:22:43 +0000896 return lpad;
John McCallbd309292010-07-06 01:34:17 +0000897}
898
David Majnemer4e52d6f2015-12-12 05:39:21 +0000899static void emitCatchPadBlock(CodeGenFunction &CGF, EHCatchScope &CatchScope) {
David Majnemerdbf10452015-07-31 17:58:45 +0000900 llvm::BasicBlock *DispatchBlock = CatchScope.getCachedEHDispatchBlock();
901 assert(DispatchBlock);
902
903 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveIP();
904 CGF.EmitBlockAfterUses(DispatchBlock);
905
David Majnemer4e52d6f2015-12-12 05:39:21 +0000906 llvm::Value *ParentPad = CGF.CurrentFuncletPad;
907 if (!ParentPad)
908 ParentPad = llvm::ConstantTokenNone::get(CGF.getLLVMContext());
909 llvm::BasicBlock *UnwindBB =
910 CGF.getEHDispatchBlock(CatchScope.getEnclosingEHScope());
911
912 unsigned NumHandlers = CatchScope.getNumHandlers();
913 llvm::CatchSwitchInst *CatchSwitch =
914 CGF.Builder.CreateCatchSwitch(ParentPad, UnwindBB, NumHandlers);
David Majnemerdbf10452015-07-31 17:58:45 +0000915
916 // Test against each of the exception types we claim to catch.
David Majnemer4e52d6f2015-12-12 05:39:21 +0000917 for (unsigned I = 0; I < NumHandlers; ++I) {
David Majnemerdbf10452015-07-31 17:58:45 +0000918 const EHCatchScope::Handler &Handler = CatchScope.getHandler(I);
919
Reid Kleckner10aa7702015-09-16 20:15:55 +0000920 CatchTypeInfo TypeInfo = Handler.Type;
921 if (!TypeInfo.RTTI)
922 TypeInfo.RTTI = llvm::Constant::getNullValue(CGF.VoidPtrTy);
David Majnemerdbf10452015-07-31 17:58:45 +0000923
David Majnemer4e52d6f2015-12-12 05:39:21 +0000924 CGF.Builder.SetInsertPoint(Handler.Block);
David Majnemerdbf10452015-07-31 17:58:45 +0000925
926 if (EHPersonality::get(CGF).isMSVCXXPersonality()) {
David Majnemer4e52d6f2015-12-12 05:39:21 +0000927 CGF.Builder.CreateCatchPad(
928 CatchSwitch, {TypeInfo.RTTI, CGF.Builder.getInt32(TypeInfo.Flags),
929 llvm::Constant::getNullValue(CGF.VoidPtrTy)});
David Majnemerdbf10452015-07-31 17:58:45 +0000930 } else {
David Majnemer4e52d6f2015-12-12 05:39:21 +0000931 CGF.Builder.CreateCatchPad(CatchSwitch, {TypeInfo.RTTI});
David Majnemerdbf10452015-07-31 17:58:45 +0000932 }
933
David Majnemer4e52d6f2015-12-12 05:39:21 +0000934 CatchSwitch->addHandler(Handler.Block);
David Majnemerdbf10452015-07-31 17:58:45 +0000935 }
936 CGF.Builder.restoreIP(SavedIP);
David Majnemerdbf10452015-07-31 17:58:45 +0000937}
938
Heejin Ahnc6479192018-05-31 22:18:13 +0000939// Wasm uses Windows-style EH instructions, but it merges all catch clauses into
940// one big catchpad, within which we use Itanium's landingpad-style selector
941// comparison instructions.
942static void emitWasmCatchPadBlock(CodeGenFunction &CGF,
943 EHCatchScope &CatchScope) {
944 llvm::BasicBlock *DispatchBlock = CatchScope.getCachedEHDispatchBlock();
945 assert(DispatchBlock);
946
947 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveIP();
948 CGF.EmitBlockAfterUses(DispatchBlock);
949
950 llvm::Value *ParentPad = CGF.CurrentFuncletPad;
951 if (!ParentPad)
952 ParentPad = llvm::ConstantTokenNone::get(CGF.getLLVMContext());
953 llvm::BasicBlock *UnwindBB =
954 CGF.getEHDispatchBlock(CatchScope.getEnclosingEHScope());
955
956 unsigned NumHandlers = CatchScope.getNumHandlers();
957 llvm::CatchSwitchInst *CatchSwitch =
958 CGF.Builder.CreateCatchSwitch(ParentPad, UnwindBB, NumHandlers);
959
960 // We don't use a landingpad instruction, so generate intrinsic calls to
961 // provide exception and selector values.
962 llvm::BasicBlock *WasmCatchStartBlock = CGF.createBasicBlock("catch.start");
963 CatchSwitch->addHandler(WasmCatchStartBlock);
964 CGF.EmitBlockAfterUses(WasmCatchStartBlock);
965
966 // Create a catchpad instruction.
967 SmallVector<llvm::Value *, 4> CatchTypes;
968 for (unsigned I = 0, E = NumHandlers; I < E; ++I) {
969 const EHCatchScope::Handler &Handler = CatchScope.getHandler(I);
970 CatchTypeInfo TypeInfo = Handler.Type;
971 if (!TypeInfo.RTTI)
972 TypeInfo.RTTI = llvm::Constant::getNullValue(CGF.VoidPtrTy);
973 CatchTypes.push_back(TypeInfo.RTTI);
974 }
975 auto *CPI = CGF.Builder.CreateCatchPad(CatchSwitch, CatchTypes);
976
977 // Create calls to wasm.get.exception and wasm.get.ehselector intrinsics.
978 // Before they are lowered appropriately later, they provide values for the
979 // exception and selector.
James Y Knight8799cae2019-02-03 21:53:49 +0000980 llvm::Function *GetExnFn =
Heejin Ahnc6479192018-05-31 22:18:13 +0000981 CGF.CGM.getIntrinsic(llvm::Intrinsic::wasm_get_exception);
James Y Knight8799cae2019-02-03 21:53:49 +0000982 llvm::Function *GetSelectorFn =
Heejin Ahnc6479192018-05-31 22:18:13 +0000983 CGF.CGM.getIntrinsic(llvm::Intrinsic::wasm_get_ehselector);
984 llvm::CallInst *Exn = CGF.Builder.CreateCall(GetExnFn, CPI);
985 CGF.Builder.CreateStore(Exn, CGF.getExceptionSlot());
986 llvm::CallInst *Selector = CGF.Builder.CreateCall(GetSelectorFn, CPI);
987
James Y Knight8799cae2019-02-03 21:53:49 +0000988 llvm::Function *TypeIDFn = CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
Heejin Ahnc6479192018-05-31 22:18:13 +0000989
990 // If there's only a single catch-all, branch directly to its handler.
991 if (CatchScope.getNumHandlers() == 1 &&
992 CatchScope.getHandler(0).isCatchAll()) {
993 CGF.Builder.CreateBr(CatchScope.getHandler(0).Block);
994 CGF.Builder.restoreIP(SavedIP);
995 return;
996 }
997
998 // Test against each of the exception types we claim to catch.
999 for (unsigned I = 0, E = NumHandlers;; ++I) {
1000 assert(I < E && "ran off end of handlers!");
1001 const EHCatchScope::Handler &Handler = CatchScope.getHandler(I);
1002 CatchTypeInfo TypeInfo = Handler.Type;
1003 if (!TypeInfo.RTTI)
1004 TypeInfo.RTTI = llvm::Constant::getNullValue(CGF.VoidPtrTy);
1005
1006 // Figure out the next block.
1007 llvm::BasicBlock *NextBlock;
1008
1009 bool EmitNextBlock = false, NextIsEnd = false;
1010
1011 // If this is the last handler, we're at the end, and the next block is a
1012 // block that contains a call to the rethrow function, so we can unwind to
1013 // the enclosing EH scope. The call itself will be generated later.
1014 if (I + 1 == E) {
1015 NextBlock = CGF.createBasicBlock("rethrow");
1016 EmitNextBlock = true;
1017 NextIsEnd = true;
1018
1019 // If the next handler is a catch-all, we're at the end, and the
1020 // next block is that handler.
1021 } else if (CatchScope.getHandler(I + 1).isCatchAll()) {
1022 NextBlock = CatchScope.getHandler(I + 1).Block;
1023 NextIsEnd = true;
1024
1025 // Otherwise, we're not at the end and we need a new block.
1026 } else {
1027 NextBlock = CGF.createBasicBlock("catch.fallthrough");
1028 EmitNextBlock = true;
1029 }
1030
1031 // Figure out the catch type's index in the LSDA's type table.
1032 llvm::CallInst *TypeIndex = CGF.Builder.CreateCall(TypeIDFn, TypeInfo.RTTI);
1033 TypeIndex->setDoesNotThrow();
1034
1035 llvm::Value *MatchesTypeIndex =
1036 CGF.Builder.CreateICmpEQ(Selector, TypeIndex, "matches");
1037 CGF.Builder.CreateCondBr(MatchesTypeIndex, Handler.Block, NextBlock);
1038
1039 if (EmitNextBlock)
1040 CGF.EmitBlock(NextBlock);
1041 if (NextIsEnd)
1042 break;
1043 }
1044
1045 CGF.Builder.restoreIP(SavedIP);
1046}
1047
John McCall8e4c74b2011-08-11 02:22:43 +00001048/// Emit the structure of the dispatch block for the given catch scope.
1049/// It is an invariant that the dispatch block already exists.
David Majnemer4e52d6f2015-12-12 05:39:21 +00001050static void emitCatchDispatchBlock(CodeGenFunction &CGF,
1051 EHCatchScope &catchScope) {
Heejin Ahnc6479192018-05-31 22:18:13 +00001052 if (EHPersonality::get(CGF).isWasmPersonality())
1053 return emitWasmCatchPadBlock(CGF, catchScope);
Reid Kleckner129552b2015-10-08 01:13:52 +00001054 if (EHPersonality::get(CGF).usesFuncletPads())
1055 return emitCatchPadBlock(CGF, catchScope);
David Majnemerdbf10452015-07-31 17:58:45 +00001056
John McCall8e4c74b2011-08-11 02:22:43 +00001057 llvm::BasicBlock *dispatchBlock = catchScope.getCachedEHDispatchBlock();
1058 assert(dispatchBlock);
1059
1060 // If there's only a single catch-all, getEHDispatchBlock returned
1061 // that catch-all as the dispatch block.
1062 if (catchScope.getNumHandlers() == 1 &&
1063 catchScope.getHandler(0).isCatchAll()) {
1064 assert(dispatchBlock == catchScope.getHandler(0).Block);
David Majnemer4e52d6f2015-12-12 05:39:21 +00001065 return;
John McCall8e4c74b2011-08-11 02:22:43 +00001066 }
1067
1068 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveIP();
1069 CGF.EmitBlockAfterUses(dispatchBlock);
1070
1071 // Select the right handler.
James Y Knight8799cae2019-02-03 21:53:49 +00001072 llvm::Function *llvm_eh_typeid_for =
John McCall8e4c74b2011-08-11 02:22:43 +00001073 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
1074
1075 // Load the selector value.
Bill Wendling79a70e42011-09-15 18:57:19 +00001076 llvm::Value *selector = CGF.getSelectorFromSlot();
John McCall8e4c74b2011-08-11 02:22:43 +00001077
1078 // Test against each of the exception types we claim to catch.
1079 for (unsigned i = 0, e = catchScope.getNumHandlers(); ; ++i) {
1080 assert(i < e && "ran off end of handlers!");
1081 const EHCatchScope::Handler &handler = catchScope.getHandler(i);
1082
Reid Kleckner10aa7702015-09-16 20:15:55 +00001083 llvm::Value *typeValue = handler.Type.RTTI;
1084 assert(handler.Type.Flags == 0 &&
1085 "landingpads do not support catch handler flags");
John McCall8e4c74b2011-08-11 02:22:43 +00001086 assert(typeValue && "fell into catch-all case!");
1087 typeValue = CGF.Builder.CreateBitCast(typeValue, CGF.Int8PtrTy);
1088
1089 // Figure out the next block.
1090 bool nextIsEnd;
1091 llvm::BasicBlock *nextBlock;
1092
1093 // If this is the last handler, we're at the end, and the next
1094 // block is the block for the enclosing EH scope.
1095 if (i + 1 == e) {
1096 nextBlock = CGF.getEHDispatchBlock(catchScope.getEnclosingEHScope());
1097 nextIsEnd = true;
1098
1099 // If the next handler is a catch-all, we're at the end, and the
1100 // next block is that handler.
1101 } else if (catchScope.getHandler(i+1).isCatchAll()) {
1102 nextBlock = catchScope.getHandler(i+1).Block;
1103 nextIsEnd = true;
1104
1105 // Otherwise, we're not at the end and we need a new block.
1106 } else {
1107 nextBlock = CGF.createBasicBlock("catch.fallthrough");
1108 nextIsEnd = false;
1109 }
1110
1111 // Figure out the catch type's index in the LSDA's type table.
1112 llvm::CallInst *typeIndex =
1113 CGF.Builder.CreateCall(llvm_eh_typeid_for, typeValue);
1114 typeIndex->setDoesNotThrow();
1115
1116 llvm::Value *matchesTypeIndex =
1117 CGF.Builder.CreateICmpEQ(selector, typeIndex, "matches");
1118 CGF.Builder.CreateCondBr(matchesTypeIndex, handler.Block, nextBlock);
1119
1120 // If the next handler is a catch-all, we're completely done.
1121 if (nextIsEnd) {
1122 CGF.Builder.restoreIP(savedIP);
David Majnemer4e52d6f2015-12-12 05:39:21 +00001123 return;
John McCall8e4c74b2011-08-11 02:22:43 +00001124 }
Ahmed Charles289896d2012-02-19 11:57:29 +00001125 // Otherwise we need to emit and continue at that block.
1126 CGF.EmitBlock(nextBlock);
John McCall8e4c74b2011-08-11 02:22:43 +00001127 }
John McCall8e4c74b2011-08-11 02:22:43 +00001128}
1129
1130void CodeGenFunction::popCatchScope() {
1131 EHCatchScope &catchScope = cast<EHCatchScope>(*EHStack.begin());
1132 if (catchScope.hasEHBranches())
1133 emitCatchDispatchBlock(*this, catchScope);
1134 EHStack.popCatch();
1135}
1136
John McCallb609d3f2010-07-07 06:56:46 +00001137void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallbd309292010-07-06 01:34:17 +00001138 unsigned NumHandlers = S.getNumHandlers();
1139 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1140 assert(CatchScope.getNumHandlers() == NumHandlers);
Heejin Ahnc6479192018-05-31 22:18:13 +00001141 llvm::BasicBlock *DispatchBlock = CatchScope.getCachedEHDispatchBlock();
Mike Stump58ef18b2009-11-20 23:44:51 +00001142
John McCall8e4c74b2011-08-11 02:22:43 +00001143 // If the catch was not required, bail out now.
1144 if (!CatchScope.hasEHBranches()) {
Kostya Serebryanyba4aced2014-01-09 09:22:32 +00001145 CatchScope.clearHandlerBlocks();
John McCall8e4c74b2011-08-11 02:22:43 +00001146 EHStack.popCatch();
1147 return;
1148 }
1149
1150 // Emit the structure of the EH dispatch for this catch.
David Majnemer4e52d6f2015-12-12 05:39:21 +00001151 emitCatchDispatchBlock(*this, CatchScope);
John McCall8e4c74b2011-08-11 02:22:43 +00001152
John McCallbd309292010-07-06 01:34:17 +00001153 // Copy the handler blocks off before we pop the EH stack. Emitting
1154 // the handlers might scribble on this memory.
Benjamin Kramerda32cf82015-08-04 15:38:49 +00001155 SmallVector<EHCatchScope::Handler, 8> Handlers(
1156 CatchScope.begin(), CatchScope.begin() + NumHandlers);
John McCall8e4c74b2011-08-11 02:22:43 +00001157
John McCallbd309292010-07-06 01:34:17 +00001158 EHStack.popCatch();
Mike Stump58ef18b2009-11-20 23:44:51 +00001159
John McCallbd309292010-07-06 01:34:17 +00001160 // The fall-through block.
1161 llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
Mike Stump58ef18b2009-11-20 23:44:51 +00001162
John McCallbd309292010-07-06 01:34:17 +00001163 // We just emitted the body of the try; jump to the continue block.
1164 if (HaveInsertPoint())
1165 Builder.CreateBr(ContBB);
Mike Stump97329152009-12-02 19:53:57 +00001166
John McCalld8d00be2012-06-15 05:27:05 +00001167 // Determine if we need an implicit rethrow for all these catch handlers;
1168 // see the comment below.
1169 bool doImplicitRethrow = false;
John McCallb609d3f2010-07-07 06:56:46 +00001170 if (IsFnTryBlock)
John McCalld8d00be2012-06-15 05:27:05 +00001171 doImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
1172 isa<CXXConstructorDecl>(CurCodeDecl);
John McCallb609d3f2010-07-07 06:56:46 +00001173
Heejin Ahnc6479192018-05-31 22:18:13 +00001174 // Wasm uses Windows-style EH instructions, but merges all catch clauses into
1175 // one big catchpad. So we save the old funclet pad here before we traverse
1176 // each catch handler.
1177 SaveAndRestore<llvm::Instruction *> RestoreCurrentFuncletPad(
1178 CurrentFuncletPad);
1179 llvm::BasicBlock *WasmCatchStartBlock = nullptr;
1180 if (EHPersonality::get(*this).isWasmPersonality()) {
1181 auto *CatchSwitch =
1182 cast<llvm::CatchSwitchInst>(DispatchBlock->getFirstNonPHI());
1183 WasmCatchStartBlock = CatchSwitch->hasUnwindDest()
1184 ? CatchSwitch->getSuccessor(1)
1185 : CatchSwitch->getSuccessor(0);
1186 auto *CPI = cast<llvm::CatchPadInst>(WasmCatchStartBlock->getFirstNonPHI());
1187 CurrentFuncletPad = CPI;
1188 }
1189
John McCall8e4c74b2011-08-11 02:22:43 +00001190 // Perversely, we emit the handlers backwards precisely because we
1191 // want them to appear in source order. In all of these cases, the
1192 // catch block will have exactly one predecessor, which will be a
1193 // particular block in the catch dispatch. However, in the case of
1194 // a catch-all, one of the dispatch blocks will branch to two
1195 // different handlers, and EmitBlockAfterUses will cause the second
1196 // handler to be moved before the first.
Heejin Ahnc6479192018-05-31 22:18:13 +00001197 bool HasCatchAll = false;
John McCall8e4c74b2011-08-11 02:22:43 +00001198 for (unsigned I = NumHandlers; I != 0; --I) {
Heejin Ahnc6479192018-05-31 22:18:13 +00001199 HasCatchAll |= Handlers[I - 1].isCatchAll();
John McCall8e4c74b2011-08-11 02:22:43 +00001200 llvm::BasicBlock *CatchBlock = Handlers[I-1].Block;
1201 EmitBlockAfterUses(CatchBlock);
Mike Stump75546b82009-12-10 00:06:18 +00001202
John McCallbd309292010-07-06 01:34:17 +00001203 // Catch the exception if this isn't a catch-all.
John McCall8e4c74b2011-08-11 02:22:43 +00001204 const CXXCatchStmt *C = S.getHandler(I-1);
Mike Stump58ef18b2009-11-20 23:44:51 +00001205
John McCallbd309292010-07-06 01:34:17 +00001206 // Enter a cleanup scope, including the catch variable and the
1207 // end-catch.
1208 RunCleanupsScope CatchScope(*this);
Mike Stump58ef18b2009-11-20 23:44:51 +00001209
John McCallbd309292010-07-06 01:34:17 +00001210 // Initialize the catch variable and set up the cleanups.
David Majnemer4e52d6f2015-12-12 05:39:21 +00001211 SaveAndRestore<llvm::Instruction *> RestoreCurrentFuncletPad(
1212 CurrentFuncletPad);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00001213 CGM.getCXXABI().emitBeginCatch(*this, C);
John McCallbd309292010-07-06 01:34:17 +00001214
Justin Bognerea278c32014-01-07 00:20:28 +00001215 // Emit the PGO counter increment.
Justin Bogner66242d62015-04-23 23:06:47 +00001216 incrementProfileCounter(C);
Justin Bogneref512b92014-01-06 22:27:43 +00001217
John McCallbd309292010-07-06 01:34:17 +00001218 // Perform the body of the catch.
1219 EmitStmt(C->getHandlerBlock());
1220
John McCalld8d00be2012-06-15 05:27:05 +00001221 // [except.handle]p11:
1222 // The currently handled exception is rethrown if control
1223 // reaches the end of a handler of the function-try-block of a
1224 // constructor or destructor.
1225
1226 // It is important that we only do this on fallthrough and not on
1227 // return. Note that it's illegal to put a return in a
1228 // constructor function-try-block's catch handler (p14), so this
1229 // really only applies to destructors.
1230 if (doImplicitRethrow && HaveInsertPoint()) {
David Majnemer442d0a22014-11-25 07:20:20 +00001231 CGM.getCXXABI().emitRethrow(*this, /*isNoReturn*/false);
John McCalld8d00be2012-06-15 05:27:05 +00001232 Builder.CreateUnreachable();
1233 Builder.ClearInsertionPoint();
1234 }
1235
John McCallbd309292010-07-06 01:34:17 +00001236 // Fall out through the catch cleanups.
1237 CatchScope.ForceCleanup();
1238
1239 // Branch out of the try.
1240 if (HaveInsertPoint())
1241 Builder.CreateBr(ContBB);
Mike Stump58ef18b2009-11-20 23:44:51 +00001242 }
1243
Heejin Ahnc6479192018-05-31 22:18:13 +00001244 // Because in wasm we merge all catch clauses into one big catchpad, in case
1245 // none of the types in catch handlers matches after we test against each of
1246 // them, we should unwind to the next EH enclosing scope. We generate a call
1247 // to rethrow function here to do that.
1248 if (EHPersonality::get(*this).isWasmPersonality() && !HasCatchAll) {
1249 assert(WasmCatchStartBlock);
1250 // Navigate for the "rethrow" block we created in emitWasmCatchPadBlock().
1251 // Wasm uses landingpad-style conditional branches to compare selectors, so
1252 // we follow the false destination for each of the cond branches to reach
1253 // the rethrow block.
1254 llvm::BasicBlock *RethrowBlock = WasmCatchStartBlock;
Chandler Carruthe303c872018-10-15 10:42:50 +00001255 while (llvm::Instruction *TI = RethrowBlock->getTerminator()) {
Heejin Ahnc6479192018-05-31 22:18:13 +00001256 auto *BI = cast<llvm::BranchInst>(TI);
1257 assert(BI->isConditional());
1258 RethrowBlock = BI->getSuccessor(1);
1259 }
1260 assert(RethrowBlock != WasmCatchStartBlock && RethrowBlock->empty());
1261 Builder.SetInsertPoint(RethrowBlock);
Heejin Ahn7e66a502019-03-16 05:39:12 +00001262 llvm::Function *RethrowInCatchFn =
1263 CGM.getIntrinsic(llvm::Intrinsic::wasm_rethrow_in_catch);
1264 EmitNoreturnRuntimeCallOrInvoke(RethrowInCatchFn, {});
Heejin Ahnc6479192018-05-31 22:18:13 +00001265 }
1266
John McCallbd309292010-07-06 01:34:17 +00001267 EmitBlock(ContBB);
Justin Bogner66242d62015-04-23 23:06:47 +00001268 incrementProfileCounter(&S);
Mike Stump58ef18b2009-11-20 23:44:51 +00001269}
Mike Stumpaff69af2009-12-09 03:35:49 +00001270
John McCall1e670402010-07-21 00:52:03 +00001271namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001272 struct CallEndCatchForFinally final : EHScopeStack::Cleanup {
John McCall1e670402010-07-21 00:52:03 +00001273 llvm::Value *ForEHVar;
James Y Knight9871db02019-02-05 16:42:33 +00001274 llvm::FunctionCallee EndCatchFn;
1275 CallEndCatchForFinally(llvm::Value *ForEHVar,
1276 llvm::FunctionCallee EndCatchFn)
1277 : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
John McCall1e670402010-07-21 00:52:03 +00001278
Craig Topper4f12f102014-03-12 06:41:41 +00001279 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall1e670402010-07-21 00:52:03 +00001280 llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
1281 llvm::BasicBlock *CleanupContBB =
1282 CGF.createBasicBlock("finally.cleanup.cont");
1283
1284 llvm::Value *ShouldEndCatch =
John McCall7f416cc2015-09-08 08:05:57 +00001285 CGF.Builder.CreateFlagLoad(ForEHVar, "finally.endcatch");
John McCall1e670402010-07-21 00:52:03 +00001286 CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1287 CGF.EmitBlock(EndCatchBB);
John McCall882987f2013-02-28 19:01:20 +00001288 CGF.EmitRuntimeCallOrInvoke(EndCatchFn); // catch-all, so might throw
John McCall1e670402010-07-21 00:52:03 +00001289 CGF.EmitBlock(CleanupContBB);
1290 }
1291 };
John McCall906da4b2010-07-21 05:47:49 +00001292
David Blaikie7e70d682015-08-18 22:40:54 +00001293 struct PerformFinally final : EHScopeStack::Cleanup {
John McCall906da4b2010-07-21 05:47:49 +00001294 const Stmt *Body;
1295 llvm::Value *ForEHVar;
James Y Knight9871db02019-02-05 16:42:33 +00001296 llvm::FunctionCallee EndCatchFn;
1297 llvm::FunctionCallee RethrowFn;
John McCall906da4b2010-07-21 05:47:49 +00001298 llvm::Value *SavedExnVar;
1299
1300 PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
James Y Knight9871db02019-02-05 16:42:33 +00001301 llvm::FunctionCallee EndCatchFn,
1302 llvm::FunctionCallee RethrowFn, llvm::Value *SavedExnVar)
1303 : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1304 RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
John McCall906da4b2010-07-21 05:47:49 +00001305
Craig Topper4f12f102014-03-12 06:41:41 +00001306 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall906da4b2010-07-21 05:47:49 +00001307 // Enter a cleanup to call the end-catch function if one was provided.
1308 if (EndCatchFn)
John McCallcda666c2010-07-21 07:22:38 +00001309 CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
1310 ForEHVar, EndCatchFn);
John McCall906da4b2010-07-21 05:47:49 +00001311
John McCallcebe0ca2010-08-11 00:16:14 +00001312 // Save the current cleanup destination in case there are
1313 // cleanups in the finally block.
1314 llvm::Value *SavedCleanupDest =
1315 CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
1316 "cleanup.dest.saved");
1317
John McCall906da4b2010-07-21 05:47:49 +00001318 // Emit the finally block.
1319 CGF.EmitStmt(Body);
1320
1321 // If the end of the finally is reachable, check whether this was
1322 // for EH. If so, rethrow.
1323 if (CGF.HaveInsertPoint()) {
1324 llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
1325 llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
1326
1327 llvm::Value *ShouldRethrow =
John McCall7f416cc2015-09-08 08:05:57 +00001328 CGF.Builder.CreateFlagLoad(ForEHVar, "finally.shouldthrow");
John McCall906da4b2010-07-21 05:47:49 +00001329 CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1330
1331 CGF.EmitBlock(RethrowBB);
1332 if (SavedExnVar) {
John McCall882987f2013-02-28 19:01:20 +00001333 CGF.EmitRuntimeCallOrInvoke(RethrowFn,
John McCall7f416cc2015-09-08 08:05:57 +00001334 CGF.Builder.CreateAlignedLoad(SavedExnVar, CGF.getPointerAlign()));
John McCall906da4b2010-07-21 05:47:49 +00001335 } else {
John McCall882987f2013-02-28 19:01:20 +00001336 CGF.EmitRuntimeCallOrInvoke(RethrowFn);
John McCall906da4b2010-07-21 05:47:49 +00001337 }
1338 CGF.Builder.CreateUnreachable();
1339
1340 CGF.EmitBlock(ContBB);
John McCallcebe0ca2010-08-11 00:16:14 +00001341
1342 // Restore the cleanup destination.
1343 CGF.Builder.CreateStore(SavedCleanupDest,
1344 CGF.getNormalCleanupDestSlot());
John McCall906da4b2010-07-21 05:47:49 +00001345 }
1346
1347 // Leave the end-catch cleanup. As an optimization, pretend that
1348 // the fallthrough path was inaccessible; we've dynamically proven
1349 // that we're not in the EH case along that path.
1350 if (EndCatchFn) {
1351 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1352 CGF.PopCleanupBlock();
1353 CGF.Builder.restoreIP(SavedIP);
1354 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001355
John McCall906da4b2010-07-21 05:47:49 +00001356 // Now make sure we actually have an insertion point or the
1357 // cleanup gods will hate us.
1358 CGF.EnsureInsertPoint();
1359 }
1360 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00001361} // end anonymous namespace
John McCall1e670402010-07-21 00:52:03 +00001362
John McCallbd309292010-07-06 01:34:17 +00001363/// Enters a finally block for an implementation using zero-cost
1364/// exceptions. This is mostly general, but hard-codes some
1365/// language/ABI-specific behavior in the catch-all sections.
James Y Knight9871db02019-02-05 16:42:33 +00001366void CodeGenFunction::FinallyInfo::enter(CodeGenFunction &CGF, const Stmt *body,
1367 llvm::FunctionCallee beginCatchFn,
1368 llvm::FunctionCallee endCatchFn,
1369 llvm::FunctionCallee rethrowFn) {
1370 assert((!!beginCatchFn) == (!!endCatchFn) &&
John McCallbd309292010-07-06 01:34:17 +00001371 "begin/end catch functions not paired");
John McCall6b0feb72011-06-22 02:32:12 +00001372 assert(rethrowFn && "rethrow function is required");
1373
1374 BeginCatchFn = beginCatchFn;
Mike Stumpaff69af2009-12-09 03:35:49 +00001375
John McCallbd309292010-07-06 01:34:17 +00001376 // The rethrow function has one of the following two types:
1377 // void (*)()
1378 // void (*)(void*)
1379 // In the latter case we need to pass it the exception object.
1380 // But we can't use the exception slot because the @finally might
1381 // have a landing pad (which would overwrite the exception slot).
James Y Knight9871db02019-02-05 16:42:33 +00001382 llvm::FunctionType *rethrowFnTy = rethrowFn.getFunctionType();
Craig Topper8a13c412014-05-21 05:09:00 +00001383 SavedExnVar = nullptr;
John McCall6b0feb72011-06-22 02:32:12 +00001384 if (rethrowFnTy->getNumParams())
1385 SavedExnVar = CGF.CreateTempAlloca(CGF.Int8PtrTy, "finally.exn");
Mike Stumpaff69af2009-12-09 03:35:49 +00001386
John McCallbd309292010-07-06 01:34:17 +00001387 // A finally block is a statement which must be executed on any edge
1388 // out of a given scope. Unlike a cleanup, the finally block may
1389 // contain arbitrary control flow leading out of itself. In
1390 // addition, finally blocks should always be executed, even if there
1391 // are no catch handlers higher on the stack. Therefore, we
1392 // surround the protected scope with a combination of a normal
1393 // cleanup (to catch attempts to break out of the block via normal
1394 // control flow) and an EH catch-all (semantically "outside" any try
1395 // statement to which the finally block might have been attached).
1396 // The finally block itself is generated in the context of a cleanup
1397 // which conditionally leaves the catch-all.
John McCall21886962010-04-21 10:05:39 +00001398
John McCallbd309292010-07-06 01:34:17 +00001399 // Jump destination for performing the finally block on an exception
1400 // edge. We'll never actually reach this block, so unreachable is
1401 // fine.
John McCall6b0feb72011-06-22 02:32:12 +00001402 RethrowDest = CGF.getJumpDestInCurrentScope(CGF.getUnreachableBlock());
John McCall21886962010-04-21 10:05:39 +00001403
John McCallbd309292010-07-06 01:34:17 +00001404 // Whether the finally block is being executed for EH purposes.
John McCall6b0feb72011-06-22 02:32:12 +00001405 ForEHVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "finally.for-eh");
John McCall7f416cc2015-09-08 08:05:57 +00001406 CGF.Builder.CreateFlagStore(false, ForEHVar);
Mike Stumpaff69af2009-12-09 03:35:49 +00001407
John McCallbd309292010-07-06 01:34:17 +00001408 // Enter a normal cleanup which will perform the @finally block.
John McCall6b0feb72011-06-22 02:32:12 +00001409 CGF.EHStack.pushCleanup<PerformFinally>(NormalCleanup, body,
1410 ForEHVar, endCatchFn,
1411 rethrowFn, SavedExnVar);
John McCallbd309292010-07-06 01:34:17 +00001412
1413 // Enter a catch-all scope.
John McCall6b0feb72011-06-22 02:32:12 +00001414 llvm::BasicBlock *catchBB = CGF.createBasicBlock("finally.catchall");
1415 EHCatchScope *catchScope = CGF.EHStack.pushCatch(1);
1416 catchScope->setCatchAllHandler(0, catchBB);
John McCallbd309292010-07-06 01:34:17 +00001417}
1418
John McCall6b0feb72011-06-22 02:32:12 +00001419void CodeGenFunction::FinallyInfo::exit(CodeGenFunction &CGF) {
John McCallbd309292010-07-06 01:34:17 +00001420 // Leave the finally catch-all.
John McCall6b0feb72011-06-22 02:32:12 +00001421 EHCatchScope &catchScope = cast<EHCatchScope>(*CGF.EHStack.begin());
1422 llvm::BasicBlock *catchBB = catchScope.getHandler(0).Block;
John McCall8e4c74b2011-08-11 02:22:43 +00001423
1424 CGF.popCatchScope();
John McCallbd309292010-07-06 01:34:17 +00001425
John McCall6b0feb72011-06-22 02:32:12 +00001426 // If there are any references to the catch-all block, emit it.
1427 if (catchBB->use_empty()) {
1428 delete catchBB;
1429 } else {
1430 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveAndClearIP();
1431 CGF.EmitBlock(catchBB);
John McCallbd309292010-07-06 01:34:17 +00001432
Craig Topper8a13c412014-05-21 05:09:00 +00001433 llvm::Value *exn = nullptr;
John McCallbd309292010-07-06 01:34:17 +00001434
John McCall6b0feb72011-06-22 02:32:12 +00001435 // If there's a begin-catch function, call it.
1436 if (BeginCatchFn) {
Bill Wendling79a70e42011-09-15 18:57:19 +00001437 exn = CGF.getExceptionFromSlot();
John McCall882987f2013-02-28 19:01:20 +00001438 CGF.EmitNounwindRuntimeCall(BeginCatchFn, exn);
John McCall6b0feb72011-06-22 02:32:12 +00001439 }
1440
1441 // If we need to remember the exception pointer to rethrow later, do so.
1442 if (SavedExnVar) {
Bill Wendling79a70e42011-09-15 18:57:19 +00001443 if (!exn) exn = CGF.getExceptionFromSlot();
John McCall7f416cc2015-09-08 08:05:57 +00001444 CGF.Builder.CreateAlignedStore(exn, SavedExnVar, CGF.getPointerAlign());
John McCall6b0feb72011-06-22 02:32:12 +00001445 }
1446
1447 // Tell the cleanups in the finally block that we're do this for EH.
John McCall7f416cc2015-09-08 08:05:57 +00001448 CGF.Builder.CreateFlagStore(true, ForEHVar);
John McCall6b0feb72011-06-22 02:32:12 +00001449
1450 // Thread a jump through the finally cleanup.
1451 CGF.EmitBranchThroughCleanup(RethrowDest);
1452
1453 CGF.Builder.restoreIP(savedIP);
1454 }
1455
1456 // Finally, leave the @finally cleanup.
1457 CGF.PopCleanupBlock();
John McCallbd309292010-07-06 01:34:17 +00001458}
1459
1460llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
1461 if (TerminateLandingPad)
1462 return TerminateLandingPad;
1463
1464 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1465
1466 // This will get inserted at the end of the function.
1467 TerminateLandingPad = createBasicBlock("terminate.lpad");
1468 Builder.SetInsertPoint(TerminateLandingPad);
1469
1470 // Tell the backend that this is a landing pad.
Reid Klecknerdeeddec2015-02-05 18:56:03 +00001471 const EHPersonality &Personality = EHPersonality::get(*this);
David Majnemerfcbdb6e2015-06-17 20:53:19 +00001472
1473 if (!CurFn->hasPersonalityFn())
1474 CurFn->setPersonalityFn(getOpaquePersonalityFn(CGM, Personality));
1475
Serge Guelton1d993272017-05-09 19:31:30 +00001476 llvm::LandingPadInst *LPadInst =
1477 Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty), 0);
Bill Wendlingf0724e82011-09-19 20:31:14 +00001478 LPadInst->addClause(getCatchAllValue(*this));
John McCallbd309292010-07-06 01:34:17 +00001479
Hans Wennborgdcfba332015-10-06 23:40:43 +00001480 llvm::Value *Exn = nullptr;
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00001481 if (getLangOpts().CPlusPlus)
1482 Exn = Builder.CreateExtractValue(LPadInst, 0);
1483 llvm::CallInst *terminateCall =
1484 CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
John McCalle142ad52013-02-12 03:51:46 +00001485 terminateCall->setDoesNotReturn();
John McCallad7c5c12011-02-08 08:22:06 +00001486 Builder.CreateUnreachable();
Mike Stumpaff69af2009-12-09 03:35:49 +00001487
John McCallbd309292010-07-06 01:34:17 +00001488 // Restore the saved insertion state.
1489 Builder.restoreIP(SavedIP);
John McCalldac3ea62010-04-30 00:06:43 +00001490
John McCallbd309292010-07-06 01:34:17 +00001491 return TerminateLandingPad;
Mike Stumpaff69af2009-12-09 03:35:49 +00001492}
Mike Stump2b488872009-12-09 22:59:31 +00001493
1494llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
Mike Stumpf5cbb082009-12-10 00:02:42 +00001495 if (TerminateHandler)
1496 return TerminateHandler;
1497
John McCallbd309292010-07-06 01:34:17 +00001498 // Set up the terminate handler. This block is inserted at the very
1499 // end of the function by FinishFunction.
Mike Stumpf5cbb082009-12-10 00:02:42 +00001500 TerminateHandler = createBasicBlock("terminate.handler");
Reid Kleckner06f19a02018-01-02 21:34:16 +00001501 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
John McCallbd309292010-07-06 01:34:17 +00001502 Builder.SetInsertPoint(TerminateHandler);
Reid Kleckner06f19a02018-01-02 21:34:16 +00001503
David Majnemerfeeefb22015-12-14 18:34:18 +00001504 llvm::Value *Exn = nullptr;
Reid Kleckner06f19a02018-01-02 21:34:16 +00001505 if (getLangOpts().CPlusPlus)
1506 Exn = getExceptionFromSlot();
David Majnemerfeeefb22015-12-14 18:34:18 +00001507 llvm::CallInst *terminateCall =
1508 CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
1509 terminateCall->setDoesNotReturn();
1510 Builder.CreateUnreachable();
Mike Stump2b488872009-12-09 22:59:31 +00001511
John McCall21886962010-04-21 10:05:39 +00001512 // Restore the saved insertion state.
John McCallbd309292010-07-06 01:34:17 +00001513 Builder.restoreIP(SavedIP);
Mike Stump25b20fc2009-12-09 23:31:35 +00001514
Mike Stump2b488872009-12-09 22:59:31 +00001515 return TerminateHandler;
1516}
John McCallbd309292010-07-06 01:34:17 +00001517
Reid Kleckner06f19a02018-01-02 21:34:16 +00001518llvm::BasicBlock *CodeGenFunction::getTerminateFunclet() {
1519 assert(EHPersonality::get(*this).usesFuncletPads() &&
1520 "use getTerminateLandingPad for non-funclet EH");
1521
1522 llvm::BasicBlock *&TerminateFunclet = TerminateFunclets[CurrentFuncletPad];
1523 if (TerminateFunclet)
1524 return TerminateFunclet;
1525
1526 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1527
1528 // Set up the terminate handler. This block is inserted at the very
1529 // end of the function by FinishFunction.
1530 TerminateFunclet = createBasicBlock("terminate.handler");
1531 Builder.SetInsertPoint(TerminateFunclet);
1532
1533 // Create the cleanuppad using the current parent pad as its token. Use 'none'
1534 // if this is a top-level terminate scope, which is the common case.
1535 SaveAndRestore<llvm::Instruction *> RestoreCurrentFuncletPad(
1536 CurrentFuncletPad);
1537 llvm::Value *ParentPad = CurrentFuncletPad;
1538 if (!ParentPad)
1539 ParentPad = llvm::ConstantTokenNone::get(CGM.getLLVMContext());
1540 CurrentFuncletPad = Builder.CreateCleanupPad(ParentPad);
1541
1542 // Emit the __std_terminate call.
Heejin Ahnc6479192018-05-31 22:18:13 +00001543 llvm::Value *Exn = nullptr;
1544 // In case of wasm personality, we need to pass the exception value to
1545 // __clang_call_terminate function.
1546 if (getLangOpts().CPlusPlus &&
1547 EHPersonality::get(*this).isWasmPersonality()) {
James Y Knight8799cae2019-02-03 21:53:49 +00001548 llvm::Function *GetExnFn =
Heejin Ahnc6479192018-05-31 22:18:13 +00001549 CGM.getIntrinsic(llvm::Intrinsic::wasm_get_exception);
1550 Exn = Builder.CreateCall(GetExnFn, CurrentFuncletPad);
1551 }
Reid Kleckner06f19a02018-01-02 21:34:16 +00001552 llvm::CallInst *terminateCall =
Heejin Ahnc6479192018-05-31 22:18:13 +00001553 CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
Reid Kleckner06f19a02018-01-02 21:34:16 +00001554 terminateCall->setDoesNotReturn();
1555 Builder.CreateUnreachable();
1556
1557 // Restore the saved insertion state.
1558 Builder.restoreIP(SavedIP);
1559
1560 return TerminateFunclet;
1561}
1562
David Chisnall9a837be2012-11-07 16:50:40 +00001563llvm::BasicBlock *CodeGenFunction::getEHResumeBlock(bool isCleanup) {
John McCall8e4c74b2011-08-11 02:22:43 +00001564 if (EHResumeBlock) return EHResumeBlock;
John McCallad5d61e2010-07-23 21:56:41 +00001565
1566 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1567
1568 // We emit a jump to a notional label at the outermost unwind state.
John McCall8e4c74b2011-08-11 02:22:43 +00001569 EHResumeBlock = createBasicBlock("eh.resume");
1570 Builder.SetInsertPoint(EHResumeBlock);
John McCallad5d61e2010-07-23 21:56:41 +00001571
Reid Klecknerdeeddec2015-02-05 18:56:03 +00001572 const EHPersonality &Personality = EHPersonality::get(*this);
John McCallad5d61e2010-07-23 21:56:41 +00001573
1574 // This can always be a call because we necessarily didn't find
1575 // anything on the EH stack which needs our help.
Benjamin Kramer793bd552012-02-08 12:41:24 +00001576 const char *RethrowName = Personality.CatchallRethrowFn;
Craig Topper8a13c412014-05-21 05:09:00 +00001577 if (RethrowName != nullptr && !isCleanup) {
John McCall882987f2013-02-28 19:01:20 +00001578 EmitRuntimeCall(getCatchallRethrowFn(CGM, RethrowName),
Nico Weberff62a6a2015-02-26 22:34:33 +00001579 getExceptionFromSlot())->setDoesNotReturn();
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001580 Builder.CreateUnreachable();
1581 Builder.restoreIP(SavedIP);
1582 return EHResumeBlock;
John McCall9b382dd2011-05-28 21:13:02 +00001583 }
1584
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001585 // Recreate the landingpad's return value for the 'resume' instruction.
1586 llvm::Value *Exn = getExceptionFromSlot();
1587 llvm::Value *Sel = getSelectorFromSlot();
John McCallad5d61e2010-07-23 21:56:41 +00001588
Serge Guelton1d993272017-05-09 19:31:30 +00001589 llvm::Type *LPadType = llvm::StructType::get(Exn->getType(), Sel->getType());
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001590 llvm::Value *LPadVal = llvm::UndefValue::get(LPadType);
1591 LPadVal = Builder.CreateInsertValue(LPadVal, Exn, 0, "lpad.val");
1592 LPadVal = Builder.CreateInsertValue(LPadVal, Sel, 1, "lpad.val");
1593
1594 Builder.CreateResume(LPadVal);
John McCallad5d61e2010-07-23 21:56:41 +00001595 Builder.restoreIP(SavedIP);
John McCall8e4c74b2011-08-11 02:22:43 +00001596 return EHResumeBlock;
John McCallad5d61e2010-07-23 21:56:41 +00001597}
Reid Kleckner543a16c2013-09-16 21:46:30 +00001598
1599void CodeGenFunction::EmitSEHTryStmt(const SEHTryStmt &S) {
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001600 EnterSEHTryStmt(S);
Reid Klecknera5930002015-02-11 21:40:48 +00001601 {
Nico Weber5779f842015-02-12 23:16:11 +00001602 JumpDest TryExit = getJumpDestInCurrentScope("__try.__leave");
Nico Weber5779f842015-02-12 23:16:11 +00001603
Reid Kleckner11c033e2015-02-12 23:40:45 +00001604 SEHTryEpilogueStack.push_back(&TryExit);
Reid Klecknera5930002015-02-11 21:40:48 +00001605 EmitStmt(S.getTryBlock());
Reid Kleckner11c033e2015-02-12 23:40:45 +00001606 SEHTryEpilogueStack.pop_back();
Nico Weber5779f842015-02-12 23:16:11 +00001607
1608 if (!TryExit.getBlock()->use_empty())
1609 EmitBlock(TryExit.getBlock(), /*IsFinished=*/true);
1610 else
1611 delete TryExit.getBlock();
Reid Klecknera5930002015-02-11 21:40:48 +00001612 }
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001613 ExitSEHTryStmt(S);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001614}
1615
1616namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001617struct PerformSEHFinally final : EHScopeStack::Cleanup {
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001618 llvm::Function *OutlinedFinally;
Reid Kleckner55391522015-10-08 21:14:56 +00001619 PerformSEHFinally(llvm::Function *OutlinedFinally)
1620 : OutlinedFinally(OutlinedFinally) {}
Reid Kleckneraca01db2015-02-04 22:37:07 +00001621
Reid Kleckner1d59f992015-01-22 01:36:17 +00001622 void Emit(CodeGenFunction &CGF, Flags F) override {
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001623 ASTContext &Context = CGF.getContext();
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001624 CodeGenModule &CGM = CGF.CGM;
Reid Kleckner65870442015-06-09 17:47:50 +00001625
Reid Klecknerd0d9a1f2015-07-01 17:10:10 +00001626 CallArgList Args;
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001627
1628 // Compute the two argument values.
1629 QualType ArgTys[2] = {Context.UnsignedCharTy, Context.VoidPtrTy};
Sanjin Sijariccfa2a2a2019-01-16 07:39:44 +00001630 llvm::Value *FP = nullptr;
1631 // If CFG.IsOutlinedSEHHelper is true, then we are within a finally block.
1632 if (CGF.IsOutlinedSEHHelper) {
1633 FP = &CGF.CurFn->arg_begin()[1];
1634 } else {
James Y Knight8799cae2019-02-03 21:53:49 +00001635 llvm::Function *LocalAddrFn =
Sanjin Sijariccfa2a2a2019-01-16 07:39:44 +00001636 CGM.getIntrinsic(llvm::Intrinsic::localaddress);
1637 FP = CGF.Builder.CreateCall(LocalAddrFn);
1638 }
1639
Reid Klecknereb11c412015-07-01 21:00:00 +00001640 llvm::Value *IsForEH =
1641 llvm::ConstantInt::get(CGF.ConvertType(ArgTys[0]), F.isForEHCleanup());
1642 Args.add(RValue::get(IsForEH), ArgTys[0]);
1643 Args.add(RValue::get(FP), ArgTys[1]);
Reid Klecknerd0d9a1f2015-07-01 17:10:10 +00001644
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001645 // Arrange a two-arg function info and type.
Reid Klecknereb11c412015-07-01 21:00:00 +00001646 const CGFunctionInfo &FnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00001647 CGM.getTypes().arrangeBuiltinFunctionCall(Context.VoidTy, Args);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001648
John McCallb92ab1a2016-10-26 23:46:34 +00001649 auto Callee = CGCallee::forDirect(OutlinedFinally);
1650 CGF.EmitCall(FnInfo, Callee, ReturnValueSlot(), Args);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001651 }
1652};
Hans Wennborgdcfba332015-10-06 23:40:43 +00001653} // end anonymous namespace
Reid Kleckner1d59f992015-01-22 01:36:17 +00001654
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001655namespace {
1656/// Find all local variable captures in the statement.
1657struct CaptureFinder : ConstStmtVisitor<CaptureFinder> {
1658 CodeGenFunction &ParentCGF;
1659 const VarDecl *ParentThis;
John McCall0a490152015-09-08 21:15:22 +00001660 llvm::SmallSetVector<const VarDecl *, 4> Captures;
John McCall7f416cc2015-09-08 08:05:57 +00001661 Address SEHCodeSlot = Address::invalid();
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001662 CaptureFinder(CodeGenFunction &ParentCGF, const VarDecl *ParentThis)
1663 : ParentCGF(ParentCGF), ParentThis(ParentThis) {}
1664
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001665 // Return true if we need to do any capturing work.
1666 bool foundCaptures() {
John McCall7f416cc2015-09-08 08:05:57 +00001667 return !Captures.empty() || SEHCodeSlot.isValid();
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001668 }
1669
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001670 void Visit(const Stmt *S) {
1671 // See if this is a capture, then recurse.
1672 ConstStmtVisitor<CaptureFinder>::Visit(S);
1673 for (const Stmt *Child : S->children())
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001674 if (Child)
1675 Visit(Child);
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001676 }
1677
1678 void VisitDeclRefExpr(const DeclRefExpr *E) {
1679 // If this is already a capture, just make sure we capture 'this'.
1680 if (E->refersToEnclosingVariableOrCapture()) {
John McCall0a490152015-09-08 21:15:22 +00001681 Captures.insert(ParentThis);
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001682 return;
1683 }
1684
1685 const auto *D = dyn_cast<VarDecl>(E->getDecl());
1686 if (D && D->isLocalVarDeclOrParm() && D->hasLocalStorage())
John McCall0a490152015-09-08 21:15:22 +00001687 Captures.insert(D);
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001688 }
1689
1690 void VisitCXXThisExpr(const CXXThisExpr *E) {
John McCall0a490152015-09-08 21:15:22 +00001691 Captures.insert(ParentThis);
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001692 }
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001693
1694 void VisitCallExpr(const CallExpr *E) {
1695 // We only need to add parent frame allocations for these builtins in x86.
1696 if (ParentCGF.getTarget().getTriple().getArch() != llvm::Triple::x86)
1697 return;
1698
1699 unsigned ID = E->getBuiltinCallee();
1700 switch (ID) {
1701 case Builtin::BI__exception_code:
1702 case Builtin::BI_exception_code:
1703 // This is the simple case where we are the outermost finally. All we
1704 // have to do here is make sure we escape this and recover it in the
1705 // outlined handler.
John McCall7f416cc2015-09-08 08:05:57 +00001706 if (!SEHCodeSlot.isValid())
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001707 SEHCodeSlot = ParentCGF.SEHCodeSlotStack.back();
1708 break;
1709 }
1710 }
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001711};
Hans Wennborgdcfba332015-10-06 23:40:43 +00001712} // end anonymous namespace
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001713
Reid Kleckner39329d57b2015-12-16 00:26:37 +00001714Address CodeGenFunction::recoverAddrOfEscapedLocal(CodeGenFunction &ParentCGF,
1715 Address ParentVar,
1716 llvm::Value *ParentFP) {
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001717 llvm::CallInst *RecoverCall = nullptr;
John McCall7f416cc2015-09-08 08:05:57 +00001718 CGBuilderTy Builder(*this, AllocaInsertPt);
1719 if (auto *ParentAlloca = dyn_cast<llvm::AllocaInst>(ParentVar.getPointer())) {
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001720 // Mark the variable escaped if nobody else referenced it and compute the
Reid Kleckner98cb8ba2015-07-07 22:26:07 +00001721 // localescape index.
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001722 auto InsertPair = ParentCGF.EscapedLocals.insert(
1723 std::make_pair(ParentAlloca, ParentCGF.EscapedLocals.size()));
1724 int FrameEscapeIdx = InsertPair.first->second;
Reid Kleckner98cb8ba2015-07-07 22:26:07 +00001725 // call i8* @llvm.localrecover(i8* bitcast(@parentFn), i8* %fp, i32 N)
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001726 llvm::Function *FrameRecoverFn = llvm::Intrinsic::getDeclaration(
Reid Kleckner98cb8ba2015-07-07 22:26:07 +00001727 &CGM.getModule(), llvm::Intrinsic::localrecover);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001728 llvm::Constant *ParentI8Fn =
1729 llvm::ConstantExpr::getBitCast(ParentCGF.CurFn, Int8PtrTy);
1730 RecoverCall = Builder.CreateCall(
1731 FrameRecoverFn, {ParentI8Fn, ParentFP,
1732 llvm::ConstantInt::get(Int32Ty, FrameEscapeIdx)});
1733
1734 } else {
1735 // If the parent didn't have an alloca, we're doing some nested outlining.
Reid Kleckner98cb8ba2015-07-07 22:26:07 +00001736 // Just clone the existing localrecover call, but tweak the FP argument to
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001737 // use our FP value. All other arguments are constants.
1738 auto *ParentRecover =
John McCall7f416cc2015-09-08 08:05:57 +00001739 cast<llvm::IntrinsicInst>(ParentVar.getPointer()->stripPointerCasts());
Reid Kleckner98cb8ba2015-07-07 22:26:07 +00001740 assert(ParentRecover->getIntrinsicID() == llvm::Intrinsic::localrecover &&
1741 "expected alloca or localrecover in parent LocalDeclMap");
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001742 RecoverCall = cast<llvm::CallInst>(ParentRecover->clone());
1743 RecoverCall->setArgOperand(1, ParentFP);
1744 RecoverCall->insertBefore(AllocaInsertPt);
1745 }
1746
1747 // Bitcast the variable, rename it, and insert it in the local decl map.
1748 llvm::Value *ChildVar =
John McCall7f416cc2015-09-08 08:05:57 +00001749 Builder.CreateBitCast(RecoverCall, ParentVar.getType());
1750 ChildVar->setName(ParentVar.getName());
1751 return Address(ChildVar, ParentVar.getAlignment());
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001752}
1753
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001754void CodeGenFunction::EmitCapturedLocals(CodeGenFunction &ParentCGF,
Reid Kleckner0b9bbbf2015-06-09 17:49:42 +00001755 const Stmt *OutlinedStmt,
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001756 bool IsFilter) {
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001757 // Find all captures in the Stmt.
1758 CaptureFinder Finder(ParentCGF, ParentCGF.CXXABIThisDecl);
1759 Finder.Visit(OutlinedStmt);
1760
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001761 // We can exit early on x86_64 when there are no captures. We just have to
1762 // save the exception code in filters so that __exception_code() works.
1763 if (!Finder.foundCaptures() &&
1764 CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
1765 if (IsFilter)
1766 EmitSEHExceptionCodeSave(ParentCGF, nullptr, nullptr);
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001767 return;
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001768 }
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001769
Reid Kleckner39329d57b2015-12-16 00:26:37 +00001770 llvm::Value *EntryFP = nullptr;
1771 CGBuilderTy Builder(CGM, AllocaInsertPt);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001772 if (IsFilter && CGM.getTarget().getTriple().getArch() == llvm::Triple::x86) {
1773 // 32-bit SEH filters need to be careful about FP recovery. The end of the
1774 // EH registration is passed in as the EBP physical register. We can
Reid Kleckner39329d57b2015-12-16 00:26:37 +00001775 // recover that with llvm.frameaddress(1).
1776 EntryFP = Builder.CreateCall(
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001777 CGM.getIntrinsic(llvm::Intrinsic::frameaddress), {Builder.getInt32(1)});
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001778 } else {
1779 // Otherwise, for x64 and 32-bit finally functions, the parent FP is the
1780 // second parameter.
1781 auto AI = CurFn->arg_begin();
1782 ++AI;
Reid Kleckner39329d57b2015-12-16 00:26:37 +00001783 EntryFP = &*AI;
1784 }
1785
1786 llvm::Value *ParentFP = EntryFP;
1787 if (IsFilter) {
1788 // Given whatever FP the runtime provided us in EntryFP, recover the true
1789 // frame pointer of the parent function. We only need to do this in filters,
1790 // since finally funclets recover the parent FP for us.
1791 llvm::Function *RecoverFPIntrin =
Eli Friedmanc4c43b22019-01-16 00:50:44 +00001792 CGM.getIntrinsic(llvm::Intrinsic::eh_recoverfp);
Reid Kleckner39329d57b2015-12-16 00:26:37 +00001793 llvm::Constant *ParentI8Fn =
1794 llvm::ConstantExpr::getBitCast(ParentCGF.CurFn, Int8PtrTy);
1795 ParentFP = Builder.CreateCall(RecoverFPIntrin, {ParentI8Fn, EntryFP});
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001796 }
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001797
Reid Kleckner98cb8ba2015-07-07 22:26:07 +00001798 // Create llvm.localrecover calls for all captures.
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001799 for (const VarDecl *VD : Finder.Captures) {
1800 if (isa<ImplicitParamDecl>(VD)) {
1801 CGM.ErrorUnsupported(VD, "'this' captured by SEH");
1802 CXXThisValue = llvm::UndefValue::get(ConvertTypeForMem(VD->getType()));
1803 continue;
1804 }
1805 if (VD->getType()->isVariablyModifiedType()) {
1806 CGM.ErrorUnsupported(VD, "VLA captured by SEH");
1807 continue;
1808 }
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001809 assert((isa<ImplicitParamDecl>(VD) || VD->isLocalVarDeclOrParm()) &&
1810 "captured non-local variable");
1811
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001812 // If this decl hasn't been declared yet, it will be declared in the
1813 // OutlinedStmt.
1814 auto I = ParentCGF.LocalDeclMap.find(VD);
1815 if (I == ParentCGF.LocalDeclMap.end())
1816 continue;
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001817
John McCall7f416cc2015-09-08 08:05:57 +00001818 Address ParentVar = I->second;
Reid Kleckner39329d57b2015-12-16 00:26:37 +00001819 setAddrOfLocalVar(
1820 VD, recoverAddrOfEscapedLocal(ParentCGF, ParentVar, ParentFP));
Nico Webere4f974c2015-07-02 06:10:53 +00001821 }
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001822
John McCall7f416cc2015-09-08 08:05:57 +00001823 if (Finder.SEHCodeSlot.isValid()) {
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001824 SEHCodeSlotStack.push_back(
1825 recoverAddrOfEscapedLocal(ParentCGF, Finder.SEHCodeSlot, ParentFP));
1826 }
1827
1828 if (IsFilter)
Reid Kleckner39329d57b2015-12-16 00:26:37 +00001829 EmitSEHExceptionCodeSave(ParentCGF, ParentFP, EntryFP);
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001830}
1831
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001832/// Arrange a function prototype that can be called by Windows exception
1833/// handling personalities. On Win64, the prototype looks like:
1834/// RetTy func(void *EHPtrs, void *ParentFP);
1835void CodeGenFunction::startOutlinedSEHHelper(CodeGenFunction &ParentCGF,
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001836 bool IsFilter,
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001837 const Stmt *OutlinedStmt) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001838 SourceLocation StartLoc = OutlinedStmt->getBeginLoc();
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001839
1840 // Get the mangled function name.
1841 SmallString<128> Name;
1842 {
1843 llvm::raw_svector_ostream OS(Name);
David Chisnall93ce0182018-08-10 12:53:13 +00001844 const NamedDecl *ParentSEHFn = ParentCGF.CurSEHParent;
David Majnemer25eb1652016-03-01 19:42:53 +00001845 assert(ParentSEHFn && "No CurSEHParent!");
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001846 MangleContext &Mangler = CGM.getCXXABI().getMangleContext();
1847 if (IsFilter)
David Majnemer25eb1652016-03-01 19:42:53 +00001848 Mangler.mangleSEHFilterExpression(ParentSEHFn, OS);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001849 else
David Majnemer25eb1652016-03-01 19:42:53 +00001850 Mangler.mangleSEHFinallyBlock(ParentSEHFn, OS);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001851 }
1852
1853 FunctionArgList Args;
1854 if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86 || !IsFilter) {
1855 // All SEH finally functions take two parameters. Win64 filters take two
1856 // parameters. Win32 filters take no parameters.
1857 if (IsFilter) {
1858 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00001859 getContext(), /*DC=*/nullptr, StartLoc,
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001860 &getContext().Idents.get("exception_pointers"),
Alexey Bataev56223232017-06-09 13:40:18 +00001861 getContext().VoidPtrTy, ImplicitParamDecl::Other));
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001862 } else {
1863 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00001864 getContext(), /*DC=*/nullptr, StartLoc,
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001865 &getContext().Idents.get("abnormal_termination"),
Alexey Bataev56223232017-06-09 13:40:18 +00001866 getContext().UnsignedCharTy, ImplicitParamDecl::Other));
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001867 }
1868 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00001869 getContext(), /*DC=*/nullptr, StartLoc,
1870 &getContext().Idents.get("frame_pointer"), getContext().VoidPtrTy,
1871 ImplicitParamDecl::Other));
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001872 }
1873
1874 QualType RetTy = IsFilter ? getContext().LongTy : getContext().VoidTy;
1875
John McCallc56a8b32016-03-11 04:30:31 +00001876 const CGFunctionInfo &FnInfo =
1877 CGM.getTypes().arrangeBuiltinFunctionDeclaration(RetTy, Args);
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001878
Reid Kleckner1d59f992015-01-22 01:36:17 +00001879 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001880 llvm::Function *Fn = llvm::Function::Create(
1881 FnTy, llvm::GlobalValue::InternalLinkage, Name.str(), &CGM.getModule());
Reid Kleckner1d59f992015-01-22 01:36:17 +00001882
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001883 IsOutlinedSEHHelper = true;
Nico Weberf2a39a72015-04-13 20:03:03 +00001884
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001885 StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001886 OutlinedStmt->getBeginLoc(), OutlinedStmt->getBeginLoc());
David Majnemer25eb1652016-03-01 19:42:53 +00001887 CurSEHParent = ParentCGF.CurSEHParent;
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001888
Erich Keanede6480a32018-11-13 15:48:08 +00001889 CGM.SetLLVMFunctionAttributes(GlobalDecl(), FnInfo, CurFn);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001890 EmitCapturedLocals(ParentCGF, OutlinedStmt, IsFilter);
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001891}
1892
1893/// Create a stub filter function that will ultimately hold the code of the
1894/// filter expression. The EH preparation passes in LLVM will outline the code
1895/// from the main function body into this stub.
1896llvm::Function *
1897CodeGenFunction::GenerateSEHFilterFunction(CodeGenFunction &ParentCGF,
1898 const SEHExceptStmt &Except) {
1899 const Expr *FilterExpr = Except.getFilterExpr();
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001900 startOutlinedSEHHelper(ParentCGF, true, FilterExpr);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001901
1902 // Emit the original filter expression, convert to i32, and return.
1903 llvm::Value *R = EmitScalarExpr(FilterExpr);
David Majnemer2ccba832015-04-17 06:57:25 +00001904 R = Builder.CreateIntCast(R, ConvertType(getContext().LongTy),
Reid Kleckner1d59f992015-01-22 01:36:17 +00001905 FilterExpr->getType()->isSignedIntegerType());
1906 Builder.CreateStore(R, ReturnValue);
1907
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001908 FinishFunction(FilterExpr->getEndLoc());
Reid Kleckner1d59f992015-01-22 01:36:17 +00001909
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001910 return CurFn;
1911}
1912
1913llvm::Function *
1914CodeGenFunction::GenerateSEHFinallyFunction(CodeGenFunction &ParentCGF,
1915 const SEHFinallyStmt &Finally) {
1916 const Stmt *FinallyBlock = Finally.getBlock();
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001917 startOutlinedSEHHelper(ParentCGF, false, FinallyBlock);
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001918
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001919 // Emit the original filter expression, convert to i32, and return.
1920 EmitStmt(FinallyBlock);
1921
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001922 FinishFunction(FinallyBlock->getEndLoc());
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001923
1924 return CurFn;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001925}
1926
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001927void CodeGenFunction::EmitSEHExceptionCodeSave(CodeGenFunction &ParentCGF,
1928 llvm::Value *ParentFP,
Reid Kleckner39329d57b2015-12-16 00:26:37 +00001929 llvm::Value *EntryFP) {
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001930 // Get the pointer to the EXCEPTION_POINTERS struct. This is returned by the
1931 // __exception_info intrinsic.
1932 if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
1933 // On Win64, the info is passed as the first parameter to the filter.
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00001934 SEHInfo = &*CurFn->arg_begin();
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001935 SEHCodeSlotStack.push_back(
1936 CreateMemTemp(getContext().IntTy, "__exception_code"));
1937 } else {
1938 // On Win32, the EBP on entry to the filter points to the end of an
1939 // exception registration object. It contains 6 32-bit fields, and the info
1940 // pointer is stored in the second field. So, GEP 20 bytes backwards and
1941 // load the pointer.
Reid Kleckner39329d57b2015-12-16 00:26:37 +00001942 SEHInfo = Builder.CreateConstInBoundsGEP1_32(Int8Ty, EntryFP, -20);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001943 SEHInfo = Builder.CreateBitCast(SEHInfo, Int8PtrTy->getPointerTo());
John McCall7f416cc2015-09-08 08:05:57 +00001944 SEHInfo = Builder.CreateAlignedLoad(Int8PtrTy, SEHInfo, getPointerAlign());
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001945 SEHCodeSlotStack.push_back(recoverAddrOfEscapedLocal(
1946 ParentCGF, ParentCGF.SEHCodeSlotStack.back(), ParentFP));
1947 }
1948
Reid Kleckner1d59f992015-01-22 01:36:17 +00001949 // Save the exception code in the exception slot to unify exception access in
1950 // the filter function and the landing pad.
1951 // struct EXCEPTION_POINTERS {
1952 // EXCEPTION_RECORD *ExceptionRecord;
1953 // CONTEXT *ContextRecord;
1954 // };
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001955 // int exceptioncode = exception_pointers->ExceptionRecord->ExceptionCode;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001956 llvm::Type *RecordTy = CGM.Int32Ty->getPointerTo();
Serge Guelton1d993272017-05-09 19:31:30 +00001957 llvm::Type *PtrsTy = llvm::StructType::get(RecordTy, CGM.VoidPtrTy);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001958 llvm::Value *Ptrs = Builder.CreateBitCast(SEHInfo, PtrsTy->getPointerTo());
David Blaikie1ed728c2015-04-05 22:45:47 +00001959 llvm::Value *Rec = Builder.CreateStructGEP(PtrsTy, Ptrs, 0);
John McCall7f416cc2015-09-08 08:05:57 +00001960 Rec = Builder.CreateAlignedLoad(Rec, getPointerAlign());
1961 llvm::Value *Code = Builder.CreateAlignedLoad(Rec, getIntAlign());
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001962 assert(!SEHCodeSlotStack.empty() && "emitting EH code outside of __except");
1963 Builder.CreateStore(Code, SEHCodeSlotStack.back());
Reid Kleckner1d59f992015-01-22 01:36:17 +00001964}
1965
1966llvm::Value *CodeGenFunction::EmitSEHExceptionInfo() {
1967 // Sema should diagnose calling this builtin outside of a filter context, but
1968 // don't crash if we screw up.
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001969 if (!SEHInfo)
Reid Kleckner1d59f992015-01-22 01:36:17 +00001970 return llvm::UndefValue::get(Int8PtrTy);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001971 assert(SEHInfo->getType() == Int8PtrTy);
1972 return SEHInfo;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001973}
1974
1975llvm::Value *CodeGenFunction::EmitSEHExceptionCode() {
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001976 assert(!SEHCodeSlotStack.empty() && "emitting EH code outside of __except");
John McCall7f416cc2015-09-08 08:05:57 +00001977 return Builder.CreateLoad(SEHCodeSlotStack.back());
Reid Kleckner1d59f992015-01-22 01:36:17 +00001978}
1979
Reid Kleckneraca01db2015-02-04 22:37:07 +00001980llvm::Value *CodeGenFunction::EmitSEHAbnormalTermination() {
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001981 // Abnormal termination is just the first parameter to the outlined finally
1982 // helper.
1983 auto AI = CurFn->arg_begin();
1984 return Builder.CreateZExt(&*AI, Int32Ty);
Reid Kleckneraca01db2015-02-04 22:37:07 +00001985}
1986
David Chisnall93ce0182018-08-10 12:53:13 +00001987void CodeGenFunction::pushSEHCleanup(CleanupKind Kind,
1988 llvm::Function *FinallyFunc) {
1989 EHStack.pushCleanup<PerformSEHFinally>(Kind, FinallyFunc);
1990}
1991
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001992void CodeGenFunction::EnterSEHTryStmt(const SEHTryStmt &S) {
1993 CodeGenFunction HelperCGF(CGM, /*suppressNewContext=*/true);
1994 if (const SEHFinallyStmt *Finally = S.getFinallyHandler()) {
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001995 // Outline the finally block.
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001996 llvm::Function *FinallyFunc =
1997 HelperCGF.GenerateSEHFinallyFunction(*this, *Finally);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001998
1999 // Push a cleanup for __finally blocks.
Reid Kleckner55391522015-10-08 21:14:56 +00002000 EHStack.pushCleanup<PerformSEHFinally>(NormalAndEHCleanup, FinallyFunc);
Reid Kleckner1d59f992015-01-22 01:36:17 +00002001 return;
2002 }
2003
2004 // Otherwise, we must have an __except block.
Reid Klecknerebaf28d2015-04-14 20:59:00 +00002005 const SEHExceptStmt *Except = S.getExceptHandler();
Reid Kleckner1d59f992015-01-22 01:36:17 +00002006 assert(Except);
2007 EHCatchScope *CatchScope = EHStack.pushCatch(1);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00002008 SEHCodeSlotStack.push_back(
2009 CreateMemTemp(getContext().IntTy, "__exception_code"));
Reid Kleckner2a2e1562015-01-22 02:25:56 +00002010
Reid Kleckner9fe7f232015-07-07 00:36:30 +00002011 // If the filter is known to evaluate to 1, then we can use the clause
2012 // "catch i8* null". We can't do this on x86 because the filter has to save
2013 // the exception code.
Reid Kleckner2a2e1562015-01-22 02:25:56 +00002014 llvm::Constant *C =
John McCallde0fe072017-08-15 21:42:52 +00002015 ConstantEmitter(*this).tryEmitAbstract(Except->getFilterExpr(),
2016 getContext().IntTy);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00002017 if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86 && C &&
2018 C->isOneValue()) {
Reid Kleckner2a2e1562015-01-22 02:25:56 +00002019 CatchScope->setCatchAllHandler(0, createBasicBlock("__except"));
2020 return;
2021 }
2022
2023 // In general, we have to emit an outlined filter function. Use the function
2024 // in place of the RTTI typeinfo global that C++ EH uses.
Reid Kleckner1d59f992015-01-22 01:36:17 +00002025 llvm::Function *FilterFunc =
Reid Klecknerebaf28d2015-04-14 20:59:00 +00002026 HelperCGF.GenerateSEHFilterFunction(*this, *Except);
Reid Kleckner1d59f992015-01-22 01:36:17 +00002027 llvm::Constant *OpaqueFunc =
2028 llvm::ConstantExpr::getBitCast(FilterFunc, Int8PtrTy);
Reid Kleckner8be18472015-09-16 21:06:09 +00002029 CatchScope->setHandler(0, OpaqueFunc, createBasicBlock("__except.ret"));
Reid Kleckner1d59f992015-01-22 01:36:17 +00002030}
2031
Reid Klecknerebaf28d2015-04-14 20:59:00 +00002032void CodeGenFunction::ExitSEHTryStmt(const SEHTryStmt &S) {
Reid Kleckner1d59f992015-01-22 01:36:17 +00002033 // Just pop the cleanup if it's a __finally block.
Reid Klecknerebaf28d2015-04-14 20:59:00 +00002034 if (S.getFinallyHandler()) {
Reid Kleckner1d59f992015-01-22 01:36:17 +00002035 PopCleanupBlock();
2036 return;
2037 }
2038
2039 // Otherwise, we must have an __except block.
Reid Kleckneraca01db2015-02-04 22:37:07 +00002040 const SEHExceptStmt *Except = S.getExceptHandler();
Reid Kleckner1d59f992015-01-22 01:36:17 +00002041 assert(Except && "__try must have __finally xor __except");
2042 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
2043
2044 // Don't emit the __except block if the __try block lacked invokes.
2045 // TODO: Model unwind edges from instructions, either with iload / istore or
2046 // a try body function.
2047 if (!CatchScope.hasEHBranches()) {
2048 CatchScope.clearHandlerBlocks();
2049 EHStack.popCatch();
Reid Kleckner9fe7f232015-07-07 00:36:30 +00002050 SEHCodeSlotStack.pop_back();
Reid Kleckner1d59f992015-01-22 01:36:17 +00002051 return;
2052 }
2053
2054 // The fall-through block.
2055 llvm::BasicBlock *ContBB = createBasicBlock("__try.cont");
2056
2057 // We just emitted the body of the __try; jump to the continue block.
2058 if (HaveInsertPoint())
2059 Builder.CreateBr(ContBB);
2060
2061 // Check if our filter function returned true.
2062 emitCatchDispatchBlock(*this, CatchScope);
2063
2064 // Grab the block before we pop the handler.
David Majnemer4e52d6f2015-12-12 05:39:21 +00002065 llvm::BasicBlock *CatchPadBB = CatchScope.getHandler(0).Block;
Reid Kleckner1d59f992015-01-22 01:36:17 +00002066 EHStack.popCatch();
2067
David Majnemer4e52d6f2015-12-12 05:39:21 +00002068 EmitBlockAfterUses(CatchPadBB);
Reid Kleckner1d59f992015-01-22 01:36:17 +00002069
Reid Kleckner129552b2015-10-08 01:13:52 +00002070 // __except blocks don't get outlined into funclets, so immediately do a
2071 // catchret.
Reid Kleckner129552b2015-10-08 01:13:52 +00002072 llvm::CatchPadInst *CPI =
2073 cast<llvm::CatchPadInst>(CatchPadBB->getFirstNonPHI());
David Majnemer4e52d6f2015-12-12 05:39:21 +00002074 llvm::BasicBlock *ExceptBB = createBasicBlock("__except");
Reid Kleckner129552b2015-10-08 01:13:52 +00002075 Builder.CreateCatchRet(CPI, ExceptBB);
2076 EmitBlock(ExceptBB);
2077
2078 // On Win64, the exception code is returned in EAX. Copy it into the slot.
2079 if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
2080 llvm::Function *SEHCodeIntrin =
2081 CGM.getIntrinsic(llvm::Intrinsic::eh_exceptioncode);
2082 llvm::Value *Code = Builder.CreateCall(SEHCodeIntrin, {CPI});
2083 Builder.CreateStore(Code, SEHCodeSlotStack.back());
Reid Kleckner9fe7f232015-07-07 00:36:30 +00002084 }
2085
Reid Kleckner1d59f992015-01-22 01:36:17 +00002086 // Emit the __except body.
2087 EmitStmt(Except->getBlock());
2088
Reid Kleckner9fe7f232015-07-07 00:36:30 +00002089 // End the lifetime of the exception code.
2090 SEHCodeSlotStack.pop_back();
2091
Reid Kleckner3a417c32015-01-30 22:16:45 +00002092 if (HaveInsertPoint())
2093 Builder.CreateBr(ContBB);
Reid Kleckner1d59f992015-01-22 01:36:17 +00002094
2095 EmitBlock(ContBB);
Reid Kleckner543a16c2013-09-16 21:46:30 +00002096}
Nico Weber9b982072014-07-07 00:12:30 +00002097
2098void CodeGenFunction::EmitSEHLeaveStmt(const SEHLeaveStmt &S) {
Nico Weber5779f842015-02-12 23:16:11 +00002099 // If this code is reachable then emit a stop point (if generating
2100 // debug info). We have to do this ourselves because we are on the
2101 // "simple" statement path.
2102 if (HaveInsertPoint())
2103 EmitStopPoint(&S);
2104
Reid Klecknerebaf28d2015-04-14 20:59:00 +00002105 // This must be a __leave from a __finally block, which we warn on and is UB.
2106 // Just emit unreachable.
2107 if (!isSEHTryScope()) {
2108 Builder.CreateUnreachable();
2109 Builder.ClearInsertionPoint();
2110 return;
2111 }
2112
Nico Weber5779f842015-02-12 23:16:11 +00002113 EmitBranchThroughCleanup(*SEHTryEpilogueStack.back());
Nico Weber9b982072014-07-07 00:12:30 +00002114}