blob: c1e7eae405f067814c72d226cf0b4c9cf7ee1284 [file] [log] [blame]
Anders Carlsson4b08db72009-10-30 01:42:31 +00001//===--- CGException.cpp - Emit LLVM Code for C++ exceptions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code dealing with C++ exception related code generation.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
David Majnemer442d0a22014-11-25 07:20:20 +000015#include "CGCXXABI.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000016#include "CGCleanup.h"
Benjamin Kramer793bd552012-02-08 12:41:24 +000017#include "CGObjCRuntime.h"
John McCall5add20c2010-07-20 22:17:55 +000018#include "TargetInfo.h"
Reid Kleckner1d59f992015-01-22 01:36:17 +000019#include "clang/AST/Mangle.h"
Benjamin Kramer793bd552012-02-08 12:41:24 +000020#include "clang/AST/StmtCXX.h"
Chandler Carruth4b417452013-01-19 08:09:44 +000021#include "clang/AST/StmtObjC.h"
Reid Kleckner31a1bb02015-04-08 22:23:48 +000022#include "clang/AST/StmtVisitor.h"
Reid Klecknerd0d9a1f2015-07-01 17:10:10 +000023#include "clang/Basic/TargetBuiltins.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000024#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000025#include "llvm/IR/Intrinsics.h"
Reid Kleckner31a1bb02015-04-08 22:23:48 +000026#include "llvm/IR/IntrinsicInst.h"
Reid Klecknerebaf28d2015-04-14 20:59:00 +000027#include "llvm/Support/SaveAndRestore.h"
John McCallbd309292010-07-06 01:34:17 +000028
Anders Carlsson4b08db72009-10-30 01:42:31 +000029using namespace clang;
30using namespace CodeGen;
31
John McCall2c33ba82013-02-12 03:51:38 +000032static llvm::Constant *getFreeExceptionFn(CodeGenModule &CGM) {
Mike Stump33270212009-12-02 07:41:41 +000033 // void __cxa_free_exception(void *thrown_exception);
Mike Stump75546b82009-12-10 00:06:18 +000034
Chris Lattner2192fe52011-07-18 04:24:23 +000035 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +000036 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000037
John McCall2c33ba82013-02-12 03:51:38 +000038 return CGM.CreateRuntimeFunction(FTy, "__cxa_free_exception");
Mike Stump33270212009-12-02 07:41:41 +000039}
40
John McCall2c33ba82013-02-12 03:51:38 +000041static llvm::Constant *getUnexpectedFn(CodeGenModule &CGM) {
Richard Smith2f7aa192013-06-20 23:03:35 +000042 // void __cxa_call_unexpected(void *thrown_exception);
Mike Stump1d849212009-12-07 23:38:24 +000043
Chris Lattner2192fe52011-07-18 04:24:23 +000044 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +000045 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000046
John McCall2c33ba82013-02-12 03:51:38 +000047 return CGM.CreateRuntimeFunction(FTy, "__cxa_call_unexpected");
Mike Stump1d849212009-12-07 23:38:24 +000048}
49
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000050llvm::Constant *CodeGenModule::getTerminateFn() {
Mike Stump33270212009-12-02 07:41:41 +000051 // void __terminate();
52
Chris Lattner2192fe52011-07-18 04:24:23 +000053 llvm::FunctionType *FTy =
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000054 llvm::FunctionType::get(VoidTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000055
Chris Lattner0e62c1c2011-07-23 10:55:15 +000056 StringRef name;
John McCall9de19782011-07-06 01:22:26 +000057
58 // In C++, use std::terminate().
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000059 if (getLangOpts().CPlusPlus &&
60 getTarget().getCXXABI().isItaniumFamily()) {
Reid Kleckner1d59f992015-01-22 01:36:17 +000061 name = "_ZSt9terminatev";
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000062 } else if (getLangOpts().CPlusPlus &&
63 getTarget().getCXXABI().isMicrosoft()) {
David Majnemerb710a932015-05-11 03:57:49 +000064 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
David Majnemerfb6ffca2015-05-10 21:38:26 +000065 name = "__std_terminate";
66 else
67 name = "\01?terminate@@YAXXZ";
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000068 } else if (getLangOpts().ObjC1 &&
69 getLangOpts().ObjCRuntime.hasTerminate())
John McCall9de19782011-07-06 01:22:26 +000070 name = "objc_terminate";
71 else
72 name = "abort";
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000073 return CreateRuntimeFunction(FTy, name);
David Chisnallf9c42252010-05-17 13:49:20 +000074}
75
John McCall2c33ba82013-02-12 03:51:38 +000076static llvm::Constant *getCatchallRethrowFn(CodeGenModule &CGM,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000077 StringRef Name) {
Chris Lattner2192fe52011-07-18 04:24:23 +000078 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +000079 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
John McCall36ea3722010-07-17 00:43:08 +000080
John McCall2c33ba82013-02-12 03:51:38 +000081 return CGM.CreateRuntimeFunction(FTy, Name);
John McCallbd309292010-07-06 01:34:17 +000082}
83
Benjamin Kramer793bd552012-02-08 12:41:24 +000084namespace {
85 /// The exceptions personality for a function.
86 struct EHPersonality {
87 const char *PersonalityFn;
88
89 // If this is non-null, this personality requires a non-standard
90 // function for rethrowing an exception after a catchall cleanup.
91 // This function must have prototype void(void*).
92 const char *CatchallRethrowFn;
93
Reid Klecknerdeeddec2015-02-05 18:56:03 +000094 static const EHPersonality &get(CodeGenModule &CGM,
95 const FunctionDecl *FD);
96 static const EHPersonality &get(CodeGenFunction &CGF) {
97 return get(CGF.CGM, dyn_cast_or_null<FunctionDecl>(CGF.CurCodeDecl));
98 }
99
Benjamin Kramer793bd552012-02-08 12:41:24 +0000100 static const EHPersonality GNU_C;
101 static const EHPersonality GNU_C_SJLJ;
Reid Kleckner8f45c9c2014-09-15 17:19:16 +0000102 static const EHPersonality GNU_C_SEH;
Benjamin Kramer793bd552012-02-08 12:41:24 +0000103 static const EHPersonality GNU_ObjC;
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000104 static const EHPersonality GNUstep_ObjC;
Benjamin Kramer793bd552012-02-08 12:41:24 +0000105 static const EHPersonality GNU_ObjCXX;
106 static const EHPersonality NeXT_ObjC;
107 static const EHPersonality GNU_CPlusPlus;
108 static const EHPersonality GNU_CPlusPlus_SJLJ;
Reid Kleckner8f45c9c2014-09-15 17:19:16 +0000109 static const EHPersonality GNU_CPlusPlus_SEH;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000110 static const EHPersonality MSVC_except_handler;
111 static const EHPersonality MSVC_C_specific_handler;
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000112 static const EHPersonality MSVC_CxxFrameHandler3;
Benjamin Kramer793bd552012-02-08 12:41:24 +0000113 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000114}
Benjamin Kramer793bd552012-02-08 12:41:24 +0000115
Craig Topper8a13c412014-05-21 05:09:00 +0000116const EHPersonality EHPersonality::GNU_C = { "__gcc_personality_v0", nullptr };
Benjamin Kramer793bd552012-02-08 12:41:24 +0000117const EHPersonality
Craig Topper8a13c412014-05-21 05:09:00 +0000118EHPersonality::GNU_C_SJLJ = { "__gcc_personality_sj0", nullptr };
119const EHPersonality
Reid Kleckner8f45c9c2014-09-15 17:19:16 +0000120EHPersonality::GNU_C_SEH = { "__gcc_personality_seh0", nullptr };
121const EHPersonality
Craig Topper8a13c412014-05-21 05:09:00 +0000122EHPersonality::NeXT_ObjC = { "__objc_personality_v0", nullptr };
123const EHPersonality
124EHPersonality::GNU_CPlusPlus = { "__gxx_personality_v0", nullptr };
125const EHPersonality
126EHPersonality::GNU_CPlusPlus_SJLJ = { "__gxx_personality_sj0", nullptr };
Benjamin Kramer793bd552012-02-08 12:41:24 +0000127const EHPersonality
Reid Kleckner8f45c9c2014-09-15 17:19:16 +0000128EHPersonality::GNU_CPlusPlus_SEH = { "__gxx_personality_seh0", nullptr };
129const EHPersonality
Benjamin Kramer793bd552012-02-08 12:41:24 +0000130EHPersonality::GNU_ObjC = {"__gnu_objc_personality_v0", "objc_exception_throw"};
131const EHPersonality
Craig Topper8a13c412014-05-21 05:09:00 +0000132EHPersonality::GNU_ObjCXX = { "__gnustep_objcxx_personality_v0", nullptr };
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000133const EHPersonality
Craig Topper8a13c412014-05-21 05:09:00 +0000134EHPersonality::GNUstep_ObjC = { "__gnustep_objc_personality_v0", nullptr };
Reid Kleckner1d59f992015-01-22 01:36:17 +0000135const EHPersonality
136EHPersonality::MSVC_except_handler = { "_except_handler3", nullptr };
137const EHPersonality
138EHPersonality::MSVC_C_specific_handler = { "__C_specific_handler", nullptr };
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000139const EHPersonality
140EHPersonality::MSVC_CxxFrameHandler3 = { "__CxxFrameHandler3", nullptr };
John McCall36ea3722010-07-17 00:43:08 +0000141
Reid Klecknere070b992014-11-14 02:01:10 +0000142/// On Win64, use libgcc's SEH personality function. We fall back to dwarf on
143/// other platforms, unless the user asked for SjLj exceptions.
144static bool useLibGCCSEHPersonality(const llvm::Triple &T) {
145 return T.isOSWindows() && T.getArch() == llvm::Triple::x86_64;
146}
147
148static const EHPersonality &getCPersonality(const llvm::Triple &T,
149 const LangOptions &L) {
John McCall2faab302010-11-07 02:35:25 +0000150 if (L.SjLjExceptions)
151 return EHPersonality::GNU_C_SJLJ;
Reid Klecknere070b992014-11-14 02:01:10 +0000152 else if (useLibGCCSEHPersonality(T))
Reid Kleckner8f45c9c2014-09-15 17:19:16 +0000153 return EHPersonality::GNU_C_SEH;
John McCall36ea3722010-07-17 00:43:08 +0000154 return EHPersonality::GNU_C;
155}
156
Reid Klecknere070b992014-11-14 02:01:10 +0000157static const EHPersonality &getObjCPersonality(const llvm::Triple &T,
158 const LangOptions &L) {
John McCall5fb5df92012-06-20 06:18:46 +0000159 switch (L.ObjCRuntime.getKind()) {
160 case ObjCRuntime::FragileMacOSX:
Reid Klecknere070b992014-11-14 02:01:10 +0000161 return getCPersonality(T, L);
John McCall5fb5df92012-06-20 06:18:46 +0000162 case ObjCRuntime::MacOSX:
163 case ObjCRuntime::iOS:
164 return EHPersonality::NeXT_ObjC;
David Chisnallb601c962012-07-03 20:49:52 +0000165 case ObjCRuntime::GNUstep:
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000166 if (L.ObjCRuntime.getVersion() >= VersionTuple(1, 7))
167 return EHPersonality::GNUstep_ObjC;
168 // fallthrough
David Chisnallb601c962012-07-03 20:49:52 +0000169 case ObjCRuntime::GCC:
John McCall775086e2012-07-12 02:07:58 +0000170 case ObjCRuntime::ObjFW:
John McCall36ea3722010-07-17 00:43:08 +0000171 return EHPersonality::GNU_ObjC;
John McCallbd309292010-07-06 01:34:17 +0000172 }
John McCall5fb5df92012-06-20 06:18:46 +0000173 llvm_unreachable("bad runtime kind");
John McCallbd309292010-07-06 01:34:17 +0000174}
175
Reid Klecknere070b992014-11-14 02:01:10 +0000176static const EHPersonality &getCXXPersonality(const llvm::Triple &T,
177 const LangOptions &L) {
John McCall36ea3722010-07-17 00:43:08 +0000178 if (L.SjLjExceptions)
179 return EHPersonality::GNU_CPlusPlus_SJLJ;
Reid Klecknere070b992014-11-14 02:01:10 +0000180 else if (useLibGCCSEHPersonality(T))
Reid Kleckner8f45c9c2014-09-15 17:19:16 +0000181 return EHPersonality::GNU_CPlusPlus_SEH;
Reid Klecknere070b992014-11-14 02:01:10 +0000182 return EHPersonality::GNU_CPlusPlus;
John McCallbd309292010-07-06 01:34:17 +0000183}
184
185/// Determines the personality function to use when both C++
186/// and Objective-C exceptions are being caught.
Reid Klecknere070b992014-11-14 02:01:10 +0000187static const EHPersonality &getObjCXXPersonality(const llvm::Triple &T,
188 const LangOptions &L) {
John McCall5fb5df92012-06-20 06:18:46 +0000189 switch (L.ObjCRuntime.getKind()) {
John McCallbd309292010-07-06 01:34:17 +0000190 // The ObjC personality defers to the C++ personality for non-ObjC
191 // handlers. Unlike the C++ case, we use the same personality
192 // function on targets using (backend-driven) SJLJ EH.
John McCall5fb5df92012-06-20 06:18:46 +0000193 case ObjCRuntime::MacOSX:
194 case ObjCRuntime::iOS:
195 return EHPersonality::NeXT_ObjC;
John McCallbd309292010-07-06 01:34:17 +0000196
John McCall5fb5df92012-06-20 06:18:46 +0000197 // In the fragile ABI, just use C++ exception handling and hope
198 // they're not doing crazy exception mixing.
199 case ObjCRuntime::FragileMacOSX:
Reid Klecknere070b992014-11-14 02:01:10 +0000200 return getCXXPersonality(T, L);
David Chisnallf9c42252010-05-17 13:49:20 +0000201
David Chisnallb601c962012-07-03 20:49:52 +0000202 // The GCC runtime's personality function inherently doesn't support
John McCall36ea3722010-07-17 00:43:08 +0000203 // mixed EH. Use the C++ personality just to avoid returning null.
David Chisnallb601c962012-07-03 20:49:52 +0000204 case ObjCRuntime::GCC:
John McCall775086e2012-07-12 02:07:58 +0000205 case ObjCRuntime::ObjFW: // XXX: this will change soon
David Chisnallb601c962012-07-03 20:49:52 +0000206 return EHPersonality::GNU_ObjC;
207 case ObjCRuntime::GNUstep:
John McCall5fb5df92012-06-20 06:18:46 +0000208 return EHPersonality::GNU_ObjCXX;
209 }
210 llvm_unreachable("bad runtime kind");
John McCallbd309292010-07-06 01:34:17 +0000211}
212
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000213static const EHPersonality &getSEHPersonalityMSVC(const llvm::Triple &T) {
Reid Kleckner1d59f992015-01-22 01:36:17 +0000214 if (T.getArch() == llvm::Triple::x86)
215 return EHPersonality::MSVC_except_handler;
216 return EHPersonality::MSVC_C_specific_handler;
217}
218
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000219const EHPersonality &EHPersonality::get(CodeGenModule &CGM,
220 const FunctionDecl *FD) {
Reid Klecknere070b992014-11-14 02:01:10 +0000221 const llvm::Triple &T = CGM.getTarget().getTriple();
222 const LangOptions &L = CGM.getLangOpts();
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000223
Reid Kleckner1d59f992015-01-22 01:36:17 +0000224 // Try to pick a personality function that is compatible with MSVC if we're
225 // not compiling Obj-C. Obj-C users better have an Obj-C runtime that supports
226 // the GCC-style personality function.
227 if (T.isWindowsMSVCEnvironment() && !L.ObjC1) {
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000228 if (L.SjLjExceptions)
229 return EHPersonality::GNU_CPlusPlus_SJLJ;
230 else if (FD && FD->usesSEHTry())
231 return getSEHPersonalityMSVC(T);
Reid Kleckner1d59f992015-01-22 01:36:17 +0000232 else
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000233 return EHPersonality::MSVC_CxxFrameHandler3;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000234 }
235
John McCall36ea3722010-07-17 00:43:08 +0000236 if (L.CPlusPlus && L.ObjC1)
Reid Klecknere070b992014-11-14 02:01:10 +0000237 return getObjCXXPersonality(T, L);
John McCall36ea3722010-07-17 00:43:08 +0000238 else if (L.CPlusPlus)
Reid Klecknere070b992014-11-14 02:01:10 +0000239 return getCXXPersonality(T, L);
John McCall36ea3722010-07-17 00:43:08 +0000240 else if (L.ObjC1)
Reid Klecknere070b992014-11-14 02:01:10 +0000241 return getObjCPersonality(T, L);
John McCallbd309292010-07-06 01:34:17 +0000242 else
Reid Klecknere070b992014-11-14 02:01:10 +0000243 return getCPersonality(T, L);
John McCall36ea3722010-07-17 00:43:08 +0000244}
John McCallbd309292010-07-06 01:34:17 +0000245
John McCall0bdb1fd2010-09-16 06:16:50 +0000246static llvm::Constant *getPersonalityFn(CodeGenModule &CGM,
John McCall36ea3722010-07-17 00:43:08 +0000247 const EHPersonality &Personality) {
John McCall36ea3722010-07-17 00:43:08 +0000248 llvm::Constant *Fn =
Chris Lattnerece04092012-02-07 00:39:47 +0000249 CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.Int32Ty, true),
Benjamin Kramer793bd552012-02-08 12:41:24 +0000250 Personality.PersonalityFn);
John McCall0bdb1fd2010-09-16 06:16:50 +0000251 return Fn;
252}
253
254static llvm::Constant *getOpaquePersonalityFn(CodeGenModule &CGM,
255 const EHPersonality &Personality) {
256 llvm::Constant *Fn = getPersonalityFn(CGM, Personality);
John McCallad7c5c12011-02-08 08:22:06 +0000257 return llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
John McCall0bdb1fd2010-09-16 06:16:50 +0000258}
259
260/// Check whether a personality function could reasonably be swapped
261/// for a C++ personality function.
262static bool PersonalityHasOnlyCXXUses(llvm::Constant *Fn) {
Chandler Carruth4d01fff2014-03-09 03:16:50 +0000263 for (llvm::User *U : Fn->users()) {
John McCall0bdb1fd2010-09-16 06:16:50 +0000264 // Conditionally white-list bitcasts.
Chandler Carruth4d01fff2014-03-09 03:16:50 +0000265 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(U)) {
John McCall0bdb1fd2010-09-16 06:16:50 +0000266 if (CE->getOpcode() != llvm::Instruction::BitCast) return false;
267 if (!PersonalityHasOnlyCXXUses(CE))
268 return false;
269 continue;
270 }
271
Bill Wendling58e58fe2011-09-19 22:08:36 +0000272 // Otherwise, it has to be a landingpad instruction.
Chandler Carruth4d01fff2014-03-09 03:16:50 +0000273 llvm::LandingPadInst *LPI = dyn_cast<llvm::LandingPadInst>(U);
Bill Wendling58e58fe2011-09-19 22:08:36 +0000274 if (!LPI) return false;
John McCall0bdb1fd2010-09-16 06:16:50 +0000275
Bill Wendling58e58fe2011-09-19 22:08:36 +0000276 for (unsigned I = 0, E = LPI->getNumClauses(); I != E; ++I) {
John McCall0bdb1fd2010-09-16 06:16:50 +0000277 // Look for something that would've been returned by the ObjC
278 // runtime's GetEHType() method.
Bill Wendling58e58fe2011-09-19 22:08:36 +0000279 llvm::Value *Val = LPI->getClause(I)->stripPointerCasts();
280 if (LPI->isCatch(I)) {
281 // Check if the catch value has the ObjC prefix.
Bill Wendling5d7469e2011-09-20 00:40:19 +0000282 if (llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Val))
283 // ObjC EH selector entries are always global variables with
284 // names starting like this.
285 if (GV->getName().startswith("OBJC_EHTYPE"))
286 return false;
Bill Wendling58e58fe2011-09-19 22:08:36 +0000287 } else {
288 // Check if any of the filter values have the ObjC prefix.
289 llvm::Constant *CVal = cast<llvm::Constant>(Val);
290 for (llvm::User::op_iterator
291 II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II) {
Bill Wendling5d7469e2011-09-20 00:40:19 +0000292 if (llvm::GlobalVariable *GV =
293 cast<llvm::GlobalVariable>((*II)->stripPointerCasts()))
294 // ObjC EH selector entries are always global variables with
295 // names starting like this.
296 if (GV->getName().startswith("OBJC_EHTYPE"))
297 return false;
Bill Wendling58e58fe2011-09-19 22:08:36 +0000298 }
299 }
John McCall0bdb1fd2010-09-16 06:16:50 +0000300 }
301 }
302
303 return true;
304}
305
306/// Try to use the C++ personality function in ObjC++. Not doing this
307/// can cause some incompatibilities with gcc, which is more
308/// aggressive about only using the ObjC++ personality in a function
309/// when it really needs it.
310void CodeGenModule::SimplifyPersonality() {
John McCall0bdb1fd2010-09-16 06:16:50 +0000311 // If we're not in ObjC++ -fexceptions, there's nothing to do.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000312 if (!LangOpts.CPlusPlus || !LangOpts.ObjC1 || !LangOpts.Exceptions)
John McCall0bdb1fd2010-09-16 06:16:50 +0000313 return;
314
John McCall3c223932012-11-14 17:48:31 +0000315 // Both the problem this endeavors to fix and the way the logic
316 // above works is specific to the NeXT runtime.
317 if (!LangOpts.ObjCRuntime.isNeXTFamily())
318 return;
319
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000320 const EHPersonality &ObjCXX = EHPersonality::get(*this, /*FD=*/nullptr);
Reid Klecknere070b992014-11-14 02:01:10 +0000321 const EHPersonality &CXX =
322 getCXXPersonality(getTarget().getTriple(), LangOpts);
Benjamin Kramer793bd552012-02-08 12:41:24 +0000323 if (&ObjCXX == &CXX)
John McCall0bdb1fd2010-09-16 06:16:50 +0000324 return;
325
Benjamin Kramer793bd552012-02-08 12:41:24 +0000326 assert(std::strcmp(ObjCXX.PersonalityFn, CXX.PersonalityFn) != 0 &&
327 "Different EHPersonalities using the same personality function.");
328
329 llvm::Function *Fn = getModule().getFunction(ObjCXX.PersonalityFn);
John McCall0bdb1fd2010-09-16 06:16:50 +0000330
331 // Nothing to do if it's unused.
332 if (!Fn || Fn->use_empty()) return;
333
334 // Can't do the optimization if it has non-C++ uses.
335 if (!PersonalityHasOnlyCXXUses(Fn)) return;
336
337 // Create the C++ personality function and kill off the old
338 // function.
339 llvm::Constant *CXXFn = getPersonalityFn(*this, CXX);
340
341 // This can happen if the user is screwing with us.
342 if (Fn->getType() != CXXFn->getType()) return;
343
344 Fn->replaceAllUsesWith(CXXFn);
345 Fn->eraseFromParent();
John McCallbd309292010-07-06 01:34:17 +0000346}
347
348/// Returns the value to inject into a selector to indicate the
349/// presence of a catch-all.
350static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
351 // Possibly we should use @llvm.eh.catch.all.value here.
John McCallad7c5c12011-02-08 08:22:06 +0000352 return llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
John McCallbd309292010-07-06 01:34:17 +0000353}
354
John McCallbb026012010-07-13 21:17:51 +0000355namespace {
356 /// A cleanup to free the exception object if its initialization
357 /// throws.
John McCall5fcf8da2011-07-12 00:15:30 +0000358 struct FreeException : EHScopeStack::Cleanup {
359 llvm::Value *exn;
360 FreeException(llvm::Value *exn) : exn(exn) {}
Craig Topper4f12f102014-03-12 06:41:41 +0000361 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +0000362 CGF.EmitNounwindRuntimeCall(getFreeExceptionFn(CGF.CGM), exn);
John McCallbb026012010-07-13 21:17:51 +0000363 }
364 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000365}
John McCallbb026012010-07-13 21:17:51 +0000366
John McCall2e6567a2010-04-22 01:10:34 +0000367// Emits an exception expression into the given location. This
368// differs from EmitAnyExprToMem only in that, if a final copy-ctor
369// call is required, an exception within that copy ctor causes
370// std::terminate to be invoked.
David Majnemer7c237072015-03-05 00:46:22 +0000371void CodeGenFunction::EmitAnyExprToExn(const Expr *e, llvm::Value *addr) {
John McCallbd309292010-07-06 01:34:17 +0000372 // Make sure the exception object is cleaned up if there's an
373 // exception during initialization.
David Majnemer7c237072015-03-05 00:46:22 +0000374 pushFullExprCleanup<FreeException>(EHCleanup, addr);
375 EHScopeStack::stable_iterator cleanup = EHStack.stable_begin();
John McCall2e6567a2010-04-22 01:10:34 +0000376
377 // __cxa_allocate_exception returns a void*; we need to cast this
378 // to the appropriate type for the object.
David Majnemer7c237072015-03-05 00:46:22 +0000379 llvm::Type *ty = ConvertTypeForMem(e->getType())->getPointerTo();
380 llvm::Value *typedAddr = Builder.CreateBitCast(addr, ty);
John McCall2e6567a2010-04-22 01:10:34 +0000381
382 // FIXME: this isn't quite right! If there's a final unelided call
383 // to a copy constructor, then according to [except.terminate]p1 we
384 // must call std::terminate() if that constructor throws, because
385 // technically that copy occurs after the exception expression is
386 // evaluated but before the exception is caught. But the best way
387 // to handle that is to teach EmitAggExpr to do the final copy
388 // differently if it can't be elided.
David Majnemer7c237072015-03-05 00:46:22 +0000389 EmitAnyExprToMem(e, typedAddr, e->getType().getQualifiers(),
390 /*IsInit*/ true);
John McCall2e6567a2010-04-22 01:10:34 +0000391
John McCalle4df6c82011-01-28 08:37:24 +0000392 // Deactivate the cleanup block.
David Majnemer7c237072015-03-05 00:46:22 +0000393 DeactivateCleanupBlock(cleanup, cast<llvm::Instruction>(typedAddr));
Mike Stump54066142009-12-01 03:41:18 +0000394}
395
John McCallbd309292010-07-06 01:34:17 +0000396llvm::Value *CodeGenFunction::getExceptionSlot() {
John McCall9b382dd2011-05-28 21:13:02 +0000397 if (!ExceptionSlot)
398 ExceptionSlot = CreateTempAlloca(Int8PtrTy, "exn.slot");
John McCallbd309292010-07-06 01:34:17 +0000399 return ExceptionSlot;
Mike Stump54066142009-12-01 03:41:18 +0000400}
401
John McCall9b382dd2011-05-28 21:13:02 +0000402llvm::Value *CodeGenFunction::getEHSelectorSlot() {
403 if (!EHSelectorSlot)
404 EHSelectorSlot = CreateTempAlloca(Int32Ty, "ehselector.slot");
405 return EHSelectorSlot;
406}
407
Bill Wendling79a70e42011-09-15 18:57:19 +0000408llvm::Value *CodeGenFunction::getExceptionFromSlot() {
409 return Builder.CreateLoad(getExceptionSlot(), "exn");
410}
411
412llvm::Value *CodeGenFunction::getSelectorFromSlot() {
413 return Builder.CreateLoad(getEHSelectorSlot(), "sel");
414}
415
Richard Smithea852322013-05-07 21:53:22 +0000416void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E,
417 bool KeepInsertionPoint) {
David Majnemer7c237072015-03-05 00:46:22 +0000418 if (const Expr *SubExpr = E->getSubExpr()) {
419 QualType ThrowType = SubExpr->getType();
420 if (ThrowType->isObjCObjectPointerType()) {
421 const Stmt *ThrowStmt = E->getSubExpr();
422 const ObjCAtThrowStmt S(E->getExprLoc(), const_cast<Stmt *>(ThrowStmt));
423 CGM.getObjCRuntime().EmitThrowStmt(*this, S, false);
424 } else {
425 CGM.getCXXABI().emitThrow(*this, E);
John McCall2e6567a2010-04-22 01:10:34 +0000426 }
David Majnemer7c237072015-03-05 00:46:22 +0000427 } else {
428 CGM.getCXXABI().emitRethrow(*this, /*isNoReturn=*/true);
John McCall2e6567a2010-04-22 01:10:34 +0000429 }
Mike Stump75546b82009-12-10 00:06:18 +0000430
John McCall20f6ab82011-01-12 03:41:02 +0000431 // throw is an expression, and the expression emitters expect us
432 // to leave ourselves at a valid insertion point.
Richard Smithea852322013-05-07 21:53:22 +0000433 if (KeepInsertionPoint)
434 EmitBlock(createBasicBlock("throw.cont"));
Anders Carlsson4b08db72009-10-30 01:42:31 +0000435}
Mike Stump58ef18b2009-11-20 23:44:51 +0000436
Mike Stump1d849212009-12-07 23:38:24 +0000437void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000438 if (!CGM.getLangOpts().CXXExceptions)
Anders Carlsson9878f9f2010-02-06 23:59:05 +0000439 return;
440
Mike Stump1d849212009-12-07 23:38:24 +0000441 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
Craig Topper8a13c412014-05-21 05:09:00 +0000442 if (!FD) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000443 // Check if CapturedDecl is nothrow and create terminate scope for it.
444 if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
445 if (CD->isNothrow())
446 EHStack.pushTerminate();
447 }
Mike Stump1d849212009-12-07 23:38:24 +0000448 return;
Alexey Bataev9959db52014-05-06 10:08:46 +0000449 }
Mike Stump1d849212009-12-07 23:38:24 +0000450 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
Craig Topper8a13c412014-05-21 05:09:00 +0000451 if (!Proto)
Mike Stump1d849212009-12-07 23:38:24 +0000452 return;
453
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000454 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
455 if (isNoexceptExceptionSpec(EST)) {
456 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
457 // noexcept functions are simple terminate scopes.
458 EHStack.pushTerminate();
459 }
460 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
David Majnemer1f192e22015-04-01 04:45:52 +0000461 // TODO: Revisit exception specifications for the MS ABI. There is a way to
462 // encode these in an object file but MSVC doesn't do anything with it.
463 if (getTarget().getCXXABI().isMicrosoft())
464 return;
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000465 unsigned NumExceptions = Proto->getNumExceptions();
466 EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
Mike Stump1d849212009-12-07 23:38:24 +0000467
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000468 for (unsigned I = 0; I != NumExceptions; ++I) {
469 QualType Ty = Proto->getExceptionType(I);
470 QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
471 llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType,
472 /*ForEH=*/true);
473 Filter->setFilter(I, EHType);
474 }
Mike Stump1d849212009-12-07 23:38:24 +0000475 }
Mike Stump1d849212009-12-07 23:38:24 +0000476}
477
John McCall8e4c74b2011-08-11 02:22:43 +0000478/// Emit the dispatch block for a filter scope if necessary.
479static void emitFilterDispatchBlock(CodeGenFunction &CGF,
480 EHFilterScope &filterScope) {
481 llvm::BasicBlock *dispatchBlock = filterScope.getCachedEHDispatchBlock();
482 if (!dispatchBlock) return;
483 if (dispatchBlock->use_empty()) {
484 delete dispatchBlock;
485 return;
486 }
487
John McCall8e4c74b2011-08-11 02:22:43 +0000488 CGF.EmitBlockAfterUses(dispatchBlock);
489
490 // If this isn't a catch-all filter, we need to check whether we got
491 // here because the filter triggered.
492 if (filterScope.getNumFilters()) {
493 // Load the selector value.
Bill Wendling79a70e42011-09-15 18:57:19 +0000494 llvm::Value *selector = CGF.getSelectorFromSlot();
John McCall8e4c74b2011-08-11 02:22:43 +0000495 llvm::BasicBlock *unexpectedBB = CGF.createBasicBlock("ehspec.unexpected");
496
497 llvm::Value *zero = CGF.Builder.getInt32(0);
498 llvm::Value *failsFilter =
Nico Weber1bebad12015-02-11 22:33:32 +0000499 CGF.Builder.CreateICmpSLT(selector, zero, "ehspec.fails");
500 CGF.Builder.CreateCondBr(failsFilter, unexpectedBB,
501 CGF.getEHResumeBlock(false));
John McCall8e4c74b2011-08-11 02:22:43 +0000502
503 CGF.EmitBlock(unexpectedBB);
504 }
505
506 // Call __cxa_call_unexpected. This doesn't need to be an invoke
507 // because __cxa_call_unexpected magically filters exceptions
508 // according to the last landing pad the exception was thrown
509 // into. Seriously.
Bill Wendling79a70e42011-09-15 18:57:19 +0000510 llvm::Value *exn = CGF.getExceptionFromSlot();
John McCall882987f2013-02-28 19:01:20 +0000511 CGF.EmitRuntimeCall(getUnexpectedFn(CGF.CGM), exn)
John McCall8e4c74b2011-08-11 02:22:43 +0000512 ->setDoesNotReturn();
513 CGF.Builder.CreateUnreachable();
514}
515
Mike Stump1d849212009-12-07 23:38:24 +0000516void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000517 if (!CGM.getLangOpts().CXXExceptions)
Anders Carlsson9878f9f2010-02-06 23:59:05 +0000518 return;
519
Mike Stump1d849212009-12-07 23:38:24 +0000520 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
Craig Topper8a13c412014-05-21 05:09:00 +0000521 if (!FD) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000522 // Check if CapturedDecl is nothrow and pop terminate scope for it.
523 if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
524 if (CD->isNothrow())
525 EHStack.popTerminate();
526 }
Mike Stump1d849212009-12-07 23:38:24 +0000527 return;
Alexey Bataev9959db52014-05-06 10:08:46 +0000528 }
Mike Stump1d849212009-12-07 23:38:24 +0000529 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
Craig Topper8a13c412014-05-21 05:09:00 +0000530 if (!Proto)
Mike Stump1d849212009-12-07 23:38:24 +0000531 return;
532
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000533 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
534 if (isNoexceptExceptionSpec(EST)) {
535 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
536 EHStack.popTerminate();
537 }
538 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
David Majnemer1f192e22015-04-01 04:45:52 +0000539 // TODO: Revisit exception specifications for the MS ABI. There is a way to
540 // encode these in an object file but MSVC doesn't do anything with it.
541 if (getTarget().getCXXABI().isMicrosoft())
542 return;
John McCall8e4c74b2011-08-11 02:22:43 +0000543 EHFilterScope &filterScope = cast<EHFilterScope>(*EHStack.begin());
544 emitFilterDispatchBlock(*this, filterScope);
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000545 EHStack.popFilter();
546 }
Mike Stump1d849212009-12-07 23:38:24 +0000547}
548
Mike Stump58ef18b2009-11-20 23:44:51 +0000549void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
John McCallb609d3f2010-07-07 06:56:46 +0000550 EnterCXXTryStmt(S);
John McCallb81884d2010-02-19 09:25:03 +0000551 EmitStmt(S.getTryBlock());
John McCallb609d3f2010-07-07 06:56:46 +0000552 ExitCXXTryStmt(S);
John McCallb81884d2010-02-19 09:25:03 +0000553}
554
John McCallb609d3f2010-07-07 06:56:46 +0000555void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallbd309292010-07-06 01:34:17 +0000556 unsigned NumHandlers = S.getNumHandlers();
557 EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
John McCallb81884d2010-02-19 09:25:03 +0000558
John McCallbd309292010-07-06 01:34:17 +0000559 for (unsigned I = 0; I != NumHandlers; ++I) {
560 const CXXCatchStmt *C = S.getHandler(I);
John McCallb81884d2010-02-19 09:25:03 +0000561
John McCallbd309292010-07-06 01:34:17 +0000562 llvm::BasicBlock *Handler = createBasicBlock("catch");
563 if (C->getExceptionDecl()) {
564 // FIXME: Dropping the reference type on the type into makes it
565 // impossible to correctly implement catch-by-reference
566 // semantics for pointers. Unfortunately, this is what all
567 // existing compilers do, and it's not clear that the standard
568 // personality routine is capable of doing this right. See C++ DR 388:
569 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
David Majnemer571162a2014-10-12 06:58:22 +0000570 Qualifiers CaughtTypeQuals;
571 QualType CaughtType = CGM.getContext().getUnqualifiedArrayType(
572 C->getCaughtType().getNonReferenceType(), CaughtTypeQuals);
John McCall2ca705e2010-07-24 00:37:23 +0000573
Rafael Espindolabb9e7a32014-06-04 18:51:46 +0000574 llvm::Constant *TypeInfo = nullptr;
John McCall2ca705e2010-07-24 00:37:23 +0000575 if (CaughtType->isObjCObjectPointerType())
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +0000576 TypeInfo = CGM.getObjCRuntime().GetEHType(CaughtType);
John McCall2ca705e2010-07-24 00:37:23 +0000577 else
David Majnemer5f0dd612015-03-17 20:35:05 +0000578 TypeInfo =
David Majnemer37b417f2015-03-29 21:55:10 +0000579 CGM.getAddrOfCXXCatchHandlerType(CaughtType, C->getCaughtType());
John McCallbd309292010-07-06 01:34:17 +0000580 CatchScope->setHandler(I, TypeInfo, Handler);
581 } else {
582 // No exception decl indicates '...', a catch-all.
583 CatchScope->setCatchAllHandler(I, Handler);
584 }
585 }
John McCallbd309292010-07-06 01:34:17 +0000586}
587
John McCall8e4c74b2011-08-11 02:22:43 +0000588llvm::BasicBlock *
589CodeGenFunction::getEHDispatchBlock(EHScopeStack::stable_iterator si) {
590 // The dispatch block for the end of the scope chain is a block that
591 // just resumes unwinding.
592 if (si == EHStack.stable_end())
David Chisnall9a837be2012-11-07 16:50:40 +0000593 return getEHResumeBlock(true);
John McCall8e4c74b2011-08-11 02:22:43 +0000594
595 // Otherwise, we should look at the actual scope.
596 EHScope &scope = *EHStack.find(si);
597
598 llvm::BasicBlock *dispatchBlock = scope.getCachedEHDispatchBlock();
599 if (!dispatchBlock) {
600 switch (scope.getKind()) {
601 case EHScope::Catch: {
602 // Apply a special case to a single catch-all.
603 EHCatchScope &catchScope = cast<EHCatchScope>(scope);
604 if (catchScope.getNumHandlers() == 1 &&
605 catchScope.getHandler(0).isCatchAll()) {
606 dispatchBlock = catchScope.getHandler(0).Block;
607
608 // Otherwise, make a dispatch block.
609 } else {
610 dispatchBlock = createBasicBlock("catch.dispatch");
611 }
612 break;
613 }
614
615 case EHScope::Cleanup:
616 dispatchBlock = createBasicBlock("ehcleanup");
617 break;
618
619 case EHScope::Filter:
620 dispatchBlock = createBasicBlock("filter.dispatch");
621 break;
622
623 case EHScope::Terminate:
624 dispatchBlock = getTerminateHandler();
625 break;
626 }
627 scope.setCachedEHDispatchBlock(dispatchBlock);
628 }
629 return dispatchBlock;
630}
631
John McCallbd309292010-07-06 01:34:17 +0000632/// Check whether this is a non-EH scope, i.e. a scope which doesn't
633/// affect exception handling. Currently, the only non-EH scopes are
634/// normal-only cleanup scopes.
635static bool isNonEHScope(const EHScope &S) {
John McCall2b7fc382010-07-13 20:32:21 +0000636 switch (S.getKind()) {
John McCallcda666c2010-07-21 07:22:38 +0000637 case EHScope::Cleanup:
638 return !cast<EHCleanupScope>(S).isEHCleanup();
John McCall2b7fc382010-07-13 20:32:21 +0000639 case EHScope::Filter:
640 case EHScope::Catch:
641 case EHScope::Terminate:
642 return false;
643 }
644
David Blaikiee4d798f2012-01-20 21:50:17 +0000645 llvm_unreachable("Invalid EHScope Kind!");
John McCallbd309292010-07-06 01:34:17 +0000646}
647
648llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
649 assert(EHStack.requiresLandingPad());
650 assert(!EHStack.empty());
651
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000652 // If exceptions are disabled, there are usually no landingpads. However, when
653 // SEH is enabled, functions using SEH still get landingpads.
654 const LangOptions &LO = CGM.getLangOpts();
655 if (!LO.Exceptions) {
656 if (!LO.Borland && !LO.MicrosoftExt)
657 return nullptr;
Reid Klecknere7b3f7c2015-02-11 00:00:21 +0000658 if (!currentFunctionUsesSEHTry())
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000659 return nullptr;
660 }
John McCall2b7fc382010-07-13 20:32:21 +0000661
John McCallbd309292010-07-06 01:34:17 +0000662 // Check the innermost scope for a cached landing pad. If this is
663 // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
664 llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
665 if (LP) return LP;
666
667 // Build the landing pad for this scope.
668 LP = EmitLandingPad();
669 assert(LP);
670
671 // Cache the landing pad on the innermost scope. If this is a
672 // non-EH scope, cache the landing pad on the enclosing scope, too.
673 for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
674 ir->setCachedLandingPad(LP);
675 if (!isNonEHScope(*ir)) break;
676 }
677
678 return LP;
679}
680
681llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
682 assert(EHStack.requiresLandingPad());
683
John McCall8e4c74b2011-08-11 02:22:43 +0000684 EHScope &innermostEHScope = *EHStack.find(EHStack.getInnermostEHScope());
685 switch (innermostEHScope.getKind()) {
686 case EHScope::Terminate:
687 return getTerminateLandingPad();
John McCallbd309292010-07-06 01:34:17 +0000688
John McCall8e4c74b2011-08-11 02:22:43 +0000689 case EHScope::Catch:
690 case EHScope::Cleanup:
691 case EHScope::Filter:
692 if (llvm::BasicBlock *lpad = innermostEHScope.getCachedLandingPad())
693 return lpad;
John McCallbd309292010-07-06 01:34:17 +0000694 }
695
696 // Save the current IR generation state.
John McCall8e4c74b2011-08-11 02:22:43 +0000697 CGBuilderTy::InsertPoint savedIP = Builder.saveAndClearIP();
Adrian Prantl95b24e92015-02-03 20:00:54 +0000698 auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, CurEHLocation);
John McCallbd309292010-07-06 01:34:17 +0000699
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000700 const EHPersonality &personality = EHPersonality::get(*this);
John McCall36ea3722010-07-17 00:43:08 +0000701
David Majnemerfcbdb6e2015-06-17 20:53:19 +0000702 if (!CurFn->hasPersonalityFn())
703 CurFn->setPersonalityFn(getOpaquePersonalityFn(CGM, personality));
704
John McCallbd309292010-07-06 01:34:17 +0000705 // Create and configure the landing pad.
John McCall8e4c74b2011-08-11 02:22:43 +0000706 llvm::BasicBlock *lpad = createBasicBlock("lpad");
707 EmitBlock(lpad);
John McCallbd309292010-07-06 01:34:17 +0000708
David Majnemerfcbdb6e2015-06-17 20:53:19 +0000709 llvm::LandingPadInst *LPadInst = Builder.CreateLandingPad(
710 llvm::StructType::get(Int8PtrTy, Int32Ty, nullptr), 0);
Bill Wendlingf0724e82011-09-19 20:31:14 +0000711
712 llvm::Value *LPadExn = Builder.CreateExtractValue(LPadInst, 0);
713 Builder.CreateStore(LPadExn, getExceptionSlot());
714 llvm::Value *LPadSel = Builder.CreateExtractValue(LPadInst, 1);
715 Builder.CreateStore(LPadSel, getEHSelectorSlot());
716
John McCallbd309292010-07-06 01:34:17 +0000717 // Save the exception pointer. It's safe to use a single exception
718 // pointer per function because EH cleanups can never have nested
719 // try/catches.
Bill Wendlingf0724e82011-09-19 20:31:14 +0000720 // Build the landingpad instruction.
John McCallbd309292010-07-06 01:34:17 +0000721
722 // Accumulate all the handlers in scope.
John McCall8e4c74b2011-08-11 02:22:43 +0000723 bool hasCatchAll = false;
724 bool hasCleanup = false;
725 bool hasFilter = false;
726 SmallVector<llvm::Value*, 4> filterTypes;
727 llvm::SmallPtrSet<llvm::Value*, 4> catchTypes;
Nico Webere68b9f32015-02-25 16:25:00 +0000728 for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end(); I != E;
729 ++I) {
John McCallbd309292010-07-06 01:34:17 +0000730
731 switch (I->getKind()) {
John McCallcda666c2010-07-21 07:22:38 +0000732 case EHScope::Cleanup:
John McCall8e4c74b2011-08-11 02:22:43 +0000733 // If we have a cleanup, remember that.
734 hasCleanup = (hasCleanup || cast<EHCleanupScope>(*I).isEHCleanup());
John McCall2b7fc382010-07-13 20:32:21 +0000735 continue;
736
John McCallbd309292010-07-06 01:34:17 +0000737 case EHScope::Filter: {
738 assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
John McCall8e4c74b2011-08-11 02:22:43 +0000739 assert(!hasCatchAll && "EH filter reached after catch-all");
John McCallbd309292010-07-06 01:34:17 +0000740
Bill Wendlingf0724e82011-09-19 20:31:14 +0000741 // Filter scopes get added to the landingpad in weird ways.
John McCall8e4c74b2011-08-11 02:22:43 +0000742 EHFilterScope &filter = cast<EHFilterScope>(*I);
743 hasFilter = true;
John McCallbd309292010-07-06 01:34:17 +0000744
Bill Wendling8c4b7162011-09-22 20:32:54 +0000745 // Add all the filter values.
746 for (unsigned i = 0, e = filter.getNumFilters(); i != e; ++i)
747 filterTypes.push_back(filter.getFilter(i));
John McCallbd309292010-07-06 01:34:17 +0000748 goto done;
749 }
750
751 case EHScope::Terminate:
752 // Terminate scopes are basically catch-alls.
John McCall8e4c74b2011-08-11 02:22:43 +0000753 assert(!hasCatchAll);
754 hasCatchAll = true;
John McCallbd309292010-07-06 01:34:17 +0000755 goto done;
756
757 case EHScope::Catch:
758 break;
759 }
760
John McCall8e4c74b2011-08-11 02:22:43 +0000761 EHCatchScope &catchScope = cast<EHCatchScope>(*I);
762 for (unsigned hi = 0, he = catchScope.getNumHandlers(); hi != he; ++hi) {
763 EHCatchScope::Handler handler = catchScope.getHandler(hi);
John McCallbd309292010-07-06 01:34:17 +0000764
John McCall8e4c74b2011-08-11 02:22:43 +0000765 // If this is a catch-all, register that and abort.
766 if (!handler.Type) {
767 assert(!hasCatchAll);
768 hasCatchAll = true;
769 goto done;
John McCallbd309292010-07-06 01:34:17 +0000770 }
771
772 // Check whether we already have a handler for this type.
David Blaikie82e95a32014-11-19 07:49:47 +0000773 if (catchTypes.insert(handler.Type).second)
Bill Wendlingf0724e82011-09-19 20:31:14 +0000774 // If not, add it directly to the landingpad.
775 LPadInst->addClause(handler.Type);
John McCallbd309292010-07-06 01:34:17 +0000776 }
John McCallbd309292010-07-06 01:34:17 +0000777 }
778
779 done:
Bill Wendlingf0724e82011-09-19 20:31:14 +0000780 // If we have a catch-all, add null to the landingpad.
John McCall8e4c74b2011-08-11 02:22:43 +0000781 assert(!(hasCatchAll && hasFilter));
782 if (hasCatchAll) {
Bill Wendlingf0724e82011-09-19 20:31:14 +0000783 LPadInst->addClause(getCatchAllValue(*this));
John McCallbd309292010-07-06 01:34:17 +0000784
785 // If we have an EH filter, we need to add those handlers in the
Bill Wendlingf0724e82011-09-19 20:31:14 +0000786 // right place in the landingpad, which is to say, at the end.
John McCall8e4c74b2011-08-11 02:22:43 +0000787 } else if (hasFilter) {
Bill Wendling58e58fe2011-09-19 22:08:36 +0000788 // Create a filter expression: a constant array indicating which filter
789 // types there are. The personality routine only lands here if the filter
790 // doesn't match.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000791 SmallVector<llvm::Constant*, 8> Filters;
Bill Wendlingf0724e82011-09-19 20:31:14 +0000792 llvm::ArrayType *AType =
793 llvm::ArrayType::get(!filterTypes.empty() ?
794 filterTypes[0]->getType() : Int8PtrTy,
795 filterTypes.size());
796
797 for (unsigned i = 0, e = filterTypes.size(); i != e; ++i)
798 Filters.push_back(cast<llvm::Constant>(filterTypes[i]));
799 llvm::Constant *FilterArray = llvm::ConstantArray::get(AType, Filters);
800 LPadInst->addClause(FilterArray);
John McCallbd309292010-07-06 01:34:17 +0000801
802 // Also check whether we need a cleanup.
Bill Wendlingf0724e82011-09-19 20:31:14 +0000803 if (hasCleanup)
804 LPadInst->setCleanup(true);
John McCallbd309292010-07-06 01:34:17 +0000805
806 // Otherwise, signal that we at least have cleanups.
Logan Chiene9c8ccb2014-07-01 11:47:10 +0000807 } else if (hasCleanup) {
808 LPadInst->setCleanup(true);
John McCallbd309292010-07-06 01:34:17 +0000809 }
810
Bill Wendlingf0724e82011-09-19 20:31:14 +0000811 assert((LPadInst->getNumClauses() > 0 || LPadInst->isCleanup()) &&
812 "landingpad instruction has no clauses!");
John McCallbd309292010-07-06 01:34:17 +0000813
814 // Tell the backend how to generate the landing pad.
John McCall8e4c74b2011-08-11 02:22:43 +0000815 Builder.CreateBr(getEHDispatchBlock(EHStack.getInnermostEHScope()));
John McCallbd309292010-07-06 01:34:17 +0000816
817 // Restore the old IR generation state.
John McCall8e4c74b2011-08-11 02:22:43 +0000818 Builder.restoreIP(savedIP);
John McCallbd309292010-07-06 01:34:17 +0000819
John McCall8e4c74b2011-08-11 02:22:43 +0000820 return lpad;
John McCallbd309292010-07-06 01:34:17 +0000821}
822
John McCall8e4c74b2011-08-11 02:22:43 +0000823/// Emit the structure of the dispatch block for the given catch scope.
824/// It is an invariant that the dispatch block already exists.
825static void emitCatchDispatchBlock(CodeGenFunction &CGF,
826 EHCatchScope &catchScope) {
827 llvm::BasicBlock *dispatchBlock = catchScope.getCachedEHDispatchBlock();
828 assert(dispatchBlock);
829
830 // If there's only a single catch-all, getEHDispatchBlock returned
831 // that catch-all as the dispatch block.
832 if (catchScope.getNumHandlers() == 1 &&
833 catchScope.getHandler(0).isCatchAll()) {
834 assert(dispatchBlock == catchScope.getHandler(0).Block);
835 return;
836 }
837
838 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveIP();
839 CGF.EmitBlockAfterUses(dispatchBlock);
840
841 // Select the right handler.
842 llvm::Value *llvm_eh_typeid_for =
843 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
844
845 // Load the selector value.
Bill Wendling79a70e42011-09-15 18:57:19 +0000846 llvm::Value *selector = CGF.getSelectorFromSlot();
John McCall8e4c74b2011-08-11 02:22:43 +0000847
848 // Test against each of the exception types we claim to catch.
849 for (unsigned i = 0, e = catchScope.getNumHandlers(); ; ++i) {
850 assert(i < e && "ran off end of handlers!");
851 const EHCatchScope::Handler &handler = catchScope.getHandler(i);
852
853 llvm::Value *typeValue = handler.Type;
854 assert(typeValue && "fell into catch-all case!");
855 typeValue = CGF.Builder.CreateBitCast(typeValue, CGF.Int8PtrTy);
856
857 // Figure out the next block.
858 bool nextIsEnd;
859 llvm::BasicBlock *nextBlock;
860
861 // If this is the last handler, we're at the end, and the next
862 // block is the block for the enclosing EH scope.
863 if (i + 1 == e) {
864 nextBlock = CGF.getEHDispatchBlock(catchScope.getEnclosingEHScope());
865 nextIsEnd = true;
866
867 // If the next handler is a catch-all, we're at the end, and the
868 // next block is that handler.
869 } else if (catchScope.getHandler(i+1).isCatchAll()) {
870 nextBlock = catchScope.getHandler(i+1).Block;
871 nextIsEnd = true;
872
873 // Otherwise, we're not at the end and we need a new block.
874 } else {
875 nextBlock = CGF.createBasicBlock("catch.fallthrough");
876 nextIsEnd = false;
877 }
878
879 // Figure out the catch type's index in the LSDA's type table.
880 llvm::CallInst *typeIndex =
881 CGF.Builder.CreateCall(llvm_eh_typeid_for, typeValue);
882 typeIndex->setDoesNotThrow();
883
884 llvm::Value *matchesTypeIndex =
885 CGF.Builder.CreateICmpEQ(selector, typeIndex, "matches");
886 CGF.Builder.CreateCondBr(matchesTypeIndex, handler.Block, nextBlock);
887
888 // If the next handler is a catch-all, we're completely done.
889 if (nextIsEnd) {
890 CGF.Builder.restoreIP(savedIP);
891 return;
John McCall8e4c74b2011-08-11 02:22:43 +0000892 }
Ahmed Charles289896d2012-02-19 11:57:29 +0000893 // Otherwise we need to emit and continue at that block.
894 CGF.EmitBlock(nextBlock);
John McCall8e4c74b2011-08-11 02:22:43 +0000895 }
John McCall8e4c74b2011-08-11 02:22:43 +0000896}
897
898void CodeGenFunction::popCatchScope() {
899 EHCatchScope &catchScope = cast<EHCatchScope>(*EHStack.begin());
900 if (catchScope.hasEHBranches())
901 emitCatchDispatchBlock(*this, catchScope);
902 EHStack.popCatch();
903}
904
John McCallb609d3f2010-07-07 06:56:46 +0000905void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallbd309292010-07-06 01:34:17 +0000906 unsigned NumHandlers = S.getNumHandlers();
907 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
908 assert(CatchScope.getNumHandlers() == NumHandlers);
Mike Stump58ef18b2009-11-20 23:44:51 +0000909
John McCall8e4c74b2011-08-11 02:22:43 +0000910 // If the catch was not required, bail out now.
911 if (!CatchScope.hasEHBranches()) {
Kostya Serebryanyba4aced2014-01-09 09:22:32 +0000912 CatchScope.clearHandlerBlocks();
John McCall8e4c74b2011-08-11 02:22:43 +0000913 EHStack.popCatch();
914 return;
915 }
916
917 // Emit the structure of the EH dispatch for this catch.
918 emitCatchDispatchBlock(*this, CatchScope);
919
John McCallbd309292010-07-06 01:34:17 +0000920 // Copy the handler blocks off before we pop the EH stack. Emitting
921 // the handlers might scribble on this memory.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000922 SmallVector<EHCatchScope::Handler, 8> Handlers(NumHandlers);
John McCallbd309292010-07-06 01:34:17 +0000923 memcpy(Handlers.data(), CatchScope.begin(),
924 NumHandlers * sizeof(EHCatchScope::Handler));
John McCall8e4c74b2011-08-11 02:22:43 +0000925
John McCallbd309292010-07-06 01:34:17 +0000926 EHStack.popCatch();
Mike Stump58ef18b2009-11-20 23:44:51 +0000927
John McCallbd309292010-07-06 01:34:17 +0000928 // The fall-through block.
929 llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
Mike Stump58ef18b2009-11-20 23:44:51 +0000930
John McCallbd309292010-07-06 01:34:17 +0000931 // We just emitted the body of the try; jump to the continue block.
932 if (HaveInsertPoint())
933 Builder.CreateBr(ContBB);
Mike Stump97329152009-12-02 19:53:57 +0000934
John McCalld8d00be2012-06-15 05:27:05 +0000935 // Determine if we need an implicit rethrow for all these catch handlers;
936 // see the comment below.
937 bool doImplicitRethrow = false;
John McCallb609d3f2010-07-07 06:56:46 +0000938 if (IsFnTryBlock)
John McCalld8d00be2012-06-15 05:27:05 +0000939 doImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
940 isa<CXXConstructorDecl>(CurCodeDecl);
John McCallb609d3f2010-07-07 06:56:46 +0000941
John McCall8e4c74b2011-08-11 02:22:43 +0000942 // Perversely, we emit the handlers backwards precisely because we
943 // want them to appear in source order. In all of these cases, the
944 // catch block will have exactly one predecessor, which will be a
945 // particular block in the catch dispatch. However, in the case of
946 // a catch-all, one of the dispatch blocks will branch to two
947 // different handlers, and EmitBlockAfterUses will cause the second
948 // handler to be moved before the first.
949 for (unsigned I = NumHandlers; I != 0; --I) {
950 llvm::BasicBlock *CatchBlock = Handlers[I-1].Block;
951 EmitBlockAfterUses(CatchBlock);
Mike Stump75546b82009-12-10 00:06:18 +0000952
John McCallbd309292010-07-06 01:34:17 +0000953 // Catch the exception if this isn't a catch-all.
John McCall8e4c74b2011-08-11 02:22:43 +0000954 const CXXCatchStmt *C = S.getHandler(I-1);
Mike Stump58ef18b2009-11-20 23:44:51 +0000955
John McCallbd309292010-07-06 01:34:17 +0000956 // Enter a cleanup scope, including the catch variable and the
957 // end-catch.
958 RunCleanupsScope CatchScope(*this);
Mike Stump58ef18b2009-11-20 23:44:51 +0000959
John McCallbd309292010-07-06 01:34:17 +0000960 // Initialize the catch variable and set up the cleanups.
Reid Klecknerfff8e7f2015-03-03 19:21:04 +0000961 CGM.getCXXABI().emitBeginCatch(*this, C);
John McCallbd309292010-07-06 01:34:17 +0000962
Justin Bognerea278c32014-01-07 00:20:28 +0000963 // Emit the PGO counter increment.
Justin Bogner66242d62015-04-23 23:06:47 +0000964 incrementProfileCounter(C);
Justin Bogneref512b92014-01-06 22:27:43 +0000965
John McCallbd309292010-07-06 01:34:17 +0000966 // Perform the body of the catch.
967 EmitStmt(C->getHandlerBlock());
968
John McCalld8d00be2012-06-15 05:27:05 +0000969 // [except.handle]p11:
970 // The currently handled exception is rethrown if control
971 // reaches the end of a handler of the function-try-block of a
972 // constructor or destructor.
973
974 // It is important that we only do this on fallthrough and not on
975 // return. Note that it's illegal to put a return in a
976 // constructor function-try-block's catch handler (p14), so this
977 // really only applies to destructors.
978 if (doImplicitRethrow && HaveInsertPoint()) {
David Majnemer442d0a22014-11-25 07:20:20 +0000979 CGM.getCXXABI().emitRethrow(*this, /*isNoReturn*/false);
John McCalld8d00be2012-06-15 05:27:05 +0000980 Builder.CreateUnreachable();
981 Builder.ClearInsertionPoint();
982 }
983
John McCallbd309292010-07-06 01:34:17 +0000984 // Fall out through the catch cleanups.
985 CatchScope.ForceCleanup();
986
987 // Branch out of the try.
988 if (HaveInsertPoint())
989 Builder.CreateBr(ContBB);
Mike Stump58ef18b2009-11-20 23:44:51 +0000990 }
991
John McCallbd309292010-07-06 01:34:17 +0000992 EmitBlock(ContBB);
Justin Bogner66242d62015-04-23 23:06:47 +0000993 incrementProfileCounter(&S);
Mike Stump58ef18b2009-11-20 23:44:51 +0000994}
Mike Stumpaff69af2009-12-09 03:35:49 +0000995
John McCall1e670402010-07-21 00:52:03 +0000996namespace {
John McCallcda666c2010-07-21 07:22:38 +0000997 struct CallEndCatchForFinally : EHScopeStack::Cleanup {
John McCall1e670402010-07-21 00:52:03 +0000998 llvm::Value *ForEHVar;
999 llvm::Value *EndCatchFn;
1000 CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn)
1001 : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
1002
Craig Topper4f12f102014-03-12 06:41:41 +00001003 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall1e670402010-07-21 00:52:03 +00001004 llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
1005 llvm::BasicBlock *CleanupContBB =
1006 CGF.createBasicBlock("finally.cleanup.cont");
1007
1008 llvm::Value *ShouldEndCatch =
1009 CGF.Builder.CreateLoad(ForEHVar, "finally.endcatch");
1010 CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1011 CGF.EmitBlock(EndCatchBB);
John McCall882987f2013-02-28 19:01:20 +00001012 CGF.EmitRuntimeCallOrInvoke(EndCatchFn); // catch-all, so might throw
John McCall1e670402010-07-21 00:52:03 +00001013 CGF.EmitBlock(CleanupContBB);
1014 }
1015 };
John McCall906da4b2010-07-21 05:47:49 +00001016
John McCallcda666c2010-07-21 07:22:38 +00001017 struct PerformFinally : EHScopeStack::Cleanup {
John McCall906da4b2010-07-21 05:47:49 +00001018 const Stmt *Body;
1019 llvm::Value *ForEHVar;
1020 llvm::Value *EndCatchFn;
1021 llvm::Value *RethrowFn;
1022 llvm::Value *SavedExnVar;
1023
1024 PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
1025 llvm::Value *EndCatchFn,
1026 llvm::Value *RethrowFn, llvm::Value *SavedExnVar)
1027 : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1028 RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
1029
Craig Topper4f12f102014-03-12 06:41:41 +00001030 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall906da4b2010-07-21 05:47:49 +00001031 // Enter a cleanup to call the end-catch function if one was provided.
1032 if (EndCatchFn)
John McCallcda666c2010-07-21 07:22:38 +00001033 CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
1034 ForEHVar, EndCatchFn);
John McCall906da4b2010-07-21 05:47:49 +00001035
John McCallcebe0ca2010-08-11 00:16:14 +00001036 // Save the current cleanup destination in case there are
1037 // cleanups in the finally block.
1038 llvm::Value *SavedCleanupDest =
1039 CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
1040 "cleanup.dest.saved");
1041
John McCall906da4b2010-07-21 05:47:49 +00001042 // Emit the finally block.
1043 CGF.EmitStmt(Body);
1044
1045 // If the end of the finally is reachable, check whether this was
1046 // for EH. If so, rethrow.
1047 if (CGF.HaveInsertPoint()) {
1048 llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
1049 llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
1050
1051 llvm::Value *ShouldRethrow =
1052 CGF.Builder.CreateLoad(ForEHVar, "finally.shouldthrow");
1053 CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1054
1055 CGF.EmitBlock(RethrowBB);
1056 if (SavedExnVar) {
John McCall882987f2013-02-28 19:01:20 +00001057 CGF.EmitRuntimeCallOrInvoke(RethrowFn,
1058 CGF.Builder.CreateLoad(SavedExnVar));
John McCall906da4b2010-07-21 05:47:49 +00001059 } else {
John McCall882987f2013-02-28 19:01:20 +00001060 CGF.EmitRuntimeCallOrInvoke(RethrowFn);
John McCall906da4b2010-07-21 05:47:49 +00001061 }
1062 CGF.Builder.CreateUnreachable();
1063
1064 CGF.EmitBlock(ContBB);
John McCallcebe0ca2010-08-11 00:16:14 +00001065
1066 // Restore the cleanup destination.
1067 CGF.Builder.CreateStore(SavedCleanupDest,
1068 CGF.getNormalCleanupDestSlot());
John McCall906da4b2010-07-21 05:47:49 +00001069 }
1070
1071 // Leave the end-catch cleanup. As an optimization, pretend that
1072 // the fallthrough path was inaccessible; we've dynamically proven
1073 // that we're not in the EH case along that path.
1074 if (EndCatchFn) {
1075 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1076 CGF.PopCleanupBlock();
1077 CGF.Builder.restoreIP(SavedIP);
1078 }
1079
1080 // Now make sure we actually have an insertion point or the
1081 // cleanup gods will hate us.
1082 CGF.EnsureInsertPoint();
1083 }
1084 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001085}
John McCall1e670402010-07-21 00:52:03 +00001086
John McCallbd309292010-07-06 01:34:17 +00001087/// Enters a finally block for an implementation using zero-cost
1088/// exceptions. This is mostly general, but hard-codes some
1089/// language/ABI-specific behavior in the catch-all sections.
John McCall6b0feb72011-06-22 02:32:12 +00001090void CodeGenFunction::FinallyInfo::enter(CodeGenFunction &CGF,
1091 const Stmt *body,
1092 llvm::Constant *beginCatchFn,
1093 llvm::Constant *endCatchFn,
1094 llvm::Constant *rethrowFn) {
Craig Topper8a13c412014-05-21 05:09:00 +00001095 assert((beginCatchFn != nullptr) == (endCatchFn != nullptr) &&
John McCallbd309292010-07-06 01:34:17 +00001096 "begin/end catch functions not paired");
John McCall6b0feb72011-06-22 02:32:12 +00001097 assert(rethrowFn && "rethrow function is required");
1098
1099 BeginCatchFn = beginCatchFn;
Mike Stumpaff69af2009-12-09 03:35:49 +00001100
John McCallbd309292010-07-06 01:34:17 +00001101 // The rethrow function has one of the following two types:
1102 // void (*)()
1103 // void (*)(void*)
1104 // In the latter case we need to pass it the exception object.
1105 // But we can't use the exception slot because the @finally might
1106 // have a landing pad (which would overwrite the exception slot).
Chris Lattner2192fe52011-07-18 04:24:23 +00001107 llvm::FunctionType *rethrowFnTy =
John McCallbd309292010-07-06 01:34:17 +00001108 cast<llvm::FunctionType>(
John McCall6b0feb72011-06-22 02:32:12 +00001109 cast<llvm::PointerType>(rethrowFn->getType())->getElementType());
Craig Topper8a13c412014-05-21 05:09:00 +00001110 SavedExnVar = nullptr;
John McCall6b0feb72011-06-22 02:32:12 +00001111 if (rethrowFnTy->getNumParams())
1112 SavedExnVar = CGF.CreateTempAlloca(CGF.Int8PtrTy, "finally.exn");
Mike Stumpaff69af2009-12-09 03:35:49 +00001113
John McCallbd309292010-07-06 01:34:17 +00001114 // A finally block is a statement which must be executed on any edge
1115 // out of a given scope. Unlike a cleanup, the finally block may
1116 // contain arbitrary control flow leading out of itself. In
1117 // addition, finally blocks should always be executed, even if there
1118 // are no catch handlers higher on the stack. Therefore, we
1119 // surround the protected scope with a combination of a normal
1120 // cleanup (to catch attempts to break out of the block via normal
1121 // control flow) and an EH catch-all (semantically "outside" any try
1122 // statement to which the finally block might have been attached).
1123 // The finally block itself is generated in the context of a cleanup
1124 // which conditionally leaves the catch-all.
John McCall21886962010-04-21 10:05:39 +00001125
John McCallbd309292010-07-06 01:34:17 +00001126 // Jump destination for performing the finally block on an exception
1127 // edge. We'll never actually reach this block, so unreachable is
1128 // fine.
John McCall6b0feb72011-06-22 02:32:12 +00001129 RethrowDest = CGF.getJumpDestInCurrentScope(CGF.getUnreachableBlock());
John McCall21886962010-04-21 10:05:39 +00001130
John McCallbd309292010-07-06 01:34:17 +00001131 // Whether the finally block is being executed for EH purposes.
John McCall6b0feb72011-06-22 02:32:12 +00001132 ForEHVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "finally.for-eh");
1133 CGF.Builder.CreateStore(CGF.Builder.getFalse(), ForEHVar);
Mike Stumpaff69af2009-12-09 03:35:49 +00001134
John McCallbd309292010-07-06 01:34:17 +00001135 // Enter a normal cleanup which will perform the @finally block.
John McCall6b0feb72011-06-22 02:32:12 +00001136 CGF.EHStack.pushCleanup<PerformFinally>(NormalCleanup, body,
1137 ForEHVar, endCatchFn,
1138 rethrowFn, SavedExnVar);
John McCallbd309292010-07-06 01:34:17 +00001139
1140 // Enter a catch-all scope.
John McCall6b0feb72011-06-22 02:32:12 +00001141 llvm::BasicBlock *catchBB = CGF.createBasicBlock("finally.catchall");
1142 EHCatchScope *catchScope = CGF.EHStack.pushCatch(1);
1143 catchScope->setCatchAllHandler(0, catchBB);
John McCallbd309292010-07-06 01:34:17 +00001144}
1145
John McCall6b0feb72011-06-22 02:32:12 +00001146void CodeGenFunction::FinallyInfo::exit(CodeGenFunction &CGF) {
John McCallbd309292010-07-06 01:34:17 +00001147 // Leave the finally catch-all.
John McCall6b0feb72011-06-22 02:32:12 +00001148 EHCatchScope &catchScope = cast<EHCatchScope>(*CGF.EHStack.begin());
1149 llvm::BasicBlock *catchBB = catchScope.getHandler(0).Block;
John McCall8e4c74b2011-08-11 02:22:43 +00001150
1151 CGF.popCatchScope();
John McCallbd309292010-07-06 01:34:17 +00001152
John McCall6b0feb72011-06-22 02:32:12 +00001153 // If there are any references to the catch-all block, emit it.
1154 if (catchBB->use_empty()) {
1155 delete catchBB;
1156 } else {
1157 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveAndClearIP();
1158 CGF.EmitBlock(catchBB);
John McCallbd309292010-07-06 01:34:17 +00001159
Craig Topper8a13c412014-05-21 05:09:00 +00001160 llvm::Value *exn = nullptr;
John McCallbd309292010-07-06 01:34:17 +00001161
John McCall6b0feb72011-06-22 02:32:12 +00001162 // If there's a begin-catch function, call it.
1163 if (BeginCatchFn) {
Bill Wendling79a70e42011-09-15 18:57:19 +00001164 exn = CGF.getExceptionFromSlot();
John McCall882987f2013-02-28 19:01:20 +00001165 CGF.EmitNounwindRuntimeCall(BeginCatchFn, exn);
John McCall6b0feb72011-06-22 02:32:12 +00001166 }
1167
1168 // If we need to remember the exception pointer to rethrow later, do so.
1169 if (SavedExnVar) {
Bill Wendling79a70e42011-09-15 18:57:19 +00001170 if (!exn) exn = CGF.getExceptionFromSlot();
John McCall6b0feb72011-06-22 02:32:12 +00001171 CGF.Builder.CreateStore(exn, SavedExnVar);
1172 }
1173
1174 // Tell the cleanups in the finally block that we're do this for EH.
1175 CGF.Builder.CreateStore(CGF.Builder.getTrue(), ForEHVar);
1176
1177 // Thread a jump through the finally cleanup.
1178 CGF.EmitBranchThroughCleanup(RethrowDest);
1179
1180 CGF.Builder.restoreIP(savedIP);
1181 }
1182
1183 // Finally, leave the @finally cleanup.
1184 CGF.PopCleanupBlock();
John McCallbd309292010-07-06 01:34:17 +00001185}
1186
1187llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
1188 if (TerminateLandingPad)
1189 return TerminateLandingPad;
1190
1191 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1192
1193 // This will get inserted at the end of the function.
1194 TerminateLandingPad = createBasicBlock("terminate.lpad");
1195 Builder.SetInsertPoint(TerminateLandingPad);
1196
1197 // Tell the backend that this is a landing pad.
Reid Klecknerdeeddec2015-02-05 18:56:03 +00001198 const EHPersonality &Personality = EHPersonality::get(*this);
David Majnemerfcbdb6e2015-06-17 20:53:19 +00001199
1200 if (!CurFn->hasPersonalityFn())
1201 CurFn->setPersonalityFn(getOpaquePersonalityFn(CGM, Personality));
1202
1203 llvm::LandingPadInst *LPadInst = Builder.CreateLandingPad(
1204 llvm::StructType::get(Int8PtrTy, Int32Ty, nullptr), 0);
Bill Wendlingf0724e82011-09-19 20:31:14 +00001205 LPadInst->addClause(getCatchAllValue(*this));
John McCallbd309292010-07-06 01:34:17 +00001206
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00001207 llvm::Value *Exn = 0;
1208 if (getLangOpts().CPlusPlus)
1209 Exn = Builder.CreateExtractValue(LPadInst, 0);
1210 llvm::CallInst *terminateCall =
1211 CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
John McCalle142ad52013-02-12 03:51:46 +00001212 terminateCall->setDoesNotReturn();
John McCallad7c5c12011-02-08 08:22:06 +00001213 Builder.CreateUnreachable();
Mike Stumpaff69af2009-12-09 03:35:49 +00001214
John McCallbd309292010-07-06 01:34:17 +00001215 // Restore the saved insertion state.
1216 Builder.restoreIP(SavedIP);
John McCalldac3ea62010-04-30 00:06:43 +00001217
John McCallbd309292010-07-06 01:34:17 +00001218 return TerminateLandingPad;
Mike Stumpaff69af2009-12-09 03:35:49 +00001219}
Mike Stump2b488872009-12-09 22:59:31 +00001220
1221llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
Mike Stumpf5cbb082009-12-10 00:02:42 +00001222 if (TerminateHandler)
1223 return TerminateHandler;
1224
John McCallbd309292010-07-06 01:34:17 +00001225 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
Mike Stump25b20fc2009-12-09 23:31:35 +00001226
John McCallbd309292010-07-06 01:34:17 +00001227 // Set up the terminate handler. This block is inserted at the very
1228 // end of the function by FinishFunction.
Mike Stumpf5cbb082009-12-10 00:02:42 +00001229 TerminateHandler = createBasicBlock("terminate.handler");
John McCallbd309292010-07-06 01:34:17 +00001230 Builder.SetInsertPoint(TerminateHandler);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00001231 llvm::Value *Exn = 0;
1232 if (getLangOpts().CPlusPlus)
1233 Exn = getExceptionFromSlot();
1234 llvm::CallInst *terminateCall =
1235 CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
John McCallc84e4e92013-06-20 21:37:43 +00001236 terminateCall->setDoesNotReturn();
Mike Stump2b488872009-12-09 22:59:31 +00001237 Builder.CreateUnreachable();
1238
John McCall21886962010-04-21 10:05:39 +00001239 // Restore the saved insertion state.
John McCallbd309292010-07-06 01:34:17 +00001240 Builder.restoreIP(SavedIP);
Mike Stump25b20fc2009-12-09 23:31:35 +00001241
Mike Stump2b488872009-12-09 22:59:31 +00001242 return TerminateHandler;
1243}
John McCallbd309292010-07-06 01:34:17 +00001244
David Chisnall9a837be2012-11-07 16:50:40 +00001245llvm::BasicBlock *CodeGenFunction::getEHResumeBlock(bool isCleanup) {
John McCall8e4c74b2011-08-11 02:22:43 +00001246 if (EHResumeBlock) return EHResumeBlock;
John McCallad5d61e2010-07-23 21:56:41 +00001247
1248 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1249
1250 // We emit a jump to a notional label at the outermost unwind state.
John McCall8e4c74b2011-08-11 02:22:43 +00001251 EHResumeBlock = createBasicBlock("eh.resume");
1252 Builder.SetInsertPoint(EHResumeBlock);
John McCallad5d61e2010-07-23 21:56:41 +00001253
Reid Klecknerdeeddec2015-02-05 18:56:03 +00001254 const EHPersonality &Personality = EHPersonality::get(*this);
John McCallad5d61e2010-07-23 21:56:41 +00001255
1256 // This can always be a call because we necessarily didn't find
1257 // anything on the EH stack which needs our help.
Benjamin Kramer793bd552012-02-08 12:41:24 +00001258 const char *RethrowName = Personality.CatchallRethrowFn;
Craig Topper8a13c412014-05-21 05:09:00 +00001259 if (RethrowName != nullptr && !isCleanup) {
John McCall882987f2013-02-28 19:01:20 +00001260 EmitRuntimeCall(getCatchallRethrowFn(CGM, RethrowName),
Nico Weberff62a6a2015-02-26 22:34:33 +00001261 getExceptionFromSlot())->setDoesNotReturn();
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001262 Builder.CreateUnreachable();
1263 Builder.restoreIP(SavedIP);
1264 return EHResumeBlock;
John McCall9b382dd2011-05-28 21:13:02 +00001265 }
1266
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001267 // Recreate the landingpad's return value for the 'resume' instruction.
1268 llvm::Value *Exn = getExceptionFromSlot();
1269 llvm::Value *Sel = getSelectorFromSlot();
John McCallad5d61e2010-07-23 21:56:41 +00001270
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001271 llvm::Type *LPadType = llvm::StructType::get(Exn->getType(),
Reid Kleckneree7cf842014-12-01 22:02:27 +00001272 Sel->getType(), nullptr);
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001273 llvm::Value *LPadVal = llvm::UndefValue::get(LPadType);
1274 LPadVal = Builder.CreateInsertValue(LPadVal, Exn, 0, "lpad.val");
1275 LPadVal = Builder.CreateInsertValue(LPadVal, Sel, 1, "lpad.val");
1276
1277 Builder.CreateResume(LPadVal);
John McCallad5d61e2010-07-23 21:56:41 +00001278 Builder.restoreIP(SavedIP);
John McCall8e4c74b2011-08-11 02:22:43 +00001279 return EHResumeBlock;
John McCallad5d61e2010-07-23 21:56:41 +00001280}
Reid Kleckner543a16c2013-09-16 21:46:30 +00001281
1282void CodeGenFunction::EmitSEHTryStmt(const SEHTryStmt &S) {
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001283 EnterSEHTryStmt(S);
Reid Klecknera5930002015-02-11 21:40:48 +00001284 {
Nico Weber5779f842015-02-12 23:16:11 +00001285 JumpDest TryExit = getJumpDestInCurrentScope("__try.__leave");
Nico Weber5779f842015-02-12 23:16:11 +00001286
Reid Kleckner11c033e2015-02-12 23:40:45 +00001287 SEHTryEpilogueStack.push_back(&TryExit);
Reid Klecknera5930002015-02-11 21:40:48 +00001288 EmitStmt(S.getTryBlock());
Reid Kleckner11c033e2015-02-12 23:40:45 +00001289 SEHTryEpilogueStack.pop_back();
Nico Weber5779f842015-02-12 23:16:11 +00001290
1291 if (!TryExit.getBlock()->use_empty())
1292 EmitBlock(TryExit.getBlock(), /*IsFinished=*/true);
1293 else
1294 delete TryExit.getBlock();
Reid Klecknera5930002015-02-11 21:40:48 +00001295 }
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001296 ExitSEHTryStmt(S);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001297}
1298
1299namespace {
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001300struct PerformSEHFinally : EHScopeStack::Cleanup {
1301 llvm::Function *OutlinedFinally;
1302 PerformSEHFinally(llvm::Function *OutlinedFinally)
1303 : OutlinedFinally(OutlinedFinally) {}
Reid Kleckneraca01db2015-02-04 22:37:07 +00001304
Reid Kleckner1d59f992015-01-22 01:36:17 +00001305 void Emit(CodeGenFunction &CGF, Flags F) override {
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001306 ASTContext &Context = CGF.getContext();
Reid Kleckner0b9bbbf2015-06-09 17:49:42 +00001307 CodeGenModule &CGM = CGF.CGM;
Reid Kleckner65870442015-06-09 17:47:50 +00001308
Reid Klecknerd0d9a1f2015-07-01 17:10:10 +00001309 CallArgList Args;
Reid Klecknerd0d9a1f2015-07-01 17:10:10 +00001310
Reid Klecknereb11c412015-07-01 21:00:00 +00001311 // Compute the two argument values.
1312 QualType ArgTys[2] = {Context.UnsignedCharTy, Context.VoidPtrTy};
1313 llvm::Value *FrameAddr = CGM.getIntrinsic(llvm::Intrinsic::frameaddress);
1314 llvm::Value *FP =
1315 CGF.Builder.CreateCall(FrameAddr, {CGF.Builder.getInt32(0)});
1316 llvm::Value *IsForEH =
1317 llvm::ConstantInt::get(CGF.ConvertType(ArgTys[0]), F.isForEHCleanup());
1318 Args.add(RValue::get(IsForEH), ArgTys[0]);
1319 Args.add(RValue::get(FP), ArgTys[1]);
Reid Klecknerd0d9a1f2015-07-01 17:10:10 +00001320
Reid Klecknereb11c412015-07-01 21:00:00 +00001321 // Arrange a two-arg function info and type.
1322 FunctionProtoType::ExtProtoInfo EPI;
1323 const auto *FPT = cast<FunctionProtoType>(
1324 Context.getFunctionType(Context.VoidTy, ArgTys, EPI));
1325 const CGFunctionInfo &FnInfo =
1326 CGM.getTypes().arrangeFreeFunctionCall(Args, FPT,
1327 /*chainCall=*/false);
1328
1329 CGF.EmitCall(FnInfo, OutlinedFinally, ReturnValueSlot(), Args);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001330 }
1331};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001332}
Reid Kleckner1d59f992015-01-22 01:36:17 +00001333
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001334namespace {
1335/// Find all local variable captures in the statement.
1336struct CaptureFinder : ConstStmtVisitor<CaptureFinder> {
1337 CodeGenFunction &ParentCGF;
1338 const VarDecl *ParentThis;
1339 SmallVector<const VarDecl *, 4> Captures;
Reid Klecknerd0d9a1f2015-07-01 17:10:10 +00001340 llvm::Value *SEHCodeSlot = nullptr;
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001341 CaptureFinder(CodeGenFunction &ParentCGF, const VarDecl *ParentThis)
1342 : ParentCGF(ParentCGF), ParentThis(ParentThis) {}
1343
Reid Klecknerd0d9a1f2015-07-01 17:10:10 +00001344 // Return true if we need to do any capturing work.
1345 bool foundCaptures() {
Reid Klecknereb11c412015-07-01 21:00:00 +00001346 return !Captures.empty() || SEHCodeSlot;
Reid Klecknerd0d9a1f2015-07-01 17:10:10 +00001347 }
1348
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001349 void Visit(const Stmt *S) {
1350 // See if this is a capture, then recurse.
1351 ConstStmtVisitor<CaptureFinder>::Visit(S);
1352 for (const Stmt *Child : S->children())
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001353 if (Child)
1354 Visit(Child);
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001355 }
1356
1357 void VisitDeclRefExpr(const DeclRefExpr *E) {
1358 // If this is already a capture, just make sure we capture 'this'.
1359 if (E->refersToEnclosingVariableOrCapture()) {
1360 Captures.push_back(ParentThis);
1361 return;
1362 }
1363
1364 const auto *D = dyn_cast<VarDecl>(E->getDecl());
1365 if (D && D->isLocalVarDeclOrParm() && D->hasLocalStorage())
1366 Captures.push_back(D);
1367 }
1368
1369 void VisitCXXThisExpr(const CXXThisExpr *E) {
1370 Captures.push_back(ParentThis);
1371 }
Reid Klecknerd0d9a1f2015-07-01 17:10:10 +00001372
1373 void VisitCallExpr(const CallExpr *E) {
1374 // We only need to add parent frame allocations for these builtins in x86.
1375 if (ParentCGF.getTarget().getTriple().getArch() != llvm::Triple::x86)
1376 return;
1377
1378 unsigned ID = E->getBuiltinCallee();
1379 switch (ID) {
Reid Klecknerd0d9a1f2015-07-01 17:10:10 +00001380 case Builtin::BI__exception_code:
1381 case Builtin::BI_exception_code:
1382 // This is the simple case where we are the outermost finally. All we
1383 // have to do here is make sure we escape this and recover it in the
1384 // outlined handler.
1385 if (!SEHCodeSlot)
1386 SEHCodeSlot = ParentCGF.SEHCodeSlotStack.back();
1387 break;
1388 }
1389 }
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001390};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001391}
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001392
Reid Klecknerd0d9a1f2015-07-01 17:10:10 +00001393llvm::Value *CodeGenFunction::recoverAddrOfEscapedLocal(
1394 CodeGenFunction &ParentCGF, llvm::Value *ParentVar, llvm::Value *ParentFP) {
1395 llvm::CallInst *RecoverCall = nullptr;
1396 CGBuilderTy Builder(AllocaInsertPt);
1397 if (auto *ParentAlloca = dyn_cast<llvm::AllocaInst>(ParentVar)) {
1398 // Mark the variable escaped if nobody else referenced it and compute the
1399 // frameescape index.
1400 auto InsertPair = ParentCGF.EscapedLocals.insert(
1401 std::make_pair(ParentAlloca, ParentCGF.EscapedLocals.size()));
1402 int FrameEscapeIdx = InsertPair.first->second;
1403 // call i8* @llvm.framerecover(i8* bitcast(@parentFn), i8* %fp, i32 N)
1404 llvm::Function *FrameRecoverFn = llvm::Intrinsic::getDeclaration(
1405 &CGM.getModule(), llvm::Intrinsic::framerecover);
1406 llvm::Constant *ParentI8Fn =
1407 llvm::ConstantExpr::getBitCast(ParentCGF.CurFn, Int8PtrTy);
1408 RecoverCall = Builder.CreateCall(
1409 FrameRecoverFn, {ParentI8Fn, ParentFP,
1410 llvm::ConstantInt::get(Int32Ty, FrameEscapeIdx)});
1411
1412 } else {
1413 // If the parent didn't have an alloca, we're doing some nested outlining.
1414 // Just clone the existing framerecover call, but tweak the FP argument to
1415 // use our FP value. All other arguments are constants.
1416 auto *ParentRecover =
1417 cast<llvm::IntrinsicInst>(ParentVar->stripPointerCasts());
1418 assert(ParentRecover->getIntrinsicID() == llvm::Intrinsic::framerecover &&
1419 "expected alloca or framerecover in parent LocalDeclMap");
1420 RecoverCall = cast<llvm::CallInst>(ParentRecover->clone());
1421 RecoverCall->setArgOperand(1, ParentFP);
1422 RecoverCall->insertBefore(AllocaInsertPt);
1423 }
1424
1425 // Bitcast the variable, rename it, and insert it in the local decl map.
1426 llvm::Value *ChildVar =
1427 Builder.CreateBitCast(RecoverCall, ParentVar->getType());
1428 ChildVar->setName(ParentVar->getName());
1429 return ChildVar;
1430}
1431
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001432void CodeGenFunction::EmitCapturedLocals(CodeGenFunction &ParentCGF,
Reid Kleckner0b9bbbf2015-06-09 17:49:42 +00001433 const Stmt *OutlinedStmt,
Reid Klecknerd0d9a1f2015-07-01 17:10:10 +00001434 bool IsFilter) {
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001435 // Find all captures in the Stmt.
1436 CaptureFinder Finder(ParentCGF, ParentCGF.CXXABIThisDecl);
1437 Finder.Visit(OutlinedStmt);
1438
Reid Klecknerd0d9a1f2015-07-01 17:10:10 +00001439 // We can exit early on x86_64 when there are no captures. We just have to
1440 // save the exception code in filters so that __exception_code() works.
1441 if (!Finder.foundCaptures() &&
1442 CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
1443 if (IsFilter)
1444 EmitSEHExceptionCodeSave(ParentCGF, nullptr, nullptr);
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001445 return;
Reid Klecknerd0d9a1f2015-07-01 17:10:10 +00001446 }
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001447
Reid Klecknerd0d9a1f2015-07-01 17:10:10 +00001448 llvm::Value *EntryEBP = nullptr;
1449 llvm::Value *ParentFP;
1450 if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
1451 // On x64, the parent FP is passed as the second argument.
1452 auto AI = CurFn->arg_begin();
1453 ++AI;
1454 ParentFP = AI;
1455 } else {
1456 // The end of the EH registration is passed in as the EBP physical register.
1457 // We can recover that with llvm.frameaddress(1), and adjust that to
1458 // recover the parent's true frame pointer.
1459 CGBuilderTy Builder(AllocaInsertPt);
1460 EntryEBP = Builder.CreateCall(
1461 CGM.getIntrinsic(llvm::Intrinsic::frameaddress), {Builder.getInt32(1)});
1462 llvm::Function *RecoverFPIntrin =
1463 CGM.getIntrinsic(llvm::Intrinsic::x86_seh_recoverfp);
1464 llvm::Constant *ParentI8Fn =
1465 llvm::ConstantExpr::getBitCast(ParentCGF.CurFn, Int8PtrTy);
1466 ParentFP = Builder.CreateCall(RecoverFPIntrin, {ParentI8Fn, EntryEBP});
1467
1468 // Inlining will break llvm.frameaddress(1), so disable it.
1469 // FIXME: We could teach the inliner about the special meaning of
1470 // frameaddress, framerecover, and frameescape to remove this limitation.
1471 CurFn->addFnAttr(llvm::Attribute::NoInline);
1472 }
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001473
1474 // Create llvm.framerecover calls for all captures.
1475 for (const VarDecl *VD : Finder.Captures) {
1476 if (isa<ImplicitParamDecl>(VD)) {
1477 CGM.ErrorUnsupported(VD, "'this' captured by SEH");
1478 CXXThisValue = llvm::UndefValue::get(ConvertTypeForMem(VD->getType()));
1479 continue;
1480 }
1481 if (VD->getType()->isVariablyModifiedType()) {
1482 CGM.ErrorUnsupported(VD, "VLA captured by SEH");
1483 continue;
1484 }
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001485 assert((isa<ImplicitParamDecl>(VD) || VD->isLocalVarDeclOrParm()) &&
1486 "captured non-local variable");
1487
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001488 // If this decl hasn't been declared yet, it will be declared in the
1489 // OutlinedStmt.
1490 auto I = ParentCGF.LocalDeclMap.find(VD);
1491 if (I == ParentCGF.LocalDeclMap.end())
1492 continue;
1493 llvm::Value *ParentVar = I->second;
1494
Reid Klecknerd0d9a1f2015-07-01 17:10:10 +00001495 LocalDeclMap[VD] =
1496 recoverAddrOfEscapedLocal(ParentCGF, ParentVar, ParentFP);
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001497 }
Reid Klecknerd0d9a1f2015-07-01 17:10:10 +00001498
Reid Klecknerd0d9a1f2015-07-01 17:10:10 +00001499 if (Finder.SEHCodeSlot) {
1500 SEHCodeSlotStack.push_back(
1501 recoverAddrOfEscapedLocal(ParentCGF, Finder.SEHCodeSlot, ParentFP));
1502 }
1503
1504 if (IsFilter)
1505 EmitSEHExceptionCodeSave(ParentCGF, ParentFP, EntryEBP);
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001506}
1507
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001508/// Arrange a function prototype that can be called by Windows exception
1509/// handling personalities. On Win64, the prototype looks like:
1510/// RetTy func(void *EHPtrs, void *ParentFP);
1511void CodeGenFunction::startOutlinedSEHHelper(CodeGenFunction &ParentCGF,
Reid Klecknerd0d9a1f2015-07-01 17:10:10 +00001512 bool IsFilter,
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001513 const Stmt *OutlinedStmt) {
Reid Klecknerd0d9a1f2015-07-01 17:10:10 +00001514 SourceLocation StartLoc = OutlinedStmt->getLocStart();
1515
1516 // Get the mangled function name.
1517 SmallString<128> Name;
1518 {
1519 llvm::raw_svector_ostream OS(Name);
1520 const Decl *ParentCodeDecl = ParentCGF.CurCodeDecl;
1521 const NamedDecl *Parent = dyn_cast_or_null<NamedDecl>(ParentCodeDecl);
1522 assert(Parent && "FIXME: handle unnamed decls (lambdas, blocks) with SEH");
1523 MangleContext &Mangler = CGM.getCXXABI().getMangleContext();
1524 if (IsFilter)
1525 Mangler.mangleSEHFilterExpression(Parent, OS);
1526 else
1527 Mangler.mangleSEHFinallyBlock(Parent, OS);
1528 }
1529
1530 FunctionArgList Args;
Reid Klecknereb11c412015-07-01 21:00:00 +00001531 if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86 || !IsFilter) {
1532 // All SEH finally functions take two parameters. Win64 filters take two
1533 // parameters. Win32 filters take no parameters.
Reid Klecknerd0d9a1f2015-07-01 17:10:10 +00001534 if (IsFilter) {
1535 Args.push_back(ImplicitParamDecl::Create(
1536 getContext(), nullptr, StartLoc,
1537 &getContext().Idents.get("exception_pointers"),
1538 getContext().VoidPtrTy));
1539 } else {
1540 Args.push_back(ImplicitParamDecl::Create(
1541 getContext(), nullptr, StartLoc,
1542 &getContext().Idents.get("abnormal_termination"),
1543 getContext().UnsignedCharTy));
1544 }
1545 Args.push_back(ImplicitParamDecl::Create(
1546 getContext(), nullptr, StartLoc,
1547 &getContext().Idents.get("frame_pointer"), getContext().VoidPtrTy));
1548 }
1549
1550 QualType RetTy = IsFilter ? getContext().LongTy : getContext().VoidTy;
1551
Reid Kleckner1d59f992015-01-22 01:36:17 +00001552 llvm::Function *ParentFn = ParentCGF.CurFn;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001553 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionDeclaration(
1554 RetTy, Args, FunctionType::ExtInfo(), /*isVariadic=*/false);
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001555
Reid Kleckner1d59f992015-01-22 01:36:17 +00001556 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001557 llvm::Function *Fn = llvm::Function::Create(
1558 FnTy, llvm::GlobalValue::InternalLinkage, Name.str(), &CGM.getModule());
Reid Kleckner1d59f992015-01-22 01:36:17 +00001559 // The filter is either in the same comdat as the function, or it's internal.
1560 if (llvm::Comdat *C = ParentFn->getComdat()) {
1561 Fn->setComdat(C);
1562 } else if (ParentFn->hasWeakLinkage() || ParentFn->hasLinkOnceLinkage()) {
Reid Kleckner1d59f992015-01-22 01:36:17 +00001563 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(ParentFn->getName());
1564 ParentFn->setComdat(C);
1565 Fn->setComdat(C);
1566 } else {
1567 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
1568 }
1569
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001570 IsOutlinedSEHHelper = true;
Nico Weberf2a39a72015-04-13 20:03:03 +00001571
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001572 StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args,
1573 OutlinedStmt->getLocStart(), OutlinedStmt->getLocStart());
1574
1575 CGM.SetLLVMFunctionAttributes(nullptr, FnInfo, CurFn);
Reid Klecknerd0d9a1f2015-07-01 17:10:10 +00001576 EmitCapturedLocals(ParentCGF, OutlinedStmt, IsFilter);
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001577}
1578
1579/// Create a stub filter function that will ultimately hold the code of the
1580/// filter expression. The EH preparation passes in LLVM will outline the code
1581/// from the main function body into this stub.
1582llvm::Function *
1583CodeGenFunction::GenerateSEHFilterFunction(CodeGenFunction &ParentCGF,
1584 const SEHExceptStmt &Except) {
1585 const Expr *FilterExpr = Except.getFilterExpr();
Reid Klecknerd0d9a1f2015-07-01 17:10:10 +00001586 startOutlinedSEHHelper(ParentCGF, true, FilterExpr);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001587
1588 // Emit the original filter expression, convert to i32, and return.
1589 llvm::Value *R = EmitScalarExpr(FilterExpr);
David Majnemer2ccba832015-04-17 06:57:25 +00001590 R = Builder.CreateIntCast(R, ConvertType(getContext().LongTy),
Reid Kleckner1d59f992015-01-22 01:36:17 +00001591 FilterExpr->getType()->isSignedIntegerType());
1592 Builder.CreateStore(R, ReturnValue);
1593
1594 FinishFunction(FilterExpr->getLocEnd());
1595
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001596 return CurFn;
1597}
1598
1599llvm::Function *
1600CodeGenFunction::GenerateSEHFinallyFunction(CodeGenFunction &ParentCGF,
1601 const SEHFinallyStmt &Finally) {
1602 const Stmt *FinallyBlock = Finally.getBlock();
Reid Klecknerd0d9a1f2015-07-01 17:10:10 +00001603 startOutlinedSEHHelper(ParentCGF, false, FinallyBlock);
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001604
Reid Klecknerd0d9a1f2015-07-01 17:10:10 +00001605 // Mark finally block calls as nounwind and noinline to make LLVM's job a
1606 // little easier.
1607 // FIXME: Remove these restrictions in the future.
1608 CurFn->addFnAttr(llvm::Attribute::NoUnwind);
1609 CurFn->addFnAttr(llvm::Attribute::NoInline);
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001610
1611 // Emit the original filter expression, convert to i32, and return.
1612 EmitStmt(FinallyBlock);
1613
1614 FinishFunction(FinallyBlock->getLocEnd());
1615
1616 return CurFn;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001617}
1618
Reid Klecknerd0d9a1f2015-07-01 17:10:10 +00001619void CodeGenFunction::EmitSEHExceptionCodeSave(CodeGenFunction &ParentCGF,
1620 llvm::Value *ParentFP,
1621 llvm::Value *EntryEBP) {
1622 // Get the pointer to the EXCEPTION_POINTERS struct. This is returned by the
1623 // __exception_info intrinsic.
1624 if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
1625 // On Win64, the info is passed as the first parameter to the filter.
1626 auto AI = CurFn->arg_begin();
1627 SEHInfo = AI;
1628 SEHCodeSlotStack.push_back(
1629 CreateMemTemp(getContext().IntTy, "__exception_code"));
1630 } else {
1631 // On Win32, the EBP on entry to the filter points to the end of an
1632 // exception registration object. It contains 6 32-bit fields, and the info
1633 // pointer is stored in the second field. So, GEP 20 bytes backwards and
1634 // load the pointer.
1635 SEHInfo = Builder.CreateConstInBoundsGEP1_32(Int8Ty, EntryEBP, -20);
1636 SEHInfo = Builder.CreateBitCast(SEHInfo, Int8PtrTy->getPointerTo());
1637 SEHInfo = Builder.CreateLoad(Int8PtrTy, SEHInfo);
1638 SEHCodeSlotStack.push_back(recoverAddrOfEscapedLocal(
1639 ParentCGF, ParentCGF.SEHCodeSlotStack.back(), ParentFP));
1640 }
1641
Reid Kleckner1d59f992015-01-22 01:36:17 +00001642 // Save the exception code in the exception slot to unify exception access in
1643 // the filter function and the landing pad.
1644 // struct EXCEPTION_POINTERS {
1645 // EXCEPTION_RECORD *ExceptionRecord;
1646 // CONTEXT *ContextRecord;
1647 // };
Reid Klecknerd0d9a1f2015-07-01 17:10:10 +00001648 // int exceptioncode = exception_pointers->ExceptionRecord->ExceptionCode;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001649 llvm::Type *RecordTy = CGM.Int32Ty->getPointerTo();
1650 llvm::Type *PtrsTy = llvm::StructType::get(RecordTy, CGM.VoidPtrTy, nullptr);
Reid Klecknerd0d9a1f2015-07-01 17:10:10 +00001651 llvm::Value *Ptrs = Builder.CreateBitCast(SEHInfo, PtrsTy->getPointerTo());
David Blaikie1ed728c2015-04-05 22:45:47 +00001652 llvm::Value *Rec = Builder.CreateStructGEP(PtrsTy, Ptrs, 0);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001653 Rec = Builder.CreateLoad(Rec);
1654 llvm::Value *Code = Builder.CreateLoad(Rec);
Reid Klecknerd0d9a1f2015-07-01 17:10:10 +00001655 assert(!SEHCodeSlotStack.empty() && "emitting EH code outside of __except");
1656 Builder.CreateStore(Code, SEHCodeSlotStack.back());
Reid Kleckner1d59f992015-01-22 01:36:17 +00001657}
1658
1659llvm::Value *CodeGenFunction::EmitSEHExceptionInfo() {
1660 // Sema should diagnose calling this builtin outside of a filter context, but
1661 // don't crash if we screw up.
Reid Klecknerd0d9a1f2015-07-01 17:10:10 +00001662 if (!SEHInfo)
Reid Kleckner1d59f992015-01-22 01:36:17 +00001663 return llvm::UndefValue::get(Int8PtrTy);
Reid Klecknerd0d9a1f2015-07-01 17:10:10 +00001664 assert(SEHInfo->getType() == Int8PtrTy);
1665 return SEHInfo;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001666}
1667
1668llvm::Value *CodeGenFunction::EmitSEHExceptionCode() {
Reid Klecknerd0d9a1f2015-07-01 17:10:10 +00001669 assert(!SEHCodeSlotStack.empty() && "emitting EH code outside of __except");
1670 return Builder.CreateLoad(Int32Ty, SEHCodeSlotStack.back());
Reid Kleckner1d59f992015-01-22 01:36:17 +00001671}
1672
Reid Kleckneraca01db2015-02-04 22:37:07 +00001673llvm::Value *CodeGenFunction::EmitSEHAbnormalTermination() {
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001674 // Abnormal termination is just the first parameter to the outlined finally
1675 // helper.
1676 auto AI = CurFn->arg_begin();
1677 return Builder.CreateZExt(&*AI, Int32Ty);
Reid Kleckneraca01db2015-02-04 22:37:07 +00001678}
1679
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001680void CodeGenFunction::EnterSEHTryStmt(const SEHTryStmt &S) {
1681 CodeGenFunction HelperCGF(CGM, /*suppressNewContext=*/true);
1682 if (const SEHFinallyStmt *Finally = S.getFinallyHandler()) {
Reid Klecknerd0d9a1f2015-07-01 17:10:10 +00001683 // Outline the finally block.
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001684 llvm::Function *FinallyFunc =
1685 HelperCGF.GenerateSEHFinallyFunction(*this, *Finally);
Reid Klecknerd0d9a1f2015-07-01 17:10:10 +00001686
Reid Klecknerd0d9a1f2015-07-01 17:10:10 +00001687 // Push a cleanup for __finally blocks.
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001688 EHStack.pushCleanup<PerformSEHFinally>(NormalAndEHCleanup, FinallyFunc);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001689 return;
1690 }
1691
1692 // Otherwise, we must have an __except block.
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001693 const SEHExceptStmt *Except = S.getExceptHandler();
Reid Kleckner1d59f992015-01-22 01:36:17 +00001694 assert(Except);
1695 EHCatchScope *CatchScope = EHStack.pushCatch(1);
Reid Klecknerd0d9a1f2015-07-01 17:10:10 +00001696 SEHCodeSlotStack.push_back(
1697 CreateMemTemp(getContext().IntTy, "__exception_code"));
Reid Kleckner2a2e1562015-01-22 02:25:56 +00001698
Reid Klecknerd0d9a1f2015-07-01 17:10:10 +00001699 // If the filter is known to evaluate to 1, then we can use the clause
1700 // "catch i8* null". We can't do this on x86 because the filter has to save
1701 // the exception code.
Reid Kleckner2a2e1562015-01-22 02:25:56 +00001702 llvm::Constant *C =
1703 CGM.EmitConstantExpr(Except->getFilterExpr(), getContext().IntTy, this);
Reid Klecknerd0d9a1f2015-07-01 17:10:10 +00001704 if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86 && C &&
1705 C->isOneValue()) {
Reid Kleckner2a2e1562015-01-22 02:25:56 +00001706 CatchScope->setCatchAllHandler(0, createBasicBlock("__except"));
1707 return;
1708 }
1709
1710 // In general, we have to emit an outlined filter function. Use the function
1711 // in place of the RTTI typeinfo global that C++ EH uses.
Reid Kleckner1d59f992015-01-22 01:36:17 +00001712 llvm::Function *FilterFunc =
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001713 HelperCGF.GenerateSEHFilterFunction(*this, *Except);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001714 llvm::Constant *OpaqueFunc =
1715 llvm::ConstantExpr::getBitCast(FilterFunc, Int8PtrTy);
1716 CatchScope->setHandler(0, OpaqueFunc, createBasicBlock("__except"));
1717}
1718
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001719void CodeGenFunction::ExitSEHTryStmt(const SEHTryStmt &S) {
Reid Kleckner1d59f992015-01-22 01:36:17 +00001720 // Just pop the cleanup if it's a __finally block.
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001721 if (S.getFinallyHandler()) {
Reid Kleckner1d59f992015-01-22 01:36:17 +00001722 PopCleanupBlock();
1723 return;
1724 }
1725
1726 // Otherwise, we must have an __except block.
Reid Kleckneraca01db2015-02-04 22:37:07 +00001727 const SEHExceptStmt *Except = S.getExceptHandler();
Reid Kleckner1d59f992015-01-22 01:36:17 +00001728 assert(Except && "__try must have __finally xor __except");
1729 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1730
1731 // Don't emit the __except block if the __try block lacked invokes.
1732 // TODO: Model unwind edges from instructions, either with iload / istore or
1733 // a try body function.
1734 if (!CatchScope.hasEHBranches()) {
1735 CatchScope.clearHandlerBlocks();
1736 EHStack.popCatch();
Reid Klecknerd0d9a1f2015-07-01 17:10:10 +00001737 SEHCodeSlotStack.pop_back();
Reid Kleckner1d59f992015-01-22 01:36:17 +00001738 return;
1739 }
1740
1741 // The fall-through block.
1742 llvm::BasicBlock *ContBB = createBasicBlock("__try.cont");
1743
1744 // We just emitted the body of the __try; jump to the continue block.
1745 if (HaveInsertPoint())
1746 Builder.CreateBr(ContBB);
1747
1748 // Check if our filter function returned true.
1749 emitCatchDispatchBlock(*this, CatchScope);
1750
1751 // Grab the block before we pop the handler.
1752 llvm::BasicBlock *ExceptBB = CatchScope.getHandler(0).Block;
1753 EHStack.popCatch();
1754
1755 EmitBlockAfterUses(ExceptBB);
1756
Reid Klecknerd0d9a1f2015-07-01 17:10:10 +00001757 // On Win64, the exception pointer is the exception code. Copy it to the slot.
1758 if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
1759 llvm::Value *Code =
1760 Builder.CreatePtrToInt(getExceptionFromSlot(), IntPtrTy);
1761 Code = Builder.CreateTrunc(Code, Int32Ty);
1762 Builder.CreateStore(Code, SEHCodeSlotStack.back());
1763 }
1764
Reid Kleckner1d59f992015-01-22 01:36:17 +00001765 // Emit the __except body.
1766 EmitStmt(Except->getBlock());
1767
Reid Klecknerd0d9a1f2015-07-01 17:10:10 +00001768 // End the lifetime of the exception code.
1769 SEHCodeSlotStack.pop_back();
1770
Reid Kleckner3a417c32015-01-30 22:16:45 +00001771 if (HaveInsertPoint())
1772 Builder.CreateBr(ContBB);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001773
1774 EmitBlock(ContBB);
Reid Kleckner543a16c2013-09-16 21:46:30 +00001775}
Nico Weber9b982072014-07-07 00:12:30 +00001776
1777void CodeGenFunction::EmitSEHLeaveStmt(const SEHLeaveStmt &S) {
Nico Weber5779f842015-02-12 23:16:11 +00001778 // If this code is reachable then emit a stop point (if generating
1779 // debug info). We have to do this ourselves because we are on the
1780 // "simple" statement path.
1781 if (HaveInsertPoint())
1782 EmitStopPoint(&S);
1783
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001784 // This must be a __leave from a __finally block, which we warn on and is UB.
1785 // Just emit unreachable.
1786 if (!isSEHTryScope()) {
1787 Builder.CreateUnreachable();
1788 Builder.ClearInsertionPoint();
1789 return;
1790 }
1791
Nico Weber5779f842015-02-12 23:16:11 +00001792 EmitBranchThroughCleanup(*SEHTryEpilogueStack.back());
Nico Weber9b982072014-07-07 00:12:30 +00001793}