1 //===--- CGException.cpp - Emit LLVM Code for C++ exceptions --------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This contains code dealing with C++ exception related code generation. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "CodeGenFunction.h" 15 #include "CGCleanup.h" 16 #include "CGCXXABI.h" 17 #include "CGObjCRuntime.h" 18 #include "TargetInfo.h" 19 #include "clang/AST/StmtCXX.h" 20 #include "clang/AST/StmtObjC.h" 21 #include "llvm/IR/CallSite.h" 22 #include "llvm/IR/Intrinsics.h" 23 24 using namespace clang; 25 using namespace CodeGen; 26 27 static llvm::Constant *getAllocateExceptionFn(CodeGenModule &CGM) { 28 // void *__cxa_allocate_exception(size_t thrown_size); 29 30 llvm::FunctionType *FTy = 31 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.SizeTy, /*IsVarArgs=*/false); 32 33 return CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception"); 34 } 35 36 static llvm::Constant *getFreeExceptionFn(CodeGenModule &CGM) { 37 // void __cxa_free_exception(void *thrown_exception); 38 39 llvm::FunctionType *FTy = 40 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false); 41 42 return CGM.CreateRuntimeFunction(FTy, "__cxa_free_exception"); 43 } 44 45 static llvm::Constant *getThrowFn(CodeGenModule &CGM) { 46 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo, 47 // void (*dest) (void *)); 48 49 llvm::Type *Args[3] = { CGM.Int8PtrTy, CGM.Int8PtrTy, CGM.Int8PtrTy }; 50 llvm::FunctionType *FTy = 51 llvm::FunctionType::get(CGM.VoidTy, Args, /*IsVarArgs=*/false); 52 53 return CGM.CreateRuntimeFunction(FTy, "__cxa_throw"); 54 } 55 56 static llvm::Constant *getGetExceptionPtrFn(CodeGenModule &CGM) { 57 // void *__cxa_get_exception_ptr(void*); 58 59 llvm::FunctionType *FTy = 60 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false); 61 62 return CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr"); 63 } 64 65 static llvm::Constant *getBeginCatchFn(CodeGenModule &CGM) { 66 // void *__cxa_begin_catch(void*); 67 68 llvm::FunctionType *FTy = 69 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false); 70 71 return CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch"); 72 } 73 74 static llvm::Constant *getEndCatchFn(CodeGenModule &CGM) { 75 // void __cxa_end_catch(); 76 77 llvm::FunctionType *FTy = 78 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false); 79 80 return CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch"); 81 } 82 83 static llvm::Constant *getUnexpectedFn(CodeGenModule &CGM) { 84 // void __cxa_call_unexpected(void *thrown_exception); 85 86 llvm::FunctionType *FTy = 87 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false); 88 89 return CGM.CreateRuntimeFunction(FTy, "__cxa_call_unexpected"); 90 } 91 92 static llvm::Constant *getTerminateFn(CodeGenModule &CGM) { 93 // void __terminate(); 94 95 llvm::FunctionType *FTy = 96 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false); 97 98 StringRef name; 99 100 // In C++, use std::terminate(). 101 if (CGM.getLangOpts().CPlusPlus) 102 name = "_ZSt9terminatev"; // FIXME: mangling! 103 else if (CGM.getLangOpts().ObjC1 && 104 CGM.getLangOpts().ObjCRuntime.hasTerminate()) 105 name = "objc_terminate"; 106 else 107 name = "abort"; 108 return CGM.CreateRuntimeFunction(FTy, name); 109 } 110 111 static llvm::Constant *getCatchallRethrowFn(CodeGenModule &CGM, 112 StringRef Name) { 113 llvm::FunctionType *FTy = 114 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false); 115 116 return CGM.CreateRuntimeFunction(FTy, Name); 117 } 118 119 namespace { 120 /// The exceptions personality for a function. 121 struct EHPersonality { 122 const char *PersonalityFn; 123 124 // If this is non-null, this personality requires a non-standard 125 // function for rethrowing an exception after a catchall cleanup. 126 // This function must have prototype void(void*). 127 const char *CatchallRethrowFn; 128 129 static const EHPersonality &get(CodeGenModule &CGM); 130 static const EHPersonality GNU_C; 131 static const EHPersonality GNU_C_SJLJ; 132 static const EHPersonality GNU_C_SEH; 133 static const EHPersonality GNU_ObjC; 134 static const EHPersonality GNUstep_ObjC; 135 static const EHPersonality GNU_ObjCXX; 136 static const EHPersonality NeXT_ObjC; 137 static const EHPersonality GNU_CPlusPlus; 138 static const EHPersonality GNU_CPlusPlus_SJLJ; 139 static const EHPersonality GNU_CPlusPlus_SEH; 140 }; 141 } 142 143 const EHPersonality EHPersonality::GNU_C = { "__gcc_personality_v0", nullptr }; 144 const EHPersonality 145 EHPersonality::GNU_C_SJLJ = { "__gcc_personality_sj0", nullptr }; 146 const EHPersonality 147 EHPersonality::GNU_C_SEH = { "__gcc_personality_seh0", nullptr }; 148 const EHPersonality 149 EHPersonality::NeXT_ObjC = { "__objc_personality_v0", nullptr }; 150 const EHPersonality 151 EHPersonality::GNU_CPlusPlus = { "__gxx_personality_v0", nullptr }; 152 const EHPersonality 153 EHPersonality::GNU_CPlusPlus_SJLJ = { "__gxx_personality_sj0", nullptr }; 154 const EHPersonality 155 EHPersonality::GNU_CPlusPlus_SEH = { "__gxx_personality_seh0", nullptr }; 156 const EHPersonality 157 EHPersonality::GNU_ObjC = {"__gnu_objc_personality_v0", "objc_exception_throw"}; 158 const EHPersonality 159 EHPersonality::GNU_ObjCXX = { "__gnustep_objcxx_personality_v0", nullptr }; 160 const EHPersonality 161 EHPersonality::GNUstep_ObjC = { "__gnustep_objc_personality_v0", nullptr }; 162 163 /// On Win64, use libgcc's SEH personality function. We fall back to dwarf on 164 /// other platforms, unless the user asked for SjLj exceptions. 165 static bool useLibGCCSEHPersonality(const llvm::Triple &T) { 166 return T.isOSWindows() && T.getArch() == llvm::Triple::x86_64; 167 } 168 169 static const EHPersonality &getCPersonality(const llvm::Triple &T, 170 const LangOptions &L) { 171 if (L.SjLjExceptions) 172 return EHPersonality::GNU_C_SJLJ; 173 else if (useLibGCCSEHPersonality(T)) 174 return EHPersonality::GNU_C_SEH; 175 return EHPersonality::GNU_C; 176 } 177 178 static const EHPersonality &getObjCPersonality(const llvm::Triple &T, 179 const LangOptions &L) { 180 switch (L.ObjCRuntime.getKind()) { 181 case ObjCRuntime::FragileMacOSX: 182 return getCPersonality(T, L); 183 case ObjCRuntime::MacOSX: 184 case ObjCRuntime::iOS: 185 return EHPersonality::NeXT_ObjC; 186 case ObjCRuntime::GNUstep: 187 if (L.ObjCRuntime.getVersion() >= VersionTuple(1, 7)) 188 return EHPersonality::GNUstep_ObjC; 189 // fallthrough 190 case ObjCRuntime::GCC: 191 case ObjCRuntime::ObjFW: 192 return EHPersonality::GNU_ObjC; 193 } 194 llvm_unreachable("bad runtime kind"); 195 } 196 197 static const EHPersonality &getCXXPersonality(const llvm::Triple &T, 198 const LangOptions &L) { 199 if (L.SjLjExceptions) 200 return EHPersonality::GNU_CPlusPlus_SJLJ; 201 else if (useLibGCCSEHPersonality(T)) 202 return EHPersonality::GNU_CPlusPlus_SEH; 203 return EHPersonality::GNU_CPlusPlus; 204 } 205 206 /// Determines the personality function to use when both C++ 207 /// and Objective-C exceptions are being caught. 208 static const EHPersonality &getObjCXXPersonality(const llvm::Triple &T, 209 const LangOptions &L) { 210 switch (L.ObjCRuntime.getKind()) { 211 // The ObjC personality defers to the C++ personality for non-ObjC 212 // handlers. Unlike the C++ case, we use the same personality 213 // function on targets using (backend-driven) SJLJ EH. 214 case ObjCRuntime::MacOSX: 215 case ObjCRuntime::iOS: 216 return EHPersonality::NeXT_ObjC; 217 218 // In the fragile ABI, just use C++ exception handling and hope 219 // they're not doing crazy exception mixing. 220 case ObjCRuntime::FragileMacOSX: 221 return getCXXPersonality(T, L); 222 223 // The GCC runtime's personality function inherently doesn't support 224 // mixed EH. Use the C++ personality just to avoid returning null. 225 case ObjCRuntime::GCC: 226 case ObjCRuntime::ObjFW: // XXX: this will change soon 227 return EHPersonality::GNU_ObjC; 228 case ObjCRuntime::GNUstep: 229 return EHPersonality::GNU_ObjCXX; 230 } 231 llvm_unreachable("bad runtime kind"); 232 } 233 234 const EHPersonality &EHPersonality::get(CodeGenModule &CGM) { 235 const llvm::Triple &T = CGM.getTarget().getTriple(); 236 const LangOptions &L = CGM.getLangOpts(); 237 if (L.CPlusPlus && L.ObjC1) 238 return getObjCXXPersonality(T, L); 239 else if (L.CPlusPlus) 240 return getCXXPersonality(T, L); 241 else if (L.ObjC1) 242 return getObjCPersonality(T, L); 243 else 244 return getCPersonality(T, L); 245 } 246 247 static llvm::Constant *getPersonalityFn(CodeGenModule &CGM, 248 const EHPersonality &Personality) { 249 llvm::Constant *Fn = 250 CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.Int32Ty, true), 251 Personality.PersonalityFn); 252 return Fn; 253 } 254 255 static llvm::Constant *getOpaquePersonalityFn(CodeGenModule &CGM, 256 const EHPersonality &Personality) { 257 llvm::Constant *Fn = getPersonalityFn(CGM, Personality); 258 return llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy); 259 } 260 261 /// Check whether a personality function could reasonably be swapped 262 /// for a C++ personality function. 263 static bool PersonalityHasOnlyCXXUses(llvm::Constant *Fn) { 264 for (llvm::User *U : Fn->users()) { 265 // Conditionally white-list bitcasts. 266 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(U)) { 267 if (CE->getOpcode() != llvm::Instruction::BitCast) return false; 268 if (!PersonalityHasOnlyCXXUses(CE)) 269 return false; 270 continue; 271 } 272 273 // Otherwise, it has to be a landingpad instruction. 274 llvm::LandingPadInst *LPI = dyn_cast<llvm::LandingPadInst>(U); 275 if (!LPI) return false; 276 277 for (unsigned I = 0, E = LPI->getNumClauses(); I != E; ++I) { 278 // Look for something that would've been returned by the ObjC 279 // runtime's GetEHType() method. 280 llvm::Value *Val = LPI->getClause(I)->stripPointerCasts(); 281 if (LPI->isCatch(I)) { 282 // Check if the catch value has the ObjC prefix. 283 if (llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Val)) 284 // ObjC EH selector entries are always global variables with 285 // names starting like this. 286 if (GV->getName().startswith("OBJC_EHTYPE")) 287 return false; 288 } else { 289 // Check if any of the filter values have the ObjC prefix. 290 llvm::Constant *CVal = cast<llvm::Constant>(Val); 291 for (llvm::User::op_iterator 292 II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II) { 293 if (llvm::GlobalVariable *GV = 294 cast<llvm::GlobalVariable>((*II)->stripPointerCasts())) 295 // ObjC EH selector entries are always global variables with 296 // names starting like this. 297 if (GV->getName().startswith("OBJC_EHTYPE")) 298 return false; 299 } 300 } 301 } 302 } 303 304 return true; 305 } 306 307 /// Try to use the C++ personality function in ObjC++. Not doing this 308 /// can cause some incompatibilities with gcc, which is more 309 /// aggressive about only using the ObjC++ personality in a function 310 /// when it really needs it. 311 void CodeGenModule::SimplifyPersonality() { 312 // If we're not in ObjC++ -fexceptions, there's nothing to do. 313 if (!LangOpts.CPlusPlus || !LangOpts.ObjC1 || !LangOpts.Exceptions) 314 return; 315 316 // Both the problem this endeavors to fix and the way the logic 317 // above works is specific to the NeXT runtime. 318 if (!LangOpts.ObjCRuntime.isNeXTFamily()) 319 return; 320 321 const EHPersonality &ObjCXX = EHPersonality::get(*this); 322 const EHPersonality &CXX = 323 getCXXPersonality(getTarget().getTriple(), LangOpts); 324 if (&ObjCXX == &CXX) 325 return; 326 327 assert(std::strcmp(ObjCXX.PersonalityFn, CXX.PersonalityFn) != 0 && 328 "Different EHPersonalities using the same personality function."); 329 330 llvm::Function *Fn = getModule().getFunction(ObjCXX.PersonalityFn); 331 332 // Nothing to do if it's unused. 333 if (!Fn || Fn->use_empty()) return; 334 335 // Can't do the optimization if it has non-C++ uses. 336 if (!PersonalityHasOnlyCXXUses(Fn)) return; 337 338 // Create the C++ personality function and kill off the old 339 // function. 340 llvm::Constant *CXXFn = getPersonalityFn(*this, CXX); 341 342 // This can happen if the user is screwing with us. 343 if (Fn->getType() != CXXFn->getType()) return; 344 345 Fn->replaceAllUsesWith(CXXFn); 346 Fn->eraseFromParent(); 347 } 348 349 /// Returns the value to inject into a selector to indicate the 350 /// presence of a catch-all. 351 static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) { 352 // Possibly we should use @llvm.eh.catch.all.value here. 353 return llvm::ConstantPointerNull::get(CGF.Int8PtrTy); 354 } 355 356 namespace { 357 /// A cleanup to free the exception object if its initialization 358 /// throws. 359 struct FreeException : EHScopeStack::Cleanup { 360 llvm::Value *exn; 361 FreeException(llvm::Value *exn) : exn(exn) {} 362 void Emit(CodeGenFunction &CGF, Flags flags) override { 363 CGF.EmitNounwindRuntimeCall(getFreeExceptionFn(CGF.CGM), exn); 364 } 365 }; 366 } 367 368 // Emits an exception expression into the given location. This 369 // differs from EmitAnyExprToMem only in that, if a final copy-ctor 370 // call is required, an exception within that copy ctor causes 371 // std::terminate to be invoked. 372 static void EmitAnyExprToExn(CodeGenFunction &CGF, const Expr *e, 373 llvm::Value *addr) { 374 // Make sure the exception object is cleaned up if there's an 375 // exception during initialization. 376 CGF.pushFullExprCleanup<FreeException>(EHCleanup, addr); 377 EHScopeStack::stable_iterator cleanup = CGF.EHStack.stable_begin(); 378 379 // __cxa_allocate_exception returns a void*; we need to cast this 380 // to the appropriate type for the object. 381 llvm::Type *ty = CGF.ConvertTypeForMem(e->getType())->getPointerTo(); 382 llvm::Value *typedAddr = CGF.Builder.CreateBitCast(addr, ty); 383 384 // FIXME: this isn't quite right! If there's a final unelided call 385 // to a copy constructor, then according to [except.terminate]p1 we 386 // must call std::terminate() if that constructor throws, because 387 // technically that copy occurs after the exception expression is 388 // evaluated but before the exception is caught. But the best way 389 // to handle that is to teach EmitAggExpr to do the final copy 390 // differently if it can't be elided. 391 CGF.EmitAnyExprToMem(e, typedAddr, e->getType().getQualifiers(), 392 /*IsInit*/ true); 393 394 // Deactivate the cleanup block. 395 CGF.DeactivateCleanupBlock(cleanup, cast<llvm::Instruction>(typedAddr)); 396 } 397 398 llvm::Value *CodeGenFunction::getExceptionSlot() { 399 if (!ExceptionSlot) 400 ExceptionSlot = CreateTempAlloca(Int8PtrTy, "exn.slot"); 401 return ExceptionSlot; 402 } 403 404 llvm::Value *CodeGenFunction::getEHSelectorSlot() { 405 if (!EHSelectorSlot) 406 EHSelectorSlot = CreateTempAlloca(Int32Ty, "ehselector.slot"); 407 return EHSelectorSlot; 408 } 409 410 llvm::Value *CodeGenFunction::getExceptionFromSlot() { 411 return Builder.CreateLoad(getExceptionSlot(), "exn"); 412 } 413 414 llvm::Value *CodeGenFunction::getSelectorFromSlot() { 415 return Builder.CreateLoad(getEHSelectorSlot(), "sel"); 416 } 417 418 void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E, 419 bool KeepInsertionPoint) { 420 if (!E->getSubExpr()) { 421 CGM.getCXXABI().emitRethrow(*this, /*isNoReturn*/true); 422 423 // throw is an expression, and the expression emitters expect us 424 // to leave ourselves at a valid insertion point. 425 if (KeepInsertionPoint) 426 EmitBlock(createBasicBlock("throw.cont")); 427 428 return; 429 } 430 431 if (CGM.getTarget().getTriple().isKnownWindowsMSVCEnvironment()) { 432 ErrorUnsupported(E, "throw expression"); 433 return; 434 } 435 436 QualType ThrowType = E->getSubExpr()->getType(); 437 438 if (ThrowType->isObjCObjectPointerType()) { 439 const Stmt *ThrowStmt = E->getSubExpr(); 440 const ObjCAtThrowStmt S(E->getExprLoc(), 441 const_cast<Stmt *>(ThrowStmt)); 442 CGM.getObjCRuntime().EmitThrowStmt(*this, S, false); 443 // This will clear insertion point which was not cleared in 444 // call to EmitThrowStmt. 445 if (KeepInsertionPoint) 446 EmitBlock(createBasicBlock("throw.cont")); 447 return; 448 } 449 450 // Now allocate the exception object. 451 llvm::Type *SizeTy = ConvertType(getContext().getSizeType()); 452 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity(); 453 454 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(CGM); 455 llvm::CallInst *ExceptionPtr = 456 EmitNounwindRuntimeCall(AllocExceptionFn, 457 llvm::ConstantInt::get(SizeTy, TypeSize), 458 "exception"); 459 460 EmitAnyExprToExn(*this, E->getSubExpr(), ExceptionPtr); 461 462 // Now throw the exception. 463 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType, 464 /*ForEH=*/true); 465 466 // The address of the destructor. If the exception type has a 467 // trivial destructor (or isn't a record), we just pass null. 468 llvm::Constant *Dtor = nullptr; 469 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) { 470 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl()); 471 if (!Record->hasTrivialDestructor()) { 472 CXXDestructorDecl *DtorD = Record->getDestructor(); 473 Dtor = CGM.getAddrOfCXXStructor(DtorD, StructorType::Complete); 474 Dtor = llvm::ConstantExpr::getBitCast(Dtor, Int8PtrTy); 475 } 476 } 477 if (!Dtor) Dtor = llvm::Constant::getNullValue(Int8PtrTy); 478 479 llvm::Value *args[] = { ExceptionPtr, TypeInfo, Dtor }; 480 EmitNoreturnRuntimeCallOrInvoke(getThrowFn(CGM), args); 481 482 // throw is an expression, and the expression emitters expect us 483 // to leave ourselves at a valid insertion point. 484 if (KeepInsertionPoint) 485 EmitBlock(createBasicBlock("throw.cont")); 486 } 487 488 void CodeGenFunction::EmitStartEHSpec(const Decl *D) { 489 if (!CGM.getLangOpts().CXXExceptions) 490 return; 491 492 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D); 493 if (!FD) { 494 // Check if CapturedDecl is nothrow and create terminate scope for it. 495 if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) { 496 if (CD->isNothrow()) 497 EHStack.pushTerminate(); 498 } 499 return; 500 } 501 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>(); 502 if (!Proto) 503 return; 504 505 ExceptionSpecificationType EST = Proto->getExceptionSpecType(); 506 if (isNoexceptExceptionSpec(EST)) { 507 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) { 508 // noexcept functions are simple terminate scopes. 509 EHStack.pushTerminate(); 510 } 511 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) { 512 unsigned NumExceptions = Proto->getNumExceptions(); 513 EHFilterScope *Filter = EHStack.pushFilter(NumExceptions); 514 515 for (unsigned I = 0; I != NumExceptions; ++I) { 516 QualType Ty = Proto->getExceptionType(I); 517 QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType(); 518 llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType, 519 /*ForEH=*/true); 520 Filter->setFilter(I, EHType); 521 } 522 } 523 } 524 525 /// Emit the dispatch block for a filter scope if necessary. 526 static void emitFilterDispatchBlock(CodeGenFunction &CGF, 527 EHFilterScope &filterScope) { 528 llvm::BasicBlock *dispatchBlock = filterScope.getCachedEHDispatchBlock(); 529 if (!dispatchBlock) return; 530 if (dispatchBlock->use_empty()) { 531 delete dispatchBlock; 532 return; 533 } 534 535 CGF.EmitBlockAfterUses(dispatchBlock); 536 537 // If this isn't a catch-all filter, we need to check whether we got 538 // here because the filter triggered. 539 if (filterScope.getNumFilters()) { 540 // Load the selector value. 541 llvm::Value *selector = CGF.getSelectorFromSlot(); 542 llvm::BasicBlock *unexpectedBB = CGF.createBasicBlock("ehspec.unexpected"); 543 544 llvm::Value *zero = CGF.Builder.getInt32(0); 545 llvm::Value *failsFilter = 546 CGF.Builder.CreateICmpSLT(selector, zero, "ehspec.fails"); 547 CGF.Builder.CreateCondBr(failsFilter, unexpectedBB, CGF.getEHResumeBlock(false)); 548 549 CGF.EmitBlock(unexpectedBB); 550 } 551 552 // Call __cxa_call_unexpected. This doesn't need to be an invoke 553 // because __cxa_call_unexpected magically filters exceptions 554 // according to the last landing pad the exception was thrown 555 // into. Seriously. 556 llvm::Value *exn = CGF.getExceptionFromSlot(); 557 CGF.EmitRuntimeCall(getUnexpectedFn(CGF.CGM), exn) 558 ->setDoesNotReturn(); 559 CGF.Builder.CreateUnreachable(); 560 } 561 562 void CodeGenFunction::EmitEndEHSpec(const Decl *D) { 563 if (!CGM.getLangOpts().CXXExceptions) 564 return; 565 566 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D); 567 if (!FD) { 568 // Check if CapturedDecl is nothrow and pop terminate scope for it. 569 if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) { 570 if (CD->isNothrow()) 571 EHStack.popTerminate(); 572 } 573 return; 574 } 575 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>(); 576 if (!Proto) 577 return; 578 579 ExceptionSpecificationType EST = Proto->getExceptionSpecType(); 580 if (isNoexceptExceptionSpec(EST)) { 581 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) { 582 EHStack.popTerminate(); 583 } 584 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) { 585 EHFilterScope &filterScope = cast<EHFilterScope>(*EHStack.begin()); 586 emitFilterDispatchBlock(*this, filterScope); 587 EHStack.popFilter(); 588 } 589 } 590 591 void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) { 592 if (CGM.getTarget().getTriple().isKnownWindowsMSVCEnvironment()) { 593 ErrorUnsupported(&S, "try statement"); 594 return; 595 } 596 597 EnterCXXTryStmt(S); 598 EmitStmt(S.getTryBlock()); 599 ExitCXXTryStmt(S); 600 } 601 602 void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) { 603 unsigned NumHandlers = S.getNumHandlers(); 604 EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers); 605 606 for (unsigned I = 0; I != NumHandlers; ++I) { 607 const CXXCatchStmt *C = S.getHandler(I); 608 609 llvm::BasicBlock *Handler = createBasicBlock("catch"); 610 if (C->getExceptionDecl()) { 611 // FIXME: Dropping the reference type on the type into makes it 612 // impossible to correctly implement catch-by-reference 613 // semantics for pointers. Unfortunately, this is what all 614 // existing compilers do, and it's not clear that the standard 615 // personality routine is capable of doing this right. See C++ DR 388: 616 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388 617 Qualifiers CaughtTypeQuals; 618 QualType CaughtType = CGM.getContext().getUnqualifiedArrayType( 619 C->getCaughtType().getNonReferenceType(), CaughtTypeQuals); 620 621 llvm::Constant *TypeInfo = nullptr; 622 if (CaughtType->isObjCObjectPointerType()) 623 TypeInfo = CGM.getObjCRuntime().GetEHType(CaughtType); 624 else 625 TypeInfo = CGM.GetAddrOfRTTIDescriptor(CaughtType, /*ForEH=*/true); 626 CatchScope->setHandler(I, TypeInfo, Handler); 627 } else { 628 // No exception decl indicates '...', a catch-all. 629 CatchScope->setCatchAllHandler(I, Handler); 630 } 631 } 632 } 633 634 llvm::BasicBlock * 635 CodeGenFunction::getEHDispatchBlock(EHScopeStack::stable_iterator si) { 636 // The dispatch block for the end of the scope chain is a block that 637 // just resumes unwinding. 638 if (si == EHStack.stable_end()) 639 return getEHResumeBlock(true); 640 641 // Otherwise, we should look at the actual scope. 642 EHScope &scope = *EHStack.find(si); 643 644 llvm::BasicBlock *dispatchBlock = scope.getCachedEHDispatchBlock(); 645 if (!dispatchBlock) { 646 switch (scope.getKind()) { 647 case EHScope::Catch: { 648 // Apply a special case to a single catch-all. 649 EHCatchScope &catchScope = cast<EHCatchScope>(scope); 650 if (catchScope.getNumHandlers() == 1 && 651 catchScope.getHandler(0).isCatchAll()) { 652 dispatchBlock = catchScope.getHandler(0).Block; 653 654 // Otherwise, make a dispatch block. 655 } else { 656 dispatchBlock = createBasicBlock("catch.dispatch"); 657 } 658 break; 659 } 660 661 case EHScope::Cleanup: 662 dispatchBlock = createBasicBlock("ehcleanup"); 663 break; 664 665 case EHScope::Filter: 666 dispatchBlock = createBasicBlock("filter.dispatch"); 667 break; 668 669 case EHScope::Terminate: 670 dispatchBlock = getTerminateHandler(); 671 break; 672 } 673 scope.setCachedEHDispatchBlock(dispatchBlock); 674 } 675 return dispatchBlock; 676 } 677 678 /// Check whether this is a non-EH scope, i.e. a scope which doesn't 679 /// affect exception handling. Currently, the only non-EH scopes are 680 /// normal-only cleanup scopes. 681 static bool isNonEHScope(const EHScope &S) { 682 switch (S.getKind()) { 683 case EHScope::Cleanup: 684 return !cast<EHCleanupScope>(S).isEHCleanup(); 685 case EHScope::Filter: 686 case EHScope::Catch: 687 case EHScope::Terminate: 688 return false; 689 } 690 691 llvm_unreachable("Invalid EHScope Kind!"); 692 } 693 694 llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() { 695 assert(EHStack.requiresLandingPad()); 696 assert(!EHStack.empty()); 697 698 if (!CGM.getLangOpts().Exceptions) 699 return nullptr; 700 701 // Check the innermost scope for a cached landing pad. If this is 702 // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad. 703 llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad(); 704 if (LP) return LP; 705 706 // Build the landing pad for this scope. 707 LP = EmitLandingPad(); 708 assert(LP); 709 710 // Cache the landing pad on the innermost scope. If this is a 711 // non-EH scope, cache the landing pad on the enclosing scope, too. 712 for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) { 713 ir->setCachedLandingPad(LP); 714 if (!isNonEHScope(*ir)) break; 715 } 716 717 return LP; 718 } 719 720 llvm::BasicBlock *CodeGenFunction::EmitLandingPad() { 721 assert(EHStack.requiresLandingPad()); 722 723 EHScope &innermostEHScope = *EHStack.find(EHStack.getInnermostEHScope()); 724 switch (innermostEHScope.getKind()) { 725 case EHScope::Terminate: 726 return getTerminateLandingPad(); 727 728 case EHScope::Catch: 729 case EHScope::Cleanup: 730 case EHScope::Filter: 731 if (llvm::BasicBlock *lpad = innermostEHScope.getCachedLandingPad()) 732 return lpad; 733 } 734 735 // Save the current IR generation state. 736 CGBuilderTy::InsertPoint savedIP = Builder.saveAndClearIP(); 737 SaveAndRestoreLocation AutoRestoreLocation(*this, Builder); 738 if (CGDebugInfo *DI = getDebugInfo()) 739 DI->EmitLocation(Builder, CurEHLocation); 740 741 const EHPersonality &personality = EHPersonality::get(CGM); 742 743 // Create and configure the landing pad. 744 llvm::BasicBlock *lpad = createBasicBlock("lpad"); 745 EmitBlock(lpad); 746 747 llvm::LandingPadInst *LPadInst = 748 Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, nullptr), 749 getOpaquePersonalityFn(CGM, personality), 0); 750 751 llvm::Value *LPadExn = Builder.CreateExtractValue(LPadInst, 0); 752 Builder.CreateStore(LPadExn, getExceptionSlot()); 753 llvm::Value *LPadSel = Builder.CreateExtractValue(LPadInst, 1); 754 Builder.CreateStore(LPadSel, getEHSelectorSlot()); 755 756 // Save the exception pointer. It's safe to use a single exception 757 // pointer per function because EH cleanups can never have nested 758 // try/catches. 759 // Build the landingpad instruction. 760 761 // Accumulate all the handlers in scope. 762 bool hasCatchAll = false; 763 bool hasCleanup = false; 764 bool hasFilter = false; 765 SmallVector<llvm::Value*, 4> filterTypes; 766 llvm::SmallPtrSet<llvm::Value*, 4> catchTypes; 767 for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end(); 768 I != E; ++I) { 769 770 switch (I->getKind()) { 771 case EHScope::Cleanup: 772 // If we have a cleanup, remember that. 773 hasCleanup = (hasCleanup || cast<EHCleanupScope>(*I).isEHCleanup()); 774 continue; 775 776 case EHScope::Filter: { 777 assert(I.next() == EHStack.end() && "EH filter is not end of EH stack"); 778 assert(!hasCatchAll && "EH filter reached after catch-all"); 779 780 // Filter scopes get added to the landingpad in weird ways. 781 EHFilterScope &filter = cast<EHFilterScope>(*I); 782 hasFilter = true; 783 784 // Add all the filter values. 785 for (unsigned i = 0, e = filter.getNumFilters(); i != e; ++i) 786 filterTypes.push_back(filter.getFilter(i)); 787 goto done; 788 } 789 790 case EHScope::Terminate: 791 // Terminate scopes are basically catch-alls. 792 assert(!hasCatchAll); 793 hasCatchAll = true; 794 goto done; 795 796 case EHScope::Catch: 797 break; 798 } 799 800 EHCatchScope &catchScope = cast<EHCatchScope>(*I); 801 for (unsigned hi = 0, he = catchScope.getNumHandlers(); hi != he; ++hi) { 802 EHCatchScope::Handler handler = catchScope.getHandler(hi); 803 804 // If this is a catch-all, register that and abort. 805 if (!handler.Type) { 806 assert(!hasCatchAll); 807 hasCatchAll = true; 808 goto done; 809 } 810 811 // Check whether we already have a handler for this type. 812 if (catchTypes.insert(handler.Type).second) 813 // If not, add it directly to the landingpad. 814 LPadInst->addClause(handler.Type); 815 } 816 } 817 818 done: 819 // If we have a catch-all, add null to the landingpad. 820 assert(!(hasCatchAll && hasFilter)); 821 if (hasCatchAll) { 822 LPadInst->addClause(getCatchAllValue(*this)); 823 824 // If we have an EH filter, we need to add those handlers in the 825 // right place in the landingpad, which is to say, at the end. 826 } else if (hasFilter) { 827 // Create a filter expression: a constant array indicating which filter 828 // types there are. The personality routine only lands here if the filter 829 // doesn't match. 830 SmallVector<llvm::Constant*, 8> Filters; 831 llvm::ArrayType *AType = 832 llvm::ArrayType::get(!filterTypes.empty() ? 833 filterTypes[0]->getType() : Int8PtrTy, 834 filterTypes.size()); 835 836 for (unsigned i = 0, e = filterTypes.size(); i != e; ++i) 837 Filters.push_back(cast<llvm::Constant>(filterTypes[i])); 838 llvm::Constant *FilterArray = llvm::ConstantArray::get(AType, Filters); 839 LPadInst->addClause(FilterArray); 840 841 // Also check whether we need a cleanup. 842 if (hasCleanup) 843 LPadInst->setCleanup(true); 844 845 // Otherwise, signal that we at least have cleanups. 846 } else if (hasCleanup) { 847 LPadInst->setCleanup(true); 848 } 849 850 assert((LPadInst->getNumClauses() > 0 || LPadInst->isCleanup()) && 851 "landingpad instruction has no clauses!"); 852 853 // Tell the backend how to generate the landing pad. 854 Builder.CreateBr(getEHDispatchBlock(EHStack.getInnermostEHScope())); 855 856 // Restore the old IR generation state. 857 Builder.restoreIP(savedIP); 858 859 return lpad; 860 } 861 862 namespace { 863 /// A cleanup to call __cxa_end_catch. In many cases, the caught 864 /// exception type lets us state definitively that the thrown exception 865 /// type does not have a destructor. In particular: 866 /// - Catch-alls tell us nothing, so we have to conservatively 867 /// assume that the thrown exception might have a destructor. 868 /// - Catches by reference behave according to their base types. 869 /// - Catches of non-record types will only trigger for exceptions 870 /// of non-record types, which never have destructors. 871 /// - Catches of record types can trigger for arbitrary subclasses 872 /// of the caught type, so we have to assume the actual thrown 873 /// exception type might have a throwing destructor, even if the 874 /// caught type's destructor is trivial or nothrow. 875 struct CallEndCatch : EHScopeStack::Cleanup { 876 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {} 877 bool MightThrow; 878 879 void Emit(CodeGenFunction &CGF, Flags flags) override { 880 if (!MightThrow) { 881 CGF.EmitNounwindRuntimeCall(getEndCatchFn(CGF.CGM)); 882 return; 883 } 884 885 CGF.EmitRuntimeCallOrInvoke(getEndCatchFn(CGF.CGM)); 886 } 887 }; 888 } 889 890 /// Emits a call to __cxa_begin_catch and enters a cleanup to call 891 /// __cxa_end_catch. 892 /// 893 /// \param EndMightThrow - true if __cxa_end_catch might throw 894 static llvm::Value *CallBeginCatch(CodeGenFunction &CGF, 895 llvm::Value *Exn, 896 bool EndMightThrow) { 897 llvm::CallInst *call = 898 CGF.EmitNounwindRuntimeCall(getBeginCatchFn(CGF.CGM), Exn); 899 900 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow); 901 902 return call; 903 } 904 905 /// A "special initializer" callback for initializing a catch 906 /// parameter during catch initialization. 907 static void InitCatchParam(CodeGenFunction &CGF, 908 const VarDecl &CatchParam, 909 llvm::Value *ParamAddr, 910 SourceLocation Loc) { 911 // Load the exception from where the landing pad saved it. 912 llvm::Value *Exn = CGF.getExceptionFromSlot(); 913 914 CanQualType CatchType = 915 CGF.CGM.getContext().getCanonicalType(CatchParam.getType()); 916 llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType); 917 918 // If we're catching by reference, we can just cast the object 919 // pointer to the appropriate pointer. 920 if (isa<ReferenceType>(CatchType)) { 921 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType(); 922 bool EndCatchMightThrow = CaughtType->isRecordType(); 923 924 // __cxa_begin_catch returns the adjusted object pointer. 925 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow); 926 927 // We have no way to tell the personality function that we're 928 // catching by reference, so if we're catching a pointer, 929 // __cxa_begin_catch will actually return that pointer by value. 930 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) { 931 QualType PointeeType = PT->getPointeeType(); 932 933 // When catching by reference, generally we should just ignore 934 // this by-value pointer and use the exception object instead. 935 if (!PointeeType->isRecordType()) { 936 937 // Exn points to the struct _Unwind_Exception header, which 938 // we have to skip past in order to reach the exception data. 939 unsigned HeaderSize = 940 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException(); 941 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize); 942 943 // However, if we're catching a pointer-to-record type that won't 944 // work, because the personality function might have adjusted 945 // the pointer. There's actually no way for us to fully satisfy 946 // the language/ABI contract here: we can't use Exn because it 947 // might have the wrong adjustment, but we can't use the by-value 948 // pointer because it's off by a level of abstraction. 949 // 950 // The current solution is to dump the adjusted pointer into an 951 // alloca, which breaks language semantics (because changing the 952 // pointer doesn't change the exception) but at least works. 953 // The better solution would be to filter out non-exact matches 954 // and rethrow them, but this is tricky because the rethrow 955 // really needs to be catchable by other sites at this landing 956 // pad. The best solution is to fix the personality function. 957 } else { 958 // Pull the pointer for the reference type off. 959 llvm::Type *PtrTy = 960 cast<llvm::PointerType>(LLVMCatchTy)->getElementType(); 961 962 // Create the temporary and write the adjusted pointer into it. 963 llvm::Value *ExnPtrTmp = CGF.CreateTempAlloca(PtrTy, "exn.byref.tmp"); 964 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy); 965 CGF.Builder.CreateStore(Casted, ExnPtrTmp); 966 967 // Bind the reference to the temporary. 968 AdjustedExn = ExnPtrTmp; 969 } 970 } 971 972 llvm::Value *ExnCast = 973 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref"); 974 CGF.Builder.CreateStore(ExnCast, ParamAddr); 975 return; 976 } 977 978 // Scalars and complexes. 979 TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType); 980 if (TEK != TEK_Aggregate) { 981 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false); 982 983 // If the catch type is a pointer type, __cxa_begin_catch returns 984 // the pointer by value. 985 if (CatchType->hasPointerRepresentation()) { 986 llvm::Value *CastExn = 987 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted"); 988 989 switch (CatchType.getQualifiers().getObjCLifetime()) { 990 case Qualifiers::OCL_Strong: 991 CastExn = CGF.EmitARCRetainNonBlock(CastExn); 992 // fallthrough 993 994 case Qualifiers::OCL_None: 995 case Qualifiers::OCL_ExplicitNone: 996 case Qualifiers::OCL_Autoreleasing: 997 CGF.Builder.CreateStore(CastExn, ParamAddr); 998 return; 999 1000 case Qualifiers::OCL_Weak: 1001 CGF.EmitARCInitWeak(ParamAddr, CastExn); 1002 return; 1003 } 1004 llvm_unreachable("bad ownership qualifier!"); 1005 } 1006 1007 // Otherwise, it returns a pointer into the exception object. 1008 1009 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok 1010 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy); 1011 1012 LValue srcLV = CGF.MakeNaturalAlignAddrLValue(Cast, CatchType); 1013 LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType, 1014 CGF.getContext().getDeclAlign(&CatchParam)); 1015 switch (TEK) { 1016 case TEK_Complex: 1017 CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV, 1018 /*init*/ true); 1019 return; 1020 case TEK_Scalar: { 1021 llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc); 1022 CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true); 1023 return; 1024 } 1025 case TEK_Aggregate: 1026 llvm_unreachable("evaluation kind filtered out!"); 1027 } 1028 llvm_unreachable("bad evaluation kind"); 1029 } 1030 1031 assert(isa<RecordType>(CatchType) && "unexpected catch type!"); 1032 1033 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok 1034 1035 // Check for a copy expression. If we don't have a copy expression, 1036 // that means a trivial copy is okay. 1037 const Expr *copyExpr = CatchParam.getInit(); 1038 if (!copyExpr) { 1039 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true); 1040 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy); 1041 CGF.EmitAggregateCopy(ParamAddr, adjustedExn, CatchType); 1042 return; 1043 } 1044 1045 // We have to call __cxa_get_exception_ptr to get the adjusted 1046 // pointer before copying. 1047 llvm::CallInst *rawAdjustedExn = 1048 CGF.EmitNounwindRuntimeCall(getGetExceptionPtrFn(CGF.CGM), Exn); 1049 1050 // Cast that to the appropriate type. 1051 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy); 1052 1053 // The copy expression is defined in terms of an OpaqueValueExpr. 1054 // Find it and map it to the adjusted expression. 1055 CodeGenFunction::OpaqueValueMapping 1056 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr), 1057 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType())); 1058 1059 // Call the copy ctor in a terminate scope. 1060 CGF.EHStack.pushTerminate(); 1061 1062 // Perform the copy construction. 1063 CharUnits Alignment = CGF.getContext().getDeclAlign(&CatchParam); 1064 CGF.EmitAggExpr(copyExpr, 1065 AggValueSlot::forAddr(ParamAddr, Alignment, Qualifiers(), 1066 AggValueSlot::IsNotDestructed, 1067 AggValueSlot::DoesNotNeedGCBarriers, 1068 AggValueSlot::IsNotAliased)); 1069 1070 // Leave the terminate scope. 1071 CGF.EHStack.popTerminate(); 1072 1073 // Undo the opaque value mapping. 1074 opaque.pop(); 1075 1076 // Finally we can call __cxa_begin_catch. 1077 CallBeginCatch(CGF, Exn, true); 1078 } 1079 1080 /// Begins a catch statement by initializing the catch variable and 1081 /// calling __cxa_begin_catch. 1082 static void BeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *S) { 1083 // We have to be very careful with the ordering of cleanups here: 1084 // C++ [except.throw]p4: 1085 // The destruction [of the exception temporary] occurs 1086 // immediately after the destruction of the object declared in 1087 // the exception-declaration in the handler. 1088 // 1089 // So the precise ordering is: 1090 // 1. Construct catch variable. 1091 // 2. __cxa_begin_catch 1092 // 3. Enter __cxa_end_catch cleanup 1093 // 4. Enter dtor cleanup 1094 // 1095 // We do this by using a slightly abnormal initialization process. 1096 // Delegation sequence: 1097 // - ExitCXXTryStmt opens a RunCleanupsScope 1098 // - EmitAutoVarAlloca creates the variable and debug info 1099 // - InitCatchParam initializes the variable from the exception 1100 // - CallBeginCatch calls __cxa_begin_catch 1101 // - CallBeginCatch enters the __cxa_end_catch cleanup 1102 // - EmitAutoVarCleanups enters the variable destructor cleanup 1103 // - EmitCXXTryStmt emits the code for the catch body 1104 // - EmitCXXTryStmt close the RunCleanupsScope 1105 1106 VarDecl *CatchParam = S->getExceptionDecl(); 1107 if (!CatchParam) { 1108 llvm::Value *Exn = CGF.getExceptionFromSlot(); 1109 CallBeginCatch(CGF, Exn, true); 1110 return; 1111 } 1112 1113 // Emit the local. 1114 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam); 1115 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF), S->getLocStart()); 1116 CGF.EmitAutoVarCleanups(var); 1117 } 1118 1119 /// Emit the structure of the dispatch block for the given catch scope. 1120 /// It is an invariant that the dispatch block already exists. 1121 static void emitCatchDispatchBlock(CodeGenFunction &CGF, 1122 EHCatchScope &catchScope) { 1123 llvm::BasicBlock *dispatchBlock = catchScope.getCachedEHDispatchBlock(); 1124 assert(dispatchBlock); 1125 1126 // If there's only a single catch-all, getEHDispatchBlock returned 1127 // that catch-all as the dispatch block. 1128 if (catchScope.getNumHandlers() == 1 && 1129 catchScope.getHandler(0).isCatchAll()) { 1130 assert(dispatchBlock == catchScope.getHandler(0).Block); 1131 return; 1132 } 1133 1134 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveIP(); 1135 CGF.EmitBlockAfterUses(dispatchBlock); 1136 1137 // Select the right handler. 1138 llvm::Value *llvm_eh_typeid_for = 1139 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for); 1140 1141 // Load the selector value. 1142 llvm::Value *selector = CGF.getSelectorFromSlot(); 1143 1144 // Test against each of the exception types we claim to catch. 1145 for (unsigned i = 0, e = catchScope.getNumHandlers(); ; ++i) { 1146 assert(i < e && "ran off end of handlers!"); 1147 const EHCatchScope::Handler &handler = catchScope.getHandler(i); 1148 1149 llvm::Value *typeValue = handler.Type; 1150 assert(typeValue && "fell into catch-all case!"); 1151 typeValue = CGF.Builder.CreateBitCast(typeValue, CGF.Int8PtrTy); 1152 1153 // Figure out the next block. 1154 bool nextIsEnd; 1155 llvm::BasicBlock *nextBlock; 1156 1157 // If this is the last handler, we're at the end, and the next 1158 // block is the block for the enclosing EH scope. 1159 if (i + 1 == e) { 1160 nextBlock = CGF.getEHDispatchBlock(catchScope.getEnclosingEHScope()); 1161 nextIsEnd = true; 1162 1163 // If the next handler is a catch-all, we're at the end, and the 1164 // next block is that handler. 1165 } else if (catchScope.getHandler(i+1).isCatchAll()) { 1166 nextBlock = catchScope.getHandler(i+1).Block; 1167 nextIsEnd = true; 1168 1169 // Otherwise, we're not at the end and we need a new block. 1170 } else { 1171 nextBlock = CGF.createBasicBlock("catch.fallthrough"); 1172 nextIsEnd = false; 1173 } 1174 1175 // Figure out the catch type's index in the LSDA's type table. 1176 llvm::CallInst *typeIndex = 1177 CGF.Builder.CreateCall(llvm_eh_typeid_for, typeValue); 1178 typeIndex->setDoesNotThrow(); 1179 1180 llvm::Value *matchesTypeIndex = 1181 CGF.Builder.CreateICmpEQ(selector, typeIndex, "matches"); 1182 CGF.Builder.CreateCondBr(matchesTypeIndex, handler.Block, nextBlock); 1183 1184 // If the next handler is a catch-all, we're completely done. 1185 if (nextIsEnd) { 1186 CGF.Builder.restoreIP(savedIP); 1187 return; 1188 } 1189 // Otherwise we need to emit and continue at that block. 1190 CGF.EmitBlock(nextBlock); 1191 } 1192 } 1193 1194 void CodeGenFunction::popCatchScope() { 1195 EHCatchScope &catchScope = cast<EHCatchScope>(*EHStack.begin()); 1196 if (catchScope.hasEHBranches()) 1197 emitCatchDispatchBlock(*this, catchScope); 1198 EHStack.popCatch(); 1199 } 1200 1201 void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) { 1202 unsigned NumHandlers = S.getNumHandlers(); 1203 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin()); 1204 assert(CatchScope.getNumHandlers() == NumHandlers); 1205 1206 // If the catch was not required, bail out now. 1207 if (!CatchScope.hasEHBranches()) { 1208 CatchScope.clearHandlerBlocks(); 1209 EHStack.popCatch(); 1210 return; 1211 } 1212 1213 // Emit the structure of the EH dispatch for this catch. 1214 emitCatchDispatchBlock(*this, CatchScope); 1215 1216 // Copy the handler blocks off before we pop the EH stack. Emitting 1217 // the handlers might scribble on this memory. 1218 SmallVector<EHCatchScope::Handler, 8> Handlers(NumHandlers); 1219 memcpy(Handlers.data(), CatchScope.begin(), 1220 NumHandlers * sizeof(EHCatchScope::Handler)); 1221 1222 EHStack.popCatch(); 1223 1224 // The fall-through block. 1225 llvm::BasicBlock *ContBB = createBasicBlock("try.cont"); 1226 1227 // We just emitted the body of the try; jump to the continue block. 1228 if (HaveInsertPoint()) 1229 Builder.CreateBr(ContBB); 1230 1231 // Determine if we need an implicit rethrow for all these catch handlers; 1232 // see the comment below. 1233 bool doImplicitRethrow = false; 1234 if (IsFnTryBlock) 1235 doImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) || 1236 isa<CXXConstructorDecl>(CurCodeDecl); 1237 1238 // Perversely, we emit the handlers backwards precisely because we 1239 // want them to appear in source order. In all of these cases, the 1240 // catch block will have exactly one predecessor, which will be a 1241 // particular block in the catch dispatch. However, in the case of 1242 // a catch-all, one of the dispatch blocks will branch to two 1243 // different handlers, and EmitBlockAfterUses will cause the second 1244 // handler to be moved before the first. 1245 for (unsigned I = NumHandlers; I != 0; --I) { 1246 llvm::BasicBlock *CatchBlock = Handlers[I-1].Block; 1247 EmitBlockAfterUses(CatchBlock); 1248 1249 // Catch the exception if this isn't a catch-all. 1250 const CXXCatchStmt *C = S.getHandler(I-1); 1251 1252 // Enter a cleanup scope, including the catch variable and the 1253 // end-catch. 1254 RunCleanupsScope CatchScope(*this); 1255 1256 // Initialize the catch variable and set up the cleanups. 1257 BeginCatch(*this, C); 1258 1259 // Emit the PGO counter increment. 1260 RegionCounter CatchCnt = getPGORegionCounter(C); 1261 CatchCnt.beginRegion(Builder); 1262 1263 // Perform the body of the catch. 1264 EmitStmt(C->getHandlerBlock()); 1265 1266 // [except.handle]p11: 1267 // The currently handled exception is rethrown if control 1268 // reaches the end of a handler of the function-try-block of a 1269 // constructor or destructor. 1270 1271 // It is important that we only do this on fallthrough and not on 1272 // return. Note that it's illegal to put a return in a 1273 // constructor function-try-block's catch handler (p14), so this 1274 // really only applies to destructors. 1275 if (doImplicitRethrow && HaveInsertPoint()) { 1276 CGM.getCXXABI().emitRethrow(*this, /*isNoReturn*/false); 1277 Builder.CreateUnreachable(); 1278 Builder.ClearInsertionPoint(); 1279 } 1280 1281 // Fall out through the catch cleanups. 1282 CatchScope.ForceCleanup(); 1283 1284 // Branch out of the try. 1285 if (HaveInsertPoint()) 1286 Builder.CreateBr(ContBB); 1287 } 1288 1289 RegionCounter ContCnt = getPGORegionCounter(&S); 1290 EmitBlock(ContBB); 1291 ContCnt.beginRegion(Builder); 1292 } 1293 1294 namespace { 1295 struct CallEndCatchForFinally : EHScopeStack::Cleanup { 1296 llvm::Value *ForEHVar; 1297 llvm::Value *EndCatchFn; 1298 CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn) 1299 : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {} 1300 1301 void Emit(CodeGenFunction &CGF, Flags flags) override { 1302 llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch"); 1303 llvm::BasicBlock *CleanupContBB = 1304 CGF.createBasicBlock("finally.cleanup.cont"); 1305 1306 llvm::Value *ShouldEndCatch = 1307 CGF.Builder.CreateLoad(ForEHVar, "finally.endcatch"); 1308 CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB); 1309 CGF.EmitBlock(EndCatchBB); 1310 CGF.EmitRuntimeCallOrInvoke(EndCatchFn); // catch-all, so might throw 1311 CGF.EmitBlock(CleanupContBB); 1312 } 1313 }; 1314 1315 struct PerformFinally : EHScopeStack::Cleanup { 1316 const Stmt *Body; 1317 llvm::Value *ForEHVar; 1318 llvm::Value *EndCatchFn; 1319 llvm::Value *RethrowFn; 1320 llvm::Value *SavedExnVar; 1321 1322 PerformFinally(const Stmt *Body, llvm::Value *ForEHVar, 1323 llvm::Value *EndCatchFn, 1324 llvm::Value *RethrowFn, llvm::Value *SavedExnVar) 1325 : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn), 1326 RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {} 1327 1328 void Emit(CodeGenFunction &CGF, Flags flags) override { 1329 // Enter a cleanup to call the end-catch function if one was provided. 1330 if (EndCatchFn) 1331 CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup, 1332 ForEHVar, EndCatchFn); 1333 1334 // Save the current cleanup destination in case there are 1335 // cleanups in the finally block. 1336 llvm::Value *SavedCleanupDest = 1337 CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(), 1338 "cleanup.dest.saved"); 1339 1340 // Emit the finally block. 1341 CGF.EmitStmt(Body); 1342 1343 // If the end of the finally is reachable, check whether this was 1344 // for EH. If so, rethrow. 1345 if (CGF.HaveInsertPoint()) { 1346 llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow"); 1347 llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont"); 1348 1349 llvm::Value *ShouldRethrow = 1350 CGF.Builder.CreateLoad(ForEHVar, "finally.shouldthrow"); 1351 CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB); 1352 1353 CGF.EmitBlock(RethrowBB); 1354 if (SavedExnVar) { 1355 CGF.EmitRuntimeCallOrInvoke(RethrowFn, 1356 CGF.Builder.CreateLoad(SavedExnVar)); 1357 } else { 1358 CGF.EmitRuntimeCallOrInvoke(RethrowFn); 1359 } 1360 CGF.Builder.CreateUnreachable(); 1361 1362 CGF.EmitBlock(ContBB); 1363 1364 // Restore the cleanup destination. 1365 CGF.Builder.CreateStore(SavedCleanupDest, 1366 CGF.getNormalCleanupDestSlot()); 1367 } 1368 1369 // Leave the end-catch cleanup. As an optimization, pretend that 1370 // the fallthrough path was inaccessible; we've dynamically proven 1371 // that we're not in the EH case along that path. 1372 if (EndCatchFn) { 1373 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP(); 1374 CGF.PopCleanupBlock(); 1375 CGF.Builder.restoreIP(SavedIP); 1376 } 1377 1378 // Now make sure we actually have an insertion point or the 1379 // cleanup gods will hate us. 1380 CGF.EnsureInsertPoint(); 1381 } 1382 }; 1383 } 1384 1385 /// Enters a finally block for an implementation using zero-cost 1386 /// exceptions. This is mostly general, but hard-codes some 1387 /// language/ABI-specific behavior in the catch-all sections. 1388 void CodeGenFunction::FinallyInfo::enter(CodeGenFunction &CGF, 1389 const Stmt *body, 1390 llvm::Constant *beginCatchFn, 1391 llvm::Constant *endCatchFn, 1392 llvm::Constant *rethrowFn) { 1393 assert((beginCatchFn != nullptr) == (endCatchFn != nullptr) && 1394 "begin/end catch functions not paired"); 1395 assert(rethrowFn && "rethrow function is required"); 1396 1397 BeginCatchFn = beginCatchFn; 1398 1399 // The rethrow function has one of the following two types: 1400 // void (*)() 1401 // void (*)(void*) 1402 // In the latter case we need to pass it the exception object. 1403 // But we can't use the exception slot because the @finally might 1404 // have a landing pad (which would overwrite the exception slot). 1405 llvm::FunctionType *rethrowFnTy = 1406 cast<llvm::FunctionType>( 1407 cast<llvm::PointerType>(rethrowFn->getType())->getElementType()); 1408 SavedExnVar = nullptr; 1409 if (rethrowFnTy->getNumParams()) 1410 SavedExnVar = CGF.CreateTempAlloca(CGF.Int8PtrTy, "finally.exn"); 1411 1412 // A finally block is a statement which must be executed on any edge 1413 // out of a given scope. Unlike a cleanup, the finally block may 1414 // contain arbitrary control flow leading out of itself. In 1415 // addition, finally blocks should always be executed, even if there 1416 // are no catch handlers higher on the stack. Therefore, we 1417 // surround the protected scope with a combination of a normal 1418 // cleanup (to catch attempts to break out of the block via normal 1419 // control flow) and an EH catch-all (semantically "outside" any try 1420 // statement to which the finally block might have been attached). 1421 // The finally block itself is generated in the context of a cleanup 1422 // which conditionally leaves the catch-all. 1423 1424 // Jump destination for performing the finally block on an exception 1425 // edge. We'll never actually reach this block, so unreachable is 1426 // fine. 1427 RethrowDest = CGF.getJumpDestInCurrentScope(CGF.getUnreachableBlock()); 1428 1429 // Whether the finally block is being executed for EH purposes. 1430 ForEHVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "finally.for-eh"); 1431 CGF.Builder.CreateStore(CGF.Builder.getFalse(), ForEHVar); 1432 1433 // Enter a normal cleanup which will perform the @finally block. 1434 CGF.EHStack.pushCleanup<PerformFinally>(NormalCleanup, body, 1435 ForEHVar, endCatchFn, 1436 rethrowFn, SavedExnVar); 1437 1438 // Enter a catch-all scope. 1439 llvm::BasicBlock *catchBB = CGF.createBasicBlock("finally.catchall"); 1440 EHCatchScope *catchScope = CGF.EHStack.pushCatch(1); 1441 catchScope->setCatchAllHandler(0, catchBB); 1442 } 1443 1444 void CodeGenFunction::FinallyInfo::exit(CodeGenFunction &CGF) { 1445 // Leave the finally catch-all. 1446 EHCatchScope &catchScope = cast<EHCatchScope>(*CGF.EHStack.begin()); 1447 llvm::BasicBlock *catchBB = catchScope.getHandler(0).Block; 1448 1449 CGF.popCatchScope(); 1450 1451 // If there are any references to the catch-all block, emit it. 1452 if (catchBB->use_empty()) { 1453 delete catchBB; 1454 } else { 1455 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveAndClearIP(); 1456 CGF.EmitBlock(catchBB); 1457 1458 llvm::Value *exn = nullptr; 1459 1460 // If there's a begin-catch function, call it. 1461 if (BeginCatchFn) { 1462 exn = CGF.getExceptionFromSlot(); 1463 CGF.EmitNounwindRuntimeCall(BeginCatchFn, exn); 1464 } 1465 1466 // If we need to remember the exception pointer to rethrow later, do so. 1467 if (SavedExnVar) { 1468 if (!exn) exn = CGF.getExceptionFromSlot(); 1469 CGF.Builder.CreateStore(exn, SavedExnVar); 1470 } 1471 1472 // Tell the cleanups in the finally block that we're do this for EH. 1473 CGF.Builder.CreateStore(CGF.Builder.getTrue(), ForEHVar); 1474 1475 // Thread a jump through the finally cleanup. 1476 CGF.EmitBranchThroughCleanup(RethrowDest); 1477 1478 CGF.Builder.restoreIP(savedIP); 1479 } 1480 1481 // Finally, leave the @finally cleanup. 1482 CGF.PopCleanupBlock(); 1483 } 1484 1485 /// In a terminate landing pad, should we use __clang__call_terminate 1486 /// or just a naked call to std::terminate? 1487 /// 1488 /// __clang_call_terminate calls __cxa_begin_catch, which then allows 1489 /// std::terminate to usefully report something about the 1490 /// violating exception. 1491 static bool useClangCallTerminate(CodeGenModule &CGM) { 1492 // Only do this for Itanium-family ABIs in C++ mode. 1493 return (CGM.getLangOpts().CPlusPlus && 1494 CGM.getTarget().getCXXABI().isItaniumFamily()); 1495 } 1496 1497 /// Get or define the following function: 1498 /// void @__clang_call_terminate(i8* %exn) nounwind noreturn 1499 /// This code is used only in C++. 1500 static llvm::Constant *getClangCallTerminateFn(CodeGenModule &CGM) { 1501 llvm::FunctionType *fnTy = 1502 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false); 1503 llvm::Constant *fnRef = 1504 CGM.CreateRuntimeFunction(fnTy, "__clang_call_terminate"); 1505 1506 llvm::Function *fn = dyn_cast<llvm::Function>(fnRef); 1507 if (fn && fn->empty()) { 1508 fn->setDoesNotThrow(); 1509 fn->setDoesNotReturn(); 1510 1511 // What we really want is to massively penalize inlining without 1512 // forbidding it completely. The difference between that and 1513 // 'noinline' is negligible. 1514 fn->addFnAttr(llvm::Attribute::NoInline); 1515 1516 // Allow this function to be shared across translation units, but 1517 // we don't want it to turn into an exported symbol. 1518 fn->setLinkage(llvm::Function::LinkOnceODRLinkage); 1519 fn->setVisibility(llvm::Function::HiddenVisibility); 1520 1521 // Set up the function. 1522 llvm::BasicBlock *entry = 1523 llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn); 1524 CGBuilderTy builder(entry); 1525 1526 // Pull the exception pointer out of the parameter list. 1527 llvm::Value *exn = &*fn->arg_begin(); 1528 1529 // Call __cxa_begin_catch(exn). 1530 llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn); 1531 catchCall->setDoesNotThrow(); 1532 catchCall->setCallingConv(CGM.getRuntimeCC()); 1533 1534 // Call std::terminate(). 1535 llvm::CallInst *termCall = builder.CreateCall(getTerminateFn(CGM)); 1536 termCall->setDoesNotThrow(); 1537 termCall->setDoesNotReturn(); 1538 termCall->setCallingConv(CGM.getRuntimeCC()); 1539 1540 // std::terminate cannot return. 1541 builder.CreateUnreachable(); 1542 } 1543 1544 return fnRef; 1545 } 1546 1547 llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() { 1548 if (TerminateLandingPad) 1549 return TerminateLandingPad; 1550 1551 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP(); 1552 1553 // This will get inserted at the end of the function. 1554 TerminateLandingPad = createBasicBlock("terminate.lpad"); 1555 Builder.SetInsertPoint(TerminateLandingPad); 1556 1557 // Tell the backend that this is a landing pad. 1558 const EHPersonality &Personality = EHPersonality::get(CGM); 1559 llvm::LandingPadInst *LPadInst = 1560 Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, nullptr), 1561 getOpaquePersonalityFn(CGM, Personality), 0); 1562 LPadInst->addClause(getCatchAllValue(*this)); 1563 1564 llvm::CallInst *terminateCall; 1565 if (useClangCallTerminate(CGM)) { 1566 // Extract out the exception pointer. 1567 llvm::Value *exn = Builder.CreateExtractValue(LPadInst, 0); 1568 terminateCall = EmitNounwindRuntimeCall(getClangCallTerminateFn(CGM), exn); 1569 } else { 1570 terminateCall = EmitNounwindRuntimeCall(getTerminateFn(CGM)); 1571 } 1572 terminateCall->setDoesNotReturn(); 1573 Builder.CreateUnreachable(); 1574 1575 // Restore the saved insertion state. 1576 Builder.restoreIP(SavedIP); 1577 1578 return TerminateLandingPad; 1579 } 1580 1581 llvm::BasicBlock *CodeGenFunction::getTerminateHandler() { 1582 if (TerminateHandler) 1583 return TerminateHandler; 1584 1585 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP(); 1586 1587 // Set up the terminate handler. This block is inserted at the very 1588 // end of the function by FinishFunction. 1589 TerminateHandler = createBasicBlock("terminate.handler"); 1590 Builder.SetInsertPoint(TerminateHandler); 1591 llvm::CallInst *terminateCall; 1592 if (useClangCallTerminate(CGM)) { 1593 // Load the exception pointer. 1594 llvm::Value *exn = getExceptionFromSlot(); 1595 terminateCall = EmitNounwindRuntimeCall(getClangCallTerminateFn(CGM), exn); 1596 } else { 1597 terminateCall = EmitNounwindRuntimeCall(getTerminateFn(CGM)); 1598 } 1599 terminateCall->setDoesNotReturn(); 1600 Builder.CreateUnreachable(); 1601 1602 // Restore the saved insertion state. 1603 Builder.restoreIP(SavedIP); 1604 1605 return TerminateHandler; 1606 } 1607 1608 llvm::BasicBlock *CodeGenFunction::getEHResumeBlock(bool isCleanup) { 1609 if (EHResumeBlock) return EHResumeBlock; 1610 1611 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP(); 1612 1613 // We emit a jump to a notional label at the outermost unwind state. 1614 EHResumeBlock = createBasicBlock("eh.resume"); 1615 Builder.SetInsertPoint(EHResumeBlock); 1616 1617 const EHPersonality &Personality = EHPersonality::get(CGM); 1618 1619 // This can always be a call because we necessarily didn't find 1620 // anything on the EH stack which needs our help. 1621 const char *RethrowName = Personality.CatchallRethrowFn; 1622 if (RethrowName != nullptr && !isCleanup) { 1623 EmitRuntimeCall(getCatchallRethrowFn(CGM, RethrowName), 1624 getExceptionFromSlot()) 1625 ->setDoesNotReturn(); 1626 Builder.CreateUnreachable(); 1627 Builder.restoreIP(SavedIP); 1628 return EHResumeBlock; 1629 } 1630 1631 // Recreate the landingpad's return value for the 'resume' instruction. 1632 llvm::Value *Exn = getExceptionFromSlot(); 1633 llvm::Value *Sel = getSelectorFromSlot(); 1634 1635 llvm::Type *LPadType = llvm::StructType::get(Exn->getType(), 1636 Sel->getType(), nullptr); 1637 llvm::Value *LPadVal = llvm::UndefValue::get(LPadType); 1638 LPadVal = Builder.CreateInsertValue(LPadVal, Exn, 0, "lpad.val"); 1639 LPadVal = Builder.CreateInsertValue(LPadVal, Sel, 1, "lpad.val"); 1640 1641 Builder.CreateResume(LPadVal); 1642 Builder.restoreIP(SavedIP); 1643 return EHResumeBlock; 1644 } 1645 1646 void CodeGenFunction::EmitSEHTryStmt(const SEHTryStmt &S) { 1647 CGM.ErrorUnsupported(&S, "SEH __try"); 1648 } 1649 1650 void CodeGenFunction::EmitSEHLeaveStmt(const SEHLeaveStmt &S) { 1651 CGM.ErrorUnsupported(&S, "SEH __leave"); 1652 } 1653