blob: ca31717403e2e0dbafcdb8a5dba5aa86f5fb6933 [file] [log] [blame]
Anders Carlsson756b5c42009-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 McCall36f893c2011-01-28 11:13:47 +000015#include "CGCleanup.h"
Benjamin Krameraf2771b2012-02-08 12:41:24 +000016#include "CGObjCRuntime.h"
John McCall204b0752010-07-20 22:17:55 +000017#include "TargetInfo.h"
Benjamin Krameraf2771b2012-02-08 12:41:24 +000018#include "clang/AST/StmtCXX.h"
Chandler Carruthb1ba0ef2013-01-19 08:09:44 +000019#include "clang/AST/StmtObjC.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070020#include "llvm/IR/CallSite.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000021#include "llvm/IR/Intrinsics.h"
John McCallf1549f62010-07-06 01:34:17 +000022
Anders Carlsson756b5c42009-10-30 01:42:31 +000023using namespace clang;
24using namespace CodeGen;
25
John McCall629df012013-02-12 03:51:38 +000026static llvm::Constant *getAllocateExceptionFn(CodeGenModule &CGM) {
Anders Carlssond3379292009-10-30 02:27:02 +000027 // void *__cxa_allocate_exception(size_t thrown_size);
Mike Stump8755ec32009-12-10 00:06:18 +000028
Chris Lattner2acc6e32011-07-18 04:24:23 +000029 llvm::FunctionType *FTy =
John McCall629df012013-02-12 03:51:38 +000030 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.SizeTy, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +000031
John McCall629df012013-02-12 03:51:38 +000032 return CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
Anders Carlssond3379292009-10-30 02:27:02 +000033}
34
John McCall629df012013-02-12 03:51:38 +000035static llvm::Constant *getFreeExceptionFn(CodeGenModule &CGM) {
Mike Stump99533832009-12-02 07:41:41 +000036 // void __cxa_free_exception(void *thrown_exception);
Mike Stump8755ec32009-12-10 00:06:18 +000037
Chris Lattner2acc6e32011-07-18 04:24:23 +000038 llvm::FunctionType *FTy =
John McCall629df012013-02-12 03:51:38 +000039 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +000040
John McCall629df012013-02-12 03:51:38 +000041 return CGM.CreateRuntimeFunction(FTy, "__cxa_free_exception");
Mike Stump99533832009-12-02 07:41:41 +000042}
43
John McCall629df012013-02-12 03:51:38 +000044static llvm::Constant *getThrowFn(CodeGenModule &CGM) {
Mike Stump8755ec32009-12-10 00:06:18 +000045 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
Mike Stump99533832009-12-02 07:41:41 +000046 // void (*dest) (void *));
Anders Carlssond3379292009-10-30 02:27:02 +000047
John McCall629df012013-02-12 03:51:38 +000048 llvm::Type *Args[3] = { CGM.Int8PtrTy, CGM.Int8PtrTy, CGM.Int8PtrTy };
Chris Lattner2acc6e32011-07-18 04:24:23 +000049 llvm::FunctionType *FTy =
John McCall629df012013-02-12 03:51:38 +000050 llvm::FunctionType::get(CGM.VoidTy, Args, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +000051
John McCall629df012013-02-12 03:51:38 +000052 return CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
Anders Carlssond3379292009-10-30 02:27:02 +000053}
54
John McCall629df012013-02-12 03:51:38 +000055static llvm::Constant *getReThrowFn(CodeGenModule &CGM) {
Mike Stump99533832009-12-02 07:41:41 +000056 // void __cxa_rethrow();
Mike Stumpb4eea692009-11-20 00:56:31 +000057
Chris Lattner2acc6e32011-07-18 04:24:23 +000058 llvm::FunctionType *FTy =
John McCall629df012013-02-12 03:51:38 +000059 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +000060
John McCall629df012013-02-12 03:51:38 +000061 return CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
Mike Stumpb4eea692009-11-20 00:56:31 +000062}
63
John McCall629df012013-02-12 03:51:38 +000064static llvm::Constant *getGetExceptionPtrFn(CodeGenModule &CGM) {
John McCallf1549f62010-07-06 01:34:17 +000065 // void *__cxa_get_exception_ptr(void*);
John McCallf1549f62010-07-06 01:34:17 +000066
Chris Lattner2acc6e32011-07-18 04:24:23 +000067 llvm::FunctionType *FTy =
John McCall629df012013-02-12 03:51:38 +000068 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
John McCallf1549f62010-07-06 01:34:17 +000069
John McCall629df012013-02-12 03:51:38 +000070 return CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
John McCallf1549f62010-07-06 01:34:17 +000071}
72
John McCall629df012013-02-12 03:51:38 +000073static llvm::Constant *getBeginCatchFn(CodeGenModule &CGM) {
John McCallf1549f62010-07-06 01:34:17 +000074 // void *__cxa_begin_catch(void*);
Mike Stump2bf701e2009-11-20 23:44:51 +000075
Chris Lattner2acc6e32011-07-18 04:24:23 +000076 llvm::FunctionType *FTy =
John McCall629df012013-02-12 03:51:38 +000077 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +000078
John McCall629df012013-02-12 03:51:38 +000079 return CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
Mike Stump2bf701e2009-11-20 23:44:51 +000080}
81
John McCall629df012013-02-12 03:51:38 +000082static llvm::Constant *getEndCatchFn(CodeGenModule &CGM) {
Mike Stump99533832009-12-02 07:41:41 +000083 // void __cxa_end_catch();
Mike Stump2bf701e2009-11-20 23:44:51 +000084
Chris Lattner2acc6e32011-07-18 04:24:23 +000085 llvm::FunctionType *FTy =
John McCall629df012013-02-12 03:51:38 +000086 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +000087
John McCall629df012013-02-12 03:51:38 +000088 return CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
Mike Stump2bf701e2009-11-20 23:44:51 +000089}
90
John McCall629df012013-02-12 03:51:38 +000091static llvm::Constant *getUnexpectedFn(CodeGenModule &CGM) {
Richard Smith14b0e4b2013-06-20 23:03:35 +000092 // void __cxa_call_unexpected(void *thrown_exception);
Mike Stumpcce3d4f2009-12-07 23:38:24 +000093
Chris Lattner2acc6e32011-07-18 04:24:23 +000094 llvm::FunctionType *FTy =
John McCall629df012013-02-12 03:51:38 +000095 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +000096
John McCall629df012013-02-12 03:51:38 +000097 return CGM.CreateRuntimeFunction(FTy, "__cxa_call_unexpected");
Mike Stumpcce3d4f2009-12-07 23:38:24 +000098}
99
John McCall93c332a2011-05-28 21:13:02 +0000100llvm::Constant *CodeGenFunction::getUnwindResumeFn() {
Chris Lattner2acc6e32011-07-18 04:24:23 +0000101 llvm::FunctionType *FTy =
Jay Foadda549e82011-07-29 13:56:53 +0000102 llvm::FunctionType::get(VoidTy, Int8PtrTy, /*IsVarArgs=*/false);
John McCall93c332a2011-05-28 21:13:02 +0000103
David Blaikie4e4d0842012-03-11 07:00:24 +0000104 if (CGM.getLangOpts().SjLjExceptions)
John McCall93c332a2011-05-28 21:13:02 +0000105 return CGM.CreateRuntimeFunction(FTy, "_Unwind_SjLj_Resume");
106 return CGM.CreateRuntimeFunction(FTy, "_Unwind_Resume");
107}
108
109llvm::Constant *CodeGenFunction::getUnwindResumeOrRethrowFn() {
Chris Lattner2acc6e32011-07-18 04:24:23 +0000110 llvm::FunctionType *FTy =
Jay Foadda549e82011-07-29 13:56:53 +0000111 llvm::FunctionType::get(VoidTy, Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +0000112
David Blaikie4e4d0842012-03-11 07:00:24 +0000113 if (CGM.getLangOpts().SjLjExceptions)
John McCalla5f2de22010-08-11 20:59:53 +0000114 return CGM.CreateRuntimeFunction(FTy, "_Unwind_SjLj_Resume_or_Rethrow");
Douglas Gregor86a3a032010-05-16 01:24:12 +0000115 return CGM.CreateRuntimeFunction(FTy, "_Unwind_Resume_or_Rethrow");
Mike Stump0f590be2009-12-01 03:41:18 +0000116}
117
John McCall629df012013-02-12 03:51:38 +0000118static llvm::Constant *getTerminateFn(CodeGenModule &CGM) {
Mike Stump99533832009-12-02 07:41:41 +0000119 // void __terminate();
120
Chris Lattner2acc6e32011-07-18 04:24:23 +0000121 llvm::FunctionType *FTy =
John McCall629df012013-02-12 03:51:38 +0000122 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +0000123
Chris Lattner5f9e2722011-07-23 10:55:15 +0000124 StringRef name;
John McCall256a76e2011-07-06 01:22:26 +0000125
126 // In C++, use std::terminate().
John McCall629df012013-02-12 03:51:38 +0000127 if (CGM.getLangOpts().CPlusPlus)
John McCall256a76e2011-07-06 01:22:26 +0000128 name = "_ZSt9terminatev"; // FIXME: mangling!
John McCall629df012013-02-12 03:51:38 +0000129 else if (CGM.getLangOpts().ObjC1 &&
130 CGM.getLangOpts().ObjCRuntime.hasTerminate())
John McCall256a76e2011-07-06 01:22:26 +0000131 name = "objc_terminate";
132 else
133 name = "abort";
John McCall629df012013-02-12 03:51:38 +0000134 return CGM.CreateRuntimeFunction(FTy, name);
David Chisnall79a9ad82010-05-17 13:49:20 +0000135}
136
John McCall629df012013-02-12 03:51:38 +0000137static llvm::Constant *getCatchallRethrowFn(CodeGenModule &CGM,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000138 StringRef Name) {
Chris Lattner2acc6e32011-07-18 04:24:23 +0000139 llvm::FunctionType *FTy =
John McCall629df012013-02-12 03:51:38 +0000140 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
John McCall8262b6a2010-07-17 00:43:08 +0000141
John McCall629df012013-02-12 03:51:38 +0000142 return CGM.CreateRuntimeFunction(FTy, Name);
John McCallf1549f62010-07-06 01:34:17 +0000143}
144
Benjamin Krameraf2771b2012-02-08 12:41:24 +0000145namespace {
146 /// The exceptions personality for a function.
147 struct EHPersonality {
148 const char *PersonalityFn;
149
150 // If this is non-null, this personality requires a non-standard
151 // function for rethrowing an exception after a catchall cleanup.
152 // This function must have prototype void(void*).
153 const char *CatchallRethrowFn;
154
155 static const EHPersonality &get(const LangOptions &Lang);
156 static const EHPersonality GNU_C;
157 static const EHPersonality GNU_C_SJLJ;
158 static const EHPersonality GNU_ObjC;
David Chisnall65bd4ac2013-01-11 15:33:01 +0000159 static const EHPersonality GNUstep_ObjC;
Benjamin Krameraf2771b2012-02-08 12:41:24 +0000160 static const EHPersonality GNU_ObjCXX;
161 static const EHPersonality NeXT_ObjC;
162 static const EHPersonality GNU_CPlusPlus;
163 static const EHPersonality GNU_CPlusPlus_SJLJ;
164 };
165}
166
167const EHPersonality EHPersonality::GNU_C = { "__gcc_personality_v0", 0 };
168const EHPersonality EHPersonality::GNU_C_SJLJ = { "__gcc_personality_sj0", 0 };
169const EHPersonality EHPersonality::NeXT_ObjC = { "__objc_personality_v0", 0 };
170const EHPersonality EHPersonality::GNU_CPlusPlus = { "__gxx_personality_v0", 0};
171const EHPersonality
172EHPersonality::GNU_CPlusPlus_SJLJ = { "__gxx_personality_sj0", 0 };
173const EHPersonality
174EHPersonality::GNU_ObjC = {"__gnu_objc_personality_v0", "objc_exception_throw"};
175const EHPersonality
176EHPersonality::GNU_ObjCXX = { "__gnustep_objcxx_personality_v0", 0 };
David Chisnall65bd4ac2013-01-11 15:33:01 +0000177const EHPersonality
178EHPersonality::GNUstep_ObjC = { "__gnustep_objc_personality_v0", 0 };
John McCall8262b6a2010-07-17 00:43:08 +0000179
180static const EHPersonality &getCPersonality(const LangOptions &L) {
John McCall44680782010-11-07 02:35:25 +0000181 if (L.SjLjExceptions)
182 return EHPersonality::GNU_C_SJLJ;
John McCall8262b6a2010-07-17 00:43:08 +0000183 return EHPersonality::GNU_C;
184}
185
186static const EHPersonality &getObjCPersonality(const LangOptions &L) {
John McCall260611a2012-06-20 06:18:46 +0000187 switch (L.ObjCRuntime.getKind()) {
188 case ObjCRuntime::FragileMacOSX:
189 return getCPersonality(L);
190 case ObjCRuntime::MacOSX:
191 case ObjCRuntime::iOS:
192 return EHPersonality::NeXT_ObjC;
David Chisnall11d3f4c2012-07-03 20:49:52 +0000193 case ObjCRuntime::GNUstep:
David Chisnall65bd4ac2013-01-11 15:33:01 +0000194 if (L.ObjCRuntime.getVersion() >= VersionTuple(1, 7))
195 return EHPersonality::GNUstep_ObjC;
196 // fallthrough
David Chisnall11d3f4c2012-07-03 20:49:52 +0000197 case ObjCRuntime::GCC:
John McCallf7226fb2012-07-12 02:07:58 +0000198 case ObjCRuntime::ObjFW:
John McCall8262b6a2010-07-17 00:43:08 +0000199 return EHPersonality::GNU_ObjC;
John McCallf1549f62010-07-06 01:34:17 +0000200 }
John McCall260611a2012-06-20 06:18:46 +0000201 llvm_unreachable("bad runtime kind");
John McCallf1549f62010-07-06 01:34:17 +0000202}
203
John McCall8262b6a2010-07-17 00:43:08 +0000204static const EHPersonality &getCXXPersonality(const LangOptions &L) {
205 if (L.SjLjExceptions)
206 return EHPersonality::GNU_CPlusPlus_SJLJ;
John McCallf1549f62010-07-06 01:34:17 +0000207 else
John McCall8262b6a2010-07-17 00:43:08 +0000208 return EHPersonality::GNU_CPlusPlus;
John McCallf1549f62010-07-06 01:34:17 +0000209}
210
211/// Determines the personality function to use when both C++
212/// and Objective-C exceptions are being caught.
John McCall8262b6a2010-07-17 00:43:08 +0000213static const EHPersonality &getObjCXXPersonality(const LangOptions &L) {
John McCall260611a2012-06-20 06:18:46 +0000214 switch (L.ObjCRuntime.getKind()) {
John McCallf1549f62010-07-06 01:34:17 +0000215 // The ObjC personality defers to the C++ personality for non-ObjC
216 // handlers. Unlike the C++ case, we use the same personality
217 // function on targets using (backend-driven) SJLJ EH.
John McCall260611a2012-06-20 06:18:46 +0000218 case ObjCRuntime::MacOSX:
219 case ObjCRuntime::iOS:
220 return EHPersonality::NeXT_ObjC;
John McCallf1549f62010-07-06 01:34:17 +0000221
John McCall260611a2012-06-20 06:18:46 +0000222 // In the fragile ABI, just use C++ exception handling and hope
223 // they're not doing crazy exception mixing.
224 case ObjCRuntime::FragileMacOSX:
225 return getCXXPersonality(L);
David Chisnall79a9ad82010-05-17 13:49:20 +0000226
David Chisnall11d3f4c2012-07-03 20:49:52 +0000227 // The GCC runtime's personality function inherently doesn't support
John McCall8262b6a2010-07-17 00:43:08 +0000228 // mixed EH. Use the C++ personality just to avoid returning null.
David Chisnall11d3f4c2012-07-03 20:49:52 +0000229 case ObjCRuntime::GCC:
John McCallf7226fb2012-07-12 02:07:58 +0000230 case ObjCRuntime::ObjFW: // XXX: this will change soon
David Chisnall11d3f4c2012-07-03 20:49:52 +0000231 return EHPersonality::GNU_ObjC;
232 case ObjCRuntime::GNUstep:
John McCall260611a2012-06-20 06:18:46 +0000233 return EHPersonality::GNU_ObjCXX;
234 }
235 llvm_unreachable("bad runtime kind");
John McCallf1549f62010-07-06 01:34:17 +0000236}
237
John McCall8262b6a2010-07-17 00:43:08 +0000238const EHPersonality &EHPersonality::get(const LangOptions &L) {
239 if (L.CPlusPlus && L.ObjC1)
240 return getObjCXXPersonality(L);
241 else if (L.CPlusPlus)
242 return getCXXPersonality(L);
243 else if (L.ObjC1)
244 return getObjCPersonality(L);
John McCallf1549f62010-07-06 01:34:17 +0000245 else
John McCall8262b6a2010-07-17 00:43:08 +0000246 return getCPersonality(L);
247}
John McCallf1549f62010-07-06 01:34:17 +0000248
John McCallb2593832010-09-16 06:16:50 +0000249static llvm::Constant *getPersonalityFn(CodeGenModule &CGM,
John McCall8262b6a2010-07-17 00:43:08 +0000250 const EHPersonality &Personality) {
John McCall8262b6a2010-07-17 00:43:08 +0000251 llvm::Constant *Fn =
Chris Lattner8b418682012-02-07 00:39:47 +0000252 CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.Int32Ty, true),
Benjamin Krameraf2771b2012-02-08 12:41:24 +0000253 Personality.PersonalityFn);
John McCallb2593832010-09-16 06:16:50 +0000254 return Fn;
255}
256
257static llvm::Constant *getOpaquePersonalityFn(CodeGenModule &CGM,
258 const EHPersonality &Personality) {
259 llvm::Constant *Fn = getPersonalityFn(CGM, Personality);
John McCalld16c2cf2011-02-08 08:22:06 +0000260 return llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
John McCallb2593832010-09-16 06:16:50 +0000261}
262
263/// Check whether a personality function could reasonably be swapped
264/// for a C++ personality function.
265static bool PersonalityHasOnlyCXXUses(llvm::Constant *Fn) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700266 for (llvm::User *U : Fn->users()) {
John McCallb2593832010-09-16 06:16:50 +0000267 // Conditionally white-list bitcasts.
Stephen Hines651f13c2014-04-23 16:59:28 -0700268 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(U)) {
John McCallb2593832010-09-16 06:16:50 +0000269 if (CE->getOpcode() != llvm::Instruction::BitCast) return false;
270 if (!PersonalityHasOnlyCXXUses(CE))
271 return false;
272 continue;
273 }
274
Bill Wendling40ccacc2011-09-19 22:08:36 +0000275 // Otherwise, it has to be a landingpad instruction.
Stephen Hines651f13c2014-04-23 16:59:28 -0700276 llvm::LandingPadInst *LPI = dyn_cast<llvm::LandingPadInst>(U);
Bill Wendling40ccacc2011-09-19 22:08:36 +0000277 if (!LPI) return false;
John McCallb2593832010-09-16 06:16:50 +0000278
Bill Wendling40ccacc2011-09-19 22:08:36 +0000279 for (unsigned I = 0, E = LPI->getNumClauses(); I != E; ++I) {
John McCallb2593832010-09-16 06:16:50 +0000280 // Look for something that would've been returned by the ObjC
281 // runtime's GetEHType() method.
Bill Wendling40ccacc2011-09-19 22:08:36 +0000282 llvm::Value *Val = LPI->getClause(I)->stripPointerCasts();
283 if (LPI->isCatch(I)) {
284 // Check if the catch value has the ObjC prefix.
Bill Wendlingeecb6a12011-09-20 00:40:19 +0000285 if (llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Val))
286 // ObjC EH selector entries are always global variables with
287 // names starting like this.
288 if (GV->getName().startswith("OBJC_EHTYPE"))
289 return false;
Bill Wendling40ccacc2011-09-19 22:08:36 +0000290 } else {
291 // Check if any of the filter values have the ObjC prefix.
292 llvm::Constant *CVal = cast<llvm::Constant>(Val);
293 for (llvm::User::op_iterator
294 II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II) {
Bill Wendlingeecb6a12011-09-20 00:40:19 +0000295 if (llvm::GlobalVariable *GV =
296 cast<llvm::GlobalVariable>((*II)->stripPointerCasts()))
297 // ObjC EH selector entries are always global variables with
298 // names starting like this.
299 if (GV->getName().startswith("OBJC_EHTYPE"))
300 return false;
Bill Wendling40ccacc2011-09-19 22:08:36 +0000301 }
302 }
John McCallb2593832010-09-16 06:16:50 +0000303 }
304 }
305
306 return true;
307}
308
309/// Try to use the C++ personality function in ObjC++. Not doing this
310/// can cause some incompatibilities with gcc, which is more
311/// aggressive about only using the ObjC++ personality in a function
312/// when it really needs it.
313void CodeGenModule::SimplifyPersonality() {
John McCallb2593832010-09-16 06:16:50 +0000314 // If we're not in ObjC++ -fexceptions, there's nothing to do.
David Blaikie4e4d0842012-03-11 07:00:24 +0000315 if (!LangOpts.CPlusPlus || !LangOpts.ObjC1 || !LangOpts.Exceptions)
John McCallb2593832010-09-16 06:16:50 +0000316 return;
317
John McCall70cd6192012-11-14 17:48:31 +0000318 // Both the problem this endeavors to fix and the way the logic
319 // above works is specific to the NeXT runtime.
320 if (!LangOpts.ObjCRuntime.isNeXTFamily())
321 return;
322
David Blaikie4e4d0842012-03-11 07:00:24 +0000323 const EHPersonality &ObjCXX = EHPersonality::get(LangOpts);
324 const EHPersonality &CXX = getCXXPersonality(LangOpts);
Benjamin Krameraf2771b2012-02-08 12:41:24 +0000325 if (&ObjCXX == &CXX)
John McCallb2593832010-09-16 06:16:50 +0000326 return;
327
Benjamin Krameraf2771b2012-02-08 12:41:24 +0000328 assert(std::strcmp(ObjCXX.PersonalityFn, CXX.PersonalityFn) != 0 &&
329 "Different EHPersonalities using the same personality function.");
330
331 llvm::Function *Fn = getModule().getFunction(ObjCXX.PersonalityFn);
John McCallb2593832010-09-16 06:16:50 +0000332
333 // Nothing to do if it's unused.
334 if (!Fn || Fn->use_empty()) return;
335
336 // Can't do the optimization if it has non-C++ uses.
337 if (!PersonalityHasOnlyCXXUses(Fn)) return;
338
339 // Create the C++ personality function and kill off the old
340 // function.
341 llvm::Constant *CXXFn = getPersonalityFn(*this, CXX);
342
343 // This can happen if the user is screwing with us.
344 if (Fn->getType() != CXXFn->getType()) return;
345
346 Fn->replaceAllUsesWith(CXXFn);
347 Fn->eraseFromParent();
John McCallf1549f62010-07-06 01:34:17 +0000348}
349
350/// Returns the value to inject into a selector to indicate the
351/// presence of a catch-all.
352static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
353 // Possibly we should use @llvm.eh.catch.all.value here.
John McCalld16c2cf2011-02-08 08:22:06 +0000354 return llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
John McCallf1549f62010-07-06 01:34:17 +0000355}
356
John McCall09faeab2010-07-13 21:17:51 +0000357namespace {
358 /// A cleanup to free the exception object if its initialization
359 /// throws.
John McCallc4a1a842011-07-12 00:15:30 +0000360 struct FreeException : EHScopeStack::Cleanup {
361 llvm::Value *exn;
362 FreeException(llvm::Value *exn) : exn(exn) {}
Stephen Hines651f13c2014-04-23 16:59:28 -0700363 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallbd7370a2013-02-28 19:01:20 +0000364 CGF.EmitNounwindRuntimeCall(getFreeExceptionFn(CGF.CGM), exn);
John McCall09faeab2010-07-13 21:17:51 +0000365 }
366 };
367}
368
John McCallac418162010-04-22 01:10:34 +0000369// Emits an exception expression into the given location. This
370// differs from EmitAnyExprToMem only in that, if a final copy-ctor
371// call is required, an exception within that copy ctor causes
372// std::terminate to be invoked.
John McCall3ad32c82011-01-28 08:37:24 +0000373static void EmitAnyExprToExn(CodeGenFunction &CGF, const Expr *e,
374 llvm::Value *addr) {
John McCallf1549f62010-07-06 01:34:17 +0000375 // Make sure the exception object is cleaned up if there's an
376 // exception during initialization.
John McCall3ad32c82011-01-28 08:37:24 +0000377 CGF.pushFullExprCleanup<FreeException>(EHCleanup, addr);
378 EHScopeStack::stable_iterator cleanup = CGF.EHStack.stable_begin();
John McCallac418162010-04-22 01:10:34 +0000379
380 // __cxa_allocate_exception returns a void*; we need to cast this
381 // to the appropriate type for the object.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000382 llvm::Type *ty = CGF.ConvertTypeForMem(e->getType())->getPointerTo();
John McCall3ad32c82011-01-28 08:37:24 +0000383 llvm::Value *typedAddr = CGF.Builder.CreateBitCast(addr, ty);
John McCallac418162010-04-22 01:10:34 +0000384
385 // FIXME: this isn't quite right! If there's a final unelided call
386 // to a copy constructor, then according to [except.terminate]p1 we
387 // must call std::terminate() if that constructor throws, because
388 // technically that copy occurs after the exception expression is
389 // evaluated but before the exception is caught. But the best way
390 // to handle that is to teach EmitAggExpr to do the final copy
391 // differently if it can't be elided.
Chad Rosier649b4a12012-03-29 17:37:10 +0000392 CGF.EmitAnyExprToMem(e, typedAddr, e->getType().getQualifiers(),
393 /*IsInit*/ true);
John McCallac418162010-04-22 01:10:34 +0000394
John McCall3ad32c82011-01-28 08:37:24 +0000395 // Deactivate the cleanup block.
John McCall6f103ba2011-11-10 10:43:54 +0000396 CGF.DeactivateCleanupBlock(cleanup, cast<llvm::Instruction>(typedAddr));
Mike Stump0f590be2009-12-01 03:41:18 +0000397}
398
John McCallf1549f62010-07-06 01:34:17 +0000399llvm::Value *CodeGenFunction::getExceptionSlot() {
John McCall93c332a2011-05-28 21:13:02 +0000400 if (!ExceptionSlot)
401 ExceptionSlot = CreateTempAlloca(Int8PtrTy, "exn.slot");
John McCallf1549f62010-07-06 01:34:17 +0000402 return ExceptionSlot;
Mike Stump0f590be2009-12-01 03:41:18 +0000403}
404
John McCall93c332a2011-05-28 21:13:02 +0000405llvm::Value *CodeGenFunction::getEHSelectorSlot() {
406 if (!EHSelectorSlot)
407 EHSelectorSlot = CreateTempAlloca(Int32Ty, "ehselector.slot");
408 return EHSelectorSlot;
409}
410
Bill Wendlingae270592011-09-15 18:57:19 +0000411llvm::Value *CodeGenFunction::getExceptionFromSlot() {
412 return Builder.CreateLoad(getExceptionSlot(), "exn");
413}
414
415llvm::Value *CodeGenFunction::getSelectorFromSlot() {
416 return Builder.CreateLoad(getEHSelectorSlot(), "sel");
417}
418
Richard Smith4c71b8c2013-05-07 21:53:22 +0000419void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E,
420 bool KeepInsertionPoint) {
Anders Carlssond3379292009-10-30 02:27:02 +0000421 if (!E->getSubExpr()) {
John McCallbd7370a2013-02-28 19:01:20 +0000422 EmitNoreturnRuntimeCallOrInvoke(getReThrowFn(CGM),
423 ArrayRef<llvm::Value*>());
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000424
John McCallcd5b22e2011-01-12 03:41:02 +0000425 // throw is an expression, and the expression emitters expect us
426 // to leave ourselves at a valid insertion point.
Richard Smith4c71b8c2013-05-07 21:53:22 +0000427 if (KeepInsertionPoint)
428 EmitBlock(createBasicBlock("throw.cont"));
John McCallcd5b22e2011-01-12 03:41:02 +0000429
Anders Carlssond3379292009-10-30 02:27:02 +0000430 return;
431 }
Mike Stump8755ec32009-12-10 00:06:18 +0000432
Anders Carlssond3379292009-10-30 02:27:02 +0000433 QualType ThrowType = E->getSubExpr()->getType();
Mike Stump8755ec32009-12-10 00:06:18 +0000434
Fariborz Jahanian6a3c70e2013-01-10 19:02:56 +0000435 if (ThrowType->isObjCObjectPointerType()) {
436 const Stmt *ThrowStmt = E->getSubExpr();
437 const ObjCAtThrowStmt S(E->getExprLoc(),
438 const_cast<Stmt *>(ThrowStmt));
439 CGM.getObjCRuntime().EmitThrowStmt(*this, S, false);
440 // This will clear insertion point which was not cleared in
441 // call to EmitThrowStmt.
Richard Smith4c71b8c2013-05-07 21:53:22 +0000442 if (KeepInsertionPoint)
443 EmitBlock(createBasicBlock("throw.cont"));
Fariborz Jahanian6a3c70e2013-01-10 19:02:56 +0000444 return;
445 }
446
Anders Carlssond3379292009-10-30 02:27:02 +0000447 // Now allocate the exception object.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000448 llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
John McCall3d3ec1c2010-04-21 10:05:39 +0000449 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
Mike Stump8755ec32009-12-10 00:06:18 +0000450
John McCall629df012013-02-12 03:51:38 +0000451 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(CGM);
John McCallf1549f62010-07-06 01:34:17 +0000452 llvm::CallInst *ExceptionPtr =
John McCallbd7370a2013-02-28 19:01:20 +0000453 EmitNounwindRuntimeCall(AllocExceptionFn,
454 llvm::ConstantInt::get(SizeTy, TypeSize),
455 "exception");
Anders Carlsson8370c582009-12-11 00:32:37 +0000456
John McCallac418162010-04-22 01:10:34 +0000457 EmitAnyExprToExn(*this, E->getSubExpr(), ExceptionPtr);
Mike Stump8755ec32009-12-10 00:06:18 +0000458
Anders Carlssond3379292009-10-30 02:27:02 +0000459 // Now throw the exception.
Anders Carlsson82a113a2011-01-24 01:59:49 +0000460 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
461 /*ForEH=*/true);
John McCallac418162010-04-22 01:10:34 +0000462
463 // The address of the destructor. If the exception type has a
464 // trivial destructor (or isn't a record), we just pass null.
465 llvm::Constant *Dtor = 0;
466 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
467 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
468 if (!Record->hasTrivialDestructor()) {
Douglas Gregor1d110e02010-07-01 14:13:13 +0000469 CXXDestructorDecl *DtorD = Record->getDestructor();
John McCallac418162010-04-22 01:10:34 +0000470 Dtor = CGM.GetAddrOfCXXDestructor(DtorD, Dtor_Complete);
471 Dtor = llvm::ConstantExpr::getBitCast(Dtor, Int8PtrTy);
472 }
473 }
474 if (!Dtor) Dtor = llvm::Constant::getNullValue(Int8PtrTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000475
John McCallbd7370a2013-02-28 19:01:20 +0000476 llvm::Value *args[] = { ExceptionPtr, TypeInfo, Dtor };
477 EmitNoreturnRuntimeCallOrInvoke(getThrowFn(CGM), args);
Mike Stump8755ec32009-12-10 00:06:18 +0000478
John McCallcd5b22e2011-01-12 03:41:02 +0000479 // throw is an expression, and the expression emitters expect us
480 // to leave ourselves at a valid insertion point.
Richard Smith4c71b8c2013-05-07 21:53:22 +0000481 if (KeepInsertionPoint)
482 EmitBlock(createBasicBlock("throw.cont"));
Anders Carlsson756b5c42009-10-30 01:42:31 +0000483}
Mike Stump2bf701e2009-11-20 23:44:51 +0000484
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000485void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000486 if (!CGM.getLangOpts().CXXExceptions)
Anders Carlssona994ee42010-02-06 23:59:05 +0000487 return;
488
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000489 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
490 if (FD == 0)
491 return;
492 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
493 if (Proto == 0)
494 return;
495
Sebastian Redla968e972011-03-15 18:42:48 +0000496 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
497 if (isNoexceptExceptionSpec(EST)) {
498 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
499 // noexcept functions are simple terminate scopes.
500 EHStack.pushTerminate();
501 }
502 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
503 unsigned NumExceptions = Proto->getNumExceptions();
504 EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000505
Sebastian Redla968e972011-03-15 18:42:48 +0000506 for (unsigned I = 0; I != NumExceptions; ++I) {
507 QualType Ty = Proto->getExceptionType(I);
508 QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
509 llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType,
510 /*ForEH=*/true);
511 Filter->setFilter(I, EHType);
512 }
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000513 }
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000514}
515
John McCall777d6e52011-08-11 02:22:43 +0000516/// Emit the dispatch block for a filter scope if necessary.
517static void emitFilterDispatchBlock(CodeGenFunction &CGF,
518 EHFilterScope &filterScope) {
519 llvm::BasicBlock *dispatchBlock = filterScope.getCachedEHDispatchBlock();
520 if (!dispatchBlock) return;
521 if (dispatchBlock->use_empty()) {
522 delete dispatchBlock;
523 return;
524 }
525
John McCall777d6e52011-08-11 02:22:43 +0000526 CGF.EmitBlockAfterUses(dispatchBlock);
527
528 // If this isn't a catch-all filter, we need to check whether we got
529 // here because the filter triggered.
530 if (filterScope.getNumFilters()) {
531 // Load the selector value.
Bill Wendlingae270592011-09-15 18:57:19 +0000532 llvm::Value *selector = CGF.getSelectorFromSlot();
John McCall777d6e52011-08-11 02:22:43 +0000533 llvm::BasicBlock *unexpectedBB = CGF.createBasicBlock("ehspec.unexpected");
534
535 llvm::Value *zero = CGF.Builder.getInt32(0);
536 llvm::Value *failsFilter =
537 CGF.Builder.CreateICmpSLT(selector, zero, "ehspec.fails");
David Chisnallc6860042012-11-07 16:50:40 +0000538 CGF.Builder.CreateCondBr(failsFilter, unexpectedBB, CGF.getEHResumeBlock(false));
John McCall777d6e52011-08-11 02:22:43 +0000539
540 CGF.EmitBlock(unexpectedBB);
541 }
542
543 // Call __cxa_call_unexpected. This doesn't need to be an invoke
544 // because __cxa_call_unexpected magically filters exceptions
545 // according to the last landing pad the exception was thrown
546 // into. Seriously.
Bill Wendlingae270592011-09-15 18:57:19 +0000547 llvm::Value *exn = CGF.getExceptionFromSlot();
John McCallbd7370a2013-02-28 19:01:20 +0000548 CGF.EmitRuntimeCall(getUnexpectedFn(CGF.CGM), exn)
John McCall777d6e52011-08-11 02:22:43 +0000549 ->setDoesNotReturn();
550 CGF.Builder.CreateUnreachable();
551}
552
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000553void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000554 if (!CGM.getLangOpts().CXXExceptions)
Anders Carlssona994ee42010-02-06 23:59:05 +0000555 return;
556
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000557 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
558 if (FD == 0)
559 return;
560 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
561 if (Proto == 0)
562 return;
563
Sebastian Redla968e972011-03-15 18:42:48 +0000564 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
565 if (isNoexceptExceptionSpec(EST)) {
566 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
567 EHStack.popTerminate();
568 }
569 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
John McCall777d6e52011-08-11 02:22:43 +0000570 EHFilterScope &filterScope = cast<EHFilterScope>(*EHStack.begin());
571 emitFilterDispatchBlock(*this, filterScope);
Sebastian Redla968e972011-03-15 18:42:48 +0000572 EHStack.popFilter();
573 }
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000574}
575
Mike Stump2bf701e2009-11-20 23:44:51 +0000576void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
John McCall59a70002010-07-07 06:56:46 +0000577 EnterCXXTryStmt(S);
John McCall9fc6a772010-02-19 09:25:03 +0000578 EmitStmt(S.getTryBlock());
John McCall59a70002010-07-07 06:56:46 +0000579 ExitCXXTryStmt(S);
John McCall9fc6a772010-02-19 09:25:03 +0000580}
581
John McCall59a70002010-07-07 06:56:46 +0000582void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallf1549f62010-07-06 01:34:17 +0000583 unsigned NumHandlers = S.getNumHandlers();
584 EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
John McCall9fc6a772010-02-19 09:25:03 +0000585
John McCallf1549f62010-07-06 01:34:17 +0000586 for (unsigned I = 0; I != NumHandlers; ++I) {
587 const CXXCatchStmt *C = S.getHandler(I);
John McCall9fc6a772010-02-19 09:25:03 +0000588
John McCallf1549f62010-07-06 01:34:17 +0000589 llvm::BasicBlock *Handler = createBasicBlock("catch");
590 if (C->getExceptionDecl()) {
591 // FIXME: Dropping the reference type on the type into makes it
592 // impossible to correctly implement catch-by-reference
593 // semantics for pointers. Unfortunately, this is what all
594 // existing compilers do, and it's not clear that the standard
595 // personality routine is capable of doing this right. See C++ DR 388:
596 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
597 QualType CaughtType = C->getCaughtType();
598 CaughtType = CaughtType.getNonReferenceType().getUnqualifiedType();
John McCall5a180392010-07-24 00:37:23 +0000599
600 llvm::Value *TypeInfo = 0;
601 if (CaughtType->isObjCObjectPointerType())
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +0000602 TypeInfo = CGM.getObjCRuntime().GetEHType(CaughtType);
John McCall5a180392010-07-24 00:37:23 +0000603 else
Anders Carlsson82a113a2011-01-24 01:59:49 +0000604 TypeInfo = CGM.GetAddrOfRTTIDescriptor(CaughtType, /*ForEH=*/true);
John McCallf1549f62010-07-06 01:34:17 +0000605 CatchScope->setHandler(I, TypeInfo, Handler);
606 } else {
607 // No exception decl indicates '...', a catch-all.
608 CatchScope->setCatchAllHandler(I, Handler);
609 }
610 }
John McCallf1549f62010-07-06 01:34:17 +0000611}
612
John McCall777d6e52011-08-11 02:22:43 +0000613llvm::BasicBlock *
614CodeGenFunction::getEHDispatchBlock(EHScopeStack::stable_iterator si) {
615 // The dispatch block for the end of the scope chain is a block that
616 // just resumes unwinding.
617 if (si == EHStack.stable_end())
David Chisnallc6860042012-11-07 16:50:40 +0000618 return getEHResumeBlock(true);
John McCall777d6e52011-08-11 02:22:43 +0000619
620 // Otherwise, we should look at the actual scope.
621 EHScope &scope = *EHStack.find(si);
622
623 llvm::BasicBlock *dispatchBlock = scope.getCachedEHDispatchBlock();
624 if (!dispatchBlock) {
625 switch (scope.getKind()) {
626 case EHScope::Catch: {
627 // Apply a special case to a single catch-all.
628 EHCatchScope &catchScope = cast<EHCatchScope>(scope);
629 if (catchScope.getNumHandlers() == 1 &&
630 catchScope.getHandler(0).isCatchAll()) {
631 dispatchBlock = catchScope.getHandler(0).Block;
632
633 // Otherwise, make a dispatch block.
634 } else {
635 dispatchBlock = createBasicBlock("catch.dispatch");
636 }
637 break;
638 }
639
640 case EHScope::Cleanup:
641 dispatchBlock = createBasicBlock("ehcleanup");
642 break;
643
644 case EHScope::Filter:
645 dispatchBlock = createBasicBlock("filter.dispatch");
646 break;
647
648 case EHScope::Terminate:
649 dispatchBlock = getTerminateHandler();
650 break;
651 }
652 scope.setCachedEHDispatchBlock(dispatchBlock);
653 }
654 return dispatchBlock;
655}
656
John McCallf1549f62010-07-06 01:34:17 +0000657/// Check whether this is a non-EH scope, i.e. a scope which doesn't
658/// affect exception handling. Currently, the only non-EH scopes are
659/// normal-only cleanup scopes.
660static bool isNonEHScope(const EHScope &S) {
John McCallda65ea82010-07-13 20:32:21 +0000661 switch (S.getKind()) {
John McCall1f0fca52010-07-21 07:22:38 +0000662 case EHScope::Cleanup:
663 return !cast<EHCleanupScope>(S).isEHCleanup();
John McCallda65ea82010-07-13 20:32:21 +0000664 case EHScope::Filter:
665 case EHScope::Catch:
666 case EHScope::Terminate:
667 return false;
668 }
669
David Blaikie30263482012-01-20 21:50:17 +0000670 llvm_unreachable("Invalid EHScope Kind!");
John McCallf1549f62010-07-06 01:34:17 +0000671}
672
673llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
674 assert(EHStack.requiresLandingPad());
675 assert(!EHStack.empty());
676
David Blaikie4e4d0842012-03-11 07:00:24 +0000677 if (!CGM.getLangOpts().Exceptions)
John McCallda65ea82010-07-13 20:32:21 +0000678 return 0;
679
John McCallf1549f62010-07-06 01:34:17 +0000680 // Check the innermost scope for a cached landing pad. If this is
681 // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
682 llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
683 if (LP) return LP;
684
685 // Build the landing pad for this scope.
686 LP = EmitLandingPad();
687 assert(LP);
688
689 // Cache the landing pad on the innermost scope. If this is a
690 // non-EH scope, cache the landing pad on the enclosing scope, too.
691 for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
692 ir->setCachedLandingPad(LP);
693 if (!isNonEHScope(*ir)) break;
694 }
695
696 return LP;
697}
698
John McCall93c332a2011-05-28 21:13:02 +0000699// This code contains a hack to work around a design flaw in
700// LLVM's EH IR which breaks semantics after inlining. This same
701// hack is implemented in llvm-gcc.
702//
703// The LLVM EH abstraction is basically a thin veneer over the
704// traditional GCC zero-cost design: for each range of instructions
705// in the function, there is (at most) one "landing pad" with an
706// associated chain of EH actions. A language-specific personality
707// function interprets this chain of actions and (1) decides whether
708// or not to resume execution at the landing pad and (2) if so,
709// provides an integer indicating why it's stopping. In LLVM IR,
710// the association of a landing pad with a range of instructions is
711// achieved via an invoke instruction, the chain of actions becomes
712// the arguments to the @llvm.eh.selector call, and the selector
713// call returns the integer indicator. Other than the required
714// presence of two intrinsic function calls in the landing pad,
715// the IR exactly describes the layout of the output code.
716//
717// A principal advantage of this design is that it is completely
718// language-agnostic; in theory, the LLVM optimizers can treat
719// landing pads neutrally, and targets need only know how to lower
720// the intrinsics to have a functioning exceptions system (assuming
721// that platform exceptions follow something approximately like the
722// GCC design). Unfortunately, landing pads cannot be combined in a
723// language-agnostic way: given selectors A and B, there is no way
724// to make a single landing pad which faithfully represents the
725// semantics of propagating an exception first through A, then
726// through B, without knowing how the personality will interpret the
727// (lowered form of the) selectors. This means that inlining has no
728// choice but to crudely chain invokes (i.e., to ignore invokes in
729// the inlined function, but to turn all unwindable calls into
730// invokes), which is only semantically valid if every unwind stops
731// at every landing pad.
732//
733// Therefore, the invoke-inline hack is to guarantee that every
734// landing pad has a catch-all.
735enum CleanupHackLevel_t {
736 /// A level of hack that requires that all landing pads have
737 /// catch-alls.
738 CHL_MandatoryCatchall,
739
740 /// A level of hack that requires that all landing pads handle
741 /// cleanups.
742 CHL_MandatoryCleanup,
743
744 /// No hacks at all; ideal IR generation.
745 CHL_Ideal
746};
747const CleanupHackLevel_t CleanupHackLevel = CHL_MandatoryCleanup;
748
John McCallf1549f62010-07-06 01:34:17 +0000749llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
750 assert(EHStack.requiresLandingPad());
751
John McCall777d6e52011-08-11 02:22:43 +0000752 EHScope &innermostEHScope = *EHStack.find(EHStack.getInnermostEHScope());
753 switch (innermostEHScope.getKind()) {
754 case EHScope::Terminate:
755 return getTerminateLandingPad();
John McCallf1549f62010-07-06 01:34:17 +0000756
John McCall777d6e52011-08-11 02:22:43 +0000757 case EHScope::Catch:
758 case EHScope::Cleanup:
759 case EHScope::Filter:
760 if (llvm::BasicBlock *lpad = innermostEHScope.getCachedLandingPad())
761 return lpad;
John McCallf1549f62010-07-06 01:34:17 +0000762 }
763
764 // Save the current IR generation state.
John McCall777d6e52011-08-11 02:22:43 +0000765 CGBuilderTy::InsertPoint savedIP = Builder.saveAndClearIP();
Stephen Hines651f13c2014-04-23 16:59:28 -0700766 SaveAndRestoreLocation AutoRestoreLocation(*this, Builder);
767 if (CGDebugInfo *DI = getDebugInfo())
Adrian Prantl59f0a5a2013-05-16 00:41:29 +0000768 DI->EmitLocation(Builder, CurEHLocation);
John McCallf1549f62010-07-06 01:34:17 +0000769
David Blaikie4e4d0842012-03-11 07:00:24 +0000770 const EHPersonality &personality = EHPersonality::get(getLangOpts());
John McCall8262b6a2010-07-17 00:43:08 +0000771
John McCallf1549f62010-07-06 01:34:17 +0000772 // Create and configure the landing pad.
John McCall777d6e52011-08-11 02:22:43 +0000773 llvm::BasicBlock *lpad = createBasicBlock("lpad");
774 EmitBlock(lpad);
John McCallf1549f62010-07-06 01:34:17 +0000775
Bill Wendling285cfd82011-09-19 20:31:14 +0000776 llvm::LandingPadInst *LPadInst =
777 Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, NULL),
778 getOpaquePersonalityFn(CGM, personality), 0);
779
780 llvm::Value *LPadExn = Builder.CreateExtractValue(LPadInst, 0);
781 Builder.CreateStore(LPadExn, getExceptionSlot());
782 llvm::Value *LPadSel = Builder.CreateExtractValue(LPadInst, 1);
783 Builder.CreateStore(LPadSel, getEHSelectorSlot());
784
John McCallf1549f62010-07-06 01:34:17 +0000785 // Save the exception pointer. It's safe to use a single exception
786 // pointer per function because EH cleanups can never have nested
787 // try/catches.
Bill Wendling285cfd82011-09-19 20:31:14 +0000788 // Build the landingpad instruction.
John McCallf1549f62010-07-06 01:34:17 +0000789
790 // Accumulate all the handlers in scope.
John McCall777d6e52011-08-11 02:22:43 +0000791 bool hasCatchAll = false;
792 bool hasCleanup = false;
793 bool hasFilter = false;
794 SmallVector<llvm::Value*, 4> filterTypes;
795 llvm::SmallPtrSet<llvm::Value*, 4> catchTypes;
John McCallf1549f62010-07-06 01:34:17 +0000796 for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end();
797 I != E; ++I) {
798
799 switch (I->getKind()) {
John McCall1f0fca52010-07-21 07:22:38 +0000800 case EHScope::Cleanup:
John McCall777d6e52011-08-11 02:22:43 +0000801 // If we have a cleanup, remember that.
802 hasCleanup = (hasCleanup || cast<EHCleanupScope>(*I).isEHCleanup());
John McCallda65ea82010-07-13 20:32:21 +0000803 continue;
804
John McCallf1549f62010-07-06 01:34:17 +0000805 case EHScope::Filter: {
806 assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
John McCall777d6e52011-08-11 02:22:43 +0000807 assert(!hasCatchAll && "EH filter reached after catch-all");
John McCallf1549f62010-07-06 01:34:17 +0000808
Bill Wendling285cfd82011-09-19 20:31:14 +0000809 // Filter scopes get added to the landingpad in weird ways.
John McCall777d6e52011-08-11 02:22:43 +0000810 EHFilterScope &filter = cast<EHFilterScope>(*I);
811 hasFilter = true;
John McCallf1549f62010-07-06 01:34:17 +0000812
Bill Wendling8990daf2011-09-22 20:32:54 +0000813 // Add all the filter values.
814 for (unsigned i = 0, e = filter.getNumFilters(); i != e; ++i)
815 filterTypes.push_back(filter.getFilter(i));
John McCallf1549f62010-07-06 01:34:17 +0000816 goto done;
817 }
818
819 case EHScope::Terminate:
820 // Terminate scopes are basically catch-alls.
John McCall777d6e52011-08-11 02:22:43 +0000821 assert(!hasCatchAll);
822 hasCatchAll = true;
John McCallf1549f62010-07-06 01:34:17 +0000823 goto done;
824
825 case EHScope::Catch:
826 break;
827 }
828
John McCall777d6e52011-08-11 02:22:43 +0000829 EHCatchScope &catchScope = cast<EHCatchScope>(*I);
830 for (unsigned hi = 0, he = catchScope.getNumHandlers(); hi != he; ++hi) {
831 EHCatchScope::Handler handler = catchScope.getHandler(hi);
John McCallf1549f62010-07-06 01:34:17 +0000832
John McCall777d6e52011-08-11 02:22:43 +0000833 // If this is a catch-all, register that and abort.
834 if (!handler.Type) {
835 assert(!hasCatchAll);
836 hasCatchAll = true;
837 goto done;
John McCallf1549f62010-07-06 01:34:17 +0000838 }
839
840 // Check whether we already have a handler for this type.
Bill Wendling285cfd82011-09-19 20:31:14 +0000841 if (catchTypes.insert(handler.Type))
842 // If not, add it directly to the landingpad.
843 LPadInst->addClause(handler.Type);
John McCallf1549f62010-07-06 01:34:17 +0000844 }
John McCallf1549f62010-07-06 01:34:17 +0000845 }
846
847 done:
Bill Wendling285cfd82011-09-19 20:31:14 +0000848 // If we have a catch-all, add null to the landingpad.
John McCall777d6e52011-08-11 02:22:43 +0000849 assert(!(hasCatchAll && hasFilter));
850 if (hasCatchAll) {
Bill Wendling285cfd82011-09-19 20:31:14 +0000851 LPadInst->addClause(getCatchAllValue(*this));
John McCallf1549f62010-07-06 01:34:17 +0000852
853 // If we have an EH filter, we need to add those handlers in the
Bill Wendling285cfd82011-09-19 20:31:14 +0000854 // right place in the landingpad, which is to say, at the end.
John McCall777d6e52011-08-11 02:22:43 +0000855 } else if (hasFilter) {
Bill Wendling40ccacc2011-09-19 22:08:36 +0000856 // Create a filter expression: a constant array indicating which filter
857 // types there are. The personality routine only lands here if the filter
858 // doesn't match.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000859 SmallVector<llvm::Constant*, 8> Filters;
Bill Wendling285cfd82011-09-19 20:31:14 +0000860 llvm::ArrayType *AType =
861 llvm::ArrayType::get(!filterTypes.empty() ?
862 filterTypes[0]->getType() : Int8PtrTy,
863 filterTypes.size());
864
865 for (unsigned i = 0, e = filterTypes.size(); i != e; ++i)
866 Filters.push_back(cast<llvm::Constant>(filterTypes[i]));
867 llvm::Constant *FilterArray = llvm::ConstantArray::get(AType, Filters);
868 LPadInst->addClause(FilterArray);
John McCallf1549f62010-07-06 01:34:17 +0000869
870 // Also check whether we need a cleanup.
Bill Wendling285cfd82011-09-19 20:31:14 +0000871 if (hasCleanup)
872 LPadInst->setCleanup(true);
John McCallf1549f62010-07-06 01:34:17 +0000873
874 // Otherwise, signal that we at least have cleanups.
John McCall777d6e52011-08-11 02:22:43 +0000875 } else if (CleanupHackLevel == CHL_MandatoryCatchall || hasCleanup) {
Bill Wendling285cfd82011-09-19 20:31:14 +0000876 if (CleanupHackLevel == CHL_MandatoryCatchall)
877 LPadInst->addClause(getCatchAllValue(*this));
878 else
879 LPadInst->setCleanup(true);
John McCallf1549f62010-07-06 01:34:17 +0000880 }
881
Bill Wendling285cfd82011-09-19 20:31:14 +0000882 assert((LPadInst->getNumClauses() > 0 || LPadInst->isCleanup()) &&
883 "landingpad instruction has no clauses!");
John McCallf1549f62010-07-06 01:34:17 +0000884
885 // Tell the backend how to generate the landing pad.
John McCall777d6e52011-08-11 02:22:43 +0000886 Builder.CreateBr(getEHDispatchBlock(EHStack.getInnermostEHScope()));
John McCallf1549f62010-07-06 01:34:17 +0000887
888 // Restore the old IR generation state.
John McCall777d6e52011-08-11 02:22:43 +0000889 Builder.restoreIP(savedIP);
John McCallf1549f62010-07-06 01:34:17 +0000890
John McCall777d6e52011-08-11 02:22:43 +0000891 return lpad;
John McCallf1549f62010-07-06 01:34:17 +0000892}
893
John McCall8e3f8612010-07-13 22:12:14 +0000894namespace {
895 /// A cleanup to call __cxa_end_catch. In many cases, the caught
896 /// exception type lets us state definitively that the thrown exception
897 /// type does not have a destructor. In particular:
898 /// - Catch-alls tell us nothing, so we have to conservatively
899 /// assume that the thrown exception might have a destructor.
900 /// - Catches by reference behave according to their base types.
901 /// - Catches of non-record types will only trigger for exceptions
902 /// of non-record types, which never have destructors.
903 /// - Catches of record types can trigger for arbitrary subclasses
904 /// of the caught type, so we have to assume the actual thrown
905 /// exception type might have a throwing destructor, even if the
906 /// caught type's destructor is trivial or nothrow.
John McCall1f0fca52010-07-21 07:22:38 +0000907 struct CallEndCatch : EHScopeStack::Cleanup {
John McCall8e3f8612010-07-13 22:12:14 +0000908 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
909 bool MightThrow;
910
Stephen Hines651f13c2014-04-23 16:59:28 -0700911 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall8e3f8612010-07-13 22:12:14 +0000912 if (!MightThrow) {
John McCallbd7370a2013-02-28 19:01:20 +0000913 CGF.EmitNounwindRuntimeCall(getEndCatchFn(CGF.CGM));
John McCall8e3f8612010-07-13 22:12:14 +0000914 return;
915 }
916
John McCallbd7370a2013-02-28 19:01:20 +0000917 CGF.EmitRuntimeCallOrInvoke(getEndCatchFn(CGF.CGM));
John McCall8e3f8612010-07-13 22:12:14 +0000918 }
919 };
920}
921
John McCallf1549f62010-07-06 01:34:17 +0000922/// Emits a call to __cxa_begin_catch and enters a cleanup to call
923/// __cxa_end_catch.
John McCall8e3f8612010-07-13 22:12:14 +0000924///
925/// \param EndMightThrow - true if __cxa_end_catch might throw
926static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
927 llvm::Value *Exn,
928 bool EndMightThrow) {
John McCallbd7370a2013-02-28 19:01:20 +0000929 llvm::CallInst *call =
930 CGF.EmitNounwindRuntimeCall(getBeginCatchFn(CGF.CGM), Exn);
John McCallf1549f62010-07-06 01:34:17 +0000931
John McCall1f0fca52010-07-21 07:22:38 +0000932 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
John McCallf1549f62010-07-06 01:34:17 +0000933
John McCallbd7370a2013-02-28 19:01:20 +0000934 return call;
John McCallf1549f62010-07-06 01:34:17 +0000935}
936
937/// A "special initializer" callback for initializing a catch
938/// parameter during catch initialization.
939static void InitCatchParam(CodeGenFunction &CGF,
940 const VarDecl &CatchParam,
Nick Lewycky4ee7dc22013-10-02 02:29:49 +0000941 llvm::Value *ParamAddr,
942 SourceLocation Loc) {
John McCallf1549f62010-07-06 01:34:17 +0000943 // Load the exception from where the landing pad saved it.
Bill Wendlingae270592011-09-15 18:57:19 +0000944 llvm::Value *Exn = CGF.getExceptionFromSlot();
John McCallf1549f62010-07-06 01:34:17 +0000945
946 CanQualType CatchType =
947 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
Chris Lattner2acc6e32011-07-18 04:24:23 +0000948 llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
John McCallf1549f62010-07-06 01:34:17 +0000949
950 // If we're catching by reference, we can just cast the object
951 // pointer to the appropriate pointer.
952 if (isa<ReferenceType>(CatchType)) {
John McCall204b0752010-07-20 22:17:55 +0000953 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
954 bool EndCatchMightThrow = CaughtType->isRecordType();
John McCall8e3f8612010-07-13 22:12:14 +0000955
John McCallf1549f62010-07-06 01:34:17 +0000956 // __cxa_begin_catch returns the adjusted object pointer.
John McCall8e3f8612010-07-13 22:12:14 +0000957 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
John McCall204b0752010-07-20 22:17:55 +0000958
959 // We have no way to tell the personality function that we're
960 // catching by reference, so if we're catching a pointer,
961 // __cxa_begin_catch will actually return that pointer by value.
962 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
963 QualType PointeeType = PT->getPointeeType();
964
965 // When catching by reference, generally we should just ignore
966 // this by-value pointer and use the exception object instead.
967 if (!PointeeType->isRecordType()) {
968
969 // Exn points to the struct _Unwind_Exception header, which
970 // we have to skip past in order to reach the exception data.
971 unsigned HeaderSize =
972 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
973 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
974
975 // However, if we're catching a pointer-to-record type that won't
976 // work, because the personality function might have adjusted
977 // the pointer. There's actually no way for us to fully satisfy
978 // the language/ABI contract here: we can't use Exn because it
979 // might have the wrong adjustment, but we can't use the by-value
980 // pointer because it's off by a level of abstraction.
981 //
982 // The current solution is to dump the adjusted pointer into an
983 // alloca, which breaks language semantics (because changing the
984 // pointer doesn't change the exception) but at least works.
985 // The better solution would be to filter out non-exact matches
986 // and rethrow them, but this is tricky because the rethrow
987 // really needs to be catchable by other sites at this landing
988 // pad. The best solution is to fix the personality function.
989 } else {
990 // Pull the pointer for the reference type off.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000991 llvm::Type *PtrTy =
John McCall204b0752010-07-20 22:17:55 +0000992 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
993
994 // Create the temporary and write the adjusted pointer into it.
995 llvm::Value *ExnPtrTmp = CGF.CreateTempAlloca(PtrTy, "exn.byref.tmp");
996 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
997 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
998
999 // Bind the reference to the temporary.
1000 AdjustedExn = ExnPtrTmp;
1001 }
1002 }
1003
John McCallf1549f62010-07-06 01:34:17 +00001004 llvm::Value *ExnCast =
1005 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
1006 CGF.Builder.CreateStore(ExnCast, ParamAddr);
1007 return;
1008 }
1009
John McCall9d232c82013-03-07 21:37:08 +00001010 // Scalars and complexes.
1011 TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType);
1012 if (TEK != TEK_Aggregate) {
John McCall8e3f8612010-07-13 22:12:14 +00001013 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
John McCallf1549f62010-07-06 01:34:17 +00001014
1015 // If the catch type is a pointer type, __cxa_begin_catch returns
1016 // the pointer by value.
1017 if (CatchType->hasPointerRepresentation()) {
1018 llvm::Value *CastExn =
1019 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
John McCallb29b12d2012-01-17 20:16:56 +00001020
1021 switch (CatchType.getQualifiers().getObjCLifetime()) {
1022 case Qualifiers::OCL_Strong:
1023 CastExn = CGF.EmitARCRetainNonBlock(CastExn);
1024 // fallthrough
1025
1026 case Qualifiers::OCL_None:
1027 case Qualifiers::OCL_ExplicitNone:
1028 case Qualifiers::OCL_Autoreleasing:
1029 CGF.Builder.CreateStore(CastExn, ParamAddr);
1030 return;
1031
1032 case Qualifiers::OCL_Weak:
1033 CGF.EmitARCInitWeak(ParamAddr, CastExn);
1034 return;
1035 }
1036 llvm_unreachable("bad ownership qualifier!");
John McCallf1549f62010-07-06 01:34:17 +00001037 }
1038
1039 // Otherwise, it returns a pointer into the exception object.
1040
Chris Lattner2acc6e32011-07-18 04:24:23 +00001041 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
John McCallf1549f62010-07-06 01:34:17 +00001042 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1043
John McCall9d232c82013-03-07 21:37:08 +00001044 LValue srcLV = CGF.MakeNaturalAlignAddrLValue(Cast, CatchType);
1045 LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType,
1046 CGF.getContext().getDeclAlign(&CatchParam));
1047 switch (TEK) {
1048 case TEK_Complex:
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00001049 CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV,
John McCall9d232c82013-03-07 21:37:08 +00001050 /*init*/ true);
1051 return;
1052 case TEK_Scalar: {
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00001053 llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc);
John McCall9d232c82013-03-07 21:37:08 +00001054 CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true);
1055 return;
John McCallf1549f62010-07-06 01:34:17 +00001056 }
John McCall9d232c82013-03-07 21:37:08 +00001057 case TEK_Aggregate:
1058 llvm_unreachable("evaluation kind filtered out!");
1059 }
1060 llvm_unreachable("bad evaluation kind");
John McCallf1549f62010-07-06 01:34:17 +00001061 }
1062
John McCallacff6962011-02-16 08:39:19 +00001063 assert(isa<RecordType>(CatchType) && "unexpected catch type!");
John McCallf1549f62010-07-06 01:34:17 +00001064
Chris Lattner2acc6e32011-07-18 04:24:23 +00001065 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
John McCallf1549f62010-07-06 01:34:17 +00001066
John McCallacff6962011-02-16 08:39:19 +00001067 // Check for a copy expression. If we don't have a copy expression,
1068 // that means a trivial copy is okay.
John McCalle996ffd2011-02-16 08:02:54 +00001069 const Expr *copyExpr = CatchParam.getInit();
1070 if (!copyExpr) {
John McCallacff6962011-02-16 08:39:19 +00001071 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
1072 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
Chad Rosier649b4a12012-03-29 17:37:10 +00001073 CGF.EmitAggregateCopy(ParamAddr, adjustedExn, CatchType);
John McCallf1549f62010-07-06 01:34:17 +00001074 return;
1075 }
1076
1077 // We have to call __cxa_get_exception_ptr to get the adjusted
1078 // pointer before copying.
John McCalle996ffd2011-02-16 08:02:54 +00001079 llvm::CallInst *rawAdjustedExn =
John McCallbd7370a2013-02-28 19:01:20 +00001080 CGF.EmitNounwindRuntimeCall(getGetExceptionPtrFn(CGF.CGM), Exn);
John McCallf1549f62010-07-06 01:34:17 +00001081
John McCalle996ffd2011-02-16 08:02:54 +00001082 // Cast that to the appropriate type.
1083 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
John McCallf1549f62010-07-06 01:34:17 +00001084
John McCalle996ffd2011-02-16 08:02:54 +00001085 // The copy expression is defined in terms of an OpaqueValueExpr.
1086 // Find it and map it to the adjusted expression.
1087 CodeGenFunction::OpaqueValueMapping
John McCall56ca35d2011-02-17 10:25:35 +00001088 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
1089 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
John McCallf1549f62010-07-06 01:34:17 +00001090
1091 // Call the copy ctor in a terminate scope.
1092 CGF.EHStack.pushTerminate();
John McCalle996ffd2011-02-16 08:02:54 +00001093
1094 // Perform the copy construction.
Eli Friedmand7722d92011-12-03 02:13:40 +00001095 CharUnits Alignment = CGF.getContext().getDeclAlign(&CatchParam);
Eli Friedmanf3940782011-12-03 00:54:26 +00001096 CGF.EmitAggExpr(copyExpr,
1097 AggValueSlot::forAddr(ParamAddr, Alignment, Qualifiers(),
1098 AggValueSlot::IsNotDestructed,
1099 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +00001100 AggValueSlot::IsNotAliased));
John McCalle996ffd2011-02-16 08:02:54 +00001101
1102 // Leave the terminate scope.
John McCallf1549f62010-07-06 01:34:17 +00001103 CGF.EHStack.popTerminate();
1104
John McCalle996ffd2011-02-16 08:02:54 +00001105 // Undo the opaque value mapping.
1106 opaque.pop();
1107
John McCallf1549f62010-07-06 01:34:17 +00001108 // Finally we can call __cxa_begin_catch.
John McCall8e3f8612010-07-13 22:12:14 +00001109 CallBeginCatch(CGF, Exn, true);
John McCallf1549f62010-07-06 01:34:17 +00001110}
1111
1112/// Begins a catch statement by initializing the catch variable and
1113/// calling __cxa_begin_catch.
John McCalle996ffd2011-02-16 08:02:54 +00001114static void BeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *S) {
John McCallf1549f62010-07-06 01:34:17 +00001115 // We have to be very careful with the ordering of cleanups here:
1116 // C++ [except.throw]p4:
1117 // The destruction [of the exception temporary] occurs
1118 // immediately after the destruction of the object declared in
1119 // the exception-declaration in the handler.
1120 //
1121 // So the precise ordering is:
1122 // 1. Construct catch variable.
1123 // 2. __cxa_begin_catch
1124 // 3. Enter __cxa_end_catch cleanup
1125 // 4. Enter dtor cleanup
1126 //
John McCall34695852011-02-22 06:44:22 +00001127 // We do this by using a slightly abnormal initialization process.
1128 // Delegation sequence:
John McCallf1549f62010-07-06 01:34:17 +00001129 // - ExitCXXTryStmt opens a RunCleanupsScope
John McCall34695852011-02-22 06:44:22 +00001130 // - EmitAutoVarAlloca creates the variable and debug info
John McCallf1549f62010-07-06 01:34:17 +00001131 // - InitCatchParam initializes the variable from the exception
John McCall34695852011-02-22 06:44:22 +00001132 // - CallBeginCatch calls __cxa_begin_catch
1133 // - CallBeginCatch enters the __cxa_end_catch cleanup
1134 // - EmitAutoVarCleanups enters the variable destructor cleanup
John McCallf1549f62010-07-06 01:34:17 +00001135 // - EmitCXXTryStmt emits the code for the catch body
1136 // - EmitCXXTryStmt close the RunCleanupsScope
1137
1138 VarDecl *CatchParam = S->getExceptionDecl();
1139 if (!CatchParam) {
Bill Wendlingae270592011-09-15 18:57:19 +00001140 llvm::Value *Exn = CGF.getExceptionFromSlot();
John McCall8e3f8612010-07-13 22:12:14 +00001141 CallBeginCatch(CGF, Exn, true);
John McCallf1549f62010-07-06 01:34:17 +00001142 return;
1143 }
1144
1145 // Emit the local.
John McCall34695852011-02-22 06:44:22 +00001146 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00001147 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF), S->getLocStart());
John McCall34695852011-02-22 06:44:22 +00001148 CGF.EmitAutoVarCleanups(var);
John McCall9fc6a772010-02-19 09:25:03 +00001149}
1150
John McCall777d6e52011-08-11 02:22:43 +00001151/// Emit the structure of the dispatch block for the given catch scope.
1152/// It is an invariant that the dispatch block already exists.
1153static void emitCatchDispatchBlock(CodeGenFunction &CGF,
1154 EHCatchScope &catchScope) {
1155 llvm::BasicBlock *dispatchBlock = catchScope.getCachedEHDispatchBlock();
1156 assert(dispatchBlock);
1157
1158 // If there's only a single catch-all, getEHDispatchBlock returned
1159 // that catch-all as the dispatch block.
1160 if (catchScope.getNumHandlers() == 1 &&
1161 catchScope.getHandler(0).isCatchAll()) {
1162 assert(dispatchBlock == catchScope.getHandler(0).Block);
1163 return;
1164 }
1165
1166 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveIP();
1167 CGF.EmitBlockAfterUses(dispatchBlock);
1168
1169 // Select the right handler.
1170 llvm::Value *llvm_eh_typeid_for =
1171 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
1172
1173 // Load the selector value.
Bill Wendlingae270592011-09-15 18:57:19 +00001174 llvm::Value *selector = CGF.getSelectorFromSlot();
John McCall777d6e52011-08-11 02:22:43 +00001175
1176 // Test against each of the exception types we claim to catch.
1177 for (unsigned i = 0, e = catchScope.getNumHandlers(); ; ++i) {
1178 assert(i < e && "ran off end of handlers!");
1179 const EHCatchScope::Handler &handler = catchScope.getHandler(i);
1180
1181 llvm::Value *typeValue = handler.Type;
1182 assert(typeValue && "fell into catch-all case!");
1183 typeValue = CGF.Builder.CreateBitCast(typeValue, CGF.Int8PtrTy);
1184
1185 // Figure out the next block.
1186 bool nextIsEnd;
1187 llvm::BasicBlock *nextBlock;
1188
1189 // If this is the last handler, we're at the end, and the next
1190 // block is the block for the enclosing EH scope.
1191 if (i + 1 == e) {
1192 nextBlock = CGF.getEHDispatchBlock(catchScope.getEnclosingEHScope());
1193 nextIsEnd = true;
1194
1195 // If the next handler is a catch-all, we're at the end, and the
1196 // next block is that handler.
1197 } else if (catchScope.getHandler(i+1).isCatchAll()) {
1198 nextBlock = catchScope.getHandler(i+1).Block;
1199 nextIsEnd = true;
1200
1201 // Otherwise, we're not at the end and we need a new block.
1202 } else {
1203 nextBlock = CGF.createBasicBlock("catch.fallthrough");
1204 nextIsEnd = false;
1205 }
1206
1207 // Figure out the catch type's index in the LSDA's type table.
1208 llvm::CallInst *typeIndex =
1209 CGF.Builder.CreateCall(llvm_eh_typeid_for, typeValue);
1210 typeIndex->setDoesNotThrow();
1211
1212 llvm::Value *matchesTypeIndex =
1213 CGF.Builder.CreateICmpEQ(selector, typeIndex, "matches");
1214 CGF.Builder.CreateCondBr(matchesTypeIndex, handler.Block, nextBlock);
1215
1216 // If the next handler is a catch-all, we're completely done.
1217 if (nextIsEnd) {
1218 CGF.Builder.restoreIP(savedIP);
1219 return;
John McCall777d6e52011-08-11 02:22:43 +00001220 }
Ahmed Charlese8e92b92012-02-19 11:57:29 +00001221 // Otherwise we need to emit and continue at that block.
1222 CGF.EmitBlock(nextBlock);
John McCall777d6e52011-08-11 02:22:43 +00001223 }
John McCall777d6e52011-08-11 02:22:43 +00001224}
1225
1226void CodeGenFunction::popCatchScope() {
1227 EHCatchScope &catchScope = cast<EHCatchScope>(*EHStack.begin());
1228 if (catchScope.hasEHBranches())
1229 emitCatchDispatchBlock(*this, catchScope);
1230 EHStack.popCatch();
1231}
1232
John McCall59a70002010-07-07 06:56:46 +00001233void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallf1549f62010-07-06 01:34:17 +00001234 unsigned NumHandlers = S.getNumHandlers();
1235 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1236 assert(CatchScope.getNumHandlers() == NumHandlers);
Mike Stump2bf701e2009-11-20 23:44:51 +00001237
John McCall777d6e52011-08-11 02:22:43 +00001238 // If the catch was not required, bail out now.
1239 if (!CatchScope.hasEHBranches()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001240 CatchScope.clearHandlerBlocks();
John McCall777d6e52011-08-11 02:22:43 +00001241 EHStack.popCatch();
1242 return;
1243 }
1244
1245 // Emit the structure of the EH dispatch for this catch.
1246 emitCatchDispatchBlock(*this, CatchScope);
1247
John McCallf1549f62010-07-06 01:34:17 +00001248 // Copy the handler blocks off before we pop the EH stack. Emitting
1249 // the handlers might scribble on this memory.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001250 SmallVector<EHCatchScope::Handler, 8> Handlers(NumHandlers);
John McCallf1549f62010-07-06 01:34:17 +00001251 memcpy(Handlers.data(), CatchScope.begin(),
1252 NumHandlers * sizeof(EHCatchScope::Handler));
John McCall777d6e52011-08-11 02:22:43 +00001253
John McCallf1549f62010-07-06 01:34:17 +00001254 EHStack.popCatch();
Mike Stump2bf701e2009-11-20 23:44:51 +00001255
John McCallf1549f62010-07-06 01:34:17 +00001256 // The fall-through block.
1257 llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
Mike Stump2bf701e2009-11-20 23:44:51 +00001258
John McCallf1549f62010-07-06 01:34:17 +00001259 // We just emitted the body of the try; jump to the continue block.
1260 if (HaveInsertPoint())
1261 Builder.CreateBr(ContBB);
Mike Stump639787c2009-12-02 19:53:57 +00001262
John McCallf5533012012-06-15 05:27:05 +00001263 // Determine if we need an implicit rethrow for all these catch handlers;
1264 // see the comment below.
1265 bool doImplicitRethrow = false;
John McCall59a70002010-07-07 06:56:46 +00001266 if (IsFnTryBlock)
John McCallf5533012012-06-15 05:27:05 +00001267 doImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
1268 isa<CXXConstructorDecl>(CurCodeDecl);
John McCall59a70002010-07-07 06:56:46 +00001269
John McCall777d6e52011-08-11 02:22:43 +00001270 // Perversely, we emit the handlers backwards precisely because we
1271 // want them to appear in source order. In all of these cases, the
1272 // catch block will have exactly one predecessor, which will be a
1273 // particular block in the catch dispatch. However, in the case of
1274 // a catch-all, one of the dispatch blocks will branch to two
1275 // different handlers, and EmitBlockAfterUses will cause the second
1276 // handler to be moved before the first.
1277 for (unsigned I = NumHandlers; I != 0; --I) {
1278 llvm::BasicBlock *CatchBlock = Handlers[I-1].Block;
1279 EmitBlockAfterUses(CatchBlock);
Mike Stump8755ec32009-12-10 00:06:18 +00001280
John McCallf1549f62010-07-06 01:34:17 +00001281 // Catch the exception if this isn't a catch-all.
John McCall777d6e52011-08-11 02:22:43 +00001282 const CXXCatchStmt *C = S.getHandler(I-1);
Mike Stump2bf701e2009-11-20 23:44:51 +00001283
John McCallf1549f62010-07-06 01:34:17 +00001284 // Enter a cleanup scope, including the catch variable and the
1285 // end-catch.
1286 RunCleanupsScope CatchScope(*this);
Mike Stump2bf701e2009-11-20 23:44:51 +00001287
John McCallf1549f62010-07-06 01:34:17 +00001288 // Initialize the catch variable and set up the cleanups.
1289 BeginCatch(*this, C);
1290
Stephen Hines651f13c2014-04-23 16:59:28 -07001291 // Emit the PGO counter increment.
1292 RegionCounter CatchCnt = getPGORegionCounter(C);
1293 CatchCnt.beginRegion(Builder);
1294
John McCallf1549f62010-07-06 01:34:17 +00001295 // Perform the body of the catch.
1296 EmitStmt(C->getHandlerBlock());
1297
John McCallf5533012012-06-15 05:27:05 +00001298 // [except.handle]p11:
1299 // The currently handled exception is rethrown if control
1300 // reaches the end of a handler of the function-try-block of a
1301 // constructor or destructor.
1302
1303 // It is important that we only do this on fallthrough and not on
1304 // return. Note that it's illegal to put a return in a
1305 // constructor function-try-block's catch handler (p14), so this
1306 // really only applies to destructors.
1307 if (doImplicitRethrow && HaveInsertPoint()) {
John McCallbd7370a2013-02-28 19:01:20 +00001308 EmitRuntimeCallOrInvoke(getReThrowFn(CGM));
John McCallf5533012012-06-15 05:27:05 +00001309 Builder.CreateUnreachable();
1310 Builder.ClearInsertionPoint();
1311 }
1312
John McCallf1549f62010-07-06 01:34:17 +00001313 // Fall out through the catch cleanups.
1314 CatchScope.ForceCleanup();
1315
1316 // Branch out of the try.
1317 if (HaveInsertPoint())
1318 Builder.CreateBr(ContBB);
Mike Stump2bf701e2009-11-20 23:44:51 +00001319 }
1320
Stephen Hines651f13c2014-04-23 16:59:28 -07001321 RegionCounter ContCnt = getPGORegionCounter(&S);
John McCallf1549f62010-07-06 01:34:17 +00001322 EmitBlock(ContBB);
Stephen Hines651f13c2014-04-23 16:59:28 -07001323 ContCnt.beginRegion(Builder);
Mike Stump2bf701e2009-11-20 23:44:51 +00001324}
Mike Stumpd88ea562009-12-09 03:35:49 +00001325
John McCall55b20fc2010-07-21 00:52:03 +00001326namespace {
John McCall1f0fca52010-07-21 07:22:38 +00001327 struct CallEndCatchForFinally : EHScopeStack::Cleanup {
John McCall55b20fc2010-07-21 00:52:03 +00001328 llvm::Value *ForEHVar;
1329 llvm::Value *EndCatchFn;
1330 CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn)
1331 : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
1332
Stephen Hines651f13c2014-04-23 16:59:28 -07001333 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall55b20fc2010-07-21 00:52:03 +00001334 llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
1335 llvm::BasicBlock *CleanupContBB =
1336 CGF.createBasicBlock("finally.cleanup.cont");
1337
1338 llvm::Value *ShouldEndCatch =
1339 CGF.Builder.CreateLoad(ForEHVar, "finally.endcatch");
1340 CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1341 CGF.EmitBlock(EndCatchBB);
John McCallbd7370a2013-02-28 19:01:20 +00001342 CGF.EmitRuntimeCallOrInvoke(EndCatchFn); // catch-all, so might throw
John McCall55b20fc2010-07-21 00:52:03 +00001343 CGF.EmitBlock(CleanupContBB);
1344 }
1345 };
John McCall77199712010-07-21 05:47:49 +00001346
John McCall1f0fca52010-07-21 07:22:38 +00001347 struct PerformFinally : EHScopeStack::Cleanup {
John McCall77199712010-07-21 05:47:49 +00001348 const Stmt *Body;
1349 llvm::Value *ForEHVar;
1350 llvm::Value *EndCatchFn;
1351 llvm::Value *RethrowFn;
1352 llvm::Value *SavedExnVar;
1353
1354 PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
1355 llvm::Value *EndCatchFn,
1356 llvm::Value *RethrowFn, llvm::Value *SavedExnVar)
1357 : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1358 RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
1359
Stephen Hines651f13c2014-04-23 16:59:28 -07001360 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall77199712010-07-21 05:47:49 +00001361 // Enter a cleanup to call the end-catch function if one was provided.
1362 if (EndCatchFn)
John McCall1f0fca52010-07-21 07:22:38 +00001363 CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
1364 ForEHVar, EndCatchFn);
John McCall77199712010-07-21 05:47:49 +00001365
John McCalld96a8e72010-08-11 00:16:14 +00001366 // Save the current cleanup destination in case there are
1367 // cleanups in the finally block.
1368 llvm::Value *SavedCleanupDest =
1369 CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
1370 "cleanup.dest.saved");
1371
John McCall77199712010-07-21 05:47:49 +00001372 // Emit the finally block.
1373 CGF.EmitStmt(Body);
1374
1375 // If the end of the finally is reachable, check whether this was
1376 // for EH. If so, rethrow.
1377 if (CGF.HaveInsertPoint()) {
1378 llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
1379 llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
1380
1381 llvm::Value *ShouldRethrow =
1382 CGF.Builder.CreateLoad(ForEHVar, "finally.shouldthrow");
1383 CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1384
1385 CGF.EmitBlock(RethrowBB);
1386 if (SavedExnVar) {
John McCallbd7370a2013-02-28 19:01:20 +00001387 CGF.EmitRuntimeCallOrInvoke(RethrowFn,
1388 CGF.Builder.CreateLoad(SavedExnVar));
John McCall77199712010-07-21 05:47:49 +00001389 } else {
John McCallbd7370a2013-02-28 19:01:20 +00001390 CGF.EmitRuntimeCallOrInvoke(RethrowFn);
John McCall77199712010-07-21 05:47:49 +00001391 }
1392 CGF.Builder.CreateUnreachable();
1393
1394 CGF.EmitBlock(ContBB);
John McCalld96a8e72010-08-11 00:16:14 +00001395
1396 // Restore the cleanup destination.
1397 CGF.Builder.CreateStore(SavedCleanupDest,
1398 CGF.getNormalCleanupDestSlot());
John McCall77199712010-07-21 05:47:49 +00001399 }
1400
1401 // Leave the end-catch cleanup. As an optimization, pretend that
1402 // the fallthrough path was inaccessible; we've dynamically proven
1403 // that we're not in the EH case along that path.
1404 if (EndCatchFn) {
1405 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1406 CGF.PopCleanupBlock();
1407 CGF.Builder.restoreIP(SavedIP);
1408 }
1409
1410 // Now make sure we actually have an insertion point or the
1411 // cleanup gods will hate us.
1412 CGF.EnsureInsertPoint();
1413 }
1414 };
John McCall55b20fc2010-07-21 00:52:03 +00001415}
1416
John McCallf1549f62010-07-06 01:34:17 +00001417/// Enters a finally block for an implementation using zero-cost
1418/// exceptions. This is mostly general, but hard-codes some
1419/// language/ABI-specific behavior in the catch-all sections.
John McCalld768e9d2011-06-22 02:32:12 +00001420void CodeGenFunction::FinallyInfo::enter(CodeGenFunction &CGF,
1421 const Stmt *body,
1422 llvm::Constant *beginCatchFn,
1423 llvm::Constant *endCatchFn,
1424 llvm::Constant *rethrowFn) {
1425 assert((beginCatchFn != 0) == (endCatchFn != 0) &&
John McCallf1549f62010-07-06 01:34:17 +00001426 "begin/end catch functions not paired");
John McCalld768e9d2011-06-22 02:32:12 +00001427 assert(rethrowFn && "rethrow function is required");
1428
1429 BeginCatchFn = beginCatchFn;
Mike Stumpd88ea562009-12-09 03:35:49 +00001430
John McCallf1549f62010-07-06 01:34:17 +00001431 // The rethrow function has one of the following two types:
1432 // void (*)()
1433 // void (*)(void*)
1434 // In the latter case we need to pass it the exception object.
1435 // But we can't use the exception slot because the @finally might
1436 // have a landing pad (which would overwrite the exception slot).
Chris Lattner2acc6e32011-07-18 04:24:23 +00001437 llvm::FunctionType *rethrowFnTy =
John McCallf1549f62010-07-06 01:34:17 +00001438 cast<llvm::FunctionType>(
John McCalld768e9d2011-06-22 02:32:12 +00001439 cast<llvm::PointerType>(rethrowFn->getType())->getElementType());
1440 SavedExnVar = 0;
1441 if (rethrowFnTy->getNumParams())
1442 SavedExnVar = CGF.CreateTempAlloca(CGF.Int8PtrTy, "finally.exn");
Mike Stumpd88ea562009-12-09 03:35:49 +00001443
John McCallf1549f62010-07-06 01:34:17 +00001444 // A finally block is a statement which must be executed on any edge
1445 // out of a given scope. Unlike a cleanup, the finally block may
1446 // contain arbitrary control flow leading out of itself. In
1447 // addition, finally blocks should always be executed, even if there
1448 // are no catch handlers higher on the stack. Therefore, we
1449 // surround the protected scope with a combination of a normal
1450 // cleanup (to catch attempts to break out of the block via normal
1451 // control flow) and an EH catch-all (semantically "outside" any try
1452 // statement to which the finally block might have been attached).
1453 // The finally block itself is generated in the context of a cleanup
1454 // which conditionally leaves the catch-all.
John McCall3d3ec1c2010-04-21 10:05:39 +00001455
John McCallf1549f62010-07-06 01:34:17 +00001456 // Jump destination for performing the finally block on an exception
1457 // edge. We'll never actually reach this block, so unreachable is
1458 // fine.
John McCalld768e9d2011-06-22 02:32:12 +00001459 RethrowDest = CGF.getJumpDestInCurrentScope(CGF.getUnreachableBlock());
John McCall3d3ec1c2010-04-21 10:05:39 +00001460
John McCallf1549f62010-07-06 01:34:17 +00001461 // Whether the finally block is being executed for EH purposes.
John McCalld768e9d2011-06-22 02:32:12 +00001462 ForEHVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "finally.for-eh");
1463 CGF.Builder.CreateStore(CGF.Builder.getFalse(), ForEHVar);
Mike Stumpd88ea562009-12-09 03:35:49 +00001464
John McCallf1549f62010-07-06 01:34:17 +00001465 // Enter a normal cleanup which will perform the @finally block.
John McCalld768e9d2011-06-22 02:32:12 +00001466 CGF.EHStack.pushCleanup<PerformFinally>(NormalCleanup, body,
1467 ForEHVar, endCatchFn,
1468 rethrowFn, SavedExnVar);
John McCallf1549f62010-07-06 01:34:17 +00001469
1470 // Enter a catch-all scope.
John McCalld768e9d2011-06-22 02:32:12 +00001471 llvm::BasicBlock *catchBB = CGF.createBasicBlock("finally.catchall");
1472 EHCatchScope *catchScope = CGF.EHStack.pushCatch(1);
1473 catchScope->setCatchAllHandler(0, catchBB);
John McCallf1549f62010-07-06 01:34:17 +00001474}
1475
John McCalld768e9d2011-06-22 02:32:12 +00001476void CodeGenFunction::FinallyInfo::exit(CodeGenFunction &CGF) {
John McCallf1549f62010-07-06 01:34:17 +00001477 // Leave the finally catch-all.
John McCalld768e9d2011-06-22 02:32:12 +00001478 EHCatchScope &catchScope = cast<EHCatchScope>(*CGF.EHStack.begin());
1479 llvm::BasicBlock *catchBB = catchScope.getHandler(0).Block;
John McCall777d6e52011-08-11 02:22:43 +00001480
1481 CGF.popCatchScope();
John McCallf1549f62010-07-06 01:34:17 +00001482
John McCalld768e9d2011-06-22 02:32:12 +00001483 // If there are any references to the catch-all block, emit it.
1484 if (catchBB->use_empty()) {
1485 delete catchBB;
1486 } else {
1487 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveAndClearIP();
1488 CGF.EmitBlock(catchBB);
John McCallf1549f62010-07-06 01:34:17 +00001489
John McCalld768e9d2011-06-22 02:32:12 +00001490 llvm::Value *exn = 0;
John McCallf1549f62010-07-06 01:34:17 +00001491
John McCalld768e9d2011-06-22 02:32:12 +00001492 // If there's a begin-catch function, call it.
1493 if (BeginCatchFn) {
Bill Wendlingae270592011-09-15 18:57:19 +00001494 exn = CGF.getExceptionFromSlot();
John McCallbd7370a2013-02-28 19:01:20 +00001495 CGF.EmitNounwindRuntimeCall(BeginCatchFn, exn);
John McCalld768e9d2011-06-22 02:32:12 +00001496 }
1497
1498 // If we need to remember the exception pointer to rethrow later, do so.
1499 if (SavedExnVar) {
Bill Wendlingae270592011-09-15 18:57:19 +00001500 if (!exn) exn = CGF.getExceptionFromSlot();
John McCalld768e9d2011-06-22 02:32:12 +00001501 CGF.Builder.CreateStore(exn, SavedExnVar);
1502 }
1503
1504 // Tell the cleanups in the finally block that we're do this for EH.
1505 CGF.Builder.CreateStore(CGF.Builder.getTrue(), ForEHVar);
1506
1507 // Thread a jump through the finally cleanup.
1508 CGF.EmitBranchThroughCleanup(RethrowDest);
1509
1510 CGF.Builder.restoreIP(savedIP);
1511 }
1512
1513 // Finally, leave the @finally cleanup.
1514 CGF.PopCleanupBlock();
John McCallf1549f62010-07-06 01:34:17 +00001515}
1516
John McCall66b22772013-02-12 03:51:46 +00001517/// In a terminate landing pad, should we use __clang__call_terminate
1518/// or just a naked call to std::terminate?
1519///
1520/// __clang_call_terminate calls __cxa_begin_catch, which then allows
1521/// std::terminate to usefully report something about the
1522/// violating exception.
1523static bool useClangCallTerminate(CodeGenModule &CGM) {
1524 // Only do this for Itanium-family ABIs in C++ mode.
1525 return (CGM.getLangOpts().CPlusPlus &&
1526 CGM.getTarget().getCXXABI().isItaniumFamily());
1527}
1528
1529/// Get or define the following function:
1530/// void @__clang_call_terminate(i8* %exn) nounwind noreturn
1531/// This code is used only in C++.
1532static llvm::Constant *getClangCallTerminateFn(CodeGenModule &CGM) {
1533 llvm::FunctionType *fnTy =
1534 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
1535 llvm::Constant *fnRef =
1536 CGM.CreateRuntimeFunction(fnTy, "__clang_call_terminate");
1537
1538 llvm::Function *fn = dyn_cast<llvm::Function>(fnRef);
1539 if (fn && fn->empty()) {
1540 fn->setDoesNotThrow();
1541 fn->setDoesNotReturn();
1542
1543 // What we really want is to massively penalize inlining without
1544 // forbidding it completely. The difference between that and
1545 // 'noinline' is negligible.
1546 fn->addFnAttr(llvm::Attribute::NoInline);
1547
1548 // Allow this function to be shared across translation units, but
1549 // we don't want it to turn into an exported symbol.
1550 fn->setLinkage(llvm::Function::LinkOnceODRLinkage);
1551 fn->setVisibility(llvm::Function::HiddenVisibility);
1552
1553 // Set up the function.
1554 llvm::BasicBlock *entry =
1555 llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn);
1556 CGBuilderTy builder(entry);
1557
1558 // Pull the exception pointer out of the parameter list.
1559 llvm::Value *exn = &*fn->arg_begin();
1560
1561 // Call __cxa_begin_catch(exn).
John McCallbd7370a2013-02-28 19:01:20 +00001562 llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn);
1563 catchCall->setDoesNotThrow();
1564 catchCall->setCallingConv(CGM.getRuntimeCC());
John McCall66b22772013-02-12 03:51:46 +00001565
1566 // Call std::terminate().
1567 llvm::CallInst *termCall = builder.CreateCall(getTerminateFn(CGM));
1568 termCall->setDoesNotThrow();
1569 termCall->setDoesNotReturn();
John McCallbd7370a2013-02-28 19:01:20 +00001570 termCall->setCallingConv(CGM.getRuntimeCC());
John McCall66b22772013-02-12 03:51:46 +00001571
1572 // std::terminate cannot return.
1573 builder.CreateUnreachable();
1574 }
1575
1576 return fnRef;
1577}
1578
John McCallf1549f62010-07-06 01:34:17 +00001579llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
1580 if (TerminateLandingPad)
1581 return TerminateLandingPad;
1582
1583 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1584
1585 // This will get inserted at the end of the function.
1586 TerminateLandingPad = createBasicBlock("terminate.lpad");
1587 Builder.SetInsertPoint(TerminateLandingPad);
1588
1589 // Tell the backend that this is a landing pad.
David Blaikie4e4d0842012-03-11 07:00:24 +00001590 const EHPersonality &Personality = EHPersonality::get(CGM.getLangOpts());
Bill Wendling285cfd82011-09-19 20:31:14 +00001591 llvm::LandingPadInst *LPadInst =
1592 Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, NULL),
1593 getOpaquePersonalityFn(CGM, Personality), 0);
1594 LPadInst->addClause(getCatchAllValue(*this));
John McCallf1549f62010-07-06 01:34:17 +00001595
John McCall66b22772013-02-12 03:51:46 +00001596 llvm::CallInst *terminateCall;
1597 if (useClangCallTerminate(CGM)) {
1598 // Extract out the exception pointer.
1599 llvm::Value *exn = Builder.CreateExtractValue(LPadInst, 0);
John McCallbd7370a2013-02-28 19:01:20 +00001600 terminateCall = EmitNounwindRuntimeCall(getClangCallTerminateFn(CGM), exn);
John McCall66b22772013-02-12 03:51:46 +00001601 } else {
John McCallbd7370a2013-02-28 19:01:20 +00001602 terminateCall = EmitNounwindRuntimeCall(getTerminateFn(CGM));
John McCall66b22772013-02-12 03:51:46 +00001603 }
1604 terminateCall->setDoesNotReturn();
John McCalld16c2cf2011-02-08 08:22:06 +00001605 Builder.CreateUnreachable();
Mike Stumpd88ea562009-12-09 03:35:49 +00001606
John McCallf1549f62010-07-06 01:34:17 +00001607 // Restore the saved insertion state.
1608 Builder.restoreIP(SavedIP);
John McCall891f80e2010-04-30 00:06:43 +00001609
John McCallf1549f62010-07-06 01:34:17 +00001610 return TerminateLandingPad;
Mike Stumpd88ea562009-12-09 03:35:49 +00001611}
Mike Stump9b39c512009-12-09 22:59:31 +00001612
1613llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
Mike Stump182f3832009-12-10 00:02:42 +00001614 if (TerminateHandler)
1615 return TerminateHandler;
1616
John McCallf1549f62010-07-06 01:34:17 +00001617 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
Mike Stump76958092009-12-09 23:31:35 +00001618
John McCallf1549f62010-07-06 01:34:17 +00001619 // Set up the terminate handler. This block is inserted at the very
1620 // end of the function by FinishFunction.
Mike Stump182f3832009-12-10 00:02:42 +00001621 TerminateHandler = createBasicBlock("terminate.handler");
John McCallf1549f62010-07-06 01:34:17 +00001622 Builder.SetInsertPoint(TerminateHandler);
John McCall45ff3802013-06-20 21:37:43 +00001623 llvm::CallInst *terminateCall;
1624 if (useClangCallTerminate(CGM)) {
1625 // Load the exception pointer.
1626 llvm::Value *exn = getExceptionFromSlot();
1627 terminateCall = EmitNounwindRuntimeCall(getClangCallTerminateFn(CGM), exn);
1628 } else {
1629 terminateCall = EmitNounwindRuntimeCall(getTerminateFn(CGM));
1630 }
1631 terminateCall->setDoesNotReturn();
Mike Stump9b39c512009-12-09 22:59:31 +00001632 Builder.CreateUnreachable();
1633
John McCall3d3ec1c2010-04-21 10:05:39 +00001634 // Restore the saved insertion state.
John McCallf1549f62010-07-06 01:34:17 +00001635 Builder.restoreIP(SavedIP);
Mike Stump76958092009-12-09 23:31:35 +00001636
Mike Stump9b39c512009-12-09 22:59:31 +00001637 return TerminateHandler;
1638}
John McCallf1549f62010-07-06 01:34:17 +00001639
David Chisnallc6860042012-11-07 16:50:40 +00001640llvm::BasicBlock *CodeGenFunction::getEHResumeBlock(bool isCleanup) {
John McCall777d6e52011-08-11 02:22:43 +00001641 if (EHResumeBlock) return EHResumeBlock;
John McCallff8e1152010-07-23 21:56:41 +00001642
1643 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1644
1645 // We emit a jump to a notional label at the outermost unwind state.
John McCall777d6e52011-08-11 02:22:43 +00001646 EHResumeBlock = createBasicBlock("eh.resume");
1647 Builder.SetInsertPoint(EHResumeBlock);
John McCallff8e1152010-07-23 21:56:41 +00001648
David Blaikie4e4d0842012-03-11 07:00:24 +00001649 const EHPersonality &Personality = EHPersonality::get(CGM.getLangOpts());
John McCallff8e1152010-07-23 21:56:41 +00001650
1651 // This can always be a call because we necessarily didn't find
1652 // anything on the EH stack which needs our help.
Benjamin Krameraf2771b2012-02-08 12:41:24 +00001653 const char *RethrowName = Personality.CatchallRethrowFn;
David Chisnallc6860042012-11-07 16:50:40 +00001654 if (RethrowName != 0 && !isCleanup) {
John McCallbd7370a2013-02-28 19:01:20 +00001655 EmitRuntimeCall(getCatchallRethrowFn(CGM, RethrowName),
1656 getExceptionFromSlot())
John McCall93c332a2011-05-28 21:13:02 +00001657 ->setDoesNotReturn();
1658 } else {
John McCall93c332a2011-05-28 21:13:02 +00001659 switch (CleanupHackLevel) {
1660 case CHL_MandatoryCatchall:
1661 // In mandatory-catchall mode, we need to use
1662 // _Unwind_Resume_or_Rethrow, or whatever the personality's
1663 // equivalent is.
John McCallbd7370a2013-02-28 19:01:20 +00001664 EmitRuntimeCall(getUnwindResumeOrRethrowFn(),
1665 getExceptionFromSlot())
John McCall93c332a2011-05-28 21:13:02 +00001666 ->setDoesNotReturn();
1667 break;
1668 case CHL_MandatoryCleanup: {
Bill Wendling285cfd82011-09-19 20:31:14 +00001669 // In mandatory-cleanup mode, we should use 'resume'.
1670
1671 // Recreate the landingpad's return value for the 'resume' instruction.
1672 llvm::Value *Exn = getExceptionFromSlot();
1673 llvm::Value *Sel = getSelectorFromSlot();
1674
1675 llvm::Type *LPadType = llvm::StructType::get(Exn->getType(),
1676 Sel->getType(), NULL);
1677 llvm::Value *LPadVal = llvm::UndefValue::get(LPadType);
1678 LPadVal = Builder.CreateInsertValue(LPadVal, Exn, 0, "lpad.val");
1679 LPadVal = Builder.CreateInsertValue(LPadVal, Sel, 1, "lpad.val");
1680
1681 Builder.CreateResume(LPadVal);
1682 Builder.restoreIP(SavedIP);
1683 return EHResumeBlock;
John McCall93c332a2011-05-28 21:13:02 +00001684 }
1685 case CHL_Ideal:
1686 // In an idealized mode where we don't have to worry about the
1687 // optimizer combining landing pads, we should just use
1688 // _Unwind_Resume (or the personality's equivalent).
John McCallbd7370a2013-02-28 19:01:20 +00001689 EmitRuntimeCall(getUnwindResumeFn(), getExceptionFromSlot())
John McCall93c332a2011-05-28 21:13:02 +00001690 ->setDoesNotReturn();
1691 break;
1692 }
1693 }
1694
John McCallff8e1152010-07-23 21:56:41 +00001695 Builder.CreateUnreachable();
1696
1697 Builder.restoreIP(SavedIP);
1698
John McCall777d6e52011-08-11 02:22:43 +00001699 return EHResumeBlock;
John McCallff8e1152010-07-23 21:56:41 +00001700}
Reid Kleckner98592d92013-09-16 21:46:30 +00001701
1702void CodeGenFunction::EmitSEHTryStmt(const SEHTryStmt &S) {
1703 CGM.ErrorUnsupported(&S, "SEH __try");
1704}