blob: 5ddd3bbb82b84bf2324731c8c37c2aca2d934f3b [file] [log] [blame]
Anders Carlsson4b08db72009-10-30 01:42:31 +00001//===--- CGException.cpp - Emit LLVM Code for C++ exceptions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code dealing with C++ exception related code generation.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
David Majnemer442d0a22014-11-25 07:20:20 +000015#include "CGCXXABI.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000016#include "CGCleanup.h"
Benjamin Kramer793bd552012-02-08 12:41:24 +000017#include "CGObjCRuntime.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"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000022#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000023#include "llvm/IR/Intrinsics.h"
John McCallbd309292010-07-06 01:34:17 +000024
Anders Carlsson4b08db72009-10-30 01:42:31 +000025using namespace clang;
26using namespace CodeGen;
27
John McCall2c33ba82013-02-12 03:51:38 +000028static llvm::Constant *getAllocateExceptionFn(CodeGenModule &CGM) {
Anders Carlsson32e1b1c2009-10-30 02:27:02 +000029 // void *__cxa_allocate_exception(size_t thrown_size);
Mike Stump75546b82009-12-10 00:06:18 +000030
Chris Lattner2192fe52011-07-18 04:24:23 +000031 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +000032 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.SizeTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000033
John McCall2c33ba82013-02-12 03:51:38 +000034 return CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
Anders Carlsson32e1b1c2009-10-30 02:27:02 +000035}
36
John McCall2c33ba82013-02-12 03:51:38 +000037static llvm::Constant *getFreeExceptionFn(CodeGenModule &CGM) {
Mike Stump33270212009-12-02 07:41:41 +000038 // void __cxa_free_exception(void *thrown_exception);
Mike Stump75546b82009-12-10 00:06:18 +000039
Chris Lattner2192fe52011-07-18 04:24:23 +000040 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +000041 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000042
John McCall2c33ba82013-02-12 03:51:38 +000043 return CGM.CreateRuntimeFunction(FTy, "__cxa_free_exception");
Mike Stump33270212009-12-02 07:41:41 +000044}
45
John McCall2c33ba82013-02-12 03:51:38 +000046static llvm::Constant *getThrowFn(CodeGenModule &CGM) {
Mike Stump75546b82009-12-10 00:06:18 +000047 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
Mike Stump33270212009-12-02 07:41:41 +000048 // void (*dest) (void *));
Anders Carlsson32e1b1c2009-10-30 02:27:02 +000049
John McCall2c33ba82013-02-12 03:51:38 +000050 llvm::Type *Args[3] = { CGM.Int8PtrTy, CGM.Int8PtrTy, CGM.Int8PtrTy };
Chris Lattner2192fe52011-07-18 04:24:23 +000051 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +000052 llvm::FunctionType::get(CGM.VoidTy, Args, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000053
John McCall2c33ba82013-02-12 03:51:38 +000054 return CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
Anders Carlsson32e1b1c2009-10-30 02:27:02 +000055}
56
John McCall2c33ba82013-02-12 03:51:38 +000057static llvm::Constant *getGetExceptionPtrFn(CodeGenModule &CGM) {
John McCallbd309292010-07-06 01:34:17 +000058 // void *__cxa_get_exception_ptr(void*);
John McCallbd309292010-07-06 01:34:17 +000059
Chris Lattner2192fe52011-07-18 04:24:23 +000060 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +000061 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
John McCallbd309292010-07-06 01:34:17 +000062
John McCall2c33ba82013-02-12 03:51:38 +000063 return CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
John McCallbd309292010-07-06 01:34:17 +000064}
65
John McCall2c33ba82013-02-12 03:51:38 +000066static llvm::Constant *getBeginCatchFn(CodeGenModule &CGM) {
John McCallbd309292010-07-06 01:34:17 +000067 // void *__cxa_begin_catch(void*);
Mike Stump58ef18b2009-11-20 23:44:51 +000068
Chris Lattner2192fe52011-07-18 04:24:23 +000069 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +000070 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000071
John McCall2c33ba82013-02-12 03:51:38 +000072 return CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
Mike Stump58ef18b2009-11-20 23:44:51 +000073}
74
John McCall2c33ba82013-02-12 03:51:38 +000075static llvm::Constant *getEndCatchFn(CodeGenModule &CGM) {
Mike Stump33270212009-12-02 07:41:41 +000076 // void __cxa_end_catch();
Mike Stump58ef18b2009-11-20 23:44:51 +000077
Chris Lattner2192fe52011-07-18 04:24:23 +000078 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +000079 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000080
John McCall2c33ba82013-02-12 03:51:38 +000081 return CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
Mike Stump58ef18b2009-11-20 23:44:51 +000082}
83
John McCall2c33ba82013-02-12 03:51:38 +000084static llvm::Constant *getUnexpectedFn(CodeGenModule &CGM) {
Richard Smith2f7aa192013-06-20 23:03:35 +000085 // void __cxa_call_unexpected(void *thrown_exception);
Mike Stump1d849212009-12-07 23:38:24 +000086
Chris Lattner2192fe52011-07-18 04:24:23 +000087 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +000088 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000089
John McCall2c33ba82013-02-12 03:51:38 +000090 return CGM.CreateRuntimeFunction(FTy, "__cxa_call_unexpected");
Mike Stump1d849212009-12-07 23:38:24 +000091}
92
John McCall2c33ba82013-02-12 03:51:38 +000093static llvm::Constant *getTerminateFn(CodeGenModule &CGM) {
Mike Stump33270212009-12-02 07:41:41 +000094 // void __terminate();
95
Chris Lattner2192fe52011-07-18 04:24:23 +000096 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +000097 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000098
Chris Lattner0e62c1c2011-07-23 10:55:15 +000099 StringRef name;
John McCall9de19782011-07-06 01:22:26 +0000100
101 // In C++, use std::terminate().
Reid Kleckner1d59f992015-01-22 01:36:17 +0000102 if (CGM.getLangOpts().CPlusPlus &&
103 CGM.getTarget().getCXXABI().isItaniumFamily()) {
104 name = "_ZSt9terminatev";
105 } else if (CGM.getLangOpts().ObjC1 &&
John McCall2c33ba82013-02-12 03:51:38 +0000106 CGM.getLangOpts().ObjCRuntime.hasTerminate())
John McCall9de19782011-07-06 01:22:26 +0000107 name = "objc_terminate";
108 else
109 name = "abort";
John McCall2c33ba82013-02-12 03:51:38 +0000110 return CGM.CreateRuntimeFunction(FTy, name);
David Chisnallf9c42252010-05-17 13:49:20 +0000111}
112
John McCall2c33ba82013-02-12 03:51:38 +0000113static llvm::Constant *getCatchallRethrowFn(CodeGenModule &CGM,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000114 StringRef Name) {
Chris Lattner2192fe52011-07-18 04:24:23 +0000115 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +0000116 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
John McCall36ea3722010-07-17 00:43:08 +0000117
John McCall2c33ba82013-02-12 03:51:38 +0000118 return CGM.CreateRuntimeFunction(FTy, Name);
John McCallbd309292010-07-06 01:34:17 +0000119}
120
Benjamin Kramer793bd552012-02-08 12:41:24 +0000121namespace {
122 /// The exceptions personality for a function.
123 struct EHPersonality {
124 const char *PersonalityFn;
125
126 // If this is non-null, this personality requires a non-standard
127 // function for rethrowing an exception after a catchall cleanup.
128 // This function must have prototype void(void*).
129 const char *CatchallRethrowFn;
130
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000131 static const EHPersonality &get(CodeGenModule &CGM,
132 const FunctionDecl *FD);
133 static const EHPersonality &get(CodeGenFunction &CGF) {
134 return get(CGF.CGM, dyn_cast_or_null<FunctionDecl>(CGF.CurCodeDecl));
135 }
136
Benjamin Kramer793bd552012-02-08 12:41:24 +0000137 static const EHPersonality GNU_C;
138 static const EHPersonality GNU_C_SJLJ;
Reid Kleckner8f45c9c2014-09-15 17:19:16 +0000139 static const EHPersonality GNU_C_SEH;
Benjamin Kramer793bd552012-02-08 12:41:24 +0000140 static const EHPersonality GNU_ObjC;
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000141 static const EHPersonality GNUstep_ObjC;
Benjamin Kramer793bd552012-02-08 12:41:24 +0000142 static const EHPersonality GNU_ObjCXX;
143 static const EHPersonality NeXT_ObjC;
144 static const EHPersonality GNU_CPlusPlus;
145 static const EHPersonality GNU_CPlusPlus_SJLJ;
Reid Kleckner8f45c9c2014-09-15 17:19:16 +0000146 static const EHPersonality GNU_CPlusPlus_SEH;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000147 static const EHPersonality MSVC_except_handler;
148 static const EHPersonality MSVC_C_specific_handler;
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000149 static const EHPersonality MSVC_CxxFrameHandler3;
Benjamin Kramer793bd552012-02-08 12:41:24 +0000150 };
151}
152
Craig Topper8a13c412014-05-21 05:09:00 +0000153const EHPersonality EHPersonality::GNU_C = { "__gcc_personality_v0", nullptr };
Benjamin Kramer793bd552012-02-08 12:41:24 +0000154const EHPersonality
Craig Topper8a13c412014-05-21 05:09:00 +0000155EHPersonality::GNU_C_SJLJ = { "__gcc_personality_sj0", nullptr };
156const EHPersonality
Reid Kleckner8f45c9c2014-09-15 17:19:16 +0000157EHPersonality::GNU_C_SEH = { "__gcc_personality_seh0", nullptr };
158const EHPersonality
Craig Topper8a13c412014-05-21 05:09:00 +0000159EHPersonality::NeXT_ObjC = { "__objc_personality_v0", nullptr };
160const EHPersonality
161EHPersonality::GNU_CPlusPlus = { "__gxx_personality_v0", nullptr };
162const EHPersonality
163EHPersonality::GNU_CPlusPlus_SJLJ = { "__gxx_personality_sj0", nullptr };
Benjamin Kramer793bd552012-02-08 12:41:24 +0000164const EHPersonality
Reid Kleckner8f45c9c2014-09-15 17:19:16 +0000165EHPersonality::GNU_CPlusPlus_SEH = { "__gxx_personality_seh0", nullptr };
166const EHPersonality
Benjamin Kramer793bd552012-02-08 12:41:24 +0000167EHPersonality::GNU_ObjC = {"__gnu_objc_personality_v0", "objc_exception_throw"};
168const EHPersonality
Craig Topper8a13c412014-05-21 05:09:00 +0000169EHPersonality::GNU_ObjCXX = { "__gnustep_objcxx_personality_v0", nullptr };
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000170const EHPersonality
Craig Topper8a13c412014-05-21 05:09:00 +0000171EHPersonality::GNUstep_ObjC = { "__gnustep_objc_personality_v0", nullptr };
Reid Kleckner1d59f992015-01-22 01:36:17 +0000172const EHPersonality
173EHPersonality::MSVC_except_handler = { "_except_handler3", nullptr };
174const EHPersonality
175EHPersonality::MSVC_C_specific_handler = { "__C_specific_handler", nullptr };
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000176const EHPersonality
177EHPersonality::MSVC_CxxFrameHandler3 = { "__CxxFrameHandler3", nullptr };
John McCall36ea3722010-07-17 00:43:08 +0000178
Reid Klecknere070b992014-11-14 02:01:10 +0000179/// On Win64, use libgcc's SEH personality function. We fall back to dwarf on
180/// other platforms, unless the user asked for SjLj exceptions.
181static bool useLibGCCSEHPersonality(const llvm::Triple &T) {
182 return T.isOSWindows() && T.getArch() == llvm::Triple::x86_64;
183}
184
185static const EHPersonality &getCPersonality(const llvm::Triple &T,
186 const LangOptions &L) {
John McCall2faab302010-11-07 02:35:25 +0000187 if (L.SjLjExceptions)
188 return EHPersonality::GNU_C_SJLJ;
Reid Klecknere070b992014-11-14 02:01:10 +0000189 else if (useLibGCCSEHPersonality(T))
Reid Kleckner8f45c9c2014-09-15 17:19:16 +0000190 return EHPersonality::GNU_C_SEH;
John McCall36ea3722010-07-17 00:43:08 +0000191 return EHPersonality::GNU_C;
192}
193
Reid Klecknere070b992014-11-14 02:01:10 +0000194static const EHPersonality &getObjCPersonality(const llvm::Triple &T,
195 const LangOptions &L) {
John McCall5fb5df92012-06-20 06:18:46 +0000196 switch (L.ObjCRuntime.getKind()) {
197 case ObjCRuntime::FragileMacOSX:
Reid Klecknere070b992014-11-14 02:01:10 +0000198 return getCPersonality(T, L);
John McCall5fb5df92012-06-20 06:18:46 +0000199 case ObjCRuntime::MacOSX:
200 case ObjCRuntime::iOS:
201 return EHPersonality::NeXT_ObjC;
David Chisnallb601c962012-07-03 20:49:52 +0000202 case ObjCRuntime::GNUstep:
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000203 if (L.ObjCRuntime.getVersion() >= VersionTuple(1, 7))
204 return EHPersonality::GNUstep_ObjC;
205 // fallthrough
David Chisnallb601c962012-07-03 20:49:52 +0000206 case ObjCRuntime::GCC:
John McCall775086e2012-07-12 02:07:58 +0000207 case ObjCRuntime::ObjFW:
John McCall36ea3722010-07-17 00:43:08 +0000208 return EHPersonality::GNU_ObjC;
John McCallbd309292010-07-06 01:34:17 +0000209 }
John McCall5fb5df92012-06-20 06:18:46 +0000210 llvm_unreachable("bad runtime kind");
John McCallbd309292010-07-06 01:34:17 +0000211}
212
Reid Klecknere070b992014-11-14 02:01:10 +0000213static const EHPersonality &getCXXPersonality(const llvm::Triple &T,
214 const LangOptions &L) {
John McCall36ea3722010-07-17 00:43:08 +0000215 if (L.SjLjExceptions)
216 return EHPersonality::GNU_CPlusPlus_SJLJ;
Reid Klecknere070b992014-11-14 02:01:10 +0000217 else if (useLibGCCSEHPersonality(T))
Reid Kleckner8f45c9c2014-09-15 17:19:16 +0000218 return EHPersonality::GNU_CPlusPlus_SEH;
Reid Klecknere070b992014-11-14 02:01:10 +0000219 return EHPersonality::GNU_CPlusPlus;
John McCallbd309292010-07-06 01:34:17 +0000220}
221
222/// Determines the personality function to use when both C++
223/// and Objective-C exceptions are being caught.
Reid Klecknere070b992014-11-14 02:01:10 +0000224static const EHPersonality &getObjCXXPersonality(const llvm::Triple &T,
225 const LangOptions &L) {
John McCall5fb5df92012-06-20 06:18:46 +0000226 switch (L.ObjCRuntime.getKind()) {
John McCallbd309292010-07-06 01:34:17 +0000227 // The ObjC personality defers to the C++ personality for non-ObjC
228 // handlers. Unlike the C++ case, we use the same personality
229 // function on targets using (backend-driven) SJLJ EH.
John McCall5fb5df92012-06-20 06:18:46 +0000230 case ObjCRuntime::MacOSX:
231 case ObjCRuntime::iOS:
232 return EHPersonality::NeXT_ObjC;
John McCallbd309292010-07-06 01:34:17 +0000233
John McCall5fb5df92012-06-20 06:18:46 +0000234 // In the fragile ABI, just use C++ exception handling and hope
235 // they're not doing crazy exception mixing.
236 case ObjCRuntime::FragileMacOSX:
Reid Klecknere070b992014-11-14 02:01:10 +0000237 return getCXXPersonality(T, L);
David Chisnallf9c42252010-05-17 13:49:20 +0000238
David Chisnallb601c962012-07-03 20:49:52 +0000239 // The GCC runtime's personality function inherently doesn't support
John McCall36ea3722010-07-17 00:43:08 +0000240 // mixed EH. Use the C++ personality just to avoid returning null.
David Chisnallb601c962012-07-03 20:49:52 +0000241 case ObjCRuntime::GCC:
John McCall775086e2012-07-12 02:07:58 +0000242 case ObjCRuntime::ObjFW: // XXX: this will change soon
David Chisnallb601c962012-07-03 20:49:52 +0000243 return EHPersonality::GNU_ObjC;
244 case ObjCRuntime::GNUstep:
John McCall5fb5df92012-06-20 06:18:46 +0000245 return EHPersonality::GNU_ObjCXX;
246 }
247 llvm_unreachable("bad runtime kind");
John McCallbd309292010-07-06 01:34:17 +0000248}
249
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000250static const EHPersonality &getSEHPersonalityMSVC(const llvm::Triple &T) {
Reid Kleckner1d59f992015-01-22 01:36:17 +0000251 if (T.getArch() == llvm::Triple::x86)
252 return EHPersonality::MSVC_except_handler;
253 return EHPersonality::MSVC_C_specific_handler;
254}
255
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000256const EHPersonality &EHPersonality::get(CodeGenModule &CGM,
257 const FunctionDecl *FD) {
Reid Klecknere070b992014-11-14 02:01:10 +0000258 const llvm::Triple &T = CGM.getTarget().getTriple();
259 const LangOptions &L = CGM.getLangOpts();
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000260
Reid Kleckner1d59f992015-01-22 01:36:17 +0000261 // Try to pick a personality function that is compatible with MSVC if we're
262 // not compiling Obj-C. Obj-C users better have an Obj-C runtime that supports
263 // the GCC-style personality function.
264 if (T.isWindowsMSVCEnvironment() && !L.ObjC1) {
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000265 if (L.SjLjExceptions)
266 return EHPersonality::GNU_CPlusPlus_SJLJ;
267 else if (FD && FD->usesSEHTry())
268 return getSEHPersonalityMSVC(T);
Reid Kleckner1d59f992015-01-22 01:36:17 +0000269 else
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000270 return EHPersonality::MSVC_CxxFrameHandler3;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000271 }
272
John McCall36ea3722010-07-17 00:43:08 +0000273 if (L.CPlusPlus && L.ObjC1)
Reid Klecknere070b992014-11-14 02:01:10 +0000274 return getObjCXXPersonality(T, L);
John McCall36ea3722010-07-17 00:43:08 +0000275 else if (L.CPlusPlus)
Reid Klecknere070b992014-11-14 02:01:10 +0000276 return getCXXPersonality(T, L);
John McCall36ea3722010-07-17 00:43:08 +0000277 else if (L.ObjC1)
Reid Klecknere070b992014-11-14 02:01:10 +0000278 return getObjCPersonality(T, L);
John McCallbd309292010-07-06 01:34:17 +0000279 else
Reid Klecknere070b992014-11-14 02:01:10 +0000280 return getCPersonality(T, L);
John McCall36ea3722010-07-17 00:43:08 +0000281}
John McCallbd309292010-07-06 01:34:17 +0000282
John McCall0bdb1fd2010-09-16 06:16:50 +0000283static llvm::Constant *getPersonalityFn(CodeGenModule &CGM,
John McCall36ea3722010-07-17 00:43:08 +0000284 const EHPersonality &Personality) {
John McCall36ea3722010-07-17 00:43:08 +0000285 llvm::Constant *Fn =
Chris Lattnerece04092012-02-07 00:39:47 +0000286 CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.Int32Ty, true),
Benjamin Kramer793bd552012-02-08 12:41:24 +0000287 Personality.PersonalityFn);
John McCall0bdb1fd2010-09-16 06:16:50 +0000288 return Fn;
289}
290
291static llvm::Constant *getOpaquePersonalityFn(CodeGenModule &CGM,
292 const EHPersonality &Personality) {
293 llvm::Constant *Fn = getPersonalityFn(CGM, Personality);
John McCallad7c5c12011-02-08 08:22:06 +0000294 return llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
John McCall0bdb1fd2010-09-16 06:16:50 +0000295}
296
297/// Check whether a personality function could reasonably be swapped
298/// for a C++ personality function.
299static bool PersonalityHasOnlyCXXUses(llvm::Constant *Fn) {
Chandler Carruth4d01fff2014-03-09 03:16:50 +0000300 for (llvm::User *U : Fn->users()) {
John McCall0bdb1fd2010-09-16 06:16:50 +0000301 // Conditionally white-list bitcasts.
Chandler Carruth4d01fff2014-03-09 03:16:50 +0000302 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(U)) {
John McCall0bdb1fd2010-09-16 06:16:50 +0000303 if (CE->getOpcode() != llvm::Instruction::BitCast) return false;
304 if (!PersonalityHasOnlyCXXUses(CE))
305 return false;
306 continue;
307 }
308
Bill Wendling58e58fe2011-09-19 22:08:36 +0000309 // Otherwise, it has to be a landingpad instruction.
Chandler Carruth4d01fff2014-03-09 03:16:50 +0000310 llvm::LandingPadInst *LPI = dyn_cast<llvm::LandingPadInst>(U);
Bill Wendling58e58fe2011-09-19 22:08:36 +0000311 if (!LPI) return false;
John McCall0bdb1fd2010-09-16 06:16:50 +0000312
Bill Wendling58e58fe2011-09-19 22:08:36 +0000313 for (unsigned I = 0, E = LPI->getNumClauses(); I != E; ++I) {
John McCall0bdb1fd2010-09-16 06:16:50 +0000314 // Look for something that would've been returned by the ObjC
315 // runtime's GetEHType() method.
Bill Wendling58e58fe2011-09-19 22:08:36 +0000316 llvm::Value *Val = LPI->getClause(I)->stripPointerCasts();
317 if (LPI->isCatch(I)) {
318 // Check if the catch value has the ObjC prefix.
Bill Wendling5d7469e2011-09-20 00:40:19 +0000319 if (llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Val))
320 // ObjC EH selector entries are always global variables with
321 // names starting like this.
322 if (GV->getName().startswith("OBJC_EHTYPE"))
323 return false;
Bill Wendling58e58fe2011-09-19 22:08:36 +0000324 } else {
325 // Check if any of the filter values have the ObjC prefix.
326 llvm::Constant *CVal = cast<llvm::Constant>(Val);
327 for (llvm::User::op_iterator
328 II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II) {
Bill Wendling5d7469e2011-09-20 00:40:19 +0000329 if (llvm::GlobalVariable *GV =
330 cast<llvm::GlobalVariable>((*II)->stripPointerCasts()))
331 // ObjC EH selector entries are always global variables with
332 // names starting like this.
333 if (GV->getName().startswith("OBJC_EHTYPE"))
334 return false;
Bill Wendling58e58fe2011-09-19 22:08:36 +0000335 }
336 }
John McCall0bdb1fd2010-09-16 06:16:50 +0000337 }
338 }
339
340 return true;
341}
342
343/// Try to use the C++ personality function in ObjC++. Not doing this
344/// can cause some incompatibilities with gcc, which is more
345/// aggressive about only using the ObjC++ personality in a function
346/// when it really needs it.
347void CodeGenModule::SimplifyPersonality() {
John McCall0bdb1fd2010-09-16 06:16:50 +0000348 // If we're not in ObjC++ -fexceptions, there's nothing to do.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000349 if (!LangOpts.CPlusPlus || !LangOpts.ObjC1 || !LangOpts.Exceptions)
John McCall0bdb1fd2010-09-16 06:16:50 +0000350 return;
351
John McCall3c223932012-11-14 17:48:31 +0000352 // Both the problem this endeavors to fix and the way the logic
353 // above works is specific to the NeXT runtime.
354 if (!LangOpts.ObjCRuntime.isNeXTFamily())
355 return;
356
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000357 const EHPersonality &ObjCXX = EHPersonality::get(*this, /*FD=*/nullptr);
Reid Klecknere070b992014-11-14 02:01:10 +0000358 const EHPersonality &CXX =
359 getCXXPersonality(getTarget().getTriple(), LangOpts);
Benjamin Kramer793bd552012-02-08 12:41:24 +0000360 if (&ObjCXX == &CXX)
John McCall0bdb1fd2010-09-16 06:16:50 +0000361 return;
362
Benjamin Kramer793bd552012-02-08 12:41:24 +0000363 assert(std::strcmp(ObjCXX.PersonalityFn, CXX.PersonalityFn) != 0 &&
364 "Different EHPersonalities using the same personality function.");
365
366 llvm::Function *Fn = getModule().getFunction(ObjCXX.PersonalityFn);
John McCall0bdb1fd2010-09-16 06:16:50 +0000367
368 // Nothing to do if it's unused.
369 if (!Fn || Fn->use_empty()) return;
370
371 // Can't do the optimization if it has non-C++ uses.
372 if (!PersonalityHasOnlyCXXUses(Fn)) return;
373
374 // Create the C++ personality function and kill off the old
375 // function.
376 llvm::Constant *CXXFn = getPersonalityFn(*this, CXX);
377
378 // This can happen if the user is screwing with us.
379 if (Fn->getType() != CXXFn->getType()) return;
380
381 Fn->replaceAllUsesWith(CXXFn);
382 Fn->eraseFromParent();
John McCallbd309292010-07-06 01:34:17 +0000383}
384
385/// Returns the value to inject into a selector to indicate the
386/// presence of a catch-all.
387static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
388 // Possibly we should use @llvm.eh.catch.all.value here.
John McCallad7c5c12011-02-08 08:22:06 +0000389 return llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
John McCallbd309292010-07-06 01:34:17 +0000390}
391
John McCallbb026012010-07-13 21:17:51 +0000392namespace {
393 /// A cleanup to free the exception object if its initialization
394 /// throws.
John McCall5fcf8da2011-07-12 00:15:30 +0000395 struct FreeException : EHScopeStack::Cleanup {
396 llvm::Value *exn;
397 FreeException(llvm::Value *exn) : exn(exn) {}
Craig Topper4f12f102014-03-12 06:41:41 +0000398 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +0000399 CGF.EmitNounwindRuntimeCall(getFreeExceptionFn(CGF.CGM), exn);
John McCallbb026012010-07-13 21:17:51 +0000400 }
401 };
402}
403
John McCall2e6567a2010-04-22 01:10:34 +0000404// Emits an exception expression into the given location. This
405// differs from EmitAnyExprToMem only in that, if a final copy-ctor
406// call is required, an exception within that copy ctor causes
407// std::terminate to be invoked.
John McCalle4df6c82011-01-28 08:37:24 +0000408static void EmitAnyExprToExn(CodeGenFunction &CGF, const Expr *e,
409 llvm::Value *addr) {
John McCallbd309292010-07-06 01:34:17 +0000410 // Make sure the exception object is cleaned up if there's an
411 // exception during initialization.
John McCalle4df6c82011-01-28 08:37:24 +0000412 CGF.pushFullExprCleanup<FreeException>(EHCleanup, addr);
413 EHScopeStack::stable_iterator cleanup = CGF.EHStack.stable_begin();
John McCall2e6567a2010-04-22 01:10:34 +0000414
415 // __cxa_allocate_exception returns a void*; we need to cast this
416 // to the appropriate type for the object.
Chris Lattner2192fe52011-07-18 04:24:23 +0000417 llvm::Type *ty = CGF.ConvertTypeForMem(e->getType())->getPointerTo();
John McCalle4df6c82011-01-28 08:37:24 +0000418 llvm::Value *typedAddr = CGF.Builder.CreateBitCast(addr, ty);
John McCall2e6567a2010-04-22 01:10:34 +0000419
420 // FIXME: this isn't quite right! If there's a final unelided call
421 // to a copy constructor, then according to [except.terminate]p1 we
422 // must call std::terminate() if that constructor throws, because
423 // technically that copy occurs after the exception expression is
424 // evaluated but before the exception is caught. But the best way
425 // to handle that is to teach EmitAggExpr to do the final copy
426 // differently if it can't be elided.
Chad Rosier615ed1a2012-03-29 17:37:10 +0000427 CGF.EmitAnyExprToMem(e, typedAddr, e->getType().getQualifiers(),
428 /*IsInit*/ true);
John McCall2e6567a2010-04-22 01:10:34 +0000429
John McCalle4df6c82011-01-28 08:37:24 +0000430 // Deactivate the cleanup block.
John McCallf4beacd2011-11-10 10:43:54 +0000431 CGF.DeactivateCleanupBlock(cleanup, cast<llvm::Instruction>(typedAddr));
Mike Stump54066142009-12-01 03:41:18 +0000432}
433
John McCallbd309292010-07-06 01:34:17 +0000434llvm::Value *CodeGenFunction::getExceptionSlot() {
John McCall9b382dd2011-05-28 21:13:02 +0000435 if (!ExceptionSlot)
436 ExceptionSlot = CreateTempAlloca(Int8PtrTy, "exn.slot");
John McCallbd309292010-07-06 01:34:17 +0000437 return ExceptionSlot;
Mike Stump54066142009-12-01 03:41:18 +0000438}
439
John McCall9b382dd2011-05-28 21:13:02 +0000440llvm::Value *CodeGenFunction::getEHSelectorSlot() {
441 if (!EHSelectorSlot)
442 EHSelectorSlot = CreateTempAlloca(Int32Ty, "ehselector.slot");
443 return EHSelectorSlot;
444}
445
Bill Wendling79a70e42011-09-15 18:57:19 +0000446llvm::Value *CodeGenFunction::getExceptionFromSlot() {
447 return Builder.CreateLoad(getExceptionSlot(), "exn");
448}
449
450llvm::Value *CodeGenFunction::getSelectorFromSlot() {
451 return Builder.CreateLoad(getEHSelectorSlot(), "sel");
452}
453
Reid Kleckneraca01db2015-02-04 22:37:07 +0000454llvm::Value *CodeGenFunction::getAbnormalTerminationSlot() {
455 if (!AbnormalTerminationSlot)
456 AbnormalTerminationSlot = CreateTempAlloca(Int8Ty, "abnormal.termination.slot");
457 return AbnormalTerminationSlot;
458}
459
Richard Smithea852322013-05-07 21:53:22 +0000460void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E,
461 bool KeepInsertionPoint) {
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000462 if (!E->getSubExpr()) {
David Majnemer442d0a22014-11-25 07:20:20 +0000463 CGM.getCXXABI().emitRethrow(*this, /*isNoReturn*/true);
Douglas Gregorc278d1b2010-05-16 00:44:00 +0000464
John McCall20f6ab82011-01-12 03:41:02 +0000465 // throw is an expression, and the expression emitters expect us
466 // to leave ourselves at a valid insertion point.
Richard Smithea852322013-05-07 21:53:22 +0000467 if (KeepInsertionPoint)
468 EmitBlock(createBasicBlock("throw.cont"));
John McCall20f6ab82011-01-12 03:41:02 +0000469
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000470 return;
471 }
Mike Stump75546b82009-12-10 00:06:18 +0000472
David Majnemer442d0a22014-11-25 07:20:20 +0000473 if (CGM.getTarget().getTriple().isKnownWindowsMSVCEnvironment()) {
474 ErrorUnsupported(E, "throw expression");
475 return;
476 }
477
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000478 QualType ThrowType = E->getSubExpr()->getType();
Mike Stump75546b82009-12-10 00:06:18 +0000479
Fariborz Jahanian1eab0522013-01-10 19:02:56 +0000480 if (ThrowType->isObjCObjectPointerType()) {
481 const Stmt *ThrowStmt = E->getSubExpr();
482 const ObjCAtThrowStmt S(E->getExprLoc(),
483 const_cast<Stmt *>(ThrowStmt));
484 CGM.getObjCRuntime().EmitThrowStmt(*this, S, false);
485 // This will clear insertion point which was not cleared in
486 // call to EmitThrowStmt.
Richard Smithea852322013-05-07 21:53:22 +0000487 if (KeepInsertionPoint)
488 EmitBlock(createBasicBlock("throw.cont"));
Fariborz Jahanian1eab0522013-01-10 19:02:56 +0000489 return;
490 }
491
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000492 // Now allocate the exception object.
Chris Lattner2192fe52011-07-18 04:24:23 +0000493 llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
John McCall21886962010-04-21 10:05:39 +0000494 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
Mike Stump75546b82009-12-10 00:06:18 +0000495
John McCall2c33ba82013-02-12 03:51:38 +0000496 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(CGM);
John McCallbd309292010-07-06 01:34:17 +0000497 llvm::CallInst *ExceptionPtr =
John McCall882987f2013-02-28 19:01:20 +0000498 EmitNounwindRuntimeCall(AllocExceptionFn,
499 llvm::ConstantInt::get(SizeTy, TypeSize),
500 "exception");
Anders Carlssonafd1edb2009-12-11 00:32:37 +0000501
John McCall2e6567a2010-04-22 01:10:34 +0000502 EmitAnyExprToExn(*this, E->getSubExpr(), ExceptionPtr);
Mike Stump75546b82009-12-10 00:06:18 +0000503
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000504 // Now throw the exception.
Anders Carlssonba840fb2011-01-24 01:59:49 +0000505 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
506 /*ForEH=*/true);
John McCall2e6567a2010-04-22 01:10:34 +0000507
508 // The address of the destructor. If the exception type has a
509 // trivial destructor (or isn't a record), we just pass null.
Craig Topper8a13c412014-05-21 05:09:00 +0000510 llvm::Constant *Dtor = nullptr;
John McCall2e6567a2010-04-22 01:10:34 +0000511 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
512 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
513 if (!Record->hasTrivialDestructor()) {
Douglas Gregorbac74902010-07-01 14:13:13 +0000514 CXXDestructorDecl *DtorD = Record->getDestructor();
Rafael Espindola1ac0ec82014-09-11 15:42:06 +0000515 Dtor = CGM.getAddrOfCXXStructor(DtorD, StructorType::Complete);
John McCall2e6567a2010-04-22 01:10:34 +0000516 Dtor = llvm::ConstantExpr::getBitCast(Dtor, Int8PtrTy);
517 }
518 }
519 if (!Dtor) Dtor = llvm::Constant::getNullValue(Int8PtrTy);
Mike Stump75546b82009-12-10 00:06:18 +0000520
John McCall882987f2013-02-28 19:01:20 +0000521 llvm::Value *args[] = { ExceptionPtr, TypeInfo, Dtor };
522 EmitNoreturnRuntimeCallOrInvoke(getThrowFn(CGM), args);
Mike Stump75546b82009-12-10 00:06:18 +0000523
John McCall20f6ab82011-01-12 03:41:02 +0000524 // throw is an expression, and the expression emitters expect us
525 // to leave ourselves at a valid insertion point.
Richard Smithea852322013-05-07 21:53:22 +0000526 if (KeepInsertionPoint)
527 EmitBlock(createBasicBlock("throw.cont"));
Anders Carlsson4b08db72009-10-30 01:42:31 +0000528}
Mike Stump58ef18b2009-11-20 23:44:51 +0000529
Mike Stump1d849212009-12-07 23:38:24 +0000530void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000531 if (!CGM.getLangOpts().CXXExceptions)
Anders Carlsson9878f9f2010-02-06 23:59:05 +0000532 return;
533
Mike Stump1d849212009-12-07 23:38:24 +0000534 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
Craig Topper8a13c412014-05-21 05:09:00 +0000535 if (!FD) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000536 // Check if CapturedDecl is nothrow and create terminate scope for it.
537 if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
538 if (CD->isNothrow())
539 EHStack.pushTerminate();
540 }
Mike Stump1d849212009-12-07 23:38:24 +0000541 return;
Alexey Bataev9959db52014-05-06 10:08:46 +0000542 }
Mike Stump1d849212009-12-07 23:38:24 +0000543 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
Craig Topper8a13c412014-05-21 05:09:00 +0000544 if (!Proto)
Mike Stump1d849212009-12-07 23:38:24 +0000545 return;
546
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000547 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
548 if (isNoexceptExceptionSpec(EST)) {
549 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
550 // noexcept functions are simple terminate scopes.
551 EHStack.pushTerminate();
552 }
553 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
554 unsigned NumExceptions = Proto->getNumExceptions();
555 EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
Mike Stump1d849212009-12-07 23:38:24 +0000556
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000557 for (unsigned I = 0; I != NumExceptions; ++I) {
558 QualType Ty = Proto->getExceptionType(I);
559 QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
560 llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType,
561 /*ForEH=*/true);
562 Filter->setFilter(I, EHType);
563 }
Mike Stump1d849212009-12-07 23:38:24 +0000564 }
Mike Stump1d849212009-12-07 23:38:24 +0000565}
566
John McCall8e4c74b2011-08-11 02:22:43 +0000567/// Emit the dispatch block for a filter scope if necessary.
568static void emitFilterDispatchBlock(CodeGenFunction &CGF,
569 EHFilterScope &filterScope) {
570 llvm::BasicBlock *dispatchBlock = filterScope.getCachedEHDispatchBlock();
571 if (!dispatchBlock) return;
572 if (dispatchBlock->use_empty()) {
573 delete dispatchBlock;
574 return;
575 }
576
John McCall8e4c74b2011-08-11 02:22:43 +0000577 CGF.EmitBlockAfterUses(dispatchBlock);
578
579 // If this isn't a catch-all filter, we need to check whether we got
580 // here because the filter triggered.
581 if (filterScope.getNumFilters()) {
582 // Load the selector value.
Bill Wendling79a70e42011-09-15 18:57:19 +0000583 llvm::Value *selector = CGF.getSelectorFromSlot();
John McCall8e4c74b2011-08-11 02:22:43 +0000584 llvm::BasicBlock *unexpectedBB = CGF.createBasicBlock("ehspec.unexpected");
585
586 llvm::Value *zero = CGF.Builder.getInt32(0);
587 llvm::Value *failsFilter =
588 CGF.Builder.CreateICmpSLT(selector, zero, "ehspec.fails");
David Chisnall9a837be2012-11-07 16:50:40 +0000589 CGF.Builder.CreateCondBr(failsFilter, unexpectedBB, CGF.getEHResumeBlock(false));
John McCall8e4c74b2011-08-11 02:22:43 +0000590
591 CGF.EmitBlock(unexpectedBB);
592 }
593
594 // Call __cxa_call_unexpected. This doesn't need to be an invoke
595 // because __cxa_call_unexpected magically filters exceptions
596 // according to the last landing pad the exception was thrown
597 // into. Seriously.
Bill Wendling79a70e42011-09-15 18:57:19 +0000598 llvm::Value *exn = CGF.getExceptionFromSlot();
John McCall882987f2013-02-28 19:01:20 +0000599 CGF.EmitRuntimeCall(getUnexpectedFn(CGF.CGM), exn)
John McCall8e4c74b2011-08-11 02:22:43 +0000600 ->setDoesNotReturn();
601 CGF.Builder.CreateUnreachable();
602}
603
Mike Stump1d849212009-12-07 23:38:24 +0000604void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000605 if (!CGM.getLangOpts().CXXExceptions)
Anders Carlsson9878f9f2010-02-06 23:59:05 +0000606 return;
607
Mike Stump1d849212009-12-07 23:38:24 +0000608 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
Craig Topper8a13c412014-05-21 05:09:00 +0000609 if (!FD) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000610 // Check if CapturedDecl is nothrow and pop terminate scope for it.
611 if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
612 if (CD->isNothrow())
613 EHStack.popTerminate();
614 }
Mike Stump1d849212009-12-07 23:38:24 +0000615 return;
Alexey Bataev9959db52014-05-06 10:08:46 +0000616 }
Mike Stump1d849212009-12-07 23:38:24 +0000617 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
Craig Topper8a13c412014-05-21 05:09:00 +0000618 if (!Proto)
Mike Stump1d849212009-12-07 23:38:24 +0000619 return;
620
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000621 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
622 if (isNoexceptExceptionSpec(EST)) {
623 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
624 EHStack.popTerminate();
625 }
626 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
John McCall8e4c74b2011-08-11 02:22:43 +0000627 EHFilterScope &filterScope = cast<EHFilterScope>(*EHStack.begin());
628 emitFilterDispatchBlock(*this, filterScope);
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000629 EHStack.popFilter();
630 }
Mike Stump1d849212009-12-07 23:38:24 +0000631}
632
Mike Stump58ef18b2009-11-20 23:44:51 +0000633void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
Saleem Abdulrasoolb7698742014-11-17 22:11:07 +0000634 if (CGM.getTarget().getTriple().isKnownWindowsMSVCEnvironment()) {
Reid Klecknera82b5d82014-05-05 21:12:12 +0000635 ErrorUnsupported(&S, "try statement");
636 return;
637 }
638
John McCallb609d3f2010-07-07 06:56:46 +0000639 EnterCXXTryStmt(S);
John McCallb81884d2010-02-19 09:25:03 +0000640 EmitStmt(S.getTryBlock());
John McCallb609d3f2010-07-07 06:56:46 +0000641 ExitCXXTryStmt(S);
John McCallb81884d2010-02-19 09:25:03 +0000642}
643
John McCallb609d3f2010-07-07 06:56:46 +0000644void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallbd309292010-07-06 01:34:17 +0000645 unsigned NumHandlers = S.getNumHandlers();
646 EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
John McCallb81884d2010-02-19 09:25:03 +0000647
John McCallbd309292010-07-06 01:34:17 +0000648 for (unsigned I = 0; I != NumHandlers; ++I) {
649 const CXXCatchStmt *C = S.getHandler(I);
John McCallb81884d2010-02-19 09:25:03 +0000650
John McCallbd309292010-07-06 01:34:17 +0000651 llvm::BasicBlock *Handler = createBasicBlock("catch");
652 if (C->getExceptionDecl()) {
653 // FIXME: Dropping the reference type on the type into makes it
654 // impossible to correctly implement catch-by-reference
655 // semantics for pointers. Unfortunately, this is what all
656 // existing compilers do, and it's not clear that the standard
657 // personality routine is capable of doing this right. See C++ DR 388:
658 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
David Majnemer571162a2014-10-12 06:58:22 +0000659 Qualifiers CaughtTypeQuals;
660 QualType CaughtType = CGM.getContext().getUnqualifiedArrayType(
661 C->getCaughtType().getNonReferenceType(), CaughtTypeQuals);
John McCall2ca705e2010-07-24 00:37:23 +0000662
Rafael Espindolabb9e7a32014-06-04 18:51:46 +0000663 llvm::Constant *TypeInfo = nullptr;
John McCall2ca705e2010-07-24 00:37:23 +0000664 if (CaughtType->isObjCObjectPointerType())
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +0000665 TypeInfo = CGM.getObjCRuntime().GetEHType(CaughtType);
John McCall2ca705e2010-07-24 00:37:23 +0000666 else
Anders Carlssonba840fb2011-01-24 01:59:49 +0000667 TypeInfo = CGM.GetAddrOfRTTIDescriptor(CaughtType, /*ForEH=*/true);
John McCallbd309292010-07-06 01:34:17 +0000668 CatchScope->setHandler(I, TypeInfo, Handler);
669 } else {
670 // No exception decl indicates '...', a catch-all.
671 CatchScope->setCatchAllHandler(I, Handler);
672 }
673 }
John McCallbd309292010-07-06 01:34:17 +0000674}
675
John McCall8e4c74b2011-08-11 02:22:43 +0000676llvm::BasicBlock *
677CodeGenFunction::getEHDispatchBlock(EHScopeStack::stable_iterator si) {
678 // The dispatch block for the end of the scope chain is a block that
679 // just resumes unwinding.
680 if (si == EHStack.stable_end())
David Chisnall9a837be2012-11-07 16:50:40 +0000681 return getEHResumeBlock(true);
John McCall8e4c74b2011-08-11 02:22:43 +0000682
683 // Otherwise, we should look at the actual scope.
684 EHScope &scope = *EHStack.find(si);
685
686 llvm::BasicBlock *dispatchBlock = scope.getCachedEHDispatchBlock();
687 if (!dispatchBlock) {
688 switch (scope.getKind()) {
689 case EHScope::Catch: {
690 // Apply a special case to a single catch-all.
691 EHCatchScope &catchScope = cast<EHCatchScope>(scope);
692 if (catchScope.getNumHandlers() == 1 &&
693 catchScope.getHandler(0).isCatchAll()) {
694 dispatchBlock = catchScope.getHandler(0).Block;
695
696 // Otherwise, make a dispatch block.
697 } else {
698 dispatchBlock = createBasicBlock("catch.dispatch");
699 }
700 break;
701 }
702
703 case EHScope::Cleanup:
704 dispatchBlock = createBasicBlock("ehcleanup");
705 break;
706
707 case EHScope::Filter:
708 dispatchBlock = createBasicBlock("filter.dispatch");
709 break;
710
711 case EHScope::Terminate:
712 dispatchBlock = getTerminateHandler();
713 break;
714 }
715 scope.setCachedEHDispatchBlock(dispatchBlock);
716 }
717 return dispatchBlock;
718}
719
John McCallbd309292010-07-06 01:34:17 +0000720/// Check whether this is a non-EH scope, i.e. a scope which doesn't
721/// affect exception handling. Currently, the only non-EH scopes are
722/// normal-only cleanup scopes.
723static bool isNonEHScope(const EHScope &S) {
John McCall2b7fc382010-07-13 20:32:21 +0000724 switch (S.getKind()) {
John McCallcda666c2010-07-21 07:22:38 +0000725 case EHScope::Cleanup:
726 return !cast<EHCleanupScope>(S).isEHCleanup();
John McCall2b7fc382010-07-13 20:32:21 +0000727 case EHScope::Filter:
728 case EHScope::Catch:
729 case EHScope::Terminate:
730 return false;
731 }
732
David Blaikiee4d798f2012-01-20 21:50:17 +0000733 llvm_unreachable("Invalid EHScope Kind!");
John McCallbd309292010-07-06 01:34:17 +0000734}
735
736llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
737 assert(EHStack.requiresLandingPad());
738 assert(!EHStack.empty());
739
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000740 // If exceptions are disabled, there are usually no landingpads. However, when
741 // SEH is enabled, functions using SEH still get landingpads.
742 const LangOptions &LO = CGM.getLangOpts();
743 if (!LO.Exceptions) {
744 if (!LO.Borland && !LO.MicrosoftExt)
745 return nullptr;
746 const auto *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl);
747 if (!FD || !FD->usesSEHTry())
748 return nullptr;
749 }
John McCall2b7fc382010-07-13 20:32:21 +0000750
John McCallbd309292010-07-06 01:34:17 +0000751 // Check the innermost scope for a cached landing pad. If this is
752 // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
753 llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
754 if (LP) return LP;
755
756 // Build the landing pad for this scope.
757 LP = EmitLandingPad();
758 assert(LP);
759
760 // Cache the landing pad on the innermost scope. If this is a
761 // non-EH scope, cache the landing pad on the enclosing scope, too.
762 for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
763 ir->setCachedLandingPad(LP);
764 if (!isNonEHScope(*ir)) break;
765 }
766
767 return LP;
768}
769
770llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
771 assert(EHStack.requiresLandingPad());
772
John McCall8e4c74b2011-08-11 02:22:43 +0000773 EHScope &innermostEHScope = *EHStack.find(EHStack.getInnermostEHScope());
774 switch (innermostEHScope.getKind()) {
775 case EHScope::Terminate:
776 return getTerminateLandingPad();
John McCallbd309292010-07-06 01:34:17 +0000777
John McCall8e4c74b2011-08-11 02:22:43 +0000778 case EHScope::Catch:
779 case EHScope::Cleanup:
780 case EHScope::Filter:
781 if (llvm::BasicBlock *lpad = innermostEHScope.getCachedLandingPad())
782 return lpad;
John McCallbd309292010-07-06 01:34:17 +0000783 }
784
785 // Save the current IR generation state.
John McCall8e4c74b2011-08-11 02:22:43 +0000786 CGBuilderTy::InsertPoint savedIP = Builder.saveAndClearIP();
Adrian Prantl95b24e92015-02-03 20:00:54 +0000787 auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, CurEHLocation);
John McCallbd309292010-07-06 01:34:17 +0000788
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000789 const EHPersonality &personality = EHPersonality::get(*this);
John McCall36ea3722010-07-17 00:43:08 +0000790
John McCallbd309292010-07-06 01:34:17 +0000791 // Create and configure the landing pad.
John McCall8e4c74b2011-08-11 02:22:43 +0000792 llvm::BasicBlock *lpad = createBasicBlock("lpad");
793 EmitBlock(lpad);
John McCallbd309292010-07-06 01:34:17 +0000794
Bill Wendlingf0724e82011-09-19 20:31:14 +0000795 llvm::LandingPadInst *LPadInst =
Reid Kleckneree7cf842014-12-01 22:02:27 +0000796 Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, nullptr),
Bill Wendlingf0724e82011-09-19 20:31:14 +0000797 getOpaquePersonalityFn(CGM, personality), 0);
798
799 llvm::Value *LPadExn = Builder.CreateExtractValue(LPadInst, 0);
800 Builder.CreateStore(LPadExn, getExceptionSlot());
801 llvm::Value *LPadSel = Builder.CreateExtractValue(LPadInst, 1);
802 Builder.CreateStore(LPadSel, getEHSelectorSlot());
803
John McCallbd309292010-07-06 01:34:17 +0000804 // Save the exception pointer. It's safe to use a single exception
805 // pointer per function because EH cleanups can never have nested
806 // try/catches.
Bill Wendlingf0724e82011-09-19 20:31:14 +0000807 // Build the landingpad instruction.
John McCallbd309292010-07-06 01:34:17 +0000808
809 // Accumulate all the handlers in scope.
John McCall8e4c74b2011-08-11 02:22:43 +0000810 bool hasCatchAll = false;
811 bool hasCleanup = false;
812 bool hasFilter = false;
813 SmallVector<llvm::Value*, 4> filterTypes;
814 llvm::SmallPtrSet<llvm::Value*, 4> catchTypes;
John McCallbd309292010-07-06 01:34:17 +0000815 for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end();
816 I != E; ++I) {
817
818 switch (I->getKind()) {
John McCallcda666c2010-07-21 07:22:38 +0000819 case EHScope::Cleanup:
John McCall8e4c74b2011-08-11 02:22:43 +0000820 // If we have a cleanup, remember that.
821 hasCleanup = (hasCleanup || cast<EHCleanupScope>(*I).isEHCleanup());
John McCall2b7fc382010-07-13 20:32:21 +0000822 continue;
823
John McCallbd309292010-07-06 01:34:17 +0000824 case EHScope::Filter: {
825 assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
John McCall8e4c74b2011-08-11 02:22:43 +0000826 assert(!hasCatchAll && "EH filter reached after catch-all");
John McCallbd309292010-07-06 01:34:17 +0000827
Bill Wendlingf0724e82011-09-19 20:31:14 +0000828 // Filter scopes get added to the landingpad in weird ways.
John McCall8e4c74b2011-08-11 02:22:43 +0000829 EHFilterScope &filter = cast<EHFilterScope>(*I);
830 hasFilter = true;
John McCallbd309292010-07-06 01:34:17 +0000831
Bill Wendling8c4b7162011-09-22 20:32:54 +0000832 // Add all the filter values.
833 for (unsigned i = 0, e = filter.getNumFilters(); i != e; ++i)
834 filterTypes.push_back(filter.getFilter(i));
John McCallbd309292010-07-06 01:34:17 +0000835 goto done;
836 }
837
838 case EHScope::Terminate:
839 // Terminate scopes are basically catch-alls.
John McCall8e4c74b2011-08-11 02:22:43 +0000840 assert(!hasCatchAll);
841 hasCatchAll = true;
John McCallbd309292010-07-06 01:34:17 +0000842 goto done;
843
844 case EHScope::Catch:
845 break;
846 }
847
John McCall8e4c74b2011-08-11 02:22:43 +0000848 EHCatchScope &catchScope = cast<EHCatchScope>(*I);
849 for (unsigned hi = 0, he = catchScope.getNumHandlers(); hi != he; ++hi) {
850 EHCatchScope::Handler handler = catchScope.getHandler(hi);
John McCallbd309292010-07-06 01:34:17 +0000851
John McCall8e4c74b2011-08-11 02:22:43 +0000852 // If this is a catch-all, register that and abort.
853 if (!handler.Type) {
854 assert(!hasCatchAll);
855 hasCatchAll = true;
856 goto done;
John McCallbd309292010-07-06 01:34:17 +0000857 }
858
859 // Check whether we already have a handler for this type.
David Blaikie82e95a32014-11-19 07:49:47 +0000860 if (catchTypes.insert(handler.Type).second)
Bill Wendlingf0724e82011-09-19 20:31:14 +0000861 // If not, add it directly to the landingpad.
862 LPadInst->addClause(handler.Type);
John McCallbd309292010-07-06 01:34:17 +0000863 }
John McCallbd309292010-07-06 01:34:17 +0000864 }
865
866 done:
Bill Wendlingf0724e82011-09-19 20:31:14 +0000867 // If we have a catch-all, add null to the landingpad.
John McCall8e4c74b2011-08-11 02:22:43 +0000868 assert(!(hasCatchAll && hasFilter));
869 if (hasCatchAll) {
Bill Wendlingf0724e82011-09-19 20:31:14 +0000870 LPadInst->addClause(getCatchAllValue(*this));
John McCallbd309292010-07-06 01:34:17 +0000871
872 // If we have an EH filter, we need to add those handlers in the
Bill Wendlingf0724e82011-09-19 20:31:14 +0000873 // right place in the landingpad, which is to say, at the end.
John McCall8e4c74b2011-08-11 02:22:43 +0000874 } else if (hasFilter) {
Bill Wendling58e58fe2011-09-19 22:08:36 +0000875 // Create a filter expression: a constant array indicating which filter
876 // types there are. The personality routine only lands here if the filter
877 // doesn't match.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000878 SmallVector<llvm::Constant*, 8> Filters;
Bill Wendlingf0724e82011-09-19 20:31:14 +0000879 llvm::ArrayType *AType =
880 llvm::ArrayType::get(!filterTypes.empty() ?
881 filterTypes[0]->getType() : Int8PtrTy,
882 filterTypes.size());
883
884 for (unsigned i = 0, e = filterTypes.size(); i != e; ++i)
885 Filters.push_back(cast<llvm::Constant>(filterTypes[i]));
886 llvm::Constant *FilterArray = llvm::ConstantArray::get(AType, Filters);
887 LPadInst->addClause(FilterArray);
John McCallbd309292010-07-06 01:34:17 +0000888
889 // Also check whether we need a cleanup.
Bill Wendlingf0724e82011-09-19 20:31:14 +0000890 if (hasCleanup)
891 LPadInst->setCleanup(true);
John McCallbd309292010-07-06 01:34:17 +0000892
893 // Otherwise, signal that we at least have cleanups.
Logan Chiene9c8ccb2014-07-01 11:47:10 +0000894 } else if (hasCleanup) {
895 LPadInst->setCleanup(true);
John McCallbd309292010-07-06 01:34:17 +0000896 }
897
Bill Wendlingf0724e82011-09-19 20:31:14 +0000898 assert((LPadInst->getNumClauses() > 0 || LPadInst->isCleanup()) &&
899 "landingpad instruction has no clauses!");
John McCallbd309292010-07-06 01:34:17 +0000900
901 // Tell the backend how to generate the landing pad.
John McCall8e4c74b2011-08-11 02:22:43 +0000902 Builder.CreateBr(getEHDispatchBlock(EHStack.getInnermostEHScope()));
John McCallbd309292010-07-06 01:34:17 +0000903
904 // Restore the old IR generation state.
John McCall8e4c74b2011-08-11 02:22:43 +0000905 Builder.restoreIP(savedIP);
John McCallbd309292010-07-06 01:34:17 +0000906
John McCall8e4c74b2011-08-11 02:22:43 +0000907 return lpad;
John McCallbd309292010-07-06 01:34:17 +0000908}
909
John McCall5c08ab92010-07-13 22:12:14 +0000910namespace {
911 /// A cleanup to call __cxa_end_catch. In many cases, the caught
912 /// exception type lets us state definitively that the thrown exception
913 /// type does not have a destructor. In particular:
914 /// - Catch-alls tell us nothing, so we have to conservatively
915 /// assume that the thrown exception might have a destructor.
916 /// - Catches by reference behave according to their base types.
917 /// - Catches of non-record types will only trigger for exceptions
918 /// of non-record types, which never have destructors.
919 /// - Catches of record types can trigger for arbitrary subclasses
920 /// of the caught type, so we have to assume the actual thrown
921 /// exception type might have a throwing destructor, even if the
922 /// caught type's destructor is trivial or nothrow.
John McCallcda666c2010-07-21 07:22:38 +0000923 struct CallEndCatch : EHScopeStack::Cleanup {
John McCall5c08ab92010-07-13 22:12:14 +0000924 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
925 bool MightThrow;
926
Craig Topper4f12f102014-03-12 06:41:41 +0000927 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall5c08ab92010-07-13 22:12:14 +0000928 if (!MightThrow) {
John McCall882987f2013-02-28 19:01:20 +0000929 CGF.EmitNounwindRuntimeCall(getEndCatchFn(CGF.CGM));
John McCall5c08ab92010-07-13 22:12:14 +0000930 return;
931 }
932
John McCall882987f2013-02-28 19:01:20 +0000933 CGF.EmitRuntimeCallOrInvoke(getEndCatchFn(CGF.CGM));
John McCall5c08ab92010-07-13 22:12:14 +0000934 }
935 };
936}
937
John McCallbd309292010-07-06 01:34:17 +0000938/// Emits a call to __cxa_begin_catch and enters a cleanup to call
939/// __cxa_end_catch.
John McCall5c08ab92010-07-13 22:12:14 +0000940///
941/// \param EndMightThrow - true if __cxa_end_catch might throw
942static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
943 llvm::Value *Exn,
944 bool EndMightThrow) {
John McCall882987f2013-02-28 19:01:20 +0000945 llvm::CallInst *call =
946 CGF.EmitNounwindRuntimeCall(getBeginCatchFn(CGF.CGM), Exn);
John McCallbd309292010-07-06 01:34:17 +0000947
John McCallcda666c2010-07-21 07:22:38 +0000948 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
John McCallbd309292010-07-06 01:34:17 +0000949
John McCall882987f2013-02-28 19:01:20 +0000950 return call;
John McCallbd309292010-07-06 01:34:17 +0000951}
952
953/// A "special initializer" callback for initializing a catch
954/// parameter during catch initialization.
955static void InitCatchParam(CodeGenFunction &CGF,
956 const VarDecl &CatchParam,
Nick Lewycky2d84e842013-10-02 02:29:49 +0000957 llvm::Value *ParamAddr,
958 SourceLocation Loc) {
John McCallbd309292010-07-06 01:34:17 +0000959 // Load the exception from where the landing pad saved it.
Bill Wendling79a70e42011-09-15 18:57:19 +0000960 llvm::Value *Exn = CGF.getExceptionFromSlot();
John McCallbd309292010-07-06 01:34:17 +0000961
962 CanQualType CatchType =
963 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
Chris Lattner2192fe52011-07-18 04:24:23 +0000964 llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
John McCallbd309292010-07-06 01:34:17 +0000965
966 // If we're catching by reference, we can just cast the object
967 // pointer to the appropriate pointer.
968 if (isa<ReferenceType>(CatchType)) {
John McCall5add20c2010-07-20 22:17:55 +0000969 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
970 bool EndCatchMightThrow = CaughtType->isRecordType();
John McCall5c08ab92010-07-13 22:12:14 +0000971
John McCallbd309292010-07-06 01:34:17 +0000972 // __cxa_begin_catch returns the adjusted object pointer.
John McCall5c08ab92010-07-13 22:12:14 +0000973 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
John McCall5add20c2010-07-20 22:17:55 +0000974
975 // We have no way to tell the personality function that we're
976 // catching by reference, so if we're catching a pointer,
977 // __cxa_begin_catch will actually return that pointer by value.
978 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
979 QualType PointeeType = PT->getPointeeType();
980
981 // When catching by reference, generally we should just ignore
982 // this by-value pointer and use the exception object instead.
983 if (!PointeeType->isRecordType()) {
984
985 // Exn points to the struct _Unwind_Exception header, which
986 // we have to skip past in order to reach the exception data.
987 unsigned HeaderSize =
988 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
989 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
990
991 // However, if we're catching a pointer-to-record type that won't
992 // work, because the personality function might have adjusted
993 // the pointer. There's actually no way for us to fully satisfy
994 // the language/ABI contract here: we can't use Exn because it
995 // might have the wrong adjustment, but we can't use the by-value
996 // pointer because it's off by a level of abstraction.
997 //
998 // The current solution is to dump the adjusted pointer into an
999 // alloca, which breaks language semantics (because changing the
1000 // pointer doesn't change the exception) but at least works.
1001 // The better solution would be to filter out non-exact matches
1002 // and rethrow them, but this is tricky because the rethrow
1003 // really needs to be catchable by other sites at this landing
1004 // pad. The best solution is to fix the personality function.
1005 } else {
1006 // Pull the pointer for the reference type off.
Chris Lattner2192fe52011-07-18 04:24:23 +00001007 llvm::Type *PtrTy =
John McCall5add20c2010-07-20 22:17:55 +00001008 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
1009
1010 // Create the temporary and write the adjusted pointer into it.
1011 llvm::Value *ExnPtrTmp = CGF.CreateTempAlloca(PtrTy, "exn.byref.tmp");
1012 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1013 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
1014
1015 // Bind the reference to the temporary.
1016 AdjustedExn = ExnPtrTmp;
1017 }
1018 }
1019
John McCallbd309292010-07-06 01:34:17 +00001020 llvm::Value *ExnCast =
1021 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
1022 CGF.Builder.CreateStore(ExnCast, ParamAddr);
1023 return;
1024 }
1025
John McCall47fb9502013-03-07 21:37:08 +00001026 // Scalars and complexes.
1027 TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType);
1028 if (TEK != TEK_Aggregate) {
John McCall5c08ab92010-07-13 22:12:14 +00001029 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
John McCallbd309292010-07-06 01:34:17 +00001030
1031 // If the catch type is a pointer type, __cxa_begin_catch returns
1032 // the pointer by value.
1033 if (CatchType->hasPointerRepresentation()) {
1034 llvm::Value *CastExn =
1035 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
John McCall97017312012-01-17 20:16:56 +00001036
1037 switch (CatchType.getQualifiers().getObjCLifetime()) {
1038 case Qualifiers::OCL_Strong:
1039 CastExn = CGF.EmitARCRetainNonBlock(CastExn);
1040 // fallthrough
1041
1042 case Qualifiers::OCL_None:
1043 case Qualifiers::OCL_ExplicitNone:
1044 case Qualifiers::OCL_Autoreleasing:
1045 CGF.Builder.CreateStore(CastExn, ParamAddr);
1046 return;
1047
1048 case Qualifiers::OCL_Weak:
1049 CGF.EmitARCInitWeak(ParamAddr, CastExn);
1050 return;
1051 }
1052 llvm_unreachable("bad ownership qualifier!");
John McCallbd309292010-07-06 01:34:17 +00001053 }
1054
1055 // Otherwise, it returns a pointer into the exception object.
1056
Chris Lattner2192fe52011-07-18 04:24:23 +00001057 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
John McCallbd309292010-07-06 01:34:17 +00001058 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1059
John McCall47fb9502013-03-07 21:37:08 +00001060 LValue srcLV = CGF.MakeNaturalAlignAddrLValue(Cast, CatchType);
1061 LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType,
1062 CGF.getContext().getDeclAlign(&CatchParam));
1063 switch (TEK) {
1064 case TEK_Complex:
Nick Lewycky2d84e842013-10-02 02:29:49 +00001065 CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV,
John McCall47fb9502013-03-07 21:37:08 +00001066 /*init*/ true);
1067 return;
1068 case TEK_Scalar: {
Nick Lewycky2d84e842013-10-02 02:29:49 +00001069 llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc);
John McCall47fb9502013-03-07 21:37:08 +00001070 CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true);
1071 return;
John McCallbd309292010-07-06 01:34:17 +00001072 }
John McCall47fb9502013-03-07 21:37:08 +00001073 case TEK_Aggregate:
1074 llvm_unreachable("evaluation kind filtered out!");
1075 }
1076 llvm_unreachable("bad evaluation kind");
John McCallbd309292010-07-06 01:34:17 +00001077 }
1078
John McCallb5011ab2011-02-16 08:39:19 +00001079 assert(isa<RecordType>(CatchType) && "unexpected catch type!");
John McCallbd309292010-07-06 01:34:17 +00001080
Chris Lattner2192fe52011-07-18 04:24:23 +00001081 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
John McCallbd309292010-07-06 01:34:17 +00001082
John McCallb5011ab2011-02-16 08:39:19 +00001083 // Check for a copy expression. If we don't have a copy expression,
1084 // that means a trivial copy is okay.
John McCall1bf58462011-02-16 08:02:54 +00001085 const Expr *copyExpr = CatchParam.getInit();
1086 if (!copyExpr) {
John McCallb5011ab2011-02-16 08:39:19 +00001087 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
1088 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
Chad Rosier615ed1a2012-03-29 17:37:10 +00001089 CGF.EmitAggregateCopy(ParamAddr, adjustedExn, CatchType);
John McCallbd309292010-07-06 01:34:17 +00001090 return;
1091 }
1092
1093 // We have to call __cxa_get_exception_ptr to get the adjusted
1094 // pointer before copying.
John McCall1bf58462011-02-16 08:02:54 +00001095 llvm::CallInst *rawAdjustedExn =
John McCall882987f2013-02-28 19:01:20 +00001096 CGF.EmitNounwindRuntimeCall(getGetExceptionPtrFn(CGF.CGM), Exn);
John McCallbd309292010-07-06 01:34:17 +00001097
John McCall1bf58462011-02-16 08:02:54 +00001098 // Cast that to the appropriate type.
1099 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
John McCallbd309292010-07-06 01:34:17 +00001100
John McCall1bf58462011-02-16 08:02:54 +00001101 // The copy expression is defined in terms of an OpaqueValueExpr.
1102 // Find it and map it to the adjusted expression.
1103 CodeGenFunction::OpaqueValueMapping
John McCallc07a0c72011-02-17 10:25:35 +00001104 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
1105 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
John McCallbd309292010-07-06 01:34:17 +00001106
1107 // Call the copy ctor in a terminate scope.
1108 CGF.EHStack.pushTerminate();
John McCall1bf58462011-02-16 08:02:54 +00001109
1110 // Perform the copy construction.
Eli Friedman38cd36d2011-12-03 02:13:40 +00001111 CharUnits Alignment = CGF.getContext().getDeclAlign(&CatchParam);
Eli Friedmanc1d85b92011-12-03 00:54:26 +00001112 CGF.EmitAggExpr(copyExpr,
1113 AggValueSlot::forAddr(ParamAddr, Alignment, Qualifiers(),
1114 AggValueSlot::IsNotDestructed,
1115 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001116 AggValueSlot::IsNotAliased));
John McCall1bf58462011-02-16 08:02:54 +00001117
1118 // Leave the terminate scope.
John McCallbd309292010-07-06 01:34:17 +00001119 CGF.EHStack.popTerminate();
1120
John McCall1bf58462011-02-16 08:02:54 +00001121 // Undo the opaque value mapping.
1122 opaque.pop();
1123
John McCallbd309292010-07-06 01:34:17 +00001124 // Finally we can call __cxa_begin_catch.
John McCall5c08ab92010-07-13 22:12:14 +00001125 CallBeginCatch(CGF, Exn, true);
John McCallbd309292010-07-06 01:34:17 +00001126}
1127
1128/// Begins a catch statement by initializing the catch variable and
1129/// calling __cxa_begin_catch.
John McCall1bf58462011-02-16 08:02:54 +00001130static void BeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *S) {
John McCallbd309292010-07-06 01:34:17 +00001131 // We have to be very careful with the ordering of cleanups here:
1132 // C++ [except.throw]p4:
1133 // The destruction [of the exception temporary] occurs
1134 // immediately after the destruction of the object declared in
1135 // the exception-declaration in the handler.
1136 //
1137 // So the precise ordering is:
1138 // 1. Construct catch variable.
1139 // 2. __cxa_begin_catch
1140 // 3. Enter __cxa_end_catch cleanup
1141 // 4. Enter dtor cleanup
1142 //
John McCallc533cb72011-02-22 06:44:22 +00001143 // We do this by using a slightly abnormal initialization process.
1144 // Delegation sequence:
John McCallbd309292010-07-06 01:34:17 +00001145 // - ExitCXXTryStmt opens a RunCleanupsScope
John McCallc533cb72011-02-22 06:44:22 +00001146 // - EmitAutoVarAlloca creates the variable and debug info
John McCallbd309292010-07-06 01:34:17 +00001147 // - InitCatchParam initializes the variable from the exception
John McCallc533cb72011-02-22 06:44:22 +00001148 // - CallBeginCatch calls __cxa_begin_catch
1149 // - CallBeginCatch enters the __cxa_end_catch cleanup
1150 // - EmitAutoVarCleanups enters the variable destructor cleanup
John McCallbd309292010-07-06 01:34:17 +00001151 // - EmitCXXTryStmt emits the code for the catch body
1152 // - EmitCXXTryStmt close the RunCleanupsScope
1153
1154 VarDecl *CatchParam = S->getExceptionDecl();
1155 if (!CatchParam) {
Bill Wendling79a70e42011-09-15 18:57:19 +00001156 llvm::Value *Exn = CGF.getExceptionFromSlot();
John McCall5c08ab92010-07-13 22:12:14 +00001157 CallBeginCatch(CGF, Exn, true);
John McCallbd309292010-07-06 01:34:17 +00001158 return;
1159 }
1160
1161 // Emit the local.
John McCallc533cb72011-02-22 06:44:22 +00001162 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
Nick Lewycky2d84e842013-10-02 02:29:49 +00001163 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF), S->getLocStart());
John McCallc533cb72011-02-22 06:44:22 +00001164 CGF.EmitAutoVarCleanups(var);
John McCallb81884d2010-02-19 09:25:03 +00001165}
1166
John McCall8e4c74b2011-08-11 02:22:43 +00001167/// Emit the structure of the dispatch block for the given catch scope.
1168/// It is an invariant that the dispatch block already exists.
1169static void emitCatchDispatchBlock(CodeGenFunction &CGF,
1170 EHCatchScope &catchScope) {
1171 llvm::BasicBlock *dispatchBlock = catchScope.getCachedEHDispatchBlock();
1172 assert(dispatchBlock);
1173
1174 // If there's only a single catch-all, getEHDispatchBlock returned
1175 // that catch-all as the dispatch block.
1176 if (catchScope.getNumHandlers() == 1 &&
1177 catchScope.getHandler(0).isCatchAll()) {
1178 assert(dispatchBlock == catchScope.getHandler(0).Block);
1179 return;
1180 }
1181
1182 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveIP();
1183 CGF.EmitBlockAfterUses(dispatchBlock);
1184
1185 // Select the right handler.
1186 llvm::Value *llvm_eh_typeid_for =
1187 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
1188
1189 // Load the selector value.
Bill Wendling79a70e42011-09-15 18:57:19 +00001190 llvm::Value *selector = CGF.getSelectorFromSlot();
John McCall8e4c74b2011-08-11 02:22:43 +00001191
1192 // Test against each of the exception types we claim to catch.
1193 for (unsigned i = 0, e = catchScope.getNumHandlers(); ; ++i) {
1194 assert(i < e && "ran off end of handlers!");
1195 const EHCatchScope::Handler &handler = catchScope.getHandler(i);
1196
1197 llvm::Value *typeValue = handler.Type;
1198 assert(typeValue && "fell into catch-all case!");
1199 typeValue = CGF.Builder.CreateBitCast(typeValue, CGF.Int8PtrTy);
1200
1201 // Figure out the next block.
1202 bool nextIsEnd;
1203 llvm::BasicBlock *nextBlock;
1204
1205 // If this is the last handler, we're at the end, and the next
1206 // block is the block for the enclosing EH scope.
1207 if (i + 1 == e) {
1208 nextBlock = CGF.getEHDispatchBlock(catchScope.getEnclosingEHScope());
1209 nextIsEnd = true;
1210
1211 // If the next handler is a catch-all, we're at the end, and the
1212 // next block is that handler.
1213 } else if (catchScope.getHandler(i+1).isCatchAll()) {
1214 nextBlock = catchScope.getHandler(i+1).Block;
1215 nextIsEnd = true;
1216
1217 // Otherwise, we're not at the end and we need a new block.
1218 } else {
1219 nextBlock = CGF.createBasicBlock("catch.fallthrough");
1220 nextIsEnd = false;
1221 }
1222
1223 // Figure out the catch type's index in the LSDA's type table.
1224 llvm::CallInst *typeIndex =
1225 CGF.Builder.CreateCall(llvm_eh_typeid_for, typeValue);
1226 typeIndex->setDoesNotThrow();
1227
1228 llvm::Value *matchesTypeIndex =
1229 CGF.Builder.CreateICmpEQ(selector, typeIndex, "matches");
1230 CGF.Builder.CreateCondBr(matchesTypeIndex, handler.Block, nextBlock);
1231
1232 // If the next handler is a catch-all, we're completely done.
1233 if (nextIsEnd) {
1234 CGF.Builder.restoreIP(savedIP);
1235 return;
John McCall8e4c74b2011-08-11 02:22:43 +00001236 }
Ahmed Charles289896d2012-02-19 11:57:29 +00001237 // Otherwise we need to emit and continue at that block.
1238 CGF.EmitBlock(nextBlock);
John McCall8e4c74b2011-08-11 02:22:43 +00001239 }
John McCall8e4c74b2011-08-11 02:22:43 +00001240}
1241
1242void CodeGenFunction::popCatchScope() {
1243 EHCatchScope &catchScope = cast<EHCatchScope>(*EHStack.begin());
1244 if (catchScope.hasEHBranches())
1245 emitCatchDispatchBlock(*this, catchScope);
1246 EHStack.popCatch();
1247}
1248
John McCallb609d3f2010-07-07 06:56:46 +00001249void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallbd309292010-07-06 01:34:17 +00001250 unsigned NumHandlers = S.getNumHandlers();
1251 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1252 assert(CatchScope.getNumHandlers() == NumHandlers);
Mike Stump58ef18b2009-11-20 23:44:51 +00001253
John McCall8e4c74b2011-08-11 02:22:43 +00001254 // If the catch was not required, bail out now.
1255 if (!CatchScope.hasEHBranches()) {
Kostya Serebryanyba4aced2014-01-09 09:22:32 +00001256 CatchScope.clearHandlerBlocks();
John McCall8e4c74b2011-08-11 02:22:43 +00001257 EHStack.popCatch();
1258 return;
1259 }
1260
1261 // Emit the structure of the EH dispatch for this catch.
1262 emitCatchDispatchBlock(*this, CatchScope);
1263
John McCallbd309292010-07-06 01:34:17 +00001264 // Copy the handler blocks off before we pop the EH stack. Emitting
1265 // the handlers might scribble on this memory.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001266 SmallVector<EHCatchScope::Handler, 8> Handlers(NumHandlers);
John McCallbd309292010-07-06 01:34:17 +00001267 memcpy(Handlers.data(), CatchScope.begin(),
1268 NumHandlers * sizeof(EHCatchScope::Handler));
John McCall8e4c74b2011-08-11 02:22:43 +00001269
John McCallbd309292010-07-06 01:34:17 +00001270 EHStack.popCatch();
Mike Stump58ef18b2009-11-20 23:44:51 +00001271
John McCallbd309292010-07-06 01:34:17 +00001272 // The fall-through block.
1273 llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
Mike Stump58ef18b2009-11-20 23:44:51 +00001274
John McCallbd309292010-07-06 01:34:17 +00001275 // We just emitted the body of the try; jump to the continue block.
1276 if (HaveInsertPoint())
1277 Builder.CreateBr(ContBB);
Mike Stump97329152009-12-02 19:53:57 +00001278
John McCalld8d00be2012-06-15 05:27:05 +00001279 // Determine if we need an implicit rethrow for all these catch handlers;
1280 // see the comment below.
1281 bool doImplicitRethrow = false;
John McCallb609d3f2010-07-07 06:56:46 +00001282 if (IsFnTryBlock)
John McCalld8d00be2012-06-15 05:27:05 +00001283 doImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
1284 isa<CXXConstructorDecl>(CurCodeDecl);
John McCallb609d3f2010-07-07 06:56:46 +00001285
John McCall8e4c74b2011-08-11 02:22:43 +00001286 // Perversely, we emit the handlers backwards precisely because we
1287 // want them to appear in source order. In all of these cases, the
1288 // catch block will have exactly one predecessor, which will be a
1289 // particular block in the catch dispatch. However, in the case of
1290 // a catch-all, one of the dispatch blocks will branch to two
1291 // different handlers, and EmitBlockAfterUses will cause the second
1292 // handler to be moved before the first.
1293 for (unsigned I = NumHandlers; I != 0; --I) {
1294 llvm::BasicBlock *CatchBlock = Handlers[I-1].Block;
1295 EmitBlockAfterUses(CatchBlock);
Mike Stump75546b82009-12-10 00:06:18 +00001296
John McCallbd309292010-07-06 01:34:17 +00001297 // Catch the exception if this isn't a catch-all.
John McCall8e4c74b2011-08-11 02:22:43 +00001298 const CXXCatchStmt *C = S.getHandler(I-1);
Mike Stump58ef18b2009-11-20 23:44:51 +00001299
John McCallbd309292010-07-06 01:34:17 +00001300 // Enter a cleanup scope, including the catch variable and the
1301 // end-catch.
1302 RunCleanupsScope CatchScope(*this);
Mike Stump58ef18b2009-11-20 23:44:51 +00001303
John McCallbd309292010-07-06 01:34:17 +00001304 // Initialize the catch variable and set up the cleanups.
1305 BeginCatch(*this, C);
1306
Justin Bognerea278c32014-01-07 00:20:28 +00001307 // Emit the PGO counter increment.
Justin Bogneref512b92014-01-06 22:27:43 +00001308 RegionCounter CatchCnt = getPGORegionCounter(C);
1309 CatchCnt.beginRegion(Builder);
1310
John McCallbd309292010-07-06 01:34:17 +00001311 // Perform the body of the catch.
1312 EmitStmt(C->getHandlerBlock());
1313
John McCalld8d00be2012-06-15 05:27:05 +00001314 // [except.handle]p11:
1315 // The currently handled exception is rethrown if control
1316 // reaches the end of a handler of the function-try-block of a
1317 // constructor or destructor.
1318
1319 // It is important that we only do this on fallthrough and not on
1320 // return. Note that it's illegal to put a return in a
1321 // constructor function-try-block's catch handler (p14), so this
1322 // really only applies to destructors.
1323 if (doImplicitRethrow && HaveInsertPoint()) {
David Majnemer442d0a22014-11-25 07:20:20 +00001324 CGM.getCXXABI().emitRethrow(*this, /*isNoReturn*/false);
John McCalld8d00be2012-06-15 05:27:05 +00001325 Builder.CreateUnreachable();
1326 Builder.ClearInsertionPoint();
1327 }
1328
John McCallbd309292010-07-06 01:34:17 +00001329 // Fall out through the catch cleanups.
1330 CatchScope.ForceCleanup();
1331
1332 // Branch out of the try.
1333 if (HaveInsertPoint())
1334 Builder.CreateBr(ContBB);
Mike Stump58ef18b2009-11-20 23:44:51 +00001335 }
1336
Justin Bogneref512b92014-01-06 22:27:43 +00001337 RegionCounter ContCnt = getPGORegionCounter(&S);
John McCallbd309292010-07-06 01:34:17 +00001338 EmitBlock(ContBB);
Justin Bogneref512b92014-01-06 22:27:43 +00001339 ContCnt.beginRegion(Builder);
Mike Stump58ef18b2009-11-20 23:44:51 +00001340}
Mike Stumpaff69af2009-12-09 03:35:49 +00001341
John McCall1e670402010-07-21 00:52:03 +00001342namespace {
John McCallcda666c2010-07-21 07:22:38 +00001343 struct CallEndCatchForFinally : EHScopeStack::Cleanup {
John McCall1e670402010-07-21 00:52:03 +00001344 llvm::Value *ForEHVar;
1345 llvm::Value *EndCatchFn;
1346 CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn)
1347 : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
1348
Craig Topper4f12f102014-03-12 06:41:41 +00001349 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall1e670402010-07-21 00:52:03 +00001350 llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
1351 llvm::BasicBlock *CleanupContBB =
1352 CGF.createBasicBlock("finally.cleanup.cont");
1353
1354 llvm::Value *ShouldEndCatch =
1355 CGF.Builder.CreateLoad(ForEHVar, "finally.endcatch");
1356 CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1357 CGF.EmitBlock(EndCatchBB);
John McCall882987f2013-02-28 19:01:20 +00001358 CGF.EmitRuntimeCallOrInvoke(EndCatchFn); // catch-all, so might throw
John McCall1e670402010-07-21 00:52:03 +00001359 CGF.EmitBlock(CleanupContBB);
1360 }
1361 };
John McCall906da4b2010-07-21 05:47:49 +00001362
John McCallcda666c2010-07-21 07:22:38 +00001363 struct PerformFinally : EHScopeStack::Cleanup {
John McCall906da4b2010-07-21 05:47:49 +00001364 const Stmt *Body;
1365 llvm::Value *ForEHVar;
1366 llvm::Value *EndCatchFn;
1367 llvm::Value *RethrowFn;
1368 llvm::Value *SavedExnVar;
1369
1370 PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
1371 llvm::Value *EndCatchFn,
1372 llvm::Value *RethrowFn, llvm::Value *SavedExnVar)
1373 : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1374 RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
1375
Craig Topper4f12f102014-03-12 06:41:41 +00001376 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall906da4b2010-07-21 05:47:49 +00001377 // Enter a cleanup to call the end-catch function if one was provided.
1378 if (EndCatchFn)
John McCallcda666c2010-07-21 07:22:38 +00001379 CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
1380 ForEHVar, EndCatchFn);
John McCall906da4b2010-07-21 05:47:49 +00001381
John McCallcebe0ca2010-08-11 00:16:14 +00001382 // Save the current cleanup destination in case there are
1383 // cleanups in the finally block.
1384 llvm::Value *SavedCleanupDest =
1385 CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
1386 "cleanup.dest.saved");
1387
John McCall906da4b2010-07-21 05:47:49 +00001388 // Emit the finally block.
1389 CGF.EmitStmt(Body);
1390
1391 // If the end of the finally is reachable, check whether this was
1392 // for EH. If so, rethrow.
1393 if (CGF.HaveInsertPoint()) {
1394 llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
1395 llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
1396
1397 llvm::Value *ShouldRethrow =
1398 CGF.Builder.CreateLoad(ForEHVar, "finally.shouldthrow");
1399 CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1400
1401 CGF.EmitBlock(RethrowBB);
1402 if (SavedExnVar) {
John McCall882987f2013-02-28 19:01:20 +00001403 CGF.EmitRuntimeCallOrInvoke(RethrowFn,
1404 CGF.Builder.CreateLoad(SavedExnVar));
John McCall906da4b2010-07-21 05:47:49 +00001405 } else {
John McCall882987f2013-02-28 19:01:20 +00001406 CGF.EmitRuntimeCallOrInvoke(RethrowFn);
John McCall906da4b2010-07-21 05:47:49 +00001407 }
1408 CGF.Builder.CreateUnreachable();
1409
1410 CGF.EmitBlock(ContBB);
John McCallcebe0ca2010-08-11 00:16:14 +00001411
1412 // Restore the cleanup destination.
1413 CGF.Builder.CreateStore(SavedCleanupDest,
1414 CGF.getNormalCleanupDestSlot());
John McCall906da4b2010-07-21 05:47:49 +00001415 }
1416
1417 // Leave the end-catch cleanup. As an optimization, pretend that
1418 // the fallthrough path was inaccessible; we've dynamically proven
1419 // that we're not in the EH case along that path.
1420 if (EndCatchFn) {
1421 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1422 CGF.PopCleanupBlock();
1423 CGF.Builder.restoreIP(SavedIP);
1424 }
1425
1426 // Now make sure we actually have an insertion point or the
1427 // cleanup gods will hate us.
1428 CGF.EnsureInsertPoint();
1429 }
1430 };
John McCall1e670402010-07-21 00:52:03 +00001431}
1432
John McCallbd309292010-07-06 01:34:17 +00001433/// Enters a finally block for an implementation using zero-cost
1434/// exceptions. This is mostly general, but hard-codes some
1435/// language/ABI-specific behavior in the catch-all sections.
John McCall6b0feb72011-06-22 02:32:12 +00001436void CodeGenFunction::FinallyInfo::enter(CodeGenFunction &CGF,
1437 const Stmt *body,
1438 llvm::Constant *beginCatchFn,
1439 llvm::Constant *endCatchFn,
1440 llvm::Constant *rethrowFn) {
Craig Topper8a13c412014-05-21 05:09:00 +00001441 assert((beginCatchFn != nullptr) == (endCatchFn != nullptr) &&
John McCallbd309292010-07-06 01:34:17 +00001442 "begin/end catch functions not paired");
John McCall6b0feb72011-06-22 02:32:12 +00001443 assert(rethrowFn && "rethrow function is required");
1444
1445 BeginCatchFn = beginCatchFn;
Mike Stumpaff69af2009-12-09 03:35:49 +00001446
John McCallbd309292010-07-06 01:34:17 +00001447 // The rethrow function has one of the following two types:
1448 // void (*)()
1449 // void (*)(void*)
1450 // In the latter case we need to pass it the exception object.
1451 // But we can't use the exception slot because the @finally might
1452 // have a landing pad (which would overwrite the exception slot).
Chris Lattner2192fe52011-07-18 04:24:23 +00001453 llvm::FunctionType *rethrowFnTy =
John McCallbd309292010-07-06 01:34:17 +00001454 cast<llvm::FunctionType>(
John McCall6b0feb72011-06-22 02:32:12 +00001455 cast<llvm::PointerType>(rethrowFn->getType())->getElementType());
Craig Topper8a13c412014-05-21 05:09:00 +00001456 SavedExnVar = nullptr;
John McCall6b0feb72011-06-22 02:32:12 +00001457 if (rethrowFnTy->getNumParams())
1458 SavedExnVar = CGF.CreateTempAlloca(CGF.Int8PtrTy, "finally.exn");
Mike Stumpaff69af2009-12-09 03:35:49 +00001459
John McCallbd309292010-07-06 01:34:17 +00001460 // A finally block is a statement which must be executed on any edge
1461 // out of a given scope. Unlike a cleanup, the finally block may
1462 // contain arbitrary control flow leading out of itself. In
1463 // addition, finally blocks should always be executed, even if there
1464 // are no catch handlers higher on the stack. Therefore, we
1465 // surround the protected scope with a combination of a normal
1466 // cleanup (to catch attempts to break out of the block via normal
1467 // control flow) and an EH catch-all (semantically "outside" any try
1468 // statement to which the finally block might have been attached).
1469 // The finally block itself is generated in the context of a cleanup
1470 // which conditionally leaves the catch-all.
John McCall21886962010-04-21 10:05:39 +00001471
John McCallbd309292010-07-06 01:34:17 +00001472 // Jump destination for performing the finally block on an exception
1473 // edge. We'll never actually reach this block, so unreachable is
1474 // fine.
John McCall6b0feb72011-06-22 02:32:12 +00001475 RethrowDest = CGF.getJumpDestInCurrentScope(CGF.getUnreachableBlock());
John McCall21886962010-04-21 10:05:39 +00001476
John McCallbd309292010-07-06 01:34:17 +00001477 // Whether the finally block is being executed for EH purposes.
John McCall6b0feb72011-06-22 02:32:12 +00001478 ForEHVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "finally.for-eh");
1479 CGF.Builder.CreateStore(CGF.Builder.getFalse(), ForEHVar);
Mike Stumpaff69af2009-12-09 03:35:49 +00001480
John McCallbd309292010-07-06 01:34:17 +00001481 // Enter a normal cleanup which will perform the @finally block.
John McCall6b0feb72011-06-22 02:32:12 +00001482 CGF.EHStack.pushCleanup<PerformFinally>(NormalCleanup, body,
1483 ForEHVar, endCatchFn,
1484 rethrowFn, SavedExnVar);
John McCallbd309292010-07-06 01:34:17 +00001485
1486 // Enter a catch-all scope.
John McCall6b0feb72011-06-22 02:32:12 +00001487 llvm::BasicBlock *catchBB = CGF.createBasicBlock("finally.catchall");
1488 EHCatchScope *catchScope = CGF.EHStack.pushCatch(1);
1489 catchScope->setCatchAllHandler(0, catchBB);
John McCallbd309292010-07-06 01:34:17 +00001490}
1491
John McCall6b0feb72011-06-22 02:32:12 +00001492void CodeGenFunction::FinallyInfo::exit(CodeGenFunction &CGF) {
John McCallbd309292010-07-06 01:34:17 +00001493 // Leave the finally catch-all.
John McCall6b0feb72011-06-22 02:32:12 +00001494 EHCatchScope &catchScope = cast<EHCatchScope>(*CGF.EHStack.begin());
1495 llvm::BasicBlock *catchBB = catchScope.getHandler(0).Block;
John McCall8e4c74b2011-08-11 02:22:43 +00001496
1497 CGF.popCatchScope();
John McCallbd309292010-07-06 01:34:17 +00001498
John McCall6b0feb72011-06-22 02:32:12 +00001499 // If there are any references to the catch-all block, emit it.
1500 if (catchBB->use_empty()) {
1501 delete catchBB;
1502 } else {
1503 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveAndClearIP();
1504 CGF.EmitBlock(catchBB);
John McCallbd309292010-07-06 01:34:17 +00001505
Craig Topper8a13c412014-05-21 05:09:00 +00001506 llvm::Value *exn = nullptr;
John McCallbd309292010-07-06 01:34:17 +00001507
John McCall6b0feb72011-06-22 02:32:12 +00001508 // If there's a begin-catch function, call it.
1509 if (BeginCatchFn) {
Bill Wendling79a70e42011-09-15 18:57:19 +00001510 exn = CGF.getExceptionFromSlot();
John McCall882987f2013-02-28 19:01:20 +00001511 CGF.EmitNounwindRuntimeCall(BeginCatchFn, exn);
John McCall6b0feb72011-06-22 02:32:12 +00001512 }
1513
1514 // If we need to remember the exception pointer to rethrow later, do so.
1515 if (SavedExnVar) {
Bill Wendling79a70e42011-09-15 18:57:19 +00001516 if (!exn) exn = CGF.getExceptionFromSlot();
John McCall6b0feb72011-06-22 02:32:12 +00001517 CGF.Builder.CreateStore(exn, SavedExnVar);
1518 }
1519
1520 // Tell the cleanups in the finally block that we're do this for EH.
1521 CGF.Builder.CreateStore(CGF.Builder.getTrue(), ForEHVar);
1522
1523 // Thread a jump through the finally cleanup.
1524 CGF.EmitBranchThroughCleanup(RethrowDest);
1525
1526 CGF.Builder.restoreIP(savedIP);
1527 }
1528
1529 // Finally, leave the @finally cleanup.
1530 CGF.PopCleanupBlock();
John McCallbd309292010-07-06 01:34:17 +00001531}
1532
John McCalle142ad52013-02-12 03:51:46 +00001533/// In a terminate landing pad, should we use __clang__call_terminate
1534/// or just a naked call to std::terminate?
1535///
1536/// __clang_call_terminate calls __cxa_begin_catch, which then allows
1537/// std::terminate to usefully report something about the
1538/// violating exception.
1539static bool useClangCallTerminate(CodeGenModule &CGM) {
1540 // Only do this for Itanium-family ABIs in C++ mode.
1541 return (CGM.getLangOpts().CPlusPlus &&
1542 CGM.getTarget().getCXXABI().isItaniumFamily());
1543}
1544
1545/// Get or define the following function:
1546/// void @__clang_call_terminate(i8* %exn) nounwind noreturn
1547/// This code is used only in C++.
1548static llvm::Constant *getClangCallTerminateFn(CodeGenModule &CGM) {
1549 llvm::FunctionType *fnTy =
1550 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
1551 llvm::Constant *fnRef =
1552 CGM.CreateRuntimeFunction(fnTy, "__clang_call_terminate");
1553
1554 llvm::Function *fn = dyn_cast<llvm::Function>(fnRef);
1555 if (fn && fn->empty()) {
1556 fn->setDoesNotThrow();
1557 fn->setDoesNotReturn();
1558
1559 // What we really want is to massively penalize inlining without
1560 // forbidding it completely. The difference between that and
1561 // 'noinline' is negligible.
1562 fn->addFnAttr(llvm::Attribute::NoInline);
1563
1564 // Allow this function to be shared across translation units, but
1565 // we don't want it to turn into an exported symbol.
1566 fn->setLinkage(llvm::Function::LinkOnceODRLinkage);
1567 fn->setVisibility(llvm::Function::HiddenVisibility);
1568
1569 // Set up the function.
1570 llvm::BasicBlock *entry =
1571 llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn);
1572 CGBuilderTy builder(entry);
1573
1574 // Pull the exception pointer out of the parameter list.
1575 llvm::Value *exn = &*fn->arg_begin();
1576
1577 // Call __cxa_begin_catch(exn).
John McCall882987f2013-02-28 19:01:20 +00001578 llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn);
1579 catchCall->setDoesNotThrow();
1580 catchCall->setCallingConv(CGM.getRuntimeCC());
John McCalle142ad52013-02-12 03:51:46 +00001581
1582 // Call std::terminate().
1583 llvm::CallInst *termCall = builder.CreateCall(getTerminateFn(CGM));
1584 termCall->setDoesNotThrow();
1585 termCall->setDoesNotReturn();
John McCall882987f2013-02-28 19:01:20 +00001586 termCall->setCallingConv(CGM.getRuntimeCC());
John McCalle142ad52013-02-12 03:51:46 +00001587
1588 // std::terminate cannot return.
1589 builder.CreateUnreachable();
1590 }
1591
1592 return fnRef;
1593}
1594
John McCallbd309292010-07-06 01:34:17 +00001595llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
1596 if (TerminateLandingPad)
1597 return TerminateLandingPad;
1598
1599 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1600
1601 // This will get inserted at the end of the function.
1602 TerminateLandingPad = createBasicBlock("terminate.lpad");
1603 Builder.SetInsertPoint(TerminateLandingPad);
1604
1605 // Tell the backend that this is a landing pad.
Reid Klecknerdeeddec2015-02-05 18:56:03 +00001606 const EHPersonality &Personality = EHPersonality::get(*this);
Bill Wendlingf0724e82011-09-19 20:31:14 +00001607 llvm::LandingPadInst *LPadInst =
Reid Kleckneree7cf842014-12-01 22:02:27 +00001608 Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, nullptr),
Bill Wendlingf0724e82011-09-19 20:31:14 +00001609 getOpaquePersonalityFn(CGM, Personality), 0);
1610 LPadInst->addClause(getCatchAllValue(*this));
John McCallbd309292010-07-06 01:34:17 +00001611
John McCalle142ad52013-02-12 03:51:46 +00001612 llvm::CallInst *terminateCall;
1613 if (useClangCallTerminate(CGM)) {
1614 // Extract out the exception pointer.
1615 llvm::Value *exn = Builder.CreateExtractValue(LPadInst, 0);
John McCall882987f2013-02-28 19:01:20 +00001616 terminateCall = EmitNounwindRuntimeCall(getClangCallTerminateFn(CGM), exn);
John McCalle142ad52013-02-12 03:51:46 +00001617 } else {
John McCall882987f2013-02-28 19:01:20 +00001618 terminateCall = EmitNounwindRuntimeCall(getTerminateFn(CGM));
John McCalle142ad52013-02-12 03:51:46 +00001619 }
1620 terminateCall->setDoesNotReturn();
John McCallad7c5c12011-02-08 08:22:06 +00001621 Builder.CreateUnreachable();
Mike Stumpaff69af2009-12-09 03:35:49 +00001622
John McCallbd309292010-07-06 01:34:17 +00001623 // Restore the saved insertion state.
1624 Builder.restoreIP(SavedIP);
John McCalldac3ea62010-04-30 00:06:43 +00001625
John McCallbd309292010-07-06 01:34:17 +00001626 return TerminateLandingPad;
Mike Stumpaff69af2009-12-09 03:35:49 +00001627}
Mike Stump2b488872009-12-09 22:59:31 +00001628
1629llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
Mike Stumpf5cbb082009-12-10 00:02:42 +00001630 if (TerminateHandler)
1631 return TerminateHandler;
1632
John McCallbd309292010-07-06 01:34:17 +00001633 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
Mike Stump25b20fc2009-12-09 23:31:35 +00001634
John McCallbd309292010-07-06 01:34:17 +00001635 // Set up the terminate handler. This block is inserted at the very
1636 // end of the function by FinishFunction.
Mike Stumpf5cbb082009-12-10 00:02:42 +00001637 TerminateHandler = createBasicBlock("terminate.handler");
John McCallbd309292010-07-06 01:34:17 +00001638 Builder.SetInsertPoint(TerminateHandler);
John McCallc84e4e92013-06-20 21:37:43 +00001639 llvm::CallInst *terminateCall;
1640 if (useClangCallTerminate(CGM)) {
1641 // Load the exception pointer.
1642 llvm::Value *exn = getExceptionFromSlot();
1643 terminateCall = EmitNounwindRuntimeCall(getClangCallTerminateFn(CGM), exn);
1644 } else {
1645 terminateCall = EmitNounwindRuntimeCall(getTerminateFn(CGM));
1646 }
1647 terminateCall->setDoesNotReturn();
Mike Stump2b488872009-12-09 22:59:31 +00001648 Builder.CreateUnreachable();
1649
John McCall21886962010-04-21 10:05:39 +00001650 // Restore the saved insertion state.
John McCallbd309292010-07-06 01:34:17 +00001651 Builder.restoreIP(SavedIP);
Mike Stump25b20fc2009-12-09 23:31:35 +00001652
Mike Stump2b488872009-12-09 22:59:31 +00001653 return TerminateHandler;
1654}
John McCallbd309292010-07-06 01:34:17 +00001655
David Chisnall9a837be2012-11-07 16:50:40 +00001656llvm::BasicBlock *CodeGenFunction::getEHResumeBlock(bool isCleanup) {
John McCall8e4c74b2011-08-11 02:22:43 +00001657 if (EHResumeBlock) return EHResumeBlock;
John McCallad5d61e2010-07-23 21:56:41 +00001658
1659 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1660
1661 // We emit a jump to a notional label at the outermost unwind state.
John McCall8e4c74b2011-08-11 02:22:43 +00001662 EHResumeBlock = createBasicBlock("eh.resume");
1663 Builder.SetInsertPoint(EHResumeBlock);
John McCallad5d61e2010-07-23 21:56:41 +00001664
Reid Klecknerdeeddec2015-02-05 18:56:03 +00001665 const EHPersonality &Personality = EHPersonality::get(*this);
John McCallad5d61e2010-07-23 21:56:41 +00001666
1667 // This can always be a call because we necessarily didn't find
1668 // anything on the EH stack which needs our help.
Benjamin Kramer793bd552012-02-08 12:41:24 +00001669 const char *RethrowName = Personality.CatchallRethrowFn;
Craig Topper8a13c412014-05-21 05:09:00 +00001670 if (RethrowName != nullptr && !isCleanup) {
John McCall882987f2013-02-28 19:01:20 +00001671 EmitRuntimeCall(getCatchallRethrowFn(CGM, RethrowName),
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001672 getExceptionFromSlot())
John McCall9b382dd2011-05-28 21:13:02 +00001673 ->setDoesNotReturn();
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001674 Builder.CreateUnreachable();
1675 Builder.restoreIP(SavedIP);
1676 return EHResumeBlock;
John McCall9b382dd2011-05-28 21:13:02 +00001677 }
1678
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001679 // Recreate the landingpad's return value for the 'resume' instruction.
1680 llvm::Value *Exn = getExceptionFromSlot();
1681 llvm::Value *Sel = getSelectorFromSlot();
John McCallad5d61e2010-07-23 21:56:41 +00001682
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001683 llvm::Type *LPadType = llvm::StructType::get(Exn->getType(),
Reid Kleckneree7cf842014-12-01 22:02:27 +00001684 Sel->getType(), nullptr);
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001685 llvm::Value *LPadVal = llvm::UndefValue::get(LPadType);
1686 LPadVal = Builder.CreateInsertValue(LPadVal, Exn, 0, "lpad.val");
1687 LPadVal = Builder.CreateInsertValue(LPadVal, Sel, 1, "lpad.val");
1688
1689 Builder.CreateResume(LPadVal);
John McCallad5d61e2010-07-23 21:56:41 +00001690 Builder.restoreIP(SavedIP);
John McCall8e4c74b2011-08-11 02:22:43 +00001691 return EHResumeBlock;
John McCallad5d61e2010-07-23 21:56:41 +00001692}
Reid Kleckner543a16c2013-09-16 21:46:30 +00001693
1694void CodeGenFunction::EmitSEHTryStmt(const SEHTryStmt &S) {
Reid Kleckner1d59f992015-01-22 01:36:17 +00001695 // FIXME: Implement SEH on other architectures.
1696 const llvm::Triple &T = CGM.getTarget().getTriple();
1697 if (T.getArch() != llvm::Triple::x86_64 ||
1698 !T.isKnownWindowsMSVCEnvironment()) {
1699 ErrorUnsupported(&S, "__try statement");
1700 return;
1701 }
1702
Reid Kleckneraca01db2015-02-04 22:37:07 +00001703 SEHFinallyInfo FI;
1704 EnterSEHTryStmt(S, FI);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001705 EmitStmt(S.getTryBlock());
Reid Kleckneraca01db2015-02-04 22:37:07 +00001706 ExitSEHTryStmt(S, FI);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001707}
1708
1709namespace {
1710struct PerformSEHFinally : EHScopeStack::Cleanup {
Reid Kleckneraca01db2015-02-04 22:37:07 +00001711 CodeGenFunction::SEHFinallyInfo *FI;
1712 PerformSEHFinally(CodeGenFunction::SEHFinallyInfo *FI) : FI(FI) {}
1713
Reid Kleckner1d59f992015-01-22 01:36:17 +00001714 void Emit(CodeGenFunction &CGF, Flags F) override {
Reid Kleckneraca01db2015-02-04 22:37:07 +00001715 // Cleanups are emitted at most twice: once for normal control flow and once
1716 // for exception control flow. Branch into the finally block, and remember
1717 // the continuation block so we can branch out later.
1718 if (!FI->FinallyBB) {
1719 FI->FinallyBB = CGF.createBasicBlock("__finally");
1720 FI->FinallyBB->insertInto(CGF.CurFn);
1721 FI->FinallyBB->moveAfter(CGF.Builder.GetInsertBlock());
1722 }
1723
1724 // Set the termination status and branch in.
1725 CGF.Builder.CreateStore(
1726 llvm::ConstantInt::get(CGF.Int8Ty, F.isForEHCleanup()),
1727 CGF.getAbnormalTerminationSlot());
1728 CGF.Builder.CreateBr(FI->FinallyBB);
1729
1730 // Create a continuation block for normal or exceptional control.
1731 if (F.isForEHCleanup()) {
1732 assert(!FI->ResumeBB && "double emission for EH");
1733 FI->ResumeBB = CGF.createBasicBlock("__finally.resume");
1734 CGF.EmitBlock(FI->ResumeBB);
1735 } else {
1736 assert(F.isForNormalCleanup() && !FI->ContBB && "double normal emission");
1737 FI->ContBB = CGF.createBasicBlock("__finally.cont");
1738 CGF.EmitBlock(FI->ContBB);
1739 // Try to keep source order.
1740 FI->ContBB->moveAfter(FI->FinallyBB);
1741 }
Reid Kleckner1d59f992015-01-22 01:36:17 +00001742 }
1743};
1744}
1745
1746/// Create a stub filter function that will ultimately hold the code of the
1747/// filter expression. The EH preparation passes in LLVM will outline the code
1748/// from the main function body into this stub.
1749llvm::Function *
1750CodeGenFunction::GenerateSEHFilterFunction(CodeGenFunction &ParentCGF,
1751 const SEHExceptStmt &Except) {
1752 const Decl *ParentCodeDecl = ParentCGF.CurCodeDecl;
1753 llvm::Function *ParentFn = ParentCGF.CurFn;
1754
1755 Expr *FilterExpr = Except.getFilterExpr();
1756
1757 // Get the mangled function name.
1758 SmallString<128> Name;
1759 {
1760 llvm::raw_svector_ostream OS(Name);
1761 const NamedDecl *Parent = dyn_cast_or_null<NamedDecl>(ParentCodeDecl);
1762 assert(Parent && "FIXME: handle unnamed decls (lambdas, blocks) with SEH");
1763 CGM.getCXXABI().getMangleContext().mangleSEHFilterExpression(Parent, OS);
1764 }
1765
1766 // Arrange a function with the declaration:
1767 // int filt(EXCEPTION_POINTERS *exception_pointers, void *frame_pointer)
1768 QualType RetTy = getContext().IntTy;
1769 FunctionArgList Args;
1770 SEHPointersDecl = ImplicitParamDecl::Create(
1771 getContext(), nullptr, FilterExpr->getLocStart(),
1772 &getContext().Idents.get("exception_pointers"), getContext().VoidPtrTy);
1773 Args.push_back(SEHPointersDecl);
1774 Args.push_back(ImplicitParamDecl::Create(
1775 getContext(), nullptr, FilterExpr->getLocStart(),
1776 &getContext().Idents.get("frame_pointer"), getContext().VoidPtrTy));
1777 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionDeclaration(
1778 RetTy, Args, FunctionType::ExtInfo(), /*isVariadic=*/false);
1779 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
1780 llvm::Function *Fn = llvm::Function::Create(FnTy, ParentFn->getLinkage(),
1781 Name.str(), &CGM.getModule());
1782 // The filter is either in the same comdat as the function, or it's internal.
1783 if (llvm::Comdat *C = ParentFn->getComdat()) {
1784 Fn->setComdat(C);
1785 } else if (ParentFn->hasWeakLinkage() || ParentFn->hasLinkOnceLinkage()) {
1786 // FIXME: Unreachable with Rafael's changes?
1787 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(ParentFn->getName());
1788 ParentFn->setComdat(C);
1789 Fn->setComdat(C);
1790 } else {
1791 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
1792 }
1793
1794 StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args,
1795 FilterExpr->getLocStart(), FilterExpr->getLocStart());
1796
1797 EmitSEHExceptionCodeSave();
1798
1799 // Insert dummy allocas for every local variable in scope. We'll initialize
1800 // them and prune the unused ones after we find out which ones were
1801 // referenced.
1802 for (const auto &DeclPtrs : ParentCGF.LocalDeclMap) {
1803 const Decl *VD = DeclPtrs.first;
1804 llvm::Value *Ptr = DeclPtrs.second;
1805 auto *ValTy = cast<llvm::PointerType>(Ptr->getType())->getElementType();
1806 LocalDeclMap[VD] = CreateTempAlloca(ValTy, Ptr->getName() + ".filt");
1807 }
1808
1809 // Emit the original filter expression, convert to i32, and return.
1810 llvm::Value *R = EmitScalarExpr(FilterExpr);
1811 R = Builder.CreateIntCast(R, CGM.IntTy,
1812 FilterExpr->getType()->isSignedIntegerType());
1813 Builder.CreateStore(R, ReturnValue);
1814
1815 FinishFunction(FilterExpr->getLocEnd());
1816
1817 for (const auto &DeclPtrs : ParentCGF.LocalDeclMap) {
1818 const Decl *VD = DeclPtrs.first;
1819 auto *Alloca = cast<llvm::AllocaInst>(LocalDeclMap[VD]);
1820 if (Alloca->hasNUses(0)) {
1821 Alloca->eraseFromParent();
1822 continue;
1823 }
1824 ErrorUnsupported(FilterExpr,
1825 "SEH filter expression local variable capture");
1826 }
1827
1828 return Fn;
1829}
1830
1831void CodeGenFunction::EmitSEHExceptionCodeSave() {
1832 // Save the exception code in the exception slot to unify exception access in
1833 // the filter function and the landing pad.
1834 // struct EXCEPTION_POINTERS {
1835 // EXCEPTION_RECORD *ExceptionRecord;
1836 // CONTEXT *ContextRecord;
1837 // };
1838 // void *exn.slot =
1839 // (void *)(uintptr_t)exception_pointers->ExceptionRecord->ExceptionCode;
1840 llvm::Value *Ptrs = Builder.CreateLoad(GetAddrOfLocalVar(SEHPointersDecl));
1841 llvm::Type *RecordTy = CGM.Int32Ty->getPointerTo();
1842 llvm::Type *PtrsTy = llvm::StructType::get(RecordTy, CGM.VoidPtrTy, nullptr);
1843 Ptrs = Builder.CreateBitCast(Ptrs, PtrsTy->getPointerTo());
1844 llvm::Value *Rec = Builder.CreateStructGEP(Ptrs, 0);
1845 Rec = Builder.CreateLoad(Rec);
1846 llvm::Value *Code = Builder.CreateLoad(Rec);
1847 Code = Builder.CreateZExt(Code, CGM.IntPtrTy);
1848 // FIXME: Change landing pads to produce {i32, i32} and make the exception
1849 // slot an i32.
1850 Code = Builder.CreateIntToPtr(Code, CGM.VoidPtrTy);
1851 Builder.CreateStore(Code, getExceptionSlot());
1852}
1853
1854llvm::Value *CodeGenFunction::EmitSEHExceptionInfo() {
1855 // Sema should diagnose calling this builtin outside of a filter context, but
1856 // don't crash if we screw up.
1857 if (!SEHPointersDecl)
1858 return llvm::UndefValue::get(Int8PtrTy);
1859 return Builder.CreateLoad(GetAddrOfLocalVar(SEHPointersDecl));
1860}
1861
1862llvm::Value *CodeGenFunction::EmitSEHExceptionCode() {
1863 // If we're in a landing pad or filter function, the exception slot contains
1864 // the code.
1865 assert(ExceptionSlot);
1866 llvm::Value *Code =
1867 Builder.CreatePtrToInt(getExceptionFromSlot(), CGM.IntPtrTy);
1868 return Builder.CreateTrunc(Code, CGM.Int32Ty);
1869}
1870
Reid Kleckneraca01db2015-02-04 22:37:07 +00001871llvm::Value *CodeGenFunction::EmitSEHAbnormalTermination() {
1872 // Load from the abnormal termination slot. It will be uninitialized outside
1873 // of __finally blocks, which we should warn or error on.
1874 llvm::Value *IsEH = Builder.CreateLoad(getAbnormalTerminationSlot());
1875 return Builder.CreateZExt(IsEH, Int32Ty);
1876}
1877
1878void CodeGenFunction::EnterSEHTryStmt(const SEHTryStmt &S, SEHFinallyInfo &FI) {
Sean Silvab1287ee2015-02-05 01:20:26 +00001879 if (S.getFinallyHandler()) {
Reid Kleckner1d59f992015-01-22 01:36:17 +00001880 // Push a cleanup for __finally blocks.
Reid Kleckneraca01db2015-02-04 22:37:07 +00001881 EHStack.pushCleanup<PerformSEHFinally>(NormalAndEHCleanup, &FI);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001882 return;
1883 }
1884
1885 // Otherwise, we must have an __except block.
1886 SEHExceptStmt *Except = S.getExceptHandler();
1887 assert(Except);
1888 EHCatchScope *CatchScope = EHStack.pushCatch(1);
Reid Kleckner2a2e1562015-01-22 02:25:56 +00001889
1890 // If the filter is known to evaluate to 1, then we can use the clause "catch
1891 // i8* null".
1892 llvm::Constant *C =
1893 CGM.EmitConstantExpr(Except->getFilterExpr(), getContext().IntTy, this);
1894 if (C && C->isOneValue()) {
1895 CatchScope->setCatchAllHandler(0, createBasicBlock("__except"));
1896 return;
1897 }
1898
1899 // In general, we have to emit an outlined filter function. Use the function
1900 // in place of the RTTI typeinfo global that C++ EH uses.
Reid Kleckner1d59f992015-01-22 01:36:17 +00001901 CodeGenFunction FilterCGF(CGM, /*suppressNewContext=*/true);
1902 llvm::Function *FilterFunc =
1903 FilterCGF.GenerateSEHFilterFunction(*this, *Except);
1904 llvm::Constant *OpaqueFunc =
1905 llvm::ConstantExpr::getBitCast(FilterFunc, Int8PtrTy);
1906 CatchScope->setHandler(0, OpaqueFunc, createBasicBlock("__except"));
1907}
1908
Reid Kleckneraca01db2015-02-04 22:37:07 +00001909void CodeGenFunction::ExitSEHTryStmt(const SEHTryStmt &S, SEHFinallyInfo &FI) {
Reid Kleckner1d59f992015-01-22 01:36:17 +00001910 // Just pop the cleanup if it's a __finally block.
Reid Kleckneraca01db2015-02-04 22:37:07 +00001911 if (const SEHFinallyStmt *Finally = S.getFinallyHandler()) {
Reid Kleckner1d59f992015-01-22 01:36:17 +00001912 PopCleanupBlock();
Reid Kleckner16f9a6b2015-02-05 00:58:46 +00001913 assert(FI.ContBB && "did not emit normal cleanup");
Reid Kleckneraca01db2015-02-04 22:37:07 +00001914
1915 // Emit the code into FinallyBB.
1916 Builder.SetInsertPoint(FI.FinallyBB);
1917 EmitStmt(Finally->getBlock());
1918
Reid Kleckner16f9a6b2015-02-05 00:58:46 +00001919 // If the finally block doesn't fall through, we don't need these blocks.
1920 if (!HaveInsertPoint()) {
1921 FI.ContBB->eraseFromParent();
1922 if (FI.ResumeBB)
1923 FI.ResumeBB->eraseFromParent();
1924 return;
1925 }
1926
Reid Kleckneraca01db2015-02-04 22:37:07 +00001927 if (FI.ResumeBB) {
1928 llvm::Value *IsEH = Builder.CreateLoad(getAbnormalTerminationSlot(),
1929 "abnormal.termination");
1930 IsEH = Builder.CreateICmpEQ(IsEH, llvm::ConstantInt::get(Int8Ty, 0));
1931 Builder.CreateCondBr(IsEH, FI.ContBB, FI.ResumeBB);
1932 } else {
1933 // There was nothing exceptional in the try body, so we only have normal
1934 // control flow.
1935 Builder.CreateBr(FI.ContBB);
1936 }
1937
1938 Builder.SetInsertPoint(FI.ContBB);
1939
Reid Kleckner1d59f992015-01-22 01:36:17 +00001940 return;
1941 }
1942
1943 // Otherwise, we must have an __except block.
Reid Kleckneraca01db2015-02-04 22:37:07 +00001944 const SEHExceptStmt *Except = S.getExceptHandler();
Reid Kleckner1d59f992015-01-22 01:36:17 +00001945 assert(Except && "__try must have __finally xor __except");
1946 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1947
1948 // Don't emit the __except block if the __try block lacked invokes.
1949 // TODO: Model unwind edges from instructions, either with iload / istore or
1950 // a try body function.
1951 if (!CatchScope.hasEHBranches()) {
1952 CatchScope.clearHandlerBlocks();
1953 EHStack.popCatch();
1954 return;
1955 }
1956
1957 // The fall-through block.
1958 llvm::BasicBlock *ContBB = createBasicBlock("__try.cont");
1959
1960 // We just emitted the body of the __try; jump to the continue block.
1961 if (HaveInsertPoint())
1962 Builder.CreateBr(ContBB);
1963
1964 // Check if our filter function returned true.
1965 emitCatchDispatchBlock(*this, CatchScope);
1966
1967 // Grab the block before we pop the handler.
1968 llvm::BasicBlock *ExceptBB = CatchScope.getHandler(0).Block;
1969 EHStack.popCatch();
1970
1971 EmitBlockAfterUses(ExceptBB);
1972
1973 // Emit the __except body.
1974 EmitStmt(Except->getBlock());
1975
Reid Kleckner3a417c32015-01-30 22:16:45 +00001976 if (HaveInsertPoint())
1977 Builder.CreateBr(ContBB);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001978
1979 EmitBlock(ContBB);
Reid Kleckner543a16c2013-09-16 21:46:30 +00001980}
Nico Weber9b982072014-07-07 00:12:30 +00001981
1982void CodeGenFunction::EmitSEHLeaveStmt(const SEHLeaveStmt &S) {
1983 CGM.ErrorUnsupported(&S, "SEH __leave");
1984}