blob: a76b3d82abbba18f5496f7a666c22d04b4e983f5 [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"
Reid Klecknera5930002015-02-11 21:40:48 +000024#include "llvm/Support/SaveAndRestore.h"
John McCallbd309292010-07-06 01:34:17 +000025
Anders Carlsson4b08db72009-10-30 01:42:31 +000026using namespace clang;
27using namespace CodeGen;
28
John McCall2c33ba82013-02-12 03:51:38 +000029static llvm::Constant *getAllocateExceptionFn(CodeGenModule &CGM) {
Anders Carlsson32e1b1c2009-10-30 02:27:02 +000030 // void *__cxa_allocate_exception(size_t thrown_size);
Mike Stump75546b82009-12-10 00:06:18 +000031
Chris Lattner2192fe52011-07-18 04:24:23 +000032 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +000033 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.SizeTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000034
John McCall2c33ba82013-02-12 03:51:38 +000035 return CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
Anders Carlsson32e1b1c2009-10-30 02:27:02 +000036}
37
John McCall2c33ba82013-02-12 03:51:38 +000038static llvm::Constant *getFreeExceptionFn(CodeGenModule &CGM) {
Mike Stump33270212009-12-02 07:41:41 +000039 // void __cxa_free_exception(void *thrown_exception);
Mike Stump75546b82009-12-10 00:06:18 +000040
Chris Lattner2192fe52011-07-18 04:24:23 +000041 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +000042 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000043
John McCall2c33ba82013-02-12 03:51:38 +000044 return CGM.CreateRuntimeFunction(FTy, "__cxa_free_exception");
Mike Stump33270212009-12-02 07:41:41 +000045}
46
John McCall2c33ba82013-02-12 03:51:38 +000047static llvm::Constant *getThrowFn(CodeGenModule &CGM) {
Mike Stump75546b82009-12-10 00:06:18 +000048 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
Mike Stump33270212009-12-02 07:41:41 +000049 // void (*dest) (void *));
Anders Carlsson32e1b1c2009-10-30 02:27:02 +000050
John McCall2c33ba82013-02-12 03:51:38 +000051 llvm::Type *Args[3] = { CGM.Int8PtrTy, CGM.Int8PtrTy, CGM.Int8PtrTy };
Chris Lattner2192fe52011-07-18 04:24:23 +000052 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +000053 llvm::FunctionType::get(CGM.VoidTy, Args, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000054
John McCall2c33ba82013-02-12 03:51:38 +000055 return CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
Anders Carlsson32e1b1c2009-10-30 02:27:02 +000056}
57
John McCall2c33ba82013-02-12 03:51:38 +000058static llvm::Constant *getGetExceptionPtrFn(CodeGenModule &CGM) {
John McCallbd309292010-07-06 01:34:17 +000059 // void *__cxa_get_exception_ptr(void*);
John McCallbd309292010-07-06 01:34:17 +000060
Chris Lattner2192fe52011-07-18 04:24:23 +000061 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +000062 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
John McCallbd309292010-07-06 01:34:17 +000063
John McCall2c33ba82013-02-12 03:51:38 +000064 return CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
John McCallbd309292010-07-06 01:34:17 +000065}
66
John McCall2c33ba82013-02-12 03:51:38 +000067static llvm::Constant *getBeginCatchFn(CodeGenModule &CGM) {
John McCallbd309292010-07-06 01:34:17 +000068 // void *__cxa_begin_catch(void*);
Mike Stump58ef18b2009-11-20 23:44:51 +000069
Chris Lattner2192fe52011-07-18 04:24:23 +000070 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +000071 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000072
John McCall2c33ba82013-02-12 03:51:38 +000073 return CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
Mike Stump58ef18b2009-11-20 23:44:51 +000074}
75
John McCall2c33ba82013-02-12 03:51:38 +000076static llvm::Constant *getEndCatchFn(CodeGenModule &CGM) {
Mike Stump33270212009-12-02 07:41:41 +000077 // void __cxa_end_catch();
Mike Stump58ef18b2009-11-20 23:44:51 +000078
Chris Lattner2192fe52011-07-18 04:24:23 +000079 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +000080 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000081
John McCall2c33ba82013-02-12 03:51:38 +000082 return CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
Mike Stump58ef18b2009-11-20 23:44:51 +000083}
84
John McCall2c33ba82013-02-12 03:51:38 +000085static llvm::Constant *getUnexpectedFn(CodeGenModule &CGM) {
Richard Smith2f7aa192013-06-20 23:03:35 +000086 // void __cxa_call_unexpected(void *thrown_exception);
Mike Stump1d849212009-12-07 23:38:24 +000087
Chris Lattner2192fe52011-07-18 04:24:23 +000088 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +000089 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000090
John McCall2c33ba82013-02-12 03:51:38 +000091 return CGM.CreateRuntimeFunction(FTy, "__cxa_call_unexpected");
Mike Stump1d849212009-12-07 23:38:24 +000092}
93
John McCall2c33ba82013-02-12 03:51:38 +000094static llvm::Constant *getTerminateFn(CodeGenModule &CGM) {
Mike Stump33270212009-12-02 07:41:41 +000095 // void __terminate();
96
Chris Lattner2192fe52011-07-18 04:24:23 +000097 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +000098 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000099
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000100 StringRef name;
John McCall9de19782011-07-06 01:22:26 +0000101
102 // In C++, use std::terminate().
Reid Kleckner1d59f992015-01-22 01:36:17 +0000103 if (CGM.getLangOpts().CPlusPlus &&
104 CGM.getTarget().getCXXABI().isItaniumFamily()) {
105 name = "_ZSt9terminatev";
106 } else if (CGM.getLangOpts().ObjC1 &&
John McCall2c33ba82013-02-12 03:51:38 +0000107 CGM.getLangOpts().ObjCRuntime.hasTerminate())
John McCall9de19782011-07-06 01:22:26 +0000108 name = "objc_terminate";
109 else
110 name = "abort";
John McCall2c33ba82013-02-12 03:51:38 +0000111 return CGM.CreateRuntimeFunction(FTy, name);
David Chisnallf9c42252010-05-17 13:49:20 +0000112}
113
John McCall2c33ba82013-02-12 03:51:38 +0000114static llvm::Constant *getCatchallRethrowFn(CodeGenModule &CGM,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000115 StringRef Name) {
Chris Lattner2192fe52011-07-18 04:24:23 +0000116 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +0000117 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
John McCall36ea3722010-07-17 00:43:08 +0000118
John McCall2c33ba82013-02-12 03:51:38 +0000119 return CGM.CreateRuntimeFunction(FTy, Name);
John McCallbd309292010-07-06 01:34:17 +0000120}
121
Benjamin Kramer793bd552012-02-08 12:41:24 +0000122namespace {
123 /// The exceptions personality for a function.
124 struct EHPersonality {
125 const char *PersonalityFn;
126
127 // If this is non-null, this personality requires a non-standard
128 // function for rethrowing an exception after a catchall cleanup.
129 // This function must have prototype void(void*).
130 const char *CatchallRethrowFn;
131
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000132 static const EHPersonality &get(CodeGenModule &CGM,
133 const FunctionDecl *FD);
134 static const EHPersonality &get(CodeGenFunction &CGF) {
135 return get(CGF.CGM, dyn_cast_or_null<FunctionDecl>(CGF.CurCodeDecl));
136 }
137
Benjamin Kramer793bd552012-02-08 12:41:24 +0000138 static const EHPersonality GNU_C;
139 static const EHPersonality GNU_C_SJLJ;
Reid Kleckner8f45c9c2014-09-15 17:19:16 +0000140 static const EHPersonality GNU_C_SEH;
Benjamin Kramer793bd552012-02-08 12:41:24 +0000141 static const EHPersonality GNU_ObjC;
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000142 static const EHPersonality GNUstep_ObjC;
Benjamin Kramer793bd552012-02-08 12:41:24 +0000143 static const EHPersonality GNU_ObjCXX;
144 static const EHPersonality NeXT_ObjC;
145 static const EHPersonality GNU_CPlusPlus;
146 static const EHPersonality GNU_CPlusPlus_SJLJ;
Reid Kleckner8f45c9c2014-09-15 17:19:16 +0000147 static const EHPersonality GNU_CPlusPlus_SEH;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000148 static const EHPersonality MSVC_except_handler;
149 static const EHPersonality MSVC_C_specific_handler;
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000150 static const EHPersonality MSVC_CxxFrameHandler3;
Benjamin Kramer793bd552012-02-08 12:41:24 +0000151 };
152}
153
Craig Topper8a13c412014-05-21 05:09:00 +0000154const EHPersonality EHPersonality::GNU_C = { "__gcc_personality_v0", nullptr };
Benjamin Kramer793bd552012-02-08 12:41:24 +0000155const EHPersonality
Craig Topper8a13c412014-05-21 05:09:00 +0000156EHPersonality::GNU_C_SJLJ = { "__gcc_personality_sj0", nullptr };
157const EHPersonality
Reid Kleckner8f45c9c2014-09-15 17:19:16 +0000158EHPersonality::GNU_C_SEH = { "__gcc_personality_seh0", nullptr };
159const EHPersonality
Craig Topper8a13c412014-05-21 05:09:00 +0000160EHPersonality::NeXT_ObjC = { "__objc_personality_v0", nullptr };
161const EHPersonality
162EHPersonality::GNU_CPlusPlus = { "__gxx_personality_v0", nullptr };
163const EHPersonality
164EHPersonality::GNU_CPlusPlus_SJLJ = { "__gxx_personality_sj0", nullptr };
Benjamin Kramer793bd552012-02-08 12:41:24 +0000165const EHPersonality
Reid Kleckner8f45c9c2014-09-15 17:19:16 +0000166EHPersonality::GNU_CPlusPlus_SEH = { "__gxx_personality_seh0", nullptr };
167const EHPersonality
Benjamin Kramer793bd552012-02-08 12:41:24 +0000168EHPersonality::GNU_ObjC = {"__gnu_objc_personality_v0", "objc_exception_throw"};
169const EHPersonality
Craig Topper8a13c412014-05-21 05:09:00 +0000170EHPersonality::GNU_ObjCXX = { "__gnustep_objcxx_personality_v0", nullptr };
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000171const EHPersonality
Craig Topper8a13c412014-05-21 05:09:00 +0000172EHPersonality::GNUstep_ObjC = { "__gnustep_objc_personality_v0", nullptr };
Reid Kleckner1d59f992015-01-22 01:36:17 +0000173const EHPersonality
174EHPersonality::MSVC_except_handler = { "_except_handler3", nullptr };
175const EHPersonality
176EHPersonality::MSVC_C_specific_handler = { "__C_specific_handler", nullptr };
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000177const EHPersonality
178EHPersonality::MSVC_CxxFrameHandler3 = { "__CxxFrameHandler3", nullptr };
John McCall36ea3722010-07-17 00:43:08 +0000179
Reid Klecknere070b992014-11-14 02:01:10 +0000180/// On Win64, use libgcc's SEH personality function. We fall back to dwarf on
181/// other platforms, unless the user asked for SjLj exceptions.
182static bool useLibGCCSEHPersonality(const llvm::Triple &T) {
183 return T.isOSWindows() && T.getArch() == llvm::Triple::x86_64;
184}
185
186static const EHPersonality &getCPersonality(const llvm::Triple &T,
187 const LangOptions &L) {
John McCall2faab302010-11-07 02:35:25 +0000188 if (L.SjLjExceptions)
189 return EHPersonality::GNU_C_SJLJ;
Reid Klecknere070b992014-11-14 02:01:10 +0000190 else if (useLibGCCSEHPersonality(T))
Reid Kleckner8f45c9c2014-09-15 17:19:16 +0000191 return EHPersonality::GNU_C_SEH;
John McCall36ea3722010-07-17 00:43:08 +0000192 return EHPersonality::GNU_C;
193}
194
Reid Klecknere070b992014-11-14 02:01:10 +0000195static const EHPersonality &getObjCPersonality(const llvm::Triple &T,
196 const LangOptions &L) {
John McCall5fb5df92012-06-20 06:18:46 +0000197 switch (L.ObjCRuntime.getKind()) {
198 case ObjCRuntime::FragileMacOSX:
Reid Klecknere070b992014-11-14 02:01:10 +0000199 return getCPersonality(T, L);
John McCall5fb5df92012-06-20 06:18:46 +0000200 case ObjCRuntime::MacOSX:
201 case ObjCRuntime::iOS:
202 return EHPersonality::NeXT_ObjC;
David Chisnallb601c962012-07-03 20:49:52 +0000203 case ObjCRuntime::GNUstep:
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000204 if (L.ObjCRuntime.getVersion() >= VersionTuple(1, 7))
205 return EHPersonality::GNUstep_ObjC;
206 // fallthrough
David Chisnallb601c962012-07-03 20:49:52 +0000207 case ObjCRuntime::GCC:
John McCall775086e2012-07-12 02:07:58 +0000208 case ObjCRuntime::ObjFW:
John McCall36ea3722010-07-17 00:43:08 +0000209 return EHPersonality::GNU_ObjC;
John McCallbd309292010-07-06 01:34:17 +0000210 }
John McCall5fb5df92012-06-20 06:18:46 +0000211 llvm_unreachable("bad runtime kind");
John McCallbd309292010-07-06 01:34:17 +0000212}
213
Reid Klecknere070b992014-11-14 02:01:10 +0000214static const EHPersonality &getCXXPersonality(const llvm::Triple &T,
215 const LangOptions &L) {
John McCall36ea3722010-07-17 00:43:08 +0000216 if (L.SjLjExceptions)
217 return EHPersonality::GNU_CPlusPlus_SJLJ;
Reid Klecknere070b992014-11-14 02:01:10 +0000218 else if (useLibGCCSEHPersonality(T))
Reid Kleckner8f45c9c2014-09-15 17:19:16 +0000219 return EHPersonality::GNU_CPlusPlus_SEH;
Reid Klecknere070b992014-11-14 02:01:10 +0000220 return EHPersonality::GNU_CPlusPlus;
John McCallbd309292010-07-06 01:34:17 +0000221}
222
223/// Determines the personality function to use when both C++
224/// and Objective-C exceptions are being caught.
Reid Klecknere070b992014-11-14 02:01:10 +0000225static const EHPersonality &getObjCXXPersonality(const llvm::Triple &T,
226 const LangOptions &L) {
John McCall5fb5df92012-06-20 06:18:46 +0000227 switch (L.ObjCRuntime.getKind()) {
John McCallbd309292010-07-06 01:34:17 +0000228 // The ObjC personality defers to the C++ personality for non-ObjC
229 // handlers. Unlike the C++ case, we use the same personality
230 // function on targets using (backend-driven) SJLJ EH.
John McCall5fb5df92012-06-20 06:18:46 +0000231 case ObjCRuntime::MacOSX:
232 case ObjCRuntime::iOS:
233 return EHPersonality::NeXT_ObjC;
John McCallbd309292010-07-06 01:34:17 +0000234
John McCall5fb5df92012-06-20 06:18:46 +0000235 // In the fragile ABI, just use C++ exception handling and hope
236 // they're not doing crazy exception mixing.
237 case ObjCRuntime::FragileMacOSX:
Reid Klecknere070b992014-11-14 02:01:10 +0000238 return getCXXPersonality(T, L);
David Chisnallf9c42252010-05-17 13:49:20 +0000239
David Chisnallb601c962012-07-03 20:49:52 +0000240 // The GCC runtime's personality function inherently doesn't support
John McCall36ea3722010-07-17 00:43:08 +0000241 // mixed EH. Use the C++ personality just to avoid returning null.
David Chisnallb601c962012-07-03 20:49:52 +0000242 case ObjCRuntime::GCC:
John McCall775086e2012-07-12 02:07:58 +0000243 case ObjCRuntime::ObjFW: // XXX: this will change soon
David Chisnallb601c962012-07-03 20:49:52 +0000244 return EHPersonality::GNU_ObjC;
245 case ObjCRuntime::GNUstep:
John McCall5fb5df92012-06-20 06:18:46 +0000246 return EHPersonality::GNU_ObjCXX;
247 }
248 llvm_unreachable("bad runtime kind");
John McCallbd309292010-07-06 01:34:17 +0000249}
250
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000251static const EHPersonality &getSEHPersonalityMSVC(const llvm::Triple &T) {
Reid Kleckner1d59f992015-01-22 01:36:17 +0000252 if (T.getArch() == llvm::Triple::x86)
253 return EHPersonality::MSVC_except_handler;
254 return EHPersonality::MSVC_C_specific_handler;
255}
256
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000257const EHPersonality &EHPersonality::get(CodeGenModule &CGM,
258 const FunctionDecl *FD) {
Reid Klecknere070b992014-11-14 02:01:10 +0000259 const llvm::Triple &T = CGM.getTarget().getTriple();
260 const LangOptions &L = CGM.getLangOpts();
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000261
Reid Kleckner1d59f992015-01-22 01:36:17 +0000262 // Try to pick a personality function that is compatible with MSVC if we're
263 // not compiling Obj-C. Obj-C users better have an Obj-C runtime that supports
264 // the GCC-style personality function.
265 if (T.isWindowsMSVCEnvironment() && !L.ObjC1) {
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000266 if (L.SjLjExceptions)
267 return EHPersonality::GNU_CPlusPlus_SJLJ;
268 else if (FD && FD->usesSEHTry())
269 return getSEHPersonalityMSVC(T);
Reid Kleckner1d59f992015-01-22 01:36:17 +0000270 else
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000271 return EHPersonality::MSVC_CxxFrameHandler3;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000272 }
273
John McCall36ea3722010-07-17 00:43:08 +0000274 if (L.CPlusPlus && L.ObjC1)
Reid Klecknere070b992014-11-14 02:01:10 +0000275 return getObjCXXPersonality(T, L);
John McCall36ea3722010-07-17 00:43:08 +0000276 else if (L.CPlusPlus)
Reid Klecknere070b992014-11-14 02:01:10 +0000277 return getCXXPersonality(T, L);
John McCall36ea3722010-07-17 00:43:08 +0000278 else if (L.ObjC1)
Reid Klecknere070b992014-11-14 02:01:10 +0000279 return getObjCPersonality(T, L);
John McCallbd309292010-07-06 01:34:17 +0000280 else
Reid Klecknere070b992014-11-14 02:01:10 +0000281 return getCPersonality(T, L);
John McCall36ea3722010-07-17 00:43:08 +0000282}
John McCallbd309292010-07-06 01:34:17 +0000283
John McCall0bdb1fd2010-09-16 06:16:50 +0000284static llvm::Constant *getPersonalityFn(CodeGenModule &CGM,
John McCall36ea3722010-07-17 00:43:08 +0000285 const EHPersonality &Personality) {
John McCall36ea3722010-07-17 00:43:08 +0000286 llvm::Constant *Fn =
Chris Lattnerece04092012-02-07 00:39:47 +0000287 CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.Int32Ty, true),
Benjamin Kramer793bd552012-02-08 12:41:24 +0000288 Personality.PersonalityFn);
John McCall0bdb1fd2010-09-16 06:16:50 +0000289 return Fn;
290}
291
292static llvm::Constant *getOpaquePersonalityFn(CodeGenModule &CGM,
293 const EHPersonality &Personality) {
294 llvm::Constant *Fn = getPersonalityFn(CGM, Personality);
John McCallad7c5c12011-02-08 08:22:06 +0000295 return llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
John McCall0bdb1fd2010-09-16 06:16:50 +0000296}
297
298/// Check whether a personality function could reasonably be swapped
299/// for a C++ personality function.
300static bool PersonalityHasOnlyCXXUses(llvm::Constant *Fn) {
Chandler Carruth4d01fff2014-03-09 03:16:50 +0000301 for (llvm::User *U : Fn->users()) {
John McCall0bdb1fd2010-09-16 06:16:50 +0000302 // Conditionally white-list bitcasts.
Chandler Carruth4d01fff2014-03-09 03:16:50 +0000303 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(U)) {
John McCall0bdb1fd2010-09-16 06:16:50 +0000304 if (CE->getOpcode() != llvm::Instruction::BitCast) return false;
305 if (!PersonalityHasOnlyCXXUses(CE))
306 return false;
307 continue;
308 }
309
Bill Wendling58e58fe2011-09-19 22:08:36 +0000310 // Otherwise, it has to be a landingpad instruction.
Chandler Carruth4d01fff2014-03-09 03:16:50 +0000311 llvm::LandingPadInst *LPI = dyn_cast<llvm::LandingPadInst>(U);
Bill Wendling58e58fe2011-09-19 22:08:36 +0000312 if (!LPI) return false;
John McCall0bdb1fd2010-09-16 06:16:50 +0000313
Bill Wendling58e58fe2011-09-19 22:08:36 +0000314 for (unsigned I = 0, E = LPI->getNumClauses(); I != E; ++I) {
John McCall0bdb1fd2010-09-16 06:16:50 +0000315 // Look for something that would've been returned by the ObjC
316 // runtime's GetEHType() method.
Bill Wendling58e58fe2011-09-19 22:08:36 +0000317 llvm::Value *Val = LPI->getClause(I)->stripPointerCasts();
318 if (LPI->isCatch(I)) {
319 // Check if the catch value has the ObjC prefix.
Bill Wendling5d7469e2011-09-20 00:40:19 +0000320 if (llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Val))
321 // ObjC EH selector entries are always global variables with
322 // names starting like this.
323 if (GV->getName().startswith("OBJC_EHTYPE"))
324 return false;
Bill Wendling58e58fe2011-09-19 22:08:36 +0000325 } else {
326 // Check if any of the filter values have the ObjC prefix.
327 llvm::Constant *CVal = cast<llvm::Constant>(Val);
328 for (llvm::User::op_iterator
329 II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II) {
Bill Wendling5d7469e2011-09-20 00:40:19 +0000330 if (llvm::GlobalVariable *GV =
331 cast<llvm::GlobalVariable>((*II)->stripPointerCasts()))
332 // ObjC EH selector entries are always global variables with
333 // names starting like this.
334 if (GV->getName().startswith("OBJC_EHTYPE"))
335 return false;
Bill Wendling58e58fe2011-09-19 22:08:36 +0000336 }
337 }
John McCall0bdb1fd2010-09-16 06:16:50 +0000338 }
339 }
340
341 return true;
342}
343
344/// Try to use the C++ personality function in ObjC++. Not doing this
345/// can cause some incompatibilities with gcc, which is more
346/// aggressive about only using the ObjC++ personality in a function
347/// when it really needs it.
348void CodeGenModule::SimplifyPersonality() {
John McCall0bdb1fd2010-09-16 06:16:50 +0000349 // If we're not in ObjC++ -fexceptions, there's nothing to do.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000350 if (!LangOpts.CPlusPlus || !LangOpts.ObjC1 || !LangOpts.Exceptions)
John McCall0bdb1fd2010-09-16 06:16:50 +0000351 return;
352
John McCall3c223932012-11-14 17:48:31 +0000353 // Both the problem this endeavors to fix and the way the logic
354 // above works is specific to the NeXT runtime.
355 if (!LangOpts.ObjCRuntime.isNeXTFamily())
356 return;
357
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000358 const EHPersonality &ObjCXX = EHPersonality::get(*this, /*FD=*/nullptr);
Reid Klecknere070b992014-11-14 02:01:10 +0000359 const EHPersonality &CXX =
360 getCXXPersonality(getTarget().getTriple(), LangOpts);
Benjamin Kramer793bd552012-02-08 12:41:24 +0000361 if (&ObjCXX == &CXX)
John McCall0bdb1fd2010-09-16 06:16:50 +0000362 return;
363
Benjamin Kramer793bd552012-02-08 12:41:24 +0000364 assert(std::strcmp(ObjCXX.PersonalityFn, CXX.PersonalityFn) != 0 &&
365 "Different EHPersonalities using the same personality function.");
366
367 llvm::Function *Fn = getModule().getFunction(ObjCXX.PersonalityFn);
John McCall0bdb1fd2010-09-16 06:16:50 +0000368
369 // Nothing to do if it's unused.
370 if (!Fn || Fn->use_empty()) return;
371
372 // Can't do the optimization if it has non-C++ uses.
373 if (!PersonalityHasOnlyCXXUses(Fn)) return;
374
375 // Create the C++ personality function and kill off the old
376 // function.
377 llvm::Constant *CXXFn = getPersonalityFn(*this, CXX);
378
379 // This can happen if the user is screwing with us.
380 if (Fn->getType() != CXXFn->getType()) return;
381
382 Fn->replaceAllUsesWith(CXXFn);
383 Fn->eraseFromParent();
John McCallbd309292010-07-06 01:34:17 +0000384}
385
386/// Returns the value to inject into a selector to indicate the
387/// presence of a catch-all.
388static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
389 // Possibly we should use @llvm.eh.catch.all.value here.
John McCallad7c5c12011-02-08 08:22:06 +0000390 return llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
John McCallbd309292010-07-06 01:34:17 +0000391}
392
John McCallbb026012010-07-13 21:17:51 +0000393namespace {
394 /// A cleanup to free the exception object if its initialization
395 /// throws.
John McCall5fcf8da2011-07-12 00:15:30 +0000396 struct FreeException : EHScopeStack::Cleanup {
397 llvm::Value *exn;
398 FreeException(llvm::Value *exn) : exn(exn) {}
Craig Topper4f12f102014-03-12 06:41:41 +0000399 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +0000400 CGF.EmitNounwindRuntimeCall(getFreeExceptionFn(CGF.CGM), exn);
John McCallbb026012010-07-13 21:17:51 +0000401 }
402 };
403}
404
John McCall2e6567a2010-04-22 01:10:34 +0000405// Emits an exception expression into the given location. This
406// differs from EmitAnyExprToMem only in that, if a final copy-ctor
407// call is required, an exception within that copy ctor causes
408// std::terminate to be invoked.
John McCalle4df6c82011-01-28 08:37:24 +0000409static void EmitAnyExprToExn(CodeGenFunction &CGF, const Expr *e,
410 llvm::Value *addr) {
John McCallbd309292010-07-06 01:34:17 +0000411 // Make sure the exception object is cleaned up if there's an
412 // exception during initialization.
John McCalle4df6c82011-01-28 08:37:24 +0000413 CGF.pushFullExprCleanup<FreeException>(EHCleanup, addr);
414 EHScopeStack::stable_iterator cleanup = CGF.EHStack.stable_begin();
John McCall2e6567a2010-04-22 01:10:34 +0000415
416 // __cxa_allocate_exception returns a void*; we need to cast this
417 // to the appropriate type for the object.
Chris Lattner2192fe52011-07-18 04:24:23 +0000418 llvm::Type *ty = CGF.ConvertTypeForMem(e->getType())->getPointerTo();
John McCalle4df6c82011-01-28 08:37:24 +0000419 llvm::Value *typedAddr = CGF.Builder.CreateBitCast(addr, ty);
John McCall2e6567a2010-04-22 01:10:34 +0000420
421 // FIXME: this isn't quite right! If there's a final unelided call
422 // to a copy constructor, then according to [except.terminate]p1 we
423 // must call std::terminate() if that constructor throws, because
424 // technically that copy occurs after the exception expression is
425 // evaluated but before the exception is caught. But the best way
426 // to handle that is to teach EmitAggExpr to do the final copy
427 // differently if it can't be elided.
Chad Rosier615ed1a2012-03-29 17:37:10 +0000428 CGF.EmitAnyExprToMem(e, typedAddr, e->getType().getQualifiers(),
429 /*IsInit*/ true);
John McCall2e6567a2010-04-22 01:10:34 +0000430
John McCalle4df6c82011-01-28 08:37:24 +0000431 // Deactivate the cleanup block.
John McCallf4beacd2011-11-10 10:43:54 +0000432 CGF.DeactivateCleanupBlock(cleanup, cast<llvm::Instruction>(typedAddr));
Mike Stump54066142009-12-01 03:41:18 +0000433}
434
John McCallbd309292010-07-06 01:34:17 +0000435llvm::Value *CodeGenFunction::getExceptionSlot() {
John McCall9b382dd2011-05-28 21:13:02 +0000436 if (!ExceptionSlot)
437 ExceptionSlot = CreateTempAlloca(Int8PtrTy, "exn.slot");
John McCallbd309292010-07-06 01:34:17 +0000438 return ExceptionSlot;
Mike Stump54066142009-12-01 03:41:18 +0000439}
440
John McCall9b382dd2011-05-28 21:13:02 +0000441llvm::Value *CodeGenFunction::getEHSelectorSlot() {
442 if (!EHSelectorSlot)
443 EHSelectorSlot = CreateTempAlloca(Int32Ty, "ehselector.slot");
444 return EHSelectorSlot;
445}
446
Bill Wendling79a70e42011-09-15 18:57:19 +0000447llvm::Value *CodeGenFunction::getExceptionFromSlot() {
448 return Builder.CreateLoad(getExceptionSlot(), "exn");
449}
450
451llvm::Value *CodeGenFunction::getSelectorFromSlot() {
452 return Builder.CreateLoad(getEHSelectorSlot(), "sel");
453}
454
Reid Kleckneraca01db2015-02-04 22:37:07 +0000455llvm::Value *CodeGenFunction::getAbnormalTerminationSlot() {
456 if (!AbnormalTerminationSlot)
Nico Weber1bebad12015-02-11 22:33:32 +0000457 AbnormalTerminationSlot =
458 CreateTempAlloca(Int8Ty, "abnormal.termination.slot");
Reid Kleckneraca01db2015-02-04 22:37:07 +0000459 return AbnormalTerminationSlot;
460}
461
Richard Smithea852322013-05-07 21:53:22 +0000462void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E,
463 bool KeepInsertionPoint) {
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000464 if (!E->getSubExpr()) {
David Majnemer442d0a22014-11-25 07:20:20 +0000465 CGM.getCXXABI().emitRethrow(*this, /*isNoReturn*/true);
Douglas Gregorc278d1b2010-05-16 00:44:00 +0000466
John McCall20f6ab82011-01-12 03:41:02 +0000467 // throw is an expression, and the expression emitters expect us
468 // to leave ourselves at a valid insertion point.
Richard Smithea852322013-05-07 21:53:22 +0000469 if (KeepInsertionPoint)
470 EmitBlock(createBasicBlock("throw.cont"));
John McCall20f6ab82011-01-12 03:41:02 +0000471
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000472 return;
473 }
Mike Stump75546b82009-12-10 00:06:18 +0000474
David Majnemer442d0a22014-11-25 07:20:20 +0000475 if (CGM.getTarget().getTriple().isKnownWindowsMSVCEnvironment()) {
476 ErrorUnsupported(E, "throw expression");
477 return;
478 }
479
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000480 QualType ThrowType = E->getSubExpr()->getType();
Mike Stump75546b82009-12-10 00:06:18 +0000481
Fariborz Jahanian1eab0522013-01-10 19:02:56 +0000482 if (ThrowType->isObjCObjectPointerType()) {
483 const Stmt *ThrowStmt = E->getSubExpr();
484 const ObjCAtThrowStmt S(E->getExprLoc(),
485 const_cast<Stmt *>(ThrowStmt));
486 CGM.getObjCRuntime().EmitThrowStmt(*this, S, false);
487 // This will clear insertion point which was not cleared in
488 // call to EmitThrowStmt.
Richard Smithea852322013-05-07 21:53:22 +0000489 if (KeepInsertionPoint)
490 EmitBlock(createBasicBlock("throw.cont"));
Fariborz Jahanian1eab0522013-01-10 19:02:56 +0000491 return;
492 }
493
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000494 // Now allocate the exception object.
Chris Lattner2192fe52011-07-18 04:24:23 +0000495 llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
John McCall21886962010-04-21 10:05:39 +0000496 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
Mike Stump75546b82009-12-10 00:06:18 +0000497
John McCall2c33ba82013-02-12 03:51:38 +0000498 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(CGM);
John McCallbd309292010-07-06 01:34:17 +0000499 llvm::CallInst *ExceptionPtr =
John McCall882987f2013-02-28 19:01:20 +0000500 EmitNounwindRuntimeCall(AllocExceptionFn,
501 llvm::ConstantInt::get(SizeTy, TypeSize),
502 "exception");
Anders Carlssonafd1edb2009-12-11 00:32:37 +0000503
John McCall2e6567a2010-04-22 01:10:34 +0000504 EmitAnyExprToExn(*this, E->getSubExpr(), ExceptionPtr);
Mike Stump75546b82009-12-10 00:06:18 +0000505
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000506 // Now throw the exception.
Anders Carlssonba840fb2011-01-24 01:59:49 +0000507 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
508 /*ForEH=*/true);
John McCall2e6567a2010-04-22 01:10:34 +0000509
510 // The address of the destructor. If the exception type has a
511 // trivial destructor (or isn't a record), we just pass null.
Craig Topper8a13c412014-05-21 05:09:00 +0000512 llvm::Constant *Dtor = nullptr;
John McCall2e6567a2010-04-22 01:10:34 +0000513 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
514 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
515 if (!Record->hasTrivialDestructor()) {
Douglas Gregorbac74902010-07-01 14:13:13 +0000516 CXXDestructorDecl *DtorD = Record->getDestructor();
Rafael Espindola1ac0ec82014-09-11 15:42:06 +0000517 Dtor = CGM.getAddrOfCXXStructor(DtorD, StructorType::Complete);
John McCall2e6567a2010-04-22 01:10:34 +0000518 Dtor = llvm::ConstantExpr::getBitCast(Dtor, Int8PtrTy);
519 }
520 }
521 if (!Dtor) Dtor = llvm::Constant::getNullValue(Int8PtrTy);
Mike Stump75546b82009-12-10 00:06:18 +0000522
John McCall882987f2013-02-28 19:01:20 +0000523 llvm::Value *args[] = { ExceptionPtr, TypeInfo, Dtor };
524 EmitNoreturnRuntimeCallOrInvoke(getThrowFn(CGM), args);
Mike Stump75546b82009-12-10 00:06:18 +0000525
John McCall20f6ab82011-01-12 03:41:02 +0000526 // throw is an expression, and the expression emitters expect us
527 // to leave ourselves at a valid insertion point.
Richard Smithea852322013-05-07 21:53:22 +0000528 if (KeepInsertionPoint)
529 EmitBlock(createBasicBlock("throw.cont"));
Anders Carlsson4b08db72009-10-30 01:42:31 +0000530}
Mike Stump58ef18b2009-11-20 23:44:51 +0000531
Mike Stump1d849212009-12-07 23:38:24 +0000532void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000533 if (!CGM.getLangOpts().CXXExceptions)
Anders Carlsson9878f9f2010-02-06 23:59:05 +0000534 return;
535
Mike Stump1d849212009-12-07 23:38:24 +0000536 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
Craig Topper8a13c412014-05-21 05:09:00 +0000537 if (!FD) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000538 // Check if CapturedDecl is nothrow and create terminate scope for it.
539 if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
540 if (CD->isNothrow())
541 EHStack.pushTerminate();
542 }
Mike Stump1d849212009-12-07 23:38:24 +0000543 return;
Alexey Bataev9959db52014-05-06 10:08:46 +0000544 }
Mike Stump1d849212009-12-07 23:38:24 +0000545 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
Craig Topper8a13c412014-05-21 05:09:00 +0000546 if (!Proto)
Mike Stump1d849212009-12-07 23:38:24 +0000547 return;
548
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000549 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
550 if (isNoexceptExceptionSpec(EST)) {
551 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
552 // noexcept functions are simple terminate scopes.
553 EHStack.pushTerminate();
554 }
555 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
556 unsigned NumExceptions = Proto->getNumExceptions();
557 EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
Mike Stump1d849212009-12-07 23:38:24 +0000558
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000559 for (unsigned I = 0; I != NumExceptions; ++I) {
560 QualType Ty = Proto->getExceptionType(I);
561 QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
562 llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType,
563 /*ForEH=*/true);
564 Filter->setFilter(I, EHType);
565 }
Mike Stump1d849212009-12-07 23:38:24 +0000566 }
Mike Stump1d849212009-12-07 23:38:24 +0000567}
568
John McCall8e4c74b2011-08-11 02:22:43 +0000569/// Emit the dispatch block for a filter scope if necessary.
570static void emitFilterDispatchBlock(CodeGenFunction &CGF,
571 EHFilterScope &filterScope) {
572 llvm::BasicBlock *dispatchBlock = filterScope.getCachedEHDispatchBlock();
573 if (!dispatchBlock) return;
574 if (dispatchBlock->use_empty()) {
575 delete dispatchBlock;
576 return;
577 }
578
John McCall8e4c74b2011-08-11 02:22:43 +0000579 CGF.EmitBlockAfterUses(dispatchBlock);
580
581 // If this isn't a catch-all filter, we need to check whether we got
582 // here because the filter triggered.
583 if (filterScope.getNumFilters()) {
584 // Load the selector value.
Bill Wendling79a70e42011-09-15 18:57:19 +0000585 llvm::Value *selector = CGF.getSelectorFromSlot();
John McCall8e4c74b2011-08-11 02:22:43 +0000586 llvm::BasicBlock *unexpectedBB = CGF.createBasicBlock("ehspec.unexpected");
587
588 llvm::Value *zero = CGF.Builder.getInt32(0);
589 llvm::Value *failsFilter =
Nico Weber1bebad12015-02-11 22:33:32 +0000590 CGF.Builder.CreateICmpSLT(selector, zero, "ehspec.fails");
591 CGF.Builder.CreateCondBr(failsFilter, unexpectedBB,
592 CGF.getEHResumeBlock(false));
John McCall8e4c74b2011-08-11 02:22:43 +0000593
594 CGF.EmitBlock(unexpectedBB);
595 }
596
597 // Call __cxa_call_unexpected. This doesn't need to be an invoke
598 // because __cxa_call_unexpected magically filters exceptions
599 // according to the last landing pad the exception was thrown
600 // into. Seriously.
Bill Wendling79a70e42011-09-15 18:57:19 +0000601 llvm::Value *exn = CGF.getExceptionFromSlot();
John McCall882987f2013-02-28 19:01:20 +0000602 CGF.EmitRuntimeCall(getUnexpectedFn(CGF.CGM), exn)
John McCall8e4c74b2011-08-11 02:22:43 +0000603 ->setDoesNotReturn();
604 CGF.Builder.CreateUnreachable();
605}
606
Mike Stump1d849212009-12-07 23:38:24 +0000607void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000608 if (!CGM.getLangOpts().CXXExceptions)
Anders Carlsson9878f9f2010-02-06 23:59:05 +0000609 return;
610
Mike Stump1d849212009-12-07 23:38:24 +0000611 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
Craig Topper8a13c412014-05-21 05:09:00 +0000612 if (!FD) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000613 // Check if CapturedDecl is nothrow and pop terminate scope for it.
614 if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
615 if (CD->isNothrow())
616 EHStack.popTerminate();
617 }
Mike Stump1d849212009-12-07 23:38:24 +0000618 return;
Alexey Bataev9959db52014-05-06 10:08:46 +0000619 }
Mike Stump1d849212009-12-07 23:38:24 +0000620 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
Craig Topper8a13c412014-05-21 05:09:00 +0000621 if (!Proto)
Mike Stump1d849212009-12-07 23:38:24 +0000622 return;
623
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000624 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
625 if (isNoexceptExceptionSpec(EST)) {
626 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
627 EHStack.popTerminate();
628 }
629 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
John McCall8e4c74b2011-08-11 02:22:43 +0000630 EHFilterScope &filterScope = cast<EHFilterScope>(*EHStack.begin());
631 emitFilterDispatchBlock(*this, filterScope);
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000632 EHStack.popFilter();
633 }
Mike Stump1d849212009-12-07 23:38:24 +0000634}
635
Mike Stump58ef18b2009-11-20 23:44:51 +0000636void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
Saleem Abdulrasoolb7698742014-11-17 22:11:07 +0000637 if (CGM.getTarget().getTriple().isKnownWindowsMSVCEnvironment()) {
Reid Klecknera82b5d82014-05-05 21:12:12 +0000638 ErrorUnsupported(&S, "try statement");
639 return;
640 }
641
John McCallb609d3f2010-07-07 06:56:46 +0000642 EnterCXXTryStmt(S);
John McCallb81884d2010-02-19 09:25:03 +0000643 EmitStmt(S.getTryBlock());
John McCallb609d3f2010-07-07 06:56:46 +0000644 ExitCXXTryStmt(S);
John McCallb81884d2010-02-19 09:25:03 +0000645}
646
John McCallb609d3f2010-07-07 06:56:46 +0000647void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallbd309292010-07-06 01:34:17 +0000648 unsigned NumHandlers = S.getNumHandlers();
649 EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
John McCallb81884d2010-02-19 09:25:03 +0000650
John McCallbd309292010-07-06 01:34:17 +0000651 for (unsigned I = 0; I != NumHandlers; ++I) {
652 const CXXCatchStmt *C = S.getHandler(I);
John McCallb81884d2010-02-19 09:25:03 +0000653
John McCallbd309292010-07-06 01:34:17 +0000654 llvm::BasicBlock *Handler = createBasicBlock("catch");
655 if (C->getExceptionDecl()) {
656 // FIXME: Dropping the reference type on the type into makes it
657 // impossible to correctly implement catch-by-reference
658 // semantics for pointers. Unfortunately, this is what all
659 // existing compilers do, and it's not clear that the standard
660 // personality routine is capable of doing this right. See C++ DR 388:
661 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
David Majnemer571162a2014-10-12 06:58:22 +0000662 Qualifiers CaughtTypeQuals;
663 QualType CaughtType = CGM.getContext().getUnqualifiedArrayType(
664 C->getCaughtType().getNonReferenceType(), CaughtTypeQuals);
John McCall2ca705e2010-07-24 00:37:23 +0000665
Rafael Espindolabb9e7a32014-06-04 18:51:46 +0000666 llvm::Constant *TypeInfo = nullptr;
John McCall2ca705e2010-07-24 00:37:23 +0000667 if (CaughtType->isObjCObjectPointerType())
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +0000668 TypeInfo = CGM.getObjCRuntime().GetEHType(CaughtType);
John McCall2ca705e2010-07-24 00:37:23 +0000669 else
Anders Carlssonba840fb2011-01-24 01:59:49 +0000670 TypeInfo = CGM.GetAddrOfRTTIDescriptor(CaughtType, /*ForEH=*/true);
John McCallbd309292010-07-06 01:34:17 +0000671 CatchScope->setHandler(I, TypeInfo, Handler);
672 } else {
673 // No exception decl indicates '...', a catch-all.
674 CatchScope->setCatchAllHandler(I, Handler);
675 }
676 }
John McCallbd309292010-07-06 01:34:17 +0000677}
678
John McCall8e4c74b2011-08-11 02:22:43 +0000679llvm::BasicBlock *
680CodeGenFunction::getEHDispatchBlock(EHScopeStack::stable_iterator si) {
681 // The dispatch block for the end of the scope chain is a block that
682 // just resumes unwinding.
683 if (si == EHStack.stable_end())
David Chisnall9a837be2012-11-07 16:50:40 +0000684 return getEHResumeBlock(true);
John McCall8e4c74b2011-08-11 02:22:43 +0000685
686 // Otherwise, we should look at the actual scope.
687 EHScope &scope = *EHStack.find(si);
688
689 llvm::BasicBlock *dispatchBlock = scope.getCachedEHDispatchBlock();
690 if (!dispatchBlock) {
691 switch (scope.getKind()) {
692 case EHScope::Catch: {
693 // Apply a special case to a single catch-all.
694 EHCatchScope &catchScope = cast<EHCatchScope>(scope);
695 if (catchScope.getNumHandlers() == 1 &&
696 catchScope.getHandler(0).isCatchAll()) {
697 dispatchBlock = catchScope.getHandler(0).Block;
698
699 // Otherwise, make a dispatch block.
700 } else {
701 dispatchBlock = createBasicBlock("catch.dispatch");
702 }
703 break;
704 }
705
706 case EHScope::Cleanup:
707 dispatchBlock = createBasicBlock("ehcleanup");
708 break;
709
710 case EHScope::Filter:
711 dispatchBlock = createBasicBlock("filter.dispatch");
712 break;
713
714 case EHScope::Terminate:
715 dispatchBlock = getTerminateHandler();
716 break;
717 }
718 scope.setCachedEHDispatchBlock(dispatchBlock);
719 }
720 return dispatchBlock;
721}
722
John McCallbd309292010-07-06 01:34:17 +0000723/// Check whether this is a non-EH scope, i.e. a scope which doesn't
724/// affect exception handling. Currently, the only non-EH scopes are
725/// normal-only cleanup scopes.
726static bool isNonEHScope(const EHScope &S) {
John McCall2b7fc382010-07-13 20:32:21 +0000727 switch (S.getKind()) {
John McCallcda666c2010-07-21 07:22:38 +0000728 case EHScope::Cleanup:
729 return !cast<EHCleanupScope>(S).isEHCleanup();
John McCall2b7fc382010-07-13 20:32:21 +0000730 case EHScope::Filter:
731 case EHScope::Catch:
732 case EHScope::Terminate:
733 return false;
734 }
735
David Blaikiee4d798f2012-01-20 21:50:17 +0000736 llvm_unreachable("Invalid EHScope Kind!");
John McCallbd309292010-07-06 01:34:17 +0000737}
738
739llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
740 assert(EHStack.requiresLandingPad());
741 assert(!EHStack.empty());
742
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000743 // If exceptions are disabled, there are usually no landingpads. However, when
744 // SEH is enabled, functions using SEH still get landingpads.
745 const LangOptions &LO = CGM.getLangOpts();
746 if (!LO.Exceptions) {
747 if (!LO.Borland && !LO.MicrosoftExt)
748 return nullptr;
Reid Klecknere7b3f7c2015-02-11 00:00:21 +0000749 if (!currentFunctionUsesSEHTry())
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000750 return nullptr;
751 }
John McCall2b7fc382010-07-13 20:32:21 +0000752
John McCallbd309292010-07-06 01:34:17 +0000753 // Check the innermost scope for a cached landing pad. If this is
754 // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
755 llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
756 if (LP) return LP;
757
758 // Build the landing pad for this scope.
759 LP = EmitLandingPad();
760 assert(LP);
761
762 // Cache the landing pad on the innermost scope. If this is a
763 // non-EH scope, cache the landing pad on the enclosing scope, too.
764 for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
765 ir->setCachedLandingPad(LP);
766 if (!isNonEHScope(*ir)) break;
767 }
768
769 return LP;
770}
771
772llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
773 assert(EHStack.requiresLandingPad());
774
John McCall8e4c74b2011-08-11 02:22:43 +0000775 EHScope &innermostEHScope = *EHStack.find(EHStack.getInnermostEHScope());
776 switch (innermostEHScope.getKind()) {
777 case EHScope::Terminate:
778 return getTerminateLandingPad();
John McCallbd309292010-07-06 01:34:17 +0000779
John McCall8e4c74b2011-08-11 02:22:43 +0000780 case EHScope::Catch:
781 case EHScope::Cleanup:
782 case EHScope::Filter:
783 if (llvm::BasicBlock *lpad = innermostEHScope.getCachedLandingPad())
784 return lpad;
John McCallbd309292010-07-06 01:34:17 +0000785 }
786
787 // Save the current IR generation state.
John McCall8e4c74b2011-08-11 02:22:43 +0000788 CGBuilderTy::InsertPoint savedIP = Builder.saveAndClearIP();
Adrian Prantl95b24e92015-02-03 20:00:54 +0000789 auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, CurEHLocation);
John McCallbd309292010-07-06 01:34:17 +0000790
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000791 const EHPersonality &personality = EHPersonality::get(*this);
John McCall36ea3722010-07-17 00:43:08 +0000792
John McCallbd309292010-07-06 01:34:17 +0000793 // Create and configure the landing pad.
John McCall8e4c74b2011-08-11 02:22:43 +0000794 llvm::BasicBlock *lpad = createBasicBlock("lpad");
795 EmitBlock(lpad);
John McCallbd309292010-07-06 01:34:17 +0000796
Bill Wendlingf0724e82011-09-19 20:31:14 +0000797 llvm::LandingPadInst *LPadInst =
Reid Kleckneree7cf842014-12-01 22:02:27 +0000798 Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, nullptr),
Bill Wendlingf0724e82011-09-19 20:31:14 +0000799 getOpaquePersonalityFn(CGM, personality), 0);
800
801 llvm::Value *LPadExn = Builder.CreateExtractValue(LPadInst, 0);
802 Builder.CreateStore(LPadExn, getExceptionSlot());
803 llvm::Value *LPadSel = Builder.CreateExtractValue(LPadInst, 1);
804 Builder.CreateStore(LPadSel, getEHSelectorSlot());
805
John McCallbd309292010-07-06 01:34:17 +0000806 // Save the exception pointer. It's safe to use a single exception
807 // pointer per function because EH cleanups can never have nested
808 // try/catches.
Bill Wendlingf0724e82011-09-19 20:31:14 +0000809 // Build the landingpad instruction.
John McCallbd309292010-07-06 01:34:17 +0000810
811 // Accumulate all the handlers in scope.
John McCall8e4c74b2011-08-11 02:22:43 +0000812 bool hasCatchAll = false;
813 bool hasCleanup = false;
814 bool hasFilter = false;
815 SmallVector<llvm::Value*, 4> filterTypes;
816 llvm::SmallPtrSet<llvm::Value*, 4> catchTypes;
John McCallbd309292010-07-06 01:34:17 +0000817 for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end();
818 I != E; ++I) {
819
820 switch (I->getKind()) {
John McCallcda666c2010-07-21 07:22:38 +0000821 case EHScope::Cleanup:
John McCall8e4c74b2011-08-11 02:22:43 +0000822 // If we have a cleanup, remember that.
823 hasCleanup = (hasCleanup || cast<EHCleanupScope>(*I).isEHCleanup());
John McCall2b7fc382010-07-13 20:32:21 +0000824 continue;
825
John McCallbd309292010-07-06 01:34:17 +0000826 case EHScope::Filter: {
827 assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
John McCall8e4c74b2011-08-11 02:22:43 +0000828 assert(!hasCatchAll && "EH filter reached after catch-all");
John McCallbd309292010-07-06 01:34:17 +0000829
Bill Wendlingf0724e82011-09-19 20:31:14 +0000830 // Filter scopes get added to the landingpad in weird ways.
John McCall8e4c74b2011-08-11 02:22:43 +0000831 EHFilterScope &filter = cast<EHFilterScope>(*I);
832 hasFilter = true;
John McCallbd309292010-07-06 01:34:17 +0000833
Bill Wendling8c4b7162011-09-22 20:32:54 +0000834 // Add all the filter values.
835 for (unsigned i = 0, e = filter.getNumFilters(); i != e; ++i)
836 filterTypes.push_back(filter.getFilter(i));
John McCallbd309292010-07-06 01:34:17 +0000837 goto done;
838 }
839
840 case EHScope::Terminate:
841 // Terminate scopes are basically catch-alls.
John McCall8e4c74b2011-08-11 02:22:43 +0000842 assert(!hasCatchAll);
843 hasCatchAll = true;
John McCallbd309292010-07-06 01:34:17 +0000844 goto done;
845
846 case EHScope::Catch:
847 break;
848 }
849
John McCall8e4c74b2011-08-11 02:22:43 +0000850 EHCatchScope &catchScope = cast<EHCatchScope>(*I);
851 for (unsigned hi = 0, he = catchScope.getNumHandlers(); hi != he; ++hi) {
852 EHCatchScope::Handler handler = catchScope.getHandler(hi);
John McCallbd309292010-07-06 01:34:17 +0000853
John McCall8e4c74b2011-08-11 02:22:43 +0000854 // If this is a catch-all, register that and abort.
855 if (!handler.Type) {
856 assert(!hasCatchAll);
857 hasCatchAll = true;
858 goto done;
John McCallbd309292010-07-06 01:34:17 +0000859 }
860
861 // Check whether we already have a handler for this type.
David Blaikie82e95a32014-11-19 07:49:47 +0000862 if (catchTypes.insert(handler.Type).second)
Bill Wendlingf0724e82011-09-19 20:31:14 +0000863 // If not, add it directly to the landingpad.
864 LPadInst->addClause(handler.Type);
John McCallbd309292010-07-06 01:34:17 +0000865 }
John McCallbd309292010-07-06 01:34:17 +0000866 }
867
868 done:
Bill Wendlingf0724e82011-09-19 20:31:14 +0000869 // If we have a catch-all, add null to the landingpad.
John McCall8e4c74b2011-08-11 02:22:43 +0000870 assert(!(hasCatchAll && hasFilter));
871 if (hasCatchAll) {
Bill Wendlingf0724e82011-09-19 20:31:14 +0000872 LPadInst->addClause(getCatchAllValue(*this));
John McCallbd309292010-07-06 01:34:17 +0000873
874 // If we have an EH filter, we need to add those handlers in the
Bill Wendlingf0724e82011-09-19 20:31:14 +0000875 // right place in the landingpad, which is to say, at the end.
John McCall8e4c74b2011-08-11 02:22:43 +0000876 } else if (hasFilter) {
Bill Wendling58e58fe2011-09-19 22:08:36 +0000877 // Create a filter expression: a constant array indicating which filter
878 // types there are. The personality routine only lands here if the filter
879 // doesn't match.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000880 SmallVector<llvm::Constant*, 8> Filters;
Bill Wendlingf0724e82011-09-19 20:31:14 +0000881 llvm::ArrayType *AType =
882 llvm::ArrayType::get(!filterTypes.empty() ?
883 filterTypes[0]->getType() : Int8PtrTy,
884 filterTypes.size());
885
886 for (unsigned i = 0, e = filterTypes.size(); i != e; ++i)
887 Filters.push_back(cast<llvm::Constant>(filterTypes[i]));
888 llvm::Constant *FilterArray = llvm::ConstantArray::get(AType, Filters);
889 LPadInst->addClause(FilterArray);
John McCallbd309292010-07-06 01:34:17 +0000890
891 // Also check whether we need a cleanup.
Bill Wendlingf0724e82011-09-19 20:31:14 +0000892 if (hasCleanup)
893 LPadInst->setCleanup(true);
John McCallbd309292010-07-06 01:34:17 +0000894
895 // Otherwise, signal that we at least have cleanups.
Logan Chiene9c8ccb2014-07-01 11:47:10 +0000896 } else if (hasCleanup) {
897 LPadInst->setCleanup(true);
John McCallbd309292010-07-06 01:34:17 +0000898 }
899
Bill Wendlingf0724e82011-09-19 20:31:14 +0000900 assert((LPadInst->getNumClauses() > 0 || LPadInst->isCleanup()) &&
901 "landingpad instruction has no clauses!");
John McCallbd309292010-07-06 01:34:17 +0000902
903 // Tell the backend how to generate the landing pad.
John McCall8e4c74b2011-08-11 02:22:43 +0000904 Builder.CreateBr(getEHDispatchBlock(EHStack.getInnermostEHScope()));
John McCallbd309292010-07-06 01:34:17 +0000905
906 // Restore the old IR generation state.
John McCall8e4c74b2011-08-11 02:22:43 +0000907 Builder.restoreIP(savedIP);
John McCallbd309292010-07-06 01:34:17 +0000908
John McCall8e4c74b2011-08-11 02:22:43 +0000909 return lpad;
John McCallbd309292010-07-06 01:34:17 +0000910}
911
John McCall5c08ab92010-07-13 22:12:14 +0000912namespace {
913 /// A cleanup to call __cxa_end_catch. In many cases, the caught
914 /// exception type lets us state definitively that the thrown exception
915 /// type does not have a destructor. In particular:
916 /// - Catch-alls tell us nothing, so we have to conservatively
917 /// assume that the thrown exception might have a destructor.
918 /// - Catches by reference behave according to their base types.
919 /// - Catches of non-record types will only trigger for exceptions
920 /// of non-record types, which never have destructors.
921 /// - Catches of record types can trigger for arbitrary subclasses
922 /// of the caught type, so we have to assume the actual thrown
923 /// exception type might have a throwing destructor, even if the
924 /// caught type's destructor is trivial or nothrow.
John McCallcda666c2010-07-21 07:22:38 +0000925 struct CallEndCatch : EHScopeStack::Cleanup {
John McCall5c08ab92010-07-13 22:12:14 +0000926 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
927 bool MightThrow;
928
Craig Topper4f12f102014-03-12 06:41:41 +0000929 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall5c08ab92010-07-13 22:12:14 +0000930 if (!MightThrow) {
John McCall882987f2013-02-28 19:01:20 +0000931 CGF.EmitNounwindRuntimeCall(getEndCatchFn(CGF.CGM));
John McCall5c08ab92010-07-13 22:12:14 +0000932 return;
933 }
934
John McCall882987f2013-02-28 19:01:20 +0000935 CGF.EmitRuntimeCallOrInvoke(getEndCatchFn(CGF.CGM));
John McCall5c08ab92010-07-13 22:12:14 +0000936 }
937 };
938}
939
John McCallbd309292010-07-06 01:34:17 +0000940/// Emits a call to __cxa_begin_catch and enters a cleanup to call
941/// __cxa_end_catch.
John McCall5c08ab92010-07-13 22:12:14 +0000942///
943/// \param EndMightThrow - true if __cxa_end_catch might throw
944static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
945 llvm::Value *Exn,
946 bool EndMightThrow) {
John McCall882987f2013-02-28 19:01:20 +0000947 llvm::CallInst *call =
948 CGF.EmitNounwindRuntimeCall(getBeginCatchFn(CGF.CGM), Exn);
John McCallbd309292010-07-06 01:34:17 +0000949
John McCallcda666c2010-07-21 07:22:38 +0000950 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
John McCallbd309292010-07-06 01:34:17 +0000951
John McCall882987f2013-02-28 19:01:20 +0000952 return call;
John McCallbd309292010-07-06 01:34:17 +0000953}
954
955/// A "special initializer" callback for initializing a catch
956/// parameter during catch initialization.
957static void InitCatchParam(CodeGenFunction &CGF,
958 const VarDecl &CatchParam,
Nick Lewycky2d84e842013-10-02 02:29:49 +0000959 llvm::Value *ParamAddr,
960 SourceLocation Loc) {
John McCallbd309292010-07-06 01:34:17 +0000961 // Load the exception from where the landing pad saved it.
Bill Wendling79a70e42011-09-15 18:57:19 +0000962 llvm::Value *Exn = CGF.getExceptionFromSlot();
John McCallbd309292010-07-06 01:34:17 +0000963
964 CanQualType CatchType =
965 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
Chris Lattner2192fe52011-07-18 04:24:23 +0000966 llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
John McCallbd309292010-07-06 01:34:17 +0000967
968 // If we're catching by reference, we can just cast the object
969 // pointer to the appropriate pointer.
970 if (isa<ReferenceType>(CatchType)) {
John McCall5add20c2010-07-20 22:17:55 +0000971 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
972 bool EndCatchMightThrow = CaughtType->isRecordType();
John McCall5c08ab92010-07-13 22:12:14 +0000973
John McCallbd309292010-07-06 01:34:17 +0000974 // __cxa_begin_catch returns the adjusted object pointer.
John McCall5c08ab92010-07-13 22:12:14 +0000975 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
John McCall5add20c2010-07-20 22:17:55 +0000976
977 // We have no way to tell the personality function that we're
978 // catching by reference, so if we're catching a pointer,
979 // __cxa_begin_catch will actually return that pointer by value.
980 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
981 QualType PointeeType = PT->getPointeeType();
982
983 // When catching by reference, generally we should just ignore
984 // this by-value pointer and use the exception object instead.
985 if (!PointeeType->isRecordType()) {
986
987 // Exn points to the struct _Unwind_Exception header, which
988 // we have to skip past in order to reach the exception data.
989 unsigned HeaderSize =
990 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
991 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
992
993 // However, if we're catching a pointer-to-record type that won't
994 // work, because the personality function might have adjusted
995 // the pointer. There's actually no way for us to fully satisfy
996 // the language/ABI contract here: we can't use Exn because it
997 // might have the wrong adjustment, but we can't use the by-value
998 // pointer because it's off by a level of abstraction.
999 //
1000 // The current solution is to dump the adjusted pointer into an
1001 // alloca, which breaks language semantics (because changing the
1002 // pointer doesn't change the exception) but at least works.
1003 // The better solution would be to filter out non-exact matches
1004 // and rethrow them, but this is tricky because the rethrow
1005 // really needs to be catchable by other sites at this landing
1006 // pad. The best solution is to fix the personality function.
1007 } else {
1008 // Pull the pointer for the reference type off.
Chris Lattner2192fe52011-07-18 04:24:23 +00001009 llvm::Type *PtrTy =
John McCall5add20c2010-07-20 22:17:55 +00001010 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
1011
1012 // Create the temporary and write the adjusted pointer into it.
1013 llvm::Value *ExnPtrTmp = CGF.CreateTempAlloca(PtrTy, "exn.byref.tmp");
1014 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1015 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
1016
1017 // Bind the reference to the temporary.
1018 AdjustedExn = ExnPtrTmp;
1019 }
1020 }
1021
John McCallbd309292010-07-06 01:34:17 +00001022 llvm::Value *ExnCast =
1023 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
1024 CGF.Builder.CreateStore(ExnCast, ParamAddr);
1025 return;
1026 }
1027
John McCall47fb9502013-03-07 21:37:08 +00001028 // Scalars and complexes.
1029 TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType);
1030 if (TEK != TEK_Aggregate) {
John McCall5c08ab92010-07-13 22:12:14 +00001031 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
John McCallbd309292010-07-06 01:34:17 +00001032
1033 // If the catch type is a pointer type, __cxa_begin_catch returns
1034 // the pointer by value.
1035 if (CatchType->hasPointerRepresentation()) {
1036 llvm::Value *CastExn =
1037 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
John McCall97017312012-01-17 20:16:56 +00001038
1039 switch (CatchType.getQualifiers().getObjCLifetime()) {
1040 case Qualifiers::OCL_Strong:
1041 CastExn = CGF.EmitARCRetainNonBlock(CastExn);
1042 // fallthrough
1043
1044 case Qualifiers::OCL_None:
1045 case Qualifiers::OCL_ExplicitNone:
1046 case Qualifiers::OCL_Autoreleasing:
1047 CGF.Builder.CreateStore(CastExn, ParamAddr);
1048 return;
1049
1050 case Qualifiers::OCL_Weak:
1051 CGF.EmitARCInitWeak(ParamAddr, CastExn);
1052 return;
1053 }
1054 llvm_unreachable("bad ownership qualifier!");
John McCallbd309292010-07-06 01:34:17 +00001055 }
1056
1057 // Otherwise, it returns a pointer into the exception object.
1058
Chris Lattner2192fe52011-07-18 04:24:23 +00001059 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
John McCallbd309292010-07-06 01:34:17 +00001060 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1061
John McCall47fb9502013-03-07 21:37:08 +00001062 LValue srcLV = CGF.MakeNaturalAlignAddrLValue(Cast, CatchType);
1063 LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType,
1064 CGF.getContext().getDeclAlign(&CatchParam));
1065 switch (TEK) {
1066 case TEK_Complex:
Nick Lewycky2d84e842013-10-02 02:29:49 +00001067 CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV,
John McCall47fb9502013-03-07 21:37:08 +00001068 /*init*/ true);
1069 return;
1070 case TEK_Scalar: {
Nick Lewycky2d84e842013-10-02 02:29:49 +00001071 llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc);
John McCall47fb9502013-03-07 21:37:08 +00001072 CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true);
1073 return;
John McCallbd309292010-07-06 01:34:17 +00001074 }
John McCall47fb9502013-03-07 21:37:08 +00001075 case TEK_Aggregate:
1076 llvm_unreachable("evaluation kind filtered out!");
1077 }
1078 llvm_unreachable("bad evaluation kind");
John McCallbd309292010-07-06 01:34:17 +00001079 }
1080
John McCallb5011ab2011-02-16 08:39:19 +00001081 assert(isa<RecordType>(CatchType) && "unexpected catch type!");
John McCallbd309292010-07-06 01:34:17 +00001082
Chris Lattner2192fe52011-07-18 04:24:23 +00001083 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
John McCallbd309292010-07-06 01:34:17 +00001084
John McCallb5011ab2011-02-16 08:39:19 +00001085 // Check for a copy expression. If we don't have a copy expression,
1086 // that means a trivial copy is okay.
John McCall1bf58462011-02-16 08:02:54 +00001087 const Expr *copyExpr = CatchParam.getInit();
1088 if (!copyExpr) {
John McCallb5011ab2011-02-16 08:39:19 +00001089 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
1090 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
Chad Rosier615ed1a2012-03-29 17:37:10 +00001091 CGF.EmitAggregateCopy(ParamAddr, adjustedExn, CatchType);
John McCallbd309292010-07-06 01:34:17 +00001092 return;
1093 }
1094
1095 // We have to call __cxa_get_exception_ptr to get the adjusted
1096 // pointer before copying.
John McCall1bf58462011-02-16 08:02:54 +00001097 llvm::CallInst *rawAdjustedExn =
John McCall882987f2013-02-28 19:01:20 +00001098 CGF.EmitNounwindRuntimeCall(getGetExceptionPtrFn(CGF.CGM), Exn);
John McCallbd309292010-07-06 01:34:17 +00001099
John McCall1bf58462011-02-16 08:02:54 +00001100 // Cast that to the appropriate type.
1101 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
John McCallbd309292010-07-06 01:34:17 +00001102
John McCall1bf58462011-02-16 08:02:54 +00001103 // The copy expression is defined in terms of an OpaqueValueExpr.
1104 // Find it and map it to the adjusted expression.
1105 CodeGenFunction::OpaqueValueMapping
John McCallc07a0c72011-02-17 10:25:35 +00001106 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
1107 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
John McCallbd309292010-07-06 01:34:17 +00001108
1109 // Call the copy ctor in a terminate scope.
1110 CGF.EHStack.pushTerminate();
John McCall1bf58462011-02-16 08:02:54 +00001111
1112 // Perform the copy construction.
Eli Friedman38cd36d2011-12-03 02:13:40 +00001113 CharUnits Alignment = CGF.getContext().getDeclAlign(&CatchParam);
Eli Friedmanc1d85b92011-12-03 00:54:26 +00001114 CGF.EmitAggExpr(copyExpr,
1115 AggValueSlot::forAddr(ParamAddr, Alignment, Qualifiers(),
1116 AggValueSlot::IsNotDestructed,
1117 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001118 AggValueSlot::IsNotAliased));
John McCall1bf58462011-02-16 08:02:54 +00001119
1120 // Leave the terminate scope.
John McCallbd309292010-07-06 01:34:17 +00001121 CGF.EHStack.popTerminate();
1122
John McCall1bf58462011-02-16 08:02:54 +00001123 // Undo the opaque value mapping.
1124 opaque.pop();
1125
John McCallbd309292010-07-06 01:34:17 +00001126 // Finally we can call __cxa_begin_catch.
John McCall5c08ab92010-07-13 22:12:14 +00001127 CallBeginCatch(CGF, Exn, true);
John McCallbd309292010-07-06 01:34:17 +00001128}
1129
1130/// Begins a catch statement by initializing the catch variable and
1131/// calling __cxa_begin_catch.
John McCall1bf58462011-02-16 08:02:54 +00001132static void BeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *S) {
John McCallbd309292010-07-06 01:34:17 +00001133 // We have to be very careful with the ordering of cleanups here:
1134 // C++ [except.throw]p4:
1135 // The destruction [of the exception temporary] occurs
1136 // immediately after the destruction of the object declared in
1137 // the exception-declaration in the handler.
1138 //
1139 // So the precise ordering is:
1140 // 1. Construct catch variable.
1141 // 2. __cxa_begin_catch
1142 // 3. Enter __cxa_end_catch cleanup
1143 // 4. Enter dtor cleanup
1144 //
John McCallc533cb72011-02-22 06:44:22 +00001145 // We do this by using a slightly abnormal initialization process.
1146 // Delegation sequence:
John McCallbd309292010-07-06 01:34:17 +00001147 // - ExitCXXTryStmt opens a RunCleanupsScope
John McCallc533cb72011-02-22 06:44:22 +00001148 // - EmitAutoVarAlloca creates the variable and debug info
John McCallbd309292010-07-06 01:34:17 +00001149 // - InitCatchParam initializes the variable from the exception
John McCallc533cb72011-02-22 06:44:22 +00001150 // - CallBeginCatch calls __cxa_begin_catch
1151 // - CallBeginCatch enters the __cxa_end_catch cleanup
1152 // - EmitAutoVarCleanups enters the variable destructor cleanup
John McCallbd309292010-07-06 01:34:17 +00001153 // - EmitCXXTryStmt emits the code for the catch body
1154 // - EmitCXXTryStmt close the RunCleanupsScope
1155
1156 VarDecl *CatchParam = S->getExceptionDecl();
1157 if (!CatchParam) {
Bill Wendling79a70e42011-09-15 18:57:19 +00001158 llvm::Value *Exn = CGF.getExceptionFromSlot();
John McCall5c08ab92010-07-13 22:12:14 +00001159 CallBeginCatch(CGF, Exn, true);
John McCallbd309292010-07-06 01:34:17 +00001160 return;
1161 }
1162
1163 // Emit the local.
John McCallc533cb72011-02-22 06:44:22 +00001164 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
Nick Lewycky2d84e842013-10-02 02:29:49 +00001165 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF), S->getLocStart());
John McCallc533cb72011-02-22 06:44:22 +00001166 CGF.EmitAutoVarCleanups(var);
John McCallb81884d2010-02-19 09:25:03 +00001167}
1168
John McCall8e4c74b2011-08-11 02:22:43 +00001169/// Emit the structure of the dispatch block for the given catch scope.
1170/// It is an invariant that the dispatch block already exists.
1171static void emitCatchDispatchBlock(CodeGenFunction &CGF,
1172 EHCatchScope &catchScope) {
1173 llvm::BasicBlock *dispatchBlock = catchScope.getCachedEHDispatchBlock();
1174 assert(dispatchBlock);
1175
1176 // If there's only a single catch-all, getEHDispatchBlock returned
1177 // that catch-all as the dispatch block.
1178 if (catchScope.getNumHandlers() == 1 &&
1179 catchScope.getHandler(0).isCatchAll()) {
1180 assert(dispatchBlock == catchScope.getHandler(0).Block);
1181 return;
1182 }
1183
1184 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveIP();
1185 CGF.EmitBlockAfterUses(dispatchBlock);
1186
1187 // Select the right handler.
1188 llvm::Value *llvm_eh_typeid_for =
1189 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
1190
1191 // Load the selector value.
Bill Wendling79a70e42011-09-15 18:57:19 +00001192 llvm::Value *selector = CGF.getSelectorFromSlot();
John McCall8e4c74b2011-08-11 02:22:43 +00001193
1194 // Test against each of the exception types we claim to catch.
1195 for (unsigned i = 0, e = catchScope.getNumHandlers(); ; ++i) {
1196 assert(i < e && "ran off end of handlers!");
1197 const EHCatchScope::Handler &handler = catchScope.getHandler(i);
1198
1199 llvm::Value *typeValue = handler.Type;
1200 assert(typeValue && "fell into catch-all case!");
1201 typeValue = CGF.Builder.CreateBitCast(typeValue, CGF.Int8PtrTy);
1202
1203 // Figure out the next block.
1204 bool nextIsEnd;
1205 llvm::BasicBlock *nextBlock;
1206
1207 // If this is the last handler, we're at the end, and the next
1208 // block is the block for the enclosing EH scope.
1209 if (i + 1 == e) {
1210 nextBlock = CGF.getEHDispatchBlock(catchScope.getEnclosingEHScope());
1211 nextIsEnd = true;
1212
1213 // If the next handler is a catch-all, we're at the end, and the
1214 // next block is that handler.
1215 } else if (catchScope.getHandler(i+1).isCatchAll()) {
1216 nextBlock = catchScope.getHandler(i+1).Block;
1217 nextIsEnd = true;
1218
1219 // Otherwise, we're not at the end and we need a new block.
1220 } else {
1221 nextBlock = CGF.createBasicBlock("catch.fallthrough");
1222 nextIsEnd = false;
1223 }
1224
1225 // Figure out the catch type's index in the LSDA's type table.
1226 llvm::CallInst *typeIndex =
1227 CGF.Builder.CreateCall(llvm_eh_typeid_for, typeValue);
1228 typeIndex->setDoesNotThrow();
1229
1230 llvm::Value *matchesTypeIndex =
1231 CGF.Builder.CreateICmpEQ(selector, typeIndex, "matches");
1232 CGF.Builder.CreateCondBr(matchesTypeIndex, handler.Block, nextBlock);
1233
1234 // If the next handler is a catch-all, we're completely done.
1235 if (nextIsEnd) {
1236 CGF.Builder.restoreIP(savedIP);
1237 return;
John McCall8e4c74b2011-08-11 02:22:43 +00001238 }
Ahmed Charles289896d2012-02-19 11:57:29 +00001239 // Otherwise we need to emit and continue at that block.
1240 CGF.EmitBlock(nextBlock);
John McCall8e4c74b2011-08-11 02:22:43 +00001241 }
John McCall8e4c74b2011-08-11 02:22:43 +00001242}
1243
1244void CodeGenFunction::popCatchScope() {
1245 EHCatchScope &catchScope = cast<EHCatchScope>(*EHStack.begin());
1246 if (catchScope.hasEHBranches())
1247 emitCatchDispatchBlock(*this, catchScope);
1248 EHStack.popCatch();
1249}
1250
John McCallb609d3f2010-07-07 06:56:46 +00001251void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallbd309292010-07-06 01:34:17 +00001252 unsigned NumHandlers = S.getNumHandlers();
1253 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1254 assert(CatchScope.getNumHandlers() == NumHandlers);
Mike Stump58ef18b2009-11-20 23:44:51 +00001255
John McCall8e4c74b2011-08-11 02:22:43 +00001256 // If the catch was not required, bail out now.
1257 if (!CatchScope.hasEHBranches()) {
Kostya Serebryanyba4aced2014-01-09 09:22:32 +00001258 CatchScope.clearHandlerBlocks();
John McCall8e4c74b2011-08-11 02:22:43 +00001259 EHStack.popCatch();
1260 return;
1261 }
1262
1263 // Emit the structure of the EH dispatch for this catch.
1264 emitCatchDispatchBlock(*this, CatchScope);
1265
John McCallbd309292010-07-06 01:34:17 +00001266 // Copy the handler blocks off before we pop the EH stack. Emitting
1267 // the handlers might scribble on this memory.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001268 SmallVector<EHCatchScope::Handler, 8> Handlers(NumHandlers);
John McCallbd309292010-07-06 01:34:17 +00001269 memcpy(Handlers.data(), CatchScope.begin(),
1270 NumHandlers * sizeof(EHCatchScope::Handler));
John McCall8e4c74b2011-08-11 02:22:43 +00001271
John McCallbd309292010-07-06 01:34:17 +00001272 EHStack.popCatch();
Mike Stump58ef18b2009-11-20 23:44:51 +00001273
John McCallbd309292010-07-06 01:34:17 +00001274 // The fall-through block.
1275 llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
Mike Stump58ef18b2009-11-20 23:44:51 +00001276
John McCallbd309292010-07-06 01:34:17 +00001277 // We just emitted the body of the try; jump to the continue block.
1278 if (HaveInsertPoint())
1279 Builder.CreateBr(ContBB);
Mike Stump97329152009-12-02 19:53:57 +00001280
John McCalld8d00be2012-06-15 05:27:05 +00001281 // Determine if we need an implicit rethrow for all these catch handlers;
1282 // see the comment below.
1283 bool doImplicitRethrow = false;
John McCallb609d3f2010-07-07 06:56:46 +00001284 if (IsFnTryBlock)
John McCalld8d00be2012-06-15 05:27:05 +00001285 doImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
1286 isa<CXXConstructorDecl>(CurCodeDecl);
John McCallb609d3f2010-07-07 06:56:46 +00001287
John McCall8e4c74b2011-08-11 02:22:43 +00001288 // Perversely, we emit the handlers backwards precisely because we
1289 // want them to appear in source order. In all of these cases, the
1290 // catch block will have exactly one predecessor, which will be a
1291 // particular block in the catch dispatch. However, in the case of
1292 // a catch-all, one of the dispatch blocks will branch to two
1293 // different handlers, and EmitBlockAfterUses will cause the second
1294 // handler to be moved before the first.
1295 for (unsigned I = NumHandlers; I != 0; --I) {
1296 llvm::BasicBlock *CatchBlock = Handlers[I-1].Block;
1297 EmitBlockAfterUses(CatchBlock);
Mike Stump75546b82009-12-10 00:06:18 +00001298
John McCallbd309292010-07-06 01:34:17 +00001299 // Catch the exception if this isn't a catch-all.
John McCall8e4c74b2011-08-11 02:22:43 +00001300 const CXXCatchStmt *C = S.getHandler(I-1);
Mike Stump58ef18b2009-11-20 23:44:51 +00001301
John McCallbd309292010-07-06 01:34:17 +00001302 // Enter a cleanup scope, including the catch variable and the
1303 // end-catch.
1304 RunCleanupsScope CatchScope(*this);
Mike Stump58ef18b2009-11-20 23:44:51 +00001305
John McCallbd309292010-07-06 01:34:17 +00001306 // Initialize the catch variable and set up the cleanups.
1307 BeginCatch(*this, C);
1308
Justin Bognerea278c32014-01-07 00:20:28 +00001309 // Emit the PGO counter increment.
Justin Bogneref512b92014-01-06 22:27:43 +00001310 RegionCounter CatchCnt = getPGORegionCounter(C);
1311 CatchCnt.beginRegion(Builder);
1312
John McCallbd309292010-07-06 01:34:17 +00001313 // Perform the body of the catch.
1314 EmitStmt(C->getHandlerBlock());
1315
John McCalld8d00be2012-06-15 05:27:05 +00001316 // [except.handle]p11:
1317 // The currently handled exception is rethrown if control
1318 // reaches the end of a handler of the function-try-block of a
1319 // constructor or destructor.
1320
1321 // It is important that we only do this on fallthrough and not on
1322 // return. Note that it's illegal to put a return in a
1323 // constructor function-try-block's catch handler (p14), so this
1324 // really only applies to destructors.
1325 if (doImplicitRethrow && HaveInsertPoint()) {
David Majnemer442d0a22014-11-25 07:20:20 +00001326 CGM.getCXXABI().emitRethrow(*this, /*isNoReturn*/false);
John McCalld8d00be2012-06-15 05:27:05 +00001327 Builder.CreateUnreachable();
1328 Builder.ClearInsertionPoint();
1329 }
1330
John McCallbd309292010-07-06 01:34:17 +00001331 // Fall out through the catch cleanups.
1332 CatchScope.ForceCleanup();
1333
1334 // Branch out of the try.
1335 if (HaveInsertPoint())
1336 Builder.CreateBr(ContBB);
Mike Stump58ef18b2009-11-20 23:44:51 +00001337 }
1338
Justin Bogneref512b92014-01-06 22:27:43 +00001339 RegionCounter ContCnt = getPGORegionCounter(&S);
John McCallbd309292010-07-06 01:34:17 +00001340 EmitBlock(ContBB);
Justin Bogneref512b92014-01-06 22:27:43 +00001341 ContCnt.beginRegion(Builder);
Mike Stump58ef18b2009-11-20 23:44:51 +00001342}
Mike Stumpaff69af2009-12-09 03:35:49 +00001343
John McCall1e670402010-07-21 00:52:03 +00001344namespace {
John McCallcda666c2010-07-21 07:22:38 +00001345 struct CallEndCatchForFinally : EHScopeStack::Cleanup {
John McCall1e670402010-07-21 00:52:03 +00001346 llvm::Value *ForEHVar;
1347 llvm::Value *EndCatchFn;
1348 CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn)
1349 : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
1350
Craig Topper4f12f102014-03-12 06:41:41 +00001351 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall1e670402010-07-21 00:52:03 +00001352 llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
1353 llvm::BasicBlock *CleanupContBB =
1354 CGF.createBasicBlock("finally.cleanup.cont");
1355
1356 llvm::Value *ShouldEndCatch =
1357 CGF.Builder.CreateLoad(ForEHVar, "finally.endcatch");
1358 CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1359 CGF.EmitBlock(EndCatchBB);
John McCall882987f2013-02-28 19:01:20 +00001360 CGF.EmitRuntimeCallOrInvoke(EndCatchFn); // catch-all, so might throw
John McCall1e670402010-07-21 00:52:03 +00001361 CGF.EmitBlock(CleanupContBB);
1362 }
1363 };
John McCall906da4b2010-07-21 05:47:49 +00001364
John McCallcda666c2010-07-21 07:22:38 +00001365 struct PerformFinally : EHScopeStack::Cleanup {
John McCall906da4b2010-07-21 05:47:49 +00001366 const Stmt *Body;
1367 llvm::Value *ForEHVar;
1368 llvm::Value *EndCatchFn;
1369 llvm::Value *RethrowFn;
1370 llvm::Value *SavedExnVar;
1371
1372 PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
1373 llvm::Value *EndCatchFn,
1374 llvm::Value *RethrowFn, llvm::Value *SavedExnVar)
1375 : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1376 RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
1377
Craig Topper4f12f102014-03-12 06:41:41 +00001378 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall906da4b2010-07-21 05:47:49 +00001379 // Enter a cleanup to call the end-catch function if one was provided.
1380 if (EndCatchFn)
John McCallcda666c2010-07-21 07:22:38 +00001381 CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
1382 ForEHVar, EndCatchFn);
John McCall906da4b2010-07-21 05:47:49 +00001383
John McCallcebe0ca2010-08-11 00:16:14 +00001384 // Save the current cleanup destination in case there are
1385 // cleanups in the finally block.
1386 llvm::Value *SavedCleanupDest =
1387 CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
1388 "cleanup.dest.saved");
1389
John McCall906da4b2010-07-21 05:47:49 +00001390 // Emit the finally block.
1391 CGF.EmitStmt(Body);
1392
1393 // If the end of the finally is reachable, check whether this was
1394 // for EH. If so, rethrow.
1395 if (CGF.HaveInsertPoint()) {
1396 llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
1397 llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
1398
1399 llvm::Value *ShouldRethrow =
1400 CGF.Builder.CreateLoad(ForEHVar, "finally.shouldthrow");
1401 CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1402
1403 CGF.EmitBlock(RethrowBB);
1404 if (SavedExnVar) {
John McCall882987f2013-02-28 19:01:20 +00001405 CGF.EmitRuntimeCallOrInvoke(RethrowFn,
1406 CGF.Builder.CreateLoad(SavedExnVar));
John McCall906da4b2010-07-21 05:47:49 +00001407 } else {
John McCall882987f2013-02-28 19:01:20 +00001408 CGF.EmitRuntimeCallOrInvoke(RethrowFn);
John McCall906da4b2010-07-21 05:47:49 +00001409 }
1410 CGF.Builder.CreateUnreachable();
1411
1412 CGF.EmitBlock(ContBB);
John McCallcebe0ca2010-08-11 00:16:14 +00001413
1414 // Restore the cleanup destination.
1415 CGF.Builder.CreateStore(SavedCleanupDest,
1416 CGF.getNormalCleanupDestSlot());
John McCall906da4b2010-07-21 05:47:49 +00001417 }
1418
1419 // Leave the end-catch cleanup. As an optimization, pretend that
1420 // the fallthrough path was inaccessible; we've dynamically proven
1421 // that we're not in the EH case along that path.
1422 if (EndCatchFn) {
1423 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1424 CGF.PopCleanupBlock();
1425 CGF.Builder.restoreIP(SavedIP);
1426 }
1427
1428 // Now make sure we actually have an insertion point or the
1429 // cleanup gods will hate us.
1430 CGF.EnsureInsertPoint();
1431 }
1432 };
John McCall1e670402010-07-21 00:52:03 +00001433}
1434
John McCallbd309292010-07-06 01:34:17 +00001435/// Enters a finally block for an implementation using zero-cost
1436/// exceptions. This is mostly general, but hard-codes some
1437/// language/ABI-specific behavior in the catch-all sections.
John McCall6b0feb72011-06-22 02:32:12 +00001438void CodeGenFunction::FinallyInfo::enter(CodeGenFunction &CGF,
1439 const Stmt *body,
1440 llvm::Constant *beginCatchFn,
1441 llvm::Constant *endCatchFn,
1442 llvm::Constant *rethrowFn) {
Craig Topper8a13c412014-05-21 05:09:00 +00001443 assert((beginCatchFn != nullptr) == (endCatchFn != nullptr) &&
John McCallbd309292010-07-06 01:34:17 +00001444 "begin/end catch functions not paired");
John McCall6b0feb72011-06-22 02:32:12 +00001445 assert(rethrowFn && "rethrow function is required");
1446
1447 BeginCatchFn = beginCatchFn;
Mike Stumpaff69af2009-12-09 03:35:49 +00001448
John McCallbd309292010-07-06 01:34:17 +00001449 // The rethrow function has one of the following two types:
1450 // void (*)()
1451 // void (*)(void*)
1452 // In the latter case we need to pass it the exception object.
1453 // But we can't use the exception slot because the @finally might
1454 // have a landing pad (which would overwrite the exception slot).
Chris Lattner2192fe52011-07-18 04:24:23 +00001455 llvm::FunctionType *rethrowFnTy =
John McCallbd309292010-07-06 01:34:17 +00001456 cast<llvm::FunctionType>(
John McCall6b0feb72011-06-22 02:32:12 +00001457 cast<llvm::PointerType>(rethrowFn->getType())->getElementType());
Craig Topper8a13c412014-05-21 05:09:00 +00001458 SavedExnVar = nullptr;
John McCall6b0feb72011-06-22 02:32:12 +00001459 if (rethrowFnTy->getNumParams())
1460 SavedExnVar = CGF.CreateTempAlloca(CGF.Int8PtrTy, "finally.exn");
Mike Stumpaff69af2009-12-09 03:35:49 +00001461
John McCallbd309292010-07-06 01:34:17 +00001462 // A finally block is a statement which must be executed on any edge
1463 // out of a given scope. Unlike a cleanup, the finally block may
1464 // contain arbitrary control flow leading out of itself. In
1465 // addition, finally blocks should always be executed, even if there
1466 // are no catch handlers higher on the stack. Therefore, we
1467 // surround the protected scope with a combination of a normal
1468 // cleanup (to catch attempts to break out of the block via normal
1469 // control flow) and an EH catch-all (semantically "outside" any try
1470 // statement to which the finally block might have been attached).
1471 // The finally block itself is generated in the context of a cleanup
1472 // which conditionally leaves the catch-all.
John McCall21886962010-04-21 10:05:39 +00001473
John McCallbd309292010-07-06 01:34:17 +00001474 // Jump destination for performing the finally block on an exception
1475 // edge. We'll never actually reach this block, so unreachable is
1476 // fine.
John McCall6b0feb72011-06-22 02:32:12 +00001477 RethrowDest = CGF.getJumpDestInCurrentScope(CGF.getUnreachableBlock());
John McCall21886962010-04-21 10:05:39 +00001478
John McCallbd309292010-07-06 01:34:17 +00001479 // Whether the finally block is being executed for EH purposes.
John McCall6b0feb72011-06-22 02:32:12 +00001480 ForEHVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "finally.for-eh");
1481 CGF.Builder.CreateStore(CGF.Builder.getFalse(), ForEHVar);
Mike Stumpaff69af2009-12-09 03:35:49 +00001482
John McCallbd309292010-07-06 01:34:17 +00001483 // Enter a normal cleanup which will perform the @finally block.
John McCall6b0feb72011-06-22 02:32:12 +00001484 CGF.EHStack.pushCleanup<PerformFinally>(NormalCleanup, body,
1485 ForEHVar, endCatchFn,
1486 rethrowFn, SavedExnVar);
John McCallbd309292010-07-06 01:34:17 +00001487
1488 // Enter a catch-all scope.
John McCall6b0feb72011-06-22 02:32:12 +00001489 llvm::BasicBlock *catchBB = CGF.createBasicBlock("finally.catchall");
1490 EHCatchScope *catchScope = CGF.EHStack.pushCatch(1);
1491 catchScope->setCatchAllHandler(0, catchBB);
John McCallbd309292010-07-06 01:34:17 +00001492}
1493
John McCall6b0feb72011-06-22 02:32:12 +00001494void CodeGenFunction::FinallyInfo::exit(CodeGenFunction &CGF) {
John McCallbd309292010-07-06 01:34:17 +00001495 // Leave the finally catch-all.
John McCall6b0feb72011-06-22 02:32:12 +00001496 EHCatchScope &catchScope = cast<EHCatchScope>(*CGF.EHStack.begin());
1497 llvm::BasicBlock *catchBB = catchScope.getHandler(0).Block;
John McCall8e4c74b2011-08-11 02:22:43 +00001498
1499 CGF.popCatchScope();
John McCallbd309292010-07-06 01:34:17 +00001500
John McCall6b0feb72011-06-22 02:32:12 +00001501 // If there are any references to the catch-all block, emit it.
1502 if (catchBB->use_empty()) {
1503 delete catchBB;
1504 } else {
1505 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveAndClearIP();
1506 CGF.EmitBlock(catchBB);
John McCallbd309292010-07-06 01:34:17 +00001507
Craig Topper8a13c412014-05-21 05:09:00 +00001508 llvm::Value *exn = nullptr;
John McCallbd309292010-07-06 01:34:17 +00001509
John McCall6b0feb72011-06-22 02:32:12 +00001510 // If there's a begin-catch function, call it.
1511 if (BeginCatchFn) {
Bill Wendling79a70e42011-09-15 18:57:19 +00001512 exn = CGF.getExceptionFromSlot();
John McCall882987f2013-02-28 19:01:20 +00001513 CGF.EmitNounwindRuntimeCall(BeginCatchFn, exn);
John McCall6b0feb72011-06-22 02:32:12 +00001514 }
1515
1516 // If we need to remember the exception pointer to rethrow later, do so.
1517 if (SavedExnVar) {
Bill Wendling79a70e42011-09-15 18:57:19 +00001518 if (!exn) exn = CGF.getExceptionFromSlot();
John McCall6b0feb72011-06-22 02:32:12 +00001519 CGF.Builder.CreateStore(exn, SavedExnVar);
1520 }
1521
1522 // Tell the cleanups in the finally block that we're do this for EH.
1523 CGF.Builder.CreateStore(CGF.Builder.getTrue(), ForEHVar);
1524
1525 // Thread a jump through the finally cleanup.
1526 CGF.EmitBranchThroughCleanup(RethrowDest);
1527
1528 CGF.Builder.restoreIP(savedIP);
1529 }
1530
1531 // Finally, leave the @finally cleanup.
1532 CGF.PopCleanupBlock();
John McCallbd309292010-07-06 01:34:17 +00001533}
1534
John McCalle142ad52013-02-12 03:51:46 +00001535/// In a terminate landing pad, should we use __clang__call_terminate
1536/// or just a naked call to std::terminate?
1537///
1538/// __clang_call_terminate calls __cxa_begin_catch, which then allows
1539/// std::terminate to usefully report something about the
1540/// violating exception.
1541static bool useClangCallTerminate(CodeGenModule &CGM) {
1542 // Only do this for Itanium-family ABIs in C++ mode.
1543 return (CGM.getLangOpts().CPlusPlus &&
1544 CGM.getTarget().getCXXABI().isItaniumFamily());
1545}
1546
1547/// Get or define the following function:
1548/// void @__clang_call_terminate(i8* %exn) nounwind noreturn
1549/// This code is used only in C++.
1550static llvm::Constant *getClangCallTerminateFn(CodeGenModule &CGM) {
1551 llvm::FunctionType *fnTy =
1552 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
1553 llvm::Constant *fnRef =
1554 CGM.CreateRuntimeFunction(fnTy, "__clang_call_terminate");
1555
1556 llvm::Function *fn = dyn_cast<llvm::Function>(fnRef);
1557 if (fn && fn->empty()) {
1558 fn->setDoesNotThrow();
1559 fn->setDoesNotReturn();
1560
1561 // What we really want is to massively penalize inlining without
1562 // forbidding it completely. The difference between that and
1563 // 'noinline' is negligible.
1564 fn->addFnAttr(llvm::Attribute::NoInline);
1565
1566 // Allow this function to be shared across translation units, but
1567 // we don't want it to turn into an exported symbol.
1568 fn->setLinkage(llvm::Function::LinkOnceODRLinkage);
1569 fn->setVisibility(llvm::Function::HiddenVisibility);
Reid Kleckner4c209c72015-02-11 18:50:13 +00001570 if (CGM.supportsCOMDAT())
1571 fn->setComdat(CGM.getModule().getOrInsertComdat(fn->getName()));
John McCalle142ad52013-02-12 03:51:46 +00001572
1573 // Set up the function.
1574 llvm::BasicBlock *entry =
1575 llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn);
1576 CGBuilderTy builder(entry);
1577
1578 // Pull the exception pointer out of the parameter list.
1579 llvm::Value *exn = &*fn->arg_begin();
1580
1581 // Call __cxa_begin_catch(exn).
John McCall882987f2013-02-28 19:01:20 +00001582 llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn);
1583 catchCall->setDoesNotThrow();
1584 catchCall->setCallingConv(CGM.getRuntimeCC());
John McCalle142ad52013-02-12 03:51:46 +00001585
1586 // Call std::terminate().
1587 llvm::CallInst *termCall = builder.CreateCall(getTerminateFn(CGM));
1588 termCall->setDoesNotThrow();
1589 termCall->setDoesNotReturn();
John McCall882987f2013-02-28 19:01:20 +00001590 termCall->setCallingConv(CGM.getRuntimeCC());
John McCalle142ad52013-02-12 03:51:46 +00001591
1592 // std::terminate cannot return.
1593 builder.CreateUnreachable();
1594 }
1595
1596 return fnRef;
1597}
1598
John McCallbd309292010-07-06 01:34:17 +00001599llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
1600 if (TerminateLandingPad)
1601 return TerminateLandingPad;
1602
1603 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1604
1605 // This will get inserted at the end of the function.
1606 TerminateLandingPad = createBasicBlock("terminate.lpad");
1607 Builder.SetInsertPoint(TerminateLandingPad);
1608
1609 // Tell the backend that this is a landing pad.
Reid Klecknerdeeddec2015-02-05 18:56:03 +00001610 const EHPersonality &Personality = EHPersonality::get(*this);
Bill Wendlingf0724e82011-09-19 20:31:14 +00001611 llvm::LandingPadInst *LPadInst =
Reid Kleckneree7cf842014-12-01 22:02:27 +00001612 Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, nullptr),
Bill Wendlingf0724e82011-09-19 20:31:14 +00001613 getOpaquePersonalityFn(CGM, Personality), 0);
1614 LPadInst->addClause(getCatchAllValue(*this));
John McCallbd309292010-07-06 01:34:17 +00001615
John McCalle142ad52013-02-12 03:51:46 +00001616 llvm::CallInst *terminateCall;
1617 if (useClangCallTerminate(CGM)) {
1618 // Extract out the exception pointer.
1619 llvm::Value *exn = Builder.CreateExtractValue(LPadInst, 0);
John McCall882987f2013-02-28 19:01:20 +00001620 terminateCall = EmitNounwindRuntimeCall(getClangCallTerminateFn(CGM), exn);
John McCalle142ad52013-02-12 03:51:46 +00001621 } else {
John McCall882987f2013-02-28 19:01:20 +00001622 terminateCall = EmitNounwindRuntimeCall(getTerminateFn(CGM));
John McCalle142ad52013-02-12 03:51:46 +00001623 }
1624 terminateCall->setDoesNotReturn();
John McCallad7c5c12011-02-08 08:22:06 +00001625 Builder.CreateUnreachable();
Mike Stumpaff69af2009-12-09 03:35:49 +00001626
John McCallbd309292010-07-06 01:34:17 +00001627 // Restore the saved insertion state.
1628 Builder.restoreIP(SavedIP);
John McCalldac3ea62010-04-30 00:06:43 +00001629
John McCallbd309292010-07-06 01:34:17 +00001630 return TerminateLandingPad;
Mike Stumpaff69af2009-12-09 03:35:49 +00001631}
Mike Stump2b488872009-12-09 22:59:31 +00001632
1633llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
Mike Stumpf5cbb082009-12-10 00:02:42 +00001634 if (TerminateHandler)
1635 return TerminateHandler;
1636
John McCallbd309292010-07-06 01:34:17 +00001637 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
Mike Stump25b20fc2009-12-09 23:31:35 +00001638
John McCallbd309292010-07-06 01:34:17 +00001639 // Set up the terminate handler. This block is inserted at the very
1640 // end of the function by FinishFunction.
Mike Stumpf5cbb082009-12-10 00:02:42 +00001641 TerminateHandler = createBasicBlock("terminate.handler");
John McCallbd309292010-07-06 01:34:17 +00001642 Builder.SetInsertPoint(TerminateHandler);
John McCallc84e4e92013-06-20 21:37:43 +00001643 llvm::CallInst *terminateCall;
1644 if (useClangCallTerminate(CGM)) {
1645 // Load the exception pointer.
1646 llvm::Value *exn = getExceptionFromSlot();
1647 terminateCall = EmitNounwindRuntimeCall(getClangCallTerminateFn(CGM), exn);
1648 } else {
1649 terminateCall = EmitNounwindRuntimeCall(getTerminateFn(CGM));
1650 }
1651 terminateCall->setDoesNotReturn();
Mike Stump2b488872009-12-09 22:59:31 +00001652 Builder.CreateUnreachable();
1653
John McCall21886962010-04-21 10:05:39 +00001654 // Restore the saved insertion state.
John McCallbd309292010-07-06 01:34:17 +00001655 Builder.restoreIP(SavedIP);
Mike Stump25b20fc2009-12-09 23:31:35 +00001656
Mike Stump2b488872009-12-09 22:59:31 +00001657 return TerminateHandler;
1658}
John McCallbd309292010-07-06 01:34:17 +00001659
David Chisnall9a837be2012-11-07 16:50:40 +00001660llvm::BasicBlock *CodeGenFunction::getEHResumeBlock(bool isCleanup) {
John McCall8e4c74b2011-08-11 02:22:43 +00001661 if (EHResumeBlock) return EHResumeBlock;
John McCallad5d61e2010-07-23 21:56:41 +00001662
1663 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1664
1665 // We emit a jump to a notional label at the outermost unwind state.
John McCall8e4c74b2011-08-11 02:22:43 +00001666 EHResumeBlock = createBasicBlock("eh.resume");
1667 Builder.SetInsertPoint(EHResumeBlock);
John McCallad5d61e2010-07-23 21:56:41 +00001668
Reid Klecknerdeeddec2015-02-05 18:56:03 +00001669 const EHPersonality &Personality = EHPersonality::get(*this);
John McCallad5d61e2010-07-23 21:56:41 +00001670
1671 // This can always be a call because we necessarily didn't find
1672 // anything on the EH stack which needs our help.
Benjamin Kramer793bd552012-02-08 12:41:24 +00001673 const char *RethrowName = Personality.CatchallRethrowFn;
Craig Topper8a13c412014-05-21 05:09:00 +00001674 if (RethrowName != nullptr && !isCleanup) {
John McCall882987f2013-02-28 19:01:20 +00001675 EmitRuntimeCall(getCatchallRethrowFn(CGM, RethrowName),
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001676 getExceptionFromSlot())
John McCall9b382dd2011-05-28 21:13:02 +00001677 ->setDoesNotReturn();
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001678 Builder.CreateUnreachable();
1679 Builder.restoreIP(SavedIP);
1680 return EHResumeBlock;
John McCall9b382dd2011-05-28 21:13:02 +00001681 }
1682
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001683 // Recreate the landingpad's return value for the 'resume' instruction.
1684 llvm::Value *Exn = getExceptionFromSlot();
1685 llvm::Value *Sel = getSelectorFromSlot();
John McCallad5d61e2010-07-23 21:56:41 +00001686
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001687 llvm::Type *LPadType = llvm::StructType::get(Exn->getType(),
Reid Kleckneree7cf842014-12-01 22:02:27 +00001688 Sel->getType(), nullptr);
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001689 llvm::Value *LPadVal = llvm::UndefValue::get(LPadType);
1690 LPadVal = Builder.CreateInsertValue(LPadVal, Exn, 0, "lpad.val");
1691 LPadVal = Builder.CreateInsertValue(LPadVal, Sel, 1, "lpad.val");
1692
1693 Builder.CreateResume(LPadVal);
John McCallad5d61e2010-07-23 21:56:41 +00001694 Builder.restoreIP(SavedIP);
John McCall8e4c74b2011-08-11 02:22:43 +00001695 return EHResumeBlock;
John McCallad5d61e2010-07-23 21:56:41 +00001696}
Reid Kleckner543a16c2013-09-16 21:46:30 +00001697
1698void CodeGenFunction::EmitSEHTryStmt(const SEHTryStmt &S) {
Reid Kleckner1d59f992015-01-22 01:36:17 +00001699 // FIXME: Implement SEH on other architectures.
1700 const llvm::Triple &T = CGM.getTarget().getTriple();
1701 if (T.getArch() != llvm::Triple::x86_64 ||
1702 !T.isKnownWindowsMSVCEnvironment()) {
1703 ErrorUnsupported(&S, "__try statement");
1704 return;
1705 }
1706
Reid Kleckneraca01db2015-02-04 22:37:07 +00001707 SEHFinallyInfo FI;
1708 EnterSEHTryStmt(S, FI);
Reid Klecknera5930002015-02-11 21:40:48 +00001709 {
Nico Weber5779f842015-02-12 23:16:11 +00001710 JumpDest TryExit = getJumpDestInCurrentScope("__try.__leave");
1711 SEHTryEpilogueStack.push_back(&TryExit);
1712
Reid Klecknera5930002015-02-11 21:40:48 +00001713 // Disable inlining inside SEH __try scopes.
1714 SaveAndRestore<bool> Saver(IsSEHTryScope, true);
1715 EmitStmt(S.getTryBlock());
Nico Weber5779f842015-02-12 23:16:11 +00001716
1717 if (!TryExit.getBlock()->use_empty())
1718 EmitBlock(TryExit.getBlock(), /*IsFinished=*/true);
1719 else
1720 delete TryExit.getBlock();
1721 SEHTryEpilogueStack.pop_back();
Reid Klecknera5930002015-02-11 21:40:48 +00001722 }
Reid Kleckneraca01db2015-02-04 22:37:07 +00001723 ExitSEHTryStmt(S, FI);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001724}
1725
1726namespace {
1727struct PerformSEHFinally : EHScopeStack::Cleanup {
Reid Kleckneraca01db2015-02-04 22:37:07 +00001728 CodeGenFunction::SEHFinallyInfo *FI;
1729 PerformSEHFinally(CodeGenFunction::SEHFinallyInfo *FI) : FI(FI) {}
1730
Reid Kleckner1d59f992015-01-22 01:36:17 +00001731 void Emit(CodeGenFunction &CGF, Flags F) override {
Reid Kleckneraca01db2015-02-04 22:37:07 +00001732 // Cleanups are emitted at most twice: once for normal control flow and once
1733 // for exception control flow. Branch into the finally block, and remember
1734 // the continuation block so we can branch out later.
1735 if (!FI->FinallyBB) {
1736 FI->FinallyBB = CGF.createBasicBlock("__finally");
1737 FI->FinallyBB->insertInto(CGF.CurFn);
1738 FI->FinallyBB->moveAfter(CGF.Builder.GetInsertBlock());
1739 }
1740
1741 // Set the termination status and branch in.
1742 CGF.Builder.CreateStore(
1743 llvm::ConstantInt::get(CGF.Int8Ty, F.isForEHCleanup()),
1744 CGF.getAbnormalTerminationSlot());
1745 CGF.Builder.CreateBr(FI->FinallyBB);
1746
1747 // Create a continuation block for normal or exceptional control.
1748 if (F.isForEHCleanup()) {
1749 assert(!FI->ResumeBB && "double emission for EH");
1750 FI->ResumeBB = CGF.createBasicBlock("__finally.resume");
1751 CGF.EmitBlock(FI->ResumeBB);
1752 } else {
1753 assert(F.isForNormalCleanup() && !FI->ContBB && "double normal emission");
1754 FI->ContBB = CGF.createBasicBlock("__finally.cont");
1755 CGF.EmitBlock(FI->ContBB);
1756 // Try to keep source order.
1757 FI->ContBB->moveAfter(FI->FinallyBB);
1758 }
Reid Kleckner1d59f992015-01-22 01:36:17 +00001759 }
1760};
1761}
1762
1763/// Create a stub filter function that will ultimately hold the code of the
1764/// filter expression. The EH preparation passes in LLVM will outline the code
1765/// from the main function body into this stub.
1766llvm::Function *
1767CodeGenFunction::GenerateSEHFilterFunction(CodeGenFunction &ParentCGF,
1768 const SEHExceptStmt &Except) {
1769 const Decl *ParentCodeDecl = ParentCGF.CurCodeDecl;
1770 llvm::Function *ParentFn = ParentCGF.CurFn;
1771
1772 Expr *FilterExpr = Except.getFilterExpr();
1773
1774 // Get the mangled function name.
1775 SmallString<128> Name;
1776 {
1777 llvm::raw_svector_ostream OS(Name);
1778 const NamedDecl *Parent = dyn_cast_or_null<NamedDecl>(ParentCodeDecl);
1779 assert(Parent && "FIXME: handle unnamed decls (lambdas, blocks) with SEH");
1780 CGM.getCXXABI().getMangleContext().mangleSEHFilterExpression(Parent, OS);
1781 }
1782
1783 // Arrange a function with the declaration:
1784 // int filt(EXCEPTION_POINTERS *exception_pointers, void *frame_pointer)
1785 QualType RetTy = getContext().IntTy;
1786 FunctionArgList Args;
1787 SEHPointersDecl = ImplicitParamDecl::Create(
1788 getContext(), nullptr, FilterExpr->getLocStart(),
1789 &getContext().Idents.get("exception_pointers"), getContext().VoidPtrTy);
1790 Args.push_back(SEHPointersDecl);
1791 Args.push_back(ImplicitParamDecl::Create(
1792 getContext(), nullptr, FilterExpr->getLocStart(),
1793 &getContext().Idents.get("frame_pointer"), getContext().VoidPtrTy));
1794 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionDeclaration(
1795 RetTy, Args, FunctionType::ExtInfo(), /*isVariadic=*/false);
1796 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
1797 llvm::Function *Fn = llvm::Function::Create(FnTy, ParentFn->getLinkage(),
1798 Name.str(), &CGM.getModule());
1799 // The filter is either in the same comdat as the function, or it's internal.
1800 if (llvm::Comdat *C = ParentFn->getComdat()) {
1801 Fn->setComdat(C);
1802 } else if (ParentFn->hasWeakLinkage() || ParentFn->hasLinkOnceLinkage()) {
1803 // FIXME: Unreachable with Rafael's changes?
1804 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(ParentFn->getName());
1805 ParentFn->setComdat(C);
1806 Fn->setComdat(C);
1807 } else {
1808 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
1809 }
1810
1811 StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args,
1812 FilterExpr->getLocStart(), FilterExpr->getLocStart());
1813
1814 EmitSEHExceptionCodeSave();
1815
1816 // Insert dummy allocas for every local variable in scope. We'll initialize
1817 // them and prune the unused ones after we find out which ones were
1818 // referenced.
1819 for (const auto &DeclPtrs : ParentCGF.LocalDeclMap) {
1820 const Decl *VD = DeclPtrs.first;
1821 llvm::Value *Ptr = DeclPtrs.second;
1822 auto *ValTy = cast<llvm::PointerType>(Ptr->getType())->getElementType();
1823 LocalDeclMap[VD] = CreateTempAlloca(ValTy, Ptr->getName() + ".filt");
1824 }
1825
1826 // Emit the original filter expression, convert to i32, and return.
1827 llvm::Value *R = EmitScalarExpr(FilterExpr);
1828 R = Builder.CreateIntCast(R, CGM.IntTy,
1829 FilterExpr->getType()->isSignedIntegerType());
1830 Builder.CreateStore(R, ReturnValue);
1831
1832 FinishFunction(FilterExpr->getLocEnd());
1833
1834 for (const auto &DeclPtrs : ParentCGF.LocalDeclMap) {
1835 const Decl *VD = DeclPtrs.first;
1836 auto *Alloca = cast<llvm::AllocaInst>(LocalDeclMap[VD]);
1837 if (Alloca->hasNUses(0)) {
1838 Alloca->eraseFromParent();
1839 continue;
1840 }
1841 ErrorUnsupported(FilterExpr,
1842 "SEH filter expression local variable capture");
1843 }
1844
1845 return Fn;
1846}
1847
1848void CodeGenFunction::EmitSEHExceptionCodeSave() {
1849 // Save the exception code in the exception slot to unify exception access in
1850 // the filter function and the landing pad.
1851 // struct EXCEPTION_POINTERS {
1852 // EXCEPTION_RECORD *ExceptionRecord;
1853 // CONTEXT *ContextRecord;
1854 // };
1855 // void *exn.slot =
1856 // (void *)(uintptr_t)exception_pointers->ExceptionRecord->ExceptionCode;
1857 llvm::Value *Ptrs = Builder.CreateLoad(GetAddrOfLocalVar(SEHPointersDecl));
1858 llvm::Type *RecordTy = CGM.Int32Ty->getPointerTo();
1859 llvm::Type *PtrsTy = llvm::StructType::get(RecordTy, CGM.VoidPtrTy, nullptr);
1860 Ptrs = Builder.CreateBitCast(Ptrs, PtrsTy->getPointerTo());
1861 llvm::Value *Rec = Builder.CreateStructGEP(Ptrs, 0);
1862 Rec = Builder.CreateLoad(Rec);
1863 llvm::Value *Code = Builder.CreateLoad(Rec);
1864 Code = Builder.CreateZExt(Code, CGM.IntPtrTy);
1865 // FIXME: Change landing pads to produce {i32, i32} and make the exception
1866 // slot an i32.
1867 Code = Builder.CreateIntToPtr(Code, CGM.VoidPtrTy);
1868 Builder.CreateStore(Code, getExceptionSlot());
1869}
1870
1871llvm::Value *CodeGenFunction::EmitSEHExceptionInfo() {
1872 // Sema should diagnose calling this builtin outside of a filter context, but
1873 // don't crash if we screw up.
1874 if (!SEHPointersDecl)
1875 return llvm::UndefValue::get(Int8PtrTy);
1876 return Builder.CreateLoad(GetAddrOfLocalVar(SEHPointersDecl));
1877}
1878
1879llvm::Value *CodeGenFunction::EmitSEHExceptionCode() {
1880 // If we're in a landing pad or filter function, the exception slot contains
1881 // the code.
1882 assert(ExceptionSlot);
1883 llvm::Value *Code =
1884 Builder.CreatePtrToInt(getExceptionFromSlot(), CGM.IntPtrTy);
1885 return Builder.CreateTrunc(Code, CGM.Int32Ty);
1886}
1887
Reid Kleckneraca01db2015-02-04 22:37:07 +00001888llvm::Value *CodeGenFunction::EmitSEHAbnormalTermination() {
1889 // Load from the abnormal termination slot. It will be uninitialized outside
1890 // of __finally blocks, which we should warn or error on.
1891 llvm::Value *IsEH = Builder.CreateLoad(getAbnormalTerminationSlot());
1892 return Builder.CreateZExt(IsEH, Int32Ty);
1893}
1894
1895void CodeGenFunction::EnterSEHTryStmt(const SEHTryStmt &S, SEHFinallyInfo &FI) {
Sean Silvab1287ee2015-02-05 01:20:26 +00001896 if (S.getFinallyHandler()) {
Reid Kleckner1d59f992015-01-22 01:36:17 +00001897 // Push a cleanup for __finally blocks.
Reid Kleckneraca01db2015-02-04 22:37:07 +00001898 EHStack.pushCleanup<PerformSEHFinally>(NormalAndEHCleanup, &FI);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001899 return;
1900 }
1901
1902 // Otherwise, we must have an __except block.
1903 SEHExceptStmt *Except = S.getExceptHandler();
1904 assert(Except);
1905 EHCatchScope *CatchScope = EHStack.pushCatch(1);
Reid Kleckner2a2e1562015-01-22 02:25:56 +00001906
1907 // If the filter is known to evaluate to 1, then we can use the clause "catch
1908 // i8* null".
1909 llvm::Constant *C =
1910 CGM.EmitConstantExpr(Except->getFilterExpr(), getContext().IntTy, this);
1911 if (C && C->isOneValue()) {
1912 CatchScope->setCatchAllHandler(0, createBasicBlock("__except"));
1913 return;
1914 }
1915
1916 // In general, we have to emit an outlined filter function. Use the function
1917 // in place of the RTTI typeinfo global that C++ EH uses.
Reid Kleckner1d59f992015-01-22 01:36:17 +00001918 CodeGenFunction FilterCGF(CGM, /*suppressNewContext=*/true);
1919 llvm::Function *FilterFunc =
1920 FilterCGF.GenerateSEHFilterFunction(*this, *Except);
1921 llvm::Constant *OpaqueFunc =
1922 llvm::ConstantExpr::getBitCast(FilterFunc, Int8PtrTy);
1923 CatchScope->setHandler(0, OpaqueFunc, createBasicBlock("__except"));
1924}
1925
Reid Kleckneraca01db2015-02-04 22:37:07 +00001926void CodeGenFunction::ExitSEHTryStmt(const SEHTryStmt &S, SEHFinallyInfo &FI) {
Reid Kleckner1d59f992015-01-22 01:36:17 +00001927 // Just pop the cleanup if it's a __finally block.
Reid Kleckneraca01db2015-02-04 22:37:07 +00001928 if (const SEHFinallyStmt *Finally = S.getFinallyHandler()) {
Reid Kleckner1d59f992015-01-22 01:36:17 +00001929 PopCleanupBlock();
Reid Kleckner16f9a6b2015-02-05 00:58:46 +00001930 assert(FI.ContBB && "did not emit normal cleanup");
Reid Kleckneraca01db2015-02-04 22:37:07 +00001931
1932 // Emit the code into FinallyBB.
1933 Builder.SetInsertPoint(FI.FinallyBB);
1934 EmitStmt(Finally->getBlock());
1935
Reid Kleckner16f9a6b2015-02-05 00:58:46 +00001936 // If the finally block doesn't fall through, we don't need these blocks.
1937 if (!HaveInsertPoint()) {
1938 FI.ContBB->eraseFromParent();
1939 if (FI.ResumeBB)
1940 FI.ResumeBB->eraseFromParent();
1941 return;
1942 }
1943
Reid Kleckneraca01db2015-02-04 22:37:07 +00001944 if (FI.ResumeBB) {
1945 llvm::Value *IsEH = Builder.CreateLoad(getAbnormalTerminationSlot(),
1946 "abnormal.termination");
1947 IsEH = Builder.CreateICmpEQ(IsEH, llvm::ConstantInt::get(Int8Ty, 0));
1948 Builder.CreateCondBr(IsEH, FI.ContBB, FI.ResumeBB);
1949 } else {
1950 // There was nothing exceptional in the try body, so we only have normal
1951 // control flow.
1952 Builder.CreateBr(FI.ContBB);
1953 }
1954
1955 Builder.SetInsertPoint(FI.ContBB);
1956
Reid Kleckner1d59f992015-01-22 01:36:17 +00001957 return;
1958 }
1959
1960 // Otherwise, we must have an __except block.
Reid Kleckneraca01db2015-02-04 22:37:07 +00001961 const SEHExceptStmt *Except = S.getExceptHandler();
Reid Kleckner1d59f992015-01-22 01:36:17 +00001962 assert(Except && "__try must have __finally xor __except");
1963 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1964
1965 // Don't emit the __except block if the __try block lacked invokes.
1966 // TODO: Model unwind edges from instructions, either with iload / istore or
1967 // a try body function.
1968 if (!CatchScope.hasEHBranches()) {
1969 CatchScope.clearHandlerBlocks();
1970 EHStack.popCatch();
1971 return;
1972 }
1973
1974 // The fall-through block.
1975 llvm::BasicBlock *ContBB = createBasicBlock("__try.cont");
1976
1977 // We just emitted the body of the __try; jump to the continue block.
1978 if (HaveInsertPoint())
1979 Builder.CreateBr(ContBB);
1980
1981 // Check if our filter function returned true.
1982 emitCatchDispatchBlock(*this, CatchScope);
1983
1984 // Grab the block before we pop the handler.
1985 llvm::BasicBlock *ExceptBB = CatchScope.getHandler(0).Block;
1986 EHStack.popCatch();
1987
1988 EmitBlockAfterUses(ExceptBB);
1989
1990 // Emit the __except body.
1991 EmitStmt(Except->getBlock());
1992
Reid Kleckner3a417c32015-01-30 22:16:45 +00001993 if (HaveInsertPoint())
1994 Builder.CreateBr(ContBB);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001995
1996 EmitBlock(ContBB);
Reid Kleckner543a16c2013-09-16 21:46:30 +00001997}
Nico Weber9b982072014-07-07 00:12:30 +00001998
1999void CodeGenFunction::EmitSEHLeaveStmt(const SEHLeaveStmt &S) {
Nico Weber5779f842015-02-12 23:16:11 +00002000 // If this code is reachable then emit a stop point (if generating
2001 // debug info). We have to do this ourselves because we are on the
2002 // "simple" statement path.
2003 if (HaveInsertPoint())
2004 EmitStopPoint(&S);
2005
2006 assert(!SEHTryEpilogueStack.empty() &&
2007 "sema should have rejected this __leave");
2008 EmitBranchThroughCleanup(*SEHTryEpilogueStack.back());
Nico Weber9b982072014-07-07 00:12:30 +00002009}