25 #include "llvm/IR/CallSite.h" 26 #include "llvm/IR/Intrinsics.h" 27 #include "llvm/IR/IntrinsicInst.h" 28 #include "llvm/Support/SaveAndRestore.h" 30 using namespace clang;
31 using namespace CodeGen;
36 llvm::FunctionType *FTy =
45 llvm::FunctionType *FTy =
54 llvm::FunctionType *FTy =
55 llvm::FunctionType::get(
VoidTy,
false);
62 name =
"_ZSt9terminatev";
66 name =
"__std_terminate";
68 name =
"\01?terminate@@YAXXZ";
71 name =
"objc_terminate";
79 llvm::FunctionType *FTy =
117 if (L.SjLjExceptions)
135 return EHPersonality::GNUstep_ObjC;
139 if (L.SjLjExceptions)
145 llvm_unreachable(
"bad runtime kind");
150 if (L.SjLjExceptions)
184 llvm_unreachable(
"bad runtime kind");
188 if (T.getArch() == llvm::Triple::x86)
189 return EHPersonality::MSVC_except_handler;
205 if (T.isWindowsMSVCEnvironment() && !L.ObjC1) {
206 if (L.SjLjExceptions)
208 if (L.DWARFExceptions)
213 if (L.CPlusPlus && L.ObjC1)
215 else if (L.CPlusPlus)
229 return get(CGF.
CGM, dyn_cast_or_null<FunctionDecl>(FD));
236 llvm::AttributeList(),
true);
242 return llvm::ConstantExpr::getBitCast(Fn, CGM.
Int8PtrTy);
247 for (
unsigned I = 0, E = LPI->getNumClauses(); I != E; ++I) {
250 llvm::Value *Val = LPI->getClause(I)->stripPointerCasts();
251 if (LPI->isCatch(I)) {
253 if (llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Val))
256 if (GV->getName().startswith(
"OBJC_EHTYPE"))
260 llvm::Constant *CVal = cast<llvm::Constant>(Val);
261 for (llvm::User::op_iterator
262 II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II) {
263 if (llvm::GlobalVariable *GV =
264 cast<llvm::GlobalVariable>((*II)->stripPointerCasts()))
267 if (GV->getName().startswith(
"OBJC_EHTYPE"))
278 for (llvm::User *U : Fn->users()) {
280 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(U)) {
281 if (CE->getOpcode() != llvm::Instruction::BitCast)
return false;
288 llvm::Function *F = dyn_cast<llvm::Function>(U);
289 if (!F)
return false;
291 for (
auto BB = F->begin(), E = F->end(); BB != E; ++BB) {
292 if (BB->isLandingPad())
305 void CodeGenModule::SimplifyPersonality() {
307 if (!LangOpts.CPlusPlus || !LangOpts.ObjC1 || !LangOpts.Exceptions)
322 "Different EHPersonalities using the same personality function.");
327 if (!Fn || Fn->use_empty())
return;
337 if (Fn->getType() != CXXFn->getType())
return;
339 Fn->replaceAllUsesWith(CXXFn);
340 Fn->eraseFromParent();
347 return llvm::ConstantPointerNull::get(CGF.
Int8PtrTy);
375 Address typedAddr = Builder.CreateBitCast(addr, ty);
388 DeactivateCleanupBlock(cleanup,
389 cast<llvm::Instruction>(typedAddr.
getPointer()));
394 ExceptionSlot = CreateTempAlloca(
Int8PtrTy,
"exn.slot");
400 EHSelectorSlot = CreateTempAlloca(
Int32Ty,
"ehselector.slot");
405 return Builder.CreateLoad(getExceptionSlot(),
"exn");
409 return Builder.CreateLoad(getEHSelectorSlot(),
"sel");
413 bool KeepInsertionPoint) {
415 QualType ThrowType = SubExpr->getType();
419 CGM.getObjCRuntime().EmitThrowStmt(*
this, S,
false);
421 CGM.getCXXABI().emitThrow(*
this, E);
424 CGM.getCXXABI().emitRethrow(*
this,
true);
429 if (KeepInsertionPoint)
430 EmitBlock(createBasicBlock(
"throw.cont"));
434 if (!CGM.getLangOpts().CXXExceptions)
437 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
440 if (
const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
442 EHStack.pushTerminate();
454 EHStack.pushTerminate();
464 for (
unsigned I = 0; I != NumExceptions; ++I) {
467 llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType,
478 if (!dispatchBlock)
return;
479 if (dispatchBlock->use_empty()) {
480 delete dispatchBlock;
495 CGF.
Builder.CreateICmpSLT(selector, zero,
"ehspec.fails");
496 CGF.
Builder.CreateCondBr(failsFilter, unexpectedBB,
508 ->setDoesNotReturn();
509 CGF.
Builder.CreateUnreachable();
513 if (!CGM.getLangOpts().CXXExceptions)
516 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
519 if (
const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
521 EHStack.popTerminate();
532 EHStack.popTerminate();
539 EHFilterScope &filterScope = cast<EHFilterScope>(*EHStack.begin());
553 EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
555 for (
unsigned I = 0; I != NumHandlers; ++I) {
558 llvm::BasicBlock *Handler = createBasicBlock(
"catch");
567 QualType CaughtType = CGM.getContext().getUnqualifiedArrayType(
572 TypeInfo.RTTI = CGM.getObjCRuntime().GetEHType(CaughtType);
574 TypeInfo = CGM.getCXXABI().getAddrOfCXXCatchHandlerType(
579 CatchScope->
setHandler(I, CGM.getCXXABI().getCatchAllTypeInfo(), Handler);
587 return getMSVCDispatchBlock(si);
591 if (si == EHStack.stable_end())
592 return getEHResumeBlock(
true);
595 EHScope &scope = *EHStack.find(si);
598 if (!dispatchBlock) {
609 dispatchBlock = createBasicBlock(
"catch.dispatch");
615 dispatchBlock = createBasicBlock(
"ehcleanup");
619 dispatchBlock = createBasicBlock(
"filter.dispatch");
623 dispatchBlock = getTerminateHandler();
627 llvm_unreachable(
"PadEnd unnecessary for Itanium!");
631 return dispatchBlock;
638 if (SI == EHStack.stable_end())
642 EHScope &EHS = *EHStack.find(SI);
646 return DispatchBlock;
649 DispatchBlock = getTerminateFunclet();
651 DispatchBlock = createBasicBlock();
656 DispatchBlock->setName(
"catch.dispatch");
660 DispatchBlock->setName(
"ehcleanup");
664 llvm_unreachable(
"exception specifications not handled yet!");
667 DispatchBlock->setName(
"terminate");
671 llvm_unreachable(
"PadEnd dispatch block missing!");
674 return DispatchBlock;
683 return !cast<EHCleanupScope>(S).isEHCleanup();
691 llvm_unreachable(
"Invalid EHScope Kind!");
695 assert(EHStack.requiresLandingPad());
696 assert(!EHStack.empty());
703 if (!LO.Exceptions) {
704 if (!LO.Borland && !LO.MicrosoftExt)
706 if (!currentFunctionUsesSEHTry())
711 if (LO.CUDA && LO.CUDAIsDevice)
716 llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
721 if (!CurFn->hasPersonalityFn())
726 LP = getEHDispatchBlock(EHStack.getInnermostEHScope());
729 LP = EmitLandingPad();
737 ir->setCachedLandingPad(LP);
745 assert(EHStack.requiresLandingPad());
747 EHScope &innermostEHScope = *EHStack.find(EHStack.getInnermostEHScope());
748 switch (innermostEHScope.getKind()) {
750 return getTerminateLandingPad();
753 llvm_unreachable(
"PadEnd unnecessary for Itanium!");
758 if (llvm::BasicBlock *lpad = innermostEHScope.getCachedLandingPad())
763 CGBuilderTy::InsertPoint savedIP = Builder.saveAndClearIP();
767 llvm::BasicBlock *lpad = createBasicBlock(
"lpad");
770 llvm::LandingPadInst *LPadInst =
773 llvm::Value *LPadExn = Builder.CreateExtractValue(LPadInst, 0);
774 Builder.CreateStore(LPadExn, getExceptionSlot());
775 llvm::Value *LPadSel = Builder.CreateExtractValue(LPadInst, 1);
776 Builder.CreateStore(LPadSel, getEHSelectorSlot());
784 bool hasCatchAll =
false;
785 bool hasCleanup =
false;
786 bool hasFilter =
false;
788 llvm::SmallPtrSet<llvm::Value*, 4> catchTypes;
792 switch (I->getKind()) {
795 hasCleanup = (hasCleanup || cast<EHCleanupScope>(*I).isEHCleanup());
799 assert(I.next() == EHStack.end() &&
"EH filter is not end of EH stack");
800 assert(!hasCatchAll &&
"EH filter reached after catch-all");
807 for (
unsigned i = 0, e = filter.
getNumFilters(); i != e; ++i)
808 filterTypes.push_back(filter.
getFilter(i));
814 assert(!hasCatchAll);
822 llvm_unreachable(
"PadEnd unnecessary for Itanium!");
826 for (
unsigned hi = 0, he = catchScope.
getNumHandlers(); hi != he; ++hi) {
829 "landingpads do not support catch handler flags");
833 assert(!hasCatchAll);
839 if (catchTypes.insert(handler.
Type.
RTTI).second)
841 LPadInst->addClause(handler.
Type.
RTTI);
847 assert(!(hasCatchAll && hasFilter));
853 }
else if (hasFilter) {
858 llvm::ArrayType *AType =
859 llvm::ArrayType::get(!filterTypes.empty() ?
863 for (
unsigned i = 0, e = filterTypes.size(); i != e; ++i)
864 Filters.push_back(cast<llvm::Constant>(filterTypes[i]));
865 llvm::Constant *FilterArray = llvm::ConstantArray::get(AType, Filters);
866 LPadInst->addClause(FilterArray);
870 LPadInst->setCleanup(
true);
873 }
else if (hasCleanup) {
874 LPadInst->setCleanup(
true);
877 assert((LPadInst->getNumClauses() > 0 || LPadInst->isCleanup()) &&
878 "landingpad instruction has no clauses!");
881 Builder.CreateBr(getEHDispatchBlock(EHStack.getInnermostEHScope()));
884 Builder.restoreIP(savedIP);
891 assert(DispatchBlock);
893 CGBuilderTy::InsertPoint SavedIP = CGF.
Builder.saveIP();
899 llvm::BasicBlock *UnwindBB =
903 llvm::CatchSwitchInst *CatchSwitch =
904 CGF.
Builder.CreateCatchSwitch(ParentPad, UnwindBB, NumHandlers);
907 for (
unsigned I = 0; I < NumHandlers; ++I) {
919 llvm::Constant::getNullValue(CGF.
VoidPtrTy)});
921 CGF.
Builder.CreateCatchPad(CatchSwitch, {TypeInfo.
RTTI});
924 CatchSwitch->addHandler(Handler.
Block);
926 CGF.
Builder.restoreIP(SavedIP);
937 assert(dispatchBlock);
947 CGBuilderTy::InsertPoint savedIP = CGF.
Builder.saveIP();
959 assert(i < e &&
"ran off end of handlers!");
964 "landingpads do not support catch handler flags");
965 assert(typeValue &&
"fell into catch-all case!");
970 llvm::BasicBlock *nextBlock;
991 llvm::CallInst *typeIndex =
992 CGF.
Builder.CreateCall(llvm_eh_typeid_for, typeValue);
993 typeIndex->setDoesNotThrow();
996 CGF.
Builder.CreateICmpEQ(selector, typeIndex,
"matches");
997 CGF.
Builder.CreateCondBr(matchesTypeIndex, handler.
Block, nextBlock);
1001 CGF.
Builder.restoreIP(savedIP);
1010 EHCatchScope &catchScope = cast<EHCatchScope>(*EHStack.begin());
1018 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1034 CatchScope.
begin(), CatchScope.
begin() + NumHandlers);
1039 llvm::BasicBlock *ContBB = createBasicBlock(
"try.cont");
1042 if (HaveInsertPoint())
1043 Builder.CreateBr(ContBB);
1047 bool doImplicitRethrow =
false;
1049 doImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
1050 isa<CXXConstructorDecl>(CurCodeDecl);
1059 for (
unsigned I = NumHandlers; I != 0; --I) {
1060 llvm::BasicBlock *CatchBlock = Handlers[I-1].Block;
1061 EmitBlockAfterUses(CatchBlock);
1073 CGM.getCXXABI().emitBeginCatch(*
this, C);
1076 incrementProfileCounter(C);
1090 if (doImplicitRethrow && HaveInsertPoint()) {
1091 CGM.getCXXABI().emitRethrow(*
this,
false);
1092 Builder.CreateUnreachable();
1093 Builder.ClearInsertionPoint();
1100 if (HaveInsertPoint())
1101 Builder.CreateBr(ContBB);
1105 incrementProfileCounter(&S);
1113 : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
1117 llvm::BasicBlock *CleanupContBB =
1122 CGF.
Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1139 : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1140 RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
1146 ForEHVar, EndCatchFn);
1152 "cleanup.dest.saved");
1165 CGF.
Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1174 CGF.
Builder.CreateUnreachable();
1187 CGBuilderTy::InsertPoint SavedIP = CGF.
Builder.saveAndClearIP();
1189 CGF.
Builder.restoreIP(SavedIP);
1204 llvm::Constant *beginCatchFn,
1205 llvm::Constant *endCatchFn,
1206 llvm::Constant *rethrowFn) {
1207 assert((beginCatchFn !=
nullptr) == (endCatchFn !=
nullptr) &&
1208 "begin/end catch functions not paired");
1209 assert(rethrowFn &&
"rethrow function is required");
1211 BeginCatchFn = beginCatchFn;
1219 llvm::FunctionType *rethrowFnTy =
1220 cast<llvm::FunctionType>(
1221 cast<llvm::PointerType>(rethrowFn->getType())->getElementType());
1222 SavedExnVar =
nullptr;
1223 if (rethrowFnTy->getNumParams())
1249 ForEHVar, endCatchFn,
1250 rethrowFn, SavedExnVar);
1266 if (catchBB->use_empty()) {
1269 CGBuilderTy::InsertPoint savedIP = CGF.
Builder.saveAndClearIP();
1292 CGF.
Builder.restoreIP(savedIP);
1300 if (TerminateLandingPad)
1301 return TerminateLandingPad;
1303 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1306 TerminateLandingPad = createBasicBlock(
"terminate.lpad");
1307 Builder.SetInsertPoint(TerminateLandingPad);
1312 if (!CurFn->hasPersonalityFn())
1315 llvm::LandingPadInst *LPadInst =
1321 Exn = Builder.CreateExtractValue(LPadInst, 0);
1322 llvm::CallInst *terminateCall =
1323 CGM.getCXXABI().emitTerminateForUnexpectedException(*
this, Exn);
1324 terminateCall->setDoesNotReturn();
1325 Builder.CreateUnreachable();
1328 Builder.restoreIP(SavedIP);
1330 return TerminateLandingPad;
1334 if (TerminateHandler)
1335 return TerminateHandler;
1339 TerminateHandler = createBasicBlock(
"terminate.handler");
1340 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1341 Builder.SetInsertPoint(TerminateHandler);
1345 Exn = getExceptionFromSlot();
1346 llvm::CallInst *terminateCall =
1347 CGM.getCXXABI().emitTerminateForUnexpectedException(*
this, Exn);
1348 terminateCall->setDoesNotReturn();
1349 Builder.CreateUnreachable();
1352 Builder.restoreIP(SavedIP);
1354 return TerminateHandler;
1359 "use getTerminateLandingPad for non-funclet EH");
1361 llvm::BasicBlock *&TerminateFunclet = TerminateFunclets[CurrentFuncletPad];
1362 if (TerminateFunclet)
1363 return TerminateFunclet;
1365 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1369 TerminateFunclet = createBasicBlock(
"terminate.handler");
1370 Builder.SetInsertPoint(TerminateFunclet);
1378 ParentPad = llvm::ConstantTokenNone::get(CGM.getLLVMContext());
1379 CurrentFuncletPad = Builder.CreateCleanupPad(ParentPad);
1382 llvm::CallInst *terminateCall =
1383 CGM.getCXXABI().emitTerminateForUnexpectedException(*
this,
nullptr);
1384 terminateCall->setDoesNotReturn();
1385 Builder.CreateUnreachable();
1388 Builder.restoreIP(SavedIP);
1390 return TerminateFunclet;
1394 if (EHResumeBlock)
return EHResumeBlock;
1396 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1399 EHResumeBlock = createBasicBlock(
"eh.resume");
1400 Builder.SetInsertPoint(EHResumeBlock);
1407 if (RethrowName !=
nullptr && !isCleanup) {
1409 getExceptionFromSlot())->setDoesNotReturn();
1410 Builder.CreateUnreachable();
1411 Builder.restoreIP(SavedIP);
1412 return EHResumeBlock;
1419 llvm::Type *LPadType = llvm::StructType::get(Exn->getType(), Sel->getType());
1420 llvm::Value *LPadVal = llvm::UndefValue::get(LPadType);
1421 LPadVal = Builder.CreateInsertValue(LPadVal, Exn, 0,
"lpad.val");
1422 LPadVal = Builder.CreateInsertValue(LPadVal, Sel, 1,
"lpad.val");
1424 Builder.CreateResume(LPadVal);
1425 Builder.restoreIP(SavedIP);
1426 return EHResumeBlock;
1432 JumpDest TryExit = getJumpDestInCurrentScope(
"__try.__leave");
1434 SEHTryEpilogueStack.push_back(&TryExit);
1436 SEHTryEpilogueStack.pop_back();
1438 if (!TryExit.
getBlock()->use_empty())
1439 EmitBlock(TryExit.
getBlock(),
true);
1448 llvm::Function *OutlinedFinally;
1449 PerformSEHFinally(llvm::Function *OutlinedFinally)
1450 : OutlinedFinally(OutlinedFinally) {}
1463 llvm::ConstantInt::get(CGF.
ConvertType(ArgTys[0]), F.isForEHCleanup());
1485 : ParentCGF(ParentCGF), ParentThis(ParentThis) {}
1488 bool foundCaptures() {
1489 return !Captures.empty() || SEHCodeSlot.
isValid();
1492 void Visit(
const Stmt *S) {
1503 Captures.insert(ParentThis);
1508 if (D && D->isLocalVarDeclOrParm() && D->hasLocalStorage())
1513 Captures.insert(ParentThis);
1516 void VisitCallExpr(
const CallExpr *E) {
1523 case Builtin::BI__exception_code:
1524 case Builtin::BI_exception_code:
1539 llvm::CallInst *RecoverCall =
nullptr;
1541 if (
auto *ParentAlloca = dyn_cast<llvm::AllocaInst>(ParentVar.
getPointer())) {
1544 auto InsertPair = ParentCGF.EscapedLocals.insert(
1545 std::make_pair(ParentAlloca, ParentCGF.EscapedLocals.size()));
1546 int FrameEscapeIdx = InsertPair.first->second;
1548 llvm::Function *FrameRecoverFn = llvm::Intrinsic::getDeclaration(
1549 &CGM.getModule(), llvm::Intrinsic::localrecover);
1550 llvm::Constant *ParentI8Fn =
1552 RecoverCall = Builder.CreateCall(
1553 FrameRecoverFn, {ParentI8Fn, ParentFP,
1554 llvm::ConstantInt::get(
Int32Ty, FrameEscapeIdx)});
1560 auto *ParentRecover =
1561 cast<llvm::IntrinsicInst>(ParentVar.
getPointer()->stripPointerCasts());
1562 assert(ParentRecover->getIntrinsicID() == llvm::Intrinsic::localrecover &&
1563 "expected alloca or localrecover in parent LocalDeclMap");
1564 RecoverCall = cast<llvm::CallInst>(ParentRecover->clone());
1565 RecoverCall->setArgOperand(1, ParentFP);
1566 RecoverCall->insertBefore(AllocaInsertPt);
1572 ChildVar->setName(ParentVar.
getName());
1577 const Stmt *OutlinedStmt,
1580 CaptureFinder Finder(ParentCGF, ParentCGF.CXXABIThisDecl);
1581 Finder.Visit(OutlinedStmt);
1585 if (!Finder.foundCaptures() &&
1586 CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
1588 EmitSEHExceptionCodeSave(ParentCGF,
nullptr,
nullptr);
1594 if (IsFilter && CGM.getTarget().getTriple().getArch() == llvm::Triple::x86) {
1598 EntryFP = Builder.CreateCall(
1599 CGM.getIntrinsic(llvm::Intrinsic::frameaddress), {Builder.getInt32(1)});
1603 auto AI = CurFn->arg_begin();
1613 llvm::Function *RecoverFPIntrin =
1614 CGM.getIntrinsic(llvm::Intrinsic::x86_seh_recoverfp);
1615 llvm::Constant *ParentI8Fn =
1617 ParentFP = Builder.CreateCall(RecoverFPIntrin, {ParentI8Fn, EntryFP});
1621 for (
const VarDecl *VD : Finder.Captures) {
1622 if (isa<ImplicitParamDecl>(VD)) {
1623 CGM.ErrorUnsupported(VD,
"'this' captured by SEH");
1624 CXXThisValue = llvm::UndefValue::get(ConvertTypeForMem(VD->
getType()));
1628 CGM.ErrorUnsupported(VD,
"VLA captured by SEH");
1632 "captured non-local variable");
1636 auto I = ParentCGF.LocalDeclMap.find(VD);
1637 if (I == ParentCGF.LocalDeclMap.end())
1640 Address ParentVar = I->second;
1642 VD, recoverAddrOfEscapedLocal(ParentCGF, ParentVar, ParentFP));
1645 if (Finder.SEHCodeSlot.isValid()) {
1646 SEHCodeSlotStack.push_back(
1647 recoverAddrOfEscapedLocal(ParentCGF, Finder.SEHCodeSlot, ParentFP));
1651 EmitSEHExceptionCodeSave(ParentCGF, ParentFP, EntryFP);
1659 const Stmt *OutlinedStmt) {
1665 llvm::raw_svector_ostream OS(Name);
1667 assert(ParentSEHFn &&
"No CurSEHParent!");
1668 MangleContext &Mangler = CGM.getCXXABI().getMangleContext();
1676 if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86 || !IsFilter) {
1682 &
getContext().Idents.get(
"exception_pointers"),
1687 &
getContext().Idents.get(
"abnormal_termination"),
1699 CGM.getTypes().arrangeBuiltinFunctionDeclaration(RetTy, Args);
1701 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
1705 IsOutlinedSEHHelper =
true;
1707 StartFunction(
GlobalDecl(), RetTy, Fn, FnInfo, Args,
1711 CGM.SetLLVMFunctionAttributes(
nullptr, FnInfo, CurFn);
1712 EmitCapturedLocals(ParentCGF, OutlinedStmt, IsFilter);
1722 startOutlinedSEHHelper(ParentCGF,
true, FilterExpr);
1726 R = Builder.CreateIntCast(R, ConvertType(
getContext().LongTy),
1728 Builder.CreateStore(R, ReturnValue);
1730 FinishFunction(FilterExpr->
getLocEnd());
1739 startOutlinedSEHHelper(ParentCGF,
false, FinallyBlock);
1742 EmitStmt(FinallyBlock);
1744 FinishFunction(FinallyBlock->
getLocEnd());
1754 if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
1756 SEHInfo = &*CurFn->arg_begin();
1757 SEHCodeSlotStack.push_back(
1764 SEHInfo = Builder.CreateConstInBoundsGEP1_32(
Int8Ty, EntryFP, -20);
1765 SEHInfo = Builder.CreateBitCast(SEHInfo,
Int8PtrTy->getPointerTo());
1767 SEHCodeSlotStack.push_back(recoverAddrOfEscapedLocal(
1778 llvm::Type *RecordTy = CGM.Int32Ty->getPointerTo();
1779 llvm::Type *PtrsTy = llvm::StructType::get(RecordTy, CGM.VoidPtrTy);
1780 llvm::Value *Ptrs = Builder.CreateBitCast(SEHInfo, PtrsTy->getPointerTo());
1781 llvm::Value *Rec = Builder.CreateStructGEP(PtrsTy, Ptrs, 0);
1784 assert(!SEHCodeSlotStack.empty() &&
"emitting EH code outside of __except");
1785 Builder.CreateStore(Code, SEHCodeSlotStack.back());
1792 return llvm::UndefValue::get(
Int8PtrTy);
1793 assert(SEHInfo->getType() ==
Int8PtrTy);
1798 assert(!SEHCodeSlotStack.empty() &&
"emitting EH code outside of __except");
1799 return Builder.CreateLoad(SEHCodeSlotStack.back());
1805 auto AI = CurFn->arg_begin();
1806 return Builder.CreateZExt(&*AI,
Int32Ty);
1813 llvm::Function *FinallyFunc =
1825 SEHCodeSlotStack.push_back(
1834 if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86 && C &&
1842 llvm::Function *FilterFunc =
1844 llvm::Constant *OpaqueFunc =
1845 llvm::ConstantExpr::getBitCast(FilterFunc,
Int8PtrTy);
1846 CatchScope->
setHandler(0, OpaqueFunc, createBasicBlock(
"__except.ret"));
1858 assert(Except &&
"__try must have __finally xor __except");
1859 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1867 SEHCodeSlotStack.pop_back();
1872 llvm::BasicBlock *ContBB = createBasicBlock(
"__try.cont");
1875 if (HaveInsertPoint())
1876 Builder.CreateBr(ContBB);
1885 EmitBlockAfterUses(CatchPadBB);
1889 llvm::CatchPadInst *CPI =
1890 cast<llvm::CatchPadInst>(CatchPadBB->getFirstNonPHI());
1891 llvm::BasicBlock *ExceptBB = createBasicBlock(
"__except");
1892 Builder.CreateCatchRet(CPI, ExceptBB);
1893 EmitBlock(ExceptBB);
1896 if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
1897 llvm::Function *SEHCodeIntrin =
1898 CGM.getIntrinsic(llvm::Intrinsic::eh_exceptioncode);
1899 llvm::Value *Code = Builder.CreateCall(SEHCodeIntrin, {CPI});
1900 Builder.CreateStore(Code, SEHCodeSlotStack.back());
1907 SEHCodeSlotStack.pop_back();
1909 if (HaveInsertPoint())
1910 Builder.CreateBr(ContBB);
1919 if (HaveInsertPoint())
1924 if (!isSEHTryScope()) {
1925 Builder.CreateUnreachable();
1926 Builder.ClearInsertionPoint();
1930 EmitBranchThroughCleanup(*SEHTryEpilogueStack.back());
virtual void mangleSEHFilterExpression(const NamedDecl *EnclosingDecl, raw_ostream &Out)=0
ReturnValueSlot - Contains the address where the return value of a function can be stored...
An instance of this class is created to represent a function declaration or definition.
llvm::IntegerType * IntTy
int
EHScopeStack::stable_iterator getEnclosingEHScope() const
CharUnits getIntAlign() const
Other implicit parameter.
CompoundStmt * getBlock() const
void setCatchAllHandler(unsigned I, llvm::BasicBlock *Block)
A (possibly-)qualified type.
void EmitSEHLeaveStmt(const SEHLeaveStmt &S)
CodeGenTypes & getTypes()
bool usesFuncletPads() const
Does this personality use landingpads or the family of pad instructions designed to form funclets...
Represents a version number in the form major[.minor[.subminor[.build]]].
unsigned getNumExceptions() const
const Expr * getSubExpr() const
ConstStmtVisitor - This class implements a simple visitor for Stmt subclasses.
llvm::BasicBlock * getCachedEHDispatchBlock() const
bool HaveInsertPoint() const
HaveInsertPoint - True if an insertion point is defined.
static const EHPersonality GNU_C_SJLJ
void EmitCXXTryStmt(const CXXTryStmt &S)
Stmt - This represents one statement.
CXXCatchStmt * getHandler(unsigned i)
static const EHPersonality MSVC_C_specific_handler
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
static const EHPersonality MSVC_CxxFrameHandler3
bool hasEHBranches() const
Decl - This represents one declaration (or definition), e.g.
Stmt * getHandlerBlock() const
void clearHandlerBlocks()
const Decl * CurCodeDecl
CurCodeDecl - This is the inner-most code context, which includes blocks.
Address getEHSelectorSlot()
static const EHPersonality GNU_C
virtual void mangleSEHFinallyBlock(const NamedDecl *EnclosingDecl, raw_ostream &Out)=0
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Represents Objective-C's @throw statement.
static llvm::Constant * getUnexpectedFn(CodeGenModule &CGM)
void EmitSEHExceptionCodeSave(CodeGenFunction &ParentCGF, llvm::Value *ParentFP, llvm::Value *EntryEBP)
bool usesSEHTry() const
Indicates the function uses __try.
static llvm::Constant * getPersonalityFn(CodeGenModule &CGM, const EHPersonality &Personality)
unsigned getNumFilters() const
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
'gcc' is the Objective-C runtime shipped with GCC, implementing a fragile Objective-C ABI ...
RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee, ReturnValueSlot ReturnValue, const CallArgList &Args, llvm::Instruction **callOrInvoke, SourceLocation Loc)
EmitCall - Generate a call of the given function, expecting the given result type, and using the given argument list which specifies both the LLVM arguments and the types they were derived from.
VarDecl - An instance of this class is created to represent a variable declaration or definition...
const T * getAs() const
Member-template getAs<specific type>'.
unsigned getNumHandlers() const
llvm::Value * getPointer() const
iterator begin() const
Returns an iterator pointing to the innermost EH scope.
llvm::BasicBlock * EmitLandingPad()
Emits a landing pad for the current EH stack.
A protected scope for zero-cost EH handling.
Defines the Objective-C statement AST node classes.
A C++ throw-expression (C++ [except.throw]).
A scope which attempts to handle some, possibly all, types of exceptions.
The collection of all-type qualifiers we support.
A jump destination is an abstract label, branching to which may require a jump out through normal cle...
bool isNoexceptExceptionSpec(ExceptionSpecificationType ESpecType)
void popCatchScope()
popCatchScope - Pops the catch scope at the top of the EHScope stack, emitting any required code (oth...
const TargetInfo & getTarget() const
llvm::BasicBlock * getTerminateHandler()
getTerminateHandler - Return a handler (not a landing pad, just a catch handler) that just calls term...
'macosx-fragile' is the Apple-provided NeXT-derived runtime on Mac OS X platforms that use the fragil...
const char * CatchallRethrowFn
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
QualType getCaughtType() const
SmallVector< Address, 1 > SEHCodeSlotStack
A stack of exception code slots.
static const EHPersonality GNU_CPlusPlus_SJLJ
const FunctionDecl * CurSEHParent
llvm::CallInst * EmitRuntimeCall(llvm::Value *callee, const Twine &name="")
Denotes a cleanup that should run when a scope is exited using exceptional control flow (a throw stat...
static const EHPersonality & get(CodeGenModule &CGM, const FunctionDecl *FD)
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Address getExceptionSlot()
Returns a pointer to the function's exception object and selector slot, which is assigned in every la...
void setFilter(unsigned i, llvm::Value *filterValue)
class EHCatchScope * pushCatch(unsigned NumHandlers)
Push a set of catch handlers on the stack.
bool isNeXTFamily() const
Is this runtime basically of the NeXT family of runtimes?
static llvm::Constant * getFreeExceptionFn(CodeGenModule &CGM)
static llvm::Constant * getCatchAllValue(CodeGenFunction &CGF)
Returns the value to inject into a selector to indicate the presence of a catch-all.
void ExitSEHTryStmt(const SEHTryStmt &S)
QualType getExceptionType(unsigned i) const
CharUnits getAlignment() const
Return the alignment of this pointer.
llvm::PointerType * VoidPtrTy
const Handler & getHandler(unsigned I) const
static const EHPersonality GNUstep_ObjC
llvm::Constant * getTerminateFn()
Get the declaration of std::terminate for the platform.
llvm::BasicBlock * getInvokeDestImpl()
llvm::Function * GenerateSEHFinallyFunction(CodeGenFunction &ParentCGF, const SEHFinallyStmt &Finally)
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
Denotes a cleanup that should run when a scope is exited using normal control flow (falling off the e...
void ForceCleanup(std::initializer_list< llvm::Value **> ValuesToReload={})
Force the emission of cleanups now, instead of waiting until this object is destroyed.
CharUnits getPointerAlign() const
This represents the body of a CapturedStmt, and serves as its DeclContext.
llvm::AllocaInst * CreateTempAlloca(llvm::Type *Ty, const Twine &Name="tmp", llvm::Value *ArraySize=nullptr)
CreateTempAlloca - This creates an alloca and inserts it into the entry block if ArraySize is nullptr...
CanQualType UnsignedCharTy
llvm::Value * EmitSEHExceptionCode()
Represents the this expression in C++.
llvm::Constant * CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name, llvm::AttributeList ExtraAttrs=llvm::AttributeList(), bool Local=false)
Create a new runtime function with the specified type and name.
static ImplicitParamDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, ImplicitParamKind ParamKind)
Create implicit parameter.
'watchos' is a variant of iOS for Apple's watchOS.
ASTContext & getContext() const
Represents a prototype with parameter type info, e.g.
llvm::CallInst * EmitNounwindRuntimeCall(llvm::Value *callee, const Twine &name="")
static const EHPersonality MSVC_except_handler
static llvm::Constant * getOpaquePersonalityFn(CodeGenModule &CGM, const EHPersonality &Personality)
SourceLocation getLocEnd() const LLVM_READONLY
CatchTypeInfo Type
A type info value, or null (C++ null, not an LLVM null pointer) for a catch-all.
void EmitCapturedLocals(CodeGenFunction &ParentCGF, const Stmt *OutlinedStmt, bool IsFilter)
Scan the outlined statement for captures from the parent function.
Expr - This represents one expression.
void enter(CodeGenFunction &CGF, const Stmt *Finally, llvm::Constant *beginCatchFn, llvm::Constant *endCatchFn, llvm::Constant *rethrowFn)
Enters a finally block for an implementation using zero-cost exceptions.
static bool PersonalityHasOnlyCXXUses(llvm::Constant *Fn)
Check whether a personality function could reasonably be swapped for a C++ personality function...
'macosx' is the Apple-provided NeXT-derived runtime on Mac OS X platforms that use the non-fragile AB...
Enters a new scope for capturing cleanups, all of which will be executed once the scope is exited...
const FunctionProtoType * T
llvm::Function * GenerateSEHFilterFunction(CodeGenFunction &ParentCGF, const SEHExceptStmt &Except)
Create a stub filter function that will ultimately hold the code of the filter expression.
llvm::BasicBlock * getBlock() const
static CGCallee forDirect(llvm::Constant *functionPtr, const CGCalleeInfo &abstractInfo=CGCalleeInfo())
llvm::Value * EmitSEHExceptionInfo()
VarDecl * getExceptionDecl() const
llvm::PointerType * getType() const
Return the type of the pointer value.
void EmitSEHTryStmt(const SEHTryStmt &S)
llvm::Value * getSelectorFromSlot()
llvm::BasicBlock * Block
The catch handler for this type.
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
CXXTryStmt - A C++ try block, including all handlers.
void add(RValue rvalue, QualType type, bool needscopy=false)
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
llvm::Value * getExceptionFromSlot()
Returns the contents of the function's exception object and selector slots.
static void emitCatchDispatchBlock(CodeGenFunction &CGF, EHCatchScope &catchScope)
Emit the structure of the dispatch block for the given catch scope.
llvm::LLVMContext & getLLVMContext()
const CGFunctionInfo & arrangeBuiltinFunctionCall(QualType resultType, const CallArgList &args)
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char, signed char, short, int, long..], or an enum decl which has a signed representation.
llvm::IntegerType * Int32Ty
static const EHPersonality & getObjCXXPersonality(const llvm::Triple &T, const LangOptions &L)
Determines the personality function to use when both C++ and Objective-C exceptions are being caught...
static const EHPersonality GNU_ObjCXX
bool hasTerminate() const
Does this runtime provide an objc_terminate function?
clang::ObjCRuntime ObjCRuntime
static const EHPersonality GNU_ObjC_SEH
const TargetInfo & getTarget() const
'gnustep' is the modern non-fragile GNUstep runtime.
const LangOptions & getLangOpts() const
ASTContext & getContext() const
llvm::StoreInst * CreateFlagStore(bool Value, llvm::Value *Addr)
Emit a store to an i1 flag variable.
GlobalDecl - represents a global declaration.
unsigned getBuiltinCallee() const
getBuiltinCallee - If this is a call to a builtin, return the builtin ID of the callee.
llvm::BasicBlock * getEHDispatchBlock(EHScopeStack::stable_iterator scope)
The l-value was considered opaque, so the alignment was determined from a type.
static void emitFilterDispatchBlock(CodeGenFunction &CGF, EHFilterScope &filterScope)
Emit the dispatch block for a filter scope if necessary.
Address recoverAddrOfEscapedLocal(CodeGenFunction &ParentCGF, Address ParentVar, llvm::Value *ParentFP)
Recovers the address of a local in a parent function.
Enumerates target-specific builtins in their own namespaces within namespace clang.
Address CreateBitCast(Address Addr, llvm::Type *Ty, const llvm::Twine &Name="")
static const EHPersonality & getObjCPersonality(const llvm::Triple &T, const LangOptions &L)
Encodes a location in the source.
void EnsureInsertPoint()
EnsureInsertPoint - Ensure that an insertion point is defined so that emitted IR has a place to go...
A saved depth on the scope stack.
unsigned getNumHandlers() const
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
const char * PersonalityFn
'objfw' is the Objective-C runtime included in ObjFW
llvm::BasicBlock * getUnreachableBlock()
llvm::CallSite EmitRuntimeCallOrInvoke(llvm::Value *callee, ArrayRef< llvm::Value *> args, const Twine &name="")
Emits a call or invoke instruction to the given runtime function.
MangleContext - Context for tracking state which persists across multiple calls to the C++ name mangl...
void EmitStmt(const Stmt *S, ArrayRef< const Attr *> Attrs=None)
EmitStmt - Emit the code for the statement.
The noexcept specifier evaluates to true.
bool isObjCObjectPointerType() const
llvm::BasicBlock * getEHResumeBlock(bool isCleanup)
void setCachedEHDispatchBlock(llvm::BasicBlock *block)
llvm::Instruction * CurrentFuncletPad
llvm::Value * getFilter(unsigned i) const
void exit(CodeGenFunction &CGF)
JumpDest getJumpDestInCurrentScope(llvm::BasicBlock *Target)
The given basic block lies in the current EH scope, but may be a target of a potentially scope-crossi...
const VersionTuple & getVersion() const
void EmitStartEHSpec(const Decl *D)
EmitStartEHSpec - Emit the start of the exception spec.
The MS C++ ABI needs a pointer to RTTI data plus some flags to describe the type of a catch handler...
static const EHPersonality & getCXXPersonality(const llvm::Triple &T, const LangOptions &L)
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
static const EHPersonality NeXT_ObjC
FunctionArgList - Type for representing both the decl and type of parameters to a function...
llvm::BasicBlock * getMSVCDispatchBlock(EHScopeStack::stable_iterator scope)
CGFunctionInfo - Class to encapsulate the information about a function definition.
This class organizes the cross-function state that is used while generating LLVM code.
Dataflow Directional Tag Classes.
static ApplyDebugLocation CreateDefaultArtificial(CodeGenFunction &CGF, SourceLocation TemporaryLocation)
Apply TemporaryLocation if it is valid.
static bool LandingPadHasOnlyCXXUses(llvm::LandingPadInst *LPI)
Check whether a landingpad instruction only uses C++ features.
static const EHPersonality GNU_CPlusPlus_SEH
The basic abstraction for the target Objective-C runtime.
static const EHPersonality GNU_ObjC
static bool isNonEHScope(const EHScope &S)
Check whether this is a non-EH scope, i.e.
void EmitAnyExprToExn(const Expr *E, Address Addr)
llvm::LoadInst * CreateAlignedLoad(llvm::Value *Addr, CharUnits Align, const llvm::Twine &Name="")
llvm::LoadInst * CreateLoad(Address Addr, const llvm::Twine &Name="")
SEHExceptStmt * getExceptHandler() const
Returns 0 if not defined.
llvm::Function * getIntrinsic(unsigned IID, ArrayRef< llvm::Type *> Tys=None)
llvm::StoreInst * CreateStore(llvm::Value *Val, Address Addr, bool IsVolatile=false)
llvm::Module & getModule() const
Address getNormalCleanupDestSlot()
Represents a __leave statement.
'ios' is the Apple-provided NeXT-derived runtime on iOS or the iOS simulator; it is always non-fragil...
llvm::BasicBlock * getTerminateFunclet()
getTerminateLandingPad - Return a cleanup funclet that just calls terminate.
static const EHPersonality GNU_CPlusPlus
llvm::PointerType * Int8PtrTy
llvm::LoadInst * CreateFlagLoad(llvm::Value *Addr, const llvm::Twine &Name="")
Emit a load from an i1 flag variable.
llvm::StringRef getName() const
Return the IR name of the pointer value.
static const EHPersonality GNU_ObjC_SJLJ
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
ExceptionSpecificationType
The various types of exception specifications that exist in C++11.
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
void EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock=false)
SEHFinallyStmt * getFinallyHandler() const
static const EHPersonality & getSEHPersonalityMSVC(const llvm::Triple &T)
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Expr * getFilterExpr() const
llvm::BasicBlock * getTerminateLandingPad()
getTerminateLandingPad - Return a landing pad that just calls terminate.
CXXCatchStmt - This represents a C++ catch block.
llvm::Type * ConvertType(QualType T)
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
static const EHPersonality GNU_C_SEH
static const EHPersonality & getCPersonality(const llvm::Triple &T, const LangOptions &L)
The exceptions personality for a function.
CompoundStmt * getTryBlock()
llvm::Value * EmitSEHAbnormalTermination()
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
llvm::Constant * tryEmitAbstract(const Expr *E, QualType T)
Try to emit the result of the given expression as an abstract constant.
void EnterSEHTryStmt(const SEHTryStmt &S)
void startOutlinedSEHHelper(CodeGenFunction &ParentCGF, bool IsFilter, const Stmt *OutlinedStmt)
Arrange a function prototype that can be called by Windows exception handling personalities.
RetTy Visit(PTR(Stmt) S, ParamTys... P)
CGCXXABI & getCXXABI() const
An exceptions scope which filters exceptions thrown through it.
A reference to a declared variable, function, enum, etc.
static RValue get(llvm::Value *V)
void ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock=false)
void EmitBranchThroughCleanup(JumpDest Dest)
EmitBranchThroughCleanup - Emit a branch from the current insert block through the normal cleanup han...
void EmitEndEHSpec(const Decl *D)
EmitEndEHSpec - Emit the end of the exception spec.
static llvm::Constant * getCatchallRethrowFn(CodeGenModule &CGM, StringRef Name)
llvm::StoreInst * CreateAlignedStore(llvm::Value *Val, llvm::Value *Addr, CharUnits Align, bool IsVolatile=false)
NoexceptResult getNoexceptSpec(const ASTContext &Ctx) const
Get the meaning of the noexcept spec on this function, if any.
Information for lazily generating a cleanup.
A non-stable pointer into the scope stack.
void EmitBlockAfterUses(llvm::BasicBlock *BB)
EmitBlockAfterUses - Emit the given block somewhere hopefully near its uses, and leave the insertion ...
static void emitCatchPadBlock(CodeGenFunction &CGF, EHCatchScope &CatchScope)
SourceLocation getLocStart() const LLVM_READONLY
CallArgList - Type for representing both the value and type of arguments in a call.
void PopCleanupBlock(bool FallThroughIsBranchThrough=false)
PopCleanupBlock - Will pop the cleanup entry on the stack and process all branch fixups.
void setHandler(unsigned I, llvm::Constant *Type, llvm::BasicBlock *Block)
CompoundStmt * getTryBlock() const
CompoundStmt * getBlock() const
void EmitCXXThrowExpr(const CXXThrowExpr *E, bool KeepInsertionPoint=true)
bool isLocalVarDeclOrParm() const
Similar to isLocalVarDecl but also includes parameters.
static OMPLinearClause * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, OpenMPLinearClauseKind Modifier, SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc, ArrayRef< Expr *> VL, ArrayRef< Expr *> PL, ArrayRef< Expr *> IL, Expr *Step, Expr *CalcStep, Stmt *PreInit, Expr *PostUpdate)
Creates clause with a list of variables VL and a linear step Step.
const llvm::Triple & getTriple() const