blob: 0e257ac7794e92a617b43b0d071ff9683c64af69 [file] [log] [blame]
Hans Wennborgdcfba332015-10-06 23:40:43 +00001//===--- CGException.cpp - Emit LLVM Code for C++ exceptions ----*- C++ -*-===//
Anders Carlsson4b08db72009-10-30 01:42:31 +00002//
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 McCallde0fe072017-08-15 21:42:52 +000018#include "ConstantEmitter.h"
John McCall5add20c2010-07-20 22:17:55 +000019#include "TargetInfo.h"
Reid Kleckner1d59f992015-01-22 01:36:17 +000020#include "clang/AST/Mangle.h"
Benjamin Kramer793bd552012-02-08 12:41:24 +000021#include "clang/AST/StmtCXX.h"
Chandler Carruth4b417452013-01-19 08:09:44 +000022#include "clang/AST/StmtObjC.h"
Reid Kleckner31a1bb02015-04-08 22:23:48 +000023#include "clang/AST/StmtVisitor.h"
Reid Kleckner9fe7f232015-07-07 00:36:30 +000024#include "clang/Basic/TargetBuiltins.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000025#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000026#include "llvm/IR/Intrinsics.h"
Reid Kleckner31a1bb02015-04-08 22:23:48 +000027#include "llvm/IR/IntrinsicInst.h"
Reid Klecknerebaf28d2015-04-14 20:59:00 +000028#include "llvm/Support/SaveAndRestore.h"
John McCallbd309292010-07-06 01:34:17 +000029
Anders Carlsson4b08db72009-10-30 01:42:31 +000030using namespace clang;
31using namespace CodeGen;
32
John McCall2c33ba82013-02-12 03:51:38 +000033static llvm::Constant *getFreeExceptionFn(CodeGenModule &CGM) {
Mike Stump33270212009-12-02 07:41:41 +000034 // void __cxa_free_exception(void *thrown_exception);
Mike Stump75546b82009-12-10 00:06:18 +000035
Chris Lattner2192fe52011-07-18 04:24:23 +000036 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +000037 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000038
John McCall2c33ba82013-02-12 03:51:38 +000039 return CGM.CreateRuntimeFunction(FTy, "__cxa_free_exception");
Mike Stump33270212009-12-02 07:41:41 +000040}
41
John McCall2c33ba82013-02-12 03:51:38 +000042static llvm::Constant *getUnexpectedFn(CodeGenModule &CGM) {
Richard Smith2f7aa192013-06-20 23:03:35 +000043 // void __cxa_call_unexpected(void *thrown_exception);
Mike Stump1d849212009-12-07 23:38:24 +000044
Chris Lattner2192fe52011-07-18 04:24:23 +000045 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +000046 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000047
John McCall2c33ba82013-02-12 03:51:38 +000048 return CGM.CreateRuntimeFunction(FTy, "__cxa_call_unexpected");
Mike Stump1d849212009-12-07 23:38:24 +000049}
50
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000051llvm::Constant *CodeGenModule::getTerminateFn() {
Mike Stump33270212009-12-02 07:41:41 +000052 // void __terminate();
53
Chris Lattner2192fe52011-07-18 04:24:23 +000054 llvm::FunctionType *FTy =
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000055 llvm::FunctionType::get(VoidTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000056
Chris Lattner0e62c1c2011-07-23 10:55:15 +000057 StringRef name;
John McCall9de19782011-07-06 01:22:26 +000058
59 // In C++, use std::terminate().
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000060 if (getLangOpts().CPlusPlus &&
61 getTarget().getCXXABI().isItaniumFamily()) {
Reid Kleckner1d59f992015-01-22 01:36:17 +000062 name = "_ZSt9terminatev";
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000063 } else if (getLangOpts().CPlusPlus &&
64 getTarget().getCXXABI().isMicrosoft()) {
David Majnemerb710a932015-05-11 03:57:49 +000065 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
David Majnemerfb6ffca2015-05-10 21:38:26 +000066 name = "__std_terminate";
67 else
68 name = "\01?terminate@@YAXXZ";
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000069 } else if (getLangOpts().ObjC1 &&
70 getLangOpts().ObjCRuntime.hasTerminate())
John McCall9de19782011-07-06 01:22:26 +000071 name = "objc_terminate";
72 else
73 name = "abort";
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000074 return CreateRuntimeFunction(FTy, name);
David Chisnallf9c42252010-05-17 13:49:20 +000075}
76
John McCall2c33ba82013-02-12 03:51:38 +000077static llvm::Constant *getCatchallRethrowFn(CodeGenModule &CGM,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000078 StringRef Name) {
Chris Lattner2192fe52011-07-18 04:24:23 +000079 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +000080 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
John McCall36ea3722010-07-17 00:43:08 +000081
John McCall2c33ba82013-02-12 03:51:38 +000082 return CGM.CreateRuntimeFunction(FTy, Name);
John McCallbd309292010-07-06 01:34:17 +000083}
84
Craig Topper8a13c412014-05-21 05:09:00 +000085const EHPersonality EHPersonality::GNU_C = { "__gcc_personality_v0", nullptr };
Benjamin Kramer793bd552012-02-08 12:41:24 +000086const EHPersonality
Craig Topper8a13c412014-05-21 05:09:00 +000087EHPersonality::GNU_C_SJLJ = { "__gcc_personality_sj0", nullptr };
88const EHPersonality
Reid Kleckner8f45c9c2014-09-15 17:19:16 +000089EHPersonality::GNU_C_SEH = { "__gcc_personality_seh0", nullptr };
90const EHPersonality
Craig Topper8a13c412014-05-21 05:09:00 +000091EHPersonality::NeXT_ObjC = { "__objc_personality_v0", nullptr };
92const EHPersonality
93EHPersonality::GNU_CPlusPlus = { "__gxx_personality_v0", nullptr };
94const EHPersonality
95EHPersonality::GNU_CPlusPlus_SJLJ = { "__gxx_personality_sj0", nullptr };
Benjamin Kramer793bd552012-02-08 12:41:24 +000096const EHPersonality
Reid Kleckner8f45c9c2014-09-15 17:19:16 +000097EHPersonality::GNU_CPlusPlus_SEH = { "__gxx_personality_seh0", nullptr };
98const EHPersonality
Benjamin Kramer793bd552012-02-08 12:41:24 +000099EHPersonality::GNU_ObjC = {"__gnu_objc_personality_v0", "objc_exception_throw"};
100const EHPersonality
Benjamin Kramer796c1d92017-01-08 22:58:07 +0000101EHPersonality::GNU_ObjC_SJLJ = {"__gnu_objc_personality_sj0", "objc_exception_throw"};
102const EHPersonality
103EHPersonality::GNU_ObjC_SEH = {"__gnu_objc_personality_seh0", "objc_exception_throw"};
104const EHPersonality
Craig Topper8a13c412014-05-21 05:09:00 +0000105EHPersonality::GNU_ObjCXX = { "__gnustep_objcxx_personality_v0", nullptr };
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000106const EHPersonality
Craig Topper8a13c412014-05-21 05:09:00 +0000107EHPersonality::GNUstep_ObjC = { "__gnustep_objc_personality_v0", nullptr };
Reid Kleckner1d59f992015-01-22 01:36:17 +0000108const EHPersonality
109EHPersonality::MSVC_except_handler = { "_except_handler3", nullptr };
110const EHPersonality
111EHPersonality::MSVC_C_specific_handler = { "__C_specific_handler", nullptr };
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000112const EHPersonality
113EHPersonality::MSVC_CxxFrameHandler3 = { "__CxxFrameHandler3", nullptr };
John McCall36ea3722010-07-17 00:43:08 +0000114
Reid Klecknere070b992014-11-14 02:01:10 +0000115static const EHPersonality &getCPersonality(const llvm::Triple &T,
116 const LangOptions &L) {
John McCall2faab302010-11-07 02:35:25 +0000117 if (L.SjLjExceptions)
118 return EHPersonality::GNU_C_SJLJ;
Saleem Abdulrasool3e701322018-03-09 07:06:42 +0000119 if (L.DWARFExceptions)
120 return EHPersonality::GNU_C;
121 if (T.isWindowsMSVCEnvironment())
122 return EHPersonality::MSVC_CxxFrameHandler3;
Martell Malonec950c652017-11-29 07:25:12 +0000123 if (L.SEHExceptions)
Reid Kleckner8f45c9c2014-09-15 17:19:16 +0000124 return EHPersonality::GNU_C_SEH;
John McCall36ea3722010-07-17 00:43:08 +0000125 return EHPersonality::GNU_C;
126}
127
Reid Klecknere070b992014-11-14 02:01:10 +0000128static const EHPersonality &getObjCPersonality(const llvm::Triple &T,
129 const LangOptions &L) {
John McCall5fb5df92012-06-20 06:18:46 +0000130 switch (L.ObjCRuntime.getKind()) {
131 case ObjCRuntime::FragileMacOSX:
Reid Klecknere070b992014-11-14 02:01:10 +0000132 return getCPersonality(T, L);
John McCall5fb5df92012-06-20 06:18:46 +0000133 case ObjCRuntime::MacOSX:
134 case ObjCRuntime::iOS:
Tim Northover756447a2015-10-30 16:30:36 +0000135 case ObjCRuntime::WatchOS:
Saleem Abdulrasool3e701322018-03-09 07:06:42 +0000136 if (T.isWindowsMSVCEnvironment())
137 return EHPersonality::MSVC_CxxFrameHandler3;
John McCall5fb5df92012-06-20 06:18:46 +0000138 return EHPersonality::NeXT_ObjC;
David Chisnallb601c962012-07-03 20:49:52 +0000139 case ObjCRuntime::GNUstep:
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000140 if (L.ObjCRuntime.getVersion() >= VersionTuple(1, 7))
141 return EHPersonality::GNUstep_ObjC;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +0000142 LLVM_FALLTHROUGH;
David Chisnallb601c962012-07-03 20:49:52 +0000143 case ObjCRuntime::GCC:
John McCall775086e2012-07-12 02:07:58 +0000144 case ObjCRuntime::ObjFW:
Benjamin Kramer796c1d92017-01-08 22:58:07 +0000145 if (L.SjLjExceptions)
146 return EHPersonality::GNU_ObjC_SJLJ;
Martell Malonec950c652017-11-29 07:25:12 +0000147 if (L.SEHExceptions)
Benjamin Kramer796c1d92017-01-08 22:58:07 +0000148 return EHPersonality::GNU_ObjC_SEH;
John McCall36ea3722010-07-17 00:43:08 +0000149 return EHPersonality::GNU_ObjC;
John McCallbd309292010-07-06 01:34:17 +0000150 }
John McCall5fb5df92012-06-20 06:18:46 +0000151 llvm_unreachable("bad runtime kind");
John McCallbd309292010-07-06 01:34:17 +0000152}
153
Reid Klecknere070b992014-11-14 02:01:10 +0000154static const EHPersonality &getCXXPersonality(const llvm::Triple &T,
155 const LangOptions &L) {
John McCall36ea3722010-07-17 00:43:08 +0000156 if (L.SjLjExceptions)
157 return EHPersonality::GNU_CPlusPlus_SJLJ;
Saleem Abdulrasool3e701322018-03-09 07:06:42 +0000158 if (L.DWARFExceptions)
159 return EHPersonality::GNU_CPlusPlus;
160 if (T.isWindowsMSVCEnvironment())
161 return EHPersonality::MSVC_CxxFrameHandler3;
Martell Malonec950c652017-11-29 07:25:12 +0000162 if (L.SEHExceptions)
Reid Kleckner8f45c9c2014-09-15 17:19:16 +0000163 return EHPersonality::GNU_CPlusPlus_SEH;
Reid Klecknere070b992014-11-14 02:01:10 +0000164 return EHPersonality::GNU_CPlusPlus;
John McCallbd309292010-07-06 01:34:17 +0000165}
166
167/// Determines the personality function to use when both C++
168/// and Objective-C exceptions are being caught.
Reid Klecknere070b992014-11-14 02:01:10 +0000169static const EHPersonality &getObjCXXPersonality(const llvm::Triple &T,
170 const LangOptions &L) {
John McCall5fb5df92012-06-20 06:18:46 +0000171 switch (L.ObjCRuntime.getKind()) {
Saleem Abdulrasool8f6d9442017-11-02 00:25:40 +0000172 // In the fragile ABI, just use C++ exception handling and hope
173 // they're not doing crazy exception mixing.
174 case ObjCRuntime::FragileMacOSX:
175 return getCXXPersonality(T, L);
176
John McCallbd309292010-07-06 01:34:17 +0000177 // The ObjC personality defers to the C++ personality for non-ObjC
178 // handlers. Unlike the C++ case, we use the same personality
179 // function on targets using (backend-driven) SJLJ EH.
John McCall5fb5df92012-06-20 06:18:46 +0000180 case ObjCRuntime::MacOSX:
181 case ObjCRuntime::iOS:
Tim Northover756447a2015-10-30 16:30:36 +0000182 case ObjCRuntime::WatchOS:
Saleem Abdulrasool8f6d9442017-11-02 00:25:40 +0000183 return getObjCPersonality(T, L);
John McCallbd309292010-07-06 01:34:17 +0000184
Saleem Abdulrasool8f6d9442017-11-02 00:25:40 +0000185 case ObjCRuntime::GNUstep:
186 return EHPersonality::GNU_ObjCXX;
David Chisnallf9c42252010-05-17 13:49:20 +0000187
David Chisnallb601c962012-07-03 20:49:52 +0000188 // The GCC runtime's personality function inherently doesn't support
Saleem Abdulrasool8f6d9442017-11-02 00:25:40 +0000189 // mixed EH. Use the ObjC personality just to avoid returning null.
David Chisnallb601c962012-07-03 20:49:52 +0000190 case ObjCRuntime::GCC:
Benjamin Kramer9851cb72017-04-01 17:59:01 +0000191 case ObjCRuntime::ObjFW:
192 return getObjCPersonality(T, L);
John McCall5fb5df92012-06-20 06:18:46 +0000193 }
194 llvm_unreachable("bad runtime kind");
John McCallbd309292010-07-06 01:34:17 +0000195}
196
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000197static const EHPersonality &getSEHPersonalityMSVC(const llvm::Triple &T) {
Reid Kleckner1d59f992015-01-22 01:36:17 +0000198 if (T.getArch() == llvm::Triple::x86)
199 return EHPersonality::MSVC_except_handler;
200 return EHPersonality::MSVC_C_specific_handler;
201}
202
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000203const EHPersonality &EHPersonality::get(CodeGenModule &CGM,
204 const FunctionDecl *FD) {
Reid Klecknere070b992014-11-14 02:01:10 +0000205 const llvm::Triple &T = CGM.getTarget().getTriple();
206 const LangOptions &L = CGM.getLangOpts();
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000207
Reid Kleckner01485652015-09-17 17:04:13 +0000208 // Functions using SEH get an SEH personality.
209 if (FD && FD->usesSEHTry())
210 return getSEHPersonalityMSVC(T);
211
Saleem Abdulrasool3e701322018-03-09 07:06:42 +0000212 if (L.ObjC1)
213 return L.CPlusPlus ? getObjCXXPersonality(T, L) : getObjCPersonality(T, L);
214 return L.CPlusPlus ? getCXXPersonality(T, L) : getCPersonality(T, L);
John McCall36ea3722010-07-17 00:43:08 +0000215}
John McCallbd309292010-07-06 01:34:17 +0000216
David Majnemerc28d46e2015-07-22 23:46:21 +0000217const EHPersonality &EHPersonality::get(CodeGenFunction &CGF) {
Reid Kleckner65fa8692017-10-13 16:55:14 +0000218 const auto *FD = CGF.CurCodeDecl;
219 // For outlined finallys and filters, use the SEH personality in case they
220 // contain more SEH. This mostly only affects finallys. Filters could
221 // hypothetically use gnu statement expressions to sneak in nested SEH.
222 FD = FD ? FD : CGF.CurSEHParent;
223 return get(CGF.CGM, dyn_cast_or_null<FunctionDecl>(FD));
David Majnemerc28d46e2015-07-22 23:46:21 +0000224}
225
John McCall0bdb1fd2010-09-16 06:16:50 +0000226static llvm::Constant *getPersonalityFn(CodeGenModule &CGM,
John McCall36ea3722010-07-17 00:43:08 +0000227 const EHPersonality &Personality) {
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +0000228 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.Int32Ty, true),
229 Personality.PersonalityFn,
Reid Klecknerde864822017-03-21 16:57:30 +0000230 llvm::AttributeList(), /*Local=*/true);
John McCall0bdb1fd2010-09-16 06:16:50 +0000231}
232
233static llvm::Constant *getOpaquePersonalityFn(CodeGenModule &CGM,
234 const EHPersonality &Personality) {
235 llvm::Constant *Fn = getPersonalityFn(CGM, Personality);
John McCallad7c5c12011-02-08 08:22:06 +0000236 return llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
John McCall0bdb1fd2010-09-16 06:16:50 +0000237}
238
Vedant Kumardb609472015-09-11 15:40:05 +0000239/// Check whether a landingpad instruction only uses C++ features.
240static bool LandingPadHasOnlyCXXUses(llvm::LandingPadInst *LPI) {
241 for (unsigned I = 0, E = LPI->getNumClauses(); I != E; ++I) {
242 // Look for something that would've been returned by the ObjC
243 // runtime's GetEHType() method.
244 llvm::Value *Val = LPI->getClause(I)->stripPointerCasts();
245 if (LPI->isCatch(I)) {
246 // Check if the catch value has the ObjC prefix.
247 if (llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Val))
248 // ObjC EH selector entries are always global variables with
249 // names starting like this.
250 if (GV->getName().startswith("OBJC_EHTYPE"))
251 return false;
252 } else {
253 // Check if any of the filter values have the ObjC prefix.
254 llvm::Constant *CVal = cast<llvm::Constant>(Val);
255 for (llvm::User::op_iterator
256 II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II) {
257 if (llvm::GlobalVariable *GV =
258 cast<llvm::GlobalVariable>((*II)->stripPointerCasts()))
259 // ObjC EH selector entries are always global variables with
260 // names starting like this.
261 if (GV->getName().startswith("OBJC_EHTYPE"))
262 return false;
263 }
264 }
265 }
266 return true;
267}
268
John McCall0bdb1fd2010-09-16 06:16:50 +0000269/// Check whether a personality function could reasonably be swapped
270/// for a C++ personality function.
271static bool PersonalityHasOnlyCXXUses(llvm::Constant *Fn) {
Chandler Carruth4d01fff2014-03-09 03:16:50 +0000272 for (llvm::User *U : Fn->users()) {
John McCall0bdb1fd2010-09-16 06:16:50 +0000273 // Conditionally white-list bitcasts.
Chandler Carruth4d01fff2014-03-09 03:16:50 +0000274 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(U)) {
John McCall0bdb1fd2010-09-16 06:16:50 +0000275 if (CE->getOpcode() != llvm::Instruction::BitCast) return false;
276 if (!PersonalityHasOnlyCXXUses(CE))
277 return false;
278 continue;
279 }
280
Vedant Kumardb609472015-09-11 15:40:05 +0000281 // Otherwise it must be a function.
282 llvm::Function *F = dyn_cast<llvm::Function>(U);
283 if (!F) return false;
John McCall0bdb1fd2010-09-16 06:16:50 +0000284
Vedant Kumardb609472015-09-11 15:40:05 +0000285 for (auto BB = F->begin(), E = F->end(); BB != E; ++BB) {
286 if (BB->isLandingPad())
287 if (!LandingPadHasOnlyCXXUses(BB->getLandingPadInst()))
288 return false;
John McCall0bdb1fd2010-09-16 06:16:50 +0000289 }
290 }
291
292 return true;
293}
294
295/// Try to use the C++ personality function in ObjC++. Not doing this
296/// can cause some incompatibilities with gcc, which is more
297/// aggressive about only using the ObjC++ personality in a function
298/// when it really needs it.
299void CodeGenModule::SimplifyPersonality() {
John McCall0bdb1fd2010-09-16 06:16:50 +0000300 // If we're not in ObjC++ -fexceptions, there's nothing to do.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000301 if (!LangOpts.CPlusPlus || !LangOpts.ObjC1 || !LangOpts.Exceptions)
John McCall0bdb1fd2010-09-16 06:16:50 +0000302 return;
303
John McCall3c223932012-11-14 17:48:31 +0000304 // Both the problem this endeavors to fix and the way the logic
305 // above works is specific to the NeXT runtime.
306 if (!LangOpts.ObjCRuntime.isNeXTFamily())
307 return;
308
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000309 const EHPersonality &ObjCXX = EHPersonality::get(*this, /*FD=*/nullptr);
Reid Klecknere070b992014-11-14 02:01:10 +0000310 const EHPersonality &CXX =
311 getCXXPersonality(getTarget().getTriple(), LangOpts);
Benjamin Kramer793bd552012-02-08 12:41:24 +0000312 if (&ObjCXX == &CXX)
John McCall0bdb1fd2010-09-16 06:16:50 +0000313 return;
314
Benjamin Kramer793bd552012-02-08 12:41:24 +0000315 assert(std::strcmp(ObjCXX.PersonalityFn, CXX.PersonalityFn) != 0 &&
316 "Different EHPersonalities using the same personality function.");
317
318 llvm::Function *Fn = getModule().getFunction(ObjCXX.PersonalityFn);
John McCall0bdb1fd2010-09-16 06:16:50 +0000319
320 // Nothing to do if it's unused.
321 if (!Fn || Fn->use_empty()) return;
322
323 // Can't do the optimization if it has non-C++ uses.
324 if (!PersonalityHasOnlyCXXUses(Fn)) return;
325
326 // Create the C++ personality function and kill off the old
327 // function.
328 llvm::Constant *CXXFn = getPersonalityFn(*this, CXX);
329
330 // This can happen if the user is screwing with us.
331 if (Fn->getType() != CXXFn->getType()) return;
332
333 Fn->replaceAllUsesWith(CXXFn);
334 Fn->eraseFromParent();
John McCallbd309292010-07-06 01:34:17 +0000335}
336
337/// Returns the value to inject into a selector to indicate the
338/// presence of a catch-all.
339static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
340 // Possibly we should use @llvm.eh.catch.all.value here.
John McCallad7c5c12011-02-08 08:22:06 +0000341 return llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
John McCallbd309292010-07-06 01:34:17 +0000342}
343
John McCallbb026012010-07-13 21:17:51 +0000344namespace {
345 /// A cleanup to free the exception object if its initialization
346 /// throws.
David Blaikie7e70d682015-08-18 22:40:54 +0000347 struct FreeException final : EHScopeStack::Cleanup {
John McCall5fcf8da2011-07-12 00:15:30 +0000348 llvm::Value *exn;
349 FreeException(llvm::Value *exn) : exn(exn) {}
Craig Topper4f12f102014-03-12 06:41:41 +0000350 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +0000351 CGF.EmitNounwindRuntimeCall(getFreeExceptionFn(CGF.CGM), exn);
John McCallbb026012010-07-13 21:17:51 +0000352 }
353 };
Hans Wennborgdcfba332015-10-06 23:40:43 +0000354} // end anonymous namespace
John McCallbb026012010-07-13 21:17:51 +0000355
John McCall2e6567a2010-04-22 01:10:34 +0000356// Emits an exception expression into the given location. This
357// differs from EmitAnyExprToMem only in that, if a final copy-ctor
358// call is required, an exception within that copy ctor causes
359// std::terminate to be invoked.
John McCall7f416cc2015-09-08 08:05:57 +0000360void CodeGenFunction::EmitAnyExprToExn(const Expr *e, Address addr) {
John McCallbd309292010-07-06 01:34:17 +0000361 // Make sure the exception object is cleaned up if there's an
362 // exception during initialization.
John McCall7f416cc2015-09-08 08:05:57 +0000363 pushFullExprCleanup<FreeException>(EHCleanup, addr.getPointer());
David Majnemer7c237072015-03-05 00:46:22 +0000364 EHScopeStack::stable_iterator cleanup = EHStack.stable_begin();
John McCall2e6567a2010-04-22 01:10:34 +0000365
366 // __cxa_allocate_exception returns a void*; we need to cast this
367 // to the appropriate type for the object.
David Majnemer7c237072015-03-05 00:46:22 +0000368 llvm::Type *ty = ConvertTypeForMem(e->getType())->getPointerTo();
John McCall7f416cc2015-09-08 08:05:57 +0000369 Address typedAddr = Builder.CreateBitCast(addr, ty);
John McCall2e6567a2010-04-22 01:10:34 +0000370
371 // FIXME: this isn't quite right! If there's a final unelided call
372 // to a copy constructor, then according to [except.terminate]p1 we
373 // must call std::terminate() if that constructor throws, because
374 // technically that copy occurs after the exception expression is
375 // evaluated but before the exception is caught. But the best way
376 // to handle that is to teach EmitAggExpr to do the final copy
377 // differently if it can't be elided.
David Majnemer7c237072015-03-05 00:46:22 +0000378 EmitAnyExprToMem(e, typedAddr, e->getType().getQualifiers(),
379 /*IsInit*/ true);
John McCall2e6567a2010-04-22 01:10:34 +0000380
John McCalle4df6c82011-01-28 08:37:24 +0000381 // Deactivate the cleanup block.
John McCall7f416cc2015-09-08 08:05:57 +0000382 DeactivateCleanupBlock(cleanup,
383 cast<llvm::Instruction>(typedAddr.getPointer()));
Mike Stump54066142009-12-01 03:41:18 +0000384}
385
John McCall7f416cc2015-09-08 08:05:57 +0000386Address CodeGenFunction::getExceptionSlot() {
John McCall9b382dd2011-05-28 21:13:02 +0000387 if (!ExceptionSlot)
388 ExceptionSlot = CreateTempAlloca(Int8PtrTy, "exn.slot");
John McCall7f416cc2015-09-08 08:05:57 +0000389 return Address(ExceptionSlot, getPointerAlign());
Mike Stump54066142009-12-01 03:41:18 +0000390}
391
John McCall7f416cc2015-09-08 08:05:57 +0000392Address CodeGenFunction::getEHSelectorSlot() {
John McCall9b382dd2011-05-28 21:13:02 +0000393 if (!EHSelectorSlot)
394 EHSelectorSlot = CreateTempAlloca(Int32Ty, "ehselector.slot");
John McCall7f416cc2015-09-08 08:05:57 +0000395 return Address(EHSelectorSlot, CharUnits::fromQuantity(4));
John McCall9b382dd2011-05-28 21:13:02 +0000396}
397
Bill Wendling79a70e42011-09-15 18:57:19 +0000398llvm::Value *CodeGenFunction::getExceptionFromSlot() {
399 return Builder.CreateLoad(getExceptionSlot(), "exn");
400}
401
402llvm::Value *CodeGenFunction::getSelectorFromSlot() {
403 return Builder.CreateLoad(getEHSelectorSlot(), "sel");
404}
405
Richard Smithea852322013-05-07 21:53:22 +0000406void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E,
407 bool KeepInsertionPoint) {
David Majnemer7c237072015-03-05 00:46:22 +0000408 if (const Expr *SubExpr = E->getSubExpr()) {
409 QualType ThrowType = SubExpr->getType();
410 if (ThrowType->isObjCObjectPointerType()) {
411 const Stmt *ThrowStmt = E->getSubExpr();
412 const ObjCAtThrowStmt S(E->getExprLoc(), const_cast<Stmt *>(ThrowStmt));
413 CGM.getObjCRuntime().EmitThrowStmt(*this, S, false);
414 } else {
415 CGM.getCXXABI().emitThrow(*this, E);
John McCall2e6567a2010-04-22 01:10:34 +0000416 }
David Majnemer7c237072015-03-05 00:46:22 +0000417 } else {
418 CGM.getCXXABI().emitRethrow(*this, /*isNoReturn=*/true);
John McCall2e6567a2010-04-22 01:10:34 +0000419 }
Mike Stump75546b82009-12-10 00:06:18 +0000420
John McCall20f6ab82011-01-12 03:41:02 +0000421 // throw is an expression, and the expression emitters expect us
422 // to leave ourselves at a valid insertion point.
Richard Smithea852322013-05-07 21:53:22 +0000423 if (KeepInsertionPoint)
424 EmitBlock(createBasicBlock("throw.cont"));
Anders Carlsson4b08db72009-10-30 01:42:31 +0000425}
Mike Stump58ef18b2009-11-20 23:44:51 +0000426
Mike Stump1d849212009-12-07 23:38:24 +0000427void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000428 if (!CGM.getLangOpts().CXXExceptions)
Anders Carlsson9878f9f2010-02-06 23:59:05 +0000429 return;
430
Mike Stump1d849212009-12-07 23:38:24 +0000431 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
Craig Topper8a13c412014-05-21 05:09:00 +0000432 if (!FD) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000433 // Check if CapturedDecl is nothrow and create terminate scope for it.
434 if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
435 if (CD->isNothrow())
436 EHStack.pushTerminate();
437 }
Mike Stump1d849212009-12-07 23:38:24 +0000438 return;
Alexey Bataev9959db52014-05-06 10:08:46 +0000439 }
Mike Stump1d849212009-12-07 23:38:24 +0000440 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
Craig Topper8a13c412014-05-21 05:09:00 +0000441 if (!Proto)
Mike Stump1d849212009-12-07 23:38:24 +0000442 return;
443
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000444 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
445 if (isNoexceptExceptionSpec(EST)) {
446 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
447 // noexcept functions are simple terminate scopes.
448 EHStack.pushTerminate();
449 }
450 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
David Majnemer1f192e22015-04-01 04:45:52 +0000451 // TODO: Revisit exception specifications for the MS ABI. There is a way to
452 // encode these in an object file but MSVC doesn't do anything with it.
453 if (getTarget().getCXXABI().isMicrosoft())
454 return;
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000455 unsigned NumExceptions = Proto->getNumExceptions();
456 EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
Mike Stump1d849212009-12-07 23:38:24 +0000457
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000458 for (unsigned I = 0; I != NumExceptions; ++I) {
459 QualType Ty = Proto->getExceptionType(I);
460 QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
461 llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType,
462 /*ForEH=*/true);
463 Filter->setFilter(I, EHType);
464 }
Mike Stump1d849212009-12-07 23:38:24 +0000465 }
Mike Stump1d849212009-12-07 23:38:24 +0000466}
467
John McCall8e4c74b2011-08-11 02:22:43 +0000468/// Emit the dispatch block for a filter scope if necessary.
469static void emitFilterDispatchBlock(CodeGenFunction &CGF,
470 EHFilterScope &filterScope) {
471 llvm::BasicBlock *dispatchBlock = filterScope.getCachedEHDispatchBlock();
472 if (!dispatchBlock) return;
473 if (dispatchBlock->use_empty()) {
474 delete dispatchBlock;
475 return;
476 }
477
John McCall8e4c74b2011-08-11 02:22:43 +0000478 CGF.EmitBlockAfterUses(dispatchBlock);
479
480 // If this isn't a catch-all filter, we need to check whether we got
481 // here because the filter triggered.
482 if (filterScope.getNumFilters()) {
483 // Load the selector value.
Bill Wendling79a70e42011-09-15 18:57:19 +0000484 llvm::Value *selector = CGF.getSelectorFromSlot();
John McCall8e4c74b2011-08-11 02:22:43 +0000485 llvm::BasicBlock *unexpectedBB = CGF.createBasicBlock("ehspec.unexpected");
486
487 llvm::Value *zero = CGF.Builder.getInt32(0);
488 llvm::Value *failsFilter =
Nico Weber1bebad12015-02-11 22:33:32 +0000489 CGF.Builder.CreateICmpSLT(selector, zero, "ehspec.fails");
490 CGF.Builder.CreateCondBr(failsFilter, unexpectedBB,
491 CGF.getEHResumeBlock(false));
John McCall8e4c74b2011-08-11 02:22:43 +0000492
493 CGF.EmitBlock(unexpectedBB);
494 }
495
496 // Call __cxa_call_unexpected. This doesn't need to be an invoke
497 // because __cxa_call_unexpected magically filters exceptions
498 // according to the last landing pad the exception was thrown
499 // into. Seriously.
Bill Wendling79a70e42011-09-15 18:57:19 +0000500 llvm::Value *exn = CGF.getExceptionFromSlot();
John McCall882987f2013-02-28 19:01:20 +0000501 CGF.EmitRuntimeCall(getUnexpectedFn(CGF.CGM), exn)
John McCall8e4c74b2011-08-11 02:22:43 +0000502 ->setDoesNotReturn();
503 CGF.Builder.CreateUnreachable();
504}
505
Mike Stump1d849212009-12-07 23:38:24 +0000506void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000507 if (!CGM.getLangOpts().CXXExceptions)
Anders Carlsson9878f9f2010-02-06 23:59:05 +0000508 return;
509
Mike Stump1d849212009-12-07 23:38:24 +0000510 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
Craig Topper8a13c412014-05-21 05:09:00 +0000511 if (!FD) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000512 // Check if CapturedDecl is nothrow and pop terminate scope for it.
513 if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
514 if (CD->isNothrow())
515 EHStack.popTerminate();
516 }
Mike Stump1d849212009-12-07 23:38:24 +0000517 return;
Alexey Bataev9959db52014-05-06 10:08:46 +0000518 }
Mike Stump1d849212009-12-07 23:38:24 +0000519 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
Craig Topper8a13c412014-05-21 05:09:00 +0000520 if (!Proto)
Mike Stump1d849212009-12-07 23:38:24 +0000521 return;
522
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000523 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
524 if (isNoexceptExceptionSpec(EST)) {
525 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
526 EHStack.popTerminate();
527 }
528 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
David Majnemer1f192e22015-04-01 04:45:52 +0000529 // TODO: Revisit exception specifications for the MS ABI. There is a way to
530 // encode these in an object file but MSVC doesn't do anything with it.
531 if (getTarget().getCXXABI().isMicrosoft())
532 return;
John McCall8e4c74b2011-08-11 02:22:43 +0000533 EHFilterScope &filterScope = cast<EHFilterScope>(*EHStack.begin());
534 emitFilterDispatchBlock(*this, filterScope);
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000535 EHStack.popFilter();
536 }
Mike Stump1d849212009-12-07 23:38:24 +0000537}
538
Mike Stump58ef18b2009-11-20 23:44:51 +0000539void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
John McCallb609d3f2010-07-07 06:56:46 +0000540 EnterCXXTryStmt(S);
John McCallb81884d2010-02-19 09:25:03 +0000541 EmitStmt(S.getTryBlock());
John McCallb609d3f2010-07-07 06:56:46 +0000542 ExitCXXTryStmt(S);
John McCallb81884d2010-02-19 09:25:03 +0000543}
544
John McCallb609d3f2010-07-07 06:56:46 +0000545void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallbd309292010-07-06 01:34:17 +0000546 unsigned NumHandlers = S.getNumHandlers();
547 EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
John McCallb81884d2010-02-19 09:25:03 +0000548
John McCallbd309292010-07-06 01:34:17 +0000549 for (unsigned I = 0; I != NumHandlers; ++I) {
550 const CXXCatchStmt *C = S.getHandler(I);
John McCallb81884d2010-02-19 09:25:03 +0000551
John McCallbd309292010-07-06 01:34:17 +0000552 llvm::BasicBlock *Handler = createBasicBlock("catch");
553 if (C->getExceptionDecl()) {
554 // FIXME: Dropping the reference type on the type into makes it
555 // impossible to correctly implement catch-by-reference
556 // semantics for pointers. Unfortunately, this is what all
557 // existing compilers do, and it's not clear that the standard
558 // personality routine is capable of doing this right. See C++ DR 388:
559 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
David Majnemer571162a2014-10-12 06:58:22 +0000560 Qualifiers CaughtTypeQuals;
561 QualType CaughtType = CGM.getContext().getUnqualifiedArrayType(
562 C->getCaughtType().getNonReferenceType(), CaughtTypeQuals);
John McCall2ca705e2010-07-24 00:37:23 +0000563
Reid Kleckner10aa7702015-09-16 20:15:55 +0000564 CatchTypeInfo TypeInfo{nullptr, 0};
John McCall2ca705e2010-07-24 00:37:23 +0000565 if (CaughtType->isObjCObjectPointerType())
Reid Kleckner10aa7702015-09-16 20:15:55 +0000566 TypeInfo.RTTI = CGM.getObjCRuntime().GetEHType(CaughtType);
John McCall2ca705e2010-07-24 00:37:23 +0000567 else
Reid Kleckner10aa7702015-09-16 20:15:55 +0000568 TypeInfo = CGM.getCXXABI().getAddrOfCXXCatchHandlerType(
569 CaughtType, C->getCaughtType());
John McCallbd309292010-07-06 01:34:17 +0000570 CatchScope->setHandler(I, TypeInfo, Handler);
571 } else {
572 // No exception decl indicates '...', a catch-all.
Reid Kleckner10aa7702015-09-16 20:15:55 +0000573 CatchScope->setHandler(I, CGM.getCXXABI().getCatchAllTypeInfo(), Handler);
John McCallbd309292010-07-06 01:34:17 +0000574 }
575 }
John McCallbd309292010-07-06 01:34:17 +0000576}
577
John McCall8e4c74b2011-08-11 02:22:43 +0000578llvm::BasicBlock *
579CodeGenFunction::getEHDispatchBlock(EHScopeStack::stable_iterator si) {
Reid Kleckner129552b2015-10-08 01:13:52 +0000580 if (EHPersonality::get(*this).usesFuncletPads())
David Majnemerdbf10452015-07-31 17:58:45 +0000581 return getMSVCDispatchBlock(si);
582
John McCall8e4c74b2011-08-11 02:22:43 +0000583 // The dispatch block for the end of the scope chain is a block that
584 // just resumes unwinding.
585 if (si == EHStack.stable_end())
David Chisnall9a837be2012-11-07 16:50:40 +0000586 return getEHResumeBlock(true);
John McCall8e4c74b2011-08-11 02:22:43 +0000587
588 // Otherwise, we should look at the actual scope.
589 EHScope &scope = *EHStack.find(si);
590
591 llvm::BasicBlock *dispatchBlock = scope.getCachedEHDispatchBlock();
592 if (!dispatchBlock) {
593 switch (scope.getKind()) {
594 case EHScope::Catch: {
595 // Apply a special case to a single catch-all.
596 EHCatchScope &catchScope = cast<EHCatchScope>(scope);
597 if (catchScope.getNumHandlers() == 1 &&
598 catchScope.getHandler(0).isCatchAll()) {
599 dispatchBlock = catchScope.getHandler(0).Block;
600
601 // Otherwise, make a dispatch block.
602 } else {
603 dispatchBlock = createBasicBlock("catch.dispatch");
604 }
605 break;
606 }
607
608 case EHScope::Cleanup:
609 dispatchBlock = createBasicBlock("ehcleanup");
610 break;
611
612 case EHScope::Filter:
613 dispatchBlock = createBasicBlock("filter.dispatch");
614 break;
615
616 case EHScope::Terminate:
617 dispatchBlock = getTerminateHandler();
618 break;
David Majnemerdbf10452015-07-31 17:58:45 +0000619
Reid Kleckner2586aac2015-09-10 22:11:13 +0000620 case EHScope::PadEnd:
621 llvm_unreachable("PadEnd unnecessary for Itanium!");
John McCall8e4c74b2011-08-11 02:22:43 +0000622 }
623 scope.setCachedEHDispatchBlock(dispatchBlock);
624 }
625 return dispatchBlock;
626}
627
David Majnemerdbf10452015-07-31 17:58:45 +0000628llvm::BasicBlock *
629CodeGenFunction::getMSVCDispatchBlock(EHScopeStack::stable_iterator SI) {
630 // Returning nullptr indicates that the previous dispatch block should unwind
631 // to caller.
632 if (SI == EHStack.stable_end())
633 return nullptr;
634
635 // Otherwise, we should look at the actual scope.
636 EHScope &EHS = *EHStack.find(SI);
637
638 llvm::BasicBlock *DispatchBlock = EHS.getCachedEHDispatchBlock();
639 if (DispatchBlock)
640 return DispatchBlock;
641
642 if (EHS.getKind() == EHScope::Terminate)
Reid Kleckner06f19a02018-01-02 21:34:16 +0000643 DispatchBlock = getTerminateFunclet();
David Majnemerdbf10452015-07-31 17:58:45 +0000644 else
645 DispatchBlock = createBasicBlock();
John McCall7f416cc2015-09-08 08:05:57 +0000646 CGBuilderTy Builder(*this, DispatchBlock);
David Majnemerdbf10452015-07-31 17:58:45 +0000647
648 switch (EHS.getKind()) {
649 case EHScope::Catch:
650 DispatchBlock->setName("catch.dispatch");
651 break;
652
653 case EHScope::Cleanup:
654 DispatchBlock->setName("ehcleanup");
655 break;
656
657 case EHScope::Filter:
658 llvm_unreachable("exception specifications not handled yet!");
659
660 case EHScope::Terminate:
661 DispatchBlock->setName("terminate");
662 break;
663
Reid Kleckner2586aac2015-09-10 22:11:13 +0000664 case EHScope::PadEnd:
665 llvm_unreachable("PadEnd dispatch block missing!");
David Majnemerdbf10452015-07-31 17:58:45 +0000666 }
667 EHS.setCachedEHDispatchBlock(DispatchBlock);
668 return DispatchBlock;
669}
670
John McCallbd309292010-07-06 01:34:17 +0000671/// Check whether this is a non-EH scope, i.e. a scope which doesn't
672/// affect exception handling. Currently, the only non-EH scopes are
673/// normal-only cleanup scopes.
674static bool isNonEHScope(const EHScope &S) {
John McCall2b7fc382010-07-13 20:32:21 +0000675 switch (S.getKind()) {
John McCallcda666c2010-07-21 07:22:38 +0000676 case EHScope::Cleanup:
677 return !cast<EHCleanupScope>(S).isEHCleanup();
John McCall2b7fc382010-07-13 20:32:21 +0000678 case EHScope::Filter:
679 case EHScope::Catch:
680 case EHScope::Terminate:
Reid Kleckner2586aac2015-09-10 22:11:13 +0000681 case EHScope::PadEnd:
John McCall2b7fc382010-07-13 20:32:21 +0000682 return false;
683 }
684
David Blaikiee4d798f2012-01-20 21:50:17 +0000685 llvm_unreachable("Invalid EHScope Kind!");
John McCallbd309292010-07-06 01:34:17 +0000686}
687
688llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
689 assert(EHStack.requiresLandingPad());
690 assert(!EHStack.empty());
691
Reid Kleckner8f1b1f52016-03-01 19:51:48 +0000692 // If exceptions are disabled and SEH is not in use, then there is no invoke
693 // destination. SEH "works" even if exceptions are off. In practice, this
694 // means that C++ destructors and other EH cleanups don't run, which is
695 // consistent with MSVC's behavior.
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000696 const LangOptions &LO = CGM.getLangOpts();
697 if (!LO.Exceptions) {
698 if (!LO.Borland && !LO.MicrosoftExt)
699 return nullptr;
Reid Klecknere7b3f7c2015-02-11 00:00:21 +0000700 if (!currentFunctionUsesSEHTry())
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000701 return nullptr;
702 }
John McCall2b7fc382010-07-13 20:32:21 +0000703
Justin Lebar3e6449b2016-10-04 23:41:49 +0000704 // CUDA device code doesn't have exceptions.
705 if (LO.CUDA && LO.CUDAIsDevice)
706 return nullptr;
707
John McCallbd309292010-07-06 01:34:17 +0000708 // Check the innermost scope for a cached landing pad. If this is
709 // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
710 llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
711 if (LP) return LP;
712
David Majnemerdbf10452015-07-31 17:58:45 +0000713 const EHPersonality &Personality = EHPersonality::get(*this);
714
715 if (!CurFn->hasPersonalityFn())
716 CurFn->setPersonalityFn(getOpaquePersonalityFn(CGM, Personality));
717
Reid Kleckner129552b2015-10-08 01:13:52 +0000718 if (Personality.usesFuncletPads()) {
719 // We don't need separate landing pads in the funclet model.
David Majnemerdbf10452015-07-31 17:58:45 +0000720 LP = getEHDispatchBlock(EHStack.getInnermostEHScope());
721 } else {
722 // Build the landing pad for this scope.
723 LP = EmitLandingPad();
724 }
725
John McCallbd309292010-07-06 01:34:17 +0000726 assert(LP);
727
728 // Cache the landing pad on the innermost scope. If this is a
729 // non-EH scope, cache the landing pad on the enclosing scope, too.
730 for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
731 ir->setCachedLandingPad(LP);
732 if (!isNonEHScope(*ir)) break;
733 }
734
735 return LP;
736}
737
738llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
739 assert(EHStack.requiresLandingPad());
740
John McCall8e4c74b2011-08-11 02:22:43 +0000741 EHScope &innermostEHScope = *EHStack.find(EHStack.getInnermostEHScope());
742 switch (innermostEHScope.getKind()) {
743 case EHScope::Terminate:
744 return getTerminateLandingPad();
John McCallbd309292010-07-06 01:34:17 +0000745
Reid Kleckner2586aac2015-09-10 22:11:13 +0000746 case EHScope::PadEnd:
747 llvm_unreachable("PadEnd unnecessary for Itanium!");
David Majnemerdbf10452015-07-31 17:58:45 +0000748
John McCall8e4c74b2011-08-11 02:22:43 +0000749 case EHScope::Catch:
750 case EHScope::Cleanup:
751 case EHScope::Filter:
752 if (llvm::BasicBlock *lpad = innermostEHScope.getCachedLandingPad())
753 return lpad;
John McCallbd309292010-07-06 01:34:17 +0000754 }
755
756 // Save the current IR generation state.
John McCall8e4c74b2011-08-11 02:22:43 +0000757 CGBuilderTy::InsertPoint savedIP = Builder.saveAndClearIP();
Adrian Prantl95b24e92015-02-03 20:00:54 +0000758 auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, CurEHLocation);
John McCallbd309292010-07-06 01:34:17 +0000759
760 // Create and configure the landing pad.
John McCall8e4c74b2011-08-11 02:22:43 +0000761 llvm::BasicBlock *lpad = createBasicBlock("lpad");
762 EmitBlock(lpad);
John McCallbd309292010-07-06 01:34:17 +0000763
Serge Guelton1d993272017-05-09 19:31:30 +0000764 llvm::LandingPadInst *LPadInst =
765 Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty), 0);
Bill Wendlingf0724e82011-09-19 20:31:14 +0000766
767 llvm::Value *LPadExn = Builder.CreateExtractValue(LPadInst, 0);
768 Builder.CreateStore(LPadExn, getExceptionSlot());
769 llvm::Value *LPadSel = Builder.CreateExtractValue(LPadInst, 1);
770 Builder.CreateStore(LPadSel, getEHSelectorSlot());
771
John McCallbd309292010-07-06 01:34:17 +0000772 // Save the exception pointer. It's safe to use a single exception
773 // pointer per function because EH cleanups can never have nested
774 // try/catches.
Bill Wendlingf0724e82011-09-19 20:31:14 +0000775 // Build the landingpad instruction.
John McCallbd309292010-07-06 01:34:17 +0000776
777 // Accumulate all the handlers in scope.
John McCall8e4c74b2011-08-11 02:22:43 +0000778 bool hasCatchAll = false;
779 bool hasCleanup = false;
780 bool hasFilter = false;
781 SmallVector<llvm::Value*, 4> filterTypes;
782 llvm::SmallPtrSet<llvm::Value*, 4> catchTypes;
Nico Webere68b9f32015-02-25 16:25:00 +0000783 for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end(); I != E;
784 ++I) {
John McCallbd309292010-07-06 01:34:17 +0000785
786 switch (I->getKind()) {
John McCallcda666c2010-07-21 07:22:38 +0000787 case EHScope::Cleanup:
John McCall8e4c74b2011-08-11 02:22:43 +0000788 // If we have a cleanup, remember that.
789 hasCleanup = (hasCleanup || cast<EHCleanupScope>(*I).isEHCleanup());
John McCall2b7fc382010-07-13 20:32:21 +0000790 continue;
791
John McCallbd309292010-07-06 01:34:17 +0000792 case EHScope::Filter: {
793 assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
John McCall8e4c74b2011-08-11 02:22:43 +0000794 assert(!hasCatchAll && "EH filter reached after catch-all");
John McCallbd309292010-07-06 01:34:17 +0000795
Bill Wendlingf0724e82011-09-19 20:31:14 +0000796 // Filter scopes get added to the landingpad in weird ways.
John McCall8e4c74b2011-08-11 02:22:43 +0000797 EHFilterScope &filter = cast<EHFilterScope>(*I);
798 hasFilter = true;
John McCallbd309292010-07-06 01:34:17 +0000799
Bill Wendling8c4b7162011-09-22 20:32:54 +0000800 // Add all the filter values.
801 for (unsigned i = 0, e = filter.getNumFilters(); i != e; ++i)
802 filterTypes.push_back(filter.getFilter(i));
John McCallbd309292010-07-06 01:34:17 +0000803 goto done;
804 }
805
806 case EHScope::Terminate:
807 // Terminate scopes are basically catch-alls.
John McCall8e4c74b2011-08-11 02:22:43 +0000808 assert(!hasCatchAll);
809 hasCatchAll = true;
John McCallbd309292010-07-06 01:34:17 +0000810 goto done;
811
812 case EHScope::Catch:
813 break;
David Majnemerdbf10452015-07-31 17:58:45 +0000814
Reid Kleckner2586aac2015-09-10 22:11:13 +0000815 case EHScope::PadEnd:
816 llvm_unreachable("PadEnd unnecessary for Itanium!");
John McCallbd309292010-07-06 01:34:17 +0000817 }
818
John McCall8e4c74b2011-08-11 02:22:43 +0000819 EHCatchScope &catchScope = cast<EHCatchScope>(*I);
820 for (unsigned hi = 0, he = catchScope.getNumHandlers(); hi != he; ++hi) {
821 EHCatchScope::Handler handler = catchScope.getHandler(hi);
Reid Kleckner10aa7702015-09-16 20:15:55 +0000822 assert(handler.Type.Flags == 0 &&
823 "landingpads do not support catch handler flags");
John McCallbd309292010-07-06 01:34:17 +0000824
John McCall8e4c74b2011-08-11 02:22:43 +0000825 // If this is a catch-all, register that and abort.
Reid Kleckner10aa7702015-09-16 20:15:55 +0000826 if (!handler.Type.RTTI) {
John McCall8e4c74b2011-08-11 02:22:43 +0000827 assert(!hasCatchAll);
828 hasCatchAll = true;
829 goto done;
John McCallbd309292010-07-06 01:34:17 +0000830 }
831
832 // Check whether we already have a handler for this type.
Reid Kleckner10aa7702015-09-16 20:15:55 +0000833 if (catchTypes.insert(handler.Type.RTTI).second)
Bill Wendlingf0724e82011-09-19 20:31:14 +0000834 // If not, add it directly to the landingpad.
Reid Kleckner10aa7702015-09-16 20:15:55 +0000835 LPadInst->addClause(handler.Type.RTTI);
John McCallbd309292010-07-06 01:34:17 +0000836 }
John McCallbd309292010-07-06 01:34:17 +0000837 }
838
839 done:
Bill Wendlingf0724e82011-09-19 20:31:14 +0000840 // If we have a catch-all, add null to the landingpad.
John McCall8e4c74b2011-08-11 02:22:43 +0000841 assert(!(hasCatchAll && hasFilter));
842 if (hasCatchAll) {
Bill Wendlingf0724e82011-09-19 20:31:14 +0000843 LPadInst->addClause(getCatchAllValue(*this));
John McCallbd309292010-07-06 01:34:17 +0000844
845 // If we have an EH filter, we need to add those handlers in the
Bill Wendlingf0724e82011-09-19 20:31:14 +0000846 // right place in the landingpad, which is to say, at the end.
John McCall8e4c74b2011-08-11 02:22:43 +0000847 } else if (hasFilter) {
Bill Wendling58e58fe2011-09-19 22:08:36 +0000848 // Create a filter expression: a constant array indicating which filter
849 // types there are. The personality routine only lands here if the filter
850 // doesn't match.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000851 SmallVector<llvm::Constant*, 8> Filters;
Bill Wendlingf0724e82011-09-19 20:31:14 +0000852 llvm::ArrayType *AType =
853 llvm::ArrayType::get(!filterTypes.empty() ?
854 filterTypes[0]->getType() : Int8PtrTy,
855 filterTypes.size());
856
857 for (unsigned i = 0, e = filterTypes.size(); i != e; ++i)
858 Filters.push_back(cast<llvm::Constant>(filterTypes[i]));
859 llvm::Constant *FilterArray = llvm::ConstantArray::get(AType, Filters);
860 LPadInst->addClause(FilterArray);
John McCallbd309292010-07-06 01:34:17 +0000861
862 // Also check whether we need a cleanup.
Bill Wendlingf0724e82011-09-19 20:31:14 +0000863 if (hasCleanup)
864 LPadInst->setCleanup(true);
John McCallbd309292010-07-06 01:34:17 +0000865
866 // Otherwise, signal that we at least have cleanups.
Logan Chiene9c8ccb2014-07-01 11:47:10 +0000867 } else if (hasCleanup) {
868 LPadInst->setCleanup(true);
John McCallbd309292010-07-06 01:34:17 +0000869 }
870
Bill Wendlingf0724e82011-09-19 20:31:14 +0000871 assert((LPadInst->getNumClauses() > 0 || LPadInst->isCleanup()) &&
872 "landingpad instruction has no clauses!");
John McCallbd309292010-07-06 01:34:17 +0000873
874 // Tell the backend how to generate the landing pad.
John McCall8e4c74b2011-08-11 02:22:43 +0000875 Builder.CreateBr(getEHDispatchBlock(EHStack.getInnermostEHScope()));
John McCallbd309292010-07-06 01:34:17 +0000876
877 // Restore the old IR generation state.
John McCall8e4c74b2011-08-11 02:22:43 +0000878 Builder.restoreIP(savedIP);
John McCallbd309292010-07-06 01:34:17 +0000879
John McCall8e4c74b2011-08-11 02:22:43 +0000880 return lpad;
John McCallbd309292010-07-06 01:34:17 +0000881}
882
David Majnemer4e52d6f2015-12-12 05:39:21 +0000883static void emitCatchPadBlock(CodeGenFunction &CGF, EHCatchScope &CatchScope) {
David Majnemerdbf10452015-07-31 17:58:45 +0000884 llvm::BasicBlock *DispatchBlock = CatchScope.getCachedEHDispatchBlock();
885 assert(DispatchBlock);
886
887 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveIP();
888 CGF.EmitBlockAfterUses(DispatchBlock);
889
David Majnemer4e52d6f2015-12-12 05:39:21 +0000890 llvm::Value *ParentPad = CGF.CurrentFuncletPad;
891 if (!ParentPad)
892 ParentPad = llvm::ConstantTokenNone::get(CGF.getLLVMContext());
893 llvm::BasicBlock *UnwindBB =
894 CGF.getEHDispatchBlock(CatchScope.getEnclosingEHScope());
895
896 unsigned NumHandlers = CatchScope.getNumHandlers();
897 llvm::CatchSwitchInst *CatchSwitch =
898 CGF.Builder.CreateCatchSwitch(ParentPad, UnwindBB, NumHandlers);
David Majnemerdbf10452015-07-31 17:58:45 +0000899
900 // Test against each of the exception types we claim to catch.
David Majnemer4e52d6f2015-12-12 05:39:21 +0000901 for (unsigned I = 0; I < NumHandlers; ++I) {
David Majnemerdbf10452015-07-31 17:58:45 +0000902 const EHCatchScope::Handler &Handler = CatchScope.getHandler(I);
903
Reid Kleckner10aa7702015-09-16 20:15:55 +0000904 CatchTypeInfo TypeInfo = Handler.Type;
905 if (!TypeInfo.RTTI)
906 TypeInfo.RTTI = llvm::Constant::getNullValue(CGF.VoidPtrTy);
David Majnemerdbf10452015-07-31 17:58:45 +0000907
David Majnemer4e52d6f2015-12-12 05:39:21 +0000908 CGF.Builder.SetInsertPoint(Handler.Block);
David Majnemerdbf10452015-07-31 17:58:45 +0000909
910 if (EHPersonality::get(CGF).isMSVCXXPersonality()) {
David Majnemer4e52d6f2015-12-12 05:39:21 +0000911 CGF.Builder.CreateCatchPad(
912 CatchSwitch, {TypeInfo.RTTI, CGF.Builder.getInt32(TypeInfo.Flags),
913 llvm::Constant::getNullValue(CGF.VoidPtrTy)});
David Majnemerdbf10452015-07-31 17:58:45 +0000914 } else {
David Majnemer4e52d6f2015-12-12 05:39:21 +0000915 CGF.Builder.CreateCatchPad(CatchSwitch, {TypeInfo.RTTI});
David Majnemerdbf10452015-07-31 17:58:45 +0000916 }
917
David Majnemer4e52d6f2015-12-12 05:39:21 +0000918 CatchSwitch->addHandler(Handler.Block);
David Majnemerdbf10452015-07-31 17:58:45 +0000919 }
920 CGF.Builder.restoreIP(SavedIP);
David Majnemerdbf10452015-07-31 17:58:45 +0000921}
922
John McCall8e4c74b2011-08-11 02:22:43 +0000923/// Emit the structure of the dispatch block for the given catch scope.
924/// It is an invariant that the dispatch block already exists.
David Majnemer4e52d6f2015-12-12 05:39:21 +0000925static void emitCatchDispatchBlock(CodeGenFunction &CGF,
926 EHCatchScope &catchScope) {
Reid Kleckner129552b2015-10-08 01:13:52 +0000927 if (EHPersonality::get(CGF).usesFuncletPads())
928 return emitCatchPadBlock(CGF, catchScope);
David Majnemerdbf10452015-07-31 17:58:45 +0000929
John McCall8e4c74b2011-08-11 02:22:43 +0000930 llvm::BasicBlock *dispatchBlock = catchScope.getCachedEHDispatchBlock();
931 assert(dispatchBlock);
932
933 // If there's only a single catch-all, getEHDispatchBlock returned
934 // that catch-all as the dispatch block.
935 if (catchScope.getNumHandlers() == 1 &&
936 catchScope.getHandler(0).isCatchAll()) {
937 assert(dispatchBlock == catchScope.getHandler(0).Block);
David Majnemer4e52d6f2015-12-12 05:39:21 +0000938 return;
John McCall8e4c74b2011-08-11 02:22:43 +0000939 }
940
941 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveIP();
942 CGF.EmitBlockAfterUses(dispatchBlock);
943
944 // Select the right handler.
945 llvm::Value *llvm_eh_typeid_for =
946 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
947
948 // Load the selector value.
Bill Wendling79a70e42011-09-15 18:57:19 +0000949 llvm::Value *selector = CGF.getSelectorFromSlot();
John McCall8e4c74b2011-08-11 02:22:43 +0000950
951 // Test against each of the exception types we claim to catch.
952 for (unsigned i = 0, e = catchScope.getNumHandlers(); ; ++i) {
953 assert(i < e && "ran off end of handlers!");
954 const EHCatchScope::Handler &handler = catchScope.getHandler(i);
955
Reid Kleckner10aa7702015-09-16 20:15:55 +0000956 llvm::Value *typeValue = handler.Type.RTTI;
957 assert(handler.Type.Flags == 0 &&
958 "landingpads do not support catch handler flags");
John McCall8e4c74b2011-08-11 02:22:43 +0000959 assert(typeValue && "fell into catch-all case!");
960 typeValue = CGF.Builder.CreateBitCast(typeValue, CGF.Int8PtrTy);
961
962 // Figure out the next block.
963 bool nextIsEnd;
964 llvm::BasicBlock *nextBlock;
965
966 // If this is the last handler, we're at the end, and the next
967 // block is the block for the enclosing EH scope.
968 if (i + 1 == e) {
969 nextBlock = CGF.getEHDispatchBlock(catchScope.getEnclosingEHScope());
970 nextIsEnd = true;
971
972 // If the next handler is a catch-all, we're at the end, and the
973 // next block is that handler.
974 } else if (catchScope.getHandler(i+1).isCatchAll()) {
975 nextBlock = catchScope.getHandler(i+1).Block;
976 nextIsEnd = true;
977
978 // Otherwise, we're not at the end and we need a new block.
979 } else {
980 nextBlock = CGF.createBasicBlock("catch.fallthrough");
981 nextIsEnd = false;
982 }
983
984 // Figure out the catch type's index in the LSDA's type table.
985 llvm::CallInst *typeIndex =
986 CGF.Builder.CreateCall(llvm_eh_typeid_for, typeValue);
987 typeIndex->setDoesNotThrow();
988
989 llvm::Value *matchesTypeIndex =
990 CGF.Builder.CreateICmpEQ(selector, typeIndex, "matches");
991 CGF.Builder.CreateCondBr(matchesTypeIndex, handler.Block, nextBlock);
992
993 // If the next handler is a catch-all, we're completely done.
994 if (nextIsEnd) {
995 CGF.Builder.restoreIP(savedIP);
David Majnemer4e52d6f2015-12-12 05:39:21 +0000996 return;
John McCall8e4c74b2011-08-11 02:22:43 +0000997 }
Ahmed Charles289896d2012-02-19 11:57:29 +0000998 // Otherwise we need to emit and continue at that block.
999 CGF.EmitBlock(nextBlock);
John McCall8e4c74b2011-08-11 02:22:43 +00001000 }
John McCall8e4c74b2011-08-11 02:22:43 +00001001}
1002
1003void CodeGenFunction::popCatchScope() {
1004 EHCatchScope &catchScope = cast<EHCatchScope>(*EHStack.begin());
1005 if (catchScope.hasEHBranches())
1006 emitCatchDispatchBlock(*this, catchScope);
1007 EHStack.popCatch();
1008}
1009
John McCallb609d3f2010-07-07 06:56:46 +00001010void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallbd309292010-07-06 01:34:17 +00001011 unsigned NumHandlers = S.getNumHandlers();
1012 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1013 assert(CatchScope.getNumHandlers() == NumHandlers);
Mike Stump58ef18b2009-11-20 23:44:51 +00001014
John McCall8e4c74b2011-08-11 02:22:43 +00001015 // If the catch was not required, bail out now.
1016 if (!CatchScope.hasEHBranches()) {
Kostya Serebryanyba4aced2014-01-09 09:22:32 +00001017 CatchScope.clearHandlerBlocks();
John McCall8e4c74b2011-08-11 02:22:43 +00001018 EHStack.popCatch();
1019 return;
1020 }
1021
1022 // Emit the structure of the EH dispatch for this catch.
David Majnemer4e52d6f2015-12-12 05:39:21 +00001023 emitCatchDispatchBlock(*this, CatchScope);
John McCall8e4c74b2011-08-11 02:22:43 +00001024
John McCallbd309292010-07-06 01:34:17 +00001025 // Copy the handler blocks off before we pop the EH stack. Emitting
1026 // the handlers might scribble on this memory.
Benjamin Kramerda32cf82015-08-04 15:38:49 +00001027 SmallVector<EHCatchScope::Handler, 8> Handlers(
1028 CatchScope.begin(), CatchScope.begin() + NumHandlers);
John McCall8e4c74b2011-08-11 02:22:43 +00001029
John McCallbd309292010-07-06 01:34:17 +00001030 EHStack.popCatch();
Mike Stump58ef18b2009-11-20 23:44:51 +00001031
John McCallbd309292010-07-06 01:34:17 +00001032 // The fall-through block.
1033 llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
Mike Stump58ef18b2009-11-20 23:44:51 +00001034
John McCallbd309292010-07-06 01:34:17 +00001035 // We just emitted the body of the try; jump to the continue block.
1036 if (HaveInsertPoint())
1037 Builder.CreateBr(ContBB);
Mike Stump97329152009-12-02 19:53:57 +00001038
John McCalld8d00be2012-06-15 05:27:05 +00001039 // Determine if we need an implicit rethrow for all these catch handlers;
1040 // see the comment below.
1041 bool doImplicitRethrow = false;
John McCallb609d3f2010-07-07 06:56:46 +00001042 if (IsFnTryBlock)
John McCalld8d00be2012-06-15 05:27:05 +00001043 doImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
1044 isa<CXXConstructorDecl>(CurCodeDecl);
John McCallb609d3f2010-07-07 06:56:46 +00001045
John McCall8e4c74b2011-08-11 02:22:43 +00001046 // Perversely, we emit the handlers backwards precisely because we
1047 // want them to appear in source order. In all of these cases, the
1048 // catch block will have exactly one predecessor, which will be a
1049 // particular block in the catch dispatch. However, in the case of
1050 // a catch-all, one of the dispatch blocks will branch to two
1051 // different handlers, and EmitBlockAfterUses will cause the second
1052 // handler to be moved before the first.
1053 for (unsigned I = NumHandlers; I != 0; --I) {
1054 llvm::BasicBlock *CatchBlock = Handlers[I-1].Block;
1055 EmitBlockAfterUses(CatchBlock);
Mike Stump75546b82009-12-10 00:06:18 +00001056
John McCallbd309292010-07-06 01:34:17 +00001057 // Catch the exception if this isn't a catch-all.
John McCall8e4c74b2011-08-11 02:22:43 +00001058 const CXXCatchStmt *C = S.getHandler(I-1);
Mike Stump58ef18b2009-11-20 23:44:51 +00001059
John McCallbd309292010-07-06 01:34:17 +00001060 // Enter a cleanup scope, including the catch variable and the
1061 // end-catch.
1062 RunCleanupsScope CatchScope(*this);
Mike Stump58ef18b2009-11-20 23:44:51 +00001063
John McCallbd309292010-07-06 01:34:17 +00001064 // Initialize the catch variable and set up the cleanups.
David Majnemer4e52d6f2015-12-12 05:39:21 +00001065 SaveAndRestore<llvm::Instruction *> RestoreCurrentFuncletPad(
1066 CurrentFuncletPad);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00001067 CGM.getCXXABI().emitBeginCatch(*this, C);
John McCallbd309292010-07-06 01:34:17 +00001068
Justin Bognerea278c32014-01-07 00:20:28 +00001069 // Emit the PGO counter increment.
Justin Bogner66242d62015-04-23 23:06:47 +00001070 incrementProfileCounter(C);
Justin Bogneref512b92014-01-06 22:27:43 +00001071
John McCallbd309292010-07-06 01:34:17 +00001072 // Perform the body of the catch.
1073 EmitStmt(C->getHandlerBlock());
1074
John McCalld8d00be2012-06-15 05:27:05 +00001075 // [except.handle]p11:
1076 // The currently handled exception is rethrown if control
1077 // reaches the end of a handler of the function-try-block of a
1078 // constructor or destructor.
1079
1080 // It is important that we only do this on fallthrough and not on
1081 // return. Note that it's illegal to put a return in a
1082 // constructor function-try-block's catch handler (p14), so this
1083 // really only applies to destructors.
1084 if (doImplicitRethrow && HaveInsertPoint()) {
David Majnemer442d0a22014-11-25 07:20:20 +00001085 CGM.getCXXABI().emitRethrow(*this, /*isNoReturn*/false);
John McCalld8d00be2012-06-15 05:27:05 +00001086 Builder.CreateUnreachable();
1087 Builder.ClearInsertionPoint();
1088 }
1089
John McCallbd309292010-07-06 01:34:17 +00001090 // Fall out through the catch cleanups.
1091 CatchScope.ForceCleanup();
1092
1093 // Branch out of the try.
1094 if (HaveInsertPoint())
1095 Builder.CreateBr(ContBB);
Mike Stump58ef18b2009-11-20 23:44:51 +00001096 }
1097
John McCallbd309292010-07-06 01:34:17 +00001098 EmitBlock(ContBB);
Justin Bogner66242d62015-04-23 23:06:47 +00001099 incrementProfileCounter(&S);
Mike Stump58ef18b2009-11-20 23:44:51 +00001100}
Mike Stumpaff69af2009-12-09 03:35:49 +00001101
John McCall1e670402010-07-21 00:52:03 +00001102namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001103 struct CallEndCatchForFinally final : EHScopeStack::Cleanup {
John McCall1e670402010-07-21 00:52:03 +00001104 llvm::Value *ForEHVar;
1105 llvm::Value *EndCatchFn;
1106 CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn)
1107 : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
1108
Craig Topper4f12f102014-03-12 06:41:41 +00001109 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall1e670402010-07-21 00:52:03 +00001110 llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
1111 llvm::BasicBlock *CleanupContBB =
1112 CGF.createBasicBlock("finally.cleanup.cont");
1113
1114 llvm::Value *ShouldEndCatch =
John McCall7f416cc2015-09-08 08:05:57 +00001115 CGF.Builder.CreateFlagLoad(ForEHVar, "finally.endcatch");
John McCall1e670402010-07-21 00:52:03 +00001116 CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1117 CGF.EmitBlock(EndCatchBB);
John McCall882987f2013-02-28 19:01:20 +00001118 CGF.EmitRuntimeCallOrInvoke(EndCatchFn); // catch-all, so might throw
John McCall1e670402010-07-21 00:52:03 +00001119 CGF.EmitBlock(CleanupContBB);
1120 }
1121 };
John McCall906da4b2010-07-21 05:47:49 +00001122
David Blaikie7e70d682015-08-18 22:40:54 +00001123 struct PerformFinally final : EHScopeStack::Cleanup {
John McCall906da4b2010-07-21 05:47:49 +00001124 const Stmt *Body;
1125 llvm::Value *ForEHVar;
1126 llvm::Value *EndCatchFn;
1127 llvm::Value *RethrowFn;
1128 llvm::Value *SavedExnVar;
1129
1130 PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
1131 llvm::Value *EndCatchFn,
1132 llvm::Value *RethrowFn, llvm::Value *SavedExnVar)
1133 : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1134 RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
1135
Craig Topper4f12f102014-03-12 06:41:41 +00001136 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall906da4b2010-07-21 05:47:49 +00001137 // Enter a cleanup to call the end-catch function if one was provided.
1138 if (EndCatchFn)
John McCallcda666c2010-07-21 07:22:38 +00001139 CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
1140 ForEHVar, EndCatchFn);
John McCall906da4b2010-07-21 05:47:49 +00001141
John McCallcebe0ca2010-08-11 00:16:14 +00001142 // Save the current cleanup destination in case there are
1143 // cleanups in the finally block.
1144 llvm::Value *SavedCleanupDest =
1145 CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
1146 "cleanup.dest.saved");
1147
John McCall906da4b2010-07-21 05:47:49 +00001148 // Emit the finally block.
1149 CGF.EmitStmt(Body);
1150
1151 // If the end of the finally is reachable, check whether this was
1152 // for EH. If so, rethrow.
1153 if (CGF.HaveInsertPoint()) {
1154 llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
1155 llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
1156
1157 llvm::Value *ShouldRethrow =
John McCall7f416cc2015-09-08 08:05:57 +00001158 CGF.Builder.CreateFlagLoad(ForEHVar, "finally.shouldthrow");
John McCall906da4b2010-07-21 05:47:49 +00001159 CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1160
1161 CGF.EmitBlock(RethrowBB);
1162 if (SavedExnVar) {
John McCall882987f2013-02-28 19:01:20 +00001163 CGF.EmitRuntimeCallOrInvoke(RethrowFn,
John McCall7f416cc2015-09-08 08:05:57 +00001164 CGF.Builder.CreateAlignedLoad(SavedExnVar, CGF.getPointerAlign()));
John McCall906da4b2010-07-21 05:47:49 +00001165 } else {
John McCall882987f2013-02-28 19:01:20 +00001166 CGF.EmitRuntimeCallOrInvoke(RethrowFn);
John McCall906da4b2010-07-21 05:47:49 +00001167 }
1168 CGF.Builder.CreateUnreachable();
1169
1170 CGF.EmitBlock(ContBB);
John McCallcebe0ca2010-08-11 00:16:14 +00001171
1172 // Restore the cleanup destination.
1173 CGF.Builder.CreateStore(SavedCleanupDest,
1174 CGF.getNormalCleanupDestSlot());
John McCall906da4b2010-07-21 05:47:49 +00001175 }
1176
1177 // Leave the end-catch cleanup. As an optimization, pretend that
1178 // the fallthrough path was inaccessible; we've dynamically proven
1179 // that we're not in the EH case along that path.
1180 if (EndCatchFn) {
1181 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1182 CGF.PopCleanupBlock();
1183 CGF.Builder.restoreIP(SavedIP);
1184 }
1185
1186 // Now make sure we actually have an insertion point or the
1187 // cleanup gods will hate us.
1188 CGF.EnsureInsertPoint();
1189 }
1190 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00001191} // end anonymous namespace
John McCall1e670402010-07-21 00:52:03 +00001192
John McCallbd309292010-07-06 01:34:17 +00001193/// Enters a finally block for an implementation using zero-cost
1194/// exceptions. This is mostly general, but hard-codes some
1195/// language/ABI-specific behavior in the catch-all sections.
John McCall6b0feb72011-06-22 02:32:12 +00001196void CodeGenFunction::FinallyInfo::enter(CodeGenFunction &CGF,
1197 const Stmt *body,
1198 llvm::Constant *beginCatchFn,
1199 llvm::Constant *endCatchFn,
1200 llvm::Constant *rethrowFn) {
Craig Topper8a13c412014-05-21 05:09:00 +00001201 assert((beginCatchFn != nullptr) == (endCatchFn != nullptr) &&
John McCallbd309292010-07-06 01:34:17 +00001202 "begin/end catch functions not paired");
John McCall6b0feb72011-06-22 02:32:12 +00001203 assert(rethrowFn && "rethrow function is required");
1204
1205 BeginCatchFn = beginCatchFn;
Mike Stumpaff69af2009-12-09 03:35:49 +00001206
John McCallbd309292010-07-06 01:34:17 +00001207 // The rethrow function has one of the following two types:
1208 // void (*)()
1209 // void (*)(void*)
1210 // In the latter case we need to pass it the exception object.
1211 // But we can't use the exception slot because the @finally might
1212 // have a landing pad (which would overwrite the exception slot).
Chris Lattner2192fe52011-07-18 04:24:23 +00001213 llvm::FunctionType *rethrowFnTy =
John McCallbd309292010-07-06 01:34:17 +00001214 cast<llvm::FunctionType>(
John McCall6b0feb72011-06-22 02:32:12 +00001215 cast<llvm::PointerType>(rethrowFn->getType())->getElementType());
Craig Topper8a13c412014-05-21 05:09:00 +00001216 SavedExnVar = nullptr;
John McCall6b0feb72011-06-22 02:32:12 +00001217 if (rethrowFnTy->getNumParams())
1218 SavedExnVar = CGF.CreateTempAlloca(CGF.Int8PtrTy, "finally.exn");
Mike Stumpaff69af2009-12-09 03:35:49 +00001219
John McCallbd309292010-07-06 01:34:17 +00001220 // A finally block is a statement which must be executed on any edge
1221 // out of a given scope. Unlike a cleanup, the finally block may
1222 // contain arbitrary control flow leading out of itself. In
1223 // addition, finally blocks should always be executed, even if there
1224 // are no catch handlers higher on the stack. Therefore, we
1225 // surround the protected scope with a combination of a normal
1226 // cleanup (to catch attempts to break out of the block via normal
1227 // control flow) and an EH catch-all (semantically "outside" any try
1228 // statement to which the finally block might have been attached).
1229 // The finally block itself is generated in the context of a cleanup
1230 // which conditionally leaves the catch-all.
John McCall21886962010-04-21 10:05:39 +00001231
John McCallbd309292010-07-06 01:34:17 +00001232 // Jump destination for performing the finally block on an exception
1233 // edge. We'll never actually reach this block, so unreachable is
1234 // fine.
John McCall6b0feb72011-06-22 02:32:12 +00001235 RethrowDest = CGF.getJumpDestInCurrentScope(CGF.getUnreachableBlock());
John McCall21886962010-04-21 10:05:39 +00001236
John McCallbd309292010-07-06 01:34:17 +00001237 // Whether the finally block is being executed for EH purposes.
John McCall6b0feb72011-06-22 02:32:12 +00001238 ForEHVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "finally.for-eh");
John McCall7f416cc2015-09-08 08:05:57 +00001239 CGF.Builder.CreateFlagStore(false, ForEHVar);
Mike Stumpaff69af2009-12-09 03:35:49 +00001240
John McCallbd309292010-07-06 01:34:17 +00001241 // Enter a normal cleanup which will perform the @finally block.
John McCall6b0feb72011-06-22 02:32:12 +00001242 CGF.EHStack.pushCleanup<PerformFinally>(NormalCleanup, body,
1243 ForEHVar, endCatchFn,
1244 rethrowFn, SavedExnVar);
John McCallbd309292010-07-06 01:34:17 +00001245
1246 // Enter a catch-all scope.
John McCall6b0feb72011-06-22 02:32:12 +00001247 llvm::BasicBlock *catchBB = CGF.createBasicBlock("finally.catchall");
1248 EHCatchScope *catchScope = CGF.EHStack.pushCatch(1);
1249 catchScope->setCatchAllHandler(0, catchBB);
John McCallbd309292010-07-06 01:34:17 +00001250}
1251
John McCall6b0feb72011-06-22 02:32:12 +00001252void CodeGenFunction::FinallyInfo::exit(CodeGenFunction &CGF) {
John McCallbd309292010-07-06 01:34:17 +00001253 // Leave the finally catch-all.
John McCall6b0feb72011-06-22 02:32:12 +00001254 EHCatchScope &catchScope = cast<EHCatchScope>(*CGF.EHStack.begin());
1255 llvm::BasicBlock *catchBB = catchScope.getHandler(0).Block;
John McCall8e4c74b2011-08-11 02:22:43 +00001256
1257 CGF.popCatchScope();
John McCallbd309292010-07-06 01:34:17 +00001258
John McCall6b0feb72011-06-22 02:32:12 +00001259 // If there are any references to the catch-all block, emit it.
1260 if (catchBB->use_empty()) {
1261 delete catchBB;
1262 } else {
1263 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveAndClearIP();
1264 CGF.EmitBlock(catchBB);
John McCallbd309292010-07-06 01:34:17 +00001265
Craig Topper8a13c412014-05-21 05:09:00 +00001266 llvm::Value *exn = nullptr;
John McCallbd309292010-07-06 01:34:17 +00001267
John McCall6b0feb72011-06-22 02:32:12 +00001268 // If there's a begin-catch function, call it.
1269 if (BeginCatchFn) {
Bill Wendling79a70e42011-09-15 18:57:19 +00001270 exn = CGF.getExceptionFromSlot();
John McCall882987f2013-02-28 19:01:20 +00001271 CGF.EmitNounwindRuntimeCall(BeginCatchFn, exn);
John McCall6b0feb72011-06-22 02:32:12 +00001272 }
1273
1274 // If we need to remember the exception pointer to rethrow later, do so.
1275 if (SavedExnVar) {
Bill Wendling79a70e42011-09-15 18:57:19 +00001276 if (!exn) exn = CGF.getExceptionFromSlot();
John McCall7f416cc2015-09-08 08:05:57 +00001277 CGF.Builder.CreateAlignedStore(exn, SavedExnVar, CGF.getPointerAlign());
John McCall6b0feb72011-06-22 02:32:12 +00001278 }
1279
1280 // Tell the cleanups in the finally block that we're do this for EH.
John McCall7f416cc2015-09-08 08:05:57 +00001281 CGF.Builder.CreateFlagStore(true, ForEHVar);
John McCall6b0feb72011-06-22 02:32:12 +00001282
1283 // Thread a jump through the finally cleanup.
1284 CGF.EmitBranchThroughCleanup(RethrowDest);
1285
1286 CGF.Builder.restoreIP(savedIP);
1287 }
1288
1289 // Finally, leave the @finally cleanup.
1290 CGF.PopCleanupBlock();
John McCallbd309292010-07-06 01:34:17 +00001291}
1292
1293llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
1294 if (TerminateLandingPad)
1295 return TerminateLandingPad;
1296
1297 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1298
1299 // This will get inserted at the end of the function.
1300 TerminateLandingPad = createBasicBlock("terminate.lpad");
1301 Builder.SetInsertPoint(TerminateLandingPad);
1302
1303 // Tell the backend that this is a landing pad.
Reid Klecknerdeeddec2015-02-05 18:56:03 +00001304 const EHPersonality &Personality = EHPersonality::get(*this);
David Majnemerfcbdb6e2015-06-17 20:53:19 +00001305
1306 if (!CurFn->hasPersonalityFn())
1307 CurFn->setPersonalityFn(getOpaquePersonalityFn(CGM, Personality));
1308
Serge Guelton1d993272017-05-09 19:31:30 +00001309 llvm::LandingPadInst *LPadInst =
1310 Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty), 0);
Bill Wendlingf0724e82011-09-19 20:31:14 +00001311 LPadInst->addClause(getCatchAllValue(*this));
John McCallbd309292010-07-06 01:34:17 +00001312
Hans Wennborgdcfba332015-10-06 23:40:43 +00001313 llvm::Value *Exn = nullptr;
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00001314 if (getLangOpts().CPlusPlus)
1315 Exn = Builder.CreateExtractValue(LPadInst, 0);
1316 llvm::CallInst *terminateCall =
1317 CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
John McCalle142ad52013-02-12 03:51:46 +00001318 terminateCall->setDoesNotReturn();
John McCallad7c5c12011-02-08 08:22:06 +00001319 Builder.CreateUnreachable();
Mike Stumpaff69af2009-12-09 03:35:49 +00001320
John McCallbd309292010-07-06 01:34:17 +00001321 // Restore the saved insertion state.
1322 Builder.restoreIP(SavedIP);
John McCalldac3ea62010-04-30 00:06:43 +00001323
John McCallbd309292010-07-06 01:34:17 +00001324 return TerminateLandingPad;
Mike Stumpaff69af2009-12-09 03:35:49 +00001325}
Mike Stump2b488872009-12-09 22:59:31 +00001326
1327llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
Mike Stumpf5cbb082009-12-10 00:02:42 +00001328 if (TerminateHandler)
1329 return TerminateHandler;
1330
John McCallbd309292010-07-06 01:34:17 +00001331 // Set up the terminate handler. This block is inserted at the very
1332 // end of the function by FinishFunction.
Mike Stumpf5cbb082009-12-10 00:02:42 +00001333 TerminateHandler = createBasicBlock("terminate.handler");
Reid Kleckner06f19a02018-01-02 21:34:16 +00001334 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
John McCallbd309292010-07-06 01:34:17 +00001335 Builder.SetInsertPoint(TerminateHandler);
Reid Kleckner06f19a02018-01-02 21:34:16 +00001336
David Majnemerfeeefb22015-12-14 18:34:18 +00001337 llvm::Value *Exn = nullptr;
Reid Kleckner06f19a02018-01-02 21:34:16 +00001338 if (getLangOpts().CPlusPlus)
1339 Exn = getExceptionFromSlot();
David Majnemerfeeefb22015-12-14 18:34:18 +00001340 llvm::CallInst *terminateCall =
1341 CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
1342 terminateCall->setDoesNotReturn();
1343 Builder.CreateUnreachable();
Mike Stump2b488872009-12-09 22:59:31 +00001344
John McCall21886962010-04-21 10:05:39 +00001345 // Restore the saved insertion state.
John McCallbd309292010-07-06 01:34:17 +00001346 Builder.restoreIP(SavedIP);
Mike Stump25b20fc2009-12-09 23:31:35 +00001347
Mike Stump2b488872009-12-09 22:59:31 +00001348 return TerminateHandler;
1349}
John McCallbd309292010-07-06 01:34:17 +00001350
Reid Kleckner06f19a02018-01-02 21:34:16 +00001351llvm::BasicBlock *CodeGenFunction::getTerminateFunclet() {
1352 assert(EHPersonality::get(*this).usesFuncletPads() &&
1353 "use getTerminateLandingPad for non-funclet EH");
1354
1355 llvm::BasicBlock *&TerminateFunclet = TerminateFunclets[CurrentFuncletPad];
1356 if (TerminateFunclet)
1357 return TerminateFunclet;
1358
1359 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1360
1361 // Set up the terminate handler. This block is inserted at the very
1362 // end of the function by FinishFunction.
1363 TerminateFunclet = createBasicBlock("terminate.handler");
1364 Builder.SetInsertPoint(TerminateFunclet);
1365
1366 // Create the cleanuppad using the current parent pad as its token. Use 'none'
1367 // if this is a top-level terminate scope, which is the common case.
1368 SaveAndRestore<llvm::Instruction *> RestoreCurrentFuncletPad(
1369 CurrentFuncletPad);
1370 llvm::Value *ParentPad = CurrentFuncletPad;
1371 if (!ParentPad)
1372 ParentPad = llvm::ConstantTokenNone::get(CGM.getLLVMContext());
1373 CurrentFuncletPad = Builder.CreateCleanupPad(ParentPad);
1374
1375 // Emit the __std_terminate call.
1376 llvm::CallInst *terminateCall =
1377 CGM.getCXXABI().emitTerminateForUnexpectedException(*this, nullptr);
1378 terminateCall->setDoesNotReturn();
1379 Builder.CreateUnreachable();
1380
1381 // Restore the saved insertion state.
1382 Builder.restoreIP(SavedIP);
1383
1384 return TerminateFunclet;
1385}
1386
David Chisnall9a837be2012-11-07 16:50:40 +00001387llvm::BasicBlock *CodeGenFunction::getEHResumeBlock(bool isCleanup) {
John McCall8e4c74b2011-08-11 02:22:43 +00001388 if (EHResumeBlock) return EHResumeBlock;
John McCallad5d61e2010-07-23 21:56:41 +00001389
1390 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1391
1392 // We emit a jump to a notional label at the outermost unwind state.
John McCall8e4c74b2011-08-11 02:22:43 +00001393 EHResumeBlock = createBasicBlock("eh.resume");
1394 Builder.SetInsertPoint(EHResumeBlock);
John McCallad5d61e2010-07-23 21:56:41 +00001395
Reid Klecknerdeeddec2015-02-05 18:56:03 +00001396 const EHPersonality &Personality = EHPersonality::get(*this);
John McCallad5d61e2010-07-23 21:56:41 +00001397
1398 // This can always be a call because we necessarily didn't find
1399 // anything on the EH stack which needs our help.
Benjamin Kramer793bd552012-02-08 12:41:24 +00001400 const char *RethrowName = Personality.CatchallRethrowFn;
Craig Topper8a13c412014-05-21 05:09:00 +00001401 if (RethrowName != nullptr && !isCleanup) {
John McCall882987f2013-02-28 19:01:20 +00001402 EmitRuntimeCall(getCatchallRethrowFn(CGM, RethrowName),
Nico Weberff62a6a2015-02-26 22:34:33 +00001403 getExceptionFromSlot())->setDoesNotReturn();
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001404 Builder.CreateUnreachable();
1405 Builder.restoreIP(SavedIP);
1406 return EHResumeBlock;
John McCall9b382dd2011-05-28 21:13:02 +00001407 }
1408
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001409 // Recreate the landingpad's return value for the 'resume' instruction.
1410 llvm::Value *Exn = getExceptionFromSlot();
1411 llvm::Value *Sel = getSelectorFromSlot();
John McCallad5d61e2010-07-23 21:56:41 +00001412
Serge Guelton1d993272017-05-09 19:31:30 +00001413 llvm::Type *LPadType = llvm::StructType::get(Exn->getType(), Sel->getType());
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001414 llvm::Value *LPadVal = llvm::UndefValue::get(LPadType);
1415 LPadVal = Builder.CreateInsertValue(LPadVal, Exn, 0, "lpad.val");
1416 LPadVal = Builder.CreateInsertValue(LPadVal, Sel, 1, "lpad.val");
1417
1418 Builder.CreateResume(LPadVal);
John McCallad5d61e2010-07-23 21:56:41 +00001419 Builder.restoreIP(SavedIP);
John McCall8e4c74b2011-08-11 02:22:43 +00001420 return EHResumeBlock;
John McCallad5d61e2010-07-23 21:56:41 +00001421}
Reid Kleckner543a16c2013-09-16 21:46:30 +00001422
1423void CodeGenFunction::EmitSEHTryStmt(const SEHTryStmt &S) {
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001424 EnterSEHTryStmt(S);
Reid Klecknera5930002015-02-11 21:40:48 +00001425 {
Nico Weber5779f842015-02-12 23:16:11 +00001426 JumpDest TryExit = getJumpDestInCurrentScope("__try.__leave");
Nico Weber5779f842015-02-12 23:16:11 +00001427
Reid Kleckner11c033e2015-02-12 23:40:45 +00001428 SEHTryEpilogueStack.push_back(&TryExit);
Reid Klecknera5930002015-02-11 21:40:48 +00001429 EmitStmt(S.getTryBlock());
Reid Kleckner11c033e2015-02-12 23:40:45 +00001430 SEHTryEpilogueStack.pop_back();
Nico Weber5779f842015-02-12 23:16:11 +00001431
1432 if (!TryExit.getBlock()->use_empty())
1433 EmitBlock(TryExit.getBlock(), /*IsFinished=*/true);
1434 else
1435 delete TryExit.getBlock();
Reid Klecknera5930002015-02-11 21:40:48 +00001436 }
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001437 ExitSEHTryStmt(S);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001438}
1439
1440namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001441struct PerformSEHFinally final : EHScopeStack::Cleanup {
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001442 llvm::Function *OutlinedFinally;
Reid Kleckner55391522015-10-08 21:14:56 +00001443 PerformSEHFinally(llvm::Function *OutlinedFinally)
1444 : OutlinedFinally(OutlinedFinally) {}
Reid Kleckneraca01db2015-02-04 22:37:07 +00001445
Reid Kleckner1d59f992015-01-22 01:36:17 +00001446 void Emit(CodeGenFunction &CGF, Flags F) override {
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001447 ASTContext &Context = CGF.getContext();
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001448 CodeGenModule &CGM = CGF.CGM;
Reid Kleckner65870442015-06-09 17:47:50 +00001449
Reid Klecknerd0d9a1f2015-07-01 17:10:10 +00001450 CallArgList Args;
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001451
1452 // Compute the two argument values.
1453 QualType ArgTys[2] = {Context.UnsignedCharTy, Context.VoidPtrTy};
Reid Kleckner15d152d2015-07-07 23:23:31 +00001454 llvm::Value *LocalAddrFn = CGM.getIntrinsic(llvm::Intrinsic::localaddress);
David Blaikie4ba525b2015-07-14 17:27:39 +00001455 llvm::Value *FP = CGF.Builder.CreateCall(LocalAddrFn);
Reid Klecknereb11c412015-07-01 21:00:00 +00001456 llvm::Value *IsForEH =
1457 llvm::ConstantInt::get(CGF.ConvertType(ArgTys[0]), F.isForEHCleanup());
1458 Args.add(RValue::get(IsForEH), ArgTys[0]);
1459 Args.add(RValue::get(FP), ArgTys[1]);
Reid Klecknerd0d9a1f2015-07-01 17:10:10 +00001460
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001461 // Arrange a two-arg function info and type.
Reid Klecknereb11c412015-07-01 21:00:00 +00001462 const CGFunctionInfo &FnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00001463 CGM.getTypes().arrangeBuiltinFunctionCall(Context.VoidTy, Args);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001464
John McCallb92ab1a2016-10-26 23:46:34 +00001465 auto Callee = CGCallee::forDirect(OutlinedFinally);
1466 CGF.EmitCall(FnInfo, Callee, ReturnValueSlot(), Args);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001467 }
1468};
Hans Wennborgdcfba332015-10-06 23:40:43 +00001469} // end anonymous namespace
Reid Kleckner1d59f992015-01-22 01:36:17 +00001470
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001471namespace {
1472/// Find all local variable captures in the statement.
1473struct CaptureFinder : ConstStmtVisitor<CaptureFinder> {
1474 CodeGenFunction &ParentCGF;
1475 const VarDecl *ParentThis;
John McCall0a490152015-09-08 21:15:22 +00001476 llvm::SmallSetVector<const VarDecl *, 4> Captures;
John McCall7f416cc2015-09-08 08:05:57 +00001477 Address SEHCodeSlot = Address::invalid();
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001478 CaptureFinder(CodeGenFunction &ParentCGF, const VarDecl *ParentThis)
1479 : ParentCGF(ParentCGF), ParentThis(ParentThis) {}
1480
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001481 // Return true if we need to do any capturing work.
1482 bool foundCaptures() {
John McCall7f416cc2015-09-08 08:05:57 +00001483 return !Captures.empty() || SEHCodeSlot.isValid();
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001484 }
1485
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001486 void Visit(const Stmt *S) {
1487 // See if this is a capture, then recurse.
1488 ConstStmtVisitor<CaptureFinder>::Visit(S);
1489 for (const Stmt *Child : S->children())
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001490 if (Child)
1491 Visit(Child);
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001492 }
1493
1494 void VisitDeclRefExpr(const DeclRefExpr *E) {
1495 // If this is already a capture, just make sure we capture 'this'.
1496 if (E->refersToEnclosingVariableOrCapture()) {
John McCall0a490152015-09-08 21:15:22 +00001497 Captures.insert(ParentThis);
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001498 return;
1499 }
1500
1501 const auto *D = dyn_cast<VarDecl>(E->getDecl());
1502 if (D && D->isLocalVarDeclOrParm() && D->hasLocalStorage())
John McCall0a490152015-09-08 21:15:22 +00001503 Captures.insert(D);
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001504 }
1505
1506 void VisitCXXThisExpr(const CXXThisExpr *E) {
John McCall0a490152015-09-08 21:15:22 +00001507 Captures.insert(ParentThis);
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001508 }
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001509
1510 void VisitCallExpr(const CallExpr *E) {
1511 // We only need to add parent frame allocations for these builtins in x86.
1512 if (ParentCGF.getTarget().getTriple().getArch() != llvm::Triple::x86)
1513 return;
1514
1515 unsigned ID = E->getBuiltinCallee();
1516 switch (ID) {
1517 case Builtin::BI__exception_code:
1518 case Builtin::BI_exception_code:
1519 // This is the simple case where we are the outermost finally. All we
1520 // have to do here is make sure we escape this and recover it in the
1521 // outlined handler.
John McCall7f416cc2015-09-08 08:05:57 +00001522 if (!SEHCodeSlot.isValid())
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001523 SEHCodeSlot = ParentCGF.SEHCodeSlotStack.back();
1524 break;
1525 }
1526 }
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001527};
Hans Wennborgdcfba332015-10-06 23:40:43 +00001528} // end anonymous namespace
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001529
Reid Kleckner39329d57b2015-12-16 00:26:37 +00001530Address CodeGenFunction::recoverAddrOfEscapedLocal(CodeGenFunction &ParentCGF,
1531 Address ParentVar,
1532 llvm::Value *ParentFP) {
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001533 llvm::CallInst *RecoverCall = nullptr;
John McCall7f416cc2015-09-08 08:05:57 +00001534 CGBuilderTy Builder(*this, AllocaInsertPt);
1535 if (auto *ParentAlloca = dyn_cast<llvm::AllocaInst>(ParentVar.getPointer())) {
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001536 // Mark the variable escaped if nobody else referenced it and compute the
Reid Kleckner98cb8ba2015-07-07 22:26:07 +00001537 // localescape index.
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001538 auto InsertPair = ParentCGF.EscapedLocals.insert(
1539 std::make_pair(ParentAlloca, ParentCGF.EscapedLocals.size()));
1540 int FrameEscapeIdx = InsertPair.first->second;
Reid Kleckner98cb8ba2015-07-07 22:26:07 +00001541 // call i8* @llvm.localrecover(i8* bitcast(@parentFn), i8* %fp, i32 N)
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001542 llvm::Function *FrameRecoverFn = llvm::Intrinsic::getDeclaration(
Reid Kleckner98cb8ba2015-07-07 22:26:07 +00001543 &CGM.getModule(), llvm::Intrinsic::localrecover);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001544 llvm::Constant *ParentI8Fn =
1545 llvm::ConstantExpr::getBitCast(ParentCGF.CurFn, Int8PtrTy);
1546 RecoverCall = Builder.CreateCall(
1547 FrameRecoverFn, {ParentI8Fn, ParentFP,
1548 llvm::ConstantInt::get(Int32Ty, FrameEscapeIdx)});
1549
1550 } else {
1551 // If the parent didn't have an alloca, we're doing some nested outlining.
Reid Kleckner98cb8ba2015-07-07 22:26:07 +00001552 // Just clone the existing localrecover call, but tweak the FP argument to
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001553 // use our FP value. All other arguments are constants.
1554 auto *ParentRecover =
John McCall7f416cc2015-09-08 08:05:57 +00001555 cast<llvm::IntrinsicInst>(ParentVar.getPointer()->stripPointerCasts());
Reid Kleckner98cb8ba2015-07-07 22:26:07 +00001556 assert(ParentRecover->getIntrinsicID() == llvm::Intrinsic::localrecover &&
1557 "expected alloca or localrecover in parent LocalDeclMap");
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001558 RecoverCall = cast<llvm::CallInst>(ParentRecover->clone());
1559 RecoverCall->setArgOperand(1, ParentFP);
1560 RecoverCall->insertBefore(AllocaInsertPt);
1561 }
1562
1563 // Bitcast the variable, rename it, and insert it in the local decl map.
1564 llvm::Value *ChildVar =
John McCall7f416cc2015-09-08 08:05:57 +00001565 Builder.CreateBitCast(RecoverCall, ParentVar.getType());
1566 ChildVar->setName(ParentVar.getName());
1567 return Address(ChildVar, ParentVar.getAlignment());
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001568}
1569
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001570void CodeGenFunction::EmitCapturedLocals(CodeGenFunction &ParentCGF,
Reid Kleckner0b9bbbf2015-06-09 17:49:42 +00001571 const Stmt *OutlinedStmt,
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001572 bool IsFilter) {
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001573 // Find all captures in the Stmt.
1574 CaptureFinder Finder(ParentCGF, ParentCGF.CXXABIThisDecl);
1575 Finder.Visit(OutlinedStmt);
1576
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001577 // We can exit early on x86_64 when there are no captures. We just have to
1578 // save the exception code in filters so that __exception_code() works.
1579 if (!Finder.foundCaptures() &&
1580 CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
1581 if (IsFilter)
1582 EmitSEHExceptionCodeSave(ParentCGF, nullptr, nullptr);
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001583 return;
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001584 }
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001585
Reid Kleckner39329d57b2015-12-16 00:26:37 +00001586 llvm::Value *EntryFP = nullptr;
1587 CGBuilderTy Builder(CGM, AllocaInsertPt);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001588 if (IsFilter && CGM.getTarget().getTriple().getArch() == llvm::Triple::x86) {
1589 // 32-bit SEH filters need to be careful about FP recovery. The end of the
1590 // EH registration is passed in as the EBP physical register. We can
Reid Kleckner39329d57b2015-12-16 00:26:37 +00001591 // recover that with llvm.frameaddress(1).
1592 EntryFP = Builder.CreateCall(
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001593 CGM.getIntrinsic(llvm::Intrinsic::frameaddress), {Builder.getInt32(1)});
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001594 } else {
1595 // Otherwise, for x64 and 32-bit finally functions, the parent FP is the
1596 // second parameter.
1597 auto AI = CurFn->arg_begin();
1598 ++AI;
Reid Kleckner39329d57b2015-12-16 00:26:37 +00001599 EntryFP = &*AI;
1600 }
1601
1602 llvm::Value *ParentFP = EntryFP;
1603 if (IsFilter) {
1604 // Given whatever FP the runtime provided us in EntryFP, recover the true
1605 // frame pointer of the parent function. We only need to do this in filters,
1606 // since finally funclets recover the parent FP for us.
1607 llvm::Function *RecoverFPIntrin =
1608 CGM.getIntrinsic(llvm::Intrinsic::x86_seh_recoverfp);
1609 llvm::Constant *ParentI8Fn =
1610 llvm::ConstantExpr::getBitCast(ParentCGF.CurFn, Int8PtrTy);
1611 ParentFP = Builder.CreateCall(RecoverFPIntrin, {ParentI8Fn, EntryFP});
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001612 }
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001613
Reid Kleckner98cb8ba2015-07-07 22:26:07 +00001614 // Create llvm.localrecover calls for all captures.
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001615 for (const VarDecl *VD : Finder.Captures) {
1616 if (isa<ImplicitParamDecl>(VD)) {
1617 CGM.ErrorUnsupported(VD, "'this' captured by SEH");
1618 CXXThisValue = llvm::UndefValue::get(ConvertTypeForMem(VD->getType()));
1619 continue;
1620 }
1621 if (VD->getType()->isVariablyModifiedType()) {
1622 CGM.ErrorUnsupported(VD, "VLA captured by SEH");
1623 continue;
1624 }
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001625 assert((isa<ImplicitParamDecl>(VD) || VD->isLocalVarDeclOrParm()) &&
1626 "captured non-local variable");
1627
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001628 // If this decl hasn't been declared yet, it will be declared in the
1629 // OutlinedStmt.
1630 auto I = ParentCGF.LocalDeclMap.find(VD);
1631 if (I == ParentCGF.LocalDeclMap.end())
1632 continue;
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001633
John McCall7f416cc2015-09-08 08:05:57 +00001634 Address ParentVar = I->second;
Reid Kleckner39329d57b2015-12-16 00:26:37 +00001635 setAddrOfLocalVar(
1636 VD, recoverAddrOfEscapedLocal(ParentCGF, ParentVar, ParentFP));
Nico Webere4f974c2015-07-02 06:10:53 +00001637 }
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001638
John McCall7f416cc2015-09-08 08:05:57 +00001639 if (Finder.SEHCodeSlot.isValid()) {
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001640 SEHCodeSlotStack.push_back(
1641 recoverAddrOfEscapedLocal(ParentCGF, Finder.SEHCodeSlot, ParentFP));
1642 }
1643
1644 if (IsFilter)
Reid Kleckner39329d57b2015-12-16 00:26:37 +00001645 EmitSEHExceptionCodeSave(ParentCGF, ParentFP, EntryFP);
Reid Kleckner31a1bb02015-04-08 22:23:48 +00001646}
1647
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001648/// Arrange a function prototype that can be called by Windows exception
1649/// handling personalities. On Win64, the prototype looks like:
1650/// RetTy func(void *EHPtrs, void *ParentFP);
1651void CodeGenFunction::startOutlinedSEHHelper(CodeGenFunction &ParentCGF,
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001652 bool IsFilter,
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001653 const Stmt *OutlinedStmt) {
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001654 SourceLocation StartLoc = OutlinedStmt->getLocStart();
1655
1656 // Get the mangled function name.
1657 SmallString<128> Name;
1658 {
1659 llvm::raw_svector_ostream OS(Name);
David Majnemer25eb1652016-03-01 19:42:53 +00001660 const FunctionDecl *ParentSEHFn = ParentCGF.CurSEHParent;
1661 assert(ParentSEHFn && "No CurSEHParent!");
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001662 MangleContext &Mangler = CGM.getCXXABI().getMangleContext();
1663 if (IsFilter)
David Majnemer25eb1652016-03-01 19:42:53 +00001664 Mangler.mangleSEHFilterExpression(ParentSEHFn, OS);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001665 else
David Majnemer25eb1652016-03-01 19:42:53 +00001666 Mangler.mangleSEHFinallyBlock(ParentSEHFn, OS);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001667 }
1668
1669 FunctionArgList Args;
1670 if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86 || !IsFilter) {
1671 // All SEH finally functions take two parameters. Win64 filters take two
1672 // parameters. Win32 filters take no parameters.
1673 if (IsFilter) {
1674 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00001675 getContext(), /*DC=*/nullptr, StartLoc,
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001676 &getContext().Idents.get("exception_pointers"),
Alexey Bataev56223232017-06-09 13:40:18 +00001677 getContext().VoidPtrTy, ImplicitParamDecl::Other));
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001678 } else {
1679 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00001680 getContext(), /*DC=*/nullptr, StartLoc,
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001681 &getContext().Idents.get("abnormal_termination"),
Alexey Bataev56223232017-06-09 13:40:18 +00001682 getContext().UnsignedCharTy, ImplicitParamDecl::Other));
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001683 }
1684 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00001685 getContext(), /*DC=*/nullptr, StartLoc,
1686 &getContext().Idents.get("frame_pointer"), getContext().VoidPtrTy,
1687 ImplicitParamDecl::Other));
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001688 }
1689
1690 QualType RetTy = IsFilter ? getContext().LongTy : getContext().VoidTy;
1691
John McCallc56a8b32016-03-11 04:30:31 +00001692 const CGFunctionInfo &FnInfo =
1693 CGM.getTypes().arrangeBuiltinFunctionDeclaration(RetTy, Args);
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001694
Reid Kleckner1d59f992015-01-22 01:36:17 +00001695 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001696 llvm::Function *Fn = llvm::Function::Create(
1697 FnTy, llvm::GlobalValue::InternalLinkage, Name.str(), &CGM.getModule());
Reid Kleckner1d59f992015-01-22 01:36:17 +00001698
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001699 IsOutlinedSEHHelper = true;
Nico Weberf2a39a72015-04-13 20:03:03 +00001700
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001701 StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args,
1702 OutlinedStmt->getLocStart(), OutlinedStmt->getLocStart());
David Majnemer25eb1652016-03-01 19:42:53 +00001703 CurSEHParent = ParentCGF.CurSEHParent;
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001704
1705 CGM.SetLLVMFunctionAttributes(nullptr, FnInfo, CurFn);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001706 EmitCapturedLocals(ParentCGF, OutlinedStmt, IsFilter);
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001707}
1708
1709/// Create a stub filter function that will ultimately hold the code of the
1710/// filter expression. The EH preparation passes in LLVM will outline the code
1711/// from the main function body into this stub.
1712llvm::Function *
1713CodeGenFunction::GenerateSEHFilterFunction(CodeGenFunction &ParentCGF,
1714 const SEHExceptStmt &Except) {
1715 const Expr *FilterExpr = Except.getFilterExpr();
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001716 startOutlinedSEHHelper(ParentCGF, true, FilterExpr);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001717
1718 // Emit the original filter expression, convert to i32, and return.
1719 llvm::Value *R = EmitScalarExpr(FilterExpr);
David Majnemer2ccba832015-04-17 06:57:25 +00001720 R = Builder.CreateIntCast(R, ConvertType(getContext().LongTy),
Reid Kleckner1d59f992015-01-22 01:36:17 +00001721 FilterExpr->getType()->isSignedIntegerType());
1722 Builder.CreateStore(R, ReturnValue);
1723
1724 FinishFunction(FilterExpr->getLocEnd());
1725
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001726 return CurFn;
1727}
1728
1729llvm::Function *
1730CodeGenFunction::GenerateSEHFinallyFunction(CodeGenFunction &ParentCGF,
1731 const SEHFinallyStmt &Finally) {
1732 const Stmt *FinallyBlock = Finally.getBlock();
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001733 startOutlinedSEHHelper(ParentCGF, false, FinallyBlock);
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001734
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001735 // Emit the original filter expression, convert to i32, and return.
1736 EmitStmt(FinallyBlock);
1737
1738 FinishFunction(FinallyBlock->getLocEnd());
1739
1740 return CurFn;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001741}
1742
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001743void CodeGenFunction::EmitSEHExceptionCodeSave(CodeGenFunction &ParentCGF,
1744 llvm::Value *ParentFP,
Reid Kleckner39329d57b2015-12-16 00:26:37 +00001745 llvm::Value *EntryFP) {
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001746 // Get the pointer to the EXCEPTION_POINTERS struct. This is returned by the
1747 // __exception_info intrinsic.
1748 if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
1749 // On Win64, the info is passed as the first parameter to the filter.
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00001750 SEHInfo = &*CurFn->arg_begin();
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001751 SEHCodeSlotStack.push_back(
1752 CreateMemTemp(getContext().IntTy, "__exception_code"));
1753 } else {
1754 // On Win32, the EBP on entry to the filter points to the end of an
1755 // exception registration object. It contains 6 32-bit fields, and the info
1756 // pointer is stored in the second field. So, GEP 20 bytes backwards and
1757 // load the pointer.
Reid Kleckner39329d57b2015-12-16 00:26:37 +00001758 SEHInfo = Builder.CreateConstInBoundsGEP1_32(Int8Ty, EntryFP, -20);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001759 SEHInfo = Builder.CreateBitCast(SEHInfo, Int8PtrTy->getPointerTo());
John McCall7f416cc2015-09-08 08:05:57 +00001760 SEHInfo = Builder.CreateAlignedLoad(Int8PtrTy, SEHInfo, getPointerAlign());
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001761 SEHCodeSlotStack.push_back(recoverAddrOfEscapedLocal(
1762 ParentCGF, ParentCGF.SEHCodeSlotStack.back(), ParentFP));
1763 }
1764
Reid Kleckner1d59f992015-01-22 01:36:17 +00001765 // Save the exception code in the exception slot to unify exception access in
1766 // the filter function and the landing pad.
1767 // struct EXCEPTION_POINTERS {
1768 // EXCEPTION_RECORD *ExceptionRecord;
1769 // CONTEXT *ContextRecord;
1770 // };
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001771 // int exceptioncode = exception_pointers->ExceptionRecord->ExceptionCode;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001772 llvm::Type *RecordTy = CGM.Int32Ty->getPointerTo();
Serge Guelton1d993272017-05-09 19:31:30 +00001773 llvm::Type *PtrsTy = llvm::StructType::get(RecordTy, CGM.VoidPtrTy);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001774 llvm::Value *Ptrs = Builder.CreateBitCast(SEHInfo, PtrsTy->getPointerTo());
David Blaikie1ed728c2015-04-05 22:45:47 +00001775 llvm::Value *Rec = Builder.CreateStructGEP(PtrsTy, Ptrs, 0);
John McCall7f416cc2015-09-08 08:05:57 +00001776 Rec = Builder.CreateAlignedLoad(Rec, getPointerAlign());
1777 llvm::Value *Code = Builder.CreateAlignedLoad(Rec, getIntAlign());
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001778 assert(!SEHCodeSlotStack.empty() && "emitting EH code outside of __except");
1779 Builder.CreateStore(Code, SEHCodeSlotStack.back());
Reid Kleckner1d59f992015-01-22 01:36:17 +00001780}
1781
1782llvm::Value *CodeGenFunction::EmitSEHExceptionInfo() {
1783 // Sema should diagnose calling this builtin outside of a filter context, but
1784 // don't crash if we screw up.
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001785 if (!SEHInfo)
Reid Kleckner1d59f992015-01-22 01:36:17 +00001786 return llvm::UndefValue::get(Int8PtrTy);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001787 assert(SEHInfo->getType() == Int8PtrTy);
1788 return SEHInfo;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001789}
1790
1791llvm::Value *CodeGenFunction::EmitSEHExceptionCode() {
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001792 assert(!SEHCodeSlotStack.empty() && "emitting EH code outside of __except");
John McCall7f416cc2015-09-08 08:05:57 +00001793 return Builder.CreateLoad(SEHCodeSlotStack.back());
Reid Kleckner1d59f992015-01-22 01:36:17 +00001794}
1795
Reid Kleckneraca01db2015-02-04 22:37:07 +00001796llvm::Value *CodeGenFunction::EmitSEHAbnormalTermination() {
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001797 // Abnormal termination is just the first parameter to the outlined finally
1798 // helper.
1799 auto AI = CurFn->arg_begin();
1800 return Builder.CreateZExt(&*AI, Int32Ty);
Reid Kleckneraca01db2015-02-04 22:37:07 +00001801}
1802
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001803void CodeGenFunction::EnterSEHTryStmt(const SEHTryStmt &S) {
1804 CodeGenFunction HelperCGF(CGM, /*suppressNewContext=*/true);
1805 if (const SEHFinallyStmt *Finally = S.getFinallyHandler()) {
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001806 // Outline the finally block.
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001807 llvm::Function *FinallyFunc =
1808 HelperCGF.GenerateSEHFinallyFunction(*this, *Finally);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001809
1810 // Push a cleanup for __finally blocks.
Reid Kleckner55391522015-10-08 21:14:56 +00001811 EHStack.pushCleanup<PerformSEHFinally>(NormalAndEHCleanup, FinallyFunc);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001812 return;
1813 }
1814
1815 // Otherwise, we must have an __except block.
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001816 const SEHExceptStmt *Except = S.getExceptHandler();
Reid Kleckner1d59f992015-01-22 01:36:17 +00001817 assert(Except);
1818 EHCatchScope *CatchScope = EHStack.pushCatch(1);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001819 SEHCodeSlotStack.push_back(
1820 CreateMemTemp(getContext().IntTy, "__exception_code"));
Reid Kleckner2a2e1562015-01-22 02:25:56 +00001821
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001822 // If the filter is known to evaluate to 1, then we can use the clause
1823 // "catch i8* null". We can't do this on x86 because the filter has to save
1824 // the exception code.
Reid Kleckner2a2e1562015-01-22 02:25:56 +00001825 llvm::Constant *C =
John McCallde0fe072017-08-15 21:42:52 +00001826 ConstantEmitter(*this).tryEmitAbstract(Except->getFilterExpr(),
1827 getContext().IntTy);
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001828 if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86 && C &&
1829 C->isOneValue()) {
Reid Kleckner2a2e1562015-01-22 02:25:56 +00001830 CatchScope->setCatchAllHandler(0, createBasicBlock("__except"));
1831 return;
1832 }
1833
1834 // In general, we have to emit an outlined filter function. Use the function
1835 // in place of the RTTI typeinfo global that C++ EH uses.
Reid Kleckner1d59f992015-01-22 01:36:17 +00001836 llvm::Function *FilterFunc =
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001837 HelperCGF.GenerateSEHFilterFunction(*this, *Except);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001838 llvm::Constant *OpaqueFunc =
1839 llvm::ConstantExpr::getBitCast(FilterFunc, Int8PtrTy);
Reid Kleckner8be18472015-09-16 21:06:09 +00001840 CatchScope->setHandler(0, OpaqueFunc, createBasicBlock("__except.ret"));
Reid Kleckner1d59f992015-01-22 01:36:17 +00001841}
1842
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001843void CodeGenFunction::ExitSEHTryStmt(const SEHTryStmt &S) {
Reid Kleckner1d59f992015-01-22 01:36:17 +00001844 // Just pop the cleanup if it's a __finally block.
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001845 if (S.getFinallyHandler()) {
Reid Kleckner1d59f992015-01-22 01:36:17 +00001846 PopCleanupBlock();
1847 return;
1848 }
1849
1850 // Otherwise, we must have an __except block.
Reid Kleckneraca01db2015-02-04 22:37:07 +00001851 const SEHExceptStmt *Except = S.getExceptHandler();
Reid Kleckner1d59f992015-01-22 01:36:17 +00001852 assert(Except && "__try must have __finally xor __except");
1853 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1854
1855 // Don't emit the __except block if the __try block lacked invokes.
1856 // TODO: Model unwind edges from instructions, either with iload / istore or
1857 // a try body function.
1858 if (!CatchScope.hasEHBranches()) {
1859 CatchScope.clearHandlerBlocks();
1860 EHStack.popCatch();
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001861 SEHCodeSlotStack.pop_back();
Reid Kleckner1d59f992015-01-22 01:36:17 +00001862 return;
1863 }
1864
1865 // The fall-through block.
1866 llvm::BasicBlock *ContBB = createBasicBlock("__try.cont");
1867
1868 // We just emitted the body of the __try; jump to the continue block.
1869 if (HaveInsertPoint())
1870 Builder.CreateBr(ContBB);
1871
1872 // Check if our filter function returned true.
1873 emitCatchDispatchBlock(*this, CatchScope);
1874
1875 // Grab the block before we pop the handler.
David Majnemer4e52d6f2015-12-12 05:39:21 +00001876 llvm::BasicBlock *CatchPadBB = CatchScope.getHandler(0).Block;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001877 EHStack.popCatch();
1878
David Majnemer4e52d6f2015-12-12 05:39:21 +00001879 EmitBlockAfterUses(CatchPadBB);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001880
Reid Kleckner129552b2015-10-08 01:13:52 +00001881 // __except blocks don't get outlined into funclets, so immediately do a
1882 // catchret.
Reid Kleckner129552b2015-10-08 01:13:52 +00001883 llvm::CatchPadInst *CPI =
1884 cast<llvm::CatchPadInst>(CatchPadBB->getFirstNonPHI());
David Majnemer4e52d6f2015-12-12 05:39:21 +00001885 llvm::BasicBlock *ExceptBB = createBasicBlock("__except");
Reid Kleckner129552b2015-10-08 01:13:52 +00001886 Builder.CreateCatchRet(CPI, ExceptBB);
1887 EmitBlock(ExceptBB);
1888
1889 // On Win64, the exception code is returned in EAX. Copy it into the slot.
1890 if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
1891 llvm::Function *SEHCodeIntrin =
1892 CGM.getIntrinsic(llvm::Intrinsic::eh_exceptioncode);
1893 llvm::Value *Code = Builder.CreateCall(SEHCodeIntrin, {CPI});
1894 Builder.CreateStore(Code, SEHCodeSlotStack.back());
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001895 }
1896
Reid Kleckner1d59f992015-01-22 01:36:17 +00001897 // Emit the __except body.
1898 EmitStmt(Except->getBlock());
1899
Reid Kleckner9fe7f232015-07-07 00:36:30 +00001900 // End the lifetime of the exception code.
1901 SEHCodeSlotStack.pop_back();
1902
Reid Kleckner3a417c32015-01-30 22:16:45 +00001903 if (HaveInsertPoint())
1904 Builder.CreateBr(ContBB);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001905
1906 EmitBlock(ContBB);
Reid Kleckner543a16c2013-09-16 21:46:30 +00001907}
Nico Weber9b982072014-07-07 00:12:30 +00001908
1909void CodeGenFunction::EmitSEHLeaveStmt(const SEHLeaveStmt &S) {
Nico Weber5779f842015-02-12 23:16:11 +00001910 // If this code is reachable then emit a stop point (if generating
1911 // debug info). We have to do this ourselves because we are on the
1912 // "simple" statement path.
1913 if (HaveInsertPoint())
1914 EmitStopPoint(&S);
1915
Reid Klecknerebaf28d2015-04-14 20:59:00 +00001916 // This must be a __leave from a __finally block, which we warn on and is UB.
1917 // Just emit unreachable.
1918 if (!isSEHTryScope()) {
1919 Builder.CreateUnreachable();
1920 Builder.ClearInsertionPoint();
1921 return;
1922 }
1923
Nico Weber5779f842015-02-12 23:16:11 +00001924 EmitBranchThroughCleanup(*SEHTryEpilogueStack.back());
Nico Weber9b982072014-07-07 00:12:30 +00001925}