blob: 337aaf23fd0e39bde5562182c42b33785899bc99 [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"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000023#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000024#include "llvm/IR/Intrinsics.h"
Reid Kleckner31a1bb02015-04-08 22:23:48 +000025#include "llvm/IR/IntrinsicInst.h"
Reid Klecknerebaf28d2015-04-14 20:59:00 +000026#include "llvm/Support/SaveAndRestore.h"
John McCallbd309292010-07-06 01:34:17 +000027
Anders Carlsson4b08db72009-10-30 01:42:31 +000028using namespace clang;
29using namespace CodeGen;
30
John McCall2c33ba82013-02-12 03:51:38 +000031static llvm::Constant *getFreeExceptionFn(CodeGenModule &CGM) {
Mike Stump33270212009-12-02 07:41:41 +000032 // void __cxa_free_exception(void *thrown_exception);
Mike Stump75546b82009-12-10 00:06:18 +000033
Chris Lattner2192fe52011-07-18 04:24:23 +000034 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +000035 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000036
John McCall2c33ba82013-02-12 03:51:38 +000037 return CGM.CreateRuntimeFunction(FTy, "__cxa_free_exception");
Mike Stump33270212009-12-02 07:41:41 +000038}
39
John McCall2c33ba82013-02-12 03:51:38 +000040static llvm::Constant *getUnexpectedFn(CodeGenModule &CGM) {
Richard Smith2f7aa192013-06-20 23:03:35 +000041 // void __cxa_call_unexpected(void *thrown_exception);
Mike Stump1d849212009-12-07 23:38:24 +000042
Chris Lattner2192fe52011-07-18 04:24:23 +000043 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +000044 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000045
John McCall2c33ba82013-02-12 03:51:38 +000046 return CGM.CreateRuntimeFunction(FTy, "__cxa_call_unexpected");
Mike Stump1d849212009-12-07 23:38:24 +000047}
48
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000049llvm::Constant *CodeGenModule::getTerminateFn() {
Mike Stump33270212009-12-02 07:41:41 +000050 // void __terminate();
51
Chris Lattner2192fe52011-07-18 04:24:23 +000052 llvm::FunctionType *FTy =
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000053 llvm::FunctionType::get(VoidTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000054
Chris Lattner0e62c1c2011-07-23 10:55:15 +000055 StringRef name;
John McCall9de19782011-07-06 01:22:26 +000056
57 // In C++, use std::terminate().
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000058 if (getLangOpts().CPlusPlus &&
59 getTarget().getCXXABI().isItaniumFamily()) {
Reid Kleckner1d59f992015-01-22 01:36:17 +000060 name = "_ZSt9terminatev";
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000061 } else if (getLangOpts().CPlusPlus &&
62 getTarget().getCXXABI().isMicrosoft()) {
David Majnemerdbdab402015-02-25 23:01:21 +000063 name = "\01?terminate@@YAXXZ";
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000064 } else if (getLangOpts().ObjC1 &&
65 getLangOpts().ObjCRuntime.hasTerminate())
John McCall9de19782011-07-06 01:22:26 +000066 name = "objc_terminate";
67 else
68 name = "abort";
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000069 return CreateRuntimeFunction(FTy, name);
David Chisnallf9c42252010-05-17 13:49:20 +000070}
71
John McCall2c33ba82013-02-12 03:51:38 +000072static llvm::Constant *getCatchallRethrowFn(CodeGenModule &CGM,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000073 StringRef Name) {
Chris Lattner2192fe52011-07-18 04:24:23 +000074 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +000075 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
John McCall36ea3722010-07-17 00:43:08 +000076
John McCall2c33ba82013-02-12 03:51:38 +000077 return CGM.CreateRuntimeFunction(FTy, Name);
John McCallbd309292010-07-06 01:34:17 +000078}
79
Benjamin Kramer793bd552012-02-08 12:41:24 +000080namespace {
81 /// The exceptions personality for a function.
82 struct EHPersonality {
83 const char *PersonalityFn;
84
85 // If this is non-null, this personality requires a non-standard
86 // function for rethrowing an exception after a catchall cleanup.
87 // This function must have prototype void(void*).
88 const char *CatchallRethrowFn;
89
Reid Klecknerdeeddec2015-02-05 18:56:03 +000090 static const EHPersonality &get(CodeGenModule &CGM,
91 const FunctionDecl *FD);
92 static const EHPersonality &get(CodeGenFunction &CGF) {
93 return get(CGF.CGM, dyn_cast_or_null<FunctionDecl>(CGF.CurCodeDecl));
94 }
95
Benjamin Kramer793bd552012-02-08 12:41:24 +000096 static const EHPersonality GNU_C;
97 static const EHPersonality GNU_C_SJLJ;
Reid Kleckner8f45c9c2014-09-15 17:19:16 +000098 static const EHPersonality GNU_C_SEH;
Benjamin Kramer793bd552012-02-08 12:41:24 +000099 static const EHPersonality GNU_ObjC;
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000100 static const EHPersonality GNUstep_ObjC;
Benjamin Kramer793bd552012-02-08 12:41:24 +0000101 static const EHPersonality GNU_ObjCXX;
102 static const EHPersonality NeXT_ObjC;
103 static const EHPersonality GNU_CPlusPlus;
104 static const EHPersonality GNU_CPlusPlus_SJLJ;
Reid Kleckner8f45c9c2014-09-15 17:19:16 +0000105 static const EHPersonality GNU_CPlusPlus_SEH;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000106 static const EHPersonality MSVC_except_handler;
107 static const EHPersonality MSVC_C_specific_handler;
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000108 static const EHPersonality MSVC_CxxFrameHandler3;
Benjamin Kramer793bd552012-02-08 12:41:24 +0000109 };
110}
111
Craig Topper8a13c412014-05-21 05:09:00 +0000112const EHPersonality EHPersonality::GNU_C = { "__gcc_personality_v0", nullptr };
Benjamin Kramer793bd552012-02-08 12:41:24 +0000113const EHPersonality
Craig Topper8a13c412014-05-21 05:09:00 +0000114EHPersonality::GNU_C_SJLJ = { "__gcc_personality_sj0", nullptr };
115const EHPersonality
Reid Kleckner8f45c9c2014-09-15 17:19:16 +0000116EHPersonality::GNU_C_SEH = { "__gcc_personality_seh0", nullptr };
117const EHPersonality
Craig Topper8a13c412014-05-21 05:09:00 +0000118EHPersonality::NeXT_ObjC = { "__objc_personality_v0", nullptr };
119const EHPersonality
120EHPersonality::GNU_CPlusPlus = { "__gxx_personality_v0", nullptr };
121const EHPersonality
122EHPersonality::GNU_CPlusPlus_SJLJ = { "__gxx_personality_sj0", nullptr };
Benjamin Kramer793bd552012-02-08 12:41:24 +0000123const EHPersonality
Reid Kleckner8f45c9c2014-09-15 17:19:16 +0000124EHPersonality::GNU_CPlusPlus_SEH = { "__gxx_personality_seh0", nullptr };
125const EHPersonality
Benjamin Kramer793bd552012-02-08 12:41:24 +0000126EHPersonality::GNU_ObjC = {"__gnu_objc_personality_v0", "objc_exception_throw"};
127const EHPersonality
Craig Topper8a13c412014-05-21 05:09:00 +0000128EHPersonality::GNU_ObjCXX = { "__gnustep_objcxx_personality_v0", nullptr };
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000129const EHPersonality
Craig Topper8a13c412014-05-21 05:09:00 +0000130EHPersonality::GNUstep_ObjC = { "__gnustep_objc_personality_v0", nullptr };
Reid Kleckner1d59f992015-01-22 01:36:17 +0000131const EHPersonality
132EHPersonality::MSVC_except_handler = { "_except_handler3", nullptr };
133const EHPersonality
134EHPersonality::MSVC_C_specific_handler = { "__C_specific_handler", nullptr };
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000135const EHPersonality
136EHPersonality::MSVC_CxxFrameHandler3 = { "__CxxFrameHandler3", nullptr };
John McCall36ea3722010-07-17 00:43:08 +0000137
Reid Klecknere070b992014-11-14 02:01:10 +0000138/// On Win64, use libgcc's SEH personality function. We fall back to dwarf on
139/// other platforms, unless the user asked for SjLj exceptions.
140static bool useLibGCCSEHPersonality(const llvm::Triple &T) {
141 return T.isOSWindows() && T.getArch() == llvm::Triple::x86_64;
142}
143
144static const EHPersonality &getCPersonality(const llvm::Triple &T,
145 const LangOptions &L) {
John McCall2faab302010-11-07 02:35:25 +0000146 if (L.SjLjExceptions)
147 return EHPersonality::GNU_C_SJLJ;
Reid Klecknere070b992014-11-14 02:01:10 +0000148 else if (useLibGCCSEHPersonality(T))
Reid Kleckner8f45c9c2014-09-15 17:19:16 +0000149 return EHPersonality::GNU_C_SEH;
John McCall36ea3722010-07-17 00:43:08 +0000150 return EHPersonality::GNU_C;
151}
152
Reid Klecknere070b992014-11-14 02:01:10 +0000153static const EHPersonality &getObjCPersonality(const llvm::Triple &T,
154 const LangOptions &L) {
John McCall5fb5df92012-06-20 06:18:46 +0000155 switch (L.ObjCRuntime.getKind()) {
156 case ObjCRuntime::FragileMacOSX:
Reid Klecknere070b992014-11-14 02:01:10 +0000157 return getCPersonality(T, L);
John McCall5fb5df92012-06-20 06:18:46 +0000158 case ObjCRuntime::MacOSX:
159 case ObjCRuntime::iOS:
160 return EHPersonality::NeXT_ObjC;
David Chisnallb601c962012-07-03 20:49:52 +0000161 case ObjCRuntime::GNUstep:
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000162 if (L.ObjCRuntime.getVersion() >= VersionTuple(1, 7))
163 return EHPersonality::GNUstep_ObjC;
164 // fallthrough
David Chisnallb601c962012-07-03 20:49:52 +0000165 case ObjCRuntime::GCC:
John McCall775086e2012-07-12 02:07:58 +0000166 case ObjCRuntime::ObjFW:
John McCall36ea3722010-07-17 00:43:08 +0000167 return EHPersonality::GNU_ObjC;
John McCallbd309292010-07-06 01:34:17 +0000168 }
John McCall5fb5df92012-06-20 06:18:46 +0000169 llvm_unreachable("bad runtime kind");
John McCallbd309292010-07-06 01:34:17 +0000170}
171
Reid Klecknere070b992014-11-14 02:01:10 +0000172static const EHPersonality &getCXXPersonality(const llvm::Triple &T,
173 const LangOptions &L) {
John McCall36ea3722010-07-17 00:43:08 +0000174 if (L.SjLjExceptions)
175 return EHPersonality::GNU_CPlusPlus_SJLJ;
Reid Klecknere070b992014-11-14 02:01:10 +0000176 else if (useLibGCCSEHPersonality(T))
Reid Kleckner8f45c9c2014-09-15 17:19:16 +0000177 return EHPersonality::GNU_CPlusPlus_SEH;
Reid Klecknere070b992014-11-14 02:01:10 +0000178 return EHPersonality::GNU_CPlusPlus;
John McCallbd309292010-07-06 01:34:17 +0000179}
180
181/// Determines the personality function to use when both C++
182/// and Objective-C exceptions are being caught.
Reid Klecknere070b992014-11-14 02:01:10 +0000183static const EHPersonality &getObjCXXPersonality(const llvm::Triple &T,
184 const LangOptions &L) {
John McCall5fb5df92012-06-20 06:18:46 +0000185 switch (L.ObjCRuntime.getKind()) {
John McCallbd309292010-07-06 01:34:17 +0000186 // The ObjC personality defers to the C++ personality for non-ObjC
187 // handlers. Unlike the C++ case, we use the same personality
188 // function on targets using (backend-driven) SJLJ EH.
John McCall5fb5df92012-06-20 06:18:46 +0000189 case ObjCRuntime::MacOSX:
190 case ObjCRuntime::iOS:
191 return EHPersonality::NeXT_ObjC;
John McCallbd309292010-07-06 01:34:17 +0000192
John McCall5fb5df92012-06-20 06:18:46 +0000193 // In the fragile ABI, just use C++ exception handling and hope
194 // they're not doing crazy exception mixing.
195 case ObjCRuntime::FragileMacOSX:
Reid Klecknere070b992014-11-14 02:01:10 +0000196 return getCXXPersonality(T, L);
David Chisnallf9c42252010-05-17 13:49:20 +0000197
David Chisnallb601c962012-07-03 20:49:52 +0000198 // The GCC runtime's personality function inherently doesn't support
John McCall36ea3722010-07-17 00:43:08 +0000199 // mixed EH. Use the C++ personality just to avoid returning null.
David Chisnallb601c962012-07-03 20:49:52 +0000200 case ObjCRuntime::GCC:
John McCall775086e2012-07-12 02:07:58 +0000201 case ObjCRuntime::ObjFW: // XXX: this will change soon
David Chisnallb601c962012-07-03 20:49:52 +0000202 return EHPersonality::GNU_ObjC;
203 case ObjCRuntime::GNUstep:
John McCall5fb5df92012-06-20 06:18:46 +0000204 return EHPersonality::GNU_ObjCXX;
205 }
206 llvm_unreachable("bad runtime kind");
John McCallbd309292010-07-06 01:34:17 +0000207}
208
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000209static const EHPersonality &getSEHPersonalityMSVC(const llvm::Triple &T) {
Reid Kleckner1d59f992015-01-22 01:36:17 +0000210 if (T.getArch() == llvm::Triple::x86)
211 return EHPersonality::MSVC_except_handler;
212 return EHPersonality::MSVC_C_specific_handler;
213}
214
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000215const EHPersonality &EHPersonality::get(CodeGenModule &CGM,
216 const FunctionDecl *FD) {
Reid Klecknere070b992014-11-14 02:01:10 +0000217 const llvm::Triple &T = CGM.getTarget().getTriple();
218 const LangOptions &L = CGM.getLangOpts();
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000219
Reid Kleckner1d59f992015-01-22 01:36:17 +0000220 // Try to pick a personality function that is compatible with MSVC if we're
221 // not compiling Obj-C. Obj-C users better have an Obj-C runtime that supports
222 // the GCC-style personality function.
223 if (T.isWindowsMSVCEnvironment() && !L.ObjC1) {
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000224 if (L.SjLjExceptions)
225 return EHPersonality::GNU_CPlusPlus_SJLJ;
226 else if (FD && FD->usesSEHTry())
227 return getSEHPersonalityMSVC(T);
Reid Kleckner1d59f992015-01-22 01:36:17 +0000228 else
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000229 return EHPersonality::MSVC_CxxFrameHandler3;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000230 }
231
John McCall36ea3722010-07-17 00:43:08 +0000232 if (L.CPlusPlus && L.ObjC1)
Reid Klecknere070b992014-11-14 02:01:10 +0000233 return getObjCXXPersonality(T, L);
John McCall36ea3722010-07-17 00:43:08 +0000234 else if (L.CPlusPlus)
Reid Klecknere070b992014-11-14 02:01:10 +0000235 return getCXXPersonality(T, L);
John McCall36ea3722010-07-17 00:43:08 +0000236 else if (L.ObjC1)
Reid Klecknere070b992014-11-14 02:01:10 +0000237 return getObjCPersonality(T, L);
John McCallbd309292010-07-06 01:34:17 +0000238 else
Reid Klecknere070b992014-11-14 02:01:10 +0000239 return getCPersonality(T, L);
John McCall36ea3722010-07-17 00:43:08 +0000240}
John McCallbd309292010-07-06 01:34:17 +0000241
John McCall0bdb1fd2010-09-16 06:16:50 +0000242static llvm::Constant *getPersonalityFn(CodeGenModule &CGM,
John McCall36ea3722010-07-17 00:43:08 +0000243 const EHPersonality &Personality) {
John McCall36ea3722010-07-17 00:43:08 +0000244 llvm::Constant *Fn =
Chris Lattnerece04092012-02-07 00:39:47 +0000245 CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.Int32Ty, true),
Benjamin Kramer793bd552012-02-08 12:41:24 +0000246 Personality.PersonalityFn);
John McCall0bdb1fd2010-09-16 06:16:50 +0000247 return Fn;
248}
249
250static llvm::Constant *getOpaquePersonalityFn(CodeGenModule &CGM,
251 const EHPersonality &Personality) {
252 llvm::Constant *Fn = getPersonalityFn(CGM, Personality);
John McCallad7c5c12011-02-08 08:22:06 +0000253 return llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
John McCall0bdb1fd2010-09-16 06:16:50 +0000254}
255
256/// Check whether a personality function could reasonably be swapped
257/// for a C++ personality function.
258static bool PersonalityHasOnlyCXXUses(llvm::Constant *Fn) {
Chandler Carruth4d01fff2014-03-09 03:16:50 +0000259 for (llvm::User *U : Fn->users()) {
John McCall0bdb1fd2010-09-16 06:16:50 +0000260 // Conditionally white-list bitcasts.
Chandler Carruth4d01fff2014-03-09 03:16:50 +0000261 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(U)) {
John McCall0bdb1fd2010-09-16 06:16:50 +0000262 if (CE->getOpcode() != llvm::Instruction::BitCast) return false;
263 if (!PersonalityHasOnlyCXXUses(CE))
264 return false;
265 continue;
266 }
267
Bill Wendling58e58fe2011-09-19 22:08:36 +0000268 // Otherwise, it has to be a landingpad instruction.
Chandler Carruth4d01fff2014-03-09 03:16:50 +0000269 llvm::LandingPadInst *LPI = dyn_cast<llvm::LandingPadInst>(U);
Bill Wendling58e58fe2011-09-19 22:08:36 +0000270 if (!LPI) return false;
John McCall0bdb1fd2010-09-16 06:16:50 +0000271
Bill Wendling58e58fe2011-09-19 22:08:36 +0000272 for (unsigned I = 0, E = LPI->getNumClauses(); I != E; ++I) {
John McCall0bdb1fd2010-09-16 06:16:50 +0000273 // Look for something that would've been returned by the ObjC
274 // runtime's GetEHType() method.
Bill Wendling58e58fe2011-09-19 22:08:36 +0000275 llvm::Value *Val = LPI->getClause(I)->stripPointerCasts();
276 if (LPI->isCatch(I)) {
277 // Check if the catch value has the ObjC prefix.
Bill Wendling5d7469e2011-09-20 00:40:19 +0000278 if (llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Val))
279 // ObjC EH selector entries are always global variables with
280 // names starting like this.
281 if (GV->getName().startswith("OBJC_EHTYPE"))
282 return false;
Bill Wendling58e58fe2011-09-19 22:08:36 +0000283 } else {
284 // Check if any of the filter values have the ObjC prefix.
285 llvm::Constant *CVal = cast<llvm::Constant>(Val);
286 for (llvm::User::op_iterator
287 II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II) {
Bill Wendling5d7469e2011-09-20 00:40:19 +0000288 if (llvm::GlobalVariable *GV =
289 cast<llvm::GlobalVariable>((*II)->stripPointerCasts()))
290 // ObjC EH selector entries are always global variables with
291 // names starting like this.
292 if (GV->getName().startswith("OBJC_EHTYPE"))
293 return false;
Bill Wendling58e58fe2011-09-19 22:08:36 +0000294 }
295 }
John McCall0bdb1fd2010-09-16 06:16:50 +0000296 }
297 }
298
299 return true;
300}
301
302/// Try to use the C++ personality function in ObjC++. Not doing this
303/// can cause some incompatibilities with gcc, which is more
304/// aggressive about only using the ObjC++ personality in a function
305/// when it really needs it.
306void CodeGenModule::SimplifyPersonality() {
John McCall0bdb1fd2010-09-16 06:16:50 +0000307 // If we're not in ObjC++ -fexceptions, there's nothing to do.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000308 if (!LangOpts.CPlusPlus || !LangOpts.ObjC1 || !LangOpts.Exceptions)
John McCall0bdb1fd2010-09-16 06:16:50 +0000309 return;
310
John McCall3c223932012-11-14 17:48:31 +0000311 // Both the problem this endeavors to fix and the way the logic
312 // above works is specific to the NeXT runtime.
313 if (!LangOpts.ObjCRuntime.isNeXTFamily())
314 return;
315
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000316 const EHPersonality &ObjCXX = EHPersonality::get(*this, /*FD=*/nullptr);
Reid Klecknere070b992014-11-14 02:01:10 +0000317 const EHPersonality &CXX =
318 getCXXPersonality(getTarget().getTriple(), LangOpts);
Benjamin Kramer793bd552012-02-08 12:41:24 +0000319 if (&ObjCXX == &CXX)
John McCall0bdb1fd2010-09-16 06:16:50 +0000320 return;
321
Benjamin Kramer793bd552012-02-08 12:41:24 +0000322 assert(std::strcmp(ObjCXX.PersonalityFn, CXX.PersonalityFn) != 0 &&
323 "Different EHPersonalities using the same personality function.");
324
325 llvm::Function *Fn = getModule().getFunction(ObjCXX.PersonalityFn);
John McCall0bdb1fd2010-09-16 06:16:50 +0000326
327 // Nothing to do if it's unused.
328 if (!Fn || Fn->use_empty()) return;
329
330 // Can't do the optimization if it has non-C++ uses.
331 if (!PersonalityHasOnlyCXXUses(Fn)) return;
332
333 // Create the C++ personality function and kill off the old
334 // function.
335 llvm::Constant *CXXFn = getPersonalityFn(*this, CXX);
336
337 // This can happen if the user is screwing with us.
338 if (Fn->getType() != CXXFn->getType()) return;
339
340 Fn->replaceAllUsesWith(CXXFn);
341 Fn->eraseFromParent();
John McCallbd309292010-07-06 01:34:17 +0000342}
343
344/// Returns the value to inject into a selector to indicate the
345/// presence of a catch-all.
346static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
347 // Possibly we should use @llvm.eh.catch.all.value here.
John McCallad7c5c12011-02-08 08:22:06 +0000348 return llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
John McCallbd309292010-07-06 01:34:17 +0000349}
350
John McCallbb026012010-07-13 21:17:51 +0000351namespace {
352 /// A cleanup to free the exception object if its initialization
353 /// throws.
John McCall5fcf8da2011-07-12 00:15:30 +0000354 struct FreeException : EHScopeStack::Cleanup {
355 llvm::Value *exn;
356 FreeException(llvm::Value *exn) : exn(exn) {}
Craig Topper4f12f102014-03-12 06:41:41 +0000357 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +0000358 CGF.EmitNounwindRuntimeCall(getFreeExceptionFn(CGF.CGM), exn);
John McCallbb026012010-07-13 21:17:51 +0000359 }
360 };
361}
362
John McCall2e6567a2010-04-22 01:10:34 +0000363// Emits an exception expression into the given location. This
364// differs from EmitAnyExprToMem only in that, if a final copy-ctor
365// call is required, an exception within that copy ctor causes
366// std::terminate to be invoked.
David Majnemer7c237072015-03-05 00:46:22 +0000367void CodeGenFunction::EmitAnyExprToExn(const Expr *e, llvm::Value *addr) {
John McCallbd309292010-07-06 01:34:17 +0000368 // Make sure the exception object is cleaned up if there's an
369 // exception during initialization.
David Majnemer7c237072015-03-05 00:46:22 +0000370 pushFullExprCleanup<FreeException>(EHCleanup, addr);
371 EHScopeStack::stable_iterator cleanup = EHStack.stable_begin();
John McCall2e6567a2010-04-22 01:10:34 +0000372
373 // __cxa_allocate_exception returns a void*; we need to cast this
374 // to the appropriate type for the object.
David Majnemer7c237072015-03-05 00:46:22 +0000375 llvm::Type *ty = ConvertTypeForMem(e->getType())->getPointerTo();
376 llvm::Value *typedAddr = Builder.CreateBitCast(addr, ty);
John McCall2e6567a2010-04-22 01:10:34 +0000377
378 // FIXME: this isn't quite right! If there's a final unelided call
379 // to a copy constructor, then according to [except.terminate]p1 we
380 // must call std::terminate() if that constructor throws, because
381 // technically that copy occurs after the exception expression is
382 // evaluated but before the exception is caught. But the best way
383 // to handle that is to teach EmitAggExpr to do the final copy
384 // differently if it can't be elided.
David Majnemer7c237072015-03-05 00:46:22 +0000385 EmitAnyExprToMem(e, typedAddr, e->getType().getQualifiers(),
386 /*IsInit*/ true);
John McCall2e6567a2010-04-22 01:10:34 +0000387
John McCalle4df6c82011-01-28 08:37:24 +0000388 // Deactivate the cleanup block.
David Majnemer7c237072015-03-05 00:46:22 +0000389 DeactivateCleanupBlock(cleanup, cast<llvm::Instruction>(typedAddr));
Mike Stump54066142009-12-01 03:41:18 +0000390}
391
John McCallbd309292010-07-06 01:34:17 +0000392llvm::Value *CodeGenFunction::getExceptionSlot() {
John McCall9b382dd2011-05-28 21:13:02 +0000393 if (!ExceptionSlot)
394 ExceptionSlot = CreateTempAlloca(Int8PtrTy, "exn.slot");
John McCallbd309292010-07-06 01:34:17 +0000395 return ExceptionSlot;
Mike Stump54066142009-12-01 03:41:18 +0000396}
397
John McCall9b382dd2011-05-28 21:13:02 +0000398llvm::Value *CodeGenFunction::getEHSelectorSlot() {
399 if (!EHSelectorSlot)
400 EHSelectorSlot = CreateTempAlloca(Int32Ty, "ehselector.slot");
401 return EHSelectorSlot;
402}
403
Bill Wendling79a70e42011-09-15 18:57:19 +0000404llvm::Value *CodeGenFunction::getExceptionFromSlot() {
405 return Builder.CreateLoad(getExceptionSlot(), "exn");
406}
407
408llvm::Value *CodeGenFunction::getSelectorFromSlot() {
409 return Builder.CreateLoad(getEHSelectorSlot(), "sel");
410}
411
Richard Smithea852322013-05-07 21:53:22 +0000412void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E,
413 bool KeepInsertionPoint) {
David Majnemer7c237072015-03-05 00:46:22 +0000414 if (const Expr *SubExpr = E->getSubExpr()) {
415 QualType ThrowType = SubExpr->getType();
416 if (ThrowType->isObjCObjectPointerType()) {
417 const Stmt *ThrowStmt = E->getSubExpr();
418 const ObjCAtThrowStmt S(E->getExprLoc(), const_cast<Stmt *>(ThrowStmt));
419 CGM.getObjCRuntime().EmitThrowStmt(*this, S, false);
420 } else {
421 CGM.getCXXABI().emitThrow(*this, E);
John McCall2e6567a2010-04-22 01:10:34 +0000422 }
David Majnemer7c237072015-03-05 00:46:22 +0000423 } else {
424 CGM.getCXXABI().emitRethrow(*this, /*isNoReturn=*/true);
John McCall2e6567a2010-04-22 01:10:34 +0000425 }
Mike Stump75546b82009-12-10 00:06:18 +0000426
John McCall20f6ab82011-01-12 03:41:02 +0000427 // throw is an expression, and the expression emitters expect us
428 // to leave ourselves at a valid insertion point.
Richard Smithea852322013-05-07 21:53:22 +0000429 if (KeepInsertionPoint)
430 EmitBlock(createBasicBlock("throw.cont"));
Anders Carlsson4b08db72009-10-30 01:42:31 +0000431}
Mike Stump58ef18b2009-11-20 23:44:51 +0000432
Mike Stump1d849212009-12-07 23:38:24 +0000433void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000434 if (!CGM.getLangOpts().CXXExceptions)
Anders Carlsson9878f9f2010-02-06 23:59:05 +0000435 return;
436
Mike Stump1d849212009-12-07 23:38:24 +0000437 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
Craig Topper8a13c412014-05-21 05:09:00 +0000438 if (!FD) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000439 // Check if CapturedDecl is nothrow and create terminate scope for it.
440 if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
441 if (CD->isNothrow())
442 EHStack.pushTerminate();
443 }
Mike Stump1d849212009-12-07 23:38:24 +0000444 return;
Alexey Bataev9959db52014-05-06 10:08:46 +0000445 }
Mike Stump1d849212009-12-07 23:38:24 +0000446 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
Craig Topper8a13c412014-05-21 05:09:00 +0000447 if (!Proto)
Mike Stump1d849212009-12-07 23:38:24 +0000448 return;
449
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000450 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
451 if (isNoexceptExceptionSpec(EST)) {
452 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
453 // noexcept functions are simple terminate scopes.
454 EHStack.pushTerminate();
455 }
456 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
David Majnemer1f192e22015-04-01 04:45:52 +0000457 // TODO: Revisit exception specifications for the MS ABI. There is a way to
458 // encode these in an object file but MSVC doesn't do anything with it.
459 if (getTarget().getCXXABI().isMicrosoft())
460 return;
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000461 unsigned NumExceptions = Proto->getNumExceptions();
462 EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
Mike Stump1d849212009-12-07 23:38:24 +0000463
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000464 for (unsigned I = 0; I != NumExceptions; ++I) {
465 QualType Ty = Proto->getExceptionType(I);
466 QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
467 llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType,
468 /*ForEH=*/true);
469 Filter->setFilter(I, EHType);
470 }
Mike Stump1d849212009-12-07 23:38:24 +0000471 }
Mike Stump1d849212009-12-07 23:38:24 +0000472}
473
John McCall8e4c74b2011-08-11 02:22:43 +0000474/// Emit the dispatch block for a filter scope if necessary.
475static void emitFilterDispatchBlock(CodeGenFunction &CGF,
476 EHFilterScope &filterScope) {
477 llvm::BasicBlock *dispatchBlock = filterScope.getCachedEHDispatchBlock();
478 if (!dispatchBlock) return;
479 if (dispatchBlock->use_empty()) {
480 delete dispatchBlock;
481 return;
482 }
483
John McCall8e4c74b2011-08-11 02:22:43 +0000484 CGF.EmitBlockAfterUses(dispatchBlock);
485
486 // If this isn't a catch-all filter, we need to check whether we got
487 // here because the filter triggered.
488 if (filterScope.getNumFilters()) {
489 // Load the selector value.
Bill Wendling79a70e42011-09-15 18:57:19 +0000490 llvm::Value *selector = CGF.getSelectorFromSlot();
John McCall8e4c74b2011-08-11 02:22:43 +0000491 llvm::BasicBlock *unexpectedBB = CGF.createBasicBlock("ehspec.unexpected");
492
493 llvm::Value *zero = CGF.Builder.getInt32(0);
494 llvm::Value *failsFilter =
Nico Weber1bebad12015-02-11 22:33:32 +0000495 CGF.Builder.CreateICmpSLT(selector, zero, "ehspec.fails");
496 CGF.Builder.CreateCondBr(failsFilter, unexpectedBB,
497 CGF.getEHResumeBlock(false));
John McCall8e4c74b2011-08-11 02:22:43 +0000498
499 CGF.EmitBlock(unexpectedBB);
500 }
501
502 // Call __cxa_call_unexpected. This doesn't need to be an invoke
503 // because __cxa_call_unexpected magically filters exceptions
504 // according to the last landing pad the exception was thrown
505 // into. Seriously.
Bill Wendling79a70e42011-09-15 18:57:19 +0000506 llvm::Value *exn = CGF.getExceptionFromSlot();
John McCall882987f2013-02-28 19:01:20 +0000507 CGF.EmitRuntimeCall(getUnexpectedFn(CGF.CGM), exn)
John McCall8e4c74b2011-08-11 02:22:43 +0000508 ->setDoesNotReturn();
509 CGF.Builder.CreateUnreachable();
510}
511
Mike Stump1d849212009-12-07 23:38:24 +0000512void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000513 if (!CGM.getLangOpts().CXXExceptions)
Anders Carlsson9878f9f2010-02-06 23:59:05 +0000514 return;
515
Mike Stump1d849212009-12-07 23:38:24 +0000516 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
Craig Topper8a13c412014-05-21 05:09:00 +0000517 if (!FD) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000518 // Check if CapturedDecl is nothrow and pop terminate scope for it.
519 if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
520 if (CD->isNothrow())
521 EHStack.popTerminate();
522 }
Mike Stump1d849212009-12-07 23:38:24 +0000523 return;
Alexey Bataev9959db52014-05-06 10:08:46 +0000524 }
Mike Stump1d849212009-12-07 23:38:24 +0000525 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
Craig Topper8a13c412014-05-21 05:09:00 +0000526 if (!Proto)
Mike Stump1d849212009-12-07 23:38:24 +0000527 return;
528
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000529 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
530 if (isNoexceptExceptionSpec(EST)) {
531 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
532 EHStack.popTerminate();
533 }
534 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
David Majnemer1f192e22015-04-01 04:45:52 +0000535 // TODO: Revisit exception specifications for the MS ABI. There is a way to
536 // encode these in an object file but MSVC doesn't do anything with it.
537 if (getTarget().getCXXABI().isMicrosoft())
538 return;
John McCall8e4c74b2011-08-11 02:22:43 +0000539 EHFilterScope &filterScope = cast<EHFilterScope>(*EHStack.begin());
540 emitFilterDispatchBlock(*this, filterScope);
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000541 EHStack.popFilter();
542 }
Mike Stump1d849212009-12-07 23:38:24 +0000543}
544
Mike Stump58ef18b2009-11-20 23:44:51 +0000545void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
John McCallb609d3f2010-07-07 06:56:46 +0000546 EnterCXXTryStmt(S);
John McCallb81884d2010-02-19 09:25:03 +0000547 EmitStmt(S.getTryBlock());
John McCallb609d3f2010-07-07 06:56:46 +0000548 ExitCXXTryStmt(S);
John McCallb81884d2010-02-19 09:25:03 +0000549}
550
John McCallb609d3f2010-07-07 06:56:46 +0000551void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallbd309292010-07-06 01:34:17 +0000552 unsigned NumHandlers = S.getNumHandlers();
553 EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
John McCallb81884d2010-02-19 09:25:03 +0000554
John McCallbd309292010-07-06 01:34:17 +0000555 for (unsigned I = 0; I != NumHandlers; ++I) {
556 const CXXCatchStmt *C = S.getHandler(I);
John McCallb81884d2010-02-19 09:25:03 +0000557
John McCallbd309292010-07-06 01:34:17 +0000558 llvm::BasicBlock *Handler = createBasicBlock("catch");
559 if (C->getExceptionDecl()) {
560 // FIXME: Dropping the reference type on the type into makes it
561 // impossible to correctly implement catch-by-reference
562 // semantics for pointers. Unfortunately, this is what all
563 // existing compilers do, and it's not clear that the standard
564 // personality routine is capable of doing this right. See C++ DR 388:
565 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
David Majnemer571162a2014-10-12 06:58:22 +0000566 Qualifiers CaughtTypeQuals;
567 QualType CaughtType = CGM.getContext().getUnqualifiedArrayType(
568 C->getCaughtType().getNonReferenceType(), CaughtTypeQuals);
John McCall2ca705e2010-07-24 00:37:23 +0000569
Rafael Espindolabb9e7a32014-06-04 18:51:46 +0000570 llvm::Constant *TypeInfo = nullptr;
John McCall2ca705e2010-07-24 00:37:23 +0000571 if (CaughtType->isObjCObjectPointerType())
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +0000572 TypeInfo = CGM.getObjCRuntime().GetEHType(CaughtType);
John McCall2ca705e2010-07-24 00:37:23 +0000573 else
David Majnemer5f0dd612015-03-17 20:35:05 +0000574 TypeInfo =
David Majnemer37b417f2015-03-29 21:55:10 +0000575 CGM.getAddrOfCXXCatchHandlerType(CaughtType, C->getCaughtType());
John McCallbd309292010-07-06 01:34:17 +0000576 CatchScope->setHandler(I, TypeInfo, Handler);
577 } else {
578 // No exception decl indicates '...', a catch-all.
579 CatchScope->setCatchAllHandler(I, Handler);
580 }
581 }
John McCallbd309292010-07-06 01:34:17 +0000582}
583
John McCall8e4c74b2011-08-11 02:22:43 +0000584llvm::BasicBlock *
585CodeGenFunction::getEHDispatchBlock(EHScopeStack::stable_iterator si) {
586 // The dispatch block for the end of the scope chain is a block that
587 // just resumes unwinding.
588 if (si == EHStack.stable_end())
David Chisnall9a837be2012-11-07 16:50:40 +0000589 return getEHResumeBlock(true);
John McCall8e4c74b2011-08-11 02:22:43 +0000590
591 // Otherwise, we should look at the actual scope.
592 EHScope &scope = *EHStack.find(si);
593
594 llvm::BasicBlock *dispatchBlock = scope.getCachedEHDispatchBlock();
595 if (!dispatchBlock) {
596 switch (scope.getKind()) {
597 case EHScope::Catch: {
598 // Apply a special case to a single catch-all.
599 EHCatchScope &catchScope = cast<EHCatchScope>(scope);
600 if (catchScope.getNumHandlers() == 1 &&
601 catchScope.getHandler(0).isCatchAll()) {
602 dispatchBlock = catchScope.getHandler(0).Block;
603
604 // Otherwise, make a dispatch block.
605 } else {
606 dispatchBlock = createBasicBlock("catch.dispatch");
607 }
608 break;
609 }
610
611 case EHScope::Cleanup:
612 dispatchBlock = createBasicBlock("ehcleanup");
613 break;
614
615 case EHScope::Filter:
616 dispatchBlock = createBasicBlock("filter.dispatch");
617 break;
618
619 case EHScope::Terminate:
620 dispatchBlock = getTerminateHandler();
621 break;
622 }
623 scope.setCachedEHDispatchBlock(dispatchBlock);
624 }
625 return dispatchBlock;
626}
627
John McCallbd309292010-07-06 01:34:17 +0000628/// Check whether this is a non-EH scope, i.e. a scope which doesn't
629/// affect exception handling. Currently, the only non-EH scopes are
630/// normal-only cleanup scopes.
631static bool isNonEHScope(const EHScope &S) {
John McCall2b7fc382010-07-13 20:32:21 +0000632 switch (S.getKind()) {
John McCallcda666c2010-07-21 07:22:38 +0000633 case EHScope::Cleanup:
634 return !cast<EHCleanupScope>(S).isEHCleanup();
John McCall2b7fc382010-07-13 20:32:21 +0000635 case EHScope::Filter:
636 case EHScope::Catch:
637 case EHScope::Terminate:
638 return false;
639 }
640
David Blaikiee4d798f2012-01-20 21:50:17 +0000641 llvm_unreachable("Invalid EHScope Kind!");
John McCallbd309292010-07-06 01:34:17 +0000642}
643
644llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
645 assert(EHStack.requiresLandingPad());
646 assert(!EHStack.empty());
647
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000648 // If exceptions are disabled, there are usually no landingpads. However, when
649 // SEH is enabled, functions using SEH still get landingpads.
650 const LangOptions &LO = CGM.getLangOpts();
651 if (!LO.Exceptions) {
652 if (!LO.Borland && !LO.MicrosoftExt)
653 return nullptr;
Reid Klecknere7b3f7c2015-02-11 00:00:21 +0000654 if (!currentFunctionUsesSEHTry())
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000655 return nullptr;
656 }
John McCall2b7fc382010-07-13 20:32:21 +0000657
John McCallbd309292010-07-06 01:34:17 +0000658 // Check the innermost scope for a cached landing pad. If this is
659 // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
660 llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
661 if (LP) return LP;
662
663 // Build the landing pad for this scope.
664 LP = EmitLandingPad();
665 assert(LP);
666
667 // Cache the landing pad on the innermost scope. If this is a
668 // non-EH scope, cache the landing pad on the enclosing scope, too.
669 for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
670 ir->setCachedLandingPad(LP);
671 if (!isNonEHScope(*ir)) break;
672 }
673
674 return LP;
675}
676
677llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
678 assert(EHStack.requiresLandingPad());
679
John McCall8e4c74b2011-08-11 02:22:43 +0000680 EHScope &innermostEHScope = *EHStack.find(EHStack.getInnermostEHScope());
681 switch (innermostEHScope.getKind()) {
682 case EHScope::Terminate:
683 return getTerminateLandingPad();
John McCallbd309292010-07-06 01:34:17 +0000684
John McCall8e4c74b2011-08-11 02:22:43 +0000685 case EHScope::Catch:
686 case EHScope::Cleanup:
687 case EHScope::Filter:
688 if (llvm::BasicBlock *lpad = innermostEHScope.getCachedLandingPad())
689 return lpad;
John McCallbd309292010-07-06 01:34:17 +0000690 }
691
692 // Save the current IR generation state.
John McCall8e4c74b2011-08-11 02:22:43 +0000693 CGBuilderTy::InsertPoint savedIP = Builder.saveAndClearIP();
Adrian Prantl95b24e92015-02-03 20:00:54 +0000694 auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, CurEHLocation);
John McCallbd309292010-07-06 01:34:17 +0000695
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000696 const EHPersonality &personality = EHPersonality::get(*this);
John McCall36ea3722010-07-17 00:43:08 +0000697
John McCallbd309292010-07-06 01:34:17 +0000698 // Create and configure the landing pad.
John McCall8e4c74b2011-08-11 02:22:43 +0000699 llvm::BasicBlock *lpad = createBasicBlock("lpad");
700 EmitBlock(lpad);
John McCallbd309292010-07-06 01:34:17 +0000701
Bill Wendlingf0724e82011-09-19 20:31:14 +0000702 llvm::LandingPadInst *LPadInst =
Reid Kleckneree7cf842014-12-01 22:02:27 +0000703 Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, nullptr),
Bill Wendlingf0724e82011-09-19 20:31:14 +0000704 getOpaquePersonalityFn(CGM, personality), 0);
705
706 llvm::Value *LPadExn = Builder.CreateExtractValue(LPadInst, 0);
707 Builder.CreateStore(LPadExn, getExceptionSlot());
708 llvm::Value *LPadSel = Builder.CreateExtractValue(LPadInst, 1);
709 Builder.CreateStore(LPadSel, getEHSelectorSlot());
710
John McCallbd309292010-07-06 01:34:17 +0000711 // Save the exception pointer. It's safe to use a single exception
712 // pointer per function because EH cleanups can never have nested
713 // try/catches.
Bill Wendlingf0724e82011-09-19 20:31:14 +0000714 // Build the landingpad instruction.
John McCallbd309292010-07-06 01:34:17 +0000715
716 // Accumulate all the handlers in scope.
John McCall8e4c74b2011-08-11 02:22:43 +0000717 bool hasCatchAll = false;
718 bool hasCleanup = false;
719 bool hasFilter = false;
720 SmallVector<llvm::Value*, 4> filterTypes;
721 llvm::SmallPtrSet<llvm::Value*, 4> catchTypes;
Nico Webere68b9f32015-02-25 16:25:00 +0000722 for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end(); I != E;
723 ++I) {
John McCallbd309292010-07-06 01:34:17 +0000724
725 switch (I->getKind()) {
John McCallcda666c2010-07-21 07:22:38 +0000726 case EHScope::Cleanup:
John McCall8e4c74b2011-08-11 02:22:43 +0000727 // If we have a cleanup, remember that.
728 hasCleanup = (hasCleanup || cast<EHCleanupScope>(*I).isEHCleanup());
John McCall2b7fc382010-07-13 20:32:21 +0000729 continue;
730
John McCallbd309292010-07-06 01:34:17 +0000731 case EHScope::Filter: {
732 assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
John McCall8e4c74b2011-08-11 02:22:43 +0000733 assert(!hasCatchAll && "EH filter reached after catch-all");
John McCallbd309292010-07-06 01:34:17 +0000734
Bill Wendlingf0724e82011-09-19 20:31:14 +0000735 // Filter scopes get added to the landingpad in weird ways.
John McCall8e4c74b2011-08-11 02:22:43 +0000736 EHFilterScope &filter = cast<EHFilterScope>(*I);
737 hasFilter = true;
John McCallbd309292010-07-06 01:34:17 +0000738
Bill Wendling8c4b7162011-09-22 20:32:54 +0000739 // Add all the filter values.
740 for (unsigned i = 0, e = filter.getNumFilters(); i != e; ++i)
741 filterTypes.push_back(filter.getFilter(i));
John McCallbd309292010-07-06 01:34:17 +0000742 goto done;
743 }
744
745 case EHScope::Terminate:
746 // Terminate scopes are basically catch-alls.
John McCall8e4c74b2011-08-11 02:22:43 +0000747 assert(!hasCatchAll);
748 hasCatchAll = true;
John McCallbd309292010-07-06 01:34:17 +0000749 goto done;
750
751 case EHScope::Catch:
752 break;
753 }
754
John McCall8e4c74b2011-08-11 02:22:43 +0000755 EHCatchScope &catchScope = cast<EHCatchScope>(*I);
756 for (unsigned hi = 0, he = catchScope.getNumHandlers(); hi != he; ++hi) {
757 EHCatchScope::Handler handler = catchScope.getHandler(hi);
John McCallbd309292010-07-06 01:34:17 +0000758
John McCall8e4c74b2011-08-11 02:22:43 +0000759 // If this is a catch-all, register that and abort.
760 if (!handler.Type) {
761 assert(!hasCatchAll);
762 hasCatchAll = true;
763 goto done;
John McCallbd309292010-07-06 01:34:17 +0000764 }
765
766 // Check whether we already have a handler for this type.
David Blaikie82e95a32014-11-19 07:49:47 +0000767 if (catchTypes.insert(handler.Type).second)
Bill Wendlingf0724e82011-09-19 20:31:14 +0000768 // If not, add it directly to the landingpad.
769 LPadInst->addClause(handler.Type);
John McCallbd309292010-07-06 01:34:17 +0000770 }
John McCallbd309292010-07-06 01:34:17 +0000771 }
772
773 done:
Bill Wendlingf0724e82011-09-19 20:31:14 +0000774 // If we have a catch-all, add null to the landingpad.
John McCall8e4c74b2011-08-11 02:22:43 +0000775 assert(!(hasCatchAll && hasFilter));
776 if (hasCatchAll) {
Bill Wendlingf0724e82011-09-19 20:31:14 +0000777 LPadInst->addClause(getCatchAllValue(*this));
John McCallbd309292010-07-06 01:34:17 +0000778
779 // If we have an EH filter, we need to add those handlers in the
Bill Wendlingf0724e82011-09-19 20:31:14 +0000780 // right place in the landingpad, which is to say, at the end.
John McCall8e4c74b2011-08-11 02:22:43 +0000781 } else if (hasFilter) {
Bill Wendling58e58fe2011-09-19 22:08:36 +0000782 // Create a filter expression: a constant array indicating which filter
783 // types there are. The personality routine only lands here if the filter
784 // doesn't match.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000785 SmallVector<llvm::Constant*, 8> Filters;
Bill Wendlingf0724e82011-09-19 20:31:14 +0000786 llvm::ArrayType *AType =
787 llvm::ArrayType::get(!filterTypes.empty() ?
788 filterTypes[0]->getType() : Int8PtrTy,
789 filterTypes.size());
790
791 for (unsigned i = 0, e = filterTypes.size(); i != e; ++i)
792 Filters.push_back(cast<llvm::Constant>(filterTypes[i]));
793 llvm::Constant *FilterArray = llvm::ConstantArray::get(AType, Filters);
794 LPadInst->addClause(FilterArray);
John McCallbd309292010-07-06 01:34:17 +0000795
796 // Also check whether we need a cleanup.
Bill Wendlingf0724e82011-09-19 20:31:14 +0000797 if (hasCleanup)
798 LPadInst->setCleanup(true);
John McCallbd309292010-07-06 01:34:17 +0000799
800 // Otherwise, signal that we at least have cleanups.
Logan Chiene9c8ccb2014-07-01 11:47:10 +0000801 } else if (hasCleanup) {
802 LPadInst->setCleanup(true);
John McCallbd309292010-07-06 01:34:17 +0000803 }
804
Bill Wendlingf0724e82011-09-19 20:31:14 +0000805 assert((LPadInst->getNumClauses() > 0 || LPadInst->isCleanup()) &&
806 "landingpad instruction has no clauses!");
John McCallbd309292010-07-06 01:34:17 +0000807
808 // Tell the backend how to generate the landing pad.
John McCall8e4c74b2011-08-11 02:22:43 +0000809 Builder.CreateBr(getEHDispatchBlock(EHStack.getInnermostEHScope()));
John McCallbd309292010-07-06 01:34:17 +0000810
811 // Restore the old IR generation state.
John McCall8e4c74b2011-08-11 02:22:43 +0000812 Builder.restoreIP(savedIP);
John McCallbd309292010-07-06 01:34:17 +0000813
John McCall8e4c74b2011-08-11 02:22:43 +0000814 return lpad;
John McCallbd309292010-07-06 01:34:17 +0000815}
816
John McCall8e4c74b2011-08-11 02:22:43 +0000817/// Emit the structure of the dispatch block for the given catch scope.
818/// It is an invariant that the dispatch block already exists.
819static void emitCatchDispatchBlock(CodeGenFunction &CGF,
820 EHCatchScope &catchScope) {
821 llvm::BasicBlock *dispatchBlock = catchScope.getCachedEHDispatchBlock();
822 assert(dispatchBlock);
823
824 // If there's only a single catch-all, getEHDispatchBlock returned
825 // that catch-all as the dispatch block.
826 if (catchScope.getNumHandlers() == 1 &&
827 catchScope.getHandler(0).isCatchAll()) {
828 assert(dispatchBlock == catchScope.getHandler(0).Block);
829 return;
830 }
831
832 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveIP();
833 CGF.EmitBlockAfterUses(dispatchBlock);
834
835 // Select the right handler.
836 llvm::Value *llvm_eh_typeid_for =
837 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
838
839 // Load the selector value.
Bill Wendling79a70e42011-09-15 18:57:19 +0000840 llvm::Value *selector = CGF.getSelectorFromSlot();
John McCall8e4c74b2011-08-11 02:22:43 +0000841
842 // Test against each of the exception types we claim to catch.
843 for (unsigned i = 0, e = catchScope.getNumHandlers(); ; ++i) {
844 assert(i < e && "ran off end of handlers!");
845 const EHCatchScope::Handler &handler = catchScope.getHandler(i);
846
847 llvm::Value *typeValue = handler.Type;
848 assert(typeValue && "fell into catch-all case!");
849 typeValue = CGF.Builder.CreateBitCast(typeValue, CGF.Int8PtrTy);
850
851 // Figure out the next block.
852 bool nextIsEnd;
853 llvm::BasicBlock *nextBlock;
854
855 // If this is the last handler, we're at the end, and the next
856 // block is the block for the enclosing EH scope.
857 if (i + 1 == e) {
858 nextBlock = CGF.getEHDispatchBlock(catchScope.getEnclosingEHScope());
859 nextIsEnd = true;
860
861 // If the next handler is a catch-all, we're at the end, and the
862 // next block is that handler.
863 } else if (catchScope.getHandler(i+1).isCatchAll()) {
864 nextBlock = catchScope.getHandler(i+1).Block;
865 nextIsEnd = true;
866
867 // Otherwise, we're not at the end and we need a new block.
868 } else {
869 nextBlock = CGF.createBasicBlock("catch.fallthrough");
870 nextIsEnd = false;
871 }
872
873 // Figure out the catch type's index in the LSDA's type table.
874 llvm::CallInst *typeIndex =
875 CGF.Builder.CreateCall(llvm_eh_typeid_for, typeValue);
876 typeIndex->setDoesNotThrow();
877
878 llvm::Value *matchesTypeIndex =
879 CGF.Builder.CreateICmpEQ(selector, typeIndex, "matches");
880 CGF.Builder.CreateCondBr(matchesTypeIndex, handler.Block, nextBlock);
881
882 // If the next handler is a catch-all, we're completely done.
883 if (nextIsEnd) {
884 CGF.Builder.restoreIP(savedIP);
885 return;
John McCall8e4c74b2011-08-11 02:22:43 +0000886 }
Ahmed Charles289896d2012-02-19 11:57:29 +0000887 // Otherwise we need to emit and continue at that block.
888 CGF.EmitBlock(nextBlock);
John McCall8e4c74b2011-08-11 02:22:43 +0000889 }
John McCall8e4c74b2011-08-11 02:22:43 +0000890}
891
892void CodeGenFunction::popCatchScope() {
893 EHCatchScope &catchScope = cast<EHCatchScope>(*EHStack.begin());
894 if (catchScope.hasEHBranches())
895 emitCatchDispatchBlock(*this, catchScope);
896 EHStack.popCatch();
897}
898
John McCallb609d3f2010-07-07 06:56:46 +0000899void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallbd309292010-07-06 01:34:17 +0000900 unsigned NumHandlers = S.getNumHandlers();
901 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
902 assert(CatchScope.getNumHandlers() == NumHandlers);
Mike Stump58ef18b2009-11-20 23:44:51 +0000903
John McCall8e4c74b2011-08-11 02:22:43 +0000904 // If the catch was not required, bail out now.
905 if (!CatchScope.hasEHBranches()) {
Kostya Serebryanyba4aced2014-01-09 09:22:32 +0000906 CatchScope.clearHandlerBlocks();
John McCall8e4c74b2011-08-11 02:22:43 +0000907 EHStack.popCatch();
908 return;
909 }
910
911 // Emit the structure of the EH dispatch for this catch.
912 emitCatchDispatchBlock(*this, CatchScope);
913
John McCallbd309292010-07-06 01:34:17 +0000914 // Copy the handler blocks off before we pop the EH stack. Emitting
915 // the handlers might scribble on this memory.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000916 SmallVector<EHCatchScope::Handler, 8> Handlers(NumHandlers);
John McCallbd309292010-07-06 01:34:17 +0000917 memcpy(Handlers.data(), CatchScope.begin(),
918 NumHandlers * sizeof(EHCatchScope::Handler));
John McCall8e4c74b2011-08-11 02:22:43 +0000919
John McCallbd309292010-07-06 01:34:17 +0000920 EHStack.popCatch();
Mike Stump58ef18b2009-11-20 23:44:51 +0000921
John McCallbd309292010-07-06 01:34:17 +0000922 // The fall-through block.
923 llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
Mike Stump58ef18b2009-11-20 23:44:51 +0000924
John McCallbd309292010-07-06 01:34:17 +0000925 // We just emitted the body of the try; jump to the continue block.
926 if (HaveInsertPoint())
927 Builder.CreateBr(ContBB);
Mike Stump97329152009-12-02 19:53:57 +0000928
John McCalld8d00be2012-06-15 05:27:05 +0000929 // Determine if we need an implicit rethrow for all these catch handlers;
930 // see the comment below.
931 bool doImplicitRethrow = false;
John McCallb609d3f2010-07-07 06:56:46 +0000932 if (IsFnTryBlock)
John McCalld8d00be2012-06-15 05:27:05 +0000933 doImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
934 isa<CXXConstructorDecl>(CurCodeDecl);
John McCallb609d3f2010-07-07 06:56:46 +0000935
John McCall8e4c74b2011-08-11 02:22:43 +0000936 // Perversely, we emit the handlers backwards precisely because we
937 // want them to appear in source order. In all of these cases, the
938 // catch block will have exactly one predecessor, which will be a
939 // particular block in the catch dispatch. However, in the case of
940 // a catch-all, one of the dispatch blocks will branch to two
941 // different handlers, and EmitBlockAfterUses will cause the second
942 // handler to be moved before the first.
943 for (unsigned I = NumHandlers; I != 0; --I) {
944 llvm::BasicBlock *CatchBlock = Handlers[I-1].Block;
945 EmitBlockAfterUses(CatchBlock);
Mike Stump75546b82009-12-10 00:06:18 +0000946
John McCallbd309292010-07-06 01:34:17 +0000947 // Catch the exception if this isn't a catch-all.
John McCall8e4c74b2011-08-11 02:22:43 +0000948 const CXXCatchStmt *C = S.getHandler(I-1);
Mike Stump58ef18b2009-11-20 23:44:51 +0000949
John McCallbd309292010-07-06 01:34:17 +0000950 // Enter a cleanup scope, including the catch variable and the
951 // end-catch.
952 RunCleanupsScope CatchScope(*this);
Mike Stump58ef18b2009-11-20 23:44:51 +0000953
John McCallbd309292010-07-06 01:34:17 +0000954 // Initialize the catch variable and set up the cleanups.
Reid Klecknerfff8e7f2015-03-03 19:21:04 +0000955 CGM.getCXXABI().emitBeginCatch(*this, C);
John McCallbd309292010-07-06 01:34:17 +0000956
Justin Bognerea278c32014-01-07 00:20:28 +0000957 // Emit the PGO counter increment.
Justin Bogner66242d62015-04-23 23:06:47 +0000958 incrementProfileCounter(C);
Justin Bogneref512b92014-01-06 22:27:43 +0000959
John McCallbd309292010-07-06 01:34:17 +0000960 // Perform the body of the catch.
961 EmitStmt(C->getHandlerBlock());
962
John McCalld8d00be2012-06-15 05:27:05 +0000963 // [except.handle]p11:
964 // The currently handled exception is rethrown if control
965 // reaches the end of a handler of the function-try-block of a
966 // constructor or destructor.
967
968 // It is important that we only do this on fallthrough and not on
969 // return. Note that it's illegal to put a return in a
970 // constructor function-try-block's catch handler (p14), so this
971 // really only applies to destructors.
972 if (doImplicitRethrow && HaveInsertPoint()) {
David Majnemer442d0a22014-11-25 07:20:20 +0000973 CGM.getCXXABI().emitRethrow(*this, /*isNoReturn*/false);
John McCalld8d00be2012-06-15 05:27:05 +0000974 Builder.CreateUnreachable();
975 Builder.ClearInsertionPoint();
976 }
977
John McCallbd309292010-07-06 01:34:17 +0000978 // Fall out through the catch cleanups.
979 CatchScope.ForceCleanup();
980
981 // Branch out of the try.
982 if (HaveInsertPoint())
983 Builder.CreateBr(ContBB);
Mike Stump58ef18b2009-11-20 23:44:51 +0000984 }
985
John McCallbd309292010-07-06 01:34:17 +0000986 EmitBlock(ContBB);
Justin Bogner66242d62015-04-23 23:06:47 +0000987 incrementProfileCounter(&S);
Mike Stump58ef18b2009-11-20 23:44:51 +0000988}
Mike Stumpaff69af2009-12-09 03:35:49 +0000989
John McCall1e670402010-07-21 00:52:03 +0000990namespace {
John McCallcda666c2010-07-21 07:22:38 +0000991 struct CallEndCatchForFinally : EHScopeStack::Cleanup {
John McCall1e670402010-07-21 00:52:03 +0000992 llvm::Value *ForEHVar;
993 llvm::Value *EndCatchFn;
994 CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn)
995 : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
996
Craig Topper4f12f102014-03-12 06:41:41 +0000997 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall1e670402010-07-21 00:52:03 +0000998 llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
999 llvm::BasicBlock *CleanupContBB =
1000 CGF.createBasicBlock("finally.cleanup.cont");
1001
1002 llvm::Value *ShouldEndCatch =
1003 CGF.Builder.CreateLoad(ForEHVar, "finally.endcatch");
1004 CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1005 CGF.EmitBlock(EndCatchBB);
John McCall882987f2013-02-28 19:01:20 +00001006 CGF.EmitRuntimeCallOrInvoke(EndCatchFn); // catch-all, so might throw
John McCall1e670402010-07-21 00:52:03 +00001007 CGF.EmitBlock(CleanupContBB);
1008 }
1009 };
John McCall906da4b2010-07-21 05:47:49 +00001010
John McCallcda666c2010-07-21 07:22:38 +00001011 struct PerformFinally : EHScopeStack::Cleanup {
John McCall906da4b2010-07-21 05:47:49 +00001012 const Stmt *Body;
1013 llvm::Value *ForEHVar;
1014 llvm::Value *EndCatchFn;
1015 llvm::Value *RethrowFn;
1016 llvm::Value *SavedExnVar;
1017
1018 PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
1019 llvm::Value *EndCatchFn,
1020 llvm::Value *RethrowFn, llvm::Value *SavedExnVar)
1021 : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1022 RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
1023
Craig Topper4f12f102014-03-12 06:41:41 +00001024 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall906da4b2010-07-21 05:47:49 +00001025 // Enter a cleanup to call the end-catch function if one was provided.
1026 if (EndCatchFn)
John McCallcda666c2010-07-21 07:22:38 +00001027 CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
1028 ForEHVar, EndCatchFn);
John McCall906da4b2010-07-21 05:47:49 +00001029
John McCallcebe0ca2010-08-11 00:16:14 +00001030 // Save the current cleanup destination in case there are
1031 // cleanups in the finally block.
1032 llvm::Value *SavedCleanupDest =
1033 CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
1034 "cleanup.dest.saved");
1035
John McCall906da4b2010-07-21 05:47:49 +00001036 // Emit the finally block.
1037 CGF.EmitStmt(Body);
1038
1039 // If the end of the finally is reachable, check whether this was
1040 // for EH. If so, rethrow.
1041 if (CGF.HaveInsertPoint()) {
1042 llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
1043 llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
1044
1045 llvm::Value *ShouldRethrow =
1046 CGF.Builder.CreateLoad(ForEHVar, "finally.shouldthrow");
1047 CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1048
1049 CGF.EmitBlock(RethrowBB);
1050 if (SavedExnVar) {
John McCall882987f2013-02-28 19:01:20 +00001051 CGF.EmitRuntimeCallOrInvoke(RethrowFn,
1052 CGF.Builder.CreateLoad(SavedExnVar));
John McCall906da4b2010-07-21 05:47:49 +00001053 } else {
John McCall882987f2013-02-28 19:01:20 +00001054 CGF.EmitRuntimeCallOrInvoke(RethrowFn);
John McCall906da4b2010-07-21 05:47:49 +00001055 }
1056 CGF.Builder.CreateUnreachable();
1057
1058 CGF.EmitBlock(ContBB);
John McCallcebe0ca2010-08-11 00:16:14 +00001059
1060 // Restore the cleanup destination.
1061 CGF.Builder.CreateStore(SavedCleanupDest,
1062 CGF.getNormalCleanupDestSlot());
John McCall906da4b2010-07-21 05:47:49 +00001063 }
1064
1065 // Leave the end-catch cleanup. As an optimization, pretend that
1066 // the fallthrough path was inaccessible; we've dynamically proven
1067 // that we're not in the EH case along that path.
1068 if (EndCatchFn) {
1069 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1070 CGF.PopCleanupBlock();
1071 CGF.Builder.restoreIP(SavedIP);
1072 }
1073
1074 // Now make sure we actually have an insertion point or the
1075 // cleanup gods will hate us.
1076 CGF.EnsureInsertPoint();
1077 }
1078 };
John McCall1e670402010-07-21 00:52:03 +00001079}
1080
John McCallbd309292010-07-06 01:34:17 +00001081/// Enters a finally block for an implementation using zero-cost
1082/// exceptions. This is mostly general, but hard-codes some
1083/// language/ABI-specific behavior in the catch-all sections.
John McCall6b0feb72011-06-22 02:32:12 +00001084void CodeGenFunction::FinallyInfo::enter(CodeGenFunction &CGF,
1085 const Stmt *body,
1086 llvm::Constant *beginCatchFn,
1087 llvm::Constant *endCatchFn,
1088 llvm::Constant *rethrowFn) {
Craig Topper8a13c412014-05-21 05:09:00 +00001089 assert((beginCatchFn != nullptr) == (endCatchFn != nullptr) &&
John McCallbd309292010-07-06 01:34:17 +00001090 "begin/end catch functions not paired");
John McCall6b0feb72011-06-22 02:32:12 +00001091 assert(rethrowFn && "rethrow function is required");
1092
1093 BeginCatchFn = beginCatchFn;
Mike Stumpaff69af2009-12-09 03:35:49 +00001094
John McCallbd309292010-07-06 01:34:17 +00001095 // The rethrow function has one of the following two types:
1096 // void (*)()
1097 // void (*)(void*)
1098 // In the latter case we need to pass it the exception object.
1099 // But we can't use the exception slot because the @finally might
1100 // have a landing pad (which would overwrite the exception slot).
Chris Lattner2192fe52011-07-18 04:24:23 +00001101 llvm::FunctionType *rethrowFnTy =
John McCallbd309292010-07-06 01:34:17 +00001102 cast<llvm::FunctionType>(
John McCall6b0feb72011-06-22 02:32:12 +00001103 cast<llvm::PointerType>(rethrowFn->getType())->getElementType());
Craig Topper8a13c412014-05-21 05:09:00 +00001104 SavedExnVar = nullptr;
John McCall6b0feb72011-06-22 02:32:12 +00001105 if (rethrowFnTy->getNumParams())
1106 SavedExnVar = CGF.CreateTempAlloca(CGF.Int8PtrTy, "finally.exn");
Mike Stumpaff69af2009-12-09 03:35:49 +00001107
John McCallbd309292010-07-06 01:34:17 +00001108 // A finally block is a statement which must be executed on any edge
1109 // out of a given scope. Unlike a cleanup, the finally block may
1110 // contain arbitrary control flow leading out of itself. In
1111 // addition, finally blocks should always be executed, even if there
1112 // are no catch handlers higher on the stack. Therefore, we
1113 // surround the protected scope with a combination of a normal
1114 // cleanup (to catch attempts to break out of the block via normal
1115 // control flow) and an EH catch-all (semantically "outside" any try
1116 // statement to which the finally block might have been attached).
1117 // The finally block itself is generated in the context of a cleanup
1118 // which conditionally leaves the catch-all.
John McCall21886962010-04-21 10:05:39 +00001119
John McCallbd309292010-07-06 01:34:17 +00001120 // Jump destination for performing the finally block on an exception
1121 // edge. We'll never actually reach this block, so unreachable is
1122 // fine.
John McCall6b0feb72011-06-22 02:32:12 +00001123 RethrowDest = CGF.getJumpDestInCurrentScope(CGF.getUnreachableBlock());
John McCall21886962010-04-21 10:05:39 +00001124
John McCallbd309292010-07-06 01:34:17 +00001125 // Whether the finally block is being executed for EH purposes.
John McCall6b0feb72011-06-22 02:32:12 +00001126 ForEHVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "finally.for-eh");
1127 CGF.Builder.CreateStore(CGF.Builder.getFalse(), ForEHVar);
Mike Stumpaff69af2009-12-09 03:35:49 +00001128
John McCallbd309292010-07-06 01:34:17 +00001129 // Enter a normal cleanup which will perform the @finally block.
John McCall6b0feb72011-06-22 02:32:12 +00001130 CGF.EHStack.pushCleanup<PerformFinally>(NormalCleanup, body,
1131 ForEHVar, endCatchFn,
1132 rethrowFn, SavedExnVar);
John McCallbd309292010-07-06 01:34:17 +00001133
1134 // Enter a catch-all scope.
John McCall6b0feb72011-06-22 02:32:12 +00001135 llvm::BasicBlock *catchBB = CGF.createBasicBlock("finally.catchall");
1136 EHCatchScope *catchScope = CGF.EHStack.pushCatch(1);
1137 catchScope->setCatchAllHandler(0, catchBB);
John McCallbd309292010-07-06 01:34:17 +00001138}
1139
John McCall6b0feb72011-06-22 02:32:12 +00001140void CodeGenFunction::FinallyInfo::exit(CodeGenFunction &CGF) {
John McCallbd309292010-07-06 01:34:17 +00001141 // Leave the finally catch-all.
John McCall6b0feb72011-06-22 02:32:12 +00001142 EHCatchScope &catchScope = cast<EHCatchScope>(*CGF.EHStack.begin());
1143 llvm::BasicBlock *catchBB = catchScope.getHandler(0).Block;
John McCall8e4c74b2011-08-11 02:22:43 +00001144
1145 CGF.popCatchScope();
John McCallbd309292010-07-06 01:34:17 +00001146
John McCall6b0feb72011-06-22 02:32:12 +00001147 // If there are any references to the catch-all block, emit it.
1148 if (catchBB->use_empty()) {
1149 delete catchBB;
1150 } else {
1151 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveAndClearIP();
1152 CGF.EmitBlock(catchBB);
John McCallbd309292010-07-06 01:34:17 +00001153
Craig Topper8a13c412014-05-21 05:09:00 +00001154 llvm::Value *exn = nullptr;
John McCallbd309292010-07-06 01:34:17 +00001155
John McCall6b0feb72011-06-22 02:32:12 +00001156 // If there's a begin-catch function, call it.
1157 if (BeginCatchFn) {
Bill Wendling79a70e42011-09-15 18:57:19 +00001158 exn = CGF.getExceptionFromSlot();
John McCall882987f2013-02-28 19:01:20 +00001159 CGF.EmitNounwindRuntimeCall(BeginCatchFn, exn);
John McCall6b0feb72011-06-22 02:32:12 +00001160 }
1161
1162 // If we need to remember the exception pointer to rethrow later, do so.
1163 if (SavedExnVar) {
Bill Wendling79a70e42011-09-15 18:57:19 +00001164 if (!exn) exn = CGF.getExceptionFromSlot();
John McCall6b0feb72011-06-22 02:32:12 +00001165 CGF.Builder.CreateStore(exn, SavedExnVar);
1166 }
1167
1168 // Tell the cleanups in the finally block that we're do this for EH.
1169 CGF.Builder.CreateStore(CGF.Builder.getTrue(), ForEHVar);
1170
1171 // Thread a jump through the finally cleanup.
1172 CGF.EmitBranchThroughCleanup(RethrowDest);
1173
1174 CGF.Builder.restoreIP(savedIP);
1175 }
1176
1177 // Finally, leave the @finally cleanup.
1178 CGF.PopCleanupBlock();
John McCallbd309292010-07-06 01:34:17 +00001179}
1180
1181llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
1182 if (TerminateLandingPad)
1183 return TerminateLandingPad;
1184
1185 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1186
1187 // This will get inserted at the end of the function.
1188 TerminateLandingPad = createBasicBlock("terminate.lpad");
1189 Builder.SetInsertPoint(TerminateLandingPad);
1190
1191 // Tell the backend that this is a landing pad.
Reid Klecknerdeeddec2015-02-05 18:56:03 +00001192 const EHPersonality &Personality = EHPersonality::get(*this);
Bill Wendlingf0724e82011-09-19 20:31:14 +00001193 llvm::LandingPadInst *LPadInst =
Reid Kleckneree7cf842014-12-01 22:02:27 +00001194 Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, nullptr),
Bill Wendlingf0724e82011-09-19 20:31:14 +00001195 getOpaquePersonalityFn(CGM, Personality), 0);
1196 LPadInst->addClause(getCatchAllValue(*this));
John McCallbd309292010-07-06 01:34:17 +00001197
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00001198 llvm::Value *Exn = 0;
1199 if (getLangOpts().CPlusPlus)
1200 Exn = Builder.CreateExtractValue(LPadInst, 0);
1201 llvm::CallInst *terminateCall =
1202 CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
John McCalle142ad52013-02-12 03:51:46 +00001203 terminateCall->setDoesNotReturn();
John McCallad7c5c12011-02-08 08:22:06 +00001204 Builder.CreateUnreachable();
Mike Stumpaff69af2009-12-09 03:35:49 +00001205
John McCallbd309292010-07-06 01:34:17 +00001206 // Restore the saved insertion state.
1207 Builder.restoreIP(SavedIP);
John McCalldac3ea62010-04-30 00:06:43 +00001208
John McCallbd309292010-07-06 01:34:17 +00001209 return TerminateLandingPad;
Mike Stumpaff69af2009-12-09 03:35:49 +00001210}
Mike Stump2b488872009-12-09 22:59:31 +00001211
1212llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
Mike Stumpf5cbb082009-12-10 00:02:42 +00001213 if (TerminateHandler)
1214 return TerminateHandler;
1215
John McCallbd309292010-07-06 01:34:17 +00001216 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
Mike Stump25b20fc2009-12-09 23:31:35 +00001217
John McCallbd309292010-07-06 01:34:17 +00001218 // Set up the terminate handler. This block is inserted at the very
1219 // end of the function by FinishFunction.
Mike Stumpf5cbb082009-12-10 00:02:42 +00001220 TerminateHandler = createBasicBlock("terminate.handler");
John McCallbd309292010-07-06 01:34:17 +00001221 Builder.SetInsertPoint(TerminateHandler);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00001222 llvm::Value *Exn = 0;
1223 if (getLangOpts().CPlusPlus)
1224 Exn = getExceptionFromSlot();
1225 llvm::CallInst *terminateCall =
1226 CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
John McCallc84e4e92013-06-20 21:37:43 +00001227 terminateCall->setDoesNotReturn();
Mike Stump2b488872009-12-09 22:59:31 +00001228 Builder.CreateUnreachable();
1229
John McCall21886962010-04-21 10:05:39 +00001230 // Restore the saved insertion state.
John McCallbd309292010-07-06 01:34:17 +00001231 Builder.restoreIP(SavedIP);
Mike Stump25b20fc2009-12-09 23:31:35 +00001232
Mike Stump2b488872009-12-09 22:59:31 +00001233 return TerminateHandler;
1234}
John McCallbd309292010-07-06 01:34:17 +00001235
David Chisnall9a837be2012-11-07 16:50:40 +00001236llvm::BasicBlock *CodeGenFunction::getEHResumeBlock(bool isCleanup) {
John McCall8e4c74b2011-08-11 02:22:43 +00001237 if (EHResumeBlock) return EHResumeBlock;
John McCallad5d61e2010-07-23 21:56:41 +00001238
1239 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1240
1241 // We emit a jump to a notional label at the outermost unwind state.
John McCall8e4c74b2011-08-11 02:22:43 +00001242 EHResumeBlock = createBasicBlock("eh.resume");
1243 Builder.SetInsertPoint(EHResumeBlock);
John McCallad5d61e2010-07-23 21:56:41 +00001244
Reid Klecknerdeeddec2015-02-05 18:56:03 +00001245 const EHPersonality &Personality = EHPersonality::get(*this);
John McCallad5d61e2010-07-23 21:56:41 +00001246
1247 // This can always be a call because we necessarily didn't find
1248 // anything on the EH stack which needs our help.
Benjamin Kramer793bd552012-02-08 12:41:24 +00001249 const char *RethrowName = Personality.CatchallRethrowFn;
Craig Topper8a13c412014-05-21 05:09:00 +00001250 if (RethrowName != nullptr && !isCleanup) {
John McCall882987f2013-02-28 19:01:20 +00001251 EmitRuntimeCall(getCatchallRethrowFn(CGM, RethrowName),
Nico Weberff62a6a2015-02-26 22:34:33 +00001252 getExceptionFromSlot())->setDoesNotReturn();
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001253 Builder.CreateUnreachable();
1254 Builder.restoreIP(SavedIP);
1255 return EHResumeBlock;
John McCall9b382dd2011-05-28 21:13:02 +00001256 }
1257
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001258 // Recreate the landingpad's return value for the 'resume' instruction.
1259 llvm::Value *Exn = getExceptionFromSlot();
1260 llvm::Value *Sel = getSelectorFromSlot();
John McCallad5d61e2010-07-23 21:56:41 +00001261
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001262 llvm::Type *LPadType = llvm::StructType::get(Exn->getType(),
Reid Kleckneree7cf842014-12-01 22:02:27 +00001263 Sel->getType(), nullptr);
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001264 llvm::Value *LPadVal = llvm::UndefValue::get(LPadType);
1265 LPadVal = Builder.CreateInsertValue(LPadVal, Exn, 0, "lpad.val");
1266 LPadVal = Builder.CreateInsertValue(LPadVal, Sel, 1, "lpad.val");
1267
1268 Builder.CreateResume(LPadVal);
John McCallad5d61e2010-07-23 21:56:41 +00001269 Builder.restoreIP(SavedIP);
John McCall8e4c74b2011-08-11 02:22:43 +00001270 return EHResumeBlock;
John McCallad5d61e2010-07-23 21:56:41 +00001271}
Reid Kleckner543a16c2013-09-16 21:46:30 +00001272
1273void CodeGenFunction::EmitSEHTryStmt(const SEHTryStmt &S) {
Reid Klecknerbe9843c2015-04-29 21:55:21 +00001274 // FIXME: Implement SEH on other architectures.
1275 const llvm::Triple &T = CGM.getTarget().getTriple();
1276 if (T.getArch() != llvm::Triple::x86_64 ||
1277 !T.isKnownWindowsMSVCEnvironment()) {
1278 ErrorUnsupported(&S, "__try statement");
1279 return;
1280 }
1281
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001282 EnterSEHTryStmt(S);
Reid Klecknera5930002015-02-11 21:40:48 +00001283 {
Nico Weber5779f842015-02-12 23:16:11 +00001284 JumpDest TryExit = getJumpDestInCurrentScope("__try.__leave");
Nico Weber5779f842015-02-12 23:16:11 +00001285
Reid Kleckner11c033e2015-02-12 23:40:45 +00001286 SEHTryEpilogueStack.push_back(&TryExit);
Reid Klecknera5930002015-02-11 21:40:48 +00001287 EmitStmt(S.getTryBlock());
Reid Kleckner11c033e2015-02-12 23:40:45 +00001288 SEHTryEpilogueStack.pop_back();
Nico Weber5779f842015-02-12 23:16:11 +00001289
1290 if (!TryExit.getBlock()->use_empty())
1291 EmitBlock(TryExit.getBlock(), /*IsFinished=*/true);
1292 else
1293 delete TryExit.getBlock();
Reid Klecknera5930002015-02-11 21:40:48 +00001294 }
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001295 ExitSEHTryStmt(S);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001296}
1297
1298namespace {
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001299struct PerformSEHFinally : EHScopeStack::Cleanup {
1300 llvm::Function *OutlinedFinally;
1301 PerformSEHFinally(llvm::Function *OutlinedFinally)
1302 : OutlinedFinally(OutlinedFinally) {}
Reid Kleckneraca01db2015-02-04 22:37:07 +00001303
Reid Kleckner1d59f992015-01-22 01:36:17 +00001304 void Emit(CodeGenFunction &CGF, Flags F) override {
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001305 ASTContext &Context = CGF.getContext();
Reid Klecknerbe9843c2015-04-29 21:55:21 +00001306 QualType ArgTys[2] = {Context.UnsignedCharTy, Context.VoidPtrTy};
1307 FunctionProtoType::ExtProtoInfo EPI;
1308 const auto *FTP = cast<FunctionType>(
1309 Context.getFunctionType(Context.VoidTy, ArgTys, EPI));
Reid Klecknerddd40962015-04-28 22:19:32 +00001310
Reid Kleckner0bb12a82015-04-29 17:17:17 +00001311 CallArgList Args;
Reid Klecknerbe9843c2015-04-29 21:55:21 +00001312 llvm::Value *IsForEH =
1313 llvm::ConstantInt::get(CGF.ConvertType(ArgTys[0]), F.isForEHCleanup());
1314 Args.add(RValue::get(IsForEH), ArgTys[0]);
Reid Kleckner0bb12a82015-04-29 17:17:17 +00001315
Reid Klecknerbe9843c2015-04-29 21:55:21 +00001316 CodeGenModule &CGM = CGF.CGM;
1317 llvm::Value *Zero = llvm::ConstantInt::get(CGM.Int32Ty, 0);
1318 llvm::Value *FrameAddr = CGM.getIntrinsic(llvm::Intrinsic::frameaddress);
1319 llvm::Value *FP = CGF.Builder.CreateCall(FrameAddr, Zero);
1320 Args.add(RValue::get(FP), ArgTys[1]);
Reid Kleckner0bb12a82015-04-29 17:17:17 +00001321
Reid Klecknerbe9843c2015-04-29 21:55:21 +00001322 const CGFunctionInfo &FnInfo =
1323 CGM.getTypes().arrangeFreeFunctionCall(Args, FTP, /*chainCall=*/false);
1324 CGF.EmitCall(FnInfo, OutlinedFinally, ReturnValueSlot(), Args);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001325 }
1326};
1327}
1328
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001329namespace {
1330/// Find all local variable captures in the statement.
1331struct CaptureFinder : ConstStmtVisitor<CaptureFinder> {
1332 CodeGenFunction &ParentCGF;
1333 const VarDecl *ParentThis;
1334 SmallVector<const VarDecl *, 4> Captures;
1335 CaptureFinder(CodeGenFunction &ParentCGF, const VarDecl *ParentThis)
1336 : ParentCGF(ParentCGF), ParentThis(ParentThis) {}
1337
1338 void Visit(const Stmt *S) {
1339 // See if this is a capture, then recurse.
1340 ConstStmtVisitor<CaptureFinder>::Visit(S);
1341 for (const Stmt *Child : S->children())
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001342 if (Child)
1343 Visit(Child);
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001344 }
1345
1346 void VisitDeclRefExpr(const DeclRefExpr *E) {
1347 // If this is already a capture, just make sure we capture 'this'.
1348 if (E->refersToEnclosingVariableOrCapture()) {
1349 Captures.push_back(ParentThis);
1350 return;
1351 }
1352
1353 const auto *D = dyn_cast<VarDecl>(E->getDecl());
1354 if (D && D->isLocalVarDeclOrParm() && D->hasLocalStorage())
1355 Captures.push_back(D);
1356 }
1357
1358 void VisitCXXThisExpr(const CXXThisExpr *E) {
1359 Captures.push_back(ParentThis);
1360 }
1361};
1362}
1363
1364void CodeGenFunction::EmitCapturedLocals(CodeGenFunction &ParentCGF,
Reid Klecknerbe9843c2015-04-29 21:55:21 +00001365 const Stmt *OutlinedStmt,
1366 llvm::Value *ParentFP) {
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001367 // Find all captures in the Stmt.
1368 CaptureFinder Finder(ParentCGF, ParentCGF.CXXABIThisDecl);
1369 Finder.Visit(OutlinedStmt);
1370
1371 // Typically there are no captures and we can exit early.
Reid Klecknerbe9843c2015-04-29 21:55:21 +00001372 if (Finder.Captures.empty())
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001373 return;
1374
Reid Klecknerbe9843c2015-04-29 21:55:21 +00001375 // Prepare the first two arguments to llvm.framerecover.
1376 llvm::Function *FrameRecoverFn = llvm::Intrinsic::getDeclaration(
1377 &CGM.getModule(), llvm::Intrinsic::framerecover);
1378 llvm::Constant *ParentI8Fn =
1379 llvm::ConstantExpr::getBitCast(ParentCGF.CurFn, Int8PtrTy);
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001380
1381 // Create llvm.framerecover calls for all captures.
1382 for (const VarDecl *VD : Finder.Captures) {
1383 if (isa<ImplicitParamDecl>(VD)) {
1384 CGM.ErrorUnsupported(VD, "'this' captured by SEH");
1385 CXXThisValue = llvm::UndefValue::get(ConvertTypeForMem(VD->getType()));
1386 continue;
1387 }
1388 if (VD->getType()->isVariablyModifiedType()) {
1389 CGM.ErrorUnsupported(VD, "VLA captured by SEH");
1390 continue;
1391 }
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001392 assert((isa<ImplicitParamDecl>(VD) || VD->isLocalVarDeclOrParm()) &&
1393 "captured non-local variable");
1394
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001395 // If this decl hasn't been declared yet, it will be declared in the
1396 // OutlinedStmt.
1397 auto I = ParentCGF.LocalDeclMap.find(VD);
1398 if (I == ParentCGF.LocalDeclMap.end())
1399 continue;
1400 llvm::Value *ParentVar = I->second;
1401
Reid Klecknerbe9843c2015-04-29 21:55:21 +00001402 llvm::CallInst *RecoverCall = nullptr;
1403 CGBuilderTy Builder(AllocaInsertPt);
1404 if (auto *ParentAlloca = dyn_cast<llvm::AllocaInst>(ParentVar)) {
1405 // Mark the variable escaped if nobody else referenced it and compute the
1406 // frameescape index.
1407 auto InsertPair =
1408 ParentCGF.EscapedLocals.insert(std::make_pair(ParentAlloca, -1));
1409 if (InsertPair.second)
1410 InsertPair.first->second = ParentCGF.EscapedLocals.size() - 1;
1411 int FrameEscapeIdx = InsertPair.first->second;
1412 // call i8* @llvm.framerecover(i8* bitcast(@parentFn), i8* %fp, i32 N)
1413 RecoverCall =
1414 Builder.CreateCall3(FrameRecoverFn, ParentI8Fn, ParentFP,
1415 llvm::ConstantInt::get(Int32Ty, FrameEscapeIdx));
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001416
Reid Klecknerbe9843c2015-04-29 21:55:21 +00001417 } else {
1418 // If the parent didn't have an alloca, we're doing some nested outlining.
1419 // Just clone the existing framerecover call, but tweak the FP argument to
1420 // use our FP value. All other arguments are constants.
1421 auto *ParentRecover =
1422 cast<llvm::IntrinsicInst>(ParentVar->stripPointerCasts());
1423 assert(ParentRecover->getIntrinsicID() == llvm::Intrinsic::framerecover &&
1424 "expected alloca or framerecover in parent LocalDeclMap");
1425 RecoverCall = cast<llvm::CallInst>(ParentRecover->clone());
1426 RecoverCall->setArgOperand(1, ParentFP);
1427 RecoverCall->insertBefore(AllocaInsertPt);
1428 }
1429
1430 // Bitcast the variable, rename it, and insert it in the local decl map.
1431 llvm::Value *ChildVar =
1432 Builder.CreateBitCast(RecoverCall, ParentVar->getType());
1433 ChildVar->setName(ParentVar->getName());
1434 LocalDeclMap[VD] = ChildVar;
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001435 }
1436}
1437
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001438/// Arrange a function prototype that can be called by Windows exception
1439/// handling personalities. On Win64, the prototype looks like:
1440/// RetTy func(void *EHPtrs, void *ParentFP);
1441void CodeGenFunction::startOutlinedSEHHelper(CodeGenFunction &ParentCGF,
1442 StringRef Name, QualType RetTy,
1443 FunctionArgList &Args,
1444 const Stmt *OutlinedStmt) {
Reid Kleckner1d59f992015-01-22 01:36:17 +00001445 llvm::Function *ParentFn = ParentCGF.CurFn;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001446 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionDeclaration(
1447 RetTy, Args, FunctionType::ExtInfo(), /*isVariadic=*/false);
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001448
Reid Kleckner1d59f992015-01-22 01:36:17 +00001449 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001450 llvm::Function *Fn = llvm::Function::Create(
1451 FnTy, llvm::GlobalValue::InternalLinkage, Name.str(), &CGM.getModule());
Reid Kleckner1d59f992015-01-22 01:36:17 +00001452 // The filter is either in the same comdat as the function, or it's internal.
1453 if (llvm::Comdat *C = ParentFn->getComdat()) {
1454 Fn->setComdat(C);
1455 } else if (ParentFn->hasWeakLinkage() || ParentFn->hasLinkOnceLinkage()) {
Reid Kleckner1d59f992015-01-22 01:36:17 +00001456 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(ParentFn->getName());
1457 ParentFn->setComdat(C);
1458 Fn->setComdat(C);
1459 } else {
1460 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
1461 }
1462
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001463 IsOutlinedSEHHelper = true;
Nico Weberf2a39a72015-04-13 20:03:03 +00001464
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001465 StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args,
1466 OutlinedStmt->getLocStart(), OutlinedStmt->getLocStart());
1467
1468 CGM.SetLLVMFunctionAttributes(nullptr, FnInfo, CurFn);
Reid Klecknerbe9843c2015-04-29 21:55:21 +00001469
1470 auto AI = Fn->arg_begin();
1471 ++AI;
1472 EmitCapturedLocals(ParentCGF, OutlinedStmt, &*AI);
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001473}
1474
1475/// Create a stub filter function that will ultimately hold the code of the
1476/// filter expression. The EH preparation passes in LLVM will outline the code
1477/// from the main function body into this stub.
1478llvm::Function *
1479CodeGenFunction::GenerateSEHFilterFunction(CodeGenFunction &ParentCGF,
1480 const SEHExceptStmt &Except) {
1481 const Expr *FilterExpr = Except.getFilterExpr();
1482 SourceLocation StartLoc = FilterExpr->getLocStart();
1483
Reid Klecknerbe9843c2015-04-29 21:55:21 +00001484 SEHPointersDecl = ImplicitParamDecl::Create(
1485 getContext(), nullptr, StartLoc,
1486 &getContext().Idents.get("exception_pointers"), getContext().VoidPtrTy);
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001487 FunctionArgList Args;
Reid Klecknerbe9843c2015-04-29 21:55:21 +00001488 Args.push_back(SEHPointersDecl);
1489 Args.push_back(ImplicitParamDecl::Create(
1490 getContext(), nullptr, StartLoc,
1491 &getContext().Idents.get("frame_pointer"), getContext().VoidPtrTy));
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001492
1493 // Get the mangled function name.
1494 SmallString<128> Name;
1495 {
1496 llvm::raw_svector_ostream OS(Name);
1497 const Decl *ParentCodeDecl = ParentCGF.CurCodeDecl;
1498 const NamedDecl *Parent = dyn_cast_or_null<NamedDecl>(ParentCodeDecl);
1499 assert(Parent && "FIXME: handle unnamed decls (lambdas, blocks) with SEH");
1500 CGM.getCXXABI().getMangleContext().mangleSEHFilterExpression(Parent, OS);
1501 }
1502
David Majnemer2ccba832015-04-17 06:57:25 +00001503 startOutlinedSEHHelper(ParentCGF, Name, getContext().LongTy, Args,
1504 FilterExpr);
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001505
1506 // Mark finally block calls as nounwind and noinline to make LLVM's job a
1507 // little easier.
1508 // FIXME: Remove these restrictions in the future.
1509 CurFn->addFnAttr(llvm::Attribute::NoUnwind);
1510 CurFn->addFnAttr(llvm::Attribute::NoInline);
1511
1512 EmitSEHExceptionCodeSave();
Reid Kleckner1d59f992015-01-22 01:36:17 +00001513
1514 // Emit the original filter expression, convert to i32, and return.
1515 llvm::Value *R = EmitScalarExpr(FilterExpr);
David Majnemer2ccba832015-04-17 06:57:25 +00001516 R = Builder.CreateIntCast(R, ConvertType(getContext().LongTy),
Reid Kleckner1d59f992015-01-22 01:36:17 +00001517 FilterExpr->getType()->isSignedIntegerType());
1518 Builder.CreateStore(R, ReturnValue);
1519
1520 FinishFunction(FilterExpr->getLocEnd());
1521
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001522 return CurFn;
1523}
1524
1525llvm::Function *
1526CodeGenFunction::GenerateSEHFinallyFunction(CodeGenFunction &ParentCGF,
1527 const SEHFinallyStmt &Finally) {
1528 const Stmt *FinallyBlock = Finally.getBlock();
1529 SourceLocation StartLoc = FinallyBlock->getLocStart();
1530
1531 FunctionArgList Args;
Reid Klecknerbe9843c2015-04-29 21:55:21 +00001532 Args.push_back(ImplicitParamDecl::Create(
1533 getContext(), nullptr, StartLoc,
1534 &getContext().Idents.get("abnormal_termination"),
1535 getContext().UnsignedCharTy));
1536 Args.push_back(ImplicitParamDecl::Create(
1537 getContext(), nullptr, StartLoc,
1538 &getContext().Idents.get("frame_pointer"), getContext().VoidPtrTy));
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001539
1540 // Get the mangled function name.
1541 SmallString<128> Name;
1542 {
1543 llvm::raw_svector_ostream OS(Name);
1544 const Decl *ParentCodeDecl = ParentCGF.CurCodeDecl;
1545 const NamedDecl *Parent = dyn_cast_or_null<NamedDecl>(ParentCodeDecl);
1546 assert(Parent && "FIXME: handle unnamed decls (lambdas, blocks) with SEH");
1547 CGM.getCXXABI().getMangleContext().mangleSEHFinallyBlock(Parent, OS);
1548 }
1549
1550 startOutlinedSEHHelper(ParentCGF, Name, getContext().VoidTy, Args,
1551 FinallyBlock);
1552
1553 // Emit the original filter expression, convert to i32, and return.
1554 EmitStmt(FinallyBlock);
1555
1556 FinishFunction(FinallyBlock->getLocEnd());
1557
1558 return CurFn;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001559}
1560
1561void CodeGenFunction::EmitSEHExceptionCodeSave() {
1562 // Save the exception code in the exception slot to unify exception access in
1563 // the filter function and the landing pad.
1564 // struct EXCEPTION_POINTERS {
1565 // EXCEPTION_RECORD *ExceptionRecord;
1566 // CONTEXT *ContextRecord;
1567 // };
1568 // void *exn.slot =
1569 // (void *)(uintptr_t)exception_pointers->ExceptionRecord->ExceptionCode;
Reid Klecknerbe9843c2015-04-29 21:55:21 +00001570 llvm::Value *Ptrs = Builder.CreateLoad(GetAddrOfLocalVar(SEHPointersDecl));
Reid Kleckner1d59f992015-01-22 01:36:17 +00001571 llvm::Type *RecordTy = CGM.Int32Ty->getPointerTo();
1572 llvm::Type *PtrsTy = llvm::StructType::get(RecordTy, CGM.VoidPtrTy, nullptr);
1573 Ptrs = Builder.CreateBitCast(Ptrs, PtrsTy->getPointerTo());
David Blaikie1ed728c2015-04-05 22:45:47 +00001574 llvm::Value *Rec = Builder.CreateStructGEP(PtrsTy, Ptrs, 0);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001575 Rec = Builder.CreateLoad(Rec);
1576 llvm::Value *Code = Builder.CreateLoad(Rec);
1577 Code = Builder.CreateZExt(Code, CGM.IntPtrTy);
1578 // FIXME: Change landing pads to produce {i32, i32} and make the exception
1579 // slot an i32.
1580 Code = Builder.CreateIntToPtr(Code, CGM.VoidPtrTy);
1581 Builder.CreateStore(Code, getExceptionSlot());
1582}
1583
1584llvm::Value *CodeGenFunction::EmitSEHExceptionInfo() {
1585 // Sema should diagnose calling this builtin outside of a filter context, but
1586 // don't crash if we screw up.
1587 if (!SEHPointersDecl)
1588 return llvm::UndefValue::get(Int8PtrTy);
1589 return Builder.CreateLoad(GetAddrOfLocalVar(SEHPointersDecl));
1590}
1591
1592llvm::Value *CodeGenFunction::EmitSEHExceptionCode() {
1593 // If we're in a landing pad or filter function, the exception slot contains
1594 // the code.
1595 assert(ExceptionSlot);
1596 llvm::Value *Code =
1597 Builder.CreatePtrToInt(getExceptionFromSlot(), CGM.IntPtrTy);
1598 return Builder.CreateTrunc(Code, CGM.Int32Ty);
1599}
1600
Reid Kleckneraca01db2015-02-04 22:37:07 +00001601llvm::Value *CodeGenFunction::EmitSEHAbnormalTermination() {
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001602 // Abnormal termination is just the first parameter to the outlined finally
1603 // helper.
1604 auto AI = CurFn->arg_begin();
1605 return Builder.CreateZExt(&*AI, Int32Ty);
Reid Kleckneraca01db2015-02-04 22:37:07 +00001606}
1607
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001608void CodeGenFunction::EnterSEHTryStmt(const SEHTryStmt &S) {
1609 CodeGenFunction HelperCGF(CGM, /*suppressNewContext=*/true);
1610 if (const SEHFinallyStmt *Finally = S.getFinallyHandler()) {
Reid Klecknerbe9843c2015-04-29 21:55:21 +00001611 // Push a cleanup for __finally blocks.
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001612 llvm::Function *FinallyFunc =
1613 HelperCGF.GenerateSEHFinallyFunction(*this, *Finally);
1614 EHStack.pushCleanup<PerformSEHFinally>(NormalAndEHCleanup, FinallyFunc);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001615 return;
1616 }
1617
1618 // Otherwise, we must have an __except block.
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001619 const SEHExceptStmt *Except = S.getExceptHandler();
Reid Kleckner1d59f992015-01-22 01:36:17 +00001620 assert(Except);
1621 EHCatchScope *CatchScope = EHStack.pushCatch(1);
Reid Kleckner2a2e1562015-01-22 02:25:56 +00001622
1623 // If the filter is known to evaluate to 1, then we can use the clause "catch
1624 // i8* null".
1625 llvm::Constant *C =
1626 CGM.EmitConstantExpr(Except->getFilterExpr(), getContext().IntTy, this);
1627 if (C && C->isOneValue()) {
1628 CatchScope->setCatchAllHandler(0, createBasicBlock("__except"));
1629 return;
1630 }
1631
1632 // In general, we have to emit an outlined filter function. Use the function
1633 // in place of the RTTI typeinfo global that C++ EH uses.
Reid Kleckner1d59f992015-01-22 01:36:17 +00001634 llvm::Function *FilterFunc =
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001635 HelperCGF.GenerateSEHFilterFunction(*this, *Except);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001636 llvm::Constant *OpaqueFunc =
1637 llvm::ConstantExpr::getBitCast(FilterFunc, Int8PtrTy);
1638 CatchScope->setHandler(0, OpaqueFunc, createBasicBlock("__except"));
1639}
1640
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001641void CodeGenFunction::ExitSEHTryStmt(const SEHTryStmt &S) {
Reid Kleckner1d59f992015-01-22 01:36:17 +00001642 // Just pop the cleanup if it's a __finally block.
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001643 if (S.getFinallyHandler()) {
Reid Kleckner1d59f992015-01-22 01:36:17 +00001644 PopCleanupBlock();
1645 return;
1646 }
1647
1648 // Otherwise, we must have an __except block.
Reid Kleckneraca01db2015-02-04 22:37:07 +00001649 const SEHExceptStmt *Except = S.getExceptHandler();
Reid Kleckner1d59f992015-01-22 01:36:17 +00001650 assert(Except && "__try must have __finally xor __except");
1651 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1652
1653 // Don't emit the __except block if the __try block lacked invokes.
1654 // TODO: Model unwind edges from instructions, either with iload / istore or
1655 // a try body function.
1656 if (!CatchScope.hasEHBranches()) {
1657 CatchScope.clearHandlerBlocks();
1658 EHStack.popCatch();
1659 return;
1660 }
1661
1662 // The fall-through block.
1663 llvm::BasicBlock *ContBB = createBasicBlock("__try.cont");
1664
1665 // We just emitted the body of the __try; jump to the continue block.
1666 if (HaveInsertPoint())
1667 Builder.CreateBr(ContBB);
1668
1669 // Check if our filter function returned true.
1670 emitCatchDispatchBlock(*this, CatchScope);
1671
1672 // Grab the block before we pop the handler.
1673 llvm::BasicBlock *ExceptBB = CatchScope.getHandler(0).Block;
1674 EHStack.popCatch();
1675
1676 EmitBlockAfterUses(ExceptBB);
1677
1678 // Emit the __except body.
1679 EmitStmt(Except->getBlock());
1680
Reid Kleckner3a417c32015-01-30 22:16:45 +00001681 if (HaveInsertPoint())
1682 Builder.CreateBr(ContBB);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001683
1684 EmitBlock(ContBB);
Reid Kleckner543a16c2013-09-16 21:46:30 +00001685}
Nico Weber9b982072014-07-07 00:12:30 +00001686
1687void CodeGenFunction::EmitSEHLeaveStmt(const SEHLeaveStmt &S) {
Nico Weber5779f842015-02-12 23:16:11 +00001688 // If this code is reachable then emit a stop point (if generating
1689 // debug info). We have to do this ourselves because we are on the
1690 // "simple" statement path.
1691 if (HaveInsertPoint())
1692 EmitStopPoint(&S);
1693
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001694 // This must be a __leave from a __finally block, which we warn on and is UB.
1695 // Just emit unreachable.
1696 if (!isSEHTryScope()) {
1697 Builder.CreateUnreachable();
1698 Builder.ClearInsertionPoint();
1699 return;
1700 }
1701
Nico Weber5779f842015-02-12 23:16:11 +00001702 EmitBranchThroughCleanup(*SEHTryEpilogueStack.back());
Nico Weber9b982072014-07-07 00:12:30 +00001703}