blob: 9da910d9d0810869d954864330e3ca314e99c074 [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"
John McCalled1ae862011-01-28 11:13:47 +000015#include "CGCleanup.h"
Benjamin Kramer793bd552012-02-08 12:41:24 +000016#include "CGObjCRuntime.h"
John McCall5add20c2010-07-20 22:17:55 +000017#include "TargetInfo.h"
Benjamin Kramer793bd552012-02-08 12:41:24 +000018#include "clang/AST/StmtCXX.h"
Chandler Carruth4b417452013-01-19 08:09:44 +000019#include "clang/AST/StmtObjC.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000020#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000021#include "llvm/IR/Intrinsics.h"
John McCallbd309292010-07-06 01:34:17 +000022
Anders Carlsson4b08db72009-10-30 01:42:31 +000023using namespace clang;
24using namespace CodeGen;
25
John McCall2c33ba82013-02-12 03:51:38 +000026static llvm::Constant *getAllocateExceptionFn(CodeGenModule &CGM) {
Anders Carlsson32e1b1c2009-10-30 02:27:02 +000027 // void *__cxa_allocate_exception(size_t thrown_size);
Mike Stump75546b82009-12-10 00:06:18 +000028
Chris Lattner2192fe52011-07-18 04:24:23 +000029 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +000030 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.SizeTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000031
John McCall2c33ba82013-02-12 03:51:38 +000032 return CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
Anders Carlsson32e1b1c2009-10-30 02:27:02 +000033}
34
John McCall2c33ba82013-02-12 03:51:38 +000035static llvm::Constant *getFreeExceptionFn(CodeGenModule &CGM) {
Mike Stump33270212009-12-02 07:41:41 +000036 // void __cxa_free_exception(void *thrown_exception);
Mike Stump75546b82009-12-10 00:06:18 +000037
Chris Lattner2192fe52011-07-18 04:24:23 +000038 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +000039 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000040
John McCall2c33ba82013-02-12 03:51:38 +000041 return CGM.CreateRuntimeFunction(FTy, "__cxa_free_exception");
Mike Stump33270212009-12-02 07:41:41 +000042}
43
John McCall2c33ba82013-02-12 03:51:38 +000044static llvm::Constant *getThrowFn(CodeGenModule &CGM) {
Mike Stump75546b82009-12-10 00:06:18 +000045 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
Mike Stump33270212009-12-02 07:41:41 +000046 // void (*dest) (void *));
Anders Carlsson32e1b1c2009-10-30 02:27:02 +000047
John McCall2c33ba82013-02-12 03:51:38 +000048 llvm::Type *Args[3] = { CGM.Int8PtrTy, CGM.Int8PtrTy, CGM.Int8PtrTy };
Chris Lattner2192fe52011-07-18 04:24:23 +000049 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +000050 llvm::FunctionType::get(CGM.VoidTy, Args, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000051
John McCall2c33ba82013-02-12 03:51:38 +000052 return CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
Anders Carlsson32e1b1c2009-10-30 02:27:02 +000053}
54
John McCall2c33ba82013-02-12 03:51:38 +000055static llvm::Constant *getReThrowFn(CodeGenModule &CGM) {
Mike Stump33270212009-12-02 07:41:41 +000056 // void __cxa_rethrow();
Mike Stumpd1782cc2009-11-20 00:56:31 +000057
Chris Lattner2192fe52011-07-18 04:24:23 +000058 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +000059 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000060
John McCall2c33ba82013-02-12 03:51:38 +000061 return CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
Mike Stumpd1782cc2009-11-20 00:56:31 +000062}
63
John McCall2c33ba82013-02-12 03:51:38 +000064static llvm::Constant *getGetExceptionPtrFn(CodeGenModule &CGM) {
John McCallbd309292010-07-06 01:34:17 +000065 // void *__cxa_get_exception_ptr(void*);
John McCallbd309292010-07-06 01:34:17 +000066
Chris Lattner2192fe52011-07-18 04:24:23 +000067 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +000068 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
John McCallbd309292010-07-06 01:34:17 +000069
John McCall2c33ba82013-02-12 03:51:38 +000070 return CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
John McCallbd309292010-07-06 01:34:17 +000071}
72
John McCall2c33ba82013-02-12 03:51:38 +000073static llvm::Constant *getBeginCatchFn(CodeGenModule &CGM) {
John McCallbd309292010-07-06 01:34:17 +000074 // void *__cxa_begin_catch(void*);
Mike Stump58ef18b2009-11-20 23:44:51 +000075
Chris Lattner2192fe52011-07-18 04:24:23 +000076 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +000077 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000078
John McCall2c33ba82013-02-12 03:51:38 +000079 return CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
Mike Stump58ef18b2009-11-20 23:44:51 +000080}
81
John McCall2c33ba82013-02-12 03:51:38 +000082static llvm::Constant *getEndCatchFn(CodeGenModule &CGM) {
Mike Stump33270212009-12-02 07:41:41 +000083 // void __cxa_end_catch();
Mike Stump58ef18b2009-11-20 23:44:51 +000084
Chris Lattner2192fe52011-07-18 04:24:23 +000085 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +000086 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000087
John McCall2c33ba82013-02-12 03:51:38 +000088 return CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
Mike Stump58ef18b2009-11-20 23:44:51 +000089}
90
John McCall2c33ba82013-02-12 03:51:38 +000091static llvm::Constant *getUnexpectedFn(CodeGenModule &CGM) {
Richard Smith2f7aa192013-06-20 23:03:35 +000092 // void __cxa_call_unexpected(void *thrown_exception);
Mike Stump1d849212009-12-07 23:38:24 +000093
Chris Lattner2192fe52011-07-18 04:24:23 +000094 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +000095 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000096
John McCall2c33ba82013-02-12 03:51:38 +000097 return CGM.CreateRuntimeFunction(FTy, "__cxa_call_unexpected");
Mike Stump1d849212009-12-07 23:38:24 +000098}
99
John McCall2c33ba82013-02-12 03:51:38 +0000100static llvm::Constant *getTerminateFn(CodeGenModule &CGM) {
Mike Stump33270212009-12-02 07:41:41 +0000101 // void __terminate();
102
Chris Lattner2192fe52011-07-18 04:24:23 +0000103 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +0000104 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +0000105
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000106 StringRef name;
John McCall9de19782011-07-06 01:22:26 +0000107
108 // In C++, use std::terminate().
John McCall2c33ba82013-02-12 03:51:38 +0000109 if (CGM.getLangOpts().CPlusPlus)
John McCall9de19782011-07-06 01:22:26 +0000110 name = "_ZSt9terminatev"; // FIXME: mangling!
John McCall2c33ba82013-02-12 03:51:38 +0000111 else if (CGM.getLangOpts().ObjC1 &&
112 CGM.getLangOpts().ObjCRuntime.hasTerminate())
John McCall9de19782011-07-06 01:22:26 +0000113 name = "objc_terminate";
114 else
115 name = "abort";
John McCall2c33ba82013-02-12 03:51:38 +0000116 return CGM.CreateRuntimeFunction(FTy, name);
David Chisnallf9c42252010-05-17 13:49:20 +0000117}
118
John McCall2c33ba82013-02-12 03:51:38 +0000119static llvm::Constant *getCatchallRethrowFn(CodeGenModule &CGM,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000120 StringRef Name) {
Chris Lattner2192fe52011-07-18 04:24:23 +0000121 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +0000122 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
John McCall36ea3722010-07-17 00:43:08 +0000123
John McCall2c33ba82013-02-12 03:51:38 +0000124 return CGM.CreateRuntimeFunction(FTy, Name);
John McCallbd309292010-07-06 01:34:17 +0000125}
126
Benjamin Kramer793bd552012-02-08 12:41:24 +0000127namespace {
128 /// The exceptions personality for a function.
129 struct EHPersonality {
130 const char *PersonalityFn;
131
132 // If this is non-null, this personality requires a non-standard
133 // function for rethrowing an exception after a catchall cleanup.
134 // This function must have prototype void(void*).
135 const char *CatchallRethrowFn;
136
137 static const EHPersonality &get(const LangOptions &Lang);
138 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;
Benjamin Kramer793bd552012-02-08 12:41:24 +0000148 };
149}
150
Craig Topper8a13c412014-05-21 05:09:00 +0000151const EHPersonality EHPersonality::GNU_C = { "__gcc_personality_v0", nullptr };
Benjamin Kramer793bd552012-02-08 12:41:24 +0000152const EHPersonality
Craig Topper8a13c412014-05-21 05:09:00 +0000153EHPersonality::GNU_C_SJLJ = { "__gcc_personality_sj0", nullptr };
154const EHPersonality
Reid Kleckner8f45c9c2014-09-15 17:19:16 +0000155EHPersonality::GNU_C_SEH = { "__gcc_personality_seh0", nullptr };
156const EHPersonality
Craig Topper8a13c412014-05-21 05:09:00 +0000157EHPersonality::NeXT_ObjC = { "__objc_personality_v0", nullptr };
158const EHPersonality
159EHPersonality::GNU_CPlusPlus = { "__gxx_personality_v0", nullptr };
160const EHPersonality
161EHPersonality::GNU_CPlusPlus_SJLJ = { "__gxx_personality_sj0", nullptr };
Benjamin Kramer793bd552012-02-08 12:41:24 +0000162const EHPersonality
Reid Kleckner8f45c9c2014-09-15 17:19:16 +0000163EHPersonality::GNU_CPlusPlus_SEH = { "__gxx_personality_seh0", nullptr };
164const EHPersonality
Benjamin Kramer793bd552012-02-08 12:41:24 +0000165EHPersonality::GNU_ObjC = {"__gnu_objc_personality_v0", "objc_exception_throw"};
166const EHPersonality
Craig Topper8a13c412014-05-21 05:09:00 +0000167EHPersonality::GNU_ObjCXX = { "__gnustep_objcxx_personality_v0", nullptr };
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000168const EHPersonality
Craig Topper8a13c412014-05-21 05:09:00 +0000169EHPersonality::GNUstep_ObjC = { "__gnustep_objc_personality_v0", nullptr };
John McCall36ea3722010-07-17 00:43:08 +0000170
171static const EHPersonality &getCPersonality(const LangOptions &L) {
John McCall2faab302010-11-07 02:35:25 +0000172 if (L.SjLjExceptions)
173 return EHPersonality::GNU_C_SJLJ;
Reid Kleckner8f45c9c2014-09-15 17:19:16 +0000174 if (L.SEHExceptions)
175 return EHPersonality::GNU_C_SEH;
John McCall36ea3722010-07-17 00:43:08 +0000176 return EHPersonality::GNU_C;
177}
178
179static const EHPersonality &getObjCPersonality(const LangOptions &L) {
John McCall5fb5df92012-06-20 06:18:46 +0000180 switch (L.ObjCRuntime.getKind()) {
181 case ObjCRuntime::FragileMacOSX:
182 return getCPersonality(L);
183 case ObjCRuntime::MacOSX:
184 case ObjCRuntime::iOS:
185 return EHPersonality::NeXT_ObjC;
David Chisnallb601c962012-07-03 20:49:52 +0000186 case ObjCRuntime::GNUstep:
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000187 if (L.ObjCRuntime.getVersion() >= VersionTuple(1, 7))
188 return EHPersonality::GNUstep_ObjC;
189 // fallthrough
David Chisnallb601c962012-07-03 20:49:52 +0000190 case ObjCRuntime::GCC:
John McCall775086e2012-07-12 02:07:58 +0000191 case ObjCRuntime::ObjFW:
John McCall36ea3722010-07-17 00:43:08 +0000192 return EHPersonality::GNU_ObjC;
John McCallbd309292010-07-06 01:34:17 +0000193 }
John McCall5fb5df92012-06-20 06:18:46 +0000194 llvm_unreachable("bad runtime kind");
John McCallbd309292010-07-06 01:34:17 +0000195}
196
John McCall36ea3722010-07-17 00:43:08 +0000197static const EHPersonality &getCXXPersonality(const LangOptions &L) {
198 if (L.SjLjExceptions)
199 return EHPersonality::GNU_CPlusPlus_SJLJ;
Reid Kleckner8f45c9c2014-09-15 17:19:16 +0000200 else if (L.SEHExceptions)
201 return EHPersonality::GNU_CPlusPlus_SEH;
John McCallbd309292010-07-06 01:34:17 +0000202 else
John McCall36ea3722010-07-17 00:43:08 +0000203 return EHPersonality::GNU_CPlusPlus;
John McCallbd309292010-07-06 01:34:17 +0000204}
205
206/// Determines the personality function to use when both C++
207/// and Objective-C exceptions are being caught.
John McCall36ea3722010-07-17 00:43:08 +0000208static const EHPersonality &getObjCXXPersonality(const LangOptions &L) {
John McCall5fb5df92012-06-20 06:18:46 +0000209 switch (L.ObjCRuntime.getKind()) {
John McCallbd309292010-07-06 01:34:17 +0000210 // The ObjC personality defers to the C++ personality for non-ObjC
211 // handlers. Unlike the C++ case, we use the same personality
212 // function on targets using (backend-driven) SJLJ EH.
John McCall5fb5df92012-06-20 06:18:46 +0000213 case ObjCRuntime::MacOSX:
214 case ObjCRuntime::iOS:
215 return EHPersonality::NeXT_ObjC;
John McCallbd309292010-07-06 01:34:17 +0000216
John McCall5fb5df92012-06-20 06:18:46 +0000217 // In the fragile ABI, just use C++ exception handling and hope
218 // they're not doing crazy exception mixing.
219 case ObjCRuntime::FragileMacOSX:
220 return getCXXPersonality(L);
David Chisnallf9c42252010-05-17 13:49:20 +0000221
David Chisnallb601c962012-07-03 20:49:52 +0000222 // The GCC runtime's personality function inherently doesn't support
John McCall36ea3722010-07-17 00:43:08 +0000223 // mixed EH. Use the C++ personality just to avoid returning null.
David Chisnallb601c962012-07-03 20:49:52 +0000224 case ObjCRuntime::GCC:
John McCall775086e2012-07-12 02:07:58 +0000225 case ObjCRuntime::ObjFW: // XXX: this will change soon
David Chisnallb601c962012-07-03 20:49:52 +0000226 return EHPersonality::GNU_ObjC;
227 case ObjCRuntime::GNUstep:
John McCall5fb5df92012-06-20 06:18:46 +0000228 return EHPersonality::GNU_ObjCXX;
229 }
230 llvm_unreachable("bad runtime kind");
John McCallbd309292010-07-06 01:34:17 +0000231}
232
John McCall36ea3722010-07-17 00:43:08 +0000233const EHPersonality &EHPersonality::get(const LangOptions &L) {
234 if (L.CPlusPlus && L.ObjC1)
235 return getObjCXXPersonality(L);
236 else if (L.CPlusPlus)
237 return getCXXPersonality(L);
238 else if (L.ObjC1)
239 return getObjCPersonality(L);
John McCallbd309292010-07-06 01:34:17 +0000240 else
John McCall36ea3722010-07-17 00:43:08 +0000241 return getCPersonality(L);
242}
John McCallbd309292010-07-06 01:34:17 +0000243
John McCall0bdb1fd2010-09-16 06:16:50 +0000244static llvm::Constant *getPersonalityFn(CodeGenModule &CGM,
John McCall36ea3722010-07-17 00:43:08 +0000245 const EHPersonality &Personality) {
John McCall36ea3722010-07-17 00:43:08 +0000246 llvm::Constant *Fn =
Chris Lattnerece04092012-02-07 00:39:47 +0000247 CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.Int32Ty, true),
Benjamin Kramer793bd552012-02-08 12:41:24 +0000248 Personality.PersonalityFn);
John McCall0bdb1fd2010-09-16 06:16:50 +0000249 return Fn;
250}
251
252static llvm::Constant *getOpaquePersonalityFn(CodeGenModule &CGM,
253 const EHPersonality &Personality) {
254 llvm::Constant *Fn = getPersonalityFn(CGM, Personality);
John McCallad7c5c12011-02-08 08:22:06 +0000255 return llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
John McCall0bdb1fd2010-09-16 06:16:50 +0000256}
257
258/// Check whether a personality function could reasonably be swapped
259/// for a C++ personality function.
260static bool PersonalityHasOnlyCXXUses(llvm::Constant *Fn) {
Chandler Carruth4d01fff2014-03-09 03:16:50 +0000261 for (llvm::User *U : Fn->users()) {
John McCall0bdb1fd2010-09-16 06:16:50 +0000262 // Conditionally white-list bitcasts.
Chandler Carruth4d01fff2014-03-09 03:16:50 +0000263 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(U)) {
John McCall0bdb1fd2010-09-16 06:16:50 +0000264 if (CE->getOpcode() != llvm::Instruction::BitCast) return false;
265 if (!PersonalityHasOnlyCXXUses(CE))
266 return false;
267 continue;
268 }
269
Bill Wendling58e58fe2011-09-19 22:08:36 +0000270 // Otherwise, it has to be a landingpad instruction.
Chandler Carruth4d01fff2014-03-09 03:16:50 +0000271 llvm::LandingPadInst *LPI = dyn_cast<llvm::LandingPadInst>(U);
Bill Wendling58e58fe2011-09-19 22:08:36 +0000272 if (!LPI) return false;
John McCall0bdb1fd2010-09-16 06:16:50 +0000273
Bill Wendling58e58fe2011-09-19 22:08:36 +0000274 for (unsigned I = 0, E = LPI->getNumClauses(); I != E; ++I) {
John McCall0bdb1fd2010-09-16 06:16:50 +0000275 // Look for something that would've been returned by the ObjC
276 // runtime's GetEHType() method.
Bill Wendling58e58fe2011-09-19 22:08:36 +0000277 llvm::Value *Val = LPI->getClause(I)->stripPointerCasts();
278 if (LPI->isCatch(I)) {
279 // Check if the catch value has the ObjC prefix.
Bill Wendling5d7469e2011-09-20 00:40:19 +0000280 if (llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Val))
281 // ObjC EH selector entries are always global variables with
282 // names starting like this.
283 if (GV->getName().startswith("OBJC_EHTYPE"))
284 return false;
Bill Wendling58e58fe2011-09-19 22:08:36 +0000285 } else {
286 // Check if any of the filter values have the ObjC prefix.
287 llvm::Constant *CVal = cast<llvm::Constant>(Val);
288 for (llvm::User::op_iterator
289 II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II) {
Bill Wendling5d7469e2011-09-20 00:40:19 +0000290 if (llvm::GlobalVariable *GV =
291 cast<llvm::GlobalVariable>((*II)->stripPointerCasts()))
292 // ObjC EH selector entries are always global variables with
293 // names starting like this.
294 if (GV->getName().startswith("OBJC_EHTYPE"))
295 return false;
Bill Wendling58e58fe2011-09-19 22:08:36 +0000296 }
297 }
John McCall0bdb1fd2010-09-16 06:16:50 +0000298 }
299 }
300
301 return true;
302}
303
304/// Try to use the C++ personality function in ObjC++. Not doing this
305/// can cause some incompatibilities with gcc, which is more
306/// aggressive about only using the ObjC++ personality in a function
307/// when it really needs it.
308void CodeGenModule::SimplifyPersonality() {
John McCall0bdb1fd2010-09-16 06:16:50 +0000309 // If we're not in ObjC++ -fexceptions, there's nothing to do.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000310 if (!LangOpts.CPlusPlus || !LangOpts.ObjC1 || !LangOpts.Exceptions)
John McCall0bdb1fd2010-09-16 06:16:50 +0000311 return;
312
John McCall3c223932012-11-14 17:48:31 +0000313 // Both the problem this endeavors to fix and the way the logic
314 // above works is specific to the NeXT runtime.
315 if (!LangOpts.ObjCRuntime.isNeXTFamily())
316 return;
317
David Blaikiebbafb8a2012-03-11 07:00:24 +0000318 const EHPersonality &ObjCXX = EHPersonality::get(LangOpts);
319 const EHPersonality &CXX = getCXXPersonality(LangOpts);
Benjamin Kramer793bd552012-02-08 12:41:24 +0000320 if (&ObjCXX == &CXX)
John McCall0bdb1fd2010-09-16 06:16:50 +0000321 return;
322
Benjamin Kramer793bd552012-02-08 12:41:24 +0000323 assert(std::strcmp(ObjCXX.PersonalityFn, CXX.PersonalityFn) != 0 &&
324 "Different EHPersonalities using the same personality function.");
325
326 llvm::Function *Fn = getModule().getFunction(ObjCXX.PersonalityFn);
John McCall0bdb1fd2010-09-16 06:16:50 +0000327
328 // Nothing to do if it's unused.
329 if (!Fn || Fn->use_empty()) return;
330
331 // Can't do the optimization if it has non-C++ uses.
332 if (!PersonalityHasOnlyCXXUses(Fn)) return;
333
334 // Create the C++ personality function and kill off the old
335 // function.
336 llvm::Constant *CXXFn = getPersonalityFn(*this, CXX);
337
338 // This can happen if the user is screwing with us.
339 if (Fn->getType() != CXXFn->getType()) return;
340
341 Fn->replaceAllUsesWith(CXXFn);
342 Fn->eraseFromParent();
John McCallbd309292010-07-06 01:34:17 +0000343}
344
345/// Returns the value to inject into a selector to indicate the
346/// presence of a catch-all.
347static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
348 // Possibly we should use @llvm.eh.catch.all.value here.
John McCallad7c5c12011-02-08 08:22:06 +0000349 return llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
John McCallbd309292010-07-06 01:34:17 +0000350}
351
John McCallbb026012010-07-13 21:17:51 +0000352namespace {
353 /// A cleanup to free the exception object if its initialization
354 /// throws.
John McCall5fcf8da2011-07-12 00:15:30 +0000355 struct FreeException : EHScopeStack::Cleanup {
356 llvm::Value *exn;
357 FreeException(llvm::Value *exn) : exn(exn) {}
Craig Topper4f12f102014-03-12 06:41:41 +0000358 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +0000359 CGF.EmitNounwindRuntimeCall(getFreeExceptionFn(CGF.CGM), exn);
John McCallbb026012010-07-13 21:17:51 +0000360 }
361 };
362}
363
John McCall2e6567a2010-04-22 01:10:34 +0000364// Emits an exception expression into the given location. This
365// differs from EmitAnyExprToMem only in that, if a final copy-ctor
366// call is required, an exception within that copy ctor causes
367// std::terminate to be invoked.
John McCalle4df6c82011-01-28 08:37:24 +0000368static void EmitAnyExprToExn(CodeGenFunction &CGF, const Expr *e,
369 llvm::Value *addr) {
John McCallbd309292010-07-06 01:34:17 +0000370 // Make sure the exception object is cleaned up if there's an
371 // exception during initialization.
John McCalle4df6c82011-01-28 08:37:24 +0000372 CGF.pushFullExprCleanup<FreeException>(EHCleanup, addr);
373 EHScopeStack::stable_iterator cleanup = CGF.EHStack.stable_begin();
John McCall2e6567a2010-04-22 01:10:34 +0000374
375 // __cxa_allocate_exception returns a void*; we need to cast this
376 // to the appropriate type for the object.
Chris Lattner2192fe52011-07-18 04:24:23 +0000377 llvm::Type *ty = CGF.ConvertTypeForMem(e->getType())->getPointerTo();
John McCalle4df6c82011-01-28 08:37:24 +0000378 llvm::Value *typedAddr = CGF.Builder.CreateBitCast(addr, ty);
John McCall2e6567a2010-04-22 01:10:34 +0000379
380 // FIXME: this isn't quite right! If there's a final unelided call
381 // to a copy constructor, then according to [except.terminate]p1 we
382 // must call std::terminate() if that constructor throws, because
383 // technically that copy occurs after the exception expression is
384 // evaluated but before the exception is caught. But the best way
385 // to handle that is to teach EmitAggExpr to do the final copy
386 // differently if it can't be elided.
Chad Rosier615ed1a2012-03-29 17:37:10 +0000387 CGF.EmitAnyExprToMem(e, typedAddr, e->getType().getQualifiers(),
388 /*IsInit*/ true);
John McCall2e6567a2010-04-22 01:10:34 +0000389
John McCalle4df6c82011-01-28 08:37:24 +0000390 // Deactivate the cleanup block.
John McCallf4beacd2011-11-10 10:43:54 +0000391 CGF.DeactivateCleanupBlock(cleanup, cast<llvm::Instruction>(typedAddr));
Mike Stump54066142009-12-01 03:41:18 +0000392}
393
John McCallbd309292010-07-06 01:34:17 +0000394llvm::Value *CodeGenFunction::getExceptionSlot() {
John McCall9b382dd2011-05-28 21:13:02 +0000395 if (!ExceptionSlot)
396 ExceptionSlot = CreateTempAlloca(Int8PtrTy, "exn.slot");
John McCallbd309292010-07-06 01:34:17 +0000397 return ExceptionSlot;
Mike Stump54066142009-12-01 03:41:18 +0000398}
399
John McCall9b382dd2011-05-28 21:13:02 +0000400llvm::Value *CodeGenFunction::getEHSelectorSlot() {
401 if (!EHSelectorSlot)
402 EHSelectorSlot = CreateTempAlloca(Int32Ty, "ehselector.slot");
403 return EHSelectorSlot;
404}
405
Bill Wendling79a70e42011-09-15 18:57:19 +0000406llvm::Value *CodeGenFunction::getExceptionFromSlot() {
407 return Builder.CreateLoad(getExceptionSlot(), "exn");
408}
409
410llvm::Value *CodeGenFunction::getSelectorFromSlot() {
411 return Builder.CreateLoad(getEHSelectorSlot(), "sel");
412}
413
Richard Smithea852322013-05-07 21:53:22 +0000414void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E,
415 bool KeepInsertionPoint) {
Reid Klecknera82b5d82014-05-05 21:12:12 +0000416 if (CGM.getTarget().getTriple().isWindowsMSVCEnvironment()) {
417 ErrorUnsupported(E, "throw expression");
418 return;
419 }
420
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000421 if (!E->getSubExpr()) {
Craig Topper5fc8fc22014-08-27 06:28:36 +0000422 EmitNoreturnRuntimeCallOrInvoke(getReThrowFn(CGM), None);
Douglas Gregorc278d1b2010-05-16 00:44:00 +0000423
John McCall20f6ab82011-01-12 03:41:02 +0000424 // throw is an expression, and the expression emitters expect us
425 // to leave ourselves at a valid insertion point.
Richard Smithea852322013-05-07 21:53:22 +0000426 if (KeepInsertionPoint)
427 EmitBlock(createBasicBlock("throw.cont"));
John McCall20f6ab82011-01-12 03:41:02 +0000428
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000429 return;
430 }
Mike Stump75546b82009-12-10 00:06:18 +0000431
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000432 QualType ThrowType = E->getSubExpr()->getType();
Mike Stump75546b82009-12-10 00:06:18 +0000433
Fariborz Jahanian1eab0522013-01-10 19:02:56 +0000434 if (ThrowType->isObjCObjectPointerType()) {
435 const Stmt *ThrowStmt = E->getSubExpr();
436 const ObjCAtThrowStmt S(E->getExprLoc(),
437 const_cast<Stmt *>(ThrowStmt));
438 CGM.getObjCRuntime().EmitThrowStmt(*this, S, false);
439 // This will clear insertion point which was not cleared in
440 // call to EmitThrowStmt.
Richard Smithea852322013-05-07 21:53:22 +0000441 if (KeepInsertionPoint)
442 EmitBlock(createBasicBlock("throw.cont"));
Fariborz Jahanian1eab0522013-01-10 19:02:56 +0000443 return;
444 }
445
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000446 // Now allocate the exception object.
Chris Lattner2192fe52011-07-18 04:24:23 +0000447 llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
John McCall21886962010-04-21 10:05:39 +0000448 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
Mike Stump75546b82009-12-10 00:06:18 +0000449
John McCall2c33ba82013-02-12 03:51:38 +0000450 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(CGM);
John McCallbd309292010-07-06 01:34:17 +0000451 llvm::CallInst *ExceptionPtr =
John McCall882987f2013-02-28 19:01:20 +0000452 EmitNounwindRuntimeCall(AllocExceptionFn,
453 llvm::ConstantInt::get(SizeTy, TypeSize),
454 "exception");
Anders Carlssonafd1edb2009-12-11 00:32:37 +0000455
John McCall2e6567a2010-04-22 01:10:34 +0000456 EmitAnyExprToExn(*this, E->getSubExpr(), ExceptionPtr);
Mike Stump75546b82009-12-10 00:06:18 +0000457
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000458 // Now throw the exception.
Anders Carlssonba840fb2011-01-24 01:59:49 +0000459 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
460 /*ForEH=*/true);
John McCall2e6567a2010-04-22 01:10:34 +0000461
462 // The address of the destructor. If the exception type has a
463 // trivial destructor (or isn't a record), we just pass null.
Craig Topper8a13c412014-05-21 05:09:00 +0000464 llvm::Constant *Dtor = nullptr;
John McCall2e6567a2010-04-22 01:10:34 +0000465 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
466 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
467 if (!Record->hasTrivialDestructor()) {
Douglas Gregorbac74902010-07-01 14:13:13 +0000468 CXXDestructorDecl *DtorD = Record->getDestructor();
Rafael Espindola1ac0ec82014-09-11 15:42:06 +0000469 Dtor = CGM.getAddrOfCXXStructor(DtorD, StructorType::Complete);
John McCall2e6567a2010-04-22 01:10:34 +0000470 Dtor = llvm::ConstantExpr::getBitCast(Dtor, Int8PtrTy);
471 }
472 }
473 if (!Dtor) Dtor = llvm::Constant::getNullValue(Int8PtrTy);
Mike Stump75546b82009-12-10 00:06:18 +0000474
John McCall882987f2013-02-28 19:01:20 +0000475 llvm::Value *args[] = { ExceptionPtr, TypeInfo, Dtor };
476 EmitNoreturnRuntimeCallOrInvoke(getThrowFn(CGM), args);
Mike Stump75546b82009-12-10 00:06:18 +0000477
John McCall20f6ab82011-01-12 03:41:02 +0000478 // throw is an expression, and the expression emitters expect us
479 // to leave ourselves at a valid insertion point.
Richard Smithea852322013-05-07 21:53:22 +0000480 if (KeepInsertionPoint)
481 EmitBlock(createBasicBlock("throw.cont"));
Anders Carlsson4b08db72009-10-30 01:42:31 +0000482}
Mike Stump58ef18b2009-11-20 23:44:51 +0000483
Mike Stump1d849212009-12-07 23:38:24 +0000484void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000485 if (!CGM.getLangOpts().CXXExceptions)
Anders Carlsson9878f9f2010-02-06 23:59:05 +0000486 return;
487
Mike Stump1d849212009-12-07 23:38:24 +0000488 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
Craig Topper8a13c412014-05-21 05:09:00 +0000489 if (!FD) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000490 // Check if CapturedDecl is nothrow and create terminate scope for it.
491 if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
492 if (CD->isNothrow())
493 EHStack.pushTerminate();
494 }
Mike Stump1d849212009-12-07 23:38:24 +0000495 return;
Alexey Bataev9959db52014-05-06 10:08:46 +0000496 }
Mike Stump1d849212009-12-07 23:38:24 +0000497 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
Craig Topper8a13c412014-05-21 05:09:00 +0000498 if (!Proto)
Mike Stump1d849212009-12-07 23:38:24 +0000499 return;
500
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000501 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
502 if (isNoexceptExceptionSpec(EST)) {
503 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
504 // noexcept functions are simple terminate scopes.
505 EHStack.pushTerminate();
506 }
507 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
508 unsigned NumExceptions = Proto->getNumExceptions();
509 EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
Mike Stump1d849212009-12-07 23:38:24 +0000510
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000511 for (unsigned I = 0; I != NumExceptions; ++I) {
512 QualType Ty = Proto->getExceptionType(I);
513 QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
514 llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType,
515 /*ForEH=*/true);
516 Filter->setFilter(I, EHType);
517 }
Mike Stump1d849212009-12-07 23:38:24 +0000518 }
Mike Stump1d849212009-12-07 23:38:24 +0000519}
520
John McCall8e4c74b2011-08-11 02:22:43 +0000521/// Emit the dispatch block for a filter scope if necessary.
522static void emitFilterDispatchBlock(CodeGenFunction &CGF,
523 EHFilterScope &filterScope) {
524 llvm::BasicBlock *dispatchBlock = filterScope.getCachedEHDispatchBlock();
525 if (!dispatchBlock) return;
526 if (dispatchBlock->use_empty()) {
527 delete dispatchBlock;
528 return;
529 }
530
John McCall8e4c74b2011-08-11 02:22:43 +0000531 CGF.EmitBlockAfterUses(dispatchBlock);
532
533 // If this isn't a catch-all filter, we need to check whether we got
534 // here because the filter triggered.
535 if (filterScope.getNumFilters()) {
536 // Load the selector value.
Bill Wendling79a70e42011-09-15 18:57:19 +0000537 llvm::Value *selector = CGF.getSelectorFromSlot();
John McCall8e4c74b2011-08-11 02:22:43 +0000538 llvm::BasicBlock *unexpectedBB = CGF.createBasicBlock("ehspec.unexpected");
539
540 llvm::Value *zero = CGF.Builder.getInt32(0);
541 llvm::Value *failsFilter =
542 CGF.Builder.CreateICmpSLT(selector, zero, "ehspec.fails");
David Chisnall9a837be2012-11-07 16:50:40 +0000543 CGF.Builder.CreateCondBr(failsFilter, unexpectedBB, CGF.getEHResumeBlock(false));
John McCall8e4c74b2011-08-11 02:22:43 +0000544
545 CGF.EmitBlock(unexpectedBB);
546 }
547
548 // Call __cxa_call_unexpected. This doesn't need to be an invoke
549 // because __cxa_call_unexpected magically filters exceptions
550 // according to the last landing pad the exception was thrown
551 // into. Seriously.
Bill Wendling79a70e42011-09-15 18:57:19 +0000552 llvm::Value *exn = CGF.getExceptionFromSlot();
John McCall882987f2013-02-28 19:01:20 +0000553 CGF.EmitRuntimeCall(getUnexpectedFn(CGF.CGM), exn)
John McCall8e4c74b2011-08-11 02:22:43 +0000554 ->setDoesNotReturn();
555 CGF.Builder.CreateUnreachable();
556}
557
Mike Stump1d849212009-12-07 23:38:24 +0000558void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000559 if (!CGM.getLangOpts().CXXExceptions)
Anders Carlsson9878f9f2010-02-06 23:59:05 +0000560 return;
561
Mike Stump1d849212009-12-07 23:38:24 +0000562 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
Craig Topper8a13c412014-05-21 05:09:00 +0000563 if (!FD) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000564 // Check if CapturedDecl is nothrow and pop terminate scope for it.
565 if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
566 if (CD->isNothrow())
567 EHStack.popTerminate();
568 }
Mike Stump1d849212009-12-07 23:38:24 +0000569 return;
Alexey Bataev9959db52014-05-06 10:08:46 +0000570 }
Mike Stump1d849212009-12-07 23:38:24 +0000571 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
Craig Topper8a13c412014-05-21 05:09:00 +0000572 if (!Proto)
Mike Stump1d849212009-12-07 23:38:24 +0000573 return;
574
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000575 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
576 if (isNoexceptExceptionSpec(EST)) {
577 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
578 EHStack.popTerminate();
579 }
580 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
John McCall8e4c74b2011-08-11 02:22:43 +0000581 EHFilterScope &filterScope = cast<EHFilterScope>(*EHStack.begin());
582 emitFilterDispatchBlock(*this, filterScope);
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000583 EHStack.popFilter();
584 }
Mike Stump1d849212009-12-07 23:38:24 +0000585}
586
Mike Stump58ef18b2009-11-20 23:44:51 +0000587void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
Reid Klecknera82b5d82014-05-05 21:12:12 +0000588 if (CGM.getTarget().getTriple().isWindowsMSVCEnvironment()) {
589 ErrorUnsupported(&S, "try statement");
590 return;
591 }
592
John McCallb609d3f2010-07-07 06:56:46 +0000593 EnterCXXTryStmt(S);
John McCallb81884d2010-02-19 09:25:03 +0000594 EmitStmt(S.getTryBlock());
John McCallb609d3f2010-07-07 06:56:46 +0000595 ExitCXXTryStmt(S);
John McCallb81884d2010-02-19 09:25:03 +0000596}
597
John McCallb609d3f2010-07-07 06:56:46 +0000598void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallbd309292010-07-06 01:34:17 +0000599 unsigned NumHandlers = S.getNumHandlers();
600 EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
John McCallb81884d2010-02-19 09:25:03 +0000601
John McCallbd309292010-07-06 01:34:17 +0000602 for (unsigned I = 0; I != NumHandlers; ++I) {
603 const CXXCatchStmt *C = S.getHandler(I);
John McCallb81884d2010-02-19 09:25:03 +0000604
John McCallbd309292010-07-06 01:34:17 +0000605 llvm::BasicBlock *Handler = createBasicBlock("catch");
606 if (C->getExceptionDecl()) {
607 // FIXME: Dropping the reference type on the type into makes it
608 // impossible to correctly implement catch-by-reference
609 // semantics for pointers. Unfortunately, this is what all
610 // existing compilers do, and it's not clear that the standard
611 // personality routine is capable of doing this right. See C++ DR 388:
612 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
David Majnemer571162a2014-10-12 06:58:22 +0000613 Qualifiers CaughtTypeQuals;
614 QualType CaughtType = CGM.getContext().getUnqualifiedArrayType(
615 C->getCaughtType().getNonReferenceType(), CaughtTypeQuals);
John McCall2ca705e2010-07-24 00:37:23 +0000616
Rafael Espindolabb9e7a32014-06-04 18:51:46 +0000617 llvm::Constant *TypeInfo = nullptr;
John McCall2ca705e2010-07-24 00:37:23 +0000618 if (CaughtType->isObjCObjectPointerType())
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +0000619 TypeInfo = CGM.getObjCRuntime().GetEHType(CaughtType);
John McCall2ca705e2010-07-24 00:37:23 +0000620 else
Anders Carlssonba840fb2011-01-24 01:59:49 +0000621 TypeInfo = CGM.GetAddrOfRTTIDescriptor(CaughtType, /*ForEH=*/true);
John McCallbd309292010-07-06 01:34:17 +0000622 CatchScope->setHandler(I, TypeInfo, Handler);
623 } else {
624 // No exception decl indicates '...', a catch-all.
625 CatchScope->setCatchAllHandler(I, Handler);
626 }
627 }
John McCallbd309292010-07-06 01:34:17 +0000628}
629
John McCall8e4c74b2011-08-11 02:22:43 +0000630llvm::BasicBlock *
631CodeGenFunction::getEHDispatchBlock(EHScopeStack::stable_iterator si) {
632 // The dispatch block for the end of the scope chain is a block that
633 // just resumes unwinding.
634 if (si == EHStack.stable_end())
David Chisnall9a837be2012-11-07 16:50:40 +0000635 return getEHResumeBlock(true);
John McCall8e4c74b2011-08-11 02:22:43 +0000636
637 // Otherwise, we should look at the actual scope.
638 EHScope &scope = *EHStack.find(si);
639
640 llvm::BasicBlock *dispatchBlock = scope.getCachedEHDispatchBlock();
641 if (!dispatchBlock) {
642 switch (scope.getKind()) {
643 case EHScope::Catch: {
644 // Apply a special case to a single catch-all.
645 EHCatchScope &catchScope = cast<EHCatchScope>(scope);
646 if (catchScope.getNumHandlers() == 1 &&
647 catchScope.getHandler(0).isCatchAll()) {
648 dispatchBlock = catchScope.getHandler(0).Block;
649
650 // Otherwise, make a dispatch block.
651 } else {
652 dispatchBlock = createBasicBlock("catch.dispatch");
653 }
654 break;
655 }
656
657 case EHScope::Cleanup:
658 dispatchBlock = createBasicBlock("ehcleanup");
659 break;
660
661 case EHScope::Filter:
662 dispatchBlock = createBasicBlock("filter.dispatch");
663 break;
664
665 case EHScope::Terminate:
666 dispatchBlock = getTerminateHandler();
667 break;
668 }
669 scope.setCachedEHDispatchBlock(dispatchBlock);
670 }
671 return dispatchBlock;
672}
673
John McCallbd309292010-07-06 01:34:17 +0000674/// Check whether this is a non-EH scope, i.e. a scope which doesn't
675/// affect exception handling. Currently, the only non-EH scopes are
676/// normal-only cleanup scopes.
677static bool isNonEHScope(const EHScope &S) {
John McCall2b7fc382010-07-13 20:32:21 +0000678 switch (S.getKind()) {
John McCallcda666c2010-07-21 07:22:38 +0000679 case EHScope::Cleanup:
680 return !cast<EHCleanupScope>(S).isEHCleanup();
John McCall2b7fc382010-07-13 20:32:21 +0000681 case EHScope::Filter:
682 case EHScope::Catch:
683 case EHScope::Terminate:
684 return false;
685 }
686
David Blaikiee4d798f2012-01-20 21:50:17 +0000687 llvm_unreachable("Invalid EHScope Kind!");
John McCallbd309292010-07-06 01:34:17 +0000688}
689
690llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
691 assert(EHStack.requiresLandingPad());
692 assert(!EHStack.empty());
693
David Blaikiebbafb8a2012-03-11 07:00:24 +0000694 if (!CGM.getLangOpts().Exceptions)
Craig Topper8a13c412014-05-21 05:09:00 +0000695 return nullptr;
John McCall2b7fc382010-07-13 20:32:21 +0000696
John McCallbd309292010-07-06 01:34:17 +0000697 // Check the innermost scope for a cached landing pad. If this is
698 // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
699 llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
700 if (LP) return LP;
701
702 // Build the landing pad for this scope.
703 LP = EmitLandingPad();
704 assert(LP);
705
706 // Cache the landing pad on the innermost scope. If this is a
707 // non-EH scope, cache the landing pad on the enclosing scope, too.
708 for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
709 ir->setCachedLandingPad(LP);
710 if (!isNonEHScope(*ir)) break;
711 }
712
713 return LP;
714}
715
716llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
717 assert(EHStack.requiresLandingPad());
718
John McCall8e4c74b2011-08-11 02:22:43 +0000719 EHScope &innermostEHScope = *EHStack.find(EHStack.getInnermostEHScope());
720 switch (innermostEHScope.getKind()) {
721 case EHScope::Terminate:
722 return getTerminateLandingPad();
John McCallbd309292010-07-06 01:34:17 +0000723
John McCall8e4c74b2011-08-11 02:22:43 +0000724 case EHScope::Catch:
725 case EHScope::Cleanup:
726 case EHScope::Filter:
727 if (llvm::BasicBlock *lpad = innermostEHScope.getCachedLandingPad())
728 return lpad;
John McCallbd309292010-07-06 01:34:17 +0000729 }
730
731 // Save the current IR generation state.
John McCall8e4c74b2011-08-11 02:22:43 +0000732 CGBuilderTy::InsertPoint savedIP = Builder.saveAndClearIP();
Adrian Prantld1b151e2014-01-17 00:15:10 +0000733 SaveAndRestoreLocation AutoRestoreLocation(*this, Builder);
734 if (CGDebugInfo *DI = getDebugInfo())
Adrian Prantl5e5ff6e2013-05-16 00:41:29 +0000735 DI->EmitLocation(Builder, CurEHLocation);
John McCallbd309292010-07-06 01:34:17 +0000736
David Blaikiebbafb8a2012-03-11 07:00:24 +0000737 const EHPersonality &personality = EHPersonality::get(getLangOpts());
John McCall36ea3722010-07-17 00:43:08 +0000738
John McCallbd309292010-07-06 01:34:17 +0000739 // Create and configure the landing pad.
John McCall8e4c74b2011-08-11 02:22:43 +0000740 llvm::BasicBlock *lpad = createBasicBlock("lpad");
741 EmitBlock(lpad);
John McCallbd309292010-07-06 01:34:17 +0000742
Bill Wendlingf0724e82011-09-19 20:31:14 +0000743 llvm::LandingPadInst *LPadInst =
744 Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, NULL),
745 getOpaquePersonalityFn(CGM, personality), 0);
746
747 llvm::Value *LPadExn = Builder.CreateExtractValue(LPadInst, 0);
748 Builder.CreateStore(LPadExn, getExceptionSlot());
749 llvm::Value *LPadSel = Builder.CreateExtractValue(LPadInst, 1);
750 Builder.CreateStore(LPadSel, getEHSelectorSlot());
751
John McCallbd309292010-07-06 01:34:17 +0000752 // Save the exception pointer. It's safe to use a single exception
753 // pointer per function because EH cleanups can never have nested
754 // try/catches.
Bill Wendlingf0724e82011-09-19 20:31:14 +0000755 // Build the landingpad instruction.
John McCallbd309292010-07-06 01:34:17 +0000756
757 // Accumulate all the handlers in scope.
John McCall8e4c74b2011-08-11 02:22:43 +0000758 bool hasCatchAll = false;
759 bool hasCleanup = false;
760 bool hasFilter = false;
761 SmallVector<llvm::Value*, 4> filterTypes;
762 llvm::SmallPtrSet<llvm::Value*, 4> catchTypes;
John McCallbd309292010-07-06 01:34:17 +0000763 for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end();
764 I != E; ++I) {
765
766 switch (I->getKind()) {
John McCallcda666c2010-07-21 07:22:38 +0000767 case EHScope::Cleanup:
John McCall8e4c74b2011-08-11 02:22:43 +0000768 // If we have a cleanup, remember that.
769 hasCleanup = (hasCleanup || cast<EHCleanupScope>(*I).isEHCleanup());
John McCall2b7fc382010-07-13 20:32:21 +0000770 continue;
771
John McCallbd309292010-07-06 01:34:17 +0000772 case EHScope::Filter: {
773 assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
John McCall8e4c74b2011-08-11 02:22:43 +0000774 assert(!hasCatchAll && "EH filter reached after catch-all");
John McCallbd309292010-07-06 01:34:17 +0000775
Bill Wendlingf0724e82011-09-19 20:31:14 +0000776 // Filter scopes get added to the landingpad in weird ways.
John McCall8e4c74b2011-08-11 02:22:43 +0000777 EHFilterScope &filter = cast<EHFilterScope>(*I);
778 hasFilter = true;
John McCallbd309292010-07-06 01:34:17 +0000779
Bill Wendling8c4b7162011-09-22 20:32:54 +0000780 // Add all the filter values.
781 for (unsigned i = 0, e = filter.getNumFilters(); i != e; ++i)
782 filterTypes.push_back(filter.getFilter(i));
John McCallbd309292010-07-06 01:34:17 +0000783 goto done;
784 }
785
786 case EHScope::Terminate:
787 // Terminate scopes are basically catch-alls.
John McCall8e4c74b2011-08-11 02:22:43 +0000788 assert(!hasCatchAll);
789 hasCatchAll = true;
John McCallbd309292010-07-06 01:34:17 +0000790 goto done;
791
792 case EHScope::Catch:
793 break;
794 }
795
John McCall8e4c74b2011-08-11 02:22:43 +0000796 EHCatchScope &catchScope = cast<EHCatchScope>(*I);
797 for (unsigned hi = 0, he = catchScope.getNumHandlers(); hi != he; ++hi) {
798 EHCatchScope::Handler handler = catchScope.getHandler(hi);
John McCallbd309292010-07-06 01:34:17 +0000799
John McCall8e4c74b2011-08-11 02:22:43 +0000800 // If this is a catch-all, register that and abort.
801 if (!handler.Type) {
802 assert(!hasCatchAll);
803 hasCatchAll = true;
804 goto done;
John McCallbd309292010-07-06 01:34:17 +0000805 }
806
807 // Check whether we already have a handler for this type.
Bill Wendlingf0724e82011-09-19 20:31:14 +0000808 if (catchTypes.insert(handler.Type))
809 // If not, add it directly to the landingpad.
810 LPadInst->addClause(handler.Type);
John McCallbd309292010-07-06 01:34:17 +0000811 }
John McCallbd309292010-07-06 01:34:17 +0000812 }
813
814 done:
Bill Wendlingf0724e82011-09-19 20:31:14 +0000815 // If we have a catch-all, add null to the landingpad.
John McCall8e4c74b2011-08-11 02:22:43 +0000816 assert(!(hasCatchAll && hasFilter));
817 if (hasCatchAll) {
Bill Wendlingf0724e82011-09-19 20:31:14 +0000818 LPadInst->addClause(getCatchAllValue(*this));
John McCallbd309292010-07-06 01:34:17 +0000819
820 // If we have an EH filter, we need to add those handlers in the
Bill Wendlingf0724e82011-09-19 20:31:14 +0000821 // right place in the landingpad, which is to say, at the end.
John McCall8e4c74b2011-08-11 02:22:43 +0000822 } else if (hasFilter) {
Bill Wendling58e58fe2011-09-19 22:08:36 +0000823 // Create a filter expression: a constant array indicating which filter
824 // types there are. The personality routine only lands here if the filter
825 // doesn't match.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000826 SmallVector<llvm::Constant*, 8> Filters;
Bill Wendlingf0724e82011-09-19 20:31:14 +0000827 llvm::ArrayType *AType =
828 llvm::ArrayType::get(!filterTypes.empty() ?
829 filterTypes[0]->getType() : Int8PtrTy,
830 filterTypes.size());
831
832 for (unsigned i = 0, e = filterTypes.size(); i != e; ++i)
833 Filters.push_back(cast<llvm::Constant>(filterTypes[i]));
834 llvm::Constant *FilterArray = llvm::ConstantArray::get(AType, Filters);
835 LPadInst->addClause(FilterArray);
John McCallbd309292010-07-06 01:34:17 +0000836
837 // Also check whether we need a cleanup.
Bill Wendlingf0724e82011-09-19 20:31:14 +0000838 if (hasCleanup)
839 LPadInst->setCleanup(true);
John McCallbd309292010-07-06 01:34:17 +0000840
841 // Otherwise, signal that we at least have cleanups.
Logan Chiene9c8ccb2014-07-01 11:47:10 +0000842 } else if (hasCleanup) {
843 LPadInst->setCleanup(true);
John McCallbd309292010-07-06 01:34:17 +0000844 }
845
Bill Wendlingf0724e82011-09-19 20:31:14 +0000846 assert((LPadInst->getNumClauses() > 0 || LPadInst->isCleanup()) &&
847 "landingpad instruction has no clauses!");
John McCallbd309292010-07-06 01:34:17 +0000848
849 // Tell the backend how to generate the landing pad.
John McCall8e4c74b2011-08-11 02:22:43 +0000850 Builder.CreateBr(getEHDispatchBlock(EHStack.getInnermostEHScope()));
John McCallbd309292010-07-06 01:34:17 +0000851
852 // Restore the old IR generation state.
John McCall8e4c74b2011-08-11 02:22:43 +0000853 Builder.restoreIP(savedIP);
John McCallbd309292010-07-06 01:34:17 +0000854
John McCall8e4c74b2011-08-11 02:22:43 +0000855 return lpad;
John McCallbd309292010-07-06 01:34:17 +0000856}
857
John McCall5c08ab92010-07-13 22:12:14 +0000858namespace {
859 /// A cleanup to call __cxa_end_catch. In many cases, the caught
860 /// exception type lets us state definitively that the thrown exception
861 /// type does not have a destructor. In particular:
862 /// - Catch-alls tell us nothing, so we have to conservatively
863 /// assume that the thrown exception might have a destructor.
864 /// - Catches by reference behave according to their base types.
865 /// - Catches of non-record types will only trigger for exceptions
866 /// of non-record types, which never have destructors.
867 /// - Catches of record types can trigger for arbitrary subclasses
868 /// of the caught type, so we have to assume the actual thrown
869 /// exception type might have a throwing destructor, even if the
870 /// caught type's destructor is trivial or nothrow.
John McCallcda666c2010-07-21 07:22:38 +0000871 struct CallEndCatch : EHScopeStack::Cleanup {
John McCall5c08ab92010-07-13 22:12:14 +0000872 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
873 bool MightThrow;
874
Craig Topper4f12f102014-03-12 06:41:41 +0000875 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall5c08ab92010-07-13 22:12:14 +0000876 if (!MightThrow) {
John McCall882987f2013-02-28 19:01:20 +0000877 CGF.EmitNounwindRuntimeCall(getEndCatchFn(CGF.CGM));
John McCall5c08ab92010-07-13 22:12:14 +0000878 return;
879 }
880
John McCall882987f2013-02-28 19:01:20 +0000881 CGF.EmitRuntimeCallOrInvoke(getEndCatchFn(CGF.CGM));
John McCall5c08ab92010-07-13 22:12:14 +0000882 }
883 };
884}
885
John McCallbd309292010-07-06 01:34:17 +0000886/// Emits a call to __cxa_begin_catch and enters a cleanup to call
887/// __cxa_end_catch.
John McCall5c08ab92010-07-13 22:12:14 +0000888///
889/// \param EndMightThrow - true if __cxa_end_catch might throw
890static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
891 llvm::Value *Exn,
892 bool EndMightThrow) {
John McCall882987f2013-02-28 19:01:20 +0000893 llvm::CallInst *call =
894 CGF.EmitNounwindRuntimeCall(getBeginCatchFn(CGF.CGM), Exn);
John McCallbd309292010-07-06 01:34:17 +0000895
John McCallcda666c2010-07-21 07:22:38 +0000896 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
John McCallbd309292010-07-06 01:34:17 +0000897
John McCall882987f2013-02-28 19:01:20 +0000898 return call;
John McCallbd309292010-07-06 01:34:17 +0000899}
900
901/// A "special initializer" callback for initializing a catch
902/// parameter during catch initialization.
903static void InitCatchParam(CodeGenFunction &CGF,
904 const VarDecl &CatchParam,
Nick Lewycky2d84e842013-10-02 02:29:49 +0000905 llvm::Value *ParamAddr,
906 SourceLocation Loc) {
John McCallbd309292010-07-06 01:34:17 +0000907 // Load the exception from where the landing pad saved it.
Bill Wendling79a70e42011-09-15 18:57:19 +0000908 llvm::Value *Exn = CGF.getExceptionFromSlot();
John McCallbd309292010-07-06 01:34:17 +0000909
910 CanQualType CatchType =
911 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
Chris Lattner2192fe52011-07-18 04:24:23 +0000912 llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
John McCallbd309292010-07-06 01:34:17 +0000913
914 // If we're catching by reference, we can just cast the object
915 // pointer to the appropriate pointer.
916 if (isa<ReferenceType>(CatchType)) {
John McCall5add20c2010-07-20 22:17:55 +0000917 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
918 bool EndCatchMightThrow = CaughtType->isRecordType();
John McCall5c08ab92010-07-13 22:12:14 +0000919
John McCallbd309292010-07-06 01:34:17 +0000920 // __cxa_begin_catch returns the adjusted object pointer.
John McCall5c08ab92010-07-13 22:12:14 +0000921 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
John McCall5add20c2010-07-20 22:17:55 +0000922
923 // We have no way to tell the personality function that we're
924 // catching by reference, so if we're catching a pointer,
925 // __cxa_begin_catch will actually return that pointer by value.
926 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
927 QualType PointeeType = PT->getPointeeType();
928
929 // When catching by reference, generally we should just ignore
930 // this by-value pointer and use the exception object instead.
931 if (!PointeeType->isRecordType()) {
932
933 // Exn points to the struct _Unwind_Exception header, which
934 // we have to skip past in order to reach the exception data.
935 unsigned HeaderSize =
936 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
937 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
938
939 // However, if we're catching a pointer-to-record type that won't
940 // work, because the personality function might have adjusted
941 // the pointer. There's actually no way for us to fully satisfy
942 // the language/ABI contract here: we can't use Exn because it
943 // might have the wrong adjustment, but we can't use the by-value
944 // pointer because it's off by a level of abstraction.
945 //
946 // The current solution is to dump the adjusted pointer into an
947 // alloca, which breaks language semantics (because changing the
948 // pointer doesn't change the exception) but at least works.
949 // The better solution would be to filter out non-exact matches
950 // and rethrow them, but this is tricky because the rethrow
951 // really needs to be catchable by other sites at this landing
952 // pad. The best solution is to fix the personality function.
953 } else {
954 // Pull the pointer for the reference type off.
Chris Lattner2192fe52011-07-18 04:24:23 +0000955 llvm::Type *PtrTy =
John McCall5add20c2010-07-20 22:17:55 +0000956 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
957
958 // Create the temporary and write the adjusted pointer into it.
959 llvm::Value *ExnPtrTmp = CGF.CreateTempAlloca(PtrTy, "exn.byref.tmp");
960 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
961 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
962
963 // Bind the reference to the temporary.
964 AdjustedExn = ExnPtrTmp;
965 }
966 }
967
John McCallbd309292010-07-06 01:34:17 +0000968 llvm::Value *ExnCast =
969 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
970 CGF.Builder.CreateStore(ExnCast, ParamAddr);
971 return;
972 }
973
John McCall47fb9502013-03-07 21:37:08 +0000974 // Scalars and complexes.
975 TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType);
976 if (TEK != TEK_Aggregate) {
John McCall5c08ab92010-07-13 22:12:14 +0000977 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
John McCallbd309292010-07-06 01:34:17 +0000978
979 // If the catch type is a pointer type, __cxa_begin_catch returns
980 // the pointer by value.
981 if (CatchType->hasPointerRepresentation()) {
982 llvm::Value *CastExn =
983 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
John McCall97017312012-01-17 20:16:56 +0000984
985 switch (CatchType.getQualifiers().getObjCLifetime()) {
986 case Qualifiers::OCL_Strong:
987 CastExn = CGF.EmitARCRetainNonBlock(CastExn);
988 // fallthrough
989
990 case Qualifiers::OCL_None:
991 case Qualifiers::OCL_ExplicitNone:
992 case Qualifiers::OCL_Autoreleasing:
993 CGF.Builder.CreateStore(CastExn, ParamAddr);
994 return;
995
996 case Qualifiers::OCL_Weak:
997 CGF.EmitARCInitWeak(ParamAddr, CastExn);
998 return;
999 }
1000 llvm_unreachable("bad ownership qualifier!");
John McCallbd309292010-07-06 01:34:17 +00001001 }
1002
1003 // Otherwise, it returns a pointer into the exception object.
1004
Chris Lattner2192fe52011-07-18 04:24:23 +00001005 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
John McCallbd309292010-07-06 01:34:17 +00001006 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1007
John McCall47fb9502013-03-07 21:37:08 +00001008 LValue srcLV = CGF.MakeNaturalAlignAddrLValue(Cast, CatchType);
1009 LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType,
1010 CGF.getContext().getDeclAlign(&CatchParam));
1011 switch (TEK) {
1012 case TEK_Complex:
Nick Lewycky2d84e842013-10-02 02:29:49 +00001013 CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV,
John McCall47fb9502013-03-07 21:37:08 +00001014 /*init*/ true);
1015 return;
1016 case TEK_Scalar: {
Nick Lewycky2d84e842013-10-02 02:29:49 +00001017 llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc);
John McCall47fb9502013-03-07 21:37:08 +00001018 CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true);
1019 return;
John McCallbd309292010-07-06 01:34:17 +00001020 }
John McCall47fb9502013-03-07 21:37:08 +00001021 case TEK_Aggregate:
1022 llvm_unreachable("evaluation kind filtered out!");
1023 }
1024 llvm_unreachable("bad evaluation kind");
John McCallbd309292010-07-06 01:34:17 +00001025 }
1026
John McCallb5011ab2011-02-16 08:39:19 +00001027 assert(isa<RecordType>(CatchType) && "unexpected catch type!");
John McCallbd309292010-07-06 01:34:17 +00001028
Chris Lattner2192fe52011-07-18 04:24:23 +00001029 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
John McCallbd309292010-07-06 01:34:17 +00001030
John McCallb5011ab2011-02-16 08:39:19 +00001031 // Check for a copy expression. If we don't have a copy expression,
1032 // that means a trivial copy is okay.
John McCall1bf58462011-02-16 08:02:54 +00001033 const Expr *copyExpr = CatchParam.getInit();
1034 if (!copyExpr) {
John McCallb5011ab2011-02-16 08:39:19 +00001035 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
1036 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
Chad Rosier615ed1a2012-03-29 17:37:10 +00001037 CGF.EmitAggregateCopy(ParamAddr, adjustedExn, CatchType);
John McCallbd309292010-07-06 01:34:17 +00001038 return;
1039 }
1040
1041 // We have to call __cxa_get_exception_ptr to get the adjusted
1042 // pointer before copying.
John McCall1bf58462011-02-16 08:02:54 +00001043 llvm::CallInst *rawAdjustedExn =
John McCall882987f2013-02-28 19:01:20 +00001044 CGF.EmitNounwindRuntimeCall(getGetExceptionPtrFn(CGF.CGM), Exn);
John McCallbd309292010-07-06 01:34:17 +00001045
John McCall1bf58462011-02-16 08:02:54 +00001046 // Cast that to the appropriate type.
1047 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
John McCallbd309292010-07-06 01:34:17 +00001048
John McCall1bf58462011-02-16 08:02:54 +00001049 // The copy expression is defined in terms of an OpaqueValueExpr.
1050 // Find it and map it to the adjusted expression.
1051 CodeGenFunction::OpaqueValueMapping
John McCallc07a0c72011-02-17 10:25:35 +00001052 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
1053 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
John McCallbd309292010-07-06 01:34:17 +00001054
1055 // Call the copy ctor in a terminate scope.
1056 CGF.EHStack.pushTerminate();
John McCall1bf58462011-02-16 08:02:54 +00001057
1058 // Perform the copy construction.
Eli Friedman38cd36d2011-12-03 02:13:40 +00001059 CharUnits Alignment = CGF.getContext().getDeclAlign(&CatchParam);
Eli Friedmanc1d85b92011-12-03 00:54:26 +00001060 CGF.EmitAggExpr(copyExpr,
1061 AggValueSlot::forAddr(ParamAddr, Alignment, Qualifiers(),
1062 AggValueSlot::IsNotDestructed,
1063 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001064 AggValueSlot::IsNotAliased));
John McCall1bf58462011-02-16 08:02:54 +00001065
1066 // Leave the terminate scope.
John McCallbd309292010-07-06 01:34:17 +00001067 CGF.EHStack.popTerminate();
1068
John McCall1bf58462011-02-16 08:02:54 +00001069 // Undo the opaque value mapping.
1070 opaque.pop();
1071
John McCallbd309292010-07-06 01:34:17 +00001072 // Finally we can call __cxa_begin_catch.
John McCall5c08ab92010-07-13 22:12:14 +00001073 CallBeginCatch(CGF, Exn, true);
John McCallbd309292010-07-06 01:34:17 +00001074}
1075
1076/// Begins a catch statement by initializing the catch variable and
1077/// calling __cxa_begin_catch.
John McCall1bf58462011-02-16 08:02:54 +00001078static void BeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *S) {
John McCallbd309292010-07-06 01:34:17 +00001079 // We have to be very careful with the ordering of cleanups here:
1080 // C++ [except.throw]p4:
1081 // The destruction [of the exception temporary] occurs
1082 // immediately after the destruction of the object declared in
1083 // the exception-declaration in the handler.
1084 //
1085 // So the precise ordering is:
1086 // 1. Construct catch variable.
1087 // 2. __cxa_begin_catch
1088 // 3. Enter __cxa_end_catch cleanup
1089 // 4. Enter dtor cleanup
1090 //
John McCallc533cb72011-02-22 06:44:22 +00001091 // We do this by using a slightly abnormal initialization process.
1092 // Delegation sequence:
John McCallbd309292010-07-06 01:34:17 +00001093 // - ExitCXXTryStmt opens a RunCleanupsScope
John McCallc533cb72011-02-22 06:44:22 +00001094 // - EmitAutoVarAlloca creates the variable and debug info
John McCallbd309292010-07-06 01:34:17 +00001095 // - InitCatchParam initializes the variable from the exception
John McCallc533cb72011-02-22 06:44:22 +00001096 // - CallBeginCatch calls __cxa_begin_catch
1097 // - CallBeginCatch enters the __cxa_end_catch cleanup
1098 // - EmitAutoVarCleanups enters the variable destructor cleanup
John McCallbd309292010-07-06 01:34:17 +00001099 // - EmitCXXTryStmt emits the code for the catch body
1100 // - EmitCXXTryStmt close the RunCleanupsScope
1101
1102 VarDecl *CatchParam = S->getExceptionDecl();
1103 if (!CatchParam) {
Bill Wendling79a70e42011-09-15 18:57:19 +00001104 llvm::Value *Exn = CGF.getExceptionFromSlot();
John McCall5c08ab92010-07-13 22:12:14 +00001105 CallBeginCatch(CGF, Exn, true);
John McCallbd309292010-07-06 01:34:17 +00001106 return;
1107 }
1108
1109 // Emit the local.
John McCallc533cb72011-02-22 06:44:22 +00001110 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
Nick Lewycky2d84e842013-10-02 02:29:49 +00001111 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF), S->getLocStart());
John McCallc533cb72011-02-22 06:44:22 +00001112 CGF.EmitAutoVarCleanups(var);
John McCallb81884d2010-02-19 09:25:03 +00001113}
1114
John McCall8e4c74b2011-08-11 02:22:43 +00001115/// Emit the structure of the dispatch block for the given catch scope.
1116/// It is an invariant that the dispatch block already exists.
1117static void emitCatchDispatchBlock(CodeGenFunction &CGF,
1118 EHCatchScope &catchScope) {
1119 llvm::BasicBlock *dispatchBlock = catchScope.getCachedEHDispatchBlock();
1120 assert(dispatchBlock);
1121
1122 // If there's only a single catch-all, getEHDispatchBlock returned
1123 // that catch-all as the dispatch block.
1124 if (catchScope.getNumHandlers() == 1 &&
1125 catchScope.getHandler(0).isCatchAll()) {
1126 assert(dispatchBlock == catchScope.getHandler(0).Block);
1127 return;
1128 }
1129
1130 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveIP();
1131 CGF.EmitBlockAfterUses(dispatchBlock);
1132
1133 // Select the right handler.
1134 llvm::Value *llvm_eh_typeid_for =
1135 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
1136
1137 // Load the selector value.
Bill Wendling79a70e42011-09-15 18:57:19 +00001138 llvm::Value *selector = CGF.getSelectorFromSlot();
John McCall8e4c74b2011-08-11 02:22:43 +00001139
1140 // Test against each of the exception types we claim to catch.
1141 for (unsigned i = 0, e = catchScope.getNumHandlers(); ; ++i) {
1142 assert(i < e && "ran off end of handlers!");
1143 const EHCatchScope::Handler &handler = catchScope.getHandler(i);
1144
1145 llvm::Value *typeValue = handler.Type;
1146 assert(typeValue && "fell into catch-all case!");
1147 typeValue = CGF.Builder.CreateBitCast(typeValue, CGF.Int8PtrTy);
1148
1149 // Figure out the next block.
1150 bool nextIsEnd;
1151 llvm::BasicBlock *nextBlock;
1152
1153 // If this is the last handler, we're at the end, and the next
1154 // block is the block for the enclosing EH scope.
1155 if (i + 1 == e) {
1156 nextBlock = CGF.getEHDispatchBlock(catchScope.getEnclosingEHScope());
1157 nextIsEnd = true;
1158
1159 // If the next handler is a catch-all, we're at the end, and the
1160 // next block is that handler.
1161 } else if (catchScope.getHandler(i+1).isCatchAll()) {
1162 nextBlock = catchScope.getHandler(i+1).Block;
1163 nextIsEnd = true;
1164
1165 // Otherwise, we're not at the end and we need a new block.
1166 } else {
1167 nextBlock = CGF.createBasicBlock("catch.fallthrough");
1168 nextIsEnd = false;
1169 }
1170
1171 // Figure out the catch type's index in the LSDA's type table.
1172 llvm::CallInst *typeIndex =
1173 CGF.Builder.CreateCall(llvm_eh_typeid_for, typeValue);
1174 typeIndex->setDoesNotThrow();
1175
1176 llvm::Value *matchesTypeIndex =
1177 CGF.Builder.CreateICmpEQ(selector, typeIndex, "matches");
1178 CGF.Builder.CreateCondBr(matchesTypeIndex, handler.Block, nextBlock);
1179
1180 // If the next handler is a catch-all, we're completely done.
1181 if (nextIsEnd) {
1182 CGF.Builder.restoreIP(savedIP);
1183 return;
John McCall8e4c74b2011-08-11 02:22:43 +00001184 }
Ahmed Charles289896d2012-02-19 11:57:29 +00001185 // Otherwise we need to emit and continue at that block.
1186 CGF.EmitBlock(nextBlock);
John McCall8e4c74b2011-08-11 02:22:43 +00001187 }
John McCall8e4c74b2011-08-11 02:22:43 +00001188}
1189
1190void CodeGenFunction::popCatchScope() {
1191 EHCatchScope &catchScope = cast<EHCatchScope>(*EHStack.begin());
1192 if (catchScope.hasEHBranches())
1193 emitCatchDispatchBlock(*this, catchScope);
1194 EHStack.popCatch();
1195}
1196
John McCallb609d3f2010-07-07 06:56:46 +00001197void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallbd309292010-07-06 01:34:17 +00001198 unsigned NumHandlers = S.getNumHandlers();
1199 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1200 assert(CatchScope.getNumHandlers() == NumHandlers);
Mike Stump58ef18b2009-11-20 23:44:51 +00001201
John McCall8e4c74b2011-08-11 02:22:43 +00001202 // If the catch was not required, bail out now.
1203 if (!CatchScope.hasEHBranches()) {
Kostya Serebryanyba4aced2014-01-09 09:22:32 +00001204 CatchScope.clearHandlerBlocks();
John McCall8e4c74b2011-08-11 02:22:43 +00001205 EHStack.popCatch();
1206 return;
1207 }
1208
1209 // Emit the structure of the EH dispatch for this catch.
1210 emitCatchDispatchBlock(*this, CatchScope);
1211
John McCallbd309292010-07-06 01:34:17 +00001212 // Copy the handler blocks off before we pop the EH stack. Emitting
1213 // the handlers might scribble on this memory.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001214 SmallVector<EHCatchScope::Handler, 8> Handlers(NumHandlers);
John McCallbd309292010-07-06 01:34:17 +00001215 memcpy(Handlers.data(), CatchScope.begin(),
1216 NumHandlers * sizeof(EHCatchScope::Handler));
John McCall8e4c74b2011-08-11 02:22:43 +00001217
John McCallbd309292010-07-06 01:34:17 +00001218 EHStack.popCatch();
Mike Stump58ef18b2009-11-20 23:44:51 +00001219
John McCallbd309292010-07-06 01:34:17 +00001220 // The fall-through block.
1221 llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
Mike Stump58ef18b2009-11-20 23:44:51 +00001222
John McCallbd309292010-07-06 01:34:17 +00001223 // We just emitted the body of the try; jump to the continue block.
1224 if (HaveInsertPoint())
1225 Builder.CreateBr(ContBB);
Mike Stump97329152009-12-02 19:53:57 +00001226
John McCalld8d00be2012-06-15 05:27:05 +00001227 // Determine if we need an implicit rethrow for all these catch handlers;
1228 // see the comment below.
1229 bool doImplicitRethrow = false;
John McCallb609d3f2010-07-07 06:56:46 +00001230 if (IsFnTryBlock)
John McCalld8d00be2012-06-15 05:27:05 +00001231 doImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
1232 isa<CXXConstructorDecl>(CurCodeDecl);
John McCallb609d3f2010-07-07 06:56:46 +00001233
John McCall8e4c74b2011-08-11 02:22:43 +00001234 // Perversely, we emit the handlers backwards precisely because we
1235 // want them to appear in source order. In all of these cases, the
1236 // catch block will have exactly one predecessor, which will be a
1237 // particular block in the catch dispatch. However, in the case of
1238 // a catch-all, one of the dispatch blocks will branch to two
1239 // different handlers, and EmitBlockAfterUses will cause the second
1240 // handler to be moved before the first.
1241 for (unsigned I = NumHandlers; I != 0; --I) {
1242 llvm::BasicBlock *CatchBlock = Handlers[I-1].Block;
1243 EmitBlockAfterUses(CatchBlock);
Mike Stump75546b82009-12-10 00:06:18 +00001244
John McCallbd309292010-07-06 01:34:17 +00001245 // Catch the exception if this isn't a catch-all.
John McCall8e4c74b2011-08-11 02:22:43 +00001246 const CXXCatchStmt *C = S.getHandler(I-1);
Mike Stump58ef18b2009-11-20 23:44:51 +00001247
John McCallbd309292010-07-06 01:34:17 +00001248 // Enter a cleanup scope, including the catch variable and the
1249 // end-catch.
1250 RunCleanupsScope CatchScope(*this);
Mike Stump58ef18b2009-11-20 23:44:51 +00001251
John McCallbd309292010-07-06 01:34:17 +00001252 // Initialize the catch variable and set up the cleanups.
1253 BeginCatch(*this, C);
1254
Justin Bognerea278c32014-01-07 00:20:28 +00001255 // Emit the PGO counter increment.
Justin Bogneref512b92014-01-06 22:27:43 +00001256 RegionCounter CatchCnt = getPGORegionCounter(C);
1257 CatchCnt.beginRegion(Builder);
1258
John McCallbd309292010-07-06 01:34:17 +00001259 // Perform the body of the catch.
1260 EmitStmt(C->getHandlerBlock());
1261
John McCalld8d00be2012-06-15 05:27:05 +00001262 // [except.handle]p11:
1263 // The currently handled exception is rethrown if control
1264 // reaches the end of a handler of the function-try-block of a
1265 // constructor or destructor.
1266
1267 // It is important that we only do this on fallthrough and not on
1268 // return. Note that it's illegal to put a return in a
1269 // constructor function-try-block's catch handler (p14), so this
1270 // really only applies to destructors.
1271 if (doImplicitRethrow && HaveInsertPoint()) {
John McCall882987f2013-02-28 19:01:20 +00001272 EmitRuntimeCallOrInvoke(getReThrowFn(CGM));
John McCalld8d00be2012-06-15 05:27:05 +00001273 Builder.CreateUnreachable();
1274 Builder.ClearInsertionPoint();
1275 }
1276
John McCallbd309292010-07-06 01:34:17 +00001277 // Fall out through the catch cleanups.
1278 CatchScope.ForceCleanup();
1279
1280 // Branch out of the try.
1281 if (HaveInsertPoint())
1282 Builder.CreateBr(ContBB);
Mike Stump58ef18b2009-11-20 23:44:51 +00001283 }
1284
Justin Bogneref512b92014-01-06 22:27:43 +00001285 RegionCounter ContCnt = getPGORegionCounter(&S);
John McCallbd309292010-07-06 01:34:17 +00001286 EmitBlock(ContBB);
Justin Bogneref512b92014-01-06 22:27:43 +00001287 ContCnt.beginRegion(Builder);
Mike Stump58ef18b2009-11-20 23:44:51 +00001288}
Mike Stumpaff69af2009-12-09 03:35:49 +00001289
John McCall1e670402010-07-21 00:52:03 +00001290namespace {
John McCallcda666c2010-07-21 07:22:38 +00001291 struct CallEndCatchForFinally : EHScopeStack::Cleanup {
John McCall1e670402010-07-21 00:52:03 +00001292 llvm::Value *ForEHVar;
1293 llvm::Value *EndCatchFn;
1294 CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn)
1295 : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
1296
Craig Topper4f12f102014-03-12 06:41:41 +00001297 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall1e670402010-07-21 00:52:03 +00001298 llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
1299 llvm::BasicBlock *CleanupContBB =
1300 CGF.createBasicBlock("finally.cleanup.cont");
1301
1302 llvm::Value *ShouldEndCatch =
1303 CGF.Builder.CreateLoad(ForEHVar, "finally.endcatch");
1304 CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1305 CGF.EmitBlock(EndCatchBB);
John McCall882987f2013-02-28 19:01:20 +00001306 CGF.EmitRuntimeCallOrInvoke(EndCatchFn); // catch-all, so might throw
John McCall1e670402010-07-21 00:52:03 +00001307 CGF.EmitBlock(CleanupContBB);
1308 }
1309 };
John McCall906da4b2010-07-21 05:47:49 +00001310
John McCallcda666c2010-07-21 07:22:38 +00001311 struct PerformFinally : EHScopeStack::Cleanup {
John McCall906da4b2010-07-21 05:47:49 +00001312 const Stmt *Body;
1313 llvm::Value *ForEHVar;
1314 llvm::Value *EndCatchFn;
1315 llvm::Value *RethrowFn;
1316 llvm::Value *SavedExnVar;
1317
1318 PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
1319 llvm::Value *EndCatchFn,
1320 llvm::Value *RethrowFn, llvm::Value *SavedExnVar)
1321 : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1322 RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
1323
Craig Topper4f12f102014-03-12 06:41:41 +00001324 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall906da4b2010-07-21 05:47:49 +00001325 // Enter a cleanup to call the end-catch function if one was provided.
1326 if (EndCatchFn)
John McCallcda666c2010-07-21 07:22:38 +00001327 CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
1328 ForEHVar, EndCatchFn);
John McCall906da4b2010-07-21 05:47:49 +00001329
John McCallcebe0ca2010-08-11 00:16:14 +00001330 // Save the current cleanup destination in case there are
1331 // cleanups in the finally block.
1332 llvm::Value *SavedCleanupDest =
1333 CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
1334 "cleanup.dest.saved");
1335
John McCall906da4b2010-07-21 05:47:49 +00001336 // Emit the finally block.
1337 CGF.EmitStmt(Body);
1338
1339 // If the end of the finally is reachable, check whether this was
1340 // for EH. If so, rethrow.
1341 if (CGF.HaveInsertPoint()) {
1342 llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
1343 llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
1344
1345 llvm::Value *ShouldRethrow =
1346 CGF.Builder.CreateLoad(ForEHVar, "finally.shouldthrow");
1347 CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1348
1349 CGF.EmitBlock(RethrowBB);
1350 if (SavedExnVar) {
John McCall882987f2013-02-28 19:01:20 +00001351 CGF.EmitRuntimeCallOrInvoke(RethrowFn,
1352 CGF.Builder.CreateLoad(SavedExnVar));
John McCall906da4b2010-07-21 05:47:49 +00001353 } else {
John McCall882987f2013-02-28 19:01:20 +00001354 CGF.EmitRuntimeCallOrInvoke(RethrowFn);
John McCall906da4b2010-07-21 05:47:49 +00001355 }
1356 CGF.Builder.CreateUnreachable();
1357
1358 CGF.EmitBlock(ContBB);
John McCallcebe0ca2010-08-11 00:16:14 +00001359
1360 // Restore the cleanup destination.
1361 CGF.Builder.CreateStore(SavedCleanupDest,
1362 CGF.getNormalCleanupDestSlot());
John McCall906da4b2010-07-21 05:47:49 +00001363 }
1364
1365 // Leave the end-catch cleanup. As an optimization, pretend that
1366 // the fallthrough path was inaccessible; we've dynamically proven
1367 // that we're not in the EH case along that path.
1368 if (EndCatchFn) {
1369 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1370 CGF.PopCleanupBlock();
1371 CGF.Builder.restoreIP(SavedIP);
1372 }
1373
1374 // Now make sure we actually have an insertion point or the
1375 // cleanup gods will hate us.
1376 CGF.EnsureInsertPoint();
1377 }
1378 };
John McCall1e670402010-07-21 00:52:03 +00001379}
1380
John McCallbd309292010-07-06 01:34:17 +00001381/// Enters a finally block for an implementation using zero-cost
1382/// exceptions. This is mostly general, but hard-codes some
1383/// language/ABI-specific behavior in the catch-all sections.
John McCall6b0feb72011-06-22 02:32:12 +00001384void CodeGenFunction::FinallyInfo::enter(CodeGenFunction &CGF,
1385 const Stmt *body,
1386 llvm::Constant *beginCatchFn,
1387 llvm::Constant *endCatchFn,
1388 llvm::Constant *rethrowFn) {
Craig Topper8a13c412014-05-21 05:09:00 +00001389 assert((beginCatchFn != nullptr) == (endCatchFn != nullptr) &&
John McCallbd309292010-07-06 01:34:17 +00001390 "begin/end catch functions not paired");
John McCall6b0feb72011-06-22 02:32:12 +00001391 assert(rethrowFn && "rethrow function is required");
1392
1393 BeginCatchFn = beginCatchFn;
Mike Stumpaff69af2009-12-09 03:35:49 +00001394
John McCallbd309292010-07-06 01:34:17 +00001395 // The rethrow function has one of the following two types:
1396 // void (*)()
1397 // void (*)(void*)
1398 // In the latter case we need to pass it the exception object.
1399 // But we can't use the exception slot because the @finally might
1400 // have a landing pad (which would overwrite the exception slot).
Chris Lattner2192fe52011-07-18 04:24:23 +00001401 llvm::FunctionType *rethrowFnTy =
John McCallbd309292010-07-06 01:34:17 +00001402 cast<llvm::FunctionType>(
John McCall6b0feb72011-06-22 02:32:12 +00001403 cast<llvm::PointerType>(rethrowFn->getType())->getElementType());
Craig Topper8a13c412014-05-21 05:09:00 +00001404 SavedExnVar = nullptr;
John McCall6b0feb72011-06-22 02:32:12 +00001405 if (rethrowFnTy->getNumParams())
1406 SavedExnVar = CGF.CreateTempAlloca(CGF.Int8PtrTy, "finally.exn");
Mike Stumpaff69af2009-12-09 03:35:49 +00001407
John McCallbd309292010-07-06 01:34:17 +00001408 // A finally block is a statement which must be executed on any edge
1409 // out of a given scope. Unlike a cleanup, the finally block may
1410 // contain arbitrary control flow leading out of itself. In
1411 // addition, finally blocks should always be executed, even if there
1412 // are no catch handlers higher on the stack. Therefore, we
1413 // surround the protected scope with a combination of a normal
1414 // cleanup (to catch attempts to break out of the block via normal
1415 // control flow) and an EH catch-all (semantically "outside" any try
1416 // statement to which the finally block might have been attached).
1417 // The finally block itself is generated in the context of a cleanup
1418 // which conditionally leaves the catch-all.
John McCall21886962010-04-21 10:05:39 +00001419
John McCallbd309292010-07-06 01:34:17 +00001420 // Jump destination for performing the finally block on an exception
1421 // edge. We'll never actually reach this block, so unreachable is
1422 // fine.
John McCall6b0feb72011-06-22 02:32:12 +00001423 RethrowDest = CGF.getJumpDestInCurrentScope(CGF.getUnreachableBlock());
John McCall21886962010-04-21 10:05:39 +00001424
John McCallbd309292010-07-06 01:34:17 +00001425 // Whether the finally block is being executed for EH purposes.
John McCall6b0feb72011-06-22 02:32:12 +00001426 ForEHVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "finally.for-eh");
1427 CGF.Builder.CreateStore(CGF.Builder.getFalse(), ForEHVar);
Mike Stumpaff69af2009-12-09 03:35:49 +00001428
John McCallbd309292010-07-06 01:34:17 +00001429 // Enter a normal cleanup which will perform the @finally block.
John McCall6b0feb72011-06-22 02:32:12 +00001430 CGF.EHStack.pushCleanup<PerformFinally>(NormalCleanup, body,
1431 ForEHVar, endCatchFn,
1432 rethrowFn, SavedExnVar);
John McCallbd309292010-07-06 01:34:17 +00001433
1434 // Enter a catch-all scope.
John McCall6b0feb72011-06-22 02:32:12 +00001435 llvm::BasicBlock *catchBB = CGF.createBasicBlock("finally.catchall");
1436 EHCatchScope *catchScope = CGF.EHStack.pushCatch(1);
1437 catchScope->setCatchAllHandler(0, catchBB);
John McCallbd309292010-07-06 01:34:17 +00001438}
1439
John McCall6b0feb72011-06-22 02:32:12 +00001440void CodeGenFunction::FinallyInfo::exit(CodeGenFunction &CGF) {
John McCallbd309292010-07-06 01:34:17 +00001441 // Leave the finally catch-all.
John McCall6b0feb72011-06-22 02:32:12 +00001442 EHCatchScope &catchScope = cast<EHCatchScope>(*CGF.EHStack.begin());
1443 llvm::BasicBlock *catchBB = catchScope.getHandler(0).Block;
John McCall8e4c74b2011-08-11 02:22:43 +00001444
1445 CGF.popCatchScope();
John McCallbd309292010-07-06 01:34:17 +00001446
John McCall6b0feb72011-06-22 02:32:12 +00001447 // If there are any references to the catch-all block, emit it.
1448 if (catchBB->use_empty()) {
1449 delete catchBB;
1450 } else {
1451 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveAndClearIP();
1452 CGF.EmitBlock(catchBB);
John McCallbd309292010-07-06 01:34:17 +00001453
Craig Topper8a13c412014-05-21 05:09:00 +00001454 llvm::Value *exn = nullptr;
John McCallbd309292010-07-06 01:34:17 +00001455
John McCall6b0feb72011-06-22 02:32:12 +00001456 // If there's a begin-catch function, call it.
1457 if (BeginCatchFn) {
Bill Wendling79a70e42011-09-15 18:57:19 +00001458 exn = CGF.getExceptionFromSlot();
John McCall882987f2013-02-28 19:01:20 +00001459 CGF.EmitNounwindRuntimeCall(BeginCatchFn, exn);
John McCall6b0feb72011-06-22 02:32:12 +00001460 }
1461
1462 // If we need to remember the exception pointer to rethrow later, do so.
1463 if (SavedExnVar) {
Bill Wendling79a70e42011-09-15 18:57:19 +00001464 if (!exn) exn = CGF.getExceptionFromSlot();
John McCall6b0feb72011-06-22 02:32:12 +00001465 CGF.Builder.CreateStore(exn, SavedExnVar);
1466 }
1467
1468 // Tell the cleanups in the finally block that we're do this for EH.
1469 CGF.Builder.CreateStore(CGF.Builder.getTrue(), ForEHVar);
1470
1471 // Thread a jump through the finally cleanup.
1472 CGF.EmitBranchThroughCleanup(RethrowDest);
1473
1474 CGF.Builder.restoreIP(savedIP);
1475 }
1476
1477 // Finally, leave the @finally cleanup.
1478 CGF.PopCleanupBlock();
John McCallbd309292010-07-06 01:34:17 +00001479}
1480
John McCalle142ad52013-02-12 03:51:46 +00001481/// In a terminate landing pad, should we use __clang__call_terminate
1482/// or just a naked call to std::terminate?
1483///
1484/// __clang_call_terminate calls __cxa_begin_catch, which then allows
1485/// std::terminate to usefully report something about the
1486/// violating exception.
1487static bool useClangCallTerminate(CodeGenModule &CGM) {
1488 // Only do this for Itanium-family ABIs in C++ mode.
1489 return (CGM.getLangOpts().CPlusPlus &&
1490 CGM.getTarget().getCXXABI().isItaniumFamily());
1491}
1492
1493/// Get or define the following function:
1494/// void @__clang_call_terminate(i8* %exn) nounwind noreturn
1495/// This code is used only in C++.
1496static llvm::Constant *getClangCallTerminateFn(CodeGenModule &CGM) {
1497 llvm::FunctionType *fnTy =
1498 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
1499 llvm::Constant *fnRef =
1500 CGM.CreateRuntimeFunction(fnTy, "__clang_call_terminate");
1501
1502 llvm::Function *fn = dyn_cast<llvm::Function>(fnRef);
1503 if (fn && fn->empty()) {
1504 fn->setDoesNotThrow();
1505 fn->setDoesNotReturn();
1506
1507 // What we really want is to massively penalize inlining without
1508 // forbidding it completely. The difference between that and
1509 // 'noinline' is negligible.
1510 fn->addFnAttr(llvm::Attribute::NoInline);
1511
1512 // Allow this function to be shared across translation units, but
1513 // we don't want it to turn into an exported symbol.
1514 fn->setLinkage(llvm::Function::LinkOnceODRLinkage);
1515 fn->setVisibility(llvm::Function::HiddenVisibility);
1516
1517 // Set up the function.
1518 llvm::BasicBlock *entry =
1519 llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn);
1520 CGBuilderTy builder(entry);
1521
1522 // Pull the exception pointer out of the parameter list.
1523 llvm::Value *exn = &*fn->arg_begin();
1524
1525 // Call __cxa_begin_catch(exn).
John McCall882987f2013-02-28 19:01:20 +00001526 llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn);
1527 catchCall->setDoesNotThrow();
1528 catchCall->setCallingConv(CGM.getRuntimeCC());
John McCalle142ad52013-02-12 03:51:46 +00001529
1530 // Call std::terminate().
1531 llvm::CallInst *termCall = builder.CreateCall(getTerminateFn(CGM));
1532 termCall->setDoesNotThrow();
1533 termCall->setDoesNotReturn();
John McCall882987f2013-02-28 19:01:20 +00001534 termCall->setCallingConv(CGM.getRuntimeCC());
John McCalle142ad52013-02-12 03:51:46 +00001535
1536 // std::terminate cannot return.
1537 builder.CreateUnreachable();
1538 }
1539
1540 return fnRef;
1541}
1542
John McCallbd309292010-07-06 01:34:17 +00001543llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
1544 if (TerminateLandingPad)
1545 return TerminateLandingPad;
1546
1547 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1548
1549 // This will get inserted at the end of the function.
1550 TerminateLandingPad = createBasicBlock("terminate.lpad");
1551 Builder.SetInsertPoint(TerminateLandingPad);
1552
1553 // Tell the backend that this is a landing pad.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001554 const EHPersonality &Personality = EHPersonality::get(CGM.getLangOpts());
Bill Wendlingf0724e82011-09-19 20:31:14 +00001555 llvm::LandingPadInst *LPadInst =
1556 Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, NULL),
1557 getOpaquePersonalityFn(CGM, Personality), 0);
1558 LPadInst->addClause(getCatchAllValue(*this));
John McCallbd309292010-07-06 01:34:17 +00001559
John McCalle142ad52013-02-12 03:51:46 +00001560 llvm::CallInst *terminateCall;
1561 if (useClangCallTerminate(CGM)) {
1562 // Extract out the exception pointer.
1563 llvm::Value *exn = Builder.CreateExtractValue(LPadInst, 0);
John McCall882987f2013-02-28 19:01:20 +00001564 terminateCall = EmitNounwindRuntimeCall(getClangCallTerminateFn(CGM), exn);
John McCalle142ad52013-02-12 03:51:46 +00001565 } else {
John McCall882987f2013-02-28 19:01:20 +00001566 terminateCall = EmitNounwindRuntimeCall(getTerminateFn(CGM));
John McCalle142ad52013-02-12 03:51:46 +00001567 }
1568 terminateCall->setDoesNotReturn();
John McCallad7c5c12011-02-08 08:22:06 +00001569 Builder.CreateUnreachable();
Mike Stumpaff69af2009-12-09 03:35:49 +00001570
John McCallbd309292010-07-06 01:34:17 +00001571 // Restore the saved insertion state.
1572 Builder.restoreIP(SavedIP);
John McCalldac3ea62010-04-30 00:06:43 +00001573
John McCallbd309292010-07-06 01:34:17 +00001574 return TerminateLandingPad;
Mike Stumpaff69af2009-12-09 03:35:49 +00001575}
Mike Stump2b488872009-12-09 22:59:31 +00001576
1577llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
Mike Stumpf5cbb082009-12-10 00:02:42 +00001578 if (TerminateHandler)
1579 return TerminateHandler;
1580
John McCallbd309292010-07-06 01:34:17 +00001581 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
Mike Stump25b20fc2009-12-09 23:31:35 +00001582
John McCallbd309292010-07-06 01:34:17 +00001583 // Set up the terminate handler. This block is inserted at the very
1584 // end of the function by FinishFunction.
Mike Stumpf5cbb082009-12-10 00:02:42 +00001585 TerminateHandler = createBasicBlock("terminate.handler");
John McCallbd309292010-07-06 01:34:17 +00001586 Builder.SetInsertPoint(TerminateHandler);
John McCallc84e4e92013-06-20 21:37:43 +00001587 llvm::CallInst *terminateCall;
1588 if (useClangCallTerminate(CGM)) {
1589 // Load the exception pointer.
1590 llvm::Value *exn = getExceptionFromSlot();
1591 terminateCall = EmitNounwindRuntimeCall(getClangCallTerminateFn(CGM), exn);
1592 } else {
1593 terminateCall = EmitNounwindRuntimeCall(getTerminateFn(CGM));
1594 }
1595 terminateCall->setDoesNotReturn();
Mike Stump2b488872009-12-09 22:59:31 +00001596 Builder.CreateUnreachable();
1597
John McCall21886962010-04-21 10:05:39 +00001598 // Restore the saved insertion state.
John McCallbd309292010-07-06 01:34:17 +00001599 Builder.restoreIP(SavedIP);
Mike Stump25b20fc2009-12-09 23:31:35 +00001600
Mike Stump2b488872009-12-09 22:59:31 +00001601 return TerminateHandler;
1602}
John McCallbd309292010-07-06 01:34:17 +00001603
David Chisnall9a837be2012-11-07 16:50:40 +00001604llvm::BasicBlock *CodeGenFunction::getEHResumeBlock(bool isCleanup) {
John McCall8e4c74b2011-08-11 02:22:43 +00001605 if (EHResumeBlock) return EHResumeBlock;
John McCallad5d61e2010-07-23 21:56:41 +00001606
1607 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1608
1609 // We emit a jump to a notional label at the outermost unwind state.
John McCall8e4c74b2011-08-11 02:22:43 +00001610 EHResumeBlock = createBasicBlock("eh.resume");
1611 Builder.SetInsertPoint(EHResumeBlock);
John McCallad5d61e2010-07-23 21:56:41 +00001612
David Blaikiebbafb8a2012-03-11 07:00:24 +00001613 const EHPersonality &Personality = EHPersonality::get(CGM.getLangOpts());
John McCallad5d61e2010-07-23 21:56:41 +00001614
1615 // This can always be a call because we necessarily didn't find
1616 // anything on the EH stack which needs our help.
Benjamin Kramer793bd552012-02-08 12:41:24 +00001617 const char *RethrowName = Personality.CatchallRethrowFn;
Craig Topper8a13c412014-05-21 05:09:00 +00001618 if (RethrowName != nullptr && !isCleanup) {
John McCall882987f2013-02-28 19:01:20 +00001619 EmitRuntimeCall(getCatchallRethrowFn(CGM, RethrowName),
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001620 getExceptionFromSlot())
John McCall9b382dd2011-05-28 21:13:02 +00001621 ->setDoesNotReturn();
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001622 Builder.CreateUnreachable();
1623 Builder.restoreIP(SavedIP);
1624 return EHResumeBlock;
John McCall9b382dd2011-05-28 21:13:02 +00001625 }
1626
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001627 // Recreate the landingpad's return value for the 'resume' instruction.
1628 llvm::Value *Exn = getExceptionFromSlot();
1629 llvm::Value *Sel = getSelectorFromSlot();
John McCallad5d61e2010-07-23 21:56:41 +00001630
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001631 llvm::Type *LPadType = llvm::StructType::get(Exn->getType(),
1632 Sel->getType(), NULL);
1633 llvm::Value *LPadVal = llvm::UndefValue::get(LPadType);
1634 LPadVal = Builder.CreateInsertValue(LPadVal, Exn, 0, "lpad.val");
1635 LPadVal = Builder.CreateInsertValue(LPadVal, Sel, 1, "lpad.val");
1636
1637 Builder.CreateResume(LPadVal);
John McCallad5d61e2010-07-23 21:56:41 +00001638 Builder.restoreIP(SavedIP);
John McCall8e4c74b2011-08-11 02:22:43 +00001639 return EHResumeBlock;
John McCallad5d61e2010-07-23 21:56:41 +00001640}
Reid Kleckner543a16c2013-09-16 21:46:30 +00001641
1642void CodeGenFunction::EmitSEHTryStmt(const SEHTryStmt &S) {
1643 CGM.ErrorUnsupported(&S, "SEH __try");
1644}
Nico Weber9b982072014-07-07 00:12:30 +00001645
1646void CodeGenFunction::EmitSEHLeaveStmt(const SEHLeaveStmt &S) {
1647 CGM.ErrorUnsupported(&S, "SEH __leave");
1648}