blob: 30d4072af2d499aed8bdf002e041089d18385c79 [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 Lattnera5f58b02011-07-09 17:41:47 +000032 llvm::Type *SizeTy = CGF.ConvertType(CGF.getContext().getSizeType());
33 llvm::Type *ArgTys[] = { SizeTy };
Mike Stump75546b82009-12-10 00:06:18 +000034 const llvm::FunctionType *FTy =
Anders Carlsson566ae672011-04-18 14:24:10 +000035 llvm::FunctionType::get(llvm::Type::getInt8PtrTy(CGF.getLLVMContext()),
Chris Lattnera5f58b02011-07-09 17:41:47 +000036 ArgTys, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000037
Anders Carlsson32e1b1c2009-10-30 02:27:02 +000038 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
39}
40
Mike Stump33270212009-12-02 07:41:41 +000041static llvm::Constant *getFreeExceptionFn(CodeGenFunction &CGF) {
42 // void __cxa_free_exception(void *thrown_exception);
Mike Stump75546b82009-12-10 00:06:18 +000043
Chris Lattnera5f58b02011-07-09 17:41:47 +000044 llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
45 llvm::Type *ArgTys[] = { Int8PtrTy };
Mike Stump75546b82009-12-10 00:06:18 +000046 const llvm::FunctionType *FTy =
Anders Carlsson566ae672011-04-18 14:24:10 +000047 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
Chris Lattnera5f58b02011-07-09 17:41:47 +000048 ArgTys, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000049
Mike Stump33270212009-12-02 07:41:41 +000050 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_free_exception");
51}
52
Anders Carlsson32e1b1c2009-10-30 02:27:02 +000053static llvm::Constant *getThrowFn(CodeGenFunction &CGF) {
Mike Stump75546b82009-12-10 00:06:18 +000054 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
Mike Stump33270212009-12-02 07:41:41 +000055 // void (*dest) (void *));
Anders Carlsson32e1b1c2009-10-30 02:27:02 +000056
Chris Lattnera5f58b02011-07-09 17:41:47 +000057 llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
58 llvm::Type *Args[3] = { Int8PtrTy, Int8PtrTy, Int8PtrTy };
Mike Stump75546b82009-12-10 00:06:18 +000059 const llvm::FunctionType *FTy =
Mike Stumpd1782cc2009-11-20 00:56:31 +000060 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
Anders Carlsson566ae672011-04-18 14:24:10 +000061 Args, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000062
Anders Carlsson32e1b1c2009-10-30 02:27:02 +000063 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
64}
65
Mike Stumpd1782cc2009-11-20 00:56:31 +000066static llvm::Constant *getReThrowFn(CodeGenFunction &CGF) {
Mike Stump33270212009-12-02 07:41:41 +000067 // void __cxa_rethrow();
Mike Stumpd1782cc2009-11-20 00:56:31 +000068
Mike Stump75546b82009-12-10 00:06:18 +000069 const llvm::FunctionType *FTy =
Anders Carlsson566ae672011-04-18 14:24:10 +000070 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
71 /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000072
Mike Stumpd1782cc2009-11-20 00:56:31 +000073 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
74}
75
John McCallbd309292010-07-06 01:34:17 +000076static llvm::Constant *getGetExceptionPtrFn(CodeGenFunction &CGF) {
77 // void *__cxa_get_exception_ptr(void*);
John McCallbd309292010-07-06 01:34:17 +000078
Chris Lattnera5f58b02011-07-09 17:41:47 +000079 llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
80 llvm::Type *ArgTys[] = { Int8PtrTy };
John McCallbd309292010-07-06 01:34:17 +000081 const llvm::FunctionType *FTy =
Chris Lattnera5f58b02011-07-09 17:41:47 +000082 llvm::FunctionType::get(Int8PtrTy, ArgTys, /*IsVarArgs=*/false);
John McCallbd309292010-07-06 01:34:17 +000083
84 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
85}
86
Mike Stump58ef18b2009-11-20 23:44:51 +000087static llvm::Constant *getBeginCatchFn(CodeGenFunction &CGF) {
John McCallbd309292010-07-06 01:34:17 +000088 // void *__cxa_begin_catch(void*);
Mike Stump58ef18b2009-11-20 23:44:51 +000089
Chris Lattnera5f58b02011-07-09 17:41:47 +000090 llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
91 llvm::Type *ArgTys[] = { Int8PtrTy };
Mike Stump75546b82009-12-10 00:06:18 +000092 const llvm::FunctionType *FTy =
Chris Lattnera5f58b02011-07-09 17:41:47 +000093 llvm::FunctionType::get(Int8PtrTy, ArgTys, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000094
Mike Stump58ef18b2009-11-20 23:44:51 +000095 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
96}
97
98static llvm::Constant *getEndCatchFn(CodeGenFunction &CGF) {
Mike Stump33270212009-12-02 07:41:41 +000099 // void __cxa_end_catch();
Mike Stump58ef18b2009-11-20 23:44:51 +0000100
Mike Stump75546b82009-12-10 00:06:18 +0000101 const llvm::FunctionType *FTy =
Anders Carlsson566ae672011-04-18 14:24:10 +0000102 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
103 /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +0000104
Mike Stump58ef18b2009-11-20 23:44:51 +0000105 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
106}
107
Mike Stump1d849212009-12-07 23:38:24 +0000108static llvm::Constant *getUnexpectedFn(CodeGenFunction &CGF) {
109 // void __cxa_call_unexepcted(void *thrown_exception);
110
Chris Lattnera5f58b02011-07-09 17:41:47 +0000111 llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
112 llvm::Type *ArgTys[] = { Int8PtrTy };
Mike Stump75546b82009-12-10 00:06:18 +0000113 const llvm::FunctionType *FTy =
Mike Stump1d849212009-12-07 23:38:24 +0000114 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
Chris Lattnera5f58b02011-07-09 17:41:47 +0000115 ArgTys, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +0000116
Mike Stump1d849212009-12-07 23:38:24 +0000117 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_call_unexpected");
118}
119
John McCall9b382dd2011-05-28 21:13:02 +0000120llvm::Constant *CodeGenFunction::getUnwindResumeFn() {
Chris Lattnera5f58b02011-07-09 17:41:47 +0000121 llvm::Type *ArgTys[] = { Int8PtrTy };
John McCall63fb3332011-05-27 20:01:14 +0000122 const llvm::FunctionType *FTy =
Chris Lattnera5f58b02011-07-09 17:41:47 +0000123 llvm::FunctionType::get(VoidTy, ArgTys, /*IsVarArgs=*/false);
John McCall9b382dd2011-05-28 21:13:02 +0000124
125 if (CGM.getLangOptions().SjLjExceptions)
126 return CGM.CreateRuntimeFunction(FTy, "_Unwind_SjLj_Resume");
127 return CGM.CreateRuntimeFunction(FTy, "_Unwind_Resume");
128}
129
130llvm::Constant *CodeGenFunction::getUnwindResumeOrRethrowFn() {
Chris Lattnera5f58b02011-07-09 17:41:47 +0000131 llvm::Type *ArgTys[] = { Int8PtrTy };
John McCall9b382dd2011-05-28 21:13:02 +0000132 const llvm::FunctionType *FTy =
Chris Lattnera5f58b02011-07-09 17:41:47 +0000133 llvm::FunctionType::get(VoidTy, ArgTys, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +0000134
Douglas Gregor51150ab2010-05-16 01:24:12 +0000135 if (CGM.getLangOptions().SjLjExceptions)
John McCallffe46302010-08-11 20:59:53 +0000136 return CGM.CreateRuntimeFunction(FTy, "_Unwind_SjLj_Resume_or_Rethrow");
Douglas Gregor51150ab2010-05-16 01:24:12 +0000137 return CGM.CreateRuntimeFunction(FTy, "_Unwind_Resume_or_Rethrow");
Mike Stump54066142009-12-01 03:41:18 +0000138}
139
Mike Stump33270212009-12-02 07:41:41 +0000140static llvm::Constant *getTerminateFn(CodeGenFunction &CGF) {
141 // void __terminate();
142
Mike Stump75546b82009-12-10 00:06:18 +0000143 const llvm::FunctionType *FTy =
Anders Carlsson566ae672011-04-18 14:24:10 +0000144 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
145 /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +0000146
John McCall9de19782011-07-06 01:22:26 +0000147 llvm::StringRef name;
148
149 // In C++, use std::terminate().
150 if (CGF.getLangOptions().CPlusPlus)
151 name = "_ZSt9terminatev"; // FIXME: mangling!
152 else if (CGF.getLangOptions().ObjC1 &&
153 CGF.CGM.getCodeGenOpts().ObjCRuntimeHasTerminate)
154 name = "objc_terminate";
155 else
156 name = "abort";
157 return CGF.CGM.CreateRuntimeFunction(FTy, name);
David Chisnallf9c42252010-05-17 13:49:20 +0000158}
159
John McCall36ea3722010-07-17 00:43:08 +0000160static llvm::Constant *getCatchallRethrowFn(CodeGenFunction &CGF,
John McCall0bdb1fd2010-09-16 06:16:50 +0000161 llvm::StringRef Name) {
Chris Lattnera5f58b02011-07-09 17:41:47 +0000162 llvm::Type *Int8PtrTy =
John McCall36ea3722010-07-17 00:43:08 +0000163 llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
John McCall36ea3722010-07-17 00:43:08 +0000164 const llvm::Type *VoidTy = llvm::Type::getVoidTy(CGF.getLLVMContext());
Chris Lattnera5f58b02011-07-09 17:41:47 +0000165 llvm::Type *ArgTys[] = { Int8PtrTy };
166 const llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, ArgTys,
Anders Carlsson566ae672011-04-18 14:24:10 +0000167 /*IsVarArgs=*/false);
John McCall36ea3722010-07-17 00:43:08 +0000168
169 return CGF.CGM.CreateRuntimeFunction(FTy, Name);
John McCallbd309292010-07-06 01:34:17 +0000170}
171
John McCall36ea3722010-07-17 00:43:08 +0000172const EHPersonality EHPersonality::GNU_C("__gcc_personality_v0");
John McCall2faab302010-11-07 02:35:25 +0000173const EHPersonality EHPersonality::GNU_C_SJLJ("__gcc_personality_sj0");
John McCall36ea3722010-07-17 00:43:08 +0000174const EHPersonality EHPersonality::NeXT_ObjC("__objc_personality_v0");
175const EHPersonality EHPersonality::GNU_CPlusPlus("__gxx_personality_v0");
176const EHPersonality EHPersonality::GNU_CPlusPlus_SJLJ("__gxx_personality_sj0");
177const EHPersonality EHPersonality::GNU_ObjC("__gnu_objc_personality_v0",
178 "objc_exception_throw");
David Chisnalle1d2584d2011-03-20 21:35:39 +0000179const EHPersonality EHPersonality::GNU_ObjCXX("__gnustep_objcxx_personality_v0");
John McCall36ea3722010-07-17 00:43:08 +0000180
181static const EHPersonality &getCPersonality(const LangOptions &L) {
John McCall2faab302010-11-07 02:35:25 +0000182 if (L.SjLjExceptions)
183 return EHPersonality::GNU_C_SJLJ;
John McCall36ea3722010-07-17 00:43:08 +0000184 return EHPersonality::GNU_C;
185}
186
187static const EHPersonality &getObjCPersonality(const LangOptions &L) {
188 if (L.NeXTRuntime) {
189 if (L.ObjCNonFragileABI) return EHPersonality::NeXT_ObjC;
190 else return getCPersonality(L);
John McCallbd309292010-07-06 01:34:17 +0000191 } else {
John McCall36ea3722010-07-17 00:43:08 +0000192 return EHPersonality::GNU_ObjC;
John McCallbd309292010-07-06 01:34:17 +0000193 }
194}
195
John McCall36ea3722010-07-17 00:43:08 +0000196static const EHPersonality &getCXXPersonality(const LangOptions &L) {
197 if (L.SjLjExceptions)
198 return EHPersonality::GNU_CPlusPlus_SJLJ;
John McCallbd309292010-07-06 01:34:17 +0000199 else
John McCall36ea3722010-07-17 00:43:08 +0000200 return EHPersonality::GNU_CPlusPlus;
John McCallbd309292010-07-06 01:34:17 +0000201}
202
203/// Determines the personality function to use when both C++
204/// and Objective-C exceptions are being caught.
John McCall36ea3722010-07-17 00:43:08 +0000205static const EHPersonality &getObjCXXPersonality(const LangOptions &L) {
John McCallbd309292010-07-06 01:34:17 +0000206 // The ObjC personality defers to the C++ personality for non-ObjC
207 // handlers. Unlike the C++ case, we use the same personality
208 // function on targets using (backend-driven) SJLJ EH.
John McCall36ea3722010-07-17 00:43:08 +0000209 if (L.NeXTRuntime) {
210 if (L.ObjCNonFragileABI)
211 return EHPersonality::NeXT_ObjC;
John McCallbd309292010-07-06 01:34:17 +0000212
213 // In the fragile ABI, just use C++ exception handling and hope
214 // they're not doing crazy exception mixing.
215 else
John McCall36ea3722010-07-17 00:43:08 +0000216 return getCXXPersonality(L);
Chandler Carruth0450cc62010-05-17 20:58:49 +0000217 }
David Chisnallf9c42252010-05-17 13:49:20 +0000218
John McCall36ea3722010-07-17 00:43:08 +0000219 // The GNU runtime's personality function inherently doesn't support
220 // mixed EH. Use the C++ personality just to avoid returning null.
David Chisnalle1d2584d2011-03-20 21:35:39 +0000221 return EHPersonality::GNU_ObjCXX;
John McCallbd309292010-07-06 01:34:17 +0000222}
223
John McCall36ea3722010-07-17 00:43:08 +0000224const EHPersonality &EHPersonality::get(const LangOptions &L) {
225 if (L.CPlusPlus && L.ObjC1)
226 return getObjCXXPersonality(L);
227 else if (L.CPlusPlus)
228 return getCXXPersonality(L);
229 else if (L.ObjC1)
230 return getObjCPersonality(L);
John McCallbd309292010-07-06 01:34:17 +0000231 else
John McCall36ea3722010-07-17 00:43:08 +0000232 return getCPersonality(L);
233}
John McCallbd309292010-07-06 01:34:17 +0000234
John McCall0bdb1fd2010-09-16 06:16:50 +0000235static llvm::Constant *getPersonalityFn(CodeGenModule &CGM,
John McCall36ea3722010-07-17 00:43:08 +0000236 const EHPersonality &Personality) {
John McCall36ea3722010-07-17 00:43:08 +0000237 llvm::Constant *Fn =
John McCall0bdb1fd2010-09-16 06:16:50 +0000238 CGM.CreateRuntimeFunction(llvm::FunctionType::get(
239 llvm::Type::getInt32Ty(CGM.getLLVMContext()),
240 true),
241 Personality.getPersonalityFnName());
242 return Fn;
243}
244
245static llvm::Constant *getOpaquePersonalityFn(CodeGenModule &CGM,
246 const EHPersonality &Personality) {
247 llvm::Constant *Fn = getPersonalityFn(CGM, Personality);
John McCallad7c5c12011-02-08 08:22:06 +0000248 return llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
John McCall0bdb1fd2010-09-16 06:16:50 +0000249}
250
251/// Check whether a personality function could reasonably be swapped
252/// for a C++ personality function.
253static bool PersonalityHasOnlyCXXUses(llvm::Constant *Fn) {
254 for (llvm::Constant::use_iterator
255 I = Fn->use_begin(), E = Fn->use_end(); I != E; ++I) {
256 llvm::User *User = *I;
257
258 // Conditionally white-list bitcasts.
259 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(User)) {
260 if (CE->getOpcode() != llvm::Instruction::BitCast) return false;
261 if (!PersonalityHasOnlyCXXUses(CE))
262 return false;
263 continue;
264 }
265
266 // Otherwise, it has to be a selector call.
267 if (!isa<llvm::EHSelectorInst>(User)) return false;
268
269 llvm::EHSelectorInst *Selector = cast<llvm::EHSelectorInst>(User);
270 for (unsigned I = 2, E = Selector->getNumArgOperands(); I != E; ++I) {
271 // Look for something that would've been returned by the ObjC
272 // runtime's GetEHType() method.
273 llvm::GlobalVariable *GV
274 = dyn_cast<llvm::GlobalVariable>(Selector->getArgOperand(I));
275 if (!GV) continue;
276
277 // ObjC EH selector entries are always global variables with
278 // names starting like this.
279 if (GV->getName().startswith("OBJC_EHTYPE"))
280 return false;
281 }
282 }
283
284 return true;
285}
286
287/// Try to use the C++ personality function in ObjC++. Not doing this
288/// can cause some incompatibilities with gcc, which is more
289/// aggressive about only using the ObjC++ personality in a function
290/// when it really needs it.
291void CodeGenModule::SimplifyPersonality() {
292 // For now, this is really a Darwin-specific operation.
Daniel Dunbara59b0a62011-04-26 19:43:00 +0000293 if (!Context.Target.getTriple().isOSDarwin())
John McCall0bdb1fd2010-09-16 06:16:50 +0000294 return;
295
296 // If we're not in ObjC++ -fexceptions, there's nothing to do.
297 if (!Features.CPlusPlus || !Features.ObjC1 || !Features.Exceptions)
298 return;
299
300 const EHPersonality &ObjCXX = EHPersonality::get(Features);
301 const EHPersonality &CXX = getCXXPersonality(Features);
302 if (&ObjCXX == &CXX ||
303 ObjCXX.getPersonalityFnName() == CXX.getPersonalityFnName())
304 return;
305
306 llvm::Function *Fn =
307 getModule().getFunction(ObjCXX.getPersonalityFnName());
308
309 // Nothing to do if it's unused.
310 if (!Fn || Fn->use_empty()) return;
311
312 // Can't do the optimization if it has non-C++ uses.
313 if (!PersonalityHasOnlyCXXUses(Fn)) return;
314
315 // Create the C++ personality function and kill off the old
316 // function.
317 llvm::Constant *CXXFn = getPersonalityFn(*this, CXX);
318
319 // This can happen if the user is screwing with us.
320 if (Fn->getType() != CXXFn->getType()) return;
321
322 Fn->replaceAllUsesWith(CXXFn);
323 Fn->eraseFromParent();
John McCallbd309292010-07-06 01:34:17 +0000324}
325
326/// Returns the value to inject into a selector to indicate the
327/// presence of a catch-all.
328static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
329 // Possibly we should use @llvm.eh.catch.all.value here.
John McCallad7c5c12011-02-08 08:22:06 +0000330 return llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
John McCallbd309292010-07-06 01:34:17 +0000331}
332
333/// Returns the value to inject into a selector to indicate the
334/// presence of a cleanup.
335static llvm::Constant *getCleanupValue(CodeGenFunction &CGF) {
336 return llvm::ConstantInt::get(CGF.Builder.getInt32Ty(), 0);
Mike Stump33270212009-12-02 07:41:41 +0000337}
338
John McCallbb026012010-07-13 21:17:51 +0000339namespace {
340 /// A cleanup to free the exception object if its initialization
341 /// throws.
John McCalle4df6c82011-01-28 08:37:24 +0000342 struct FreeException {
343 static void Emit(CodeGenFunction &CGF, bool forEH,
344 llvm::Value *exn) {
345 CGF.Builder.CreateCall(getFreeExceptionFn(CGF), exn)
John McCallbb026012010-07-13 21:17:51 +0000346 ->setDoesNotThrow();
John McCallbb026012010-07-13 21:17:51 +0000347 }
348 };
349}
350
John McCall2e6567a2010-04-22 01:10:34 +0000351// Emits an exception expression into the given location. This
352// differs from EmitAnyExprToMem only in that, if a final copy-ctor
353// call is required, an exception within that copy ctor causes
354// std::terminate to be invoked.
John McCalle4df6c82011-01-28 08:37:24 +0000355static void EmitAnyExprToExn(CodeGenFunction &CGF, const Expr *e,
356 llvm::Value *addr) {
John McCallbd309292010-07-06 01:34:17 +0000357 // Make sure the exception object is cleaned up if there's an
358 // exception during initialization.
John McCalle4df6c82011-01-28 08:37:24 +0000359 CGF.pushFullExprCleanup<FreeException>(EHCleanup, addr);
360 EHScopeStack::stable_iterator cleanup = CGF.EHStack.stable_begin();
John McCall2e6567a2010-04-22 01:10:34 +0000361
362 // __cxa_allocate_exception returns a void*; we need to cast this
363 // to the appropriate type for the object.
John McCalle4df6c82011-01-28 08:37:24 +0000364 const llvm::Type *ty = CGF.ConvertTypeForMem(e->getType())->getPointerTo();
365 llvm::Value *typedAddr = CGF.Builder.CreateBitCast(addr, ty);
John McCall2e6567a2010-04-22 01:10:34 +0000366
367 // FIXME: this isn't quite right! If there's a final unelided call
368 // to a copy constructor, then according to [except.terminate]p1 we
369 // must call std::terminate() if that constructor throws, because
370 // technically that copy occurs after the exception expression is
371 // evaluated but before the exception is caught. But the best way
372 // to handle that is to teach EmitAggExpr to do the final copy
373 // differently if it can't be elided.
John McCall31168b02011-06-15 23:02:42 +0000374 CGF.EmitAnyExprToMem(e, typedAddr, e->getType().getQualifiers(),
375 /*IsInit*/ true);
John McCall2e6567a2010-04-22 01:10:34 +0000376
John McCalle4df6c82011-01-28 08:37:24 +0000377 // Deactivate the cleanup block.
378 CGF.DeactivateCleanupBlock(cleanup);
Mike Stump54066142009-12-01 03:41:18 +0000379}
380
John McCallbd309292010-07-06 01:34:17 +0000381llvm::Value *CodeGenFunction::getExceptionSlot() {
John McCall9b382dd2011-05-28 21:13:02 +0000382 if (!ExceptionSlot)
383 ExceptionSlot = CreateTempAlloca(Int8PtrTy, "exn.slot");
John McCallbd309292010-07-06 01:34:17 +0000384 return ExceptionSlot;
Mike Stump54066142009-12-01 03:41:18 +0000385}
386
John McCall9b382dd2011-05-28 21:13:02 +0000387llvm::Value *CodeGenFunction::getEHSelectorSlot() {
388 if (!EHSelectorSlot)
389 EHSelectorSlot = CreateTempAlloca(Int32Ty, "ehselector.slot");
390 return EHSelectorSlot;
391}
392
Anders Carlsson4b08db72009-10-30 01:42:31 +0000393void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E) {
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000394 if (!E->getSubExpr()) {
Douglas Gregorc278d1b2010-05-16 00:44:00 +0000395 if (getInvokeDest()) {
John McCallbd309292010-07-06 01:34:17 +0000396 Builder.CreateInvoke(getReThrowFn(*this),
397 getUnreachableBlock(),
398 getInvokeDest())
Douglas Gregorc278d1b2010-05-16 00:44:00 +0000399 ->setDoesNotReturn();
John McCallbd309292010-07-06 01:34:17 +0000400 } else {
Douglas Gregorc278d1b2010-05-16 00:44:00 +0000401 Builder.CreateCall(getReThrowFn(*this))->setDoesNotReturn();
John McCallbd309292010-07-06 01:34:17 +0000402 Builder.CreateUnreachable();
403 }
Douglas Gregorc278d1b2010-05-16 00:44:00 +0000404
John McCall20f6ab82011-01-12 03:41:02 +0000405 // throw is an expression, and the expression emitters expect us
406 // to leave ourselves at a valid insertion point.
407 EmitBlock(createBasicBlock("throw.cont"));
408
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000409 return;
410 }
Mike Stump75546b82009-12-10 00:06:18 +0000411
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000412 QualType ThrowType = E->getSubExpr()->getType();
Mike Stump75546b82009-12-10 00:06:18 +0000413
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000414 // Now allocate the exception object.
415 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
John McCall21886962010-04-21 10:05:39 +0000416 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
Mike Stump75546b82009-12-10 00:06:18 +0000417
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000418 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(*this);
John McCallbd309292010-07-06 01:34:17 +0000419 llvm::CallInst *ExceptionPtr =
Mike Stump75546b82009-12-10 00:06:18 +0000420 Builder.CreateCall(AllocExceptionFn,
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000421 llvm::ConstantInt::get(SizeTy, TypeSize),
422 "exception");
John McCallbd309292010-07-06 01:34:17 +0000423 ExceptionPtr->setDoesNotThrow();
Anders Carlssonafd1edb2009-12-11 00:32:37 +0000424
John McCall2e6567a2010-04-22 01:10:34 +0000425 EmitAnyExprToExn(*this, E->getSubExpr(), ExceptionPtr);
Mike Stump75546b82009-12-10 00:06:18 +0000426
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000427 // Now throw the exception.
428 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(getLLVMContext());
Anders Carlssonba840fb2011-01-24 01:59:49 +0000429 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
430 /*ForEH=*/true);
John McCall2e6567a2010-04-22 01:10:34 +0000431
432 // The address of the destructor. If the exception type has a
433 // trivial destructor (or isn't a record), we just pass null.
434 llvm::Constant *Dtor = 0;
435 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
436 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
437 if (!Record->hasTrivialDestructor()) {
Douglas Gregorbac74902010-07-01 14:13:13 +0000438 CXXDestructorDecl *DtorD = Record->getDestructor();
John McCall2e6567a2010-04-22 01:10:34 +0000439 Dtor = CGM.GetAddrOfCXXDestructor(DtorD, Dtor_Complete);
440 Dtor = llvm::ConstantExpr::getBitCast(Dtor, Int8PtrTy);
441 }
442 }
443 if (!Dtor) Dtor = llvm::Constant::getNullValue(Int8PtrTy);
Mike Stump75546b82009-12-10 00:06:18 +0000444
Mike Stump114ab9f2009-12-04 01:51:45 +0000445 if (getInvokeDest()) {
Mike Stump75546b82009-12-10 00:06:18 +0000446 llvm::InvokeInst *ThrowCall =
John McCallbd309292010-07-06 01:34:17 +0000447 Builder.CreateInvoke3(getThrowFn(*this),
448 getUnreachableBlock(), getInvokeDest(),
Mike Stump114ab9f2009-12-04 01:51:45 +0000449 ExceptionPtr, TypeInfo, Dtor);
450 ThrowCall->setDoesNotReturn();
Mike Stump114ab9f2009-12-04 01:51:45 +0000451 } else {
Mike Stump75546b82009-12-10 00:06:18 +0000452 llvm::CallInst *ThrowCall =
Mike Stump114ab9f2009-12-04 01:51:45 +0000453 Builder.CreateCall3(getThrowFn(*this), ExceptionPtr, TypeInfo, Dtor);
454 ThrowCall->setDoesNotReturn();
John McCallbd309292010-07-06 01:34:17 +0000455 Builder.CreateUnreachable();
Mike Stump114ab9f2009-12-04 01:51:45 +0000456 }
Mike Stump75546b82009-12-10 00:06:18 +0000457
John McCall20f6ab82011-01-12 03:41:02 +0000458 // throw is an expression, and the expression emitters expect us
459 // to leave ourselves at a valid insertion point.
460 EmitBlock(createBasicBlock("throw.cont"));
Anders Carlsson4b08db72009-10-30 01:42:31 +0000461}
Mike Stump58ef18b2009-11-20 23:44:51 +0000462
Mike Stump1d849212009-12-07 23:38:24 +0000463void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
Anders Carlssone96ab552011-02-28 02:27:16 +0000464 if (!CGM.getLangOptions().CXXExceptions)
Anders Carlsson9878f9f2010-02-06 23:59:05 +0000465 return;
466
Mike Stump1d849212009-12-07 23:38:24 +0000467 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
468 if (FD == 0)
469 return;
470 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
471 if (Proto == 0)
472 return;
473
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000474 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
475 if (isNoexceptExceptionSpec(EST)) {
476 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
477 // noexcept functions are simple terminate scopes.
478 EHStack.pushTerminate();
479 }
480 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
481 unsigned NumExceptions = Proto->getNumExceptions();
482 EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
Mike Stump1d849212009-12-07 23:38:24 +0000483
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000484 for (unsigned I = 0; I != NumExceptions; ++I) {
485 QualType Ty = Proto->getExceptionType(I);
486 QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
487 llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType,
488 /*ForEH=*/true);
489 Filter->setFilter(I, EHType);
490 }
Mike Stump1d849212009-12-07 23:38:24 +0000491 }
Mike Stump1d849212009-12-07 23:38:24 +0000492}
493
494void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
Anders Carlssone96ab552011-02-28 02:27:16 +0000495 if (!CGM.getLangOptions().CXXExceptions)
Anders Carlsson9878f9f2010-02-06 23:59:05 +0000496 return;
497
Mike Stump1d849212009-12-07 23:38:24 +0000498 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
499 if (FD == 0)
500 return;
501 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
502 if (Proto == 0)
503 return;
504
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000505 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
506 if (isNoexceptExceptionSpec(EST)) {
507 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
508 EHStack.popTerminate();
509 }
510 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
511 EHStack.popFilter();
512 }
Mike Stump1d849212009-12-07 23:38:24 +0000513}
514
Mike Stump58ef18b2009-11-20 23:44:51 +0000515void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
John McCallb609d3f2010-07-07 06:56:46 +0000516 EnterCXXTryStmt(S);
John McCallb81884d2010-02-19 09:25:03 +0000517 EmitStmt(S.getTryBlock());
John McCallb609d3f2010-07-07 06:56:46 +0000518 ExitCXXTryStmt(S);
John McCallb81884d2010-02-19 09:25:03 +0000519}
520
John McCallb609d3f2010-07-07 06:56:46 +0000521void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallbd309292010-07-06 01:34:17 +0000522 unsigned NumHandlers = S.getNumHandlers();
523 EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
John McCallb81884d2010-02-19 09:25:03 +0000524
John McCallbd309292010-07-06 01:34:17 +0000525 for (unsigned I = 0; I != NumHandlers; ++I) {
526 const CXXCatchStmt *C = S.getHandler(I);
John McCallb81884d2010-02-19 09:25:03 +0000527
John McCallbd309292010-07-06 01:34:17 +0000528 llvm::BasicBlock *Handler = createBasicBlock("catch");
529 if (C->getExceptionDecl()) {
530 // FIXME: Dropping the reference type on the type into makes it
531 // impossible to correctly implement catch-by-reference
532 // semantics for pointers. Unfortunately, this is what all
533 // existing compilers do, and it's not clear that the standard
534 // personality routine is capable of doing this right. See C++ DR 388:
535 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
536 QualType CaughtType = C->getCaughtType();
537 CaughtType = CaughtType.getNonReferenceType().getUnqualifiedType();
John McCall2ca705e2010-07-24 00:37:23 +0000538
539 llvm::Value *TypeInfo = 0;
540 if (CaughtType->isObjCObjectPointerType())
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +0000541 TypeInfo = CGM.getObjCRuntime().GetEHType(CaughtType);
John McCall2ca705e2010-07-24 00:37:23 +0000542 else
Anders Carlssonba840fb2011-01-24 01:59:49 +0000543 TypeInfo = CGM.GetAddrOfRTTIDescriptor(CaughtType, /*ForEH=*/true);
John McCallbd309292010-07-06 01:34:17 +0000544 CatchScope->setHandler(I, TypeInfo, Handler);
545 } else {
546 // No exception decl indicates '...', a catch-all.
547 CatchScope->setCatchAllHandler(I, Handler);
548 }
549 }
John McCallbd309292010-07-06 01:34:17 +0000550}
551
552/// Check whether this is a non-EH scope, i.e. a scope which doesn't
553/// affect exception handling. Currently, the only non-EH scopes are
554/// normal-only cleanup scopes.
555static bool isNonEHScope(const EHScope &S) {
John McCall2b7fc382010-07-13 20:32:21 +0000556 switch (S.getKind()) {
John McCallcda666c2010-07-21 07:22:38 +0000557 case EHScope::Cleanup:
558 return !cast<EHCleanupScope>(S).isEHCleanup();
John McCall2b7fc382010-07-13 20:32:21 +0000559 case EHScope::Filter:
560 case EHScope::Catch:
561 case EHScope::Terminate:
562 return false;
563 }
564
565 // Suppress warning.
566 return false;
John McCallbd309292010-07-06 01:34:17 +0000567}
568
569llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
570 assert(EHStack.requiresLandingPad());
571 assert(!EHStack.empty());
572
Anders Carlsson6dc07d42011-02-28 00:33:03 +0000573 if (!CGM.getLangOptions().Exceptions)
John McCall2b7fc382010-07-13 20:32:21 +0000574 return 0;
575
John McCallbd309292010-07-06 01:34:17 +0000576 // Check the innermost scope for a cached landing pad. If this is
577 // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
578 llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
579 if (LP) return LP;
580
581 // Build the landing pad for this scope.
582 LP = EmitLandingPad();
583 assert(LP);
584
585 // Cache the landing pad on the innermost scope. If this is a
586 // non-EH scope, cache the landing pad on the enclosing scope, too.
587 for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
588 ir->setCachedLandingPad(LP);
589 if (!isNonEHScope(*ir)) break;
590 }
591
592 return LP;
593}
594
John McCall9b382dd2011-05-28 21:13:02 +0000595// This code contains a hack to work around a design flaw in
596// LLVM's EH IR which breaks semantics after inlining. This same
597// hack is implemented in llvm-gcc.
598//
599// The LLVM EH abstraction is basically a thin veneer over the
600// traditional GCC zero-cost design: for each range of instructions
601// in the function, there is (at most) one "landing pad" with an
602// associated chain of EH actions. A language-specific personality
603// function interprets this chain of actions and (1) decides whether
604// or not to resume execution at the landing pad and (2) if so,
605// provides an integer indicating why it's stopping. In LLVM IR,
606// the association of a landing pad with a range of instructions is
607// achieved via an invoke instruction, the chain of actions becomes
608// the arguments to the @llvm.eh.selector call, and the selector
609// call returns the integer indicator. Other than the required
610// presence of two intrinsic function calls in the landing pad,
611// the IR exactly describes the layout of the output code.
612//
613// A principal advantage of this design is that it is completely
614// language-agnostic; in theory, the LLVM optimizers can treat
615// landing pads neutrally, and targets need only know how to lower
616// the intrinsics to have a functioning exceptions system (assuming
617// that platform exceptions follow something approximately like the
618// GCC design). Unfortunately, landing pads cannot be combined in a
619// language-agnostic way: given selectors A and B, there is no way
620// to make a single landing pad which faithfully represents the
621// semantics of propagating an exception first through A, then
622// through B, without knowing how the personality will interpret the
623// (lowered form of the) selectors. This means that inlining has no
624// choice but to crudely chain invokes (i.e., to ignore invokes in
625// the inlined function, but to turn all unwindable calls into
626// invokes), which is only semantically valid if every unwind stops
627// at every landing pad.
628//
629// Therefore, the invoke-inline hack is to guarantee that every
630// landing pad has a catch-all.
631enum CleanupHackLevel_t {
632 /// A level of hack that requires that all landing pads have
633 /// catch-alls.
634 CHL_MandatoryCatchall,
635
636 /// A level of hack that requires that all landing pads handle
637 /// cleanups.
638 CHL_MandatoryCleanup,
639
640 /// No hacks at all; ideal IR generation.
641 CHL_Ideal
642};
643const CleanupHackLevel_t CleanupHackLevel = CHL_MandatoryCleanup;
644
John McCallbd309292010-07-06 01:34:17 +0000645llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
646 assert(EHStack.requiresLandingPad());
647
John McCallbd309292010-07-06 01:34:17 +0000648 for (EHScopeStack::iterator ir = EHStack.begin(); ; ) {
649 assert(ir != EHStack.end() &&
650 "stack requiring landing pad is nothing but non-EH scopes?");
651
652 // If this is a terminate scope, just use the singleton terminate
653 // landing pad.
654 if (isa<EHTerminateScope>(*ir))
655 return getTerminateLandingPad();
656
657 // If this isn't an EH scope, iterate; otherwise break out.
658 if (!isNonEHScope(*ir)) break;
659 ++ir;
660
661 // We haven't checked this scope for a cached landing pad yet.
662 if (llvm::BasicBlock *LP = ir->getCachedLandingPad())
663 return LP;
664 }
665
666 // Save the current IR generation state.
667 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
668
John McCallad7c5c12011-02-08 08:22:06 +0000669 const EHPersonality &Personality = EHPersonality::get(getLangOptions());
John McCall36ea3722010-07-17 00:43:08 +0000670
John McCallbd309292010-07-06 01:34:17 +0000671 // Create and configure the landing pad.
672 llvm::BasicBlock *LP = createBasicBlock("lpad");
673 EmitBlock(LP);
674
675 // Save the exception pointer. It's safe to use a single exception
676 // pointer per function because EH cleanups can never have nested
677 // try/catches.
678 llvm::CallInst *Exn =
679 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_exception), "exn");
680 Exn->setDoesNotThrow();
681 Builder.CreateStore(Exn, getExceptionSlot());
682
683 // Build the selector arguments.
684 llvm::SmallVector<llvm::Value*, 8> EHSelector;
685 EHSelector.push_back(Exn);
John McCall0bdb1fd2010-09-16 06:16:50 +0000686 EHSelector.push_back(getOpaquePersonalityFn(CGM, Personality));
John McCallbd309292010-07-06 01:34:17 +0000687
688 // Accumulate all the handlers in scope.
John McCallad5d61e2010-07-23 21:56:41 +0000689 llvm::DenseMap<llvm::Value*, UnwindDest> EHHandlers;
690 UnwindDest CatchAll;
John McCallbd309292010-07-06 01:34:17 +0000691 bool HasEHCleanup = false;
692 bool HasEHFilter = false;
693 llvm::SmallVector<llvm::Value*, 8> EHFilters;
694 for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end();
695 I != E; ++I) {
696
697 switch (I->getKind()) {
John McCallcda666c2010-07-21 07:22:38 +0000698 case EHScope::Cleanup:
John McCall2b7fc382010-07-13 20:32:21 +0000699 if (!HasEHCleanup)
John McCallcda666c2010-07-21 07:22:38 +0000700 HasEHCleanup = cast<EHCleanupScope>(*I).isEHCleanup();
John McCall2b7fc382010-07-13 20:32:21 +0000701 // We otherwise don't care about cleanups.
702 continue;
703
John McCallbd309292010-07-06 01:34:17 +0000704 case EHScope::Filter: {
705 assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
John McCallad5d61e2010-07-23 21:56:41 +0000706 assert(!CatchAll.isValid() && "EH filter reached after catch-all");
John McCallbd309292010-07-06 01:34:17 +0000707
Chris Lattner57540c52011-04-15 05:22:18 +0000708 // Filter scopes get added to the selector in weird ways.
John McCallbd309292010-07-06 01:34:17 +0000709 EHFilterScope &Filter = cast<EHFilterScope>(*I);
710 HasEHFilter = true;
711
712 // Add all the filter values which we aren't already explicitly
713 // catching.
714 for (unsigned I = 0, E = Filter.getNumFilters(); I != E; ++I) {
715 llvm::Value *FV = Filter.getFilter(I);
716 if (!EHHandlers.count(FV))
717 EHFilters.push_back(FV);
718 }
719 goto done;
720 }
721
722 case EHScope::Terminate:
723 // Terminate scopes are basically catch-alls.
John McCallad5d61e2010-07-23 21:56:41 +0000724 assert(!CatchAll.isValid());
725 CatchAll = UnwindDest(getTerminateHandler(),
726 EHStack.getEnclosingEHCleanup(I),
727 cast<EHTerminateScope>(*I).getDestIndex());
John McCallbd309292010-07-06 01:34:17 +0000728 goto done;
729
730 case EHScope::Catch:
731 break;
732 }
733
734 EHCatchScope &Catch = cast<EHCatchScope>(*I);
735 for (unsigned HI = 0, HE = Catch.getNumHandlers(); HI != HE; ++HI) {
736 EHCatchScope::Handler Handler = Catch.getHandler(HI);
737
738 // Catch-all. We should only have one of these per catch.
739 if (!Handler.Type) {
John McCallad5d61e2010-07-23 21:56:41 +0000740 assert(!CatchAll.isValid());
741 CatchAll = UnwindDest(Handler.Block,
742 EHStack.getEnclosingEHCleanup(I),
743 Handler.Index);
John McCallbd309292010-07-06 01:34:17 +0000744 continue;
745 }
746
747 // Check whether we already have a handler for this type.
John McCallad5d61e2010-07-23 21:56:41 +0000748 UnwindDest &Dest = EHHandlers[Handler.Type];
749 if (Dest.isValid()) continue;
John McCallbd309292010-07-06 01:34:17 +0000750
751 EHSelector.push_back(Handler.Type);
John McCallad5d61e2010-07-23 21:56:41 +0000752 Dest = UnwindDest(Handler.Block,
753 EHStack.getEnclosingEHCleanup(I),
754 Handler.Index);
John McCallbd309292010-07-06 01:34:17 +0000755 }
756
757 // Stop if we found a catch-all.
John McCallad5d61e2010-07-23 21:56:41 +0000758 if (CatchAll.isValid()) break;
John McCallbd309292010-07-06 01:34:17 +0000759 }
760
761 done:
762 unsigned LastToEmitInLoop = EHSelector.size();
763
764 // If we have a catch-all, add null to the selector.
John McCallad5d61e2010-07-23 21:56:41 +0000765 if (CatchAll.isValid()) {
John McCallad7c5c12011-02-08 08:22:06 +0000766 EHSelector.push_back(getCatchAllValue(*this));
John McCallbd309292010-07-06 01:34:17 +0000767
768 // If we have an EH filter, we need to add those handlers in the
769 // right place in the selector, which is to say, at the end.
770 } else if (HasEHFilter) {
771 // Create a filter expression: an integer constant saying how many
772 // filters there are (+1 to avoid ambiguity with 0 for cleanup),
773 // followed by the filter types. The personality routine only
774 // lands here if the filter doesn't match.
775 EHSelector.push_back(llvm::ConstantInt::get(Builder.getInt32Ty(),
776 EHFilters.size() + 1));
777 EHSelector.append(EHFilters.begin(), EHFilters.end());
778
779 // Also check whether we need a cleanup.
John McCall9b382dd2011-05-28 21:13:02 +0000780 if (CleanupHackLevel == CHL_MandatoryCatchall || HasEHCleanup)
781 EHSelector.push_back(CleanupHackLevel == CHL_MandatoryCatchall
John McCallad7c5c12011-02-08 08:22:06 +0000782 ? getCatchAllValue(*this)
783 : getCleanupValue(*this));
John McCallbd309292010-07-06 01:34:17 +0000784
785 // Otherwise, signal that we at least have cleanups.
John McCall9b382dd2011-05-28 21:13:02 +0000786 } else if (CleanupHackLevel == CHL_MandatoryCatchall || HasEHCleanup) {
787 EHSelector.push_back(CleanupHackLevel == CHL_MandatoryCatchall
John McCallad7c5c12011-02-08 08:22:06 +0000788 ? getCatchAllValue(*this)
789 : getCleanupValue(*this));
John McCall9b382dd2011-05-28 21:13:02 +0000790
791 // At the MandatoryCleanup hack level, we don't need to actually
792 // spuriously tell the unwinder that we have cleanups, but we do
793 // need to always be prepared to handle cleanups.
794 } else if (CleanupHackLevel == CHL_MandatoryCleanup) {
795 // Just don't decrement LastToEmitInLoop.
796
John McCallbd309292010-07-06 01:34:17 +0000797 } else {
798 assert(LastToEmitInLoop > 2);
799 LastToEmitInLoop--;
800 }
801
802 assert(EHSelector.size() >= 3 && "selector call has only two arguments!");
803
804 // Tell the backend how to generate the landing pad.
805 llvm::CallInst *Selection =
806 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_selector),
807 EHSelector.begin(), EHSelector.end(), "eh.selector");
808 Selection->setDoesNotThrow();
John McCall9b382dd2011-05-28 21:13:02 +0000809
810 // Save the selector value in mandatory-cleanup mode.
811 if (CleanupHackLevel == CHL_MandatoryCleanup)
812 Builder.CreateStore(Selection, getEHSelectorSlot());
John McCallbd309292010-07-06 01:34:17 +0000813
814 // Select the right handler.
815 llvm::Value *llvm_eh_typeid_for =
816 CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
817
818 // The results of llvm_eh_typeid_for aren't reliable --- at least
819 // not locally --- so we basically have to do this as an 'if' chain.
820 // We walk through the first N-1 catch clauses, testing and chaining,
821 // and then fall into the final clause (which is either a cleanup, a
822 // filter (possibly with a cleanup), a catch-all, or another catch).
823 for (unsigned I = 2; I != LastToEmitInLoop; ++I) {
824 llvm::Value *Type = EHSelector[I];
John McCallad5d61e2010-07-23 21:56:41 +0000825 UnwindDest Dest = EHHandlers[Type];
826 assert(Dest.isValid() && "no handler entry for value in selector?");
John McCallbd309292010-07-06 01:34:17 +0000827
828 // Figure out where to branch on a match. As a debug code-size
829 // optimization, if the scope depth matches the innermost cleanup,
830 // we branch directly to the catch handler.
John McCallad5d61e2010-07-23 21:56:41 +0000831 llvm::BasicBlock *Match = Dest.getBlock();
832 bool MatchNeedsCleanup =
833 Dest.getScopeDepth() != EHStack.getInnermostEHCleanup();
John McCallbd309292010-07-06 01:34:17 +0000834 if (MatchNeedsCleanup)
835 Match = createBasicBlock("eh.match");
836
837 llvm::BasicBlock *Next = createBasicBlock("eh.next");
838
839 // Check whether the exception matches.
840 llvm::CallInst *Id
841 = Builder.CreateCall(llvm_eh_typeid_for,
John McCallad7c5c12011-02-08 08:22:06 +0000842 Builder.CreateBitCast(Type, Int8PtrTy));
John McCallbd309292010-07-06 01:34:17 +0000843 Id->setDoesNotThrow();
844 Builder.CreateCondBr(Builder.CreateICmpEQ(Selection, Id),
845 Match, Next);
846
847 // Emit match code if necessary.
848 if (MatchNeedsCleanup) {
849 EmitBlock(Match);
850 EmitBranchThroughEHCleanup(Dest);
851 }
852
853 // Continue to the next match.
854 EmitBlock(Next);
855 }
856
857 // Emit the final case in the selector.
858 // This might be a catch-all....
John McCallad5d61e2010-07-23 21:56:41 +0000859 if (CatchAll.isValid()) {
John McCallbd309292010-07-06 01:34:17 +0000860 assert(isa<llvm::ConstantPointerNull>(EHSelector.back()));
861 EmitBranchThroughEHCleanup(CatchAll);
862
863 // ...or an EH filter...
864 } else if (HasEHFilter) {
865 llvm::Value *SavedSelection = Selection;
866
867 // First, unwind out to the outermost scope if necessary.
868 if (EHStack.hasEHCleanups()) {
869 // The end here might not dominate the beginning, so we might need to
870 // save the selector if we need it.
871 llvm::AllocaInst *SelectorVar = 0;
872 if (HasEHCleanup) {
873 SelectorVar = CreateTempAlloca(Builder.getInt32Ty(), "selector.var");
874 Builder.CreateStore(Selection, SelectorVar);
875 }
876
877 llvm::BasicBlock *CleanupContBB = createBasicBlock("ehspec.cleanup.cont");
John McCallad5d61e2010-07-23 21:56:41 +0000878 EmitBranchThroughEHCleanup(UnwindDest(CleanupContBB, EHStack.stable_end(),
879 EHStack.getNextEHDestIndex()));
John McCallbd309292010-07-06 01:34:17 +0000880 EmitBlock(CleanupContBB);
881
882 if (HasEHCleanup)
883 SavedSelection = Builder.CreateLoad(SelectorVar, "ehspec.saved-selector");
884 }
885
886 // If there was a cleanup, we'll need to actually check whether we
887 // landed here because the filter triggered.
John McCall9b382dd2011-05-28 21:13:02 +0000888 if (CleanupHackLevel != CHL_Ideal || HasEHCleanup) {
John McCallbd309292010-07-06 01:34:17 +0000889 llvm::BasicBlock *UnexpectedBB = createBasicBlock("ehspec.unexpected");
890
John McCall9b382dd2011-05-28 21:13:02 +0000891 llvm::Constant *Zero = llvm::ConstantInt::get(Int32Ty, 0);
John McCallbd309292010-07-06 01:34:17 +0000892 llvm::Value *FailsFilter =
893 Builder.CreateICmpSLT(SavedSelection, Zero, "ehspec.fails");
John McCall9b382dd2011-05-28 21:13:02 +0000894 Builder.CreateCondBr(FailsFilter, UnexpectedBB, getRethrowDest().getBlock());
John McCallbd309292010-07-06 01:34:17 +0000895
896 EmitBlock(UnexpectedBB);
897 }
898
899 // Call __cxa_call_unexpected. This doesn't need to be an invoke
900 // because __cxa_call_unexpected magically filters exceptions
901 // according to the last landing pad the exception was thrown
902 // into. Seriously.
903 Builder.CreateCall(getUnexpectedFn(*this),
904 Builder.CreateLoad(getExceptionSlot()))
905 ->setDoesNotReturn();
906 Builder.CreateUnreachable();
907
908 // ...or a normal catch handler...
John McCall9b382dd2011-05-28 21:13:02 +0000909 } else if (CleanupHackLevel == CHL_Ideal && !HasEHCleanup) {
John McCallbd309292010-07-06 01:34:17 +0000910 llvm::Value *Type = EHSelector.back();
911 EmitBranchThroughEHCleanup(EHHandlers[Type]);
912
913 // ...or a cleanup.
914 } else {
John McCallad5d61e2010-07-23 21:56:41 +0000915 EmitBranchThroughEHCleanup(getRethrowDest());
John McCallbd309292010-07-06 01:34:17 +0000916 }
917
918 // Restore the old IR generation state.
919 Builder.restoreIP(SavedIP);
920
921 return LP;
922}
923
John McCall5c08ab92010-07-13 22:12:14 +0000924namespace {
925 /// A cleanup to call __cxa_end_catch. In many cases, the caught
926 /// exception type lets us state definitively that the thrown exception
927 /// type does not have a destructor. In particular:
928 /// - Catch-alls tell us nothing, so we have to conservatively
929 /// assume that the thrown exception might have a destructor.
930 /// - Catches by reference behave according to their base types.
931 /// - Catches of non-record types will only trigger for exceptions
932 /// of non-record types, which never have destructors.
933 /// - Catches of record types can trigger for arbitrary subclasses
934 /// of the caught type, so we have to assume the actual thrown
935 /// exception type might have a throwing destructor, even if the
936 /// caught type's destructor is trivial or nothrow.
John McCallcda666c2010-07-21 07:22:38 +0000937 struct CallEndCatch : EHScopeStack::Cleanup {
John McCall5c08ab92010-07-13 22:12:14 +0000938 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
939 bool MightThrow;
940
941 void Emit(CodeGenFunction &CGF, bool IsForEH) {
942 if (!MightThrow) {
943 CGF.Builder.CreateCall(getEndCatchFn(CGF))->setDoesNotThrow();
944 return;
945 }
946
947 CGF.EmitCallOrInvoke(getEndCatchFn(CGF), 0, 0);
948 }
949 };
950}
951
John McCallbd309292010-07-06 01:34:17 +0000952/// Emits a call to __cxa_begin_catch and enters a cleanup to call
953/// __cxa_end_catch.
John McCall5c08ab92010-07-13 22:12:14 +0000954///
955/// \param EndMightThrow - true if __cxa_end_catch might throw
956static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
957 llvm::Value *Exn,
958 bool EndMightThrow) {
John McCallbd309292010-07-06 01:34:17 +0000959 llvm::CallInst *Call = CGF.Builder.CreateCall(getBeginCatchFn(CGF), Exn);
960 Call->setDoesNotThrow();
961
John McCallcda666c2010-07-21 07:22:38 +0000962 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
John McCallbd309292010-07-06 01:34:17 +0000963
964 return Call;
965}
966
967/// A "special initializer" callback for initializing a catch
968/// parameter during catch initialization.
969static void InitCatchParam(CodeGenFunction &CGF,
970 const VarDecl &CatchParam,
971 llvm::Value *ParamAddr) {
972 // Load the exception from where the landing pad saved it.
973 llvm::Value *Exn = CGF.Builder.CreateLoad(CGF.getExceptionSlot(), "exn");
974
975 CanQualType CatchType =
976 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
977 const llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
978
979 // If we're catching by reference, we can just cast the object
980 // pointer to the appropriate pointer.
981 if (isa<ReferenceType>(CatchType)) {
John McCall5add20c2010-07-20 22:17:55 +0000982 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
983 bool EndCatchMightThrow = CaughtType->isRecordType();
John McCall5c08ab92010-07-13 22:12:14 +0000984
John McCallbd309292010-07-06 01:34:17 +0000985 // __cxa_begin_catch returns the adjusted object pointer.
John McCall5c08ab92010-07-13 22:12:14 +0000986 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
John McCall5add20c2010-07-20 22:17:55 +0000987
988 // We have no way to tell the personality function that we're
989 // catching by reference, so if we're catching a pointer,
990 // __cxa_begin_catch will actually return that pointer by value.
991 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
992 QualType PointeeType = PT->getPointeeType();
993
994 // When catching by reference, generally we should just ignore
995 // this by-value pointer and use the exception object instead.
996 if (!PointeeType->isRecordType()) {
997
998 // Exn points to the struct _Unwind_Exception header, which
999 // we have to skip past in order to reach the exception data.
1000 unsigned HeaderSize =
1001 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
1002 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
1003
1004 // However, if we're catching a pointer-to-record type that won't
1005 // work, because the personality function might have adjusted
1006 // the pointer. There's actually no way for us to fully satisfy
1007 // the language/ABI contract here: we can't use Exn because it
1008 // might have the wrong adjustment, but we can't use the by-value
1009 // pointer because it's off by a level of abstraction.
1010 //
1011 // The current solution is to dump the adjusted pointer into an
1012 // alloca, which breaks language semantics (because changing the
1013 // pointer doesn't change the exception) but at least works.
1014 // The better solution would be to filter out non-exact matches
1015 // and rethrow them, but this is tricky because the rethrow
1016 // really needs to be catchable by other sites at this landing
1017 // pad. The best solution is to fix the personality function.
1018 } else {
1019 // Pull the pointer for the reference type off.
1020 const llvm::Type *PtrTy =
1021 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
1022
1023 // Create the temporary and write the adjusted pointer into it.
1024 llvm::Value *ExnPtrTmp = CGF.CreateTempAlloca(PtrTy, "exn.byref.tmp");
1025 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1026 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
1027
1028 // Bind the reference to the temporary.
1029 AdjustedExn = ExnPtrTmp;
1030 }
1031 }
1032
John McCallbd309292010-07-06 01:34:17 +00001033 llvm::Value *ExnCast =
1034 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
1035 CGF.Builder.CreateStore(ExnCast, ParamAddr);
1036 return;
1037 }
1038
1039 // Non-aggregates (plus complexes).
1040 bool IsComplex = false;
1041 if (!CGF.hasAggregateLLVMType(CatchType) ||
1042 (IsComplex = CatchType->isAnyComplexType())) {
John McCall5c08ab92010-07-13 22:12:14 +00001043 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
John McCallbd309292010-07-06 01:34:17 +00001044
1045 // If the catch type is a pointer type, __cxa_begin_catch returns
1046 // the pointer by value.
1047 if (CatchType->hasPointerRepresentation()) {
1048 llvm::Value *CastExn =
1049 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
1050 CGF.Builder.CreateStore(CastExn, ParamAddr);
1051 return;
1052 }
1053
1054 // Otherwise, it returns a pointer into the exception object.
1055
1056 const llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
1057 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1058
1059 if (IsComplex) {
1060 CGF.StoreComplexToAddr(CGF.LoadComplexFromAddr(Cast, /*volatile*/ false),
1061 ParamAddr, /*volatile*/ false);
1062 } else {
Daniel Dunbar03816342010-08-21 02:24:36 +00001063 unsigned Alignment =
1064 CGF.getContext().getDeclAlign(&CatchParam).getQuantity();
John McCallbd309292010-07-06 01:34:17 +00001065 llvm::Value *ExnLoad = CGF.Builder.CreateLoad(Cast, "exn.scalar");
Daniel Dunbar03816342010-08-21 02:24:36 +00001066 CGF.EmitStoreOfScalar(ExnLoad, ParamAddr, /*volatile*/ false, Alignment,
1067 CatchType);
John McCallbd309292010-07-06 01:34:17 +00001068 }
1069 return;
1070 }
1071
John McCallb5011ab2011-02-16 08:39:19 +00001072 assert(isa<RecordType>(CatchType) && "unexpected catch type!");
John McCallbd309292010-07-06 01:34:17 +00001073
1074 const llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
1075
John McCallb5011ab2011-02-16 08:39:19 +00001076 // Check for a copy expression. If we don't have a copy expression,
1077 // that means a trivial copy is okay.
John McCall1bf58462011-02-16 08:02:54 +00001078 const Expr *copyExpr = CatchParam.getInit();
1079 if (!copyExpr) {
John McCallb5011ab2011-02-16 08:39:19 +00001080 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
1081 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
1082 CGF.EmitAggregateCopy(ParamAddr, adjustedExn, CatchType);
John McCallbd309292010-07-06 01:34:17 +00001083 return;
1084 }
1085
1086 // We have to call __cxa_get_exception_ptr to get the adjusted
1087 // pointer before copying.
John McCall1bf58462011-02-16 08:02:54 +00001088 llvm::CallInst *rawAdjustedExn =
John McCallbd309292010-07-06 01:34:17 +00001089 CGF.Builder.CreateCall(getGetExceptionPtrFn(CGF), Exn);
John McCall1bf58462011-02-16 08:02:54 +00001090 rawAdjustedExn->setDoesNotThrow();
John McCallbd309292010-07-06 01:34:17 +00001091
John McCall1bf58462011-02-16 08:02:54 +00001092 // Cast that to the appropriate type.
1093 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
John McCallbd309292010-07-06 01:34:17 +00001094
John McCall1bf58462011-02-16 08:02:54 +00001095 // The copy expression is defined in terms of an OpaqueValueExpr.
1096 // Find it and map it to the adjusted expression.
1097 CodeGenFunction::OpaqueValueMapping
John McCallc07a0c72011-02-17 10:25:35 +00001098 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
1099 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
John McCallbd309292010-07-06 01:34:17 +00001100
1101 // Call the copy ctor in a terminate scope.
1102 CGF.EHStack.pushTerminate();
John McCall1bf58462011-02-16 08:02:54 +00001103
1104 // Perform the copy construction.
John McCall31168b02011-06-15 23:02:42 +00001105 CGF.EmitAggExpr(copyExpr, AggValueSlot::forAddr(ParamAddr, Qualifiers(),
1106 false));
John McCall1bf58462011-02-16 08:02:54 +00001107
1108 // Leave the terminate scope.
John McCallbd309292010-07-06 01:34:17 +00001109 CGF.EHStack.popTerminate();
1110
John McCall1bf58462011-02-16 08:02:54 +00001111 // Undo the opaque value mapping.
1112 opaque.pop();
1113
John McCallbd309292010-07-06 01:34:17 +00001114 // Finally we can call __cxa_begin_catch.
John McCall5c08ab92010-07-13 22:12:14 +00001115 CallBeginCatch(CGF, Exn, true);
John McCallbd309292010-07-06 01:34:17 +00001116}
1117
1118/// Begins a catch statement by initializing the catch variable and
1119/// calling __cxa_begin_catch.
John McCall1bf58462011-02-16 08:02:54 +00001120static void BeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *S) {
John McCallbd309292010-07-06 01:34:17 +00001121 // We have to be very careful with the ordering of cleanups here:
1122 // C++ [except.throw]p4:
1123 // The destruction [of the exception temporary] occurs
1124 // immediately after the destruction of the object declared in
1125 // the exception-declaration in the handler.
1126 //
1127 // So the precise ordering is:
1128 // 1. Construct catch variable.
1129 // 2. __cxa_begin_catch
1130 // 3. Enter __cxa_end_catch cleanup
1131 // 4. Enter dtor cleanup
1132 //
John McCallc533cb72011-02-22 06:44:22 +00001133 // We do this by using a slightly abnormal initialization process.
1134 // Delegation sequence:
John McCallbd309292010-07-06 01:34:17 +00001135 // - ExitCXXTryStmt opens a RunCleanupsScope
John McCallc533cb72011-02-22 06:44:22 +00001136 // - EmitAutoVarAlloca creates the variable and debug info
John McCallbd309292010-07-06 01:34:17 +00001137 // - InitCatchParam initializes the variable from the exception
John McCallc533cb72011-02-22 06:44:22 +00001138 // - CallBeginCatch calls __cxa_begin_catch
1139 // - CallBeginCatch enters the __cxa_end_catch cleanup
1140 // - EmitAutoVarCleanups enters the variable destructor cleanup
John McCallbd309292010-07-06 01:34:17 +00001141 // - EmitCXXTryStmt emits the code for the catch body
1142 // - EmitCXXTryStmt close the RunCleanupsScope
1143
1144 VarDecl *CatchParam = S->getExceptionDecl();
1145 if (!CatchParam) {
1146 llvm::Value *Exn = CGF.Builder.CreateLoad(CGF.getExceptionSlot(), "exn");
John McCall5c08ab92010-07-13 22:12:14 +00001147 CallBeginCatch(CGF, Exn, true);
John McCallbd309292010-07-06 01:34:17 +00001148 return;
1149 }
1150
1151 // Emit the local.
John McCallc533cb72011-02-22 06:44:22 +00001152 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
1153 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF));
1154 CGF.EmitAutoVarCleanups(var);
John McCallb81884d2010-02-19 09:25:03 +00001155}
1156
John McCall5c0e69e2010-07-13 22:24:23 +00001157namespace {
John McCallcda666c2010-07-21 07:22:38 +00001158 struct CallRethrow : EHScopeStack::Cleanup {
John McCall5c0e69e2010-07-13 22:24:23 +00001159 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1160 CGF.EmitCallOrInvoke(getReThrowFn(CGF), 0, 0);
1161 }
1162 };
1163}
1164
John McCallb609d3f2010-07-07 06:56:46 +00001165void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallbd309292010-07-06 01:34:17 +00001166 unsigned NumHandlers = S.getNumHandlers();
1167 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1168 assert(CatchScope.getNumHandlers() == NumHandlers);
Mike Stump58ef18b2009-11-20 23:44:51 +00001169
John McCallbd309292010-07-06 01:34:17 +00001170 // Copy the handler blocks off before we pop the EH stack. Emitting
1171 // the handlers might scribble on this memory.
1172 llvm::SmallVector<EHCatchScope::Handler, 8> Handlers(NumHandlers);
1173 memcpy(Handlers.data(), CatchScope.begin(),
1174 NumHandlers * sizeof(EHCatchScope::Handler));
1175 EHStack.popCatch();
Mike Stump58ef18b2009-11-20 23:44:51 +00001176
John McCallbd309292010-07-06 01:34:17 +00001177 // The fall-through block.
1178 llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
Mike Stump58ef18b2009-11-20 23:44:51 +00001179
John McCallbd309292010-07-06 01:34:17 +00001180 // We just emitted the body of the try; jump to the continue block.
1181 if (HaveInsertPoint())
1182 Builder.CreateBr(ContBB);
Mike Stump97329152009-12-02 19:53:57 +00001183
John McCallb609d3f2010-07-07 06:56:46 +00001184 // Determine if we need an implicit rethrow for all these catch handlers.
1185 bool ImplicitRethrow = false;
1186 if (IsFnTryBlock)
1187 ImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
1188 isa<CXXConstructorDecl>(CurCodeDecl);
1189
John McCallbd309292010-07-06 01:34:17 +00001190 for (unsigned I = 0; I != NumHandlers; ++I) {
1191 llvm::BasicBlock *CatchBlock = Handlers[I].Block;
1192 EmitBlock(CatchBlock);
Mike Stump75546b82009-12-10 00:06:18 +00001193
John McCallbd309292010-07-06 01:34:17 +00001194 // Catch the exception if this isn't a catch-all.
1195 const CXXCatchStmt *C = S.getHandler(I);
Mike Stump58ef18b2009-11-20 23:44:51 +00001196
John McCallbd309292010-07-06 01:34:17 +00001197 // Enter a cleanup scope, including the catch variable and the
1198 // end-catch.
1199 RunCleanupsScope CatchScope(*this);
Mike Stump58ef18b2009-11-20 23:44:51 +00001200
John McCallbd309292010-07-06 01:34:17 +00001201 // Initialize the catch variable and set up the cleanups.
1202 BeginCatch(*this, C);
1203
John McCallb609d3f2010-07-07 06:56:46 +00001204 // If there's an implicit rethrow, push a normal "cleanup" to call
John McCall5c0e69e2010-07-13 22:24:23 +00001205 // _cxa_rethrow. This needs to happen before __cxa_end_catch is
1206 // called, and so it is pushed after BeginCatch.
1207 if (ImplicitRethrow)
John McCallcda666c2010-07-21 07:22:38 +00001208 EHStack.pushCleanup<CallRethrow>(NormalCleanup);
John McCallb609d3f2010-07-07 06:56:46 +00001209
John McCallbd309292010-07-06 01:34:17 +00001210 // Perform the body of the catch.
1211 EmitStmt(C->getHandlerBlock());
1212
1213 // Fall out through the catch cleanups.
1214 CatchScope.ForceCleanup();
1215
1216 // Branch out of the try.
1217 if (HaveInsertPoint())
1218 Builder.CreateBr(ContBB);
Mike Stump58ef18b2009-11-20 23:44:51 +00001219 }
1220
John McCallbd309292010-07-06 01:34:17 +00001221 EmitBlock(ContBB);
Mike Stump58ef18b2009-11-20 23:44:51 +00001222}
Mike Stumpaff69af2009-12-09 03:35:49 +00001223
John McCall1e670402010-07-21 00:52:03 +00001224namespace {
John McCallcda666c2010-07-21 07:22:38 +00001225 struct CallEndCatchForFinally : EHScopeStack::Cleanup {
John McCall1e670402010-07-21 00:52:03 +00001226 llvm::Value *ForEHVar;
1227 llvm::Value *EndCatchFn;
1228 CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn)
1229 : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
1230
1231 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1232 llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
1233 llvm::BasicBlock *CleanupContBB =
1234 CGF.createBasicBlock("finally.cleanup.cont");
1235
1236 llvm::Value *ShouldEndCatch =
1237 CGF.Builder.CreateLoad(ForEHVar, "finally.endcatch");
1238 CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1239 CGF.EmitBlock(EndCatchBB);
1240 CGF.EmitCallOrInvoke(EndCatchFn, 0, 0); // catch-all, so might throw
1241 CGF.EmitBlock(CleanupContBB);
1242 }
1243 };
John McCall906da4b2010-07-21 05:47:49 +00001244
John McCallcda666c2010-07-21 07:22:38 +00001245 struct PerformFinally : EHScopeStack::Cleanup {
John McCall906da4b2010-07-21 05:47:49 +00001246 const Stmt *Body;
1247 llvm::Value *ForEHVar;
1248 llvm::Value *EndCatchFn;
1249 llvm::Value *RethrowFn;
1250 llvm::Value *SavedExnVar;
1251
1252 PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
1253 llvm::Value *EndCatchFn,
1254 llvm::Value *RethrowFn, llvm::Value *SavedExnVar)
1255 : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1256 RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
1257
1258 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1259 // Enter a cleanup to call the end-catch function if one was provided.
1260 if (EndCatchFn)
John McCallcda666c2010-07-21 07:22:38 +00001261 CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
1262 ForEHVar, EndCatchFn);
John McCall906da4b2010-07-21 05:47:49 +00001263
John McCallcebe0ca2010-08-11 00:16:14 +00001264 // Save the current cleanup destination in case there are
1265 // cleanups in the finally block.
1266 llvm::Value *SavedCleanupDest =
1267 CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
1268 "cleanup.dest.saved");
1269
John McCall906da4b2010-07-21 05:47:49 +00001270 // Emit the finally block.
1271 CGF.EmitStmt(Body);
1272
1273 // If the end of the finally is reachable, check whether this was
1274 // for EH. If so, rethrow.
1275 if (CGF.HaveInsertPoint()) {
1276 llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
1277 llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
1278
1279 llvm::Value *ShouldRethrow =
1280 CGF.Builder.CreateLoad(ForEHVar, "finally.shouldthrow");
1281 CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1282
1283 CGF.EmitBlock(RethrowBB);
1284 if (SavedExnVar) {
1285 llvm::Value *Args[] = { CGF.Builder.CreateLoad(SavedExnVar) };
1286 CGF.EmitCallOrInvoke(RethrowFn, Args, Args+1);
1287 } else {
1288 CGF.EmitCallOrInvoke(RethrowFn, 0, 0);
1289 }
1290 CGF.Builder.CreateUnreachable();
1291
1292 CGF.EmitBlock(ContBB);
John McCallcebe0ca2010-08-11 00:16:14 +00001293
1294 // Restore the cleanup destination.
1295 CGF.Builder.CreateStore(SavedCleanupDest,
1296 CGF.getNormalCleanupDestSlot());
John McCall906da4b2010-07-21 05:47:49 +00001297 }
1298
1299 // Leave the end-catch cleanup. As an optimization, pretend that
1300 // the fallthrough path was inaccessible; we've dynamically proven
1301 // that we're not in the EH case along that path.
1302 if (EndCatchFn) {
1303 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1304 CGF.PopCleanupBlock();
1305 CGF.Builder.restoreIP(SavedIP);
1306 }
1307
1308 // Now make sure we actually have an insertion point or the
1309 // cleanup gods will hate us.
1310 CGF.EnsureInsertPoint();
1311 }
1312 };
John McCall1e670402010-07-21 00:52:03 +00001313}
1314
John McCallbd309292010-07-06 01:34:17 +00001315/// Enters a finally block for an implementation using zero-cost
1316/// exceptions. This is mostly general, but hard-codes some
1317/// language/ABI-specific behavior in the catch-all sections.
John McCall6b0feb72011-06-22 02:32:12 +00001318void CodeGenFunction::FinallyInfo::enter(CodeGenFunction &CGF,
1319 const Stmt *body,
1320 llvm::Constant *beginCatchFn,
1321 llvm::Constant *endCatchFn,
1322 llvm::Constant *rethrowFn) {
1323 assert((beginCatchFn != 0) == (endCatchFn != 0) &&
John McCallbd309292010-07-06 01:34:17 +00001324 "begin/end catch functions not paired");
John McCall6b0feb72011-06-22 02:32:12 +00001325 assert(rethrowFn && "rethrow function is required");
1326
1327 BeginCatchFn = beginCatchFn;
Mike Stumpaff69af2009-12-09 03:35:49 +00001328
John McCallbd309292010-07-06 01:34:17 +00001329 // The rethrow function has one of the following two types:
1330 // void (*)()
1331 // void (*)(void*)
1332 // In the latter case we need to pass it the exception object.
1333 // But we can't use the exception slot because the @finally might
1334 // have a landing pad (which would overwrite the exception slot).
John McCall6b0feb72011-06-22 02:32:12 +00001335 const llvm::FunctionType *rethrowFnTy =
John McCallbd309292010-07-06 01:34:17 +00001336 cast<llvm::FunctionType>(
John McCall6b0feb72011-06-22 02:32:12 +00001337 cast<llvm::PointerType>(rethrowFn->getType())->getElementType());
1338 SavedExnVar = 0;
1339 if (rethrowFnTy->getNumParams())
1340 SavedExnVar = CGF.CreateTempAlloca(CGF.Int8PtrTy, "finally.exn");
Mike Stumpaff69af2009-12-09 03:35:49 +00001341
John McCallbd309292010-07-06 01:34:17 +00001342 // A finally block is a statement which must be executed on any edge
1343 // out of a given scope. Unlike a cleanup, the finally block may
1344 // contain arbitrary control flow leading out of itself. In
1345 // addition, finally blocks should always be executed, even if there
1346 // are no catch handlers higher on the stack. Therefore, we
1347 // surround the protected scope with a combination of a normal
1348 // cleanup (to catch attempts to break out of the block via normal
1349 // control flow) and an EH catch-all (semantically "outside" any try
1350 // statement to which the finally block might have been attached).
1351 // The finally block itself is generated in the context of a cleanup
1352 // which conditionally leaves the catch-all.
John McCall21886962010-04-21 10:05:39 +00001353
John McCallbd309292010-07-06 01:34:17 +00001354 // Jump destination for performing the finally block on an exception
1355 // edge. We'll never actually reach this block, so unreachable is
1356 // fine.
John McCall6b0feb72011-06-22 02:32:12 +00001357 RethrowDest = CGF.getJumpDestInCurrentScope(CGF.getUnreachableBlock());
John McCall21886962010-04-21 10:05:39 +00001358
John McCallbd309292010-07-06 01:34:17 +00001359 // Whether the finally block is being executed for EH purposes.
John McCall6b0feb72011-06-22 02:32:12 +00001360 ForEHVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "finally.for-eh");
1361 CGF.Builder.CreateStore(CGF.Builder.getFalse(), ForEHVar);
Mike Stumpaff69af2009-12-09 03:35:49 +00001362
John McCallbd309292010-07-06 01:34:17 +00001363 // Enter a normal cleanup which will perform the @finally block.
John McCall6b0feb72011-06-22 02:32:12 +00001364 CGF.EHStack.pushCleanup<PerformFinally>(NormalCleanup, body,
1365 ForEHVar, endCatchFn,
1366 rethrowFn, SavedExnVar);
John McCallbd309292010-07-06 01:34:17 +00001367
1368 // Enter a catch-all scope.
John McCall6b0feb72011-06-22 02:32:12 +00001369 llvm::BasicBlock *catchBB = CGF.createBasicBlock("finally.catchall");
1370 EHCatchScope *catchScope = CGF.EHStack.pushCatch(1);
1371 catchScope->setCatchAllHandler(0, catchBB);
John McCallbd309292010-07-06 01:34:17 +00001372}
1373
John McCall6b0feb72011-06-22 02:32:12 +00001374void CodeGenFunction::FinallyInfo::exit(CodeGenFunction &CGF) {
John McCallbd309292010-07-06 01:34:17 +00001375 // Leave the finally catch-all.
John McCall6b0feb72011-06-22 02:32:12 +00001376 EHCatchScope &catchScope = cast<EHCatchScope>(*CGF.EHStack.begin());
1377 llvm::BasicBlock *catchBB = catchScope.getHandler(0).Block;
1378 CGF.EHStack.popCatch();
John McCallbd309292010-07-06 01:34:17 +00001379
John McCall6b0feb72011-06-22 02:32:12 +00001380 // If there are any references to the catch-all block, emit it.
1381 if (catchBB->use_empty()) {
1382 delete catchBB;
1383 } else {
1384 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveAndClearIP();
1385 CGF.EmitBlock(catchBB);
John McCallbd309292010-07-06 01:34:17 +00001386
John McCall6b0feb72011-06-22 02:32:12 +00001387 llvm::Value *exn = 0;
John McCallbd309292010-07-06 01:34:17 +00001388
John McCall6b0feb72011-06-22 02:32:12 +00001389 // If there's a begin-catch function, call it.
1390 if (BeginCatchFn) {
1391 exn = CGF.Builder.CreateLoad(CGF.getExceptionSlot());
1392 CGF.Builder.CreateCall(BeginCatchFn, exn)->setDoesNotThrow();
1393 }
1394
1395 // If we need to remember the exception pointer to rethrow later, do so.
1396 if (SavedExnVar) {
1397 if (!exn) exn = CGF.Builder.CreateLoad(CGF.getExceptionSlot());
1398 CGF.Builder.CreateStore(exn, SavedExnVar);
1399 }
1400
1401 // Tell the cleanups in the finally block that we're do this for EH.
1402 CGF.Builder.CreateStore(CGF.Builder.getTrue(), ForEHVar);
1403
1404 // Thread a jump through the finally cleanup.
1405 CGF.EmitBranchThroughCleanup(RethrowDest);
1406
1407 CGF.Builder.restoreIP(savedIP);
1408 }
1409
1410 // Finally, leave the @finally cleanup.
1411 CGF.PopCleanupBlock();
John McCallbd309292010-07-06 01:34:17 +00001412}
1413
1414llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
1415 if (TerminateLandingPad)
1416 return TerminateLandingPad;
1417
1418 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1419
1420 // This will get inserted at the end of the function.
1421 TerminateLandingPad = createBasicBlock("terminate.lpad");
1422 Builder.SetInsertPoint(TerminateLandingPad);
1423
1424 // Tell the backend that this is a landing pad.
1425 llvm::CallInst *Exn =
1426 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_exception), "exn");
1427 Exn->setDoesNotThrow();
John McCall36ea3722010-07-17 00:43:08 +00001428
1429 const EHPersonality &Personality = EHPersonality::get(CGM.getLangOptions());
John McCallbd309292010-07-06 01:34:17 +00001430
1431 // Tell the backend what the exception table should be:
1432 // nothing but a catch-all.
John McCall0bdb1fd2010-09-16 06:16:50 +00001433 llvm::Value *Args[3] = { Exn, getOpaquePersonalityFn(CGM, Personality),
John McCallbd309292010-07-06 01:34:17 +00001434 getCatchAllValue(*this) };
1435 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_selector),
1436 Args, Args+3, "eh.selector")
1437 ->setDoesNotThrow();
1438
1439 llvm::CallInst *TerminateCall = Builder.CreateCall(getTerminateFn(*this));
1440 TerminateCall->setDoesNotReturn();
1441 TerminateCall->setDoesNotThrow();
John McCallad7c5c12011-02-08 08:22:06 +00001442 Builder.CreateUnreachable();
Mike Stumpaff69af2009-12-09 03:35:49 +00001443
John McCallbd309292010-07-06 01:34:17 +00001444 // Restore the saved insertion state.
1445 Builder.restoreIP(SavedIP);
John McCalldac3ea62010-04-30 00:06:43 +00001446
John McCallbd309292010-07-06 01:34:17 +00001447 return TerminateLandingPad;
Mike Stumpaff69af2009-12-09 03:35:49 +00001448}
Mike Stump2b488872009-12-09 22:59:31 +00001449
1450llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
Mike Stumpf5cbb082009-12-10 00:02:42 +00001451 if (TerminateHandler)
1452 return TerminateHandler;
1453
John McCallbd309292010-07-06 01:34:17 +00001454 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
Mike Stump25b20fc2009-12-09 23:31:35 +00001455
John McCallbd309292010-07-06 01:34:17 +00001456 // Set up the terminate handler. This block is inserted at the very
1457 // end of the function by FinishFunction.
Mike Stumpf5cbb082009-12-10 00:02:42 +00001458 TerminateHandler = createBasicBlock("terminate.handler");
John McCallbd309292010-07-06 01:34:17 +00001459 Builder.SetInsertPoint(TerminateHandler);
1460 llvm::CallInst *TerminateCall = Builder.CreateCall(getTerminateFn(*this));
Mike Stump2b488872009-12-09 22:59:31 +00001461 TerminateCall->setDoesNotReturn();
1462 TerminateCall->setDoesNotThrow();
1463 Builder.CreateUnreachable();
1464
John McCall21886962010-04-21 10:05:39 +00001465 // Restore the saved insertion state.
John McCallbd309292010-07-06 01:34:17 +00001466 Builder.restoreIP(SavedIP);
Mike Stump25b20fc2009-12-09 23:31:35 +00001467
Mike Stump2b488872009-12-09 22:59:31 +00001468 return TerminateHandler;
1469}
John McCallbd309292010-07-06 01:34:17 +00001470
John McCallad5d61e2010-07-23 21:56:41 +00001471CodeGenFunction::UnwindDest CodeGenFunction::getRethrowDest() {
1472 if (RethrowBlock.isValid()) return RethrowBlock;
1473
1474 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1475
1476 // We emit a jump to a notional label at the outermost unwind state.
1477 llvm::BasicBlock *Unwind = createBasicBlock("eh.resume");
1478 Builder.SetInsertPoint(Unwind);
1479
1480 const EHPersonality &Personality = EHPersonality::get(CGM.getLangOptions());
1481
1482 // This can always be a call because we necessarily didn't find
1483 // anything on the EH stack which needs our help.
John McCall0bdb1fd2010-09-16 06:16:50 +00001484 llvm::StringRef RethrowName = Personality.getCatchallRethrowFnName();
John McCall9b382dd2011-05-28 21:13:02 +00001485 if (!RethrowName.empty()) {
1486 Builder.CreateCall(getCatchallRethrowFn(*this, RethrowName),
1487 Builder.CreateLoad(getExceptionSlot()))
1488 ->setDoesNotReturn();
1489 } else {
1490 llvm::Value *Exn = Builder.CreateLoad(getExceptionSlot());
John McCallad5d61e2010-07-23 21:56:41 +00001491
John McCall9b382dd2011-05-28 21:13:02 +00001492 switch (CleanupHackLevel) {
1493 case CHL_MandatoryCatchall:
1494 // In mandatory-catchall mode, we need to use
1495 // _Unwind_Resume_or_Rethrow, or whatever the personality's
1496 // equivalent is.
1497 Builder.CreateCall(getUnwindResumeOrRethrowFn(), Exn)
1498 ->setDoesNotReturn();
1499 break;
1500 case CHL_MandatoryCleanup: {
1501 // In mandatory-cleanup mode, we should use llvm.eh.resume.
1502 llvm::Value *Selector = Builder.CreateLoad(getEHSelectorSlot());
1503 Builder.CreateCall2(CGM.getIntrinsic(llvm::Intrinsic::eh_resume),
1504 Exn, Selector)
1505 ->setDoesNotReturn();
1506 break;
1507 }
1508 case CHL_Ideal:
1509 // In an idealized mode where we don't have to worry about the
1510 // optimizer combining landing pads, we should just use
1511 // _Unwind_Resume (or the personality's equivalent).
1512 Builder.CreateCall(getUnwindResumeFn(), Exn)
1513 ->setDoesNotReturn();
1514 break;
1515 }
1516 }
1517
John McCallad5d61e2010-07-23 21:56:41 +00001518 Builder.CreateUnreachable();
1519
1520 Builder.restoreIP(SavedIP);
1521
1522 RethrowBlock = UnwindDest(Unwind, EHStack.stable_end(), 0);
1523 return RethrowBlock;
1524}
1525