blob: ae47efe1ada704b91398decba538273bf0e0f359 [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 Kleckneraf676022015-04-30 22:13:05 +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 Majnemerdbdab402015-02-25 23:01:21 +000064 name = "\01?terminate@@YAXXZ";
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000065 } else if (getLangOpts().ObjC1 &&
66 getLangOpts().ObjCRuntime.hasTerminate())
John McCall9de19782011-07-06 01:22:26 +000067 name = "objc_terminate";
68 else
69 name = "abort";
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000070 return CreateRuntimeFunction(FTy, name);
David Chisnallf9c42252010-05-17 13:49:20 +000071}
72
John McCall2c33ba82013-02-12 03:51:38 +000073static llvm::Constant *getCatchallRethrowFn(CodeGenModule &CGM,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000074 StringRef Name) {
Chris Lattner2192fe52011-07-18 04:24:23 +000075 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +000076 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
John McCall36ea3722010-07-17 00:43:08 +000077
John McCall2c33ba82013-02-12 03:51:38 +000078 return CGM.CreateRuntimeFunction(FTy, Name);
John McCallbd309292010-07-06 01:34:17 +000079}
80
Benjamin Kramer793bd552012-02-08 12:41:24 +000081namespace {
82 /// The exceptions personality for a function.
83 struct EHPersonality {
84 const char *PersonalityFn;
85
86 // If this is non-null, this personality requires a non-standard
87 // function for rethrowing an exception after a catchall cleanup.
88 // This function must have prototype void(void*).
89 const char *CatchallRethrowFn;
90
Reid Klecknerdeeddec2015-02-05 18:56:03 +000091 static const EHPersonality &get(CodeGenModule &CGM,
92 const FunctionDecl *FD);
93 static const EHPersonality &get(CodeGenFunction &CGF) {
94 return get(CGF.CGM, dyn_cast_or_null<FunctionDecl>(CGF.CurCodeDecl));
95 }
96
Benjamin Kramer793bd552012-02-08 12:41:24 +000097 static const EHPersonality GNU_C;
98 static const EHPersonality GNU_C_SJLJ;
Reid Kleckner8f45c9c2014-09-15 17:19:16 +000099 static const EHPersonality GNU_C_SEH;
Benjamin Kramer793bd552012-02-08 12:41:24 +0000100 static const EHPersonality GNU_ObjC;
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000101 static const EHPersonality GNUstep_ObjC;
Benjamin Kramer793bd552012-02-08 12:41:24 +0000102 static const EHPersonality GNU_ObjCXX;
103 static const EHPersonality NeXT_ObjC;
104 static const EHPersonality GNU_CPlusPlus;
105 static const EHPersonality GNU_CPlusPlus_SJLJ;
Reid Kleckner8f45c9c2014-09-15 17:19:16 +0000106 static const EHPersonality GNU_CPlusPlus_SEH;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000107 static const EHPersonality MSVC_except_handler;
108 static const EHPersonality MSVC_C_specific_handler;
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000109 static const EHPersonality MSVC_CxxFrameHandler3;
Benjamin Kramer793bd552012-02-08 12:41:24 +0000110 };
111}
112
Craig Topper8a13c412014-05-21 05:09:00 +0000113const EHPersonality EHPersonality::GNU_C = { "__gcc_personality_v0", nullptr };
Benjamin Kramer793bd552012-02-08 12:41:24 +0000114const EHPersonality
Craig Topper8a13c412014-05-21 05:09:00 +0000115EHPersonality::GNU_C_SJLJ = { "__gcc_personality_sj0", nullptr };
116const EHPersonality
Reid Kleckner8f45c9c2014-09-15 17:19:16 +0000117EHPersonality::GNU_C_SEH = { "__gcc_personality_seh0", nullptr };
118const EHPersonality
Craig Topper8a13c412014-05-21 05:09:00 +0000119EHPersonality::NeXT_ObjC = { "__objc_personality_v0", nullptr };
120const EHPersonality
121EHPersonality::GNU_CPlusPlus = { "__gxx_personality_v0", nullptr };
122const EHPersonality
123EHPersonality::GNU_CPlusPlus_SJLJ = { "__gxx_personality_sj0", nullptr };
Benjamin Kramer793bd552012-02-08 12:41:24 +0000124const EHPersonality
Reid Kleckner8f45c9c2014-09-15 17:19:16 +0000125EHPersonality::GNU_CPlusPlus_SEH = { "__gxx_personality_seh0", nullptr };
126const EHPersonality
Benjamin Kramer793bd552012-02-08 12:41:24 +0000127EHPersonality::GNU_ObjC = {"__gnu_objc_personality_v0", "objc_exception_throw"};
128const EHPersonality
Craig Topper8a13c412014-05-21 05:09:00 +0000129EHPersonality::GNU_ObjCXX = { "__gnustep_objcxx_personality_v0", nullptr };
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000130const EHPersonality
Craig Topper8a13c412014-05-21 05:09:00 +0000131EHPersonality::GNUstep_ObjC = { "__gnustep_objc_personality_v0", nullptr };
Reid Kleckner1d59f992015-01-22 01:36:17 +0000132const EHPersonality
133EHPersonality::MSVC_except_handler = { "_except_handler3", nullptr };
134const EHPersonality
135EHPersonality::MSVC_C_specific_handler = { "__C_specific_handler", nullptr };
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000136const EHPersonality
137EHPersonality::MSVC_CxxFrameHandler3 = { "__CxxFrameHandler3", nullptr };
John McCall36ea3722010-07-17 00:43:08 +0000138
Reid Klecknere070b992014-11-14 02:01:10 +0000139/// On Win64, use libgcc's SEH personality function. We fall back to dwarf on
140/// other platforms, unless the user asked for SjLj exceptions.
141static bool useLibGCCSEHPersonality(const llvm::Triple &T) {
142 return T.isOSWindows() && T.getArch() == llvm::Triple::x86_64;
143}
144
145static const EHPersonality &getCPersonality(const llvm::Triple &T,
146 const LangOptions &L) {
John McCall2faab302010-11-07 02:35:25 +0000147 if (L.SjLjExceptions)
148 return EHPersonality::GNU_C_SJLJ;
Reid Klecknere070b992014-11-14 02:01:10 +0000149 else if (useLibGCCSEHPersonality(T))
Reid Kleckner8f45c9c2014-09-15 17:19:16 +0000150 return EHPersonality::GNU_C_SEH;
John McCall36ea3722010-07-17 00:43:08 +0000151 return EHPersonality::GNU_C;
152}
153
Reid Klecknere070b992014-11-14 02:01:10 +0000154static const EHPersonality &getObjCPersonality(const llvm::Triple &T,
155 const LangOptions &L) {
John McCall5fb5df92012-06-20 06:18:46 +0000156 switch (L.ObjCRuntime.getKind()) {
157 case ObjCRuntime::FragileMacOSX:
Reid Klecknere070b992014-11-14 02:01:10 +0000158 return getCPersonality(T, L);
John McCall5fb5df92012-06-20 06:18:46 +0000159 case ObjCRuntime::MacOSX:
160 case ObjCRuntime::iOS:
161 return EHPersonality::NeXT_ObjC;
David Chisnallb601c962012-07-03 20:49:52 +0000162 case ObjCRuntime::GNUstep:
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000163 if (L.ObjCRuntime.getVersion() >= VersionTuple(1, 7))
164 return EHPersonality::GNUstep_ObjC;
165 // fallthrough
David Chisnallb601c962012-07-03 20:49:52 +0000166 case ObjCRuntime::GCC:
John McCall775086e2012-07-12 02:07:58 +0000167 case ObjCRuntime::ObjFW:
John McCall36ea3722010-07-17 00:43:08 +0000168 return EHPersonality::GNU_ObjC;
John McCallbd309292010-07-06 01:34:17 +0000169 }
John McCall5fb5df92012-06-20 06:18:46 +0000170 llvm_unreachable("bad runtime kind");
John McCallbd309292010-07-06 01:34:17 +0000171}
172
Reid Klecknere070b992014-11-14 02:01:10 +0000173static const EHPersonality &getCXXPersonality(const llvm::Triple &T,
174 const LangOptions &L) {
John McCall36ea3722010-07-17 00:43:08 +0000175 if (L.SjLjExceptions)
176 return EHPersonality::GNU_CPlusPlus_SJLJ;
Reid Klecknere070b992014-11-14 02:01:10 +0000177 else if (useLibGCCSEHPersonality(T))
Reid Kleckner8f45c9c2014-09-15 17:19:16 +0000178 return EHPersonality::GNU_CPlusPlus_SEH;
Reid Klecknere070b992014-11-14 02:01:10 +0000179 return EHPersonality::GNU_CPlusPlus;
John McCallbd309292010-07-06 01:34:17 +0000180}
181
182/// Determines the personality function to use when both C++
183/// and Objective-C exceptions are being caught.
Reid Klecknere070b992014-11-14 02:01:10 +0000184static const EHPersonality &getObjCXXPersonality(const llvm::Triple &T,
185 const LangOptions &L) {
John McCall5fb5df92012-06-20 06:18:46 +0000186 switch (L.ObjCRuntime.getKind()) {
John McCallbd309292010-07-06 01:34:17 +0000187 // The ObjC personality defers to the C++ personality for non-ObjC
188 // handlers. Unlike the C++ case, we use the same personality
189 // function on targets using (backend-driven) SJLJ EH.
John McCall5fb5df92012-06-20 06:18:46 +0000190 case ObjCRuntime::MacOSX:
191 case ObjCRuntime::iOS:
192 return EHPersonality::NeXT_ObjC;
John McCallbd309292010-07-06 01:34:17 +0000193
John McCall5fb5df92012-06-20 06:18:46 +0000194 // In the fragile ABI, just use C++ exception handling and hope
195 // they're not doing crazy exception mixing.
196 case ObjCRuntime::FragileMacOSX:
Reid Klecknere070b992014-11-14 02:01:10 +0000197 return getCXXPersonality(T, L);
David Chisnallf9c42252010-05-17 13:49:20 +0000198
David Chisnallb601c962012-07-03 20:49:52 +0000199 // The GCC runtime's personality function inherently doesn't support
John McCall36ea3722010-07-17 00:43:08 +0000200 // mixed EH. Use the C++ personality just to avoid returning null.
David Chisnallb601c962012-07-03 20:49:52 +0000201 case ObjCRuntime::GCC:
John McCall775086e2012-07-12 02:07:58 +0000202 case ObjCRuntime::ObjFW: // XXX: this will change soon
David Chisnallb601c962012-07-03 20:49:52 +0000203 return EHPersonality::GNU_ObjC;
204 case ObjCRuntime::GNUstep:
John McCall5fb5df92012-06-20 06:18:46 +0000205 return EHPersonality::GNU_ObjCXX;
206 }
207 llvm_unreachable("bad runtime kind");
John McCallbd309292010-07-06 01:34:17 +0000208}
209
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000210static const EHPersonality &getSEHPersonalityMSVC(const llvm::Triple &T) {
Reid Kleckner1d59f992015-01-22 01:36:17 +0000211 if (T.getArch() == llvm::Triple::x86)
212 return EHPersonality::MSVC_except_handler;
213 return EHPersonality::MSVC_C_specific_handler;
214}
215
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000216const EHPersonality &EHPersonality::get(CodeGenModule &CGM,
217 const FunctionDecl *FD) {
Reid Klecknere070b992014-11-14 02:01:10 +0000218 const llvm::Triple &T = CGM.getTarget().getTriple();
219 const LangOptions &L = CGM.getLangOpts();
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000220
Reid Kleckner1d59f992015-01-22 01:36:17 +0000221 // Try to pick a personality function that is compatible with MSVC if we're
222 // not compiling Obj-C. Obj-C users better have an Obj-C runtime that supports
223 // the GCC-style personality function.
224 if (T.isWindowsMSVCEnvironment() && !L.ObjC1) {
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000225 if (L.SjLjExceptions)
226 return EHPersonality::GNU_CPlusPlus_SJLJ;
227 else if (FD && FD->usesSEHTry())
228 return getSEHPersonalityMSVC(T);
Reid Kleckner1d59f992015-01-22 01:36:17 +0000229 else
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000230 return EHPersonality::MSVC_CxxFrameHandler3;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000231 }
232
John McCall36ea3722010-07-17 00:43:08 +0000233 if (L.CPlusPlus && L.ObjC1)
Reid Klecknere070b992014-11-14 02:01:10 +0000234 return getObjCXXPersonality(T, L);
John McCall36ea3722010-07-17 00:43:08 +0000235 else if (L.CPlusPlus)
Reid Klecknere070b992014-11-14 02:01:10 +0000236 return getCXXPersonality(T, L);
John McCall36ea3722010-07-17 00:43:08 +0000237 else if (L.ObjC1)
Reid Klecknere070b992014-11-14 02:01:10 +0000238 return getObjCPersonality(T, L);
John McCallbd309292010-07-06 01:34:17 +0000239 else
Reid Klecknere070b992014-11-14 02:01:10 +0000240 return getCPersonality(T, L);
John McCall36ea3722010-07-17 00:43:08 +0000241}
John McCallbd309292010-07-06 01:34:17 +0000242
John McCall0bdb1fd2010-09-16 06:16:50 +0000243static llvm::Constant *getPersonalityFn(CodeGenModule &CGM,
John McCall36ea3722010-07-17 00:43:08 +0000244 const EHPersonality &Personality) {
John McCall36ea3722010-07-17 00:43:08 +0000245 llvm::Constant *Fn =
Chris Lattnerece04092012-02-07 00:39:47 +0000246 CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.Int32Ty, true),
Benjamin Kramer793bd552012-02-08 12:41:24 +0000247 Personality.PersonalityFn);
John McCall0bdb1fd2010-09-16 06:16:50 +0000248 return Fn;
249}
250
251static llvm::Constant *getOpaquePersonalityFn(CodeGenModule &CGM,
252 const EHPersonality &Personality) {
253 llvm::Constant *Fn = getPersonalityFn(CGM, Personality);
John McCallad7c5c12011-02-08 08:22:06 +0000254 return llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
John McCall0bdb1fd2010-09-16 06:16:50 +0000255}
256
257/// Check whether a personality function could reasonably be swapped
258/// for a C++ personality function.
259static bool PersonalityHasOnlyCXXUses(llvm::Constant *Fn) {
Chandler Carruth4d01fff2014-03-09 03:16:50 +0000260 for (llvm::User *U : Fn->users()) {
John McCall0bdb1fd2010-09-16 06:16:50 +0000261 // Conditionally white-list bitcasts.
Chandler Carruth4d01fff2014-03-09 03:16:50 +0000262 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(U)) {
John McCall0bdb1fd2010-09-16 06:16:50 +0000263 if (CE->getOpcode() != llvm::Instruction::BitCast) return false;
264 if (!PersonalityHasOnlyCXXUses(CE))
265 return false;
266 continue;
267 }
268
Bill Wendling58e58fe2011-09-19 22:08:36 +0000269 // Otherwise, it has to be a landingpad instruction.
Chandler Carruth4d01fff2014-03-09 03:16:50 +0000270 llvm::LandingPadInst *LPI = dyn_cast<llvm::LandingPadInst>(U);
Bill Wendling58e58fe2011-09-19 22:08:36 +0000271 if (!LPI) return false;
John McCall0bdb1fd2010-09-16 06:16:50 +0000272
Bill Wendling58e58fe2011-09-19 22:08:36 +0000273 for (unsigned I = 0, E = LPI->getNumClauses(); I != E; ++I) {
John McCall0bdb1fd2010-09-16 06:16:50 +0000274 // Look for something that would've been returned by the ObjC
275 // runtime's GetEHType() method.
Bill Wendling58e58fe2011-09-19 22:08:36 +0000276 llvm::Value *Val = LPI->getClause(I)->stripPointerCasts();
277 if (LPI->isCatch(I)) {
278 // Check if the catch value has the ObjC prefix.
Bill Wendling5d7469e2011-09-20 00:40:19 +0000279 if (llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Val))
280 // ObjC EH selector entries are always global variables with
281 // names starting like this.
282 if (GV->getName().startswith("OBJC_EHTYPE"))
283 return false;
Bill Wendling58e58fe2011-09-19 22:08:36 +0000284 } else {
285 // Check if any of the filter values have the ObjC prefix.
286 llvm::Constant *CVal = cast<llvm::Constant>(Val);
287 for (llvm::User::op_iterator
288 II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II) {
Bill Wendling5d7469e2011-09-20 00:40:19 +0000289 if (llvm::GlobalVariable *GV =
290 cast<llvm::GlobalVariable>((*II)->stripPointerCasts()))
291 // ObjC EH selector entries are always global variables with
292 // names starting like this.
293 if (GV->getName().startswith("OBJC_EHTYPE"))
294 return false;
Bill Wendling58e58fe2011-09-19 22:08:36 +0000295 }
296 }
John McCall0bdb1fd2010-09-16 06:16:50 +0000297 }
298 }
299
300 return true;
301}
302
303/// Try to use the C++ personality function in ObjC++. Not doing this
304/// can cause some incompatibilities with gcc, which is more
305/// aggressive about only using the ObjC++ personality in a function
306/// when it really needs it.
307void CodeGenModule::SimplifyPersonality() {
John McCall0bdb1fd2010-09-16 06:16:50 +0000308 // If we're not in ObjC++ -fexceptions, there's nothing to do.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000309 if (!LangOpts.CPlusPlus || !LangOpts.ObjC1 || !LangOpts.Exceptions)
John McCall0bdb1fd2010-09-16 06:16:50 +0000310 return;
311
John McCall3c223932012-11-14 17:48:31 +0000312 // Both the problem this endeavors to fix and the way the logic
313 // above works is specific to the NeXT runtime.
314 if (!LangOpts.ObjCRuntime.isNeXTFamily())
315 return;
316
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000317 const EHPersonality &ObjCXX = EHPersonality::get(*this, /*FD=*/nullptr);
Reid Klecknere070b992014-11-14 02:01:10 +0000318 const EHPersonality &CXX =
319 getCXXPersonality(getTarget().getTriple(), LangOpts);
Benjamin Kramer793bd552012-02-08 12:41:24 +0000320 if (&ObjCXX == &CXX)
John McCall0bdb1fd2010-09-16 06:16:50 +0000321 return;
322
Benjamin Kramer793bd552012-02-08 12:41:24 +0000323 assert(std::strcmp(ObjCXX.PersonalityFn, CXX.PersonalityFn) != 0 &&
324 "Different EHPersonalities using the same personality function.");
325
326 llvm::Function *Fn = getModule().getFunction(ObjCXX.PersonalityFn);
John McCall0bdb1fd2010-09-16 06:16:50 +0000327
328 // Nothing to do if it's unused.
329 if (!Fn || Fn->use_empty()) return;
330
331 // Can't do the optimization if it has non-C++ uses.
332 if (!PersonalityHasOnlyCXXUses(Fn)) return;
333
334 // Create the C++ personality function and kill off the old
335 // function.
336 llvm::Constant *CXXFn = getPersonalityFn(*this, CXX);
337
338 // This can happen if the user is screwing with us.
339 if (Fn->getType() != CXXFn->getType()) return;
340
341 Fn->replaceAllUsesWith(CXXFn);
342 Fn->eraseFromParent();
John McCallbd309292010-07-06 01:34:17 +0000343}
344
345/// Returns the value to inject into a selector to indicate the
346/// presence of a catch-all.
347static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
348 // Possibly we should use @llvm.eh.catch.all.value here.
John McCallad7c5c12011-02-08 08:22:06 +0000349 return llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
John McCallbd309292010-07-06 01:34:17 +0000350}
351
John McCallbb026012010-07-13 21:17:51 +0000352namespace {
353 /// A cleanup to free the exception object if its initialization
354 /// throws.
John McCall5fcf8da2011-07-12 00:15:30 +0000355 struct FreeException : EHScopeStack::Cleanup {
356 llvm::Value *exn;
357 FreeException(llvm::Value *exn) : exn(exn) {}
Craig Topper4f12f102014-03-12 06:41:41 +0000358 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +0000359 CGF.EmitNounwindRuntimeCall(getFreeExceptionFn(CGF.CGM), exn);
John McCallbb026012010-07-13 21:17:51 +0000360 }
361 };
362}
363
John McCall2e6567a2010-04-22 01:10:34 +0000364// Emits an exception expression into the given location. This
365// differs from EmitAnyExprToMem only in that, if a final copy-ctor
366// call is required, an exception within that copy ctor causes
367// std::terminate to be invoked.
David Majnemer7c237072015-03-05 00:46:22 +0000368void CodeGenFunction::EmitAnyExprToExn(const Expr *e, llvm::Value *addr) {
John McCallbd309292010-07-06 01:34:17 +0000369 // Make sure the exception object is cleaned up if there's an
370 // exception during initialization.
David Majnemer7c237072015-03-05 00:46:22 +0000371 pushFullExprCleanup<FreeException>(EHCleanup, addr);
372 EHScopeStack::stable_iterator cleanup = EHStack.stable_begin();
John McCall2e6567a2010-04-22 01:10:34 +0000373
374 // __cxa_allocate_exception returns a void*; we need to cast this
375 // to the appropriate type for the object.
David Majnemer7c237072015-03-05 00:46:22 +0000376 llvm::Type *ty = ConvertTypeForMem(e->getType())->getPointerTo();
377 llvm::Value *typedAddr = Builder.CreateBitCast(addr, ty);
John McCall2e6567a2010-04-22 01:10:34 +0000378
379 // FIXME: this isn't quite right! If there's a final unelided call
380 // to a copy constructor, then according to [except.terminate]p1 we
381 // must call std::terminate() if that constructor throws, because
382 // technically that copy occurs after the exception expression is
383 // evaluated but before the exception is caught. But the best way
384 // to handle that is to teach EmitAggExpr to do the final copy
385 // differently if it can't be elided.
David Majnemer7c237072015-03-05 00:46:22 +0000386 EmitAnyExprToMem(e, typedAddr, e->getType().getQualifiers(),
387 /*IsInit*/ true);
John McCall2e6567a2010-04-22 01:10:34 +0000388
John McCalle4df6c82011-01-28 08:37:24 +0000389 // Deactivate the cleanup block.
David Majnemer7c237072015-03-05 00:46:22 +0000390 DeactivateCleanupBlock(cleanup, cast<llvm::Instruction>(typedAddr));
Mike Stump54066142009-12-01 03:41:18 +0000391}
392
John McCallbd309292010-07-06 01:34:17 +0000393llvm::Value *CodeGenFunction::getExceptionSlot() {
John McCall9b382dd2011-05-28 21:13:02 +0000394 if (!ExceptionSlot)
395 ExceptionSlot = CreateTempAlloca(Int8PtrTy, "exn.slot");
John McCallbd309292010-07-06 01:34:17 +0000396 return ExceptionSlot;
Mike Stump54066142009-12-01 03:41:18 +0000397}
398
John McCall9b382dd2011-05-28 21:13:02 +0000399llvm::Value *CodeGenFunction::getEHSelectorSlot() {
400 if (!EHSelectorSlot)
401 EHSelectorSlot = CreateTempAlloca(Int32Ty, "ehselector.slot");
402 return EHSelectorSlot;
403}
404
Bill Wendling79a70e42011-09-15 18:57:19 +0000405llvm::Value *CodeGenFunction::getExceptionFromSlot() {
406 return Builder.CreateLoad(getExceptionSlot(), "exn");
407}
408
409llvm::Value *CodeGenFunction::getSelectorFromSlot() {
410 return Builder.CreateLoad(getEHSelectorSlot(), "sel");
411}
412
Richard Smithea852322013-05-07 21:53:22 +0000413void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E,
414 bool KeepInsertionPoint) {
David Majnemer7c237072015-03-05 00:46:22 +0000415 if (const Expr *SubExpr = E->getSubExpr()) {
416 QualType ThrowType = SubExpr->getType();
417 if (ThrowType->isObjCObjectPointerType()) {
418 const Stmt *ThrowStmt = E->getSubExpr();
419 const ObjCAtThrowStmt S(E->getExprLoc(), const_cast<Stmt *>(ThrowStmt));
420 CGM.getObjCRuntime().EmitThrowStmt(*this, S, false);
421 } else {
422 CGM.getCXXABI().emitThrow(*this, E);
John McCall2e6567a2010-04-22 01:10:34 +0000423 }
David Majnemer7c237072015-03-05 00:46:22 +0000424 } else {
425 CGM.getCXXABI().emitRethrow(*this, /*isNoReturn=*/true);
John McCall2e6567a2010-04-22 01:10:34 +0000426 }
Mike Stump75546b82009-12-10 00:06:18 +0000427
John McCall20f6ab82011-01-12 03:41:02 +0000428 // throw is an expression, and the expression emitters expect us
429 // to leave ourselves at a valid insertion point.
Richard Smithea852322013-05-07 21:53:22 +0000430 if (KeepInsertionPoint)
431 EmitBlock(createBasicBlock("throw.cont"));
Anders Carlsson4b08db72009-10-30 01:42:31 +0000432}
Mike Stump58ef18b2009-11-20 23:44:51 +0000433
Mike Stump1d849212009-12-07 23:38:24 +0000434void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000435 if (!CGM.getLangOpts().CXXExceptions)
Anders Carlsson9878f9f2010-02-06 23:59:05 +0000436 return;
437
Mike Stump1d849212009-12-07 23:38:24 +0000438 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
Craig Topper8a13c412014-05-21 05:09:00 +0000439 if (!FD) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000440 // Check if CapturedDecl is nothrow and create terminate scope for it.
441 if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
442 if (CD->isNothrow())
443 EHStack.pushTerminate();
444 }
Mike Stump1d849212009-12-07 23:38:24 +0000445 return;
Alexey Bataev9959db52014-05-06 10:08:46 +0000446 }
Mike Stump1d849212009-12-07 23:38:24 +0000447 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
Craig Topper8a13c412014-05-21 05:09:00 +0000448 if (!Proto)
Mike Stump1d849212009-12-07 23:38:24 +0000449 return;
450
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000451 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
452 if (isNoexceptExceptionSpec(EST)) {
453 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
454 // noexcept functions are simple terminate scopes.
455 EHStack.pushTerminate();
456 }
457 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
David Majnemer1f192e22015-04-01 04:45:52 +0000458 // TODO: Revisit exception specifications for the MS ABI. There is a way to
459 // encode these in an object file but MSVC doesn't do anything with it.
460 if (getTarget().getCXXABI().isMicrosoft())
461 return;
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000462 unsigned NumExceptions = Proto->getNumExceptions();
463 EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
Mike Stump1d849212009-12-07 23:38:24 +0000464
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000465 for (unsigned I = 0; I != NumExceptions; ++I) {
466 QualType Ty = Proto->getExceptionType(I);
467 QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
468 llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType,
469 /*ForEH=*/true);
470 Filter->setFilter(I, EHType);
471 }
Mike Stump1d849212009-12-07 23:38:24 +0000472 }
Mike Stump1d849212009-12-07 23:38:24 +0000473}
474
John McCall8e4c74b2011-08-11 02:22:43 +0000475/// Emit the dispatch block for a filter scope if necessary.
476static void emitFilterDispatchBlock(CodeGenFunction &CGF,
477 EHFilterScope &filterScope) {
478 llvm::BasicBlock *dispatchBlock = filterScope.getCachedEHDispatchBlock();
479 if (!dispatchBlock) return;
480 if (dispatchBlock->use_empty()) {
481 delete dispatchBlock;
482 return;
483 }
484
John McCall8e4c74b2011-08-11 02:22:43 +0000485 CGF.EmitBlockAfterUses(dispatchBlock);
486
487 // If this isn't a catch-all filter, we need to check whether we got
488 // here because the filter triggered.
489 if (filterScope.getNumFilters()) {
490 // Load the selector value.
Bill Wendling79a70e42011-09-15 18:57:19 +0000491 llvm::Value *selector = CGF.getSelectorFromSlot();
John McCall8e4c74b2011-08-11 02:22:43 +0000492 llvm::BasicBlock *unexpectedBB = CGF.createBasicBlock("ehspec.unexpected");
493
494 llvm::Value *zero = CGF.Builder.getInt32(0);
495 llvm::Value *failsFilter =
Nico Weber1bebad12015-02-11 22:33:32 +0000496 CGF.Builder.CreateICmpSLT(selector, zero, "ehspec.fails");
497 CGF.Builder.CreateCondBr(failsFilter, unexpectedBB,
498 CGF.getEHResumeBlock(false));
John McCall8e4c74b2011-08-11 02:22:43 +0000499
500 CGF.EmitBlock(unexpectedBB);
501 }
502
503 // Call __cxa_call_unexpected. This doesn't need to be an invoke
504 // because __cxa_call_unexpected magically filters exceptions
505 // according to the last landing pad the exception was thrown
506 // into. Seriously.
Bill Wendling79a70e42011-09-15 18:57:19 +0000507 llvm::Value *exn = CGF.getExceptionFromSlot();
John McCall882987f2013-02-28 19:01:20 +0000508 CGF.EmitRuntimeCall(getUnexpectedFn(CGF.CGM), exn)
John McCall8e4c74b2011-08-11 02:22:43 +0000509 ->setDoesNotReturn();
510 CGF.Builder.CreateUnreachable();
511}
512
Mike Stump1d849212009-12-07 23:38:24 +0000513void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000514 if (!CGM.getLangOpts().CXXExceptions)
Anders Carlsson9878f9f2010-02-06 23:59:05 +0000515 return;
516
Mike Stump1d849212009-12-07 23:38:24 +0000517 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
Craig Topper8a13c412014-05-21 05:09:00 +0000518 if (!FD) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000519 // Check if CapturedDecl is nothrow and pop terminate scope for it.
520 if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
521 if (CD->isNothrow())
522 EHStack.popTerminate();
523 }
Mike Stump1d849212009-12-07 23:38:24 +0000524 return;
Alexey Bataev9959db52014-05-06 10:08:46 +0000525 }
Mike Stump1d849212009-12-07 23:38:24 +0000526 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
Craig Topper8a13c412014-05-21 05:09:00 +0000527 if (!Proto)
Mike Stump1d849212009-12-07 23:38:24 +0000528 return;
529
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000530 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
531 if (isNoexceptExceptionSpec(EST)) {
532 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
533 EHStack.popTerminate();
534 }
535 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
David Majnemer1f192e22015-04-01 04:45:52 +0000536 // TODO: Revisit exception specifications for the MS ABI. There is a way to
537 // encode these in an object file but MSVC doesn't do anything with it.
538 if (getTarget().getCXXABI().isMicrosoft())
539 return;
John McCall8e4c74b2011-08-11 02:22:43 +0000540 EHFilterScope &filterScope = cast<EHFilterScope>(*EHStack.begin());
541 emitFilterDispatchBlock(*this, filterScope);
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000542 EHStack.popFilter();
543 }
Mike Stump1d849212009-12-07 23:38:24 +0000544}
545
Mike Stump58ef18b2009-11-20 23:44:51 +0000546void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
John McCallb609d3f2010-07-07 06:56:46 +0000547 EnterCXXTryStmt(S);
John McCallb81884d2010-02-19 09:25:03 +0000548 EmitStmt(S.getTryBlock());
John McCallb609d3f2010-07-07 06:56:46 +0000549 ExitCXXTryStmt(S);
John McCallb81884d2010-02-19 09:25:03 +0000550}
551
John McCallb609d3f2010-07-07 06:56:46 +0000552void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallbd309292010-07-06 01:34:17 +0000553 unsigned NumHandlers = S.getNumHandlers();
554 EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
John McCallb81884d2010-02-19 09:25:03 +0000555
John McCallbd309292010-07-06 01:34:17 +0000556 for (unsigned I = 0; I != NumHandlers; ++I) {
557 const CXXCatchStmt *C = S.getHandler(I);
John McCallb81884d2010-02-19 09:25:03 +0000558
John McCallbd309292010-07-06 01:34:17 +0000559 llvm::BasicBlock *Handler = createBasicBlock("catch");
560 if (C->getExceptionDecl()) {
561 // FIXME: Dropping the reference type on the type into makes it
562 // impossible to correctly implement catch-by-reference
563 // semantics for pointers. Unfortunately, this is what all
564 // existing compilers do, and it's not clear that the standard
565 // personality routine is capable of doing this right. See C++ DR 388:
566 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
David Majnemer571162a2014-10-12 06:58:22 +0000567 Qualifiers CaughtTypeQuals;
568 QualType CaughtType = CGM.getContext().getUnqualifiedArrayType(
569 C->getCaughtType().getNonReferenceType(), CaughtTypeQuals);
John McCall2ca705e2010-07-24 00:37:23 +0000570
Rafael Espindolabb9e7a32014-06-04 18:51:46 +0000571 llvm::Constant *TypeInfo = nullptr;
John McCall2ca705e2010-07-24 00:37:23 +0000572 if (CaughtType->isObjCObjectPointerType())
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +0000573 TypeInfo = CGM.getObjCRuntime().GetEHType(CaughtType);
John McCall2ca705e2010-07-24 00:37:23 +0000574 else
David Majnemer5f0dd612015-03-17 20:35:05 +0000575 TypeInfo =
David Majnemer37b417f2015-03-29 21:55:10 +0000576 CGM.getAddrOfCXXCatchHandlerType(CaughtType, C->getCaughtType());
John McCallbd309292010-07-06 01:34:17 +0000577 CatchScope->setHandler(I, TypeInfo, Handler);
578 } else {
579 // No exception decl indicates '...', a catch-all.
580 CatchScope->setCatchAllHandler(I, Handler);
581 }
582 }
John McCallbd309292010-07-06 01:34:17 +0000583}
584
John McCall8e4c74b2011-08-11 02:22:43 +0000585llvm::BasicBlock *
586CodeGenFunction::getEHDispatchBlock(EHScopeStack::stable_iterator si) {
587 // The dispatch block for the end of the scope chain is a block that
588 // just resumes unwinding.
589 if (si == EHStack.stable_end())
David Chisnall9a837be2012-11-07 16:50:40 +0000590 return getEHResumeBlock(true);
John McCall8e4c74b2011-08-11 02:22:43 +0000591
592 // Otherwise, we should look at the actual scope.
593 EHScope &scope = *EHStack.find(si);
594
595 llvm::BasicBlock *dispatchBlock = scope.getCachedEHDispatchBlock();
596 if (!dispatchBlock) {
597 switch (scope.getKind()) {
598 case EHScope::Catch: {
599 // Apply a special case to a single catch-all.
600 EHCatchScope &catchScope = cast<EHCatchScope>(scope);
601 if (catchScope.getNumHandlers() == 1 &&
602 catchScope.getHandler(0).isCatchAll()) {
603 dispatchBlock = catchScope.getHandler(0).Block;
604
605 // Otherwise, make a dispatch block.
606 } else {
607 dispatchBlock = createBasicBlock("catch.dispatch");
608 }
609 break;
610 }
611
612 case EHScope::Cleanup:
613 dispatchBlock = createBasicBlock("ehcleanup");
614 break;
615
616 case EHScope::Filter:
617 dispatchBlock = createBasicBlock("filter.dispatch");
618 break;
619
620 case EHScope::Terminate:
621 dispatchBlock = getTerminateHandler();
622 break;
623 }
624 scope.setCachedEHDispatchBlock(dispatchBlock);
625 }
626 return dispatchBlock;
627}
628
John McCallbd309292010-07-06 01:34:17 +0000629/// Check whether this is a non-EH scope, i.e. a scope which doesn't
630/// affect exception handling. Currently, the only non-EH scopes are
631/// normal-only cleanup scopes.
632static bool isNonEHScope(const EHScope &S) {
John McCall2b7fc382010-07-13 20:32:21 +0000633 switch (S.getKind()) {
John McCallcda666c2010-07-21 07:22:38 +0000634 case EHScope::Cleanup:
635 return !cast<EHCleanupScope>(S).isEHCleanup();
John McCall2b7fc382010-07-13 20:32:21 +0000636 case EHScope::Filter:
637 case EHScope::Catch:
638 case EHScope::Terminate:
639 return false;
640 }
641
David Blaikiee4d798f2012-01-20 21:50:17 +0000642 llvm_unreachable("Invalid EHScope Kind!");
John McCallbd309292010-07-06 01:34:17 +0000643}
644
645llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
646 assert(EHStack.requiresLandingPad());
647 assert(!EHStack.empty());
648
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000649 // If exceptions are disabled, there are usually no landingpads. However, when
650 // SEH is enabled, functions using SEH still get landingpads.
651 const LangOptions &LO = CGM.getLangOpts();
652 if (!LO.Exceptions) {
653 if (!LO.Borland && !LO.MicrosoftExt)
654 return nullptr;
Reid Klecknere7b3f7c2015-02-11 00:00:21 +0000655 if (!currentFunctionUsesSEHTry())
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000656 return nullptr;
657 }
John McCall2b7fc382010-07-13 20:32:21 +0000658
John McCallbd309292010-07-06 01:34:17 +0000659 // Check the innermost scope for a cached landing pad. If this is
660 // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
661 llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
662 if (LP) return LP;
663
664 // Build the landing pad for this scope.
665 LP = EmitLandingPad();
666 assert(LP);
667
668 // Cache the landing pad on the innermost scope. If this is a
669 // non-EH scope, cache the landing pad on the enclosing scope, too.
670 for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
671 ir->setCachedLandingPad(LP);
672 if (!isNonEHScope(*ir)) break;
673 }
674
675 return LP;
676}
677
678llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
679 assert(EHStack.requiresLandingPad());
680
John McCall8e4c74b2011-08-11 02:22:43 +0000681 EHScope &innermostEHScope = *EHStack.find(EHStack.getInnermostEHScope());
682 switch (innermostEHScope.getKind()) {
683 case EHScope::Terminate:
684 return getTerminateLandingPad();
John McCallbd309292010-07-06 01:34:17 +0000685
John McCall8e4c74b2011-08-11 02:22:43 +0000686 case EHScope::Catch:
687 case EHScope::Cleanup:
688 case EHScope::Filter:
689 if (llvm::BasicBlock *lpad = innermostEHScope.getCachedLandingPad())
690 return lpad;
John McCallbd309292010-07-06 01:34:17 +0000691 }
692
693 // Save the current IR generation state.
John McCall8e4c74b2011-08-11 02:22:43 +0000694 CGBuilderTy::InsertPoint savedIP = Builder.saveAndClearIP();
Adrian Prantl95b24e92015-02-03 20:00:54 +0000695 auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, CurEHLocation);
John McCallbd309292010-07-06 01:34:17 +0000696
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000697 const EHPersonality &personality = EHPersonality::get(*this);
John McCall36ea3722010-07-17 00:43:08 +0000698
John McCallbd309292010-07-06 01:34:17 +0000699 // Create and configure the landing pad.
John McCall8e4c74b2011-08-11 02:22:43 +0000700 llvm::BasicBlock *lpad = createBasicBlock("lpad");
701 EmitBlock(lpad);
John McCallbd309292010-07-06 01:34:17 +0000702
Bill Wendlingf0724e82011-09-19 20:31:14 +0000703 llvm::LandingPadInst *LPadInst =
Reid Kleckneree7cf842014-12-01 22:02:27 +0000704 Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, nullptr),
Bill Wendlingf0724e82011-09-19 20:31:14 +0000705 getOpaquePersonalityFn(CGM, personality), 0);
706
707 llvm::Value *LPadExn = Builder.CreateExtractValue(LPadInst, 0);
708 Builder.CreateStore(LPadExn, getExceptionSlot());
709 llvm::Value *LPadSel = Builder.CreateExtractValue(LPadInst, 1);
710 Builder.CreateStore(LPadSel, getEHSelectorSlot());
711
John McCallbd309292010-07-06 01:34:17 +0000712 // Save the exception pointer. It's safe to use a single exception
713 // pointer per function because EH cleanups can never have nested
714 // try/catches.
Bill Wendlingf0724e82011-09-19 20:31:14 +0000715 // Build the landingpad instruction.
John McCallbd309292010-07-06 01:34:17 +0000716
717 // Accumulate all the handlers in scope.
John McCall8e4c74b2011-08-11 02:22:43 +0000718 bool hasCatchAll = false;
719 bool hasCleanup = false;
720 bool hasFilter = false;
721 SmallVector<llvm::Value*, 4> filterTypes;
722 llvm::SmallPtrSet<llvm::Value*, 4> catchTypes;
Nico Webere68b9f32015-02-25 16:25:00 +0000723 for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end(); I != E;
724 ++I) {
John McCallbd309292010-07-06 01:34:17 +0000725
726 switch (I->getKind()) {
John McCallcda666c2010-07-21 07:22:38 +0000727 case EHScope::Cleanup:
John McCall8e4c74b2011-08-11 02:22:43 +0000728 // If we have a cleanup, remember that.
729 hasCleanup = (hasCleanup || cast<EHCleanupScope>(*I).isEHCleanup());
John McCall2b7fc382010-07-13 20:32:21 +0000730 continue;
731
John McCallbd309292010-07-06 01:34:17 +0000732 case EHScope::Filter: {
733 assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
John McCall8e4c74b2011-08-11 02:22:43 +0000734 assert(!hasCatchAll && "EH filter reached after catch-all");
John McCallbd309292010-07-06 01:34:17 +0000735
Bill Wendlingf0724e82011-09-19 20:31:14 +0000736 // Filter scopes get added to the landingpad in weird ways.
John McCall8e4c74b2011-08-11 02:22:43 +0000737 EHFilterScope &filter = cast<EHFilterScope>(*I);
738 hasFilter = true;
John McCallbd309292010-07-06 01:34:17 +0000739
Bill Wendling8c4b7162011-09-22 20:32:54 +0000740 // Add all the filter values.
741 for (unsigned i = 0, e = filter.getNumFilters(); i != e; ++i)
742 filterTypes.push_back(filter.getFilter(i));
John McCallbd309292010-07-06 01:34:17 +0000743 goto done;
744 }
745
746 case EHScope::Terminate:
747 // Terminate scopes are basically catch-alls.
John McCall8e4c74b2011-08-11 02:22:43 +0000748 assert(!hasCatchAll);
749 hasCatchAll = true;
John McCallbd309292010-07-06 01:34:17 +0000750 goto done;
751
752 case EHScope::Catch:
753 break;
754 }
755
John McCall8e4c74b2011-08-11 02:22:43 +0000756 EHCatchScope &catchScope = cast<EHCatchScope>(*I);
757 for (unsigned hi = 0, he = catchScope.getNumHandlers(); hi != he; ++hi) {
758 EHCatchScope::Handler handler = catchScope.getHandler(hi);
John McCallbd309292010-07-06 01:34:17 +0000759
John McCall8e4c74b2011-08-11 02:22:43 +0000760 // If this is a catch-all, register that and abort.
761 if (!handler.Type) {
762 assert(!hasCatchAll);
763 hasCatchAll = true;
764 goto done;
John McCallbd309292010-07-06 01:34:17 +0000765 }
766
767 // Check whether we already have a handler for this type.
David Blaikie82e95a32014-11-19 07:49:47 +0000768 if (catchTypes.insert(handler.Type).second)
Bill Wendlingf0724e82011-09-19 20:31:14 +0000769 // If not, add it directly to the landingpad.
770 LPadInst->addClause(handler.Type);
John McCallbd309292010-07-06 01:34:17 +0000771 }
John McCallbd309292010-07-06 01:34:17 +0000772 }
773
774 done:
Bill Wendlingf0724e82011-09-19 20:31:14 +0000775 // If we have a catch-all, add null to the landingpad.
John McCall8e4c74b2011-08-11 02:22:43 +0000776 assert(!(hasCatchAll && hasFilter));
777 if (hasCatchAll) {
Bill Wendlingf0724e82011-09-19 20:31:14 +0000778 LPadInst->addClause(getCatchAllValue(*this));
John McCallbd309292010-07-06 01:34:17 +0000779
780 // If we have an EH filter, we need to add those handlers in the
Bill Wendlingf0724e82011-09-19 20:31:14 +0000781 // right place in the landingpad, which is to say, at the end.
John McCall8e4c74b2011-08-11 02:22:43 +0000782 } else if (hasFilter) {
Bill Wendling58e58fe2011-09-19 22:08:36 +0000783 // Create a filter expression: a constant array indicating which filter
784 // types there are. The personality routine only lands here if the filter
785 // doesn't match.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000786 SmallVector<llvm::Constant*, 8> Filters;
Bill Wendlingf0724e82011-09-19 20:31:14 +0000787 llvm::ArrayType *AType =
788 llvm::ArrayType::get(!filterTypes.empty() ?
789 filterTypes[0]->getType() : Int8PtrTy,
790 filterTypes.size());
791
792 for (unsigned i = 0, e = filterTypes.size(); i != e; ++i)
793 Filters.push_back(cast<llvm::Constant>(filterTypes[i]));
794 llvm::Constant *FilterArray = llvm::ConstantArray::get(AType, Filters);
795 LPadInst->addClause(FilterArray);
John McCallbd309292010-07-06 01:34:17 +0000796
797 // Also check whether we need a cleanup.
Bill Wendlingf0724e82011-09-19 20:31:14 +0000798 if (hasCleanup)
799 LPadInst->setCleanup(true);
John McCallbd309292010-07-06 01:34:17 +0000800
801 // Otherwise, signal that we at least have cleanups.
Logan Chiene9c8ccb2014-07-01 11:47:10 +0000802 } else if (hasCleanup) {
803 LPadInst->setCleanup(true);
John McCallbd309292010-07-06 01:34:17 +0000804 }
805
Bill Wendlingf0724e82011-09-19 20:31:14 +0000806 assert((LPadInst->getNumClauses() > 0 || LPadInst->isCleanup()) &&
807 "landingpad instruction has no clauses!");
John McCallbd309292010-07-06 01:34:17 +0000808
809 // Tell the backend how to generate the landing pad.
John McCall8e4c74b2011-08-11 02:22:43 +0000810 Builder.CreateBr(getEHDispatchBlock(EHStack.getInnermostEHScope()));
John McCallbd309292010-07-06 01:34:17 +0000811
812 // Restore the old IR generation state.
John McCall8e4c74b2011-08-11 02:22:43 +0000813 Builder.restoreIP(savedIP);
John McCallbd309292010-07-06 01:34:17 +0000814
John McCall8e4c74b2011-08-11 02:22:43 +0000815 return lpad;
John McCallbd309292010-07-06 01:34:17 +0000816}
817
John McCall8e4c74b2011-08-11 02:22:43 +0000818/// Emit the structure of the dispatch block for the given catch scope.
819/// It is an invariant that the dispatch block already exists.
820static void emitCatchDispatchBlock(CodeGenFunction &CGF,
821 EHCatchScope &catchScope) {
822 llvm::BasicBlock *dispatchBlock = catchScope.getCachedEHDispatchBlock();
823 assert(dispatchBlock);
824
825 // If there's only a single catch-all, getEHDispatchBlock returned
826 // that catch-all as the dispatch block.
827 if (catchScope.getNumHandlers() == 1 &&
828 catchScope.getHandler(0).isCatchAll()) {
829 assert(dispatchBlock == catchScope.getHandler(0).Block);
830 return;
831 }
832
833 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveIP();
834 CGF.EmitBlockAfterUses(dispatchBlock);
835
836 // Select the right handler.
837 llvm::Value *llvm_eh_typeid_for =
838 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
839
840 // Load the selector value.
Bill Wendling79a70e42011-09-15 18:57:19 +0000841 llvm::Value *selector = CGF.getSelectorFromSlot();
John McCall8e4c74b2011-08-11 02:22:43 +0000842
843 // Test against each of the exception types we claim to catch.
844 for (unsigned i = 0, e = catchScope.getNumHandlers(); ; ++i) {
845 assert(i < e && "ran off end of handlers!");
846 const EHCatchScope::Handler &handler = catchScope.getHandler(i);
847
848 llvm::Value *typeValue = handler.Type;
849 assert(typeValue && "fell into catch-all case!");
850 typeValue = CGF.Builder.CreateBitCast(typeValue, CGF.Int8PtrTy);
851
852 // Figure out the next block.
853 bool nextIsEnd;
854 llvm::BasicBlock *nextBlock;
855
856 // If this is the last handler, we're at the end, and the next
857 // block is the block for the enclosing EH scope.
858 if (i + 1 == e) {
859 nextBlock = CGF.getEHDispatchBlock(catchScope.getEnclosingEHScope());
860 nextIsEnd = true;
861
862 // If the next handler is a catch-all, we're at the end, and the
863 // next block is that handler.
864 } else if (catchScope.getHandler(i+1).isCatchAll()) {
865 nextBlock = catchScope.getHandler(i+1).Block;
866 nextIsEnd = true;
867
868 // Otherwise, we're not at the end and we need a new block.
869 } else {
870 nextBlock = CGF.createBasicBlock("catch.fallthrough");
871 nextIsEnd = false;
872 }
873
874 // Figure out the catch type's index in the LSDA's type table.
875 llvm::CallInst *typeIndex =
876 CGF.Builder.CreateCall(llvm_eh_typeid_for, typeValue);
877 typeIndex->setDoesNotThrow();
878
879 llvm::Value *matchesTypeIndex =
880 CGF.Builder.CreateICmpEQ(selector, typeIndex, "matches");
881 CGF.Builder.CreateCondBr(matchesTypeIndex, handler.Block, nextBlock);
882
883 // If the next handler is a catch-all, we're completely done.
884 if (nextIsEnd) {
885 CGF.Builder.restoreIP(savedIP);
886 return;
John McCall8e4c74b2011-08-11 02:22:43 +0000887 }
Ahmed Charles289896d2012-02-19 11:57:29 +0000888 // Otherwise we need to emit and continue at that block.
889 CGF.EmitBlock(nextBlock);
John McCall8e4c74b2011-08-11 02:22:43 +0000890 }
John McCall8e4c74b2011-08-11 02:22:43 +0000891}
892
893void CodeGenFunction::popCatchScope() {
894 EHCatchScope &catchScope = cast<EHCatchScope>(*EHStack.begin());
895 if (catchScope.hasEHBranches())
896 emitCatchDispatchBlock(*this, catchScope);
897 EHStack.popCatch();
898}
899
John McCallb609d3f2010-07-07 06:56:46 +0000900void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallbd309292010-07-06 01:34:17 +0000901 unsigned NumHandlers = S.getNumHandlers();
902 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
903 assert(CatchScope.getNumHandlers() == NumHandlers);
Mike Stump58ef18b2009-11-20 23:44:51 +0000904
John McCall8e4c74b2011-08-11 02:22:43 +0000905 // If the catch was not required, bail out now.
906 if (!CatchScope.hasEHBranches()) {
Kostya Serebryanyba4aced2014-01-09 09:22:32 +0000907 CatchScope.clearHandlerBlocks();
John McCall8e4c74b2011-08-11 02:22:43 +0000908 EHStack.popCatch();
909 return;
910 }
911
912 // Emit the structure of the EH dispatch for this catch.
913 emitCatchDispatchBlock(*this, CatchScope);
914
John McCallbd309292010-07-06 01:34:17 +0000915 // Copy the handler blocks off before we pop the EH stack. Emitting
916 // the handlers might scribble on this memory.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000917 SmallVector<EHCatchScope::Handler, 8> Handlers(NumHandlers);
John McCallbd309292010-07-06 01:34:17 +0000918 memcpy(Handlers.data(), CatchScope.begin(),
919 NumHandlers * sizeof(EHCatchScope::Handler));
John McCall8e4c74b2011-08-11 02:22:43 +0000920
John McCallbd309292010-07-06 01:34:17 +0000921 EHStack.popCatch();
Mike Stump58ef18b2009-11-20 23:44:51 +0000922
John McCallbd309292010-07-06 01:34:17 +0000923 // The fall-through block.
924 llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
Mike Stump58ef18b2009-11-20 23:44:51 +0000925
John McCallbd309292010-07-06 01:34:17 +0000926 // We just emitted the body of the try; jump to the continue block.
927 if (HaveInsertPoint())
928 Builder.CreateBr(ContBB);
Mike Stump97329152009-12-02 19:53:57 +0000929
John McCalld8d00be2012-06-15 05:27:05 +0000930 // Determine if we need an implicit rethrow for all these catch handlers;
931 // see the comment below.
932 bool doImplicitRethrow = false;
John McCallb609d3f2010-07-07 06:56:46 +0000933 if (IsFnTryBlock)
John McCalld8d00be2012-06-15 05:27:05 +0000934 doImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
935 isa<CXXConstructorDecl>(CurCodeDecl);
John McCallb609d3f2010-07-07 06:56:46 +0000936
John McCall8e4c74b2011-08-11 02:22:43 +0000937 // Perversely, we emit the handlers backwards precisely because we
938 // want them to appear in source order. In all of these cases, the
939 // catch block will have exactly one predecessor, which will be a
940 // particular block in the catch dispatch. However, in the case of
941 // a catch-all, one of the dispatch blocks will branch to two
942 // different handlers, and EmitBlockAfterUses will cause the second
943 // handler to be moved before the first.
944 for (unsigned I = NumHandlers; I != 0; --I) {
945 llvm::BasicBlock *CatchBlock = Handlers[I-1].Block;
946 EmitBlockAfterUses(CatchBlock);
Mike Stump75546b82009-12-10 00:06:18 +0000947
John McCallbd309292010-07-06 01:34:17 +0000948 // Catch the exception if this isn't a catch-all.
John McCall8e4c74b2011-08-11 02:22:43 +0000949 const CXXCatchStmt *C = S.getHandler(I-1);
Mike Stump58ef18b2009-11-20 23:44:51 +0000950
John McCallbd309292010-07-06 01:34:17 +0000951 // Enter a cleanup scope, including the catch variable and the
952 // end-catch.
953 RunCleanupsScope CatchScope(*this);
Mike Stump58ef18b2009-11-20 23:44:51 +0000954
John McCallbd309292010-07-06 01:34:17 +0000955 // Initialize the catch variable and set up the cleanups.
Reid Klecknerfff8e7f2015-03-03 19:21:04 +0000956 CGM.getCXXABI().emitBeginCatch(*this, C);
John McCallbd309292010-07-06 01:34:17 +0000957
Justin Bognerea278c32014-01-07 00:20:28 +0000958 // Emit the PGO counter increment.
Justin Bogner66242d62015-04-23 23:06:47 +0000959 incrementProfileCounter(C);
Justin Bogneref512b92014-01-06 22:27:43 +0000960
John McCallbd309292010-07-06 01:34:17 +0000961 // Perform the body of the catch.
962 EmitStmt(C->getHandlerBlock());
963
John McCalld8d00be2012-06-15 05:27:05 +0000964 // [except.handle]p11:
965 // The currently handled exception is rethrown if control
966 // reaches the end of a handler of the function-try-block of a
967 // constructor or destructor.
968
969 // It is important that we only do this on fallthrough and not on
970 // return. Note that it's illegal to put a return in a
971 // constructor function-try-block's catch handler (p14), so this
972 // really only applies to destructors.
973 if (doImplicitRethrow && HaveInsertPoint()) {
David Majnemer442d0a22014-11-25 07:20:20 +0000974 CGM.getCXXABI().emitRethrow(*this, /*isNoReturn*/false);
John McCalld8d00be2012-06-15 05:27:05 +0000975 Builder.CreateUnreachable();
976 Builder.ClearInsertionPoint();
977 }
978
John McCallbd309292010-07-06 01:34:17 +0000979 // Fall out through the catch cleanups.
980 CatchScope.ForceCleanup();
981
982 // Branch out of the try.
983 if (HaveInsertPoint())
984 Builder.CreateBr(ContBB);
Mike Stump58ef18b2009-11-20 23:44:51 +0000985 }
986
John McCallbd309292010-07-06 01:34:17 +0000987 EmitBlock(ContBB);
Justin Bogner66242d62015-04-23 23:06:47 +0000988 incrementProfileCounter(&S);
Mike Stump58ef18b2009-11-20 23:44:51 +0000989}
Mike Stumpaff69af2009-12-09 03:35:49 +0000990
John McCall1e670402010-07-21 00:52:03 +0000991namespace {
John McCallcda666c2010-07-21 07:22:38 +0000992 struct CallEndCatchForFinally : EHScopeStack::Cleanup {
John McCall1e670402010-07-21 00:52:03 +0000993 llvm::Value *ForEHVar;
994 llvm::Value *EndCatchFn;
995 CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn)
996 : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
997
Craig Topper4f12f102014-03-12 06:41:41 +0000998 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall1e670402010-07-21 00:52:03 +0000999 llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
1000 llvm::BasicBlock *CleanupContBB =
1001 CGF.createBasicBlock("finally.cleanup.cont");
1002
1003 llvm::Value *ShouldEndCatch =
1004 CGF.Builder.CreateLoad(ForEHVar, "finally.endcatch");
1005 CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1006 CGF.EmitBlock(EndCatchBB);
John McCall882987f2013-02-28 19:01:20 +00001007 CGF.EmitRuntimeCallOrInvoke(EndCatchFn); // catch-all, so might throw
John McCall1e670402010-07-21 00:52:03 +00001008 CGF.EmitBlock(CleanupContBB);
1009 }
1010 };
John McCall906da4b2010-07-21 05:47:49 +00001011
John McCallcda666c2010-07-21 07:22:38 +00001012 struct PerformFinally : EHScopeStack::Cleanup {
John McCall906da4b2010-07-21 05:47:49 +00001013 const Stmt *Body;
1014 llvm::Value *ForEHVar;
1015 llvm::Value *EndCatchFn;
1016 llvm::Value *RethrowFn;
1017 llvm::Value *SavedExnVar;
1018
1019 PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
1020 llvm::Value *EndCatchFn,
1021 llvm::Value *RethrowFn, llvm::Value *SavedExnVar)
1022 : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1023 RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
1024
Craig Topper4f12f102014-03-12 06:41:41 +00001025 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall906da4b2010-07-21 05:47:49 +00001026 // Enter a cleanup to call the end-catch function if one was provided.
1027 if (EndCatchFn)
John McCallcda666c2010-07-21 07:22:38 +00001028 CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
1029 ForEHVar, EndCatchFn);
John McCall906da4b2010-07-21 05:47:49 +00001030
John McCallcebe0ca2010-08-11 00:16:14 +00001031 // Save the current cleanup destination in case there are
1032 // cleanups in the finally block.
1033 llvm::Value *SavedCleanupDest =
1034 CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
1035 "cleanup.dest.saved");
1036
John McCall906da4b2010-07-21 05:47:49 +00001037 // Emit the finally block.
1038 CGF.EmitStmt(Body);
1039
1040 // If the end of the finally is reachable, check whether this was
1041 // for EH. If so, rethrow.
1042 if (CGF.HaveInsertPoint()) {
1043 llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
1044 llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
1045
1046 llvm::Value *ShouldRethrow =
1047 CGF.Builder.CreateLoad(ForEHVar, "finally.shouldthrow");
1048 CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1049
1050 CGF.EmitBlock(RethrowBB);
1051 if (SavedExnVar) {
John McCall882987f2013-02-28 19:01:20 +00001052 CGF.EmitRuntimeCallOrInvoke(RethrowFn,
1053 CGF.Builder.CreateLoad(SavedExnVar));
John McCall906da4b2010-07-21 05:47:49 +00001054 } else {
John McCall882987f2013-02-28 19:01:20 +00001055 CGF.EmitRuntimeCallOrInvoke(RethrowFn);
John McCall906da4b2010-07-21 05:47:49 +00001056 }
1057 CGF.Builder.CreateUnreachable();
1058
1059 CGF.EmitBlock(ContBB);
John McCallcebe0ca2010-08-11 00:16:14 +00001060
1061 // Restore the cleanup destination.
1062 CGF.Builder.CreateStore(SavedCleanupDest,
1063 CGF.getNormalCleanupDestSlot());
John McCall906da4b2010-07-21 05:47:49 +00001064 }
1065
1066 // Leave the end-catch cleanup. As an optimization, pretend that
1067 // the fallthrough path was inaccessible; we've dynamically proven
1068 // that we're not in the EH case along that path.
1069 if (EndCatchFn) {
1070 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1071 CGF.PopCleanupBlock();
1072 CGF.Builder.restoreIP(SavedIP);
1073 }
1074
1075 // Now make sure we actually have an insertion point or the
1076 // cleanup gods will hate us.
1077 CGF.EnsureInsertPoint();
1078 }
1079 };
John McCall1e670402010-07-21 00:52:03 +00001080}
1081
John McCallbd309292010-07-06 01:34:17 +00001082/// Enters a finally block for an implementation using zero-cost
1083/// exceptions. This is mostly general, but hard-codes some
1084/// language/ABI-specific behavior in the catch-all sections.
John McCall6b0feb72011-06-22 02:32:12 +00001085void CodeGenFunction::FinallyInfo::enter(CodeGenFunction &CGF,
1086 const Stmt *body,
1087 llvm::Constant *beginCatchFn,
1088 llvm::Constant *endCatchFn,
1089 llvm::Constant *rethrowFn) {
Craig Topper8a13c412014-05-21 05:09:00 +00001090 assert((beginCatchFn != nullptr) == (endCatchFn != nullptr) &&
John McCallbd309292010-07-06 01:34:17 +00001091 "begin/end catch functions not paired");
John McCall6b0feb72011-06-22 02:32:12 +00001092 assert(rethrowFn && "rethrow function is required");
1093
1094 BeginCatchFn = beginCatchFn;
Mike Stumpaff69af2009-12-09 03:35:49 +00001095
John McCallbd309292010-07-06 01:34:17 +00001096 // The rethrow function has one of the following two types:
1097 // void (*)()
1098 // void (*)(void*)
1099 // In the latter case we need to pass it the exception object.
1100 // But we can't use the exception slot because the @finally might
1101 // have a landing pad (which would overwrite the exception slot).
Chris Lattner2192fe52011-07-18 04:24:23 +00001102 llvm::FunctionType *rethrowFnTy =
John McCallbd309292010-07-06 01:34:17 +00001103 cast<llvm::FunctionType>(
John McCall6b0feb72011-06-22 02:32:12 +00001104 cast<llvm::PointerType>(rethrowFn->getType())->getElementType());
Craig Topper8a13c412014-05-21 05:09:00 +00001105 SavedExnVar = nullptr;
John McCall6b0feb72011-06-22 02:32:12 +00001106 if (rethrowFnTy->getNumParams())
1107 SavedExnVar = CGF.CreateTempAlloca(CGF.Int8PtrTy, "finally.exn");
Mike Stumpaff69af2009-12-09 03:35:49 +00001108
John McCallbd309292010-07-06 01:34:17 +00001109 // A finally block is a statement which must be executed on any edge
1110 // out of a given scope. Unlike a cleanup, the finally block may
1111 // contain arbitrary control flow leading out of itself. In
1112 // addition, finally blocks should always be executed, even if there
1113 // are no catch handlers higher on the stack. Therefore, we
1114 // surround the protected scope with a combination of a normal
1115 // cleanup (to catch attempts to break out of the block via normal
1116 // control flow) and an EH catch-all (semantically "outside" any try
1117 // statement to which the finally block might have been attached).
1118 // The finally block itself is generated in the context of a cleanup
1119 // which conditionally leaves the catch-all.
John McCall21886962010-04-21 10:05:39 +00001120
John McCallbd309292010-07-06 01:34:17 +00001121 // Jump destination for performing the finally block on an exception
1122 // edge. We'll never actually reach this block, so unreachable is
1123 // fine.
John McCall6b0feb72011-06-22 02:32:12 +00001124 RethrowDest = CGF.getJumpDestInCurrentScope(CGF.getUnreachableBlock());
John McCall21886962010-04-21 10:05:39 +00001125
John McCallbd309292010-07-06 01:34:17 +00001126 // Whether the finally block is being executed for EH purposes.
John McCall6b0feb72011-06-22 02:32:12 +00001127 ForEHVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "finally.for-eh");
1128 CGF.Builder.CreateStore(CGF.Builder.getFalse(), ForEHVar);
Mike Stumpaff69af2009-12-09 03:35:49 +00001129
John McCallbd309292010-07-06 01:34:17 +00001130 // Enter a normal cleanup which will perform the @finally block.
John McCall6b0feb72011-06-22 02:32:12 +00001131 CGF.EHStack.pushCleanup<PerformFinally>(NormalCleanup, body,
1132 ForEHVar, endCatchFn,
1133 rethrowFn, SavedExnVar);
John McCallbd309292010-07-06 01:34:17 +00001134
1135 // Enter a catch-all scope.
John McCall6b0feb72011-06-22 02:32:12 +00001136 llvm::BasicBlock *catchBB = CGF.createBasicBlock("finally.catchall");
1137 EHCatchScope *catchScope = CGF.EHStack.pushCatch(1);
1138 catchScope->setCatchAllHandler(0, catchBB);
John McCallbd309292010-07-06 01:34:17 +00001139}
1140
John McCall6b0feb72011-06-22 02:32:12 +00001141void CodeGenFunction::FinallyInfo::exit(CodeGenFunction &CGF) {
John McCallbd309292010-07-06 01:34:17 +00001142 // Leave the finally catch-all.
John McCall6b0feb72011-06-22 02:32:12 +00001143 EHCatchScope &catchScope = cast<EHCatchScope>(*CGF.EHStack.begin());
1144 llvm::BasicBlock *catchBB = catchScope.getHandler(0).Block;
John McCall8e4c74b2011-08-11 02:22:43 +00001145
1146 CGF.popCatchScope();
John McCallbd309292010-07-06 01:34:17 +00001147
John McCall6b0feb72011-06-22 02:32:12 +00001148 // If there are any references to the catch-all block, emit it.
1149 if (catchBB->use_empty()) {
1150 delete catchBB;
1151 } else {
1152 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveAndClearIP();
1153 CGF.EmitBlock(catchBB);
John McCallbd309292010-07-06 01:34:17 +00001154
Craig Topper8a13c412014-05-21 05:09:00 +00001155 llvm::Value *exn = nullptr;
John McCallbd309292010-07-06 01:34:17 +00001156
John McCall6b0feb72011-06-22 02:32:12 +00001157 // If there's a begin-catch function, call it.
1158 if (BeginCatchFn) {
Bill Wendling79a70e42011-09-15 18:57:19 +00001159 exn = CGF.getExceptionFromSlot();
John McCall882987f2013-02-28 19:01:20 +00001160 CGF.EmitNounwindRuntimeCall(BeginCatchFn, exn);
John McCall6b0feb72011-06-22 02:32:12 +00001161 }
1162
1163 // If we need to remember the exception pointer to rethrow later, do so.
1164 if (SavedExnVar) {
Bill Wendling79a70e42011-09-15 18:57:19 +00001165 if (!exn) exn = CGF.getExceptionFromSlot();
John McCall6b0feb72011-06-22 02:32:12 +00001166 CGF.Builder.CreateStore(exn, SavedExnVar);
1167 }
1168
1169 // Tell the cleanups in the finally block that we're do this for EH.
1170 CGF.Builder.CreateStore(CGF.Builder.getTrue(), ForEHVar);
1171
1172 // Thread a jump through the finally cleanup.
1173 CGF.EmitBranchThroughCleanup(RethrowDest);
1174
1175 CGF.Builder.restoreIP(savedIP);
1176 }
1177
1178 // Finally, leave the @finally cleanup.
1179 CGF.PopCleanupBlock();
John McCallbd309292010-07-06 01:34:17 +00001180}
1181
1182llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
1183 if (TerminateLandingPad)
1184 return TerminateLandingPad;
1185
1186 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1187
1188 // This will get inserted at the end of the function.
1189 TerminateLandingPad = createBasicBlock("terminate.lpad");
1190 Builder.SetInsertPoint(TerminateLandingPad);
1191
1192 // Tell the backend that this is a landing pad.
Reid Klecknerdeeddec2015-02-05 18:56:03 +00001193 const EHPersonality &Personality = EHPersonality::get(*this);
Bill Wendlingf0724e82011-09-19 20:31:14 +00001194 llvm::LandingPadInst *LPadInst =
Reid Kleckneree7cf842014-12-01 22:02:27 +00001195 Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, nullptr),
Bill Wendlingf0724e82011-09-19 20:31:14 +00001196 getOpaquePersonalityFn(CGM, Personality), 0);
1197 LPadInst->addClause(getCatchAllValue(*this));
John McCallbd309292010-07-06 01:34:17 +00001198
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00001199 llvm::Value *Exn = 0;
1200 if (getLangOpts().CPlusPlus)
1201 Exn = Builder.CreateExtractValue(LPadInst, 0);
1202 llvm::CallInst *terminateCall =
1203 CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
John McCalle142ad52013-02-12 03:51:46 +00001204 terminateCall->setDoesNotReturn();
John McCallad7c5c12011-02-08 08:22:06 +00001205 Builder.CreateUnreachable();
Mike Stumpaff69af2009-12-09 03:35:49 +00001206
John McCallbd309292010-07-06 01:34:17 +00001207 // Restore the saved insertion state.
1208 Builder.restoreIP(SavedIP);
John McCalldac3ea62010-04-30 00:06:43 +00001209
John McCallbd309292010-07-06 01:34:17 +00001210 return TerminateLandingPad;
Mike Stumpaff69af2009-12-09 03:35:49 +00001211}
Mike Stump2b488872009-12-09 22:59:31 +00001212
1213llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
Mike Stumpf5cbb082009-12-10 00:02:42 +00001214 if (TerminateHandler)
1215 return TerminateHandler;
1216
John McCallbd309292010-07-06 01:34:17 +00001217 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
Mike Stump25b20fc2009-12-09 23:31:35 +00001218
John McCallbd309292010-07-06 01:34:17 +00001219 // Set up the terminate handler. This block is inserted at the very
1220 // end of the function by FinishFunction.
Mike Stumpf5cbb082009-12-10 00:02:42 +00001221 TerminateHandler = createBasicBlock("terminate.handler");
John McCallbd309292010-07-06 01:34:17 +00001222 Builder.SetInsertPoint(TerminateHandler);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00001223 llvm::Value *Exn = 0;
1224 if (getLangOpts().CPlusPlus)
1225 Exn = getExceptionFromSlot();
1226 llvm::CallInst *terminateCall =
1227 CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
John McCallc84e4e92013-06-20 21:37:43 +00001228 terminateCall->setDoesNotReturn();
Mike Stump2b488872009-12-09 22:59:31 +00001229 Builder.CreateUnreachable();
1230
John McCall21886962010-04-21 10:05:39 +00001231 // Restore the saved insertion state.
John McCallbd309292010-07-06 01:34:17 +00001232 Builder.restoreIP(SavedIP);
Mike Stump25b20fc2009-12-09 23:31:35 +00001233
Mike Stump2b488872009-12-09 22:59:31 +00001234 return TerminateHandler;
1235}
John McCallbd309292010-07-06 01:34:17 +00001236
David Chisnall9a837be2012-11-07 16:50:40 +00001237llvm::BasicBlock *CodeGenFunction::getEHResumeBlock(bool isCleanup) {
John McCall8e4c74b2011-08-11 02:22:43 +00001238 if (EHResumeBlock) return EHResumeBlock;
John McCallad5d61e2010-07-23 21:56:41 +00001239
1240 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1241
1242 // We emit a jump to a notional label at the outermost unwind state.
John McCall8e4c74b2011-08-11 02:22:43 +00001243 EHResumeBlock = createBasicBlock("eh.resume");
1244 Builder.SetInsertPoint(EHResumeBlock);
John McCallad5d61e2010-07-23 21:56:41 +00001245
Reid Klecknerdeeddec2015-02-05 18:56:03 +00001246 const EHPersonality &Personality = EHPersonality::get(*this);
John McCallad5d61e2010-07-23 21:56:41 +00001247
1248 // This can always be a call because we necessarily didn't find
1249 // anything on the EH stack which needs our help.
Benjamin Kramer793bd552012-02-08 12:41:24 +00001250 const char *RethrowName = Personality.CatchallRethrowFn;
Craig Topper8a13c412014-05-21 05:09:00 +00001251 if (RethrowName != nullptr && !isCleanup) {
John McCall882987f2013-02-28 19:01:20 +00001252 EmitRuntimeCall(getCatchallRethrowFn(CGM, RethrowName),
Nico Weberff62a6a2015-02-26 22:34:33 +00001253 getExceptionFromSlot())->setDoesNotReturn();
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001254 Builder.CreateUnreachable();
1255 Builder.restoreIP(SavedIP);
1256 return EHResumeBlock;
John McCall9b382dd2011-05-28 21:13:02 +00001257 }
1258
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001259 // Recreate the landingpad's return value for the 'resume' instruction.
1260 llvm::Value *Exn = getExceptionFromSlot();
1261 llvm::Value *Sel = getSelectorFromSlot();
John McCallad5d61e2010-07-23 21:56:41 +00001262
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001263 llvm::Type *LPadType = llvm::StructType::get(Exn->getType(),
Reid Kleckneree7cf842014-12-01 22:02:27 +00001264 Sel->getType(), nullptr);
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001265 llvm::Value *LPadVal = llvm::UndefValue::get(LPadType);
1266 LPadVal = Builder.CreateInsertValue(LPadVal, Exn, 0, "lpad.val");
1267 LPadVal = Builder.CreateInsertValue(LPadVal, Sel, 1, "lpad.val");
1268
1269 Builder.CreateResume(LPadVal);
John McCallad5d61e2010-07-23 21:56:41 +00001270 Builder.restoreIP(SavedIP);
John McCall8e4c74b2011-08-11 02:22:43 +00001271 return EHResumeBlock;
John McCallad5d61e2010-07-23 21:56:41 +00001272}
Reid Kleckner543a16c2013-09-16 21:46:30 +00001273
1274void CodeGenFunction::EmitSEHTryStmt(const SEHTryStmt &S) {
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001275 EnterSEHTryStmt(S);
Reid Klecknera5930002015-02-11 21:40:48 +00001276 {
Nico Weber5779f842015-02-12 23:16:11 +00001277 JumpDest TryExit = getJumpDestInCurrentScope("__try.__leave");
Nico Weber5779f842015-02-12 23:16:11 +00001278
Reid Kleckner11c033e2015-02-12 23:40:45 +00001279 SEHTryEpilogueStack.push_back(&TryExit);
Reid Klecknera5930002015-02-11 21:40:48 +00001280 EmitStmt(S.getTryBlock());
Reid Kleckner11c033e2015-02-12 23:40:45 +00001281 SEHTryEpilogueStack.pop_back();
Nico Weber5779f842015-02-12 23:16:11 +00001282
1283 if (!TryExit.getBlock()->use_empty())
1284 EmitBlock(TryExit.getBlock(), /*IsFinished=*/true);
1285 else
1286 delete TryExit.getBlock();
Reid Klecknera5930002015-02-11 21:40:48 +00001287 }
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001288 ExitSEHTryStmt(S);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001289}
1290
1291namespace {
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001292struct PerformSEHFinally : EHScopeStack::Cleanup {
1293 llvm::Function *OutlinedFinally;
1294 PerformSEHFinally(llvm::Function *OutlinedFinally)
1295 : OutlinedFinally(OutlinedFinally) {}
Reid Kleckneraca01db2015-02-04 22:37:07 +00001296
Reid Kleckner1d59f992015-01-22 01:36:17 +00001297 void Emit(CodeGenFunction &CGF, Flags F) override {
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001298 ASTContext &Context = CGF.getContext();
Reid Klecknerbe9843c2015-04-29 21:55:21 +00001299 CodeGenModule &CGM = CGF.CGM;
Reid Kleckner0bb12a82015-04-29 17:17:17 +00001300
Reid Kleckneraf676022015-04-30 22:13:05 +00001301 // In 64-bit, we call the child function with arguments. In 32-bit, we store
1302 // zero in the parent frame and use framerecover to check the value.
1303 const CGFunctionInfo *FnInfo;
1304 CallArgList Args;
1305 if (CGF.getTarget().getTriple().getArch() == llvm::Triple::x86_64) {
1306 // Compute the two argument values.
1307 QualType ArgTys[2] = {Context.UnsignedCharTy, Context.VoidPtrTy};
1308 llvm::Value *FrameAddr = CGM.getIntrinsic(llvm::Intrinsic::frameaddress);
1309 llvm::Value *FP =
1310 CGF.Builder.CreateCall(FrameAddr, CGF.Builder.getInt32(0));
1311 llvm::Value *IsForEH =
1312 llvm::ConstantInt::get(CGF.ConvertType(ArgTys[0]), F.isForEHCleanup());
1313 Args.add(RValue::get(IsForEH), ArgTys[0]);
1314 Args.add(RValue::get(FP), ArgTys[1]);
1315
1316 // Arrange a two-arg function info and type.
1317 FunctionProtoType::ExtProtoInfo EPI;
1318 const auto *FPT = cast<FunctionProtoType>(
1319 Context.getFunctionType(Context.VoidTy, ArgTys, EPI));
1320 FnInfo = &CGM.getTypes().arrangeFreeFunctionCall(Args, FPT,
1321 /*chainCall=*/false);
1322 } else {
1323 // Emit the zero store if this is normal control flow. There are no
1324 // explicit arguments.
1325 if (F.isForNormalCleanup() && CGF.ChildAbnormalTerminationSlot)
1326 CGF.Builder.CreateStore(CGF.Builder.getInt32(0),
1327 CGF.ChildAbnormalTerminationSlot);
1328 FnInfo = &CGM.getTypes().arrangeNullaryFunction();
1329 }
1330
1331 CGF.EmitCall(*FnInfo, OutlinedFinally, ReturnValueSlot(), Args);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001332 }
1333};
1334}
1335
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001336namespace {
1337/// Find all local variable captures in the statement.
1338struct CaptureFinder : ConstStmtVisitor<CaptureFinder> {
1339 CodeGenFunction &ParentCGF;
1340 const VarDecl *ParentThis;
1341 SmallVector<const VarDecl *, 4> Captures;
Reid Kleckneraf676022015-04-30 22:13:05 +00001342 llvm::Value *AbnormalTermination = nullptr;
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001343 CaptureFinder(CodeGenFunction &ParentCGF, const VarDecl *ParentThis)
1344 : ParentCGF(ParentCGF), ParentThis(ParentThis) {}
1345
1346 void Visit(const Stmt *S) {
1347 // See if this is a capture, then recurse.
1348 ConstStmtVisitor<CaptureFinder>::Visit(S);
1349 for (const Stmt *Child : S->children())
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001350 if (Child)
1351 Visit(Child);
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001352 }
1353
1354 void VisitDeclRefExpr(const DeclRefExpr *E) {
1355 // If this is already a capture, just make sure we capture 'this'.
1356 if (E->refersToEnclosingVariableOrCapture()) {
1357 Captures.push_back(ParentThis);
1358 return;
1359 }
1360
1361 const auto *D = dyn_cast<VarDecl>(E->getDecl());
1362 if (D && D->isLocalVarDeclOrParm() && D->hasLocalStorage())
1363 Captures.push_back(D);
1364 }
1365
1366 void VisitCXXThisExpr(const CXXThisExpr *E) {
1367 Captures.push_back(ParentThis);
1368 }
Reid Kleckneraf676022015-04-30 22:13:05 +00001369
1370 void VisitCallExpr(const CallExpr *E) {
1371 // We only need to add parent frame allocations for these builtins in x86.
1372 if (ParentCGF.getTarget().getTriple().getArch() != llvm::Triple::x86)
1373 return;
1374
1375 unsigned ID = E->getBuiltinCallee();
1376 switch (ID) {
1377 case Builtin::BI__abnormal_termination:
1378 case Builtin::BI_abnormal_termination:
1379 // This is the simple case where we are the outermost finally. All we
1380 // have to do here is make sure we escape this and recover it in the
1381 // outlined handler.
1382 if (!AbnormalTermination)
1383 AbnormalTermination = ParentCGF.CreateMemTemp(
1384 ParentCGF.getContext().IntTy, "abnormal_termination");
1385 break;
1386 }
1387 }
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001388};
1389}
1390
Reid Kleckneraf676022015-04-30 22:13:05 +00001391llvm::Value *CodeGenFunction::recoverAddrOfEscapedLocal(
1392 CodeGenFunction &ParentCGF, llvm::Value *ParentVar, llvm::Value *ParentFP) {
1393 llvm::CallInst *RecoverCall = nullptr;
1394 CGBuilderTy Builder(AllocaInsertPt);
1395 if (auto *ParentAlloca = dyn_cast<llvm::AllocaInst>(ParentVar)) {
1396 // Mark the variable escaped if nobody else referenced it and compute the
1397 // frameescape index.
1398 auto InsertPair = ParentCGF.EscapedLocals.insert(
1399 std::make_pair(ParentAlloca, ParentCGF.EscapedLocals.size()));
1400 int FrameEscapeIdx = InsertPair.first->second;
1401 // call i8* @llvm.framerecover(i8* bitcast(@parentFn), i8* %fp, i32 N)
1402 llvm::Function *FrameRecoverFn = llvm::Intrinsic::getDeclaration(
1403 &CGM.getModule(), llvm::Intrinsic::framerecover);
1404 llvm::Constant *ParentI8Fn =
1405 llvm::ConstantExpr::getBitCast(ParentCGF.CurFn, Int8PtrTy);
1406 RecoverCall =
1407 Builder.CreateCall3(FrameRecoverFn, ParentI8Fn, ParentFP,
1408 llvm::ConstantInt::get(Int32Ty, FrameEscapeIdx));
1409
1410 } else {
1411 // If the parent didn't have an alloca, we're doing some nested outlining.
1412 // Just clone the existing framerecover call, but tweak the FP argument to
1413 // use our FP value. All other arguments are constants.
1414 auto *ParentRecover =
1415 cast<llvm::IntrinsicInst>(ParentVar->stripPointerCasts());
1416 assert(ParentRecover->getIntrinsicID() == llvm::Intrinsic::framerecover &&
1417 "expected alloca or framerecover in parent LocalDeclMap");
1418 RecoverCall = cast<llvm::CallInst>(ParentRecover->clone());
1419 RecoverCall->setArgOperand(1, ParentFP);
1420 RecoverCall->insertBefore(AllocaInsertPt);
1421 }
1422
1423 // Bitcast the variable, rename it, and insert it in the local decl map.
1424 llvm::Value *ChildVar =
1425 Builder.CreateBitCast(RecoverCall, ParentVar->getType());
1426 ChildVar->setName(ParentVar->getName());
1427 return ChildVar;
1428}
1429
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001430void CodeGenFunction::EmitCapturedLocals(CodeGenFunction &ParentCGF,
Reid Kleckneraf676022015-04-30 22:13:05 +00001431 const Stmt *OutlinedStmt) {
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001432 // Find all captures in the Stmt.
1433 CaptureFinder Finder(ParentCGF, ParentCGF.CXXABIThisDecl);
1434 Finder.Visit(OutlinedStmt);
1435
1436 // Typically there are no captures and we can exit early.
Reid Kleckneraf676022015-04-30 22:13:05 +00001437 if (Finder.Captures.empty() && !Finder.AbnormalTermination)
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001438 return;
1439
Reid Kleckneraf676022015-04-30 22:13:05 +00001440 // The parent FP is passed in as EBP on x86 and the second argument on x64.
1441 llvm::Value *ParentFP;
1442 if (CGM.getTarget().getTriple().getArch() == llvm::Triple::x86_64) {
1443 auto AI = CurFn->arg_begin();
1444 ++AI;
1445 ParentFP = AI;
1446 } else {
1447 CGBuilderTy Builder(AllocaInsertPt);
1448 ParentFP = Builder.CreateCall(
1449 CGM.getIntrinsic(llvm::Intrinsic::frameaddress), Builder.getInt32(1));
1450
1451 // Inlining will break llvm.frameaddress(1), so disable it.
1452 // FIXME: We could teach the inliner about the special meaning of
1453 // frameaddress, framerecover, and frameescape to remove this limitation.
1454 CurFn->addFnAttr(llvm::Attribute::NoInline);
1455 }
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001456
1457 // Create llvm.framerecover calls for all captures.
1458 for (const VarDecl *VD : Finder.Captures) {
1459 if (isa<ImplicitParamDecl>(VD)) {
1460 CGM.ErrorUnsupported(VD, "'this' captured by SEH");
1461 CXXThisValue = llvm::UndefValue::get(ConvertTypeForMem(VD->getType()));
1462 continue;
1463 }
1464 if (VD->getType()->isVariablyModifiedType()) {
1465 CGM.ErrorUnsupported(VD, "VLA captured by SEH");
1466 continue;
1467 }
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001468 assert((isa<ImplicitParamDecl>(VD) || VD->isLocalVarDeclOrParm()) &&
1469 "captured non-local variable");
1470
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001471 // If this decl hasn't been declared yet, it will be declared in the
1472 // OutlinedStmt.
1473 auto I = ParentCGF.LocalDeclMap.find(VD);
1474 if (I == ParentCGF.LocalDeclMap.end())
1475 continue;
1476 llvm::Value *ParentVar = I->second;
1477
Reid Kleckneraf676022015-04-30 22:13:05 +00001478 LocalDeclMap[VD] =
1479 recoverAddrOfEscapedLocal(ParentCGF, ParentVar, ParentFP);
1480 }
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001481
Reid Kleckneraf676022015-04-30 22:13:05 +00001482 // AbnormalTermination is just another capture, but it has no Decl.
1483 if (Finder.AbnormalTermination) {
1484 AbnormalTerminationSlot = recoverAddrOfEscapedLocal(
1485 ParentCGF, Finder.AbnormalTermination, ParentFP);
1486 // Save the slot on the parent so it can store 1 and 0 to it.
1487 ParentCGF.ChildAbnormalTerminationSlot = Finder.AbnormalTermination;
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001488 }
1489}
1490
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001491/// Arrange a function prototype that can be called by Windows exception
1492/// handling personalities. On Win64, the prototype looks like:
1493/// RetTy func(void *EHPtrs, void *ParentFP);
1494void CodeGenFunction::startOutlinedSEHHelper(CodeGenFunction &ParentCGF,
1495 StringRef Name, QualType RetTy,
1496 FunctionArgList &Args,
1497 const Stmt *OutlinedStmt) {
Reid Kleckner1d59f992015-01-22 01:36:17 +00001498 llvm::Function *ParentFn = ParentCGF.CurFn;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001499 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionDeclaration(
1500 RetTy, Args, FunctionType::ExtInfo(), /*isVariadic=*/false);
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001501
Reid Kleckner1d59f992015-01-22 01:36:17 +00001502 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001503 llvm::Function *Fn = llvm::Function::Create(
1504 FnTy, llvm::GlobalValue::InternalLinkage, Name.str(), &CGM.getModule());
Reid Kleckner1d59f992015-01-22 01:36:17 +00001505 // The filter is either in the same comdat as the function, or it's internal.
1506 if (llvm::Comdat *C = ParentFn->getComdat()) {
1507 Fn->setComdat(C);
1508 } else if (ParentFn->hasWeakLinkage() || ParentFn->hasLinkOnceLinkage()) {
Reid Kleckner1d59f992015-01-22 01:36:17 +00001509 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(ParentFn->getName());
1510 ParentFn->setComdat(C);
1511 Fn->setComdat(C);
1512 } else {
1513 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
1514 }
1515
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001516 IsOutlinedSEHHelper = true;
Nico Weberf2a39a72015-04-13 20:03:03 +00001517
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001518 StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args,
1519 OutlinedStmt->getLocStart(), OutlinedStmt->getLocStart());
1520
1521 CGM.SetLLVMFunctionAttributes(nullptr, FnInfo, CurFn);
Reid Kleckneraf676022015-04-30 22:13:05 +00001522 EmitCapturedLocals(ParentCGF, OutlinedStmt);
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001523}
1524
1525/// Create a stub filter function that will ultimately hold the code of the
1526/// filter expression. The EH preparation passes in LLVM will outline the code
1527/// from the main function body into this stub.
1528llvm::Function *
1529CodeGenFunction::GenerateSEHFilterFunction(CodeGenFunction &ParentCGF,
1530 const SEHExceptStmt &Except) {
1531 const Expr *FilterExpr = Except.getFilterExpr();
1532 SourceLocation StartLoc = FilterExpr->getLocStart();
1533
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001534 FunctionArgList Args;
Reid Kleckneraf676022015-04-30 22:13:05 +00001535 if (CGM.getTarget().getTriple().getArch() == llvm::Triple::x86_64) {
1536 SEHPointersDecl = ImplicitParamDecl::Create(
1537 getContext(), nullptr, StartLoc,
1538 &getContext().Idents.get("exception_pointers"), getContext().VoidPtrTy);
1539 Args.push_back(SEHPointersDecl);
1540 Args.push_back(ImplicitParamDecl::Create(
1541 getContext(), nullptr, StartLoc,
1542 &getContext().Idents.get("frame_pointer"), getContext().VoidPtrTy));
1543 }
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001544
1545 // Get the mangled function name.
1546 SmallString<128> Name;
1547 {
1548 llvm::raw_svector_ostream OS(Name);
1549 const Decl *ParentCodeDecl = ParentCGF.CurCodeDecl;
1550 const NamedDecl *Parent = dyn_cast_or_null<NamedDecl>(ParentCodeDecl);
1551 assert(Parent && "FIXME: handle unnamed decls (lambdas, blocks) with SEH");
1552 CGM.getCXXABI().getMangleContext().mangleSEHFilterExpression(Parent, OS);
1553 }
1554
David Majnemer2ccba832015-04-17 06:57:25 +00001555 startOutlinedSEHHelper(ParentCGF, Name, getContext().LongTy, Args,
1556 FilterExpr);
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001557
1558 // Mark finally block calls as nounwind and noinline to make LLVM's job a
1559 // little easier.
1560 // FIXME: Remove these restrictions in the future.
1561 CurFn->addFnAttr(llvm::Attribute::NoUnwind);
1562 CurFn->addFnAttr(llvm::Attribute::NoInline);
1563
1564 EmitSEHExceptionCodeSave();
Reid Kleckner1d59f992015-01-22 01:36:17 +00001565
1566 // Emit the original filter expression, convert to i32, and return.
1567 llvm::Value *R = EmitScalarExpr(FilterExpr);
David Majnemer2ccba832015-04-17 06:57:25 +00001568 R = Builder.CreateIntCast(R, ConvertType(getContext().LongTy),
Reid Kleckner1d59f992015-01-22 01:36:17 +00001569 FilterExpr->getType()->isSignedIntegerType());
1570 Builder.CreateStore(R, ReturnValue);
1571
1572 FinishFunction(FilterExpr->getLocEnd());
1573
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001574 return CurFn;
1575}
1576
1577llvm::Function *
1578CodeGenFunction::GenerateSEHFinallyFunction(CodeGenFunction &ParentCGF,
1579 const SEHFinallyStmt &Finally) {
1580 const Stmt *FinallyBlock = Finally.getBlock();
1581 SourceLocation StartLoc = FinallyBlock->getLocStart();
1582
1583 FunctionArgList Args;
Reid Kleckneraf676022015-04-30 22:13:05 +00001584 if (CGM.getTarget().getTriple().getArch() == llvm::Triple::x86_64) {
1585 Args.push_back(ImplicitParamDecl::Create(
1586 getContext(), nullptr, StartLoc,
1587 &getContext().Idents.get("abnormal_termination"),
1588 getContext().UnsignedCharTy));
1589 Args.push_back(ImplicitParamDecl::Create(
1590 getContext(), nullptr, StartLoc,
1591 &getContext().Idents.get("frame_pointer"), getContext().VoidPtrTy));
1592 }
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001593
1594 // Get the mangled function name.
1595 SmallString<128> Name;
1596 {
1597 llvm::raw_svector_ostream OS(Name);
1598 const Decl *ParentCodeDecl = ParentCGF.CurCodeDecl;
1599 const NamedDecl *Parent = dyn_cast_or_null<NamedDecl>(ParentCodeDecl);
1600 assert(Parent && "FIXME: handle unnamed decls (lambdas, blocks) with SEH");
1601 CGM.getCXXABI().getMangleContext().mangleSEHFinallyBlock(Parent, OS);
1602 }
1603
1604 startOutlinedSEHHelper(ParentCGF, Name, getContext().VoidTy, Args,
1605 FinallyBlock);
1606
1607 // Emit the original filter expression, convert to i32, and return.
1608 EmitStmt(FinallyBlock);
1609
1610 FinishFunction(FinallyBlock->getLocEnd());
1611
1612 return CurFn;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001613}
1614
1615void CodeGenFunction::EmitSEHExceptionCodeSave() {
1616 // Save the exception code in the exception slot to unify exception access in
1617 // the filter function and the landing pad.
1618 // struct EXCEPTION_POINTERS {
1619 // EXCEPTION_RECORD *ExceptionRecord;
1620 // CONTEXT *ContextRecord;
1621 // };
1622 // void *exn.slot =
1623 // (void *)(uintptr_t)exception_pointers->ExceptionRecord->ExceptionCode;
Reid Kleckneraf676022015-04-30 22:13:05 +00001624 llvm::Value *Ptrs = EmitSEHExceptionInfo();
Reid Kleckner1d59f992015-01-22 01:36:17 +00001625 llvm::Type *RecordTy = CGM.Int32Ty->getPointerTo();
1626 llvm::Type *PtrsTy = llvm::StructType::get(RecordTy, CGM.VoidPtrTy, nullptr);
1627 Ptrs = Builder.CreateBitCast(Ptrs, PtrsTy->getPointerTo());
David Blaikie1ed728c2015-04-05 22:45:47 +00001628 llvm::Value *Rec = Builder.CreateStructGEP(PtrsTy, Ptrs, 0);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001629 Rec = Builder.CreateLoad(Rec);
1630 llvm::Value *Code = Builder.CreateLoad(Rec);
1631 Code = Builder.CreateZExt(Code, CGM.IntPtrTy);
1632 // FIXME: Change landing pads to produce {i32, i32} and make the exception
1633 // slot an i32.
1634 Code = Builder.CreateIntToPtr(Code, CGM.VoidPtrTy);
1635 Builder.CreateStore(Code, getExceptionSlot());
1636}
1637
1638llvm::Value *CodeGenFunction::EmitSEHExceptionInfo() {
Reid Kleckneraf676022015-04-30 22:13:05 +00001639 if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86_64)
1640 return Builder.CreateCall(
1641 CGM.getIntrinsic(llvm::Intrinsic::eh_exceptioninfo));
Reid Kleckner1d59f992015-01-22 01:36:17 +00001642 // Sema should diagnose calling this builtin outside of a filter context, but
1643 // don't crash if we screw up.
1644 if (!SEHPointersDecl)
1645 return llvm::UndefValue::get(Int8PtrTy);
1646 return Builder.CreateLoad(GetAddrOfLocalVar(SEHPointersDecl));
1647}
1648
1649llvm::Value *CodeGenFunction::EmitSEHExceptionCode() {
1650 // If we're in a landing pad or filter function, the exception slot contains
1651 // the code.
1652 assert(ExceptionSlot);
1653 llvm::Value *Code =
1654 Builder.CreatePtrToInt(getExceptionFromSlot(), CGM.IntPtrTy);
1655 return Builder.CreateTrunc(Code, CGM.Int32Ty);
1656}
1657
Reid Kleckneraca01db2015-02-04 22:37:07 +00001658llvm::Value *CodeGenFunction::EmitSEHAbnormalTermination() {
Reid Kleckneraf676022015-04-30 22:13:05 +00001659 if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86_64)
1660 return Builder.CreateLoad(AbnormalTerminationSlot);
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001661 // Abnormal termination is just the first parameter to the outlined finally
1662 // helper.
1663 auto AI = CurFn->arg_begin();
1664 return Builder.CreateZExt(&*AI, Int32Ty);
Reid Kleckneraca01db2015-02-04 22:37:07 +00001665}
1666
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001667void CodeGenFunction::EnterSEHTryStmt(const SEHTryStmt &S) {
1668 CodeGenFunction HelperCGF(CGM, /*suppressNewContext=*/true);
1669 if (const SEHFinallyStmt *Finally = S.getFinallyHandler()) {
Reid Kleckneraf676022015-04-30 22:13:05 +00001670 // Outline the finally block.
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001671 llvm::Function *FinallyFunc =
1672 HelperCGF.GenerateSEHFinallyFunction(*this, *Finally);
Reid Kleckneraf676022015-04-30 22:13:05 +00001673
1674 // Store 1 to indicate abnormal termination if an exception is thrown.
1675 if (ChildAbnormalTerminationSlot)
1676 Builder.CreateStore(Builder.getInt32(1), ChildAbnormalTerminationSlot);
1677
1678 // Push a cleanup for __finally blocks.
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001679 EHStack.pushCleanup<PerformSEHFinally>(NormalAndEHCleanup, FinallyFunc);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001680 return;
1681 }
1682
1683 // Otherwise, we must have an __except block.
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001684 const SEHExceptStmt *Except = S.getExceptHandler();
Reid Kleckner1d59f992015-01-22 01:36:17 +00001685 assert(Except);
1686 EHCatchScope *CatchScope = EHStack.pushCatch(1);
Reid Kleckner2a2e1562015-01-22 02:25:56 +00001687
1688 // If the filter is known to evaluate to 1, then we can use the clause "catch
1689 // i8* null".
1690 llvm::Constant *C =
1691 CGM.EmitConstantExpr(Except->getFilterExpr(), getContext().IntTy, this);
1692 if (C && C->isOneValue()) {
1693 CatchScope->setCatchAllHandler(0, createBasicBlock("__except"));
1694 return;
1695 }
1696
1697 // In general, we have to emit an outlined filter function. Use the function
1698 // in place of the RTTI typeinfo global that C++ EH uses.
Reid Kleckner1d59f992015-01-22 01:36:17 +00001699 llvm::Function *FilterFunc =
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001700 HelperCGF.GenerateSEHFilterFunction(*this, *Except);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001701 llvm::Constant *OpaqueFunc =
1702 llvm::ConstantExpr::getBitCast(FilterFunc, Int8PtrTy);
1703 CatchScope->setHandler(0, OpaqueFunc, createBasicBlock("__except"));
1704}
1705
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001706void CodeGenFunction::ExitSEHTryStmt(const SEHTryStmt &S) {
Reid Kleckner1d59f992015-01-22 01:36:17 +00001707 // Just pop the cleanup if it's a __finally block.
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001708 if (S.getFinallyHandler()) {
Reid Kleckner1d59f992015-01-22 01:36:17 +00001709 PopCleanupBlock();
Reid Kleckneraf676022015-04-30 22:13:05 +00001710 ChildAbnormalTerminationSlot = nullptr;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001711 return;
1712 }
1713
1714 // Otherwise, we must have an __except block.
Reid Kleckneraca01db2015-02-04 22:37:07 +00001715 const SEHExceptStmt *Except = S.getExceptHandler();
Reid Kleckner1d59f992015-01-22 01:36:17 +00001716 assert(Except && "__try must have __finally xor __except");
1717 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1718
1719 // Don't emit the __except block if the __try block lacked invokes.
1720 // TODO: Model unwind edges from instructions, either with iload / istore or
1721 // a try body function.
1722 if (!CatchScope.hasEHBranches()) {
1723 CatchScope.clearHandlerBlocks();
1724 EHStack.popCatch();
1725 return;
1726 }
1727
1728 // The fall-through block.
1729 llvm::BasicBlock *ContBB = createBasicBlock("__try.cont");
1730
1731 // We just emitted the body of the __try; jump to the continue block.
1732 if (HaveInsertPoint())
1733 Builder.CreateBr(ContBB);
1734
1735 // Check if our filter function returned true.
1736 emitCatchDispatchBlock(*this, CatchScope);
1737
1738 // Grab the block before we pop the handler.
1739 llvm::BasicBlock *ExceptBB = CatchScope.getHandler(0).Block;
1740 EHStack.popCatch();
1741
1742 EmitBlockAfterUses(ExceptBB);
1743
1744 // Emit the __except body.
1745 EmitStmt(Except->getBlock());
1746
Reid Kleckner3a417c32015-01-30 22:16:45 +00001747 if (HaveInsertPoint())
1748 Builder.CreateBr(ContBB);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001749
1750 EmitBlock(ContBB);
Reid Kleckner543a16c2013-09-16 21:46:30 +00001751}
Nico Weber9b982072014-07-07 00:12:30 +00001752
1753void CodeGenFunction::EmitSEHLeaveStmt(const SEHLeaveStmt &S) {
Nico Weber5779f842015-02-12 23:16:11 +00001754 // If this code is reachable then emit a stop point (if generating
1755 // debug info). We have to do this ourselves because we are on the
1756 // "simple" statement path.
1757 if (HaveInsertPoint())
1758 EmitStopPoint(&S);
1759
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001760 // This must be a __leave from a __finally block, which we warn on and is UB.
1761 // Just emit unreachable.
1762 if (!isSEHTryScope()) {
1763 Builder.CreateUnreachable();
1764 Builder.ClearInsertionPoint();
1765 return;
1766 }
1767
Nico Weber5779f842015-02-12 23:16:11 +00001768 EmitBranchThroughCleanup(*SEHTryEpilogueStack.back());
Nico Weber9b982072014-07-07 00:12:30 +00001769}