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