blob: 91be321d315e276989290421b308e323a1c92544 [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
Anders Carlsson2839d6b2011-04-18 14:24:10 +000032 const llvm::Type *SizeTy = CGF.ConvertType(CGF.getContext().getSizeType());
Mike Stump8755ec32009-12-10 00:06:18 +000033 const llvm::FunctionType *FTy =
Anders Carlsson2839d6b2011-04-18 14:24:10 +000034 llvm::FunctionType::get(llvm::Type::getInt8PtrTy(CGF.getLLVMContext()),
35 SizeTy, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +000036
Anders Carlssond3379292009-10-30 02:27:02 +000037 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
38}
39
Mike Stump99533832009-12-02 07:41:41 +000040static llvm::Constant *getFreeExceptionFn(CodeGenFunction &CGF) {
41 // void __cxa_free_exception(void *thrown_exception);
Mike Stump8755ec32009-12-10 00:06:18 +000042
Anders Carlsson2839d6b2011-04-18 14:24:10 +000043 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
Mike Stump8755ec32009-12-10 00:06:18 +000044 const llvm::FunctionType *FTy =
Anders Carlsson2839d6b2011-04-18 14:24:10 +000045 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
46 Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +000047
Mike Stump99533832009-12-02 07:41:41 +000048 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_free_exception");
49}
50
Anders Carlssond3379292009-10-30 02:27:02 +000051static llvm::Constant *getThrowFn(CodeGenFunction &CGF) {
Mike Stump8755ec32009-12-10 00:06:18 +000052 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
Mike Stump99533832009-12-02 07:41:41 +000053 // void (*dest) (void *));
Anders Carlssond3379292009-10-30 02:27:02 +000054
55 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
Anders Carlsson2839d6b2011-04-18 14:24:10 +000056 const llvm::Type *Args[3] = { Int8PtrTy, Int8PtrTy, Int8PtrTy };
Mike Stump8755ec32009-12-10 00:06:18 +000057 const llvm::FunctionType *FTy =
Mike Stumpb4eea692009-11-20 00:56:31 +000058 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
Anders Carlsson2839d6b2011-04-18 14:24:10 +000059 Args, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +000060
Anders Carlssond3379292009-10-30 02:27:02 +000061 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
62}
63
Mike Stumpb4eea692009-11-20 00:56:31 +000064static llvm::Constant *getReThrowFn(CodeGenFunction &CGF) {
Mike Stump99533832009-12-02 07:41:41 +000065 // void __cxa_rethrow();
Mike Stumpb4eea692009-11-20 00:56:31 +000066
Mike Stump8755ec32009-12-10 00:06:18 +000067 const llvm::FunctionType *FTy =
Anders Carlsson2839d6b2011-04-18 14:24:10 +000068 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
69 /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +000070
Mike Stumpb4eea692009-11-20 00:56:31 +000071 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
72}
73
John McCallf1549f62010-07-06 01:34:17 +000074static llvm::Constant *getGetExceptionPtrFn(CodeGenFunction &CGF) {
75 // void *__cxa_get_exception_ptr(void*);
John McCallf1549f62010-07-06 01:34:17 +000076
Anders Carlsson2839d6b2011-04-18 14:24:10 +000077 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
John McCallf1549f62010-07-06 01:34:17 +000078 const llvm::FunctionType *FTy =
Anders Carlsson2839d6b2011-04-18 14:24:10 +000079 llvm::FunctionType::get(Int8PtrTy, Int8PtrTy, /*IsVarArgs=*/false);
John McCallf1549f62010-07-06 01:34:17 +000080
81 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
82}
83
Mike Stump2bf701e2009-11-20 23:44:51 +000084static llvm::Constant *getBeginCatchFn(CodeGenFunction &CGF) {
John McCallf1549f62010-07-06 01:34:17 +000085 // void *__cxa_begin_catch(void*);
Mike Stump2bf701e2009-11-20 23:44:51 +000086
87 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
Mike Stump8755ec32009-12-10 00:06:18 +000088 const llvm::FunctionType *FTy =
Anders Carlsson2839d6b2011-04-18 14:24:10 +000089 llvm::FunctionType::get(Int8PtrTy, Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +000090
Mike Stump2bf701e2009-11-20 23:44:51 +000091 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
92}
93
94static llvm::Constant *getEndCatchFn(CodeGenFunction &CGF) {
Mike Stump99533832009-12-02 07:41:41 +000095 // void __cxa_end_catch();
Mike Stump2bf701e2009-11-20 23:44:51 +000096
Mike Stump8755ec32009-12-10 00:06:18 +000097 const llvm::FunctionType *FTy =
Anders Carlsson2839d6b2011-04-18 14:24:10 +000098 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
99 /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +0000100
Mike Stump2bf701e2009-11-20 23:44:51 +0000101 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
102}
103
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000104static llvm::Constant *getUnexpectedFn(CodeGenFunction &CGF) {
105 // void __cxa_call_unexepcted(void *thrown_exception);
106
107 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
Mike Stump8755ec32009-12-10 00:06:18 +0000108 const llvm::FunctionType *FTy =
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000109 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
Anders Carlsson2839d6b2011-04-18 14:24:10 +0000110 Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +0000111
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000112 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_call_unexpected");
113}
114
John McCall09034212011-05-27 20:01:14 +0000115llvm::Constant *CodeGenFunction::getUnwindResumeFn() {
Mike Stump8755ec32009-12-10 00:06:18 +0000116 const llvm::FunctionType *FTy =
John McCall09034212011-05-27 20:01:14 +0000117 llvm::FunctionType::get(VoidTy, Int8PtrTy, /*IsVarArgs=*/false);
118
119 if (CGM.getLangOptions().SjLjExceptions)
120 return CGM.CreateRuntimeFunction(FTy, "_Unwind_SjLj_Resume");
121 return CGM.CreateRuntimeFunction(FTy, "_Unwind_Resume");
122}
123
124llvm::Constant *CodeGenFunction::getUnwindResumeOrRethrowFn() {
125 const llvm::FunctionType *FTy =
126 llvm::FunctionType::get(VoidTy, Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +0000127
Douglas Gregor86a3a032010-05-16 01:24:12 +0000128 if (CGM.getLangOptions().SjLjExceptions)
John McCalla5f2de22010-08-11 20:59:53 +0000129 return CGM.CreateRuntimeFunction(FTy, "_Unwind_SjLj_Resume_or_Rethrow");
Douglas Gregor86a3a032010-05-16 01:24:12 +0000130 return CGM.CreateRuntimeFunction(FTy, "_Unwind_Resume_or_Rethrow");
Mike Stump0f590be2009-12-01 03:41:18 +0000131}
132
Mike Stump99533832009-12-02 07:41:41 +0000133static llvm::Constant *getTerminateFn(CodeGenFunction &CGF) {
134 // void __terminate();
135
Mike Stump8755ec32009-12-10 00:06:18 +0000136 const llvm::FunctionType *FTy =
Anders Carlsson2839d6b2011-04-18 14:24:10 +0000137 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
138 /*IsVarArgs=*/false);
Mike Stump8755ec32009-12-10 00:06:18 +0000139
David Chisnall79a9ad82010-05-17 13:49:20 +0000140 return CGF.CGM.CreateRuntimeFunction(FTy,
141 CGF.CGM.getLangOptions().CPlusPlus ? "_ZSt9terminatev" : "abort");
142}
143
John McCall8262b6a2010-07-17 00:43:08 +0000144static llvm::Constant *getCatchallRethrowFn(CodeGenFunction &CGF,
John McCallb2593832010-09-16 06:16:50 +0000145 llvm::StringRef Name) {
John McCall8262b6a2010-07-17 00:43:08 +0000146 const llvm::Type *Int8PtrTy =
147 llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
John McCall8262b6a2010-07-17 00:43:08 +0000148 const llvm::Type *VoidTy = llvm::Type::getVoidTy(CGF.getLLVMContext());
Anders Carlsson2839d6b2011-04-18 14:24:10 +0000149 const llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, Int8PtrTy,
150 /*IsVarArgs=*/false);
John McCall8262b6a2010-07-17 00:43:08 +0000151
152 return CGF.CGM.CreateRuntimeFunction(FTy, Name);
John McCallf1549f62010-07-06 01:34:17 +0000153}
154
John McCall8262b6a2010-07-17 00:43:08 +0000155const EHPersonality EHPersonality::GNU_C("__gcc_personality_v0");
John McCall44680782010-11-07 02:35:25 +0000156const EHPersonality EHPersonality::GNU_C_SJLJ("__gcc_personality_sj0");
John McCall8262b6a2010-07-17 00:43:08 +0000157const EHPersonality EHPersonality::NeXT_ObjC("__objc_personality_v0");
158const EHPersonality EHPersonality::GNU_CPlusPlus("__gxx_personality_v0");
159const EHPersonality EHPersonality::GNU_CPlusPlus_SJLJ("__gxx_personality_sj0");
160const EHPersonality EHPersonality::GNU_ObjC("__gnu_objc_personality_v0",
161 "objc_exception_throw");
David Chisnall80558d22011-03-20 21:35:39 +0000162const EHPersonality EHPersonality::GNU_ObjCXX("__gnustep_objcxx_personality_v0");
John McCall8262b6a2010-07-17 00:43:08 +0000163
164static const EHPersonality &getCPersonality(const LangOptions &L) {
John McCall44680782010-11-07 02:35:25 +0000165 if (L.SjLjExceptions)
166 return EHPersonality::GNU_C_SJLJ;
John McCall8262b6a2010-07-17 00:43:08 +0000167 return EHPersonality::GNU_C;
168}
169
170static const EHPersonality &getObjCPersonality(const LangOptions &L) {
171 if (L.NeXTRuntime) {
172 if (L.ObjCNonFragileABI) return EHPersonality::NeXT_ObjC;
173 else return getCPersonality(L);
John McCallf1549f62010-07-06 01:34:17 +0000174 } else {
John McCall8262b6a2010-07-17 00:43:08 +0000175 return EHPersonality::GNU_ObjC;
John McCallf1549f62010-07-06 01:34:17 +0000176 }
177}
178
John McCall8262b6a2010-07-17 00:43:08 +0000179static const EHPersonality &getCXXPersonality(const LangOptions &L) {
180 if (L.SjLjExceptions)
181 return EHPersonality::GNU_CPlusPlus_SJLJ;
John McCallf1549f62010-07-06 01:34:17 +0000182 else
John McCall8262b6a2010-07-17 00:43:08 +0000183 return EHPersonality::GNU_CPlusPlus;
John McCallf1549f62010-07-06 01:34:17 +0000184}
185
186/// Determines the personality function to use when both C++
187/// and Objective-C exceptions are being caught.
John McCall8262b6a2010-07-17 00:43:08 +0000188static const EHPersonality &getObjCXXPersonality(const LangOptions &L) {
John McCallf1549f62010-07-06 01:34:17 +0000189 // The ObjC personality defers to the C++ personality for non-ObjC
190 // handlers. Unlike the C++ case, we use the same personality
191 // function on targets using (backend-driven) SJLJ EH.
John McCall8262b6a2010-07-17 00:43:08 +0000192 if (L.NeXTRuntime) {
193 if (L.ObjCNonFragileABI)
194 return EHPersonality::NeXT_ObjC;
John McCallf1549f62010-07-06 01:34:17 +0000195
196 // In the fragile ABI, just use C++ exception handling and hope
197 // they're not doing crazy exception mixing.
198 else
John McCall8262b6a2010-07-17 00:43:08 +0000199 return getCXXPersonality(L);
Chandler Carruthdcf22ad2010-05-17 20:58:49 +0000200 }
David Chisnall79a9ad82010-05-17 13:49:20 +0000201
John McCall8262b6a2010-07-17 00:43:08 +0000202 // The GNU runtime's personality function inherently doesn't support
203 // mixed EH. Use the C++ personality just to avoid returning null.
David Chisnall80558d22011-03-20 21:35:39 +0000204 return EHPersonality::GNU_ObjCXX;
John McCallf1549f62010-07-06 01:34:17 +0000205}
206
John McCall8262b6a2010-07-17 00:43:08 +0000207const EHPersonality &EHPersonality::get(const LangOptions &L) {
208 if (L.CPlusPlus && L.ObjC1)
209 return getObjCXXPersonality(L);
210 else if (L.CPlusPlus)
211 return getCXXPersonality(L);
212 else if (L.ObjC1)
213 return getObjCPersonality(L);
John McCallf1549f62010-07-06 01:34:17 +0000214 else
John McCall8262b6a2010-07-17 00:43:08 +0000215 return getCPersonality(L);
216}
John McCallf1549f62010-07-06 01:34:17 +0000217
John McCallb2593832010-09-16 06:16:50 +0000218static llvm::Constant *getPersonalityFn(CodeGenModule &CGM,
John McCall8262b6a2010-07-17 00:43:08 +0000219 const EHPersonality &Personality) {
John McCall8262b6a2010-07-17 00:43:08 +0000220 llvm::Constant *Fn =
John McCallb2593832010-09-16 06:16:50 +0000221 CGM.CreateRuntimeFunction(llvm::FunctionType::get(
222 llvm::Type::getInt32Ty(CGM.getLLVMContext()),
223 true),
224 Personality.getPersonalityFnName());
225 return Fn;
226}
227
228static llvm::Constant *getOpaquePersonalityFn(CodeGenModule &CGM,
229 const EHPersonality &Personality) {
230 llvm::Constant *Fn = getPersonalityFn(CGM, Personality);
John McCalld16c2cf2011-02-08 08:22:06 +0000231 return llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
John McCallb2593832010-09-16 06:16:50 +0000232}
233
234/// Check whether a personality function could reasonably be swapped
235/// for a C++ personality function.
236static bool PersonalityHasOnlyCXXUses(llvm::Constant *Fn) {
237 for (llvm::Constant::use_iterator
238 I = Fn->use_begin(), E = Fn->use_end(); I != E; ++I) {
239 llvm::User *User = *I;
240
241 // Conditionally white-list bitcasts.
242 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(User)) {
243 if (CE->getOpcode() != llvm::Instruction::BitCast) return false;
244 if (!PersonalityHasOnlyCXXUses(CE))
245 return false;
246 continue;
247 }
248
249 // Otherwise, it has to be a selector call.
250 if (!isa<llvm::EHSelectorInst>(User)) return false;
251
252 llvm::EHSelectorInst *Selector = cast<llvm::EHSelectorInst>(User);
253 for (unsigned I = 2, E = Selector->getNumArgOperands(); I != E; ++I) {
254 // Look for something that would've been returned by the ObjC
255 // runtime's GetEHType() method.
256 llvm::GlobalVariable *GV
257 = dyn_cast<llvm::GlobalVariable>(Selector->getArgOperand(I));
258 if (!GV) continue;
259
260 // ObjC EH selector entries are always global variables with
261 // names starting like this.
262 if (GV->getName().startswith("OBJC_EHTYPE"))
263 return false;
264 }
265 }
266
267 return true;
268}
269
270/// Try to use the C++ personality function in ObjC++. Not doing this
271/// can cause some incompatibilities with gcc, which is more
272/// aggressive about only using the ObjC++ personality in a function
273/// when it really needs it.
274void CodeGenModule::SimplifyPersonality() {
275 // For now, this is really a Darwin-specific operation.
Daniel Dunbareab80782011-04-26 19:43:00 +0000276 if (!Context.Target.getTriple().isOSDarwin())
John McCallb2593832010-09-16 06:16:50 +0000277 return;
278
279 // If we're not in ObjC++ -fexceptions, there's nothing to do.
280 if (!Features.CPlusPlus || !Features.ObjC1 || !Features.Exceptions)
281 return;
282
283 const EHPersonality &ObjCXX = EHPersonality::get(Features);
284 const EHPersonality &CXX = getCXXPersonality(Features);
285 if (&ObjCXX == &CXX ||
286 ObjCXX.getPersonalityFnName() == CXX.getPersonalityFnName())
287 return;
288
289 llvm::Function *Fn =
290 getModule().getFunction(ObjCXX.getPersonalityFnName());
291
292 // Nothing to do if it's unused.
293 if (!Fn || Fn->use_empty()) return;
294
295 // Can't do the optimization if it has non-C++ uses.
296 if (!PersonalityHasOnlyCXXUses(Fn)) return;
297
298 // Create the C++ personality function and kill off the old
299 // function.
300 llvm::Constant *CXXFn = getPersonalityFn(*this, CXX);
301
302 // This can happen if the user is screwing with us.
303 if (Fn->getType() != CXXFn->getType()) return;
304
305 Fn->replaceAllUsesWith(CXXFn);
306 Fn->eraseFromParent();
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 catch-all.
311static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
312 // Possibly we should use @llvm.eh.catch.all.value here.
John McCalld16c2cf2011-02-08 08:22:06 +0000313 return llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
John McCallf1549f62010-07-06 01:34:17 +0000314}
315
316/// Returns the value to inject into a selector to indicate the
317/// presence of a cleanup.
318static llvm::Constant *getCleanupValue(CodeGenFunction &CGF) {
319 return llvm::ConstantInt::get(CGF.Builder.getInt32Ty(), 0);
Mike Stump99533832009-12-02 07:41:41 +0000320}
321
John McCall09faeab2010-07-13 21:17:51 +0000322namespace {
323 /// A cleanup to free the exception object if its initialization
324 /// throws.
John McCall3ad32c82011-01-28 08:37:24 +0000325 struct FreeException {
326 static void Emit(CodeGenFunction &CGF, bool forEH,
327 llvm::Value *exn) {
328 CGF.Builder.CreateCall(getFreeExceptionFn(CGF), exn)
John McCall09faeab2010-07-13 21:17:51 +0000329 ->setDoesNotThrow();
John McCall09faeab2010-07-13 21:17:51 +0000330 }
331 };
332}
333
John McCallac418162010-04-22 01:10:34 +0000334// Emits an exception expression into the given location. This
335// differs from EmitAnyExprToMem only in that, if a final copy-ctor
336// call is required, an exception within that copy ctor causes
337// std::terminate to be invoked.
John McCall3ad32c82011-01-28 08:37:24 +0000338static void EmitAnyExprToExn(CodeGenFunction &CGF, const Expr *e,
339 llvm::Value *addr) {
John McCallf1549f62010-07-06 01:34:17 +0000340 // Make sure the exception object is cleaned up if there's an
341 // exception during initialization.
John McCall3ad32c82011-01-28 08:37:24 +0000342 CGF.pushFullExprCleanup<FreeException>(EHCleanup, addr);
343 EHScopeStack::stable_iterator cleanup = CGF.EHStack.stable_begin();
John McCallac418162010-04-22 01:10:34 +0000344
345 // __cxa_allocate_exception returns a void*; we need to cast this
346 // to the appropriate type for the object.
John McCall3ad32c82011-01-28 08:37:24 +0000347 const llvm::Type *ty = CGF.ConvertTypeForMem(e->getType())->getPointerTo();
348 llvm::Value *typedAddr = CGF.Builder.CreateBitCast(addr, ty);
John McCallac418162010-04-22 01:10:34 +0000349
350 // FIXME: this isn't quite right! If there's a final unelided call
351 // to a copy constructor, then according to [except.terminate]p1 we
352 // must call std::terminate() if that constructor throws, because
353 // technically that copy occurs after the exception expression is
354 // evaluated but before the exception is caught. But the best way
355 // to handle that is to teach EmitAggExpr to do the final copy
356 // differently if it can't be elided.
John McCall3ad32c82011-01-28 08:37:24 +0000357 CGF.EmitAnyExprToMem(e, typedAddr, /*Volatile*/ false, /*IsInit*/ true);
John McCallac418162010-04-22 01:10:34 +0000358
John McCall3ad32c82011-01-28 08:37:24 +0000359 // Deactivate the cleanup block.
360 CGF.DeactivateCleanupBlock(cleanup);
Mike Stump0f590be2009-12-01 03:41:18 +0000361}
362
John McCallf1549f62010-07-06 01:34:17 +0000363llvm::Value *CodeGenFunction::getExceptionSlot() {
364 if (!ExceptionSlot) {
365 const llvm::Type *i8p = llvm::Type::getInt8PtrTy(getLLVMContext());
366 ExceptionSlot = CreateTempAlloca(i8p, "exn.slot");
Mike Stump0f590be2009-12-01 03:41:18 +0000367 }
John McCallf1549f62010-07-06 01:34:17 +0000368 return ExceptionSlot;
Mike Stump0f590be2009-12-01 03:41:18 +0000369}
370
Anders Carlsson756b5c42009-10-30 01:42:31 +0000371void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E) {
Anders Carlssond3379292009-10-30 02:27:02 +0000372 if (!E->getSubExpr()) {
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000373 if (getInvokeDest()) {
John McCallf1549f62010-07-06 01:34:17 +0000374 Builder.CreateInvoke(getReThrowFn(*this),
375 getUnreachableBlock(),
376 getInvokeDest())
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000377 ->setDoesNotReturn();
John McCallf1549f62010-07-06 01:34:17 +0000378 } else {
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000379 Builder.CreateCall(getReThrowFn(*this))->setDoesNotReturn();
John McCallf1549f62010-07-06 01:34:17 +0000380 Builder.CreateUnreachable();
381 }
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000382
John McCallcd5b22e2011-01-12 03:41:02 +0000383 // throw is an expression, and the expression emitters expect us
384 // to leave ourselves at a valid insertion point.
385 EmitBlock(createBasicBlock("throw.cont"));
386
Anders Carlssond3379292009-10-30 02:27:02 +0000387 return;
388 }
Mike Stump8755ec32009-12-10 00:06:18 +0000389
Anders Carlssond3379292009-10-30 02:27:02 +0000390 QualType ThrowType = E->getSubExpr()->getType();
Mike Stump8755ec32009-12-10 00:06:18 +0000391
Anders Carlssond3379292009-10-30 02:27:02 +0000392 // Now allocate the exception object.
393 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
John McCall3d3ec1c2010-04-21 10:05:39 +0000394 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
Mike Stump8755ec32009-12-10 00:06:18 +0000395
Anders Carlssond3379292009-10-30 02:27:02 +0000396 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(*this);
John McCallf1549f62010-07-06 01:34:17 +0000397 llvm::CallInst *ExceptionPtr =
Mike Stump8755ec32009-12-10 00:06:18 +0000398 Builder.CreateCall(AllocExceptionFn,
Anders Carlssond3379292009-10-30 02:27:02 +0000399 llvm::ConstantInt::get(SizeTy, TypeSize),
400 "exception");
John McCallf1549f62010-07-06 01:34:17 +0000401 ExceptionPtr->setDoesNotThrow();
Anders Carlsson8370c582009-12-11 00:32:37 +0000402
John McCallac418162010-04-22 01:10:34 +0000403 EmitAnyExprToExn(*this, E->getSubExpr(), ExceptionPtr);
Mike Stump8755ec32009-12-10 00:06:18 +0000404
Anders Carlssond3379292009-10-30 02:27:02 +0000405 // Now throw the exception.
406 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(getLLVMContext());
Anders Carlsson82a113a2011-01-24 01:59:49 +0000407 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
408 /*ForEH=*/true);
John McCallac418162010-04-22 01:10:34 +0000409
410 // The address of the destructor. If the exception type has a
411 // trivial destructor (or isn't a record), we just pass null.
412 llvm::Constant *Dtor = 0;
413 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
414 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
415 if (!Record->hasTrivialDestructor()) {
Douglas Gregor1d110e02010-07-01 14:13:13 +0000416 CXXDestructorDecl *DtorD = Record->getDestructor();
John McCallac418162010-04-22 01:10:34 +0000417 Dtor = CGM.GetAddrOfCXXDestructor(DtorD, Dtor_Complete);
418 Dtor = llvm::ConstantExpr::getBitCast(Dtor, Int8PtrTy);
419 }
420 }
421 if (!Dtor) Dtor = llvm::Constant::getNullValue(Int8PtrTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000422
Mike Stump0a3816e2009-12-04 01:51:45 +0000423 if (getInvokeDest()) {
Mike Stump8755ec32009-12-10 00:06:18 +0000424 llvm::InvokeInst *ThrowCall =
John McCallf1549f62010-07-06 01:34:17 +0000425 Builder.CreateInvoke3(getThrowFn(*this),
426 getUnreachableBlock(), getInvokeDest(),
Mike Stump0a3816e2009-12-04 01:51:45 +0000427 ExceptionPtr, TypeInfo, Dtor);
428 ThrowCall->setDoesNotReturn();
Mike Stump0a3816e2009-12-04 01:51:45 +0000429 } else {
Mike Stump8755ec32009-12-10 00:06:18 +0000430 llvm::CallInst *ThrowCall =
Mike Stump0a3816e2009-12-04 01:51:45 +0000431 Builder.CreateCall3(getThrowFn(*this), ExceptionPtr, TypeInfo, Dtor);
432 ThrowCall->setDoesNotReturn();
John McCallf1549f62010-07-06 01:34:17 +0000433 Builder.CreateUnreachable();
Mike Stump0a3816e2009-12-04 01:51:45 +0000434 }
Mike Stump8755ec32009-12-10 00:06:18 +0000435
John McCallcd5b22e2011-01-12 03:41:02 +0000436 // throw is an expression, and the expression emitters expect us
437 // to leave ourselves at a valid insertion point.
438 EmitBlock(createBasicBlock("throw.cont"));
Anders Carlsson756b5c42009-10-30 01:42:31 +0000439}
Mike Stump2bf701e2009-11-20 23:44:51 +0000440
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000441void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
Anders Carlsson15348ae2011-02-28 02:27:16 +0000442 if (!CGM.getLangOptions().CXXExceptions)
Anders Carlssona994ee42010-02-06 23:59:05 +0000443 return;
444
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000445 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
446 if (FD == 0)
447 return;
448 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
449 if (Proto == 0)
450 return;
451
Sebastian Redla968e972011-03-15 18:42:48 +0000452 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
453 if (isNoexceptExceptionSpec(EST)) {
454 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
455 // noexcept functions are simple terminate scopes.
456 EHStack.pushTerminate();
457 }
458 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
459 unsigned NumExceptions = Proto->getNumExceptions();
460 EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000461
Sebastian Redla968e972011-03-15 18:42:48 +0000462 for (unsigned I = 0; I != NumExceptions; ++I) {
463 QualType Ty = Proto->getExceptionType(I);
464 QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
465 llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType,
466 /*ForEH=*/true);
467 Filter->setFilter(I, EHType);
468 }
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000469 }
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000470}
471
472void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
Anders Carlsson15348ae2011-02-28 02:27:16 +0000473 if (!CGM.getLangOptions().CXXExceptions)
Anders Carlssona994ee42010-02-06 23:59:05 +0000474 return;
475
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000476 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
477 if (FD == 0)
478 return;
479 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
480 if (Proto == 0)
481 return;
482
Sebastian Redla968e972011-03-15 18:42:48 +0000483 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
484 if (isNoexceptExceptionSpec(EST)) {
485 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
486 EHStack.popTerminate();
487 }
488 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
489 EHStack.popFilter();
490 }
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000491}
492
Mike Stump2bf701e2009-11-20 23:44:51 +0000493void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
John McCall59a70002010-07-07 06:56:46 +0000494 EnterCXXTryStmt(S);
John McCall9fc6a772010-02-19 09:25:03 +0000495 EmitStmt(S.getTryBlock());
John McCall59a70002010-07-07 06:56:46 +0000496 ExitCXXTryStmt(S);
John McCall9fc6a772010-02-19 09:25:03 +0000497}
498
John McCall59a70002010-07-07 06:56:46 +0000499void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallf1549f62010-07-06 01:34:17 +0000500 unsigned NumHandlers = S.getNumHandlers();
501 EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
John McCall9fc6a772010-02-19 09:25:03 +0000502
John McCallf1549f62010-07-06 01:34:17 +0000503 for (unsigned I = 0; I != NumHandlers; ++I) {
504 const CXXCatchStmt *C = S.getHandler(I);
John McCall9fc6a772010-02-19 09:25:03 +0000505
John McCallf1549f62010-07-06 01:34:17 +0000506 llvm::BasicBlock *Handler = createBasicBlock("catch");
507 if (C->getExceptionDecl()) {
508 // FIXME: Dropping the reference type on the type into makes it
509 // impossible to correctly implement catch-by-reference
510 // semantics for pointers. Unfortunately, this is what all
511 // existing compilers do, and it's not clear that the standard
512 // personality routine is capable of doing this right. See C++ DR 388:
513 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
514 QualType CaughtType = C->getCaughtType();
515 CaughtType = CaughtType.getNonReferenceType().getUnqualifiedType();
John McCall5a180392010-07-24 00:37:23 +0000516
517 llvm::Value *TypeInfo = 0;
518 if (CaughtType->isObjCObjectPointerType())
519 TypeInfo = CGM.getObjCRuntime().GetEHType(CaughtType);
520 else
Anders Carlsson82a113a2011-01-24 01:59:49 +0000521 TypeInfo = CGM.GetAddrOfRTTIDescriptor(CaughtType, /*ForEH=*/true);
John McCallf1549f62010-07-06 01:34:17 +0000522 CatchScope->setHandler(I, TypeInfo, Handler);
523 } else {
524 // No exception decl indicates '...', a catch-all.
525 CatchScope->setCatchAllHandler(I, Handler);
526 }
527 }
John McCallf1549f62010-07-06 01:34:17 +0000528}
529
530/// Check whether this is a non-EH scope, i.e. a scope which doesn't
531/// affect exception handling. Currently, the only non-EH scopes are
532/// normal-only cleanup scopes.
533static bool isNonEHScope(const EHScope &S) {
John McCallda65ea82010-07-13 20:32:21 +0000534 switch (S.getKind()) {
John McCall1f0fca52010-07-21 07:22:38 +0000535 case EHScope::Cleanup:
536 return !cast<EHCleanupScope>(S).isEHCleanup();
John McCallda65ea82010-07-13 20:32:21 +0000537 case EHScope::Filter:
538 case EHScope::Catch:
539 case EHScope::Terminate:
540 return false;
541 }
542
543 // Suppress warning.
544 return false;
John McCallf1549f62010-07-06 01:34:17 +0000545}
546
547llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
548 assert(EHStack.requiresLandingPad());
549 assert(!EHStack.empty());
550
Anders Carlsson7a178512011-02-28 00:33:03 +0000551 if (!CGM.getLangOptions().Exceptions)
John McCallda65ea82010-07-13 20:32:21 +0000552 return 0;
553
John McCallf1549f62010-07-06 01:34:17 +0000554 // Check the innermost scope for a cached landing pad. If this is
555 // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
556 llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
557 if (LP) return LP;
558
559 // Build the landing pad for this scope.
560 LP = EmitLandingPad();
561 assert(LP);
562
563 // Cache the landing pad on the innermost scope. If this is a
564 // non-EH scope, cache the landing pad on the enclosing scope, too.
565 for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
566 ir->setCachedLandingPad(LP);
567 if (!isNonEHScope(*ir)) break;
568 }
569
570 return LP;
571}
572
John McCall09034212011-05-27 20:01:14 +0000573// This code contains a hack to work around a design flaw in
574// LLVM's EH IR which breaks semantics after inlining. This same
575// hack is implemented in llvm-gcc.
576//
577// The LLVM EH abstraction is basically a thin veneer over the
578// traditional GCC zero-cost design: for each range of instructions
579// in the function, there is (at most) one "landing pad" with an
580// associated chain of EH actions. A language-specific personality
581// function interprets this chain of actions and (1) decides whether
582// or not to resume execution at the landing pad and (2) if so,
583// provides an integer indicating why it's stopping. In LLVM IR,
584// the association of a landing pad with a range of instructions is
585// achieved via an invoke instruction, the chain of actions becomes
586// the arguments to the @llvm.eh.selector call, and the selector
587// call returns the integer indicator. Other than the required
588// presence of two intrinsic function calls in the landing pad,
589// the IR exactly describes the layout of the output code.
590//
591// A principal advantage of this design is that it is completely
592// language-agnostic; in theory, the LLVM optimizers can treat
593// landing pads neutrally, and targets need only know how to lower
594// the intrinsics to have a functioning exceptions system (assuming
595// that platform exceptions follow something approximately like the
596// GCC design). Unfortunately, landing pads cannot be combined in a
597// language-agnostic way: given selectors A and B, there is no way
598// to make a single landing pad which faithfully represents the
599// semantics of propagating an exception first through A, then
600// through B, without knowing how the personality will interpret the
601// (lowered form of the) selectors. This means that inlining has no
602// choice but to crudely chain invokes (i.e., to ignore invokes in
603// the inlined function, but to turn all unwindable calls into
604// invokes), which is only semantically valid if every unwind stops
605// at every landing pad.
606//
607// Therefore, the invoke-inline hack is to guarantee that every
608// landing pad has a catch-all.
609enum CleanupHackLevel_t {
610 /// A level of hack that requires that all landing pads have
611 /// catch-alls.
612 CHL_MandatoryCatchall,
613
614 /// A level of hack that requires that all landing pads handle
615 /// cleanups.
616 CHL_MandatoryCleanup,
617
618 /// No hacks at all; ideal IR generation.
619 CHL_Ideal
620};
621const CleanupHackLevel_t CleanupHackLevel = CHL_MandatoryCleanup;
622
John McCallf1549f62010-07-06 01:34:17 +0000623llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
624 assert(EHStack.requiresLandingPad());
625
John McCallf1549f62010-07-06 01:34:17 +0000626 for (EHScopeStack::iterator ir = EHStack.begin(); ; ) {
627 assert(ir != EHStack.end() &&
628 "stack requiring landing pad is nothing but non-EH scopes?");
629
630 // If this is a terminate scope, just use the singleton terminate
631 // landing pad.
632 if (isa<EHTerminateScope>(*ir))
633 return getTerminateLandingPad();
634
635 // If this isn't an EH scope, iterate; otherwise break out.
636 if (!isNonEHScope(*ir)) break;
637 ++ir;
638
639 // We haven't checked this scope for a cached landing pad yet.
640 if (llvm::BasicBlock *LP = ir->getCachedLandingPad())
641 return LP;
642 }
643
644 // Save the current IR generation state.
645 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
646
John McCalld16c2cf2011-02-08 08:22:06 +0000647 const EHPersonality &Personality = EHPersonality::get(getLangOptions());
John McCall8262b6a2010-07-17 00:43:08 +0000648
John McCallf1549f62010-07-06 01:34:17 +0000649 // Create and configure the landing pad.
650 llvm::BasicBlock *LP = createBasicBlock("lpad");
651 EmitBlock(LP);
652
653 // Save the exception pointer. It's safe to use a single exception
654 // pointer per function because EH cleanups can never have nested
655 // try/catches.
656 llvm::CallInst *Exn =
657 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_exception), "exn");
658 Exn->setDoesNotThrow();
659 Builder.CreateStore(Exn, getExceptionSlot());
660
661 // Build the selector arguments.
662 llvm::SmallVector<llvm::Value*, 8> EHSelector;
663 EHSelector.push_back(Exn);
John McCallb2593832010-09-16 06:16:50 +0000664 EHSelector.push_back(getOpaquePersonalityFn(CGM, Personality));
John McCallf1549f62010-07-06 01:34:17 +0000665
666 // Accumulate all the handlers in scope.
John McCallff8e1152010-07-23 21:56:41 +0000667 llvm::DenseMap<llvm::Value*, UnwindDest> EHHandlers;
668 UnwindDest CatchAll;
John McCallf1549f62010-07-06 01:34:17 +0000669 bool HasEHCleanup = false;
670 bool HasEHFilter = false;
671 llvm::SmallVector<llvm::Value*, 8> EHFilters;
672 for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end();
673 I != E; ++I) {
674
675 switch (I->getKind()) {
John McCall1f0fca52010-07-21 07:22:38 +0000676 case EHScope::Cleanup:
John McCallda65ea82010-07-13 20:32:21 +0000677 if (!HasEHCleanup)
John McCall1f0fca52010-07-21 07:22:38 +0000678 HasEHCleanup = cast<EHCleanupScope>(*I).isEHCleanup();
John McCallda65ea82010-07-13 20:32:21 +0000679 // We otherwise don't care about cleanups.
680 continue;
681
John McCallf1549f62010-07-06 01:34:17 +0000682 case EHScope::Filter: {
683 assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
John McCallff8e1152010-07-23 21:56:41 +0000684 assert(!CatchAll.isValid() && "EH filter reached after catch-all");
John McCallf1549f62010-07-06 01:34:17 +0000685
Chris Lattnerfc8f0e12011-04-15 05:22:18 +0000686 // Filter scopes get added to the selector in weird ways.
John McCallf1549f62010-07-06 01:34:17 +0000687 EHFilterScope &Filter = cast<EHFilterScope>(*I);
688 HasEHFilter = true;
689
690 // Add all the filter values which we aren't already explicitly
691 // catching.
692 for (unsigned I = 0, E = Filter.getNumFilters(); I != E; ++I) {
693 llvm::Value *FV = Filter.getFilter(I);
694 if (!EHHandlers.count(FV))
695 EHFilters.push_back(FV);
696 }
697 goto done;
698 }
699
700 case EHScope::Terminate:
701 // Terminate scopes are basically catch-alls.
John McCallff8e1152010-07-23 21:56:41 +0000702 assert(!CatchAll.isValid());
703 CatchAll = UnwindDest(getTerminateHandler(),
704 EHStack.getEnclosingEHCleanup(I),
705 cast<EHTerminateScope>(*I).getDestIndex());
John McCallf1549f62010-07-06 01:34:17 +0000706 goto done;
707
708 case EHScope::Catch:
709 break;
710 }
711
712 EHCatchScope &Catch = cast<EHCatchScope>(*I);
713 for (unsigned HI = 0, HE = Catch.getNumHandlers(); HI != HE; ++HI) {
714 EHCatchScope::Handler Handler = Catch.getHandler(HI);
715
716 // Catch-all. We should only have one of these per catch.
717 if (!Handler.Type) {
John McCallff8e1152010-07-23 21:56:41 +0000718 assert(!CatchAll.isValid());
719 CatchAll = UnwindDest(Handler.Block,
720 EHStack.getEnclosingEHCleanup(I),
721 Handler.Index);
John McCallf1549f62010-07-06 01:34:17 +0000722 continue;
723 }
724
725 // Check whether we already have a handler for this type.
John McCallff8e1152010-07-23 21:56:41 +0000726 UnwindDest &Dest = EHHandlers[Handler.Type];
727 if (Dest.isValid()) continue;
John McCallf1549f62010-07-06 01:34:17 +0000728
729 EHSelector.push_back(Handler.Type);
John McCallff8e1152010-07-23 21:56:41 +0000730 Dest = UnwindDest(Handler.Block,
731 EHStack.getEnclosingEHCleanup(I),
732 Handler.Index);
John McCallf1549f62010-07-06 01:34:17 +0000733 }
734
735 // Stop if we found a catch-all.
John McCallff8e1152010-07-23 21:56:41 +0000736 if (CatchAll.isValid()) break;
John McCallf1549f62010-07-06 01:34:17 +0000737 }
738
739 done:
740 unsigned LastToEmitInLoop = EHSelector.size();
741
742 // If we have a catch-all, add null to the selector.
John McCallff8e1152010-07-23 21:56:41 +0000743 if (CatchAll.isValid()) {
John McCalld16c2cf2011-02-08 08:22:06 +0000744 EHSelector.push_back(getCatchAllValue(*this));
John McCallf1549f62010-07-06 01:34:17 +0000745
746 // If we have an EH filter, we need to add those handlers in the
747 // right place in the selector, which is to say, at the end.
748 } else if (HasEHFilter) {
749 // Create a filter expression: an integer constant saying how many
750 // filters there are (+1 to avoid ambiguity with 0 for cleanup),
751 // followed by the filter types. The personality routine only
752 // lands here if the filter doesn't match.
753 EHSelector.push_back(llvm::ConstantInt::get(Builder.getInt32Ty(),
754 EHFilters.size() + 1));
755 EHSelector.append(EHFilters.begin(), EHFilters.end());
756
757 // Also check whether we need a cleanup.
John McCall09034212011-05-27 20:01:14 +0000758 if (CleanupHackLevel == CHL_MandatoryCatchall || HasEHCleanup)
759 EHSelector.push_back(CleanupHackLevel == CHL_MandatoryCatchall
John McCalld16c2cf2011-02-08 08:22:06 +0000760 ? getCatchAllValue(*this)
761 : getCleanupValue(*this));
John McCallf1549f62010-07-06 01:34:17 +0000762
763 // Otherwise, signal that we at least have cleanups.
John McCall09034212011-05-27 20:01:14 +0000764 } else if (CleanupHackLevel == CHL_MandatoryCatchall || HasEHCleanup) {
765 EHSelector.push_back(CleanupHackLevel == CHL_MandatoryCatchall
John McCalld16c2cf2011-02-08 08:22:06 +0000766 ? getCatchAllValue(*this)
767 : getCleanupValue(*this));
John McCall09034212011-05-27 20:01:14 +0000768
769 // At the MandatoryCleanup hack level, we don't need to actually
770 // spuriously tell the unwinder that we have cleanups, but we do
771 // need to always be prepared to handle cleanups.
772 } else if (CleanupHackLevel == CHL_MandatoryCleanup) {
773 // Just don't decrement LastToEmitInLoop.
774
John McCallf1549f62010-07-06 01:34:17 +0000775 } else {
776 assert(LastToEmitInLoop > 2);
777 LastToEmitInLoop--;
778 }
779
780 assert(EHSelector.size() >= 3 && "selector call has only two arguments!");
781
782 // Tell the backend how to generate the landing pad.
783 llvm::CallInst *Selection =
784 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_selector),
785 EHSelector.begin(), EHSelector.end(), "eh.selector");
786 Selection->setDoesNotThrow();
787
788 // Select the right handler.
789 llvm::Value *llvm_eh_typeid_for =
790 CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
791
792 // The results of llvm_eh_typeid_for aren't reliable --- at least
793 // not locally --- so we basically have to do this as an 'if' chain.
794 // We walk through the first N-1 catch clauses, testing and chaining,
795 // and then fall into the final clause (which is either a cleanup, a
796 // filter (possibly with a cleanup), a catch-all, or another catch).
797 for (unsigned I = 2; I != LastToEmitInLoop; ++I) {
798 llvm::Value *Type = EHSelector[I];
John McCallff8e1152010-07-23 21:56:41 +0000799 UnwindDest Dest = EHHandlers[Type];
800 assert(Dest.isValid() && "no handler entry for value in selector?");
John McCallf1549f62010-07-06 01:34:17 +0000801
802 // Figure out where to branch on a match. As a debug code-size
803 // optimization, if the scope depth matches the innermost cleanup,
804 // we branch directly to the catch handler.
John McCallff8e1152010-07-23 21:56:41 +0000805 llvm::BasicBlock *Match = Dest.getBlock();
806 bool MatchNeedsCleanup =
807 Dest.getScopeDepth() != EHStack.getInnermostEHCleanup();
John McCallf1549f62010-07-06 01:34:17 +0000808 if (MatchNeedsCleanup)
809 Match = createBasicBlock("eh.match");
810
811 llvm::BasicBlock *Next = createBasicBlock("eh.next");
812
813 // Check whether the exception matches.
814 llvm::CallInst *Id
815 = Builder.CreateCall(llvm_eh_typeid_for,
John McCalld16c2cf2011-02-08 08:22:06 +0000816 Builder.CreateBitCast(Type, Int8PtrTy));
John McCallf1549f62010-07-06 01:34:17 +0000817 Id->setDoesNotThrow();
818 Builder.CreateCondBr(Builder.CreateICmpEQ(Selection, Id),
819 Match, Next);
820
821 // Emit match code if necessary.
822 if (MatchNeedsCleanup) {
823 EmitBlock(Match);
824 EmitBranchThroughEHCleanup(Dest);
825 }
826
827 // Continue to the next match.
828 EmitBlock(Next);
829 }
830
831 // Emit the final case in the selector.
832 // This might be a catch-all....
John McCallff8e1152010-07-23 21:56:41 +0000833 if (CatchAll.isValid()) {
John McCallf1549f62010-07-06 01:34:17 +0000834 assert(isa<llvm::ConstantPointerNull>(EHSelector.back()));
835 EmitBranchThroughEHCleanup(CatchAll);
836
837 // ...or an EH filter...
838 } else if (HasEHFilter) {
839 llvm::Value *SavedSelection = Selection;
840
841 // First, unwind out to the outermost scope if necessary.
842 if (EHStack.hasEHCleanups()) {
843 // The end here might not dominate the beginning, so we might need to
844 // save the selector if we need it.
845 llvm::AllocaInst *SelectorVar = 0;
846 if (HasEHCleanup) {
847 SelectorVar = CreateTempAlloca(Builder.getInt32Ty(), "selector.var");
848 Builder.CreateStore(Selection, SelectorVar);
849 }
850
851 llvm::BasicBlock *CleanupContBB = createBasicBlock("ehspec.cleanup.cont");
John McCallff8e1152010-07-23 21:56:41 +0000852 EmitBranchThroughEHCleanup(UnwindDest(CleanupContBB, EHStack.stable_end(),
853 EHStack.getNextEHDestIndex()));
John McCallf1549f62010-07-06 01:34:17 +0000854 EmitBlock(CleanupContBB);
855
856 if (HasEHCleanup)
857 SavedSelection = Builder.CreateLoad(SelectorVar, "ehspec.saved-selector");
858 }
859
860 // If there was a cleanup, we'll need to actually check whether we
861 // landed here because the filter triggered.
John McCall09034212011-05-27 20:01:14 +0000862 if (CleanupHackLevel != CHL_Ideal || HasEHCleanup) {
John McCallf1549f62010-07-06 01:34:17 +0000863 llvm::BasicBlock *RethrowBB = createBasicBlock("cleanup");
864 llvm::BasicBlock *UnexpectedBB = createBasicBlock("ehspec.unexpected");
865
866 llvm::Constant *Zero = llvm::ConstantInt::get(Builder.getInt32Ty(), 0);
867 llvm::Value *FailsFilter =
868 Builder.CreateICmpSLT(SavedSelection, Zero, "ehspec.fails");
869 Builder.CreateCondBr(FailsFilter, UnexpectedBB, RethrowBB);
870
871 // The rethrow block is where we land if this was a cleanup.
John McCallf1549f62010-07-06 01:34:17 +0000872 EmitBlock(RethrowBB);
John McCall09034212011-05-27 20:01:14 +0000873 llvm::Constant *RethrowFn =
874 CleanupHackLevel == CHL_MandatoryCatchall ? getUnwindResumeOrRethrowFn()
875 : getUnwindResumeFn();
876 Builder.CreateCall(RethrowFn, Builder.CreateLoad(getExceptionSlot()))
John McCallf1549f62010-07-06 01:34:17 +0000877 ->setDoesNotReturn();
878 Builder.CreateUnreachable();
879
880 EmitBlock(UnexpectedBB);
881 }
882
883 // Call __cxa_call_unexpected. This doesn't need to be an invoke
884 // because __cxa_call_unexpected magically filters exceptions
885 // according to the last landing pad the exception was thrown
886 // into. Seriously.
887 Builder.CreateCall(getUnexpectedFn(*this),
888 Builder.CreateLoad(getExceptionSlot()))
889 ->setDoesNotReturn();
890 Builder.CreateUnreachable();
891
892 // ...or a normal catch handler...
John McCall09034212011-05-27 20:01:14 +0000893 } else if (CleanupHackLevel == CHL_Ideal && !HasEHCleanup) {
John McCallf1549f62010-07-06 01:34:17 +0000894 llvm::Value *Type = EHSelector.back();
895 EmitBranchThroughEHCleanup(EHHandlers[Type]);
896
897 // ...or a cleanup.
898 } else {
John McCallff8e1152010-07-23 21:56:41 +0000899 EmitBranchThroughEHCleanup(getRethrowDest());
John McCallf1549f62010-07-06 01:34:17 +0000900 }
901
902 // Restore the old IR generation state.
903 Builder.restoreIP(SavedIP);
904
905 return LP;
906}
907
John McCall8e3f8612010-07-13 22:12:14 +0000908namespace {
909 /// A cleanup to call __cxa_end_catch. In many cases, the caught
910 /// exception type lets us state definitively that the thrown exception
911 /// type does not have a destructor. In particular:
912 /// - Catch-alls tell us nothing, so we have to conservatively
913 /// assume that the thrown exception might have a destructor.
914 /// - Catches by reference behave according to their base types.
915 /// - Catches of non-record types will only trigger for exceptions
916 /// of non-record types, which never have destructors.
917 /// - Catches of record types can trigger for arbitrary subclasses
918 /// of the caught type, so we have to assume the actual thrown
919 /// exception type might have a throwing destructor, even if the
920 /// caught type's destructor is trivial or nothrow.
John McCall1f0fca52010-07-21 07:22:38 +0000921 struct CallEndCatch : EHScopeStack::Cleanup {
John McCall8e3f8612010-07-13 22:12:14 +0000922 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
923 bool MightThrow;
924
925 void Emit(CodeGenFunction &CGF, bool IsForEH) {
926 if (!MightThrow) {
927 CGF.Builder.CreateCall(getEndCatchFn(CGF))->setDoesNotThrow();
928 return;
929 }
930
931 CGF.EmitCallOrInvoke(getEndCatchFn(CGF), 0, 0);
932 }
933 };
934}
935
John McCallf1549f62010-07-06 01:34:17 +0000936/// Emits a call to __cxa_begin_catch and enters a cleanup to call
937/// __cxa_end_catch.
John McCall8e3f8612010-07-13 22:12:14 +0000938///
939/// \param EndMightThrow - true if __cxa_end_catch might throw
940static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
941 llvm::Value *Exn,
942 bool EndMightThrow) {
John McCallf1549f62010-07-06 01:34:17 +0000943 llvm::CallInst *Call = CGF.Builder.CreateCall(getBeginCatchFn(CGF), Exn);
944 Call->setDoesNotThrow();
945
John McCall1f0fca52010-07-21 07:22:38 +0000946 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
John McCallf1549f62010-07-06 01:34:17 +0000947
948 return Call;
949}
950
951/// A "special initializer" callback for initializing a catch
952/// parameter during catch initialization.
953static void InitCatchParam(CodeGenFunction &CGF,
954 const VarDecl &CatchParam,
955 llvm::Value *ParamAddr) {
956 // Load the exception from where the landing pad saved it.
957 llvm::Value *Exn = CGF.Builder.CreateLoad(CGF.getExceptionSlot(), "exn");
958
959 CanQualType CatchType =
960 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
961 const llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
962
963 // If we're catching by reference, we can just cast the object
964 // pointer to the appropriate pointer.
965 if (isa<ReferenceType>(CatchType)) {
John McCall204b0752010-07-20 22:17:55 +0000966 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
967 bool EndCatchMightThrow = CaughtType->isRecordType();
John McCall8e3f8612010-07-13 22:12:14 +0000968
John McCallf1549f62010-07-06 01:34:17 +0000969 // __cxa_begin_catch returns the adjusted object pointer.
John McCall8e3f8612010-07-13 22:12:14 +0000970 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
John McCall204b0752010-07-20 22:17:55 +0000971
972 // We have no way to tell the personality function that we're
973 // catching by reference, so if we're catching a pointer,
974 // __cxa_begin_catch will actually return that pointer by value.
975 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
976 QualType PointeeType = PT->getPointeeType();
977
978 // When catching by reference, generally we should just ignore
979 // this by-value pointer and use the exception object instead.
980 if (!PointeeType->isRecordType()) {
981
982 // Exn points to the struct _Unwind_Exception header, which
983 // we have to skip past in order to reach the exception data.
984 unsigned HeaderSize =
985 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
986 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
987
988 // However, if we're catching a pointer-to-record type that won't
989 // work, because the personality function might have adjusted
990 // the pointer. There's actually no way for us to fully satisfy
991 // the language/ABI contract here: we can't use Exn because it
992 // might have the wrong adjustment, but we can't use the by-value
993 // pointer because it's off by a level of abstraction.
994 //
995 // The current solution is to dump the adjusted pointer into an
996 // alloca, which breaks language semantics (because changing the
997 // pointer doesn't change the exception) but at least works.
998 // The better solution would be to filter out non-exact matches
999 // and rethrow them, but this is tricky because the rethrow
1000 // really needs to be catchable by other sites at this landing
1001 // pad. The best solution is to fix the personality function.
1002 } else {
1003 // Pull the pointer for the reference type off.
1004 const llvm::Type *PtrTy =
1005 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
1006
1007 // Create the temporary and write the adjusted pointer into it.
1008 llvm::Value *ExnPtrTmp = CGF.CreateTempAlloca(PtrTy, "exn.byref.tmp");
1009 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1010 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
1011
1012 // Bind the reference to the temporary.
1013 AdjustedExn = ExnPtrTmp;
1014 }
1015 }
1016
John McCallf1549f62010-07-06 01:34:17 +00001017 llvm::Value *ExnCast =
1018 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
1019 CGF.Builder.CreateStore(ExnCast, ParamAddr);
1020 return;
1021 }
1022
1023 // Non-aggregates (plus complexes).
1024 bool IsComplex = false;
1025 if (!CGF.hasAggregateLLVMType(CatchType) ||
1026 (IsComplex = CatchType->isAnyComplexType())) {
John McCall8e3f8612010-07-13 22:12:14 +00001027 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
John McCallf1549f62010-07-06 01:34:17 +00001028
1029 // If the catch type is a pointer type, __cxa_begin_catch returns
1030 // the pointer by value.
1031 if (CatchType->hasPointerRepresentation()) {
1032 llvm::Value *CastExn =
1033 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
1034 CGF.Builder.CreateStore(CastExn, ParamAddr);
1035 return;
1036 }
1037
1038 // Otherwise, it returns a pointer into the exception object.
1039
1040 const llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
1041 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1042
1043 if (IsComplex) {
1044 CGF.StoreComplexToAddr(CGF.LoadComplexFromAddr(Cast, /*volatile*/ false),
1045 ParamAddr, /*volatile*/ false);
1046 } else {
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001047 unsigned Alignment =
1048 CGF.getContext().getDeclAlign(&CatchParam).getQuantity();
John McCallf1549f62010-07-06 01:34:17 +00001049 llvm::Value *ExnLoad = CGF.Builder.CreateLoad(Cast, "exn.scalar");
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001050 CGF.EmitStoreOfScalar(ExnLoad, ParamAddr, /*volatile*/ false, Alignment,
1051 CatchType);
John McCallf1549f62010-07-06 01:34:17 +00001052 }
1053 return;
1054 }
1055
John McCallacff6962011-02-16 08:39:19 +00001056 assert(isa<RecordType>(CatchType) && "unexpected catch type!");
John McCallf1549f62010-07-06 01:34:17 +00001057
1058 const llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
1059
John McCallacff6962011-02-16 08:39:19 +00001060 // Check for a copy expression. If we don't have a copy expression,
1061 // that means a trivial copy is okay.
John McCalle996ffd2011-02-16 08:02:54 +00001062 const Expr *copyExpr = CatchParam.getInit();
1063 if (!copyExpr) {
John McCallacff6962011-02-16 08:39:19 +00001064 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
1065 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
1066 CGF.EmitAggregateCopy(ParamAddr, adjustedExn, CatchType);
John McCallf1549f62010-07-06 01:34:17 +00001067 return;
1068 }
1069
1070 // We have to call __cxa_get_exception_ptr to get the adjusted
1071 // pointer before copying.
John McCalle996ffd2011-02-16 08:02:54 +00001072 llvm::CallInst *rawAdjustedExn =
John McCallf1549f62010-07-06 01:34:17 +00001073 CGF.Builder.CreateCall(getGetExceptionPtrFn(CGF), Exn);
John McCalle996ffd2011-02-16 08:02:54 +00001074 rawAdjustedExn->setDoesNotThrow();
John McCallf1549f62010-07-06 01:34:17 +00001075
John McCalle996ffd2011-02-16 08:02:54 +00001076 // Cast that to the appropriate type.
1077 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
John McCallf1549f62010-07-06 01:34:17 +00001078
John McCalle996ffd2011-02-16 08:02:54 +00001079 // The copy expression is defined in terms of an OpaqueValueExpr.
1080 // Find it and map it to the adjusted expression.
1081 CodeGenFunction::OpaqueValueMapping
John McCall56ca35d2011-02-17 10:25:35 +00001082 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
1083 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
John McCallf1549f62010-07-06 01:34:17 +00001084
1085 // Call the copy ctor in a terminate scope.
1086 CGF.EHStack.pushTerminate();
John McCalle996ffd2011-02-16 08:02:54 +00001087
1088 // Perform the copy construction.
1089 CGF.EmitAggExpr(copyExpr, AggValueSlot::forAddr(ParamAddr, false, false));
1090
1091 // Leave the terminate scope.
John McCallf1549f62010-07-06 01:34:17 +00001092 CGF.EHStack.popTerminate();
1093
John McCalle996ffd2011-02-16 08:02:54 +00001094 // Undo the opaque value mapping.
1095 opaque.pop();
1096
John McCallf1549f62010-07-06 01:34:17 +00001097 // Finally we can call __cxa_begin_catch.
John McCall8e3f8612010-07-13 22:12:14 +00001098 CallBeginCatch(CGF, Exn, true);
John McCallf1549f62010-07-06 01:34:17 +00001099}
1100
1101/// Begins a catch statement by initializing the catch variable and
1102/// calling __cxa_begin_catch.
John McCalle996ffd2011-02-16 08:02:54 +00001103static void BeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *S) {
John McCallf1549f62010-07-06 01:34:17 +00001104 // We have to be very careful with the ordering of cleanups here:
1105 // C++ [except.throw]p4:
1106 // The destruction [of the exception temporary] occurs
1107 // immediately after the destruction of the object declared in
1108 // the exception-declaration in the handler.
1109 //
1110 // So the precise ordering is:
1111 // 1. Construct catch variable.
1112 // 2. __cxa_begin_catch
1113 // 3. Enter __cxa_end_catch cleanup
1114 // 4. Enter dtor cleanup
1115 //
John McCall34695852011-02-22 06:44:22 +00001116 // We do this by using a slightly abnormal initialization process.
1117 // Delegation sequence:
John McCallf1549f62010-07-06 01:34:17 +00001118 // - ExitCXXTryStmt opens a RunCleanupsScope
John McCall34695852011-02-22 06:44:22 +00001119 // - EmitAutoVarAlloca creates the variable and debug info
John McCallf1549f62010-07-06 01:34:17 +00001120 // - InitCatchParam initializes the variable from the exception
John McCall34695852011-02-22 06:44:22 +00001121 // - CallBeginCatch calls __cxa_begin_catch
1122 // - CallBeginCatch enters the __cxa_end_catch cleanup
1123 // - EmitAutoVarCleanups enters the variable destructor cleanup
John McCallf1549f62010-07-06 01:34:17 +00001124 // - EmitCXXTryStmt emits the code for the catch body
1125 // - EmitCXXTryStmt close the RunCleanupsScope
1126
1127 VarDecl *CatchParam = S->getExceptionDecl();
1128 if (!CatchParam) {
1129 llvm::Value *Exn = CGF.Builder.CreateLoad(CGF.getExceptionSlot(), "exn");
John McCall8e3f8612010-07-13 22:12:14 +00001130 CallBeginCatch(CGF, Exn, true);
John McCallf1549f62010-07-06 01:34:17 +00001131 return;
1132 }
1133
1134 // Emit the local.
John McCall34695852011-02-22 06:44:22 +00001135 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
1136 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF));
1137 CGF.EmitAutoVarCleanups(var);
John McCall9fc6a772010-02-19 09:25:03 +00001138}
1139
John McCallfcd5c0c2010-07-13 22:24:23 +00001140namespace {
John McCall1f0fca52010-07-21 07:22:38 +00001141 struct CallRethrow : EHScopeStack::Cleanup {
John McCallfcd5c0c2010-07-13 22:24:23 +00001142 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1143 CGF.EmitCallOrInvoke(getReThrowFn(CGF), 0, 0);
1144 }
1145 };
1146}
1147
John McCall59a70002010-07-07 06:56:46 +00001148void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallf1549f62010-07-06 01:34:17 +00001149 unsigned NumHandlers = S.getNumHandlers();
1150 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1151 assert(CatchScope.getNumHandlers() == NumHandlers);
Mike Stump2bf701e2009-11-20 23:44:51 +00001152
John McCallf1549f62010-07-06 01:34:17 +00001153 // Copy the handler blocks off before we pop the EH stack. Emitting
1154 // the handlers might scribble on this memory.
1155 llvm::SmallVector<EHCatchScope::Handler, 8> Handlers(NumHandlers);
1156 memcpy(Handlers.data(), CatchScope.begin(),
1157 NumHandlers * sizeof(EHCatchScope::Handler));
1158 EHStack.popCatch();
Mike Stump2bf701e2009-11-20 23:44:51 +00001159
John McCallf1549f62010-07-06 01:34:17 +00001160 // The fall-through block.
1161 llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
Mike Stump2bf701e2009-11-20 23:44:51 +00001162
John McCallf1549f62010-07-06 01:34:17 +00001163 // We just emitted the body of the try; jump to the continue block.
1164 if (HaveInsertPoint())
1165 Builder.CreateBr(ContBB);
Mike Stump639787c2009-12-02 19:53:57 +00001166
John McCall59a70002010-07-07 06:56:46 +00001167 // Determine if we need an implicit rethrow for all these catch handlers.
1168 bool ImplicitRethrow = false;
1169 if (IsFnTryBlock)
1170 ImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
1171 isa<CXXConstructorDecl>(CurCodeDecl);
1172
John McCallf1549f62010-07-06 01:34:17 +00001173 for (unsigned I = 0; I != NumHandlers; ++I) {
1174 llvm::BasicBlock *CatchBlock = Handlers[I].Block;
1175 EmitBlock(CatchBlock);
Mike Stump8755ec32009-12-10 00:06:18 +00001176
John McCallf1549f62010-07-06 01:34:17 +00001177 // Catch the exception if this isn't a catch-all.
1178 const CXXCatchStmt *C = S.getHandler(I);
Mike Stump2bf701e2009-11-20 23:44:51 +00001179
John McCallf1549f62010-07-06 01:34:17 +00001180 // Enter a cleanup scope, including the catch variable and the
1181 // end-catch.
1182 RunCleanupsScope CatchScope(*this);
Mike Stump2bf701e2009-11-20 23:44:51 +00001183
John McCallf1549f62010-07-06 01:34:17 +00001184 // Initialize the catch variable and set up the cleanups.
1185 BeginCatch(*this, C);
1186
John McCall59a70002010-07-07 06:56:46 +00001187 // If there's an implicit rethrow, push a normal "cleanup" to call
John McCallfcd5c0c2010-07-13 22:24:23 +00001188 // _cxa_rethrow. This needs to happen before __cxa_end_catch is
1189 // called, and so it is pushed after BeginCatch.
1190 if (ImplicitRethrow)
John McCall1f0fca52010-07-21 07:22:38 +00001191 EHStack.pushCleanup<CallRethrow>(NormalCleanup);
John McCall59a70002010-07-07 06:56:46 +00001192
John McCallf1549f62010-07-06 01:34:17 +00001193 // Perform the body of the catch.
1194 EmitStmt(C->getHandlerBlock());
1195
1196 // Fall out through the catch cleanups.
1197 CatchScope.ForceCleanup();
1198
1199 // Branch out of the try.
1200 if (HaveInsertPoint())
1201 Builder.CreateBr(ContBB);
Mike Stump2bf701e2009-11-20 23:44:51 +00001202 }
1203
John McCallf1549f62010-07-06 01:34:17 +00001204 EmitBlock(ContBB);
Mike Stump2bf701e2009-11-20 23:44:51 +00001205}
Mike Stumpd88ea562009-12-09 03:35:49 +00001206
John McCall55b20fc2010-07-21 00:52:03 +00001207namespace {
John McCall1f0fca52010-07-21 07:22:38 +00001208 struct CallEndCatchForFinally : EHScopeStack::Cleanup {
John McCall55b20fc2010-07-21 00:52:03 +00001209 llvm::Value *ForEHVar;
1210 llvm::Value *EndCatchFn;
1211 CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn)
1212 : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
1213
1214 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1215 llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
1216 llvm::BasicBlock *CleanupContBB =
1217 CGF.createBasicBlock("finally.cleanup.cont");
1218
1219 llvm::Value *ShouldEndCatch =
1220 CGF.Builder.CreateLoad(ForEHVar, "finally.endcatch");
1221 CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1222 CGF.EmitBlock(EndCatchBB);
1223 CGF.EmitCallOrInvoke(EndCatchFn, 0, 0); // catch-all, so might throw
1224 CGF.EmitBlock(CleanupContBB);
1225 }
1226 };
John McCall77199712010-07-21 05:47:49 +00001227
John McCall1f0fca52010-07-21 07:22:38 +00001228 struct PerformFinally : EHScopeStack::Cleanup {
John McCall77199712010-07-21 05:47:49 +00001229 const Stmt *Body;
1230 llvm::Value *ForEHVar;
1231 llvm::Value *EndCatchFn;
1232 llvm::Value *RethrowFn;
1233 llvm::Value *SavedExnVar;
1234
1235 PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
1236 llvm::Value *EndCatchFn,
1237 llvm::Value *RethrowFn, llvm::Value *SavedExnVar)
1238 : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1239 RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
1240
1241 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1242 // Enter a cleanup to call the end-catch function if one was provided.
1243 if (EndCatchFn)
John McCall1f0fca52010-07-21 07:22:38 +00001244 CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
1245 ForEHVar, EndCatchFn);
John McCall77199712010-07-21 05:47:49 +00001246
John McCalld96a8e72010-08-11 00:16:14 +00001247 // Save the current cleanup destination in case there are
1248 // cleanups in the finally block.
1249 llvm::Value *SavedCleanupDest =
1250 CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
1251 "cleanup.dest.saved");
1252
John McCall77199712010-07-21 05:47:49 +00001253 // Emit the finally block.
1254 CGF.EmitStmt(Body);
1255
1256 // If the end of the finally is reachable, check whether this was
1257 // for EH. If so, rethrow.
1258 if (CGF.HaveInsertPoint()) {
1259 llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
1260 llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
1261
1262 llvm::Value *ShouldRethrow =
1263 CGF.Builder.CreateLoad(ForEHVar, "finally.shouldthrow");
1264 CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1265
1266 CGF.EmitBlock(RethrowBB);
1267 if (SavedExnVar) {
1268 llvm::Value *Args[] = { CGF.Builder.CreateLoad(SavedExnVar) };
1269 CGF.EmitCallOrInvoke(RethrowFn, Args, Args+1);
1270 } else {
1271 CGF.EmitCallOrInvoke(RethrowFn, 0, 0);
1272 }
1273 CGF.Builder.CreateUnreachable();
1274
1275 CGF.EmitBlock(ContBB);
John McCalld96a8e72010-08-11 00:16:14 +00001276
1277 // Restore the cleanup destination.
1278 CGF.Builder.CreateStore(SavedCleanupDest,
1279 CGF.getNormalCleanupDestSlot());
John McCall77199712010-07-21 05:47:49 +00001280 }
1281
1282 // Leave the end-catch cleanup. As an optimization, pretend that
1283 // the fallthrough path was inaccessible; we've dynamically proven
1284 // that we're not in the EH case along that path.
1285 if (EndCatchFn) {
1286 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1287 CGF.PopCleanupBlock();
1288 CGF.Builder.restoreIP(SavedIP);
1289 }
1290
1291 // Now make sure we actually have an insertion point or the
1292 // cleanup gods will hate us.
1293 CGF.EnsureInsertPoint();
1294 }
1295 };
John McCall55b20fc2010-07-21 00:52:03 +00001296}
1297
John McCallf1549f62010-07-06 01:34:17 +00001298/// Enters a finally block for an implementation using zero-cost
1299/// exceptions. This is mostly general, but hard-codes some
1300/// language/ABI-specific behavior in the catch-all sections.
1301CodeGenFunction::FinallyInfo
1302CodeGenFunction::EnterFinallyBlock(const Stmt *Body,
1303 llvm::Constant *BeginCatchFn,
1304 llvm::Constant *EndCatchFn,
1305 llvm::Constant *RethrowFn) {
1306 assert((BeginCatchFn != 0) == (EndCatchFn != 0) &&
1307 "begin/end catch functions not paired");
1308 assert(RethrowFn && "rethrow function is required");
Mike Stumpd88ea562009-12-09 03:35:49 +00001309
John McCallf1549f62010-07-06 01:34:17 +00001310 // The rethrow function has one of the following two types:
1311 // void (*)()
1312 // void (*)(void*)
1313 // In the latter case we need to pass it the exception object.
1314 // But we can't use the exception slot because the @finally might
1315 // have a landing pad (which would overwrite the exception slot).
1316 const llvm::FunctionType *RethrowFnTy =
1317 cast<llvm::FunctionType>(
1318 cast<llvm::PointerType>(RethrowFn->getType())
1319 ->getElementType());
1320 llvm::Value *SavedExnVar = 0;
1321 if (RethrowFnTy->getNumParams())
1322 SavedExnVar = CreateTempAlloca(Builder.getInt8PtrTy(), "finally.exn");
Mike Stumpd88ea562009-12-09 03:35:49 +00001323
John McCallf1549f62010-07-06 01:34:17 +00001324 // A finally block is a statement which must be executed on any edge
1325 // out of a given scope. Unlike a cleanup, the finally block may
1326 // contain arbitrary control flow leading out of itself. In
1327 // addition, finally blocks should always be executed, even if there
1328 // are no catch handlers higher on the stack. Therefore, we
1329 // surround the protected scope with a combination of a normal
1330 // cleanup (to catch attempts to break out of the block via normal
1331 // control flow) and an EH catch-all (semantically "outside" any try
1332 // statement to which the finally block might have been attached).
1333 // The finally block itself is generated in the context of a cleanup
1334 // which conditionally leaves the catch-all.
John McCall3d3ec1c2010-04-21 10:05:39 +00001335
John McCallf1549f62010-07-06 01:34:17 +00001336 FinallyInfo Info;
John McCall3d3ec1c2010-04-21 10:05:39 +00001337
John McCallf1549f62010-07-06 01:34:17 +00001338 // Jump destination for performing the finally block on an exception
1339 // edge. We'll never actually reach this block, so unreachable is
1340 // fine.
1341 JumpDest RethrowDest = getJumpDestInCurrentScope(getUnreachableBlock());
John McCall3d3ec1c2010-04-21 10:05:39 +00001342
John McCallf1549f62010-07-06 01:34:17 +00001343 // Whether the finally block is being executed for EH purposes.
John McCalld16c2cf2011-02-08 08:22:06 +00001344 llvm::AllocaInst *ForEHVar = CreateTempAlloca(Builder.getInt1Ty(),
John McCallf1549f62010-07-06 01:34:17 +00001345 "finally.for-eh");
1346 InitTempAlloca(ForEHVar, llvm::ConstantInt::getFalse(getLLVMContext()));
Mike Stumpd88ea562009-12-09 03:35:49 +00001347
John McCallf1549f62010-07-06 01:34:17 +00001348 // Enter a normal cleanup which will perform the @finally block.
John McCall1f0fca52010-07-21 07:22:38 +00001349 EHStack.pushCleanup<PerformFinally>(NormalCleanup, Body,
1350 ForEHVar, EndCatchFn,
1351 RethrowFn, SavedExnVar);
John McCallf1549f62010-07-06 01:34:17 +00001352
1353 // Enter a catch-all scope.
1354 llvm::BasicBlock *CatchAllBB = createBasicBlock("finally.catchall");
1355 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1356 Builder.SetInsertPoint(CatchAllBB);
1357
1358 // If there's a begin-catch function, call it.
1359 if (BeginCatchFn) {
1360 Builder.CreateCall(BeginCatchFn, Builder.CreateLoad(getExceptionSlot()))
1361 ->setDoesNotThrow();
1362 }
1363
1364 // If we need to remember the exception pointer to rethrow later, do so.
1365 if (SavedExnVar) {
1366 llvm::Value *SavedExn = Builder.CreateLoad(getExceptionSlot());
1367 Builder.CreateStore(SavedExn, SavedExnVar);
1368 }
1369
1370 // Tell the finally block that we're in EH.
1371 Builder.CreateStore(llvm::ConstantInt::getTrue(getLLVMContext()), ForEHVar);
1372
1373 // Thread a jump through the finally cleanup.
1374 EmitBranchThroughCleanup(RethrowDest);
1375
1376 Builder.restoreIP(SavedIP);
1377
1378 EHCatchScope *CatchScope = EHStack.pushCatch(1);
1379 CatchScope->setCatchAllHandler(0, CatchAllBB);
1380
1381 return Info;
1382}
1383
1384void CodeGenFunction::ExitFinallyBlock(FinallyInfo &Info) {
1385 // Leave the finally catch-all.
1386 EHCatchScope &Catch = cast<EHCatchScope>(*EHStack.begin());
1387 llvm::BasicBlock *CatchAllBB = Catch.getHandler(0).Block;
1388 EHStack.popCatch();
1389
1390 // And leave the normal cleanup.
1391 PopCleanupBlock();
1392
1393 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1394 EmitBlock(CatchAllBB, true);
1395
1396 Builder.restoreIP(SavedIP);
1397}
1398
1399llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
1400 if (TerminateLandingPad)
1401 return TerminateLandingPad;
1402
1403 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1404
1405 // This will get inserted at the end of the function.
1406 TerminateLandingPad = createBasicBlock("terminate.lpad");
1407 Builder.SetInsertPoint(TerminateLandingPad);
1408
1409 // Tell the backend that this is a landing pad.
1410 llvm::CallInst *Exn =
1411 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_exception), "exn");
1412 Exn->setDoesNotThrow();
John McCall8262b6a2010-07-17 00:43:08 +00001413
1414 const EHPersonality &Personality = EHPersonality::get(CGM.getLangOptions());
John McCallf1549f62010-07-06 01:34:17 +00001415
1416 // Tell the backend what the exception table should be:
1417 // nothing but a catch-all.
John McCallb2593832010-09-16 06:16:50 +00001418 llvm::Value *Args[3] = { Exn, getOpaquePersonalityFn(CGM, Personality),
John McCallf1549f62010-07-06 01:34:17 +00001419 getCatchAllValue(*this) };
1420 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_selector),
1421 Args, Args+3, "eh.selector")
1422 ->setDoesNotThrow();
1423
1424 llvm::CallInst *TerminateCall = Builder.CreateCall(getTerminateFn(*this));
1425 TerminateCall->setDoesNotReturn();
1426 TerminateCall->setDoesNotThrow();
John McCalld16c2cf2011-02-08 08:22:06 +00001427 Builder.CreateUnreachable();
Mike Stumpd88ea562009-12-09 03:35:49 +00001428
John McCallf1549f62010-07-06 01:34:17 +00001429 // Restore the saved insertion state.
1430 Builder.restoreIP(SavedIP);
John McCall891f80e2010-04-30 00:06:43 +00001431
John McCallf1549f62010-07-06 01:34:17 +00001432 return TerminateLandingPad;
Mike Stumpd88ea562009-12-09 03:35:49 +00001433}
Mike Stump9b39c512009-12-09 22:59:31 +00001434
1435llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
Mike Stump182f3832009-12-10 00:02:42 +00001436 if (TerminateHandler)
1437 return TerminateHandler;
1438
John McCallf1549f62010-07-06 01:34:17 +00001439 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
Mike Stump76958092009-12-09 23:31:35 +00001440
John McCallf1549f62010-07-06 01:34:17 +00001441 // Set up the terminate handler. This block is inserted at the very
1442 // end of the function by FinishFunction.
Mike Stump182f3832009-12-10 00:02:42 +00001443 TerminateHandler = createBasicBlock("terminate.handler");
John McCallf1549f62010-07-06 01:34:17 +00001444 Builder.SetInsertPoint(TerminateHandler);
1445 llvm::CallInst *TerminateCall = Builder.CreateCall(getTerminateFn(*this));
Mike Stump9b39c512009-12-09 22:59:31 +00001446 TerminateCall->setDoesNotReturn();
1447 TerminateCall->setDoesNotThrow();
1448 Builder.CreateUnreachable();
1449
John McCall3d3ec1c2010-04-21 10:05:39 +00001450 // Restore the saved insertion state.
John McCallf1549f62010-07-06 01:34:17 +00001451 Builder.restoreIP(SavedIP);
Mike Stump76958092009-12-09 23:31:35 +00001452
Mike Stump9b39c512009-12-09 22:59:31 +00001453 return TerminateHandler;
1454}
John McCallf1549f62010-07-06 01:34:17 +00001455
John McCallff8e1152010-07-23 21:56:41 +00001456CodeGenFunction::UnwindDest CodeGenFunction::getRethrowDest() {
1457 if (RethrowBlock.isValid()) return RethrowBlock;
1458
1459 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1460
1461 // We emit a jump to a notional label at the outermost unwind state.
1462 llvm::BasicBlock *Unwind = createBasicBlock("eh.resume");
1463 Builder.SetInsertPoint(Unwind);
1464
1465 const EHPersonality &Personality = EHPersonality::get(CGM.getLangOptions());
1466
1467 // This can always be a call because we necessarily didn't find
1468 // anything on the EH stack which needs our help.
John McCallb2593832010-09-16 06:16:50 +00001469 llvm::StringRef RethrowName = Personality.getCatchallRethrowFnName();
John McCallff8e1152010-07-23 21:56:41 +00001470 llvm::Constant *RethrowFn;
John McCallb2593832010-09-16 06:16:50 +00001471 if (!RethrowName.empty())
John McCallff8e1152010-07-23 21:56:41 +00001472 RethrowFn = getCatchallRethrowFn(*this, RethrowName);
1473 else
John McCall09034212011-05-27 20:01:14 +00001474 RethrowFn = (CleanupHackLevel == CHL_MandatoryCatchall
1475 ? getUnwindResumeOrRethrowFn()
1476 : getUnwindResumeFn());
John McCallff8e1152010-07-23 21:56:41 +00001477
1478 Builder.CreateCall(RethrowFn, Builder.CreateLoad(getExceptionSlot()))
1479 ->setDoesNotReturn();
1480 Builder.CreateUnreachable();
1481
1482 Builder.restoreIP(SavedIP);
1483
1484 RethrowBlock = UnwindDest(Unwind, EHStack.stable_end(), 0);
1485 return RethrowBlock;
1486}
1487