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 "CodeGenFunction.h"
15 #include "CGCleanup.h"
16 #include "CGObjCRuntime.h"
17 #include "TargetInfo.h"
18 #include "clang/AST/StmtCXX.h"
19 #include "clang/AST/StmtObjC.h"
20 #include "llvm/IR/Intrinsics.h"
21 #include "llvm/Support/CallSite.h"
23 using namespace clang;
24 using namespace CodeGen;
26 static llvm::Constant *getAllocateExceptionFn(CodeGenModule &CGM) {
27 // void *__cxa_allocate_exception(size_t thrown_size);
29 llvm::FunctionType *FTy =
30 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.SizeTy, /*IsVarArgs=*/false);
32 return CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
35 static llvm::Constant *getFreeExceptionFn(CodeGenModule &CGM) {
36 // void __cxa_free_exception(void *thrown_exception);
38 llvm::FunctionType *FTy =
39 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
41 return CGM.CreateRuntimeFunction(FTy, "__cxa_free_exception");
44 static llvm::Constant *getThrowFn(CodeGenModule &CGM) {
45 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
46 // void (*dest) (void *));
48 llvm::Type *Args[3] = { CGM.Int8PtrTy, CGM.Int8PtrTy, CGM.Int8PtrTy };
49 llvm::FunctionType *FTy =
50 llvm::FunctionType::get(CGM.VoidTy, Args, /*IsVarArgs=*/false);
52 return CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
55 static llvm::Constant *getReThrowFn(CodeGenModule &CGM) {
56 // void __cxa_rethrow();
58 llvm::FunctionType *FTy =
59 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
61 return CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
64 static llvm::Constant *getGetExceptionPtrFn(CodeGenModule &CGM) {
65 // void *__cxa_get_exception_ptr(void*);
67 llvm::FunctionType *FTy =
68 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
70 return CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
73 static llvm::Constant *getBeginCatchFn(CodeGenModule &CGM) {
74 // void *__cxa_begin_catch(void*);
76 llvm::FunctionType *FTy =
77 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
79 return CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
82 static llvm::Constant *getEndCatchFn(CodeGenModule &CGM) {
83 // void __cxa_end_catch();
85 llvm::FunctionType *FTy =
86 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
88 return CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
91 static llvm::Constant *getUnexpectedFn(CodeGenModule &CGM) {
92 // void __cxa_call_unexpected(void *thrown_exception);
94 llvm::FunctionType *FTy =
95 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
97 return CGM.CreateRuntimeFunction(FTy, "__cxa_call_unexpected");
100 llvm::Constant *CodeGenFunction::getUnwindResumeFn() {
101 llvm::FunctionType *FTy =
102 llvm::FunctionType::get(VoidTy, Int8PtrTy, /*IsVarArgs=*/false);
104 if (CGM.getLangOpts().SjLjExceptions)
105 return CGM.CreateRuntimeFunction(FTy, "_Unwind_SjLj_Resume");
106 return CGM.CreateRuntimeFunction(FTy, "_Unwind_Resume");
109 llvm::Constant *CodeGenFunction::getUnwindResumeOrRethrowFn() {
110 llvm::FunctionType *FTy =
111 llvm::FunctionType::get(VoidTy, Int8PtrTy, /*IsVarArgs=*/false);
113 if (CGM.getLangOpts().SjLjExceptions)
114 return CGM.CreateRuntimeFunction(FTy, "_Unwind_SjLj_Resume_or_Rethrow");
115 return CGM.CreateRuntimeFunction(FTy, "_Unwind_Resume_or_Rethrow");
118 static llvm::Constant *getTerminateFn(CodeGenModule &CGM) {
119 // void __terminate();
121 llvm::FunctionType *FTy =
122 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
126 // In C++, use std::terminate().
127 if (CGM.getLangOpts().CPlusPlus)
128 name = "_ZSt9terminatev"; // FIXME: mangling!
129 else if (CGM.getLangOpts().ObjC1 &&
130 CGM.getLangOpts().ObjCRuntime.hasTerminate())
131 name = "objc_terminate";
134 return CGM.CreateRuntimeFunction(FTy, name);
137 static llvm::Constant *getCatchallRethrowFn(CodeGenModule &CGM,
139 llvm::FunctionType *FTy =
140 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
142 return CGM.CreateRuntimeFunction(FTy, Name);
146 /// The exceptions personality for a function.
147 struct EHPersonality {
148 const char *PersonalityFn;
150 // If this is non-null, this personality requires a non-standard
151 // function for rethrowing an exception after a catchall cleanup.
152 // This function must have prototype void(void*).
153 const char *CatchallRethrowFn;
155 static const EHPersonality &get(const LangOptions &Lang);
156 static const EHPersonality GNU_C;
157 static const EHPersonality GNU_C_SJLJ;
158 static const EHPersonality GNU_ObjC;
159 static const EHPersonality GNUstep_ObjC;
160 static const EHPersonality GNU_ObjCXX;
161 static const EHPersonality NeXT_ObjC;
162 static const EHPersonality GNU_CPlusPlus;
163 static const EHPersonality GNU_CPlusPlus_SJLJ;
167 const EHPersonality EHPersonality::GNU_C = { "__gcc_personality_v0", 0 };
168 const EHPersonality EHPersonality::GNU_C_SJLJ = { "__gcc_personality_sj0", 0 };
169 const EHPersonality EHPersonality::NeXT_ObjC = { "__objc_personality_v0", 0 };
170 const EHPersonality EHPersonality::GNU_CPlusPlus = { "__gxx_personality_v0", 0};
172 EHPersonality::GNU_CPlusPlus_SJLJ = { "__gxx_personality_sj0", 0 };
174 EHPersonality::GNU_ObjC = {"__gnu_objc_personality_v0", "objc_exception_throw"};
176 EHPersonality::GNU_ObjCXX = { "__gnustep_objcxx_personality_v0", 0 };
178 EHPersonality::GNUstep_ObjC = { "__gnustep_objc_personality_v0", 0 };
180 static const EHPersonality &getCPersonality(const LangOptions &L) {
181 if (L.SjLjExceptions)
182 return EHPersonality::GNU_C_SJLJ;
183 return EHPersonality::GNU_C;
186 static const EHPersonality &getObjCPersonality(const LangOptions &L) {
187 switch (L.ObjCRuntime.getKind()) {
188 case ObjCRuntime::FragileMacOSX:
189 return getCPersonality(L);
190 case ObjCRuntime::MacOSX:
191 case ObjCRuntime::iOS:
192 return EHPersonality::NeXT_ObjC;
193 case ObjCRuntime::GNUstep:
194 if (L.ObjCRuntime.getVersion() >= VersionTuple(1, 7))
195 return EHPersonality::GNUstep_ObjC;
197 case ObjCRuntime::GCC:
198 case ObjCRuntime::ObjFW:
199 return EHPersonality::GNU_ObjC;
201 llvm_unreachable("bad runtime kind");
204 static const EHPersonality &getCXXPersonality(const LangOptions &L) {
205 if (L.SjLjExceptions)
206 return EHPersonality::GNU_CPlusPlus_SJLJ;
208 return EHPersonality::GNU_CPlusPlus;
211 /// Determines the personality function to use when both C++
212 /// and Objective-C exceptions are being caught.
213 static const EHPersonality &getObjCXXPersonality(const LangOptions &L) {
214 switch (L.ObjCRuntime.getKind()) {
215 // The ObjC personality defers to the C++ personality for non-ObjC
216 // handlers. Unlike the C++ case, we use the same personality
217 // function on targets using (backend-driven) SJLJ EH.
218 case ObjCRuntime::MacOSX:
219 case ObjCRuntime::iOS:
220 return EHPersonality::NeXT_ObjC;
222 // In the fragile ABI, just use C++ exception handling and hope
223 // they're not doing crazy exception mixing.
224 case ObjCRuntime::FragileMacOSX:
225 return getCXXPersonality(L);
227 // The GCC runtime's personality function inherently doesn't support
228 // mixed EH. Use the C++ personality just to avoid returning null.
229 case ObjCRuntime::GCC:
230 case ObjCRuntime::ObjFW: // XXX: this will change soon
231 return EHPersonality::GNU_ObjC;
232 case ObjCRuntime::GNUstep:
233 return EHPersonality::GNU_ObjCXX;
235 llvm_unreachable("bad runtime kind");
238 const EHPersonality &EHPersonality::get(const LangOptions &L) {
239 if (L.CPlusPlus && L.ObjC1)
240 return getObjCXXPersonality(L);
241 else if (L.CPlusPlus)
242 return getCXXPersonality(L);
244 return getObjCPersonality(L);
246 return getCPersonality(L);
249 static llvm::Constant *getPersonalityFn(CodeGenModule &CGM,
250 const EHPersonality &Personality) {
252 CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.Int32Ty, true),
253 Personality.PersonalityFn);
257 static llvm::Constant *getOpaquePersonalityFn(CodeGenModule &CGM,
258 const EHPersonality &Personality) {
259 llvm::Constant *Fn = getPersonalityFn(CGM, Personality);
260 return llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
263 /// Check whether a personality function could reasonably be swapped
264 /// for a C++ personality function.
265 static bool PersonalityHasOnlyCXXUses(llvm::Constant *Fn) {
266 for (llvm::Constant::use_iterator
267 I = Fn->use_begin(), E = Fn->use_end(); I != E; ++I) {
268 llvm::User *User = *I;
270 // Conditionally white-list bitcasts.
271 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(User)) {
272 if (CE->getOpcode() != llvm::Instruction::BitCast) return false;
273 if (!PersonalityHasOnlyCXXUses(CE))
278 // Otherwise, it has to be a landingpad instruction.
279 llvm::LandingPadInst *LPI = dyn_cast<llvm::LandingPadInst>(User);
280 if (!LPI) return false;
282 for (unsigned I = 0, E = LPI->getNumClauses(); I != E; ++I) {
283 // Look for something that would've been returned by the ObjC
284 // runtime's GetEHType() method.
285 llvm::Value *Val = LPI->getClause(I)->stripPointerCasts();
286 if (LPI->isCatch(I)) {
287 // Check if the catch value has the ObjC prefix.
288 if (llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Val))
289 // ObjC EH selector entries are always global variables with
290 // names starting like this.
291 if (GV->getName().startswith("OBJC_EHTYPE"))
294 // Check if any of the filter values have the ObjC prefix.
295 llvm::Constant *CVal = cast<llvm::Constant>(Val);
296 for (llvm::User::op_iterator
297 II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II) {
298 if (llvm::GlobalVariable *GV =
299 cast<llvm::GlobalVariable>((*II)->stripPointerCasts()))
300 // ObjC EH selector entries are always global variables with
301 // names starting like this.
302 if (GV->getName().startswith("OBJC_EHTYPE"))
312 /// Try to use the C++ personality function in ObjC++. Not doing this
313 /// can cause some incompatibilities with gcc, which is more
314 /// aggressive about only using the ObjC++ personality in a function
315 /// when it really needs it.
316 void CodeGenModule::SimplifyPersonality() {
317 // If we're not in ObjC++ -fexceptions, there's nothing to do.
318 if (!LangOpts.CPlusPlus || !LangOpts.ObjC1 || !LangOpts.Exceptions)
321 // Both the problem this endeavors to fix and the way the logic
322 // above works is specific to the NeXT runtime.
323 if (!LangOpts.ObjCRuntime.isNeXTFamily())
326 const EHPersonality &ObjCXX = EHPersonality::get(LangOpts);
327 const EHPersonality &CXX = getCXXPersonality(LangOpts);
331 assert(std::strcmp(ObjCXX.PersonalityFn, CXX.PersonalityFn) != 0 &&
332 "Different EHPersonalities using the same personality function.");
334 llvm::Function *Fn = getModule().getFunction(ObjCXX.PersonalityFn);
336 // Nothing to do if it's unused.
337 if (!Fn || Fn->use_empty()) return;
339 // Can't do the optimization if it has non-C++ uses.
340 if (!PersonalityHasOnlyCXXUses(Fn)) return;
342 // Create the C++ personality function and kill off the old
344 llvm::Constant *CXXFn = getPersonalityFn(*this, CXX);
346 // This can happen if the user is screwing with us.
347 if (Fn->getType() != CXXFn->getType()) return;
349 Fn->replaceAllUsesWith(CXXFn);
350 Fn->eraseFromParent();
353 /// Returns the value to inject into a selector to indicate the
354 /// presence of a catch-all.
355 static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
356 // Possibly we should use @llvm.eh.catch.all.value here.
357 return llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
361 /// A cleanup to free the exception object if its initialization
363 struct FreeException : EHScopeStack::Cleanup {
365 FreeException(llvm::Value *exn) : exn(exn) {}
366 void Emit(CodeGenFunction &CGF, Flags flags) {
367 CGF.EmitNounwindRuntimeCall(getFreeExceptionFn(CGF.CGM), exn);
372 // Emits an exception expression into the given location. This
373 // differs from EmitAnyExprToMem only in that, if a final copy-ctor
374 // call is required, an exception within that copy ctor causes
375 // std::terminate to be invoked.
376 static void EmitAnyExprToExn(CodeGenFunction &CGF, const Expr *e,
378 // Make sure the exception object is cleaned up if there's an
379 // exception during initialization.
380 CGF.pushFullExprCleanup<FreeException>(EHCleanup, addr);
381 EHScopeStack::stable_iterator cleanup = CGF.EHStack.stable_begin();
383 // __cxa_allocate_exception returns a void*; we need to cast this
384 // to the appropriate type for the object.
385 llvm::Type *ty = CGF.ConvertTypeForMem(e->getType())->getPointerTo();
386 llvm::Value *typedAddr = CGF.Builder.CreateBitCast(addr, ty);
388 // FIXME: this isn't quite right! If there's a final unelided call
389 // to a copy constructor, then according to [except.terminate]p1 we
390 // must call std::terminate() if that constructor throws, because
391 // technically that copy occurs after the exception expression is
392 // evaluated but before the exception is caught. But the best way
393 // to handle that is to teach EmitAggExpr to do the final copy
394 // differently if it can't be elided.
395 CGF.EmitAnyExprToMem(e, typedAddr, e->getType().getQualifiers(),
398 // Deactivate the cleanup block.
399 CGF.DeactivateCleanupBlock(cleanup, cast<llvm::Instruction>(typedAddr));
402 llvm::Value *CodeGenFunction::getExceptionSlot() {
404 ExceptionSlot = CreateTempAlloca(Int8PtrTy, "exn.slot");
405 return ExceptionSlot;
408 llvm::Value *CodeGenFunction::getEHSelectorSlot() {
410 EHSelectorSlot = CreateTempAlloca(Int32Ty, "ehselector.slot");
411 return EHSelectorSlot;
414 llvm::Value *CodeGenFunction::getExceptionFromSlot() {
415 return Builder.CreateLoad(getExceptionSlot(), "exn");
418 llvm::Value *CodeGenFunction::getSelectorFromSlot() {
419 return Builder.CreateLoad(getEHSelectorSlot(), "sel");
422 void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E,
423 bool KeepInsertionPoint) {
424 if (!E->getSubExpr()) {
425 EmitNoreturnRuntimeCallOrInvoke(getReThrowFn(CGM),
426 ArrayRef<llvm::Value*>());
428 // throw is an expression, and the expression emitters expect us
429 // to leave ourselves at a valid insertion point.
430 if (KeepInsertionPoint)
431 EmitBlock(createBasicBlock("throw.cont"));
436 QualType ThrowType = E->getSubExpr()->getType();
438 if (ThrowType->isObjCObjectPointerType()) {
439 const Stmt *ThrowStmt = E->getSubExpr();
440 const ObjCAtThrowStmt S(E->getExprLoc(),
441 const_cast<Stmt *>(ThrowStmt));
442 CGM.getObjCRuntime().EmitThrowStmt(*this, S, false);
443 // This will clear insertion point which was not cleared in
444 // call to EmitThrowStmt.
445 if (KeepInsertionPoint)
446 EmitBlock(createBasicBlock("throw.cont"));
450 // Now allocate the exception object.
451 llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
452 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
454 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(CGM);
455 llvm::CallInst *ExceptionPtr =
456 EmitNounwindRuntimeCall(AllocExceptionFn,
457 llvm::ConstantInt::get(SizeTy, TypeSize),
460 EmitAnyExprToExn(*this, E->getSubExpr(), ExceptionPtr);
462 // Now throw the exception.
463 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
466 // The address of the destructor. If the exception type has a
467 // trivial destructor (or isn't a record), we just pass null.
468 llvm::Constant *Dtor = 0;
469 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
470 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
471 if (!Record->hasTrivialDestructor()) {
472 CXXDestructorDecl *DtorD = Record->getDestructor();
473 Dtor = CGM.GetAddrOfCXXDestructor(DtorD, Dtor_Complete);
474 Dtor = llvm::ConstantExpr::getBitCast(Dtor, Int8PtrTy);
477 if (!Dtor) Dtor = llvm::Constant::getNullValue(Int8PtrTy);
479 llvm::Value *args[] = { ExceptionPtr, TypeInfo, Dtor };
480 EmitNoreturnRuntimeCallOrInvoke(getThrowFn(CGM), args);
482 // throw is an expression, and the expression emitters expect us
483 // to leave ourselves at a valid insertion point.
484 if (KeepInsertionPoint)
485 EmitBlock(createBasicBlock("throw.cont"));
488 void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
489 if (!CGM.getLangOpts().CXXExceptions)
492 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
495 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
499 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
500 if (isNoexceptExceptionSpec(EST)) {
501 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
502 // noexcept functions are simple terminate scopes.
503 EHStack.pushTerminate();
505 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
506 unsigned NumExceptions = Proto->getNumExceptions();
507 EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
509 for (unsigned I = 0; I != NumExceptions; ++I) {
510 QualType Ty = Proto->getExceptionType(I);
511 QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
512 llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType,
514 Filter->setFilter(I, EHType);
519 /// Emit the dispatch block for a filter scope if necessary.
520 static void emitFilterDispatchBlock(CodeGenFunction &CGF,
521 EHFilterScope &filterScope) {
522 llvm::BasicBlock *dispatchBlock = filterScope.getCachedEHDispatchBlock();
523 if (!dispatchBlock) return;
524 if (dispatchBlock->use_empty()) {
525 delete dispatchBlock;
529 CGF.EmitBlockAfterUses(dispatchBlock);
531 // If this isn't a catch-all filter, we need to check whether we got
532 // here because the filter triggered.
533 if (filterScope.getNumFilters()) {
534 // Load the selector value.
535 llvm::Value *selector = CGF.getSelectorFromSlot();
536 llvm::BasicBlock *unexpectedBB = CGF.createBasicBlock("ehspec.unexpected");
538 llvm::Value *zero = CGF.Builder.getInt32(0);
539 llvm::Value *failsFilter =
540 CGF.Builder.CreateICmpSLT(selector, zero, "ehspec.fails");
541 CGF.Builder.CreateCondBr(failsFilter, unexpectedBB, CGF.getEHResumeBlock(false));
543 CGF.EmitBlock(unexpectedBB);
546 // Call __cxa_call_unexpected. This doesn't need to be an invoke
547 // because __cxa_call_unexpected magically filters exceptions
548 // according to the last landing pad the exception was thrown
550 llvm::Value *exn = CGF.getExceptionFromSlot();
551 CGF.EmitRuntimeCall(getUnexpectedFn(CGF.CGM), exn)
552 ->setDoesNotReturn();
553 CGF.Builder.CreateUnreachable();
556 void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
557 if (!CGM.getLangOpts().CXXExceptions)
560 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
563 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
567 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
568 if (isNoexceptExceptionSpec(EST)) {
569 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
570 EHStack.popTerminate();
572 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
573 EHFilterScope &filterScope = cast<EHFilterScope>(*EHStack.begin());
574 emitFilterDispatchBlock(*this, filterScope);
579 void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
581 EmitStmt(S.getTryBlock());
585 void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
586 unsigned NumHandlers = S.getNumHandlers();
587 EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
589 for (unsigned I = 0; I != NumHandlers; ++I) {
590 const CXXCatchStmt *C = S.getHandler(I);
592 llvm::BasicBlock *Handler = createBasicBlock("catch");
593 if (C->getExceptionDecl()) {
594 // FIXME: Dropping the reference type on the type into makes it
595 // impossible to correctly implement catch-by-reference
596 // semantics for pointers. Unfortunately, this is what all
597 // existing compilers do, and it's not clear that the standard
598 // personality routine is capable of doing this right. See C++ DR 388:
599 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
600 QualType CaughtType = C->getCaughtType();
601 CaughtType = CaughtType.getNonReferenceType().getUnqualifiedType();
603 llvm::Value *TypeInfo = 0;
604 if (CaughtType->isObjCObjectPointerType())
605 TypeInfo = CGM.getObjCRuntime().GetEHType(CaughtType);
607 TypeInfo = CGM.GetAddrOfRTTIDescriptor(CaughtType, /*ForEH=*/true);
608 CatchScope->setHandler(I, TypeInfo, Handler);
610 // No exception decl indicates '...', a catch-all.
611 CatchScope->setCatchAllHandler(I, Handler);
617 CodeGenFunction::getEHDispatchBlock(EHScopeStack::stable_iterator si) {
618 // The dispatch block for the end of the scope chain is a block that
619 // just resumes unwinding.
620 if (si == EHStack.stable_end())
621 return getEHResumeBlock(true);
623 // Otherwise, we should look at the actual scope.
624 EHScope &scope = *EHStack.find(si);
626 llvm::BasicBlock *dispatchBlock = scope.getCachedEHDispatchBlock();
627 if (!dispatchBlock) {
628 switch (scope.getKind()) {
629 case EHScope::Catch: {
630 // Apply a special case to a single catch-all.
631 EHCatchScope &catchScope = cast<EHCatchScope>(scope);
632 if (catchScope.getNumHandlers() == 1 &&
633 catchScope.getHandler(0).isCatchAll()) {
634 dispatchBlock = catchScope.getHandler(0).Block;
636 // Otherwise, make a dispatch block.
638 dispatchBlock = createBasicBlock("catch.dispatch");
643 case EHScope::Cleanup:
644 dispatchBlock = createBasicBlock("ehcleanup");
647 case EHScope::Filter:
648 dispatchBlock = createBasicBlock("filter.dispatch");
651 case EHScope::Terminate:
652 dispatchBlock = getTerminateHandler();
655 scope.setCachedEHDispatchBlock(dispatchBlock);
657 return dispatchBlock;
660 /// Check whether this is a non-EH scope, i.e. a scope which doesn't
661 /// affect exception handling. Currently, the only non-EH scopes are
662 /// normal-only cleanup scopes.
663 static bool isNonEHScope(const EHScope &S) {
664 switch (S.getKind()) {
665 case EHScope::Cleanup:
666 return !cast<EHCleanupScope>(S).isEHCleanup();
667 case EHScope::Filter:
669 case EHScope::Terminate:
673 llvm_unreachable("Invalid EHScope Kind!");
676 llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
677 assert(EHStack.requiresLandingPad());
678 assert(!EHStack.empty());
680 if (!CGM.getLangOpts().Exceptions)
683 // Check the innermost scope for a cached landing pad. If this is
684 // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
685 llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
688 // Build the landing pad for this scope.
689 LP = EmitLandingPad();
692 // Cache the landing pad on the innermost scope. If this is a
693 // non-EH scope, cache the landing pad on the enclosing scope, too.
694 for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
695 ir->setCachedLandingPad(LP);
696 if (!isNonEHScope(*ir)) break;
702 // This code contains a hack to work around a design flaw in
703 // LLVM's EH IR which breaks semantics after inlining. This same
704 // hack is implemented in llvm-gcc.
706 // The LLVM EH abstraction is basically a thin veneer over the
707 // traditional GCC zero-cost design: for each range of instructions
708 // in the function, there is (at most) one "landing pad" with an
709 // associated chain of EH actions. A language-specific personality
710 // function interprets this chain of actions and (1) decides whether
711 // or not to resume execution at the landing pad and (2) if so,
712 // provides an integer indicating why it's stopping. In LLVM IR,
713 // the association of a landing pad with a range of instructions is
714 // achieved via an invoke instruction, the chain of actions becomes
715 // the arguments to the @llvm.eh.selector call, and the selector
716 // call returns the integer indicator. Other than the required
717 // presence of two intrinsic function calls in the landing pad,
718 // the IR exactly describes the layout of the output code.
720 // A principal advantage of this design is that it is completely
721 // language-agnostic; in theory, the LLVM optimizers can treat
722 // landing pads neutrally, and targets need only know how to lower
723 // the intrinsics to have a functioning exceptions system (assuming
724 // that platform exceptions follow something approximately like the
725 // GCC design). Unfortunately, landing pads cannot be combined in a
726 // language-agnostic way: given selectors A and B, there is no way
727 // to make a single landing pad which faithfully represents the
728 // semantics of propagating an exception first through A, then
729 // through B, without knowing how the personality will interpret the
730 // (lowered form of the) selectors. This means that inlining has no
731 // choice but to crudely chain invokes (i.e., to ignore invokes in
732 // the inlined function, but to turn all unwindable calls into
733 // invokes), which is only semantically valid if every unwind stops
734 // at every landing pad.
736 // Therefore, the invoke-inline hack is to guarantee that every
737 // landing pad has a catch-all.
738 enum CleanupHackLevel_t {
739 /// A level of hack that requires that all landing pads have
741 CHL_MandatoryCatchall,
743 /// A level of hack that requires that all landing pads handle
745 CHL_MandatoryCleanup,
747 /// No hacks at all; ideal IR generation.
750 const CleanupHackLevel_t CleanupHackLevel = CHL_MandatoryCleanup;
752 llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
753 assert(EHStack.requiresLandingPad());
755 EHScope &innermostEHScope = *EHStack.find(EHStack.getInnermostEHScope());
756 switch (innermostEHScope.getKind()) {
757 case EHScope::Terminate:
758 return getTerminateLandingPad();
761 case EHScope::Cleanup:
762 case EHScope::Filter:
763 if (llvm::BasicBlock *lpad = innermostEHScope.getCachedLandingPad())
767 // Save the current IR generation state.
768 CGBuilderTy::InsertPoint savedIP = Builder.saveAndClearIP();
769 SourceLocation SavedLocation;
770 if (CGDebugInfo *DI = getDebugInfo()) {
771 SavedLocation = DI->getLocation();
772 DI->EmitLocation(Builder, CurEHLocation);
775 const EHPersonality &personality = EHPersonality::get(getLangOpts());
777 // Create and configure the landing pad.
778 llvm::BasicBlock *lpad = createBasicBlock("lpad");
781 llvm::LandingPadInst *LPadInst =
782 Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, NULL),
783 getOpaquePersonalityFn(CGM, personality), 0);
785 llvm::Value *LPadExn = Builder.CreateExtractValue(LPadInst, 0);
786 Builder.CreateStore(LPadExn, getExceptionSlot());
787 llvm::Value *LPadSel = Builder.CreateExtractValue(LPadInst, 1);
788 Builder.CreateStore(LPadSel, getEHSelectorSlot());
790 // Save the exception pointer. It's safe to use a single exception
791 // pointer per function because EH cleanups can never have nested
793 // Build the landingpad instruction.
795 // Accumulate all the handlers in scope.
796 bool hasCatchAll = false;
797 bool hasCleanup = false;
798 bool hasFilter = false;
799 SmallVector<llvm::Value*, 4> filterTypes;
800 llvm::SmallPtrSet<llvm::Value*, 4> catchTypes;
801 for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end();
804 switch (I->getKind()) {
805 case EHScope::Cleanup:
806 // If we have a cleanup, remember that.
807 hasCleanup = (hasCleanup || cast<EHCleanupScope>(*I).isEHCleanup());
810 case EHScope::Filter: {
811 assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
812 assert(!hasCatchAll && "EH filter reached after catch-all");
814 // Filter scopes get added to the landingpad in weird ways.
815 EHFilterScope &filter = cast<EHFilterScope>(*I);
818 // Add all the filter values.
819 for (unsigned i = 0, e = filter.getNumFilters(); i != e; ++i)
820 filterTypes.push_back(filter.getFilter(i));
824 case EHScope::Terminate:
825 // Terminate scopes are basically catch-alls.
826 assert(!hasCatchAll);
834 EHCatchScope &catchScope = cast<EHCatchScope>(*I);
835 for (unsigned hi = 0, he = catchScope.getNumHandlers(); hi != he; ++hi) {
836 EHCatchScope::Handler handler = catchScope.getHandler(hi);
838 // If this is a catch-all, register that and abort.
840 assert(!hasCatchAll);
845 // Check whether we already have a handler for this type.
846 if (catchTypes.insert(handler.Type))
847 // If not, add it directly to the landingpad.
848 LPadInst->addClause(handler.Type);
853 // If we have a catch-all, add null to the landingpad.
854 assert(!(hasCatchAll && hasFilter));
856 LPadInst->addClause(getCatchAllValue(*this));
858 // If we have an EH filter, we need to add those handlers in the
859 // right place in the landingpad, which is to say, at the end.
860 } else if (hasFilter) {
861 // Create a filter expression: a constant array indicating which filter
862 // types there are. The personality routine only lands here if the filter
864 SmallVector<llvm::Constant*, 8> Filters;
865 llvm::ArrayType *AType =
866 llvm::ArrayType::get(!filterTypes.empty() ?
867 filterTypes[0]->getType() : Int8PtrTy,
870 for (unsigned i = 0, e = filterTypes.size(); i != e; ++i)
871 Filters.push_back(cast<llvm::Constant>(filterTypes[i]));
872 llvm::Constant *FilterArray = llvm::ConstantArray::get(AType, Filters);
873 LPadInst->addClause(FilterArray);
875 // Also check whether we need a cleanup.
877 LPadInst->setCleanup(true);
879 // Otherwise, signal that we at least have cleanups.
880 } else if (CleanupHackLevel == CHL_MandatoryCatchall || hasCleanup) {
881 if (CleanupHackLevel == CHL_MandatoryCatchall)
882 LPadInst->addClause(getCatchAllValue(*this));
884 LPadInst->setCleanup(true);
887 assert((LPadInst->getNumClauses() > 0 || LPadInst->isCleanup()) &&
888 "landingpad instruction has no clauses!");
890 // Tell the backend how to generate the landing pad.
891 Builder.CreateBr(getEHDispatchBlock(EHStack.getInnermostEHScope()));
893 // Restore the old IR generation state.
894 Builder.restoreIP(savedIP);
895 if (CGDebugInfo *DI = getDebugInfo())
896 DI->EmitLocation(Builder, SavedLocation);
902 /// A cleanup to call __cxa_end_catch. In many cases, the caught
903 /// exception type lets us state definitively that the thrown exception
904 /// type does not have a destructor. In particular:
905 /// - Catch-alls tell us nothing, so we have to conservatively
906 /// assume that the thrown exception might have a destructor.
907 /// - Catches by reference behave according to their base types.
908 /// - Catches of non-record types will only trigger for exceptions
909 /// of non-record types, which never have destructors.
910 /// - Catches of record types can trigger for arbitrary subclasses
911 /// of the caught type, so we have to assume the actual thrown
912 /// exception type might have a throwing destructor, even if the
913 /// caught type's destructor is trivial or nothrow.
914 struct CallEndCatch : EHScopeStack::Cleanup {
915 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
918 void Emit(CodeGenFunction &CGF, Flags flags) {
920 CGF.EmitNounwindRuntimeCall(getEndCatchFn(CGF.CGM));
924 CGF.EmitRuntimeCallOrInvoke(getEndCatchFn(CGF.CGM));
929 /// Emits a call to __cxa_begin_catch and enters a cleanup to call
932 /// \param EndMightThrow - true if __cxa_end_catch might throw
933 static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
935 bool EndMightThrow) {
936 llvm::CallInst *call =
937 CGF.EmitNounwindRuntimeCall(getBeginCatchFn(CGF.CGM), Exn);
939 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
944 /// A "special initializer" callback for initializing a catch
945 /// parameter during catch initialization.
946 static void InitCatchParam(CodeGenFunction &CGF,
947 const VarDecl &CatchParam,
948 llvm::Value *ParamAddr,
949 SourceLocation Loc) {
950 // Load the exception from where the landing pad saved it.
951 llvm::Value *Exn = CGF.getExceptionFromSlot();
953 CanQualType CatchType =
954 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
955 llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
957 // If we're catching by reference, we can just cast the object
958 // pointer to the appropriate pointer.
959 if (isa<ReferenceType>(CatchType)) {
960 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
961 bool EndCatchMightThrow = CaughtType->isRecordType();
963 // __cxa_begin_catch returns the adjusted object pointer.
964 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
966 // We have no way to tell the personality function that we're
967 // catching by reference, so if we're catching a pointer,
968 // __cxa_begin_catch will actually return that pointer by value.
969 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
970 QualType PointeeType = PT->getPointeeType();
972 // When catching by reference, generally we should just ignore
973 // this by-value pointer and use the exception object instead.
974 if (!PointeeType->isRecordType()) {
976 // Exn points to the struct _Unwind_Exception header, which
977 // we have to skip past in order to reach the exception data.
978 unsigned HeaderSize =
979 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
980 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
982 // However, if we're catching a pointer-to-record type that won't
983 // work, because the personality function might have adjusted
984 // the pointer. There's actually no way for us to fully satisfy
985 // the language/ABI contract here: we can't use Exn because it
986 // might have the wrong adjustment, but we can't use the by-value
987 // pointer because it's off by a level of abstraction.
989 // The current solution is to dump the adjusted pointer into an
990 // alloca, which breaks language semantics (because changing the
991 // pointer doesn't change the exception) but at least works.
992 // The better solution would be to filter out non-exact matches
993 // and rethrow them, but this is tricky because the rethrow
994 // really needs to be catchable by other sites at this landing
995 // pad. The best solution is to fix the personality function.
997 // Pull the pointer for the reference type off.
999 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
1001 // Create the temporary and write the adjusted pointer into it.
1002 llvm::Value *ExnPtrTmp = CGF.CreateTempAlloca(PtrTy, "exn.byref.tmp");
1003 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1004 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
1006 // Bind the reference to the temporary.
1007 AdjustedExn = ExnPtrTmp;
1011 llvm::Value *ExnCast =
1012 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
1013 CGF.Builder.CreateStore(ExnCast, ParamAddr);
1017 // Scalars and complexes.
1018 TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType);
1019 if (TEK != TEK_Aggregate) {
1020 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
1022 // If the catch type is a pointer type, __cxa_begin_catch returns
1023 // the pointer by value.
1024 if (CatchType->hasPointerRepresentation()) {
1025 llvm::Value *CastExn =
1026 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
1028 switch (CatchType.getQualifiers().getObjCLifetime()) {
1029 case Qualifiers::OCL_Strong:
1030 CastExn = CGF.EmitARCRetainNonBlock(CastExn);
1033 case Qualifiers::OCL_None:
1034 case Qualifiers::OCL_ExplicitNone:
1035 case Qualifiers::OCL_Autoreleasing:
1036 CGF.Builder.CreateStore(CastExn, ParamAddr);
1039 case Qualifiers::OCL_Weak:
1040 CGF.EmitARCInitWeak(ParamAddr, CastExn);
1043 llvm_unreachable("bad ownership qualifier!");
1046 // Otherwise, it returns a pointer into the exception object.
1048 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
1049 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1051 LValue srcLV = CGF.MakeNaturalAlignAddrLValue(Cast, CatchType);
1052 LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType,
1053 CGF.getContext().getDeclAlign(&CatchParam));
1056 CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV,
1060 llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc);
1061 CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true);
1065 llvm_unreachable("evaluation kind filtered out!");
1067 llvm_unreachable("bad evaluation kind");
1070 assert(isa<RecordType>(CatchType) && "unexpected catch type!");
1072 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
1074 // Check for a copy expression. If we don't have a copy expression,
1075 // that means a trivial copy is okay.
1076 const Expr *copyExpr = CatchParam.getInit();
1078 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
1079 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
1080 CGF.EmitAggregateCopy(ParamAddr, adjustedExn, CatchType);
1084 // We have to call __cxa_get_exception_ptr to get the adjusted
1085 // pointer before copying.
1086 llvm::CallInst *rawAdjustedExn =
1087 CGF.EmitNounwindRuntimeCall(getGetExceptionPtrFn(CGF.CGM), Exn);
1089 // Cast that to the appropriate type.
1090 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
1092 // The copy expression is defined in terms of an OpaqueValueExpr.
1093 // Find it and map it to the adjusted expression.
1094 CodeGenFunction::OpaqueValueMapping
1095 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
1096 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
1098 // Call the copy ctor in a terminate scope.
1099 CGF.EHStack.pushTerminate();
1101 // Perform the copy construction.
1102 CharUnits Alignment = CGF.getContext().getDeclAlign(&CatchParam);
1103 CGF.EmitAggExpr(copyExpr,
1104 AggValueSlot::forAddr(ParamAddr, Alignment, Qualifiers(),
1105 AggValueSlot::IsNotDestructed,
1106 AggValueSlot::DoesNotNeedGCBarriers,
1107 AggValueSlot::IsNotAliased));
1109 // Leave the terminate scope.
1110 CGF.EHStack.popTerminate();
1112 // Undo the opaque value mapping.
1115 // Finally we can call __cxa_begin_catch.
1116 CallBeginCatch(CGF, Exn, true);
1119 /// Begins a catch statement by initializing the catch variable and
1120 /// calling __cxa_begin_catch.
1121 static void BeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *S) {
1122 // We have to be very careful with the ordering of cleanups here:
1123 // C++ [except.throw]p4:
1124 // The destruction [of the exception temporary] occurs
1125 // immediately after the destruction of the object declared in
1126 // the exception-declaration in the handler.
1128 // So the precise ordering is:
1129 // 1. Construct catch variable.
1130 // 2. __cxa_begin_catch
1131 // 3. Enter __cxa_end_catch cleanup
1132 // 4. Enter dtor cleanup
1134 // We do this by using a slightly abnormal initialization process.
1135 // Delegation sequence:
1136 // - ExitCXXTryStmt opens a RunCleanupsScope
1137 // - EmitAutoVarAlloca creates the variable and debug info
1138 // - InitCatchParam initializes the variable from the exception
1139 // - CallBeginCatch calls __cxa_begin_catch
1140 // - CallBeginCatch enters the __cxa_end_catch cleanup
1141 // - EmitAutoVarCleanups enters the variable destructor cleanup
1142 // - EmitCXXTryStmt emits the code for the catch body
1143 // - EmitCXXTryStmt close the RunCleanupsScope
1145 VarDecl *CatchParam = S->getExceptionDecl();
1147 llvm::Value *Exn = CGF.getExceptionFromSlot();
1148 CallBeginCatch(CGF, Exn, true);
1153 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
1154 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF), S->getLocStart());
1155 CGF.EmitAutoVarCleanups(var);
1158 /// Emit the structure of the dispatch block for the given catch scope.
1159 /// It is an invariant that the dispatch block already exists.
1160 static void emitCatchDispatchBlock(CodeGenFunction &CGF,
1161 EHCatchScope &catchScope) {
1162 llvm::BasicBlock *dispatchBlock = catchScope.getCachedEHDispatchBlock();
1163 assert(dispatchBlock);
1165 // If there's only a single catch-all, getEHDispatchBlock returned
1166 // that catch-all as the dispatch block.
1167 if (catchScope.getNumHandlers() == 1 &&
1168 catchScope.getHandler(0).isCatchAll()) {
1169 assert(dispatchBlock == catchScope.getHandler(0).Block);
1173 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveIP();
1174 CGF.EmitBlockAfterUses(dispatchBlock);
1176 // Select the right handler.
1177 llvm::Value *llvm_eh_typeid_for =
1178 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
1180 // Load the selector value.
1181 llvm::Value *selector = CGF.getSelectorFromSlot();
1183 // Test against each of the exception types we claim to catch.
1184 for (unsigned i = 0, e = catchScope.getNumHandlers(); ; ++i) {
1185 assert(i < e && "ran off end of handlers!");
1186 const EHCatchScope::Handler &handler = catchScope.getHandler(i);
1188 llvm::Value *typeValue = handler.Type;
1189 assert(typeValue && "fell into catch-all case!");
1190 typeValue = CGF.Builder.CreateBitCast(typeValue, CGF.Int8PtrTy);
1192 // Figure out the next block.
1194 llvm::BasicBlock *nextBlock;
1196 // If this is the last handler, we're at the end, and the next
1197 // block is the block for the enclosing EH scope.
1199 nextBlock = CGF.getEHDispatchBlock(catchScope.getEnclosingEHScope());
1202 // If the next handler is a catch-all, we're at the end, and the
1203 // next block is that handler.
1204 } else if (catchScope.getHandler(i+1).isCatchAll()) {
1205 nextBlock = catchScope.getHandler(i+1).Block;
1208 // Otherwise, we're not at the end and we need a new block.
1210 nextBlock = CGF.createBasicBlock("catch.fallthrough");
1214 // Figure out the catch type's index in the LSDA's type table.
1215 llvm::CallInst *typeIndex =
1216 CGF.Builder.CreateCall(llvm_eh_typeid_for, typeValue);
1217 typeIndex->setDoesNotThrow();
1219 llvm::Value *matchesTypeIndex =
1220 CGF.Builder.CreateICmpEQ(selector, typeIndex, "matches");
1221 CGF.Builder.CreateCondBr(matchesTypeIndex, handler.Block, nextBlock);
1223 // If the next handler is a catch-all, we're completely done.
1225 CGF.Builder.restoreIP(savedIP);
1228 // Otherwise we need to emit and continue at that block.
1229 CGF.EmitBlock(nextBlock);
1233 void CodeGenFunction::popCatchScope() {
1234 EHCatchScope &catchScope = cast<EHCatchScope>(*EHStack.begin());
1235 if (catchScope.hasEHBranches())
1236 emitCatchDispatchBlock(*this, catchScope);
1240 void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
1241 unsigned NumHandlers = S.getNumHandlers();
1242 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1243 assert(CatchScope.getNumHandlers() == NumHandlers);
1245 // If the catch was not required, bail out now.
1246 if (!CatchScope.hasEHBranches()) {
1251 // Emit the structure of the EH dispatch for this catch.
1252 emitCatchDispatchBlock(*this, CatchScope);
1254 // Copy the handler blocks off before we pop the EH stack. Emitting
1255 // the handlers might scribble on this memory.
1256 SmallVector<EHCatchScope::Handler, 8> Handlers(NumHandlers);
1257 memcpy(Handlers.data(), CatchScope.begin(),
1258 NumHandlers * sizeof(EHCatchScope::Handler));
1262 // The fall-through block.
1263 llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
1265 // We just emitted the body of the try; jump to the continue block.
1266 if (HaveInsertPoint())
1267 Builder.CreateBr(ContBB);
1269 // Determine if we need an implicit rethrow for all these catch handlers;
1270 // see the comment below.
1271 bool doImplicitRethrow = false;
1273 doImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
1274 isa<CXXConstructorDecl>(CurCodeDecl);
1276 // Perversely, we emit the handlers backwards precisely because we
1277 // want them to appear in source order. In all of these cases, the
1278 // catch block will have exactly one predecessor, which will be a
1279 // particular block in the catch dispatch. However, in the case of
1280 // a catch-all, one of the dispatch blocks will branch to two
1281 // different handlers, and EmitBlockAfterUses will cause the second
1282 // handler to be moved before the first.
1283 for (unsigned I = NumHandlers; I != 0; --I) {
1284 llvm::BasicBlock *CatchBlock = Handlers[I-1].Block;
1285 EmitBlockAfterUses(CatchBlock);
1287 // Catch the exception if this isn't a catch-all.
1288 const CXXCatchStmt *C = S.getHandler(I-1);
1290 // Enter a cleanup scope, including the catch variable and the
1292 RunCleanupsScope CatchScope(*this);
1294 // Initialize the catch variable and set up the cleanups.
1295 BeginCatch(*this, C);
1297 // Perform the body of the catch.
1298 EmitStmt(C->getHandlerBlock());
1300 // [except.handle]p11:
1301 // The currently handled exception is rethrown if control
1302 // reaches the end of a handler of the function-try-block of a
1303 // constructor or destructor.
1305 // It is important that we only do this on fallthrough and not on
1306 // return. Note that it's illegal to put a return in a
1307 // constructor function-try-block's catch handler (p14), so this
1308 // really only applies to destructors.
1309 if (doImplicitRethrow && HaveInsertPoint()) {
1310 EmitRuntimeCallOrInvoke(getReThrowFn(CGM));
1311 Builder.CreateUnreachable();
1312 Builder.ClearInsertionPoint();
1315 // Fall out through the catch cleanups.
1316 CatchScope.ForceCleanup();
1318 // Branch out of the try.
1319 if (HaveInsertPoint())
1320 Builder.CreateBr(ContBB);
1327 struct CallEndCatchForFinally : EHScopeStack::Cleanup {
1328 llvm::Value *ForEHVar;
1329 llvm::Value *EndCatchFn;
1330 CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn)
1331 : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
1333 void Emit(CodeGenFunction &CGF, Flags flags) {
1334 llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
1335 llvm::BasicBlock *CleanupContBB =
1336 CGF.createBasicBlock("finally.cleanup.cont");
1338 llvm::Value *ShouldEndCatch =
1339 CGF.Builder.CreateLoad(ForEHVar, "finally.endcatch");
1340 CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1341 CGF.EmitBlock(EndCatchBB);
1342 CGF.EmitRuntimeCallOrInvoke(EndCatchFn); // catch-all, so might throw
1343 CGF.EmitBlock(CleanupContBB);
1347 struct PerformFinally : EHScopeStack::Cleanup {
1349 llvm::Value *ForEHVar;
1350 llvm::Value *EndCatchFn;
1351 llvm::Value *RethrowFn;
1352 llvm::Value *SavedExnVar;
1354 PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
1355 llvm::Value *EndCatchFn,
1356 llvm::Value *RethrowFn, llvm::Value *SavedExnVar)
1357 : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1358 RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
1360 void Emit(CodeGenFunction &CGF, Flags flags) {
1361 // Enter a cleanup to call the end-catch function if one was provided.
1363 CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
1364 ForEHVar, EndCatchFn);
1366 // Save the current cleanup destination in case there are
1367 // cleanups in the finally block.
1368 llvm::Value *SavedCleanupDest =
1369 CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
1370 "cleanup.dest.saved");
1372 // Emit the finally block.
1375 // If the end of the finally is reachable, check whether this was
1376 // for EH. If so, rethrow.
1377 if (CGF.HaveInsertPoint()) {
1378 llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
1379 llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
1381 llvm::Value *ShouldRethrow =
1382 CGF.Builder.CreateLoad(ForEHVar, "finally.shouldthrow");
1383 CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1385 CGF.EmitBlock(RethrowBB);
1387 CGF.EmitRuntimeCallOrInvoke(RethrowFn,
1388 CGF.Builder.CreateLoad(SavedExnVar));
1390 CGF.EmitRuntimeCallOrInvoke(RethrowFn);
1392 CGF.Builder.CreateUnreachable();
1394 CGF.EmitBlock(ContBB);
1396 // Restore the cleanup destination.
1397 CGF.Builder.CreateStore(SavedCleanupDest,
1398 CGF.getNormalCleanupDestSlot());
1401 // Leave the end-catch cleanup. As an optimization, pretend that
1402 // the fallthrough path was inaccessible; we've dynamically proven
1403 // that we're not in the EH case along that path.
1405 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1406 CGF.PopCleanupBlock();
1407 CGF.Builder.restoreIP(SavedIP);
1410 // Now make sure we actually have an insertion point or the
1411 // cleanup gods will hate us.
1412 CGF.EnsureInsertPoint();
1417 /// Enters a finally block for an implementation using zero-cost
1418 /// exceptions. This is mostly general, but hard-codes some
1419 /// language/ABI-specific behavior in the catch-all sections.
1420 void CodeGenFunction::FinallyInfo::enter(CodeGenFunction &CGF,
1422 llvm::Constant *beginCatchFn,
1423 llvm::Constant *endCatchFn,
1424 llvm::Constant *rethrowFn) {
1425 assert((beginCatchFn != 0) == (endCatchFn != 0) &&
1426 "begin/end catch functions not paired");
1427 assert(rethrowFn && "rethrow function is required");
1429 BeginCatchFn = beginCatchFn;
1431 // The rethrow function has one of the following two types:
1434 // In the latter case we need to pass it the exception object.
1435 // But we can't use the exception slot because the @finally might
1436 // have a landing pad (which would overwrite the exception slot).
1437 llvm::FunctionType *rethrowFnTy =
1438 cast<llvm::FunctionType>(
1439 cast<llvm::PointerType>(rethrowFn->getType())->getElementType());
1441 if (rethrowFnTy->getNumParams())
1442 SavedExnVar = CGF.CreateTempAlloca(CGF.Int8PtrTy, "finally.exn");
1444 // A finally block is a statement which must be executed on any edge
1445 // out of a given scope. Unlike a cleanup, the finally block may
1446 // contain arbitrary control flow leading out of itself. In
1447 // addition, finally blocks should always be executed, even if there
1448 // are no catch handlers higher on the stack. Therefore, we
1449 // surround the protected scope with a combination of a normal
1450 // cleanup (to catch attempts to break out of the block via normal
1451 // control flow) and an EH catch-all (semantically "outside" any try
1452 // statement to which the finally block might have been attached).
1453 // The finally block itself is generated in the context of a cleanup
1454 // which conditionally leaves the catch-all.
1456 // Jump destination for performing the finally block on an exception
1457 // edge. We'll never actually reach this block, so unreachable is
1459 RethrowDest = CGF.getJumpDestInCurrentScope(CGF.getUnreachableBlock());
1461 // Whether the finally block is being executed for EH purposes.
1462 ForEHVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "finally.for-eh");
1463 CGF.Builder.CreateStore(CGF.Builder.getFalse(), ForEHVar);
1465 // Enter a normal cleanup which will perform the @finally block.
1466 CGF.EHStack.pushCleanup<PerformFinally>(NormalCleanup, body,
1467 ForEHVar, endCatchFn,
1468 rethrowFn, SavedExnVar);
1470 // Enter a catch-all scope.
1471 llvm::BasicBlock *catchBB = CGF.createBasicBlock("finally.catchall");
1472 EHCatchScope *catchScope = CGF.EHStack.pushCatch(1);
1473 catchScope->setCatchAllHandler(0, catchBB);
1476 void CodeGenFunction::FinallyInfo::exit(CodeGenFunction &CGF) {
1477 // Leave the finally catch-all.
1478 EHCatchScope &catchScope = cast<EHCatchScope>(*CGF.EHStack.begin());
1479 llvm::BasicBlock *catchBB = catchScope.getHandler(0).Block;
1481 CGF.popCatchScope();
1483 // If there are any references to the catch-all block, emit it.
1484 if (catchBB->use_empty()) {
1487 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveAndClearIP();
1488 CGF.EmitBlock(catchBB);
1490 llvm::Value *exn = 0;
1492 // If there's a begin-catch function, call it.
1494 exn = CGF.getExceptionFromSlot();
1495 CGF.EmitNounwindRuntimeCall(BeginCatchFn, exn);
1498 // If we need to remember the exception pointer to rethrow later, do so.
1500 if (!exn) exn = CGF.getExceptionFromSlot();
1501 CGF.Builder.CreateStore(exn, SavedExnVar);
1504 // Tell the cleanups in the finally block that we're do this for EH.
1505 CGF.Builder.CreateStore(CGF.Builder.getTrue(), ForEHVar);
1507 // Thread a jump through the finally cleanup.
1508 CGF.EmitBranchThroughCleanup(RethrowDest);
1510 CGF.Builder.restoreIP(savedIP);
1513 // Finally, leave the @finally cleanup.
1514 CGF.PopCleanupBlock();
1517 /// In a terminate landing pad, should we use __clang__call_terminate
1518 /// or just a naked call to std::terminate?
1520 /// __clang_call_terminate calls __cxa_begin_catch, which then allows
1521 /// std::terminate to usefully report something about the
1522 /// violating exception.
1523 static bool useClangCallTerminate(CodeGenModule &CGM) {
1524 // Only do this for Itanium-family ABIs in C++ mode.
1525 return (CGM.getLangOpts().CPlusPlus &&
1526 CGM.getTarget().getCXXABI().isItaniumFamily());
1529 /// Get or define the following function:
1530 /// void @__clang_call_terminate(i8* %exn) nounwind noreturn
1531 /// This code is used only in C++.
1532 static llvm::Constant *getClangCallTerminateFn(CodeGenModule &CGM) {
1533 llvm::FunctionType *fnTy =
1534 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
1535 llvm::Constant *fnRef =
1536 CGM.CreateRuntimeFunction(fnTy, "__clang_call_terminate");
1538 llvm::Function *fn = dyn_cast<llvm::Function>(fnRef);
1539 if (fn && fn->empty()) {
1540 fn->setDoesNotThrow();
1541 fn->setDoesNotReturn();
1543 // What we really want is to massively penalize inlining without
1544 // forbidding it completely. The difference between that and
1545 // 'noinline' is negligible.
1546 fn->addFnAttr(llvm::Attribute::NoInline);
1548 // Allow this function to be shared across translation units, but
1549 // we don't want it to turn into an exported symbol.
1550 fn->setLinkage(llvm::Function::LinkOnceODRLinkage);
1551 fn->setVisibility(llvm::Function::HiddenVisibility);
1553 // Set up the function.
1554 llvm::BasicBlock *entry =
1555 llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn);
1556 CGBuilderTy builder(entry);
1558 // Pull the exception pointer out of the parameter list.
1559 llvm::Value *exn = &*fn->arg_begin();
1561 // Call __cxa_begin_catch(exn).
1562 llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn);
1563 catchCall->setDoesNotThrow();
1564 catchCall->setCallingConv(CGM.getRuntimeCC());
1566 // Call std::terminate().
1567 llvm::CallInst *termCall = builder.CreateCall(getTerminateFn(CGM));
1568 termCall->setDoesNotThrow();
1569 termCall->setDoesNotReturn();
1570 termCall->setCallingConv(CGM.getRuntimeCC());
1572 // std::terminate cannot return.
1573 builder.CreateUnreachable();
1579 llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
1580 if (TerminateLandingPad)
1581 return TerminateLandingPad;
1583 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1585 // This will get inserted at the end of the function.
1586 TerminateLandingPad = createBasicBlock("terminate.lpad");
1587 Builder.SetInsertPoint(TerminateLandingPad);
1589 // Tell the backend that this is a landing pad.
1590 const EHPersonality &Personality = EHPersonality::get(CGM.getLangOpts());
1591 llvm::LandingPadInst *LPadInst =
1592 Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, NULL),
1593 getOpaquePersonalityFn(CGM, Personality), 0);
1594 LPadInst->addClause(getCatchAllValue(*this));
1596 llvm::CallInst *terminateCall;
1597 if (useClangCallTerminate(CGM)) {
1598 // Extract out the exception pointer.
1599 llvm::Value *exn = Builder.CreateExtractValue(LPadInst, 0);
1600 terminateCall = EmitNounwindRuntimeCall(getClangCallTerminateFn(CGM), exn);
1602 terminateCall = EmitNounwindRuntimeCall(getTerminateFn(CGM));
1604 terminateCall->setDoesNotReturn();
1605 Builder.CreateUnreachable();
1607 // Restore the saved insertion state.
1608 Builder.restoreIP(SavedIP);
1610 return TerminateLandingPad;
1613 llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
1614 if (TerminateHandler)
1615 return TerminateHandler;
1617 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1619 // Set up the terminate handler. This block is inserted at the very
1620 // end of the function by FinishFunction.
1621 TerminateHandler = createBasicBlock("terminate.handler");
1622 Builder.SetInsertPoint(TerminateHandler);
1623 llvm::CallInst *terminateCall;
1624 if (useClangCallTerminate(CGM)) {
1625 // Load the exception pointer.
1626 llvm::Value *exn = getExceptionFromSlot();
1627 terminateCall = EmitNounwindRuntimeCall(getClangCallTerminateFn(CGM), exn);
1629 terminateCall = EmitNounwindRuntimeCall(getTerminateFn(CGM));
1631 terminateCall->setDoesNotReturn();
1632 Builder.CreateUnreachable();
1634 // Restore the saved insertion state.
1635 Builder.restoreIP(SavedIP);
1637 return TerminateHandler;
1640 llvm::BasicBlock *CodeGenFunction::getEHResumeBlock(bool isCleanup) {
1641 if (EHResumeBlock) return EHResumeBlock;
1643 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1645 // We emit a jump to a notional label at the outermost unwind state.
1646 EHResumeBlock = createBasicBlock("eh.resume");
1647 Builder.SetInsertPoint(EHResumeBlock);
1649 const EHPersonality &Personality = EHPersonality::get(CGM.getLangOpts());
1651 // This can always be a call because we necessarily didn't find
1652 // anything on the EH stack which needs our help.
1653 const char *RethrowName = Personality.CatchallRethrowFn;
1654 if (RethrowName != 0 && !isCleanup) {
1655 EmitRuntimeCall(getCatchallRethrowFn(CGM, RethrowName),
1656 getExceptionFromSlot())
1657 ->setDoesNotReturn();
1659 switch (CleanupHackLevel) {
1660 case CHL_MandatoryCatchall:
1661 // In mandatory-catchall mode, we need to use
1662 // _Unwind_Resume_or_Rethrow, or whatever the personality's
1664 EmitRuntimeCall(getUnwindResumeOrRethrowFn(),
1665 getExceptionFromSlot())
1666 ->setDoesNotReturn();
1668 case CHL_MandatoryCleanup: {
1669 // In mandatory-cleanup mode, we should use 'resume'.
1671 // Recreate the landingpad's return value for the 'resume' instruction.
1672 llvm::Value *Exn = getExceptionFromSlot();
1673 llvm::Value *Sel = getSelectorFromSlot();
1675 llvm::Type *LPadType = llvm::StructType::get(Exn->getType(),
1676 Sel->getType(), NULL);
1677 llvm::Value *LPadVal = llvm::UndefValue::get(LPadType);
1678 LPadVal = Builder.CreateInsertValue(LPadVal, Exn, 0, "lpad.val");
1679 LPadVal = Builder.CreateInsertValue(LPadVal, Sel, 1, "lpad.val");
1681 Builder.CreateResume(LPadVal);
1682 Builder.restoreIP(SavedIP);
1683 return EHResumeBlock;
1686 // In an idealized mode where we don't have to worry about the
1687 // optimizer combining landing pads, we should just use
1688 // _Unwind_Resume (or the personality's equivalent).
1689 EmitRuntimeCall(getUnwindResumeFn(), getExceptionFromSlot())
1690 ->setDoesNotReturn();
1695 Builder.CreateUnreachable();
1697 Builder.restoreIP(SavedIP);
1699 return EHResumeBlock;
1702 void CodeGenFunction::EmitSEHTryStmt(const SEHTryStmt &S) {
1703 CGM.ErrorUnsupported(&S, "SEH __try");