blob: 46d127cf80336852c67570d0172214f3d3daddb7 [file] [log] [blame]
Anders Carlsson756b5c42009-10-30 01:42:31 +00001//===--- CGException.cpp - Emit LLVM Code for C++ exceptions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code dealing with C++ exception related code generation.
11//
12//===----------------------------------------------------------------------===//
13
Mike Stump2bf701e2009-11-20 23:44:51 +000014#include "clang/AST/StmtCXX.h"
15
16#include "llvm/Intrinsics.h"
John McCallb2593832010-09-16 06:16:50 +000017#include "llvm/IntrinsicInst.h"
John McCallf1549f62010-07-06 01:34:17 +000018#include "llvm/Support/CallSite.h"
Mike Stump2bf701e2009-11-20 23:44:51 +000019
John McCall5a180392010-07-24 00:37:23 +000020#include "CGObjCRuntime.h"
Anders Carlsson756b5c42009-10-30 01:42:31 +000021#include "CodeGenFunction.h"
John McCallf1549f62010-07-06 01:34:17 +000022#include "CGException.h"
John McCall36f893c2011-01-28 11:13:47 +000023#include "CGCleanup.h"
John McCall204b0752010-07-20 22:17:55 +000024#include "TargetInfo.h"
John McCallf1549f62010-07-06 01:34:17 +000025
Anders Carlsson756b5c42009-10-30 01:42:31 +000026using namespace clang;
27using namespace CodeGen;
28
Anders Carlssond3379292009-10-30 02:27:02 +000029static llvm::Constant *getAllocateExceptionFn(CodeGenFunction &CGF) {
30 // void *__cxa_allocate_exception(size_t thrown_size);
Mike Stump8755ec32009-12-10 00:06:18 +000031
Chris Lattner2acc6e32011-07-18 04:24:23 +000032 llvm::FunctionType *FTy =
Jay Foadda549e82011-07-29 13:56:53 +000033 llvm::FunctionType::get(CGF.Int8PtrTy, CGF.SizeTy, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +000034
Anders Carlssond3379292009-10-30 02:27:02 +000035 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
36}
37
Mike Stump99533832009-12-02 07:41:41 +000038static llvm::Constant *getFreeExceptionFn(CodeGenFunction &CGF) {
39 // void __cxa_free_exception(void *thrown_exception);
Mike Stump8755ec32009-12-10 00:06:18 +000040
Chris Lattner2acc6e32011-07-18 04:24:23 +000041 llvm::FunctionType *FTy =
Jay Foadda549e82011-07-29 13:56:53 +000042 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +000043
Mike Stump99533832009-12-02 07:41:41 +000044 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_free_exception");
45}
46
Anders Carlssond3379292009-10-30 02:27:02 +000047static llvm::Constant *getThrowFn(CodeGenFunction &CGF) {
Mike Stump8755ec32009-12-10 00:06:18 +000048 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
Mike Stump99533832009-12-02 07:41:41 +000049 // void (*dest) (void *));
Anders Carlssond3379292009-10-30 02:27:02 +000050
John McCall61c16012011-07-10 20:11:30 +000051 llvm::Type *Args[3] = { CGF.Int8PtrTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
Chris Lattner2acc6e32011-07-18 04:24:23 +000052 llvm::FunctionType *FTy =
John McCall61c16012011-07-10 20:11:30 +000053 llvm::FunctionType::get(CGF.VoidTy, Args, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +000054
Anders Carlssond3379292009-10-30 02:27:02 +000055 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
56}
57
Mike Stumpb4eea692009-11-20 00:56:31 +000058static llvm::Constant *getReThrowFn(CodeGenFunction &CGF) {
Mike Stump99533832009-12-02 07:41:41 +000059 // void __cxa_rethrow();
Mike Stumpb4eea692009-11-20 00:56:31 +000060
Chris Lattner2acc6e32011-07-18 04:24:23 +000061 llvm::FunctionType *FTy =
John McCall61c16012011-07-10 20:11:30 +000062 llvm::FunctionType::get(CGF.VoidTy, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +000063
Mike Stumpb4eea692009-11-20 00:56:31 +000064 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
65}
66
John McCallf1549f62010-07-06 01:34:17 +000067static llvm::Constant *getGetExceptionPtrFn(CodeGenFunction &CGF) {
68 // void *__cxa_get_exception_ptr(void*);
John McCallf1549f62010-07-06 01:34:17 +000069
Chris Lattner2acc6e32011-07-18 04:24:23 +000070 llvm::FunctionType *FTy =
Jay Foadda549e82011-07-29 13:56:53 +000071 llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrTy, /*IsVarArgs=*/false);
John McCallf1549f62010-07-06 01:34:17 +000072
73 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
74}
75
Mike Stump2bf701e2009-11-20 23:44:51 +000076static llvm::Constant *getBeginCatchFn(CodeGenFunction &CGF) {
John McCallf1549f62010-07-06 01:34:17 +000077 // void *__cxa_begin_catch(void*);
Mike Stump2bf701e2009-11-20 23:44:51 +000078
Chris Lattner2acc6e32011-07-18 04:24:23 +000079 llvm::FunctionType *FTy =
Jay Foadda549e82011-07-29 13:56:53 +000080 llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +000081
Mike Stump2bf701e2009-11-20 23:44:51 +000082 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
83}
84
85static llvm::Constant *getEndCatchFn(CodeGenFunction &CGF) {
Mike Stump99533832009-12-02 07:41:41 +000086 // void __cxa_end_catch();
Mike Stump2bf701e2009-11-20 23:44:51 +000087
Chris Lattner2acc6e32011-07-18 04:24:23 +000088 llvm::FunctionType *FTy =
John McCall61c16012011-07-10 20:11:30 +000089 llvm::FunctionType::get(CGF.VoidTy, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +000090
Mike Stump2bf701e2009-11-20 23:44:51 +000091 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
92}
93
Mike Stumpcce3d4f2009-12-07 23:38:24 +000094static llvm::Constant *getUnexpectedFn(CodeGenFunction &CGF) {
95 // void __cxa_call_unexepcted(void *thrown_exception);
96
Chris Lattner2acc6e32011-07-18 04:24:23 +000097 llvm::FunctionType *FTy =
Jay Foadda549e82011-07-29 13:56:53 +000098 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +000099
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000100 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_call_unexpected");
101}
102
John McCall93c332a2011-05-28 21:13:02 +0000103llvm::Constant *CodeGenFunction::getUnwindResumeFn() {
Chris Lattner2acc6e32011-07-18 04:24:23 +0000104 llvm::FunctionType *FTy =
Jay Foadda549e82011-07-29 13:56:53 +0000105 llvm::FunctionType::get(VoidTy, Int8PtrTy, /*IsVarArgs=*/false);
John McCall93c332a2011-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 Lattner2acc6e32011-07-18 04:24:23 +0000113 llvm::FunctionType *FTy =
Jay Foadda549e82011-07-29 13:56:53 +0000114 llvm::FunctionType::get(VoidTy, Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +0000115
Douglas Gregor86a3a032010-05-16 01:24:12 +0000116 if (CGM.getLangOptions().SjLjExceptions)
John McCalla5f2de22010-08-11 20:59:53 +0000117 return CGM.CreateRuntimeFunction(FTy, "_Unwind_SjLj_Resume_or_Rethrow");
Douglas Gregor86a3a032010-05-16 01:24:12 +0000118 return CGM.CreateRuntimeFunction(FTy, "_Unwind_Resume_or_Rethrow");
Mike Stump0f590be2009-12-01 03:41:18 +0000119}
120
Mike Stump99533832009-12-02 07:41:41 +0000121static llvm::Constant *getTerminateFn(CodeGenFunction &CGF) {
122 // void __terminate();
123
Chris Lattner2acc6e32011-07-18 04:24:23 +0000124 llvm::FunctionType *FTy =
John McCall61c16012011-07-10 20:11:30 +0000125 llvm::FunctionType::get(CGF.VoidTy, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +0000126
Chris Lattner5f9e2722011-07-23 10:55:15 +0000127 StringRef name;
John McCall256a76e2011-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 Chisnall79a9ad82010-05-17 13:49:20 +0000138}
139
John McCall8262b6a2010-07-17 00:43:08 +0000140static llvm::Constant *getCatchallRethrowFn(CodeGenFunction &CGF,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000141 StringRef Name) {
Chris Lattner2acc6e32011-07-18 04:24:23 +0000142 llvm::FunctionType *FTy =
Jay Foadda549e82011-07-29 13:56:53 +0000143 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, /*IsVarArgs=*/false);
John McCall8262b6a2010-07-17 00:43:08 +0000144
145 return CGF.CGM.CreateRuntimeFunction(FTy, Name);
John McCallf1549f62010-07-06 01:34:17 +0000146}
147
John McCall8262b6a2010-07-17 00:43:08 +0000148const EHPersonality EHPersonality::GNU_C("__gcc_personality_v0");
John McCall44680782010-11-07 02:35:25 +0000149const EHPersonality EHPersonality::GNU_C_SJLJ("__gcc_personality_sj0");
John McCall8262b6a2010-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 Chisnall80558d22011-03-20 21:35:39 +0000155const EHPersonality EHPersonality::GNU_ObjCXX("__gnustep_objcxx_personality_v0");
John McCall8262b6a2010-07-17 00:43:08 +0000156
157static const EHPersonality &getCPersonality(const LangOptions &L) {
John McCall44680782010-11-07 02:35:25 +0000158 if (L.SjLjExceptions)
159 return EHPersonality::GNU_C_SJLJ;
John McCall8262b6a2010-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 McCallf1549f62010-07-06 01:34:17 +0000167 } else {
John McCall8262b6a2010-07-17 00:43:08 +0000168 return EHPersonality::GNU_ObjC;
John McCallf1549f62010-07-06 01:34:17 +0000169 }
170}
171
John McCall8262b6a2010-07-17 00:43:08 +0000172static const EHPersonality &getCXXPersonality(const LangOptions &L) {
173 if (L.SjLjExceptions)
174 return EHPersonality::GNU_CPlusPlus_SJLJ;
John McCallf1549f62010-07-06 01:34:17 +0000175 else
John McCall8262b6a2010-07-17 00:43:08 +0000176 return EHPersonality::GNU_CPlusPlus;
John McCallf1549f62010-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 McCall8262b6a2010-07-17 00:43:08 +0000181static const EHPersonality &getObjCXXPersonality(const LangOptions &L) {
John McCallf1549f62010-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 McCall8262b6a2010-07-17 00:43:08 +0000185 if (L.NeXTRuntime) {
186 if (L.ObjCNonFragileABI)
187 return EHPersonality::NeXT_ObjC;
John McCallf1549f62010-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 McCall8262b6a2010-07-17 00:43:08 +0000192 return getCXXPersonality(L);
Chandler Carruthdcf22ad2010-05-17 20:58:49 +0000193 }
David Chisnall79a9ad82010-05-17 13:49:20 +0000194
John McCall8262b6a2010-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 Chisnall80558d22011-03-20 21:35:39 +0000197 return EHPersonality::GNU_ObjCXX;
John McCallf1549f62010-07-06 01:34:17 +0000198}
199
John McCall8262b6a2010-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 McCallf1549f62010-07-06 01:34:17 +0000207 else
John McCall8262b6a2010-07-17 00:43:08 +0000208 return getCPersonality(L);
209}
John McCallf1549f62010-07-06 01:34:17 +0000210
John McCallb2593832010-09-16 06:16:50 +0000211static llvm::Constant *getPersonalityFn(CodeGenModule &CGM,
John McCall8262b6a2010-07-17 00:43:08 +0000212 const EHPersonality &Personality) {
John McCall8262b6a2010-07-17 00:43:08 +0000213 llvm::Constant *Fn =
John McCallb2593832010-09-16 06:16:50 +0000214 CGM.CreateRuntimeFunction(llvm::FunctionType::get(
215 llvm::Type::getInt32Ty(CGM.getLLVMContext()),
216 true),
217 Personality.getPersonalityFnName());
218 return Fn;
219}
220
221static llvm::Constant *getOpaquePersonalityFn(CodeGenModule &CGM,
222 const EHPersonality &Personality) {
223 llvm::Constant *Fn = getPersonalityFn(CGM, Personality);
John McCalld16c2cf2011-02-08 08:22:06 +0000224 return llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
John McCallb2593832010-09-16 06:16:50 +0000225}
226
227/// Check whether a personality function could reasonably be swapped
228/// for a C++ personality function.
229static bool PersonalityHasOnlyCXXUses(llvm::Constant *Fn) {
230 for (llvm::Constant::use_iterator
231 I = Fn->use_begin(), E = Fn->use_end(); I != E; ++I) {
232 llvm::User *User = *I;
233
234 // Conditionally white-list bitcasts.
235 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(User)) {
236 if (CE->getOpcode() != llvm::Instruction::BitCast) return false;
237 if (!PersonalityHasOnlyCXXUses(CE))
238 return false;
239 continue;
240 }
241
242 // Otherwise, it has to be a selector call.
243 if (!isa<llvm::EHSelectorInst>(User)) return false;
244
245 llvm::EHSelectorInst *Selector = cast<llvm::EHSelectorInst>(User);
246 for (unsigned I = 2, E = Selector->getNumArgOperands(); I != E; ++I) {
247 // Look for something that would've been returned by the ObjC
248 // runtime's GetEHType() method.
249 llvm::GlobalVariable *GV
250 = dyn_cast<llvm::GlobalVariable>(Selector->getArgOperand(I));
251 if (!GV) continue;
252
253 // ObjC EH selector entries are always global variables with
254 // names starting like this.
255 if (GV->getName().startswith("OBJC_EHTYPE"))
256 return false;
257 }
258 }
259
260 return true;
261}
262
263/// Try to use the C++ personality function in ObjC++. Not doing this
264/// can cause some incompatibilities with gcc, which is more
265/// aggressive about only using the ObjC++ personality in a function
266/// when it really needs it.
267void CodeGenModule::SimplifyPersonality() {
268 // For now, this is really a Darwin-specific operation.
Daniel Dunbareab80782011-04-26 19:43:00 +0000269 if (!Context.Target.getTriple().isOSDarwin())
John McCallb2593832010-09-16 06:16:50 +0000270 return;
271
272 // If we're not in ObjC++ -fexceptions, there's nothing to do.
273 if (!Features.CPlusPlus || !Features.ObjC1 || !Features.Exceptions)
274 return;
275
276 const EHPersonality &ObjCXX = EHPersonality::get(Features);
277 const EHPersonality &CXX = getCXXPersonality(Features);
278 if (&ObjCXX == &CXX ||
279 ObjCXX.getPersonalityFnName() == CXX.getPersonalityFnName())
280 return;
281
282 llvm::Function *Fn =
283 getModule().getFunction(ObjCXX.getPersonalityFnName());
284
285 // Nothing to do if it's unused.
286 if (!Fn || Fn->use_empty()) return;
287
288 // Can't do the optimization if it has non-C++ uses.
289 if (!PersonalityHasOnlyCXXUses(Fn)) return;
290
291 // Create the C++ personality function and kill off the old
292 // function.
293 llvm::Constant *CXXFn = getPersonalityFn(*this, CXX);
294
295 // This can happen if the user is screwing with us.
296 if (Fn->getType() != CXXFn->getType()) return;
297
298 Fn->replaceAllUsesWith(CXXFn);
299 Fn->eraseFromParent();
John McCallf1549f62010-07-06 01:34:17 +0000300}
301
302/// Returns the value to inject into a selector to indicate the
303/// presence of a catch-all.
304static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
305 // Possibly we should use @llvm.eh.catch.all.value here.
John McCalld16c2cf2011-02-08 08:22:06 +0000306 return llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
John McCallf1549f62010-07-06 01:34:17 +0000307}
308
309/// Returns the value to inject into a selector to indicate the
310/// presence of a cleanup.
311static llvm::Constant *getCleanupValue(CodeGenFunction &CGF) {
312 return llvm::ConstantInt::get(CGF.Builder.getInt32Ty(), 0);
Mike Stump99533832009-12-02 07:41:41 +0000313}
314
John McCall09faeab2010-07-13 21:17:51 +0000315namespace {
316 /// A cleanup to free the exception object if its initialization
317 /// throws.
John McCallc4a1a842011-07-12 00:15:30 +0000318 struct FreeException : EHScopeStack::Cleanup {
319 llvm::Value *exn;
320 FreeException(llvm::Value *exn) : exn(exn) {}
John McCallad346f42011-07-12 20:27:29 +0000321 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall3ad32c82011-01-28 08:37:24 +0000322 CGF.Builder.CreateCall(getFreeExceptionFn(CGF), exn)
John McCall09faeab2010-07-13 21:17:51 +0000323 ->setDoesNotThrow();
John McCall09faeab2010-07-13 21:17:51 +0000324 }
325 };
326}
327
John McCallac418162010-04-22 01:10:34 +0000328// Emits an exception expression into the given location. This
329// differs from EmitAnyExprToMem only in that, if a final copy-ctor
330// call is required, an exception within that copy ctor causes
331// std::terminate to be invoked.
John McCall3ad32c82011-01-28 08:37:24 +0000332static void EmitAnyExprToExn(CodeGenFunction &CGF, const Expr *e,
333 llvm::Value *addr) {
John McCallf1549f62010-07-06 01:34:17 +0000334 // Make sure the exception object is cleaned up if there's an
335 // exception during initialization.
John McCall3ad32c82011-01-28 08:37:24 +0000336 CGF.pushFullExprCleanup<FreeException>(EHCleanup, addr);
337 EHScopeStack::stable_iterator cleanup = CGF.EHStack.stable_begin();
John McCallac418162010-04-22 01:10:34 +0000338
339 // __cxa_allocate_exception returns a void*; we need to cast this
340 // to the appropriate type for the object.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000341 llvm::Type *ty = CGF.ConvertTypeForMem(e->getType())->getPointerTo();
John McCall3ad32c82011-01-28 08:37:24 +0000342 llvm::Value *typedAddr = CGF.Builder.CreateBitCast(addr, ty);
John McCallac418162010-04-22 01:10:34 +0000343
344 // FIXME: this isn't quite right! If there's a final unelided call
345 // to a copy constructor, then according to [except.terminate]p1 we
346 // must call std::terminate() if that constructor throws, because
347 // technically that copy occurs after the exception expression is
348 // evaluated but before the exception is caught. But the best way
349 // to handle that is to teach EmitAggExpr to do the final copy
350 // differently if it can't be elided.
John McCallf85e1932011-06-15 23:02:42 +0000351 CGF.EmitAnyExprToMem(e, typedAddr, e->getType().getQualifiers(),
352 /*IsInit*/ true);
John McCallac418162010-04-22 01:10:34 +0000353
John McCall3ad32c82011-01-28 08:37:24 +0000354 // Deactivate the cleanup block.
355 CGF.DeactivateCleanupBlock(cleanup);
Mike Stump0f590be2009-12-01 03:41:18 +0000356}
357
John McCallf1549f62010-07-06 01:34:17 +0000358llvm::Value *CodeGenFunction::getExceptionSlot() {
John McCall93c332a2011-05-28 21:13:02 +0000359 if (!ExceptionSlot)
360 ExceptionSlot = CreateTempAlloca(Int8PtrTy, "exn.slot");
John McCallf1549f62010-07-06 01:34:17 +0000361 return ExceptionSlot;
Mike Stump0f590be2009-12-01 03:41:18 +0000362}
363
John McCall93c332a2011-05-28 21:13:02 +0000364llvm::Value *CodeGenFunction::getEHSelectorSlot() {
365 if (!EHSelectorSlot)
366 EHSelectorSlot = CreateTempAlloca(Int32Ty, "ehselector.slot");
367 return EHSelectorSlot;
368}
369
Anders Carlsson756b5c42009-10-30 01:42:31 +0000370void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E) {
Anders Carlssond3379292009-10-30 02:27:02 +0000371 if (!E->getSubExpr()) {
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000372 if (getInvokeDest()) {
John McCallf1549f62010-07-06 01:34:17 +0000373 Builder.CreateInvoke(getReThrowFn(*this),
374 getUnreachableBlock(),
375 getInvokeDest())
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000376 ->setDoesNotReturn();
John McCallf1549f62010-07-06 01:34:17 +0000377 } else {
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000378 Builder.CreateCall(getReThrowFn(*this))->setDoesNotReturn();
John McCallf1549f62010-07-06 01:34:17 +0000379 Builder.CreateUnreachable();
380 }
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000381
John McCallcd5b22e2011-01-12 03:41:02 +0000382 // throw is an expression, and the expression emitters expect us
383 // to leave ourselves at a valid insertion point.
384 EmitBlock(createBasicBlock("throw.cont"));
385
Anders Carlssond3379292009-10-30 02:27:02 +0000386 return;
387 }
Mike Stump8755ec32009-12-10 00:06:18 +0000388
Anders Carlssond3379292009-10-30 02:27:02 +0000389 QualType ThrowType = E->getSubExpr()->getType();
Mike Stump8755ec32009-12-10 00:06:18 +0000390
Anders Carlssond3379292009-10-30 02:27:02 +0000391 // Now allocate the exception object.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000392 llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
John McCall3d3ec1c2010-04-21 10:05:39 +0000393 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
Mike Stump8755ec32009-12-10 00:06:18 +0000394
Anders Carlssond3379292009-10-30 02:27:02 +0000395 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(*this);
John McCallf1549f62010-07-06 01:34:17 +0000396 llvm::CallInst *ExceptionPtr =
Mike Stump8755ec32009-12-10 00:06:18 +0000397 Builder.CreateCall(AllocExceptionFn,
Anders Carlssond3379292009-10-30 02:27:02 +0000398 llvm::ConstantInt::get(SizeTy, TypeSize),
399 "exception");
John McCallf1549f62010-07-06 01:34:17 +0000400 ExceptionPtr->setDoesNotThrow();
Anders Carlsson8370c582009-12-11 00:32:37 +0000401
John McCallac418162010-04-22 01:10:34 +0000402 EmitAnyExprToExn(*this, E->getSubExpr(), ExceptionPtr);
Mike Stump8755ec32009-12-10 00:06:18 +0000403
Anders Carlssond3379292009-10-30 02:27:02 +0000404 // Now throw the exception.
Anders Carlsson82a113a2011-01-24 01:59:49 +0000405 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
406 /*ForEH=*/true);
John McCallac418162010-04-22 01:10:34 +0000407
408 // The address of the destructor. If the exception type has a
409 // trivial destructor (or isn't a record), we just pass null.
410 llvm::Constant *Dtor = 0;
411 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
412 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
413 if (!Record->hasTrivialDestructor()) {
Douglas Gregor1d110e02010-07-01 14:13:13 +0000414 CXXDestructorDecl *DtorD = Record->getDestructor();
John McCallac418162010-04-22 01:10:34 +0000415 Dtor = CGM.GetAddrOfCXXDestructor(DtorD, Dtor_Complete);
416 Dtor = llvm::ConstantExpr::getBitCast(Dtor, Int8PtrTy);
417 }
418 }
419 if (!Dtor) Dtor = llvm::Constant::getNullValue(Int8PtrTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000420
Mike Stump0a3816e2009-12-04 01:51:45 +0000421 if (getInvokeDest()) {
Mike Stump8755ec32009-12-10 00:06:18 +0000422 llvm::InvokeInst *ThrowCall =
John McCallf1549f62010-07-06 01:34:17 +0000423 Builder.CreateInvoke3(getThrowFn(*this),
424 getUnreachableBlock(), getInvokeDest(),
Mike Stump0a3816e2009-12-04 01:51:45 +0000425 ExceptionPtr, TypeInfo, Dtor);
426 ThrowCall->setDoesNotReturn();
Mike Stump0a3816e2009-12-04 01:51:45 +0000427 } else {
Mike Stump8755ec32009-12-10 00:06:18 +0000428 llvm::CallInst *ThrowCall =
Mike Stump0a3816e2009-12-04 01:51:45 +0000429 Builder.CreateCall3(getThrowFn(*this), ExceptionPtr, TypeInfo, Dtor);
430 ThrowCall->setDoesNotReturn();
John McCallf1549f62010-07-06 01:34:17 +0000431 Builder.CreateUnreachable();
Mike Stump0a3816e2009-12-04 01:51:45 +0000432 }
Mike Stump8755ec32009-12-10 00:06:18 +0000433
John McCallcd5b22e2011-01-12 03:41:02 +0000434 // throw is an expression, and the expression emitters expect us
435 // to leave ourselves at a valid insertion point.
436 EmitBlock(createBasicBlock("throw.cont"));
Anders Carlsson756b5c42009-10-30 01:42:31 +0000437}
Mike Stump2bf701e2009-11-20 23:44:51 +0000438
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000439void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
Anders Carlsson15348ae2011-02-28 02:27:16 +0000440 if (!CGM.getLangOptions().CXXExceptions)
Anders Carlssona994ee42010-02-06 23:59:05 +0000441 return;
442
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000443 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
444 if (FD == 0)
445 return;
446 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
447 if (Proto == 0)
448 return;
449
Sebastian Redla968e972011-03-15 18:42:48 +0000450 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
451 if (isNoexceptExceptionSpec(EST)) {
452 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
453 // noexcept functions are simple terminate scopes.
454 EHStack.pushTerminate();
455 }
456 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
457 unsigned NumExceptions = Proto->getNumExceptions();
458 EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000459
Sebastian Redla968e972011-03-15 18:42:48 +0000460 for (unsigned I = 0; I != NumExceptions; ++I) {
461 QualType Ty = Proto->getExceptionType(I);
462 QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
463 llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType,
464 /*ForEH=*/true);
465 Filter->setFilter(I, EHType);
466 }
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000467 }
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000468}
469
470void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
Anders Carlsson15348ae2011-02-28 02:27:16 +0000471 if (!CGM.getLangOptions().CXXExceptions)
Anders Carlssona994ee42010-02-06 23:59:05 +0000472 return;
473
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000474 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
475 if (FD == 0)
476 return;
477 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
478 if (Proto == 0)
479 return;
480
Sebastian Redla968e972011-03-15 18:42:48 +0000481 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
482 if (isNoexceptExceptionSpec(EST)) {
483 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
484 EHStack.popTerminate();
485 }
486 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
487 EHStack.popFilter();
488 }
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000489}
490
Mike Stump2bf701e2009-11-20 23:44:51 +0000491void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
John McCall59a70002010-07-07 06:56:46 +0000492 EnterCXXTryStmt(S);
John McCall9fc6a772010-02-19 09:25:03 +0000493 EmitStmt(S.getTryBlock());
John McCall59a70002010-07-07 06:56:46 +0000494 ExitCXXTryStmt(S);
John McCall9fc6a772010-02-19 09:25:03 +0000495}
496
John McCall59a70002010-07-07 06:56:46 +0000497void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallf1549f62010-07-06 01:34:17 +0000498 unsigned NumHandlers = S.getNumHandlers();
499 EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
John McCall9fc6a772010-02-19 09:25:03 +0000500
John McCallf1549f62010-07-06 01:34:17 +0000501 for (unsigned I = 0; I != NumHandlers; ++I) {
502 const CXXCatchStmt *C = S.getHandler(I);
John McCall9fc6a772010-02-19 09:25:03 +0000503
John McCallf1549f62010-07-06 01:34:17 +0000504 llvm::BasicBlock *Handler = createBasicBlock("catch");
505 if (C->getExceptionDecl()) {
506 // FIXME: Dropping the reference type on the type into makes it
507 // impossible to correctly implement catch-by-reference
508 // semantics for pointers. Unfortunately, this is what all
509 // existing compilers do, and it's not clear that the standard
510 // personality routine is capable of doing this right. See C++ DR 388:
511 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
512 QualType CaughtType = C->getCaughtType();
513 CaughtType = CaughtType.getNonReferenceType().getUnqualifiedType();
John McCall5a180392010-07-24 00:37:23 +0000514
515 llvm::Value *TypeInfo = 0;
516 if (CaughtType->isObjCObjectPointerType())
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +0000517 TypeInfo = CGM.getObjCRuntime().GetEHType(CaughtType);
John McCall5a180392010-07-24 00:37:23 +0000518 else
Anders Carlsson82a113a2011-01-24 01:59:49 +0000519 TypeInfo = CGM.GetAddrOfRTTIDescriptor(CaughtType, /*ForEH=*/true);
John McCallf1549f62010-07-06 01:34:17 +0000520 CatchScope->setHandler(I, TypeInfo, Handler);
521 } else {
522 // No exception decl indicates '...', a catch-all.
523 CatchScope->setCatchAllHandler(I, Handler);
524 }
525 }
John McCallf1549f62010-07-06 01:34:17 +0000526}
527
528/// Check whether this is a non-EH scope, i.e. a scope which doesn't
529/// affect exception handling. Currently, the only non-EH scopes are
530/// normal-only cleanup scopes.
531static bool isNonEHScope(const EHScope &S) {
John McCallda65ea82010-07-13 20:32:21 +0000532 switch (S.getKind()) {
John McCall1f0fca52010-07-21 07:22:38 +0000533 case EHScope::Cleanup:
534 return !cast<EHCleanupScope>(S).isEHCleanup();
John McCallda65ea82010-07-13 20:32:21 +0000535 case EHScope::Filter:
536 case EHScope::Catch:
537 case EHScope::Terminate:
538 return false;
539 }
540
541 // Suppress warning.
542 return false;
John McCallf1549f62010-07-06 01:34:17 +0000543}
544
545llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
546 assert(EHStack.requiresLandingPad());
547 assert(!EHStack.empty());
548
Anders Carlsson7a178512011-02-28 00:33:03 +0000549 if (!CGM.getLangOptions().Exceptions)
John McCallda65ea82010-07-13 20:32:21 +0000550 return 0;
551
John McCallf1549f62010-07-06 01:34:17 +0000552 // Check the innermost scope for a cached landing pad. If this is
553 // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
554 llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
555 if (LP) return LP;
556
557 // Build the landing pad for this scope.
558 LP = EmitLandingPad();
559 assert(LP);
560
561 // Cache the landing pad on the innermost scope. If this is a
562 // non-EH scope, cache the landing pad on the enclosing scope, too.
563 for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
564 ir->setCachedLandingPad(LP);
565 if (!isNonEHScope(*ir)) break;
566 }
567
568 return LP;
569}
570
John McCall93c332a2011-05-28 21:13:02 +0000571// This code contains a hack to work around a design flaw in
572// LLVM's EH IR which breaks semantics after inlining. This same
573// hack is implemented in llvm-gcc.
574//
575// The LLVM EH abstraction is basically a thin veneer over the
576// traditional GCC zero-cost design: for each range of instructions
577// in the function, there is (at most) one "landing pad" with an
578// associated chain of EH actions. A language-specific personality
579// function interprets this chain of actions and (1) decides whether
580// or not to resume execution at the landing pad and (2) if so,
581// provides an integer indicating why it's stopping. In LLVM IR,
582// the association of a landing pad with a range of instructions is
583// achieved via an invoke instruction, the chain of actions becomes
584// the arguments to the @llvm.eh.selector call, and the selector
585// call returns the integer indicator. Other than the required
586// presence of two intrinsic function calls in the landing pad,
587// the IR exactly describes the layout of the output code.
588//
589// A principal advantage of this design is that it is completely
590// language-agnostic; in theory, the LLVM optimizers can treat
591// landing pads neutrally, and targets need only know how to lower
592// the intrinsics to have a functioning exceptions system (assuming
593// that platform exceptions follow something approximately like the
594// GCC design). Unfortunately, landing pads cannot be combined in a
595// language-agnostic way: given selectors A and B, there is no way
596// to make a single landing pad which faithfully represents the
597// semantics of propagating an exception first through A, then
598// through B, without knowing how the personality will interpret the
599// (lowered form of the) selectors. This means that inlining has no
600// choice but to crudely chain invokes (i.e., to ignore invokes in
601// the inlined function, but to turn all unwindable calls into
602// invokes), which is only semantically valid if every unwind stops
603// at every landing pad.
604//
605// Therefore, the invoke-inline hack is to guarantee that every
606// landing pad has a catch-all.
607enum CleanupHackLevel_t {
608 /// A level of hack that requires that all landing pads have
609 /// catch-alls.
610 CHL_MandatoryCatchall,
611
612 /// A level of hack that requires that all landing pads handle
613 /// cleanups.
614 CHL_MandatoryCleanup,
615
616 /// No hacks at all; ideal IR generation.
617 CHL_Ideal
618};
619const CleanupHackLevel_t CleanupHackLevel = CHL_MandatoryCleanup;
620
John McCallf1549f62010-07-06 01:34:17 +0000621llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
622 assert(EHStack.requiresLandingPad());
623
John McCallf1549f62010-07-06 01:34:17 +0000624 for (EHScopeStack::iterator ir = EHStack.begin(); ; ) {
625 assert(ir != EHStack.end() &&
626 "stack requiring landing pad is nothing but non-EH scopes?");
627
628 // If this is a terminate scope, just use the singleton terminate
629 // landing pad.
630 if (isa<EHTerminateScope>(*ir))
631 return getTerminateLandingPad();
632
633 // If this isn't an EH scope, iterate; otherwise break out.
634 if (!isNonEHScope(*ir)) break;
635 ++ir;
636
637 // We haven't checked this scope for a cached landing pad yet.
638 if (llvm::BasicBlock *LP = ir->getCachedLandingPad())
639 return LP;
640 }
641
642 // Save the current IR generation state.
643 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
644
John McCalld16c2cf2011-02-08 08:22:06 +0000645 const EHPersonality &Personality = EHPersonality::get(getLangOptions());
John McCall8262b6a2010-07-17 00:43:08 +0000646
John McCallf1549f62010-07-06 01:34:17 +0000647 // Create and configure the landing pad.
648 llvm::BasicBlock *LP = createBasicBlock("lpad");
649 EmitBlock(LP);
650
651 // Save the exception pointer. It's safe to use a single exception
652 // pointer per function because EH cleanups can never have nested
653 // try/catches.
654 llvm::CallInst *Exn =
655 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_exception), "exn");
656 Exn->setDoesNotThrow();
657 Builder.CreateStore(Exn, getExceptionSlot());
658
659 // Build the selector arguments.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000660 SmallVector<llvm::Value*, 8> EHSelector;
John McCallf1549f62010-07-06 01:34:17 +0000661 EHSelector.push_back(Exn);
John McCallb2593832010-09-16 06:16:50 +0000662 EHSelector.push_back(getOpaquePersonalityFn(CGM, Personality));
John McCallf1549f62010-07-06 01:34:17 +0000663
664 // Accumulate all the handlers in scope.
John McCallff8e1152010-07-23 21:56:41 +0000665 llvm::DenseMap<llvm::Value*, UnwindDest> EHHandlers;
666 UnwindDest CatchAll;
John McCallf1549f62010-07-06 01:34:17 +0000667 bool HasEHCleanup = false;
668 bool HasEHFilter = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000669 SmallVector<llvm::Value*, 8> EHFilters;
John McCallf1549f62010-07-06 01:34:17 +0000670 for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end();
671 I != E; ++I) {
672
673 switch (I->getKind()) {
John McCall1f0fca52010-07-21 07:22:38 +0000674 case EHScope::Cleanup:
John McCallda65ea82010-07-13 20:32:21 +0000675 if (!HasEHCleanup)
John McCall1f0fca52010-07-21 07:22:38 +0000676 HasEHCleanup = cast<EHCleanupScope>(*I).isEHCleanup();
John McCallda65ea82010-07-13 20:32:21 +0000677 // We otherwise don't care about cleanups.
678 continue;
679
John McCallf1549f62010-07-06 01:34:17 +0000680 case EHScope::Filter: {
681 assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
John McCallff8e1152010-07-23 21:56:41 +0000682 assert(!CatchAll.isValid() && "EH filter reached after catch-all");
John McCallf1549f62010-07-06 01:34:17 +0000683
Chris Lattnerfc8f0e12011-04-15 05:22:18 +0000684 // Filter scopes get added to the selector in weird ways.
John McCallf1549f62010-07-06 01:34:17 +0000685 EHFilterScope &Filter = cast<EHFilterScope>(*I);
686 HasEHFilter = true;
687
688 // Add all the filter values which we aren't already explicitly
689 // catching.
690 for (unsigned I = 0, E = Filter.getNumFilters(); I != E; ++I) {
691 llvm::Value *FV = Filter.getFilter(I);
692 if (!EHHandlers.count(FV))
693 EHFilters.push_back(FV);
694 }
695 goto done;
696 }
697
698 case EHScope::Terminate:
699 // Terminate scopes are basically catch-alls.
John McCallff8e1152010-07-23 21:56:41 +0000700 assert(!CatchAll.isValid());
701 CatchAll = UnwindDest(getTerminateHandler(),
702 EHStack.getEnclosingEHCleanup(I),
703 cast<EHTerminateScope>(*I).getDestIndex());
John McCallf1549f62010-07-06 01:34:17 +0000704 goto done;
705
706 case EHScope::Catch:
707 break;
708 }
709
710 EHCatchScope &Catch = cast<EHCatchScope>(*I);
711 for (unsigned HI = 0, HE = Catch.getNumHandlers(); HI != HE; ++HI) {
712 EHCatchScope::Handler Handler = Catch.getHandler(HI);
713
714 // Catch-all. We should only have one of these per catch.
715 if (!Handler.Type) {
John McCallff8e1152010-07-23 21:56:41 +0000716 assert(!CatchAll.isValid());
717 CatchAll = UnwindDest(Handler.Block,
718 EHStack.getEnclosingEHCleanup(I),
719 Handler.Index);
John McCallf1549f62010-07-06 01:34:17 +0000720 continue;
721 }
722
723 // Check whether we already have a handler for this type.
John McCallff8e1152010-07-23 21:56:41 +0000724 UnwindDest &Dest = EHHandlers[Handler.Type];
725 if (Dest.isValid()) continue;
John McCallf1549f62010-07-06 01:34:17 +0000726
727 EHSelector.push_back(Handler.Type);
John McCallff8e1152010-07-23 21:56:41 +0000728 Dest = UnwindDest(Handler.Block,
729 EHStack.getEnclosingEHCleanup(I),
730 Handler.Index);
John McCallf1549f62010-07-06 01:34:17 +0000731 }
732
733 // Stop if we found a catch-all.
John McCallff8e1152010-07-23 21:56:41 +0000734 if (CatchAll.isValid()) break;
John McCallf1549f62010-07-06 01:34:17 +0000735 }
736
737 done:
738 unsigned LastToEmitInLoop = EHSelector.size();
739
740 // If we have a catch-all, add null to the selector.
John McCallff8e1152010-07-23 21:56:41 +0000741 if (CatchAll.isValid()) {
John McCalld16c2cf2011-02-08 08:22:06 +0000742 EHSelector.push_back(getCatchAllValue(*this));
John McCallf1549f62010-07-06 01:34:17 +0000743
744 // If we have an EH filter, we need to add those handlers in the
745 // right place in the selector, which is to say, at the end.
746 } else if (HasEHFilter) {
747 // Create a filter expression: an integer constant saying how many
748 // filters there are (+1 to avoid ambiguity with 0 for cleanup),
749 // followed by the filter types. The personality routine only
750 // lands here if the filter doesn't match.
751 EHSelector.push_back(llvm::ConstantInt::get(Builder.getInt32Ty(),
752 EHFilters.size() + 1));
753 EHSelector.append(EHFilters.begin(), EHFilters.end());
754
755 // Also check whether we need a cleanup.
John McCall93c332a2011-05-28 21:13:02 +0000756 if (CleanupHackLevel == CHL_MandatoryCatchall || HasEHCleanup)
757 EHSelector.push_back(CleanupHackLevel == CHL_MandatoryCatchall
John McCalld16c2cf2011-02-08 08:22:06 +0000758 ? getCatchAllValue(*this)
759 : getCleanupValue(*this));
John McCallf1549f62010-07-06 01:34:17 +0000760
761 // Otherwise, signal that we at least have cleanups.
John McCall93c332a2011-05-28 21:13:02 +0000762 } else if (CleanupHackLevel == CHL_MandatoryCatchall || HasEHCleanup) {
763 EHSelector.push_back(CleanupHackLevel == CHL_MandatoryCatchall
John McCalld16c2cf2011-02-08 08:22:06 +0000764 ? getCatchAllValue(*this)
765 : getCleanupValue(*this));
John McCall93c332a2011-05-28 21:13:02 +0000766
767 // At the MandatoryCleanup hack level, we don't need to actually
768 // spuriously tell the unwinder that we have cleanups, but we do
769 // need to always be prepared to handle cleanups.
770 } else if (CleanupHackLevel == CHL_MandatoryCleanup) {
771 // Just don't decrement LastToEmitInLoop.
772
John McCallf1549f62010-07-06 01:34:17 +0000773 } else {
774 assert(LastToEmitInLoop > 2);
775 LastToEmitInLoop--;
776 }
777
778 assert(EHSelector.size() >= 3 && "selector call has only two arguments!");
779
780 // Tell the backend how to generate the landing pad.
781 llvm::CallInst *Selection =
782 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_selector),
Jay Foad4c7d9f12011-07-15 08:37:34 +0000783 EHSelector, "eh.selector");
John McCallf1549f62010-07-06 01:34:17 +0000784 Selection->setDoesNotThrow();
John McCall93c332a2011-05-28 21:13:02 +0000785
786 // Save the selector value in mandatory-cleanup mode.
787 if (CleanupHackLevel == CHL_MandatoryCleanup)
788 Builder.CreateStore(Selection, getEHSelectorSlot());
John McCallf1549f62010-07-06 01:34:17 +0000789
790 // Select the right handler.
791 llvm::Value *llvm_eh_typeid_for =
792 CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
793
794 // The results of llvm_eh_typeid_for aren't reliable --- at least
795 // not locally --- so we basically have to do this as an 'if' chain.
796 // We walk through the first N-1 catch clauses, testing and chaining,
797 // and then fall into the final clause (which is either a cleanup, a
798 // filter (possibly with a cleanup), a catch-all, or another catch).
799 for (unsigned I = 2; I != LastToEmitInLoop; ++I) {
800 llvm::Value *Type = EHSelector[I];
John McCallff8e1152010-07-23 21:56:41 +0000801 UnwindDest Dest = EHHandlers[Type];
802 assert(Dest.isValid() && "no handler entry for value in selector?");
John McCallf1549f62010-07-06 01:34:17 +0000803
804 // Figure out where to branch on a match. As a debug code-size
805 // optimization, if the scope depth matches the innermost cleanup,
806 // we branch directly to the catch handler.
John McCallff8e1152010-07-23 21:56:41 +0000807 llvm::BasicBlock *Match = Dest.getBlock();
808 bool MatchNeedsCleanup =
809 Dest.getScopeDepth() != EHStack.getInnermostEHCleanup();
John McCallf1549f62010-07-06 01:34:17 +0000810 if (MatchNeedsCleanup)
811 Match = createBasicBlock("eh.match");
812
813 llvm::BasicBlock *Next = createBasicBlock("eh.next");
814
815 // Check whether the exception matches.
816 llvm::CallInst *Id
817 = Builder.CreateCall(llvm_eh_typeid_for,
John McCalld16c2cf2011-02-08 08:22:06 +0000818 Builder.CreateBitCast(Type, Int8PtrTy));
John McCallf1549f62010-07-06 01:34:17 +0000819 Id->setDoesNotThrow();
820 Builder.CreateCondBr(Builder.CreateICmpEQ(Selection, Id),
821 Match, Next);
822
823 // Emit match code if necessary.
824 if (MatchNeedsCleanup) {
825 EmitBlock(Match);
826 EmitBranchThroughEHCleanup(Dest);
827 }
828
829 // Continue to the next match.
830 EmitBlock(Next);
831 }
832
833 // Emit the final case in the selector.
834 // This might be a catch-all....
John McCallff8e1152010-07-23 21:56:41 +0000835 if (CatchAll.isValid()) {
John McCallf1549f62010-07-06 01:34:17 +0000836 assert(isa<llvm::ConstantPointerNull>(EHSelector.back()));
837 EmitBranchThroughEHCleanup(CatchAll);
838
839 // ...or an EH filter...
840 } else if (HasEHFilter) {
841 llvm::Value *SavedSelection = Selection;
842
843 // First, unwind out to the outermost scope if necessary.
844 if (EHStack.hasEHCleanups()) {
845 // The end here might not dominate the beginning, so we might need to
846 // save the selector if we need it.
847 llvm::AllocaInst *SelectorVar = 0;
848 if (HasEHCleanup) {
849 SelectorVar = CreateTempAlloca(Builder.getInt32Ty(), "selector.var");
850 Builder.CreateStore(Selection, SelectorVar);
851 }
852
853 llvm::BasicBlock *CleanupContBB = createBasicBlock("ehspec.cleanup.cont");
John McCallff8e1152010-07-23 21:56:41 +0000854 EmitBranchThroughEHCleanup(UnwindDest(CleanupContBB, EHStack.stable_end(),
855 EHStack.getNextEHDestIndex()));
John McCallf1549f62010-07-06 01:34:17 +0000856 EmitBlock(CleanupContBB);
857
858 if (HasEHCleanup)
859 SavedSelection = Builder.CreateLoad(SelectorVar, "ehspec.saved-selector");
860 }
861
862 // If there was a cleanup, we'll need to actually check whether we
863 // landed here because the filter triggered.
John McCall93c332a2011-05-28 21:13:02 +0000864 if (CleanupHackLevel != CHL_Ideal || HasEHCleanup) {
John McCallf1549f62010-07-06 01:34:17 +0000865 llvm::BasicBlock *UnexpectedBB = createBasicBlock("ehspec.unexpected");
866
John McCall93c332a2011-05-28 21:13:02 +0000867 llvm::Constant *Zero = llvm::ConstantInt::get(Int32Ty, 0);
John McCallf1549f62010-07-06 01:34:17 +0000868 llvm::Value *FailsFilter =
869 Builder.CreateICmpSLT(SavedSelection, Zero, "ehspec.fails");
John McCall93c332a2011-05-28 21:13:02 +0000870 Builder.CreateCondBr(FailsFilter, UnexpectedBB, getRethrowDest().getBlock());
John McCallf1549f62010-07-06 01:34:17 +0000871
872 EmitBlock(UnexpectedBB);
873 }
874
875 // Call __cxa_call_unexpected. This doesn't need to be an invoke
876 // because __cxa_call_unexpected magically filters exceptions
877 // according to the last landing pad the exception was thrown
878 // into. Seriously.
879 Builder.CreateCall(getUnexpectedFn(*this),
880 Builder.CreateLoad(getExceptionSlot()))
881 ->setDoesNotReturn();
882 Builder.CreateUnreachable();
883
884 // ...or a normal catch handler...
John McCall93c332a2011-05-28 21:13:02 +0000885 } else if (CleanupHackLevel == CHL_Ideal && !HasEHCleanup) {
John McCallf1549f62010-07-06 01:34:17 +0000886 llvm::Value *Type = EHSelector.back();
887 EmitBranchThroughEHCleanup(EHHandlers[Type]);
888
889 // ...or a cleanup.
890 } else {
John McCallff8e1152010-07-23 21:56:41 +0000891 EmitBranchThroughEHCleanup(getRethrowDest());
John McCallf1549f62010-07-06 01:34:17 +0000892 }
893
894 // Restore the old IR generation state.
895 Builder.restoreIP(SavedIP);
896
897 return LP;
898}
899
John McCall8e3f8612010-07-13 22:12:14 +0000900namespace {
901 /// A cleanup to call __cxa_end_catch. In many cases, the caught
902 /// exception type lets us state definitively that the thrown exception
903 /// type does not have a destructor. In particular:
904 /// - Catch-alls tell us nothing, so we have to conservatively
905 /// assume that the thrown exception might have a destructor.
906 /// - Catches by reference behave according to their base types.
907 /// - Catches of non-record types will only trigger for exceptions
908 /// of non-record types, which never have destructors.
909 /// - Catches of record types can trigger for arbitrary subclasses
910 /// of the caught type, so we have to assume the actual thrown
911 /// exception type might have a throwing destructor, even if the
912 /// caught type's destructor is trivial or nothrow.
John McCall1f0fca52010-07-21 07:22:38 +0000913 struct CallEndCatch : EHScopeStack::Cleanup {
John McCall8e3f8612010-07-13 22:12:14 +0000914 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
915 bool MightThrow;
916
John McCallad346f42011-07-12 20:27:29 +0000917 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall8e3f8612010-07-13 22:12:14 +0000918 if (!MightThrow) {
919 CGF.Builder.CreateCall(getEndCatchFn(CGF))->setDoesNotThrow();
920 return;
921 }
922
Jay Foad4c7d9f12011-07-15 08:37:34 +0000923 CGF.EmitCallOrInvoke(getEndCatchFn(CGF));
John McCall8e3f8612010-07-13 22:12:14 +0000924 }
925 };
926}
927
John McCallf1549f62010-07-06 01:34:17 +0000928/// Emits a call to __cxa_begin_catch and enters a cleanup to call
929/// __cxa_end_catch.
John McCall8e3f8612010-07-13 22:12:14 +0000930///
931/// \param EndMightThrow - true if __cxa_end_catch might throw
932static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
933 llvm::Value *Exn,
934 bool EndMightThrow) {
John McCallf1549f62010-07-06 01:34:17 +0000935 llvm::CallInst *Call = CGF.Builder.CreateCall(getBeginCatchFn(CGF), Exn);
936 Call->setDoesNotThrow();
937
John McCall1f0fca52010-07-21 07:22:38 +0000938 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
John McCallf1549f62010-07-06 01:34:17 +0000939
940 return Call;
941}
942
943/// A "special initializer" callback for initializing a catch
944/// parameter during catch initialization.
945static void InitCatchParam(CodeGenFunction &CGF,
946 const VarDecl &CatchParam,
947 llvm::Value *ParamAddr) {
948 // Load the exception from where the landing pad saved it.
949 llvm::Value *Exn = CGF.Builder.CreateLoad(CGF.getExceptionSlot(), "exn");
950
951 CanQualType CatchType =
952 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
Chris Lattner2acc6e32011-07-18 04:24:23 +0000953 llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
John McCallf1549f62010-07-06 01:34:17 +0000954
955 // If we're catching by reference, we can just cast the object
956 // pointer to the appropriate pointer.
957 if (isa<ReferenceType>(CatchType)) {
John McCall204b0752010-07-20 22:17:55 +0000958 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
959 bool EndCatchMightThrow = CaughtType->isRecordType();
John McCall8e3f8612010-07-13 22:12:14 +0000960
John McCallf1549f62010-07-06 01:34:17 +0000961 // __cxa_begin_catch returns the adjusted object pointer.
John McCall8e3f8612010-07-13 22:12:14 +0000962 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
John McCall204b0752010-07-20 22:17:55 +0000963
964 // We have no way to tell the personality function that we're
965 // catching by reference, so if we're catching a pointer,
966 // __cxa_begin_catch will actually return that pointer by value.
967 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
968 QualType PointeeType = PT->getPointeeType();
969
970 // When catching by reference, generally we should just ignore
971 // this by-value pointer and use the exception object instead.
972 if (!PointeeType->isRecordType()) {
973
974 // Exn points to the struct _Unwind_Exception header, which
975 // we have to skip past in order to reach the exception data.
976 unsigned HeaderSize =
977 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
978 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
979
980 // However, if we're catching a pointer-to-record type that won't
981 // work, because the personality function might have adjusted
982 // the pointer. There's actually no way for us to fully satisfy
983 // the language/ABI contract here: we can't use Exn because it
984 // might have the wrong adjustment, but we can't use the by-value
985 // pointer because it's off by a level of abstraction.
986 //
987 // The current solution is to dump the adjusted pointer into an
988 // alloca, which breaks language semantics (because changing the
989 // pointer doesn't change the exception) but at least works.
990 // The better solution would be to filter out non-exact matches
991 // and rethrow them, but this is tricky because the rethrow
992 // really needs to be catchable by other sites at this landing
993 // pad. The best solution is to fix the personality function.
994 } else {
995 // Pull the pointer for the reference type off.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000996 llvm::Type *PtrTy =
John McCall204b0752010-07-20 22:17:55 +0000997 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
998
999 // Create the temporary and write the adjusted pointer into it.
1000 llvm::Value *ExnPtrTmp = CGF.CreateTempAlloca(PtrTy, "exn.byref.tmp");
1001 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1002 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
1003
1004 // Bind the reference to the temporary.
1005 AdjustedExn = ExnPtrTmp;
1006 }
1007 }
1008
John McCallf1549f62010-07-06 01:34:17 +00001009 llvm::Value *ExnCast =
1010 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
1011 CGF.Builder.CreateStore(ExnCast, ParamAddr);
1012 return;
1013 }
1014
1015 // Non-aggregates (plus complexes).
1016 bool IsComplex = false;
1017 if (!CGF.hasAggregateLLVMType(CatchType) ||
1018 (IsComplex = CatchType->isAnyComplexType())) {
John McCall8e3f8612010-07-13 22:12:14 +00001019 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
John McCallf1549f62010-07-06 01:34:17 +00001020
1021 // If the catch type is a pointer type, __cxa_begin_catch returns
1022 // the pointer by value.
1023 if (CatchType->hasPointerRepresentation()) {
1024 llvm::Value *CastExn =
1025 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
1026 CGF.Builder.CreateStore(CastExn, ParamAddr);
1027 return;
1028 }
1029
1030 // Otherwise, it returns a pointer into the exception object.
1031
Chris Lattner2acc6e32011-07-18 04:24:23 +00001032 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
John McCallf1549f62010-07-06 01:34:17 +00001033 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1034
1035 if (IsComplex) {
1036 CGF.StoreComplexToAddr(CGF.LoadComplexFromAddr(Cast, /*volatile*/ false),
1037 ParamAddr, /*volatile*/ false);
1038 } else {
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001039 unsigned Alignment =
1040 CGF.getContext().getDeclAlign(&CatchParam).getQuantity();
John McCallf1549f62010-07-06 01:34:17 +00001041 llvm::Value *ExnLoad = CGF.Builder.CreateLoad(Cast, "exn.scalar");
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001042 CGF.EmitStoreOfScalar(ExnLoad, ParamAddr, /*volatile*/ false, Alignment,
1043 CatchType);
John McCallf1549f62010-07-06 01:34:17 +00001044 }
1045 return;
1046 }
1047
John McCallacff6962011-02-16 08:39:19 +00001048 assert(isa<RecordType>(CatchType) && "unexpected catch type!");
John McCallf1549f62010-07-06 01:34:17 +00001049
Chris Lattner2acc6e32011-07-18 04:24:23 +00001050 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
John McCallf1549f62010-07-06 01:34:17 +00001051
John McCallacff6962011-02-16 08:39:19 +00001052 // Check for a copy expression. If we don't have a copy expression,
1053 // that means a trivial copy is okay.
John McCalle996ffd2011-02-16 08:02:54 +00001054 const Expr *copyExpr = CatchParam.getInit();
1055 if (!copyExpr) {
John McCallacff6962011-02-16 08:39:19 +00001056 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
1057 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
1058 CGF.EmitAggregateCopy(ParamAddr, adjustedExn, CatchType);
John McCallf1549f62010-07-06 01:34:17 +00001059 return;
1060 }
1061
1062 // We have to call __cxa_get_exception_ptr to get the adjusted
1063 // pointer before copying.
John McCalle996ffd2011-02-16 08:02:54 +00001064 llvm::CallInst *rawAdjustedExn =
John McCallf1549f62010-07-06 01:34:17 +00001065 CGF.Builder.CreateCall(getGetExceptionPtrFn(CGF), Exn);
John McCalle996ffd2011-02-16 08:02:54 +00001066 rawAdjustedExn->setDoesNotThrow();
John McCallf1549f62010-07-06 01:34:17 +00001067
John McCalle996ffd2011-02-16 08:02:54 +00001068 // Cast that to the appropriate type.
1069 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
John McCallf1549f62010-07-06 01:34:17 +00001070
John McCalle996ffd2011-02-16 08:02:54 +00001071 // The copy expression is defined in terms of an OpaqueValueExpr.
1072 // Find it and map it to the adjusted expression.
1073 CodeGenFunction::OpaqueValueMapping
John McCall56ca35d2011-02-17 10:25:35 +00001074 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
1075 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
John McCallf1549f62010-07-06 01:34:17 +00001076
1077 // Call the copy ctor in a terminate scope.
1078 CGF.EHStack.pushTerminate();
John McCalle996ffd2011-02-16 08:02:54 +00001079
1080 // Perform the copy construction.
John McCallf85e1932011-06-15 23:02:42 +00001081 CGF.EmitAggExpr(copyExpr, AggValueSlot::forAddr(ParamAddr, Qualifiers(),
1082 false));
John McCalle996ffd2011-02-16 08:02:54 +00001083
1084 // Leave the terminate scope.
John McCallf1549f62010-07-06 01:34:17 +00001085 CGF.EHStack.popTerminate();
1086
John McCalle996ffd2011-02-16 08:02:54 +00001087 // Undo the opaque value mapping.
1088 opaque.pop();
1089
John McCallf1549f62010-07-06 01:34:17 +00001090 // Finally we can call __cxa_begin_catch.
John McCall8e3f8612010-07-13 22:12:14 +00001091 CallBeginCatch(CGF, Exn, true);
John McCallf1549f62010-07-06 01:34:17 +00001092}
1093
1094/// Begins a catch statement by initializing the catch variable and
1095/// calling __cxa_begin_catch.
John McCalle996ffd2011-02-16 08:02:54 +00001096static void BeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *S) {
John McCallf1549f62010-07-06 01:34:17 +00001097 // We have to be very careful with the ordering of cleanups here:
1098 // C++ [except.throw]p4:
1099 // The destruction [of the exception temporary] occurs
1100 // immediately after the destruction of the object declared in
1101 // the exception-declaration in the handler.
1102 //
1103 // So the precise ordering is:
1104 // 1. Construct catch variable.
1105 // 2. __cxa_begin_catch
1106 // 3. Enter __cxa_end_catch cleanup
1107 // 4. Enter dtor cleanup
1108 //
John McCall34695852011-02-22 06:44:22 +00001109 // We do this by using a slightly abnormal initialization process.
1110 // Delegation sequence:
John McCallf1549f62010-07-06 01:34:17 +00001111 // - ExitCXXTryStmt opens a RunCleanupsScope
John McCall34695852011-02-22 06:44:22 +00001112 // - EmitAutoVarAlloca creates the variable and debug info
John McCallf1549f62010-07-06 01:34:17 +00001113 // - InitCatchParam initializes the variable from the exception
John McCall34695852011-02-22 06:44:22 +00001114 // - CallBeginCatch calls __cxa_begin_catch
1115 // - CallBeginCatch enters the __cxa_end_catch cleanup
1116 // - EmitAutoVarCleanups enters the variable destructor cleanup
John McCallf1549f62010-07-06 01:34:17 +00001117 // - EmitCXXTryStmt emits the code for the catch body
1118 // - EmitCXXTryStmt close the RunCleanupsScope
1119
1120 VarDecl *CatchParam = S->getExceptionDecl();
1121 if (!CatchParam) {
1122 llvm::Value *Exn = CGF.Builder.CreateLoad(CGF.getExceptionSlot(), "exn");
John McCall8e3f8612010-07-13 22:12:14 +00001123 CallBeginCatch(CGF, Exn, true);
John McCallf1549f62010-07-06 01:34:17 +00001124 return;
1125 }
1126
1127 // Emit the local.
John McCall34695852011-02-22 06:44:22 +00001128 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
1129 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF));
1130 CGF.EmitAutoVarCleanups(var);
John McCall9fc6a772010-02-19 09:25:03 +00001131}
1132
John McCallfcd5c0c2010-07-13 22:24:23 +00001133namespace {
John McCall1f0fca52010-07-21 07:22:38 +00001134 struct CallRethrow : EHScopeStack::Cleanup {
John McCallad346f42011-07-12 20:27:29 +00001135 void Emit(CodeGenFunction &CGF, Flags flags) {
Jay Foad4c7d9f12011-07-15 08:37:34 +00001136 CGF.EmitCallOrInvoke(getReThrowFn(CGF));
John McCallfcd5c0c2010-07-13 22:24:23 +00001137 }
1138 };
1139}
1140
John McCall59a70002010-07-07 06:56:46 +00001141void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallf1549f62010-07-06 01:34:17 +00001142 unsigned NumHandlers = S.getNumHandlers();
1143 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1144 assert(CatchScope.getNumHandlers() == NumHandlers);
Mike Stump2bf701e2009-11-20 23:44:51 +00001145
John McCallf1549f62010-07-06 01:34:17 +00001146 // Copy the handler blocks off before we pop the EH stack. Emitting
1147 // the handlers might scribble on this memory.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001148 SmallVector<EHCatchScope::Handler, 8> Handlers(NumHandlers);
John McCallf1549f62010-07-06 01:34:17 +00001149 memcpy(Handlers.data(), CatchScope.begin(),
1150 NumHandlers * sizeof(EHCatchScope::Handler));
1151 EHStack.popCatch();
Mike Stump2bf701e2009-11-20 23:44:51 +00001152
John McCallf1549f62010-07-06 01:34:17 +00001153 // The fall-through block.
1154 llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
Mike Stump2bf701e2009-11-20 23:44:51 +00001155
John McCallf1549f62010-07-06 01:34:17 +00001156 // We just emitted the body of the try; jump to the continue block.
1157 if (HaveInsertPoint())
1158 Builder.CreateBr(ContBB);
Mike Stump639787c2009-12-02 19:53:57 +00001159
John McCall59a70002010-07-07 06:56:46 +00001160 // Determine if we need an implicit rethrow for all these catch handlers.
1161 bool ImplicitRethrow = false;
1162 if (IsFnTryBlock)
1163 ImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
1164 isa<CXXConstructorDecl>(CurCodeDecl);
1165
John McCallf1549f62010-07-06 01:34:17 +00001166 for (unsigned I = 0; I != NumHandlers; ++I) {
1167 llvm::BasicBlock *CatchBlock = Handlers[I].Block;
1168 EmitBlock(CatchBlock);
Mike Stump8755ec32009-12-10 00:06:18 +00001169
John McCallf1549f62010-07-06 01:34:17 +00001170 // Catch the exception if this isn't a catch-all.
1171 const CXXCatchStmt *C = S.getHandler(I);
Mike Stump2bf701e2009-11-20 23:44:51 +00001172
John McCallf1549f62010-07-06 01:34:17 +00001173 // Enter a cleanup scope, including the catch variable and the
1174 // end-catch.
1175 RunCleanupsScope CatchScope(*this);
Mike Stump2bf701e2009-11-20 23:44:51 +00001176
John McCallf1549f62010-07-06 01:34:17 +00001177 // Initialize the catch variable and set up the cleanups.
1178 BeginCatch(*this, C);
1179
John McCall59a70002010-07-07 06:56:46 +00001180 // If there's an implicit rethrow, push a normal "cleanup" to call
John McCallfcd5c0c2010-07-13 22:24:23 +00001181 // _cxa_rethrow. This needs to happen before __cxa_end_catch is
1182 // called, and so it is pushed after BeginCatch.
1183 if (ImplicitRethrow)
John McCall1f0fca52010-07-21 07:22:38 +00001184 EHStack.pushCleanup<CallRethrow>(NormalCleanup);
John McCall59a70002010-07-07 06:56:46 +00001185
John McCallf1549f62010-07-06 01:34:17 +00001186 // Perform the body of the catch.
1187 EmitStmt(C->getHandlerBlock());
1188
1189 // Fall out through the catch cleanups.
1190 CatchScope.ForceCleanup();
1191
1192 // Branch out of the try.
1193 if (HaveInsertPoint())
1194 Builder.CreateBr(ContBB);
Mike Stump2bf701e2009-11-20 23:44:51 +00001195 }
1196
John McCallf1549f62010-07-06 01:34:17 +00001197 EmitBlock(ContBB);
Mike Stump2bf701e2009-11-20 23:44:51 +00001198}
Mike Stumpd88ea562009-12-09 03:35:49 +00001199
John McCall55b20fc2010-07-21 00:52:03 +00001200namespace {
John McCall1f0fca52010-07-21 07:22:38 +00001201 struct CallEndCatchForFinally : EHScopeStack::Cleanup {
John McCall55b20fc2010-07-21 00:52:03 +00001202 llvm::Value *ForEHVar;
1203 llvm::Value *EndCatchFn;
1204 CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn)
1205 : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
1206
John McCallad346f42011-07-12 20:27:29 +00001207 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall55b20fc2010-07-21 00:52:03 +00001208 llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
1209 llvm::BasicBlock *CleanupContBB =
1210 CGF.createBasicBlock("finally.cleanup.cont");
1211
1212 llvm::Value *ShouldEndCatch =
1213 CGF.Builder.CreateLoad(ForEHVar, "finally.endcatch");
1214 CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1215 CGF.EmitBlock(EndCatchBB);
Jay Foad4c7d9f12011-07-15 08:37:34 +00001216 CGF.EmitCallOrInvoke(EndCatchFn); // catch-all, so might throw
John McCall55b20fc2010-07-21 00:52:03 +00001217 CGF.EmitBlock(CleanupContBB);
1218 }
1219 };
John McCall77199712010-07-21 05:47:49 +00001220
John McCall1f0fca52010-07-21 07:22:38 +00001221 struct PerformFinally : EHScopeStack::Cleanup {
John McCall77199712010-07-21 05:47:49 +00001222 const Stmt *Body;
1223 llvm::Value *ForEHVar;
1224 llvm::Value *EndCatchFn;
1225 llvm::Value *RethrowFn;
1226 llvm::Value *SavedExnVar;
1227
1228 PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
1229 llvm::Value *EndCatchFn,
1230 llvm::Value *RethrowFn, llvm::Value *SavedExnVar)
1231 : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1232 RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
1233
John McCallad346f42011-07-12 20:27:29 +00001234 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall77199712010-07-21 05:47:49 +00001235 // Enter a cleanup to call the end-catch function if one was provided.
1236 if (EndCatchFn)
John McCall1f0fca52010-07-21 07:22:38 +00001237 CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
1238 ForEHVar, EndCatchFn);
John McCall77199712010-07-21 05:47:49 +00001239
John McCalld96a8e72010-08-11 00:16:14 +00001240 // Save the current cleanup destination in case there are
1241 // cleanups in the finally block.
1242 llvm::Value *SavedCleanupDest =
1243 CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
1244 "cleanup.dest.saved");
1245
John McCall77199712010-07-21 05:47:49 +00001246 // Emit the finally block.
1247 CGF.EmitStmt(Body);
1248
1249 // If the end of the finally is reachable, check whether this was
1250 // for EH. If so, rethrow.
1251 if (CGF.HaveInsertPoint()) {
1252 llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
1253 llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
1254
1255 llvm::Value *ShouldRethrow =
1256 CGF.Builder.CreateLoad(ForEHVar, "finally.shouldthrow");
1257 CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1258
1259 CGF.EmitBlock(RethrowBB);
1260 if (SavedExnVar) {
Jay Foad4c7d9f12011-07-15 08:37:34 +00001261 CGF.EmitCallOrInvoke(RethrowFn, CGF.Builder.CreateLoad(SavedExnVar));
John McCall77199712010-07-21 05:47:49 +00001262 } else {
Jay Foad4c7d9f12011-07-15 08:37:34 +00001263 CGF.EmitCallOrInvoke(RethrowFn);
John McCall77199712010-07-21 05:47:49 +00001264 }
1265 CGF.Builder.CreateUnreachable();
1266
1267 CGF.EmitBlock(ContBB);
John McCalld96a8e72010-08-11 00:16:14 +00001268
1269 // Restore the cleanup destination.
1270 CGF.Builder.CreateStore(SavedCleanupDest,
1271 CGF.getNormalCleanupDestSlot());
John McCall77199712010-07-21 05:47:49 +00001272 }
1273
1274 // Leave the end-catch cleanup. As an optimization, pretend that
1275 // the fallthrough path was inaccessible; we've dynamically proven
1276 // that we're not in the EH case along that path.
1277 if (EndCatchFn) {
1278 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1279 CGF.PopCleanupBlock();
1280 CGF.Builder.restoreIP(SavedIP);
1281 }
1282
1283 // Now make sure we actually have an insertion point or the
1284 // cleanup gods will hate us.
1285 CGF.EnsureInsertPoint();
1286 }
1287 };
John McCall55b20fc2010-07-21 00:52:03 +00001288}
1289
John McCallf1549f62010-07-06 01:34:17 +00001290/// Enters a finally block for an implementation using zero-cost
1291/// exceptions. This is mostly general, but hard-codes some
1292/// language/ABI-specific behavior in the catch-all sections.
John McCalld768e9d2011-06-22 02:32:12 +00001293void CodeGenFunction::FinallyInfo::enter(CodeGenFunction &CGF,
1294 const Stmt *body,
1295 llvm::Constant *beginCatchFn,
1296 llvm::Constant *endCatchFn,
1297 llvm::Constant *rethrowFn) {
1298 assert((beginCatchFn != 0) == (endCatchFn != 0) &&
John McCallf1549f62010-07-06 01:34:17 +00001299 "begin/end catch functions not paired");
John McCalld768e9d2011-06-22 02:32:12 +00001300 assert(rethrowFn && "rethrow function is required");
1301
1302 BeginCatchFn = beginCatchFn;
Mike Stumpd88ea562009-12-09 03:35:49 +00001303
John McCallf1549f62010-07-06 01:34:17 +00001304 // The rethrow function has one of the following two types:
1305 // void (*)()
1306 // void (*)(void*)
1307 // In the latter case we need to pass it the exception object.
1308 // But we can't use the exception slot because the @finally might
1309 // have a landing pad (which would overwrite the exception slot).
Chris Lattner2acc6e32011-07-18 04:24:23 +00001310 llvm::FunctionType *rethrowFnTy =
John McCallf1549f62010-07-06 01:34:17 +00001311 cast<llvm::FunctionType>(
John McCalld768e9d2011-06-22 02:32:12 +00001312 cast<llvm::PointerType>(rethrowFn->getType())->getElementType());
1313 SavedExnVar = 0;
1314 if (rethrowFnTy->getNumParams())
1315 SavedExnVar = CGF.CreateTempAlloca(CGF.Int8PtrTy, "finally.exn");
Mike Stumpd88ea562009-12-09 03:35:49 +00001316
John McCallf1549f62010-07-06 01:34:17 +00001317 // A finally block is a statement which must be executed on any edge
1318 // out of a given scope. Unlike a cleanup, the finally block may
1319 // contain arbitrary control flow leading out of itself. In
1320 // addition, finally blocks should always be executed, even if there
1321 // are no catch handlers higher on the stack. Therefore, we
1322 // surround the protected scope with a combination of a normal
1323 // cleanup (to catch attempts to break out of the block via normal
1324 // control flow) and an EH catch-all (semantically "outside" any try
1325 // statement to which the finally block might have been attached).
1326 // The finally block itself is generated in the context of a cleanup
1327 // which conditionally leaves the catch-all.
John McCall3d3ec1c2010-04-21 10:05:39 +00001328
John McCallf1549f62010-07-06 01:34:17 +00001329 // Jump destination for performing the finally block on an exception
1330 // edge. We'll never actually reach this block, so unreachable is
1331 // fine.
John McCalld768e9d2011-06-22 02:32:12 +00001332 RethrowDest = CGF.getJumpDestInCurrentScope(CGF.getUnreachableBlock());
John McCall3d3ec1c2010-04-21 10:05:39 +00001333
John McCallf1549f62010-07-06 01:34:17 +00001334 // Whether the finally block is being executed for EH purposes.
John McCalld768e9d2011-06-22 02:32:12 +00001335 ForEHVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "finally.for-eh");
1336 CGF.Builder.CreateStore(CGF.Builder.getFalse(), ForEHVar);
Mike Stumpd88ea562009-12-09 03:35:49 +00001337
John McCallf1549f62010-07-06 01:34:17 +00001338 // Enter a normal cleanup which will perform the @finally block.
John McCalld768e9d2011-06-22 02:32:12 +00001339 CGF.EHStack.pushCleanup<PerformFinally>(NormalCleanup, body,
1340 ForEHVar, endCatchFn,
1341 rethrowFn, SavedExnVar);
John McCallf1549f62010-07-06 01:34:17 +00001342
1343 // Enter a catch-all scope.
John McCalld768e9d2011-06-22 02:32:12 +00001344 llvm::BasicBlock *catchBB = CGF.createBasicBlock("finally.catchall");
1345 EHCatchScope *catchScope = CGF.EHStack.pushCatch(1);
1346 catchScope->setCatchAllHandler(0, catchBB);
John McCallf1549f62010-07-06 01:34:17 +00001347}
1348
John McCalld768e9d2011-06-22 02:32:12 +00001349void CodeGenFunction::FinallyInfo::exit(CodeGenFunction &CGF) {
John McCallf1549f62010-07-06 01:34:17 +00001350 // Leave the finally catch-all.
John McCalld768e9d2011-06-22 02:32:12 +00001351 EHCatchScope &catchScope = cast<EHCatchScope>(*CGF.EHStack.begin());
1352 llvm::BasicBlock *catchBB = catchScope.getHandler(0).Block;
1353 CGF.EHStack.popCatch();
John McCallf1549f62010-07-06 01:34:17 +00001354
John McCalld768e9d2011-06-22 02:32:12 +00001355 // If there are any references to the catch-all block, emit it.
1356 if (catchBB->use_empty()) {
1357 delete catchBB;
1358 } else {
1359 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveAndClearIP();
1360 CGF.EmitBlock(catchBB);
John McCallf1549f62010-07-06 01:34:17 +00001361
John McCalld768e9d2011-06-22 02:32:12 +00001362 llvm::Value *exn = 0;
John McCallf1549f62010-07-06 01:34:17 +00001363
John McCalld768e9d2011-06-22 02:32:12 +00001364 // If there's a begin-catch function, call it.
1365 if (BeginCatchFn) {
1366 exn = CGF.Builder.CreateLoad(CGF.getExceptionSlot());
1367 CGF.Builder.CreateCall(BeginCatchFn, exn)->setDoesNotThrow();
1368 }
1369
1370 // If we need to remember the exception pointer to rethrow later, do so.
1371 if (SavedExnVar) {
1372 if (!exn) exn = CGF.Builder.CreateLoad(CGF.getExceptionSlot());
1373 CGF.Builder.CreateStore(exn, SavedExnVar);
1374 }
1375
1376 // Tell the cleanups in the finally block that we're do this for EH.
1377 CGF.Builder.CreateStore(CGF.Builder.getTrue(), ForEHVar);
1378
1379 // Thread a jump through the finally cleanup.
1380 CGF.EmitBranchThroughCleanup(RethrowDest);
1381
1382 CGF.Builder.restoreIP(savedIP);
1383 }
1384
1385 // Finally, leave the @finally cleanup.
1386 CGF.PopCleanupBlock();
John McCallf1549f62010-07-06 01:34:17 +00001387}
1388
1389llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
1390 if (TerminateLandingPad)
1391 return TerminateLandingPad;
1392
1393 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1394
1395 // This will get inserted at the end of the function.
1396 TerminateLandingPad = createBasicBlock("terminate.lpad");
1397 Builder.SetInsertPoint(TerminateLandingPad);
1398
1399 // Tell the backend that this is a landing pad.
1400 llvm::CallInst *Exn =
1401 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_exception), "exn");
1402 Exn->setDoesNotThrow();
John McCall8262b6a2010-07-17 00:43:08 +00001403
1404 const EHPersonality &Personality = EHPersonality::get(CGM.getLangOptions());
John McCallf1549f62010-07-06 01:34:17 +00001405
1406 // Tell the backend what the exception table should be:
1407 // nothing but a catch-all.
John McCallb2593832010-09-16 06:16:50 +00001408 llvm::Value *Args[3] = { Exn, getOpaquePersonalityFn(CGM, Personality),
John McCallf1549f62010-07-06 01:34:17 +00001409 getCatchAllValue(*this) };
1410 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_selector),
Jay Foad4c7d9f12011-07-15 08:37:34 +00001411 Args, "eh.selector")
John McCallf1549f62010-07-06 01:34:17 +00001412 ->setDoesNotThrow();
1413
1414 llvm::CallInst *TerminateCall = Builder.CreateCall(getTerminateFn(*this));
1415 TerminateCall->setDoesNotReturn();
1416 TerminateCall->setDoesNotThrow();
John McCalld16c2cf2011-02-08 08:22:06 +00001417 Builder.CreateUnreachable();
Mike Stumpd88ea562009-12-09 03:35:49 +00001418
John McCallf1549f62010-07-06 01:34:17 +00001419 // Restore the saved insertion state.
1420 Builder.restoreIP(SavedIP);
John McCall891f80e2010-04-30 00:06:43 +00001421
John McCallf1549f62010-07-06 01:34:17 +00001422 return TerminateLandingPad;
Mike Stumpd88ea562009-12-09 03:35:49 +00001423}
Mike Stump9b39c512009-12-09 22:59:31 +00001424
1425llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
Mike Stump182f3832009-12-10 00:02:42 +00001426 if (TerminateHandler)
1427 return TerminateHandler;
1428
John McCallf1549f62010-07-06 01:34:17 +00001429 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
Mike Stump76958092009-12-09 23:31:35 +00001430
John McCallf1549f62010-07-06 01:34:17 +00001431 // Set up the terminate handler. This block is inserted at the very
1432 // end of the function by FinishFunction.
Mike Stump182f3832009-12-10 00:02:42 +00001433 TerminateHandler = createBasicBlock("terminate.handler");
John McCallf1549f62010-07-06 01:34:17 +00001434 Builder.SetInsertPoint(TerminateHandler);
1435 llvm::CallInst *TerminateCall = Builder.CreateCall(getTerminateFn(*this));
Mike Stump9b39c512009-12-09 22:59:31 +00001436 TerminateCall->setDoesNotReturn();
1437 TerminateCall->setDoesNotThrow();
1438 Builder.CreateUnreachable();
1439
John McCall3d3ec1c2010-04-21 10:05:39 +00001440 // Restore the saved insertion state.
John McCallf1549f62010-07-06 01:34:17 +00001441 Builder.restoreIP(SavedIP);
Mike Stump76958092009-12-09 23:31:35 +00001442
Mike Stump9b39c512009-12-09 22:59:31 +00001443 return TerminateHandler;
1444}
John McCallf1549f62010-07-06 01:34:17 +00001445
John McCallff8e1152010-07-23 21:56:41 +00001446CodeGenFunction::UnwindDest CodeGenFunction::getRethrowDest() {
1447 if (RethrowBlock.isValid()) return RethrowBlock;
1448
1449 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1450
1451 // We emit a jump to a notional label at the outermost unwind state.
1452 llvm::BasicBlock *Unwind = createBasicBlock("eh.resume");
1453 Builder.SetInsertPoint(Unwind);
1454
1455 const EHPersonality &Personality = EHPersonality::get(CGM.getLangOptions());
1456
1457 // This can always be a call because we necessarily didn't find
1458 // anything on the EH stack which needs our help.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001459 StringRef RethrowName = Personality.getCatchallRethrowFnName();
John McCall93c332a2011-05-28 21:13:02 +00001460 if (!RethrowName.empty()) {
1461 Builder.CreateCall(getCatchallRethrowFn(*this, RethrowName),
1462 Builder.CreateLoad(getExceptionSlot()))
1463 ->setDoesNotReturn();
1464 } else {
1465 llvm::Value *Exn = Builder.CreateLoad(getExceptionSlot());
John McCallff8e1152010-07-23 21:56:41 +00001466
John McCall93c332a2011-05-28 21:13:02 +00001467 switch (CleanupHackLevel) {
1468 case CHL_MandatoryCatchall:
1469 // In mandatory-catchall mode, we need to use
1470 // _Unwind_Resume_or_Rethrow, or whatever the personality's
1471 // equivalent is.
1472 Builder.CreateCall(getUnwindResumeOrRethrowFn(), Exn)
1473 ->setDoesNotReturn();
1474 break;
1475 case CHL_MandatoryCleanup: {
1476 // In mandatory-cleanup mode, we should use llvm.eh.resume.
1477 llvm::Value *Selector = Builder.CreateLoad(getEHSelectorSlot());
1478 Builder.CreateCall2(CGM.getIntrinsic(llvm::Intrinsic::eh_resume),
1479 Exn, Selector)
1480 ->setDoesNotReturn();
1481 break;
1482 }
1483 case CHL_Ideal:
1484 // In an idealized mode where we don't have to worry about the
1485 // optimizer combining landing pads, we should just use
1486 // _Unwind_Resume (or the personality's equivalent).
1487 Builder.CreateCall(getUnwindResumeFn(), Exn)
1488 ->setDoesNotReturn();
1489 break;
1490 }
1491 }
1492
John McCallff8e1152010-07-23 21:56:41 +00001493 Builder.CreateUnreachable();
1494
1495 Builder.restoreIP(SavedIP);
1496
1497 RethrowBlock = UnwindDest(Unwind, EHStack.stable_end(), 0);
1498 return RethrowBlock;
1499}
1500