blob: 255cb841c861488da0b06cf125c21b7c0d590b68 [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 Kleckner9fe7f232015-07-07 00:36:30 +000023#include "clang/Basic/TargetBuiltins.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000024#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000025#include "llvm/IR/Intrinsics.h"
Reid Kleckner31a1bb02015-04-08 22:23:48 +000026#include "llvm/IR/IntrinsicInst.h"
Reid Klecknerebaf28d2015-04-14 20:59:00 +000027#include "llvm/Support/SaveAndRestore.h"
John McCallbd309292010-07-06 01:34:17 +000028
Anders Carlsson4b08db72009-10-30 01:42:31 +000029using namespace clang;
30using namespace CodeGen;
31
John McCall2c33ba82013-02-12 03:51:38 +000032static llvm::Constant *getFreeExceptionFn(CodeGenModule &CGM) {
Mike Stump33270212009-12-02 07:41:41 +000033 // void __cxa_free_exception(void *thrown_exception);
Mike Stump75546b82009-12-10 00:06:18 +000034
Chris Lattner2192fe52011-07-18 04:24:23 +000035 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +000036 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000037
John McCall2c33ba82013-02-12 03:51:38 +000038 return CGM.CreateRuntimeFunction(FTy, "__cxa_free_exception");
Mike Stump33270212009-12-02 07:41:41 +000039}
40
John McCall2c33ba82013-02-12 03:51:38 +000041static llvm::Constant *getUnexpectedFn(CodeGenModule &CGM) {
Richard Smith2f7aa192013-06-20 23:03:35 +000042 // void __cxa_call_unexpected(void *thrown_exception);
Mike Stump1d849212009-12-07 23:38:24 +000043
Chris Lattner2192fe52011-07-18 04:24:23 +000044 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +000045 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000046
John McCall2c33ba82013-02-12 03:51:38 +000047 return CGM.CreateRuntimeFunction(FTy, "__cxa_call_unexpected");
Mike Stump1d849212009-12-07 23:38:24 +000048}
49
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000050llvm::Constant *CodeGenModule::getTerminateFn() {
Mike Stump33270212009-12-02 07:41:41 +000051 // void __terminate();
52
Chris Lattner2192fe52011-07-18 04:24:23 +000053 llvm::FunctionType *FTy =
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000054 llvm::FunctionType::get(VoidTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000055
Chris Lattner0e62c1c2011-07-23 10:55:15 +000056 StringRef name;
John McCall9de19782011-07-06 01:22:26 +000057
58 // In C++, use std::terminate().
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000059 if (getLangOpts().CPlusPlus &&
60 getTarget().getCXXABI().isItaniumFamily()) {
Reid Kleckner1d59f992015-01-22 01:36:17 +000061 name = "_ZSt9terminatev";
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000062 } else if (getLangOpts().CPlusPlus &&
63 getTarget().getCXXABI().isMicrosoft()) {
David Majnemerb710a932015-05-11 03:57:49 +000064 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
David Majnemerfb6ffca2015-05-10 21:38:26 +000065 name = "__std_terminate";
66 else
67 name = "\01?terminate@@YAXXZ";
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000068 } else if (getLangOpts().ObjC1 &&
69 getLangOpts().ObjCRuntime.hasTerminate())
John McCall9de19782011-07-06 01:22:26 +000070 name = "objc_terminate";
71 else
72 name = "abort";
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000073 return CreateRuntimeFunction(FTy, name);
David Chisnallf9c42252010-05-17 13:49:20 +000074}
75
John McCall2c33ba82013-02-12 03:51:38 +000076static llvm::Constant *getCatchallRethrowFn(CodeGenModule &CGM,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000077 StringRef Name) {
Chris Lattner2192fe52011-07-18 04:24:23 +000078 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +000079 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
John McCall36ea3722010-07-17 00:43:08 +000080
John McCall2c33ba82013-02-12 03:51:38 +000081 return CGM.CreateRuntimeFunction(FTy, Name);
John McCallbd309292010-07-06 01:34:17 +000082}
83
Craig Topper8a13c412014-05-21 05:09:00 +000084const EHPersonality EHPersonality::GNU_C = { "__gcc_personality_v0", nullptr };
Benjamin Kramer793bd552012-02-08 12:41:24 +000085const EHPersonality
Craig Topper8a13c412014-05-21 05:09:00 +000086EHPersonality::GNU_C_SJLJ = { "__gcc_personality_sj0", nullptr };
87const EHPersonality
Reid Kleckner8f45c9c2014-09-15 17:19:16 +000088EHPersonality::GNU_C_SEH = { "__gcc_personality_seh0", nullptr };
89const EHPersonality
Craig Topper8a13c412014-05-21 05:09:00 +000090EHPersonality::NeXT_ObjC = { "__objc_personality_v0", nullptr };
91const EHPersonality
92EHPersonality::GNU_CPlusPlus = { "__gxx_personality_v0", nullptr };
93const EHPersonality
94EHPersonality::GNU_CPlusPlus_SJLJ = { "__gxx_personality_sj0", nullptr };
Benjamin Kramer793bd552012-02-08 12:41:24 +000095const EHPersonality
Reid Kleckner8f45c9c2014-09-15 17:19:16 +000096EHPersonality::GNU_CPlusPlus_SEH = { "__gxx_personality_seh0", nullptr };
97const EHPersonality
Benjamin Kramer793bd552012-02-08 12:41:24 +000098EHPersonality::GNU_ObjC = {"__gnu_objc_personality_v0", "objc_exception_throw"};
99const EHPersonality
Craig Topper8a13c412014-05-21 05:09:00 +0000100EHPersonality::GNU_ObjCXX = { "__gnustep_objcxx_personality_v0", nullptr };
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000101const EHPersonality
Craig Topper8a13c412014-05-21 05:09:00 +0000102EHPersonality::GNUstep_ObjC = { "__gnustep_objc_personality_v0", nullptr };
Reid Kleckner1d59f992015-01-22 01:36:17 +0000103const EHPersonality
104EHPersonality::MSVC_except_handler = { "_except_handler3", nullptr };
105const EHPersonality
106EHPersonality::MSVC_C_specific_handler = { "__C_specific_handler", nullptr };
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000107const EHPersonality
108EHPersonality::MSVC_CxxFrameHandler3 = { "__CxxFrameHandler3", nullptr };
John McCall36ea3722010-07-17 00:43:08 +0000109
Reid Klecknere070b992014-11-14 02:01:10 +0000110/// On Win64, use libgcc's SEH personality function. We fall back to dwarf on
111/// other platforms, unless the user asked for SjLj exceptions.
112static bool useLibGCCSEHPersonality(const llvm::Triple &T) {
113 return T.isOSWindows() && T.getArch() == llvm::Triple::x86_64;
114}
115
116static const EHPersonality &getCPersonality(const llvm::Triple &T,
117 const LangOptions &L) {
John McCall2faab302010-11-07 02:35:25 +0000118 if (L.SjLjExceptions)
119 return EHPersonality::GNU_C_SJLJ;
Reid Klecknere070b992014-11-14 02:01:10 +0000120 else if (useLibGCCSEHPersonality(T))
Reid Kleckner8f45c9c2014-09-15 17:19:16 +0000121 return EHPersonality::GNU_C_SEH;
John McCall36ea3722010-07-17 00:43:08 +0000122 return EHPersonality::GNU_C;
123}
124
Reid Klecknere070b992014-11-14 02:01:10 +0000125static const EHPersonality &getObjCPersonality(const llvm::Triple &T,
126 const LangOptions &L) {
John McCall5fb5df92012-06-20 06:18:46 +0000127 switch (L.ObjCRuntime.getKind()) {
128 case ObjCRuntime::FragileMacOSX:
Reid Klecknere070b992014-11-14 02:01:10 +0000129 return getCPersonality(T, L);
John McCall5fb5df92012-06-20 06:18:46 +0000130 case ObjCRuntime::MacOSX:
131 case ObjCRuntime::iOS:
132 return EHPersonality::NeXT_ObjC;
David Chisnallb601c962012-07-03 20:49:52 +0000133 case ObjCRuntime::GNUstep:
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000134 if (L.ObjCRuntime.getVersion() >= VersionTuple(1, 7))
135 return EHPersonality::GNUstep_ObjC;
136 // fallthrough
David Chisnallb601c962012-07-03 20:49:52 +0000137 case ObjCRuntime::GCC:
John McCall775086e2012-07-12 02:07:58 +0000138 case ObjCRuntime::ObjFW:
John McCall36ea3722010-07-17 00:43:08 +0000139 return EHPersonality::GNU_ObjC;
John McCallbd309292010-07-06 01:34:17 +0000140 }
John McCall5fb5df92012-06-20 06:18:46 +0000141 llvm_unreachable("bad runtime kind");
John McCallbd309292010-07-06 01:34:17 +0000142}
143
Reid Klecknere070b992014-11-14 02:01:10 +0000144static const EHPersonality &getCXXPersonality(const llvm::Triple &T,
145 const LangOptions &L) {
John McCall36ea3722010-07-17 00:43:08 +0000146 if (L.SjLjExceptions)
147 return EHPersonality::GNU_CPlusPlus_SJLJ;
Reid Klecknere070b992014-11-14 02:01:10 +0000148 else if (useLibGCCSEHPersonality(T))
Reid Kleckner8f45c9c2014-09-15 17:19:16 +0000149 return EHPersonality::GNU_CPlusPlus_SEH;
Reid Klecknere070b992014-11-14 02:01:10 +0000150 return EHPersonality::GNU_CPlusPlus;
John McCallbd309292010-07-06 01:34:17 +0000151}
152
153/// Determines the personality function to use when both C++
154/// and Objective-C exceptions are being caught.
Reid Klecknere070b992014-11-14 02:01:10 +0000155static const EHPersonality &getObjCXXPersonality(const llvm::Triple &T,
156 const LangOptions &L) {
John McCall5fb5df92012-06-20 06:18:46 +0000157 switch (L.ObjCRuntime.getKind()) {
John McCallbd309292010-07-06 01:34:17 +0000158 // The ObjC personality defers to the C++ personality for non-ObjC
159 // handlers. Unlike the C++ case, we use the same personality
160 // function on targets using (backend-driven) SJLJ EH.
John McCall5fb5df92012-06-20 06:18:46 +0000161 case ObjCRuntime::MacOSX:
162 case ObjCRuntime::iOS:
163 return EHPersonality::NeXT_ObjC;
John McCallbd309292010-07-06 01:34:17 +0000164
John McCall5fb5df92012-06-20 06:18:46 +0000165 // In the fragile ABI, just use C++ exception handling and hope
166 // they're not doing crazy exception mixing.
167 case ObjCRuntime::FragileMacOSX:
Reid Klecknere070b992014-11-14 02:01:10 +0000168 return getCXXPersonality(T, L);
David Chisnallf9c42252010-05-17 13:49:20 +0000169
David Chisnallb601c962012-07-03 20:49:52 +0000170 // The GCC runtime's personality function inherently doesn't support
John McCall36ea3722010-07-17 00:43:08 +0000171 // mixed EH. Use the C++ personality just to avoid returning null.
David Chisnallb601c962012-07-03 20:49:52 +0000172 case ObjCRuntime::GCC:
John McCall775086e2012-07-12 02:07:58 +0000173 case ObjCRuntime::ObjFW: // XXX: this will change soon
David Chisnallb601c962012-07-03 20:49:52 +0000174 return EHPersonality::GNU_ObjC;
175 case ObjCRuntime::GNUstep:
John McCall5fb5df92012-06-20 06:18:46 +0000176 return EHPersonality::GNU_ObjCXX;
177 }
178 llvm_unreachable("bad runtime kind");
John McCallbd309292010-07-06 01:34:17 +0000179}
180
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000181static const EHPersonality &getSEHPersonalityMSVC(const llvm::Triple &T) {
Reid Kleckner1d59f992015-01-22 01:36:17 +0000182 if (T.getArch() == llvm::Triple::x86)
183 return EHPersonality::MSVC_except_handler;
184 return EHPersonality::MSVC_C_specific_handler;
185}
186
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000187const EHPersonality &EHPersonality::get(CodeGenModule &CGM,
188 const FunctionDecl *FD) {
Reid Klecknere070b992014-11-14 02:01:10 +0000189 const llvm::Triple &T = CGM.getTarget().getTriple();
190 const LangOptions &L = CGM.getLangOpts();
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000191
Reid Kleckner1d59f992015-01-22 01:36:17 +0000192 // Try to pick a personality function that is compatible with MSVC if we're
193 // not compiling Obj-C. Obj-C users better have an Obj-C runtime that supports
194 // the GCC-style personality function.
195 if (T.isWindowsMSVCEnvironment() && !L.ObjC1) {
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000196 if (L.SjLjExceptions)
197 return EHPersonality::GNU_CPlusPlus_SJLJ;
198 else if (FD && FD->usesSEHTry())
199 return getSEHPersonalityMSVC(T);
Reid Kleckner1d59f992015-01-22 01:36:17 +0000200 else
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000201 return EHPersonality::MSVC_CxxFrameHandler3;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000202 }
203
John McCall36ea3722010-07-17 00:43:08 +0000204 if (L.CPlusPlus && L.ObjC1)
Reid Klecknere070b992014-11-14 02:01:10 +0000205 return getObjCXXPersonality(T, L);
John McCall36ea3722010-07-17 00:43:08 +0000206 else if (L.CPlusPlus)
Reid Klecknere070b992014-11-14 02:01:10 +0000207 return getCXXPersonality(T, L);
John McCall36ea3722010-07-17 00:43:08 +0000208 else if (L.ObjC1)
Reid Klecknere070b992014-11-14 02:01:10 +0000209 return getObjCPersonality(T, L);
John McCallbd309292010-07-06 01:34:17 +0000210 else
Reid Klecknere070b992014-11-14 02:01:10 +0000211 return getCPersonality(T, L);
John McCall36ea3722010-07-17 00:43:08 +0000212}
John McCallbd309292010-07-06 01:34:17 +0000213
David Majnemerc28d46e2015-07-22 23:46:21 +0000214const EHPersonality &EHPersonality::get(CodeGenFunction &CGF) {
215 return get(CGF.CGM, dyn_cast_or_null<FunctionDecl>(CGF.CurCodeDecl));
216}
217
John McCall0bdb1fd2010-09-16 06:16:50 +0000218static llvm::Constant *getPersonalityFn(CodeGenModule &CGM,
John McCall36ea3722010-07-17 00:43:08 +0000219 const EHPersonality &Personality) {
John McCall36ea3722010-07-17 00:43:08 +0000220 llvm::Constant *Fn =
Chris Lattnerece04092012-02-07 00:39:47 +0000221 CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.Int32Ty, true),
Benjamin Kramer793bd552012-02-08 12:41:24 +0000222 Personality.PersonalityFn);
John McCall0bdb1fd2010-09-16 06:16:50 +0000223 return Fn;
224}
225
226static llvm::Constant *getOpaquePersonalityFn(CodeGenModule &CGM,
227 const EHPersonality &Personality) {
228 llvm::Constant *Fn = getPersonalityFn(CGM, Personality);
John McCallad7c5c12011-02-08 08:22:06 +0000229 return llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
John McCall0bdb1fd2010-09-16 06:16:50 +0000230}
231
232/// Check whether a personality function could reasonably be swapped
233/// for a C++ personality function.
234static bool PersonalityHasOnlyCXXUses(llvm::Constant *Fn) {
Chandler Carruth4d01fff2014-03-09 03:16:50 +0000235 for (llvm::User *U : Fn->users()) {
John McCall0bdb1fd2010-09-16 06:16:50 +0000236 // Conditionally white-list bitcasts.
Chandler Carruth4d01fff2014-03-09 03:16:50 +0000237 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(U)) {
John McCall0bdb1fd2010-09-16 06:16:50 +0000238 if (CE->getOpcode() != llvm::Instruction::BitCast) return false;
239 if (!PersonalityHasOnlyCXXUses(CE))
240 return false;
241 continue;
242 }
243
Bill Wendling58e58fe2011-09-19 22:08:36 +0000244 // Otherwise, it has to be a landingpad instruction.
Chandler Carruth4d01fff2014-03-09 03:16:50 +0000245 llvm::LandingPadInst *LPI = dyn_cast<llvm::LandingPadInst>(U);
Bill Wendling58e58fe2011-09-19 22:08:36 +0000246 if (!LPI) return false;
John McCall0bdb1fd2010-09-16 06:16:50 +0000247
Bill Wendling58e58fe2011-09-19 22:08:36 +0000248 for (unsigned I = 0, E = LPI->getNumClauses(); I != E; ++I) {
John McCall0bdb1fd2010-09-16 06:16:50 +0000249 // Look for something that would've been returned by the ObjC
250 // runtime's GetEHType() method.
Bill Wendling58e58fe2011-09-19 22:08:36 +0000251 llvm::Value *Val = LPI->getClause(I)->stripPointerCasts();
252 if (LPI->isCatch(I)) {
253 // Check if the catch value has the ObjC prefix.
Bill Wendling5d7469e2011-09-20 00:40:19 +0000254 if (llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Val))
255 // ObjC EH selector entries are always global variables with
256 // names starting like this.
257 if (GV->getName().startswith("OBJC_EHTYPE"))
258 return false;
Bill Wendling58e58fe2011-09-19 22:08:36 +0000259 } else {
260 // Check if any of the filter values have the ObjC prefix.
261 llvm::Constant *CVal = cast<llvm::Constant>(Val);
262 for (llvm::User::op_iterator
263 II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II) {
Bill Wendling5d7469e2011-09-20 00:40:19 +0000264 if (llvm::GlobalVariable *GV =
265 cast<llvm::GlobalVariable>((*II)->stripPointerCasts()))
266 // ObjC EH selector entries are always global variables with
267 // names starting like this.
268 if (GV->getName().startswith("OBJC_EHTYPE"))
269 return false;
Bill Wendling58e58fe2011-09-19 22:08:36 +0000270 }
271 }
John McCall0bdb1fd2010-09-16 06:16:50 +0000272 }
273 }
274
275 return true;
276}
277
278/// Try to use the C++ personality function in ObjC++. Not doing this
279/// can cause some incompatibilities with gcc, which is more
280/// aggressive about only using the ObjC++ personality in a function
281/// when it really needs it.
282void CodeGenModule::SimplifyPersonality() {
John McCall0bdb1fd2010-09-16 06:16:50 +0000283 // If we're not in ObjC++ -fexceptions, there's nothing to do.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000284 if (!LangOpts.CPlusPlus || !LangOpts.ObjC1 || !LangOpts.Exceptions)
John McCall0bdb1fd2010-09-16 06:16:50 +0000285 return;
286
John McCall3c223932012-11-14 17:48:31 +0000287 // Both the problem this endeavors to fix and the way the logic
288 // above works is specific to the NeXT runtime.
289 if (!LangOpts.ObjCRuntime.isNeXTFamily())
290 return;
291
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000292 const EHPersonality &ObjCXX = EHPersonality::get(*this, /*FD=*/nullptr);
Reid Klecknere070b992014-11-14 02:01:10 +0000293 const EHPersonality &CXX =
294 getCXXPersonality(getTarget().getTriple(), LangOpts);
Benjamin Kramer793bd552012-02-08 12:41:24 +0000295 if (&ObjCXX == &CXX)
John McCall0bdb1fd2010-09-16 06:16:50 +0000296 return;
297
Benjamin Kramer793bd552012-02-08 12:41:24 +0000298 assert(std::strcmp(ObjCXX.PersonalityFn, CXX.PersonalityFn) != 0 &&
299 "Different EHPersonalities using the same personality function.");
300
301 llvm::Function *Fn = getModule().getFunction(ObjCXX.PersonalityFn);
John McCall0bdb1fd2010-09-16 06:16:50 +0000302
303 // Nothing to do if it's unused.
304 if (!Fn || Fn->use_empty()) return;
305
306 // Can't do the optimization if it has non-C++ uses.
307 if (!PersonalityHasOnlyCXXUses(Fn)) return;
308
309 // Create the C++ personality function and kill off the old
310 // function.
311 llvm::Constant *CXXFn = getPersonalityFn(*this, CXX);
312
313 // This can happen if the user is screwing with us.
314 if (Fn->getType() != CXXFn->getType()) return;
315
316 Fn->replaceAllUsesWith(CXXFn);
317 Fn->eraseFromParent();
John McCallbd309292010-07-06 01:34:17 +0000318}
319
320/// Returns the value to inject into a selector to indicate the
321/// presence of a catch-all.
322static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
323 // Possibly we should use @llvm.eh.catch.all.value here.
John McCallad7c5c12011-02-08 08:22:06 +0000324 return llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
John McCallbd309292010-07-06 01:34:17 +0000325}
326
John McCallbb026012010-07-13 21:17:51 +0000327namespace {
328 /// A cleanup to free the exception object if its initialization
329 /// throws.
David Blaikie7e70d682015-08-18 22:40:54 +0000330 struct FreeException final : EHScopeStack::Cleanup {
John McCall5fcf8da2011-07-12 00:15:30 +0000331 llvm::Value *exn;
332 FreeException(llvm::Value *exn) : exn(exn) {}
Craig Topper4f12f102014-03-12 06:41:41 +0000333 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +0000334 CGF.EmitNounwindRuntimeCall(getFreeExceptionFn(CGF.CGM), exn);
John McCallbb026012010-07-13 21:17:51 +0000335 }
336 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000337}
John McCallbb026012010-07-13 21:17:51 +0000338
John McCall2e6567a2010-04-22 01:10:34 +0000339// Emits an exception expression into the given location. This
340// differs from EmitAnyExprToMem only in that, if a final copy-ctor
341// call is required, an exception within that copy ctor causes
342// std::terminate to be invoked.
John McCall7f416cc2015-09-08 08:05:57 +0000343void CodeGenFunction::EmitAnyExprToExn(const Expr *e, Address addr) {
John McCallbd309292010-07-06 01:34:17 +0000344 // Make sure the exception object is cleaned up if there's an
345 // exception during initialization.
John McCall7f416cc2015-09-08 08:05:57 +0000346 pushFullExprCleanup<FreeException>(EHCleanup, addr.getPointer());
David Majnemer7c237072015-03-05 00:46:22 +0000347 EHScopeStack::stable_iterator cleanup = EHStack.stable_begin();
John McCall2e6567a2010-04-22 01:10:34 +0000348
349 // __cxa_allocate_exception returns a void*; we need to cast this
350 // to the appropriate type for the object.
David Majnemer7c237072015-03-05 00:46:22 +0000351 llvm::Type *ty = ConvertTypeForMem(e->getType())->getPointerTo();
John McCall7f416cc2015-09-08 08:05:57 +0000352 Address typedAddr = Builder.CreateBitCast(addr, ty);
John McCall2e6567a2010-04-22 01:10:34 +0000353
354 // FIXME: this isn't quite right! If there's a final unelided call
355 // to a copy constructor, then according to [except.terminate]p1 we
356 // must call std::terminate() if that constructor throws, because
357 // technically that copy occurs after the exception expression is
358 // evaluated but before the exception is caught. But the best way
359 // to handle that is to teach EmitAggExpr to do the final copy
360 // differently if it can't be elided.
David Majnemer7c237072015-03-05 00:46:22 +0000361 EmitAnyExprToMem(e, typedAddr, e->getType().getQualifiers(),
362 /*IsInit*/ true);
John McCall2e6567a2010-04-22 01:10:34 +0000363
John McCalle4df6c82011-01-28 08:37:24 +0000364 // Deactivate the cleanup block.
John McCall7f416cc2015-09-08 08:05:57 +0000365 DeactivateCleanupBlock(cleanup,
366 cast<llvm::Instruction>(typedAddr.getPointer()));
Mike Stump54066142009-12-01 03:41:18 +0000367}
368
John McCall7f416cc2015-09-08 08:05:57 +0000369Address CodeGenFunction::getExceptionSlot() {
John McCall9b382dd2011-05-28 21:13:02 +0000370 if (!ExceptionSlot)
371 ExceptionSlot = CreateTempAlloca(Int8PtrTy, "exn.slot");
John McCall7f416cc2015-09-08 08:05:57 +0000372 return Address(ExceptionSlot, getPointerAlign());
Mike Stump54066142009-12-01 03:41:18 +0000373}
374
John McCall7f416cc2015-09-08 08:05:57 +0000375Address CodeGenFunction::getEHSelectorSlot() {
John McCall9b382dd2011-05-28 21:13:02 +0000376 if (!EHSelectorSlot)
377 EHSelectorSlot = CreateTempAlloca(Int32Ty, "ehselector.slot");
John McCall7f416cc2015-09-08 08:05:57 +0000378 return Address(EHSelectorSlot, CharUnits::fromQuantity(4));
John McCall9b382dd2011-05-28 21:13:02 +0000379}
380
Bill Wendling79a70e42011-09-15 18:57:19 +0000381llvm::Value *CodeGenFunction::getExceptionFromSlot() {
382 return Builder.CreateLoad(getExceptionSlot(), "exn");
383}
384
385llvm::Value *CodeGenFunction::getSelectorFromSlot() {
386 return Builder.CreateLoad(getEHSelectorSlot(), "sel");
387}
388
Richard Smithea852322013-05-07 21:53:22 +0000389void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E,
390 bool KeepInsertionPoint) {
David Majnemer7c237072015-03-05 00:46:22 +0000391 if (const Expr *SubExpr = E->getSubExpr()) {
392 QualType ThrowType = SubExpr->getType();
393 if (ThrowType->isObjCObjectPointerType()) {
394 const Stmt *ThrowStmt = E->getSubExpr();
395 const ObjCAtThrowStmt S(E->getExprLoc(), const_cast<Stmt *>(ThrowStmt));
396 CGM.getObjCRuntime().EmitThrowStmt(*this, S, false);
397 } else {
398 CGM.getCXXABI().emitThrow(*this, E);
John McCall2e6567a2010-04-22 01:10:34 +0000399 }
David Majnemer7c237072015-03-05 00:46:22 +0000400 } else {
401 CGM.getCXXABI().emitRethrow(*this, /*isNoReturn=*/true);
John McCall2e6567a2010-04-22 01:10:34 +0000402 }
Mike Stump75546b82009-12-10 00:06:18 +0000403
John McCall20f6ab82011-01-12 03:41:02 +0000404 // throw is an expression, and the expression emitters expect us
405 // to leave ourselves at a valid insertion point.
Richard Smithea852322013-05-07 21:53:22 +0000406 if (KeepInsertionPoint)
407 EmitBlock(createBasicBlock("throw.cont"));
Anders Carlsson4b08db72009-10-30 01:42:31 +0000408}
Mike Stump58ef18b2009-11-20 23:44:51 +0000409
Mike Stump1d849212009-12-07 23:38:24 +0000410void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000411 if (!CGM.getLangOpts().CXXExceptions)
Anders Carlsson9878f9f2010-02-06 23:59:05 +0000412 return;
413
Mike Stump1d849212009-12-07 23:38:24 +0000414 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
Craig Topper8a13c412014-05-21 05:09:00 +0000415 if (!FD) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000416 // Check if CapturedDecl is nothrow and create terminate scope for it.
417 if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
418 if (CD->isNothrow())
419 EHStack.pushTerminate();
420 }
Mike Stump1d849212009-12-07 23:38:24 +0000421 return;
Alexey Bataev9959db52014-05-06 10:08:46 +0000422 }
Mike Stump1d849212009-12-07 23:38:24 +0000423 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
Craig Topper8a13c412014-05-21 05:09:00 +0000424 if (!Proto)
Mike Stump1d849212009-12-07 23:38:24 +0000425 return;
426
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000427 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
428 if (isNoexceptExceptionSpec(EST)) {
429 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
430 // noexcept functions are simple terminate scopes.
431 EHStack.pushTerminate();
432 }
433 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
David Majnemer1f192e22015-04-01 04:45:52 +0000434 // TODO: Revisit exception specifications for the MS ABI. There is a way to
435 // encode these in an object file but MSVC doesn't do anything with it.
436 if (getTarget().getCXXABI().isMicrosoft())
437 return;
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000438 unsigned NumExceptions = Proto->getNumExceptions();
439 EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
Mike Stump1d849212009-12-07 23:38:24 +0000440
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000441 for (unsigned I = 0; I != NumExceptions; ++I) {
442 QualType Ty = Proto->getExceptionType(I);
443 QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
444 llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType,
445 /*ForEH=*/true);
446 Filter->setFilter(I, EHType);
447 }
Mike Stump1d849212009-12-07 23:38:24 +0000448 }
Mike Stump1d849212009-12-07 23:38:24 +0000449}
450
John McCall8e4c74b2011-08-11 02:22:43 +0000451/// Emit the dispatch block for a filter scope if necessary.
452static void emitFilterDispatchBlock(CodeGenFunction &CGF,
453 EHFilterScope &filterScope) {
454 llvm::BasicBlock *dispatchBlock = filterScope.getCachedEHDispatchBlock();
455 if (!dispatchBlock) return;
456 if (dispatchBlock->use_empty()) {
457 delete dispatchBlock;
458 return;
459 }
460
John McCall8e4c74b2011-08-11 02:22:43 +0000461 CGF.EmitBlockAfterUses(dispatchBlock);
462
463 // If this isn't a catch-all filter, we need to check whether we got
464 // here because the filter triggered.
465 if (filterScope.getNumFilters()) {
466 // Load the selector value.
Bill Wendling79a70e42011-09-15 18:57:19 +0000467 llvm::Value *selector = CGF.getSelectorFromSlot();
John McCall8e4c74b2011-08-11 02:22:43 +0000468 llvm::BasicBlock *unexpectedBB = CGF.createBasicBlock("ehspec.unexpected");
469
470 llvm::Value *zero = CGF.Builder.getInt32(0);
471 llvm::Value *failsFilter =
Nico Weber1bebad12015-02-11 22:33:32 +0000472 CGF.Builder.CreateICmpSLT(selector, zero, "ehspec.fails");
473 CGF.Builder.CreateCondBr(failsFilter, unexpectedBB,
474 CGF.getEHResumeBlock(false));
John McCall8e4c74b2011-08-11 02:22:43 +0000475
476 CGF.EmitBlock(unexpectedBB);
477 }
478
479 // Call __cxa_call_unexpected. This doesn't need to be an invoke
480 // because __cxa_call_unexpected magically filters exceptions
481 // according to the last landing pad the exception was thrown
482 // into. Seriously.
Bill Wendling79a70e42011-09-15 18:57:19 +0000483 llvm::Value *exn = CGF.getExceptionFromSlot();
John McCall882987f2013-02-28 19:01:20 +0000484 CGF.EmitRuntimeCall(getUnexpectedFn(CGF.CGM), exn)
John McCall8e4c74b2011-08-11 02:22:43 +0000485 ->setDoesNotReturn();
486 CGF.Builder.CreateUnreachable();
487}
488
Mike Stump1d849212009-12-07 23:38:24 +0000489void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000490 if (!CGM.getLangOpts().CXXExceptions)
Anders Carlsson9878f9f2010-02-06 23:59:05 +0000491 return;
492
Mike Stump1d849212009-12-07 23:38:24 +0000493 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
Craig Topper8a13c412014-05-21 05:09:00 +0000494 if (!FD) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000495 // Check if CapturedDecl is nothrow and pop terminate scope for it.
496 if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
497 if (CD->isNothrow())
498 EHStack.popTerminate();
499 }
Mike Stump1d849212009-12-07 23:38:24 +0000500 return;
Alexey Bataev9959db52014-05-06 10:08:46 +0000501 }
Mike Stump1d849212009-12-07 23:38:24 +0000502 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
Craig Topper8a13c412014-05-21 05:09:00 +0000503 if (!Proto)
Mike Stump1d849212009-12-07 23:38:24 +0000504 return;
505
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000506 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
507 if (isNoexceptExceptionSpec(EST)) {
508 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
509 EHStack.popTerminate();
510 }
511 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
David Majnemer1f192e22015-04-01 04:45:52 +0000512 // TODO: Revisit exception specifications for the MS ABI. There is a way to
513 // encode these in an object file but MSVC doesn't do anything with it.
514 if (getTarget().getCXXABI().isMicrosoft())
515 return;
John McCall8e4c74b2011-08-11 02:22:43 +0000516 EHFilterScope &filterScope = cast<EHFilterScope>(*EHStack.begin());
517 emitFilterDispatchBlock(*this, filterScope);
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000518 EHStack.popFilter();
519 }
Mike Stump1d849212009-12-07 23:38:24 +0000520}
521
Mike Stump58ef18b2009-11-20 23:44:51 +0000522void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
John McCallb609d3f2010-07-07 06:56:46 +0000523 EnterCXXTryStmt(S);
John McCallb81884d2010-02-19 09:25:03 +0000524 EmitStmt(S.getTryBlock());
John McCallb609d3f2010-07-07 06:56:46 +0000525 ExitCXXTryStmt(S);
John McCallb81884d2010-02-19 09:25:03 +0000526}
527
John McCallb609d3f2010-07-07 06:56:46 +0000528void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallbd309292010-07-06 01:34:17 +0000529 unsigned NumHandlers = S.getNumHandlers();
530 EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
John McCallb81884d2010-02-19 09:25:03 +0000531
John McCallbd309292010-07-06 01:34:17 +0000532 for (unsigned I = 0; I != NumHandlers; ++I) {
533 const CXXCatchStmt *C = S.getHandler(I);
John McCallb81884d2010-02-19 09:25:03 +0000534
John McCallbd309292010-07-06 01:34:17 +0000535 llvm::BasicBlock *Handler = createBasicBlock("catch");
536 if (C->getExceptionDecl()) {
537 // FIXME: Dropping the reference type on the type into makes it
538 // impossible to correctly implement catch-by-reference
539 // semantics for pointers. Unfortunately, this is what all
540 // existing compilers do, and it's not clear that the standard
541 // personality routine is capable of doing this right. See C++ DR 388:
542 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
David Majnemer571162a2014-10-12 06:58:22 +0000543 Qualifiers CaughtTypeQuals;
544 QualType CaughtType = CGM.getContext().getUnqualifiedArrayType(
545 C->getCaughtType().getNonReferenceType(), CaughtTypeQuals);
John McCall2ca705e2010-07-24 00:37:23 +0000546
Rafael Espindolabb9e7a32014-06-04 18:51:46 +0000547 llvm::Constant *TypeInfo = nullptr;
John McCall2ca705e2010-07-24 00:37:23 +0000548 if (CaughtType->isObjCObjectPointerType())
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +0000549 TypeInfo = CGM.getObjCRuntime().GetEHType(CaughtType);
John McCall2ca705e2010-07-24 00:37:23 +0000550 else
David Majnemer5f0dd612015-03-17 20:35:05 +0000551 TypeInfo =
David Majnemer37b417f2015-03-29 21:55:10 +0000552 CGM.getAddrOfCXXCatchHandlerType(CaughtType, C->getCaughtType());
John McCallbd309292010-07-06 01:34:17 +0000553 CatchScope->setHandler(I, TypeInfo, Handler);
554 } else {
555 // No exception decl indicates '...', a catch-all.
556 CatchScope->setCatchAllHandler(I, Handler);
557 }
558 }
John McCallbd309292010-07-06 01:34:17 +0000559}
560
John McCall8e4c74b2011-08-11 02:22:43 +0000561llvm::BasicBlock *
562CodeGenFunction::getEHDispatchBlock(EHScopeStack::stable_iterator si) {
David Majnemerdbf10452015-07-31 17:58:45 +0000563 if (CGM.getCodeGenOpts().NewMSEH &&
564 EHPersonality::get(*this).isMSVCPersonality())
565 return getMSVCDispatchBlock(si);
566
John McCall8e4c74b2011-08-11 02:22:43 +0000567 // The dispatch block for the end of the scope chain is a block that
568 // just resumes unwinding.
569 if (si == EHStack.stable_end())
David Chisnall9a837be2012-11-07 16:50:40 +0000570 return getEHResumeBlock(true);
John McCall8e4c74b2011-08-11 02:22:43 +0000571
572 // Otherwise, we should look at the actual scope.
573 EHScope &scope = *EHStack.find(si);
574
575 llvm::BasicBlock *dispatchBlock = scope.getCachedEHDispatchBlock();
576 if (!dispatchBlock) {
577 switch (scope.getKind()) {
578 case EHScope::Catch: {
579 // Apply a special case to a single catch-all.
580 EHCatchScope &catchScope = cast<EHCatchScope>(scope);
581 if (catchScope.getNumHandlers() == 1 &&
582 catchScope.getHandler(0).isCatchAll()) {
583 dispatchBlock = catchScope.getHandler(0).Block;
584
585 // Otherwise, make a dispatch block.
586 } else {
587 dispatchBlock = createBasicBlock("catch.dispatch");
588 }
589 break;
590 }
591
592 case EHScope::Cleanup:
593 dispatchBlock = createBasicBlock("ehcleanup");
594 break;
595
596 case EHScope::Filter:
597 dispatchBlock = createBasicBlock("filter.dispatch");
598 break;
599
600 case EHScope::Terminate:
601 dispatchBlock = getTerminateHandler();
602 break;
David Majnemerdbf10452015-07-31 17:58:45 +0000603
Reid Kleckner2586aac2015-09-10 22:11:13 +0000604 case EHScope::PadEnd:
605 llvm_unreachable("PadEnd unnecessary for Itanium!");
John McCall8e4c74b2011-08-11 02:22:43 +0000606 }
607 scope.setCachedEHDispatchBlock(dispatchBlock);
608 }
609 return dispatchBlock;
610}
611
David Majnemerdbf10452015-07-31 17:58:45 +0000612llvm::BasicBlock *
613CodeGenFunction::getMSVCDispatchBlock(EHScopeStack::stable_iterator SI) {
614 // Returning nullptr indicates that the previous dispatch block should unwind
615 // to caller.
616 if (SI == EHStack.stable_end())
617 return nullptr;
618
619 // Otherwise, we should look at the actual scope.
620 EHScope &EHS = *EHStack.find(SI);
621
622 llvm::BasicBlock *DispatchBlock = EHS.getCachedEHDispatchBlock();
623 if (DispatchBlock)
624 return DispatchBlock;
625
626 if (EHS.getKind() == EHScope::Terminate)
627 DispatchBlock = getTerminateHandler();
628 else
629 DispatchBlock = createBasicBlock();
John McCall7f416cc2015-09-08 08:05:57 +0000630 CGBuilderTy Builder(*this, DispatchBlock);
David Majnemerdbf10452015-07-31 17:58:45 +0000631
632 switch (EHS.getKind()) {
633 case EHScope::Catch:
634 DispatchBlock->setName("catch.dispatch");
635 break;
636
637 case EHScope::Cleanup:
638 DispatchBlock->setName("ehcleanup");
639 break;
640
641 case EHScope::Filter:
642 llvm_unreachable("exception specifications not handled yet!");
643
644 case EHScope::Terminate:
645 DispatchBlock->setName("terminate");
646 break;
647
Reid Kleckner2586aac2015-09-10 22:11:13 +0000648 case EHScope::PadEnd:
649 llvm_unreachable("PadEnd dispatch block missing!");
David Majnemerdbf10452015-07-31 17:58:45 +0000650 }
651 EHS.setCachedEHDispatchBlock(DispatchBlock);
652 return DispatchBlock;
653}
654
John McCallbd309292010-07-06 01:34:17 +0000655/// Check whether this is a non-EH scope, i.e. a scope which doesn't
656/// affect exception handling. Currently, the only non-EH scopes are
657/// normal-only cleanup scopes.
658static bool isNonEHScope(const EHScope &S) {
John McCall2b7fc382010-07-13 20:32:21 +0000659 switch (S.getKind()) {
John McCallcda666c2010-07-21 07:22:38 +0000660 case EHScope::Cleanup:
661 return !cast<EHCleanupScope>(S).isEHCleanup();
John McCall2b7fc382010-07-13 20:32:21 +0000662 case EHScope::Filter:
663 case EHScope::Catch:
664 case EHScope::Terminate:
Reid Kleckner2586aac2015-09-10 22:11:13 +0000665 case EHScope::PadEnd:
John McCall2b7fc382010-07-13 20:32:21 +0000666 return false;
667 }
668
David Blaikiee4d798f2012-01-20 21:50:17 +0000669 llvm_unreachable("Invalid EHScope Kind!");
John McCallbd309292010-07-06 01:34:17 +0000670}
671
672llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
673 assert(EHStack.requiresLandingPad());
674 assert(!EHStack.empty());
675
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000676 // If exceptions are disabled, there are usually no landingpads. However, when
677 // SEH is enabled, functions using SEH still get landingpads.
678 const LangOptions &LO = CGM.getLangOpts();
679 if (!LO.Exceptions) {
680 if (!LO.Borland && !LO.MicrosoftExt)
681 return nullptr;
Reid Klecknere7b3f7c2015-02-11 00:00:21 +0000682 if (!currentFunctionUsesSEHTry())
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000683 return nullptr;
684 }
John McCall2b7fc382010-07-13 20:32:21 +0000685
John McCallbd309292010-07-06 01:34:17 +0000686 // Check the innermost scope for a cached landing pad. If this is
687 // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
688 llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
689 if (LP) return LP;
690
David Majnemerdbf10452015-07-31 17:58:45 +0000691 const EHPersonality &Personality = EHPersonality::get(*this);
692
693 if (!CurFn->hasPersonalityFn())
694 CurFn->setPersonalityFn(getOpaquePersonalityFn(CGM, Personality));
695
696 if (CGM.getCodeGenOpts().NewMSEH && Personality.isMSVCPersonality()) {
697 // We don't need separate landing pads in the MSVC model.
698 LP = getEHDispatchBlock(EHStack.getInnermostEHScope());
699 } else {
700 // Build the landing pad for this scope.
701 LP = EmitLandingPad();
702 }
703
John McCallbd309292010-07-06 01:34:17 +0000704 assert(LP);
705
706 // Cache the landing pad on the innermost scope. If this is a
707 // non-EH scope, cache the landing pad on the enclosing scope, too.
708 for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
709 ir->setCachedLandingPad(LP);
710 if (!isNonEHScope(*ir)) break;
711 }
712
713 return LP;
714}
715
716llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
717 assert(EHStack.requiresLandingPad());
718
John McCall8e4c74b2011-08-11 02:22:43 +0000719 EHScope &innermostEHScope = *EHStack.find(EHStack.getInnermostEHScope());
720 switch (innermostEHScope.getKind()) {
721 case EHScope::Terminate:
722 return getTerminateLandingPad();
John McCallbd309292010-07-06 01:34:17 +0000723
Reid Kleckner2586aac2015-09-10 22:11:13 +0000724 case EHScope::PadEnd:
725 llvm_unreachable("PadEnd unnecessary for Itanium!");
David Majnemerdbf10452015-07-31 17:58:45 +0000726
John McCall8e4c74b2011-08-11 02:22:43 +0000727 case EHScope::Catch:
728 case EHScope::Cleanup:
729 case EHScope::Filter:
730 if (llvm::BasicBlock *lpad = innermostEHScope.getCachedLandingPad())
731 return lpad;
John McCallbd309292010-07-06 01:34:17 +0000732 }
733
734 // Save the current IR generation state.
John McCall8e4c74b2011-08-11 02:22:43 +0000735 CGBuilderTy::InsertPoint savedIP = Builder.saveAndClearIP();
Adrian Prantl95b24e92015-02-03 20:00:54 +0000736 auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, CurEHLocation);
John McCallbd309292010-07-06 01:34:17 +0000737
738 // Create and configure the landing pad.
John McCall8e4c74b2011-08-11 02:22:43 +0000739 llvm::BasicBlock *lpad = createBasicBlock("lpad");
740 EmitBlock(lpad);
John McCallbd309292010-07-06 01:34:17 +0000741
David Majnemerfcbdb6e2015-06-17 20:53:19 +0000742 llvm::LandingPadInst *LPadInst = Builder.CreateLandingPad(
743 llvm::StructType::get(Int8PtrTy, Int32Ty, nullptr), 0);
Bill Wendlingf0724e82011-09-19 20:31:14 +0000744
745 llvm::Value *LPadExn = Builder.CreateExtractValue(LPadInst, 0);
746 Builder.CreateStore(LPadExn, getExceptionSlot());
747 llvm::Value *LPadSel = Builder.CreateExtractValue(LPadInst, 1);
748 Builder.CreateStore(LPadSel, getEHSelectorSlot());
749
John McCallbd309292010-07-06 01:34:17 +0000750 // Save the exception pointer. It's safe to use a single exception
751 // pointer per function because EH cleanups can never have nested
752 // try/catches.
Bill Wendlingf0724e82011-09-19 20:31:14 +0000753 // Build the landingpad instruction.
John McCallbd309292010-07-06 01:34:17 +0000754
755 // Accumulate all the handlers in scope.
John McCall8e4c74b2011-08-11 02:22:43 +0000756 bool hasCatchAll = false;
757 bool hasCleanup = false;
758 bool hasFilter = false;
759 SmallVector<llvm::Value*, 4> filterTypes;
760 llvm::SmallPtrSet<llvm::Value*, 4> catchTypes;
Nico Webere68b9f32015-02-25 16:25:00 +0000761 for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end(); I != E;
762 ++I) {
John McCallbd309292010-07-06 01:34:17 +0000763
764 switch (I->getKind()) {
John McCallcda666c2010-07-21 07:22:38 +0000765 case EHScope::Cleanup:
John McCall8e4c74b2011-08-11 02:22:43 +0000766 // If we have a cleanup, remember that.
767 hasCleanup = (hasCleanup || cast<EHCleanupScope>(*I).isEHCleanup());
John McCall2b7fc382010-07-13 20:32:21 +0000768 continue;
769
John McCallbd309292010-07-06 01:34:17 +0000770 case EHScope::Filter: {
771 assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
John McCall8e4c74b2011-08-11 02:22:43 +0000772 assert(!hasCatchAll && "EH filter reached after catch-all");
John McCallbd309292010-07-06 01:34:17 +0000773
Bill Wendlingf0724e82011-09-19 20:31:14 +0000774 // Filter scopes get added to the landingpad in weird ways.
John McCall8e4c74b2011-08-11 02:22:43 +0000775 EHFilterScope &filter = cast<EHFilterScope>(*I);
776 hasFilter = true;
John McCallbd309292010-07-06 01:34:17 +0000777
Bill Wendling8c4b7162011-09-22 20:32:54 +0000778 // Add all the filter values.
779 for (unsigned i = 0, e = filter.getNumFilters(); i != e; ++i)
780 filterTypes.push_back(filter.getFilter(i));
John McCallbd309292010-07-06 01:34:17 +0000781 goto done;
782 }
783
784 case EHScope::Terminate:
785 // Terminate scopes are basically catch-alls.
John McCall8e4c74b2011-08-11 02:22:43 +0000786 assert(!hasCatchAll);
787 hasCatchAll = true;
John McCallbd309292010-07-06 01:34:17 +0000788 goto done;
789
790 case EHScope::Catch:
791 break;
David Majnemerdbf10452015-07-31 17:58:45 +0000792
Reid Kleckner2586aac2015-09-10 22:11:13 +0000793 case EHScope::PadEnd:
794 llvm_unreachable("PadEnd unnecessary for Itanium!");
John McCallbd309292010-07-06 01:34:17 +0000795 }
796
John McCall8e4c74b2011-08-11 02:22:43 +0000797 EHCatchScope &catchScope = cast<EHCatchScope>(*I);
798 for (unsigned hi = 0, he = catchScope.getNumHandlers(); hi != he; ++hi) {
799 EHCatchScope::Handler handler = catchScope.getHandler(hi);
John McCallbd309292010-07-06 01:34:17 +0000800
John McCall8e4c74b2011-08-11 02:22:43 +0000801 // If this is a catch-all, register that and abort.
802 if (!handler.Type) {
803 assert(!hasCatchAll);
804 hasCatchAll = true;
805 goto done;
John McCallbd309292010-07-06 01:34:17 +0000806 }
807
808 // Check whether we already have a handler for this type.
David Blaikie82e95a32014-11-19 07:49:47 +0000809 if (catchTypes.insert(handler.Type).second)
Bill Wendlingf0724e82011-09-19 20:31:14 +0000810 // If not, add it directly to the landingpad.
811 LPadInst->addClause(handler.Type);
John McCallbd309292010-07-06 01:34:17 +0000812 }
John McCallbd309292010-07-06 01:34:17 +0000813 }
814
815 done:
Bill Wendlingf0724e82011-09-19 20:31:14 +0000816 // If we have a catch-all, add null to the landingpad.
John McCall8e4c74b2011-08-11 02:22:43 +0000817 assert(!(hasCatchAll && hasFilter));
818 if (hasCatchAll) {
Bill Wendlingf0724e82011-09-19 20:31:14 +0000819 LPadInst->addClause(getCatchAllValue(*this));
John McCallbd309292010-07-06 01:34:17 +0000820
821 // If we have an EH filter, we need to add those handlers in the
Bill Wendlingf0724e82011-09-19 20:31:14 +0000822 // right place in the landingpad, which is to say, at the end.
John McCall8e4c74b2011-08-11 02:22:43 +0000823 } else if (hasFilter) {
Bill Wendling58e58fe2011-09-19 22:08:36 +0000824 // Create a filter expression: a constant array indicating which filter
825 // types there are. The personality routine only lands here if the filter
826 // doesn't match.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000827 SmallVector<llvm::Constant*, 8> Filters;
Bill Wendlingf0724e82011-09-19 20:31:14 +0000828 llvm::ArrayType *AType =
829 llvm::ArrayType::get(!filterTypes.empty() ?
830 filterTypes[0]->getType() : Int8PtrTy,
831 filterTypes.size());
832
833 for (unsigned i = 0, e = filterTypes.size(); i != e; ++i)
834 Filters.push_back(cast<llvm::Constant>(filterTypes[i]));
835 llvm::Constant *FilterArray = llvm::ConstantArray::get(AType, Filters);
836 LPadInst->addClause(FilterArray);
John McCallbd309292010-07-06 01:34:17 +0000837
838 // Also check whether we need a cleanup.
Bill Wendlingf0724e82011-09-19 20:31:14 +0000839 if (hasCleanup)
840 LPadInst->setCleanup(true);
John McCallbd309292010-07-06 01:34:17 +0000841
842 // Otherwise, signal that we at least have cleanups.
Logan Chiene9c8ccb2014-07-01 11:47:10 +0000843 } else if (hasCleanup) {
844 LPadInst->setCleanup(true);
John McCallbd309292010-07-06 01:34:17 +0000845 }
846
Bill Wendlingf0724e82011-09-19 20:31:14 +0000847 assert((LPadInst->getNumClauses() > 0 || LPadInst->isCleanup()) &&
848 "landingpad instruction has no clauses!");
John McCallbd309292010-07-06 01:34:17 +0000849
850 // Tell the backend how to generate the landing pad.
John McCall8e4c74b2011-08-11 02:22:43 +0000851 Builder.CreateBr(getEHDispatchBlock(EHStack.getInnermostEHScope()));
John McCallbd309292010-07-06 01:34:17 +0000852
853 // Restore the old IR generation state.
John McCall8e4c74b2011-08-11 02:22:43 +0000854 Builder.restoreIP(savedIP);
John McCallbd309292010-07-06 01:34:17 +0000855
John McCall8e4c74b2011-08-11 02:22:43 +0000856 return lpad;
John McCallbd309292010-07-06 01:34:17 +0000857}
858
David Majnemerdbf10452015-07-31 17:58:45 +0000859static llvm::BasicBlock *emitMSVCCatchDispatchBlock(CodeGenFunction &CGF,
860 EHCatchScope &CatchScope) {
861 llvm::BasicBlock *DispatchBlock = CatchScope.getCachedEHDispatchBlock();
862 assert(DispatchBlock);
863
864 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveIP();
865 CGF.EmitBlockAfterUses(DispatchBlock);
866
867 // Figure out the next block.
868 llvm::BasicBlock *NextBlock = nullptr;
869
870 // Test against each of the exception types we claim to catch.
871 for (unsigned I = 0, E = CatchScope.getNumHandlers(); I < E; ++I) {
872 const EHCatchScope::Handler &Handler = CatchScope.getHandler(I);
873
874 llvm::Value *TypeValue = Handler.Type;
875 assert(TypeValue != nullptr || Handler.isCatchAll());
876 if (!TypeValue)
877 TypeValue = llvm::Constant::getNullValue(CGF.VoidPtrTy);
878
879 // If this is the last handler, we're at the end, and the next
880 // block is the block for the enclosing EH scope.
881 if (I + 1 == E) {
882 NextBlock = CGF.createBasicBlock("catchendblock");
John McCall7f416cc2015-09-08 08:05:57 +0000883 CGBuilderTy(CGF, NextBlock).CreateCatchEndPad(
David Majnemerdbf10452015-07-31 17:58:45 +0000884 CGF.getEHDispatchBlock(CatchScope.getEnclosingEHScope()));
885 } else {
886 NextBlock = CGF.createBasicBlock("catch.dispatch");
887 }
888
889 if (EHPersonality::get(CGF).isMSVCXXPersonality()) {
890 CGF.Builder.CreateCatchPad(
Joseph Tremouletce536a52015-08-23 00:26:48 +0000891 Handler.Block, NextBlock,
892 {TypeValue, llvm::Constant::getNullValue(CGF.VoidPtrTy)});
David Majnemerdbf10452015-07-31 17:58:45 +0000893 } else {
Joseph Tremouletce536a52015-08-23 00:26:48 +0000894 CGF.Builder.CreateCatchPad(Handler.Block, NextBlock, {TypeValue});
David Majnemerdbf10452015-07-31 17:58:45 +0000895 }
896
897 // Otherwise we need to emit and continue at that block.
898 CGF.EmitBlock(NextBlock);
899 }
900 CGF.Builder.restoreIP(SavedIP);
901
902 return NextBlock;
903}
904
John McCall8e4c74b2011-08-11 02:22:43 +0000905/// Emit the structure of the dispatch block for the given catch scope.
906/// It is an invariant that the dispatch block already exists.
David Majnemerdbf10452015-07-31 17:58:45 +0000907/// If the catchblock instructions are used for EH dispatch, then the basic
908/// block holding the final catchendblock instruction is returned.
909static llvm::BasicBlock *emitCatchDispatchBlock(CodeGenFunction &CGF,
910 EHCatchScope &catchScope) {
911 if (CGF.CGM.getCodeGenOpts().NewMSEH &&
912 EHPersonality::get(CGF).isMSVCPersonality())
913 return emitMSVCCatchDispatchBlock(CGF, catchScope);
914
John McCall8e4c74b2011-08-11 02:22:43 +0000915 llvm::BasicBlock *dispatchBlock = catchScope.getCachedEHDispatchBlock();
916 assert(dispatchBlock);
917
918 // If there's only a single catch-all, getEHDispatchBlock returned
919 // that catch-all as the dispatch block.
920 if (catchScope.getNumHandlers() == 1 &&
921 catchScope.getHandler(0).isCatchAll()) {
922 assert(dispatchBlock == catchScope.getHandler(0).Block);
David Majnemerdbf10452015-07-31 17:58:45 +0000923 return nullptr;
John McCall8e4c74b2011-08-11 02:22:43 +0000924 }
925
926 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveIP();
927 CGF.EmitBlockAfterUses(dispatchBlock);
928
929 // Select the right handler.
930 llvm::Value *llvm_eh_typeid_for =
931 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
932
933 // Load the selector value.
Bill Wendling79a70e42011-09-15 18:57:19 +0000934 llvm::Value *selector = CGF.getSelectorFromSlot();
John McCall8e4c74b2011-08-11 02:22:43 +0000935
936 // Test against each of the exception types we claim to catch.
937 for (unsigned i = 0, e = catchScope.getNumHandlers(); ; ++i) {
938 assert(i < e && "ran off end of handlers!");
939 const EHCatchScope::Handler &handler = catchScope.getHandler(i);
940
941 llvm::Value *typeValue = handler.Type;
942 assert(typeValue && "fell into catch-all case!");
943 typeValue = CGF.Builder.CreateBitCast(typeValue, CGF.Int8PtrTy);
944
945 // Figure out the next block.
946 bool nextIsEnd;
947 llvm::BasicBlock *nextBlock;
948
949 // If this is the last handler, we're at the end, and the next
950 // block is the block for the enclosing EH scope.
951 if (i + 1 == e) {
952 nextBlock = CGF.getEHDispatchBlock(catchScope.getEnclosingEHScope());
953 nextIsEnd = true;
954
955 // If the next handler is a catch-all, we're at the end, and the
956 // next block is that handler.
957 } else if (catchScope.getHandler(i+1).isCatchAll()) {
958 nextBlock = catchScope.getHandler(i+1).Block;
959 nextIsEnd = true;
960
961 // Otherwise, we're not at the end and we need a new block.
962 } else {
963 nextBlock = CGF.createBasicBlock("catch.fallthrough");
964 nextIsEnd = false;
965 }
966
967 // Figure out the catch type's index in the LSDA's type table.
968 llvm::CallInst *typeIndex =
969 CGF.Builder.CreateCall(llvm_eh_typeid_for, typeValue);
970 typeIndex->setDoesNotThrow();
971
972 llvm::Value *matchesTypeIndex =
973 CGF.Builder.CreateICmpEQ(selector, typeIndex, "matches");
974 CGF.Builder.CreateCondBr(matchesTypeIndex, handler.Block, nextBlock);
975
976 // If the next handler is a catch-all, we're completely done.
977 if (nextIsEnd) {
978 CGF.Builder.restoreIP(savedIP);
David Majnemerdbf10452015-07-31 17:58:45 +0000979 return nullptr;
John McCall8e4c74b2011-08-11 02:22:43 +0000980 }
Ahmed Charles289896d2012-02-19 11:57:29 +0000981 // Otherwise we need to emit and continue at that block.
982 CGF.EmitBlock(nextBlock);
John McCall8e4c74b2011-08-11 02:22:43 +0000983 }
David Majnemerdbf10452015-07-31 17:58:45 +0000984 return nullptr;
John McCall8e4c74b2011-08-11 02:22:43 +0000985}
986
987void CodeGenFunction::popCatchScope() {
988 EHCatchScope &catchScope = cast<EHCatchScope>(*EHStack.begin());
989 if (catchScope.hasEHBranches())
990 emitCatchDispatchBlock(*this, catchScope);
991 EHStack.popCatch();
992}
993
John McCallb609d3f2010-07-07 06:56:46 +0000994void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallbd309292010-07-06 01:34:17 +0000995 unsigned NumHandlers = S.getNumHandlers();
996 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
997 assert(CatchScope.getNumHandlers() == NumHandlers);
Mike Stump58ef18b2009-11-20 23:44:51 +0000998
John McCall8e4c74b2011-08-11 02:22:43 +0000999 // If the catch was not required, bail out now.
1000 if (!CatchScope.hasEHBranches()) {
Kostya Serebryanyba4aced2014-01-09 09:22:32 +00001001 CatchScope.clearHandlerBlocks();
John McCall8e4c74b2011-08-11 02:22:43 +00001002 EHStack.popCatch();
1003 return;
1004 }
1005
1006 // Emit the structure of the EH dispatch for this catch.
David Majnemerdbf10452015-07-31 17:58:45 +00001007 llvm::BasicBlock *CatchEndBlockBB = emitCatchDispatchBlock(*this, CatchScope);
John McCall8e4c74b2011-08-11 02:22:43 +00001008
John McCallbd309292010-07-06 01:34:17 +00001009 // Copy the handler blocks off before we pop the EH stack. Emitting
1010 // the handlers might scribble on this memory.
Benjamin Kramerda32cf82015-08-04 15:38:49 +00001011 SmallVector<EHCatchScope::Handler, 8> Handlers(
1012 CatchScope.begin(), CatchScope.begin() + NumHandlers);
John McCall8e4c74b2011-08-11 02:22:43 +00001013
John McCallbd309292010-07-06 01:34:17 +00001014 EHStack.popCatch();
Mike Stump58ef18b2009-11-20 23:44:51 +00001015
John McCallbd309292010-07-06 01:34:17 +00001016 // The fall-through block.
1017 llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
Mike Stump58ef18b2009-11-20 23:44:51 +00001018
John McCallbd309292010-07-06 01:34:17 +00001019 // We just emitted the body of the try; jump to the continue block.
1020 if (HaveInsertPoint())
1021 Builder.CreateBr(ContBB);
Mike Stump97329152009-12-02 19:53:57 +00001022
John McCalld8d00be2012-06-15 05:27:05 +00001023 // Determine if we need an implicit rethrow for all these catch handlers;
1024 // see the comment below.
1025 bool doImplicitRethrow = false;
John McCallb609d3f2010-07-07 06:56:46 +00001026 if (IsFnTryBlock)
John McCalld8d00be2012-06-15 05:27:05 +00001027 doImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
1028 isa<CXXConstructorDecl>(CurCodeDecl);
John McCallb609d3f2010-07-07 06:56:46 +00001029
David Majnemerdbf10452015-07-31 17:58:45 +00001030 if (CatchEndBlockBB)
Reid Kleckner2586aac2015-09-10 22:11:13 +00001031 EHStack.pushPadEnd(CatchEndBlockBB);
David Majnemerdbf10452015-07-31 17:58:45 +00001032
John McCall8e4c74b2011-08-11 02:22:43 +00001033 // Perversely, we emit the handlers backwards precisely because we
1034 // want them to appear in source order. In all of these cases, the
1035 // catch block will have exactly one predecessor, which will be a
1036 // particular block in the catch dispatch. However, in the case of
1037 // a catch-all, one of the dispatch blocks will branch to two
1038 // different handlers, and EmitBlockAfterUses will cause the second
1039 // handler to be moved before the first.
1040 for (unsigned I = NumHandlers; I != 0; --I) {
1041 llvm::BasicBlock *CatchBlock = Handlers[I-1].Block;
1042 EmitBlockAfterUses(CatchBlock);
Mike Stump75546b82009-12-10 00:06:18 +00001043
John McCallbd309292010-07-06 01:34:17 +00001044 // Catch the exception if this isn't a catch-all.
John McCall8e4c74b2011-08-11 02:22:43 +00001045 const CXXCatchStmt *C = S.getHandler(I-1);
Mike Stump58ef18b2009-11-20 23:44:51 +00001046
John McCallbd309292010-07-06 01:34:17 +00001047 // Enter a cleanup scope, including the catch variable and the
1048 // end-catch.
1049 RunCleanupsScope CatchScope(*this);
Mike Stump58ef18b2009-11-20 23:44:51 +00001050
John McCallbd309292010-07-06 01:34:17 +00001051 // Initialize the catch variable and set up the cleanups.
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00001052 CGM.getCXXABI().emitBeginCatch(*this, C);
John McCallbd309292010-07-06 01:34:17 +00001053
Justin Bognerea278c32014-01-07 00:20:28 +00001054 // Emit the PGO counter increment.
Justin Bogner66242d62015-04-23 23:06:47 +00001055 incrementProfileCounter(C);
Justin Bogneref512b92014-01-06 22:27:43 +00001056
John McCallbd309292010-07-06 01:34:17 +00001057 // Perform the body of the catch.
1058 EmitStmt(C->getHandlerBlock());
1059
John McCalld8d00be2012-06-15 05:27:05 +00001060 // [except.handle]p11:
1061 // The currently handled exception is rethrown if control
1062 // reaches the end of a handler of the function-try-block of a
1063 // constructor or destructor.
1064
1065 // It is important that we only do this on fallthrough and not on
1066 // return. Note that it's illegal to put a return in a
1067 // constructor function-try-block's catch handler (p14), so this
1068 // really only applies to destructors.
1069 if (doImplicitRethrow && HaveInsertPoint()) {
David Majnemer442d0a22014-11-25 07:20:20 +00001070 CGM.getCXXABI().emitRethrow(*this, /*isNoReturn*/false);
John McCalld8d00be2012-06-15 05:27:05 +00001071 Builder.CreateUnreachable();
1072 Builder.ClearInsertionPoint();
1073 }
1074
John McCallbd309292010-07-06 01:34:17 +00001075 // Fall out through the catch cleanups.
1076 CatchScope.ForceCleanup();
1077
1078 // Branch out of the try.
1079 if (HaveInsertPoint())
1080 Builder.CreateBr(ContBB);
Mike Stump58ef18b2009-11-20 23:44:51 +00001081 }
1082
John McCallbd309292010-07-06 01:34:17 +00001083 EmitBlock(ContBB);
Justin Bogner66242d62015-04-23 23:06:47 +00001084 incrementProfileCounter(&S);
David Majnemerdbf10452015-07-31 17:58:45 +00001085 if (CatchEndBlockBB)
Reid Kleckner2586aac2015-09-10 22:11:13 +00001086 EHStack.popPadEnd();
Mike Stump58ef18b2009-11-20 23:44:51 +00001087}
Mike Stumpaff69af2009-12-09 03:35:49 +00001088
John McCall1e670402010-07-21 00:52:03 +00001089namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001090 struct CallEndCatchForFinally final : EHScopeStack::Cleanup {
John McCall1e670402010-07-21 00:52:03 +00001091 llvm::Value *ForEHVar;
1092 llvm::Value *EndCatchFn;
1093 CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn)
1094 : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
1095
Craig Topper4f12f102014-03-12 06:41:41 +00001096 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall1e670402010-07-21 00:52:03 +00001097 llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
1098 llvm::BasicBlock *CleanupContBB =
1099 CGF.createBasicBlock("finally.cleanup.cont");
1100
1101 llvm::Value *ShouldEndCatch =
John McCall7f416cc2015-09-08 08:05:57 +00001102 CGF.Builder.CreateFlagLoad(ForEHVar, "finally.endcatch");
John McCall1e670402010-07-21 00:52:03 +00001103 CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1104 CGF.EmitBlock(EndCatchBB);
John McCall882987f2013-02-28 19:01:20 +00001105 CGF.EmitRuntimeCallOrInvoke(EndCatchFn); // catch-all, so might throw
John McCall1e670402010-07-21 00:52:03 +00001106 CGF.EmitBlock(CleanupContBB);
1107 }
1108 };
John McCall906da4b2010-07-21 05:47:49 +00001109
David Blaikie7e70d682015-08-18 22:40:54 +00001110 struct PerformFinally final : EHScopeStack::Cleanup {
John McCall906da4b2010-07-21 05:47:49 +00001111 const Stmt *Body;
1112 llvm::Value *ForEHVar;
1113 llvm::Value *EndCatchFn;
1114 llvm::Value *RethrowFn;
1115 llvm::Value *SavedExnVar;
1116
1117 PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
1118 llvm::Value *EndCatchFn,
1119 llvm::Value *RethrowFn, llvm::Value *SavedExnVar)
1120 : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1121 RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
1122
Craig Topper4f12f102014-03-12 06:41:41 +00001123 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall906da4b2010-07-21 05:47:49 +00001124 // Enter a cleanup to call the end-catch function if one was provided.
1125 if (EndCatchFn)
John McCallcda666c2010-07-21 07:22:38 +00001126 CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
1127 ForEHVar, EndCatchFn);
John McCall906da4b2010-07-21 05:47:49 +00001128
John McCallcebe0ca2010-08-11 00:16:14 +00001129 // Save the current cleanup destination in case there are
1130 // cleanups in the finally block.
1131 llvm::Value *SavedCleanupDest =
1132 CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
1133 "cleanup.dest.saved");
1134
John McCall906da4b2010-07-21 05:47:49 +00001135 // Emit the finally block.
1136 CGF.EmitStmt(Body);
1137
1138 // If the end of the finally is reachable, check whether this was
1139 // for EH. If so, rethrow.
1140 if (CGF.HaveInsertPoint()) {
1141 llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
1142 llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
1143
1144 llvm::Value *ShouldRethrow =
John McCall7f416cc2015-09-08 08:05:57 +00001145 CGF.Builder.CreateFlagLoad(ForEHVar, "finally.shouldthrow");
John McCall906da4b2010-07-21 05:47:49 +00001146 CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1147
1148 CGF.EmitBlock(RethrowBB);
1149 if (SavedExnVar) {
John McCall882987f2013-02-28 19:01:20 +00001150 CGF.EmitRuntimeCallOrInvoke(RethrowFn,
John McCall7f416cc2015-09-08 08:05:57 +00001151 CGF.Builder.CreateAlignedLoad(SavedExnVar, CGF.getPointerAlign()));
John McCall906da4b2010-07-21 05:47:49 +00001152 } else {
John McCall882987f2013-02-28 19:01:20 +00001153 CGF.EmitRuntimeCallOrInvoke(RethrowFn);
John McCall906da4b2010-07-21 05:47:49 +00001154 }
1155 CGF.Builder.CreateUnreachable();
1156
1157 CGF.EmitBlock(ContBB);
John McCallcebe0ca2010-08-11 00:16:14 +00001158
1159 // Restore the cleanup destination.
1160 CGF.Builder.CreateStore(SavedCleanupDest,
1161 CGF.getNormalCleanupDestSlot());
John McCall906da4b2010-07-21 05:47:49 +00001162 }
1163
1164 // Leave the end-catch cleanup. As an optimization, pretend that
1165 // the fallthrough path was inaccessible; we've dynamically proven
1166 // that we're not in the EH case along that path.
1167 if (EndCatchFn) {
1168 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1169 CGF.PopCleanupBlock();
1170 CGF.Builder.restoreIP(SavedIP);
1171 }
1172
1173 // Now make sure we actually have an insertion point or the
1174 // cleanup gods will hate us.
1175 CGF.EnsureInsertPoint();
1176 }
1177 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001178}
John McCall1e670402010-07-21 00:52:03 +00001179
John McCallbd309292010-07-06 01:34:17 +00001180/// Enters a finally block for an implementation using zero-cost
1181/// exceptions. This is mostly general, but hard-codes some
1182/// language/ABI-specific behavior in the catch-all sections.
John McCall6b0feb72011-06-22 02:32:12 +00001183void CodeGenFunction::FinallyInfo::enter(CodeGenFunction &CGF,
1184 const Stmt *body,
1185 llvm::Constant *beginCatchFn,
1186 llvm::Constant *endCatchFn,
1187 llvm::Constant *rethrowFn) {
Craig Topper8a13c412014-05-21 05:09:00 +00001188 assert((beginCatchFn != nullptr) == (endCatchFn != nullptr) &&
John McCallbd309292010-07-06 01:34:17 +00001189 "begin/end catch functions not paired");
John McCall6b0feb72011-06-22 02:32:12 +00001190 assert(rethrowFn && "rethrow function is required");
1191
1192 BeginCatchFn = beginCatchFn;
Mike Stumpaff69af2009-12-09 03:35:49 +00001193
John McCallbd309292010-07-06 01:34:17 +00001194 // The rethrow function has one of the following two types:
1195 // void (*)()
1196 // void (*)(void*)
1197 // In the latter case we need to pass it the exception object.
1198 // But we can't use the exception slot because the @finally might
1199 // have a landing pad (which would overwrite the exception slot).
Chris Lattner2192fe52011-07-18 04:24:23 +00001200 llvm::FunctionType *rethrowFnTy =
John McCallbd309292010-07-06 01:34:17 +00001201 cast<llvm::FunctionType>(
John McCall6b0feb72011-06-22 02:32:12 +00001202 cast<llvm::PointerType>(rethrowFn->getType())->getElementType());
Craig Topper8a13c412014-05-21 05:09:00 +00001203 SavedExnVar = nullptr;
John McCall6b0feb72011-06-22 02:32:12 +00001204 if (rethrowFnTy->getNumParams())
1205 SavedExnVar = CGF.CreateTempAlloca(CGF.Int8PtrTy, "finally.exn");
Mike Stumpaff69af2009-12-09 03:35:49 +00001206
John McCallbd309292010-07-06 01:34:17 +00001207 // A finally block is a statement which must be executed on any edge
1208 // out of a given scope. Unlike a cleanup, the finally block may
1209 // contain arbitrary control flow leading out of itself. In
1210 // addition, finally blocks should always be executed, even if there
1211 // are no catch handlers higher on the stack. Therefore, we
1212 // surround the protected scope with a combination of a normal
1213 // cleanup (to catch attempts to break out of the block via normal
1214 // control flow) and an EH catch-all (semantically "outside" any try
1215 // statement to which the finally block might have been attached).
1216 // The finally block itself is generated in the context of a cleanup
1217 // which conditionally leaves the catch-all.
John McCall21886962010-04-21 10:05:39 +00001218
John McCallbd309292010-07-06 01:34:17 +00001219 // Jump destination for performing the finally block on an exception
1220 // edge. We'll never actually reach this block, so unreachable is
1221 // fine.
John McCall6b0feb72011-06-22 02:32:12 +00001222 RethrowDest = CGF.getJumpDestInCurrentScope(CGF.getUnreachableBlock());
John McCall21886962010-04-21 10:05:39 +00001223
John McCallbd309292010-07-06 01:34:17 +00001224 // Whether the finally block is being executed for EH purposes.
John McCall6b0feb72011-06-22 02:32:12 +00001225 ForEHVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "finally.for-eh");
John McCall7f416cc2015-09-08 08:05:57 +00001226 CGF.Builder.CreateFlagStore(false, ForEHVar);
Mike Stumpaff69af2009-12-09 03:35:49 +00001227
John McCallbd309292010-07-06 01:34:17 +00001228 // Enter a normal cleanup which will perform the @finally block.
John McCall6b0feb72011-06-22 02:32:12 +00001229 CGF.EHStack.pushCleanup<PerformFinally>(NormalCleanup, body,
1230 ForEHVar, endCatchFn,
1231 rethrowFn, SavedExnVar);
John McCallbd309292010-07-06 01:34:17 +00001232
1233 // Enter a catch-all scope.
John McCall6b0feb72011-06-22 02:32:12 +00001234 llvm::BasicBlock *catchBB = CGF.createBasicBlock("finally.catchall");
1235 EHCatchScope *catchScope = CGF.EHStack.pushCatch(1);
1236 catchScope->setCatchAllHandler(0, catchBB);
John McCallbd309292010-07-06 01:34:17 +00001237}
1238
John McCall6b0feb72011-06-22 02:32:12 +00001239void CodeGenFunction::FinallyInfo::exit(CodeGenFunction &CGF) {
John McCallbd309292010-07-06 01:34:17 +00001240 // Leave the finally catch-all.
John McCall6b0feb72011-06-22 02:32:12 +00001241 EHCatchScope &catchScope = cast<EHCatchScope>(*CGF.EHStack.begin());
1242 llvm::BasicBlock *catchBB = catchScope.getHandler(0).Block;
John McCall8e4c74b2011-08-11 02:22:43 +00001243
1244 CGF.popCatchScope();
John McCallbd309292010-07-06 01:34:17 +00001245
John McCall6b0feb72011-06-22 02:32:12 +00001246 // If there are any references to the catch-all block, emit it.
1247 if (catchBB->use_empty()) {
1248 delete catchBB;
1249 } else {
1250 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveAndClearIP();
1251 CGF.EmitBlock(catchBB);
John McCallbd309292010-07-06 01:34:17 +00001252
Craig Topper8a13c412014-05-21 05:09:00 +00001253 llvm::Value *exn = nullptr;
John McCallbd309292010-07-06 01:34:17 +00001254
John McCall6b0feb72011-06-22 02:32:12 +00001255 // If there's a begin-catch function, call it.
1256 if (BeginCatchFn) {
Bill Wendling79a70e42011-09-15 18:57:19 +00001257 exn = CGF.getExceptionFromSlot();
John McCall882987f2013-02-28 19:01:20 +00001258 CGF.EmitNounwindRuntimeCall(BeginCatchFn, exn);
John McCall6b0feb72011-06-22 02:32:12 +00001259 }
1260
1261 // If we need to remember the exception pointer to rethrow later, do so.
1262 if (SavedExnVar) {
Bill Wendling79a70e42011-09-15 18:57:19 +00001263 if (!exn) exn = CGF.getExceptionFromSlot();
John McCall7f416cc2015-09-08 08:05:57 +00001264 CGF.Builder.CreateAlignedStore(exn, SavedExnVar, CGF.getPointerAlign());
John McCall6b0feb72011-06-22 02:32:12 +00001265 }
1266
1267 // Tell the cleanups in the finally block that we're do this for EH.
John McCall7f416cc2015-09-08 08:05:57 +00001268 CGF.Builder.CreateFlagStore(true, ForEHVar);
John McCall6b0feb72011-06-22 02:32:12 +00001269
1270 // Thread a jump through the finally cleanup.
1271 CGF.EmitBranchThroughCleanup(RethrowDest);
1272
1273 CGF.Builder.restoreIP(savedIP);
1274 }
1275
1276 // Finally, leave the @finally cleanup.
1277 CGF.PopCleanupBlock();
John McCallbd309292010-07-06 01:34:17 +00001278}
1279
1280llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
1281 if (TerminateLandingPad)
1282 return TerminateLandingPad;
1283
1284 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1285
1286 // This will get inserted at the end of the function.
1287 TerminateLandingPad = createBasicBlock("terminate.lpad");
1288 Builder.SetInsertPoint(TerminateLandingPad);
1289
1290 // Tell the backend that this is a landing pad.
Reid Klecknerdeeddec2015-02-05 18:56:03 +00001291 const EHPersonality &Personality = EHPersonality::get(*this);
David Majnemerfcbdb6e2015-06-17 20:53:19 +00001292
1293 if (!CurFn->hasPersonalityFn())
1294 CurFn->setPersonalityFn(getOpaquePersonalityFn(CGM, Personality));
1295
1296 llvm::LandingPadInst *LPadInst = Builder.CreateLandingPad(
1297 llvm::StructType::get(Int8PtrTy, Int32Ty, nullptr), 0);
Bill Wendlingf0724e82011-09-19 20:31:14 +00001298 LPadInst->addClause(getCatchAllValue(*this));
John McCallbd309292010-07-06 01:34:17 +00001299
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00001300 llvm::Value *Exn = 0;
1301 if (getLangOpts().CPlusPlus)
1302 Exn = Builder.CreateExtractValue(LPadInst, 0);
1303 llvm::CallInst *terminateCall =
1304 CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
John McCalle142ad52013-02-12 03:51:46 +00001305 terminateCall->setDoesNotReturn();
John McCallad7c5c12011-02-08 08:22:06 +00001306 Builder.CreateUnreachable();
Mike Stumpaff69af2009-12-09 03:35:49 +00001307
John McCallbd309292010-07-06 01:34:17 +00001308 // Restore the saved insertion state.
1309 Builder.restoreIP(SavedIP);
John McCalldac3ea62010-04-30 00:06:43 +00001310
John McCallbd309292010-07-06 01:34:17 +00001311 return TerminateLandingPad;
Mike Stumpaff69af2009-12-09 03:35:49 +00001312}
Mike Stump2b488872009-12-09 22:59:31 +00001313
1314llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
Mike Stumpf5cbb082009-12-10 00:02:42 +00001315 if (TerminateHandler)
1316 return TerminateHandler;
1317
John McCallbd309292010-07-06 01:34:17 +00001318 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
Mike Stump25b20fc2009-12-09 23:31:35 +00001319
John McCallbd309292010-07-06 01:34:17 +00001320 // Set up the terminate handler. This block is inserted at the very
1321 // end of the function by FinishFunction.
Mike Stumpf5cbb082009-12-10 00:02:42 +00001322 TerminateHandler = createBasicBlock("terminate.handler");
John McCallbd309292010-07-06 01:34:17 +00001323 Builder.SetInsertPoint(TerminateHandler);
David Majnemerdbf10452015-07-31 17:58:45 +00001324 if (CGM.getCodeGenOpts().NewMSEH &&
1325 EHPersonality::get(*this).isMSVCPersonality()) {
1326 Builder.CreateTerminatePad(/*UnwindBB=*/nullptr, CGM.getTerminateFn());
1327 } else {
1328 llvm::Value *Exn = 0;
1329 if (getLangOpts().CPlusPlus)
1330 Exn = getExceptionFromSlot();
1331 llvm::CallInst *terminateCall =
1332 CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
1333 terminateCall->setDoesNotReturn();
1334 Builder.CreateUnreachable();
1335 }
Mike Stump2b488872009-12-09 22:59:31 +00001336
John McCall21886962010-04-21 10:05:39 +00001337 // Restore the saved insertion state.
John McCallbd309292010-07-06 01:34:17 +00001338 Builder.restoreIP(SavedIP);
Mike Stump25b20fc2009-12-09 23:31:35 +00001339
Mike Stump2b488872009-12-09 22:59:31 +00001340 return TerminateHandler;
1341}
John McCallbd309292010-07-06 01:34:17 +00001342
David Chisnall9a837be2012-11-07 16:50:40 +00001343llvm::BasicBlock *CodeGenFunction::getEHResumeBlock(bool isCleanup) {
John McCall8e4c74b2011-08-11 02:22:43 +00001344 if (EHResumeBlock) return EHResumeBlock;
John McCallad5d61e2010-07-23 21:56:41 +00001345
1346 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1347
1348 // We emit a jump to a notional label at the outermost unwind state.
John McCall8e4c74b2011-08-11 02:22:43 +00001349 EHResumeBlock = createBasicBlock("eh.resume");
1350 Builder.SetInsertPoint(EHResumeBlock);
John McCallad5d61e2010-07-23 21:56:41 +00001351
Reid Klecknerdeeddec2015-02-05 18:56:03 +00001352 const EHPersonality &Personality = EHPersonality::get(*this);
John McCallad5d61e2010-07-23 21:56:41 +00001353
1354 // This can always be a call because we necessarily didn't find
1355 // anything on the EH stack which needs our help.
Benjamin Kramer793bd552012-02-08 12:41:24 +00001356 const char *RethrowName = Personality.CatchallRethrowFn;
Craig Topper8a13c412014-05-21 05:09:00 +00001357 if (RethrowName != nullptr && !isCleanup) {
John McCall882987f2013-02-28 19:01:20 +00001358 EmitRuntimeCall(getCatchallRethrowFn(CGM, RethrowName),
Nico Weberff62a6a2015-02-26 22:34:33 +00001359 getExceptionFromSlot())->setDoesNotReturn();
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001360 Builder.CreateUnreachable();
1361 Builder.restoreIP(SavedIP);
1362 return EHResumeBlock;
John McCall9b382dd2011-05-28 21:13:02 +00001363 }
1364
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001365 // Recreate the landingpad's return value for the 'resume' instruction.
1366 llvm::Value *Exn = getExceptionFromSlot();
1367 llvm::Value *Sel = getSelectorFromSlot();
John McCallad5d61e2010-07-23 21:56:41 +00001368
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001369 llvm::Type *LPadType = llvm::StructType::get(Exn->getType(),
Reid Kleckneree7cf842014-12-01 22:02:27 +00001370 Sel->getType(), nullptr);
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001371 llvm::Value *LPadVal = llvm::UndefValue::get(LPadType);
1372 LPadVal = Builder.CreateInsertValue(LPadVal, Exn, 0, "lpad.val");
1373 LPadVal = Builder.CreateInsertValue(LPadVal, Sel, 1, "lpad.val");
1374
1375 Builder.CreateResume(LPadVal);
John McCallad5d61e2010-07-23 21:56:41 +00001376 Builder.restoreIP(SavedIP);
John McCall8e4c74b2011-08-11 02:22:43 +00001377 return EHResumeBlock;
John McCallad5d61e2010-07-23 21:56:41 +00001378}
Reid Kleckner543a16c2013-09-16 21:46:30 +00001379
1380void CodeGenFunction::EmitSEHTryStmt(const SEHTryStmt &S) {
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001381 EnterSEHTryStmt(S);
Reid Klecknera5930002015-02-11 21:40:48 +00001382 {
Nico Weber5779f842015-02-12 23:16:11 +00001383 JumpDest TryExit = getJumpDestInCurrentScope("__try.__leave");
Nico Weber5779f842015-02-12 23:16:11 +00001384
Reid Kleckner11c033e2015-02-12 23:40:45 +00001385 SEHTryEpilogueStack.push_back(&TryExit);
Reid Klecknera5930002015-02-11 21:40:48 +00001386 EmitStmt(S.getTryBlock());
Reid Kleckner11c033e2015-02-12 23:40:45 +00001387 SEHTryEpilogueStack.pop_back();
Nico Weber5779f842015-02-12 23:16:11 +00001388
1389 if (!TryExit.getBlock()->use_empty())
1390 EmitBlock(TryExit.getBlock(), /*IsFinished=*/true);
1391 else
1392 delete TryExit.getBlock();
Reid Klecknera5930002015-02-11 21:40:48 +00001393 }
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001394 ExitSEHTryStmt(S);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001395}
1396
1397namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001398struct PerformSEHFinally final : EHScopeStack::Cleanup {
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001399 llvm::Function *OutlinedFinally;
Reid Kleckner2586aac2015-09-10 22:11:13 +00001400 EHScopeStack::stable_iterator EnclosingScope;
1401 PerformSEHFinally(llvm::Function *OutlinedFinally,
1402 EHScopeStack::stable_iterator EnclosingScope)
1403 : OutlinedFinally(OutlinedFinally), EnclosingScope(EnclosingScope) {}
Reid Kleckneraca01db2015-02-04 22:37:07 +00001404
Reid Kleckner1d59f992015-01-22 01:36:17 +00001405 void Emit(CodeGenFunction &CGF, Flags F) override {
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001406 ASTContext &Context = CGF.getContext();
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001407 CodeGenModule &CGM = CGF.CGM;
Reid Kleckner65870442015-06-09 17:47:50 +00001408
Reid Klecknerd0d9a1f2015-07-01 17:10:10 +00001409 CallArgList Args;
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001410
1411 // Compute the two argument values.
1412 QualType ArgTys[2] = {Context.UnsignedCharTy, Context.VoidPtrTy};
Reid Kleckner15d152d2015-07-07 23:23:31 +00001413 llvm::Value *LocalAddrFn = CGM.getIntrinsic(llvm::Intrinsic::localaddress);
David Blaikie4ba525b2015-07-14 17:27:39 +00001414 llvm::Value *FP = CGF.Builder.CreateCall(LocalAddrFn);
Reid Klecknereb11c412015-07-01 21:00:00 +00001415 llvm::Value *IsForEH =
1416 llvm::ConstantInt::get(CGF.ConvertType(ArgTys[0]), F.isForEHCleanup());
1417 Args.add(RValue::get(IsForEH), ArgTys[0]);
1418 Args.add(RValue::get(FP), ArgTys[1]);
Reid Klecknerd0d9a1f2015-07-01 17:10:10 +00001419
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001420 // Arrange a two-arg function info and type.
1421 FunctionProtoType::ExtProtoInfo EPI;
1422 const auto *FPT = cast<FunctionProtoType>(
1423 Context.getFunctionType(Context.VoidTy, ArgTys, EPI));
Reid Klecknereb11c412015-07-01 21:00:00 +00001424 const CGFunctionInfo &FnInfo =
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001425 CGM.getTypes().arrangeFreeFunctionCall(Args, FPT,
1426 /*chainCall=*/false);
1427
Reid Kleckner2586aac2015-09-10 22:11:13 +00001428 // If this is the normal cleanup or using the old EH IR, just emit the call.
1429 if (!F.isForEHCleanup() || !CGM.getCodeGenOpts().NewMSEH) {
1430 CGF.EmitCall(FnInfo, OutlinedFinally, ReturnValueSlot(), Args);
1431 return;
1432 }
1433
1434 // Build a cleanupendpad to unwind through.
1435 llvm::BasicBlock *CleanupBB = CGF.Builder.GetInsertBlock();
1436 llvm::BasicBlock *CleanupEndBB = CGF.createBasicBlock("ehcleanup.end");
1437 llvm::Instruction *PadInst = CleanupBB->getFirstNonPHI();
1438 auto *CPI = cast<llvm::CleanupPadInst>(PadInst);
1439 CGBuilderTy(CGF, CleanupEndBB)
1440 .CreateCleanupEndPad(CPI, CGF.getEHDispatchBlock(EnclosingScope));
1441
1442 // Push and pop the cleanupendpad around the call.
1443 CGF.EHStack.pushPadEnd(CleanupEndBB);
Reid Klecknereb11c412015-07-01 21:00:00 +00001444 CGF.EmitCall(FnInfo, OutlinedFinally, ReturnValueSlot(), Args);
Reid Kleckner2586aac2015-09-10 22:11:13 +00001445 CGF.EHStack.popPadEnd();
1446
1447 // Insert the catchendpad block here.
1448 CGF.CurFn->getBasicBlockList().insertAfter(CGF.Builder.GetInsertBlock(),
1449 CleanupEndBB);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001450 }
1451};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001452}
Reid Kleckner1d59f992015-01-22 01:36:17 +00001453
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001454namespace {
1455/// Find all local variable captures in the statement.
1456struct CaptureFinder : ConstStmtVisitor<CaptureFinder> {
1457 CodeGenFunction &ParentCGF;
1458 const VarDecl *ParentThis;
John McCall0a490152015-09-08 21:15:22 +00001459 llvm::SmallSetVector<const VarDecl *, 4> Captures;
John McCall7f416cc2015-09-08 08:05:57 +00001460 Address SEHCodeSlot = Address::invalid();
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001461 CaptureFinder(CodeGenFunction &ParentCGF, const VarDecl *ParentThis)
1462 : ParentCGF(ParentCGF), ParentThis(ParentThis) {}
1463
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001464 // Return true if we need to do any capturing work.
1465 bool foundCaptures() {
John McCall7f416cc2015-09-08 08:05:57 +00001466 return !Captures.empty() || SEHCodeSlot.isValid();
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001467 }
1468
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001469 void Visit(const Stmt *S) {
1470 // See if this is a capture, then recurse.
1471 ConstStmtVisitor<CaptureFinder>::Visit(S);
1472 for (const Stmt *Child : S->children())
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001473 if (Child)
1474 Visit(Child);
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001475 }
1476
1477 void VisitDeclRefExpr(const DeclRefExpr *E) {
1478 // If this is already a capture, just make sure we capture 'this'.
1479 if (E->refersToEnclosingVariableOrCapture()) {
John McCall0a490152015-09-08 21:15:22 +00001480 Captures.insert(ParentThis);
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001481 return;
1482 }
1483
1484 const auto *D = dyn_cast<VarDecl>(E->getDecl());
1485 if (D && D->isLocalVarDeclOrParm() && D->hasLocalStorage())
John McCall0a490152015-09-08 21:15:22 +00001486 Captures.insert(D);
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001487 }
1488
1489 void VisitCXXThisExpr(const CXXThisExpr *E) {
John McCall0a490152015-09-08 21:15:22 +00001490 Captures.insert(ParentThis);
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001491 }
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001492
1493 void VisitCallExpr(const CallExpr *E) {
1494 // We only need to add parent frame allocations for these builtins in x86.
1495 if (ParentCGF.getTarget().getTriple().getArch() != llvm::Triple::x86)
1496 return;
1497
1498 unsigned ID = E->getBuiltinCallee();
1499 switch (ID) {
1500 case Builtin::BI__exception_code:
1501 case Builtin::BI_exception_code:
1502 // This is the simple case where we are the outermost finally. All we
1503 // have to do here is make sure we escape this and recover it in the
1504 // outlined handler.
John McCall7f416cc2015-09-08 08:05:57 +00001505 if (!SEHCodeSlot.isValid())
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001506 SEHCodeSlot = ParentCGF.SEHCodeSlotStack.back();
1507 break;
1508 }
1509 }
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001510};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001511}
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001512
John McCall7f416cc2015-09-08 08:05:57 +00001513Address CodeGenFunction::recoverAddrOfEscapedLocal(
1514 CodeGenFunction &ParentCGF, Address ParentVar, llvm::Value *ParentFP) {
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001515 llvm::CallInst *RecoverCall = nullptr;
John McCall7f416cc2015-09-08 08:05:57 +00001516 CGBuilderTy Builder(*this, AllocaInsertPt);
1517 if (auto *ParentAlloca = dyn_cast<llvm::AllocaInst>(ParentVar.getPointer())) {
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001518 // Mark the variable escaped if nobody else referenced it and compute the
Reid Kleckner98cb8ba2015-07-07 22:26:07 +00001519 // localescape index.
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001520 auto InsertPair = ParentCGF.EscapedLocals.insert(
1521 std::make_pair(ParentAlloca, ParentCGF.EscapedLocals.size()));
1522 int FrameEscapeIdx = InsertPair.first->second;
Reid Kleckner98cb8ba2015-07-07 22:26:07 +00001523 // call i8* @llvm.localrecover(i8* bitcast(@parentFn), i8* %fp, i32 N)
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001524 llvm::Function *FrameRecoverFn = llvm::Intrinsic::getDeclaration(
Reid Kleckner98cb8ba2015-07-07 22:26:07 +00001525 &CGM.getModule(), llvm::Intrinsic::localrecover);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001526 llvm::Constant *ParentI8Fn =
1527 llvm::ConstantExpr::getBitCast(ParentCGF.CurFn, Int8PtrTy);
1528 RecoverCall = Builder.CreateCall(
1529 FrameRecoverFn, {ParentI8Fn, ParentFP,
1530 llvm::ConstantInt::get(Int32Ty, FrameEscapeIdx)});
1531
1532 } else {
1533 // If the parent didn't have an alloca, we're doing some nested outlining.
Reid Kleckner98cb8ba2015-07-07 22:26:07 +00001534 // Just clone the existing localrecover call, but tweak the FP argument to
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001535 // use our FP value. All other arguments are constants.
1536 auto *ParentRecover =
John McCall7f416cc2015-09-08 08:05:57 +00001537 cast<llvm::IntrinsicInst>(ParentVar.getPointer()->stripPointerCasts());
Reid Kleckner98cb8ba2015-07-07 22:26:07 +00001538 assert(ParentRecover->getIntrinsicID() == llvm::Intrinsic::localrecover &&
1539 "expected alloca or localrecover in parent LocalDeclMap");
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001540 RecoverCall = cast<llvm::CallInst>(ParentRecover->clone());
1541 RecoverCall->setArgOperand(1, ParentFP);
1542 RecoverCall->insertBefore(AllocaInsertPt);
1543 }
1544
1545 // Bitcast the variable, rename it, and insert it in the local decl map.
1546 llvm::Value *ChildVar =
John McCall7f416cc2015-09-08 08:05:57 +00001547 Builder.CreateBitCast(RecoverCall, ParentVar.getType());
1548 ChildVar->setName(ParentVar.getName());
1549 return Address(ChildVar, ParentVar.getAlignment());
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001550}
1551
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001552void CodeGenFunction::EmitCapturedLocals(CodeGenFunction &ParentCGF,
Reid Kleckner0b9bbbf2015-06-09 17:49:42 +00001553 const Stmt *OutlinedStmt,
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001554 bool IsFilter) {
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001555 // Find all captures in the Stmt.
1556 CaptureFinder Finder(ParentCGF, ParentCGF.CXXABIThisDecl);
1557 Finder.Visit(OutlinedStmt);
1558
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001559 // We can exit early on x86_64 when there are no captures. We just have to
1560 // save the exception code in filters so that __exception_code() works.
1561 if (!Finder.foundCaptures() &&
1562 CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
1563 if (IsFilter)
1564 EmitSEHExceptionCodeSave(ParentCGF, nullptr, nullptr);
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001565 return;
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001566 }
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001567
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001568 llvm::Value *EntryEBP = nullptr;
1569 llvm::Value *ParentFP;
1570 if (IsFilter && CGM.getTarget().getTriple().getArch() == llvm::Triple::x86) {
1571 // 32-bit SEH filters need to be careful about FP recovery. The end of the
1572 // EH registration is passed in as the EBP physical register. We can
1573 // recover that with llvm.frameaddress(1), and adjust that to recover the
1574 // parent's true frame pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001575 CGBuilderTy Builder(CGM, AllocaInsertPt);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001576 EntryEBP = Builder.CreateCall(
1577 CGM.getIntrinsic(llvm::Intrinsic::frameaddress), {Builder.getInt32(1)});
1578 llvm::Function *RecoverFPIntrin =
1579 CGM.getIntrinsic(llvm::Intrinsic::x86_seh_recoverfp);
1580 llvm::Constant *ParentI8Fn =
1581 llvm::ConstantExpr::getBitCast(ParentCGF.CurFn, Int8PtrTy);
1582 ParentFP = Builder.CreateCall(RecoverFPIntrin, {ParentI8Fn, EntryEBP});
1583 } else {
1584 // Otherwise, for x64 and 32-bit finally functions, the parent FP is the
1585 // second parameter.
1586 auto AI = CurFn->arg_begin();
1587 ++AI;
1588 ParentFP = AI;
1589 }
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001590
Reid Kleckner98cb8ba2015-07-07 22:26:07 +00001591 // Create llvm.localrecover calls for all captures.
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001592 for (const VarDecl *VD : Finder.Captures) {
1593 if (isa<ImplicitParamDecl>(VD)) {
1594 CGM.ErrorUnsupported(VD, "'this' captured by SEH");
1595 CXXThisValue = llvm::UndefValue::get(ConvertTypeForMem(VD->getType()));
1596 continue;
1597 }
1598 if (VD->getType()->isVariablyModifiedType()) {
1599 CGM.ErrorUnsupported(VD, "VLA captured by SEH");
1600 continue;
1601 }
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001602 assert((isa<ImplicitParamDecl>(VD) || VD->isLocalVarDeclOrParm()) &&
1603 "captured non-local variable");
1604
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001605 // If this decl hasn't been declared yet, it will be declared in the
1606 // OutlinedStmt.
1607 auto I = ParentCGF.LocalDeclMap.find(VD);
1608 if (I == ParentCGF.LocalDeclMap.end())
1609 continue;
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001610
John McCall7f416cc2015-09-08 08:05:57 +00001611 Address ParentVar = I->second;
1612 setAddrOfLocalVar(VD,
1613 recoverAddrOfEscapedLocal(ParentCGF, ParentVar, ParentFP));
Nico Webere4f974c2015-07-02 06:10:53 +00001614 }
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001615
John McCall7f416cc2015-09-08 08:05:57 +00001616 if (Finder.SEHCodeSlot.isValid()) {
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001617 SEHCodeSlotStack.push_back(
1618 recoverAddrOfEscapedLocal(ParentCGF, Finder.SEHCodeSlot, ParentFP));
1619 }
1620
1621 if (IsFilter)
1622 EmitSEHExceptionCodeSave(ParentCGF, ParentFP, EntryEBP);
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001623}
1624
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001625/// Arrange a function prototype that can be called by Windows exception
1626/// handling personalities. On Win64, the prototype looks like:
1627/// RetTy func(void *EHPtrs, void *ParentFP);
1628void CodeGenFunction::startOutlinedSEHHelper(CodeGenFunction &ParentCGF,
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001629 bool IsFilter,
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001630 const Stmt *OutlinedStmt) {
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001631 SourceLocation StartLoc = OutlinedStmt->getLocStart();
1632
1633 // Get the mangled function name.
1634 SmallString<128> Name;
1635 {
1636 llvm::raw_svector_ostream OS(Name);
1637 const Decl *ParentCodeDecl = ParentCGF.CurCodeDecl;
1638 const NamedDecl *Parent = dyn_cast_or_null<NamedDecl>(ParentCodeDecl);
1639 assert(Parent && "FIXME: handle unnamed decls (lambdas, blocks) with SEH");
1640 MangleContext &Mangler = CGM.getCXXABI().getMangleContext();
1641 if (IsFilter)
1642 Mangler.mangleSEHFilterExpression(Parent, OS);
1643 else
1644 Mangler.mangleSEHFinallyBlock(Parent, OS);
1645 }
1646
1647 FunctionArgList Args;
1648 if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86 || !IsFilter) {
1649 // All SEH finally functions take two parameters. Win64 filters take two
1650 // parameters. Win32 filters take no parameters.
1651 if (IsFilter) {
1652 Args.push_back(ImplicitParamDecl::Create(
1653 getContext(), nullptr, StartLoc,
1654 &getContext().Idents.get("exception_pointers"),
1655 getContext().VoidPtrTy));
1656 } else {
1657 Args.push_back(ImplicitParamDecl::Create(
1658 getContext(), nullptr, StartLoc,
1659 &getContext().Idents.get("abnormal_termination"),
1660 getContext().UnsignedCharTy));
1661 }
1662 Args.push_back(ImplicitParamDecl::Create(
1663 getContext(), nullptr, StartLoc,
1664 &getContext().Idents.get("frame_pointer"), getContext().VoidPtrTy));
1665 }
1666
1667 QualType RetTy = IsFilter ? getContext().LongTy : getContext().VoidTy;
1668
Reid Kleckner1d59f992015-01-22 01:36:17 +00001669 llvm::Function *ParentFn = ParentCGF.CurFn;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001670 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionDeclaration(
1671 RetTy, Args, FunctionType::ExtInfo(), /*isVariadic=*/false);
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001672
Reid Kleckner1d59f992015-01-22 01:36:17 +00001673 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001674 llvm::Function *Fn = llvm::Function::Create(
1675 FnTy, llvm::GlobalValue::InternalLinkage, Name.str(), &CGM.getModule());
Reid Kleckner1d59f992015-01-22 01:36:17 +00001676 // The filter is either in the same comdat as the function, or it's internal.
1677 if (llvm::Comdat *C = ParentFn->getComdat()) {
1678 Fn->setComdat(C);
1679 } else if (ParentFn->hasWeakLinkage() || ParentFn->hasLinkOnceLinkage()) {
Reid Kleckner1d59f992015-01-22 01:36:17 +00001680 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(ParentFn->getName());
1681 ParentFn->setComdat(C);
1682 Fn->setComdat(C);
1683 } else {
1684 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
1685 }
1686
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001687 IsOutlinedSEHHelper = true;
Nico Weberf2a39a72015-04-13 20:03:03 +00001688
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001689 StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args,
1690 OutlinedStmt->getLocStart(), OutlinedStmt->getLocStart());
1691
1692 CGM.SetLLVMFunctionAttributes(nullptr, FnInfo, CurFn);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001693 EmitCapturedLocals(ParentCGF, OutlinedStmt, IsFilter);
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001694}
1695
1696/// Create a stub filter function that will ultimately hold the code of the
1697/// filter expression. The EH preparation passes in LLVM will outline the code
1698/// from the main function body into this stub.
1699llvm::Function *
1700CodeGenFunction::GenerateSEHFilterFunction(CodeGenFunction &ParentCGF,
1701 const SEHExceptStmt &Except) {
1702 const Expr *FilterExpr = Except.getFilterExpr();
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001703 startOutlinedSEHHelper(ParentCGF, true, FilterExpr);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001704
1705 // Emit the original filter expression, convert to i32, and return.
1706 llvm::Value *R = EmitScalarExpr(FilterExpr);
David Majnemer2ccba832015-04-17 06:57:25 +00001707 R = Builder.CreateIntCast(R, ConvertType(getContext().LongTy),
Reid Kleckner1d59f992015-01-22 01:36:17 +00001708 FilterExpr->getType()->isSignedIntegerType());
1709 Builder.CreateStore(R, ReturnValue);
1710
1711 FinishFunction(FilterExpr->getLocEnd());
1712
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001713 return CurFn;
1714}
1715
1716llvm::Function *
1717CodeGenFunction::GenerateSEHFinallyFunction(CodeGenFunction &ParentCGF,
1718 const SEHFinallyStmt &Finally) {
1719 const Stmt *FinallyBlock = Finally.getBlock();
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001720 startOutlinedSEHHelper(ParentCGF, false, FinallyBlock);
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001721
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001722 // Mark finally block calls as nounwind and noinline to make LLVM's job a
1723 // little easier.
1724 // FIXME: Remove these restrictions in the future.
1725 CurFn->addFnAttr(llvm::Attribute::NoUnwind);
1726 CurFn->addFnAttr(llvm::Attribute::NoInline);
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001727
1728 // Emit the original filter expression, convert to i32, and return.
1729 EmitStmt(FinallyBlock);
1730
1731 FinishFunction(FinallyBlock->getLocEnd());
1732
1733 return CurFn;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001734}
1735
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001736void CodeGenFunction::EmitSEHExceptionCodeSave(CodeGenFunction &ParentCGF,
1737 llvm::Value *ParentFP,
1738 llvm::Value *EntryEBP) {
1739 // Get the pointer to the EXCEPTION_POINTERS struct. This is returned by the
1740 // __exception_info intrinsic.
1741 if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
1742 // On Win64, the info is passed as the first parameter to the filter.
1743 auto AI = CurFn->arg_begin();
1744 SEHInfo = AI;
1745 SEHCodeSlotStack.push_back(
1746 CreateMemTemp(getContext().IntTy, "__exception_code"));
1747 } else {
1748 // On Win32, the EBP on entry to the filter points to the end of an
1749 // exception registration object. It contains 6 32-bit fields, and the info
1750 // pointer is stored in the second field. So, GEP 20 bytes backwards and
1751 // load the pointer.
1752 SEHInfo = Builder.CreateConstInBoundsGEP1_32(Int8Ty, EntryEBP, -20);
1753 SEHInfo = Builder.CreateBitCast(SEHInfo, Int8PtrTy->getPointerTo());
John McCall7f416cc2015-09-08 08:05:57 +00001754 SEHInfo = Builder.CreateAlignedLoad(Int8PtrTy, SEHInfo, getPointerAlign());
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001755 SEHCodeSlotStack.push_back(recoverAddrOfEscapedLocal(
1756 ParentCGF, ParentCGF.SEHCodeSlotStack.back(), ParentFP));
1757 }
1758
Reid Kleckner1d59f992015-01-22 01:36:17 +00001759 // Save the exception code in the exception slot to unify exception access in
1760 // the filter function and the landing pad.
1761 // struct EXCEPTION_POINTERS {
1762 // EXCEPTION_RECORD *ExceptionRecord;
1763 // CONTEXT *ContextRecord;
1764 // };
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001765 // int exceptioncode = exception_pointers->ExceptionRecord->ExceptionCode;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001766 llvm::Type *RecordTy = CGM.Int32Ty->getPointerTo();
1767 llvm::Type *PtrsTy = llvm::StructType::get(RecordTy, CGM.VoidPtrTy, nullptr);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001768 llvm::Value *Ptrs = Builder.CreateBitCast(SEHInfo, PtrsTy->getPointerTo());
David Blaikie1ed728c2015-04-05 22:45:47 +00001769 llvm::Value *Rec = Builder.CreateStructGEP(PtrsTy, Ptrs, 0);
John McCall7f416cc2015-09-08 08:05:57 +00001770 Rec = Builder.CreateAlignedLoad(Rec, getPointerAlign());
1771 llvm::Value *Code = Builder.CreateAlignedLoad(Rec, getIntAlign());
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001772 assert(!SEHCodeSlotStack.empty() && "emitting EH code outside of __except");
1773 Builder.CreateStore(Code, SEHCodeSlotStack.back());
Reid Kleckner1d59f992015-01-22 01:36:17 +00001774}
1775
1776llvm::Value *CodeGenFunction::EmitSEHExceptionInfo() {
1777 // Sema should diagnose calling this builtin outside of a filter context, but
1778 // don't crash if we screw up.
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001779 if (!SEHInfo)
Reid Kleckner1d59f992015-01-22 01:36:17 +00001780 return llvm::UndefValue::get(Int8PtrTy);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001781 assert(SEHInfo->getType() == Int8PtrTy);
1782 return SEHInfo;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001783}
1784
1785llvm::Value *CodeGenFunction::EmitSEHExceptionCode() {
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001786 assert(!SEHCodeSlotStack.empty() && "emitting EH code outside of __except");
John McCall7f416cc2015-09-08 08:05:57 +00001787 return Builder.CreateLoad(SEHCodeSlotStack.back());
Reid Kleckner1d59f992015-01-22 01:36:17 +00001788}
1789
Reid Kleckneraca01db2015-02-04 22:37:07 +00001790llvm::Value *CodeGenFunction::EmitSEHAbnormalTermination() {
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001791 // Abnormal termination is just the first parameter to the outlined finally
1792 // helper.
1793 auto AI = CurFn->arg_begin();
1794 return Builder.CreateZExt(&*AI, Int32Ty);
Reid Kleckneraca01db2015-02-04 22:37:07 +00001795}
1796
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001797void CodeGenFunction::EnterSEHTryStmt(const SEHTryStmt &S) {
1798 CodeGenFunction HelperCGF(CGM, /*suppressNewContext=*/true);
1799 if (const SEHFinallyStmt *Finally = S.getFinallyHandler()) {
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001800 // Outline the finally block.
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001801 llvm::Function *FinallyFunc =
1802 HelperCGF.GenerateSEHFinallyFunction(*this, *Finally);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001803
1804 // Push a cleanup for __finally blocks.
Reid Kleckner2586aac2015-09-10 22:11:13 +00001805 EHStack.pushCleanup<PerformSEHFinally>(NormalAndEHCleanup, FinallyFunc,
1806 EHStack.getInnermostEHScope());
Reid Kleckner1d59f992015-01-22 01:36:17 +00001807 return;
1808 }
1809
1810 // Otherwise, we must have an __except block.
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001811 const SEHExceptStmt *Except = S.getExceptHandler();
Reid Kleckner1d59f992015-01-22 01:36:17 +00001812 assert(Except);
1813 EHCatchScope *CatchScope = EHStack.pushCatch(1);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001814 SEHCodeSlotStack.push_back(
1815 CreateMemTemp(getContext().IntTy, "__exception_code"));
Reid Kleckner2a2e1562015-01-22 02:25:56 +00001816
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001817 // If the filter is known to evaluate to 1, then we can use the clause
1818 // "catch i8* null". We can't do this on x86 because the filter has to save
1819 // the exception code.
Reid Kleckner2a2e1562015-01-22 02:25:56 +00001820 llvm::Constant *C =
1821 CGM.EmitConstantExpr(Except->getFilterExpr(), getContext().IntTy, this);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001822 if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86 && C &&
1823 C->isOneValue()) {
Reid Kleckner2a2e1562015-01-22 02:25:56 +00001824 CatchScope->setCatchAllHandler(0, createBasicBlock("__except"));
1825 return;
1826 }
1827
1828 // In general, we have to emit an outlined filter function. Use the function
1829 // in place of the RTTI typeinfo global that C++ EH uses.
Reid Kleckner1d59f992015-01-22 01:36:17 +00001830 llvm::Function *FilterFunc =
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001831 HelperCGF.GenerateSEHFilterFunction(*this, *Except);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001832 llvm::Constant *OpaqueFunc =
1833 llvm::ConstantExpr::getBitCast(FilterFunc, Int8PtrTy);
Reid Klecknerbb34b602015-09-10 18:39:41 +00001834 CatchScope->setHandler(0, OpaqueFunc, createBasicBlock("__except.ret"));
Reid Kleckner1d59f992015-01-22 01:36:17 +00001835}
1836
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001837void CodeGenFunction::ExitSEHTryStmt(const SEHTryStmt &S) {
Reid Kleckner1d59f992015-01-22 01:36:17 +00001838 // Just pop the cleanup if it's a __finally block.
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001839 if (S.getFinallyHandler()) {
Reid Kleckner1d59f992015-01-22 01:36:17 +00001840 PopCleanupBlock();
1841 return;
1842 }
1843
1844 // Otherwise, we must have an __except block.
Reid Kleckneraca01db2015-02-04 22:37:07 +00001845 const SEHExceptStmt *Except = S.getExceptHandler();
Reid Kleckner1d59f992015-01-22 01:36:17 +00001846 assert(Except && "__try must have __finally xor __except");
1847 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1848
1849 // Don't emit the __except block if the __try block lacked invokes.
1850 // TODO: Model unwind edges from instructions, either with iload / istore or
1851 // a try body function.
1852 if (!CatchScope.hasEHBranches()) {
1853 CatchScope.clearHandlerBlocks();
1854 EHStack.popCatch();
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001855 SEHCodeSlotStack.pop_back();
Reid Kleckner1d59f992015-01-22 01:36:17 +00001856 return;
1857 }
1858
1859 // The fall-through block.
1860 llvm::BasicBlock *ContBB = createBasicBlock("__try.cont");
1861
1862 // We just emitted the body of the __try; jump to the continue block.
1863 if (HaveInsertPoint())
1864 Builder.CreateBr(ContBB);
1865
1866 // Check if our filter function returned true.
1867 emitCatchDispatchBlock(*this, CatchScope);
1868
1869 // Grab the block before we pop the handler.
1870 llvm::BasicBlock *ExceptBB = CatchScope.getHandler(0).Block;
1871 EHStack.popCatch();
1872
1873 EmitBlockAfterUses(ExceptBB);
1874
Reid Klecknerbb34b602015-09-10 18:39:41 +00001875 if (CGM.getCodeGenOpts().NewMSEH) {
1876 // __except blocks don't get outlined into funclets, so immediately do a
1877 // catchret.
1878 llvm::BasicBlock *CatchPadBB = ExceptBB->getSinglePredecessor();
1879 assert(CatchPadBB && "only ExceptBB pred should be catchpad");
1880 llvm::CatchPadInst *CPI =
1881 cast<llvm::CatchPadInst>(CatchPadBB->getFirstNonPHI());
1882 ExceptBB = createBasicBlock("__except");
1883 Builder.CreateCatchRet(CPI, ExceptBB);
1884 EmitBlock(ExceptBB);
1885 }
1886
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001887 // On Win64, the exception pointer is the exception code. Copy it to the slot.
1888 if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
1889 llvm::Value *Code =
1890 Builder.CreatePtrToInt(getExceptionFromSlot(), IntPtrTy);
1891 Code = Builder.CreateTrunc(Code, Int32Ty);
1892 Builder.CreateStore(Code, SEHCodeSlotStack.back());
1893 }
1894
Reid Kleckner1d59f992015-01-22 01:36:17 +00001895 // Emit the __except body.
1896 EmitStmt(Except->getBlock());
1897
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001898 // End the lifetime of the exception code.
1899 SEHCodeSlotStack.pop_back();
1900
Reid Kleckner3a417c32015-01-30 22:16:45 +00001901 if (HaveInsertPoint())
1902 Builder.CreateBr(ContBB);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001903
1904 EmitBlock(ContBB);
Reid Kleckner543a16c2013-09-16 21:46:30 +00001905}
Nico Weber9b982072014-07-07 00:12:30 +00001906
1907void CodeGenFunction::EmitSEHLeaveStmt(const SEHLeaveStmt &S) {
Nico Weber5779f842015-02-12 23:16:11 +00001908 // If this code is reachable then emit a stop point (if generating
1909 // debug info). We have to do this ourselves because we are on the
1910 // "simple" statement path.
1911 if (HaveInsertPoint())
1912 EmitStopPoint(&S);
1913
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001914 // This must be a __leave from a __finally block, which we warn on and is UB.
1915 // Just emit unreachable.
1916 if (!isSEHTryScope()) {
1917 Builder.CreateUnreachable();
1918 Builder.ClearInsertionPoint();
1919 return;
1920 }
1921
Nico Weber5779f842015-02-12 23:16:11 +00001922 EmitBranchThroughCleanup(*SEHTryEpilogueStack.back());
Nico Weber9b982072014-07-07 00:12:30 +00001923}