clang API Documentation

CGException.cpp
Go to the documentation of this file.
00001 //===--- CGException.cpp - Emit LLVM Code for C++ exceptions --------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This contains code dealing with C++ exception related code generation.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "CodeGenFunction.h"
00015 #include "CGCleanup.h"
00016 #include "CGObjCRuntime.h"
00017 #include "TargetInfo.h"
00018 #include "clang/AST/StmtCXX.h"
00019 #include "llvm/Intrinsics.h"
00020 #include "llvm/Support/CallSite.h"
00021 
00022 using namespace clang;
00023 using namespace CodeGen;
00024 
00025 static llvm::Constant *getAllocateExceptionFn(CodeGenFunction &CGF) {
00026   // void *__cxa_allocate_exception(size_t thrown_size);
00027 
00028   llvm::FunctionType *FTy =
00029     llvm::FunctionType::get(CGF.Int8PtrTy, CGF.SizeTy, /*IsVarArgs=*/false);
00030 
00031   return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
00032 }
00033 
00034 static llvm::Constant *getFreeExceptionFn(CodeGenFunction &CGF) {
00035   // void __cxa_free_exception(void *thrown_exception);
00036 
00037   llvm::FunctionType *FTy =
00038     llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, /*IsVarArgs=*/false);
00039 
00040   return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_free_exception");
00041 }
00042 
00043 static llvm::Constant *getThrowFn(CodeGenFunction &CGF) {
00044   // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
00045   //                  void (*dest) (void *));
00046 
00047   llvm::Type *Args[3] = { CGF.Int8PtrTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
00048   llvm::FunctionType *FTy =
00049     llvm::FunctionType::get(CGF.VoidTy, Args, /*IsVarArgs=*/false);
00050 
00051   return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
00052 }
00053 
00054 static llvm::Constant *getReThrowFn(CodeGenFunction &CGF) {
00055   // void __cxa_rethrow();
00056 
00057   llvm::FunctionType *FTy =
00058     llvm::FunctionType::get(CGF.VoidTy, /*IsVarArgs=*/false);
00059 
00060   return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
00061 }
00062 
00063 static llvm::Constant *getGetExceptionPtrFn(CodeGenFunction &CGF) {
00064   // void *__cxa_get_exception_ptr(void*);
00065 
00066   llvm::FunctionType *FTy =
00067     llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrTy, /*IsVarArgs=*/false);
00068 
00069   return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
00070 }
00071 
00072 static llvm::Constant *getBeginCatchFn(CodeGenFunction &CGF) {
00073   // void *__cxa_begin_catch(void*);
00074 
00075   llvm::FunctionType *FTy =
00076     llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrTy, /*IsVarArgs=*/false);
00077 
00078   return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
00079 }
00080 
00081 static llvm::Constant *getEndCatchFn(CodeGenFunction &CGF) {
00082   // void __cxa_end_catch();
00083 
00084   llvm::FunctionType *FTy =
00085     llvm::FunctionType::get(CGF.VoidTy, /*IsVarArgs=*/false);
00086 
00087   return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
00088 }
00089 
00090 static llvm::Constant *getUnexpectedFn(CodeGenFunction &CGF) {
00091   // void __cxa_call_unexepcted(void *thrown_exception);
00092 
00093   llvm::FunctionType *FTy =
00094     llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, /*IsVarArgs=*/false);
00095 
00096   return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_call_unexpected");
00097 }
00098 
00099 llvm::Constant *CodeGenFunction::getUnwindResumeFn() {
00100   llvm::FunctionType *FTy =
00101     llvm::FunctionType::get(VoidTy, Int8PtrTy, /*IsVarArgs=*/false);
00102 
00103   if (CGM.getLangOpts().SjLjExceptions)
00104     return CGM.CreateRuntimeFunction(FTy, "_Unwind_SjLj_Resume");
00105   return CGM.CreateRuntimeFunction(FTy, "_Unwind_Resume");
00106 }
00107 
00108 llvm::Constant *CodeGenFunction::getUnwindResumeOrRethrowFn() {
00109   llvm::FunctionType *FTy =
00110     llvm::FunctionType::get(VoidTy, Int8PtrTy, /*IsVarArgs=*/false);
00111 
00112   if (CGM.getLangOpts().SjLjExceptions)
00113     return CGM.CreateRuntimeFunction(FTy, "_Unwind_SjLj_Resume_or_Rethrow");
00114   return CGM.CreateRuntimeFunction(FTy, "_Unwind_Resume_or_Rethrow");
00115 }
00116 
00117 static llvm::Constant *getTerminateFn(CodeGenFunction &CGF) {
00118   // void __terminate();
00119 
00120   llvm::FunctionType *FTy =
00121     llvm::FunctionType::get(CGF.VoidTy, /*IsVarArgs=*/false);
00122 
00123   StringRef name;
00124 
00125   // In C++, use std::terminate().
00126   if (CGF.getLangOpts().CPlusPlus)
00127     name = "_ZSt9terminatev"; // FIXME: mangling!
00128   else if (CGF.getLangOpts().ObjC1 &&
00129            CGF.CGM.getCodeGenOpts().ObjCRuntimeHasTerminate)
00130     name = "objc_terminate";
00131   else
00132     name = "abort";
00133   return CGF.CGM.CreateRuntimeFunction(FTy, name);
00134 }
00135 
00136 static llvm::Constant *getCatchallRethrowFn(CodeGenFunction &CGF,
00137                                             StringRef Name) {
00138   llvm::FunctionType *FTy =
00139     llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, /*IsVarArgs=*/false);
00140 
00141   return CGF.CGM.CreateRuntimeFunction(FTy, Name);
00142 }
00143 
00144 namespace {
00145   /// The exceptions personality for a function.
00146   struct EHPersonality {
00147     const char *PersonalityFn;
00148 
00149     // If this is non-null, this personality requires a non-standard
00150     // function for rethrowing an exception after a catchall cleanup.
00151     // This function must have prototype void(void*).
00152     const char *CatchallRethrowFn;
00153 
00154     static const EHPersonality &get(const LangOptions &Lang);
00155     static const EHPersonality GNU_C;
00156     static const EHPersonality GNU_C_SJLJ;
00157     static const EHPersonality GNU_ObjC;
00158     static const EHPersonality GNU_ObjCXX;
00159     static const EHPersonality NeXT_ObjC;
00160     static const EHPersonality GNU_CPlusPlus;
00161     static const EHPersonality GNU_CPlusPlus_SJLJ;
00162   };
00163 }
00164 
00165 const EHPersonality EHPersonality::GNU_C = { "__gcc_personality_v0", 0 };
00166 const EHPersonality EHPersonality::GNU_C_SJLJ = { "__gcc_personality_sj0", 0 };
00167 const EHPersonality EHPersonality::NeXT_ObjC = { "__objc_personality_v0", 0 };
00168 const EHPersonality EHPersonality::GNU_CPlusPlus = { "__gxx_personality_v0", 0};
00169 const EHPersonality
00170 EHPersonality::GNU_CPlusPlus_SJLJ = { "__gxx_personality_sj0", 0 };
00171 const EHPersonality
00172 EHPersonality::GNU_ObjC = {"__gnu_objc_personality_v0", "objc_exception_throw"};
00173 const EHPersonality
00174 EHPersonality::GNU_ObjCXX = { "__gnustep_objcxx_personality_v0", 0 };
00175 
00176 static const EHPersonality &getCPersonality(const LangOptions &L) {
00177   if (L.SjLjExceptions)
00178     return EHPersonality::GNU_C_SJLJ;
00179   return EHPersonality::GNU_C;
00180 }
00181 
00182 static const EHPersonality &getObjCPersonality(const LangOptions &L) {
00183   if (L.NeXTRuntime) {
00184     if (L.ObjCNonFragileABI) return EHPersonality::NeXT_ObjC;
00185     else return getCPersonality(L);
00186   } else {
00187     return EHPersonality::GNU_ObjC;
00188   }
00189 }
00190 
00191 static const EHPersonality &getCXXPersonality(const LangOptions &L) {
00192   if (L.SjLjExceptions)
00193     return EHPersonality::GNU_CPlusPlus_SJLJ;
00194   else
00195     return EHPersonality::GNU_CPlusPlus;
00196 }
00197 
00198 /// Determines the personality function to use when both C++
00199 /// and Objective-C exceptions are being caught.
00200 static const EHPersonality &getObjCXXPersonality(const LangOptions &L) {
00201   // The ObjC personality defers to the C++ personality for non-ObjC
00202   // handlers.  Unlike the C++ case, we use the same personality
00203   // function on targets using (backend-driven) SJLJ EH.
00204   if (L.NeXTRuntime) {
00205     if (L.ObjCNonFragileABI)
00206       return EHPersonality::NeXT_ObjC;
00207 
00208     // In the fragile ABI, just use C++ exception handling and hope
00209     // they're not doing crazy exception mixing.
00210     else
00211       return getCXXPersonality(L);
00212   }
00213 
00214   // The GNU runtime's personality function inherently doesn't support
00215   // mixed EH.  Use the C++ personality just to avoid returning null.
00216   return EHPersonality::GNU_ObjCXX;
00217 }
00218 
00219 const EHPersonality &EHPersonality::get(const LangOptions &L) {
00220   if (L.CPlusPlus && L.ObjC1)
00221     return getObjCXXPersonality(L);
00222   else if (L.CPlusPlus)
00223     return getCXXPersonality(L);
00224   else if (L.ObjC1)
00225     return getObjCPersonality(L);
00226   else
00227     return getCPersonality(L);
00228 }
00229 
00230 static llvm::Constant *getPersonalityFn(CodeGenModule &CGM,
00231                                         const EHPersonality &Personality) {
00232   llvm::Constant *Fn =
00233     CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.Int32Ty, true),
00234                               Personality.PersonalityFn);
00235   return Fn;
00236 }
00237 
00238 static llvm::Constant *getOpaquePersonalityFn(CodeGenModule &CGM,
00239                                         const EHPersonality &Personality) {
00240   llvm::Constant *Fn = getPersonalityFn(CGM, Personality);
00241   return llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
00242 }
00243 
00244 /// Check whether a personality function could reasonably be swapped
00245 /// for a C++ personality function.
00246 static bool PersonalityHasOnlyCXXUses(llvm::Constant *Fn) {
00247   for (llvm::Constant::use_iterator
00248          I = Fn->use_begin(), E = Fn->use_end(); I != E; ++I) {
00249     llvm::User *User = *I;
00250 
00251     // Conditionally white-list bitcasts.
00252     if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(User)) {
00253       if (CE->getOpcode() != llvm::Instruction::BitCast) return false;
00254       if (!PersonalityHasOnlyCXXUses(CE))
00255         return false;
00256       continue;
00257     }
00258 
00259     // Otherwise, it has to be a landingpad instruction.
00260     llvm::LandingPadInst *LPI = dyn_cast<llvm::LandingPadInst>(User);
00261     if (!LPI) return false;
00262 
00263     for (unsigned I = 0, E = LPI->getNumClauses(); I != E; ++I) {
00264       // Look for something that would've been returned by the ObjC
00265       // runtime's GetEHType() method.
00266       llvm::Value *Val = LPI->getClause(I)->stripPointerCasts();
00267       if (LPI->isCatch(I)) {
00268         // Check if the catch value has the ObjC prefix.
00269         if (llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Val))
00270           // ObjC EH selector entries are always global variables with
00271           // names starting like this.
00272           if (GV->getName().startswith("OBJC_EHTYPE"))
00273             return false;
00274       } else {
00275         // Check if any of the filter values have the ObjC prefix.
00276         llvm::Constant *CVal = cast<llvm::Constant>(Val);
00277         for (llvm::User::op_iterator
00278                II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II) {
00279           if (llvm::GlobalVariable *GV =
00280               cast<llvm::GlobalVariable>((*II)->stripPointerCasts()))
00281             // ObjC EH selector entries are always global variables with
00282             // names starting like this.
00283             if (GV->getName().startswith("OBJC_EHTYPE"))
00284               return false;
00285         }
00286       }
00287     }
00288   }
00289 
00290   return true;
00291 }
00292 
00293 /// Try to use the C++ personality function in ObjC++.  Not doing this
00294 /// can cause some incompatibilities with gcc, which is more
00295 /// aggressive about only using the ObjC++ personality in a function
00296 /// when it really needs it.
00297 void CodeGenModule::SimplifyPersonality() {
00298   // For now, this is really a Darwin-specific operation.
00299   if (!Context.getTargetInfo().getTriple().isOSDarwin())
00300     return;
00301 
00302   // If we're not in ObjC++ -fexceptions, there's nothing to do.
00303   if (!LangOpts.CPlusPlus || !LangOpts.ObjC1 || !LangOpts.Exceptions)
00304     return;
00305 
00306   const EHPersonality &ObjCXX = EHPersonality::get(LangOpts);
00307   const EHPersonality &CXX = getCXXPersonality(LangOpts);
00308   if (&ObjCXX == &CXX)
00309     return;
00310 
00311   assert(std::strcmp(ObjCXX.PersonalityFn, CXX.PersonalityFn) != 0 &&
00312          "Different EHPersonalities using the same personality function.");
00313 
00314   llvm::Function *Fn = getModule().getFunction(ObjCXX.PersonalityFn);
00315 
00316   // Nothing to do if it's unused.
00317   if (!Fn || Fn->use_empty()) return;
00318   
00319   // Can't do the optimization if it has non-C++ uses.
00320   if (!PersonalityHasOnlyCXXUses(Fn)) return;
00321 
00322   // Create the C++ personality function and kill off the old
00323   // function.
00324   llvm::Constant *CXXFn = getPersonalityFn(*this, CXX);
00325 
00326   // This can happen if the user is screwing with us.
00327   if (Fn->getType() != CXXFn->getType()) return;
00328 
00329   Fn->replaceAllUsesWith(CXXFn);
00330   Fn->eraseFromParent();
00331 }
00332 
00333 /// Returns the value to inject into a selector to indicate the
00334 /// presence of a catch-all.
00335 static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
00336   // Possibly we should use @llvm.eh.catch.all.value here.
00337   return llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
00338 }
00339 
00340 namespace {
00341   /// A cleanup to free the exception object if its initialization
00342   /// throws.
00343   struct FreeException : EHScopeStack::Cleanup {
00344     llvm::Value *exn;
00345     FreeException(llvm::Value *exn) : exn(exn) {}
00346     void Emit(CodeGenFunction &CGF, Flags flags) {
00347       CGF.Builder.CreateCall(getFreeExceptionFn(CGF), exn)
00348         ->setDoesNotThrow();
00349     }
00350   };
00351 }
00352 
00353 // Emits an exception expression into the given location.  This
00354 // differs from EmitAnyExprToMem only in that, if a final copy-ctor
00355 // call is required, an exception within that copy ctor causes
00356 // std::terminate to be invoked.
00357 static void EmitAnyExprToExn(CodeGenFunction &CGF, const Expr *e,
00358                              llvm::Value *addr) {
00359   // Make sure the exception object is cleaned up if there's an
00360   // exception during initialization.
00361   CGF.pushFullExprCleanup<FreeException>(EHCleanup, addr);
00362   EHScopeStack::stable_iterator cleanup = CGF.EHStack.stable_begin();
00363 
00364   // __cxa_allocate_exception returns a void*;  we need to cast this
00365   // to the appropriate type for the object.
00366   llvm::Type *ty = CGF.ConvertTypeForMem(e->getType())->getPointerTo();
00367   llvm::Value *typedAddr = CGF.Builder.CreateBitCast(addr, ty);
00368 
00369   // FIXME: this isn't quite right!  If there's a final unelided call
00370   // to a copy constructor, then according to [except.terminate]p1 we
00371   // must call std::terminate() if that constructor throws, because
00372   // technically that copy occurs after the exception expression is
00373   // evaluated but before the exception is caught.  But the best way
00374   // to handle that is to teach EmitAggExpr to do the final copy
00375   // differently if it can't be elided.
00376   CGF.EmitAnyExprToMem(e, typedAddr, e->getType().getQualifiers(), 
00377                        /*IsInit*/ true);
00378 
00379   // Deactivate the cleanup block.
00380   CGF.DeactivateCleanupBlock(cleanup, cast<llvm::Instruction>(typedAddr));
00381 }
00382 
00383 llvm::Value *CodeGenFunction::getExceptionSlot() {
00384   if (!ExceptionSlot)
00385     ExceptionSlot = CreateTempAlloca(Int8PtrTy, "exn.slot");
00386   return ExceptionSlot;
00387 }
00388 
00389 llvm::Value *CodeGenFunction::getEHSelectorSlot() {
00390   if (!EHSelectorSlot)
00391     EHSelectorSlot = CreateTempAlloca(Int32Ty, "ehselector.slot");
00392   return EHSelectorSlot;
00393 }
00394 
00395 llvm::Value *CodeGenFunction::getExceptionFromSlot() {
00396   return Builder.CreateLoad(getExceptionSlot(), "exn");
00397 }
00398 
00399 llvm::Value *CodeGenFunction::getSelectorFromSlot() {
00400   return Builder.CreateLoad(getEHSelectorSlot(), "sel");
00401 }
00402 
00403 void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E) {
00404   if (!E->getSubExpr()) {
00405     if (getInvokeDest()) {
00406       Builder.CreateInvoke(getReThrowFn(*this),
00407                            getUnreachableBlock(),
00408                            getInvokeDest())
00409         ->setDoesNotReturn();
00410     } else {
00411       Builder.CreateCall(getReThrowFn(*this))->setDoesNotReturn();
00412       Builder.CreateUnreachable();
00413     }
00414 
00415     // throw is an expression, and the expression emitters expect us
00416     // to leave ourselves at a valid insertion point.
00417     EmitBlock(createBasicBlock("throw.cont"));
00418 
00419     return;
00420   }
00421 
00422   QualType ThrowType = E->getSubExpr()->getType();
00423 
00424   // Now allocate the exception object.
00425   llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
00426   uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
00427 
00428   llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(*this);
00429   llvm::CallInst *ExceptionPtr =
00430     Builder.CreateCall(AllocExceptionFn,
00431                        llvm::ConstantInt::get(SizeTy, TypeSize),
00432                        "exception");
00433   ExceptionPtr->setDoesNotThrow();
00434   
00435   EmitAnyExprToExn(*this, E->getSubExpr(), ExceptionPtr);
00436 
00437   // Now throw the exception.
00438   llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType, 
00439                                                          /*ForEH=*/true);
00440 
00441   // The address of the destructor.  If the exception type has a
00442   // trivial destructor (or isn't a record), we just pass null.
00443   llvm::Constant *Dtor = 0;
00444   if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
00445     CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
00446     if (!Record->hasTrivialDestructor()) {
00447       CXXDestructorDecl *DtorD = Record->getDestructor();
00448       Dtor = CGM.GetAddrOfCXXDestructor(DtorD, Dtor_Complete);
00449       Dtor = llvm::ConstantExpr::getBitCast(Dtor, Int8PtrTy);
00450     }
00451   }
00452   if (!Dtor) Dtor = llvm::Constant::getNullValue(Int8PtrTy);
00453 
00454   if (getInvokeDest()) {
00455     llvm::InvokeInst *ThrowCall =
00456       Builder.CreateInvoke3(getThrowFn(*this),
00457                             getUnreachableBlock(), getInvokeDest(),
00458                             ExceptionPtr, TypeInfo, Dtor);
00459     ThrowCall->setDoesNotReturn();
00460   } else {
00461     llvm::CallInst *ThrowCall =
00462       Builder.CreateCall3(getThrowFn(*this), ExceptionPtr, TypeInfo, Dtor);
00463     ThrowCall->setDoesNotReturn();
00464     Builder.CreateUnreachable();
00465   }
00466 
00467   // throw is an expression, and the expression emitters expect us
00468   // to leave ourselves at a valid insertion point.
00469   EmitBlock(createBasicBlock("throw.cont"));
00470 }
00471 
00472 void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
00473   if (!CGM.getLangOpts().CXXExceptions)
00474     return;
00475   
00476   const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
00477   if (FD == 0)
00478     return;
00479   const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
00480   if (Proto == 0)
00481     return;
00482 
00483   ExceptionSpecificationType EST = Proto->getExceptionSpecType();
00484   if (isNoexceptExceptionSpec(EST)) {
00485     if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
00486       // noexcept functions are simple terminate scopes.
00487       EHStack.pushTerminate();
00488     }
00489   } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
00490     unsigned NumExceptions = Proto->getNumExceptions();
00491     EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
00492 
00493     for (unsigned I = 0; I != NumExceptions; ++I) {
00494       QualType Ty = Proto->getExceptionType(I);
00495       QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
00496       llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType,
00497                                                         /*ForEH=*/true);
00498       Filter->setFilter(I, EHType);
00499     }
00500   }
00501 }
00502 
00503 /// Emit the dispatch block for a filter scope if necessary.
00504 static void emitFilterDispatchBlock(CodeGenFunction &CGF,
00505                                     EHFilterScope &filterScope) {
00506   llvm::BasicBlock *dispatchBlock = filterScope.getCachedEHDispatchBlock();
00507   if (!dispatchBlock) return;
00508   if (dispatchBlock->use_empty()) {
00509     delete dispatchBlock;
00510     return;
00511   }
00512 
00513   CGF.EmitBlockAfterUses(dispatchBlock);
00514 
00515   // If this isn't a catch-all filter, we need to check whether we got
00516   // here because the filter triggered.
00517   if (filterScope.getNumFilters()) {
00518     // Load the selector value.
00519     llvm::Value *selector = CGF.getSelectorFromSlot();
00520     llvm::BasicBlock *unexpectedBB = CGF.createBasicBlock("ehspec.unexpected");
00521 
00522     llvm::Value *zero = CGF.Builder.getInt32(0);
00523     llvm::Value *failsFilter =
00524       CGF.Builder.CreateICmpSLT(selector, zero, "ehspec.fails");
00525     CGF.Builder.CreateCondBr(failsFilter, unexpectedBB, CGF.getEHResumeBlock());
00526 
00527     CGF.EmitBlock(unexpectedBB);
00528   }
00529 
00530   // Call __cxa_call_unexpected.  This doesn't need to be an invoke
00531   // because __cxa_call_unexpected magically filters exceptions
00532   // according to the last landing pad the exception was thrown
00533   // into.  Seriously.
00534   llvm::Value *exn = CGF.getExceptionFromSlot();
00535   CGF.Builder.CreateCall(getUnexpectedFn(CGF), exn)
00536     ->setDoesNotReturn();
00537   CGF.Builder.CreateUnreachable();
00538 }
00539 
00540 void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
00541   if (!CGM.getLangOpts().CXXExceptions)
00542     return;
00543   
00544   const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
00545   if (FD == 0)
00546     return;
00547   const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
00548   if (Proto == 0)
00549     return;
00550 
00551   ExceptionSpecificationType EST = Proto->getExceptionSpecType();
00552   if (isNoexceptExceptionSpec(EST)) {
00553     if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
00554       EHStack.popTerminate();
00555     }
00556   } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
00557     EHFilterScope &filterScope = cast<EHFilterScope>(*EHStack.begin());
00558     emitFilterDispatchBlock(*this, filterScope);
00559     EHStack.popFilter();
00560   }
00561 }
00562 
00563 void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
00564   EnterCXXTryStmt(S);
00565   EmitStmt(S.getTryBlock());
00566   ExitCXXTryStmt(S);
00567 }
00568 
00569 void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
00570   unsigned NumHandlers = S.getNumHandlers();
00571   EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
00572 
00573   for (unsigned I = 0; I != NumHandlers; ++I) {
00574     const CXXCatchStmt *C = S.getHandler(I);
00575 
00576     llvm::BasicBlock *Handler = createBasicBlock("catch");
00577     if (C->getExceptionDecl()) {
00578       // FIXME: Dropping the reference type on the type into makes it
00579       // impossible to correctly implement catch-by-reference
00580       // semantics for pointers.  Unfortunately, this is what all
00581       // existing compilers do, and it's not clear that the standard
00582       // personality routine is capable of doing this right.  See C++ DR 388:
00583       //   http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
00584       QualType CaughtType = C->getCaughtType();
00585       CaughtType = CaughtType.getNonReferenceType().getUnqualifiedType();
00586 
00587       llvm::Value *TypeInfo = 0;
00588       if (CaughtType->isObjCObjectPointerType())
00589         TypeInfo = CGM.getObjCRuntime().GetEHType(CaughtType);
00590       else
00591         TypeInfo = CGM.GetAddrOfRTTIDescriptor(CaughtType, /*ForEH=*/true);
00592       CatchScope->setHandler(I, TypeInfo, Handler);
00593     } else {
00594       // No exception decl indicates '...', a catch-all.
00595       CatchScope->setCatchAllHandler(I, Handler);
00596     }
00597   }
00598 }
00599 
00600 llvm::BasicBlock *
00601 CodeGenFunction::getEHDispatchBlock(EHScopeStack::stable_iterator si) {
00602   // The dispatch block for the end of the scope chain is a block that
00603   // just resumes unwinding.
00604   if (si == EHStack.stable_end())
00605     return getEHResumeBlock();
00606 
00607   // Otherwise, we should look at the actual scope.
00608   EHScope &scope = *EHStack.find(si);
00609 
00610   llvm::BasicBlock *dispatchBlock = scope.getCachedEHDispatchBlock();
00611   if (!dispatchBlock) {
00612     switch (scope.getKind()) {
00613     case EHScope::Catch: {
00614       // Apply a special case to a single catch-all.
00615       EHCatchScope &catchScope = cast<EHCatchScope>(scope);
00616       if (catchScope.getNumHandlers() == 1 &&
00617           catchScope.getHandler(0).isCatchAll()) {
00618         dispatchBlock = catchScope.getHandler(0).Block;
00619 
00620       // Otherwise, make a dispatch block.
00621       } else {
00622         dispatchBlock = createBasicBlock("catch.dispatch");
00623       }
00624       break;
00625     }
00626 
00627     case EHScope::Cleanup:
00628       dispatchBlock = createBasicBlock("ehcleanup");
00629       break;
00630 
00631     case EHScope::Filter:
00632       dispatchBlock = createBasicBlock("filter.dispatch");
00633       break;
00634 
00635     case EHScope::Terminate:
00636       dispatchBlock = getTerminateHandler();
00637       break;
00638     }
00639     scope.setCachedEHDispatchBlock(dispatchBlock);
00640   }
00641   return dispatchBlock;
00642 }
00643 
00644 /// Check whether this is a non-EH scope, i.e. a scope which doesn't
00645 /// affect exception handling.  Currently, the only non-EH scopes are
00646 /// normal-only cleanup scopes.
00647 static bool isNonEHScope(const EHScope &S) {
00648   switch (S.getKind()) {
00649   case EHScope::Cleanup:
00650     return !cast<EHCleanupScope>(S).isEHCleanup();
00651   case EHScope::Filter:
00652   case EHScope::Catch:
00653   case EHScope::Terminate:
00654     return false;
00655   }
00656 
00657   llvm_unreachable("Invalid EHScope Kind!");
00658 }
00659 
00660 llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
00661   assert(EHStack.requiresLandingPad());
00662   assert(!EHStack.empty());
00663 
00664   if (!CGM.getLangOpts().Exceptions)
00665     return 0;
00666 
00667   // Check the innermost scope for a cached landing pad.  If this is
00668   // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
00669   llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
00670   if (LP) return LP;
00671 
00672   // Build the landing pad for this scope.
00673   LP = EmitLandingPad();
00674   assert(LP);
00675 
00676   // Cache the landing pad on the innermost scope.  If this is a
00677   // non-EH scope, cache the landing pad on the enclosing scope, too.
00678   for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
00679     ir->setCachedLandingPad(LP);
00680     if (!isNonEHScope(*ir)) break;
00681   }
00682 
00683   return LP;
00684 }
00685 
00686 // This code contains a hack to work around a design flaw in
00687 // LLVM's EH IR which breaks semantics after inlining.  This same
00688 // hack is implemented in llvm-gcc.
00689 //
00690 // The LLVM EH abstraction is basically a thin veneer over the
00691 // traditional GCC zero-cost design: for each range of instructions
00692 // in the function, there is (at most) one "landing pad" with an
00693 // associated chain of EH actions.  A language-specific personality
00694 // function interprets this chain of actions and (1) decides whether
00695 // or not to resume execution at the landing pad and (2) if so,
00696 // provides an integer indicating why it's stopping.  In LLVM IR,
00697 // the association of a landing pad with a range of instructions is
00698 // achieved via an invoke instruction, the chain of actions becomes
00699 // the arguments to the @llvm.eh.selector call, and the selector
00700 // call returns the integer indicator.  Other than the required
00701 // presence of two intrinsic function calls in the landing pad,
00702 // the IR exactly describes the layout of the output code.
00703 //
00704 // A principal advantage of this design is that it is completely
00705 // language-agnostic; in theory, the LLVM optimizers can treat
00706 // landing pads neutrally, and targets need only know how to lower
00707 // the intrinsics to have a functioning exceptions system (assuming
00708 // that platform exceptions follow something approximately like the
00709 // GCC design).  Unfortunately, landing pads cannot be combined in a
00710 // language-agnostic way: given selectors A and B, there is no way
00711 // to make a single landing pad which faithfully represents the
00712 // semantics of propagating an exception first through A, then
00713 // through B, without knowing how the personality will interpret the
00714 // (lowered form of the) selectors.  This means that inlining has no
00715 // choice but to crudely chain invokes (i.e., to ignore invokes in
00716 // the inlined function, but to turn all unwindable calls into
00717 // invokes), which is only semantically valid if every unwind stops
00718 // at every landing pad.
00719 //
00720 // Therefore, the invoke-inline hack is to guarantee that every
00721 // landing pad has a catch-all.
00722 enum CleanupHackLevel_t {
00723   /// A level of hack that requires that all landing pads have
00724   /// catch-alls.
00725   CHL_MandatoryCatchall,
00726 
00727   /// A level of hack that requires that all landing pads handle
00728   /// cleanups.
00729   CHL_MandatoryCleanup,
00730 
00731   /// No hacks at all;  ideal IR generation.
00732   CHL_Ideal
00733 };
00734 const CleanupHackLevel_t CleanupHackLevel = CHL_MandatoryCleanup;
00735 
00736 llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
00737   assert(EHStack.requiresLandingPad());
00738 
00739   EHScope &innermostEHScope = *EHStack.find(EHStack.getInnermostEHScope());
00740   switch (innermostEHScope.getKind()) {
00741   case EHScope::Terminate:
00742     return getTerminateLandingPad();
00743 
00744   case EHScope::Catch:
00745   case EHScope::Cleanup:
00746   case EHScope::Filter:
00747     if (llvm::BasicBlock *lpad = innermostEHScope.getCachedLandingPad())
00748       return lpad;
00749   }
00750 
00751   // Save the current IR generation state.
00752   CGBuilderTy::InsertPoint savedIP = Builder.saveAndClearIP();
00753 
00754   const EHPersonality &personality = EHPersonality::get(getLangOpts());
00755 
00756   // Create and configure the landing pad.
00757   llvm::BasicBlock *lpad = createBasicBlock("lpad");
00758   EmitBlock(lpad);
00759 
00760   llvm::LandingPadInst *LPadInst =
00761     Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, NULL),
00762                              getOpaquePersonalityFn(CGM, personality), 0);
00763 
00764   llvm::Value *LPadExn = Builder.CreateExtractValue(LPadInst, 0);
00765   Builder.CreateStore(LPadExn, getExceptionSlot());
00766   llvm::Value *LPadSel = Builder.CreateExtractValue(LPadInst, 1);
00767   Builder.CreateStore(LPadSel, getEHSelectorSlot());
00768 
00769   // Save the exception pointer.  It's safe to use a single exception
00770   // pointer per function because EH cleanups can never have nested
00771   // try/catches.
00772   // Build the landingpad instruction.
00773 
00774   // Accumulate all the handlers in scope.
00775   bool hasCatchAll = false;
00776   bool hasCleanup = false;
00777   bool hasFilter = false;
00778   SmallVector<llvm::Value*, 4> filterTypes;
00779   llvm::SmallPtrSet<llvm::Value*, 4> catchTypes;
00780   for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end();
00781          I != E; ++I) {
00782 
00783     switch (I->getKind()) {
00784     case EHScope::Cleanup:
00785       // If we have a cleanup, remember that.
00786       hasCleanup = (hasCleanup || cast<EHCleanupScope>(*I).isEHCleanup());
00787       continue;
00788 
00789     case EHScope::Filter: {
00790       assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
00791       assert(!hasCatchAll && "EH filter reached after catch-all");
00792 
00793       // Filter scopes get added to the landingpad in weird ways.
00794       EHFilterScope &filter = cast<EHFilterScope>(*I);
00795       hasFilter = true;
00796 
00797       // Add all the filter values.
00798       for (unsigned i = 0, e = filter.getNumFilters(); i != e; ++i)
00799         filterTypes.push_back(filter.getFilter(i));
00800       goto done;
00801     }
00802 
00803     case EHScope::Terminate:
00804       // Terminate scopes are basically catch-alls.
00805       assert(!hasCatchAll);
00806       hasCatchAll = true;
00807       goto done;
00808 
00809     case EHScope::Catch:
00810       break;
00811     }
00812 
00813     EHCatchScope &catchScope = cast<EHCatchScope>(*I);
00814     for (unsigned hi = 0, he = catchScope.getNumHandlers(); hi != he; ++hi) {
00815       EHCatchScope::Handler handler = catchScope.getHandler(hi);
00816 
00817       // If this is a catch-all, register that and abort.
00818       if (!handler.Type) {
00819         assert(!hasCatchAll);
00820         hasCatchAll = true;
00821         goto done;
00822       }
00823 
00824       // Check whether we already have a handler for this type.
00825       if (catchTypes.insert(handler.Type))
00826         // If not, add it directly to the landingpad.
00827         LPadInst->addClause(handler.Type);
00828     }
00829   }
00830 
00831  done:
00832   // If we have a catch-all, add null to the landingpad.
00833   assert(!(hasCatchAll && hasFilter));
00834   if (hasCatchAll) {
00835     LPadInst->addClause(getCatchAllValue(*this));
00836 
00837   // If we have an EH filter, we need to add those handlers in the
00838   // right place in the landingpad, which is to say, at the end.
00839   } else if (hasFilter) {
00840     // Create a filter expression: a constant array indicating which filter
00841     // types there are. The personality routine only lands here if the filter
00842     // doesn't match.
00843     llvm::SmallVector<llvm::Constant*, 8> Filters;
00844     llvm::ArrayType *AType =
00845       llvm::ArrayType::get(!filterTypes.empty() ?
00846                              filterTypes[0]->getType() : Int8PtrTy,
00847                            filterTypes.size());
00848 
00849     for (unsigned i = 0, e = filterTypes.size(); i != e; ++i)
00850       Filters.push_back(cast<llvm::Constant>(filterTypes[i]));
00851     llvm::Constant *FilterArray = llvm::ConstantArray::get(AType, Filters);
00852     LPadInst->addClause(FilterArray);
00853 
00854     // Also check whether we need a cleanup.
00855     if (hasCleanup)
00856       LPadInst->setCleanup(true);
00857 
00858   // Otherwise, signal that we at least have cleanups.
00859   } else if (CleanupHackLevel == CHL_MandatoryCatchall || hasCleanup) {
00860     if (CleanupHackLevel == CHL_MandatoryCatchall)
00861       LPadInst->addClause(getCatchAllValue(*this));
00862     else
00863       LPadInst->setCleanup(true);
00864   }
00865 
00866   assert((LPadInst->getNumClauses() > 0 || LPadInst->isCleanup()) &&
00867          "landingpad instruction has no clauses!");
00868 
00869   // Tell the backend how to generate the landing pad.
00870   Builder.CreateBr(getEHDispatchBlock(EHStack.getInnermostEHScope()));
00871 
00872   // Restore the old IR generation state.
00873   Builder.restoreIP(savedIP);
00874 
00875   return lpad;
00876 }
00877 
00878 namespace {
00879   /// A cleanup to call __cxa_end_catch.  In many cases, the caught
00880   /// exception type lets us state definitively that the thrown exception
00881   /// type does not have a destructor.  In particular:
00882   ///   - Catch-alls tell us nothing, so we have to conservatively
00883   ///     assume that the thrown exception might have a destructor.
00884   ///   - Catches by reference behave according to their base types.
00885   ///   - Catches of non-record types will only trigger for exceptions
00886   ///     of non-record types, which never have destructors.
00887   ///   - Catches of record types can trigger for arbitrary subclasses
00888   ///     of the caught type, so we have to assume the actual thrown
00889   ///     exception type might have a throwing destructor, even if the
00890   ///     caught type's destructor is trivial or nothrow.
00891   struct CallEndCatch : EHScopeStack::Cleanup {
00892     CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
00893     bool MightThrow;
00894 
00895     void Emit(CodeGenFunction &CGF, Flags flags) {
00896       if (!MightThrow) {
00897         CGF.Builder.CreateCall(getEndCatchFn(CGF))->setDoesNotThrow();
00898         return;
00899       }
00900 
00901       CGF.EmitCallOrInvoke(getEndCatchFn(CGF));
00902     }
00903   };
00904 }
00905 
00906 /// Emits a call to __cxa_begin_catch and enters a cleanup to call
00907 /// __cxa_end_catch.
00908 ///
00909 /// \param EndMightThrow - true if __cxa_end_catch might throw
00910 static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
00911                                    llvm::Value *Exn,
00912                                    bool EndMightThrow) {
00913   llvm::CallInst *Call = CGF.Builder.CreateCall(getBeginCatchFn(CGF), Exn);
00914   Call->setDoesNotThrow();
00915 
00916   CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
00917 
00918   return Call;
00919 }
00920 
00921 /// A "special initializer" callback for initializing a catch
00922 /// parameter during catch initialization.
00923 static void InitCatchParam(CodeGenFunction &CGF,
00924                            const VarDecl &CatchParam,
00925                            llvm::Value *ParamAddr) {
00926   // Load the exception from where the landing pad saved it.
00927   llvm::Value *Exn = CGF.getExceptionFromSlot();
00928 
00929   CanQualType CatchType =
00930     CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
00931   llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
00932 
00933   // If we're catching by reference, we can just cast the object
00934   // pointer to the appropriate pointer.
00935   if (isa<ReferenceType>(CatchType)) {
00936     QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
00937     bool EndCatchMightThrow = CaughtType->isRecordType();
00938 
00939     // __cxa_begin_catch returns the adjusted object pointer.
00940     llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
00941 
00942     // We have no way to tell the personality function that we're
00943     // catching by reference, so if we're catching a pointer,
00944     // __cxa_begin_catch will actually return that pointer by value.
00945     if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
00946       QualType PointeeType = PT->getPointeeType();
00947 
00948       // When catching by reference, generally we should just ignore
00949       // this by-value pointer and use the exception object instead.
00950       if (!PointeeType->isRecordType()) {
00951 
00952         // Exn points to the struct _Unwind_Exception header, which
00953         // we have to skip past in order to reach the exception data.
00954         unsigned HeaderSize =
00955           CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
00956         AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
00957 
00958       // However, if we're catching a pointer-to-record type that won't
00959       // work, because the personality function might have adjusted
00960       // the pointer.  There's actually no way for us to fully satisfy
00961       // the language/ABI contract here:  we can't use Exn because it
00962       // might have the wrong adjustment, but we can't use the by-value
00963       // pointer because it's off by a level of abstraction.
00964       //
00965       // The current solution is to dump the adjusted pointer into an
00966       // alloca, which breaks language semantics (because changing the
00967       // pointer doesn't change the exception) but at least works.
00968       // The better solution would be to filter out non-exact matches
00969       // and rethrow them, but this is tricky because the rethrow
00970       // really needs to be catchable by other sites at this landing
00971       // pad.  The best solution is to fix the personality function.
00972       } else {
00973         // Pull the pointer for the reference type off.
00974         llvm::Type *PtrTy =
00975           cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
00976 
00977         // Create the temporary and write the adjusted pointer into it.
00978         llvm::Value *ExnPtrTmp = CGF.CreateTempAlloca(PtrTy, "exn.byref.tmp");
00979         llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
00980         CGF.Builder.CreateStore(Casted, ExnPtrTmp);
00981 
00982         // Bind the reference to the temporary.
00983         AdjustedExn = ExnPtrTmp;
00984       }
00985     }
00986 
00987     llvm::Value *ExnCast =
00988       CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
00989     CGF.Builder.CreateStore(ExnCast, ParamAddr);
00990     return;
00991   }
00992 
00993   // Non-aggregates (plus complexes).
00994   bool IsComplex = false;
00995   if (!CGF.hasAggregateLLVMType(CatchType) ||
00996       (IsComplex = CatchType->isAnyComplexType())) {
00997     llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
00998     
00999     // If the catch type is a pointer type, __cxa_begin_catch returns
01000     // the pointer by value.
01001     if (CatchType->hasPointerRepresentation()) {
01002       llvm::Value *CastExn =
01003         CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
01004 
01005       switch (CatchType.getQualifiers().getObjCLifetime()) {
01006       case Qualifiers::OCL_Strong:
01007         CastExn = CGF.EmitARCRetainNonBlock(CastExn);
01008         // fallthrough
01009 
01010       case Qualifiers::OCL_None:
01011       case Qualifiers::OCL_ExplicitNone:
01012       case Qualifiers::OCL_Autoreleasing:
01013         CGF.Builder.CreateStore(CastExn, ParamAddr);
01014         return;
01015 
01016       case Qualifiers::OCL_Weak:
01017         CGF.EmitARCInitWeak(ParamAddr, CastExn);
01018         return;
01019       }
01020       llvm_unreachable("bad ownership qualifier!");
01021     }
01022 
01023     // Otherwise, it returns a pointer into the exception object.
01024 
01025     llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
01026     llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
01027 
01028     if (IsComplex) {
01029       CGF.StoreComplexToAddr(CGF.LoadComplexFromAddr(Cast, /*volatile*/ false),
01030                              ParamAddr, /*volatile*/ false);
01031     } else {
01032       unsigned Alignment =
01033         CGF.getContext().getDeclAlign(&CatchParam).getQuantity();
01034       llvm::Value *ExnLoad = CGF.Builder.CreateLoad(Cast, "exn.scalar");
01035       CGF.EmitStoreOfScalar(ExnLoad, ParamAddr, /*volatile*/ false, Alignment,
01036                             CatchType);
01037     }
01038     return;
01039   }
01040 
01041   assert(isa<RecordType>(CatchType) && "unexpected catch type!");
01042 
01043   llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
01044 
01045   // Check for a copy expression.  If we don't have a copy expression,
01046   // that means a trivial copy is okay.
01047   const Expr *copyExpr = CatchParam.getInit();
01048   if (!copyExpr) {
01049     llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
01050     llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
01051     CGF.EmitAggregateCopy(ParamAddr, adjustedExn, CatchType);
01052     return;
01053   }
01054 
01055   // We have to call __cxa_get_exception_ptr to get the adjusted
01056   // pointer before copying.
01057   llvm::CallInst *rawAdjustedExn =
01058     CGF.Builder.CreateCall(getGetExceptionPtrFn(CGF), Exn);
01059   rawAdjustedExn->setDoesNotThrow();
01060 
01061   // Cast that to the appropriate type.
01062   llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
01063 
01064   // The copy expression is defined in terms of an OpaqueValueExpr.
01065   // Find it and map it to the adjusted expression.
01066   CodeGenFunction::OpaqueValueMapping
01067     opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
01068            CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
01069 
01070   // Call the copy ctor in a terminate scope.
01071   CGF.EHStack.pushTerminate();
01072 
01073   // Perform the copy construction.
01074   CharUnits Alignment = CGF.getContext().getDeclAlign(&CatchParam);
01075   CGF.EmitAggExpr(copyExpr,
01076                   AggValueSlot::forAddr(ParamAddr, Alignment, Qualifiers(),
01077                                         AggValueSlot::IsNotDestructed,
01078                                         AggValueSlot::DoesNotNeedGCBarriers,
01079                                         AggValueSlot::IsNotAliased));
01080 
01081   // Leave the terminate scope.
01082   CGF.EHStack.popTerminate();
01083 
01084   // Undo the opaque value mapping.
01085   opaque.pop();
01086 
01087   // Finally we can call __cxa_begin_catch.
01088   CallBeginCatch(CGF, Exn, true);
01089 }
01090 
01091 /// Begins a catch statement by initializing the catch variable and
01092 /// calling __cxa_begin_catch.
01093 static void BeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *S) {
01094   // We have to be very careful with the ordering of cleanups here:
01095   //   C++ [except.throw]p4:
01096   //     The destruction [of the exception temporary] occurs
01097   //     immediately after the destruction of the object declared in
01098   //     the exception-declaration in the handler.
01099   //
01100   // So the precise ordering is:
01101   //   1.  Construct catch variable.
01102   //   2.  __cxa_begin_catch
01103   //   3.  Enter __cxa_end_catch cleanup
01104   //   4.  Enter dtor cleanup
01105   //
01106   // We do this by using a slightly abnormal initialization process.
01107   // Delegation sequence:
01108   //   - ExitCXXTryStmt opens a RunCleanupsScope
01109   //     - EmitAutoVarAlloca creates the variable and debug info
01110   //       - InitCatchParam initializes the variable from the exception
01111   //       - CallBeginCatch calls __cxa_begin_catch
01112   //       - CallBeginCatch enters the __cxa_end_catch cleanup
01113   //     - EmitAutoVarCleanups enters the variable destructor cleanup
01114   //   - EmitCXXTryStmt emits the code for the catch body
01115   //   - EmitCXXTryStmt close the RunCleanupsScope
01116 
01117   VarDecl *CatchParam = S->getExceptionDecl();
01118   if (!CatchParam) {
01119     llvm::Value *Exn = CGF.getExceptionFromSlot();
01120     CallBeginCatch(CGF, Exn, true);
01121     return;
01122   }
01123 
01124   // Emit the local.
01125   CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
01126   InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF));
01127   CGF.EmitAutoVarCleanups(var);
01128 }
01129 
01130 namespace {
01131   struct CallRethrow : EHScopeStack::Cleanup {
01132     void Emit(CodeGenFunction &CGF, Flags flags) {
01133       CGF.EmitCallOrInvoke(getReThrowFn(CGF));
01134     }
01135   };
01136 }
01137 
01138 /// Emit the structure of the dispatch block for the given catch scope.
01139 /// It is an invariant that the dispatch block already exists.
01140 static void emitCatchDispatchBlock(CodeGenFunction &CGF,
01141                                    EHCatchScope &catchScope) {
01142   llvm::BasicBlock *dispatchBlock = catchScope.getCachedEHDispatchBlock();
01143   assert(dispatchBlock);
01144 
01145   // If there's only a single catch-all, getEHDispatchBlock returned
01146   // that catch-all as the dispatch block.
01147   if (catchScope.getNumHandlers() == 1 &&
01148       catchScope.getHandler(0).isCatchAll()) {
01149     assert(dispatchBlock == catchScope.getHandler(0).Block);
01150     return;
01151   }
01152 
01153   CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveIP();
01154   CGF.EmitBlockAfterUses(dispatchBlock);
01155 
01156   // Select the right handler.
01157   llvm::Value *llvm_eh_typeid_for =
01158     CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
01159 
01160   // Load the selector value.
01161   llvm::Value *selector = CGF.getSelectorFromSlot();
01162 
01163   // Test against each of the exception types we claim to catch.
01164   for (unsigned i = 0, e = catchScope.getNumHandlers(); ; ++i) {
01165     assert(i < e && "ran off end of handlers!");
01166     const EHCatchScope::Handler &handler = catchScope.getHandler(i);
01167 
01168     llvm::Value *typeValue = handler.Type;
01169     assert(typeValue && "fell into catch-all case!");
01170     typeValue = CGF.Builder.CreateBitCast(typeValue, CGF.Int8PtrTy);
01171 
01172     // Figure out the next block.
01173     bool nextIsEnd;
01174     llvm::BasicBlock *nextBlock;
01175 
01176     // If this is the last handler, we're at the end, and the next
01177     // block is the block for the enclosing EH scope.
01178     if (i + 1 == e) {
01179       nextBlock = CGF.getEHDispatchBlock(catchScope.getEnclosingEHScope());
01180       nextIsEnd = true;
01181 
01182     // If the next handler is a catch-all, we're at the end, and the
01183     // next block is that handler.
01184     } else if (catchScope.getHandler(i+1).isCatchAll()) {
01185       nextBlock = catchScope.getHandler(i+1).Block;
01186       nextIsEnd = true;
01187 
01188     // Otherwise, we're not at the end and we need a new block.
01189     } else {
01190       nextBlock = CGF.createBasicBlock("catch.fallthrough");
01191       nextIsEnd = false;
01192     }
01193 
01194     // Figure out the catch type's index in the LSDA's type table.
01195     llvm::CallInst *typeIndex =
01196       CGF.Builder.CreateCall(llvm_eh_typeid_for, typeValue);
01197     typeIndex->setDoesNotThrow();
01198 
01199     llvm::Value *matchesTypeIndex =
01200       CGF.Builder.CreateICmpEQ(selector, typeIndex, "matches");
01201     CGF.Builder.CreateCondBr(matchesTypeIndex, handler.Block, nextBlock);
01202 
01203     // If the next handler is a catch-all, we're completely done.
01204     if (nextIsEnd) {
01205       CGF.Builder.restoreIP(savedIP);
01206       return;
01207     }
01208     // Otherwise we need to emit and continue at that block.
01209     CGF.EmitBlock(nextBlock);
01210   }
01211 }
01212 
01213 void CodeGenFunction::popCatchScope() {
01214   EHCatchScope &catchScope = cast<EHCatchScope>(*EHStack.begin());
01215   if (catchScope.hasEHBranches())
01216     emitCatchDispatchBlock(*this, catchScope);
01217   EHStack.popCatch();
01218 }
01219 
01220 void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
01221   unsigned NumHandlers = S.getNumHandlers();
01222   EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
01223   assert(CatchScope.getNumHandlers() == NumHandlers);
01224 
01225   // If the catch was not required, bail out now.
01226   if (!CatchScope.hasEHBranches()) {
01227     EHStack.popCatch();
01228     return;
01229   }
01230 
01231   // Emit the structure of the EH dispatch for this catch.
01232   emitCatchDispatchBlock(*this, CatchScope);
01233 
01234   // Copy the handler blocks off before we pop the EH stack.  Emitting
01235   // the handlers might scribble on this memory.
01236   SmallVector<EHCatchScope::Handler, 8> Handlers(NumHandlers);
01237   memcpy(Handlers.data(), CatchScope.begin(),
01238          NumHandlers * sizeof(EHCatchScope::Handler));
01239 
01240   EHStack.popCatch();
01241 
01242   // The fall-through block.
01243   llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
01244 
01245   // We just emitted the body of the try; jump to the continue block.
01246   if (HaveInsertPoint())
01247     Builder.CreateBr(ContBB);
01248 
01249   // Determine if we need an implicit rethrow for all these catch handlers.
01250   bool ImplicitRethrow = false;
01251   if (IsFnTryBlock)
01252     ImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
01253                       isa<CXXConstructorDecl>(CurCodeDecl);
01254 
01255   // Perversely, we emit the handlers backwards precisely because we
01256   // want them to appear in source order.  In all of these cases, the
01257   // catch block will have exactly one predecessor, which will be a
01258   // particular block in the catch dispatch.  However, in the case of
01259   // a catch-all, one of the dispatch blocks will branch to two
01260   // different handlers, and EmitBlockAfterUses will cause the second
01261   // handler to be moved before the first.
01262   for (unsigned I = NumHandlers; I != 0; --I) {
01263     llvm::BasicBlock *CatchBlock = Handlers[I-1].Block;
01264     EmitBlockAfterUses(CatchBlock);
01265 
01266     // Catch the exception if this isn't a catch-all.
01267     const CXXCatchStmt *C = S.getHandler(I-1);
01268 
01269     // Enter a cleanup scope, including the catch variable and the
01270     // end-catch.
01271     RunCleanupsScope CatchScope(*this);
01272 
01273     // Initialize the catch variable and set up the cleanups.
01274     BeginCatch(*this, C);
01275 
01276     // If there's an implicit rethrow, push a normal "cleanup" to call
01277     // _cxa_rethrow.  This needs to happen before __cxa_end_catch is
01278     // called, and so it is pushed after BeginCatch.
01279     if (ImplicitRethrow)
01280       EHStack.pushCleanup<CallRethrow>(NormalCleanup);
01281 
01282     // Perform the body of the catch.
01283     EmitStmt(C->getHandlerBlock());
01284 
01285     // Fall out through the catch cleanups.
01286     CatchScope.ForceCleanup();
01287 
01288     // Branch out of the try.
01289     if (HaveInsertPoint())
01290       Builder.CreateBr(ContBB);
01291   }
01292 
01293   EmitBlock(ContBB);
01294 }
01295 
01296 namespace {
01297   struct CallEndCatchForFinally : EHScopeStack::Cleanup {
01298     llvm::Value *ForEHVar;
01299     llvm::Value *EndCatchFn;
01300     CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn)
01301       : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
01302 
01303     void Emit(CodeGenFunction &CGF, Flags flags) {
01304       llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
01305       llvm::BasicBlock *CleanupContBB =
01306         CGF.createBasicBlock("finally.cleanup.cont");
01307 
01308       llvm::Value *ShouldEndCatch =
01309         CGF.Builder.CreateLoad(ForEHVar, "finally.endcatch");
01310       CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
01311       CGF.EmitBlock(EndCatchBB);
01312       CGF.EmitCallOrInvoke(EndCatchFn); // catch-all, so might throw
01313       CGF.EmitBlock(CleanupContBB);
01314     }
01315   };
01316 
01317   struct PerformFinally : EHScopeStack::Cleanup {
01318     const Stmt *Body;
01319     llvm::Value *ForEHVar;
01320     llvm::Value *EndCatchFn;
01321     llvm::Value *RethrowFn;
01322     llvm::Value *SavedExnVar;
01323 
01324     PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
01325                    llvm::Value *EndCatchFn,
01326                    llvm::Value *RethrowFn, llvm::Value *SavedExnVar)
01327       : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
01328         RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
01329 
01330     void Emit(CodeGenFunction &CGF, Flags flags) {
01331       // Enter a cleanup to call the end-catch function if one was provided.
01332       if (EndCatchFn)
01333         CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
01334                                                         ForEHVar, EndCatchFn);
01335 
01336       // Save the current cleanup destination in case there are
01337       // cleanups in the finally block.
01338       llvm::Value *SavedCleanupDest =
01339         CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
01340                                "cleanup.dest.saved");
01341 
01342       // Emit the finally block.
01343       CGF.EmitStmt(Body);
01344 
01345       // If the end of the finally is reachable, check whether this was
01346       // for EH.  If so, rethrow.
01347       if (CGF.HaveInsertPoint()) {
01348         llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
01349         llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
01350 
01351         llvm::Value *ShouldRethrow =
01352           CGF.Builder.CreateLoad(ForEHVar, "finally.shouldthrow");
01353         CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
01354 
01355         CGF.EmitBlock(RethrowBB);
01356         if (SavedExnVar) {
01357           CGF.EmitCallOrInvoke(RethrowFn, CGF.Builder.CreateLoad(SavedExnVar));
01358         } else {
01359           CGF.EmitCallOrInvoke(RethrowFn);
01360         }
01361         CGF.Builder.CreateUnreachable();
01362 
01363         CGF.EmitBlock(ContBB);
01364 
01365         // Restore the cleanup destination.
01366         CGF.Builder.CreateStore(SavedCleanupDest,
01367                                 CGF.getNormalCleanupDestSlot());
01368       }
01369 
01370       // Leave the end-catch cleanup.  As an optimization, pretend that
01371       // the fallthrough path was inaccessible; we've dynamically proven
01372       // that we're not in the EH case along that path.
01373       if (EndCatchFn) {
01374         CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
01375         CGF.PopCleanupBlock();
01376         CGF.Builder.restoreIP(SavedIP);
01377       }
01378     
01379       // Now make sure we actually have an insertion point or the
01380       // cleanup gods will hate us.
01381       CGF.EnsureInsertPoint();
01382     }
01383   };
01384 }
01385 
01386 /// Enters a finally block for an implementation using zero-cost
01387 /// exceptions.  This is mostly general, but hard-codes some
01388 /// language/ABI-specific behavior in the catch-all sections.
01389 void CodeGenFunction::FinallyInfo::enter(CodeGenFunction &CGF,
01390                                          const Stmt *body,
01391                                          llvm::Constant *beginCatchFn,
01392                                          llvm::Constant *endCatchFn,
01393                                          llvm::Constant *rethrowFn) {
01394   assert((beginCatchFn != 0) == (endCatchFn != 0) &&
01395          "begin/end catch functions not paired");
01396   assert(rethrowFn && "rethrow function is required");
01397 
01398   BeginCatchFn = beginCatchFn;
01399 
01400   // The rethrow function has one of the following two types:
01401   //   void (*)()
01402   //   void (*)(void*)
01403   // In the latter case we need to pass it the exception object.
01404   // But we can't use the exception slot because the @finally might
01405   // have a landing pad (which would overwrite the exception slot).
01406   llvm::FunctionType *rethrowFnTy =
01407     cast<llvm::FunctionType>(
01408       cast<llvm::PointerType>(rethrowFn->getType())->getElementType());
01409   SavedExnVar = 0;
01410   if (rethrowFnTy->getNumParams())
01411     SavedExnVar = CGF.CreateTempAlloca(CGF.Int8PtrTy, "finally.exn");
01412 
01413   // A finally block is a statement which must be executed on any edge
01414   // out of a given scope.  Unlike a cleanup, the finally block may
01415   // contain arbitrary control flow leading out of itself.  In
01416   // addition, finally blocks should always be executed, even if there
01417   // are no catch handlers higher on the stack.  Therefore, we
01418   // surround the protected scope with a combination of a normal
01419   // cleanup (to catch attempts to break out of the block via normal
01420   // control flow) and an EH catch-all (semantically "outside" any try
01421   // statement to which the finally block might have been attached).
01422   // The finally block itself is generated in the context of a cleanup
01423   // which conditionally leaves the catch-all.
01424 
01425   // Jump destination for performing the finally block on an exception
01426   // edge.  We'll never actually reach this block, so unreachable is
01427   // fine.
01428   RethrowDest = CGF.getJumpDestInCurrentScope(CGF.getUnreachableBlock());
01429 
01430   // Whether the finally block is being executed for EH purposes.
01431   ForEHVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "finally.for-eh");
01432   CGF.Builder.CreateStore(CGF.Builder.getFalse(), ForEHVar);
01433 
01434   // Enter a normal cleanup which will perform the @finally block.
01435   CGF.EHStack.pushCleanup<PerformFinally>(NormalCleanup, body,
01436                                           ForEHVar, endCatchFn,
01437                                           rethrowFn, SavedExnVar);
01438 
01439   // Enter a catch-all scope.
01440   llvm::BasicBlock *catchBB = CGF.createBasicBlock("finally.catchall");
01441   EHCatchScope *catchScope = CGF.EHStack.pushCatch(1);
01442   catchScope->setCatchAllHandler(0, catchBB);
01443 }
01444 
01445 void CodeGenFunction::FinallyInfo::exit(CodeGenFunction &CGF) {
01446   // Leave the finally catch-all.
01447   EHCatchScope &catchScope = cast<EHCatchScope>(*CGF.EHStack.begin());
01448   llvm::BasicBlock *catchBB = catchScope.getHandler(0).Block;
01449 
01450   CGF.popCatchScope();
01451 
01452   // If there are any references to the catch-all block, emit it.
01453   if (catchBB->use_empty()) {
01454     delete catchBB;
01455   } else {
01456     CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveAndClearIP();
01457     CGF.EmitBlock(catchBB);
01458 
01459     llvm::Value *exn = 0;
01460 
01461     // If there's a begin-catch function, call it.
01462     if (BeginCatchFn) {
01463       exn = CGF.getExceptionFromSlot();
01464       CGF.Builder.CreateCall(BeginCatchFn, exn)->setDoesNotThrow();
01465     }
01466 
01467     // If we need to remember the exception pointer to rethrow later, do so.
01468     if (SavedExnVar) {
01469       if (!exn) exn = CGF.getExceptionFromSlot();
01470       CGF.Builder.CreateStore(exn, SavedExnVar);
01471     }
01472 
01473     // Tell the cleanups in the finally block that we're do this for EH.
01474     CGF.Builder.CreateStore(CGF.Builder.getTrue(), ForEHVar);
01475 
01476     // Thread a jump through the finally cleanup.
01477     CGF.EmitBranchThroughCleanup(RethrowDest);
01478 
01479     CGF.Builder.restoreIP(savedIP);
01480   }
01481 
01482   // Finally, leave the @finally cleanup.
01483   CGF.PopCleanupBlock();
01484 }
01485 
01486 llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
01487   if (TerminateLandingPad)
01488     return TerminateLandingPad;
01489 
01490   CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
01491 
01492   // This will get inserted at the end of the function.
01493   TerminateLandingPad = createBasicBlock("terminate.lpad");
01494   Builder.SetInsertPoint(TerminateLandingPad);
01495 
01496   // Tell the backend that this is a landing pad.
01497   const EHPersonality &Personality = EHPersonality::get(CGM.getLangOpts());
01498   llvm::LandingPadInst *LPadInst =
01499     Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, NULL),
01500                              getOpaquePersonalityFn(CGM, Personality), 0);
01501   LPadInst->addClause(getCatchAllValue(*this));
01502 
01503   llvm::CallInst *TerminateCall = Builder.CreateCall(getTerminateFn(*this));
01504   TerminateCall->setDoesNotReturn();
01505   TerminateCall->setDoesNotThrow();
01506   Builder.CreateUnreachable();
01507 
01508   // Restore the saved insertion state.
01509   Builder.restoreIP(SavedIP);
01510 
01511   return TerminateLandingPad;
01512 }
01513 
01514 llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
01515   if (TerminateHandler)
01516     return TerminateHandler;
01517 
01518   CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
01519 
01520   // Set up the terminate handler.  This block is inserted at the very
01521   // end of the function by FinishFunction.
01522   TerminateHandler = createBasicBlock("terminate.handler");
01523   Builder.SetInsertPoint(TerminateHandler);
01524   llvm::CallInst *TerminateCall = Builder.CreateCall(getTerminateFn(*this));
01525   TerminateCall->setDoesNotReturn();
01526   TerminateCall->setDoesNotThrow();
01527   Builder.CreateUnreachable();
01528 
01529   // Restore the saved insertion state.
01530   Builder.restoreIP(SavedIP);
01531 
01532   return TerminateHandler;
01533 }
01534 
01535 llvm::BasicBlock *CodeGenFunction::getEHResumeBlock() {
01536   if (EHResumeBlock) return EHResumeBlock;
01537 
01538   CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
01539 
01540   // We emit a jump to a notional label at the outermost unwind state.
01541   EHResumeBlock = createBasicBlock("eh.resume");
01542   Builder.SetInsertPoint(EHResumeBlock);
01543 
01544   const EHPersonality &Personality = EHPersonality::get(CGM.getLangOpts());
01545 
01546   // This can always be a call because we necessarily didn't find
01547   // anything on the EH stack which needs our help.
01548   const char *RethrowName = Personality.CatchallRethrowFn;
01549   if (RethrowName != 0) {
01550     Builder.CreateCall(getCatchallRethrowFn(*this, RethrowName),
01551                        getExceptionFromSlot())
01552       ->setDoesNotReturn();
01553   } else {
01554     switch (CleanupHackLevel) {
01555     case CHL_MandatoryCatchall:
01556       // In mandatory-catchall mode, we need to use
01557       // _Unwind_Resume_or_Rethrow, or whatever the personality's
01558       // equivalent is.
01559       Builder.CreateCall(getUnwindResumeOrRethrowFn(),
01560                          getExceptionFromSlot())
01561         ->setDoesNotReturn();
01562       break;
01563     case CHL_MandatoryCleanup: {
01564       // In mandatory-cleanup mode, we should use 'resume'.
01565 
01566       // Recreate the landingpad's return value for the 'resume' instruction.
01567       llvm::Value *Exn = getExceptionFromSlot();
01568       llvm::Value *Sel = getSelectorFromSlot();
01569 
01570       llvm::Type *LPadType = llvm::StructType::get(Exn->getType(),
01571                                                    Sel->getType(), NULL);
01572       llvm::Value *LPadVal = llvm::UndefValue::get(LPadType);
01573       LPadVal = Builder.CreateInsertValue(LPadVal, Exn, 0, "lpad.val");
01574       LPadVal = Builder.CreateInsertValue(LPadVal, Sel, 1, "lpad.val");
01575 
01576       Builder.CreateResume(LPadVal);
01577       Builder.restoreIP(SavedIP);
01578       return EHResumeBlock;
01579     }
01580     case CHL_Ideal:
01581       // In an idealized mode where we don't have to worry about the
01582       // optimizer combining landing pads, we should just use
01583       // _Unwind_Resume (or the personality's equivalent).
01584       Builder.CreateCall(getUnwindResumeFn(), getExceptionFromSlot())
01585         ->setDoesNotReturn();
01586       break;
01587     }
01588   }
01589 
01590   Builder.CreateUnreachable();
01591 
01592   Builder.restoreIP(SavedIP);
01593 
01594   return EHResumeBlock;
01595 }