blob: 0edbce72676c9a40398a4b1f3ae30c829a0c48d2 [file] [log] [blame]
Anders Carlsson4b08db72009-10-30 01:42:31 +00001//===--- CGException.cpp - Emit LLVM Code for C++ exceptions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code dealing with C++ exception related code generation.
11//
12//===----------------------------------------------------------------------===//
13
Mike Stump58ef18b2009-11-20 23:44:51 +000014#include "clang/AST/StmtCXX.h"
15
16#include "llvm/Intrinsics.h"
John McCall0bdb1fd2010-09-16 06:16:50 +000017#include "llvm/IntrinsicInst.h"
John McCallbd309292010-07-06 01:34:17 +000018#include "llvm/Support/CallSite.h"
Mike Stump58ef18b2009-11-20 23:44:51 +000019
John McCall2ca705e2010-07-24 00:37:23 +000020#include "CGObjCRuntime.h"
Anders Carlsson4b08db72009-10-30 01:42:31 +000021#include "CodeGenFunction.h"
John McCallbd309292010-07-06 01:34:17 +000022#include "CGException.h"
John McCalled1ae862011-01-28 11:13:47 +000023#include "CGCleanup.h"
John McCall5add20c2010-07-20 22:17:55 +000024#include "TargetInfo.h"
John McCallbd309292010-07-06 01:34:17 +000025
Anders Carlsson4b08db72009-10-30 01:42:31 +000026using namespace clang;
27using namespace CodeGen;
28
Anders Carlsson32e1b1c2009-10-30 02:27:02 +000029static llvm::Constant *getAllocateExceptionFn(CodeGenFunction &CGF) {
30 // void *__cxa_allocate_exception(size_t thrown_size);
Mike Stump75546b82009-12-10 00:06:18 +000031
Chris Lattner2192fe52011-07-18 04:24:23 +000032 llvm::FunctionType *FTy =
Jay Foad5709f7c2011-07-29 13:56:53 +000033 llvm::FunctionType::get(CGF.Int8PtrTy, CGF.SizeTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000034
Anders Carlsson32e1b1c2009-10-30 02:27:02 +000035 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
36}
37
Mike Stump33270212009-12-02 07:41:41 +000038static llvm::Constant *getFreeExceptionFn(CodeGenFunction &CGF) {
39 // void __cxa_free_exception(void *thrown_exception);
Mike Stump75546b82009-12-10 00:06:18 +000040
Chris Lattner2192fe52011-07-18 04:24:23 +000041 llvm::FunctionType *FTy =
Jay Foad5709f7c2011-07-29 13:56:53 +000042 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000043
Mike Stump33270212009-12-02 07:41:41 +000044 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_free_exception");
45}
46
Anders Carlsson32e1b1c2009-10-30 02:27:02 +000047static llvm::Constant *getThrowFn(CodeGenFunction &CGF) {
Mike Stump75546b82009-12-10 00:06:18 +000048 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
Mike Stump33270212009-12-02 07:41:41 +000049 // void (*dest) (void *));
Anders Carlsson32e1b1c2009-10-30 02:27:02 +000050
John McCall944e5022011-07-10 20:11:30 +000051 llvm::Type *Args[3] = { CGF.Int8PtrTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
Chris Lattner2192fe52011-07-18 04:24:23 +000052 llvm::FunctionType *FTy =
John McCall944e5022011-07-10 20:11:30 +000053 llvm::FunctionType::get(CGF.VoidTy, Args, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000054
Anders Carlsson32e1b1c2009-10-30 02:27:02 +000055 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
56}
57
Mike Stumpd1782cc2009-11-20 00:56:31 +000058static llvm::Constant *getReThrowFn(CodeGenFunction &CGF) {
Mike Stump33270212009-12-02 07:41:41 +000059 // void __cxa_rethrow();
Mike Stumpd1782cc2009-11-20 00:56:31 +000060
Chris Lattner2192fe52011-07-18 04:24:23 +000061 llvm::FunctionType *FTy =
John McCall944e5022011-07-10 20:11:30 +000062 llvm::FunctionType::get(CGF.VoidTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000063
Mike Stumpd1782cc2009-11-20 00:56:31 +000064 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
65}
66
John McCallbd309292010-07-06 01:34:17 +000067static llvm::Constant *getGetExceptionPtrFn(CodeGenFunction &CGF) {
68 // void *__cxa_get_exception_ptr(void*);
John McCallbd309292010-07-06 01:34:17 +000069
Chris Lattner2192fe52011-07-18 04:24:23 +000070 llvm::FunctionType *FTy =
Jay Foad5709f7c2011-07-29 13:56:53 +000071 llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrTy, /*IsVarArgs=*/false);
John McCallbd309292010-07-06 01:34:17 +000072
73 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
74}
75
Mike Stump58ef18b2009-11-20 23:44:51 +000076static llvm::Constant *getBeginCatchFn(CodeGenFunction &CGF) {
John McCallbd309292010-07-06 01:34:17 +000077 // void *__cxa_begin_catch(void*);
Mike Stump58ef18b2009-11-20 23:44:51 +000078
Chris Lattner2192fe52011-07-18 04:24:23 +000079 llvm::FunctionType *FTy =
Jay Foad5709f7c2011-07-29 13:56:53 +000080 llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000081
Mike Stump58ef18b2009-11-20 23:44:51 +000082 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
83}
84
85static llvm::Constant *getEndCatchFn(CodeGenFunction &CGF) {
Mike Stump33270212009-12-02 07:41:41 +000086 // void __cxa_end_catch();
Mike Stump58ef18b2009-11-20 23:44:51 +000087
Chris Lattner2192fe52011-07-18 04:24:23 +000088 llvm::FunctionType *FTy =
John McCall944e5022011-07-10 20:11:30 +000089 llvm::FunctionType::get(CGF.VoidTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000090
Mike Stump58ef18b2009-11-20 23:44:51 +000091 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
92}
93
Mike Stump1d849212009-12-07 23:38:24 +000094static llvm::Constant *getUnexpectedFn(CodeGenFunction &CGF) {
95 // void __cxa_call_unexepcted(void *thrown_exception);
96
Chris Lattner2192fe52011-07-18 04:24:23 +000097 llvm::FunctionType *FTy =
Jay Foad5709f7c2011-07-29 13:56:53 +000098 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000099
Mike Stump1d849212009-12-07 23:38:24 +0000100 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_call_unexpected");
101}
102
John McCall9b382dd2011-05-28 21:13:02 +0000103llvm::Constant *CodeGenFunction::getUnwindResumeFn() {
Chris Lattner2192fe52011-07-18 04:24:23 +0000104 llvm::FunctionType *FTy =
Jay Foad5709f7c2011-07-29 13:56:53 +0000105 llvm::FunctionType::get(VoidTy, Int8PtrTy, /*IsVarArgs=*/false);
John McCall9b382dd2011-05-28 21:13:02 +0000106
107 if (CGM.getLangOptions().SjLjExceptions)
108 return CGM.CreateRuntimeFunction(FTy, "_Unwind_SjLj_Resume");
109 return CGM.CreateRuntimeFunction(FTy, "_Unwind_Resume");
110}
111
112llvm::Constant *CodeGenFunction::getUnwindResumeOrRethrowFn() {
Chris Lattner2192fe52011-07-18 04:24:23 +0000113 llvm::FunctionType *FTy =
Jay Foad5709f7c2011-07-29 13:56:53 +0000114 llvm::FunctionType::get(VoidTy, Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +0000115
Douglas Gregor51150ab2010-05-16 01:24:12 +0000116 if (CGM.getLangOptions().SjLjExceptions)
John McCallffe46302010-08-11 20:59:53 +0000117 return CGM.CreateRuntimeFunction(FTy, "_Unwind_SjLj_Resume_or_Rethrow");
Douglas Gregor51150ab2010-05-16 01:24:12 +0000118 return CGM.CreateRuntimeFunction(FTy, "_Unwind_Resume_or_Rethrow");
Mike Stump54066142009-12-01 03:41:18 +0000119}
120
Mike Stump33270212009-12-02 07:41:41 +0000121static llvm::Constant *getTerminateFn(CodeGenFunction &CGF) {
122 // void __terminate();
123
Chris Lattner2192fe52011-07-18 04:24:23 +0000124 llvm::FunctionType *FTy =
John McCall944e5022011-07-10 20:11:30 +0000125 llvm::FunctionType::get(CGF.VoidTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +0000126
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000127 StringRef name;
John McCall9de19782011-07-06 01:22:26 +0000128
129 // In C++, use std::terminate().
130 if (CGF.getLangOptions().CPlusPlus)
131 name = "_ZSt9terminatev"; // FIXME: mangling!
132 else if (CGF.getLangOptions().ObjC1 &&
133 CGF.CGM.getCodeGenOpts().ObjCRuntimeHasTerminate)
134 name = "objc_terminate";
135 else
136 name = "abort";
137 return CGF.CGM.CreateRuntimeFunction(FTy, name);
David Chisnallf9c42252010-05-17 13:49:20 +0000138}
139
John McCall36ea3722010-07-17 00:43:08 +0000140static llvm::Constant *getCatchallRethrowFn(CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000141 StringRef Name) {
Chris Lattner2192fe52011-07-18 04:24:23 +0000142 llvm::FunctionType *FTy =
Jay Foad5709f7c2011-07-29 13:56:53 +0000143 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, /*IsVarArgs=*/false);
John McCall36ea3722010-07-17 00:43:08 +0000144
145 return CGF.CGM.CreateRuntimeFunction(FTy, Name);
John McCallbd309292010-07-06 01:34:17 +0000146}
147
John McCall36ea3722010-07-17 00:43:08 +0000148const EHPersonality EHPersonality::GNU_C("__gcc_personality_v0");
John McCall2faab302010-11-07 02:35:25 +0000149const EHPersonality EHPersonality::GNU_C_SJLJ("__gcc_personality_sj0");
John McCall36ea3722010-07-17 00:43:08 +0000150const EHPersonality EHPersonality::NeXT_ObjC("__objc_personality_v0");
151const EHPersonality EHPersonality::GNU_CPlusPlus("__gxx_personality_v0");
152const EHPersonality EHPersonality::GNU_CPlusPlus_SJLJ("__gxx_personality_sj0");
153const EHPersonality EHPersonality::GNU_ObjC("__gnu_objc_personality_v0",
154 "objc_exception_throw");
David Chisnalle1d2584d2011-03-20 21:35:39 +0000155const EHPersonality EHPersonality::GNU_ObjCXX("__gnustep_objcxx_personality_v0");
John McCall36ea3722010-07-17 00:43:08 +0000156
157static const EHPersonality &getCPersonality(const LangOptions &L) {
John McCall2faab302010-11-07 02:35:25 +0000158 if (L.SjLjExceptions)
159 return EHPersonality::GNU_C_SJLJ;
John McCall36ea3722010-07-17 00:43:08 +0000160 return EHPersonality::GNU_C;
161}
162
163static const EHPersonality &getObjCPersonality(const LangOptions &L) {
164 if (L.NeXTRuntime) {
165 if (L.ObjCNonFragileABI) return EHPersonality::NeXT_ObjC;
166 else return getCPersonality(L);
John McCallbd309292010-07-06 01:34:17 +0000167 } else {
John McCall36ea3722010-07-17 00:43:08 +0000168 return EHPersonality::GNU_ObjC;
John McCallbd309292010-07-06 01:34:17 +0000169 }
170}
171
John McCall36ea3722010-07-17 00:43:08 +0000172static const EHPersonality &getCXXPersonality(const LangOptions &L) {
173 if (L.SjLjExceptions)
174 return EHPersonality::GNU_CPlusPlus_SJLJ;
John McCallbd309292010-07-06 01:34:17 +0000175 else
John McCall36ea3722010-07-17 00:43:08 +0000176 return EHPersonality::GNU_CPlusPlus;
John McCallbd309292010-07-06 01:34:17 +0000177}
178
179/// Determines the personality function to use when both C++
180/// and Objective-C exceptions are being caught.
John McCall36ea3722010-07-17 00:43:08 +0000181static const EHPersonality &getObjCXXPersonality(const LangOptions &L) {
John McCallbd309292010-07-06 01:34:17 +0000182 // The ObjC personality defers to the C++ personality for non-ObjC
183 // handlers. Unlike the C++ case, we use the same personality
184 // function on targets using (backend-driven) SJLJ EH.
John McCall36ea3722010-07-17 00:43:08 +0000185 if (L.NeXTRuntime) {
186 if (L.ObjCNonFragileABI)
187 return EHPersonality::NeXT_ObjC;
John McCallbd309292010-07-06 01:34:17 +0000188
189 // In the fragile ABI, just use C++ exception handling and hope
190 // they're not doing crazy exception mixing.
191 else
John McCall36ea3722010-07-17 00:43:08 +0000192 return getCXXPersonality(L);
Chandler Carruth0450cc62010-05-17 20:58:49 +0000193 }
David Chisnallf9c42252010-05-17 13:49:20 +0000194
John McCall36ea3722010-07-17 00:43:08 +0000195 // The GNU runtime's personality function inherently doesn't support
196 // mixed EH. Use the C++ personality just to avoid returning null.
David Chisnalle1d2584d2011-03-20 21:35:39 +0000197 return EHPersonality::GNU_ObjCXX;
John McCallbd309292010-07-06 01:34:17 +0000198}
199
John McCall36ea3722010-07-17 00:43:08 +0000200const EHPersonality &EHPersonality::get(const LangOptions &L) {
201 if (L.CPlusPlus && L.ObjC1)
202 return getObjCXXPersonality(L);
203 else if (L.CPlusPlus)
204 return getCXXPersonality(L);
205 else if (L.ObjC1)
206 return getObjCPersonality(L);
John McCallbd309292010-07-06 01:34:17 +0000207 else
John McCall36ea3722010-07-17 00:43:08 +0000208 return getCPersonality(L);
209}
John McCallbd309292010-07-06 01:34:17 +0000210
John McCall0bdb1fd2010-09-16 06:16:50 +0000211static llvm::Constant *getPersonalityFn(CodeGenModule &CGM,
John McCall36ea3722010-07-17 00:43:08 +0000212 const EHPersonality &Personality) {
John McCall36ea3722010-07-17 00:43:08 +0000213 llvm::Constant *Fn =
Chris Lattnerece04092012-02-07 00:39:47 +0000214 CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.Int32Ty, true),
John McCall0bdb1fd2010-09-16 06:16:50 +0000215 Personality.getPersonalityFnName());
216 return Fn;
217}
218
219static llvm::Constant *getOpaquePersonalityFn(CodeGenModule &CGM,
220 const EHPersonality &Personality) {
221 llvm::Constant *Fn = getPersonalityFn(CGM, Personality);
John McCallad7c5c12011-02-08 08:22:06 +0000222 return llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
John McCall0bdb1fd2010-09-16 06:16:50 +0000223}
224
225/// Check whether a personality function could reasonably be swapped
226/// for a C++ personality function.
227static bool PersonalityHasOnlyCXXUses(llvm::Constant *Fn) {
228 for (llvm::Constant::use_iterator
229 I = Fn->use_begin(), E = Fn->use_end(); I != E; ++I) {
230 llvm::User *User = *I;
231
232 // Conditionally white-list bitcasts.
233 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(User)) {
234 if (CE->getOpcode() != llvm::Instruction::BitCast) return false;
235 if (!PersonalityHasOnlyCXXUses(CE))
236 return false;
237 continue;
238 }
239
Bill Wendling58e58fe2011-09-19 22:08:36 +0000240 // Otherwise, it has to be a landingpad instruction.
241 llvm::LandingPadInst *LPI = dyn_cast<llvm::LandingPadInst>(User);
242 if (!LPI) return false;
John McCall0bdb1fd2010-09-16 06:16:50 +0000243
Bill Wendling58e58fe2011-09-19 22:08:36 +0000244 for (unsigned I = 0, E = LPI->getNumClauses(); I != E; ++I) {
John McCall0bdb1fd2010-09-16 06:16:50 +0000245 // Look for something that would've been returned by the ObjC
246 // runtime's GetEHType() method.
Bill Wendling58e58fe2011-09-19 22:08:36 +0000247 llvm::Value *Val = LPI->getClause(I)->stripPointerCasts();
248 if (LPI->isCatch(I)) {
249 // Check if the catch value has the ObjC prefix.
Bill Wendling5d7469e2011-09-20 00:40:19 +0000250 if (llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Val))
251 // ObjC EH selector entries are always global variables with
252 // names starting like this.
253 if (GV->getName().startswith("OBJC_EHTYPE"))
254 return false;
Bill Wendling58e58fe2011-09-19 22:08:36 +0000255 } else {
256 // Check if any of the filter values have the ObjC prefix.
257 llvm::Constant *CVal = cast<llvm::Constant>(Val);
258 for (llvm::User::op_iterator
259 II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II) {
Bill Wendling5d7469e2011-09-20 00:40:19 +0000260 if (llvm::GlobalVariable *GV =
261 cast<llvm::GlobalVariable>((*II)->stripPointerCasts()))
262 // ObjC EH selector entries are always global variables with
263 // names starting like this.
264 if (GV->getName().startswith("OBJC_EHTYPE"))
265 return false;
Bill Wendling58e58fe2011-09-19 22:08:36 +0000266 }
267 }
John McCall0bdb1fd2010-09-16 06:16:50 +0000268 }
269 }
270
271 return true;
272}
273
274/// Try to use the C++ personality function in ObjC++. Not doing this
275/// can cause some incompatibilities with gcc, which is more
276/// aggressive about only using the ObjC++ personality in a function
277/// when it really needs it.
278void CodeGenModule::SimplifyPersonality() {
279 // For now, this is really a Darwin-specific operation.
Douglas Gregore8bbc122011-09-02 00:18:52 +0000280 if (!Context.getTargetInfo().getTriple().isOSDarwin())
John McCall0bdb1fd2010-09-16 06:16:50 +0000281 return;
282
283 // If we're not in ObjC++ -fexceptions, there's nothing to do.
284 if (!Features.CPlusPlus || !Features.ObjC1 || !Features.Exceptions)
285 return;
286
287 const EHPersonality &ObjCXX = EHPersonality::get(Features);
288 const EHPersonality &CXX = getCXXPersonality(Features);
289 if (&ObjCXX == &CXX ||
290 ObjCXX.getPersonalityFnName() == CXX.getPersonalityFnName())
291 return;
292
293 llvm::Function *Fn =
294 getModule().getFunction(ObjCXX.getPersonalityFnName());
295
296 // Nothing to do if it's unused.
297 if (!Fn || Fn->use_empty()) return;
298
299 // Can't do the optimization if it has non-C++ uses.
300 if (!PersonalityHasOnlyCXXUses(Fn)) return;
301
302 // Create the C++ personality function and kill off the old
303 // function.
304 llvm::Constant *CXXFn = getPersonalityFn(*this, CXX);
305
306 // This can happen if the user is screwing with us.
307 if (Fn->getType() != CXXFn->getType()) return;
308
309 Fn->replaceAllUsesWith(CXXFn);
310 Fn->eraseFromParent();
John McCallbd309292010-07-06 01:34:17 +0000311}
312
313/// Returns the value to inject into a selector to indicate the
314/// presence of a catch-all.
315static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
316 // Possibly we should use @llvm.eh.catch.all.value here.
John McCallad7c5c12011-02-08 08:22:06 +0000317 return llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
John McCallbd309292010-07-06 01:34:17 +0000318}
319
John McCallbb026012010-07-13 21:17:51 +0000320namespace {
321 /// A cleanup to free the exception object if its initialization
322 /// throws.
John McCall5fcf8da2011-07-12 00:15:30 +0000323 struct FreeException : EHScopeStack::Cleanup {
324 llvm::Value *exn;
325 FreeException(llvm::Value *exn) : exn(exn) {}
John McCall30317fd2011-07-12 20:27:29 +0000326 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCalle4df6c82011-01-28 08:37:24 +0000327 CGF.Builder.CreateCall(getFreeExceptionFn(CGF), exn)
John McCallbb026012010-07-13 21:17:51 +0000328 ->setDoesNotThrow();
John McCallbb026012010-07-13 21:17:51 +0000329 }
330 };
331}
332
John McCall2e6567a2010-04-22 01:10:34 +0000333// Emits an exception expression into the given location. This
334// differs from EmitAnyExprToMem only in that, if a final copy-ctor
335// call is required, an exception within that copy ctor causes
336// std::terminate to be invoked.
John McCalle4df6c82011-01-28 08:37:24 +0000337static void EmitAnyExprToExn(CodeGenFunction &CGF, const Expr *e,
338 llvm::Value *addr) {
John McCallbd309292010-07-06 01:34:17 +0000339 // Make sure the exception object is cleaned up if there's an
340 // exception during initialization.
John McCalle4df6c82011-01-28 08:37:24 +0000341 CGF.pushFullExprCleanup<FreeException>(EHCleanup, addr);
342 EHScopeStack::stable_iterator cleanup = CGF.EHStack.stable_begin();
John McCall2e6567a2010-04-22 01:10:34 +0000343
344 // __cxa_allocate_exception returns a void*; we need to cast this
345 // to the appropriate type for the object.
Chris Lattner2192fe52011-07-18 04:24:23 +0000346 llvm::Type *ty = CGF.ConvertTypeForMem(e->getType())->getPointerTo();
John McCalle4df6c82011-01-28 08:37:24 +0000347 llvm::Value *typedAddr = CGF.Builder.CreateBitCast(addr, ty);
John McCall2e6567a2010-04-22 01:10:34 +0000348
349 // FIXME: this isn't quite right! If there's a final unelided call
350 // to a copy constructor, then according to [except.terminate]p1 we
351 // must call std::terminate() if that constructor throws, because
352 // technically that copy occurs after the exception expression is
353 // evaluated but before the exception is caught. But the best way
354 // to handle that is to teach EmitAggExpr to do the final copy
355 // differently if it can't be elided.
John McCall31168b02011-06-15 23:02:42 +0000356 CGF.EmitAnyExprToMem(e, typedAddr, e->getType().getQualifiers(),
357 /*IsInit*/ true);
John McCall2e6567a2010-04-22 01:10:34 +0000358
John McCalle4df6c82011-01-28 08:37:24 +0000359 // Deactivate the cleanup block.
John McCallf4beacd2011-11-10 10:43:54 +0000360 CGF.DeactivateCleanupBlock(cleanup, cast<llvm::Instruction>(typedAddr));
Mike Stump54066142009-12-01 03:41:18 +0000361}
362
John McCallbd309292010-07-06 01:34:17 +0000363llvm::Value *CodeGenFunction::getExceptionSlot() {
John McCall9b382dd2011-05-28 21:13:02 +0000364 if (!ExceptionSlot)
365 ExceptionSlot = CreateTempAlloca(Int8PtrTy, "exn.slot");
John McCallbd309292010-07-06 01:34:17 +0000366 return ExceptionSlot;
Mike Stump54066142009-12-01 03:41:18 +0000367}
368
John McCall9b382dd2011-05-28 21:13:02 +0000369llvm::Value *CodeGenFunction::getEHSelectorSlot() {
370 if (!EHSelectorSlot)
371 EHSelectorSlot = CreateTempAlloca(Int32Ty, "ehselector.slot");
372 return EHSelectorSlot;
373}
374
Bill Wendling79a70e42011-09-15 18:57:19 +0000375llvm::Value *CodeGenFunction::getExceptionFromSlot() {
376 return Builder.CreateLoad(getExceptionSlot(), "exn");
377}
378
379llvm::Value *CodeGenFunction::getSelectorFromSlot() {
380 return Builder.CreateLoad(getEHSelectorSlot(), "sel");
381}
382
Anders Carlsson4b08db72009-10-30 01:42:31 +0000383void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E) {
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000384 if (!E->getSubExpr()) {
Douglas Gregorc278d1b2010-05-16 00:44:00 +0000385 if (getInvokeDest()) {
John McCallbd309292010-07-06 01:34:17 +0000386 Builder.CreateInvoke(getReThrowFn(*this),
387 getUnreachableBlock(),
388 getInvokeDest())
Douglas Gregorc278d1b2010-05-16 00:44:00 +0000389 ->setDoesNotReturn();
John McCallbd309292010-07-06 01:34:17 +0000390 } else {
Douglas Gregorc278d1b2010-05-16 00:44:00 +0000391 Builder.CreateCall(getReThrowFn(*this))->setDoesNotReturn();
John McCallbd309292010-07-06 01:34:17 +0000392 Builder.CreateUnreachable();
393 }
Douglas Gregorc278d1b2010-05-16 00:44:00 +0000394
John McCall20f6ab82011-01-12 03:41:02 +0000395 // throw is an expression, and the expression emitters expect us
396 // to leave ourselves at a valid insertion point.
397 EmitBlock(createBasicBlock("throw.cont"));
398
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000399 return;
400 }
Mike Stump75546b82009-12-10 00:06:18 +0000401
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000402 QualType ThrowType = E->getSubExpr()->getType();
Mike Stump75546b82009-12-10 00:06:18 +0000403
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000404 // Now allocate the exception object.
Chris Lattner2192fe52011-07-18 04:24:23 +0000405 llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
John McCall21886962010-04-21 10:05:39 +0000406 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
Mike Stump75546b82009-12-10 00:06:18 +0000407
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000408 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(*this);
John McCallbd309292010-07-06 01:34:17 +0000409 llvm::CallInst *ExceptionPtr =
Mike Stump75546b82009-12-10 00:06:18 +0000410 Builder.CreateCall(AllocExceptionFn,
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000411 llvm::ConstantInt::get(SizeTy, TypeSize),
412 "exception");
John McCallbd309292010-07-06 01:34:17 +0000413 ExceptionPtr->setDoesNotThrow();
Anders Carlssonafd1edb2009-12-11 00:32:37 +0000414
John McCall2e6567a2010-04-22 01:10:34 +0000415 EmitAnyExprToExn(*this, E->getSubExpr(), ExceptionPtr);
Mike Stump75546b82009-12-10 00:06:18 +0000416
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000417 // Now throw the exception.
Anders Carlssonba840fb2011-01-24 01:59:49 +0000418 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
419 /*ForEH=*/true);
John McCall2e6567a2010-04-22 01:10:34 +0000420
421 // The address of the destructor. If the exception type has a
422 // trivial destructor (or isn't a record), we just pass null.
423 llvm::Constant *Dtor = 0;
424 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
425 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
426 if (!Record->hasTrivialDestructor()) {
Douglas Gregorbac74902010-07-01 14:13:13 +0000427 CXXDestructorDecl *DtorD = Record->getDestructor();
John McCall2e6567a2010-04-22 01:10:34 +0000428 Dtor = CGM.GetAddrOfCXXDestructor(DtorD, Dtor_Complete);
429 Dtor = llvm::ConstantExpr::getBitCast(Dtor, Int8PtrTy);
430 }
431 }
432 if (!Dtor) Dtor = llvm::Constant::getNullValue(Int8PtrTy);
Mike Stump75546b82009-12-10 00:06:18 +0000433
Mike Stump114ab9f2009-12-04 01:51:45 +0000434 if (getInvokeDest()) {
Mike Stump75546b82009-12-10 00:06:18 +0000435 llvm::InvokeInst *ThrowCall =
John McCallbd309292010-07-06 01:34:17 +0000436 Builder.CreateInvoke3(getThrowFn(*this),
437 getUnreachableBlock(), getInvokeDest(),
Mike Stump114ab9f2009-12-04 01:51:45 +0000438 ExceptionPtr, TypeInfo, Dtor);
439 ThrowCall->setDoesNotReturn();
Mike Stump114ab9f2009-12-04 01:51:45 +0000440 } else {
Mike Stump75546b82009-12-10 00:06:18 +0000441 llvm::CallInst *ThrowCall =
Mike Stump114ab9f2009-12-04 01:51:45 +0000442 Builder.CreateCall3(getThrowFn(*this), ExceptionPtr, TypeInfo, Dtor);
443 ThrowCall->setDoesNotReturn();
John McCallbd309292010-07-06 01:34:17 +0000444 Builder.CreateUnreachable();
Mike Stump114ab9f2009-12-04 01:51:45 +0000445 }
Mike Stump75546b82009-12-10 00:06:18 +0000446
John McCall20f6ab82011-01-12 03:41:02 +0000447 // throw is an expression, and the expression emitters expect us
448 // to leave ourselves at a valid insertion point.
449 EmitBlock(createBasicBlock("throw.cont"));
Anders Carlsson4b08db72009-10-30 01:42:31 +0000450}
Mike Stump58ef18b2009-11-20 23:44:51 +0000451
Mike Stump1d849212009-12-07 23:38:24 +0000452void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
Anders Carlssone96ab552011-02-28 02:27:16 +0000453 if (!CGM.getLangOptions().CXXExceptions)
Anders Carlsson9878f9f2010-02-06 23:59:05 +0000454 return;
455
Mike Stump1d849212009-12-07 23:38:24 +0000456 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
457 if (FD == 0)
458 return;
459 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
460 if (Proto == 0)
461 return;
462
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000463 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
464 if (isNoexceptExceptionSpec(EST)) {
465 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
466 // noexcept functions are simple terminate scopes.
467 EHStack.pushTerminate();
468 }
469 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
470 unsigned NumExceptions = Proto->getNumExceptions();
471 EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
Mike Stump1d849212009-12-07 23:38:24 +0000472
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000473 for (unsigned I = 0; I != NumExceptions; ++I) {
474 QualType Ty = Proto->getExceptionType(I);
475 QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
476 llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType,
477 /*ForEH=*/true);
478 Filter->setFilter(I, EHType);
479 }
Mike Stump1d849212009-12-07 23:38:24 +0000480 }
Mike Stump1d849212009-12-07 23:38:24 +0000481}
482
John McCall8e4c74b2011-08-11 02:22:43 +0000483/// Emit the dispatch block for a filter scope if necessary.
484static void emitFilterDispatchBlock(CodeGenFunction &CGF,
485 EHFilterScope &filterScope) {
486 llvm::BasicBlock *dispatchBlock = filterScope.getCachedEHDispatchBlock();
487 if (!dispatchBlock) return;
488 if (dispatchBlock->use_empty()) {
489 delete dispatchBlock;
490 return;
491 }
492
John McCall8e4c74b2011-08-11 02:22:43 +0000493 CGF.EmitBlockAfterUses(dispatchBlock);
494
495 // If this isn't a catch-all filter, we need to check whether we got
496 // here because the filter triggered.
497 if (filterScope.getNumFilters()) {
498 // Load the selector value.
Bill Wendling79a70e42011-09-15 18:57:19 +0000499 llvm::Value *selector = CGF.getSelectorFromSlot();
John McCall8e4c74b2011-08-11 02:22:43 +0000500 llvm::BasicBlock *unexpectedBB = CGF.createBasicBlock("ehspec.unexpected");
501
502 llvm::Value *zero = CGF.Builder.getInt32(0);
503 llvm::Value *failsFilter =
504 CGF.Builder.CreateICmpSLT(selector, zero, "ehspec.fails");
505 CGF.Builder.CreateCondBr(failsFilter, unexpectedBB, CGF.getEHResumeBlock());
506
507 CGF.EmitBlock(unexpectedBB);
508 }
509
510 // Call __cxa_call_unexpected. This doesn't need to be an invoke
511 // because __cxa_call_unexpected magically filters exceptions
512 // according to the last landing pad the exception was thrown
513 // into. Seriously.
Bill Wendling79a70e42011-09-15 18:57:19 +0000514 llvm::Value *exn = CGF.getExceptionFromSlot();
John McCall8e4c74b2011-08-11 02:22:43 +0000515 CGF.Builder.CreateCall(getUnexpectedFn(CGF), exn)
516 ->setDoesNotReturn();
517 CGF.Builder.CreateUnreachable();
518}
519
Mike Stump1d849212009-12-07 23:38:24 +0000520void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
Anders Carlssone96ab552011-02-28 02:27:16 +0000521 if (!CGM.getLangOptions().CXXExceptions)
Anders Carlsson9878f9f2010-02-06 23:59:05 +0000522 return;
523
Mike Stump1d849212009-12-07 23:38:24 +0000524 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
525 if (FD == 0)
526 return;
527 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
528 if (Proto == 0)
529 return;
530
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000531 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
532 if (isNoexceptExceptionSpec(EST)) {
533 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
534 EHStack.popTerminate();
535 }
536 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
John McCall8e4c74b2011-08-11 02:22:43 +0000537 EHFilterScope &filterScope = cast<EHFilterScope>(*EHStack.begin());
538 emitFilterDispatchBlock(*this, filterScope);
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000539 EHStack.popFilter();
540 }
Mike Stump1d849212009-12-07 23:38:24 +0000541}
542
Mike Stump58ef18b2009-11-20 23:44:51 +0000543void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
John McCallb609d3f2010-07-07 06:56:46 +0000544 EnterCXXTryStmt(S);
John McCallb81884d2010-02-19 09:25:03 +0000545 EmitStmt(S.getTryBlock());
John McCallb609d3f2010-07-07 06:56:46 +0000546 ExitCXXTryStmt(S);
John McCallb81884d2010-02-19 09:25:03 +0000547}
548
John McCallb609d3f2010-07-07 06:56:46 +0000549void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallbd309292010-07-06 01:34:17 +0000550 unsigned NumHandlers = S.getNumHandlers();
551 EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
John McCallb81884d2010-02-19 09:25:03 +0000552
John McCallbd309292010-07-06 01:34:17 +0000553 for (unsigned I = 0; I != NumHandlers; ++I) {
554 const CXXCatchStmt *C = S.getHandler(I);
John McCallb81884d2010-02-19 09:25:03 +0000555
John McCallbd309292010-07-06 01:34:17 +0000556 llvm::BasicBlock *Handler = createBasicBlock("catch");
557 if (C->getExceptionDecl()) {
558 // FIXME: Dropping the reference type on the type into makes it
559 // impossible to correctly implement catch-by-reference
560 // semantics for pointers. Unfortunately, this is what all
561 // existing compilers do, and it's not clear that the standard
562 // personality routine is capable of doing this right. See C++ DR 388:
563 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
564 QualType CaughtType = C->getCaughtType();
565 CaughtType = CaughtType.getNonReferenceType().getUnqualifiedType();
John McCall2ca705e2010-07-24 00:37:23 +0000566
567 llvm::Value *TypeInfo = 0;
568 if (CaughtType->isObjCObjectPointerType())
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +0000569 TypeInfo = CGM.getObjCRuntime().GetEHType(CaughtType);
John McCall2ca705e2010-07-24 00:37:23 +0000570 else
Anders Carlssonba840fb2011-01-24 01:59:49 +0000571 TypeInfo = CGM.GetAddrOfRTTIDescriptor(CaughtType, /*ForEH=*/true);
John McCallbd309292010-07-06 01:34:17 +0000572 CatchScope->setHandler(I, TypeInfo, Handler);
573 } else {
574 // No exception decl indicates '...', a catch-all.
575 CatchScope->setCatchAllHandler(I, Handler);
576 }
577 }
John McCallbd309292010-07-06 01:34:17 +0000578}
579
John McCall8e4c74b2011-08-11 02:22:43 +0000580llvm::BasicBlock *
581CodeGenFunction::getEHDispatchBlock(EHScopeStack::stable_iterator si) {
582 // The dispatch block for the end of the scope chain is a block that
583 // just resumes unwinding.
584 if (si == EHStack.stable_end())
585 return getEHResumeBlock();
586
587 // Otherwise, we should look at the actual scope.
588 EHScope &scope = *EHStack.find(si);
589
590 llvm::BasicBlock *dispatchBlock = scope.getCachedEHDispatchBlock();
591 if (!dispatchBlock) {
592 switch (scope.getKind()) {
593 case EHScope::Catch: {
594 // Apply a special case to a single catch-all.
595 EHCatchScope &catchScope = cast<EHCatchScope>(scope);
596 if (catchScope.getNumHandlers() == 1 &&
597 catchScope.getHandler(0).isCatchAll()) {
598 dispatchBlock = catchScope.getHandler(0).Block;
599
600 // Otherwise, make a dispatch block.
601 } else {
602 dispatchBlock = createBasicBlock("catch.dispatch");
603 }
604 break;
605 }
606
607 case EHScope::Cleanup:
608 dispatchBlock = createBasicBlock("ehcleanup");
609 break;
610
611 case EHScope::Filter:
612 dispatchBlock = createBasicBlock("filter.dispatch");
613 break;
614
615 case EHScope::Terminate:
616 dispatchBlock = getTerminateHandler();
617 break;
618 }
619 scope.setCachedEHDispatchBlock(dispatchBlock);
620 }
621 return dispatchBlock;
622}
623
John McCallbd309292010-07-06 01:34:17 +0000624/// Check whether this is a non-EH scope, i.e. a scope which doesn't
625/// affect exception handling. Currently, the only non-EH scopes are
626/// normal-only cleanup scopes.
627static bool isNonEHScope(const EHScope &S) {
John McCall2b7fc382010-07-13 20:32:21 +0000628 switch (S.getKind()) {
John McCallcda666c2010-07-21 07:22:38 +0000629 case EHScope::Cleanup:
630 return !cast<EHCleanupScope>(S).isEHCleanup();
John McCall2b7fc382010-07-13 20:32:21 +0000631 case EHScope::Filter:
632 case EHScope::Catch:
633 case EHScope::Terminate:
634 return false;
635 }
636
David Blaikiee4d798f2012-01-20 21:50:17 +0000637 llvm_unreachable("Invalid EHScope Kind!");
John McCallbd309292010-07-06 01:34:17 +0000638}
639
640llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
641 assert(EHStack.requiresLandingPad());
642 assert(!EHStack.empty());
643
Anders Carlsson6dc07d42011-02-28 00:33:03 +0000644 if (!CGM.getLangOptions().Exceptions)
John McCall2b7fc382010-07-13 20:32:21 +0000645 return 0;
646
John McCallbd309292010-07-06 01:34:17 +0000647 // Check the innermost scope for a cached landing pad. If this is
648 // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
649 llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
650 if (LP) return LP;
651
652 // Build the landing pad for this scope.
653 LP = EmitLandingPad();
654 assert(LP);
655
656 // Cache the landing pad on the innermost scope. If this is a
657 // non-EH scope, cache the landing pad on the enclosing scope, too.
658 for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
659 ir->setCachedLandingPad(LP);
660 if (!isNonEHScope(*ir)) break;
661 }
662
663 return LP;
664}
665
John McCall9b382dd2011-05-28 21:13:02 +0000666// This code contains a hack to work around a design flaw in
667// LLVM's EH IR which breaks semantics after inlining. This same
668// hack is implemented in llvm-gcc.
669//
670// The LLVM EH abstraction is basically a thin veneer over the
671// traditional GCC zero-cost design: for each range of instructions
672// in the function, there is (at most) one "landing pad" with an
673// associated chain of EH actions. A language-specific personality
674// function interprets this chain of actions and (1) decides whether
675// or not to resume execution at the landing pad and (2) if so,
676// provides an integer indicating why it's stopping. In LLVM IR,
677// the association of a landing pad with a range of instructions is
678// achieved via an invoke instruction, the chain of actions becomes
679// the arguments to the @llvm.eh.selector call, and the selector
680// call returns the integer indicator. Other than the required
681// presence of two intrinsic function calls in the landing pad,
682// the IR exactly describes the layout of the output code.
683//
684// A principal advantage of this design is that it is completely
685// language-agnostic; in theory, the LLVM optimizers can treat
686// landing pads neutrally, and targets need only know how to lower
687// the intrinsics to have a functioning exceptions system (assuming
688// that platform exceptions follow something approximately like the
689// GCC design). Unfortunately, landing pads cannot be combined in a
690// language-agnostic way: given selectors A and B, there is no way
691// to make a single landing pad which faithfully represents the
692// semantics of propagating an exception first through A, then
693// through B, without knowing how the personality will interpret the
694// (lowered form of the) selectors. This means that inlining has no
695// choice but to crudely chain invokes (i.e., to ignore invokes in
696// the inlined function, but to turn all unwindable calls into
697// invokes), which is only semantically valid if every unwind stops
698// at every landing pad.
699//
700// Therefore, the invoke-inline hack is to guarantee that every
701// landing pad has a catch-all.
702enum CleanupHackLevel_t {
703 /// A level of hack that requires that all landing pads have
704 /// catch-alls.
705 CHL_MandatoryCatchall,
706
707 /// A level of hack that requires that all landing pads handle
708 /// cleanups.
709 CHL_MandatoryCleanup,
710
711 /// No hacks at all; ideal IR generation.
712 CHL_Ideal
713};
714const CleanupHackLevel_t CleanupHackLevel = CHL_MandatoryCleanup;
715
John McCallbd309292010-07-06 01:34:17 +0000716llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
717 assert(EHStack.requiresLandingPad());
718
John McCall8e4c74b2011-08-11 02:22:43 +0000719 EHScope &innermostEHScope = *EHStack.find(EHStack.getInnermostEHScope());
720 switch (innermostEHScope.getKind()) {
721 case EHScope::Terminate:
722 return getTerminateLandingPad();
John McCallbd309292010-07-06 01:34:17 +0000723
John McCall8e4c74b2011-08-11 02:22:43 +0000724 case EHScope::Catch:
725 case EHScope::Cleanup:
726 case EHScope::Filter:
727 if (llvm::BasicBlock *lpad = innermostEHScope.getCachedLandingPad())
728 return lpad;
John McCallbd309292010-07-06 01:34:17 +0000729 }
730
731 // Save the current IR generation state.
John McCall8e4c74b2011-08-11 02:22:43 +0000732 CGBuilderTy::InsertPoint savedIP = Builder.saveAndClearIP();
John McCallbd309292010-07-06 01:34:17 +0000733
John McCall8e4c74b2011-08-11 02:22:43 +0000734 const EHPersonality &personality = EHPersonality::get(getLangOptions());
John McCall36ea3722010-07-17 00:43:08 +0000735
John McCallbd309292010-07-06 01:34:17 +0000736 // Create and configure the landing pad.
John McCall8e4c74b2011-08-11 02:22:43 +0000737 llvm::BasicBlock *lpad = createBasicBlock("lpad");
738 EmitBlock(lpad);
John McCallbd309292010-07-06 01:34:17 +0000739
Bill Wendlingf0724e82011-09-19 20:31:14 +0000740 llvm::LandingPadInst *LPadInst =
741 Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, NULL),
742 getOpaquePersonalityFn(CGM, personality), 0);
743
744 llvm::Value *LPadExn = Builder.CreateExtractValue(LPadInst, 0);
745 Builder.CreateStore(LPadExn, getExceptionSlot());
746 llvm::Value *LPadSel = Builder.CreateExtractValue(LPadInst, 1);
747 Builder.CreateStore(LPadSel, getEHSelectorSlot());
748
John McCallbd309292010-07-06 01:34:17 +0000749 // Save the exception pointer. It's safe to use a single exception
750 // pointer per function because EH cleanups can never have nested
751 // try/catches.
Bill Wendlingf0724e82011-09-19 20:31:14 +0000752 // Build the landingpad instruction.
John McCallbd309292010-07-06 01:34:17 +0000753
754 // Accumulate all the handlers in scope.
John McCall8e4c74b2011-08-11 02:22:43 +0000755 bool hasCatchAll = false;
756 bool hasCleanup = false;
757 bool hasFilter = false;
758 SmallVector<llvm::Value*, 4> filterTypes;
759 llvm::SmallPtrSet<llvm::Value*, 4> catchTypes;
John McCallbd309292010-07-06 01:34:17 +0000760 for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end();
761 I != E; ++I) {
762
763 switch (I->getKind()) {
John McCallcda666c2010-07-21 07:22:38 +0000764 case EHScope::Cleanup:
John McCall8e4c74b2011-08-11 02:22:43 +0000765 // If we have a cleanup, remember that.
766 hasCleanup = (hasCleanup || cast<EHCleanupScope>(*I).isEHCleanup());
John McCall2b7fc382010-07-13 20:32:21 +0000767 continue;
768
John McCallbd309292010-07-06 01:34:17 +0000769 case EHScope::Filter: {
770 assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
John McCall8e4c74b2011-08-11 02:22:43 +0000771 assert(!hasCatchAll && "EH filter reached after catch-all");
John McCallbd309292010-07-06 01:34:17 +0000772
Bill Wendlingf0724e82011-09-19 20:31:14 +0000773 // Filter scopes get added to the landingpad in weird ways.
John McCall8e4c74b2011-08-11 02:22:43 +0000774 EHFilterScope &filter = cast<EHFilterScope>(*I);
775 hasFilter = true;
John McCallbd309292010-07-06 01:34:17 +0000776
Bill Wendling8c4b7162011-09-22 20:32:54 +0000777 // Add all the filter values.
778 for (unsigned i = 0, e = filter.getNumFilters(); i != e; ++i)
779 filterTypes.push_back(filter.getFilter(i));
John McCallbd309292010-07-06 01:34:17 +0000780 goto done;
781 }
782
783 case EHScope::Terminate:
784 // Terminate scopes are basically catch-alls.
John McCall8e4c74b2011-08-11 02:22:43 +0000785 assert(!hasCatchAll);
786 hasCatchAll = true;
John McCallbd309292010-07-06 01:34:17 +0000787 goto done;
788
789 case EHScope::Catch:
790 break;
791 }
792
John McCall8e4c74b2011-08-11 02:22:43 +0000793 EHCatchScope &catchScope = cast<EHCatchScope>(*I);
794 for (unsigned hi = 0, he = catchScope.getNumHandlers(); hi != he; ++hi) {
795 EHCatchScope::Handler handler = catchScope.getHandler(hi);
John McCallbd309292010-07-06 01:34:17 +0000796
John McCall8e4c74b2011-08-11 02:22:43 +0000797 // If this is a catch-all, register that and abort.
798 if (!handler.Type) {
799 assert(!hasCatchAll);
800 hasCatchAll = true;
801 goto done;
John McCallbd309292010-07-06 01:34:17 +0000802 }
803
804 // Check whether we already have a handler for this type.
Bill Wendlingf0724e82011-09-19 20:31:14 +0000805 if (catchTypes.insert(handler.Type))
806 // If not, add it directly to the landingpad.
807 LPadInst->addClause(handler.Type);
John McCallbd309292010-07-06 01:34:17 +0000808 }
John McCallbd309292010-07-06 01:34:17 +0000809 }
810
811 done:
Bill Wendlingf0724e82011-09-19 20:31:14 +0000812 // If we have a catch-all, add null to the landingpad.
John McCall8e4c74b2011-08-11 02:22:43 +0000813 assert(!(hasCatchAll && hasFilter));
814 if (hasCatchAll) {
Bill Wendlingf0724e82011-09-19 20:31:14 +0000815 LPadInst->addClause(getCatchAllValue(*this));
John McCallbd309292010-07-06 01:34:17 +0000816
817 // If we have an EH filter, we need to add those handlers in the
Bill Wendlingf0724e82011-09-19 20:31:14 +0000818 // right place in the landingpad, which is to say, at the end.
John McCall8e4c74b2011-08-11 02:22:43 +0000819 } else if (hasFilter) {
Bill Wendling58e58fe2011-09-19 22:08:36 +0000820 // Create a filter expression: a constant array indicating which filter
821 // types there are. The personality routine only lands here if the filter
822 // doesn't match.
Bill Wendlingf0724e82011-09-19 20:31:14 +0000823 llvm::SmallVector<llvm::Constant*, 8> Filters;
824 llvm::ArrayType *AType =
825 llvm::ArrayType::get(!filterTypes.empty() ?
826 filterTypes[0]->getType() : Int8PtrTy,
827 filterTypes.size());
828
829 for (unsigned i = 0, e = filterTypes.size(); i != e; ++i)
830 Filters.push_back(cast<llvm::Constant>(filterTypes[i]));
831 llvm::Constant *FilterArray = llvm::ConstantArray::get(AType, Filters);
832 LPadInst->addClause(FilterArray);
John McCallbd309292010-07-06 01:34:17 +0000833
834 // Also check whether we need a cleanup.
Bill Wendlingf0724e82011-09-19 20:31:14 +0000835 if (hasCleanup)
836 LPadInst->setCleanup(true);
John McCallbd309292010-07-06 01:34:17 +0000837
838 // Otherwise, signal that we at least have cleanups.
John McCall8e4c74b2011-08-11 02:22:43 +0000839 } else if (CleanupHackLevel == CHL_MandatoryCatchall || hasCleanup) {
Bill Wendlingf0724e82011-09-19 20:31:14 +0000840 if (CleanupHackLevel == CHL_MandatoryCatchall)
841 LPadInst->addClause(getCatchAllValue(*this));
842 else
843 LPadInst->setCleanup(true);
John McCallbd309292010-07-06 01:34:17 +0000844 }
845
Bill Wendlingf0724e82011-09-19 20:31:14 +0000846 assert((LPadInst->getNumClauses() > 0 || LPadInst->isCleanup()) &&
847 "landingpad instruction has no clauses!");
John McCallbd309292010-07-06 01:34:17 +0000848
849 // Tell the backend how to generate the landing pad.
John McCall8e4c74b2011-08-11 02:22:43 +0000850 Builder.CreateBr(getEHDispatchBlock(EHStack.getInnermostEHScope()));
John McCallbd309292010-07-06 01:34:17 +0000851
852 // Restore the old IR generation state.
John McCall8e4c74b2011-08-11 02:22:43 +0000853 Builder.restoreIP(savedIP);
John McCallbd309292010-07-06 01:34:17 +0000854
John McCall8e4c74b2011-08-11 02:22:43 +0000855 return lpad;
John McCallbd309292010-07-06 01:34:17 +0000856}
857
John McCall5c08ab92010-07-13 22:12:14 +0000858namespace {
859 /// A cleanup to call __cxa_end_catch. In many cases, the caught
860 /// exception type lets us state definitively that the thrown exception
861 /// type does not have a destructor. In particular:
862 /// - Catch-alls tell us nothing, so we have to conservatively
863 /// assume that the thrown exception might have a destructor.
864 /// - Catches by reference behave according to their base types.
865 /// - Catches of non-record types will only trigger for exceptions
866 /// of non-record types, which never have destructors.
867 /// - Catches of record types can trigger for arbitrary subclasses
868 /// of the caught type, so we have to assume the actual thrown
869 /// exception type might have a throwing destructor, even if the
870 /// caught type's destructor is trivial or nothrow.
John McCallcda666c2010-07-21 07:22:38 +0000871 struct CallEndCatch : EHScopeStack::Cleanup {
John McCall5c08ab92010-07-13 22:12:14 +0000872 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
873 bool MightThrow;
874
John McCall30317fd2011-07-12 20:27:29 +0000875 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall5c08ab92010-07-13 22:12:14 +0000876 if (!MightThrow) {
877 CGF.Builder.CreateCall(getEndCatchFn(CGF))->setDoesNotThrow();
878 return;
879 }
880
Jay Foad5bd375a2011-07-15 08:37:34 +0000881 CGF.EmitCallOrInvoke(getEndCatchFn(CGF));
John McCall5c08ab92010-07-13 22:12:14 +0000882 }
883 };
884}
885
John McCallbd309292010-07-06 01:34:17 +0000886/// Emits a call to __cxa_begin_catch and enters a cleanup to call
887/// __cxa_end_catch.
John McCall5c08ab92010-07-13 22:12:14 +0000888///
889/// \param EndMightThrow - true if __cxa_end_catch might throw
890static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
891 llvm::Value *Exn,
892 bool EndMightThrow) {
John McCallbd309292010-07-06 01:34:17 +0000893 llvm::CallInst *Call = CGF.Builder.CreateCall(getBeginCatchFn(CGF), Exn);
894 Call->setDoesNotThrow();
895
John McCallcda666c2010-07-21 07:22:38 +0000896 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
John McCallbd309292010-07-06 01:34:17 +0000897
898 return Call;
899}
900
901/// A "special initializer" callback for initializing a catch
902/// parameter during catch initialization.
903static void InitCatchParam(CodeGenFunction &CGF,
904 const VarDecl &CatchParam,
905 llvm::Value *ParamAddr) {
906 // Load the exception from where the landing pad saved it.
Bill Wendling79a70e42011-09-15 18:57:19 +0000907 llvm::Value *Exn = CGF.getExceptionFromSlot();
John McCallbd309292010-07-06 01:34:17 +0000908
909 CanQualType CatchType =
910 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
Chris Lattner2192fe52011-07-18 04:24:23 +0000911 llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
John McCallbd309292010-07-06 01:34:17 +0000912
913 // If we're catching by reference, we can just cast the object
914 // pointer to the appropriate pointer.
915 if (isa<ReferenceType>(CatchType)) {
John McCall5add20c2010-07-20 22:17:55 +0000916 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
917 bool EndCatchMightThrow = CaughtType->isRecordType();
John McCall5c08ab92010-07-13 22:12:14 +0000918
John McCallbd309292010-07-06 01:34:17 +0000919 // __cxa_begin_catch returns the adjusted object pointer.
John McCall5c08ab92010-07-13 22:12:14 +0000920 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
John McCall5add20c2010-07-20 22:17:55 +0000921
922 // We have no way to tell the personality function that we're
923 // catching by reference, so if we're catching a pointer,
924 // __cxa_begin_catch will actually return that pointer by value.
925 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
926 QualType PointeeType = PT->getPointeeType();
927
928 // When catching by reference, generally we should just ignore
929 // this by-value pointer and use the exception object instead.
930 if (!PointeeType->isRecordType()) {
931
932 // Exn points to the struct _Unwind_Exception header, which
933 // we have to skip past in order to reach the exception data.
934 unsigned HeaderSize =
935 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
936 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
937
938 // However, if we're catching a pointer-to-record type that won't
939 // work, because the personality function might have adjusted
940 // the pointer. There's actually no way for us to fully satisfy
941 // the language/ABI contract here: we can't use Exn because it
942 // might have the wrong adjustment, but we can't use the by-value
943 // pointer because it's off by a level of abstraction.
944 //
945 // The current solution is to dump the adjusted pointer into an
946 // alloca, which breaks language semantics (because changing the
947 // pointer doesn't change the exception) but at least works.
948 // The better solution would be to filter out non-exact matches
949 // and rethrow them, but this is tricky because the rethrow
950 // really needs to be catchable by other sites at this landing
951 // pad. The best solution is to fix the personality function.
952 } else {
953 // Pull the pointer for the reference type off.
Chris Lattner2192fe52011-07-18 04:24:23 +0000954 llvm::Type *PtrTy =
John McCall5add20c2010-07-20 22:17:55 +0000955 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
956
957 // Create the temporary and write the adjusted pointer into it.
958 llvm::Value *ExnPtrTmp = CGF.CreateTempAlloca(PtrTy, "exn.byref.tmp");
959 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
960 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
961
962 // Bind the reference to the temporary.
963 AdjustedExn = ExnPtrTmp;
964 }
965 }
966
John McCallbd309292010-07-06 01:34:17 +0000967 llvm::Value *ExnCast =
968 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
969 CGF.Builder.CreateStore(ExnCast, ParamAddr);
970 return;
971 }
972
973 // Non-aggregates (plus complexes).
974 bool IsComplex = false;
975 if (!CGF.hasAggregateLLVMType(CatchType) ||
976 (IsComplex = CatchType->isAnyComplexType())) {
John McCall5c08ab92010-07-13 22:12:14 +0000977 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
John McCallbd309292010-07-06 01:34:17 +0000978
979 // If the catch type is a pointer type, __cxa_begin_catch returns
980 // the pointer by value.
981 if (CatchType->hasPointerRepresentation()) {
982 llvm::Value *CastExn =
983 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
John McCall97017312012-01-17 20:16:56 +0000984
985 switch (CatchType.getQualifiers().getObjCLifetime()) {
986 case Qualifiers::OCL_Strong:
987 CastExn = CGF.EmitARCRetainNonBlock(CastExn);
988 // fallthrough
989
990 case Qualifiers::OCL_None:
991 case Qualifiers::OCL_ExplicitNone:
992 case Qualifiers::OCL_Autoreleasing:
993 CGF.Builder.CreateStore(CastExn, ParamAddr);
994 return;
995
996 case Qualifiers::OCL_Weak:
997 CGF.EmitARCInitWeak(ParamAddr, CastExn);
998 return;
999 }
1000 llvm_unreachable("bad ownership qualifier!");
John McCallbd309292010-07-06 01:34:17 +00001001 }
1002
1003 // Otherwise, it returns a pointer into the exception object.
1004
Chris Lattner2192fe52011-07-18 04:24:23 +00001005 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
John McCallbd309292010-07-06 01:34:17 +00001006 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1007
1008 if (IsComplex) {
1009 CGF.StoreComplexToAddr(CGF.LoadComplexFromAddr(Cast, /*volatile*/ false),
1010 ParamAddr, /*volatile*/ false);
1011 } else {
Daniel Dunbar03816342010-08-21 02:24:36 +00001012 unsigned Alignment =
1013 CGF.getContext().getDeclAlign(&CatchParam).getQuantity();
John McCallbd309292010-07-06 01:34:17 +00001014 llvm::Value *ExnLoad = CGF.Builder.CreateLoad(Cast, "exn.scalar");
Daniel Dunbar03816342010-08-21 02:24:36 +00001015 CGF.EmitStoreOfScalar(ExnLoad, ParamAddr, /*volatile*/ false, Alignment,
1016 CatchType);
John McCallbd309292010-07-06 01:34:17 +00001017 }
1018 return;
1019 }
1020
John McCallb5011ab2011-02-16 08:39:19 +00001021 assert(isa<RecordType>(CatchType) && "unexpected catch type!");
John McCallbd309292010-07-06 01:34:17 +00001022
Chris Lattner2192fe52011-07-18 04:24:23 +00001023 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
John McCallbd309292010-07-06 01:34:17 +00001024
John McCallb5011ab2011-02-16 08:39:19 +00001025 // Check for a copy expression. If we don't have a copy expression,
1026 // that means a trivial copy is okay.
John McCall1bf58462011-02-16 08:02:54 +00001027 const Expr *copyExpr = CatchParam.getInit();
1028 if (!copyExpr) {
John McCallb5011ab2011-02-16 08:39:19 +00001029 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
1030 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
1031 CGF.EmitAggregateCopy(ParamAddr, adjustedExn, CatchType);
John McCallbd309292010-07-06 01:34:17 +00001032 return;
1033 }
1034
1035 // We have to call __cxa_get_exception_ptr to get the adjusted
1036 // pointer before copying.
John McCall1bf58462011-02-16 08:02:54 +00001037 llvm::CallInst *rawAdjustedExn =
John McCallbd309292010-07-06 01:34:17 +00001038 CGF.Builder.CreateCall(getGetExceptionPtrFn(CGF), Exn);
John McCall1bf58462011-02-16 08:02:54 +00001039 rawAdjustedExn->setDoesNotThrow();
John McCallbd309292010-07-06 01:34:17 +00001040
John McCall1bf58462011-02-16 08:02:54 +00001041 // Cast that to the appropriate type.
1042 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
John McCallbd309292010-07-06 01:34:17 +00001043
John McCall1bf58462011-02-16 08:02:54 +00001044 // The copy expression is defined in terms of an OpaqueValueExpr.
1045 // Find it and map it to the adjusted expression.
1046 CodeGenFunction::OpaqueValueMapping
John McCallc07a0c72011-02-17 10:25:35 +00001047 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
1048 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
John McCallbd309292010-07-06 01:34:17 +00001049
1050 // Call the copy ctor in a terminate scope.
1051 CGF.EHStack.pushTerminate();
John McCall1bf58462011-02-16 08:02:54 +00001052
1053 // Perform the copy construction.
Eli Friedman38cd36d2011-12-03 02:13:40 +00001054 CharUnits Alignment = CGF.getContext().getDeclAlign(&CatchParam);
Eli Friedmanc1d85b92011-12-03 00:54:26 +00001055 CGF.EmitAggExpr(copyExpr,
1056 AggValueSlot::forAddr(ParamAddr, Alignment, Qualifiers(),
1057 AggValueSlot::IsNotDestructed,
1058 AggValueSlot::DoesNotNeedGCBarriers,
1059 AggValueSlot::IsNotAliased));
John McCall1bf58462011-02-16 08:02:54 +00001060
1061 // Leave the terminate scope.
John McCallbd309292010-07-06 01:34:17 +00001062 CGF.EHStack.popTerminate();
1063
John McCall1bf58462011-02-16 08:02:54 +00001064 // Undo the opaque value mapping.
1065 opaque.pop();
1066
John McCallbd309292010-07-06 01:34:17 +00001067 // Finally we can call __cxa_begin_catch.
John McCall5c08ab92010-07-13 22:12:14 +00001068 CallBeginCatch(CGF, Exn, true);
John McCallbd309292010-07-06 01:34:17 +00001069}
1070
1071/// Begins a catch statement by initializing the catch variable and
1072/// calling __cxa_begin_catch.
John McCall1bf58462011-02-16 08:02:54 +00001073static void BeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *S) {
John McCallbd309292010-07-06 01:34:17 +00001074 // We have to be very careful with the ordering of cleanups here:
1075 // C++ [except.throw]p4:
1076 // The destruction [of the exception temporary] occurs
1077 // immediately after the destruction of the object declared in
1078 // the exception-declaration in the handler.
1079 //
1080 // So the precise ordering is:
1081 // 1. Construct catch variable.
1082 // 2. __cxa_begin_catch
1083 // 3. Enter __cxa_end_catch cleanup
1084 // 4. Enter dtor cleanup
1085 //
John McCallc533cb72011-02-22 06:44:22 +00001086 // We do this by using a slightly abnormal initialization process.
1087 // Delegation sequence:
John McCallbd309292010-07-06 01:34:17 +00001088 // - ExitCXXTryStmt opens a RunCleanupsScope
John McCallc533cb72011-02-22 06:44:22 +00001089 // - EmitAutoVarAlloca creates the variable and debug info
John McCallbd309292010-07-06 01:34:17 +00001090 // - InitCatchParam initializes the variable from the exception
John McCallc533cb72011-02-22 06:44:22 +00001091 // - CallBeginCatch calls __cxa_begin_catch
1092 // - CallBeginCatch enters the __cxa_end_catch cleanup
1093 // - EmitAutoVarCleanups enters the variable destructor cleanup
John McCallbd309292010-07-06 01:34:17 +00001094 // - EmitCXXTryStmt emits the code for the catch body
1095 // - EmitCXXTryStmt close the RunCleanupsScope
1096
1097 VarDecl *CatchParam = S->getExceptionDecl();
1098 if (!CatchParam) {
Bill Wendling79a70e42011-09-15 18:57:19 +00001099 llvm::Value *Exn = CGF.getExceptionFromSlot();
John McCall5c08ab92010-07-13 22:12:14 +00001100 CallBeginCatch(CGF, Exn, true);
John McCallbd309292010-07-06 01:34:17 +00001101 return;
1102 }
1103
1104 // Emit the local.
John McCallc533cb72011-02-22 06:44:22 +00001105 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
1106 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF));
1107 CGF.EmitAutoVarCleanups(var);
John McCallb81884d2010-02-19 09:25:03 +00001108}
1109
John McCall5c0e69e2010-07-13 22:24:23 +00001110namespace {
John McCallcda666c2010-07-21 07:22:38 +00001111 struct CallRethrow : EHScopeStack::Cleanup {
John McCall30317fd2011-07-12 20:27:29 +00001112 void Emit(CodeGenFunction &CGF, Flags flags) {
Jay Foad5bd375a2011-07-15 08:37:34 +00001113 CGF.EmitCallOrInvoke(getReThrowFn(CGF));
John McCall5c0e69e2010-07-13 22:24:23 +00001114 }
1115 };
1116}
1117
John McCall8e4c74b2011-08-11 02:22:43 +00001118/// Emit the structure of the dispatch block for the given catch scope.
1119/// It is an invariant that the dispatch block already exists.
1120static void emitCatchDispatchBlock(CodeGenFunction &CGF,
1121 EHCatchScope &catchScope) {
1122 llvm::BasicBlock *dispatchBlock = catchScope.getCachedEHDispatchBlock();
1123 assert(dispatchBlock);
1124
1125 // If there's only a single catch-all, getEHDispatchBlock returned
1126 // that catch-all as the dispatch block.
1127 if (catchScope.getNumHandlers() == 1 &&
1128 catchScope.getHandler(0).isCatchAll()) {
1129 assert(dispatchBlock == catchScope.getHandler(0).Block);
1130 return;
1131 }
1132
1133 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveIP();
1134 CGF.EmitBlockAfterUses(dispatchBlock);
1135
1136 // Select the right handler.
1137 llvm::Value *llvm_eh_typeid_for =
1138 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
1139
1140 // Load the selector value.
Bill Wendling79a70e42011-09-15 18:57:19 +00001141 llvm::Value *selector = CGF.getSelectorFromSlot();
John McCall8e4c74b2011-08-11 02:22:43 +00001142
1143 // Test against each of the exception types we claim to catch.
1144 for (unsigned i = 0, e = catchScope.getNumHandlers(); ; ++i) {
1145 assert(i < e && "ran off end of handlers!");
1146 const EHCatchScope::Handler &handler = catchScope.getHandler(i);
1147
1148 llvm::Value *typeValue = handler.Type;
1149 assert(typeValue && "fell into catch-all case!");
1150 typeValue = CGF.Builder.CreateBitCast(typeValue, CGF.Int8PtrTy);
1151
1152 // Figure out the next block.
1153 bool nextIsEnd;
1154 llvm::BasicBlock *nextBlock;
1155
1156 // If this is the last handler, we're at the end, and the next
1157 // block is the block for the enclosing EH scope.
1158 if (i + 1 == e) {
1159 nextBlock = CGF.getEHDispatchBlock(catchScope.getEnclosingEHScope());
1160 nextIsEnd = true;
1161
1162 // If the next handler is a catch-all, we're at the end, and the
1163 // next block is that handler.
1164 } else if (catchScope.getHandler(i+1).isCatchAll()) {
1165 nextBlock = catchScope.getHandler(i+1).Block;
1166 nextIsEnd = true;
1167
1168 // Otherwise, we're not at the end and we need a new block.
1169 } else {
1170 nextBlock = CGF.createBasicBlock("catch.fallthrough");
1171 nextIsEnd = false;
1172 }
1173
1174 // Figure out the catch type's index in the LSDA's type table.
1175 llvm::CallInst *typeIndex =
1176 CGF.Builder.CreateCall(llvm_eh_typeid_for, typeValue);
1177 typeIndex->setDoesNotThrow();
1178
1179 llvm::Value *matchesTypeIndex =
1180 CGF.Builder.CreateICmpEQ(selector, typeIndex, "matches");
1181 CGF.Builder.CreateCondBr(matchesTypeIndex, handler.Block, nextBlock);
1182
1183 // If the next handler is a catch-all, we're completely done.
1184 if (nextIsEnd) {
1185 CGF.Builder.restoreIP(savedIP);
1186 return;
1187
1188 // Otherwise we need to emit and continue at that block.
1189 } else {
1190 CGF.EmitBlock(nextBlock);
1191 }
1192 }
1193
1194 llvm_unreachable("fell out of loop!");
1195}
1196
1197void CodeGenFunction::popCatchScope() {
1198 EHCatchScope &catchScope = cast<EHCatchScope>(*EHStack.begin());
1199 if (catchScope.hasEHBranches())
1200 emitCatchDispatchBlock(*this, catchScope);
1201 EHStack.popCatch();
1202}
1203
John McCallb609d3f2010-07-07 06:56:46 +00001204void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallbd309292010-07-06 01:34:17 +00001205 unsigned NumHandlers = S.getNumHandlers();
1206 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1207 assert(CatchScope.getNumHandlers() == NumHandlers);
Mike Stump58ef18b2009-11-20 23:44:51 +00001208
John McCall8e4c74b2011-08-11 02:22:43 +00001209 // If the catch was not required, bail out now.
1210 if (!CatchScope.hasEHBranches()) {
1211 EHStack.popCatch();
1212 return;
1213 }
1214
1215 // Emit the structure of the EH dispatch for this catch.
1216 emitCatchDispatchBlock(*this, CatchScope);
1217
John McCallbd309292010-07-06 01:34:17 +00001218 // Copy the handler blocks off before we pop the EH stack. Emitting
1219 // the handlers might scribble on this memory.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001220 SmallVector<EHCatchScope::Handler, 8> Handlers(NumHandlers);
John McCallbd309292010-07-06 01:34:17 +00001221 memcpy(Handlers.data(), CatchScope.begin(),
1222 NumHandlers * sizeof(EHCatchScope::Handler));
John McCall8e4c74b2011-08-11 02:22:43 +00001223
John McCallbd309292010-07-06 01:34:17 +00001224 EHStack.popCatch();
Mike Stump58ef18b2009-11-20 23:44:51 +00001225
John McCallbd309292010-07-06 01:34:17 +00001226 // The fall-through block.
1227 llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
Mike Stump58ef18b2009-11-20 23:44:51 +00001228
John McCallbd309292010-07-06 01:34:17 +00001229 // We just emitted the body of the try; jump to the continue block.
1230 if (HaveInsertPoint())
1231 Builder.CreateBr(ContBB);
Mike Stump97329152009-12-02 19:53:57 +00001232
John McCallb609d3f2010-07-07 06:56:46 +00001233 // Determine if we need an implicit rethrow for all these catch handlers.
1234 bool ImplicitRethrow = false;
1235 if (IsFnTryBlock)
1236 ImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
1237 isa<CXXConstructorDecl>(CurCodeDecl);
1238
John McCall8e4c74b2011-08-11 02:22:43 +00001239 // Perversely, we emit the handlers backwards precisely because we
1240 // want them to appear in source order. In all of these cases, the
1241 // catch block will have exactly one predecessor, which will be a
1242 // particular block in the catch dispatch. However, in the case of
1243 // a catch-all, one of the dispatch blocks will branch to two
1244 // different handlers, and EmitBlockAfterUses will cause the second
1245 // handler to be moved before the first.
1246 for (unsigned I = NumHandlers; I != 0; --I) {
1247 llvm::BasicBlock *CatchBlock = Handlers[I-1].Block;
1248 EmitBlockAfterUses(CatchBlock);
Mike Stump75546b82009-12-10 00:06:18 +00001249
John McCallbd309292010-07-06 01:34:17 +00001250 // Catch the exception if this isn't a catch-all.
John McCall8e4c74b2011-08-11 02:22:43 +00001251 const CXXCatchStmt *C = S.getHandler(I-1);
Mike Stump58ef18b2009-11-20 23:44:51 +00001252
John McCallbd309292010-07-06 01:34:17 +00001253 // Enter a cleanup scope, including the catch variable and the
1254 // end-catch.
1255 RunCleanupsScope CatchScope(*this);
Mike Stump58ef18b2009-11-20 23:44:51 +00001256
John McCallbd309292010-07-06 01:34:17 +00001257 // Initialize the catch variable and set up the cleanups.
1258 BeginCatch(*this, C);
1259
John McCallb609d3f2010-07-07 06:56:46 +00001260 // If there's an implicit rethrow, push a normal "cleanup" to call
John McCall5c0e69e2010-07-13 22:24:23 +00001261 // _cxa_rethrow. This needs to happen before __cxa_end_catch is
1262 // called, and so it is pushed after BeginCatch.
1263 if (ImplicitRethrow)
John McCallcda666c2010-07-21 07:22:38 +00001264 EHStack.pushCleanup<CallRethrow>(NormalCleanup);
John McCallb609d3f2010-07-07 06:56:46 +00001265
John McCallbd309292010-07-06 01:34:17 +00001266 // Perform the body of the catch.
1267 EmitStmt(C->getHandlerBlock());
1268
1269 // Fall out through the catch cleanups.
1270 CatchScope.ForceCleanup();
1271
1272 // Branch out of the try.
1273 if (HaveInsertPoint())
1274 Builder.CreateBr(ContBB);
Mike Stump58ef18b2009-11-20 23:44:51 +00001275 }
1276
John McCallbd309292010-07-06 01:34:17 +00001277 EmitBlock(ContBB);
Mike Stump58ef18b2009-11-20 23:44:51 +00001278}
Mike Stumpaff69af2009-12-09 03:35:49 +00001279
John McCall1e670402010-07-21 00:52:03 +00001280namespace {
John McCallcda666c2010-07-21 07:22:38 +00001281 struct CallEndCatchForFinally : EHScopeStack::Cleanup {
John McCall1e670402010-07-21 00:52:03 +00001282 llvm::Value *ForEHVar;
1283 llvm::Value *EndCatchFn;
1284 CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn)
1285 : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
1286
John McCall30317fd2011-07-12 20:27:29 +00001287 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall1e670402010-07-21 00:52:03 +00001288 llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
1289 llvm::BasicBlock *CleanupContBB =
1290 CGF.createBasicBlock("finally.cleanup.cont");
1291
1292 llvm::Value *ShouldEndCatch =
1293 CGF.Builder.CreateLoad(ForEHVar, "finally.endcatch");
1294 CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1295 CGF.EmitBlock(EndCatchBB);
Jay Foad5bd375a2011-07-15 08:37:34 +00001296 CGF.EmitCallOrInvoke(EndCatchFn); // catch-all, so might throw
John McCall1e670402010-07-21 00:52:03 +00001297 CGF.EmitBlock(CleanupContBB);
1298 }
1299 };
John McCall906da4b2010-07-21 05:47:49 +00001300
John McCallcda666c2010-07-21 07:22:38 +00001301 struct PerformFinally : EHScopeStack::Cleanup {
John McCall906da4b2010-07-21 05:47:49 +00001302 const Stmt *Body;
1303 llvm::Value *ForEHVar;
1304 llvm::Value *EndCatchFn;
1305 llvm::Value *RethrowFn;
1306 llvm::Value *SavedExnVar;
1307
1308 PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
1309 llvm::Value *EndCatchFn,
1310 llvm::Value *RethrowFn, llvm::Value *SavedExnVar)
1311 : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1312 RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
1313
John McCall30317fd2011-07-12 20:27:29 +00001314 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall906da4b2010-07-21 05:47:49 +00001315 // Enter a cleanup to call the end-catch function if one was provided.
1316 if (EndCatchFn)
John McCallcda666c2010-07-21 07:22:38 +00001317 CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
1318 ForEHVar, EndCatchFn);
John McCall906da4b2010-07-21 05:47:49 +00001319
John McCallcebe0ca2010-08-11 00:16:14 +00001320 // Save the current cleanup destination in case there are
1321 // cleanups in the finally block.
1322 llvm::Value *SavedCleanupDest =
1323 CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
1324 "cleanup.dest.saved");
1325
John McCall906da4b2010-07-21 05:47:49 +00001326 // Emit the finally block.
1327 CGF.EmitStmt(Body);
1328
1329 // If the end of the finally is reachable, check whether this was
1330 // for EH. If so, rethrow.
1331 if (CGF.HaveInsertPoint()) {
1332 llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
1333 llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
1334
1335 llvm::Value *ShouldRethrow =
1336 CGF.Builder.CreateLoad(ForEHVar, "finally.shouldthrow");
1337 CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1338
1339 CGF.EmitBlock(RethrowBB);
1340 if (SavedExnVar) {
Jay Foad5bd375a2011-07-15 08:37:34 +00001341 CGF.EmitCallOrInvoke(RethrowFn, CGF.Builder.CreateLoad(SavedExnVar));
John McCall906da4b2010-07-21 05:47:49 +00001342 } else {
Jay Foad5bd375a2011-07-15 08:37:34 +00001343 CGF.EmitCallOrInvoke(RethrowFn);
John McCall906da4b2010-07-21 05:47:49 +00001344 }
1345 CGF.Builder.CreateUnreachable();
1346
1347 CGF.EmitBlock(ContBB);
John McCallcebe0ca2010-08-11 00:16:14 +00001348
1349 // Restore the cleanup destination.
1350 CGF.Builder.CreateStore(SavedCleanupDest,
1351 CGF.getNormalCleanupDestSlot());
John McCall906da4b2010-07-21 05:47:49 +00001352 }
1353
1354 // Leave the end-catch cleanup. As an optimization, pretend that
1355 // the fallthrough path was inaccessible; we've dynamically proven
1356 // that we're not in the EH case along that path.
1357 if (EndCatchFn) {
1358 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1359 CGF.PopCleanupBlock();
1360 CGF.Builder.restoreIP(SavedIP);
1361 }
1362
1363 // Now make sure we actually have an insertion point or the
1364 // cleanup gods will hate us.
1365 CGF.EnsureInsertPoint();
1366 }
1367 };
John McCall1e670402010-07-21 00:52:03 +00001368}
1369
John McCallbd309292010-07-06 01:34:17 +00001370/// Enters a finally block for an implementation using zero-cost
1371/// exceptions. This is mostly general, but hard-codes some
1372/// language/ABI-specific behavior in the catch-all sections.
John McCall6b0feb72011-06-22 02:32:12 +00001373void CodeGenFunction::FinallyInfo::enter(CodeGenFunction &CGF,
1374 const Stmt *body,
1375 llvm::Constant *beginCatchFn,
1376 llvm::Constant *endCatchFn,
1377 llvm::Constant *rethrowFn) {
1378 assert((beginCatchFn != 0) == (endCatchFn != 0) &&
John McCallbd309292010-07-06 01:34:17 +00001379 "begin/end catch functions not paired");
John McCall6b0feb72011-06-22 02:32:12 +00001380 assert(rethrowFn && "rethrow function is required");
1381
1382 BeginCatchFn = beginCatchFn;
Mike Stumpaff69af2009-12-09 03:35:49 +00001383
John McCallbd309292010-07-06 01:34:17 +00001384 // The rethrow function has one of the following two types:
1385 // void (*)()
1386 // void (*)(void*)
1387 // In the latter case we need to pass it the exception object.
1388 // But we can't use the exception slot because the @finally might
1389 // have a landing pad (which would overwrite the exception slot).
Chris Lattner2192fe52011-07-18 04:24:23 +00001390 llvm::FunctionType *rethrowFnTy =
John McCallbd309292010-07-06 01:34:17 +00001391 cast<llvm::FunctionType>(
John McCall6b0feb72011-06-22 02:32:12 +00001392 cast<llvm::PointerType>(rethrowFn->getType())->getElementType());
1393 SavedExnVar = 0;
1394 if (rethrowFnTy->getNumParams())
1395 SavedExnVar = CGF.CreateTempAlloca(CGF.Int8PtrTy, "finally.exn");
Mike Stumpaff69af2009-12-09 03:35:49 +00001396
John McCallbd309292010-07-06 01:34:17 +00001397 // A finally block is a statement which must be executed on any edge
1398 // out of a given scope. Unlike a cleanup, the finally block may
1399 // contain arbitrary control flow leading out of itself. In
1400 // addition, finally blocks should always be executed, even if there
1401 // are no catch handlers higher on the stack. Therefore, we
1402 // surround the protected scope with a combination of a normal
1403 // cleanup (to catch attempts to break out of the block via normal
1404 // control flow) and an EH catch-all (semantically "outside" any try
1405 // statement to which the finally block might have been attached).
1406 // The finally block itself is generated in the context of a cleanup
1407 // which conditionally leaves the catch-all.
John McCall21886962010-04-21 10:05:39 +00001408
John McCallbd309292010-07-06 01:34:17 +00001409 // Jump destination for performing the finally block on an exception
1410 // edge. We'll never actually reach this block, so unreachable is
1411 // fine.
John McCall6b0feb72011-06-22 02:32:12 +00001412 RethrowDest = CGF.getJumpDestInCurrentScope(CGF.getUnreachableBlock());
John McCall21886962010-04-21 10:05:39 +00001413
John McCallbd309292010-07-06 01:34:17 +00001414 // Whether the finally block is being executed for EH purposes.
John McCall6b0feb72011-06-22 02:32:12 +00001415 ForEHVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "finally.for-eh");
1416 CGF.Builder.CreateStore(CGF.Builder.getFalse(), ForEHVar);
Mike Stumpaff69af2009-12-09 03:35:49 +00001417
John McCallbd309292010-07-06 01:34:17 +00001418 // Enter a normal cleanup which will perform the @finally block.
John McCall6b0feb72011-06-22 02:32:12 +00001419 CGF.EHStack.pushCleanup<PerformFinally>(NormalCleanup, body,
1420 ForEHVar, endCatchFn,
1421 rethrowFn, SavedExnVar);
John McCallbd309292010-07-06 01:34:17 +00001422
1423 // Enter a catch-all scope.
John McCall6b0feb72011-06-22 02:32:12 +00001424 llvm::BasicBlock *catchBB = CGF.createBasicBlock("finally.catchall");
1425 EHCatchScope *catchScope = CGF.EHStack.pushCatch(1);
1426 catchScope->setCatchAllHandler(0, catchBB);
John McCallbd309292010-07-06 01:34:17 +00001427}
1428
John McCall6b0feb72011-06-22 02:32:12 +00001429void CodeGenFunction::FinallyInfo::exit(CodeGenFunction &CGF) {
John McCallbd309292010-07-06 01:34:17 +00001430 // Leave the finally catch-all.
John McCall6b0feb72011-06-22 02:32:12 +00001431 EHCatchScope &catchScope = cast<EHCatchScope>(*CGF.EHStack.begin());
1432 llvm::BasicBlock *catchBB = catchScope.getHandler(0).Block;
John McCall8e4c74b2011-08-11 02:22:43 +00001433
1434 CGF.popCatchScope();
John McCallbd309292010-07-06 01:34:17 +00001435
John McCall6b0feb72011-06-22 02:32:12 +00001436 // If there are any references to the catch-all block, emit it.
1437 if (catchBB->use_empty()) {
1438 delete catchBB;
1439 } else {
1440 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveAndClearIP();
1441 CGF.EmitBlock(catchBB);
John McCallbd309292010-07-06 01:34:17 +00001442
John McCall6b0feb72011-06-22 02:32:12 +00001443 llvm::Value *exn = 0;
John McCallbd309292010-07-06 01:34:17 +00001444
John McCall6b0feb72011-06-22 02:32:12 +00001445 // If there's a begin-catch function, call it.
1446 if (BeginCatchFn) {
Bill Wendling79a70e42011-09-15 18:57:19 +00001447 exn = CGF.getExceptionFromSlot();
John McCall6b0feb72011-06-22 02:32:12 +00001448 CGF.Builder.CreateCall(BeginCatchFn, exn)->setDoesNotThrow();
1449 }
1450
1451 // If we need to remember the exception pointer to rethrow later, do so.
1452 if (SavedExnVar) {
Bill Wendling79a70e42011-09-15 18:57:19 +00001453 if (!exn) exn = CGF.getExceptionFromSlot();
John McCall6b0feb72011-06-22 02:32:12 +00001454 CGF.Builder.CreateStore(exn, SavedExnVar);
1455 }
1456
1457 // Tell the cleanups in the finally block that we're do this for EH.
1458 CGF.Builder.CreateStore(CGF.Builder.getTrue(), ForEHVar);
1459
1460 // Thread a jump through the finally cleanup.
1461 CGF.EmitBranchThroughCleanup(RethrowDest);
1462
1463 CGF.Builder.restoreIP(savedIP);
1464 }
1465
1466 // Finally, leave the @finally cleanup.
1467 CGF.PopCleanupBlock();
John McCallbd309292010-07-06 01:34:17 +00001468}
1469
1470llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
1471 if (TerminateLandingPad)
1472 return TerminateLandingPad;
1473
1474 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1475
1476 // This will get inserted at the end of the function.
1477 TerminateLandingPad = createBasicBlock("terminate.lpad");
1478 Builder.SetInsertPoint(TerminateLandingPad);
1479
1480 // Tell the backend that this is a landing pad.
John McCall36ea3722010-07-17 00:43:08 +00001481 const EHPersonality &Personality = EHPersonality::get(CGM.getLangOptions());
Bill Wendlingf0724e82011-09-19 20:31:14 +00001482 llvm::LandingPadInst *LPadInst =
1483 Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, NULL),
1484 getOpaquePersonalityFn(CGM, Personality), 0);
1485 LPadInst->addClause(getCatchAllValue(*this));
John McCallbd309292010-07-06 01:34:17 +00001486
1487 llvm::CallInst *TerminateCall = Builder.CreateCall(getTerminateFn(*this));
1488 TerminateCall->setDoesNotReturn();
1489 TerminateCall->setDoesNotThrow();
John McCallad7c5c12011-02-08 08:22:06 +00001490 Builder.CreateUnreachable();
Mike Stumpaff69af2009-12-09 03:35:49 +00001491
John McCallbd309292010-07-06 01:34:17 +00001492 // Restore the saved insertion state.
1493 Builder.restoreIP(SavedIP);
John McCalldac3ea62010-04-30 00:06:43 +00001494
John McCallbd309292010-07-06 01:34:17 +00001495 return TerminateLandingPad;
Mike Stumpaff69af2009-12-09 03:35:49 +00001496}
Mike Stump2b488872009-12-09 22:59:31 +00001497
1498llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
Mike Stumpf5cbb082009-12-10 00:02:42 +00001499 if (TerminateHandler)
1500 return TerminateHandler;
1501
John McCallbd309292010-07-06 01:34:17 +00001502 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
Mike Stump25b20fc2009-12-09 23:31:35 +00001503
John McCallbd309292010-07-06 01:34:17 +00001504 // Set up the terminate handler. This block is inserted at the very
1505 // end of the function by FinishFunction.
Mike Stumpf5cbb082009-12-10 00:02:42 +00001506 TerminateHandler = createBasicBlock("terminate.handler");
John McCallbd309292010-07-06 01:34:17 +00001507 Builder.SetInsertPoint(TerminateHandler);
1508 llvm::CallInst *TerminateCall = Builder.CreateCall(getTerminateFn(*this));
Mike Stump2b488872009-12-09 22:59:31 +00001509 TerminateCall->setDoesNotReturn();
1510 TerminateCall->setDoesNotThrow();
1511 Builder.CreateUnreachable();
1512
John McCall21886962010-04-21 10:05:39 +00001513 // Restore the saved insertion state.
John McCallbd309292010-07-06 01:34:17 +00001514 Builder.restoreIP(SavedIP);
Mike Stump25b20fc2009-12-09 23:31:35 +00001515
Mike Stump2b488872009-12-09 22:59:31 +00001516 return TerminateHandler;
1517}
John McCallbd309292010-07-06 01:34:17 +00001518
John McCall8e4c74b2011-08-11 02:22:43 +00001519llvm::BasicBlock *CodeGenFunction::getEHResumeBlock() {
1520 if (EHResumeBlock) return EHResumeBlock;
John McCallad5d61e2010-07-23 21:56:41 +00001521
1522 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1523
1524 // We emit a jump to a notional label at the outermost unwind state.
John McCall8e4c74b2011-08-11 02:22:43 +00001525 EHResumeBlock = createBasicBlock("eh.resume");
1526 Builder.SetInsertPoint(EHResumeBlock);
John McCallad5d61e2010-07-23 21:56:41 +00001527
1528 const EHPersonality &Personality = EHPersonality::get(CGM.getLangOptions());
1529
1530 // This can always be a call because we necessarily didn't find
1531 // anything on the EH stack which needs our help.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001532 StringRef RethrowName = Personality.getCatchallRethrowFnName();
John McCall9b382dd2011-05-28 21:13:02 +00001533 if (!RethrowName.empty()) {
1534 Builder.CreateCall(getCatchallRethrowFn(*this, RethrowName),
Bill Wendling79a70e42011-09-15 18:57:19 +00001535 getExceptionFromSlot())
John McCall9b382dd2011-05-28 21:13:02 +00001536 ->setDoesNotReturn();
1537 } else {
John McCall9b382dd2011-05-28 21:13:02 +00001538 switch (CleanupHackLevel) {
1539 case CHL_MandatoryCatchall:
1540 // In mandatory-catchall mode, we need to use
1541 // _Unwind_Resume_or_Rethrow, or whatever the personality's
1542 // equivalent is.
Bill Wendling90118a32011-12-08 23:21:26 +00001543 Builder.CreateCall(getUnwindResumeOrRethrowFn(),
1544 getExceptionFromSlot())
John McCall9b382dd2011-05-28 21:13:02 +00001545 ->setDoesNotReturn();
1546 break;
1547 case CHL_MandatoryCleanup: {
Bill Wendlingf0724e82011-09-19 20:31:14 +00001548 // In mandatory-cleanup mode, we should use 'resume'.
1549
1550 // Recreate the landingpad's return value for the 'resume' instruction.
1551 llvm::Value *Exn = getExceptionFromSlot();
1552 llvm::Value *Sel = getSelectorFromSlot();
1553
1554 llvm::Type *LPadType = llvm::StructType::get(Exn->getType(),
1555 Sel->getType(), NULL);
1556 llvm::Value *LPadVal = llvm::UndefValue::get(LPadType);
1557 LPadVal = Builder.CreateInsertValue(LPadVal, Exn, 0, "lpad.val");
1558 LPadVal = Builder.CreateInsertValue(LPadVal, Sel, 1, "lpad.val");
1559
1560 Builder.CreateResume(LPadVal);
1561 Builder.restoreIP(SavedIP);
1562 return EHResumeBlock;
John McCall9b382dd2011-05-28 21:13:02 +00001563 }
1564 case CHL_Ideal:
1565 // In an idealized mode where we don't have to worry about the
1566 // optimizer combining landing pads, we should just use
1567 // _Unwind_Resume (or the personality's equivalent).
Bill Wendling90118a32011-12-08 23:21:26 +00001568 Builder.CreateCall(getUnwindResumeFn(), getExceptionFromSlot())
John McCall9b382dd2011-05-28 21:13:02 +00001569 ->setDoesNotReturn();
1570 break;
1571 }
1572 }
1573
John McCallad5d61e2010-07-23 21:56:41 +00001574 Builder.CreateUnreachable();
1575
1576 Builder.restoreIP(SavedIP);
1577
John McCall8e4c74b2011-08-11 02:22:43 +00001578 return EHResumeBlock;
John McCallad5d61e2010-07-23 21:56:41 +00001579}