1 //===--- CGException.cpp - Emit LLVM Code for C++ exceptions --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This contains code dealing with C++ exception related code generation.
12 //===----------------------------------------------------------------------===//
14 #include "clang/AST/StmtCXX.h"
16 #include "llvm/Intrinsics.h"
17 #include "llvm/IntrinsicInst.h"
18 #include "llvm/Support/CallSite.h"
20 #include "CGObjCRuntime.h"
21 #include "CodeGenFunction.h"
22 #include "CGException.h"
23 #include "CGCleanup.h"
24 #include "TargetInfo.h"
26 using namespace clang;
27 using namespace CodeGen;
29 static llvm::Constant *getAllocateExceptionFn(CodeGenFunction &CGF) {
30 // void *__cxa_allocate_exception(size_t thrown_size);
32 llvm::FunctionType *FTy =
33 llvm::FunctionType::get(CGF.Int8PtrTy, CGF.SizeTy, /*IsVarArgs=*/false);
35 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
38 static llvm::Constant *getFreeExceptionFn(CodeGenFunction &CGF) {
39 // void __cxa_free_exception(void *thrown_exception);
41 llvm::FunctionType *FTy =
42 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, /*IsVarArgs=*/false);
44 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_free_exception");
47 static llvm::Constant *getThrowFn(CodeGenFunction &CGF) {
48 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
49 // void (*dest) (void *));
51 llvm::Type *Args[3] = { CGF.Int8PtrTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
52 llvm::FunctionType *FTy =
53 llvm::FunctionType::get(CGF.VoidTy, Args, /*IsVarArgs=*/false);
55 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
58 static llvm::Constant *getReThrowFn(CodeGenFunction &CGF) {
59 // void __cxa_rethrow();
61 llvm::FunctionType *FTy =
62 llvm::FunctionType::get(CGF.VoidTy, /*IsVarArgs=*/false);
64 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
67 static llvm::Constant *getGetExceptionPtrFn(CodeGenFunction &CGF) {
68 // void *__cxa_get_exception_ptr(void*);
70 llvm::FunctionType *FTy =
71 llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrTy, /*IsVarArgs=*/false);
73 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
76 static llvm::Constant *getBeginCatchFn(CodeGenFunction &CGF) {
77 // void *__cxa_begin_catch(void*);
79 llvm::FunctionType *FTy =
80 llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrTy, /*IsVarArgs=*/false);
82 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
85 static llvm::Constant *getEndCatchFn(CodeGenFunction &CGF) {
86 // void __cxa_end_catch();
88 llvm::FunctionType *FTy =
89 llvm::FunctionType::get(CGF.VoidTy, /*IsVarArgs=*/false);
91 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
94 static llvm::Constant *getUnexpectedFn(CodeGenFunction &CGF) {
95 // void __cxa_call_unexepcted(void *thrown_exception);
97 llvm::FunctionType *FTy =
98 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, /*IsVarArgs=*/false);
100 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_call_unexpected");
103 llvm::Constant *CodeGenFunction::getUnwindResumeFn() {
104 llvm::FunctionType *FTy =
105 llvm::FunctionType::get(VoidTy, Int8PtrTy, /*IsVarArgs=*/false);
107 if (CGM.getLangOptions().SjLjExceptions)
108 return CGM.CreateRuntimeFunction(FTy, "_Unwind_SjLj_Resume");
109 return CGM.CreateRuntimeFunction(FTy, "_Unwind_Resume");
112 llvm::Constant *CodeGenFunction::getUnwindResumeOrRethrowFn() {
113 llvm::FunctionType *FTy =
114 llvm::FunctionType::get(VoidTy, Int8PtrTy, /*IsVarArgs=*/false);
116 if (CGM.getLangOptions().SjLjExceptions)
117 return CGM.CreateRuntimeFunction(FTy, "_Unwind_SjLj_Resume_or_Rethrow");
118 return CGM.CreateRuntimeFunction(FTy, "_Unwind_Resume_or_Rethrow");
121 static llvm::Constant *getTerminateFn(CodeGenFunction &CGF) {
122 // void __terminate();
124 llvm::FunctionType *FTy =
125 llvm::FunctionType::get(CGF.VoidTy, /*IsVarArgs=*/false);
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";
137 return CGF.CGM.CreateRuntimeFunction(FTy, name);
140 static llvm::Constant *getCatchallRethrowFn(CodeGenFunction &CGF,
142 llvm::FunctionType *FTy =
143 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, /*IsVarArgs=*/false);
145 return CGF.CGM.CreateRuntimeFunction(FTy, Name);
148 const EHPersonality EHPersonality::GNU_C("__gcc_personality_v0");
149 const EHPersonality EHPersonality::GNU_C_SJLJ("__gcc_personality_sj0");
150 const EHPersonality EHPersonality::NeXT_ObjC("__objc_personality_v0");
151 const EHPersonality EHPersonality::GNU_CPlusPlus("__gxx_personality_v0");
152 const EHPersonality EHPersonality::GNU_CPlusPlus_SJLJ("__gxx_personality_sj0");
153 const EHPersonality EHPersonality::GNU_ObjC("__gnu_objc_personality_v0",
154 "objc_exception_throw");
155 const EHPersonality EHPersonality::GNU_ObjCXX("__gnustep_objcxx_personality_v0");
157 static const EHPersonality &getCPersonality(const LangOptions &L) {
158 if (L.SjLjExceptions)
159 return EHPersonality::GNU_C_SJLJ;
160 return EHPersonality::GNU_C;
163 static const EHPersonality &getObjCPersonality(const LangOptions &L) {
165 if (L.ObjCNonFragileABI) return EHPersonality::NeXT_ObjC;
166 else return getCPersonality(L);
168 return EHPersonality::GNU_ObjC;
172 static const EHPersonality &getCXXPersonality(const LangOptions &L) {
173 if (L.SjLjExceptions)
174 return EHPersonality::GNU_CPlusPlus_SJLJ;
176 return EHPersonality::GNU_CPlusPlus;
179 /// Determines the personality function to use when both C++
180 /// and Objective-C exceptions are being caught.
181 static const EHPersonality &getObjCXXPersonality(const LangOptions &L) {
182 // 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.
186 if (L.ObjCNonFragileABI)
187 return EHPersonality::NeXT_ObjC;
189 // In the fragile ABI, just use C++ exception handling and hope
190 // they're not doing crazy exception mixing.
192 return getCXXPersonality(L);
195 // The GNU runtime's personality function inherently doesn't support
196 // mixed EH. Use the C++ personality just to avoid returning null.
197 return EHPersonality::GNU_ObjCXX;
200 const 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);
206 return getObjCPersonality(L);
208 return getCPersonality(L);
211 static llvm::Constant *getPersonalityFn(CodeGenModule &CGM,
212 const EHPersonality &Personality) {
214 CGM.CreateRuntimeFunction(llvm::FunctionType::get(
215 llvm::Type::getInt32Ty(CGM.getLLVMContext()),
217 Personality.getPersonalityFnName());
221 static llvm::Constant *getOpaquePersonalityFn(CodeGenModule &CGM,
222 const EHPersonality &Personality) {
223 llvm::Constant *Fn = getPersonalityFn(CGM, Personality);
224 return llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
227 /// Check whether a personality function could reasonably be swapped
228 /// for a C++ personality function.
229 static 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;
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))
242 // Otherwise, it has to be a landingpad instruction.
243 llvm::LandingPadInst *LPI = dyn_cast<llvm::LandingPadInst>(User);
244 if (!LPI) return false;
246 for (unsigned I = 0, E = LPI->getNumClauses(); I != E; ++I) {
247 // Look for something that would've been returned by the ObjC
248 // runtime's GetEHType() method.
249 llvm::Value *Val = LPI->getClause(I)->stripPointerCasts();
250 if (LPI->isCatch(I)) {
251 // Check if the catch value has the ObjC prefix.
252 if (llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Val))
253 // ObjC EH selector entries are always global variables with
254 // names starting like this.
255 if (GV->getName().startswith("OBJC_EHTYPE"))
258 // Check if any of the filter values have the ObjC prefix.
259 llvm::Constant *CVal = cast<llvm::Constant>(Val);
260 for (llvm::User::op_iterator
261 II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II) {
262 if (llvm::GlobalVariable *GV =
263 cast<llvm::GlobalVariable>((*II)->stripPointerCasts()))
264 // ObjC EH selector entries are always global variables with
265 // names starting like this.
266 if (GV->getName().startswith("OBJC_EHTYPE"))
276 /// Try to use the C++ personality function in ObjC++. Not doing this
277 /// can cause some incompatibilities with gcc, which is more
278 /// aggressive about only using the ObjC++ personality in a function
279 /// when it really needs it.
280 void CodeGenModule::SimplifyPersonality() {
281 // For now, this is really a Darwin-specific operation.
282 if (!Context.getTargetInfo().getTriple().isOSDarwin())
285 // If we're not in ObjC++ -fexceptions, there's nothing to do.
286 if (!Features.CPlusPlus || !Features.ObjC1 || !Features.Exceptions)
289 const EHPersonality &ObjCXX = EHPersonality::get(Features);
290 const EHPersonality &CXX = getCXXPersonality(Features);
291 if (&ObjCXX == &CXX ||
292 ObjCXX.getPersonalityFnName() == CXX.getPersonalityFnName())
296 getModule().getFunction(ObjCXX.getPersonalityFnName());
298 // Nothing to do if it's unused.
299 if (!Fn || Fn->use_empty()) return;
301 // Can't do the optimization if it has non-C++ uses.
302 if (!PersonalityHasOnlyCXXUses(Fn)) return;
304 // Create the C++ personality function and kill off the old
306 llvm::Constant *CXXFn = getPersonalityFn(*this, CXX);
308 // This can happen if the user is screwing with us.
309 if (Fn->getType() != CXXFn->getType()) return;
311 Fn->replaceAllUsesWith(CXXFn);
312 Fn->eraseFromParent();
315 /// Returns the value to inject into a selector to indicate the
316 /// presence of a catch-all.
317 static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
318 // Possibly we should use @llvm.eh.catch.all.value here.
319 return llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
323 /// A cleanup to free the exception object if its initialization
325 struct FreeException : EHScopeStack::Cleanup {
327 FreeException(llvm::Value *exn) : exn(exn) {}
328 void Emit(CodeGenFunction &CGF, Flags flags) {
329 CGF.Builder.CreateCall(getFreeExceptionFn(CGF), exn)
335 // Emits an exception expression into the given location. This
336 // differs from EmitAnyExprToMem only in that, if a final copy-ctor
337 // call is required, an exception within that copy ctor causes
338 // std::terminate to be invoked.
339 static void EmitAnyExprToExn(CodeGenFunction &CGF, const Expr *e,
341 // Make sure the exception object is cleaned up if there's an
342 // exception during initialization.
343 CGF.pushFullExprCleanup<FreeException>(EHCleanup, addr);
344 EHScopeStack::stable_iterator cleanup = CGF.EHStack.stable_begin();
346 // __cxa_allocate_exception returns a void*; we need to cast this
347 // to the appropriate type for the object.
348 llvm::Type *ty = CGF.ConvertTypeForMem(e->getType())->getPointerTo();
349 llvm::Value *typedAddr = CGF.Builder.CreateBitCast(addr, ty);
351 // FIXME: this isn't quite right! If there's a final unelided call
352 // to a copy constructor, then according to [except.terminate]p1 we
353 // must call std::terminate() if that constructor throws, because
354 // technically that copy occurs after the exception expression is
355 // evaluated but before the exception is caught. But the best way
356 // to handle that is to teach EmitAggExpr to do the final copy
357 // differently if it can't be elided.
358 CGF.EmitAnyExprToMem(e, typedAddr, e->getType().getQualifiers(),
361 // Deactivate the cleanup block.
362 CGF.DeactivateCleanupBlock(cleanup);
365 llvm::Value *CodeGenFunction::getExceptionSlot() {
367 ExceptionSlot = CreateTempAlloca(Int8PtrTy, "exn.slot");
368 return ExceptionSlot;
371 llvm::Value *CodeGenFunction::getEHSelectorSlot() {
373 EHSelectorSlot = CreateTempAlloca(Int32Ty, "ehselector.slot");
374 return EHSelectorSlot;
377 llvm::Value *CodeGenFunction::getExceptionFromSlot() {
378 return Builder.CreateLoad(getExceptionSlot(), "exn");
381 llvm::Value *CodeGenFunction::getSelectorFromSlot() {
382 return Builder.CreateLoad(getEHSelectorSlot(), "sel");
385 void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E) {
386 if (!E->getSubExpr()) {
387 if (getInvokeDest()) {
388 Builder.CreateInvoke(getReThrowFn(*this),
389 getUnreachableBlock(),
391 ->setDoesNotReturn();
393 Builder.CreateCall(getReThrowFn(*this))->setDoesNotReturn();
394 Builder.CreateUnreachable();
397 // throw is an expression, and the expression emitters expect us
398 // to leave ourselves at a valid insertion point.
399 EmitBlock(createBasicBlock("throw.cont"));
404 QualType ThrowType = E->getSubExpr()->getType();
406 // Now allocate the exception object.
407 llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
408 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
410 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(*this);
411 llvm::CallInst *ExceptionPtr =
412 Builder.CreateCall(AllocExceptionFn,
413 llvm::ConstantInt::get(SizeTy, TypeSize),
415 ExceptionPtr->setDoesNotThrow();
417 EmitAnyExprToExn(*this, E->getSubExpr(), ExceptionPtr);
419 // Now throw the exception.
420 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
423 // The address of the destructor. If the exception type has a
424 // trivial destructor (or isn't a record), we just pass null.
425 llvm::Constant *Dtor = 0;
426 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
427 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
428 if (!Record->hasTrivialDestructor()) {
429 CXXDestructorDecl *DtorD = Record->getDestructor();
430 Dtor = CGM.GetAddrOfCXXDestructor(DtorD, Dtor_Complete);
431 Dtor = llvm::ConstantExpr::getBitCast(Dtor, Int8PtrTy);
434 if (!Dtor) Dtor = llvm::Constant::getNullValue(Int8PtrTy);
436 if (getInvokeDest()) {
437 llvm::InvokeInst *ThrowCall =
438 Builder.CreateInvoke3(getThrowFn(*this),
439 getUnreachableBlock(), getInvokeDest(),
440 ExceptionPtr, TypeInfo, Dtor);
441 ThrowCall->setDoesNotReturn();
443 llvm::CallInst *ThrowCall =
444 Builder.CreateCall3(getThrowFn(*this), ExceptionPtr, TypeInfo, Dtor);
445 ThrowCall->setDoesNotReturn();
446 Builder.CreateUnreachable();
449 // throw is an expression, and the expression emitters expect us
450 // to leave ourselves at a valid insertion point.
451 EmitBlock(createBasicBlock("throw.cont"));
454 void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
455 if (!CGM.getLangOptions().CXXExceptions)
458 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
461 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
465 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
466 if (isNoexceptExceptionSpec(EST)) {
467 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
468 // noexcept functions are simple terminate scopes.
469 EHStack.pushTerminate();
471 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
472 unsigned NumExceptions = Proto->getNumExceptions();
473 EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
475 for (unsigned I = 0; I != NumExceptions; ++I) {
476 QualType Ty = Proto->getExceptionType(I);
477 QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
478 llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType,
480 Filter->setFilter(I, EHType);
485 /// Emit the dispatch block for a filter scope if necessary.
486 static void emitFilterDispatchBlock(CodeGenFunction &CGF,
487 EHFilterScope &filterScope) {
488 llvm::BasicBlock *dispatchBlock = filterScope.getCachedEHDispatchBlock();
489 if (!dispatchBlock) return;
490 if (dispatchBlock->use_empty()) {
491 delete dispatchBlock;
495 CGF.EmitBlockAfterUses(dispatchBlock);
497 // If this isn't a catch-all filter, we need to check whether we got
498 // here because the filter triggered.
499 if (filterScope.getNumFilters()) {
500 // Load the selector value.
501 llvm::Value *selector = CGF.getSelectorFromSlot();
502 llvm::BasicBlock *unexpectedBB = CGF.createBasicBlock("ehspec.unexpected");
504 llvm::Value *zero = CGF.Builder.getInt32(0);
505 llvm::Value *failsFilter =
506 CGF.Builder.CreateICmpSLT(selector, zero, "ehspec.fails");
507 CGF.Builder.CreateCondBr(failsFilter, unexpectedBB, CGF.getEHResumeBlock());
509 CGF.EmitBlock(unexpectedBB);
512 // Call __cxa_call_unexpected. This doesn't need to be an invoke
513 // because __cxa_call_unexpected magically filters exceptions
514 // according to the last landing pad the exception was thrown
516 llvm::Value *exn = CGF.getExceptionFromSlot();
517 CGF.Builder.CreateCall(getUnexpectedFn(CGF), exn)
518 ->setDoesNotReturn();
519 CGF.Builder.CreateUnreachable();
522 void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
523 if (!CGM.getLangOptions().CXXExceptions)
526 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
529 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
533 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
534 if (isNoexceptExceptionSpec(EST)) {
535 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
536 EHStack.popTerminate();
538 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
539 EHFilterScope &filterScope = cast<EHFilterScope>(*EHStack.begin());
540 emitFilterDispatchBlock(*this, filterScope);
545 void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
547 EmitStmt(S.getTryBlock());
551 void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
552 unsigned NumHandlers = S.getNumHandlers();
553 EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
555 for (unsigned I = 0; I != NumHandlers; ++I) {
556 const CXXCatchStmt *C = S.getHandler(I);
558 llvm::BasicBlock *Handler = createBasicBlock("catch");
559 if (C->getExceptionDecl()) {
560 // FIXME: Dropping the reference type on the type into makes it
561 // impossible to correctly implement catch-by-reference
562 // semantics for pointers. Unfortunately, this is what all
563 // existing compilers do, and it's not clear that the standard
564 // personality routine is capable of doing this right. See C++ DR 388:
565 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
566 QualType CaughtType = C->getCaughtType();
567 CaughtType = CaughtType.getNonReferenceType().getUnqualifiedType();
569 llvm::Value *TypeInfo = 0;
570 if (CaughtType->isObjCObjectPointerType())
571 TypeInfo = CGM.getObjCRuntime().GetEHType(CaughtType);
573 TypeInfo = CGM.GetAddrOfRTTIDescriptor(CaughtType, /*ForEH=*/true);
574 CatchScope->setHandler(I, TypeInfo, Handler);
576 // No exception decl indicates '...', a catch-all.
577 CatchScope->setCatchAllHandler(I, Handler);
583 CodeGenFunction::getEHDispatchBlock(EHScopeStack::stable_iterator si) {
584 // The dispatch block for the end of the scope chain is a block that
585 // just resumes unwinding.
586 if (si == EHStack.stable_end())
587 return getEHResumeBlock();
589 // Otherwise, we should look at the actual scope.
590 EHScope &scope = *EHStack.find(si);
592 llvm::BasicBlock *dispatchBlock = scope.getCachedEHDispatchBlock();
593 if (!dispatchBlock) {
594 switch (scope.getKind()) {
595 case EHScope::Catch: {
596 // Apply a special case to a single catch-all.
597 EHCatchScope &catchScope = cast<EHCatchScope>(scope);
598 if (catchScope.getNumHandlers() == 1 &&
599 catchScope.getHandler(0).isCatchAll()) {
600 dispatchBlock = catchScope.getHandler(0).Block;
602 // Otherwise, make a dispatch block.
604 dispatchBlock = createBasicBlock("catch.dispatch");
609 case EHScope::Cleanup:
610 dispatchBlock = createBasicBlock("ehcleanup");
613 case EHScope::Filter:
614 dispatchBlock = createBasicBlock("filter.dispatch");
617 case EHScope::Terminate:
618 dispatchBlock = getTerminateHandler();
621 scope.setCachedEHDispatchBlock(dispatchBlock);
623 return dispatchBlock;
626 /// Check whether this is a non-EH scope, i.e. a scope which doesn't
627 /// affect exception handling. Currently, the only non-EH scopes are
628 /// normal-only cleanup scopes.
629 static bool isNonEHScope(const EHScope &S) {
630 switch (S.getKind()) {
631 case EHScope::Cleanup:
632 return !cast<EHCleanupScope>(S).isEHCleanup();
633 case EHScope::Filter:
635 case EHScope::Terminate:
643 llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
644 assert(EHStack.requiresLandingPad());
645 assert(!EHStack.empty());
647 if (!CGM.getLangOptions().Exceptions)
650 // Check the innermost scope for a cached landing pad. If this is
651 // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
652 llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
655 // Build the landing pad for this scope.
656 LP = EmitLandingPad();
659 // Cache the landing pad on the innermost scope. If this is a
660 // non-EH scope, cache the landing pad on the enclosing scope, too.
661 for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
662 ir->setCachedLandingPad(LP);
663 if (!isNonEHScope(*ir)) break;
669 // This code contains a hack to work around a design flaw in
670 // LLVM's EH IR which breaks semantics after inlining. This same
671 // hack is implemented in llvm-gcc.
673 // The LLVM EH abstraction is basically a thin veneer over the
674 // traditional GCC zero-cost design: for each range of instructions
675 // in the function, there is (at most) one "landing pad" with an
676 // associated chain of EH actions. A language-specific personality
677 // function interprets this chain of actions and (1) decides whether
678 // or not to resume execution at the landing pad and (2) if so,
679 // provides an integer indicating why it's stopping. In LLVM IR,
680 // the association of a landing pad with a range of instructions is
681 // achieved via an invoke instruction, the chain of actions becomes
682 // the arguments to the @llvm.eh.selector call, and the selector
683 // call returns the integer indicator. Other than the required
684 // presence of two intrinsic function calls in the landing pad,
685 // the IR exactly describes the layout of the output code.
687 // A principal advantage of this design is that it is completely
688 // language-agnostic; in theory, the LLVM optimizers can treat
689 // landing pads neutrally, and targets need only know how to lower
690 // the intrinsics to have a functioning exceptions system (assuming
691 // that platform exceptions follow something approximately like the
692 // GCC design). Unfortunately, landing pads cannot be combined in a
693 // language-agnostic way: given selectors A and B, there is no way
694 // to make a single landing pad which faithfully represents the
695 // semantics of propagating an exception first through A, then
696 // through B, without knowing how the personality will interpret the
697 // (lowered form of the) selectors. This means that inlining has no
698 // choice but to crudely chain invokes (i.e., to ignore invokes in
699 // the inlined function, but to turn all unwindable calls into
700 // invokes), which is only semantically valid if every unwind stops
701 // at every landing pad.
703 // Therefore, the invoke-inline hack is to guarantee that every
704 // landing pad has a catch-all.
705 enum CleanupHackLevel_t {
706 /// A level of hack that requires that all landing pads have
708 CHL_MandatoryCatchall,
710 /// A level of hack that requires that all landing pads handle
712 CHL_MandatoryCleanup,
714 /// No hacks at all; ideal IR generation.
717 const CleanupHackLevel_t CleanupHackLevel = CHL_MandatoryCleanup;
719 llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
720 assert(EHStack.requiresLandingPad());
722 EHScope &innermostEHScope = *EHStack.find(EHStack.getInnermostEHScope());
723 switch (innermostEHScope.getKind()) {
724 case EHScope::Terminate:
725 return getTerminateLandingPad();
728 case EHScope::Cleanup:
729 case EHScope::Filter:
730 if (llvm::BasicBlock *lpad = innermostEHScope.getCachedLandingPad())
734 // Save the current IR generation state.
735 CGBuilderTy::InsertPoint savedIP = Builder.saveAndClearIP();
737 const EHPersonality &personality = EHPersonality::get(getLangOptions());
739 // Create and configure the landing pad.
740 llvm::BasicBlock *lpad = createBasicBlock("lpad");
743 llvm::LandingPadInst *LPadInst =
744 Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, NULL),
745 getOpaquePersonalityFn(CGM, personality), 0);
747 llvm::Value *LPadExn = Builder.CreateExtractValue(LPadInst, 0);
748 Builder.CreateStore(LPadExn, getExceptionSlot());
749 llvm::Value *LPadSel = Builder.CreateExtractValue(LPadInst, 1);
750 Builder.CreateStore(LPadSel, getEHSelectorSlot());
752 // Save the exception pointer. It's safe to use a single exception
753 // pointer per function because EH cleanups can never have nested
755 // Build the landingpad instruction.
757 // Accumulate all the handlers in scope.
758 bool hasCatchAll = false;
759 bool hasCleanup = false;
760 bool hasFilter = false;
761 SmallVector<llvm::Value*, 4> filterTypes;
762 llvm::SmallPtrSet<llvm::Value*, 4> catchTypes;
763 for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end();
766 switch (I->getKind()) {
767 case EHScope::Cleanup:
768 // If we have a cleanup, remember that.
769 hasCleanup = (hasCleanup || cast<EHCleanupScope>(*I).isEHCleanup());
772 case EHScope::Filter: {
773 assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
774 assert(!hasCatchAll && "EH filter reached after catch-all");
776 // Filter scopes get added to the landingpad in weird ways.
777 EHFilterScope &filter = cast<EHFilterScope>(*I);
780 // Add all the filter values.
781 for (unsigned i = 0, e = filter.getNumFilters(); i != e; ++i)
782 filterTypes.push_back(filter.getFilter(i));
786 case EHScope::Terminate:
787 // Terminate scopes are basically catch-alls.
788 assert(!hasCatchAll);
796 EHCatchScope &catchScope = cast<EHCatchScope>(*I);
797 for (unsigned hi = 0, he = catchScope.getNumHandlers(); hi != he; ++hi) {
798 EHCatchScope::Handler handler = catchScope.getHandler(hi);
800 // If this is a catch-all, register that and abort.
802 assert(!hasCatchAll);
807 // Check whether we already have a handler for this type.
808 if (catchTypes.insert(handler.Type))
809 // If not, add it directly to the landingpad.
810 LPadInst->addClause(handler.Type);
815 // If we have a catch-all, add null to the landingpad.
816 assert(!(hasCatchAll && hasFilter));
818 LPadInst->addClause(getCatchAllValue(*this));
820 // If we have an EH filter, we need to add those handlers in the
821 // right place in the landingpad, which is to say, at the end.
822 } else if (hasFilter) {
823 // Create a filter expression: a constant array indicating which filter
824 // types there are. The personality routine only lands here if the filter
826 llvm::SmallVector<llvm::Constant*, 8> Filters;
827 llvm::ArrayType *AType =
828 llvm::ArrayType::get(!filterTypes.empty() ?
829 filterTypes[0]->getType() : Int8PtrTy,
832 for (unsigned i = 0, e = filterTypes.size(); i != e; ++i)
833 Filters.push_back(cast<llvm::Constant>(filterTypes[i]));
834 llvm::Constant *FilterArray = llvm::ConstantArray::get(AType, Filters);
835 LPadInst->addClause(FilterArray);
837 // Also check whether we need a cleanup.
839 LPadInst->setCleanup(true);
841 // Otherwise, signal that we at least have cleanups.
842 } else if (CleanupHackLevel == CHL_MandatoryCatchall || hasCleanup) {
843 if (CleanupHackLevel == CHL_MandatoryCatchall)
844 LPadInst->addClause(getCatchAllValue(*this));
846 LPadInst->setCleanup(true);
849 assert((LPadInst->getNumClauses() > 0 || LPadInst->isCleanup()) &&
850 "landingpad instruction has no clauses!");
852 // Tell the backend how to generate the landing pad.
853 Builder.CreateBr(getEHDispatchBlock(EHStack.getInnermostEHScope()));
855 // Restore the old IR generation state.
856 Builder.restoreIP(savedIP);
862 /// A cleanup to call __cxa_end_catch. In many cases, the caught
863 /// exception type lets us state definitively that the thrown exception
864 /// type does not have a destructor. In particular:
865 /// - Catch-alls tell us nothing, so we have to conservatively
866 /// assume that the thrown exception might have a destructor.
867 /// - Catches by reference behave according to their base types.
868 /// - Catches of non-record types will only trigger for exceptions
869 /// of non-record types, which never have destructors.
870 /// - Catches of record types can trigger for arbitrary subclasses
871 /// of the caught type, so we have to assume the actual thrown
872 /// exception type might have a throwing destructor, even if the
873 /// caught type's destructor is trivial or nothrow.
874 struct CallEndCatch : EHScopeStack::Cleanup {
875 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
878 void Emit(CodeGenFunction &CGF, Flags flags) {
880 CGF.Builder.CreateCall(getEndCatchFn(CGF))->setDoesNotThrow();
884 CGF.EmitCallOrInvoke(getEndCatchFn(CGF));
889 /// Emits a call to __cxa_begin_catch and enters a cleanup to call
892 /// \param EndMightThrow - true if __cxa_end_catch might throw
893 static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
895 bool EndMightThrow) {
896 llvm::CallInst *Call = CGF.Builder.CreateCall(getBeginCatchFn(CGF), Exn);
897 Call->setDoesNotThrow();
899 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
904 /// A "special initializer" callback for initializing a catch
905 /// parameter during catch initialization.
906 static void InitCatchParam(CodeGenFunction &CGF,
907 const VarDecl &CatchParam,
908 llvm::Value *ParamAddr) {
909 // Load the exception from where the landing pad saved it.
910 llvm::Value *Exn = CGF.getExceptionFromSlot();
912 CanQualType CatchType =
913 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
914 llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
916 // If we're catching by reference, we can just cast the object
917 // pointer to the appropriate pointer.
918 if (isa<ReferenceType>(CatchType)) {
919 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
920 bool EndCatchMightThrow = CaughtType->isRecordType();
922 // __cxa_begin_catch returns the adjusted object pointer.
923 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
925 // We have no way to tell the personality function that we're
926 // catching by reference, so if we're catching a pointer,
927 // __cxa_begin_catch will actually return that pointer by value.
928 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
929 QualType PointeeType = PT->getPointeeType();
931 // When catching by reference, generally we should just ignore
932 // this by-value pointer and use the exception object instead.
933 if (!PointeeType->isRecordType()) {
935 // Exn points to the struct _Unwind_Exception header, which
936 // we have to skip past in order to reach the exception data.
937 unsigned HeaderSize =
938 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
939 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
941 // However, if we're catching a pointer-to-record type that won't
942 // work, because the personality function might have adjusted
943 // the pointer. There's actually no way for us to fully satisfy
944 // the language/ABI contract here: we can't use Exn because it
945 // might have the wrong adjustment, but we can't use the by-value
946 // pointer because it's off by a level of abstraction.
948 // The current solution is to dump the adjusted pointer into an
949 // alloca, which breaks language semantics (because changing the
950 // pointer doesn't change the exception) but at least works.
951 // The better solution would be to filter out non-exact matches
952 // and rethrow them, but this is tricky because the rethrow
953 // really needs to be catchable by other sites at this landing
954 // pad. The best solution is to fix the personality function.
956 // Pull the pointer for the reference type off.
958 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
960 // Create the temporary and write the adjusted pointer into it.
961 llvm::Value *ExnPtrTmp = CGF.CreateTempAlloca(PtrTy, "exn.byref.tmp");
962 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
963 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
965 // Bind the reference to the temporary.
966 AdjustedExn = ExnPtrTmp;
970 llvm::Value *ExnCast =
971 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
972 CGF.Builder.CreateStore(ExnCast, ParamAddr);
976 // Non-aggregates (plus complexes).
977 bool IsComplex = false;
978 if (!CGF.hasAggregateLLVMType(CatchType) ||
979 (IsComplex = CatchType->isAnyComplexType())) {
980 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
982 // If the catch type is a pointer type, __cxa_begin_catch returns
983 // the pointer by value.
984 if (CatchType->hasPointerRepresentation()) {
985 llvm::Value *CastExn =
986 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
987 CGF.Builder.CreateStore(CastExn, ParamAddr);
991 // Otherwise, it returns a pointer into the exception object.
993 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
994 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
997 CGF.StoreComplexToAddr(CGF.LoadComplexFromAddr(Cast, /*volatile*/ false),
998 ParamAddr, /*volatile*/ false);
1000 unsigned Alignment =
1001 CGF.getContext().getDeclAlign(&CatchParam).getQuantity();
1002 llvm::Value *ExnLoad = CGF.Builder.CreateLoad(Cast, "exn.scalar");
1003 CGF.EmitStoreOfScalar(ExnLoad, ParamAddr, /*volatile*/ false, Alignment,
1009 assert(isa<RecordType>(CatchType) && "unexpected catch type!");
1011 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
1013 // Check for a copy expression. If we don't have a copy expression,
1014 // that means a trivial copy is okay.
1015 const Expr *copyExpr = CatchParam.getInit();
1017 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
1018 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
1019 CGF.EmitAggregateCopy(ParamAddr, adjustedExn, CatchType);
1023 // We have to call __cxa_get_exception_ptr to get the adjusted
1024 // pointer before copying.
1025 llvm::CallInst *rawAdjustedExn =
1026 CGF.Builder.CreateCall(getGetExceptionPtrFn(CGF), Exn);
1027 rawAdjustedExn->setDoesNotThrow();
1029 // Cast that to the appropriate type.
1030 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
1032 // The copy expression is defined in terms of an OpaqueValueExpr.
1033 // Find it and map it to the adjusted expression.
1034 CodeGenFunction::OpaqueValueMapping
1035 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
1036 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
1038 // Call the copy ctor in a terminate scope.
1039 CGF.EHStack.pushTerminate();
1041 // Perform the copy construction.
1042 CGF.EmitAggExpr(copyExpr, AggValueSlot::forAddr(ParamAddr, Qualifiers(),
1043 AggValueSlot::IsNotDestructed,
1044 AggValueSlot::DoesNotNeedGCBarriers,
1045 AggValueSlot::IsNotAliased));
1047 // Leave the terminate scope.
1048 CGF.EHStack.popTerminate();
1050 // Undo the opaque value mapping.
1053 // Finally we can call __cxa_begin_catch.
1054 CallBeginCatch(CGF, Exn, true);
1057 /// Begins a catch statement by initializing the catch variable and
1058 /// calling __cxa_begin_catch.
1059 static void BeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *S) {
1060 // We have to be very careful with the ordering of cleanups here:
1061 // C++ [except.throw]p4:
1062 // The destruction [of the exception temporary] occurs
1063 // immediately after the destruction of the object declared in
1064 // the exception-declaration in the handler.
1066 // So the precise ordering is:
1067 // 1. Construct catch variable.
1068 // 2. __cxa_begin_catch
1069 // 3. Enter __cxa_end_catch cleanup
1070 // 4. Enter dtor cleanup
1072 // We do this by using a slightly abnormal initialization process.
1073 // Delegation sequence:
1074 // - ExitCXXTryStmt opens a RunCleanupsScope
1075 // - EmitAutoVarAlloca creates the variable and debug info
1076 // - InitCatchParam initializes the variable from the exception
1077 // - CallBeginCatch calls __cxa_begin_catch
1078 // - CallBeginCatch enters the __cxa_end_catch cleanup
1079 // - EmitAutoVarCleanups enters the variable destructor cleanup
1080 // - EmitCXXTryStmt emits the code for the catch body
1081 // - EmitCXXTryStmt close the RunCleanupsScope
1083 VarDecl *CatchParam = S->getExceptionDecl();
1085 llvm::Value *Exn = CGF.getExceptionFromSlot();
1086 CallBeginCatch(CGF, Exn, true);
1091 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
1092 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF));
1093 CGF.EmitAutoVarCleanups(var);
1097 struct CallRethrow : EHScopeStack::Cleanup {
1098 void Emit(CodeGenFunction &CGF, Flags flags) {
1099 CGF.EmitCallOrInvoke(getReThrowFn(CGF));
1104 /// Emit the structure of the dispatch block for the given catch scope.
1105 /// It is an invariant that the dispatch block already exists.
1106 static void emitCatchDispatchBlock(CodeGenFunction &CGF,
1107 EHCatchScope &catchScope) {
1108 llvm::BasicBlock *dispatchBlock = catchScope.getCachedEHDispatchBlock();
1109 assert(dispatchBlock);
1111 // If there's only a single catch-all, getEHDispatchBlock returned
1112 // that catch-all as the dispatch block.
1113 if (catchScope.getNumHandlers() == 1 &&
1114 catchScope.getHandler(0).isCatchAll()) {
1115 assert(dispatchBlock == catchScope.getHandler(0).Block);
1119 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveIP();
1120 CGF.EmitBlockAfterUses(dispatchBlock);
1122 // Select the right handler.
1123 llvm::Value *llvm_eh_typeid_for =
1124 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
1126 // Load the selector value.
1127 llvm::Value *selector = CGF.getSelectorFromSlot();
1129 // Test against each of the exception types we claim to catch.
1130 for (unsigned i = 0, e = catchScope.getNumHandlers(); ; ++i) {
1131 assert(i < e && "ran off end of handlers!");
1132 const EHCatchScope::Handler &handler = catchScope.getHandler(i);
1134 llvm::Value *typeValue = handler.Type;
1135 assert(typeValue && "fell into catch-all case!");
1136 typeValue = CGF.Builder.CreateBitCast(typeValue, CGF.Int8PtrTy);
1138 // Figure out the next block.
1140 llvm::BasicBlock *nextBlock;
1142 // If this is the last handler, we're at the end, and the next
1143 // block is the block for the enclosing EH scope.
1145 nextBlock = CGF.getEHDispatchBlock(catchScope.getEnclosingEHScope());
1148 // If the next handler is a catch-all, we're at the end, and the
1149 // next block is that handler.
1150 } else if (catchScope.getHandler(i+1).isCatchAll()) {
1151 nextBlock = catchScope.getHandler(i+1).Block;
1154 // Otherwise, we're not at the end and we need a new block.
1156 nextBlock = CGF.createBasicBlock("catch.fallthrough");
1160 // Figure out the catch type's index in the LSDA's type table.
1161 llvm::CallInst *typeIndex =
1162 CGF.Builder.CreateCall(llvm_eh_typeid_for, typeValue);
1163 typeIndex->setDoesNotThrow();
1165 llvm::Value *matchesTypeIndex =
1166 CGF.Builder.CreateICmpEQ(selector, typeIndex, "matches");
1167 CGF.Builder.CreateCondBr(matchesTypeIndex, handler.Block, nextBlock);
1169 // If the next handler is a catch-all, we're completely done.
1171 CGF.Builder.restoreIP(savedIP);
1174 // Otherwise we need to emit and continue at that block.
1176 CGF.EmitBlock(nextBlock);
1180 llvm_unreachable("fell out of loop!");
1183 void CodeGenFunction::popCatchScope() {
1184 EHCatchScope &catchScope = cast<EHCatchScope>(*EHStack.begin());
1185 if (catchScope.hasEHBranches())
1186 emitCatchDispatchBlock(*this, catchScope);
1190 void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
1191 unsigned NumHandlers = S.getNumHandlers();
1192 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1193 assert(CatchScope.getNumHandlers() == NumHandlers);
1195 // If the catch was not required, bail out now.
1196 if (!CatchScope.hasEHBranches()) {
1201 // Emit the structure of the EH dispatch for this catch.
1202 emitCatchDispatchBlock(*this, CatchScope);
1204 // Copy the handler blocks off before we pop the EH stack. Emitting
1205 // the handlers might scribble on this memory.
1206 SmallVector<EHCatchScope::Handler, 8> Handlers(NumHandlers);
1207 memcpy(Handlers.data(), CatchScope.begin(),
1208 NumHandlers * sizeof(EHCatchScope::Handler));
1212 // The fall-through block.
1213 llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
1215 // We just emitted the body of the try; jump to the continue block.
1216 if (HaveInsertPoint())
1217 Builder.CreateBr(ContBB);
1219 // Determine if we need an implicit rethrow for all these catch handlers.
1220 bool ImplicitRethrow = false;
1222 ImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
1223 isa<CXXConstructorDecl>(CurCodeDecl);
1225 // Perversely, we emit the handlers backwards precisely because we
1226 // want them to appear in source order. In all of these cases, the
1227 // catch block will have exactly one predecessor, which will be a
1228 // particular block in the catch dispatch. However, in the case of
1229 // a catch-all, one of the dispatch blocks will branch to two
1230 // different handlers, and EmitBlockAfterUses will cause the second
1231 // handler to be moved before the first.
1232 for (unsigned I = NumHandlers; I != 0; --I) {
1233 llvm::BasicBlock *CatchBlock = Handlers[I-1].Block;
1234 EmitBlockAfterUses(CatchBlock);
1236 // Catch the exception if this isn't a catch-all.
1237 const CXXCatchStmt *C = S.getHandler(I-1);
1239 // Enter a cleanup scope, including the catch variable and the
1241 RunCleanupsScope CatchScope(*this);
1243 // Initialize the catch variable and set up the cleanups.
1244 BeginCatch(*this, C);
1246 // If there's an implicit rethrow, push a normal "cleanup" to call
1247 // _cxa_rethrow. This needs to happen before __cxa_end_catch is
1248 // called, and so it is pushed after BeginCatch.
1249 if (ImplicitRethrow)
1250 EHStack.pushCleanup<CallRethrow>(NormalCleanup);
1252 // Perform the body of the catch.
1253 EmitStmt(C->getHandlerBlock());
1255 // Fall out through the catch cleanups.
1256 CatchScope.ForceCleanup();
1258 // Branch out of the try.
1259 if (HaveInsertPoint())
1260 Builder.CreateBr(ContBB);
1267 struct CallEndCatchForFinally : EHScopeStack::Cleanup {
1268 llvm::Value *ForEHVar;
1269 llvm::Value *EndCatchFn;
1270 CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn)
1271 : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
1273 void Emit(CodeGenFunction &CGF, Flags flags) {
1274 llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
1275 llvm::BasicBlock *CleanupContBB =
1276 CGF.createBasicBlock("finally.cleanup.cont");
1278 llvm::Value *ShouldEndCatch =
1279 CGF.Builder.CreateLoad(ForEHVar, "finally.endcatch");
1280 CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1281 CGF.EmitBlock(EndCatchBB);
1282 CGF.EmitCallOrInvoke(EndCatchFn); // catch-all, so might throw
1283 CGF.EmitBlock(CleanupContBB);
1287 struct PerformFinally : EHScopeStack::Cleanup {
1289 llvm::Value *ForEHVar;
1290 llvm::Value *EndCatchFn;
1291 llvm::Value *RethrowFn;
1292 llvm::Value *SavedExnVar;
1294 PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
1295 llvm::Value *EndCatchFn,
1296 llvm::Value *RethrowFn, llvm::Value *SavedExnVar)
1297 : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1298 RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
1300 void Emit(CodeGenFunction &CGF, Flags flags) {
1301 // Enter a cleanup to call the end-catch function if one was provided.
1303 CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
1304 ForEHVar, EndCatchFn);
1306 // Save the current cleanup destination in case there are
1307 // cleanups in the finally block.
1308 llvm::Value *SavedCleanupDest =
1309 CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
1310 "cleanup.dest.saved");
1312 // Emit the finally block.
1315 // If the end of the finally is reachable, check whether this was
1316 // for EH. If so, rethrow.
1317 if (CGF.HaveInsertPoint()) {
1318 llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
1319 llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
1321 llvm::Value *ShouldRethrow =
1322 CGF.Builder.CreateLoad(ForEHVar, "finally.shouldthrow");
1323 CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1325 CGF.EmitBlock(RethrowBB);
1327 CGF.EmitCallOrInvoke(RethrowFn, CGF.Builder.CreateLoad(SavedExnVar));
1329 CGF.EmitCallOrInvoke(RethrowFn);
1331 CGF.Builder.CreateUnreachable();
1333 CGF.EmitBlock(ContBB);
1335 // Restore the cleanup destination.
1336 CGF.Builder.CreateStore(SavedCleanupDest,
1337 CGF.getNormalCleanupDestSlot());
1340 // Leave the end-catch cleanup. As an optimization, pretend that
1341 // the fallthrough path was inaccessible; we've dynamically proven
1342 // that we're not in the EH case along that path.
1344 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1345 CGF.PopCleanupBlock();
1346 CGF.Builder.restoreIP(SavedIP);
1349 // Now make sure we actually have an insertion point or the
1350 // cleanup gods will hate us.
1351 CGF.EnsureInsertPoint();
1356 /// Enters a finally block for an implementation using zero-cost
1357 /// exceptions. This is mostly general, but hard-codes some
1358 /// language/ABI-specific behavior in the catch-all sections.
1359 void CodeGenFunction::FinallyInfo::enter(CodeGenFunction &CGF,
1361 llvm::Constant *beginCatchFn,
1362 llvm::Constant *endCatchFn,
1363 llvm::Constant *rethrowFn) {
1364 assert((beginCatchFn != 0) == (endCatchFn != 0) &&
1365 "begin/end catch functions not paired");
1366 assert(rethrowFn && "rethrow function is required");
1368 BeginCatchFn = beginCatchFn;
1370 // The rethrow function has one of the following two types:
1373 // In the latter case we need to pass it the exception object.
1374 // But we can't use the exception slot because the @finally might
1375 // have a landing pad (which would overwrite the exception slot).
1376 llvm::FunctionType *rethrowFnTy =
1377 cast<llvm::FunctionType>(
1378 cast<llvm::PointerType>(rethrowFn->getType())->getElementType());
1380 if (rethrowFnTy->getNumParams())
1381 SavedExnVar = CGF.CreateTempAlloca(CGF.Int8PtrTy, "finally.exn");
1383 // A finally block is a statement which must be executed on any edge
1384 // out of a given scope. Unlike a cleanup, the finally block may
1385 // contain arbitrary control flow leading out of itself. In
1386 // addition, finally blocks should always be executed, even if there
1387 // are no catch handlers higher on the stack. Therefore, we
1388 // surround the protected scope with a combination of a normal
1389 // cleanup (to catch attempts to break out of the block via normal
1390 // control flow) and an EH catch-all (semantically "outside" any try
1391 // statement to which the finally block might have been attached).
1392 // The finally block itself is generated in the context of a cleanup
1393 // which conditionally leaves the catch-all.
1395 // Jump destination for performing the finally block on an exception
1396 // edge. We'll never actually reach this block, so unreachable is
1398 RethrowDest = CGF.getJumpDestInCurrentScope(CGF.getUnreachableBlock());
1400 // Whether the finally block is being executed for EH purposes.
1401 ForEHVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "finally.for-eh");
1402 CGF.Builder.CreateStore(CGF.Builder.getFalse(), ForEHVar);
1404 // Enter a normal cleanup which will perform the @finally block.
1405 CGF.EHStack.pushCleanup<PerformFinally>(NormalCleanup, body,
1406 ForEHVar, endCatchFn,
1407 rethrowFn, SavedExnVar);
1409 // Enter a catch-all scope.
1410 llvm::BasicBlock *catchBB = CGF.createBasicBlock("finally.catchall");
1411 EHCatchScope *catchScope = CGF.EHStack.pushCatch(1);
1412 catchScope->setCatchAllHandler(0, catchBB);
1415 void CodeGenFunction::FinallyInfo::exit(CodeGenFunction &CGF) {
1416 // Leave the finally catch-all.
1417 EHCatchScope &catchScope = cast<EHCatchScope>(*CGF.EHStack.begin());
1418 llvm::BasicBlock *catchBB = catchScope.getHandler(0).Block;
1420 CGF.popCatchScope();
1422 // If there are any references to the catch-all block, emit it.
1423 if (catchBB->use_empty()) {
1426 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveAndClearIP();
1427 CGF.EmitBlock(catchBB);
1429 llvm::Value *exn = 0;
1431 // If there's a begin-catch function, call it.
1433 exn = CGF.getExceptionFromSlot();
1434 CGF.Builder.CreateCall(BeginCatchFn, exn)->setDoesNotThrow();
1437 // If we need to remember the exception pointer to rethrow later, do so.
1439 if (!exn) exn = CGF.getExceptionFromSlot();
1440 CGF.Builder.CreateStore(exn, SavedExnVar);
1443 // Tell the cleanups in the finally block that we're do this for EH.
1444 CGF.Builder.CreateStore(CGF.Builder.getTrue(), ForEHVar);
1446 // Thread a jump through the finally cleanup.
1447 CGF.EmitBranchThroughCleanup(RethrowDest);
1449 CGF.Builder.restoreIP(savedIP);
1452 // Finally, leave the @finally cleanup.
1453 CGF.PopCleanupBlock();
1456 llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
1457 if (TerminateLandingPad)
1458 return TerminateLandingPad;
1460 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1462 // This will get inserted at the end of the function.
1463 TerminateLandingPad = createBasicBlock("terminate.lpad");
1464 Builder.SetInsertPoint(TerminateLandingPad);
1466 // Tell the backend that this is a landing pad.
1467 const EHPersonality &Personality = EHPersonality::get(CGM.getLangOptions());
1468 llvm::LandingPadInst *LPadInst =
1469 Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, NULL),
1470 getOpaquePersonalityFn(CGM, Personality), 0);
1471 LPadInst->addClause(getCatchAllValue(*this));
1473 llvm::CallInst *TerminateCall = Builder.CreateCall(getTerminateFn(*this));
1474 TerminateCall->setDoesNotReturn();
1475 TerminateCall->setDoesNotThrow();
1476 Builder.CreateUnreachable();
1478 // Restore the saved insertion state.
1479 Builder.restoreIP(SavedIP);
1481 return TerminateLandingPad;
1484 llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
1485 if (TerminateHandler)
1486 return TerminateHandler;
1488 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1490 // Set up the terminate handler. This block is inserted at the very
1491 // end of the function by FinishFunction.
1492 TerminateHandler = createBasicBlock("terminate.handler");
1493 Builder.SetInsertPoint(TerminateHandler);
1494 llvm::CallInst *TerminateCall = Builder.CreateCall(getTerminateFn(*this));
1495 TerminateCall->setDoesNotReturn();
1496 TerminateCall->setDoesNotThrow();
1497 Builder.CreateUnreachable();
1499 // Restore the saved insertion state.
1500 Builder.restoreIP(SavedIP);
1502 return TerminateHandler;
1505 llvm::BasicBlock *CodeGenFunction::getEHResumeBlock() {
1506 if (EHResumeBlock) return EHResumeBlock;
1508 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1510 // We emit a jump to a notional label at the outermost unwind state.
1511 EHResumeBlock = createBasicBlock("eh.resume");
1512 Builder.SetInsertPoint(EHResumeBlock);
1514 const EHPersonality &Personality = EHPersonality::get(CGM.getLangOptions());
1516 // This can always be a call because we necessarily didn't find
1517 // anything on the EH stack which needs our help.
1518 StringRef RethrowName = Personality.getCatchallRethrowFnName();
1519 if (!RethrowName.empty()) {
1520 Builder.CreateCall(getCatchallRethrowFn(*this, RethrowName),
1521 getExceptionFromSlot())
1522 ->setDoesNotReturn();
1524 llvm::Value *Exn = getExceptionFromSlot();
1526 switch (CleanupHackLevel) {
1527 case CHL_MandatoryCatchall:
1528 // In mandatory-catchall mode, we need to use
1529 // _Unwind_Resume_or_Rethrow, or whatever the personality's
1531 Builder.CreateCall(getUnwindResumeOrRethrowFn(), Exn)
1532 ->setDoesNotReturn();
1534 case CHL_MandatoryCleanup: {
1535 // In mandatory-cleanup mode, we should use 'resume'.
1537 // Recreate the landingpad's return value for the 'resume' instruction.
1538 llvm::Value *Exn = getExceptionFromSlot();
1539 llvm::Value *Sel = getSelectorFromSlot();
1541 llvm::Type *LPadType = llvm::StructType::get(Exn->getType(),
1542 Sel->getType(), NULL);
1543 llvm::Value *LPadVal = llvm::UndefValue::get(LPadType);
1544 LPadVal = Builder.CreateInsertValue(LPadVal, Exn, 0, "lpad.val");
1545 LPadVal = Builder.CreateInsertValue(LPadVal, Sel, 1, "lpad.val");
1547 Builder.CreateResume(LPadVal);
1548 Builder.restoreIP(SavedIP);
1549 return EHResumeBlock;
1552 // In an idealized mode where we don't have to worry about the
1553 // optimizer combining landing pads, we should just use
1554 // _Unwind_Resume (or the personality's equivalent).
1555 Builder.CreateCall(getUnwindResumeFn(), Exn)
1556 ->setDoesNotReturn();
1561 Builder.CreateUnreachable();
1563 Builder.restoreIP(SavedIP);
1565 return EHResumeBlock;