blob: d9a3f0b252a5aae756b6a03c07baddf1c08d937e [file] [log] [blame]
Anders Carlsson756b5c42009-10-30 01:42:31 +00001//===--- CGException.cpp - Emit LLVM Code for C++ exceptions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code dealing with C++ exception related code generation.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
Stephen Hines0e2c34f2015-03-23 12:09:02 -070015#include "CGCXXABI.h"
John McCall36f893c2011-01-28 11:13:47 +000016#include "CGCleanup.h"
Benjamin Krameraf2771b2012-02-08 12:41:24 +000017#include "CGObjCRuntime.h"
John McCall204b0752010-07-20 22:17:55 +000018#include "TargetInfo.h"
Stephen Hines0e2c34f2015-03-23 12:09:02 -070019#include "clang/AST/Mangle.h"
Benjamin Krameraf2771b2012-02-08 12:41:24 +000020#include "clang/AST/StmtCXX.h"
Chandler Carruthb1ba0ef2013-01-19 08:09:44 +000021#include "clang/AST/StmtObjC.h"
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -070022#include "clang/AST/StmtVisitor.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070023#include "llvm/IR/CallSite.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000024#include "llvm/IR/Intrinsics.h"
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -070025#include "llvm/IR/IntrinsicInst.h"
26#include "llvm/Support/SaveAndRestore.h"
John McCallf1549f62010-07-06 01:34:17 +000027
Anders Carlsson756b5c42009-10-30 01:42:31 +000028using namespace clang;
29using namespace CodeGen;
30
John McCall629df012013-02-12 03:51:38 +000031static llvm::Constant *getFreeExceptionFn(CodeGenModule &CGM) {
Mike Stump99533832009-12-02 07:41:41 +000032 // void __cxa_free_exception(void *thrown_exception);
Mike Stump8755ec32009-12-10 00:06:18 +000033
Chris Lattner2acc6e32011-07-18 04:24:23 +000034 llvm::FunctionType *FTy =
John McCall629df012013-02-12 03:51:38 +000035 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +000036
John McCall629df012013-02-12 03:51:38 +000037 return CGM.CreateRuntimeFunction(FTy, "__cxa_free_exception");
Mike Stump99533832009-12-02 07:41:41 +000038}
39
John McCall629df012013-02-12 03:51:38 +000040static llvm::Constant *getUnexpectedFn(CodeGenModule &CGM) {
Richard Smith14b0e4b2013-06-20 23:03:35 +000041 // void __cxa_call_unexpected(void *thrown_exception);
Mike Stumpcce3d4f2009-12-07 23:38:24 +000042
Chris Lattner2acc6e32011-07-18 04:24:23 +000043 llvm::FunctionType *FTy =
John McCall629df012013-02-12 03:51:38 +000044 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +000045
John McCall629df012013-02-12 03:51:38 +000046 return CGM.CreateRuntimeFunction(FTy, "__cxa_call_unexpected");
Mike Stumpcce3d4f2009-12-07 23:38:24 +000047}
48
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -070049llvm::Constant *CodeGenModule::getTerminateFn() {
Mike Stump99533832009-12-02 07:41:41 +000050 // void __terminate();
51
Chris Lattner2acc6e32011-07-18 04:24:23 +000052 llvm::FunctionType *FTy =
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -070053 llvm::FunctionType::get(VoidTy, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +000054
Chris Lattner5f9e2722011-07-23 10:55:15 +000055 StringRef name;
John McCall256a76e2011-07-06 01:22:26 +000056
57 // In C++, use std::terminate().
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -070058 if (getLangOpts().CPlusPlus &&
59 getTarget().getCXXABI().isItaniumFamily()) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -070060 name = "_ZSt9terminatev";
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -070061 } else if (getLangOpts().CPlusPlus &&
62 getTarget().getCXXABI().isMicrosoft()) {
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -070063 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
64 name = "__std_terminate";
65 else
66 name = "\01?terminate@@YAXXZ";
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -070067 } else if (getLangOpts().ObjC1 &&
68 getLangOpts().ObjCRuntime.hasTerminate())
John McCall256a76e2011-07-06 01:22:26 +000069 name = "objc_terminate";
70 else
71 name = "abort";
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -070072 return CreateRuntimeFunction(FTy, name);
David Chisnall79a9ad82010-05-17 13:49:20 +000073}
74
John McCall629df012013-02-12 03:51:38 +000075static llvm::Constant *getCatchallRethrowFn(CodeGenModule &CGM,
Chris Lattner5f9e2722011-07-23 10:55:15 +000076 StringRef Name) {
Chris Lattner2acc6e32011-07-18 04:24:23 +000077 llvm::FunctionType *FTy =
John McCall629df012013-02-12 03:51:38 +000078 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
John McCall8262b6a2010-07-17 00:43:08 +000079
John McCall629df012013-02-12 03:51:38 +000080 return CGM.CreateRuntimeFunction(FTy, Name);
John McCallf1549f62010-07-06 01:34:17 +000081}
82
Benjamin Krameraf2771b2012-02-08 12:41:24 +000083namespace {
84 /// The exceptions personality for a function.
85 struct EHPersonality {
86 const char *PersonalityFn;
87
88 // If this is non-null, this personality requires a non-standard
89 // function for rethrowing an exception after a catchall cleanup.
90 // This function must have prototype void(void*).
91 const char *CatchallRethrowFn;
92
Stephen Hines0e2c34f2015-03-23 12:09:02 -070093 static const EHPersonality &get(CodeGenModule &CGM,
94 const FunctionDecl *FD);
95 static const EHPersonality &get(CodeGenFunction &CGF) {
96 return get(CGF.CGM, dyn_cast_or_null<FunctionDecl>(CGF.CurCodeDecl));
97 }
98
Benjamin Krameraf2771b2012-02-08 12:41:24 +000099 static const EHPersonality GNU_C;
100 static const EHPersonality GNU_C_SJLJ;
Stephen Hines176edba2014-12-01 14:53:08 -0800101 static const EHPersonality GNU_C_SEH;
Benjamin Krameraf2771b2012-02-08 12:41:24 +0000102 static const EHPersonality GNU_ObjC;
David Chisnall65bd4ac2013-01-11 15:33:01 +0000103 static const EHPersonality GNUstep_ObjC;
Benjamin Krameraf2771b2012-02-08 12:41:24 +0000104 static const EHPersonality GNU_ObjCXX;
105 static const EHPersonality NeXT_ObjC;
106 static const EHPersonality GNU_CPlusPlus;
107 static const EHPersonality GNU_CPlusPlus_SJLJ;
Stephen Hines176edba2014-12-01 14:53:08 -0800108 static const EHPersonality GNU_CPlusPlus_SEH;
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700109 static const EHPersonality MSVC_except_handler;
110 static const EHPersonality MSVC_C_specific_handler;
111 static const EHPersonality MSVC_CxxFrameHandler3;
Benjamin Krameraf2771b2012-02-08 12:41:24 +0000112 };
113}
114
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700115const EHPersonality EHPersonality::GNU_C = { "__gcc_personality_v0", nullptr };
Benjamin Krameraf2771b2012-02-08 12:41:24 +0000116const EHPersonality
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700117EHPersonality::GNU_C_SJLJ = { "__gcc_personality_sj0", nullptr };
118const EHPersonality
Stephen Hines176edba2014-12-01 14:53:08 -0800119EHPersonality::GNU_C_SEH = { "__gcc_personality_seh0", nullptr };
120const EHPersonality
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700121EHPersonality::NeXT_ObjC = { "__objc_personality_v0", nullptr };
122const EHPersonality
123EHPersonality::GNU_CPlusPlus = { "__gxx_personality_v0", nullptr };
124const EHPersonality
125EHPersonality::GNU_CPlusPlus_SJLJ = { "__gxx_personality_sj0", nullptr };
Benjamin Krameraf2771b2012-02-08 12:41:24 +0000126const EHPersonality
Stephen Hines176edba2014-12-01 14:53:08 -0800127EHPersonality::GNU_CPlusPlus_SEH = { "__gxx_personality_seh0", nullptr };
128const EHPersonality
Benjamin Krameraf2771b2012-02-08 12:41:24 +0000129EHPersonality::GNU_ObjC = {"__gnu_objc_personality_v0", "objc_exception_throw"};
130const EHPersonality
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700131EHPersonality::GNU_ObjCXX = { "__gnustep_objcxx_personality_v0", nullptr };
David Chisnall65bd4ac2013-01-11 15:33:01 +0000132const EHPersonality
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700133EHPersonality::GNUstep_ObjC = { "__gnustep_objc_personality_v0", nullptr };
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700134const EHPersonality
135EHPersonality::MSVC_except_handler = { "_except_handler3", nullptr };
136const EHPersonality
137EHPersonality::MSVC_C_specific_handler = { "__C_specific_handler", nullptr };
138const EHPersonality
139EHPersonality::MSVC_CxxFrameHandler3 = { "__CxxFrameHandler3", nullptr };
John McCall8262b6a2010-07-17 00:43:08 +0000140
Stephen Hines176edba2014-12-01 14:53:08 -0800141/// On Win64, use libgcc's SEH personality function. We fall back to dwarf on
142/// other platforms, unless the user asked for SjLj exceptions.
143static bool useLibGCCSEHPersonality(const llvm::Triple &T) {
144 return T.isOSWindows() && T.getArch() == llvm::Triple::x86_64;
145}
146
147static const EHPersonality &getCPersonality(const llvm::Triple &T,
148 const LangOptions &L) {
John McCall44680782010-11-07 02:35:25 +0000149 if (L.SjLjExceptions)
150 return EHPersonality::GNU_C_SJLJ;
Stephen Hines176edba2014-12-01 14:53:08 -0800151 else if (useLibGCCSEHPersonality(T))
152 return EHPersonality::GNU_C_SEH;
John McCall8262b6a2010-07-17 00:43:08 +0000153 return EHPersonality::GNU_C;
154}
155
Stephen Hines176edba2014-12-01 14:53:08 -0800156static const EHPersonality &getObjCPersonality(const llvm::Triple &T,
157 const LangOptions &L) {
John McCall260611a2012-06-20 06:18:46 +0000158 switch (L.ObjCRuntime.getKind()) {
159 case ObjCRuntime::FragileMacOSX:
Stephen Hines176edba2014-12-01 14:53:08 -0800160 return getCPersonality(T, L);
John McCall260611a2012-06-20 06:18:46 +0000161 case ObjCRuntime::MacOSX:
162 case ObjCRuntime::iOS:
163 return EHPersonality::NeXT_ObjC;
David Chisnall11d3f4c2012-07-03 20:49:52 +0000164 case ObjCRuntime::GNUstep:
David Chisnall65bd4ac2013-01-11 15:33:01 +0000165 if (L.ObjCRuntime.getVersion() >= VersionTuple(1, 7))
166 return EHPersonality::GNUstep_ObjC;
167 // fallthrough
David Chisnall11d3f4c2012-07-03 20:49:52 +0000168 case ObjCRuntime::GCC:
John McCallf7226fb2012-07-12 02:07:58 +0000169 case ObjCRuntime::ObjFW:
John McCall8262b6a2010-07-17 00:43:08 +0000170 return EHPersonality::GNU_ObjC;
John McCallf1549f62010-07-06 01:34:17 +0000171 }
John McCall260611a2012-06-20 06:18:46 +0000172 llvm_unreachable("bad runtime kind");
John McCallf1549f62010-07-06 01:34:17 +0000173}
174
Stephen Hines176edba2014-12-01 14:53:08 -0800175static const EHPersonality &getCXXPersonality(const llvm::Triple &T,
176 const LangOptions &L) {
John McCall8262b6a2010-07-17 00:43:08 +0000177 if (L.SjLjExceptions)
178 return EHPersonality::GNU_CPlusPlus_SJLJ;
Stephen Hines176edba2014-12-01 14:53:08 -0800179 else if (useLibGCCSEHPersonality(T))
180 return EHPersonality::GNU_CPlusPlus_SEH;
181 return EHPersonality::GNU_CPlusPlus;
John McCallf1549f62010-07-06 01:34:17 +0000182}
183
184/// Determines the personality function to use when both C++
185/// and Objective-C exceptions are being caught.
Stephen Hines176edba2014-12-01 14:53:08 -0800186static const EHPersonality &getObjCXXPersonality(const llvm::Triple &T,
187 const LangOptions &L) {
John McCall260611a2012-06-20 06:18:46 +0000188 switch (L.ObjCRuntime.getKind()) {
John McCallf1549f62010-07-06 01:34:17 +0000189 // The ObjC personality defers to the C++ personality for non-ObjC
190 // handlers. Unlike the C++ case, we use the same personality
191 // function on targets using (backend-driven) SJLJ EH.
John McCall260611a2012-06-20 06:18:46 +0000192 case ObjCRuntime::MacOSX:
193 case ObjCRuntime::iOS:
194 return EHPersonality::NeXT_ObjC;
John McCallf1549f62010-07-06 01:34:17 +0000195
John McCall260611a2012-06-20 06:18:46 +0000196 // In the fragile ABI, just use C++ exception handling and hope
197 // they're not doing crazy exception mixing.
198 case ObjCRuntime::FragileMacOSX:
Stephen Hines176edba2014-12-01 14:53:08 -0800199 return getCXXPersonality(T, L);
David Chisnall79a9ad82010-05-17 13:49:20 +0000200
David Chisnall11d3f4c2012-07-03 20:49:52 +0000201 // The GCC runtime's personality function inherently doesn't support
John McCall8262b6a2010-07-17 00:43:08 +0000202 // mixed EH. Use the C++ personality just to avoid returning null.
David Chisnall11d3f4c2012-07-03 20:49:52 +0000203 case ObjCRuntime::GCC:
John McCallf7226fb2012-07-12 02:07:58 +0000204 case ObjCRuntime::ObjFW: // XXX: this will change soon
David Chisnall11d3f4c2012-07-03 20:49:52 +0000205 return EHPersonality::GNU_ObjC;
206 case ObjCRuntime::GNUstep:
John McCall260611a2012-06-20 06:18:46 +0000207 return EHPersonality::GNU_ObjCXX;
208 }
209 llvm_unreachable("bad runtime kind");
John McCallf1549f62010-07-06 01:34:17 +0000210}
211
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700212static const EHPersonality &getSEHPersonalityMSVC(const llvm::Triple &T) {
213 if (T.getArch() == llvm::Triple::x86)
214 return EHPersonality::MSVC_except_handler;
215 return EHPersonality::MSVC_C_specific_handler;
216}
217
218const EHPersonality &EHPersonality::get(CodeGenModule &CGM,
219 const FunctionDecl *FD) {
Stephen Hines176edba2014-12-01 14:53:08 -0800220 const llvm::Triple &T = CGM.getTarget().getTriple();
221 const LangOptions &L = CGM.getLangOpts();
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700222
223 // Try to pick a personality function that is compatible with MSVC if we're
224 // not compiling Obj-C. Obj-C users better have an Obj-C runtime that supports
225 // the GCC-style personality function.
226 if (T.isWindowsMSVCEnvironment() && !L.ObjC1) {
227 if (L.SjLjExceptions)
228 return EHPersonality::GNU_CPlusPlus_SJLJ;
229 else if (FD && FD->usesSEHTry())
230 return getSEHPersonalityMSVC(T);
231 else
232 return EHPersonality::MSVC_CxxFrameHandler3;
233 }
234
John McCall8262b6a2010-07-17 00:43:08 +0000235 if (L.CPlusPlus && L.ObjC1)
Stephen Hines176edba2014-12-01 14:53:08 -0800236 return getObjCXXPersonality(T, L);
John McCall8262b6a2010-07-17 00:43:08 +0000237 else if (L.CPlusPlus)
Stephen Hines176edba2014-12-01 14:53:08 -0800238 return getCXXPersonality(T, L);
John McCall8262b6a2010-07-17 00:43:08 +0000239 else if (L.ObjC1)
Stephen Hines176edba2014-12-01 14:53:08 -0800240 return getObjCPersonality(T, L);
John McCallf1549f62010-07-06 01:34:17 +0000241 else
Stephen Hines176edba2014-12-01 14:53:08 -0800242 return getCPersonality(T, L);
John McCall8262b6a2010-07-17 00:43:08 +0000243}
John McCallf1549f62010-07-06 01:34:17 +0000244
John McCallb2593832010-09-16 06:16:50 +0000245static llvm::Constant *getPersonalityFn(CodeGenModule &CGM,
John McCall8262b6a2010-07-17 00:43:08 +0000246 const EHPersonality &Personality) {
John McCall8262b6a2010-07-17 00:43:08 +0000247 llvm::Constant *Fn =
Chris Lattner8b418682012-02-07 00:39:47 +0000248 CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.Int32Ty, true),
Benjamin Krameraf2771b2012-02-08 12:41:24 +0000249 Personality.PersonalityFn);
John McCallb2593832010-09-16 06:16:50 +0000250 return Fn;
251}
252
253static llvm::Constant *getOpaquePersonalityFn(CodeGenModule &CGM,
254 const EHPersonality &Personality) {
255 llvm::Constant *Fn = getPersonalityFn(CGM, Personality);
John McCalld16c2cf2011-02-08 08:22:06 +0000256 return llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
John McCallb2593832010-09-16 06:16:50 +0000257}
258
259/// Check whether a personality function could reasonably be swapped
260/// for a C++ personality function.
261static bool PersonalityHasOnlyCXXUses(llvm::Constant *Fn) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700262 for (llvm::User *U : Fn->users()) {
John McCallb2593832010-09-16 06:16:50 +0000263 // Conditionally white-list bitcasts.
Stephen Hines651f13c2014-04-23 16:59:28 -0700264 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(U)) {
John McCallb2593832010-09-16 06:16:50 +0000265 if (CE->getOpcode() != llvm::Instruction::BitCast) return false;
266 if (!PersonalityHasOnlyCXXUses(CE))
267 return false;
268 continue;
269 }
270
Bill Wendling40ccacc2011-09-19 22:08:36 +0000271 // Otherwise, it has to be a landingpad instruction.
Stephen Hines651f13c2014-04-23 16:59:28 -0700272 llvm::LandingPadInst *LPI = dyn_cast<llvm::LandingPadInst>(U);
Bill Wendling40ccacc2011-09-19 22:08:36 +0000273 if (!LPI) return false;
John McCallb2593832010-09-16 06:16:50 +0000274
Bill Wendling40ccacc2011-09-19 22:08:36 +0000275 for (unsigned I = 0, E = LPI->getNumClauses(); I != E; ++I) {
John McCallb2593832010-09-16 06:16:50 +0000276 // Look for something that would've been returned by the ObjC
277 // runtime's GetEHType() method.
Bill Wendling40ccacc2011-09-19 22:08:36 +0000278 llvm::Value *Val = LPI->getClause(I)->stripPointerCasts();
279 if (LPI->isCatch(I)) {
280 // Check if the catch value has the ObjC prefix.
Bill Wendlingeecb6a12011-09-20 00:40:19 +0000281 if (llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Val))
282 // ObjC EH selector entries are always global variables with
283 // names starting like this.
284 if (GV->getName().startswith("OBJC_EHTYPE"))
285 return false;
Bill Wendling40ccacc2011-09-19 22:08:36 +0000286 } else {
287 // Check if any of the filter values have the ObjC prefix.
288 llvm::Constant *CVal = cast<llvm::Constant>(Val);
289 for (llvm::User::op_iterator
290 II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II) {
Bill Wendlingeecb6a12011-09-20 00:40:19 +0000291 if (llvm::GlobalVariable *GV =
292 cast<llvm::GlobalVariable>((*II)->stripPointerCasts()))
293 // ObjC EH selector entries are always global variables with
294 // names starting like this.
295 if (GV->getName().startswith("OBJC_EHTYPE"))
296 return false;
Bill Wendling40ccacc2011-09-19 22:08:36 +0000297 }
298 }
John McCallb2593832010-09-16 06:16:50 +0000299 }
300 }
301
302 return true;
303}
304
305/// Try to use the C++ personality function in ObjC++. Not doing this
306/// can cause some incompatibilities with gcc, which is more
307/// aggressive about only using the ObjC++ personality in a function
308/// when it really needs it.
309void CodeGenModule::SimplifyPersonality() {
John McCallb2593832010-09-16 06:16:50 +0000310 // If we're not in ObjC++ -fexceptions, there's nothing to do.
David Blaikie4e4d0842012-03-11 07:00:24 +0000311 if (!LangOpts.CPlusPlus || !LangOpts.ObjC1 || !LangOpts.Exceptions)
John McCallb2593832010-09-16 06:16:50 +0000312 return;
313
John McCall70cd6192012-11-14 17:48:31 +0000314 // Both the problem this endeavors to fix and the way the logic
315 // above works is specific to the NeXT runtime.
316 if (!LangOpts.ObjCRuntime.isNeXTFamily())
317 return;
318
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700319 const EHPersonality &ObjCXX = EHPersonality::get(*this, /*FD=*/nullptr);
Stephen Hines176edba2014-12-01 14:53:08 -0800320 const EHPersonality &CXX =
321 getCXXPersonality(getTarget().getTriple(), LangOpts);
Benjamin Krameraf2771b2012-02-08 12:41:24 +0000322 if (&ObjCXX == &CXX)
John McCallb2593832010-09-16 06:16:50 +0000323 return;
324
Benjamin Krameraf2771b2012-02-08 12:41:24 +0000325 assert(std::strcmp(ObjCXX.PersonalityFn, CXX.PersonalityFn) != 0 &&
326 "Different EHPersonalities using the same personality function.");
327
328 llvm::Function *Fn = getModule().getFunction(ObjCXX.PersonalityFn);
John McCallb2593832010-09-16 06:16:50 +0000329
330 // Nothing to do if it's unused.
331 if (!Fn || Fn->use_empty()) return;
332
333 // Can't do the optimization if it has non-C++ uses.
334 if (!PersonalityHasOnlyCXXUses(Fn)) return;
335
336 // Create the C++ personality function and kill off the old
337 // function.
338 llvm::Constant *CXXFn = getPersonalityFn(*this, CXX);
339
340 // This can happen if the user is screwing with us.
341 if (Fn->getType() != CXXFn->getType()) return;
342
343 Fn->replaceAllUsesWith(CXXFn);
344 Fn->eraseFromParent();
John McCallf1549f62010-07-06 01:34:17 +0000345}
346
347/// Returns the value to inject into a selector to indicate the
348/// presence of a catch-all.
349static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
350 // Possibly we should use @llvm.eh.catch.all.value here.
John McCalld16c2cf2011-02-08 08:22:06 +0000351 return llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
John McCallf1549f62010-07-06 01:34:17 +0000352}
353
John McCall09faeab2010-07-13 21:17:51 +0000354namespace {
355 /// A cleanup to free the exception object if its initialization
356 /// throws.
John McCallc4a1a842011-07-12 00:15:30 +0000357 struct FreeException : EHScopeStack::Cleanup {
358 llvm::Value *exn;
359 FreeException(llvm::Value *exn) : exn(exn) {}
Stephen Hines651f13c2014-04-23 16:59:28 -0700360 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallbd7370a2013-02-28 19:01:20 +0000361 CGF.EmitNounwindRuntimeCall(getFreeExceptionFn(CGF.CGM), exn);
John McCall09faeab2010-07-13 21:17:51 +0000362 }
363 };
364}
365
John McCallac418162010-04-22 01:10:34 +0000366// Emits an exception expression into the given location. This
367// differs from EmitAnyExprToMem only in that, if a final copy-ctor
368// call is required, an exception within that copy ctor causes
369// std::terminate to be invoked.
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -0700370void CodeGenFunction::EmitAnyExprToExn(const Expr *e, llvm::Value *addr) {
John McCallf1549f62010-07-06 01:34:17 +0000371 // Make sure the exception object is cleaned up if there's an
372 // exception during initialization.
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -0700373 pushFullExprCleanup<FreeException>(EHCleanup, addr);
374 EHScopeStack::stable_iterator cleanup = EHStack.stable_begin();
John McCallac418162010-04-22 01:10:34 +0000375
376 // __cxa_allocate_exception returns a void*; we need to cast this
377 // to the appropriate type for the object.
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -0700378 llvm::Type *ty = ConvertTypeForMem(e->getType())->getPointerTo();
379 llvm::Value *typedAddr = Builder.CreateBitCast(addr, ty);
John McCallac418162010-04-22 01:10:34 +0000380
381 // FIXME: this isn't quite right! If there's a final unelided call
382 // to a copy constructor, then according to [except.terminate]p1 we
383 // must call std::terminate() if that constructor throws, because
384 // technically that copy occurs after the exception expression is
385 // evaluated but before the exception is caught. But the best way
386 // to handle that is to teach EmitAggExpr to do the final copy
387 // differently if it can't be elided.
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -0700388 EmitAnyExprToMem(e, typedAddr, e->getType().getQualifiers(),
389 /*IsInit*/ true);
John McCallac418162010-04-22 01:10:34 +0000390
John McCall3ad32c82011-01-28 08:37:24 +0000391 // Deactivate the cleanup block.
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -0700392 DeactivateCleanupBlock(cleanup, cast<llvm::Instruction>(typedAddr));
Mike Stump0f590be2009-12-01 03:41:18 +0000393}
394
John McCallf1549f62010-07-06 01:34:17 +0000395llvm::Value *CodeGenFunction::getExceptionSlot() {
John McCall93c332a2011-05-28 21:13:02 +0000396 if (!ExceptionSlot)
397 ExceptionSlot = CreateTempAlloca(Int8PtrTy, "exn.slot");
John McCallf1549f62010-07-06 01:34:17 +0000398 return ExceptionSlot;
Mike Stump0f590be2009-12-01 03:41:18 +0000399}
400
John McCall93c332a2011-05-28 21:13:02 +0000401llvm::Value *CodeGenFunction::getEHSelectorSlot() {
402 if (!EHSelectorSlot)
403 EHSelectorSlot = CreateTempAlloca(Int32Ty, "ehselector.slot");
404 return EHSelectorSlot;
405}
406
Bill Wendlingae270592011-09-15 18:57:19 +0000407llvm::Value *CodeGenFunction::getExceptionFromSlot() {
408 return Builder.CreateLoad(getExceptionSlot(), "exn");
409}
410
411llvm::Value *CodeGenFunction::getSelectorFromSlot() {
412 return Builder.CreateLoad(getEHSelectorSlot(), "sel");
413}
414
Richard Smith4c71b8c2013-05-07 21:53:22 +0000415void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E,
416 bool KeepInsertionPoint) {
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -0700417 if (const Expr *SubExpr = E->getSubExpr()) {
418 QualType ThrowType = SubExpr->getType();
419 if (ThrowType->isObjCObjectPointerType()) {
420 const Stmt *ThrowStmt = E->getSubExpr();
421 const ObjCAtThrowStmt S(E->getExprLoc(), const_cast<Stmt *>(ThrowStmt));
422 CGM.getObjCRuntime().EmitThrowStmt(*this, S, false);
423 } else {
424 CGM.getCXXABI().emitThrow(*this, E);
John McCallac418162010-04-22 01:10:34 +0000425 }
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -0700426 } else {
427 CGM.getCXXABI().emitRethrow(*this, /*isNoReturn=*/true);
John McCallac418162010-04-22 01:10:34 +0000428 }
Mike Stump8755ec32009-12-10 00:06:18 +0000429
John McCallcd5b22e2011-01-12 03:41:02 +0000430 // throw is an expression, and the expression emitters expect us
431 // to leave ourselves at a valid insertion point.
Richard Smith4c71b8c2013-05-07 21:53:22 +0000432 if (KeepInsertionPoint)
433 EmitBlock(createBasicBlock("throw.cont"));
Anders Carlsson756b5c42009-10-30 01:42:31 +0000434}
Mike Stump2bf701e2009-11-20 23:44:51 +0000435
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000436void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000437 if (!CGM.getLangOpts().CXXExceptions)
Anders Carlssona994ee42010-02-06 23:59:05 +0000438 return;
439
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000440 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700441 if (!FD) {
442 // Check if CapturedDecl is nothrow and create terminate scope for it.
443 if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
444 if (CD->isNothrow())
445 EHStack.pushTerminate();
446 }
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000447 return;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700448 }
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000449 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700450 if (!Proto)
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000451 return;
452
Sebastian Redla968e972011-03-15 18:42:48 +0000453 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
454 if (isNoexceptExceptionSpec(EST)) {
455 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
456 // noexcept functions are simple terminate scopes.
457 EHStack.pushTerminate();
458 }
459 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -0700460 // TODO: Revisit exception specifications for the MS ABI. There is a way to
461 // encode these in an object file but MSVC doesn't do anything with it.
462 if (getTarget().getCXXABI().isMicrosoft())
463 return;
Sebastian Redla968e972011-03-15 18:42:48 +0000464 unsigned NumExceptions = Proto->getNumExceptions();
465 EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000466
Sebastian Redla968e972011-03-15 18:42:48 +0000467 for (unsigned I = 0; I != NumExceptions; ++I) {
468 QualType Ty = Proto->getExceptionType(I);
469 QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
470 llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType,
471 /*ForEH=*/true);
472 Filter->setFilter(I, EHType);
473 }
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000474 }
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000475}
476
John McCall777d6e52011-08-11 02:22:43 +0000477/// Emit the dispatch block for a filter scope if necessary.
478static void emitFilterDispatchBlock(CodeGenFunction &CGF,
479 EHFilterScope &filterScope) {
480 llvm::BasicBlock *dispatchBlock = filterScope.getCachedEHDispatchBlock();
481 if (!dispatchBlock) return;
482 if (dispatchBlock->use_empty()) {
483 delete dispatchBlock;
484 return;
485 }
486
John McCall777d6e52011-08-11 02:22:43 +0000487 CGF.EmitBlockAfterUses(dispatchBlock);
488
489 // If this isn't a catch-all filter, we need to check whether we got
490 // here because the filter triggered.
491 if (filterScope.getNumFilters()) {
492 // Load the selector value.
Bill Wendlingae270592011-09-15 18:57:19 +0000493 llvm::Value *selector = CGF.getSelectorFromSlot();
John McCall777d6e52011-08-11 02:22:43 +0000494 llvm::BasicBlock *unexpectedBB = CGF.createBasicBlock("ehspec.unexpected");
495
496 llvm::Value *zero = CGF.Builder.getInt32(0);
497 llvm::Value *failsFilter =
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700498 CGF.Builder.CreateICmpSLT(selector, zero, "ehspec.fails");
499 CGF.Builder.CreateCondBr(failsFilter, unexpectedBB,
500 CGF.getEHResumeBlock(false));
John McCall777d6e52011-08-11 02:22:43 +0000501
502 CGF.EmitBlock(unexpectedBB);
503 }
504
505 // Call __cxa_call_unexpected. This doesn't need to be an invoke
506 // because __cxa_call_unexpected magically filters exceptions
507 // according to the last landing pad the exception was thrown
508 // into. Seriously.
Bill Wendlingae270592011-09-15 18:57:19 +0000509 llvm::Value *exn = CGF.getExceptionFromSlot();
John McCallbd7370a2013-02-28 19:01:20 +0000510 CGF.EmitRuntimeCall(getUnexpectedFn(CGF.CGM), exn)
John McCall777d6e52011-08-11 02:22:43 +0000511 ->setDoesNotReturn();
512 CGF.Builder.CreateUnreachable();
513}
514
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000515void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000516 if (!CGM.getLangOpts().CXXExceptions)
Anders Carlssona994ee42010-02-06 23:59:05 +0000517 return;
518
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000519 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700520 if (!FD) {
521 // Check if CapturedDecl is nothrow and pop terminate scope for it.
522 if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
523 if (CD->isNothrow())
524 EHStack.popTerminate();
525 }
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000526 return;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700527 }
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000528 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700529 if (!Proto)
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000530 return;
531
Sebastian Redla968e972011-03-15 18:42:48 +0000532 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
533 if (isNoexceptExceptionSpec(EST)) {
534 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
535 EHStack.popTerminate();
536 }
537 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -0700538 // TODO: Revisit exception specifications for the MS ABI. There is a way to
539 // encode these in an object file but MSVC doesn't do anything with it.
540 if (getTarget().getCXXABI().isMicrosoft())
541 return;
John McCall777d6e52011-08-11 02:22:43 +0000542 EHFilterScope &filterScope = cast<EHFilterScope>(*EHStack.begin());
543 emitFilterDispatchBlock(*this, filterScope);
Sebastian Redla968e972011-03-15 18:42:48 +0000544 EHStack.popFilter();
545 }
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000546}
547
Mike Stump2bf701e2009-11-20 23:44:51 +0000548void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
John McCall59a70002010-07-07 06:56:46 +0000549 EnterCXXTryStmt(S);
John McCall9fc6a772010-02-19 09:25:03 +0000550 EmitStmt(S.getTryBlock());
John McCall59a70002010-07-07 06:56:46 +0000551 ExitCXXTryStmt(S);
John McCall9fc6a772010-02-19 09:25:03 +0000552}
553
John McCall59a70002010-07-07 06:56:46 +0000554void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallf1549f62010-07-06 01:34:17 +0000555 unsigned NumHandlers = S.getNumHandlers();
556 EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
John McCall9fc6a772010-02-19 09:25:03 +0000557
John McCallf1549f62010-07-06 01:34:17 +0000558 for (unsigned I = 0; I != NumHandlers; ++I) {
559 const CXXCatchStmt *C = S.getHandler(I);
John McCall9fc6a772010-02-19 09:25:03 +0000560
John McCallf1549f62010-07-06 01:34:17 +0000561 llvm::BasicBlock *Handler = createBasicBlock("catch");
562 if (C->getExceptionDecl()) {
563 // FIXME: Dropping the reference type on the type into makes it
564 // impossible to correctly implement catch-by-reference
565 // semantics for pointers. Unfortunately, this is what all
566 // existing compilers do, and it's not clear that the standard
567 // personality routine is capable of doing this right. See C++ DR 388:
568 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
Stephen Hines176edba2014-12-01 14:53:08 -0800569 Qualifiers CaughtTypeQuals;
570 QualType CaughtType = CGM.getContext().getUnqualifiedArrayType(
571 C->getCaughtType().getNonReferenceType(), CaughtTypeQuals);
John McCall5a180392010-07-24 00:37:23 +0000572
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700573 llvm::Constant *TypeInfo = nullptr;
John McCall5a180392010-07-24 00:37:23 +0000574 if (CaughtType->isObjCObjectPointerType())
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +0000575 TypeInfo = CGM.getObjCRuntime().GetEHType(CaughtType);
John McCall5a180392010-07-24 00:37:23 +0000576 else
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -0700577 TypeInfo =
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -0700578 CGM.getAddrOfCXXCatchHandlerType(CaughtType, C->getCaughtType());
John McCallf1549f62010-07-06 01:34:17 +0000579 CatchScope->setHandler(I, TypeInfo, Handler);
580 } else {
581 // No exception decl indicates '...', a catch-all.
582 CatchScope->setCatchAllHandler(I, Handler);
583 }
584 }
John McCallf1549f62010-07-06 01:34:17 +0000585}
586
John McCall777d6e52011-08-11 02:22:43 +0000587llvm::BasicBlock *
588CodeGenFunction::getEHDispatchBlock(EHScopeStack::stable_iterator si) {
589 // The dispatch block for the end of the scope chain is a block that
590 // just resumes unwinding.
591 if (si == EHStack.stable_end())
David Chisnallc6860042012-11-07 16:50:40 +0000592 return getEHResumeBlock(true);
John McCall777d6e52011-08-11 02:22:43 +0000593
594 // Otherwise, we should look at the actual scope.
595 EHScope &scope = *EHStack.find(si);
596
597 llvm::BasicBlock *dispatchBlock = scope.getCachedEHDispatchBlock();
598 if (!dispatchBlock) {
599 switch (scope.getKind()) {
600 case EHScope::Catch: {
601 // Apply a special case to a single catch-all.
602 EHCatchScope &catchScope = cast<EHCatchScope>(scope);
603 if (catchScope.getNumHandlers() == 1 &&
604 catchScope.getHandler(0).isCatchAll()) {
605 dispatchBlock = catchScope.getHandler(0).Block;
606
607 // Otherwise, make a dispatch block.
608 } else {
609 dispatchBlock = createBasicBlock("catch.dispatch");
610 }
611 break;
612 }
613
614 case EHScope::Cleanup:
615 dispatchBlock = createBasicBlock("ehcleanup");
616 break;
617
618 case EHScope::Filter:
619 dispatchBlock = createBasicBlock("filter.dispatch");
620 break;
621
622 case EHScope::Terminate:
623 dispatchBlock = getTerminateHandler();
624 break;
625 }
626 scope.setCachedEHDispatchBlock(dispatchBlock);
627 }
628 return dispatchBlock;
629}
630
John McCallf1549f62010-07-06 01:34:17 +0000631/// Check whether this is a non-EH scope, i.e. a scope which doesn't
632/// affect exception handling. Currently, the only non-EH scopes are
633/// normal-only cleanup scopes.
634static bool isNonEHScope(const EHScope &S) {
John McCallda65ea82010-07-13 20:32:21 +0000635 switch (S.getKind()) {
John McCall1f0fca52010-07-21 07:22:38 +0000636 case EHScope::Cleanup:
637 return !cast<EHCleanupScope>(S).isEHCleanup();
John McCallda65ea82010-07-13 20:32:21 +0000638 case EHScope::Filter:
639 case EHScope::Catch:
640 case EHScope::Terminate:
641 return false;
642 }
643
David Blaikie30263482012-01-20 21:50:17 +0000644 llvm_unreachable("Invalid EHScope Kind!");
John McCallf1549f62010-07-06 01:34:17 +0000645}
646
647llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
648 assert(EHStack.requiresLandingPad());
649 assert(!EHStack.empty());
650
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700651 // If exceptions are disabled, there are usually no landingpads. However, when
652 // SEH is enabled, functions using SEH still get landingpads.
653 const LangOptions &LO = CGM.getLangOpts();
654 if (!LO.Exceptions) {
655 if (!LO.Borland && !LO.MicrosoftExt)
656 return nullptr;
657 if (!currentFunctionUsesSEHTry())
658 return nullptr;
659 }
John McCallda65ea82010-07-13 20:32:21 +0000660
John McCallf1549f62010-07-06 01:34:17 +0000661 // Check the innermost scope for a cached landing pad. If this is
662 // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
663 llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
664 if (LP) return LP;
665
666 // Build the landing pad for this scope.
667 LP = EmitLandingPad();
668 assert(LP);
669
670 // Cache the landing pad on the innermost scope. If this is a
671 // non-EH scope, cache the landing pad on the enclosing scope, too.
672 for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
673 ir->setCachedLandingPad(LP);
674 if (!isNonEHScope(*ir)) break;
675 }
676
677 return LP;
678}
679
680llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
681 assert(EHStack.requiresLandingPad());
682
John McCall777d6e52011-08-11 02:22:43 +0000683 EHScope &innermostEHScope = *EHStack.find(EHStack.getInnermostEHScope());
684 switch (innermostEHScope.getKind()) {
685 case EHScope::Terminate:
686 return getTerminateLandingPad();
John McCallf1549f62010-07-06 01:34:17 +0000687
John McCall777d6e52011-08-11 02:22:43 +0000688 case EHScope::Catch:
689 case EHScope::Cleanup:
690 case EHScope::Filter:
691 if (llvm::BasicBlock *lpad = innermostEHScope.getCachedLandingPad())
692 return lpad;
John McCallf1549f62010-07-06 01:34:17 +0000693 }
694
695 // Save the current IR generation state.
John McCall777d6e52011-08-11 02:22:43 +0000696 CGBuilderTy::InsertPoint savedIP = Builder.saveAndClearIP();
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700697 auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, CurEHLocation);
John McCallf1549f62010-07-06 01:34:17 +0000698
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700699 const EHPersonality &personality = EHPersonality::get(*this);
John McCall8262b6a2010-07-17 00:43:08 +0000700
John McCallf1549f62010-07-06 01:34:17 +0000701 // Create and configure the landing pad.
John McCall777d6e52011-08-11 02:22:43 +0000702 llvm::BasicBlock *lpad = createBasicBlock("lpad");
703 EmitBlock(lpad);
John McCallf1549f62010-07-06 01:34:17 +0000704
Bill Wendling285cfd82011-09-19 20:31:14 +0000705 llvm::LandingPadInst *LPadInst =
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700706 Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, nullptr),
Bill Wendling285cfd82011-09-19 20:31:14 +0000707 getOpaquePersonalityFn(CGM, personality), 0);
708
709 llvm::Value *LPadExn = Builder.CreateExtractValue(LPadInst, 0);
710 Builder.CreateStore(LPadExn, getExceptionSlot());
711 llvm::Value *LPadSel = Builder.CreateExtractValue(LPadInst, 1);
712 Builder.CreateStore(LPadSel, getEHSelectorSlot());
713
John McCallf1549f62010-07-06 01:34:17 +0000714 // Save the exception pointer. It's safe to use a single exception
715 // pointer per function because EH cleanups can never have nested
716 // try/catches.
Bill Wendling285cfd82011-09-19 20:31:14 +0000717 // Build the landingpad instruction.
John McCallf1549f62010-07-06 01:34:17 +0000718
719 // Accumulate all the handlers in scope.
John McCall777d6e52011-08-11 02:22:43 +0000720 bool hasCatchAll = false;
721 bool hasCleanup = false;
722 bool hasFilter = false;
723 SmallVector<llvm::Value*, 4> filterTypes;
724 llvm::SmallPtrSet<llvm::Value*, 4> catchTypes;
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700725 for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end(); I != E;
726 ++I) {
John McCallf1549f62010-07-06 01:34:17 +0000727
728 switch (I->getKind()) {
John McCall1f0fca52010-07-21 07:22:38 +0000729 case EHScope::Cleanup:
John McCall777d6e52011-08-11 02:22:43 +0000730 // If we have a cleanup, remember that.
731 hasCleanup = (hasCleanup || cast<EHCleanupScope>(*I).isEHCleanup());
John McCallda65ea82010-07-13 20:32:21 +0000732 continue;
733
John McCallf1549f62010-07-06 01:34:17 +0000734 case EHScope::Filter: {
735 assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
John McCall777d6e52011-08-11 02:22:43 +0000736 assert(!hasCatchAll && "EH filter reached after catch-all");
John McCallf1549f62010-07-06 01:34:17 +0000737
Bill Wendling285cfd82011-09-19 20:31:14 +0000738 // Filter scopes get added to the landingpad in weird ways.
John McCall777d6e52011-08-11 02:22:43 +0000739 EHFilterScope &filter = cast<EHFilterScope>(*I);
740 hasFilter = true;
John McCallf1549f62010-07-06 01:34:17 +0000741
Bill Wendling8990daf2011-09-22 20:32:54 +0000742 // Add all the filter values.
743 for (unsigned i = 0, e = filter.getNumFilters(); i != e; ++i)
744 filterTypes.push_back(filter.getFilter(i));
John McCallf1549f62010-07-06 01:34:17 +0000745 goto done;
746 }
747
748 case EHScope::Terminate:
749 // Terminate scopes are basically catch-alls.
John McCall777d6e52011-08-11 02:22:43 +0000750 assert(!hasCatchAll);
751 hasCatchAll = true;
John McCallf1549f62010-07-06 01:34:17 +0000752 goto done;
753
754 case EHScope::Catch:
755 break;
756 }
757
John McCall777d6e52011-08-11 02:22:43 +0000758 EHCatchScope &catchScope = cast<EHCatchScope>(*I);
759 for (unsigned hi = 0, he = catchScope.getNumHandlers(); hi != he; ++hi) {
760 EHCatchScope::Handler handler = catchScope.getHandler(hi);
John McCallf1549f62010-07-06 01:34:17 +0000761
John McCall777d6e52011-08-11 02:22:43 +0000762 // If this is a catch-all, register that and abort.
763 if (!handler.Type) {
764 assert(!hasCatchAll);
765 hasCatchAll = true;
766 goto done;
John McCallf1549f62010-07-06 01:34:17 +0000767 }
768
769 // Check whether we already have a handler for this type.
Stephen Hines176edba2014-12-01 14:53:08 -0800770 if (catchTypes.insert(handler.Type).second)
Bill Wendling285cfd82011-09-19 20:31:14 +0000771 // If not, add it directly to the landingpad.
772 LPadInst->addClause(handler.Type);
John McCallf1549f62010-07-06 01:34:17 +0000773 }
John McCallf1549f62010-07-06 01:34:17 +0000774 }
775
776 done:
Bill Wendling285cfd82011-09-19 20:31:14 +0000777 // If we have a catch-all, add null to the landingpad.
John McCall777d6e52011-08-11 02:22:43 +0000778 assert(!(hasCatchAll && hasFilter));
779 if (hasCatchAll) {
Bill Wendling285cfd82011-09-19 20:31:14 +0000780 LPadInst->addClause(getCatchAllValue(*this));
John McCallf1549f62010-07-06 01:34:17 +0000781
782 // If we have an EH filter, we need to add those handlers in the
Bill Wendling285cfd82011-09-19 20:31:14 +0000783 // right place in the landingpad, which is to say, at the end.
John McCall777d6e52011-08-11 02:22:43 +0000784 } else if (hasFilter) {
Bill Wendling40ccacc2011-09-19 22:08:36 +0000785 // Create a filter expression: a constant array indicating which filter
786 // types there are. The personality routine only lands here if the filter
787 // doesn't match.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000788 SmallVector<llvm::Constant*, 8> Filters;
Bill Wendling285cfd82011-09-19 20:31:14 +0000789 llvm::ArrayType *AType =
790 llvm::ArrayType::get(!filterTypes.empty() ?
791 filterTypes[0]->getType() : Int8PtrTy,
792 filterTypes.size());
793
794 for (unsigned i = 0, e = filterTypes.size(); i != e; ++i)
795 Filters.push_back(cast<llvm::Constant>(filterTypes[i]));
796 llvm::Constant *FilterArray = llvm::ConstantArray::get(AType, Filters);
797 LPadInst->addClause(FilterArray);
John McCallf1549f62010-07-06 01:34:17 +0000798
799 // Also check whether we need a cleanup.
Bill Wendling285cfd82011-09-19 20:31:14 +0000800 if (hasCleanup)
801 LPadInst->setCleanup(true);
John McCallf1549f62010-07-06 01:34:17 +0000802
803 // Otherwise, signal that we at least have cleanups.
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700804 } else if (hasCleanup) {
805 LPadInst->setCleanup(true);
John McCallf1549f62010-07-06 01:34:17 +0000806 }
807
Bill Wendling285cfd82011-09-19 20:31:14 +0000808 assert((LPadInst->getNumClauses() > 0 || LPadInst->isCleanup()) &&
809 "landingpad instruction has no clauses!");
John McCallf1549f62010-07-06 01:34:17 +0000810
811 // Tell the backend how to generate the landing pad.
John McCall777d6e52011-08-11 02:22:43 +0000812 Builder.CreateBr(getEHDispatchBlock(EHStack.getInnermostEHScope()));
John McCallf1549f62010-07-06 01:34:17 +0000813
814 // Restore the old IR generation state.
John McCall777d6e52011-08-11 02:22:43 +0000815 Builder.restoreIP(savedIP);
John McCallf1549f62010-07-06 01:34:17 +0000816
John McCall777d6e52011-08-11 02:22:43 +0000817 return lpad;
John McCallf1549f62010-07-06 01:34:17 +0000818}
819
John McCall777d6e52011-08-11 02:22:43 +0000820/// Emit the structure of the dispatch block for the given catch scope.
821/// It is an invariant that the dispatch block already exists.
822static void emitCatchDispatchBlock(CodeGenFunction &CGF,
823 EHCatchScope &catchScope) {
824 llvm::BasicBlock *dispatchBlock = catchScope.getCachedEHDispatchBlock();
825 assert(dispatchBlock);
826
827 // If there's only a single catch-all, getEHDispatchBlock returned
828 // that catch-all as the dispatch block.
829 if (catchScope.getNumHandlers() == 1 &&
830 catchScope.getHandler(0).isCatchAll()) {
831 assert(dispatchBlock == catchScope.getHandler(0).Block);
832 return;
833 }
834
835 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveIP();
836 CGF.EmitBlockAfterUses(dispatchBlock);
837
838 // Select the right handler.
839 llvm::Value *llvm_eh_typeid_for =
840 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
841
842 // Load the selector value.
Bill Wendlingae270592011-09-15 18:57:19 +0000843 llvm::Value *selector = CGF.getSelectorFromSlot();
John McCall777d6e52011-08-11 02:22:43 +0000844
845 // Test against each of the exception types we claim to catch.
846 for (unsigned i = 0, e = catchScope.getNumHandlers(); ; ++i) {
847 assert(i < e && "ran off end of handlers!");
848 const EHCatchScope::Handler &handler = catchScope.getHandler(i);
849
850 llvm::Value *typeValue = handler.Type;
851 assert(typeValue && "fell into catch-all case!");
852 typeValue = CGF.Builder.CreateBitCast(typeValue, CGF.Int8PtrTy);
853
854 // Figure out the next block.
855 bool nextIsEnd;
856 llvm::BasicBlock *nextBlock;
857
858 // If this is the last handler, we're at the end, and the next
859 // block is the block for the enclosing EH scope.
860 if (i + 1 == e) {
861 nextBlock = CGF.getEHDispatchBlock(catchScope.getEnclosingEHScope());
862 nextIsEnd = true;
863
864 // If the next handler is a catch-all, we're at the end, and the
865 // next block is that handler.
866 } else if (catchScope.getHandler(i+1).isCatchAll()) {
867 nextBlock = catchScope.getHandler(i+1).Block;
868 nextIsEnd = true;
869
870 // Otherwise, we're not at the end and we need a new block.
871 } else {
872 nextBlock = CGF.createBasicBlock("catch.fallthrough");
873 nextIsEnd = false;
874 }
875
876 // Figure out the catch type's index in the LSDA's type table.
877 llvm::CallInst *typeIndex =
878 CGF.Builder.CreateCall(llvm_eh_typeid_for, typeValue);
879 typeIndex->setDoesNotThrow();
880
881 llvm::Value *matchesTypeIndex =
882 CGF.Builder.CreateICmpEQ(selector, typeIndex, "matches");
883 CGF.Builder.CreateCondBr(matchesTypeIndex, handler.Block, nextBlock);
884
885 // If the next handler is a catch-all, we're completely done.
886 if (nextIsEnd) {
887 CGF.Builder.restoreIP(savedIP);
888 return;
John McCall777d6e52011-08-11 02:22:43 +0000889 }
Ahmed Charlese8e92b92012-02-19 11:57:29 +0000890 // Otherwise we need to emit and continue at that block.
891 CGF.EmitBlock(nextBlock);
John McCall777d6e52011-08-11 02:22:43 +0000892 }
John McCall777d6e52011-08-11 02:22:43 +0000893}
894
895void CodeGenFunction::popCatchScope() {
896 EHCatchScope &catchScope = cast<EHCatchScope>(*EHStack.begin());
897 if (catchScope.hasEHBranches())
898 emitCatchDispatchBlock(*this, catchScope);
899 EHStack.popCatch();
900}
901
John McCall59a70002010-07-07 06:56:46 +0000902void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallf1549f62010-07-06 01:34:17 +0000903 unsigned NumHandlers = S.getNumHandlers();
904 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
905 assert(CatchScope.getNumHandlers() == NumHandlers);
Mike Stump2bf701e2009-11-20 23:44:51 +0000906
John McCall777d6e52011-08-11 02:22:43 +0000907 // If the catch was not required, bail out now.
908 if (!CatchScope.hasEHBranches()) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700909 CatchScope.clearHandlerBlocks();
John McCall777d6e52011-08-11 02:22:43 +0000910 EHStack.popCatch();
911 return;
912 }
913
914 // Emit the structure of the EH dispatch for this catch.
915 emitCatchDispatchBlock(*this, CatchScope);
916
John McCallf1549f62010-07-06 01:34:17 +0000917 // Copy the handler blocks off before we pop the EH stack. Emitting
918 // the handlers might scribble on this memory.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000919 SmallVector<EHCatchScope::Handler, 8> Handlers(NumHandlers);
John McCallf1549f62010-07-06 01:34:17 +0000920 memcpy(Handlers.data(), CatchScope.begin(),
921 NumHandlers * sizeof(EHCatchScope::Handler));
John McCall777d6e52011-08-11 02:22:43 +0000922
John McCallf1549f62010-07-06 01:34:17 +0000923 EHStack.popCatch();
Mike Stump2bf701e2009-11-20 23:44:51 +0000924
John McCallf1549f62010-07-06 01:34:17 +0000925 // The fall-through block.
926 llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
Mike Stump2bf701e2009-11-20 23:44:51 +0000927
John McCallf1549f62010-07-06 01:34:17 +0000928 // We just emitted the body of the try; jump to the continue block.
929 if (HaveInsertPoint())
930 Builder.CreateBr(ContBB);
Mike Stump639787c2009-12-02 19:53:57 +0000931
John McCallf5533012012-06-15 05:27:05 +0000932 // Determine if we need an implicit rethrow for all these catch handlers;
933 // see the comment below.
934 bool doImplicitRethrow = false;
John McCall59a70002010-07-07 06:56:46 +0000935 if (IsFnTryBlock)
John McCallf5533012012-06-15 05:27:05 +0000936 doImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
937 isa<CXXConstructorDecl>(CurCodeDecl);
John McCall59a70002010-07-07 06:56:46 +0000938
John McCall777d6e52011-08-11 02:22:43 +0000939 // Perversely, we emit the handlers backwards precisely because we
940 // want them to appear in source order. In all of these cases, the
941 // catch block will have exactly one predecessor, which will be a
942 // particular block in the catch dispatch. However, in the case of
943 // a catch-all, one of the dispatch blocks will branch to two
944 // different handlers, and EmitBlockAfterUses will cause the second
945 // handler to be moved before the first.
946 for (unsigned I = NumHandlers; I != 0; --I) {
947 llvm::BasicBlock *CatchBlock = Handlers[I-1].Block;
948 EmitBlockAfterUses(CatchBlock);
Mike Stump8755ec32009-12-10 00:06:18 +0000949
John McCallf1549f62010-07-06 01:34:17 +0000950 // Catch the exception if this isn't a catch-all.
John McCall777d6e52011-08-11 02:22:43 +0000951 const CXXCatchStmt *C = S.getHandler(I-1);
Mike Stump2bf701e2009-11-20 23:44:51 +0000952
John McCallf1549f62010-07-06 01:34:17 +0000953 // Enter a cleanup scope, including the catch variable and the
954 // end-catch.
955 RunCleanupsScope CatchScope(*this);
Mike Stump2bf701e2009-11-20 23:44:51 +0000956
John McCallf1549f62010-07-06 01:34:17 +0000957 // Initialize the catch variable and set up the cleanups.
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -0700958 CGM.getCXXABI().emitBeginCatch(*this, C);
John McCallf1549f62010-07-06 01:34:17 +0000959
Stephen Hines651f13c2014-04-23 16:59:28 -0700960 // Emit the PGO counter increment.
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -0700961 incrementProfileCounter(C);
Stephen Hines651f13c2014-04-23 16:59:28 -0700962
John McCallf1549f62010-07-06 01:34:17 +0000963 // Perform the body of the catch.
964 EmitStmt(C->getHandlerBlock());
965
John McCallf5533012012-06-15 05:27:05 +0000966 // [except.handle]p11:
967 // The currently handled exception is rethrown if control
968 // reaches the end of a handler of the function-try-block of a
969 // constructor or destructor.
970
971 // It is important that we only do this on fallthrough and not on
972 // return. Note that it's illegal to put a return in a
973 // constructor function-try-block's catch handler (p14), so this
974 // really only applies to destructors.
975 if (doImplicitRethrow && HaveInsertPoint()) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700976 CGM.getCXXABI().emitRethrow(*this, /*isNoReturn*/false);
John McCallf5533012012-06-15 05:27:05 +0000977 Builder.CreateUnreachable();
978 Builder.ClearInsertionPoint();
979 }
980
John McCallf1549f62010-07-06 01:34:17 +0000981 // Fall out through the catch cleanups.
982 CatchScope.ForceCleanup();
983
984 // Branch out of the try.
985 if (HaveInsertPoint())
986 Builder.CreateBr(ContBB);
Mike Stump2bf701e2009-11-20 23:44:51 +0000987 }
988
John McCallf1549f62010-07-06 01:34:17 +0000989 EmitBlock(ContBB);
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -0700990 incrementProfileCounter(&S);
Mike Stump2bf701e2009-11-20 23:44:51 +0000991}
Mike Stumpd88ea562009-12-09 03:35:49 +0000992
John McCall55b20fc2010-07-21 00:52:03 +0000993namespace {
John McCall1f0fca52010-07-21 07:22:38 +0000994 struct CallEndCatchForFinally : EHScopeStack::Cleanup {
John McCall55b20fc2010-07-21 00:52:03 +0000995 llvm::Value *ForEHVar;
996 llvm::Value *EndCatchFn;
997 CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn)
998 : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
999
Stephen Hines651f13c2014-04-23 16:59:28 -07001000 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall55b20fc2010-07-21 00:52:03 +00001001 llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
1002 llvm::BasicBlock *CleanupContBB =
1003 CGF.createBasicBlock("finally.cleanup.cont");
1004
1005 llvm::Value *ShouldEndCatch =
1006 CGF.Builder.CreateLoad(ForEHVar, "finally.endcatch");
1007 CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1008 CGF.EmitBlock(EndCatchBB);
John McCallbd7370a2013-02-28 19:01:20 +00001009 CGF.EmitRuntimeCallOrInvoke(EndCatchFn); // catch-all, so might throw
John McCall55b20fc2010-07-21 00:52:03 +00001010 CGF.EmitBlock(CleanupContBB);
1011 }
1012 };
John McCall77199712010-07-21 05:47:49 +00001013
John McCall1f0fca52010-07-21 07:22:38 +00001014 struct PerformFinally : EHScopeStack::Cleanup {
John McCall77199712010-07-21 05:47:49 +00001015 const Stmt *Body;
1016 llvm::Value *ForEHVar;
1017 llvm::Value *EndCatchFn;
1018 llvm::Value *RethrowFn;
1019 llvm::Value *SavedExnVar;
1020
1021 PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
1022 llvm::Value *EndCatchFn,
1023 llvm::Value *RethrowFn, llvm::Value *SavedExnVar)
1024 : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1025 RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
1026
Stephen Hines651f13c2014-04-23 16:59:28 -07001027 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall77199712010-07-21 05:47:49 +00001028 // Enter a cleanup to call the end-catch function if one was provided.
1029 if (EndCatchFn)
John McCall1f0fca52010-07-21 07:22:38 +00001030 CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
1031 ForEHVar, EndCatchFn);
John McCall77199712010-07-21 05:47:49 +00001032
John McCalld96a8e72010-08-11 00:16:14 +00001033 // Save the current cleanup destination in case there are
1034 // cleanups in the finally block.
1035 llvm::Value *SavedCleanupDest =
1036 CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
1037 "cleanup.dest.saved");
1038
John McCall77199712010-07-21 05:47:49 +00001039 // Emit the finally block.
1040 CGF.EmitStmt(Body);
1041
1042 // If the end of the finally is reachable, check whether this was
1043 // for EH. If so, rethrow.
1044 if (CGF.HaveInsertPoint()) {
1045 llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
1046 llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
1047
1048 llvm::Value *ShouldRethrow =
1049 CGF.Builder.CreateLoad(ForEHVar, "finally.shouldthrow");
1050 CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1051
1052 CGF.EmitBlock(RethrowBB);
1053 if (SavedExnVar) {
John McCallbd7370a2013-02-28 19:01:20 +00001054 CGF.EmitRuntimeCallOrInvoke(RethrowFn,
1055 CGF.Builder.CreateLoad(SavedExnVar));
John McCall77199712010-07-21 05:47:49 +00001056 } else {
John McCallbd7370a2013-02-28 19:01:20 +00001057 CGF.EmitRuntimeCallOrInvoke(RethrowFn);
John McCall77199712010-07-21 05:47:49 +00001058 }
1059 CGF.Builder.CreateUnreachable();
1060
1061 CGF.EmitBlock(ContBB);
John McCalld96a8e72010-08-11 00:16:14 +00001062
1063 // Restore the cleanup destination.
1064 CGF.Builder.CreateStore(SavedCleanupDest,
1065 CGF.getNormalCleanupDestSlot());
John McCall77199712010-07-21 05:47:49 +00001066 }
1067
1068 // Leave the end-catch cleanup. As an optimization, pretend that
1069 // the fallthrough path was inaccessible; we've dynamically proven
1070 // that we're not in the EH case along that path.
1071 if (EndCatchFn) {
1072 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1073 CGF.PopCleanupBlock();
1074 CGF.Builder.restoreIP(SavedIP);
1075 }
1076
1077 // Now make sure we actually have an insertion point or the
1078 // cleanup gods will hate us.
1079 CGF.EnsureInsertPoint();
1080 }
1081 };
John McCall55b20fc2010-07-21 00:52:03 +00001082}
1083
John McCallf1549f62010-07-06 01:34:17 +00001084/// Enters a finally block for an implementation using zero-cost
1085/// exceptions. This is mostly general, but hard-codes some
1086/// language/ABI-specific behavior in the catch-all sections.
John McCalld768e9d2011-06-22 02:32:12 +00001087void CodeGenFunction::FinallyInfo::enter(CodeGenFunction &CGF,
1088 const Stmt *body,
1089 llvm::Constant *beginCatchFn,
1090 llvm::Constant *endCatchFn,
1091 llvm::Constant *rethrowFn) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001092 assert((beginCatchFn != nullptr) == (endCatchFn != nullptr) &&
John McCallf1549f62010-07-06 01:34:17 +00001093 "begin/end catch functions not paired");
John McCalld768e9d2011-06-22 02:32:12 +00001094 assert(rethrowFn && "rethrow function is required");
1095
1096 BeginCatchFn = beginCatchFn;
Mike Stumpd88ea562009-12-09 03:35:49 +00001097
John McCallf1549f62010-07-06 01:34:17 +00001098 // The rethrow function has one of the following two types:
1099 // void (*)()
1100 // void (*)(void*)
1101 // In the latter case we need to pass it the exception object.
1102 // But we can't use the exception slot because the @finally might
1103 // have a landing pad (which would overwrite the exception slot).
Chris Lattner2acc6e32011-07-18 04:24:23 +00001104 llvm::FunctionType *rethrowFnTy =
John McCallf1549f62010-07-06 01:34:17 +00001105 cast<llvm::FunctionType>(
John McCalld768e9d2011-06-22 02:32:12 +00001106 cast<llvm::PointerType>(rethrowFn->getType())->getElementType());
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001107 SavedExnVar = nullptr;
John McCalld768e9d2011-06-22 02:32:12 +00001108 if (rethrowFnTy->getNumParams())
1109 SavedExnVar = CGF.CreateTempAlloca(CGF.Int8PtrTy, "finally.exn");
Mike Stumpd88ea562009-12-09 03:35:49 +00001110
John McCallf1549f62010-07-06 01:34:17 +00001111 // A finally block is a statement which must be executed on any edge
1112 // out of a given scope. Unlike a cleanup, the finally block may
1113 // contain arbitrary control flow leading out of itself. In
1114 // addition, finally blocks should always be executed, even if there
1115 // are no catch handlers higher on the stack. Therefore, we
1116 // surround the protected scope with a combination of a normal
1117 // cleanup (to catch attempts to break out of the block via normal
1118 // control flow) and an EH catch-all (semantically "outside" any try
1119 // statement to which the finally block might have been attached).
1120 // The finally block itself is generated in the context of a cleanup
1121 // which conditionally leaves the catch-all.
John McCall3d3ec1c2010-04-21 10:05:39 +00001122
John McCallf1549f62010-07-06 01:34:17 +00001123 // Jump destination for performing the finally block on an exception
1124 // edge. We'll never actually reach this block, so unreachable is
1125 // fine.
John McCalld768e9d2011-06-22 02:32:12 +00001126 RethrowDest = CGF.getJumpDestInCurrentScope(CGF.getUnreachableBlock());
John McCall3d3ec1c2010-04-21 10:05:39 +00001127
John McCallf1549f62010-07-06 01:34:17 +00001128 // Whether the finally block is being executed for EH purposes.
John McCalld768e9d2011-06-22 02:32:12 +00001129 ForEHVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "finally.for-eh");
1130 CGF.Builder.CreateStore(CGF.Builder.getFalse(), ForEHVar);
Mike Stumpd88ea562009-12-09 03:35:49 +00001131
John McCallf1549f62010-07-06 01:34:17 +00001132 // Enter a normal cleanup which will perform the @finally block.
John McCalld768e9d2011-06-22 02:32:12 +00001133 CGF.EHStack.pushCleanup<PerformFinally>(NormalCleanup, body,
1134 ForEHVar, endCatchFn,
1135 rethrowFn, SavedExnVar);
John McCallf1549f62010-07-06 01:34:17 +00001136
1137 // Enter a catch-all scope.
John McCalld768e9d2011-06-22 02:32:12 +00001138 llvm::BasicBlock *catchBB = CGF.createBasicBlock("finally.catchall");
1139 EHCatchScope *catchScope = CGF.EHStack.pushCatch(1);
1140 catchScope->setCatchAllHandler(0, catchBB);
John McCallf1549f62010-07-06 01:34:17 +00001141}
1142
John McCalld768e9d2011-06-22 02:32:12 +00001143void CodeGenFunction::FinallyInfo::exit(CodeGenFunction &CGF) {
John McCallf1549f62010-07-06 01:34:17 +00001144 // Leave the finally catch-all.
John McCalld768e9d2011-06-22 02:32:12 +00001145 EHCatchScope &catchScope = cast<EHCatchScope>(*CGF.EHStack.begin());
1146 llvm::BasicBlock *catchBB = catchScope.getHandler(0).Block;
John McCall777d6e52011-08-11 02:22:43 +00001147
1148 CGF.popCatchScope();
John McCallf1549f62010-07-06 01:34:17 +00001149
John McCalld768e9d2011-06-22 02:32:12 +00001150 // If there are any references to the catch-all block, emit it.
1151 if (catchBB->use_empty()) {
1152 delete catchBB;
1153 } else {
1154 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveAndClearIP();
1155 CGF.EmitBlock(catchBB);
John McCallf1549f62010-07-06 01:34:17 +00001156
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001157 llvm::Value *exn = nullptr;
John McCallf1549f62010-07-06 01:34:17 +00001158
John McCalld768e9d2011-06-22 02:32:12 +00001159 // If there's a begin-catch function, call it.
1160 if (BeginCatchFn) {
Bill Wendlingae270592011-09-15 18:57:19 +00001161 exn = CGF.getExceptionFromSlot();
John McCallbd7370a2013-02-28 19:01:20 +00001162 CGF.EmitNounwindRuntimeCall(BeginCatchFn, exn);
John McCalld768e9d2011-06-22 02:32:12 +00001163 }
1164
1165 // If we need to remember the exception pointer to rethrow later, do so.
1166 if (SavedExnVar) {
Bill Wendlingae270592011-09-15 18:57:19 +00001167 if (!exn) exn = CGF.getExceptionFromSlot();
John McCalld768e9d2011-06-22 02:32:12 +00001168 CGF.Builder.CreateStore(exn, SavedExnVar);
1169 }
1170
1171 // Tell the cleanups in the finally block that we're do this for EH.
1172 CGF.Builder.CreateStore(CGF.Builder.getTrue(), ForEHVar);
1173
1174 // Thread a jump through the finally cleanup.
1175 CGF.EmitBranchThroughCleanup(RethrowDest);
1176
1177 CGF.Builder.restoreIP(savedIP);
1178 }
1179
1180 // Finally, leave the @finally cleanup.
1181 CGF.PopCleanupBlock();
John McCallf1549f62010-07-06 01:34:17 +00001182}
1183
1184llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
1185 if (TerminateLandingPad)
1186 return TerminateLandingPad;
1187
1188 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1189
1190 // This will get inserted at the end of the function.
1191 TerminateLandingPad = createBasicBlock("terminate.lpad");
1192 Builder.SetInsertPoint(TerminateLandingPad);
1193
1194 // Tell the backend that this is a landing pad.
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001195 const EHPersonality &Personality = EHPersonality::get(*this);
Bill Wendling285cfd82011-09-19 20:31:14 +00001196 llvm::LandingPadInst *LPadInst =
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001197 Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, nullptr),
Bill Wendling285cfd82011-09-19 20:31:14 +00001198 getOpaquePersonalityFn(CGM, Personality), 0);
1199 LPadInst->addClause(getCatchAllValue(*this));
John McCallf1549f62010-07-06 01:34:17 +00001200
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07001201 llvm::Value *Exn = 0;
1202 if (getLangOpts().CPlusPlus)
1203 Exn = Builder.CreateExtractValue(LPadInst, 0);
1204 llvm::CallInst *terminateCall =
1205 CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
John McCall66b22772013-02-12 03:51:46 +00001206 terminateCall->setDoesNotReturn();
John McCalld16c2cf2011-02-08 08:22:06 +00001207 Builder.CreateUnreachable();
Mike Stumpd88ea562009-12-09 03:35:49 +00001208
John McCallf1549f62010-07-06 01:34:17 +00001209 // Restore the saved insertion state.
1210 Builder.restoreIP(SavedIP);
John McCall891f80e2010-04-30 00:06:43 +00001211
John McCallf1549f62010-07-06 01:34:17 +00001212 return TerminateLandingPad;
Mike Stumpd88ea562009-12-09 03:35:49 +00001213}
Mike Stump9b39c512009-12-09 22:59:31 +00001214
1215llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
Mike Stump182f3832009-12-10 00:02:42 +00001216 if (TerminateHandler)
1217 return TerminateHandler;
1218
John McCallf1549f62010-07-06 01:34:17 +00001219 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
Mike Stump76958092009-12-09 23:31:35 +00001220
John McCallf1549f62010-07-06 01:34:17 +00001221 // Set up the terminate handler. This block is inserted at the very
1222 // end of the function by FinishFunction.
Mike Stump182f3832009-12-10 00:02:42 +00001223 TerminateHandler = createBasicBlock("terminate.handler");
John McCallf1549f62010-07-06 01:34:17 +00001224 Builder.SetInsertPoint(TerminateHandler);
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07001225 llvm::Value *Exn = 0;
1226 if (getLangOpts().CPlusPlus)
1227 Exn = getExceptionFromSlot();
1228 llvm::CallInst *terminateCall =
1229 CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
John McCall45ff3802013-06-20 21:37:43 +00001230 terminateCall->setDoesNotReturn();
Mike Stump9b39c512009-12-09 22:59:31 +00001231 Builder.CreateUnreachable();
1232
John McCall3d3ec1c2010-04-21 10:05:39 +00001233 // Restore the saved insertion state.
John McCallf1549f62010-07-06 01:34:17 +00001234 Builder.restoreIP(SavedIP);
Mike Stump76958092009-12-09 23:31:35 +00001235
Mike Stump9b39c512009-12-09 22:59:31 +00001236 return TerminateHandler;
1237}
John McCallf1549f62010-07-06 01:34:17 +00001238
David Chisnallc6860042012-11-07 16:50:40 +00001239llvm::BasicBlock *CodeGenFunction::getEHResumeBlock(bool isCleanup) {
John McCall777d6e52011-08-11 02:22:43 +00001240 if (EHResumeBlock) return EHResumeBlock;
John McCallff8e1152010-07-23 21:56:41 +00001241
1242 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1243
1244 // We emit a jump to a notional label at the outermost unwind state.
John McCall777d6e52011-08-11 02:22:43 +00001245 EHResumeBlock = createBasicBlock("eh.resume");
1246 Builder.SetInsertPoint(EHResumeBlock);
John McCallff8e1152010-07-23 21:56:41 +00001247
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001248 const EHPersonality &Personality = EHPersonality::get(*this);
John McCallff8e1152010-07-23 21:56:41 +00001249
1250 // This can always be a call because we necessarily didn't find
1251 // anything on the EH stack which needs our help.
Benjamin Krameraf2771b2012-02-08 12:41:24 +00001252 const char *RethrowName = Personality.CatchallRethrowFn;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001253 if (RethrowName != nullptr && !isCleanup) {
John McCallbd7370a2013-02-28 19:01:20 +00001254 EmitRuntimeCall(getCatchallRethrowFn(CGM, RethrowName),
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001255 getExceptionFromSlot())->setDoesNotReturn();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001256 Builder.CreateUnreachable();
1257 Builder.restoreIP(SavedIP);
1258 return EHResumeBlock;
John McCall93c332a2011-05-28 21:13:02 +00001259 }
1260
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001261 // Recreate the landingpad's return value for the 'resume' instruction.
1262 llvm::Value *Exn = getExceptionFromSlot();
1263 llvm::Value *Sel = getSelectorFromSlot();
John McCallff8e1152010-07-23 21:56:41 +00001264
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001265 llvm::Type *LPadType = llvm::StructType::get(Exn->getType(),
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001266 Sel->getType(), nullptr);
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001267 llvm::Value *LPadVal = llvm::UndefValue::get(LPadType);
1268 LPadVal = Builder.CreateInsertValue(LPadVal, Exn, 0, "lpad.val");
1269 LPadVal = Builder.CreateInsertValue(LPadVal, Sel, 1, "lpad.val");
1270
1271 Builder.CreateResume(LPadVal);
John McCallff8e1152010-07-23 21:56:41 +00001272 Builder.restoreIP(SavedIP);
John McCall777d6e52011-08-11 02:22:43 +00001273 return EHResumeBlock;
John McCallff8e1152010-07-23 21:56:41 +00001274}
Reid Kleckner98592d92013-09-16 21:46:30 +00001275
1276void CodeGenFunction::EmitSEHTryStmt(const SEHTryStmt &S) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001277 // FIXME: Implement SEH on other architectures.
1278 const llvm::Triple &T = CGM.getTarget().getTriple();
1279 if (T.getArch() != llvm::Triple::x86_64 ||
1280 !T.isKnownWindowsMSVCEnvironment()) {
1281 ErrorUnsupported(&S, "__try statement");
1282 return;
1283 }
1284
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07001285 EnterSEHTryStmt(S);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001286 {
1287 JumpDest TryExit = getJumpDestInCurrentScope("__try.__leave");
1288
1289 SEHTryEpilogueStack.push_back(&TryExit);
1290 EmitStmt(S.getTryBlock());
1291 SEHTryEpilogueStack.pop_back();
1292
1293 if (!TryExit.getBlock()->use_empty())
1294 EmitBlock(TryExit.getBlock(), /*IsFinished=*/true);
1295 else
1296 delete TryExit.getBlock();
1297 }
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07001298 ExitSEHTryStmt(S);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001299}
1300
1301namespace {
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07001302struct PerformSEHFinally : EHScopeStack::Cleanup {
1303 llvm::Function *OutlinedFinally;
1304 PerformSEHFinally(llvm::Function *OutlinedFinally)
1305 : OutlinedFinally(OutlinedFinally) {}
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001306
1307 void Emit(CodeGenFunction &CGF, Flags F) override {
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07001308 ASTContext &Context = CGF.getContext();
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -07001309 QualType ArgTys[2] = {Context.UnsignedCharTy, Context.VoidPtrTy};
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07001310 FunctionProtoType::ExtProtoInfo EPI;
1311 const auto *FTP = cast<FunctionType>(
1312 Context.getFunctionType(Context.VoidTy, ArgTys, EPI));
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001313
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07001314 CallArgList Args;
1315 llvm::Value *IsForEH =
1316 llvm::ConstantInt::get(CGF.ConvertType(ArgTys[0]), F.isForEHCleanup());
1317 Args.add(RValue::get(IsForEH), ArgTys[0]);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001318
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07001319 CodeGenModule &CGM = CGF.CGM;
1320 llvm::Value *Zero = llvm::ConstantInt::get(CGM.Int32Ty, 0);
1321 llvm::Value *FrameAddr = CGM.getIntrinsic(llvm::Intrinsic::frameaddress);
1322 llvm::Value *FP = CGF.Builder.CreateCall(FrameAddr, Zero);
1323 Args.add(RValue::get(FP), ArgTys[1]);
1324
1325 const CGFunctionInfo &FnInfo =
1326 CGM.getTypes().arrangeFreeFunctionCall(Args, FTP, /*chainCall=*/false);
1327 CGF.EmitCall(FnInfo, OutlinedFinally, ReturnValueSlot(), Args);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001328 }
1329};
1330}
1331
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07001332namespace {
1333/// Find all local variable captures in the statement.
1334struct CaptureFinder : ConstStmtVisitor<CaptureFinder> {
1335 CodeGenFunction &ParentCGF;
1336 const VarDecl *ParentThis;
1337 SmallVector<const VarDecl *, 4> Captures;
1338 CaptureFinder(CodeGenFunction &ParentCGF, const VarDecl *ParentThis)
1339 : ParentCGF(ParentCGF), ParentThis(ParentThis) {}
1340
1341 void Visit(const Stmt *S) {
1342 // See if this is a capture, then recurse.
1343 ConstStmtVisitor<CaptureFinder>::Visit(S);
1344 for (const Stmt *Child : S->children())
1345 if (Child)
1346 Visit(Child);
1347 }
1348
1349 void VisitDeclRefExpr(const DeclRefExpr *E) {
1350 // If this is already a capture, just make sure we capture 'this'.
1351 if (E->refersToEnclosingVariableOrCapture()) {
1352 Captures.push_back(ParentThis);
1353 return;
1354 }
1355
1356 const auto *D = dyn_cast<VarDecl>(E->getDecl());
1357 if (D && D->isLocalVarDeclOrParm() && D->hasLocalStorage())
1358 Captures.push_back(D);
1359 }
1360
1361 void VisitCXXThisExpr(const CXXThisExpr *E) {
1362 Captures.push_back(ParentThis);
1363 }
1364};
1365}
1366
1367void CodeGenFunction::EmitCapturedLocals(CodeGenFunction &ParentCGF,
1368 const Stmt *OutlinedStmt,
1369 llvm::Value *ParentFP) {
1370 // Find all captures in the Stmt.
1371 CaptureFinder Finder(ParentCGF, ParentCGF.CXXABIThisDecl);
1372 Finder.Visit(OutlinedStmt);
1373
1374 // Typically there are no captures and we can exit early.
1375 if (Finder.Captures.empty())
1376 return;
1377
1378 // Prepare the first two arguments to llvm.framerecover.
1379 llvm::Function *FrameRecoverFn = llvm::Intrinsic::getDeclaration(
1380 &CGM.getModule(), llvm::Intrinsic::framerecover);
1381 llvm::Constant *ParentI8Fn =
1382 llvm::ConstantExpr::getBitCast(ParentCGF.CurFn, Int8PtrTy);
1383
1384 // Create llvm.framerecover calls for all captures.
1385 for (const VarDecl *VD : Finder.Captures) {
1386 if (isa<ImplicitParamDecl>(VD)) {
1387 CGM.ErrorUnsupported(VD, "'this' captured by SEH");
1388 CXXThisValue = llvm::UndefValue::get(ConvertTypeForMem(VD->getType()));
1389 continue;
1390 }
1391 if (VD->getType()->isVariablyModifiedType()) {
1392 CGM.ErrorUnsupported(VD, "VLA captured by SEH");
1393 continue;
1394 }
1395 assert((isa<ImplicitParamDecl>(VD) || VD->isLocalVarDeclOrParm()) &&
1396 "captured non-local variable");
1397
1398 // If this decl hasn't been declared yet, it will be declared in the
1399 // OutlinedStmt.
1400 auto I = ParentCGF.LocalDeclMap.find(VD);
1401 if (I == ParentCGF.LocalDeclMap.end())
1402 continue;
1403 llvm::Value *ParentVar = I->second;
1404
1405 llvm::CallInst *RecoverCall = nullptr;
1406 CGBuilderTy Builder(AllocaInsertPt);
1407 if (auto *ParentAlloca = dyn_cast<llvm::AllocaInst>(ParentVar)) {
1408 // Mark the variable escaped if nobody else referenced it and compute the
1409 // frameescape index.
1410 auto InsertPair =
1411 ParentCGF.EscapedLocals.insert(std::make_pair(ParentAlloca, -1));
1412 if (InsertPair.second)
1413 InsertPair.first->second = ParentCGF.EscapedLocals.size() - 1;
1414 int FrameEscapeIdx = InsertPair.first->second;
1415 // call i8* @llvm.framerecover(i8* bitcast(@parentFn), i8* %fp, i32 N)
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -07001416 RecoverCall = Builder.CreateCall(
1417 FrameRecoverFn, {ParentI8Fn, ParentFP,
1418 llvm::ConstantInt::get(Int32Ty, FrameEscapeIdx)});
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07001419
1420 } else {
1421 // If the parent didn't have an alloca, we're doing some nested outlining.
1422 // Just clone the existing framerecover call, but tweak the FP argument to
1423 // use our FP value. All other arguments are constants.
1424 auto *ParentRecover =
1425 cast<llvm::IntrinsicInst>(ParentVar->stripPointerCasts());
1426 assert(ParentRecover->getIntrinsicID() == llvm::Intrinsic::framerecover &&
1427 "expected alloca or framerecover in parent LocalDeclMap");
1428 RecoverCall = cast<llvm::CallInst>(ParentRecover->clone());
1429 RecoverCall->setArgOperand(1, ParentFP);
1430 RecoverCall->insertBefore(AllocaInsertPt);
1431 }
1432
1433 // Bitcast the variable, rename it, and insert it in the local decl map.
1434 llvm::Value *ChildVar =
1435 Builder.CreateBitCast(RecoverCall, ParentVar->getType());
1436 ChildVar->setName(ParentVar->getName());
1437 LocalDeclMap[VD] = ChildVar;
1438 }
1439}
1440
1441/// Arrange a function prototype that can be called by Windows exception
1442/// handling personalities. On Win64, the prototype looks like:
1443/// RetTy func(void *EHPtrs, void *ParentFP);
1444void CodeGenFunction::startOutlinedSEHHelper(CodeGenFunction &ParentCGF,
1445 StringRef Name, QualType RetTy,
1446 FunctionArgList &Args,
1447 const Stmt *OutlinedStmt) {
1448 llvm::Function *ParentFn = ParentCGF.CurFn;
1449 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionDeclaration(
1450 RetTy, Args, FunctionType::ExtInfo(), /*isVariadic=*/false);
1451
1452 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
1453 llvm::Function *Fn = llvm::Function::Create(
1454 FnTy, llvm::GlobalValue::InternalLinkage, Name.str(), &CGM.getModule());
1455 // The filter is either in the same comdat as the function, or it's internal.
1456 if (llvm::Comdat *C = ParentFn->getComdat()) {
1457 Fn->setComdat(C);
1458 } else if (ParentFn->hasWeakLinkage() || ParentFn->hasLinkOnceLinkage()) {
1459 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(ParentFn->getName());
1460 ParentFn->setComdat(C);
1461 Fn->setComdat(C);
1462 } else {
1463 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
1464 }
1465
1466 IsOutlinedSEHHelper = true;
1467
1468 StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args,
1469 OutlinedStmt->getLocStart(), OutlinedStmt->getLocStart());
1470
1471 CGM.SetLLVMFunctionAttributes(nullptr, FnInfo, CurFn);
1472
1473 auto AI = Fn->arg_begin();
1474 ++AI;
1475 EmitCapturedLocals(ParentCGF, OutlinedStmt, &*AI);
1476}
1477
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001478/// Create a stub filter function that will ultimately hold the code of the
1479/// filter expression. The EH preparation passes in LLVM will outline the code
1480/// from the main function body into this stub.
1481llvm::Function *
1482CodeGenFunction::GenerateSEHFilterFunction(CodeGenFunction &ParentCGF,
1483 const SEHExceptStmt &Except) {
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07001484 const Expr *FilterExpr = Except.getFilterExpr();
1485 SourceLocation StartLoc = FilterExpr->getLocStart();
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001486
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07001487 SEHPointersDecl = ImplicitParamDecl::Create(
1488 getContext(), nullptr, StartLoc,
1489 &getContext().Idents.get("exception_pointers"), getContext().VoidPtrTy);
1490 FunctionArgList Args;
1491 Args.push_back(SEHPointersDecl);
1492 Args.push_back(ImplicitParamDecl::Create(
1493 getContext(), nullptr, StartLoc,
1494 &getContext().Idents.get("frame_pointer"), getContext().VoidPtrTy));
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001495
1496 // Get the mangled function name.
1497 SmallString<128> Name;
1498 {
1499 llvm::raw_svector_ostream OS(Name);
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07001500 const Decl *ParentCodeDecl = ParentCGF.CurCodeDecl;
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001501 const NamedDecl *Parent = dyn_cast_or_null<NamedDecl>(ParentCodeDecl);
1502 assert(Parent && "FIXME: handle unnamed decls (lambdas, blocks) with SEH");
1503 CGM.getCXXABI().getMangleContext().mangleSEHFilterExpression(Parent, OS);
1504 }
1505
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -07001506 startOutlinedSEHHelper(ParentCGF, Name, getContext().LongTy, Args,
1507 FilterExpr);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001508
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07001509 // Mark finally block calls as nounwind and noinline to make LLVM's job a
1510 // little easier.
1511 // FIXME: Remove these restrictions in the future.
1512 CurFn->addFnAttr(llvm::Attribute::NoUnwind);
1513 CurFn->addFnAttr(llvm::Attribute::NoInline);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001514
1515 EmitSEHExceptionCodeSave();
1516
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001517 // Emit the original filter expression, convert to i32, and return.
1518 llvm::Value *R = EmitScalarExpr(FilterExpr);
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -07001519 R = Builder.CreateIntCast(R, ConvertType(getContext().LongTy),
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001520 FilterExpr->getType()->isSignedIntegerType());
1521 Builder.CreateStore(R, ReturnValue);
1522
1523 FinishFunction(FilterExpr->getLocEnd());
1524
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07001525 return CurFn;
1526}
1527
1528llvm::Function *
1529CodeGenFunction::GenerateSEHFinallyFunction(CodeGenFunction &ParentCGF,
1530 const SEHFinallyStmt &Finally) {
1531 const Stmt *FinallyBlock = Finally.getBlock();
1532 SourceLocation StartLoc = FinallyBlock->getLocStart();
1533
1534 FunctionArgList Args;
1535 Args.push_back(ImplicitParamDecl::Create(
1536 getContext(), nullptr, StartLoc,
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -07001537 &getContext().Idents.get("abnormal_termination"),
1538 getContext().UnsignedCharTy));
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07001539 Args.push_back(ImplicitParamDecl::Create(
1540 getContext(), nullptr, StartLoc,
1541 &getContext().Idents.get("frame_pointer"), getContext().VoidPtrTy));
1542
1543 // Get the mangled function name.
1544 SmallString<128> Name;
1545 {
1546 llvm::raw_svector_ostream OS(Name);
1547 const Decl *ParentCodeDecl = ParentCGF.CurCodeDecl;
1548 const NamedDecl *Parent = dyn_cast_or_null<NamedDecl>(ParentCodeDecl);
1549 assert(Parent && "FIXME: handle unnamed decls (lambdas, blocks) with SEH");
1550 CGM.getCXXABI().getMangleContext().mangleSEHFinallyBlock(Parent, OS);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001551 }
1552
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07001553 startOutlinedSEHHelper(ParentCGF, Name, getContext().VoidTy, Args,
1554 FinallyBlock);
1555
1556 // Emit the original filter expression, convert to i32, and return.
1557 EmitStmt(FinallyBlock);
1558
1559 FinishFunction(FinallyBlock->getLocEnd());
1560
1561 return CurFn;
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001562}
1563
1564void CodeGenFunction::EmitSEHExceptionCodeSave() {
1565 // Save the exception code in the exception slot to unify exception access in
1566 // the filter function and the landing pad.
1567 // struct EXCEPTION_POINTERS {
1568 // EXCEPTION_RECORD *ExceptionRecord;
1569 // CONTEXT *ContextRecord;
1570 // };
1571 // void *exn.slot =
1572 // (void *)(uintptr_t)exception_pointers->ExceptionRecord->ExceptionCode;
1573 llvm::Value *Ptrs = Builder.CreateLoad(GetAddrOfLocalVar(SEHPointersDecl));
1574 llvm::Type *RecordTy = CGM.Int32Ty->getPointerTo();
1575 llvm::Type *PtrsTy = llvm::StructType::get(RecordTy, CGM.VoidPtrTy, nullptr);
1576 Ptrs = Builder.CreateBitCast(Ptrs, PtrsTy->getPointerTo());
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07001577 llvm::Value *Rec = Builder.CreateStructGEP(PtrsTy, Ptrs, 0);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001578 Rec = Builder.CreateLoad(Rec);
1579 llvm::Value *Code = Builder.CreateLoad(Rec);
1580 Code = Builder.CreateZExt(Code, CGM.IntPtrTy);
1581 // FIXME: Change landing pads to produce {i32, i32} and make the exception
1582 // slot an i32.
1583 Code = Builder.CreateIntToPtr(Code, CGM.VoidPtrTy);
1584 Builder.CreateStore(Code, getExceptionSlot());
1585}
1586
1587llvm::Value *CodeGenFunction::EmitSEHExceptionInfo() {
1588 // Sema should diagnose calling this builtin outside of a filter context, but
1589 // don't crash if we screw up.
1590 if (!SEHPointersDecl)
1591 return llvm::UndefValue::get(Int8PtrTy);
1592 return Builder.CreateLoad(GetAddrOfLocalVar(SEHPointersDecl));
1593}
1594
1595llvm::Value *CodeGenFunction::EmitSEHExceptionCode() {
1596 // If we're in a landing pad or filter function, the exception slot contains
1597 // the code.
1598 assert(ExceptionSlot);
1599 llvm::Value *Code =
1600 Builder.CreatePtrToInt(getExceptionFromSlot(), CGM.IntPtrTy);
1601 return Builder.CreateTrunc(Code, CGM.Int32Ty);
1602}
1603
1604llvm::Value *CodeGenFunction::EmitSEHAbnormalTermination() {
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07001605 // Abnormal termination is just the first parameter to the outlined finally
1606 // helper.
1607 auto AI = CurFn->arg_begin();
1608 return Builder.CreateZExt(&*AI, Int32Ty);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001609}
1610
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07001611void CodeGenFunction::EnterSEHTryStmt(const SEHTryStmt &S) {
1612 CodeGenFunction HelperCGF(CGM, /*suppressNewContext=*/true);
1613 if (const SEHFinallyStmt *Finally = S.getFinallyHandler()) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001614 // Push a cleanup for __finally blocks.
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07001615 llvm::Function *FinallyFunc =
1616 HelperCGF.GenerateSEHFinallyFunction(*this, *Finally);
1617 EHStack.pushCleanup<PerformSEHFinally>(NormalAndEHCleanup, FinallyFunc);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001618 return;
1619 }
1620
1621 // Otherwise, we must have an __except block.
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07001622 const SEHExceptStmt *Except = S.getExceptHandler();
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001623 assert(Except);
1624 EHCatchScope *CatchScope = EHStack.pushCatch(1);
1625
1626 // If the filter is known to evaluate to 1, then we can use the clause "catch
1627 // i8* null".
1628 llvm::Constant *C =
1629 CGM.EmitConstantExpr(Except->getFilterExpr(), getContext().IntTy, this);
1630 if (C && C->isOneValue()) {
1631 CatchScope->setCatchAllHandler(0, createBasicBlock("__except"));
1632 return;
1633 }
1634
1635 // In general, we have to emit an outlined filter function. Use the function
1636 // in place of the RTTI typeinfo global that C++ EH uses.
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001637 llvm::Function *FilterFunc =
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07001638 HelperCGF.GenerateSEHFilterFunction(*this, *Except);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001639 llvm::Constant *OpaqueFunc =
1640 llvm::ConstantExpr::getBitCast(FilterFunc, Int8PtrTy);
1641 CatchScope->setHandler(0, OpaqueFunc, createBasicBlock("__except"));
1642}
1643
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07001644void CodeGenFunction::ExitSEHTryStmt(const SEHTryStmt &S) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001645 // Just pop the cleanup if it's a __finally block.
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07001646 if (S.getFinallyHandler()) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001647 PopCleanupBlock();
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001648 return;
1649 }
1650
1651 // Otherwise, we must have an __except block.
1652 const SEHExceptStmt *Except = S.getExceptHandler();
1653 assert(Except && "__try must have __finally xor __except");
1654 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1655
1656 // Don't emit the __except block if the __try block lacked invokes.
1657 // TODO: Model unwind edges from instructions, either with iload / istore or
1658 // a try body function.
1659 if (!CatchScope.hasEHBranches()) {
1660 CatchScope.clearHandlerBlocks();
1661 EHStack.popCatch();
1662 return;
1663 }
1664
1665 // The fall-through block.
1666 llvm::BasicBlock *ContBB = createBasicBlock("__try.cont");
1667
1668 // We just emitted the body of the __try; jump to the continue block.
1669 if (HaveInsertPoint())
1670 Builder.CreateBr(ContBB);
1671
1672 // Check if our filter function returned true.
1673 emitCatchDispatchBlock(*this, CatchScope);
1674
1675 // Grab the block before we pop the handler.
1676 llvm::BasicBlock *ExceptBB = CatchScope.getHandler(0).Block;
1677 EHStack.popCatch();
1678
1679 EmitBlockAfterUses(ExceptBB);
1680
1681 // Emit the __except body.
1682 EmitStmt(Except->getBlock());
1683
1684 if (HaveInsertPoint())
1685 Builder.CreateBr(ContBB);
1686
1687 EmitBlock(ContBB);
Reid Kleckner98592d92013-09-16 21:46:30 +00001688}
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001689
1690void CodeGenFunction::EmitSEHLeaveStmt(const SEHLeaveStmt &S) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001691 // If this code is reachable then emit a stop point (if generating
1692 // debug info). We have to do this ourselves because we are on the
1693 // "simple" statement path.
1694 if (HaveInsertPoint())
1695 EmitStopPoint(&S);
1696
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07001697 // This must be a __leave from a __finally block, which we warn on and is UB.
1698 // Just emit unreachable.
1699 if (!isSEHTryScope()) {
1700 Builder.CreateUnreachable();
1701 Builder.ClearInsertionPoint();
1702 return;
1703 }
1704
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001705 EmitBranchThroughCleanup(*SEHTryEpilogueStack.back());
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001706}