blob: 8cd49d1703db57c07800a4f040260889e1ec88ba [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 McCall629df012013-02-12 03:51:38 +0000100static llvm::Constant *getTerminateFn(CodeGenModule &CGM) {
Mike Stump99533832009-12-02 07:41:41 +0000101 // void __terminate();
102
Chris Lattner2acc6e32011-07-18 04:24:23 +0000103 llvm::FunctionType *FTy =
John McCall629df012013-02-12 03:51:38 +0000104 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +0000105
Chris Lattner5f9e2722011-07-23 10:55:15 +0000106 StringRef name;
John McCall256a76e2011-07-06 01:22:26 +0000107
108 // In C++, use std::terminate().
John McCall629df012013-02-12 03:51:38 +0000109 if (CGM.getLangOpts().CPlusPlus)
John McCall256a76e2011-07-06 01:22:26 +0000110 name = "_ZSt9terminatev"; // FIXME: mangling!
John McCall629df012013-02-12 03:51:38 +0000111 else if (CGM.getLangOpts().ObjC1 &&
112 CGM.getLangOpts().ObjCRuntime.hasTerminate())
John McCall256a76e2011-07-06 01:22:26 +0000113 name = "objc_terminate";
114 else
115 name = "abort";
John McCall629df012013-02-12 03:51:38 +0000116 return CGM.CreateRuntimeFunction(FTy, name);
David Chisnall79a9ad82010-05-17 13:49:20 +0000117}
118
John McCall629df012013-02-12 03:51:38 +0000119static llvm::Constant *getCatchallRethrowFn(CodeGenModule &CGM,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000120 StringRef Name) {
Chris Lattner2acc6e32011-07-18 04:24:23 +0000121 llvm::FunctionType *FTy =
John McCall629df012013-02-12 03:51:38 +0000122 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
John McCall8262b6a2010-07-17 00:43:08 +0000123
John McCall629df012013-02-12 03:51:38 +0000124 return CGM.CreateRuntimeFunction(FTy, Name);
John McCallf1549f62010-07-06 01:34:17 +0000125}
126
Benjamin Krameraf2771b2012-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
Stephen Hines176edba2014-12-01 14:53:08 -0800137 static const EHPersonality &get(CodeGenModule &CGM);
Benjamin Krameraf2771b2012-02-08 12:41:24 +0000138 static const EHPersonality GNU_C;
139 static const EHPersonality GNU_C_SJLJ;
Stephen Hines176edba2014-12-01 14:53:08 -0800140 static const EHPersonality GNU_C_SEH;
Benjamin Krameraf2771b2012-02-08 12:41:24 +0000141 static const EHPersonality GNU_ObjC;
David Chisnall65bd4ac2013-01-11 15:33:01 +0000142 static const EHPersonality GNUstep_ObjC;
Benjamin Krameraf2771b2012-02-08 12:41:24 +0000143 static const EHPersonality GNU_ObjCXX;
144 static const EHPersonality NeXT_ObjC;
145 static const EHPersonality GNU_CPlusPlus;
146 static const EHPersonality GNU_CPlusPlus_SJLJ;
Stephen Hines176edba2014-12-01 14:53:08 -0800147 static const EHPersonality GNU_CPlusPlus_SEH;
Benjamin Krameraf2771b2012-02-08 12:41:24 +0000148 };
149}
150
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700151const EHPersonality EHPersonality::GNU_C = { "__gcc_personality_v0", nullptr };
Benjamin Krameraf2771b2012-02-08 12:41:24 +0000152const EHPersonality
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700153EHPersonality::GNU_C_SJLJ = { "__gcc_personality_sj0", nullptr };
154const EHPersonality
Stephen Hines176edba2014-12-01 14:53:08 -0800155EHPersonality::GNU_C_SEH = { "__gcc_personality_seh0", nullptr };
156const EHPersonality
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700157EHPersonality::NeXT_ObjC = { "__objc_personality_v0", nullptr };
158const EHPersonality
159EHPersonality::GNU_CPlusPlus = { "__gxx_personality_v0", nullptr };
160const EHPersonality
161EHPersonality::GNU_CPlusPlus_SJLJ = { "__gxx_personality_sj0", nullptr };
Benjamin Krameraf2771b2012-02-08 12:41:24 +0000162const EHPersonality
Stephen Hines176edba2014-12-01 14:53:08 -0800163EHPersonality::GNU_CPlusPlus_SEH = { "__gxx_personality_seh0", nullptr };
164const EHPersonality
Benjamin Krameraf2771b2012-02-08 12:41:24 +0000165EHPersonality::GNU_ObjC = {"__gnu_objc_personality_v0", "objc_exception_throw"};
166const EHPersonality
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700167EHPersonality::GNU_ObjCXX = { "__gnustep_objcxx_personality_v0", nullptr };
David Chisnall65bd4ac2013-01-11 15:33:01 +0000168const EHPersonality
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700169EHPersonality::GNUstep_ObjC = { "__gnustep_objc_personality_v0", nullptr };
John McCall8262b6a2010-07-17 00:43:08 +0000170
Stephen Hines176edba2014-12-01 14:53:08 -0800171/// On Win64, use libgcc's SEH personality function. We fall back to dwarf on
172/// other platforms, unless the user asked for SjLj exceptions.
173static bool useLibGCCSEHPersonality(const llvm::Triple &T) {
174 return T.isOSWindows() && T.getArch() == llvm::Triple::x86_64;
175}
176
177static const EHPersonality &getCPersonality(const llvm::Triple &T,
178 const LangOptions &L) {
John McCall44680782010-11-07 02:35:25 +0000179 if (L.SjLjExceptions)
180 return EHPersonality::GNU_C_SJLJ;
Stephen Hines176edba2014-12-01 14:53:08 -0800181 else if (useLibGCCSEHPersonality(T))
182 return EHPersonality::GNU_C_SEH;
John McCall8262b6a2010-07-17 00:43:08 +0000183 return EHPersonality::GNU_C;
184}
185
Stephen Hines176edba2014-12-01 14:53:08 -0800186static const EHPersonality &getObjCPersonality(const llvm::Triple &T,
187 const LangOptions &L) {
John McCall260611a2012-06-20 06:18:46 +0000188 switch (L.ObjCRuntime.getKind()) {
189 case ObjCRuntime::FragileMacOSX:
Stephen Hines176edba2014-12-01 14:53:08 -0800190 return getCPersonality(T, L);
John McCall260611a2012-06-20 06:18:46 +0000191 case ObjCRuntime::MacOSX:
192 case ObjCRuntime::iOS:
193 return EHPersonality::NeXT_ObjC;
David Chisnall11d3f4c2012-07-03 20:49:52 +0000194 case ObjCRuntime::GNUstep:
David Chisnall65bd4ac2013-01-11 15:33:01 +0000195 if (L.ObjCRuntime.getVersion() >= VersionTuple(1, 7))
196 return EHPersonality::GNUstep_ObjC;
197 // fallthrough
David Chisnall11d3f4c2012-07-03 20:49:52 +0000198 case ObjCRuntime::GCC:
John McCallf7226fb2012-07-12 02:07:58 +0000199 case ObjCRuntime::ObjFW:
John McCall8262b6a2010-07-17 00:43:08 +0000200 return EHPersonality::GNU_ObjC;
John McCallf1549f62010-07-06 01:34:17 +0000201 }
John McCall260611a2012-06-20 06:18:46 +0000202 llvm_unreachable("bad runtime kind");
John McCallf1549f62010-07-06 01:34:17 +0000203}
204
Stephen Hines176edba2014-12-01 14:53:08 -0800205static const EHPersonality &getCXXPersonality(const llvm::Triple &T,
206 const LangOptions &L) {
John McCall8262b6a2010-07-17 00:43:08 +0000207 if (L.SjLjExceptions)
208 return EHPersonality::GNU_CPlusPlus_SJLJ;
Stephen Hines176edba2014-12-01 14:53:08 -0800209 else if (useLibGCCSEHPersonality(T))
210 return EHPersonality::GNU_CPlusPlus_SEH;
211 return EHPersonality::GNU_CPlusPlus;
John McCallf1549f62010-07-06 01:34:17 +0000212}
213
214/// Determines the personality function to use when both C++
215/// and Objective-C exceptions are being caught.
Stephen Hines176edba2014-12-01 14:53:08 -0800216static const EHPersonality &getObjCXXPersonality(const llvm::Triple &T,
217 const LangOptions &L) {
John McCall260611a2012-06-20 06:18:46 +0000218 switch (L.ObjCRuntime.getKind()) {
John McCallf1549f62010-07-06 01:34:17 +0000219 // The ObjC personality defers to the C++ personality for non-ObjC
220 // handlers. Unlike the C++ case, we use the same personality
221 // function on targets using (backend-driven) SJLJ EH.
John McCall260611a2012-06-20 06:18:46 +0000222 case ObjCRuntime::MacOSX:
223 case ObjCRuntime::iOS:
224 return EHPersonality::NeXT_ObjC;
John McCallf1549f62010-07-06 01:34:17 +0000225
John McCall260611a2012-06-20 06:18:46 +0000226 // In the fragile ABI, just use C++ exception handling and hope
227 // they're not doing crazy exception mixing.
228 case ObjCRuntime::FragileMacOSX:
Stephen Hines176edba2014-12-01 14:53:08 -0800229 return getCXXPersonality(T, L);
David Chisnall79a9ad82010-05-17 13:49:20 +0000230
David Chisnall11d3f4c2012-07-03 20:49:52 +0000231 // The GCC runtime's personality function inherently doesn't support
John McCall8262b6a2010-07-17 00:43:08 +0000232 // mixed EH. Use the C++ personality just to avoid returning null.
David Chisnall11d3f4c2012-07-03 20:49:52 +0000233 case ObjCRuntime::GCC:
John McCallf7226fb2012-07-12 02:07:58 +0000234 case ObjCRuntime::ObjFW: // XXX: this will change soon
David Chisnall11d3f4c2012-07-03 20:49:52 +0000235 return EHPersonality::GNU_ObjC;
236 case ObjCRuntime::GNUstep:
John McCall260611a2012-06-20 06:18:46 +0000237 return EHPersonality::GNU_ObjCXX;
238 }
239 llvm_unreachable("bad runtime kind");
John McCallf1549f62010-07-06 01:34:17 +0000240}
241
Stephen Hines176edba2014-12-01 14:53:08 -0800242const EHPersonality &EHPersonality::get(CodeGenModule &CGM) {
243 const llvm::Triple &T = CGM.getTarget().getTriple();
244 const LangOptions &L = CGM.getLangOpts();
John McCall8262b6a2010-07-17 00:43:08 +0000245 if (L.CPlusPlus && L.ObjC1)
Stephen Hines176edba2014-12-01 14:53:08 -0800246 return getObjCXXPersonality(T, L);
John McCall8262b6a2010-07-17 00:43:08 +0000247 else if (L.CPlusPlus)
Stephen Hines176edba2014-12-01 14:53:08 -0800248 return getCXXPersonality(T, L);
John McCall8262b6a2010-07-17 00:43:08 +0000249 else if (L.ObjC1)
Stephen Hines176edba2014-12-01 14:53:08 -0800250 return getObjCPersonality(T, L);
John McCallf1549f62010-07-06 01:34:17 +0000251 else
Stephen Hines176edba2014-12-01 14:53:08 -0800252 return getCPersonality(T, L);
John McCall8262b6a2010-07-17 00:43:08 +0000253}
John McCallf1549f62010-07-06 01:34:17 +0000254
John McCallb2593832010-09-16 06:16:50 +0000255static llvm::Constant *getPersonalityFn(CodeGenModule &CGM,
John McCall8262b6a2010-07-17 00:43:08 +0000256 const EHPersonality &Personality) {
John McCall8262b6a2010-07-17 00:43:08 +0000257 llvm::Constant *Fn =
Chris Lattner8b418682012-02-07 00:39:47 +0000258 CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.Int32Ty, true),
Benjamin Krameraf2771b2012-02-08 12:41:24 +0000259 Personality.PersonalityFn);
John McCallb2593832010-09-16 06:16:50 +0000260 return Fn;
261}
262
263static llvm::Constant *getOpaquePersonalityFn(CodeGenModule &CGM,
264 const EHPersonality &Personality) {
265 llvm::Constant *Fn = getPersonalityFn(CGM, Personality);
John McCalld16c2cf2011-02-08 08:22:06 +0000266 return llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
John McCallb2593832010-09-16 06:16:50 +0000267}
268
269/// Check whether a personality function could reasonably be swapped
270/// for a C++ personality function.
271static bool PersonalityHasOnlyCXXUses(llvm::Constant *Fn) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700272 for (llvm::User *U : Fn->users()) {
John McCallb2593832010-09-16 06:16:50 +0000273 // Conditionally white-list bitcasts.
Stephen Hines651f13c2014-04-23 16:59:28 -0700274 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(U)) {
John McCallb2593832010-09-16 06:16:50 +0000275 if (CE->getOpcode() != llvm::Instruction::BitCast) return false;
276 if (!PersonalityHasOnlyCXXUses(CE))
277 return false;
278 continue;
279 }
280
Bill Wendling40ccacc2011-09-19 22:08:36 +0000281 // Otherwise, it has to be a landingpad instruction.
Stephen Hines651f13c2014-04-23 16:59:28 -0700282 llvm::LandingPadInst *LPI = dyn_cast<llvm::LandingPadInst>(U);
Bill Wendling40ccacc2011-09-19 22:08:36 +0000283 if (!LPI) return false;
John McCallb2593832010-09-16 06:16:50 +0000284
Bill Wendling40ccacc2011-09-19 22:08:36 +0000285 for (unsigned I = 0, E = LPI->getNumClauses(); I != E; ++I) {
John McCallb2593832010-09-16 06:16:50 +0000286 // Look for something that would've been returned by the ObjC
287 // runtime's GetEHType() method.
Bill Wendling40ccacc2011-09-19 22:08:36 +0000288 llvm::Value *Val = LPI->getClause(I)->stripPointerCasts();
289 if (LPI->isCatch(I)) {
290 // Check if the catch value has the ObjC prefix.
Bill Wendlingeecb6a12011-09-20 00:40:19 +0000291 if (llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Val))
292 // ObjC EH selector entries are always global variables with
293 // names starting like this.
294 if (GV->getName().startswith("OBJC_EHTYPE"))
295 return false;
Bill Wendling40ccacc2011-09-19 22:08:36 +0000296 } else {
297 // Check if any of the filter values have the ObjC prefix.
298 llvm::Constant *CVal = cast<llvm::Constant>(Val);
299 for (llvm::User::op_iterator
300 II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II) {
Bill Wendlingeecb6a12011-09-20 00:40:19 +0000301 if (llvm::GlobalVariable *GV =
302 cast<llvm::GlobalVariable>((*II)->stripPointerCasts()))
303 // ObjC EH selector entries are always global variables with
304 // names starting like this.
305 if (GV->getName().startswith("OBJC_EHTYPE"))
306 return false;
Bill Wendling40ccacc2011-09-19 22:08:36 +0000307 }
308 }
John McCallb2593832010-09-16 06:16:50 +0000309 }
310 }
311
312 return true;
313}
314
315/// Try to use the C++ personality function in ObjC++. Not doing this
316/// can cause some incompatibilities with gcc, which is more
317/// aggressive about only using the ObjC++ personality in a function
318/// when it really needs it.
319void CodeGenModule::SimplifyPersonality() {
John McCallb2593832010-09-16 06:16:50 +0000320 // If we're not in ObjC++ -fexceptions, there's nothing to do.
David Blaikie4e4d0842012-03-11 07:00:24 +0000321 if (!LangOpts.CPlusPlus || !LangOpts.ObjC1 || !LangOpts.Exceptions)
John McCallb2593832010-09-16 06:16:50 +0000322 return;
323
John McCall70cd6192012-11-14 17:48:31 +0000324 // Both the problem this endeavors to fix and the way the logic
325 // above works is specific to the NeXT runtime.
326 if (!LangOpts.ObjCRuntime.isNeXTFamily())
327 return;
328
Stephen Hines176edba2014-12-01 14:53:08 -0800329 const EHPersonality &ObjCXX = EHPersonality::get(*this);
330 const EHPersonality &CXX =
331 getCXXPersonality(getTarget().getTriple(), LangOpts);
Benjamin Krameraf2771b2012-02-08 12:41:24 +0000332 if (&ObjCXX == &CXX)
John McCallb2593832010-09-16 06:16:50 +0000333 return;
334
Benjamin Krameraf2771b2012-02-08 12:41:24 +0000335 assert(std::strcmp(ObjCXX.PersonalityFn, CXX.PersonalityFn) != 0 &&
336 "Different EHPersonalities using the same personality function.");
337
338 llvm::Function *Fn = getModule().getFunction(ObjCXX.PersonalityFn);
John McCallb2593832010-09-16 06:16:50 +0000339
340 // Nothing to do if it's unused.
341 if (!Fn || Fn->use_empty()) return;
342
343 // Can't do the optimization if it has non-C++ uses.
344 if (!PersonalityHasOnlyCXXUses(Fn)) return;
345
346 // Create the C++ personality function and kill off the old
347 // function.
348 llvm::Constant *CXXFn = getPersonalityFn(*this, CXX);
349
350 // This can happen if the user is screwing with us.
351 if (Fn->getType() != CXXFn->getType()) return;
352
353 Fn->replaceAllUsesWith(CXXFn);
354 Fn->eraseFromParent();
John McCallf1549f62010-07-06 01:34:17 +0000355}
356
357/// Returns the value to inject into a selector to indicate the
358/// presence of a catch-all.
359static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
360 // Possibly we should use @llvm.eh.catch.all.value here.
John McCalld16c2cf2011-02-08 08:22:06 +0000361 return llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
John McCallf1549f62010-07-06 01:34:17 +0000362}
363
John McCall09faeab2010-07-13 21:17:51 +0000364namespace {
365 /// A cleanup to free the exception object if its initialization
366 /// throws.
John McCallc4a1a842011-07-12 00:15:30 +0000367 struct FreeException : EHScopeStack::Cleanup {
368 llvm::Value *exn;
369 FreeException(llvm::Value *exn) : exn(exn) {}
Stephen Hines651f13c2014-04-23 16:59:28 -0700370 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallbd7370a2013-02-28 19:01:20 +0000371 CGF.EmitNounwindRuntimeCall(getFreeExceptionFn(CGF.CGM), exn);
John McCall09faeab2010-07-13 21:17:51 +0000372 }
373 };
374}
375
John McCallac418162010-04-22 01:10:34 +0000376// Emits an exception expression into the given location. This
377// differs from EmitAnyExprToMem only in that, if a final copy-ctor
378// call is required, an exception within that copy ctor causes
379// std::terminate to be invoked.
John McCall3ad32c82011-01-28 08:37:24 +0000380static void EmitAnyExprToExn(CodeGenFunction &CGF, const Expr *e,
381 llvm::Value *addr) {
John McCallf1549f62010-07-06 01:34:17 +0000382 // Make sure the exception object is cleaned up if there's an
383 // exception during initialization.
John McCall3ad32c82011-01-28 08:37:24 +0000384 CGF.pushFullExprCleanup<FreeException>(EHCleanup, addr);
385 EHScopeStack::stable_iterator cleanup = CGF.EHStack.stable_begin();
John McCallac418162010-04-22 01:10:34 +0000386
387 // __cxa_allocate_exception returns a void*; we need to cast this
388 // to the appropriate type for the object.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000389 llvm::Type *ty = CGF.ConvertTypeForMem(e->getType())->getPointerTo();
John McCall3ad32c82011-01-28 08:37:24 +0000390 llvm::Value *typedAddr = CGF.Builder.CreateBitCast(addr, ty);
John McCallac418162010-04-22 01:10:34 +0000391
392 // FIXME: this isn't quite right! If there's a final unelided call
393 // to a copy constructor, then according to [except.terminate]p1 we
394 // must call std::terminate() if that constructor throws, because
395 // technically that copy occurs after the exception expression is
396 // evaluated but before the exception is caught. But the best way
397 // to handle that is to teach EmitAggExpr to do the final copy
398 // differently if it can't be elided.
Chad Rosier649b4a12012-03-29 17:37:10 +0000399 CGF.EmitAnyExprToMem(e, typedAddr, e->getType().getQualifiers(),
400 /*IsInit*/ true);
John McCallac418162010-04-22 01:10:34 +0000401
John McCall3ad32c82011-01-28 08:37:24 +0000402 // Deactivate the cleanup block.
John McCall6f103ba2011-11-10 10:43:54 +0000403 CGF.DeactivateCleanupBlock(cleanup, cast<llvm::Instruction>(typedAddr));
Mike Stump0f590be2009-12-01 03:41:18 +0000404}
405
John McCallf1549f62010-07-06 01:34:17 +0000406llvm::Value *CodeGenFunction::getExceptionSlot() {
John McCall93c332a2011-05-28 21:13:02 +0000407 if (!ExceptionSlot)
408 ExceptionSlot = CreateTempAlloca(Int8PtrTy, "exn.slot");
John McCallf1549f62010-07-06 01:34:17 +0000409 return ExceptionSlot;
Mike Stump0f590be2009-12-01 03:41:18 +0000410}
411
John McCall93c332a2011-05-28 21:13:02 +0000412llvm::Value *CodeGenFunction::getEHSelectorSlot() {
413 if (!EHSelectorSlot)
414 EHSelectorSlot = CreateTempAlloca(Int32Ty, "ehselector.slot");
415 return EHSelectorSlot;
416}
417
Bill Wendlingae270592011-09-15 18:57:19 +0000418llvm::Value *CodeGenFunction::getExceptionFromSlot() {
419 return Builder.CreateLoad(getExceptionSlot(), "exn");
420}
421
422llvm::Value *CodeGenFunction::getSelectorFromSlot() {
423 return Builder.CreateLoad(getEHSelectorSlot(), "sel");
424}
425
Richard Smith4c71b8c2013-05-07 21:53:22 +0000426void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E,
427 bool KeepInsertionPoint) {
Stephen Hines176edba2014-12-01 14:53:08 -0800428 if (CGM.getTarget().getTriple().isKnownWindowsMSVCEnvironment()) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700429 ErrorUnsupported(E, "throw expression");
430 return;
431 }
432
Anders Carlssond3379292009-10-30 02:27:02 +0000433 if (!E->getSubExpr()) {
Stephen Hines176edba2014-12-01 14:53:08 -0800434 EmitNoreturnRuntimeCallOrInvoke(getReThrowFn(CGM), None);
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000435
John McCallcd5b22e2011-01-12 03:41:02 +0000436 // throw is an expression, and the expression emitters expect us
437 // to leave ourselves at a valid insertion point.
Richard Smith4c71b8c2013-05-07 21:53:22 +0000438 if (KeepInsertionPoint)
439 EmitBlock(createBasicBlock("throw.cont"));
John McCallcd5b22e2011-01-12 03:41:02 +0000440
Anders Carlssond3379292009-10-30 02:27:02 +0000441 return;
442 }
Mike Stump8755ec32009-12-10 00:06:18 +0000443
Anders Carlssond3379292009-10-30 02:27:02 +0000444 QualType ThrowType = E->getSubExpr()->getType();
Mike Stump8755ec32009-12-10 00:06:18 +0000445
Fariborz Jahanian6a3c70e2013-01-10 19:02:56 +0000446 if (ThrowType->isObjCObjectPointerType()) {
447 const Stmt *ThrowStmt = E->getSubExpr();
448 const ObjCAtThrowStmt S(E->getExprLoc(),
449 const_cast<Stmt *>(ThrowStmt));
450 CGM.getObjCRuntime().EmitThrowStmt(*this, S, false);
451 // This will clear insertion point which was not cleared in
452 // call to EmitThrowStmt.
Richard Smith4c71b8c2013-05-07 21:53:22 +0000453 if (KeepInsertionPoint)
454 EmitBlock(createBasicBlock("throw.cont"));
Fariborz Jahanian6a3c70e2013-01-10 19:02:56 +0000455 return;
456 }
457
Anders Carlssond3379292009-10-30 02:27:02 +0000458 // Now allocate the exception object.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000459 llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
John McCall3d3ec1c2010-04-21 10:05:39 +0000460 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
Mike Stump8755ec32009-12-10 00:06:18 +0000461
John McCall629df012013-02-12 03:51:38 +0000462 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(CGM);
John McCallf1549f62010-07-06 01:34:17 +0000463 llvm::CallInst *ExceptionPtr =
John McCallbd7370a2013-02-28 19:01:20 +0000464 EmitNounwindRuntimeCall(AllocExceptionFn,
465 llvm::ConstantInt::get(SizeTy, TypeSize),
466 "exception");
Anders Carlsson8370c582009-12-11 00:32:37 +0000467
John McCallac418162010-04-22 01:10:34 +0000468 EmitAnyExprToExn(*this, E->getSubExpr(), ExceptionPtr);
Mike Stump8755ec32009-12-10 00:06:18 +0000469
Anders Carlssond3379292009-10-30 02:27:02 +0000470 // Now throw the exception.
Anders Carlsson82a113a2011-01-24 01:59:49 +0000471 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
472 /*ForEH=*/true);
John McCallac418162010-04-22 01:10:34 +0000473
474 // The address of the destructor. If the exception type has a
475 // trivial destructor (or isn't a record), we just pass null.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700476 llvm::Constant *Dtor = nullptr;
John McCallac418162010-04-22 01:10:34 +0000477 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
478 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
479 if (!Record->hasTrivialDestructor()) {
Douglas Gregor1d110e02010-07-01 14:13:13 +0000480 CXXDestructorDecl *DtorD = Record->getDestructor();
Stephen Hines176edba2014-12-01 14:53:08 -0800481 Dtor = CGM.getAddrOfCXXStructor(DtorD, StructorType::Complete);
John McCallac418162010-04-22 01:10:34 +0000482 Dtor = llvm::ConstantExpr::getBitCast(Dtor, Int8PtrTy);
483 }
484 }
485 if (!Dtor) Dtor = llvm::Constant::getNullValue(Int8PtrTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000486
John McCallbd7370a2013-02-28 19:01:20 +0000487 llvm::Value *args[] = { ExceptionPtr, TypeInfo, Dtor };
488 EmitNoreturnRuntimeCallOrInvoke(getThrowFn(CGM), args);
Mike Stump8755ec32009-12-10 00:06:18 +0000489
John McCallcd5b22e2011-01-12 03:41:02 +0000490 // throw is an expression, and the expression emitters expect us
491 // to leave ourselves at a valid insertion point.
Richard Smith4c71b8c2013-05-07 21:53:22 +0000492 if (KeepInsertionPoint)
493 EmitBlock(createBasicBlock("throw.cont"));
Anders Carlsson756b5c42009-10-30 01:42:31 +0000494}
Mike Stump2bf701e2009-11-20 23:44:51 +0000495
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000496void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000497 if (!CGM.getLangOpts().CXXExceptions)
Anders Carlssona994ee42010-02-06 23:59:05 +0000498 return;
499
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000500 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700501 if (!FD) {
502 // Check if CapturedDecl is nothrow and create terminate scope for it.
503 if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
504 if (CD->isNothrow())
505 EHStack.pushTerminate();
506 }
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000507 return;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700508 }
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000509 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700510 if (!Proto)
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000511 return;
512
Sebastian Redla968e972011-03-15 18:42:48 +0000513 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
514 if (isNoexceptExceptionSpec(EST)) {
515 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
516 // noexcept functions are simple terminate scopes.
517 EHStack.pushTerminate();
518 }
519 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
520 unsigned NumExceptions = Proto->getNumExceptions();
521 EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000522
Sebastian Redla968e972011-03-15 18:42:48 +0000523 for (unsigned I = 0; I != NumExceptions; ++I) {
524 QualType Ty = Proto->getExceptionType(I);
525 QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
526 llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType,
527 /*ForEH=*/true);
528 Filter->setFilter(I, EHType);
529 }
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000530 }
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000531}
532
John McCall777d6e52011-08-11 02:22:43 +0000533/// Emit the dispatch block for a filter scope if necessary.
534static void emitFilterDispatchBlock(CodeGenFunction &CGF,
535 EHFilterScope &filterScope) {
536 llvm::BasicBlock *dispatchBlock = filterScope.getCachedEHDispatchBlock();
537 if (!dispatchBlock) return;
538 if (dispatchBlock->use_empty()) {
539 delete dispatchBlock;
540 return;
541 }
542
John McCall777d6e52011-08-11 02:22:43 +0000543 CGF.EmitBlockAfterUses(dispatchBlock);
544
545 // If this isn't a catch-all filter, we need to check whether we got
546 // here because the filter triggered.
547 if (filterScope.getNumFilters()) {
548 // Load the selector value.
Bill Wendlingae270592011-09-15 18:57:19 +0000549 llvm::Value *selector = CGF.getSelectorFromSlot();
John McCall777d6e52011-08-11 02:22:43 +0000550 llvm::BasicBlock *unexpectedBB = CGF.createBasicBlock("ehspec.unexpected");
551
552 llvm::Value *zero = CGF.Builder.getInt32(0);
553 llvm::Value *failsFilter =
554 CGF.Builder.CreateICmpSLT(selector, zero, "ehspec.fails");
David Chisnallc6860042012-11-07 16:50:40 +0000555 CGF.Builder.CreateCondBr(failsFilter, unexpectedBB, CGF.getEHResumeBlock(false));
John McCall777d6e52011-08-11 02:22:43 +0000556
557 CGF.EmitBlock(unexpectedBB);
558 }
559
560 // Call __cxa_call_unexpected. This doesn't need to be an invoke
561 // because __cxa_call_unexpected magically filters exceptions
562 // according to the last landing pad the exception was thrown
563 // into. Seriously.
Bill Wendlingae270592011-09-15 18:57:19 +0000564 llvm::Value *exn = CGF.getExceptionFromSlot();
John McCallbd7370a2013-02-28 19:01:20 +0000565 CGF.EmitRuntimeCall(getUnexpectedFn(CGF.CGM), exn)
John McCall777d6e52011-08-11 02:22:43 +0000566 ->setDoesNotReturn();
567 CGF.Builder.CreateUnreachable();
568}
569
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000570void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000571 if (!CGM.getLangOpts().CXXExceptions)
Anders Carlssona994ee42010-02-06 23:59:05 +0000572 return;
573
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000574 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700575 if (!FD) {
576 // Check if CapturedDecl is nothrow and pop terminate scope for it.
577 if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
578 if (CD->isNothrow())
579 EHStack.popTerminate();
580 }
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000581 return;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700582 }
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000583 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700584 if (!Proto)
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000585 return;
586
Sebastian Redla968e972011-03-15 18:42:48 +0000587 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
588 if (isNoexceptExceptionSpec(EST)) {
589 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
590 EHStack.popTerminate();
591 }
592 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
John McCall777d6e52011-08-11 02:22:43 +0000593 EHFilterScope &filterScope = cast<EHFilterScope>(*EHStack.begin());
594 emitFilterDispatchBlock(*this, filterScope);
Sebastian Redla968e972011-03-15 18:42:48 +0000595 EHStack.popFilter();
596 }
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000597}
598
Mike Stump2bf701e2009-11-20 23:44:51 +0000599void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
Stephen Hines176edba2014-12-01 14:53:08 -0800600 if (CGM.getTarget().getTriple().isKnownWindowsMSVCEnvironment()) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700601 ErrorUnsupported(&S, "try statement");
602 return;
603 }
604
John McCall59a70002010-07-07 06:56:46 +0000605 EnterCXXTryStmt(S);
John McCall9fc6a772010-02-19 09:25:03 +0000606 EmitStmt(S.getTryBlock());
John McCall59a70002010-07-07 06:56:46 +0000607 ExitCXXTryStmt(S);
John McCall9fc6a772010-02-19 09:25:03 +0000608}
609
John McCall59a70002010-07-07 06:56:46 +0000610void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallf1549f62010-07-06 01:34:17 +0000611 unsigned NumHandlers = S.getNumHandlers();
612 EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
John McCall9fc6a772010-02-19 09:25:03 +0000613
John McCallf1549f62010-07-06 01:34:17 +0000614 for (unsigned I = 0; I != NumHandlers; ++I) {
615 const CXXCatchStmt *C = S.getHandler(I);
John McCall9fc6a772010-02-19 09:25:03 +0000616
John McCallf1549f62010-07-06 01:34:17 +0000617 llvm::BasicBlock *Handler = createBasicBlock("catch");
618 if (C->getExceptionDecl()) {
619 // FIXME: Dropping the reference type on the type into makes it
620 // impossible to correctly implement catch-by-reference
621 // semantics for pointers. Unfortunately, this is what all
622 // existing compilers do, and it's not clear that the standard
623 // personality routine is capable of doing this right. See C++ DR 388:
624 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
Stephen Hines176edba2014-12-01 14:53:08 -0800625 Qualifiers CaughtTypeQuals;
626 QualType CaughtType = CGM.getContext().getUnqualifiedArrayType(
627 C->getCaughtType().getNonReferenceType(), CaughtTypeQuals);
John McCall5a180392010-07-24 00:37:23 +0000628
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700629 llvm::Constant *TypeInfo = nullptr;
John McCall5a180392010-07-24 00:37:23 +0000630 if (CaughtType->isObjCObjectPointerType())
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +0000631 TypeInfo = CGM.getObjCRuntime().GetEHType(CaughtType);
John McCall5a180392010-07-24 00:37:23 +0000632 else
Anders Carlsson82a113a2011-01-24 01:59:49 +0000633 TypeInfo = CGM.GetAddrOfRTTIDescriptor(CaughtType, /*ForEH=*/true);
John McCallf1549f62010-07-06 01:34:17 +0000634 CatchScope->setHandler(I, TypeInfo, Handler);
635 } else {
636 // No exception decl indicates '...', a catch-all.
637 CatchScope->setCatchAllHandler(I, Handler);
638 }
639 }
John McCallf1549f62010-07-06 01:34:17 +0000640}
641
John McCall777d6e52011-08-11 02:22:43 +0000642llvm::BasicBlock *
643CodeGenFunction::getEHDispatchBlock(EHScopeStack::stable_iterator si) {
644 // The dispatch block for the end of the scope chain is a block that
645 // just resumes unwinding.
646 if (si == EHStack.stable_end())
David Chisnallc6860042012-11-07 16:50:40 +0000647 return getEHResumeBlock(true);
John McCall777d6e52011-08-11 02:22:43 +0000648
649 // Otherwise, we should look at the actual scope.
650 EHScope &scope = *EHStack.find(si);
651
652 llvm::BasicBlock *dispatchBlock = scope.getCachedEHDispatchBlock();
653 if (!dispatchBlock) {
654 switch (scope.getKind()) {
655 case EHScope::Catch: {
656 // Apply a special case to a single catch-all.
657 EHCatchScope &catchScope = cast<EHCatchScope>(scope);
658 if (catchScope.getNumHandlers() == 1 &&
659 catchScope.getHandler(0).isCatchAll()) {
660 dispatchBlock = catchScope.getHandler(0).Block;
661
662 // Otherwise, make a dispatch block.
663 } else {
664 dispatchBlock = createBasicBlock("catch.dispatch");
665 }
666 break;
667 }
668
669 case EHScope::Cleanup:
670 dispatchBlock = createBasicBlock("ehcleanup");
671 break;
672
673 case EHScope::Filter:
674 dispatchBlock = createBasicBlock("filter.dispatch");
675 break;
676
677 case EHScope::Terminate:
678 dispatchBlock = getTerminateHandler();
679 break;
680 }
681 scope.setCachedEHDispatchBlock(dispatchBlock);
682 }
683 return dispatchBlock;
684}
685
John McCallf1549f62010-07-06 01:34:17 +0000686/// Check whether this is a non-EH scope, i.e. a scope which doesn't
687/// affect exception handling. Currently, the only non-EH scopes are
688/// normal-only cleanup scopes.
689static bool isNonEHScope(const EHScope &S) {
John McCallda65ea82010-07-13 20:32:21 +0000690 switch (S.getKind()) {
John McCall1f0fca52010-07-21 07:22:38 +0000691 case EHScope::Cleanup:
692 return !cast<EHCleanupScope>(S).isEHCleanup();
John McCallda65ea82010-07-13 20:32:21 +0000693 case EHScope::Filter:
694 case EHScope::Catch:
695 case EHScope::Terminate:
696 return false;
697 }
698
David Blaikie30263482012-01-20 21:50:17 +0000699 llvm_unreachable("Invalid EHScope Kind!");
John McCallf1549f62010-07-06 01:34:17 +0000700}
701
702llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
703 assert(EHStack.requiresLandingPad());
704 assert(!EHStack.empty());
705
David Blaikie4e4d0842012-03-11 07:00:24 +0000706 if (!CGM.getLangOpts().Exceptions)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700707 return nullptr;
John McCallda65ea82010-07-13 20:32:21 +0000708
John McCallf1549f62010-07-06 01:34:17 +0000709 // Check the innermost scope for a cached landing pad. If this is
710 // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
711 llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
712 if (LP) return LP;
713
714 // Build the landing pad for this scope.
715 LP = EmitLandingPad();
716 assert(LP);
717
718 // Cache the landing pad on the innermost scope. If this is a
719 // non-EH scope, cache the landing pad on the enclosing scope, too.
720 for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
721 ir->setCachedLandingPad(LP);
722 if (!isNonEHScope(*ir)) break;
723 }
724
725 return LP;
726}
727
728llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
729 assert(EHStack.requiresLandingPad());
730
John McCall777d6e52011-08-11 02:22:43 +0000731 EHScope &innermostEHScope = *EHStack.find(EHStack.getInnermostEHScope());
732 switch (innermostEHScope.getKind()) {
733 case EHScope::Terminate:
734 return getTerminateLandingPad();
John McCallf1549f62010-07-06 01:34:17 +0000735
John McCall777d6e52011-08-11 02:22:43 +0000736 case EHScope::Catch:
737 case EHScope::Cleanup:
738 case EHScope::Filter:
739 if (llvm::BasicBlock *lpad = innermostEHScope.getCachedLandingPad())
740 return lpad;
John McCallf1549f62010-07-06 01:34:17 +0000741 }
742
743 // Save the current IR generation state.
John McCall777d6e52011-08-11 02:22:43 +0000744 CGBuilderTy::InsertPoint savedIP = Builder.saveAndClearIP();
Stephen Hines651f13c2014-04-23 16:59:28 -0700745 SaveAndRestoreLocation AutoRestoreLocation(*this, Builder);
746 if (CGDebugInfo *DI = getDebugInfo())
Adrian Prantl59f0a5a2013-05-16 00:41:29 +0000747 DI->EmitLocation(Builder, CurEHLocation);
John McCallf1549f62010-07-06 01:34:17 +0000748
Stephen Hines176edba2014-12-01 14:53:08 -0800749 const EHPersonality &personality = EHPersonality::get(CGM);
John McCall8262b6a2010-07-17 00:43:08 +0000750
John McCallf1549f62010-07-06 01:34:17 +0000751 // Create and configure the landing pad.
John McCall777d6e52011-08-11 02:22:43 +0000752 llvm::BasicBlock *lpad = createBasicBlock("lpad");
753 EmitBlock(lpad);
John McCallf1549f62010-07-06 01:34:17 +0000754
Bill Wendling285cfd82011-09-19 20:31:14 +0000755 llvm::LandingPadInst *LPadInst =
756 Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, NULL),
757 getOpaquePersonalityFn(CGM, personality), 0);
758
759 llvm::Value *LPadExn = Builder.CreateExtractValue(LPadInst, 0);
760 Builder.CreateStore(LPadExn, getExceptionSlot());
761 llvm::Value *LPadSel = Builder.CreateExtractValue(LPadInst, 1);
762 Builder.CreateStore(LPadSel, getEHSelectorSlot());
763
John McCallf1549f62010-07-06 01:34:17 +0000764 // Save the exception pointer. It's safe to use a single exception
765 // pointer per function because EH cleanups can never have nested
766 // try/catches.
Bill Wendling285cfd82011-09-19 20:31:14 +0000767 // Build the landingpad instruction.
John McCallf1549f62010-07-06 01:34:17 +0000768
769 // Accumulate all the handlers in scope.
John McCall777d6e52011-08-11 02:22:43 +0000770 bool hasCatchAll = false;
771 bool hasCleanup = false;
772 bool hasFilter = false;
773 SmallVector<llvm::Value*, 4> filterTypes;
774 llvm::SmallPtrSet<llvm::Value*, 4> catchTypes;
John McCallf1549f62010-07-06 01:34:17 +0000775 for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end();
776 I != E; ++I) {
777
778 switch (I->getKind()) {
John McCall1f0fca52010-07-21 07:22:38 +0000779 case EHScope::Cleanup:
John McCall777d6e52011-08-11 02:22:43 +0000780 // If we have a cleanup, remember that.
781 hasCleanup = (hasCleanup || cast<EHCleanupScope>(*I).isEHCleanup());
John McCallda65ea82010-07-13 20:32:21 +0000782 continue;
783
John McCallf1549f62010-07-06 01:34:17 +0000784 case EHScope::Filter: {
785 assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
John McCall777d6e52011-08-11 02:22:43 +0000786 assert(!hasCatchAll && "EH filter reached after catch-all");
John McCallf1549f62010-07-06 01:34:17 +0000787
Bill Wendling285cfd82011-09-19 20:31:14 +0000788 // Filter scopes get added to the landingpad in weird ways.
John McCall777d6e52011-08-11 02:22:43 +0000789 EHFilterScope &filter = cast<EHFilterScope>(*I);
790 hasFilter = true;
John McCallf1549f62010-07-06 01:34:17 +0000791
Bill Wendling8990daf2011-09-22 20:32:54 +0000792 // Add all the filter values.
793 for (unsigned i = 0, e = filter.getNumFilters(); i != e; ++i)
794 filterTypes.push_back(filter.getFilter(i));
John McCallf1549f62010-07-06 01:34:17 +0000795 goto done;
796 }
797
798 case EHScope::Terminate:
799 // Terminate scopes are basically catch-alls.
John McCall777d6e52011-08-11 02:22:43 +0000800 assert(!hasCatchAll);
801 hasCatchAll = true;
John McCallf1549f62010-07-06 01:34:17 +0000802 goto done;
803
804 case EHScope::Catch:
805 break;
806 }
807
John McCall777d6e52011-08-11 02:22:43 +0000808 EHCatchScope &catchScope = cast<EHCatchScope>(*I);
809 for (unsigned hi = 0, he = catchScope.getNumHandlers(); hi != he; ++hi) {
810 EHCatchScope::Handler handler = catchScope.getHandler(hi);
John McCallf1549f62010-07-06 01:34:17 +0000811
John McCall777d6e52011-08-11 02:22:43 +0000812 // If this is a catch-all, register that and abort.
813 if (!handler.Type) {
814 assert(!hasCatchAll);
815 hasCatchAll = true;
816 goto done;
John McCallf1549f62010-07-06 01:34:17 +0000817 }
818
819 // Check whether we already have a handler for this type.
Stephen Hines176edba2014-12-01 14:53:08 -0800820 if (catchTypes.insert(handler.Type).second)
Bill Wendling285cfd82011-09-19 20:31:14 +0000821 // If not, add it directly to the landingpad.
822 LPadInst->addClause(handler.Type);
John McCallf1549f62010-07-06 01:34:17 +0000823 }
John McCallf1549f62010-07-06 01:34:17 +0000824 }
825
826 done:
Bill Wendling285cfd82011-09-19 20:31:14 +0000827 // If we have a catch-all, add null to the landingpad.
John McCall777d6e52011-08-11 02:22:43 +0000828 assert(!(hasCatchAll && hasFilter));
829 if (hasCatchAll) {
Bill Wendling285cfd82011-09-19 20:31:14 +0000830 LPadInst->addClause(getCatchAllValue(*this));
John McCallf1549f62010-07-06 01:34:17 +0000831
832 // If we have an EH filter, we need to add those handlers in the
Bill Wendling285cfd82011-09-19 20:31:14 +0000833 // right place in the landingpad, which is to say, at the end.
John McCall777d6e52011-08-11 02:22:43 +0000834 } else if (hasFilter) {
Bill Wendling40ccacc2011-09-19 22:08:36 +0000835 // Create a filter expression: a constant array indicating which filter
836 // types there are. The personality routine only lands here if the filter
837 // doesn't match.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000838 SmallVector<llvm::Constant*, 8> Filters;
Bill Wendling285cfd82011-09-19 20:31:14 +0000839 llvm::ArrayType *AType =
840 llvm::ArrayType::get(!filterTypes.empty() ?
841 filterTypes[0]->getType() : Int8PtrTy,
842 filterTypes.size());
843
844 for (unsigned i = 0, e = filterTypes.size(); i != e; ++i)
845 Filters.push_back(cast<llvm::Constant>(filterTypes[i]));
846 llvm::Constant *FilterArray = llvm::ConstantArray::get(AType, Filters);
847 LPadInst->addClause(FilterArray);
John McCallf1549f62010-07-06 01:34:17 +0000848
849 // Also check whether we need a cleanup.
Bill Wendling285cfd82011-09-19 20:31:14 +0000850 if (hasCleanup)
851 LPadInst->setCleanup(true);
John McCallf1549f62010-07-06 01:34:17 +0000852
853 // Otherwise, signal that we at least have cleanups.
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700854 } else if (hasCleanup) {
855 LPadInst->setCleanup(true);
John McCallf1549f62010-07-06 01:34:17 +0000856 }
857
Bill Wendling285cfd82011-09-19 20:31:14 +0000858 assert((LPadInst->getNumClauses() > 0 || LPadInst->isCleanup()) &&
859 "landingpad instruction has no clauses!");
John McCallf1549f62010-07-06 01:34:17 +0000860
861 // Tell the backend how to generate the landing pad.
John McCall777d6e52011-08-11 02:22:43 +0000862 Builder.CreateBr(getEHDispatchBlock(EHStack.getInnermostEHScope()));
John McCallf1549f62010-07-06 01:34:17 +0000863
864 // Restore the old IR generation state.
John McCall777d6e52011-08-11 02:22:43 +0000865 Builder.restoreIP(savedIP);
John McCallf1549f62010-07-06 01:34:17 +0000866
John McCall777d6e52011-08-11 02:22:43 +0000867 return lpad;
John McCallf1549f62010-07-06 01:34:17 +0000868}
869
John McCall8e3f8612010-07-13 22:12:14 +0000870namespace {
871 /// A cleanup to call __cxa_end_catch. In many cases, the caught
872 /// exception type lets us state definitively that the thrown exception
873 /// type does not have a destructor. In particular:
874 /// - Catch-alls tell us nothing, so we have to conservatively
875 /// assume that the thrown exception might have a destructor.
876 /// - Catches by reference behave according to their base types.
877 /// - Catches of non-record types will only trigger for exceptions
878 /// of non-record types, which never have destructors.
879 /// - Catches of record types can trigger for arbitrary subclasses
880 /// of the caught type, so we have to assume the actual thrown
881 /// exception type might have a throwing destructor, even if the
882 /// caught type's destructor is trivial or nothrow.
John McCall1f0fca52010-07-21 07:22:38 +0000883 struct CallEndCatch : EHScopeStack::Cleanup {
John McCall8e3f8612010-07-13 22:12:14 +0000884 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
885 bool MightThrow;
886
Stephen Hines651f13c2014-04-23 16:59:28 -0700887 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall8e3f8612010-07-13 22:12:14 +0000888 if (!MightThrow) {
John McCallbd7370a2013-02-28 19:01:20 +0000889 CGF.EmitNounwindRuntimeCall(getEndCatchFn(CGF.CGM));
John McCall8e3f8612010-07-13 22:12:14 +0000890 return;
891 }
892
John McCallbd7370a2013-02-28 19:01:20 +0000893 CGF.EmitRuntimeCallOrInvoke(getEndCatchFn(CGF.CGM));
John McCall8e3f8612010-07-13 22:12:14 +0000894 }
895 };
896}
897
John McCallf1549f62010-07-06 01:34:17 +0000898/// Emits a call to __cxa_begin_catch and enters a cleanup to call
899/// __cxa_end_catch.
John McCall8e3f8612010-07-13 22:12:14 +0000900///
901/// \param EndMightThrow - true if __cxa_end_catch might throw
902static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
903 llvm::Value *Exn,
904 bool EndMightThrow) {
John McCallbd7370a2013-02-28 19:01:20 +0000905 llvm::CallInst *call =
906 CGF.EmitNounwindRuntimeCall(getBeginCatchFn(CGF.CGM), Exn);
John McCallf1549f62010-07-06 01:34:17 +0000907
John McCall1f0fca52010-07-21 07:22:38 +0000908 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
John McCallf1549f62010-07-06 01:34:17 +0000909
John McCallbd7370a2013-02-28 19:01:20 +0000910 return call;
John McCallf1549f62010-07-06 01:34:17 +0000911}
912
913/// A "special initializer" callback for initializing a catch
914/// parameter during catch initialization.
915static void InitCatchParam(CodeGenFunction &CGF,
916 const VarDecl &CatchParam,
Nick Lewycky4ee7dc22013-10-02 02:29:49 +0000917 llvm::Value *ParamAddr,
918 SourceLocation Loc) {
John McCallf1549f62010-07-06 01:34:17 +0000919 // Load the exception from where the landing pad saved it.
Bill Wendlingae270592011-09-15 18:57:19 +0000920 llvm::Value *Exn = CGF.getExceptionFromSlot();
John McCallf1549f62010-07-06 01:34:17 +0000921
922 CanQualType CatchType =
923 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
Chris Lattner2acc6e32011-07-18 04:24:23 +0000924 llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
John McCallf1549f62010-07-06 01:34:17 +0000925
926 // If we're catching by reference, we can just cast the object
927 // pointer to the appropriate pointer.
928 if (isa<ReferenceType>(CatchType)) {
John McCall204b0752010-07-20 22:17:55 +0000929 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
930 bool EndCatchMightThrow = CaughtType->isRecordType();
John McCall8e3f8612010-07-13 22:12:14 +0000931
John McCallf1549f62010-07-06 01:34:17 +0000932 // __cxa_begin_catch returns the adjusted object pointer.
John McCall8e3f8612010-07-13 22:12:14 +0000933 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
John McCall204b0752010-07-20 22:17:55 +0000934
935 // We have no way to tell the personality function that we're
936 // catching by reference, so if we're catching a pointer,
937 // __cxa_begin_catch will actually return that pointer by value.
938 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
939 QualType PointeeType = PT->getPointeeType();
940
941 // When catching by reference, generally we should just ignore
942 // this by-value pointer and use the exception object instead.
943 if (!PointeeType->isRecordType()) {
944
945 // Exn points to the struct _Unwind_Exception header, which
946 // we have to skip past in order to reach the exception data.
947 unsigned HeaderSize =
948 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
949 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
950
951 // However, if we're catching a pointer-to-record type that won't
952 // work, because the personality function might have adjusted
953 // the pointer. There's actually no way for us to fully satisfy
954 // the language/ABI contract here: we can't use Exn because it
955 // might have the wrong adjustment, but we can't use the by-value
956 // pointer because it's off by a level of abstraction.
957 //
958 // The current solution is to dump the adjusted pointer into an
959 // alloca, which breaks language semantics (because changing the
960 // pointer doesn't change the exception) but at least works.
961 // The better solution would be to filter out non-exact matches
962 // and rethrow them, but this is tricky because the rethrow
963 // really needs to be catchable by other sites at this landing
964 // pad. The best solution is to fix the personality function.
965 } else {
966 // Pull the pointer for the reference type off.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000967 llvm::Type *PtrTy =
John McCall204b0752010-07-20 22:17:55 +0000968 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
969
970 // Create the temporary and write the adjusted pointer into it.
971 llvm::Value *ExnPtrTmp = CGF.CreateTempAlloca(PtrTy, "exn.byref.tmp");
972 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
973 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
974
975 // Bind the reference to the temporary.
976 AdjustedExn = ExnPtrTmp;
977 }
978 }
979
John McCallf1549f62010-07-06 01:34:17 +0000980 llvm::Value *ExnCast =
981 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
982 CGF.Builder.CreateStore(ExnCast, ParamAddr);
983 return;
984 }
985
John McCall9d232c82013-03-07 21:37:08 +0000986 // Scalars and complexes.
987 TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType);
988 if (TEK != TEK_Aggregate) {
John McCall8e3f8612010-07-13 22:12:14 +0000989 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
John McCallf1549f62010-07-06 01:34:17 +0000990
991 // If the catch type is a pointer type, __cxa_begin_catch returns
992 // the pointer by value.
993 if (CatchType->hasPointerRepresentation()) {
994 llvm::Value *CastExn =
995 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
John McCallb29b12d2012-01-17 20:16:56 +0000996
997 switch (CatchType.getQualifiers().getObjCLifetime()) {
998 case Qualifiers::OCL_Strong:
999 CastExn = CGF.EmitARCRetainNonBlock(CastExn);
1000 // fallthrough
1001
1002 case Qualifiers::OCL_None:
1003 case Qualifiers::OCL_ExplicitNone:
1004 case Qualifiers::OCL_Autoreleasing:
1005 CGF.Builder.CreateStore(CastExn, ParamAddr);
1006 return;
1007
1008 case Qualifiers::OCL_Weak:
1009 CGF.EmitARCInitWeak(ParamAddr, CastExn);
1010 return;
1011 }
1012 llvm_unreachable("bad ownership qualifier!");
John McCallf1549f62010-07-06 01:34:17 +00001013 }
1014
1015 // Otherwise, it returns a pointer into the exception object.
1016
Chris Lattner2acc6e32011-07-18 04:24:23 +00001017 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
John McCallf1549f62010-07-06 01:34:17 +00001018 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1019
John McCall9d232c82013-03-07 21:37:08 +00001020 LValue srcLV = CGF.MakeNaturalAlignAddrLValue(Cast, CatchType);
1021 LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType,
1022 CGF.getContext().getDeclAlign(&CatchParam));
1023 switch (TEK) {
1024 case TEK_Complex:
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00001025 CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV,
John McCall9d232c82013-03-07 21:37:08 +00001026 /*init*/ true);
1027 return;
1028 case TEK_Scalar: {
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00001029 llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc);
John McCall9d232c82013-03-07 21:37:08 +00001030 CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true);
1031 return;
John McCallf1549f62010-07-06 01:34:17 +00001032 }
John McCall9d232c82013-03-07 21:37:08 +00001033 case TEK_Aggregate:
1034 llvm_unreachable("evaluation kind filtered out!");
1035 }
1036 llvm_unreachable("bad evaluation kind");
John McCallf1549f62010-07-06 01:34:17 +00001037 }
1038
John McCallacff6962011-02-16 08:39:19 +00001039 assert(isa<RecordType>(CatchType) && "unexpected catch type!");
John McCallf1549f62010-07-06 01:34:17 +00001040
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
John McCallacff6962011-02-16 08:39:19 +00001043 // Check for a copy expression. If we don't have a copy expression,
1044 // that means a trivial copy is okay.
John McCalle996ffd2011-02-16 08:02:54 +00001045 const Expr *copyExpr = CatchParam.getInit();
1046 if (!copyExpr) {
John McCallacff6962011-02-16 08:39:19 +00001047 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
1048 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
Chad Rosier649b4a12012-03-29 17:37:10 +00001049 CGF.EmitAggregateCopy(ParamAddr, adjustedExn, CatchType);
John McCallf1549f62010-07-06 01:34:17 +00001050 return;
1051 }
1052
1053 // We have to call __cxa_get_exception_ptr to get the adjusted
1054 // pointer before copying.
John McCalle996ffd2011-02-16 08:02:54 +00001055 llvm::CallInst *rawAdjustedExn =
John McCallbd7370a2013-02-28 19:01:20 +00001056 CGF.EmitNounwindRuntimeCall(getGetExceptionPtrFn(CGF.CGM), Exn);
John McCallf1549f62010-07-06 01:34:17 +00001057
John McCalle996ffd2011-02-16 08:02:54 +00001058 // Cast that to the appropriate type.
1059 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
John McCallf1549f62010-07-06 01:34:17 +00001060
John McCalle996ffd2011-02-16 08:02:54 +00001061 // The copy expression is defined in terms of an OpaqueValueExpr.
1062 // Find it and map it to the adjusted expression.
1063 CodeGenFunction::OpaqueValueMapping
John McCall56ca35d2011-02-17 10:25:35 +00001064 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
1065 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
John McCallf1549f62010-07-06 01:34:17 +00001066
1067 // Call the copy ctor in a terminate scope.
1068 CGF.EHStack.pushTerminate();
John McCalle996ffd2011-02-16 08:02:54 +00001069
1070 // Perform the copy construction.
Eli Friedmand7722d92011-12-03 02:13:40 +00001071 CharUnits Alignment = CGF.getContext().getDeclAlign(&CatchParam);
Eli Friedmanf3940782011-12-03 00:54:26 +00001072 CGF.EmitAggExpr(copyExpr,
1073 AggValueSlot::forAddr(ParamAddr, Alignment, Qualifiers(),
1074 AggValueSlot::IsNotDestructed,
1075 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +00001076 AggValueSlot::IsNotAliased));
John McCalle996ffd2011-02-16 08:02:54 +00001077
1078 // Leave the terminate scope.
John McCallf1549f62010-07-06 01:34:17 +00001079 CGF.EHStack.popTerminate();
1080
John McCalle996ffd2011-02-16 08:02:54 +00001081 // Undo the opaque value mapping.
1082 opaque.pop();
1083
John McCallf1549f62010-07-06 01:34:17 +00001084 // Finally we can call __cxa_begin_catch.
John McCall8e3f8612010-07-13 22:12:14 +00001085 CallBeginCatch(CGF, Exn, true);
John McCallf1549f62010-07-06 01:34:17 +00001086}
1087
1088/// Begins a catch statement by initializing the catch variable and
1089/// calling __cxa_begin_catch.
John McCalle996ffd2011-02-16 08:02:54 +00001090static void BeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *S) {
John McCallf1549f62010-07-06 01:34:17 +00001091 // We have to be very careful with the ordering of cleanups here:
1092 // C++ [except.throw]p4:
1093 // The destruction [of the exception temporary] occurs
1094 // immediately after the destruction of the object declared in
1095 // the exception-declaration in the handler.
1096 //
1097 // So the precise ordering is:
1098 // 1. Construct catch variable.
1099 // 2. __cxa_begin_catch
1100 // 3. Enter __cxa_end_catch cleanup
1101 // 4. Enter dtor cleanup
1102 //
John McCall34695852011-02-22 06:44:22 +00001103 // We do this by using a slightly abnormal initialization process.
1104 // Delegation sequence:
John McCallf1549f62010-07-06 01:34:17 +00001105 // - ExitCXXTryStmt opens a RunCleanupsScope
John McCall34695852011-02-22 06:44:22 +00001106 // - EmitAutoVarAlloca creates the variable and debug info
John McCallf1549f62010-07-06 01:34:17 +00001107 // - InitCatchParam initializes the variable from the exception
John McCall34695852011-02-22 06:44:22 +00001108 // - CallBeginCatch calls __cxa_begin_catch
1109 // - CallBeginCatch enters the __cxa_end_catch cleanup
1110 // - EmitAutoVarCleanups enters the variable destructor cleanup
John McCallf1549f62010-07-06 01:34:17 +00001111 // - EmitCXXTryStmt emits the code for the catch body
1112 // - EmitCXXTryStmt close the RunCleanupsScope
1113
1114 VarDecl *CatchParam = S->getExceptionDecl();
1115 if (!CatchParam) {
Bill Wendlingae270592011-09-15 18:57:19 +00001116 llvm::Value *Exn = CGF.getExceptionFromSlot();
John McCall8e3f8612010-07-13 22:12:14 +00001117 CallBeginCatch(CGF, Exn, true);
John McCallf1549f62010-07-06 01:34:17 +00001118 return;
1119 }
1120
1121 // Emit the local.
John McCall34695852011-02-22 06:44:22 +00001122 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00001123 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF), S->getLocStart());
John McCall34695852011-02-22 06:44:22 +00001124 CGF.EmitAutoVarCleanups(var);
John McCall9fc6a772010-02-19 09:25:03 +00001125}
1126
John McCall777d6e52011-08-11 02:22:43 +00001127/// Emit the structure of the dispatch block for the given catch scope.
1128/// It is an invariant that the dispatch block already exists.
1129static void emitCatchDispatchBlock(CodeGenFunction &CGF,
1130 EHCatchScope &catchScope) {
1131 llvm::BasicBlock *dispatchBlock = catchScope.getCachedEHDispatchBlock();
1132 assert(dispatchBlock);
1133
1134 // If there's only a single catch-all, getEHDispatchBlock returned
1135 // that catch-all as the dispatch block.
1136 if (catchScope.getNumHandlers() == 1 &&
1137 catchScope.getHandler(0).isCatchAll()) {
1138 assert(dispatchBlock == catchScope.getHandler(0).Block);
1139 return;
1140 }
1141
1142 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveIP();
1143 CGF.EmitBlockAfterUses(dispatchBlock);
1144
1145 // Select the right handler.
1146 llvm::Value *llvm_eh_typeid_for =
1147 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
1148
1149 // Load the selector value.
Bill Wendlingae270592011-09-15 18:57:19 +00001150 llvm::Value *selector = CGF.getSelectorFromSlot();
John McCall777d6e52011-08-11 02:22:43 +00001151
1152 // Test against each of the exception types we claim to catch.
1153 for (unsigned i = 0, e = catchScope.getNumHandlers(); ; ++i) {
1154 assert(i < e && "ran off end of handlers!");
1155 const EHCatchScope::Handler &handler = catchScope.getHandler(i);
1156
1157 llvm::Value *typeValue = handler.Type;
1158 assert(typeValue && "fell into catch-all case!");
1159 typeValue = CGF.Builder.CreateBitCast(typeValue, CGF.Int8PtrTy);
1160
1161 // Figure out the next block.
1162 bool nextIsEnd;
1163 llvm::BasicBlock *nextBlock;
1164
1165 // If this is the last handler, we're at the end, and the next
1166 // block is the block for the enclosing EH scope.
1167 if (i + 1 == e) {
1168 nextBlock = CGF.getEHDispatchBlock(catchScope.getEnclosingEHScope());
1169 nextIsEnd = true;
1170
1171 // If the next handler is a catch-all, we're at the end, and the
1172 // next block is that handler.
1173 } else if (catchScope.getHandler(i+1).isCatchAll()) {
1174 nextBlock = catchScope.getHandler(i+1).Block;
1175 nextIsEnd = true;
1176
1177 // Otherwise, we're not at the end and we need a new block.
1178 } else {
1179 nextBlock = CGF.createBasicBlock("catch.fallthrough");
1180 nextIsEnd = false;
1181 }
1182
1183 // Figure out the catch type's index in the LSDA's type table.
1184 llvm::CallInst *typeIndex =
1185 CGF.Builder.CreateCall(llvm_eh_typeid_for, typeValue);
1186 typeIndex->setDoesNotThrow();
1187
1188 llvm::Value *matchesTypeIndex =
1189 CGF.Builder.CreateICmpEQ(selector, typeIndex, "matches");
1190 CGF.Builder.CreateCondBr(matchesTypeIndex, handler.Block, nextBlock);
1191
1192 // If the next handler is a catch-all, we're completely done.
1193 if (nextIsEnd) {
1194 CGF.Builder.restoreIP(savedIP);
1195 return;
John McCall777d6e52011-08-11 02:22:43 +00001196 }
Ahmed Charlese8e92b92012-02-19 11:57:29 +00001197 // Otherwise we need to emit and continue at that block.
1198 CGF.EmitBlock(nextBlock);
John McCall777d6e52011-08-11 02:22:43 +00001199 }
John McCall777d6e52011-08-11 02:22:43 +00001200}
1201
1202void CodeGenFunction::popCatchScope() {
1203 EHCatchScope &catchScope = cast<EHCatchScope>(*EHStack.begin());
1204 if (catchScope.hasEHBranches())
1205 emitCatchDispatchBlock(*this, catchScope);
1206 EHStack.popCatch();
1207}
1208
John McCall59a70002010-07-07 06:56:46 +00001209void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallf1549f62010-07-06 01:34:17 +00001210 unsigned NumHandlers = S.getNumHandlers();
1211 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1212 assert(CatchScope.getNumHandlers() == NumHandlers);
Mike Stump2bf701e2009-11-20 23:44:51 +00001213
John McCall777d6e52011-08-11 02:22:43 +00001214 // If the catch was not required, bail out now.
1215 if (!CatchScope.hasEHBranches()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001216 CatchScope.clearHandlerBlocks();
John McCall777d6e52011-08-11 02:22:43 +00001217 EHStack.popCatch();
1218 return;
1219 }
1220
1221 // Emit the structure of the EH dispatch for this catch.
1222 emitCatchDispatchBlock(*this, CatchScope);
1223
John McCallf1549f62010-07-06 01:34:17 +00001224 // Copy the handler blocks off before we pop the EH stack. Emitting
1225 // the handlers might scribble on this memory.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001226 SmallVector<EHCatchScope::Handler, 8> Handlers(NumHandlers);
John McCallf1549f62010-07-06 01:34:17 +00001227 memcpy(Handlers.data(), CatchScope.begin(),
1228 NumHandlers * sizeof(EHCatchScope::Handler));
John McCall777d6e52011-08-11 02:22:43 +00001229
John McCallf1549f62010-07-06 01:34:17 +00001230 EHStack.popCatch();
Mike Stump2bf701e2009-11-20 23:44:51 +00001231
John McCallf1549f62010-07-06 01:34:17 +00001232 // The fall-through block.
1233 llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
Mike Stump2bf701e2009-11-20 23:44:51 +00001234
John McCallf1549f62010-07-06 01:34:17 +00001235 // We just emitted the body of the try; jump to the continue block.
1236 if (HaveInsertPoint())
1237 Builder.CreateBr(ContBB);
Mike Stump639787c2009-12-02 19:53:57 +00001238
John McCallf5533012012-06-15 05:27:05 +00001239 // Determine if we need an implicit rethrow for all these catch handlers;
1240 // see the comment below.
1241 bool doImplicitRethrow = false;
John McCall59a70002010-07-07 06:56:46 +00001242 if (IsFnTryBlock)
John McCallf5533012012-06-15 05:27:05 +00001243 doImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
1244 isa<CXXConstructorDecl>(CurCodeDecl);
John McCall59a70002010-07-07 06:56:46 +00001245
John McCall777d6e52011-08-11 02:22:43 +00001246 // Perversely, we emit the handlers backwards precisely because we
1247 // want them to appear in source order. In all of these cases, the
1248 // catch block will have exactly one predecessor, which will be a
1249 // particular block in the catch dispatch. However, in the case of
1250 // a catch-all, one of the dispatch blocks will branch to two
1251 // different handlers, and EmitBlockAfterUses will cause the second
1252 // handler to be moved before the first.
1253 for (unsigned I = NumHandlers; I != 0; --I) {
1254 llvm::BasicBlock *CatchBlock = Handlers[I-1].Block;
1255 EmitBlockAfterUses(CatchBlock);
Mike Stump8755ec32009-12-10 00:06:18 +00001256
John McCallf1549f62010-07-06 01:34:17 +00001257 // Catch the exception if this isn't a catch-all.
John McCall777d6e52011-08-11 02:22:43 +00001258 const CXXCatchStmt *C = S.getHandler(I-1);
Mike Stump2bf701e2009-11-20 23:44:51 +00001259
John McCallf1549f62010-07-06 01:34:17 +00001260 // Enter a cleanup scope, including the catch variable and the
1261 // end-catch.
1262 RunCleanupsScope CatchScope(*this);
Mike Stump2bf701e2009-11-20 23:44:51 +00001263
John McCallf1549f62010-07-06 01:34:17 +00001264 // Initialize the catch variable and set up the cleanups.
1265 BeginCatch(*this, C);
1266
Stephen Hines651f13c2014-04-23 16:59:28 -07001267 // Emit the PGO counter increment.
1268 RegionCounter CatchCnt = getPGORegionCounter(C);
1269 CatchCnt.beginRegion(Builder);
1270
John McCallf1549f62010-07-06 01:34:17 +00001271 // Perform the body of the catch.
1272 EmitStmt(C->getHandlerBlock());
1273
John McCallf5533012012-06-15 05:27:05 +00001274 // [except.handle]p11:
1275 // The currently handled exception is rethrown if control
1276 // reaches the end of a handler of the function-try-block of a
1277 // constructor or destructor.
1278
1279 // It is important that we only do this on fallthrough and not on
1280 // return. Note that it's illegal to put a return in a
1281 // constructor function-try-block's catch handler (p14), so this
1282 // really only applies to destructors.
1283 if (doImplicitRethrow && HaveInsertPoint()) {
John McCallbd7370a2013-02-28 19:01:20 +00001284 EmitRuntimeCallOrInvoke(getReThrowFn(CGM));
John McCallf5533012012-06-15 05:27:05 +00001285 Builder.CreateUnreachable();
1286 Builder.ClearInsertionPoint();
1287 }
1288
John McCallf1549f62010-07-06 01:34:17 +00001289 // Fall out through the catch cleanups.
1290 CatchScope.ForceCleanup();
1291
1292 // Branch out of the try.
1293 if (HaveInsertPoint())
1294 Builder.CreateBr(ContBB);
Mike Stump2bf701e2009-11-20 23:44:51 +00001295 }
1296
Stephen Hines651f13c2014-04-23 16:59:28 -07001297 RegionCounter ContCnt = getPGORegionCounter(&S);
John McCallf1549f62010-07-06 01:34:17 +00001298 EmitBlock(ContBB);
Stephen Hines651f13c2014-04-23 16:59:28 -07001299 ContCnt.beginRegion(Builder);
Mike Stump2bf701e2009-11-20 23:44:51 +00001300}
Mike Stumpd88ea562009-12-09 03:35:49 +00001301
John McCall55b20fc2010-07-21 00:52:03 +00001302namespace {
John McCall1f0fca52010-07-21 07:22:38 +00001303 struct CallEndCatchForFinally : EHScopeStack::Cleanup {
John McCall55b20fc2010-07-21 00:52:03 +00001304 llvm::Value *ForEHVar;
1305 llvm::Value *EndCatchFn;
1306 CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn)
1307 : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
1308
Stephen Hines651f13c2014-04-23 16:59:28 -07001309 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall55b20fc2010-07-21 00:52:03 +00001310 llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
1311 llvm::BasicBlock *CleanupContBB =
1312 CGF.createBasicBlock("finally.cleanup.cont");
1313
1314 llvm::Value *ShouldEndCatch =
1315 CGF.Builder.CreateLoad(ForEHVar, "finally.endcatch");
1316 CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1317 CGF.EmitBlock(EndCatchBB);
John McCallbd7370a2013-02-28 19:01:20 +00001318 CGF.EmitRuntimeCallOrInvoke(EndCatchFn); // catch-all, so might throw
John McCall55b20fc2010-07-21 00:52:03 +00001319 CGF.EmitBlock(CleanupContBB);
1320 }
1321 };
John McCall77199712010-07-21 05:47:49 +00001322
John McCall1f0fca52010-07-21 07:22:38 +00001323 struct PerformFinally : EHScopeStack::Cleanup {
John McCall77199712010-07-21 05:47:49 +00001324 const Stmt *Body;
1325 llvm::Value *ForEHVar;
1326 llvm::Value *EndCatchFn;
1327 llvm::Value *RethrowFn;
1328 llvm::Value *SavedExnVar;
1329
1330 PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
1331 llvm::Value *EndCatchFn,
1332 llvm::Value *RethrowFn, llvm::Value *SavedExnVar)
1333 : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1334 RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
1335
Stephen Hines651f13c2014-04-23 16:59:28 -07001336 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall77199712010-07-21 05:47:49 +00001337 // Enter a cleanup to call the end-catch function if one was provided.
1338 if (EndCatchFn)
John McCall1f0fca52010-07-21 07:22:38 +00001339 CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
1340 ForEHVar, EndCatchFn);
John McCall77199712010-07-21 05:47:49 +00001341
John McCalld96a8e72010-08-11 00:16:14 +00001342 // Save the current cleanup destination in case there are
1343 // cleanups in the finally block.
1344 llvm::Value *SavedCleanupDest =
1345 CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
1346 "cleanup.dest.saved");
1347
John McCall77199712010-07-21 05:47:49 +00001348 // Emit the finally block.
1349 CGF.EmitStmt(Body);
1350
1351 // If the end of the finally is reachable, check whether this was
1352 // for EH. If so, rethrow.
1353 if (CGF.HaveInsertPoint()) {
1354 llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
1355 llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
1356
1357 llvm::Value *ShouldRethrow =
1358 CGF.Builder.CreateLoad(ForEHVar, "finally.shouldthrow");
1359 CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1360
1361 CGF.EmitBlock(RethrowBB);
1362 if (SavedExnVar) {
John McCallbd7370a2013-02-28 19:01:20 +00001363 CGF.EmitRuntimeCallOrInvoke(RethrowFn,
1364 CGF.Builder.CreateLoad(SavedExnVar));
John McCall77199712010-07-21 05:47:49 +00001365 } else {
John McCallbd7370a2013-02-28 19:01:20 +00001366 CGF.EmitRuntimeCallOrInvoke(RethrowFn);
John McCall77199712010-07-21 05:47:49 +00001367 }
1368 CGF.Builder.CreateUnreachable();
1369
1370 CGF.EmitBlock(ContBB);
John McCalld96a8e72010-08-11 00:16:14 +00001371
1372 // Restore the cleanup destination.
1373 CGF.Builder.CreateStore(SavedCleanupDest,
1374 CGF.getNormalCleanupDestSlot());
John McCall77199712010-07-21 05:47:49 +00001375 }
1376
1377 // Leave the end-catch cleanup. As an optimization, pretend that
1378 // the fallthrough path was inaccessible; we've dynamically proven
1379 // that we're not in the EH case along that path.
1380 if (EndCatchFn) {
1381 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1382 CGF.PopCleanupBlock();
1383 CGF.Builder.restoreIP(SavedIP);
1384 }
1385
1386 // Now make sure we actually have an insertion point or the
1387 // cleanup gods will hate us.
1388 CGF.EnsureInsertPoint();
1389 }
1390 };
John McCall55b20fc2010-07-21 00:52:03 +00001391}
1392
John McCallf1549f62010-07-06 01:34:17 +00001393/// Enters a finally block for an implementation using zero-cost
1394/// exceptions. This is mostly general, but hard-codes some
1395/// language/ABI-specific behavior in the catch-all sections.
John McCalld768e9d2011-06-22 02:32:12 +00001396void CodeGenFunction::FinallyInfo::enter(CodeGenFunction &CGF,
1397 const Stmt *body,
1398 llvm::Constant *beginCatchFn,
1399 llvm::Constant *endCatchFn,
1400 llvm::Constant *rethrowFn) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001401 assert((beginCatchFn != nullptr) == (endCatchFn != nullptr) &&
John McCallf1549f62010-07-06 01:34:17 +00001402 "begin/end catch functions not paired");
John McCalld768e9d2011-06-22 02:32:12 +00001403 assert(rethrowFn && "rethrow function is required");
1404
1405 BeginCatchFn = beginCatchFn;
Mike Stumpd88ea562009-12-09 03:35:49 +00001406
John McCallf1549f62010-07-06 01:34:17 +00001407 // The rethrow function has one of the following two types:
1408 // void (*)()
1409 // void (*)(void*)
1410 // In the latter case we need to pass it the exception object.
1411 // But we can't use the exception slot because the @finally might
1412 // have a landing pad (which would overwrite the exception slot).
Chris Lattner2acc6e32011-07-18 04:24:23 +00001413 llvm::FunctionType *rethrowFnTy =
John McCallf1549f62010-07-06 01:34:17 +00001414 cast<llvm::FunctionType>(
John McCalld768e9d2011-06-22 02:32:12 +00001415 cast<llvm::PointerType>(rethrowFn->getType())->getElementType());
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001416 SavedExnVar = nullptr;
John McCalld768e9d2011-06-22 02:32:12 +00001417 if (rethrowFnTy->getNumParams())
1418 SavedExnVar = CGF.CreateTempAlloca(CGF.Int8PtrTy, "finally.exn");
Mike Stumpd88ea562009-12-09 03:35:49 +00001419
John McCallf1549f62010-07-06 01:34:17 +00001420 // A finally block is a statement which must be executed on any edge
1421 // out of a given scope. Unlike a cleanup, the finally block may
1422 // contain arbitrary control flow leading out of itself. In
1423 // addition, finally blocks should always be executed, even if there
1424 // are no catch handlers higher on the stack. Therefore, we
1425 // surround the protected scope with a combination of a normal
1426 // cleanup (to catch attempts to break out of the block via normal
1427 // control flow) and an EH catch-all (semantically "outside" any try
1428 // statement to which the finally block might have been attached).
1429 // The finally block itself is generated in the context of a cleanup
1430 // which conditionally leaves the catch-all.
John McCall3d3ec1c2010-04-21 10:05:39 +00001431
John McCallf1549f62010-07-06 01:34:17 +00001432 // Jump destination for performing the finally block on an exception
1433 // edge. We'll never actually reach this block, so unreachable is
1434 // fine.
John McCalld768e9d2011-06-22 02:32:12 +00001435 RethrowDest = CGF.getJumpDestInCurrentScope(CGF.getUnreachableBlock());
John McCall3d3ec1c2010-04-21 10:05:39 +00001436
John McCallf1549f62010-07-06 01:34:17 +00001437 // Whether the finally block is being executed for EH purposes.
John McCalld768e9d2011-06-22 02:32:12 +00001438 ForEHVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "finally.for-eh");
1439 CGF.Builder.CreateStore(CGF.Builder.getFalse(), ForEHVar);
Mike Stumpd88ea562009-12-09 03:35:49 +00001440
John McCallf1549f62010-07-06 01:34:17 +00001441 // Enter a normal cleanup which will perform the @finally block.
John McCalld768e9d2011-06-22 02:32:12 +00001442 CGF.EHStack.pushCleanup<PerformFinally>(NormalCleanup, body,
1443 ForEHVar, endCatchFn,
1444 rethrowFn, SavedExnVar);
John McCallf1549f62010-07-06 01:34:17 +00001445
1446 // Enter a catch-all scope.
John McCalld768e9d2011-06-22 02:32:12 +00001447 llvm::BasicBlock *catchBB = CGF.createBasicBlock("finally.catchall");
1448 EHCatchScope *catchScope = CGF.EHStack.pushCatch(1);
1449 catchScope->setCatchAllHandler(0, catchBB);
John McCallf1549f62010-07-06 01:34:17 +00001450}
1451
John McCalld768e9d2011-06-22 02:32:12 +00001452void CodeGenFunction::FinallyInfo::exit(CodeGenFunction &CGF) {
John McCallf1549f62010-07-06 01:34:17 +00001453 // Leave the finally catch-all.
John McCalld768e9d2011-06-22 02:32:12 +00001454 EHCatchScope &catchScope = cast<EHCatchScope>(*CGF.EHStack.begin());
1455 llvm::BasicBlock *catchBB = catchScope.getHandler(0).Block;
John McCall777d6e52011-08-11 02:22:43 +00001456
1457 CGF.popCatchScope();
John McCallf1549f62010-07-06 01:34:17 +00001458
John McCalld768e9d2011-06-22 02:32:12 +00001459 // If there are any references to the catch-all block, emit it.
1460 if (catchBB->use_empty()) {
1461 delete catchBB;
1462 } else {
1463 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveAndClearIP();
1464 CGF.EmitBlock(catchBB);
John McCallf1549f62010-07-06 01:34:17 +00001465
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001466 llvm::Value *exn = nullptr;
John McCallf1549f62010-07-06 01:34:17 +00001467
John McCalld768e9d2011-06-22 02:32:12 +00001468 // If there's a begin-catch function, call it.
1469 if (BeginCatchFn) {
Bill Wendlingae270592011-09-15 18:57:19 +00001470 exn = CGF.getExceptionFromSlot();
John McCallbd7370a2013-02-28 19:01:20 +00001471 CGF.EmitNounwindRuntimeCall(BeginCatchFn, exn);
John McCalld768e9d2011-06-22 02:32:12 +00001472 }
1473
1474 // If we need to remember the exception pointer to rethrow later, do so.
1475 if (SavedExnVar) {
Bill Wendlingae270592011-09-15 18:57:19 +00001476 if (!exn) exn = CGF.getExceptionFromSlot();
John McCalld768e9d2011-06-22 02:32:12 +00001477 CGF.Builder.CreateStore(exn, SavedExnVar);
1478 }
1479
1480 // Tell the cleanups in the finally block that we're do this for EH.
1481 CGF.Builder.CreateStore(CGF.Builder.getTrue(), ForEHVar);
1482
1483 // Thread a jump through the finally cleanup.
1484 CGF.EmitBranchThroughCleanup(RethrowDest);
1485
1486 CGF.Builder.restoreIP(savedIP);
1487 }
1488
1489 // Finally, leave the @finally cleanup.
1490 CGF.PopCleanupBlock();
John McCallf1549f62010-07-06 01:34:17 +00001491}
1492
John McCall66b22772013-02-12 03:51:46 +00001493/// In a terminate landing pad, should we use __clang__call_terminate
1494/// or just a naked call to std::terminate?
1495///
1496/// __clang_call_terminate calls __cxa_begin_catch, which then allows
1497/// std::terminate to usefully report something about the
1498/// violating exception.
1499static bool useClangCallTerminate(CodeGenModule &CGM) {
1500 // Only do this for Itanium-family ABIs in C++ mode.
1501 return (CGM.getLangOpts().CPlusPlus &&
1502 CGM.getTarget().getCXXABI().isItaniumFamily());
1503}
1504
1505/// Get or define the following function:
1506/// void @__clang_call_terminate(i8* %exn) nounwind noreturn
1507/// This code is used only in C++.
1508static llvm::Constant *getClangCallTerminateFn(CodeGenModule &CGM) {
1509 llvm::FunctionType *fnTy =
1510 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
1511 llvm::Constant *fnRef =
1512 CGM.CreateRuntimeFunction(fnTy, "__clang_call_terminate");
1513
1514 llvm::Function *fn = dyn_cast<llvm::Function>(fnRef);
1515 if (fn && fn->empty()) {
1516 fn->setDoesNotThrow();
1517 fn->setDoesNotReturn();
1518
1519 // What we really want is to massively penalize inlining without
1520 // forbidding it completely. The difference between that and
1521 // 'noinline' is negligible.
1522 fn->addFnAttr(llvm::Attribute::NoInline);
1523
1524 // Allow this function to be shared across translation units, but
1525 // we don't want it to turn into an exported symbol.
1526 fn->setLinkage(llvm::Function::LinkOnceODRLinkage);
1527 fn->setVisibility(llvm::Function::HiddenVisibility);
1528
1529 // Set up the function.
1530 llvm::BasicBlock *entry =
1531 llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn);
1532 CGBuilderTy builder(entry);
1533
1534 // Pull the exception pointer out of the parameter list.
1535 llvm::Value *exn = &*fn->arg_begin();
1536
1537 // Call __cxa_begin_catch(exn).
John McCallbd7370a2013-02-28 19:01:20 +00001538 llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn);
1539 catchCall->setDoesNotThrow();
1540 catchCall->setCallingConv(CGM.getRuntimeCC());
John McCall66b22772013-02-12 03:51:46 +00001541
1542 // Call std::terminate().
1543 llvm::CallInst *termCall = builder.CreateCall(getTerminateFn(CGM));
1544 termCall->setDoesNotThrow();
1545 termCall->setDoesNotReturn();
John McCallbd7370a2013-02-28 19:01:20 +00001546 termCall->setCallingConv(CGM.getRuntimeCC());
John McCall66b22772013-02-12 03:51:46 +00001547
1548 // std::terminate cannot return.
1549 builder.CreateUnreachable();
1550 }
1551
1552 return fnRef;
1553}
1554
John McCallf1549f62010-07-06 01:34:17 +00001555llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
1556 if (TerminateLandingPad)
1557 return TerminateLandingPad;
1558
1559 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1560
1561 // This will get inserted at the end of the function.
1562 TerminateLandingPad = createBasicBlock("terminate.lpad");
1563 Builder.SetInsertPoint(TerminateLandingPad);
1564
1565 // Tell the backend that this is a landing pad.
Stephen Hines176edba2014-12-01 14:53:08 -08001566 const EHPersonality &Personality = EHPersonality::get(CGM);
Bill Wendling285cfd82011-09-19 20:31:14 +00001567 llvm::LandingPadInst *LPadInst =
1568 Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, NULL),
1569 getOpaquePersonalityFn(CGM, Personality), 0);
1570 LPadInst->addClause(getCatchAllValue(*this));
John McCallf1549f62010-07-06 01:34:17 +00001571
John McCall66b22772013-02-12 03:51:46 +00001572 llvm::CallInst *terminateCall;
1573 if (useClangCallTerminate(CGM)) {
1574 // Extract out the exception pointer.
1575 llvm::Value *exn = Builder.CreateExtractValue(LPadInst, 0);
John McCallbd7370a2013-02-28 19:01:20 +00001576 terminateCall = EmitNounwindRuntimeCall(getClangCallTerminateFn(CGM), exn);
John McCall66b22772013-02-12 03:51:46 +00001577 } else {
John McCallbd7370a2013-02-28 19:01:20 +00001578 terminateCall = EmitNounwindRuntimeCall(getTerminateFn(CGM));
John McCall66b22772013-02-12 03:51:46 +00001579 }
1580 terminateCall->setDoesNotReturn();
John McCalld16c2cf2011-02-08 08:22:06 +00001581 Builder.CreateUnreachable();
Mike Stumpd88ea562009-12-09 03:35:49 +00001582
John McCallf1549f62010-07-06 01:34:17 +00001583 // Restore the saved insertion state.
1584 Builder.restoreIP(SavedIP);
John McCall891f80e2010-04-30 00:06:43 +00001585
John McCallf1549f62010-07-06 01:34:17 +00001586 return TerminateLandingPad;
Mike Stumpd88ea562009-12-09 03:35:49 +00001587}
Mike Stump9b39c512009-12-09 22:59:31 +00001588
1589llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
Mike Stump182f3832009-12-10 00:02:42 +00001590 if (TerminateHandler)
1591 return TerminateHandler;
1592
John McCallf1549f62010-07-06 01:34:17 +00001593 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
Mike Stump76958092009-12-09 23:31:35 +00001594
John McCallf1549f62010-07-06 01:34:17 +00001595 // Set up the terminate handler. This block is inserted at the very
1596 // end of the function by FinishFunction.
Mike Stump182f3832009-12-10 00:02:42 +00001597 TerminateHandler = createBasicBlock("terminate.handler");
John McCallf1549f62010-07-06 01:34:17 +00001598 Builder.SetInsertPoint(TerminateHandler);
John McCall45ff3802013-06-20 21:37:43 +00001599 llvm::CallInst *terminateCall;
1600 if (useClangCallTerminate(CGM)) {
1601 // Load the exception pointer.
1602 llvm::Value *exn = getExceptionFromSlot();
1603 terminateCall = EmitNounwindRuntimeCall(getClangCallTerminateFn(CGM), exn);
1604 } else {
1605 terminateCall = EmitNounwindRuntimeCall(getTerminateFn(CGM));
1606 }
1607 terminateCall->setDoesNotReturn();
Mike Stump9b39c512009-12-09 22:59:31 +00001608 Builder.CreateUnreachable();
1609
John McCall3d3ec1c2010-04-21 10:05:39 +00001610 // Restore the saved insertion state.
John McCallf1549f62010-07-06 01:34:17 +00001611 Builder.restoreIP(SavedIP);
Mike Stump76958092009-12-09 23:31:35 +00001612
Mike Stump9b39c512009-12-09 22:59:31 +00001613 return TerminateHandler;
1614}
John McCallf1549f62010-07-06 01:34:17 +00001615
David Chisnallc6860042012-11-07 16:50:40 +00001616llvm::BasicBlock *CodeGenFunction::getEHResumeBlock(bool isCleanup) {
John McCall777d6e52011-08-11 02:22:43 +00001617 if (EHResumeBlock) return EHResumeBlock;
John McCallff8e1152010-07-23 21:56:41 +00001618
1619 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1620
1621 // We emit a jump to a notional label at the outermost unwind state.
John McCall777d6e52011-08-11 02:22:43 +00001622 EHResumeBlock = createBasicBlock("eh.resume");
1623 Builder.SetInsertPoint(EHResumeBlock);
John McCallff8e1152010-07-23 21:56:41 +00001624
Stephen Hines176edba2014-12-01 14:53:08 -08001625 const EHPersonality &Personality = EHPersonality::get(CGM);
John McCallff8e1152010-07-23 21:56:41 +00001626
1627 // This can always be a call because we necessarily didn't find
1628 // anything on the EH stack which needs our help.
Benjamin Krameraf2771b2012-02-08 12:41:24 +00001629 const char *RethrowName = Personality.CatchallRethrowFn;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001630 if (RethrowName != nullptr && !isCleanup) {
John McCallbd7370a2013-02-28 19:01:20 +00001631 EmitRuntimeCall(getCatchallRethrowFn(CGM, RethrowName),
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001632 getExceptionFromSlot())
John McCall93c332a2011-05-28 21:13:02 +00001633 ->setDoesNotReturn();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001634 Builder.CreateUnreachable();
1635 Builder.restoreIP(SavedIP);
1636 return EHResumeBlock;
John McCall93c332a2011-05-28 21:13:02 +00001637 }
1638
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001639 // Recreate the landingpad's return value for the 'resume' instruction.
1640 llvm::Value *Exn = getExceptionFromSlot();
1641 llvm::Value *Sel = getSelectorFromSlot();
John McCallff8e1152010-07-23 21:56:41 +00001642
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001643 llvm::Type *LPadType = llvm::StructType::get(Exn->getType(),
1644 Sel->getType(), NULL);
1645 llvm::Value *LPadVal = llvm::UndefValue::get(LPadType);
1646 LPadVal = Builder.CreateInsertValue(LPadVal, Exn, 0, "lpad.val");
1647 LPadVal = Builder.CreateInsertValue(LPadVal, Sel, 1, "lpad.val");
1648
1649 Builder.CreateResume(LPadVal);
John McCallff8e1152010-07-23 21:56:41 +00001650 Builder.restoreIP(SavedIP);
John McCall777d6e52011-08-11 02:22:43 +00001651 return EHResumeBlock;
John McCallff8e1152010-07-23 21:56:41 +00001652}
Reid Kleckner98592d92013-09-16 21:46:30 +00001653
1654void CodeGenFunction::EmitSEHTryStmt(const SEHTryStmt &S) {
1655 CGM.ErrorUnsupported(&S, "SEH __try");
1656}
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001657
1658void CodeGenFunction::EmitSEHLeaveStmt(const SEHLeaveStmt &S) {
1659 CGM.ErrorUnsupported(&S, "SEH __leave");
1660}