blob: 49f849656081fcd15d38e2c181ed5723bbf3e828 [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;
140 static const EHPersonality GNU_ObjC;
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000141 static const EHPersonality GNUstep_ObjC;
Benjamin Kramer793bd552012-02-08 12:41:24 +0000142 static const EHPersonality GNU_ObjCXX;
143 static const EHPersonality NeXT_ObjC;
144 static const EHPersonality GNU_CPlusPlus;
145 static const EHPersonality GNU_CPlusPlus_SJLJ;
146 };
147}
148
Craig Topper8a13c412014-05-21 05:09:00 +0000149const EHPersonality EHPersonality::GNU_C = { "__gcc_personality_v0", nullptr };
Benjamin Kramer793bd552012-02-08 12:41:24 +0000150const EHPersonality
Craig Topper8a13c412014-05-21 05:09:00 +0000151EHPersonality::GNU_C_SJLJ = { "__gcc_personality_sj0", nullptr };
152const EHPersonality
153EHPersonality::NeXT_ObjC = { "__objc_personality_v0", nullptr };
154const EHPersonality
155EHPersonality::GNU_CPlusPlus = { "__gxx_personality_v0", nullptr };
156const EHPersonality
157EHPersonality::GNU_CPlusPlus_SJLJ = { "__gxx_personality_sj0", nullptr };
Benjamin Kramer793bd552012-02-08 12:41:24 +0000158const EHPersonality
159EHPersonality::GNU_ObjC = {"__gnu_objc_personality_v0", "objc_exception_throw"};
160const EHPersonality
Craig Topper8a13c412014-05-21 05:09:00 +0000161EHPersonality::GNU_ObjCXX = { "__gnustep_objcxx_personality_v0", nullptr };
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000162const EHPersonality
Craig Topper8a13c412014-05-21 05:09:00 +0000163EHPersonality::GNUstep_ObjC = { "__gnustep_objc_personality_v0", nullptr };
John McCall36ea3722010-07-17 00:43:08 +0000164
165static const EHPersonality &getCPersonality(const LangOptions &L) {
John McCall2faab302010-11-07 02:35:25 +0000166 if (L.SjLjExceptions)
167 return EHPersonality::GNU_C_SJLJ;
John McCall36ea3722010-07-17 00:43:08 +0000168 return EHPersonality::GNU_C;
169}
170
171static const EHPersonality &getObjCPersonality(const LangOptions &L) {
John McCall5fb5df92012-06-20 06:18:46 +0000172 switch (L.ObjCRuntime.getKind()) {
173 case ObjCRuntime::FragileMacOSX:
174 return getCPersonality(L);
175 case ObjCRuntime::MacOSX:
176 case ObjCRuntime::iOS:
177 return EHPersonality::NeXT_ObjC;
David Chisnallb601c962012-07-03 20:49:52 +0000178 case ObjCRuntime::GNUstep:
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000179 if (L.ObjCRuntime.getVersion() >= VersionTuple(1, 7))
180 return EHPersonality::GNUstep_ObjC;
181 // fallthrough
David Chisnallb601c962012-07-03 20:49:52 +0000182 case ObjCRuntime::GCC:
John McCall775086e2012-07-12 02:07:58 +0000183 case ObjCRuntime::ObjFW:
John McCall36ea3722010-07-17 00:43:08 +0000184 return EHPersonality::GNU_ObjC;
John McCallbd309292010-07-06 01:34:17 +0000185 }
John McCall5fb5df92012-06-20 06:18:46 +0000186 llvm_unreachable("bad runtime kind");
John McCallbd309292010-07-06 01:34:17 +0000187}
188
John McCall36ea3722010-07-17 00:43:08 +0000189static const EHPersonality &getCXXPersonality(const LangOptions &L) {
190 if (L.SjLjExceptions)
191 return EHPersonality::GNU_CPlusPlus_SJLJ;
John McCallbd309292010-07-06 01:34:17 +0000192 else
John McCall36ea3722010-07-17 00:43:08 +0000193 return EHPersonality::GNU_CPlusPlus;
John McCallbd309292010-07-06 01:34:17 +0000194}
195
196/// Determines the personality function to use when both C++
197/// and Objective-C exceptions are being caught.
John McCall36ea3722010-07-17 00:43:08 +0000198static const EHPersonality &getObjCXXPersonality(const LangOptions &L) {
John McCall5fb5df92012-06-20 06:18:46 +0000199 switch (L.ObjCRuntime.getKind()) {
John McCallbd309292010-07-06 01:34:17 +0000200 // The ObjC personality defers to the C++ personality for non-ObjC
201 // handlers. Unlike the C++ case, we use the same personality
202 // function on targets using (backend-driven) SJLJ EH.
John McCall5fb5df92012-06-20 06:18:46 +0000203 case ObjCRuntime::MacOSX:
204 case ObjCRuntime::iOS:
205 return EHPersonality::NeXT_ObjC;
John McCallbd309292010-07-06 01:34:17 +0000206
John McCall5fb5df92012-06-20 06:18:46 +0000207 // In the fragile ABI, just use C++ exception handling and hope
208 // they're not doing crazy exception mixing.
209 case ObjCRuntime::FragileMacOSX:
210 return getCXXPersonality(L);
David Chisnallf9c42252010-05-17 13:49:20 +0000211
David Chisnallb601c962012-07-03 20:49:52 +0000212 // The GCC runtime's personality function inherently doesn't support
John McCall36ea3722010-07-17 00:43:08 +0000213 // mixed EH. Use the C++ personality just to avoid returning null.
David Chisnallb601c962012-07-03 20:49:52 +0000214 case ObjCRuntime::GCC:
John McCall775086e2012-07-12 02:07:58 +0000215 case ObjCRuntime::ObjFW: // XXX: this will change soon
David Chisnallb601c962012-07-03 20:49:52 +0000216 return EHPersonality::GNU_ObjC;
217 case ObjCRuntime::GNUstep:
John McCall5fb5df92012-06-20 06:18:46 +0000218 return EHPersonality::GNU_ObjCXX;
219 }
220 llvm_unreachable("bad runtime kind");
John McCallbd309292010-07-06 01:34:17 +0000221}
222
John McCall36ea3722010-07-17 00:43:08 +0000223const EHPersonality &EHPersonality::get(const LangOptions &L) {
224 if (L.CPlusPlus && L.ObjC1)
225 return getObjCXXPersonality(L);
226 else if (L.CPlusPlus)
227 return getCXXPersonality(L);
228 else if (L.ObjC1)
229 return getObjCPersonality(L);
John McCallbd309292010-07-06 01:34:17 +0000230 else
John McCall36ea3722010-07-17 00:43:08 +0000231 return getCPersonality(L);
232}
John McCallbd309292010-07-06 01:34:17 +0000233
John McCall0bdb1fd2010-09-16 06:16:50 +0000234static llvm::Constant *getPersonalityFn(CodeGenModule &CGM,
John McCall36ea3722010-07-17 00:43:08 +0000235 const EHPersonality &Personality) {
John McCall36ea3722010-07-17 00:43:08 +0000236 llvm::Constant *Fn =
Chris Lattnerece04092012-02-07 00:39:47 +0000237 CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.Int32Ty, true),
Benjamin Kramer793bd552012-02-08 12:41:24 +0000238 Personality.PersonalityFn);
John McCall0bdb1fd2010-09-16 06:16:50 +0000239 return Fn;
240}
241
242static llvm::Constant *getOpaquePersonalityFn(CodeGenModule &CGM,
243 const EHPersonality &Personality) {
244 llvm::Constant *Fn = getPersonalityFn(CGM, Personality);
John McCallad7c5c12011-02-08 08:22:06 +0000245 return llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
John McCall0bdb1fd2010-09-16 06:16:50 +0000246}
247
248/// Check whether a personality function could reasonably be swapped
249/// for a C++ personality function.
250static bool PersonalityHasOnlyCXXUses(llvm::Constant *Fn) {
Chandler Carruth4d01fff2014-03-09 03:16:50 +0000251 for (llvm::User *U : Fn->users()) {
John McCall0bdb1fd2010-09-16 06:16:50 +0000252 // Conditionally white-list bitcasts.
Chandler Carruth4d01fff2014-03-09 03:16:50 +0000253 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(U)) {
John McCall0bdb1fd2010-09-16 06:16:50 +0000254 if (CE->getOpcode() != llvm::Instruction::BitCast) return false;
255 if (!PersonalityHasOnlyCXXUses(CE))
256 return false;
257 continue;
258 }
259
Bill Wendling58e58fe2011-09-19 22:08:36 +0000260 // Otherwise, it has to be a landingpad instruction.
Chandler Carruth4d01fff2014-03-09 03:16:50 +0000261 llvm::LandingPadInst *LPI = dyn_cast<llvm::LandingPadInst>(U);
Bill Wendling58e58fe2011-09-19 22:08:36 +0000262 if (!LPI) return false;
John McCall0bdb1fd2010-09-16 06:16:50 +0000263
Bill Wendling58e58fe2011-09-19 22:08:36 +0000264 for (unsigned I = 0, E = LPI->getNumClauses(); I != E; ++I) {
John McCall0bdb1fd2010-09-16 06:16:50 +0000265 // Look for something that would've been returned by the ObjC
266 // runtime's GetEHType() method.
Bill Wendling58e58fe2011-09-19 22:08:36 +0000267 llvm::Value *Val = LPI->getClause(I)->stripPointerCasts();
268 if (LPI->isCatch(I)) {
269 // Check if the catch value has the ObjC prefix.
Bill Wendling5d7469e2011-09-20 00:40:19 +0000270 if (llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Val))
271 // ObjC EH selector entries are always global variables with
272 // names starting like this.
273 if (GV->getName().startswith("OBJC_EHTYPE"))
274 return false;
Bill Wendling58e58fe2011-09-19 22:08:36 +0000275 } else {
276 // Check if any of the filter values have the ObjC prefix.
277 llvm::Constant *CVal = cast<llvm::Constant>(Val);
278 for (llvm::User::op_iterator
279 II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II) {
Bill Wendling5d7469e2011-09-20 00:40:19 +0000280 if (llvm::GlobalVariable *GV =
281 cast<llvm::GlobalVariable>((*II)->stripPointerCasts()))
282 // ObjC EH selector entries are always global variables with
283 // names starting like this.
284 if (GV->getName().startswith("OBJC_EHTYPE"))
285 return false;
Bill Wendling58e58fe2011-09-19 22:08:36 +0000286 }
287 }
John McCall0bdb1fd2010-09-16 06:16:50 +0000288 }
289 }
290
291 return true;
292}
293
294/// Try to use the C++ personality function in ObjC++. Not doing this
295/// can cause some incompatibilities with gcc, which is more
296/// aggressive about only using the ObjC++ personality in a function
297/// when it really needs it.
298void CodeGenModule::SimplifyPersonality() {
John McCall0bdb1fd2010-09-16 06:16:50 +0000299 // If we're not in ObjC++ -fexceptions, there's nothing to do.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000300 if (!LangOpts.CPlusPlus || !LangOpts.ObjC1 || !LangOpts.Exceptions)
John McCall0bdb1fd2010-09-16 06:16:50 +0000301 return;
302
John McCall3c223932012-11-14 17:48:31 +0000303 // Both the problem this endeavors to fix and the way the logic
304 // above works is specific to the NeXT runtime.
305 if (!LangOpts.ObjCRuntime.isNeXTFamily())
306 return;
307
David Blaikiebbafb8a2012-03-11 07:00:24 +0000308 const EHPersonality &ObjCXX = EHPersonality::get(LangOpts);
309 const EHPersonality &CXX = getCXXPersonality(LangOpts);
Benjamin Kramer793bd552012-02-08 12:41:24 +0000310 if (&ObjCXX == &CXX)
John McCall0bdb1fd2010-09-16 06:16:50 +0000311 return;
312
Benjamin Kramer793bd552012-02-08 12:41:24 +0000313 assert(std::strcmp(ObjCXX.PersonalityFn, CXX.PersonalityFn) != 0 &&
314 "Different EHPersonalities using the same personality function.");
315
316 llvm::Function *Fn = getModule().getFunction(ObjCXX.PersonalityFn);
John McCall0bdb1fd2010-09-16 06:16:50 +0000317
318 // Nothing to do if it's unused.
319 if (!Fn || Fn->use_empty()) return;
320
321 // Can't do the optimization if it has non-C++ uses.
322 if (!PersonalityHasOnlyCXXUses(Fn)) return;
323
324 // Create the C++ personality function and kill off the old
325 // function.
326 llvm::Constant *CXXFn = getPersonalityFn(*this, CXX);
327
328 // This can happen if the user is screwing with us.
329 if (Fn->getType() != CXXFn->getType()) return;
330
331 Fn->replaceAllUsesWith(CXXFn);
332 Fn->eraseFromParent();
John McCallbd309292010-07-06 01:34:17 +0000333}
334
335/// Returns the value to inject into a selector to indicate the
336/// presence of a catch-all.
337static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
338 // Possibly we should use @llvm.eh.catch.all.value here.
John McCallad7c5c12011-02-08 08:22:06 +0000339 return llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
John McCallbd309292010-07-06 01:34:17 +0000340}
341
John McCallbb026012010-07-13 21:17:51 +0000342namespace {
343 /// A cleanup to free the exception object if its initialization
344 /// throws.
John McCall5fcf8da2011-07-12 00:15:30 +0000345 struct FreeException : EHScopeStack::Cleanup {
346 llvm::Value *exn;
347 FreeException(llvm::Value *exn) : exn(exn) {}
Craig Topper4f12f102014-03-12 06:41:41 +0000348 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +0000349 CGF.EmitNounwindRuntimeCall(getFreeExceptionFn(CGF.CGM), exn);
John McCallbb026012010-07-13 21:17:51 +0000350 }
351 };
352}
353
John McCall2e6567a2010-04-22 01:10:34 +0000354// Emits an exception expression into the given location. This
355// differs from EmitAnyExprToMem only in that, if a final copy-ctor
356// call is required, an exception within that copy ctor causes
357// std::terminate to be invoked.
John McCalle4df6c82011-01-28 08:37:24 +0000358static void EmitAnyExprToExn(CodeGenFunction &CGF, const Expr *e,
359 llvm::Value *addr) {
John McCallbd309292010-07-06 01:34:17 +0000360 // Make sure the exception object is cleaned up if there's an
361 // exception during initialization.
John McCalle4df6c82011-01-28 08:37:24 +0000362 CGF.pushFullExprCleanup<FreeException>(EHCleanup, addr);
363 EHScopeStack::stable_iterator cleanup = CGF.EHStack.stable_begin();
John McCall2e6567a2010-04-22 01:10:34 +0000364
365 // __cxa_allocate_exception returns a void*; we need to cast this
366 // to the appropriate type for the object.
Chris Lattner2192fe52011-07-18 04:24:23 +0000367 llvm::Type *ty = CGF.ConvertTypeForMem(e->getType())->getPointerTo();
John McCalle4df6c82011-01-28 08:37:24 +0000368 llvm::Value *typedAddr = CGF.Builder.CreateBitCast(addr, ty);
John McCall2e6567a2010-04-22 01:10:34 +0000369
370 // FIXME: this isn't quite right! If there's a final unelided call
371 // to a copy constructor, then according to [except.terminate]p1 we
372 // must call std::terminate() if that constructor throws, because
373 // technically that copy occurs after the exception expression is
374 // evaluated but before the exception is caught. But the best way
375 // to handle that is to teach EmitAggExpr to do the final copy
376 // differently if it can't be elided.
Chad Rosier615ed1a2012-03-29 17:37:10 +0000377 CGF.EmitAnyExprToMem(e, typedAddr, e->getType().getQualifiers(),
378 /*IsInit*/ true);
John McCall2e6567a2010-04-22 01:10:34 +0000379
John McCalle4df6c82011-01-28 08:37:24 +0000380 // Deactivate the cleanup block.
John McCallf4beacd2011-11-10 10:43:54 +0000381 CGF.DeactivateCleanupBlock(cleanup, cast<llvm::Instruction>(typedAddr));
Mike Stump54066142009-12-01 03:41:18 +0000382}
383
John McCallbd309292010-07-06 01:34:17 +0000384llvm::Value *CodeGenFunction::getExceptionSlot() {
John McCall9b382dd2011-05-28 21:13:02 +0000385 if (!ExceptionSlot)
386 ExceptionSlot = CreateTempAlloca(Int8PtrTy, "exn.slot");
John McCallbd309292010-07-06 01:34:17 +0000387 return ExceptionSlot;
Mike Stump54066142009-12-01 03:41:18 +0000388}
389
John McCall9b382dd2011-05-28 21:13:02 +0000390llvm::Value *CodeGenFunction::getEHSelectorSlot() {
391 if (!EHSelectorSlot)
392 EHSelectorSlot = CreateTempAlloca(Int32Ty, "ehselector.slot");
393 return EHSelectorSlot;
394}
395
Bill Wendling79a70e42011-09-15 18:57:19 +0000396llvm::Value *CodeGenFunction::getExceptionFromSlot() {
397 return Builder.CreateLoad(getExceptionSlot(), "exn");
398}
399
400llvm::Value *CodeGenFunction::getSelectorFromSlot() {
401 return Builder.CreateLoad(getEHSelectorSlot(), "sel");
402}
403
Richard Smithea852322013-05-07 21:53:22 +0000404void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E,
405 bool KeepInsertionPoint) {
Reid Klecknera82b5d82014-05-05 21:12:12 +0000406 if (CGM.getTarget().getTriple().isWindowsMSVCEnvironment()) {
407 ErrorUnsupported(E, "throw expression");
408 return;
409 }
410
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000411 if (!E->getSubExpr()) {
Craig Topper5fc8fc22014-08-27 06:28:36 +0000412 EmitNoreturnRuntimeCallOrInvoke(getReThrowFn(CGM), None);
Douglas Gregorc278d1b2010-05-16 00:44:00 +0000413
John McCall20f6ab82011-01-12 03:41:02 +0000414 // throw is an expression, and the expression emitters expect us
415 // to leave ourselves at a valid insertion point.
Richard Smithea852322013-05-07 21:53:22 +0000416 if (KeepInsertionPoint)
417 EmitBlock(createBasicBlock("throw.cont"));
John McCall20f6ab82011-01-12 03:41:02 +0000418
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000419 return;
420 }
Mike Stump75546b82009-12-10 00:06:18 +0000421
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000422 QualType ThrowType = E->getSubExpr()->getType();
Mike Stump75546b82009-12-10 00:06:18 +0000423
Fariborz Jahanian1eab0522013-01-10 19:02:56 +0000424 if (ThrowType->isObjCObjectPointerType()) {
425 const Stmt *ThrowStmt = E->getSubExpr();
426 const ObjCAtThrowStmt S(E->getExprLoc(),
427 const_cast<Stmt *>(ThrowStmt));
428 CGM.getObjCRuntime().EmitThrowStmt(*this, S, false);
429 // This will clear insertion point which was not cleared in
430 // call to EmitThrowStmt.
Richard Smithea852322013-05-07 21:53:22 +0000431 if (KeepInsertionPoint)
432 EmitBlock(createBasicBlock("throw.cont"));
Fariborz Jahanian1eab0522013-01-10 19:02:56 +0000433 return;
434 }
435
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000436 // Now allocate the exception object.
Chris Lattner2192fe52011-07-18 04:24:23 +0000437 llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
John McCall21886962010-04-21 10:05:39 +0000438 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
Mike Stump75546b82009-12-10 00:06:18 +0000439
John McCall2c33ba82013-02-12 03:51:38 +0000440 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(CGM);
John McCallbd309292010-07-06 01:34:17 +0000441 llvm::CallInst *ExceptionPtr =
John McCall882987f2013-02-28 19:01:20 +0000442 EmitNounwindRuntimeCall(AllocExceptionFn,
443 llvm::ConstantInt::get(SizeTy, TypeSize),
444 "exception");
Anders Carlssonafd1edb2009-12-11 00:32:37 +0000445
John McCall2e6567a2010-04-22 01:10:34 +0000446 EmitAnyExprToExn(*this, E->getSubExpr(), ExceptionPtr);
Mike Stump75546b82009-12-10 00:06:18 +0000447
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000448 // Now throw the exception.
Anders Carlssonba840fb2011-01-24 01:59:49 +0000449 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
450 /*ForEH=*/true);
John McCall2e6567a2010-04-22 01:10:34 +0000451
452 // The address of the destructor. If the exception type has a
453 // trivial destructor (or isn't a record), we just pass null.
Craig Topper8a13c412014-05-21 05:09:00 +0000454 llvm::Constant *Dtor = nullptr;
John McCall2e6567a2010-04-22 01:10:34 +0000455 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
456 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
457 if (!Record->hasTrivialDestructor()) {
Douglas Gregorbac74902010-07-01 14:13:13 +0000458 CXXDestructorDecl *DtorD = Record->getDestructor();
John McCall2e6567a2010-04-22 01:10:34 +0000459 Dtor = CGM.GetAddrOfCXXDestructor(DtorD, Dtor_Complete);
460 Dtor = llvm::ConstantExpr::getBitCast(Dtor, Int8PtrTy);
461 }
462 }
463 if (!Dtor) Dtor = llvm::Constant::getNullValue(Int8PtrTy);
Mike Stump75546b82009-12-10 00:06:18 +0000464
John McCall882987f2013-02-28 19:01:20 +0000465 llvm::Value *args[] = { ExceptionPtr, TypeInfo, Dtor };
466 EmitNoreturnRuntimeCallOrInvoke(getThrowFn(CGM), args);
Mike Stump75546b82009-12-10 00:06:18 +0000467
John McCall20f6ab82011-01-12 03:41:02 +0000468 // throw is an expression, and the expression emitters expect us
469 // to leave ourselves at a valid insertion point.
Richard Smithea852322013-05-07 21:53:22 +0000470 if (KeepInsertionPoint)
471 EmitBlock(createBasicBlock("throw.cont"));
Anders Carlsson4b08db72009-10-30 01:42:31 +0000472}
Mike Stump58ef18b2009-11-20 23:44:51 +0000473
Mike Stump1d849212009-12-07 23:38:24 +0000474void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000475 if (!CGM.getLangOpts().CXXExceptions)
Anders Carlsson9878f9f2010-02-06 23:59:05 +0000476 return;
477
Mike Stump1d849212009-12-07 23:38:24 +0000478 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
Craig Topper8a13c412014-05-21 05:09:00 +0000479 if (!FD) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000480 // Check if CapturedDecl is nothrow and create terminate scope for it.
481 if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
482 if (CD->isNothrow())
483 EHStack.pushTerminate();
484 }
Mike Stump1d849212009-12-07 23:38:24 +0000485 return;
Alexey Bataev9959db52014-05-06 10:08:46 +0000486 }
Mike Stump1d849212009-12-07 23:38:24 +0000487 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
Craig Topper8a13c412014-05-21 05:09:00 +0000488 if (!Proto)
Mike Stump1d849212009-12-07 23:38:24 +0000489 return;
490
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000491 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
492 if (isNoexceptExceptionSpec(EST)) {
493 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
494 // noexcept functions are simple terminate scopes.
495 EHStack.pushTerminate();
496 }
497 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
498 unsigned NumExceptions = Proto->getNumExceptions();
499 EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
Mike Stump1d849212009-12-07 23:38:24 +0000500
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000501 for (unsigned I = 0; I != NumExceptions; ++I) {
502 QualType Ty = Proto->getExceptionType(I);
503 QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
504 llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType,
505 /*ForEH=*/true);
506 Filter->setFilter(I, EHType);
507 }
Mike Stump1d849212009-12-07 23:38:24 +0000508 }
Mike Stump1d849212009-12-07 23:38:24 +0000509}
510
John McCall8e4c74b2011-08-11 02:22:43 +0000511/// Emit the dispatch block for a filter scope if necessary.
512static void emitFilterDispatchBlock(CodeGenFunction &CGF,
513 EHFilterScope &filterScope) {
514 llvm::BasicBlock *dispatchBlock = filterScope.getCachedEHDispatchBlock();
515 if (!dispatchBlock) return;
516 if (dispatchBlock->use_empty()) {
517 delete dispatchBlock;
518 return;
519 }
520
John McCall8e4c74b2011-08-11 02:22:43 +0000521 CGF.EmitBlockAfterUses(dispatchBlock);
522
523 // If this isn't a catch-all filter, we need to check whether we got
524 // here because the filter triggered.
525 if (filterScope.getNumFilters()) {
526 // Load the selector value.
Bill Wendling79a70e42011-09-15 18:57:19 +0000527 llvm::Value *selector = CGF.getSelectorFromSlot();
John McCall8e4c74b2011-08-11 02:22:43 +0000528 llvm::BasicBlock *unexpectedBB = CGF.createBasicBlock("ehspec.unexpected");
529
530 llvm::Value *zero = CGF.Builder.getInt32(0);
531 llvm::Value *failsFilter =
532 CGF.Builder.CreateICmpSLT(selector, zero, "ehspec.fails");
David Chisnall9a837be2012-11-07 16:50:40 +0000533 CGF.Builder.CreateCondBr(failsFilter, unexpectedBB, CGF.getEHResumeBlock(false));
John McCall8e4c74b2011-08-11 02:22:43 +0000534
535 CGF.EmitBlock(unexpectedBB);
536 }
537
538 // Call __cxa_call_unexpected. This doesn't need to be an invoke
539 // because __cxa_call_unexpected magically filters exceptions
540 // according to the last landing pad the exception was thrown
541 // into. Seriously.
Bill Wendling79a70e42011-09-15 18:57:19 +0000542 llvm::Value *exn = CGF.getExceptionFromSlot();
John McCall882987f2013-02-28 19:01:20 +0000543 CGF.EmitRuntimeCall(getUnexpectedFn(CGF.CGM), exn)
John McCall8e4c74b2011-08-11 02:22:43 +0000544 ->setDoesNotReturn();
545 CGF.Builder.CreateUnreachable();
546}
547
Mike Stump1d849212009-12-07 23:38:24 +0000548void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000549 if (!CGM.getLangOpts().CXXExceptions)
Anders Carlsson9878f9f2010-02-06 23:59:05 +0000550 return;
551
Mike Stump1d849212009-12-07 23:38:24 +0000552 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
Craig Topper8a13c412014-05-21 05:09:00 +0000553 if (!FD) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000554 // Check if CapturedDecl is nothrow and pop terminate scope for it.
555 if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
556 if (CD->isNothrow())
557 EHStack.popTerminate();
558 }
Mike Stump1d849212009-12-07 23:38:24 +0000559 return;
Alexey Bataev9959db52014-05-06 10:08:46 +0000560 }
Mike Stump1d849212009-12-07 23:38:24 +0000561 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
Craig Topper8a13c412014-05-21 05:09:00 +0000562 if (!Proto)
Mike Stump1d849212009-12-07 23:38:24 +0000563 return;
564
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000565 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
566 if (isNoexceptExceptionSpec(EST)) {
567 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
568 EHStack.popTerminate();
569 }
570 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
John McCall8e4c74b2011-08-11 02:22:43 +0000571 EHFilterScope &filterScope = cast<EHFilterScope>(*EHStack.begin());
572 emitFilterDispatchBlock(*this, filterScope);
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000573 EHStack.popFilter();
574 }
Mike Stump1d849212009-12-07 23:38:24 +0000575}
576
Mike Stump58ef18b2009-11-20 23:44:51 +0000577void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
Reid Klecknera82b5d82014-05-05 21:12:12 +0000578 if (CGM.getTarget().getTriple().isWindowsMSVCEnvironment()) {
579 ErrorUnsupported(&S, "try statement");
580 return;
581 }
582
John McCallb609d3f2010-07-07 06:56:46 +0000583 EnterCXXTryStmt(S);
John McCallb81884d2010-02-19 09:25:03 +0000584 EmitStmt(S.getTryBlock());
John McCallb609d3f2010-07-07 06:56:46 +0000585 ExitCXXTryStmt(S);
John McCallb81884d2010-02-19 09:25:03 +0000586}
587
John McCallb609d3f2010-07-07 06:56:46 +0000588void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallbd309292010-07-06 01:34:17 +0000589 unsigned NumHandlers = S.getNumHandlers();
590 EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
John McCallb81884d2010-02-19 09:25:03 +0000591
John McCallbd309292010-07-06 01:34:17 +0000592 for (unsigned I = 0; I != NumHandlers; ++I) {
593 const CXXCatchStmt *C = S.getHandler(I);
John McCallb81884d2010-02-19 09:25:03 +0000594
John McCallbd309292010-07-06 01:34:17 +0000595 llvm::BasicBlock *Handler = createBasicBlock("catch");
596 if (C->getExceptionDecl()) {
597 // FIXME: Dropping the reference type on the type into makes it
598 // impossible to correctly implement catch-by-reference
599 // semantics for pointers. Unfortunately, this is what all
600 // existing compilers do, and it's not clear that the standard
601 // personality routine is capable of doing this right. See C++ DR 388:
602 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
603 QualType CaughtType = C->getCaughtType();
604 CaughtType = CaughtType.getNonReferenceType().getUnqualifiedType();
John McCall2ca705e2010-07-24 00:37:23 +0000605
Rafael Espindolabb9e7a32014-06-04 18:51:46 +0000606 llvm::Constant *TypeInfo = nullptr;
John McCall2ca705e2010-07-24 00:37:23 +0000607 if (CaughtType->isObjCObjectPointerType())
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +0000608 TypeInfo = CGM.getObjCRuntime().GetEHType(CaughtType);
John McCall2ca705e2010-07-24 00:37:23 +0000609 else
Anders Carlssonba840fb2011-01-24 01:59:49 +0000610 TypeInfo = CGM.GetAddrOfRTTIDescriptor(CaughtType, /*ForEH=*/true);
John McCallbd309292010-07-06 01:34:17 +0000611 CatchScope->setHandler(I, TypeInfo, Handler);
612 } else {
613 // No exception decl indicates '...', a catch-all.
614 CatchScope->setCatchAllHandler(I, Handler);
615 }
616 }
John McCallbd309292010-07-06 01:34:17 +0000617}
618
John McCall8e4c74b2011-08-11 02:22:43 +0000619llvm::BasicBlock *
620CodeGenFunction::getEHDispatchBlock(EHScopeStack::stable_iterator si) {
621 // The dispatch block for the end of the scope chain is a block that
622 // just resumes unwinding.
623 if (si == EHStack.stable_end())
David Chisnall9a837be2012-11-07 16:50:40 +0000624 return getEHResumeBlock(true);
John McCall8e4c74b2011-08-11 02:22:43 +0000625
626 // Otherwise, we should look at the actual scope.
627 EHScope &scope = *EHStack.find(si);
628
629 llvm::BasicBlock *dispatchBlock = scope.getCachedEHDispatchBlock();
630 if (!dispatchBlock) {
631 switch (scope.getKind()) {
632 case EHScope::Catch: {
633 // Apply a special case to a single catch-all.
634 EHCatchScope &catchScope = cast<EHCatchScope>(scope);
635 if (catchScope.getNumHandlers() == 1 &&
636 catchScope.getHandler(0).isCatchAll()) {
637 dispatchBlock = catchScope.getHandler(0).Block;
638
639 // Otherwise, make a dispatch block.
640 } else {
641 dispatchBlock = createBasicBlock("catch.dispatch");
642 }
643 break;
644 }
645
646 case EHScope::Cleanup:
647 dispatchBlock = createBasicBlock("ehcleanup");
648 break;
649
650 case EHScope::Filter:
651 dispatchBlock = createBasicBlock("filter.dispatch");
652 break;
653
654 case EHScope::Terminate:
655 dispatchBlock = getTerminateHandler();
656 break;
657 }
658 scope.setCachedEHDispatchBlock(dispatchBlock);
659 }
660 return dispatchBlock;
661}
662
John McCallbd309292010-07-06 01:34:17 +0000663/// Check whether this is a non-EH scope, i.e. a scope which doesn't
664/// affect exception handling. Currently, the only non-EH scopes are
665/// normal-only cleanup scopes.
666static bool isNonEHScope(const EHScope &S) {
John McCall2b7fc382010-07-13 20:32:21 +0000667 switch (S.getKind()) {
John McCallcda666c2010-07-21 07:22:38 +0000668 case EHScope::Cleanup:
669 return !cast<EHCleanupScope>(S).isEHCleanup();
John McCall2b7fc382010-07-13 20:32:21 +0000670 case EHScope::Filter:
671 case EHScope::Catch:
672 case EHScope::Terminate:
673 return false;
674 }
675
David Blaikiee4d798f2012-01-20 21:50:17 +0000676 llvm_unreachable("Invalid EHScope Kind!");
John McCallbd309292010-07-06 01:34:17 +0000677}
678
679llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
680 assert(EHStack.requiresLandingPad());
681 assert(!EHStack.empty());
682
David Blaikiebbafb8a2012-03-11 07:00:24 +0000683 if (!CGM.getLangOpts().Exceptions)
Craig Topper8a13c412014-05-21 05:09:00 +0000684 return nullptr;
John McCall2b7fc382010-07-13 20:32:21 +0000685
John McCallbd309292010-07-06 01:34:17 +0000686 // Check the innermost scope for a cached landing pad. If this is
687 // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
688 llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
689 if (LP) return LP;
690
691 // Build the landing pad for this scope.
692 LP = EmitLandingPad();
693 assert(LP);
694
695 // Cache the landing pad on the innermost scope. If this is a
696 // non-EH scope, cache the landing pad on the enclosing scope, too.
697 for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
698 ir->setCachedLandingPad(LP);
699 if (!isNonEHScope(*ir)) break;
700 }
701
702 return LP;
703}
704
705llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
706 assert(EHStack.requiresLandingPad());
707
John McCall8e4c74b2011-08-11 02:22:43 +0000708 EHScope &innermostEHScope = *EHStack.find(EHStack.getInnermostEHScope());
709 switch (innermostEHScope.getKind()) {
710 case EHScope::Terminate:
711 return getTerminateLandingPad();
John McCallbd309292010-07-06 01:34:17 +0000712
John McCall8e4c74b2011-08-11 02:22:43 +0000713 case EHScope::Catch:
714 case EHScope::Cleanup:
715 case EHScope::Filter:
716 if (llvm::BasicBlock *lpad = innermostEHScope.getCachedLandingPad())
717 return lpad;
John McCallbd309292010-07-06 01:34:17 +0000718 }
719
720 // Save the current IR generation state.
John McCall8e4c74b2011-08-11 02:22:43 +0000721 CGBuilderTy::InsertPoint savedIP = Builder.saveAndClearIP();
Adrian Prantld1b151e2014-01-17 00:15:10 +0000722 SaveAndRestoreLocation AutoRestoreLocation(*this, Builder);
723 if (CGDebugInfo *DI = getDebugInfo())
Adrian Prantl5e5ff6e2013-05-16 00:41:29 +0000724 DI->EmitLocation(Builder, CurEHLocation);
John McCallbd309292010-07-06 01:34:17 +0000725
David Blaikiebbafb8a2012-03-11 07:00:24 +0000726 const EHPersonality &personality = EHPersonality::get(getLangOpts());
John McCall36ea3722010-07-17 00:43:08 +0000727
John McCallbd309292010-07-06 01:34:17 +0000728 // Create and configure the landing pad.
John McCall8e4c74b2011-08-11 02:22:43 +0000729 llvm::BasicBlock *lpad = createBasicBlock("lpad");
730 EmitBlock(lpad);
John McCallbd309292010-07-06 01:34:17 +0000731
Bill Wendlingf0724e82011-09-19 20:31:14 +0000732 llvm::LandingPadInst *LPadInst =
733 Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, NULL),
734 getOpaquePersonalityFn(CGM, personality), 0);
735
736 llvm::Value *LPadExn = Builder.CreateExtractValue(LPadInst, 0);
737 Builder.CreateStore(LPadExn, getExceptionSlot());
738 llvm::Value *LPadSel = Builder.CreateExtractValue(LPadInst, 1);
739 Builder.CreateStore(LPadSel, getEHSelectorSlot());
740
John McCallbd309292010-07-06 01:34:17 +0000741 // Save the exception pointer. It's safe to use a single exception
742 // pointer per function because EH cleanups can never have nested
743 // try/catches.
Bill Wendlingf0724e82011-09-19 20:31:14 +0000744 // Build the landingpad instruction.
John McCallbd309292010-07-06 01:34:17 +0000745
746 // Accumulate all the handlers in scope.
John McCall8e4c74b2011-08-11 02:22:43 +0000747 bool hasCatchAll = false;
748 bool hasCleanup = false;
749 bool hasFilter = false;
750 SmallVector<llvm::Value*, 4> filterTypes;
751 llvm::SmallPtrSet<llvm::Value*, 4> catchTypes;
John McCallbd309292010-07-06 01:34:17 +0000752 for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end();
753 I != E; ++I) {
754
755 switch (I->getKind()) {
John McCallcda666c2010-07-21 07:22:38 +0000756 case EHScope::Cleanup:
John McCall8e4c74b2011-08-11 02:22:43 +0000757 // If we have a cleanup, remember that.
758 hasCleanup = (hasCleanup || cast<EHCleanupScope>(*I).isEHCleanup());
John McCall2b7fc382010-07-13 20:32:21 +0000759 continue;
760
John McCallbd309292010-07-06 01:34:17 +0000761 case EHScope::Filter: {
762 assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
John McCall8e4c74b2011-08-11 02:22:43 +0000763 assert(!hasCatchAll && "EH filter reached after catch-all");
John McCallbd309292010-07-06 01:34:17 +0000764
Bill Wendlingf0724e82011-09-19 20:31:14 +0000765 // Filter scopes get added to the landingpad in weird ways.
John McCall8e4c74b2011-08-11 02:22:43 +0000766 EHFilterScope &filter = cast<EHFilterScope>(*I);
767 hasFilter = true;
John McCallbd309292010-07-06 01:34:17 +0000768
Bill Wendling8c4b7162011-09-22 20:32:54 +0000769 // Add all the filter values.
770 for (unsigned i = 0, e = filter.getNumFilters(); i != e; ++i)
771 filterTypes.push_back(filter.getFilter(i));
John McCallbd309292010-07-06 01:34:17 +0000772 goto done;
773 }
774
775 case EHScope::Terminate:
776 // Terminate scopes are basically catch-alls.
John McCall8e4c74b2011-08-11 02:22:43 +0000777 assert(!hasCatchAll);
778 hasCatchAll = true;
John McCallbd309292010-07-06 01:34:17 +0000779 goto done;
780
781 case EHScope::Catch:
782 break;
783 }
784
John McCall8e4c74b2011-08-11 02:22:43 +0000785 EHCatchScope &catchScope = cast<EHCatchScope>(*I);
786 for (unsigned hi = 0, he = catchScope.getNumHandlers(); hi != he; ++hi) {
787 EHCatchScope::Handler handler = catchScope.getHandler(hi);
John McCallbd309292010-07-06 01:34:17 +0000788
John McCall8e4c74b2011-08-11 02:22:43 +0000789 // If this is a catch-all, register that and abort.
790 if (!handler.Type) {
791 assert(!hasCatchAll);
792 hasCatchAll = true;
793 goto done;
John McCallbd309292010-07-06 01:34:17 +0000794 }
795
796 // Check whether we already have a handler for this type.
Bill Wendlingf0724e82011-09-19 20:31:14 +0000797 if (catchTypes.insert(handler.Type))
798 // If not, add it directly to the landingpad.
799 LPadInst->addClause(handler.Type);
John McCallbd309292010-07-06 01:34:17 +0000800 }
John McCallbd309292010-07-06 01:34:17 +0000801 }
802
803 done:
Bill Wendlingf0724e82011-09-19 20:31:14 +0000804 // If we have a catch-all, add null to the landingpad.
John McCall8e4c74b2011-08-11 02:22:43 +0000805 assert(!(hasCatchAll && hasFilter));
806 if (hasCatchAll) {
Bill Wendlingf0724e82011-09-19 20:31:14 +0000807 LPadInst->addClause(getCatchAllValue(*this));
John McCallbd309292010-07-06 01:34:17 +0000808
809 // If we have an EH filter, we need to add those handlers in the
Bill Wendlingf0724e82011-09-19 20:31:14 +0000810 // right place in the landingpad, which is to say, at the end.
John McCall8e4c74b2011-08-11 02:22:43 +0000811 } else if (hasFilter) {
Bill Wendling58e58fe2011-09-19 22:08:36 +0000812 // Create a filter expression: a constant array indicating which filter
813 // types there are. The personality routine only lands here if the filter
814 // doesn't match.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000815 SmallVector<llvm::Constant*, 8> Filters;
Bill Wendlingf0724e82011-09-19 20:31:14 +0000816 llvm::ArrayType *AType =
817 llvm::ArrayType::get(!filterTypes.empty() ?
818 filterTypes[0]->getType() : Int8PtrTy,
819 filterTypes.size());
820
821 for (unsigned i = 0, e = filterTypes.size(); i != e; ++i)
822 Filters.push_back(cast<llvm::Constant>(filterTypes[i]));
823 llvm::Constant *FilterArray = llvm::ConstantArray::get(AType, Filters);
824 LPadInst->addClause(FilterArray);
John McCallbd309292010-07-06 01:34:17 +0000825
826 // Also check whether we need a cleanup.
Bill Wendlingf0724e82011-09-19 20:31:14 +0000827 if (hasCleanup)
828 LPadInst->setCleanup(true);
John McCallbd309292010-07-06 01:34:17 +0000829
830 // Otherwise, signal that we at least have cleanups.
Logan Chiene9c8ccb2014-07-01 11:47:10 +0000831 } else if (hasCleanup) {
832 LPadInst->setCleanup(true);
John McCallbd309292010-07-06 01:34:17 +0000833 }
834
Bill Wendlingf0724e82011-09-19 20:31:14 +0000835 assert((LPadInst->getNumClauses() > 0 || LPadInst->isCleanup()) &&
836 "landingpad instruction has no clauses!");
John McCallbd309292010-07-06 01:34:17 +0000837
838 // Tell the backend how to generate the landing pad.
John McCall8e4c74b2011-08-11 02:22:43 +0000839 Builder.CreateBr(getEHDispatchBlock(EHStack.getInnermostEHScope()));
John McCallbd309292010-07-06 01:34:17 +0000840
841 // Restore the old IR generation state.
John McCall8e4c74b2011-08-11 02:22:43 +0000842 Builder.restoreIP(savedIP);
John McCallbd309292010-07-06 01:34:17 +0000843
John McCall8e4c74b2011-08-11 02:22:43 +0000844 return lpad;
John McCallbd309292010-07-06 01:34:17 +0000845}
846
John McCall5c08ab92010-07-13 22:12:14 +0000847namespace {
848 /// A cleanup to call __cxa_end_catch. In many cases, the caught
849 /// exception type lets us state definitively that the thrown exception
850 /// type does not have a destructor. In particular:
851 /// - Catch-alls tell us nothing, so we have to conservatively
852 /// assume that the thrown exception might have a destructor.
853 /// - Catches by reference behave according to their base types.
854 /// - Catches of non-record types will only trigger for exceptions
855 /// of non-record types, which never have destructors.
856 /// - Catches of record types can trigger for arbitrary subclasses
857 /// of the caught type, so we have to assume the actual thrown
858 /// exception type might have a throwing destructor, even if the
859 /// caught type's destructor is trivial or nothrow.
John McCallcda666c2010-07-21 07:22:38 +0000860 struct CallEndCatch : EHScopeStack::Cleanup {
John McCall5c08ab92010-07-13 22:12:14 +0000861 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
862 bool MightThrow;
863
Craig Topper4f12f102014-03-12 06:41:41 +0000864 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall5c08ab92010-07-13 22:12:14 +0000865 if (!MightThrow) {
John McCall882987f2013-02-28 19:01:20 +0000866 CGF.EmitNounwindRuntimeCall(getEndCatchFn(CGF.CGM));
John McCall5c08ab92010-07-13 22:12:14 +0000867 return;
868 }
869
John McCall882987f2013-02-28 19:01:20 +0000870 CGF.EmitRuntimeCallOrInvoke(getEndCatchFn(CGF.CGM));
John McCall5c08ab92010-07-13 22:12:14 +0000871 }
872 };
873}
874
John McCallbd309292010-07-06 01:34:17 +0000875/// Emits a call to __cxa_begin_catch and enters a cleanup to call
876/// __cxa_end_catch.
John McCall5c08ab92010-07-13 22:12:14 +0000877///
878/// \param EndMightThrow - true if __cxa_end_catch might throw
879static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
880 llvm::Value *Exn,
881 bool EndMightThrow) {
John McCall882987f2013-02-28 19:01:20 +0000882 llvm::CallInst *call =
883 CGF.EmitNounwindRuntimeCall(getBeginCatchFn(CGF.CGM), Exn);
John McCallbd309292010-07-06 01:34:17 +0000884
John McCallcda666c2010-07-21 07:22:38 +0000885 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
John McCallbd309292010-07-06 01:34:17 +0000886
John McCall882987f2013-02-28 19:01:20 +0000887 return call;
John McCallbd309292010-07-06 01:34:17 +0000888}
889
890/// A "special initializer" callback for initializing a catch
891/// parameter during catch initialization.
892static void InitCatchParam(CodeGenFunction &CGF,
893 const VarDecl &CatchParam,
Nick Lewycky2d84e842013-10-02 02:29:49 +0000894 llvm::Value *ParamAddr,
895 SourceLocation Loc) {
John McCallbd309292010-07-06 01:34:17 +0000896 // Load the exception from where the landing pad saved it.
Bill Wendling79a70e42011-09-15 18:57:19 +0000897 llvm::Value *Exn = CGF.getExceptionFromSlot();
John McCallbd309292010-07-06 01:34:17 +0000898
899 CanQualType CatchType =
900 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
Chris Lattner2192fe52011-07-18 04:24:23 +0000901 llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
John McCallbd309292010-07-06 01:34:17 +0000902
903 // If we're catching by reference, we can just cast the object
904 // pointer to the appropriate pointer.
905 if (isa<ReferenceType>(CatchType)) {
John McCall5add20c2010-07-20 22:17:55 +0000906 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
907 bool EndCatchMightThrow = CaughtType->isRecordType();
John McCall5c08ab92010-07-13 22:12:14 +0000908
John McCallbd309292010-07-06 01:34:17 +0000909 // __cxa_begin_catch returns the adjusted object pointer.
John McCall5c08ab92010-07-13 22:12:14 +0000910 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
John McCall5add20c2010-07-20 22:17:55 +0000911
912 // We have no way to tell the personality function that we're
913 // catching by reference, so if we're catching a pointer,
914 // __cxa_begin_catch will actually return that pointer by value.
915 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
916 QualType PointeeType = PT->getPointeeType();
917
918 // When catching by reference, generally we should just ignore
919 // this by-value pointer and use the exception object instead.
920 if (!PointeeType->isRecordType()) {
921
922 // Exn points to the struct _Unwind_Exception header, which
923 // we have to skip past in order to reach the exception data.
924 unsigned HeaderSize =
925 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
926 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
927
928 // However, if we're catching a pointer-to-record type that won't
929 // work, because the personality function might have adjusted
930 // the pointer. There's actually no way for us to fully satisfy
931 // the language/ABI contract here: we can't use Exn because it
932 // might have the wrong adjustment, but we can't use the by-value
933 // pointer because it's off by a level of abstraction.
934 //
935 // The current solution is to dump the adjusted pointer into an
936 // alloca, which breaks language semantics (because changing the
937 // pointer doesn't change the exception) but at least works.
938 // The better solution would be to filter out non-exact matches
939 // and rethrow them, but this is tricky because the rethrow
940 // really needs to be catchable by other sites at this landing
941 // pad. The best solution is to fix the personality function.
942 } else {
943 // Pull the pointer for the reference type off.
Chris Lattner2192fe52011-07-18 04:24:23 +0000944 llvm::Type *PtrTy =
John McCall5add20c2010-07-20 22:17:55 +0000945 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
946
947 // Create the temporary and write the adjusted pointer into it.
948 llvm::Value *ExnPtrTmp = CGF.CreateTempAlloca(PtrTy, "exn.byref.tmp");
949 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
950 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
951
952 // Bind the reference to the temporary.
953 AdjustedExn = ExnPtrTmp;
954 }
955 }
956
John McCallbd309292010-07-06 01:34:17 +0000957 llvm::Value *ExnCast =
958 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
959 CGF.Builder.CreateStore(ExnCast, ParamAddr);
960 return;
961 }
962
John McCall47fb9502013-03-07 21:37:08 +0000963 // Scalars and complexes.
964 TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType);
965 if (TEK != TEK_Aggregate) {
John McCall5c08ab92010-07-13 22:12:14 +0000966 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
John McCallbd309292010-07-06 01:34:17 +0000967
968 // If the catch type is a pointer type, __cxa_begin_catch returns
969 // the pointer by value.
970 if (CatchType->hasPointerRepresentation()) {
971 llvm::Value *CastExn =
972 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
John McCall97017312012-01-17 20:16:56 +0000973
974 switch (CatchType.getQualifiers().getObjCLifetime()) {
975 case Qualifiers::OCL_Strong:
976 CastExn = CGF.EmitARCRetainNonBlock(CastExn);
977 // fallthrough
978
979 case Qualifiers::OCL_None:
980 case Qualifiers::OCL_ExplicitNone:
981 case Qualifiers::OCL_Autoreleasing:
982 CGF.Builder.CreateStore(CastExn, ParamAddr);
983 return;
984
985 case Qualifiers::OCL_Weak:
986 CGF.EmitARCInitWeak(ParamAddr, CastExn);
987 return;
988 }
989 llvm_unreachable("bad ownership qualifier!");
John McCallbd309292010-07-06 01:34:17 +0000990 }
991
992 // Otherwise, it returns a pointer into the exception object.
993
Chris Lattner2192fe52011-07-18 04:24:23 +0000994 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
John McCallbd309292010-07-06 01:34:17 +0000995 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
996
John McCall47fb9502013-03-07 21:37:08 +0000997 LValue srcLV = CGF.MakeNaturalAlignAddrLValue(Cast, CatchType);
998 LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType,
999 CGF.getContext().getDeclAlign(&CatchParam));
1000 switch (TEK) {
1001 case TEK_Complex:
Nick Lewycky2d84e842013-10-02 02:29:49 +00001002 CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV,
John McCall47fb9502013-03-07 21:37:08 +00001003 /*init*/ true);
1004 return;
1005 case TEK_Scalar: {
Nick Lewycky2d84e842013-10-02 02:29:49 +00001006 llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc);
John McCall47fb9502013-03-07 21:37:08 +00001007 CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true);
1008 return;
John McCallbd309292010-07-06 01:34:17 +00001009 }
John McCall47fb9502013-03-07 21:37:08 +00001010 case TEK_Aggregate:
1011 llvm_unreachable("evaluation kind filtered out!");
1012 }
1013 llvm_unreachable("bad evaluation kind");
John McCallbd309292010-07-06 01:34:17 +00001014 }
1015
John McCallb5011ab2011-02-16 08:39:19 +00001016 assert(isa<RecordType>(CatchType) && "unexpected catch type!");
John McCallbd309292010-07-06 01:34:17 +00001017
Chris Lattner2192fe52011-07-18 04:24:23 +00001018 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
John McCallbd309292010-07-06 01:34:17 +00001019
John McCallb5011ab2011-02-16 08:39:19 +00001020 // Check for a copy expression. If we don't have a copy expression,
1021 // that means a trivial copy is okay.
John McCall1bf58462011-02-16 08:02:54 +00001022 const Expr *copyExpr = CatchParam.getInit();
1023 if (!copyExpr) {
John McCallb5011ab2011-02-16 08:39:19 +00001024 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
1025 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
Chad Rosier615ed1a2012-03-29 17:37:10 +00001026 CGF.EmitAggregateCopy(ParamAddr, adjustedExn, CatchType);
John McCallbd309292010-07-06 01:34:17 +00001027 return;
1028 }
1029
1030 // We have to call __cxa_get_exception_ptr to get the adjusted
1031 // pointer before copying.
John McCall1bf58462011-02-16 08:02:54 +00001032 llvm::CallInst *rawAdjustedExn =
John McCall882987f2013-02-28 19:01:20 +00001033 CGF.EmitNounwindRuntimeCall(getGetExceptionPtrFn(CGF.CGM), Exn);
John McCallbd309292010-07-06 01:34:17 +00001034
John McCall1bf58462011-02-16 08:02:54 +00001035 // Cast that to the appropriate type.
1036 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
John McCallbd309292010-07-06 01:34:17 +00001037
John McCall1bf58462011-02-16 08:02:54 +00001038 // The copy expression is defined in terms of an OpaqueValueExpr.
1039 // Find it and map it to the adjusted expression.
1040 CodeGenFunction::OpaqueValueMapping
John McCallc07a0c72011-02-17 10:25:35 +00001041 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
1042 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
John McCallbd309292010-07-06 01:34:17 +00001043
1044 // Call the copy ctor in a terminate scope.
1045 CGF.EHStack.pushTerminate();
John McCall1bf58462011-02-16 08:02:54 +00001046
1047 // Perform the copy construction.
Eli Friedman38cd36d2011-12-03 02:13:40 +00001048 CharUnits Alignment = CGF.getContext().getDeclAlign(&CatchParam);
Eli Friedmanc1d85b92011-12-03 00:54:26 +00001049 CGF.EmitAggExpr(copyExpr,
1050 AggValueSlot::forAddr(ParamAddr, Alignment, Qualifiers(),
1051 AggValueSlot::IsNotDestructed,
1052 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001053 AggValueSlot::IsNotAliased));
John McCall1bf58462011-02-16 08:02:54 +00001054
1055 // Leave the terminate scope.
John McCallbd309292010-07-06 01:34:17 +00001056 CGF.EHStack.popTerminate();
1057
John McCall1bf58462011-02-16 08:02:54 +00001058 // Undo the opaque value mapping.
1059 opaque.pop();
1060
John McCallbd309292010-07-06 01:34:17 +00001061 // Finally we can call __cxa_begin_catch.
John McCall5c08ab92010-07-13 22:12:14 +00001062 CallBeginCatch(CGF, Exn, true);
John McCallbd309292010-07-06 01:34:17 +00001063}
1064
1065/// Begins a catch statement by initializing the catch variable and
1066/// calling __cxa_begin_catch.
John McCall1bf58462011-02-16 08:02:54 +00001067static void BeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *S) {
John McCallbd309292010-07-06 01:34:17 +00001068 // We have to be very careful with the ordering of cleanups here:
1069 // C++ [except.throw]p4:
1070 // The destruction [of the exception temporary] occurs
1071 // immediately after the destruction of the object declared in
1072 // the exception-declaration in the handler.
1073 //
1074 // So the precise ordering is:
1075 // 1. Construct catch variable.
1076 // 2. __cxa_begin_catch
1077 // 3. Enter __cxa_end_catch cleanup
1078 // 4. Enter dtor cleanup
1079 //
John McCallc533cb72011-02-22 06:44:22 +00001080 // We do this by using a slightly abnormal initialization process.
1081 // Delegation sequence:
John McCallbd309292010-07-06 01:34:17 +00001082 // - ExitCXXTryStmt opens a RunCleanupsScope
John McCallc533cb72011-02-22 06:44:22 +00001083 // - EmitAutoVarAlloca creates the variable and debug info
John McCallbd309292010-07-06 01:34:17 +00001084 // - InitCatchParam initializes the variable from the exception
John McCallc533cb72011-02-22 06:44:22 +00001085 // - CallBeginCatch calls __cxa_begin_catch
1086 // - CallBeginCatch enters the __cxa_end_catch cleanup
1087 // - EmitAutoVarCleanups enters the variable destructor cleanup
John McCallbd309292010-07-06 01:34:17 +00001088 // - EmitCXXTryStmt emits the code for the catch body
1089 // - EmitCXXTryStmt close the RunCleanupsScope
1090
1091 VarDecl *CatchParam = S->getExceptionDecl();
1092 if (!CatchParam) {
Bill Wendling79a70e42011-09-15 18:57:19 +00001093 llvm::Value *Exn = CGF.getExceptionFromSlot();
John McCall5c08ab92010-07-13 22:12:14 +00001094 CallBeginCatch(CGF, Exn, true);
John McCallbd309292010-07-06 01:34:17 +00001095 return;
1096 }
1097
1098 // Emit the local.
John McCallc533cb72011-02-22 06:44:22 +00001099 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
Nick Lewycky2d84e842013-10-02 02:29:49 +00001100 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF), S->getLocStart());
John McCallc533cb72011-02-22 06:44:22 +00001101 CGF.EmitAutoVarCleanups(var);
John McCallb81884d2010-02-19 09:25:03 +00001102}
1103
John McCall8e4c74b2011-08-11 02:22:43 +00001104/// Emit the structure of the dispatch block for the given catch scope.
1105/// It is an invariant that the dispatch block already exists.
1106static void emitCatchDispatchBlock(CodeGenFunction &CGF,
1107 EHCatchScope &catchScope) {
1108 llvm::BasicBlock *dispatchBlock = catchScope.getCachedEHDispatchBlock();
1109 assert(dispatchBlock);
1110
1111 // If there's only a single catch-all, getEHDispatchBlock returned
1112 // that catch-all as the dispatch block.
1113 if (catchScope.getNumHandlers() == 1 &&
1114 catchScope.getHandler(0).isCatchAll()) {
1115 assert(dispatchBlock == catchScope.getHandler(0).Block);
1116 return;
1117 }
1118
1119 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveIP();
1120 CGF.EmitBlockAfterUses(dispatchBlock);
1121
1122 // Select the right handler.
1123 llvm::Value *llvm_eh_typeid_for =
1124 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
1125
1126 // Load the selector value.
Bill Wendling79a70e42011-09-15 18:57:19 +00001127 llvm::Value *selector = CGF.getSelectorFromSlot();
John McCall8e4c74b2011-08-11 02:22:43 +00001128
1129 // Test against each of the exception types we claim to catch.
1130 for (unsigned i = 0, e = catchScope.getNumHandlers(); ; ++i) {
1131 assert(i < e && "ran off end of handlers!");
1132 const EHCatchScope::Handler &handler = catchScope.getHandler(i);
1133
1134 llvm::Value *typeValue = handler.Type;
1135 assert(typeValue && "fell into catch-all case!");
1136 typeValue = CGF.Builder.CreateBitCast(typeValue, CGF.Int8PtrTy);
1137
1138 // Figure out the next block.
1139 bool nextIsEnd;
1140 llvm::BasicBlock *nextBlock;
1141
1142 // If this is the last handler, we're at the end, and the next
1143 // block is the block for the enclosing EH scope.
1144 if (i + 1 == e) {
1145 nextBlock = CGF.getEHDispatchBlock(catchScope.getEnclosingEHScope());
1146 nextIsEnd = true;
1147
1148 // If the next handler is a catch-all, we're at the end, and the
1149 // next block is that handler.
1150 } else if (catchScope.getHandler(i+1).isCatchAll()) {
1151 nextBlock = catchScope.getHandler(i+1).Block;
1152 nextIsEnd = true;
1153
1154 // Otherwise, we're not at the end and we need a new block.
1155 } else {
1156 nextBlock = CGF.createBasicBlock("catch.fallthrough");
1157 nextIsEnd = false;
1158 }
1159
1160 // Figure out the catch type's index in the LSDA's type table.
1161 llvm::CallInst *typeIndex =
1162 CGF.Builder.CreateCall(llvm_eh_typeid_for, typeValue);
1163 typeIndex->setDoesNotThrow();
1164
1165 llvm::Value *matchesTypeIndex =
1166 CGF.Builder.CreateICmpEQ(selector, typeIndex, "matches");
1167 CGF.Builder.CreateCondBr(matchesTypeIndex, handler.Block, nextBlock);
1168
1169 // If the next handler is a catch-all, we're completely done.
1170 if (nextIsEnd) {
1171 CGF.Builder.restoreIP(savedIP);
1172 return;
John McCall8e4c74b2011-08-11 02:22:43 +00001173 }
Ahmed Charles289896d2012-02-19 11:57:29 +00001174 // Otherwise we need to emit and continue at that block.
1175 CGF.EmitBlock(nextBlock);
John McCall8e4c74b2011-08-11 02:22:43 +00001176 }
John McCall8e4c74b2011-08-11 02:22:43 +00001177}
1178
1179void CodeGenFunction::popCatchScope() {
1180 EHCatchScope &catchScope = cast<EHCatchScope>(*EHStack.begin());
1181 if (catchScope.hasEHBranches())
1182 emitCatchDispatchBlock(*this, catchScope);
1183 EHStack.popCatch();
1184}
1185
John McCallb609d3f2010-07-07 06:56:46 +00001186void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallbd309292010-07-06 01:34:17 +00001187 unsigned NumHandlers = S.getNumHandlers();
1188 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1189 assert(CatchScope.getNumHandlers() == NumHandlers);
Mike Stump58ef18b2009-11-20 23:44:51 +00001190
John McCall8e4c74b2011-08-11 02:22:43 +00001191 // If the catch was not required, bail out now.
1192 if (!CatchScope.hasEHBranches()) {
Kostya Serebryanyba4aced2014-01-09 09:22:32 +00001193 CatchScope.clearHandlerBlocks();
John McCall8e4c74b2011-08-11 02:22:43 +00001194 EHStack.popCatch();
1195 return;
1196 }
1197
1198 // Emit the structure of the EH dispatch for this catch.
1199 emitCatchDispatchBlock(*this, CatchScope);
1200
John McCallbd309292010-07-06 01:34:17 +00001201 // Copy the handler blocks off before we pop the EH stack. Emitting
1202 // the handlers might scribble on this memory.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001203 SmallVector<EHCatchScope::Handler, 8> Handlers(NumHandlers);
John McCallbd309292010-07-06 01:34:17 +00001204 memcpy(Handlers.data(), CatchScope.begin(),
1205 NumHandlers * sizeof(EHCatchScope::Handler));
John McCall8e4c74b2011-08-11 02:22:43 +00001206
John McCallbd309292010-07-06 01:34:17 +00001207 EHStack.popCatch();
Mike Stump58ef18b2009-11-20 23:44:51 +00001208
John McCallbd309292010-07-06 01:34:17 +00001209 // The fall-through block.
1210 llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
Mike Stump58ef18b2009-11-20 23:44:51 +00001211
John McCallbd309292010-07-06 01:34:17 +00001212 // We just emitted the body of the try; jump to the continue block.
1213 if (HaveInsertPoint())
1214 Builder.CreateBr(ContBB);
Mike Stump97329152009-12-02 19:53:57 +00001215
John McCalld8d00be2012-06-15 05:27:05 +00001216 // Determine if we need an implicit rethrow for all these catch handlers;
1217 // see the comment below.
1218 bool doImplicitRethrow = false;
John McCallb609d3f2010-07-07 06:56:46 +00001219 if (IsFnTryBlock)
John McCalld8d00be2012-06-15 05:27:05 +00001220 doImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
1221 isa<CXXConstructorDecl>(CurCodeDecl);
John McCallb609d3f2010-07-07 06:56:46 +00001222
John McCall8e4c74b2011-08-11 02:22:43 +00001223 // Perversely, we emit the handlers backwards precisely because we
1224 // want them to appear in source order. In all of these cases, the
1225 // catch block will have exactly one predecessor, which will be a
1226 // particular block in the catch dispatch. However, in the case of
1227 // a catch-all, one of the dispatch blocks will branch to two
1228 // different handlers, and EmitBlockAfterUses will cause the second
1229 // handler to be moved before the first.
1230 for (unsigned I = NumHandlers; I != 0; --I) {
1231 llvm::BasicBlock *CatchBlock = Handlers[I-1].Block;
1232 EmitBlockAfterUses(CatchBlock);
Mike Stump75546b82009-12-10 00:06:18 +00001233
John McCallbd309292010-07-06 01:34:17 +00001234 // Catch the exception if this isn't a catch-all.
John McCall8e4c74b2011-08-11 02:22:43 +00001235 const CXXCatchStmt *C = S.getHandler(I-1);
Mike Stump58ef18b2009-11-20 23:44:51 +00001236
John McCallbd309292010-07-06 01:34:17 +00001237 // Enter a cleanup scope, including the catch variable and the
1238 // end-catch.
1239 RunCleanupsScope CatchScope(*this);
Mike Stump58ef18b2009-11-20 23:44:51 +00001240
John McCallbd309292010-07-06 01:34:17 +00001241 // Initialize the catch variable and set up the cleanups.
1242 BeginCatch(*this, C);
1243
Justin Bognerea278c32014-01-07 00:20:28 +00001244 // Emit the PGO counter increment.
Justin Bogneref512b92014-01-06 22:27:43 +00001245 RegionCounter CatchCnt = getPGORegionCounter(C);
1246 CatchCnt.beginRegion(Builder);
1247
John McCallbd309292010-07-06 01:34:17 +00001248 // Perform the body of the catch.
1249 EmitStmt(C->getHandlerBlock());
1250
John McCalld8d00be2012-06-15 05:27:05 +00001251 // [except.handle]p11:
1252 // The currently handled exception is rethrown if control
1253 // reaches the end of a handler of the function-try-block of a
1254 // constructor or destructor.
1255
1256 // It is important that we only do this on fallthrough and not on
1257 // return. Note that it's illegal to put a return in a
1258 // constructor function-try-block's catch handler (p14), so this
1259 // really only applies to destructors.
1260 if (doImplicitRethrow && HaveInsertPoint()) {
John McCall882987f2013-02-28 19:01:20 +00001261 EmitRuntimeCallOrInvoke(getReThrowFn(CGM));
John McCalld8d00be2012-06-15 05:27:05 +00001262 Builder.CreateUnreachable();
1263 Builder.ClearInsertionPoint();
1264 }
1265
John McCallbd309292010-07-06 01:34:17 +00001266 // Fall out through the catch cleanups.
1267 CatchScope.ForceCleanup();
1268
1269 // Branch out of the try.
1270 if (HaveInsertPoint())
1271 Builder.CreateBr(ContBB);
Mike Stump58ef18b2009-11-20 23:44:51 +00001272 }
1273
Justin Bogneref512b92014-01-06 22:27:43 +00001274 RegionCounter ContCnt = getPGORegionCounter(&S);
John McCallbd309292010-07-06 01:34:17 +00001275 EmitBlock(ContBB);
Justin Bogneref512b92014-01-06 22:27:43 +00001276 ContCnt.beginRegion(Builder);
Mike Stump58ef18b2009-11-20 23:44:51 +00001277}
Mike Stumpaff69af2009-12-09 03:35:49 +00001278
John McCall1e670402010-07-21 00:52:03 +00001279namespace {
John McCallcda666c2010-07-21 07:22:38 +00001280 struct CallEndCatchForFinally : EHScopeStack::Cleanup {
John McCall1e670402010-07-21 00:52:03 +00001281 llvm::Value *ForEHVar;
1282 llvm::Value *EndCatchFn;
1283 CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn)
1284 : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
1285
Craig Topper4f12f102014-03-12 06:41:41 +00001286 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall1e670402010-07-21 00:52:03 +00001287 llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
1288 llvm::BasicBlock *CleanupContBB =
1289 CGF.createBasicBlock("finally.cleanup.cont");
1290
1291 llvm::Value *ShouldEndCatch =
1292 CGF.Builder.CreateLoad(ForEHVar, "finally.endcatch");
1293 CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1294 CGF.EmitBlock(EndCatchBB);
John McCall882987f2013-02-28 19:01:20 +00001295 CGF.EmitRuntimeCallOrInvoke(EndCatchFn); // catch-all, so might throw
John McCall1e670402010-07-21 00:52:03 +00001296 CGF.EmitBlock(CleanupContBB);
1297 }
1298 };
John McCall906da4b2010-07-21 05:47:49 +00001299
John McCallcda666c2010-07-21 07:22:38 +00001300 struct PerformFinally : EHScopeStack::Cleanup {
John McCall906da4b2010-07-21 05:47:49 +00001301 const Stmt *Body;
1302 llvm::Value *ForEHVar;
1303 llvm::Value *EndCatchFn;
1304 llvm::Value *RethrowFn;
1305 llvm::Value *SavedExnVar;
1306
1307 PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
1308 llvm::Value *EndCatchFn,
1309 llvm::Value *RethrowFn, llvm::Value *SavedExnVar)
1310 : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1311 RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
1312
Craig Topper4f12f102014-03-12 06:41:41 +00001313 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall906da4b2010-07-21 05:47:49 +00001314 // Enter a cleanup to call the end-catch function if one was provided.
1315 if (EndCatchFn)
John McCallcda666c2010-07-21 07:22:38 +00001316 CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
1317 ForEHVar, EndCatchFn);
John McCall906da4b2010-07-21 05:47:49 +00001318
John McCallcebe0ca2010-08-11 00:16:14 +00001319 // Save the current cleanup destination in case there are
1320 // cleanups in the finally block.
1321 llvm::Value *SavedCleanupDest =
1322 CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
1323 "cleanup.dest.saved");
1324
John McCall906da4b2010-07-21 05:47:49 +00001325 // Emit the finally block.
1326 CGF.EmitStmt(Body);
1327
1328 // If the end of the finally is reachable, check whether this was
1329 // for EH. If so, rethrow.
1330 if (CGF.HaveInsertPoint()) {
1331 llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
1332 llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
1333
1334 llvm::Value *ShouldRethrow =
1335 CGF.Builder.CreateLoad(ForEHVar, "finally.shouldthrow");
1336 CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1337
1338 CGF.EmitBlock(RethrowBB);
1339 if (SavedExnVar) {
John McCall882987f2013-02-28 19:01:20 +00001340 CGF.EmitRuntimeCallOrInvoke(RethrowFn,
1341 CGF.Builder.CreateLoad(SavedExnVar));
John McCall906da4b2010-07-21 05:47:49 +00001342 } else {
John McCall882987f2013-02-28 19:01:20 +00001343 CGF.EmitRuntimeCallOrInvoke(RethrowFn);
John McCall906da4b2010-07-21 05:47:49 +00001344 }
1345 CGF.Builder.CreateUnreachable();
1346
1347 CGF.EmitBlock(ContBB);
John McCallcebe0ca2010-08-11 00:16:14 +00001348
1349 // Restore the cleanup destination.
1350 CGF.Builder.CreateStore(SavedCleanupDest,
1351 CGF.getNormalCleanupDestSlot());
John McCall906da4b2010-07-21 05:47:49 +00001352 }
1353
1354 // Leave the end-catch cleanup. As an optimization, pretend that
1355 // the fallthrough path was inaccessible; we've dynamically proven
1356 // that we're not in the EH case along that path.
1357 if (EndCatchFn) {
1358 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1359 CGF.PopCleanupBlock();
1360 CGF.Builder.restoreIP(SavedIP);
1361 }
1362
1363 // Now make sure we actually have an insertion point or the
1364 // cleanup gods will hate us.
1365 CGF.EnsureInsertPoint();
1366 }
1367 };
John McCall1e670402010-07-21 00:52:03 +00001368}
1369
John McCallbd309292010-07-06 01:34:17 +00001370/// Enters a finally block for an implementation using zero-cost
1371/// exceptions. This is mostly general, but hard-codes some
1372/// language/ABI-specific behavior in the catch-all sections.
John McCall6b0feb72011-06-22 02:32:12 +00001373void CodeGenFunction::FinallyInfo::enter(CodeGenFunction &CGF,
1374 const Stmt *body,
1375 llvm::Constant *beginCatchFn,
1376 llvm::Constant *endCatchFn,
1377 llvm::Constant *rethrowFn) {
Craig Topper8a13c412014-05-21 05:09:00 +00001378 assert((beginCatchFn != nullptr) == (endCatchFn != nullptr) &&
John McCallbd309292010-07-06 01:34:17 +00001379 "begin/end catch functions not paired");
John McCall6b0feb72011-06-22 02:32:12 +00001380 assert(rethrowFn && "rethrow function is required");
1381
1382 BeginCatchFn = beginCatchFn;
Mike Stumpaff69af2009-12-09 03:35:49 +00001383
John McCallbd309292010-07-06 01:34:17 +00001384 // The rethrow function has one of the following two types:
1385 // void (*)()
1386 // void (*)(void*)
1387 // In the latter case we need to pass it the exception object.
1388 // But we can't use the exception slot because the @finally might
1389 // have a landing pad (which would overwrite the exception slot).
Chris Lattner2192fe52011-07-18 04:24:23 +00001390 llvm::FunctionType *rethrowFnTy =
John McCallbd309292010-07-06 01:34:17 +00001391 cast<llvm::FunctionType>(
John McCall6b0feb72011-06-22 02:32:12 +00001392 cast<llvm::PointerType>(rethrowFn->getType())->getElementType());
Craig Topper8a13c412014-05-21 05:09:00 +00001393 SavedExnVar = nullptr;
John McCall6b0feb72011-06-22 02:32:12 +00001394 if (rethrowFnTy->getNumParams())
1395 SavedExnVar = CGF.CreateTempAlloca(CGF.Int8PtrTy, "finally.exn");
Mike Stumpaff69af2009-12-09 03:35:49 +00001396
John McCallbd309292010-07-06 01:34:17 +00001397 // A finally block is a statement which must be executed on any edge
1398 // out of a given scope. Unlike a cleanup, the finally block may
1399 // contain arbitrary control flow leading out of itself. In
1400 // addition, finally blocks should always be executed, even if there
1401 // are no catch handlers higher on the stack. Therefore, we
1402 // surround the protected scope with a combination of a normal
1403 // cleanup (to catch attempts to break out of the block via normal
1404 // control flow) and an EH catch-all (semantically "outside" any try
1405 // statement to which the finally block might have been attached).
1406 // The finally block itself is generated in the context of a cleanup
1407 // which conditionally leaves the catch-all.
John McCall21886962010-04-21 10:05:39 +00001408
John McCallbd309292010-07-06 01:34:17 +00001409 // Jump destination for performing the finally block on an exception
1410 // edge. We'll never actually reach this block, so unreachable is
1411 // fine.
John McCall6b0feb72011-06-22 02:32:12 +00001412 RethrowDest = CGF.getJumpDestInCurrentScope(CGF.getUnreachableBlock());
John McCall21886962010-04-21 10:05:39 +00001413
John McCallbd309292010-07-06 01:34:17 +00001414 // Whether the finally block is being executed for EH purposes.
John McCall6b0feb72011-06-22 02:32:12 +00001415 ForEHVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "finally.for-eh");
1416 CGF.Builder.CreateStore(CGF.Builder.getFalse(), ForEHVar);
Mike Stumpaff69af2009-12-09 03:35:49 +00001417
John McCallbd309292010-07-06 01:34:17 +00001418 // Enter a normal cleanup which will perform the @finally block.
John McCall6b0feb72011-06-22 02:32:12 +00001419 CGF.EHStack.pushCleanup<PerformFinally>(NormalCleanup, body,
1420 ForEHVar, endCatchFn,
1421 rethrowFn, SavedExnVar);
John McCallbd309292010-07-06 01:34:17 +00001422
1423 // Enter a catch-all scope.
John McCall6b0feb72011-06-22 02:32:12 +00001424 llvm::BasicBlock *catchBB = CGF.createBasicBlock("finally.catchall");
1425 EHCatchScope *catchScope = CGF.EHStack.pushCatch(1);
1426 catchScope->setCatchAllHandler(0, catchBB);
John McCallbd309292010-07-06 01:34:17 +00001427}
1428
John McCall6b0feb72011-06-22 02:32:12 +00001429void CodeGenFunction::FinallyInfo::exit(CodeGenFunction &CGF) {
John McCallbd309292010-07-06 01:34:17 +00001430 // Leave the finally catch-all.
John McCall6b0feb72011-06-22 02:32:12 +00001431 EHCatchScope &catchScope = cast<EHCatchScope>(*CGF.EHStack.begin());
1432 llvm::BasicBlock *catchBB = catchScope.getHandler(0).Block;
John McCall8e4c74b2011-08-11 02:22:43 +00001433
1434 CGF.popCatchScope();
John McCallbd309292010-07-06 01:34:17 +00001435
John McCall6b0feb72011-06-22 02:32:12 +00001436 // If there are any references to the catch-all block, emit it.
1437 if (catchBB->use_empty()) {
1438 delete catchBB;
1439 } else {
1440 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveAndClearIP();
1441 CGF.EmitBlock(catchBB);
John McCallbd309292010-07-06 01:34:17 +00001442
Craig Topper8a13c412014-05-21 05:09:00 +00001443 llvm::Value *exn = nullptr;
John McCallbd309292010-07-06 01:34:17 +00001444
John McCall6b0feb72011-06-22 02:32:12 +00001445 // If there's a begin-catch function, call it.
1446 if (BeginCatchFn) {
Bill Wendling79a70e42011-09-15 18:57:19 +00001447 exn = CGF.getExceptionFromSlot();
John McCall882987f2013-02-28 19:01:20 +00001448 CGF.EmitNounwindRuntimeCall(BeginCatchFn, exn);
John McCall6b0feb72011-06-22 02:32:12 +00001449 }
1450
1451 // If we need to remember the exception pointer to rethrow later, do so.
1452 if (SavedExnVar) {
Bill Wendling79a70e42011-09-15 18:57:19 +00001453 if (!exn) exn = CGF.getExceptionFromSlot();
John McCall6b0feb72011-06-22 02:32:12 +00001454 CGF.Builder.CreateStore(exn, SavedExnVar);
1455 }
1456
1457 // Tell the cleanups in the finally block that we're do this for EH.
1458 CGF.Builder.CreateStore(CGF.Builder.getTrue(), ForEHVar);
1459
1460 // Thread a jump through the finally cleanup.
1461 CGF.EmitBranchThroughCleanup(RethrowDest);
1462
1463 CGF.Builder.restoreIP(savedIP);
1464 }
1465
1466 // Finally, leave the @finally cleanup.
1467 CGF.PopCleanupBlock();
John McCallbd309292010-07-06 01:34:17 +00001468}
1469
John McCalle142ad52013-02-12 03:51:46 +00001470/// In a terminate landing pad, should we use __clang__call_terminate
1471/// or just a naked call to std::terminate?
1472///
1473/// __clang_call_terminate calls __cxa_begin_catch, which then allows
1474/// std::terminate to usefully report something about the
1475/// violating exception.
1476static bool useClangCallTerminate(CodeGenModule &CGM) {
1477 // Only do this for Itanium-family ABIs in C++ mode.
1478 return (CGM.getLangOpts().CPlusPlus &&
1479 CGM.getTarget().getCXXABI().isItaniumFamily());
1480}
1481
1482/// Get or define the following function:
1483/// void @__clang_call_terminate(i8* %exn) nounwind noreturn
1484/// This code is used only in C++.
1485static llvm::Constant *getClangCallTerminateFn(CodeGenModule &CGM) {
1486 llvm::FunctionType *fnTy =
1487 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
1488 llvm::Constant *fnRef =
1489 CGM.CreateRuntimeFunction(fnTy, "__clang_call_terminate");
1490
1491 llvm::Function *fn = dyn_cast<llvm::Function>(fnRef);
1492 if (fn && fn->empty()) {
1493 fn->setDoesNotThrow();
1494 fn->setDoesNotReturn();
1495
1496 // What we really want is to massively penalize inlining without
1497 // forbidding it completely. The difference between that and
1498 // 'noinline' is negligible.
1499 fn->addFnAttr(llvm::Attribute::NoInline);
1500
1501 // Allow this function to be shared across translation units, but
1502 // we don't want it to turn into an exported symbol.
1503 fn->setLinkage(llvm::Function::LinkOnceODRLinkage);
1504 fn->setVisibility(llvm::Function::HiddenVisibility);
1505
1506 // Set up the function.
1507 llvm::BasicBlock *entry =
1508 llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn);
1509 CGBuilderTy builder(entry);
1510
1511 // Pull the exception pointer out of the parameter list.
1512 llvm::Value *exn = &*fn->arg_begin();
1513
1514 // Call __cxa_begin_catch(exn).
John McCall882987f2013-02-28 19:01:20 +00001515 llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn);
1516 catchCall->setDoesNotThrow();
1517 catchCall->setCallingConv(CGM.getRuntimeCC());
John McCalle142ad52013-02-12 03:51:46 +00001518
1519 // Call std::terminate().
1520 llvm::CallInst *termCall = builder.CreateCall(getTerminateFn(CGM));
1521 termCall->setDoesNotThrow();
1522 termCall->setDoesNotReturn();
John McCall882987f2013-02-28 19:01:20 +00001523 termCall->setCallingConv(CGM.getRuntimeCC());
John McCalle142ad52013-02-12 03:51:46 +00001524
1525 // std::terminate cannot return.
1526 builder.CreateUnreachable();
1527 }
1528
1529 return fnRef;
1530}
1531
John McCallbd309292010-07-06 01:34:17 +00001532llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
1533 if (TerminateLandingPad)
1534 return TerminateLandingPad;
1535
1536 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1537
1538 // This will get inserted at the end of the function.
1539 TerminateLandingPad = createBasicBlock("terminate.lpad");
1540 Builder.SetInsertPoint(TerminateLandingPad);
1541
1542 // Tell the backend that this is a landing pad.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001543 const EHPersonality &Personality = EHPersonality::get(CGM.getLangOpts());
Bill Wendlingf0724e82011-09-19 20:31:14 +00001544 llvm::LandingPadInst *LPadInst =
1545 Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, NULL),
1546 getOpaquePersonalityFn(CGM, Personality), 0);
1547 LPadInst->addClause(getCatchAllValue(*this));
John McCallbd309292010-07-06 01:34:17 +00001548
John McCalle142ad52013-02-12 03:51:46 +00001549 llvm::CallInst *terminateCall;
1550 if (useClangCallTerminate(CGM)) {
1551 // Extract out the exception pointer.
1552 llvm::Value *exn = Builder.CreateExtractValue(LPadInst, 0);
John McCall882987f2013-02-28 19:01:20 +00001553 terminateCall = EmitNounwindRuntimeCall(getClangCallTerminateFn(CGM), exn);
John McCalle142ad52013-02-12 03:51:46 +00001554 } else {
John McCall882987f2013-02-28 19:01:20 +00001555 terminateCall = EmitNounwindRuntimeCall(getTerminateFn(CGM));
John McCalle142ad52013-02-12 03:51:46 +00001556 }
1557 terminateCall->setDoesNotReturn();
John McCallad7c5c12011-02-08 08:22:06 +00001558 Builder.CreateUnreachable();
Mike Stumpaff69af2009-12-09 03:35:49 +00001559
John McCallbd309292010-07-06 01:34:17 +00001560 // Restore the saved insertion state.
1561 Builder.restoreIP(SavedIP);
John McCalldac3ea62010-04-30 00:06:43 +00001562
John McCallbd309292010-07-06 01:34:17 +00001563 return TerminateLandingPad;
Mike Stumpaff69af2009-12-09 03:35:49 +00001564}
Mike Stump2b488872009-12-09 22:59:31 +00001565
1566llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
Mike Stumpf5cbb082009-12-10 00:02:42 +00001567 if (TerminateHandler)
1568 return TerminateHandler;
1569
John McCallbd309292010-07-06 01:34:17 +00001570 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
Mike Stump25b20fc2009-12-09 23:31:35 +00001571
John McCallbd309292010-07-06 01:34:17 +00001572 // Set up the terminate handler. This block is inserted at the very
1573 // end of the function by FinishFunction.
Mike Stumpf5cbb082009-12-10 00:02:42 +00001574 TerminateHandler = createBasicBlock("terminate.handler");
John McCallbd309292010-07-06 01:34:17 +00001575 Builder.SetInsertPoint(TerminateHandler);
John McCallc84e4e92013-06-20 21:37:43 +00001576 llvm::CallInst *terminateCall;
1577 if (useClangCallTerminate(CGM)) {
1578 // Load the exception pointer.
1579 llvm::Value *exn = getExceptionFromSlot();
1580 terminateCall = EmitNounwindRuntimeCall(getClangCallTerminateFn(CGM), exn);
1581 } else {
1582 terminateCall = EmitNounwindRuntimeCall(getTerminateFn(CGM));
1583 }
1584 terminateCall->setDoesNotReturn();
Mike Stump2b488872009-12-09 22:59:31 +00001585 Builder.CreateUnreachable();
1586
John McCall21886962010-04-21 10:05:39 +00001587 // Restore the saved insertion state.
John McCallbd309292010-07-06 01:34:17 +00001588 Builder.restoreIP(SavedIP);
Mike Stump25b20fc2009-12-09 23:31:35 +00001589
Mike Stump2b488872009-12-09 22:59:31 +00001590 return TerminateHandler;
1591}
John McCallbd309292010-07-06 01:34:17 +00001592
David Chisnall9a837be2012-11-07 16:50:40 +00001593llvm::BasicBlock *CodeGenFunction::getEHResumeBlock(bool isCleanup) {
John McCall8e4c74b2011-08-11 02:22:43 +00001594 if (EHResumeBlock) return EHResumeBlock;
John McCallad5d61e2010-07-23 21:56:41 +00001595
1596 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1597
1598 // We emit a jump to a notional label at the outermost unwind state.
John McCall8e4c74b2011-08-11 02:22:43 +00001599 EHResumeBlock = createBasicBlock("eh.resume");
1600 Builder.SetInsertPoint(EHResumeBlock);
John McCallad5d61e2010-07-23 21:56:41 +00001601
David Blaikiebbafb8a2012-03-11 07:00:24 +00001602 const EHPersonality &Personality = EHPersonality::get(CGM.getLangOpts());
John McCallad5d61e2010-07-23 21:56:41 +00001603
1604 // This can always be a call because we necessarily didn't find
1605 // anything on the EH stack which needs our help.
Benjamin Kramer793bd552012-02-08 12:41:24 +00001606 const char *RethrowName = Personality.CatchallRethrowFn;
Craig Topper8a13c412014-05-21 05:09:00 +00001607 if (RethrowName != nullptr && !isCleanup) {
John McCall882987f2013-02-28 19:01:20 +00001608 EmitRuntimeCall(getCatchallRethrowFn(CGM, RethrowName),
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001609 getExceptionFromSlot())
John McCall9b382dd2011-05-28 21:13:02 +00001610 ->setDoesNotReturn();
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001611 Builder.CreateUnreachable();
1612 Builder.restoreIP(SavedIP);
1613 return EHResumeBlock;
John McCall9b382dd2011-05-28 21:13:02 +00001614 }
1615
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001616 // Recreate the landingpad's return value for the 'resume' instruction.
1617 llvm::Value *Exn = getExceptionFromSlot();
1618 llvm::Value *Sel = getSelectorFromSlot();
John McCallad5d61e2010-07-23 21:56:41 +00001619
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001620 llvm::Type *LPadType = llvm::StructType::get(Exn->getType(),
1621 Sel->getType(), NULL);
1622 llvm::Value *LPadVal = llvm::UndefValue::get(LPadType);
1623 LPadVal = Builder.CreateInsertValue(LPadVal, Exn, 0, "lpad.val");
1624 LPadVal = Builder.CreateInsertValue(LPadVal, Sel, 1, "lpad.val");
1625
1626 Builder.CreateResume(LPadVal);
John McCallad5d61e2010-07-23 21:56:41 +00001627 Builder.restoreIP(SavedIP);
John McCall8e4c74b2011-08-11 02:22:43 +00001628 return EHResumeBlock;
John McCallad5d61e2010-07-23 21:56:41 +00001629}
Reid Kleckner543a16c2013-09-16 21:46:30 +00001630
1631void CodeGenFunction::EmitSEHTryStmt(const SEHTryStmt &S) {
1632 CGM.ErrorUnsupported(&S, "SEH __try");
1633}
Nico Weber9b982072014-07-07 00:12:30 +00001634
1635void CodeGenFunction::EmitSEHLeaveStmt(const SEHLeaveStmt &S) {
1636 CGM.ErrorUnsupported(&S, "SEH __leave");
1637}