17330f729Sjoerg //===--- CGException.cpp - Emit LLVM Code for C++ exceptions ----*- C++ -*-===//
27330f729Sjoerg //
37330f729Sjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
47330f729Sjoerg // See https://llvm.org/LICENSE.txt for license information.
57330f729Sjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
67330f729Sjoerg //
77330f729Sjoerg //===----------------------------------------------------------------------===//
87330f729Sjoerg //
97330f729Sjoerg // This contains code dealing with C++ exception related code generation.
107330f729Sjoerg //
117330f729Sjoerg //===----------------------------------------------------------------------===//
127330f729Sjoerg
137330f729Sjoerg #include "CGCXXABI.h"
147330f729Sjoerg #include "CGCleanup.h"
157330f729Sjoerg #include "CGObjCRuntime.h"
16*e038c9c4Sjoerg #include "CodeGenFunction.h"
177330f729Sjoerg #include "ConstantEmitter.h"
187330f729Sjoerg #include "TargetInfo.h"
197330f729Sjoerg #include "clang/AST/Mangle.h"
207330f729Sjoerg #include "clang/AST/StmtCXX.h"
217330f729Sjoerg #include "clang/AST/StmtObjC.h"
227330f729Sjoerg #include "clang/AST/StmtVisitor.h"
23*e038c9c4Sjoerg #include "clang/Basic/DiagnosticSema.h"
247330f729Sjoerg #include "clang/Basic/TargetBuiltins.h"
257330f729Sjoerg #include "llvm/IR/IntrinsicInst.h"
26*e038c9c4Sjoerg #include "llvm/IR/Intrinsics.h"
27*e038c9c4Sjoerg #include "llvm/IR/IntrinsicsWebAssembly.h"
287330f729Sjoerg #include "llvm/Support/SaveAndRestore.h"
297330f729Sjoerg
307330f729Sjoerg using namespace clang;
317330f729Sjoerg using namespace CodeGen;
327330f729Sjoerg
getFreeExceptionFn(CodeGenModule & CGM)337330f729Sjoerg static llvm::FunctionCallee getFreeExceptionFn(CodeGenModule &CGM) {
347330f729Sjoerg // void __cxa_free_exception(void *thrown_exception);
357330f729Sjoerg
367330f729Sjoerg llvm::FunctionType *FTy =
377330f729Sjoerg llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*isVarArg=*/false);
387330f729Sjoerg
397330f729Sjoerg return CGM.CreateRuntimeFunction(FTy, "__cxa_free_exception");
407330f729Sjoerg }
417330f729Sjoerg
getSehTryBeginFn(CodeGenModule & CGM)42*e038c9c4Sjoerg static llvm::FunctionCallee getSehTryBeginFn(CodeGenModule &CGM) {
43*e038c9c4Sjoerg llvm::FunctionType *FTy =
44*e038c9c4Sjoerg llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
45*e038c9c4Sjoerg return CGM.CreateRuntimeFunction(FTy, "llvm.seh.try.begin");
46*e038c9c4Sjoerg }
47*e038c9c4Sjoerg
getSehTryEndFn(CodeGenModule & CGM)48*e038c9c4Sjoerg static llvm::FunctionCallee getSehTryEndFn(CodeGenModule &CGM) {
49*e038c9c4Sjoerg llvm::FunctionType *FTy =
50*e038c9c4Sjoerg llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
51*e038c9c4Sjoerg return CGM.CreateRuntimeFunction(FTy, "llvm.seh.try.end");
52*e038c9c4Sjoerg }
53*e038c9c4Sjoerg
getUnexpectedFn(CodeGenModule & CGM)547330f729Sjoerg static llvm::FunctionCallee getUnexpectedFn(CodeGenModule &CGM) {
557330f729Sjoerg // void __cxa_call_unexpected(void *thrown_exception);
567330f729Sjoerg
577330f729Sjoerg llvm::FunctionType *FTy =
587330f729Sjoerg llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*isVarArg=*/false);
597330f729Sjoerg
607330f729Sjoerg return CGM.CreateRuntimeFunction(FTy, "__cxa_call_unexpected");
617330f729Sjoerg }
627330f729Sjoerg
getTerminateFn()637330f729Sjoerg llvm::FunctionCallee CodeGenModule::getTerminateFn() {
647330f729Sjoerg // void __terminate();
657330f729Sjoerg
667330f729Sjoerg llvm::FunctionType *FTy =
677330f729Sjoerg llvm::FunctionType::get(VoidTy, /*isVarArg=*/false);
687330f729Sjoerg
697330f729Sjoerg StringRef name;
707330f729Sjoerg
717330f729Sjoerg // In C++, use std::terminate().
727330f729Sjoerg if (getLangOpts().CPlusPlus &&
737330f729Sjoerg getTarget().getCXXABI().isItaniumFamily()) {
747330f729Sjoerg name = "_ZSt9terminatev";
757330f729Sjoerg } else if (getLangOpts().CPlusPlus &&
767330f729Sjoerg getTarget().getCXXABI().isMicrosoft()) {
777330f729Sjoerg if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
787330f729Sjoerg name = "__std_terminate";
797330f729Sjoerg else
807330f729Sjoerg name = "?terminate@@YAXXZ";
817330f729Sjoerg } else if (getLangOpts().ObjC &&
827330f729Sjoerg getLangOpts().ObjCRuntime.hasTerminate())
837330f729Sjoerg name = "objc_terminate";
847330f729Sjoerg else
857330f729Sjoerg name = "abort";
867330f729Sjoerg return CreateRuntimeFunction(FTy, name);
877330f729Sjoerg }
887330f729Sjoerg
getCatchallRethrowFn(CodeGenModule & CGM,StringRef Name)897330f729Sjoerg static llvm::FunctionCallee getCatchallRethrowFn(CodeGenModule &CGM,
907330f729Sjoerg StringRef Name) {
917330f729Sjoerg llvm::FunctionType *FTy =
927330f729Sjoerg llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*isVarArg=*/false);
937330f729Sjoerg
947330f729Sjoerg return CGM.CreateRuntimeFunction(FTy, Name);
957330f729Sjoerg }
967330f729Sjoerg
977330f729Sjoerg const EHPersonality EHPersonality::GNU_C = { "__gcc_personality_v0", nullptr };
987330f729Sjoerg const EHPersonality
997330f729Sjoerg EHPersonality::GNU_C_SJLJ = { "__gcc_personality_sj0", nullptr };
1007330f729Sjoerg const EHPersonality
1017330f729Sjoerg EHPersonality::GNU_C_SEH = { "__gcc_personality_seh0", nullptr };
1027330f729Sjoerg const EHPersonality
1037330f729Sjoerg EHPersonality::NeXT_ObjC = { "__objc_personality_v0", nullptr };
1047330f729Sjoerg const EHPersonality
1057330f729Sjoerg EHPersonality::GNU_CPlusPlus = { "__gxx_personality_v0", nullptr };
1067330f729Sjoerg const EHPersonality
1077330f729Sjoerg EHPersonality::GNU_CPlusPlus_SJLJ = { "__gxx_personality_sj0", nullptr };
1087330f729Sjoerg const EHPersonality
1097330f729Sjoerg EHPersonality::GNU_CPlusPlus_SEH = { "__gxx_personality_seh0", nullptr };
1107330f729Sjoerg const EHPersonality
1117330f729Sjoerg EHPersonality::GNU_ObjC = {"__gnu_objc_personality_v0", "objc_exception_throw"};
1127330f729Sjoerg const EHPersonality
1137330f729Sjoerg EHPersonality::GNU_ObjC_SJLJ = {"__gnu_objc_personality_sj0", "objc_exception_throw"};
1147330f729Sjoerg const EHPersonality
1157330f729Sjoerg EHPersonality::GNU_ObjC_SEH = {"__gnu_objc_personality_seh0", "objc_exception_throw"};
1167330f729Sjoerg const EHPersonality
1177330f729Sjoerg EHPersonality::GNU_ObjCXX = { "__gnustep_objcxx_personality_v0", nullptr };
1187330f729Sjoerg const EHPersonality
1197330f729Sjoerg EHPersonality::GNUstep_ObjC = { "__gnustep_objc_personality_v0", nullptr };
1207330f729Sjoerg const EHPersonality
1217330f729Sjoerg EHPersonality::MSVC_except_handler = { "_except_handler3", nullptr };
1227330f729Sjoerg const EHPersonality
1237330f729Sjoerg EHPersonality::MSVC_C_specific_handler = { "__C_specific_handler", nullptr };
1247330f729Sjoerg const EHPersonality
1257330f729Sjoerg EHPersonality::MSVC_CxxFrameHandler3 = { "__CxxFrameHandler3", nullptr };
1267330f729Sjoerg const EHPersonality
1277330f729Sjoerg EHPersonality::GNU_Wasm_CPlusPlus = { "__gxx_wasm_personality_v0", nullptr };
128*e038c9c4Sjoerg const EHPersonality EHPersonality::XL_CPlusPlus = {"__xlcxx_personality_v1",
129*e038c9c4Sjoerg nullptr};
1307330f729Sjoerg
getCPersonality(const TargetInfo & Target,const LangOptions & L)1317330f729Sjoerg static const EHPersonality &getCPersonality(const TargetInfo &Target,
1327330f729Sjoerg const LangOptions &L) {
1337330f729Sjoerg const llvm::Triple &T = Target.getTriple();
1347330f729Sjoerg if (T.isWindowsMSVCEnvironment())
1357330f729Sjoerg return EHPersonality::MSVC_CxxFrameHandler3;
136*e038c9c4Sjoerg if (L.hasSjLjExceptions())
1377330f729Sjoerg return EHPersonality::GNU_C_SJLJ;
138*e038c9c4Sjoerg if (L.hasDWARFExceptions())
1397330f729Sjoerg return EHPersonality::GNU_C;
140*e038c9c4Sjoerg if (L.hasSEHExceptions())
1417330f729Sjoerg return EHPersonality::GNU_C_SEH;
1427330f729Sjoerg return EHPersonality::GNU_C;
1437330f729Sjoerg }
1447330f729Sjoerg
getObjCPersonality(const TargetInfo & Target,const LangOptions & L)1457330f729Sjoerg static const EHPersonality &getObjCPersonality(const TargetInfo &Target,
1467330f729Sjoerg const LangOptions &L) {
1477330f729Sjoerg const llvm::Triple &T = Target.getTriple();
1487330f729Sjoerg if (T.isWindowsMSVCEnvironment())
1497330f729Sjoerg return EHPersonality::MSVC_CxxFrameHandler3;
1507330f729Sjoerg
1517330f729Sjoerg switch (L.ObjCRuntime.getKind()) {
1527330f729Sjoerg case ObjCRuntime::FragileMacOSX:
1537330f729Sjoerg return getCPersonality(Target, L);
1547330f729Sjoerg case ObjCRuntime::MacOSX:
1557330f729Sjoerg case ObjCRuntime::iOS:
1567330f729Sjoerg case ObjCRuntime::WatchOS:
1577330f729Sjoerg return EHPersonality::NeXT_ObjC;
1587330f729Sjoerg case ObjCRuntime::GNUstep:
1597330f729Sjoerg if (L.ObjCRuntime.getVersion() >= VersionTuple(1, 7))
1607330f729Sjoerg return EHPersonality::GNUstep_ObjC;
1617330f729Sjoerg LLVM_FALLTHROUGH;
1627330f729Sjoerg case ObjCRuntime::GCC:
1637330f729Sjoerg case ObjCRuntime::ObjFW:
164*e038c9c4Sjoerg if (L.hasSjLjExceptions())
1657330f729Sjoerg return EHPersonality::GNU_ObjC_SJLJ;
166*e038c9c4Sjoerg if (L.hasSEHExceptions())
1677330f729Sjoerg return EHPersonality::GNU_ObjC_SEH;
1687330f729Sjoerg return EHPersonality::GNU_ObjC;
1697330f729Sjoerg }
1707330f729Sjoerg llvm_unreachable("bad runtime kind");
1717330f729Sjoerg }
1727330f729Sjoerg
getCXXPersonality(const TargetInfo & Target,const LangOptions & L)1737330f729Sjoerg static const EHPersonality &getCXXPersonality(const TargetInfo &Target,
1747330f729Sjoerg const LangOptions &L) {
1757330f729Sjoerg const llvm::Triple &T = Target.getTriple();
1767330f729Sjoerg if (T.isWindowsMSVCEnvironment())
1777330f729Sjoerg return EHPersonality::MSVC_CxxFrameHandler3;
178*e038c9c4Sjoerg if (T.isOSAIX())
179*e038c9c4Sjoerg return EHPersonality::XL_CPlusPlus;
180*e038c9c4Sjoerg if (L.hasSjLjExceptions())
1817330f729Sjoerg return EHPersonality::GNU_CPlusPlus_SJLJ;
182*e038c9c4Sjoerg if (L.hasDWARFExceptions())
1837330f729Sjoerg return EHPersonality::GNU_CPlusPlus;
184*e038c9c4Sjoerg if (L.hasSEHExceptions())
1857330f729Sjoerg return EHPersonality::GNU_CPlusPlus_SEH;
186*e038c9c4Sjoerg if (L.hasWasmExceptions())
1877330f729Sjoerg return EHPersonality::GNU_Wasm_CPlusPlus;
1887330f729Sjoerg return EHPersonality::GNU_CPlusPlus;
1897330f729Sjoerg }
1907330f729Sjoerg
1917330f729Sjoerg /// Determines the personality function to use when both C++
1927330f729Sjoerg /// and Objective-C exceptions are being caught.
getObjCXXPersonality(const TargetInfo & Target,const LangOptions & L)1937330f729Sjoerg static const EHPersonality &getObjCXXPersonality(const TargetInfo &Target,
1947330f729Sjoerg const LangOptions &L) {
1957330f729Sjoerg if (Target.getTriple().isWindowsMSVCEnvironment())
1967330f729Sjoerg return EHPersonality::MSVC_CxxFrameHandler3;
1977330f729Sjoerg
1987330f729Sjoerg switch (L.ObjCRuntime.getKind()) {
1997330f729Sjoerg // In the fragile ABI, just use C++ exception handling and hope
2007330f729Sjoerg // they're not doing crazy exception mixing.
2017330f729Sjoerg case ObjCRuntime::FragileMacOSX:
2027330f729Sjoerg return getCXXPersonality(Target, L);
2037330f729Sjoerg
2047330f729Sjoerg // The ObjC personality defers to the C++ personality for non-ObjC
2057330f729Sjoerg // handlers. Unlike the C++ case, we use the same personality
2067330f729Sjoerg // function on targets using (backend-driven) SJLJ EH.
2077330f729Sjoerg case ObjCRuntime::MacOSX:
2087330f729Sjoerg case ObjCRuntime::iOS:
2097330f729Sjoerg case ObjCRuntime::WatchOS:
2107330f729Sjoerg return getObjCPersonality(Target, L);
2117330f729Sjoerg
2127330f729Sjoerg case ObjCRuntime::GNUstep:
2137330f729Sjoerg return EHPersonality::GNU_ObjCXX;
2147330f729Sjoerg
2157330f729Sjoerg // The GCC runtime's personality function inherently doesn't support
2167330f729Sjoerg // mixed EH. Use the ObjC personality just to avoid returning null.
2177330f729Sjoerg case ObjCRuntime::GCC:
2187330f729Sjoerg case ObjCRuntime::ObjFW:
2197330f729Sjoerg return getObjCPersonality(Target, L);
2207330f729Sjoerg }
2217330f729Sjoerg llvm_unreachable("bad runtime kind");
2227330f729Sjoerg }
2237330f729Sjoerg
getSEHPersonalityMSVC(const llvm::Triple & T)2247330f729Sjoerg static const EHPersonality &getSEHPersonalityMSVC(const llvm::Triple &T) {
2257330f729Sjoerg if (T.getArch() == llvm::Triple::x86)
2267330f729Sjoerg return EHPersonality::MSVC_except_handler;
2277330f729Sjoerg return EHPersonality::MSVC_C_specific_handler;
2287330f729Sjoerg }
2297330f729Sjoerg
get(CodeGenModule & CGM,const FunctionDecl * FD)2307330f729Sjoerg const EHPersonality &EHPersonality::get(CodeGenModule &CGM,
2317330f729Sjoerg const FunctionDecl *FD) {
2327330f729Sjoerg const llvm::Triple &T = CGM.getTarget().getTriple();
2337330f729Sjoerg const LangOptions &L = CGM.getLangOpts();
2347330f729Sjoerg const TargetInfo &Target = CGM.getTarget();
2357330f729Sjoerg
2367330f729Sjoerg // Functions using SEH get an SEH personality.
2377330f729Sjoerg if (FD && FD->usesSEHTry())
2387330f729Sjoerg return getSEHPersonalityMSVC(T);
2397330f729Sjoerg
2407330f729Sjoerg if (L.ObjC)
2417330f729Sjoerg return L.CPlusPlus ? getObjCXXPersonality(Target, L)
2427330f729Sjoerg : getObjCPersonality(Target, L);
2437330f729Sjoerg return L.CPlusPlus ? getCXXPersonality(Target, L)
2447330f729Sjoerg : getCPersonality(Target, L);
2457330f729Sjoerg }
2467330f729Sjoerg
get(CodeGenFunction & CGF)2477330f729Sjoerg const EHPersonality &EHPersonality::get(CodeGenFunction &CGF) {
2487330f729Sjoerg const auto *FD = CGF.CurCodeDecl;
2497330f729Sjoerg // For outlined finallys and filters, use the SEH personality in case they
2507330f729Sjoerg // contain more SEH. This mostly only affects finallys. Filters could
2517330f729Sjoerg // hypothetically use gnu statement expressions to sneak in nested SEH.
2527330f729Sjoerg FD = FD ? FD : CGF.CurSEHParent;
2537330f729Sjoerg return get(CGF.CGM, dyn_cast_or_null<FunctionDecl>(FD));
2547330f729Sjoerg }
2557330f729Sjoerg
getPersonalityFn(CodeGenModule & CGM,const EHPersonality & Personality)2567330f729Sjoerg static llvm::FunctionCallee getPersonalityFn(CodeGenModule &CGM,
2577330f729Sjoerg const EHPersonality &Personality) {
2587330f729Sjoerg return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.Int32Ty, true),
2597330f729Sjoerg Personality.PersonalityFn,
2607330f729Sjoerg llvm::AttributeList(), /*Local=*/true);
2617330f729Sjoerg }
2627330f729Sjoerg
getOpaquePersonalityFn(CodeGenModule & CGM,const EHPersonality & Personality)2637330f729Sjoerg static llvm::Constant *getOpaquePersonalityFn(CodeGenModule &CGM,
2647330f729Sjoerg const EHPersonality &Personality) {
2657330f729Sjoerg llvm::FunctionCallee Fn = getPersonalityFn(CGM, Personality);
2667330f729Sjoerg llvm::PointerType* Int8PtrTy = llvm::PointerType::get(
2677330f729Sjoerg llvm::Type::getInt8Ty(CGM.getLLVMContext()),
2687330f729Sjoerg CGM.getDataLayout().getProgramAddressSpace());
2697330f729Sjoerg
2707330f729Sjoerg return llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(Fn.getCallee()),
2717330f729Sjoerg Int8PtrTy);
2727330f729Sjoerg }
2737330f729Sjoerg
2747330f729Sjoerg /// Check whether a landingpad instruction only uses C++ features.
LandingPadHasOnlyCXXUses(llvm::LandingPadInst * LPI)2757330f729Sjoerg static bool LandingPadHasOnlyCXXUses(llvm::LandingPadInst *LPI) {
2767330f729Sjoerg for (unsigned I = 0, E = LPI->getNumClauses(); I != E; ++I) {
2777330f729Sjoerg // Look for something that would've been returned by the ObjC
2787330f729Sjoerg // runtime's GetEHType() method.
2797330f729Sjoerg llvm::Value *Val = LPI->getClause(I)->stripPointerCasts();
2807330f729Sjoerg if (LPI->isCatch(I)) {
2817330f729Sjoerg // Check if the catch value has the ObjC prefix.
2827330f729Sjoerg if (llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Val))
2837330f729Sjoerg // ObjC EH selector entries are always global variables with
2847330f729Sjoerg // names starting like this.
2857330f729Sjoerg if (GV->getName().startswith("OBJC_EHTYPE"))
2867330f729Sjoerg return false;
2877330f729Sjoerg } else {
2887330f729Sjoerg // Check if any of the filter values have the ObjC prefix.
2897330f729Sjoerg llvm::Constant *CVal = cast<llvm::Constant>(Val);
2907330f729Sjoerg for (llvm::User::op_iterator
2917330f729Sjoerg II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II) {
2927330f729Sjoerg if (llvm::GlobalVariable *GV =
2937330f729Sjoerg cast<llvm::GlobalVariable>((*II)->stripPointerCasts()))
2947330f729Sjoerg // ObjC EH selector entries are always global variables with
2957330f729Sjoerg // names starting like this.
2967330f729Sjoerg if (GV->getName().startswith("OBJC_EHTYPE"))
2977330f729Sjoerg return false;
2987330f729Sjoerg }
2997330f729Sjoerg }
3007330f729Sjoerg }
3017330f729Sjoerg return true;
3027330f729Sjoerg }
3037330f729Sjoerg
3047330f729Sjoerg /// Check whether a personality function could reasonably be swapped
3057330f729Sjoerg /// for a C++ personality function.
PersonalityHasOnlyCXXUses(llvm::Constant * Fn)3067330f729Sjoerg static bool PersonalityHasOnlyCXXUses(llvm::Constant *Fn) {
3077330f729Sjoerg for (llvm::User *U : Fn->users()) {
3087330f729Sjoerg // Conditionally white-list bitcasts.
3097330f729Sjoerg if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(U)) {
3107330f729Sjoerg if (CE->getOpcode() != llvm::Instruction::BitCast) return false;
3117330f729Sjoerg if (!PersonalityHasOnlyCXXUses(CE))
3127330f729Sjoerg return false;
3137330f729Sjoerg continue;
3147330f729Sjoerg }
3157330f729Sjoerg
3167330f729Sjoerg // Otherwise it must be a function.
3177330f729Sjoerg llvm::Function *F = dyn_cast<llvm::Function>(U);
3187330f729Sjoerg if (!F) return false;
3197330f729Sjoerg
3207330f729Sjoerg for (auto BB = F->begin(), E = F->end(); BB != E; ++BB) {
3217330f729Sjoerg if (BB->isLandingPad())
3227330f729Sjoerg if (!LandingPadHasOnlyCXXUses(BB->getLandingPadInst()))
3237330f729Sjoerg return false;
3247330f729Sjoerg }
3257330f729Sjoerg }
3267330f729Sjoerg
3277330f729Sjoerg return true;
3287330f729Sjoerg }
3297330f729Sjoerg
3307330f729Sjoerg /// Try to use the C++ personality function in ObjC++. Not doing this
3317330f729Sjoerg /// can cause some incompatibilities with gcc, which is more
3327330f729Sjoerg /// aggressive about only using the ObjC++ personality in a function
3337330f729Sjoerg /// when it really needs it.
SimplifyPersonality()3347330f729Sjoerg void CodeGenModule::SimplifyPersonality() {
3357330f729Sjoerg // If we're not in ObjC++ -fexceptions, there's nothing to do.
3367330f729Sjoerg if (!LangOpts.CPlusPlus || !LangOpts.ObjC || !LangOpts.Exceptions)
3377330f729Sjoerg return;
3387330f729Sjoerg
3397330f729Sjoerg // Both the problem this endeavors to fix and the way the logic
3407330f729Sjoerg // above works is specific to the NeXT runtime.
3417330f729Sjoerg if (!LangOpts.ObjCRuntime.isNeXTFamily())
3427330f729Sjoerg return;
3437330f729Sjoerg
3447330f729Sjoerg const EHPersonality &ObjCXX = EHPersonality::get(*this, /*FD=*/nullptr);
3457330f729Sjoerg const EHPersonality &CXX = getCXXPersonality(getTarget(), LangOpts);
3467330f729Sjoerg if (&ObjCXX == &CXX)
3477330f729Sjoerg return;
3487330f729Sjoerg
3497330f729Sjoerg assert(std::strcmp(ObjCXX.PersonalityFn, CXX.PersonalityFn) != 0 &&
3507330f729Sjoerg "Different EHPersonalities using the same personality function.");
3517330f729Sjoerg
3527330f729Sjoerg llvm::Function *Fn = getModule().getFunction(ObjCXX.PersonalityFn);
3537330f729Sjoerg
3547330f729Sjoerg // Nothing to do if it's unused.
3557330f729Sjoerg if (!Fn || Fn->use_empty()) return;
3567330f729Sjoerg
3577330f729Sjoerg // Can't do the optimization if it has non-C++ uses.
3587330f729Sjoerg if (!PersonalityHasOnlyCXXUses(Fn)) return;
3597330f729Sjoerg
3607330f729Sjoerg // Create the C++ personality function and kill off the old
3617330f729Sjoerg // function.
3627330f729Sjoerg llvm::FunctionCallee CXXFn = getPersonalityFn(*this, CXX);
3637330f729Sjoerg
3647330f729Sjoerg // This can happen if the user is screwing with us.
3657330f729Sjoerg if (Fn->getType() != CXXFn.getCallee()->getType())
3667330f729Sjoerg return;
3677330f729Sjoerg
3687330f729Sjoerg Fn->replaceAllUsesWith(CXXFn.getCallee());
3697330f729Sjoerg Fn->eraseFromParent();
3707330f729Sjoerg }
3717330f729Sjoerg
3727330f729Sjoerg /// Returns the value to inject into a selector to indicate the
3737330f729Sjoerg /// presence of a catch-all.
getCatchAllValue(CodeGenFunction & CGF)3747330f729Sjoerg static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
3757330f729Sjoerg // Possibly we should use @llvm.eh.catch.all.value here.
3767330f729Sjoerg return llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
3777330f729Sjoerg }
3787330f729Sjoerg
3797330f729Sjoerg namespace {
3807330f729Sjoerg /// A cleanup to free the exception object if its initialization
3817330f729Sjoerg /// throws.
3827330f729Sjoerg struct FreeException final : EHScopeStack::Cleanup {
3837330f729Sjoerg llvm::Value *exn;
FreeException__anon3e0594620111::FreeException3847330f729Sjoerg FreeException(llvm::Value *exn) : exn(exn) {}
Emit__anon3e0594620111::FreeException3857330f729Sjoerg void Emit(CodeGenFunction &CGF, Flags flags) override {
3867330f729Sjoerg CGF.EmitNounwindRuntimeCall(getFreeExceptionFn(CGF.CGM), exn);
3877330f729Sjoerg }
3887330f729Sjoerg };
3897330f729Sjoerg } // end anonymous namespace
3907330f729Sjoerg
3917330f729Sjoerg // Emits an exception expression into the given location. This
3927330f729Sjoerg // differs from EmitAnyExprToMem only in that, if a final copy-ctor
3937330f729Sjoerg // call is required, an exception within that copy ctor causes
3947330f729Sjoerg // std::terminate to be invoked.
EmitAnyExprToExn(const Expr * e,Address addr)3957330f729Sjoerg void CodeGenFunction::EmitAnyExprToExn(const Expr *e, Address addr) {
3967330f729Sjoerg // Make sure the exception object is cleaned up if there's an
3977330f729Sjoerg // exception during initialization.
3987330f729Sjoerg pushFullExprCleanup<FreeException>(EHCleanup, addr.getPointer());
3997330f729Sjoerg EHScopeStack::stable_iterator cleanup = EHStack.stable_begin();
4007330f729Sjoerg
4017330f729Sjoerg // __cxa_allocate_exception returns a void*; we need to cast this
4027330f729Sjoerg // to the appropriate type for the object.
4037330f729Sjoerg llvm::Type *ty = ConvertTypeForMem(e->getType())->getPointerTo();
4047330f729Sjoerg Address typedAddr = Builder.CreateBitCast(addr, ty);
4057330f729Sjoerg
4067330f729Sjoerg // FIXME: this isn't quite right! If there's a final unelided call
4077330f729Sjoerg // to a copy constructor, then according to [except.terminate]p1 we
4087330f729Sjoerg // must call std::terminate() if that constructor throws, because
4097330f729Sjoerg // technically that copy occurs after the exception expression is
4107330f729Sjoerg // evaluated but before the exception is caught. But the best way
4117330f729Sjoerg // to handle that is to teach EmitAggExpr to do the final copy
4127330f729Sjoerg // differently if it can't be elided.
4137330f729Sjoerg EmitAnyExprToMem(e, typedAddr, e->getType().getQualifiers(),
4147330f729Sjoerg /*IsInit*/ true);
4157330f729Sjoerg
4167330f729Sjoerg // Deactivate the cleanup block.
4177330f729Sjoerg DeactivateCleanupBlock(cleanup,
4187330f729Sjoerg cast<llvm::Instruction>(typedAddr.getPointer()));
4197330f729Sjoerg }
4207330f729Sjoerg
getExceptionSlot()4217330f729Sjoerg Address CodeGenFunction::getExceptionSlot() {
4227330f729Sjoerg if (!ExceptionSlot)
4237330f729Sjoerg ExceptionSlot = CreateTempAlloca(Int8PtrTy, "exn.slot");
4247330f729Sjoerg return Address(ExceptionSlot, getPointerAlign());
4257330f729Sjoerg }
4267330f729Sjoerg
getEHSelectorSlot()4277330f729Sjoerg Address CodeGenFunction::getEHSelectorSlot() {
4287330f729Sjoerg if (!EHSelectorSlot)
4297330f729Sjoerg EHSelectorSlot = CreateTempAlloca(Int32Ty, "ehselector.slot");
4307330f729Sjoerg return Address(EHSelectorSlot, CharUnits::fromQuantity(4));
4317330f729Sjoerg }
4327330f729Sjoerg
getExceptionFromSlot()4337330f729Sjoerg llvm::Value *CodeGenFunction::getExceptionFromSlot() {
4347330f729Sjoerg return Builder.CreateLoad(getExceptionSlot(), "exn");
4357330f729Sjoerg }
4367330f729Sjoerg
getSelectorFromSlot()4377330f729Sjoerg llvm::Value *CodeGenFunction::getSelectorFromSlot() {
4387330f729Sjoerg return Builder.CreateLoad(getEHSelectorSlot(), "sel");
4397330f729Sjoerg }
4407330f729Sjoerg
EmitCXXThrowExpr(const CXXThrowExpr * E,bool KeepInsertionPoint)4417330f729Sjoerg void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E,
4427330f729Sjoerg bool KeepInsertionPoint) {
4437330f729Sjoerg if (const Expr *SubExpr = E->getSubExpr()) {
4447330f729Sjoerg QualType ThrowType = SubExpr->getType();
4457330f729Sjoerg if (ThrowType->isObjCObjectPointerType()) {
4467330f729Sjoerg const Stmt *ThrowStmt = E->getSubExpr();
4477330f729Sjoerg const ObjCAtThrowStmt S(E->getExprLoc(), const_cast<Stmt *>(ThrowStmt));
4487330f729Sjoerg CGM.getObjCRuntime().EmitThrowStmt(*this, S, false);
4497330f729Sjoerg } else {
4507330f729Sjoerg CGM.getCXXABI().emitThrow(*this, E);
4517330f729Sjoerg }
4527330f729Sjoerg } else {
4537330f729Sjoerg CGM.getCXXABI().emitRethrow(*this, /*isNoReturn=*/true);
4547330f729Sjoerg }
4557330f729Sjoerg
4567330f729Sjoerg // throw is an expression, and the expression emitters expect us
4577330f729Sjoerg // to leave ourselves at a valid insertion point.
4587330f729Sjoerg if (KeepInsertionPoint)
4597330f729Sjoerg EmitBlock(createBasicBlock("throw.cont"));
4607330f729Sjoerg }
4617330f729Sjoerg
EmitStartEHSpec(const Decl * D)4627330f729Sjoerg void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
4637330f729Sjoerg if (!CGM.getLangOpts().CXXExceptions)
4647330f729Sjoerg return;
4657330f729Sjoerg
4667330f729Sjoerg const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
4677330f729Sjoerg if (!FD) {
4687330f729Sjoerg // Check if CapturedDecl is nothrow and create terminate scope for it.
4697330f729Sjoerg if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
4707330f729Sjoerg if (CD->isNothrow())
4717330f729Sjoerg EHStack.pushTerminate();
4727330f729Sjoerg }
4737330f729Sjoerg return;
4747330f729Sjoerg }
4757330f729Sjoerg const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
4767330f729Sjoerg if (!Proto)
4777330f729Sjoerg return;
4787330f729Sjoerg
4797330f729Sjoerg ExceptionSpecificationType EST = Proto->getExceptionSpecType();
4807330f729Sjoerg if (isNoexceptExceptionSpec(EST) && Proto->canThrow() == CT_Cannot) {
4817330f729Sjoerg // noexcept functions are simple terminate scopes.
482*e038c9c4Sjoerg if (!getLangOpts().EHAsynch) // -EHa: HW exception still can occur
4837330f729Sjoerg EHStack.pushTerminate();
4847330f729Sjoerg } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
4857330f729Sjoerg // TODO: Revisit exception specifications for the MS ABI. There is a way to
4867330f729Sjoerg // encode these in an object file but MSVC doesn't do anything with it.
4877330f729Sjoerg if (getTarget().getCXXABI().isMicrosoft())
4887330f729Sjoerg return;
489*e038c9c4Sjoerg // In Wasm EH we currently treat 'throw()' in the same way as 'noexcept'. In
490*e038c9c4Sjoerg // case of throw with types, we ignore it and print a warning for now.
491*e038c9c4Sjoerg // TODO Correctly handle exception specification in Wasm EH
492*e038c9c4Sjoerg if (CGM.getLangOpts().hasWasmExceptions()) {
493*e038c9c4Sjoerg if (EST == EST_DynamicNone)
494*e038c9c4Sjoerg EHStack.pushTerminate();
495*e038c9c4Sjoerg else
496*e038c9c4Sjoerg CGM.getDiags().Report(D->getLocation(),
497*e038c9c4Sjoerg diag::warn_wasm_dynamic_exception_spec_ignored)
498*e038c9c4Sjoerg << FD->getExceptionSpecSourceRange();
499*e038c9c4Sjoerg return;
500*e038c9c4Sjoerg }
501*e038c9c4Sjoerg // Currently Emscripten EH only handles 'throw()' but not 'throw' with
502*e038c9c4Sjoerg // types. 'throw()' handling will be done in JS glue code so we don't need
503*e038c9c4Sjoerg // to do anything in that case. Just print a warning message in case of
504*e038c9c4Sjoerg // throw with types.
505*e038c9c4Sjoerg // TODO Correctly handle exception specification in Emscripten EH
506*e038c9c4Sjoerg if (getTarget().getCXXABI() == TargetCXXABI::WebAssembly &&
507*e038c9c4Sjoerg CGM.getLangOpts().getExceptionHandling() ==
508*e038c9c4Sjoerg LangOptions::ExceptionHandlingKind::None &&
509*e038c9c4Sjoerg EST == EST_Dynamic)
510*e038c9c4Sjoerg CGM.getDiags().Report(D->getLocation(),
511*e038c9c4Sjoerg diag::warn_wasm_dynamic_exception_spec_ignored)
512*e038c9c4Sjoerg << FD->getExceptionSpecSourceRange();
513*e038c9c4Sjoerg
5147330f729Sjoerg unsigned NumExceptions = Proto->getNumExceptions();
5157330f729Sjoerg EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
5167330f729Sjoerg
5177330f729Sjoerg for (unsigned I = 0; I != NumExceptions; ++I) {
5187330f729Sjoerg QualType Ty = Proto->getExceptionType(I);
5197330f729Sjoerg QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
5207330f729Sjoerg llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType,
5217330f729Sjoerg /*ForEH=*/true);
5227330f729Sjoerg Filter->setFilter(I, EHType);
5237330f729Sjoerg }
5247330f729Sjoerg }
5257330f729Sjoerg }
5267330f729Sjoerg
5277330f729Sjoerg /// Emit the dispatch block for a filter scope if necessary.
emitFilterDispatchBlock(CodeGenFunction & CGF,EHFilterScope & filterScope)5287330f729Sjoerg static void emitFilterDispatchBlock(CodeGenFunction &CGF,
5297330f729Sjoerg EHFilterScope &filterScope) {
5307330f729Sjoerg llvm::BasicBlock *dispatchBlock = filterScope.getCachedEHDispatchBlock();
5317330f729Sjoerg if (!dispatchBlock) return;
5327330f729Sjoerg if (dispatchBlock->use_empty()) {
5337330f729Sjoerg delete dispatchBlock;
5347330f729Sjoerg return;
5357330f729Sjoerg }
5367330f729Sjoerg
5377330f729Sjoerg CGF.EmitBlockAfterUses(dispatchBlock);
5387330f729Sjoerg
5397330f729Sjoerg // If this isn't a catch-all filter, we need to check whether we got
5407330f729Sjoerg // here because the filter triggered.
5417330f729Sjoerg if (filterScope.getNumFilters()) {
5427330f729Sjoerg // Load the selector value.
5437330f729Sjoerg llvm::Value *selector = CGF.getSelectorFromSlot();
5447330f729Sjoerg llvm::BasicBlock *unexpectedBB = CGF.createBasicBlock("ehspec.unexpected");
5457330f729Sjoerg
5467330f729Sjoerg llvm::Value *zero = CGF.Builder.getInt32(0);
5477330f729Sjoerg llvm::Value *failsFilter =
5487330f729Sjoerg CGF.Builder.CreateICmpSLT(selector, zero, "ehspec.fails");
5497330f729Sjoerg CGF.Builder.CreateCondBr(failsFilter, unexpectedBB,
5507330f729Sjoerg CGF.getEHResumeBlock(false));
5517330f729Sjoerg
5527330f729Sjoerg CGF.EmitBlock(unexpectedBB);
5537330f729Sjoerg }
5547330f729Sjoerg
5557330f729Sjoerg // Call __cxa_call_unexpected. This doesn't need to be an invoke
5567330f729Sjoerg // because __cxa_call_unexpected magically filters exceptions
5577330f729Sjoerg // according to the last landing pad the exception was thrown
5587330f729Sjoerg // into. Seriously.
5597330f729Sjoerg llvm::Value *exn = CGF.getExceptionFromSlot();
5607330f729Sjoerg CGF.EmitRuntimeCall(getUnexpectedFn(CGF.CGM), exn)
5617330f729Sjoerg ->setDoesNotReturn();
5627330f729Sjoerg CGF.Builder.CreateUnreachable();
5637330f729Sjoerg }
5647330f729Sjoerg
EmitEndEHSpec(const Decl * D)5657330f729Sjoerg void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
5667330f729Sjoerg if (!CGM.getLangOpts().CXXExceptions)
5677330f729Sjoerg return;
5687330f729Sjoerg
5697330f729Sjoerg const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
5707330f729Sjoerg if (!FD) {
5717330f729Sjoerg // Check if CapturedDecl is nothrow and pop terminate scope for it.
5727330f729Sjoerg if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
573*e038c9c4Sjoerg if (CD->isNothrow() && !EHStack.empty())
5747330f729Sjoerg EHStack.popTerminate();
5757330f729Sjoerg }
5767330f729Sjoerg return;
5777330f729Sjoerg }
5787330f729Sjoerg const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
5797330f729Sjoerg if (!Proto)
5807330f729Sjoerg return;
5817330f729Sjoerg
5827330f729Sjoerg ExceptionSpecificationType EST = Proto->getExceptionSpecType();
583*e038c9c4Sjoerg if (isNoexceptExceptionSpec(EST) && Proto->canThrow() == CT_Cannot &&
584*e038c9c4Sjoerg !EHStack.empty() /* possible empty when under async exceptions */) {
5857330f729Sjoerg EHStack.popTerminate();
5867330f729Sjoerg } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
5877330f729Sjoerg // TODO: Revisit exception specifications for the MS ABI. There is a way to
5887330f729Sjoerg // encode these in an object file but MSVC doesn't do anything with it.
5897330f729Sjoerg if (getTarget().getCXXABI().isMicrosoft())
5907330f729Sjoerg return;
591*e038c9c4Sjoerg // In wasm we currently treat 'throw()' in the same way as 'noexcept'. In
592*e038c9c4Sjoerg // case of throw with types, we ignore it and print a warning for now.
593*e038c9c4Sjoerg // TODO Correctly handle exception specification in wasm
594*e038c9c4Sjoerg if (CGM.getLangOpts().hasWasmExceptions()) {
595*e038c9c4Sjoerg if (EST == EST_DynamicNone)
596*e038c9c4Sjoerg EHStack.popTerminate();
597*e038c9c4Sjoerg return;
598*e038c9c4Sjoerg }
5997330f729Sjoerg EHFilterScope &filterScope = cast<EHFilterScope>(*EHStack.begin());
6007330f729Sjoerg emitFilterDispatchBlock(*this, filterScope);
6017330f729Sjoerg EHStack.popFilter();
6027330f729Sjoerg }
6037330f729Sjoerg }
6047330f729Sjoerg
EmitCXXTryStmt(const CXXTryStmt & S)6057330f729Sjoerg void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
6067330f729Sjoerg EnterCXXTryStmt(S);
6077330f729Sjoerg EmitStmt(S.getTryBlock());
6087330f729Sjoerg ExitCXXTryStmt(S);
6097330f729Sjoerg }
6107330f729Sjoerg
EnterCXXTryStmt(const CXXTryStmt & S,bool IsFnTryBlock)6117330f729Sjoerg void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
6127330f729Sjoerg unsigned NumHandlers = S.getNumHandlers();
6137330f729Sjoerg EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
6147330f729Sjoerg
6157330f729Sjoerg for (unsigned I = 0; I != NumHandlers; ++I) {
6167330f729Sjoerg const CXXCatchStmt *C = S.getHandler(I);
6177330f729Sjoerg
6187330f729Sjoerg llvm::BasicBlock *Handler = createBasicBlock("catch");
6197330f729Sjoerg if (C->getExceptionDecl()) {
6207330f729Sjoerg // FIXME: Dropping the reference type on the type into makes it
6217330f729Sjoerg // impossible to correctly implement catch-by-reference
6227330f729Sjoerg // semantics for pointers. Unfortunately, this is what all
6237330f729Sjoerg // existing compilers do, and it's not clear that the standard
6247330f729Sjoerg // personality routine is capable of doing this right. See C++ DR 388:
6257330f729Sjoerg // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
6267330f729Sjoerg Qualifiers CaughtTypeQuals;
6277330f729Sjoerg QualType CaughtType = CGM.getContext().getUnqualifiedArrayType(
6287330f729Sjoerg C->getCaughtType().getNonReferenceType(), CaughtTypeQuals);
6297330f729Sjoerg
6307330f729Sjoerg CatchTypeInfo TypeInfo{nullptr, 0};
6317330f729Sjoerg if (CaughtType->isObjCObjectPointerType())
6327330f729Sjoerg TypeInfo.RTTI = CGM.getObjCRuntime().GetEHType(CaughtType);
6337330f729Sjoerg else
6347330f729Sjoerg TypeInfo = CGM.getCXXABI().getAddrOfCXXCatchHandlerType(
6357330f729Sjoerg CaughtType, C->getCaughtType());
6367330f729Sjoerg CatchScope->setHandler(I, TypeInfo, Handler);
6377330f729Sjoerg } else {
6387330f729Sjoerg // No exception decl indicates '...', a catch-all.
6397330f729Sjoerg CatchScope->setHandler(I, CGM.getCXXABI().getCatchAllTypeInfo(), Handler);
640*e038c9c4Sjoerg // Under async exceptions, catch(...) need to catch HW exception too
641*e038c9c4Sjoerg // Mark scope with SehTryBegin as a SEH __try scope
642*e038c9c4Sjoerg if (getLangOpts().EHAsynch)
643*e038c9c4Sjoerg EmitRuntimeCallOrInvoke(getSehTryBeginFn(CGM));
6447330f729Sjoerg }
6457330f729Sjoerg }
6467330f729Sjoerg }
6477330f729Sjoerg
6487330f729Sjoerg llvm::BasicBlock *
getEHDispatchBlock(EHScopeStack::stable_iterator si)6497330f729Sjoerg CodeGenFunction::getEHDispatchBlock(EHScopeStack::stable_iterator si) {
6507330f729Sjoerg if (EHPersonality::get(*this).usesFuncletPads())
6517330f729Sjoerg return getFuncletEHDispatchBlock(si);
6527330f729Sjoerg
6537330f729Sjoerg // The dispatch block for the end of the scope chain is a block that
6547330f729Sjoerg // just resumes unwinding.
6557330f729Sjoerg if (si == EHStack.stable_end())
6567330f729Sjoerg return getEHResumeBlock(true);
6577330f729Sjoerg
6587330f729Sjoerg // Otherwise, we should look at the actual scope.
6597330f729Sjoerg EHScope &scope = *EHStack.find(si);
6607330f729Sjoerg
6617330f729Sjoerg llvm::BasicBlock *dispatchBlock = scope.getCachedEHDispatchBlock();
6627330f729Sjoerg if (!dispatchBlock) {
6637330f729Sjoerg switch (scope.getKind()) {
6647330f729Sjoerg case EHScope::Catch: {
6657330f729Sjoerg // Apply a special case to a single catch-all.
6667330f729Sjoerg EHCatchScope &catchScope = cast<EHCatchScope>(scope);
6677330f729Sjoerg if (catchScope.getNumHandlers() == 1 &&
6687330f729Sjoerg catchScope.getHandler(0).isCatchAll()) {
6697330f729Sjoerg dispatchBlock = catchScope.getHandler(0).Block;
6707330f729Sjoerg
6717330f729Sjoerg // Otherwise, make a dispatch block.
6727330f729Sjoerg } else {
6737330f729Sjoerg dispatchBlock = createBasicBlock("catch.dispatch");
6747330f729Sjoerg }
6757330f729Sjoerg break;
6767330f729Sjoerg }
6777330f729Sjoerg
6787330f729Sjoerg case EHScope::Cleanup:
6797330f729Sjoerg dispatchBlock = createBasicBlock("ehcleanup");
6807330f729Sjoerg break;
6817330f729Sjoerg
6827330f729Sjoerg case EHScope::Filter:
6837330f729Sjoerg dispatchBlock = createBasicBlock("filter.dispatch");
6847330f729Sjoerg break;
6857330f729Sjoerg
6867330f729Sjoerg case EHScope::Terminate:
6877330f729Sjoerg dispatchBlock = getTerminateHandler();
6887330f729Sjoerg break;
6897330f729Sjoerg }
6907330f729Sjoerg scope.setCachedEHDispatchBlock(dispatchBlock);
6917330f729Sjoerg }
6927330f729Sjoerg return dispatchBlock;
6937330f729Sjoerg }
6947330f729Sjoerg
6957330f729Sjoerg llvm::BasicBlock *
getFuncletEHDispatchBlock(EHScopeStack::stable_iterator SI)6967330f729Sjoerg CodeGenFunction::getFuncletEHDispatchBlock(EHScopeStack::stable_iterator SI) {
6977330f729Sjoerg // Returning nullptr indicates that the previous dispatch block should unwind
6987330f729Sjoerg // to caller.
6997330f729Sjoerg if (SI == EHStack.stable_end())
7007330f729Sjoerg return nullptr;
7017330f729Sjoerg
7027330f729Sjoerg // Otherwise, we should look at the actual scope.
7037330f729Sjoerg EHScope &EHS = *EHStack.find(SI);
7047330f729Sjoerg
7057330f729Sjoerg llvm::BasicBlock *DispatchBlock = EHS.getCachedEHDispatchBlock();
7067330f729Sjoerg if (DispatchBlock)
7077330f729Sjoerg return DispatchBlock;
7087330f729Sjoerg
7097330f729Sjoerg if (EHS.getKind() == EHScope::Terminate)
7107330f729Sjoerg DispatchBlock = getTerminateFunclet();
7117330f729Sjoerg else
7127330f729Sjoerg DispatchBlock = createBasicBlock();
7137330f729Sjoerg CGBuilderTy Builder(*this, DispatchBlock);
7147330f729Sjoerg
7157330f729Sjoerg switch (EHS.getKind()) {
7167330f729Sjoerg case EHScope::Catch:
7177330f729Sjoerg DispatchBlock->setName("catch.dispatch");
7187330f729Sjoerg break;
7197330f729Sjoerg
7207330f729Sjoerg case EHScope::Cleanup:
7217330f729Sjoerg DispatchBlock->setName("ehcleanup");
7227330f729Sjoerg break;
7237330f729Sjoerg
7247330f729Sjoerg case EHScope::Filter:
7257330f729Sjoerg llvm_unreachable("exception specifications not handled yet!");
7267330f729Sjoerg
7277330f729Sjoerg case EHScope::Terminate:
7287330f729Sjoerg DispatchBlock->setName("terminate");
7297330f729Sjoerg break;
7307330f729Sjoerg }
7317330f729Sjoerg EHS.setCachedEHDispatchBlock(DispatchBlock);
7327330f729Sjoerg return DispatchBlock;
7337330f729Sjoerg }
7347330f729Sjoerg
7357330f729Sjoerg /// Check whether this is a non-EH scope, i.e. a scope which doesn't
7367330f729Sjoerg /// affect exception handling. Currently, the only non-EH scopes are
7377330f729Sjoerg /// normal-only cleanup scopes.
isNonEHScope(const EHScope & S)7387330f729Sjoerg static bool isNonEHScope(const EHScope &S) {
7397330f729Sjoerg switch (S.getKind()) {
7407330f729Sjoerg case EHScope::Cleanup:
7417330f729Sjoerg return !cast<EHCleanupScope>(S).isEHCleanup();
7427330f729Sjoerg case EHScope::Filter:
7437330f729Sjoerg case EHScope::Catch:
7447330f729Sjoerg case EHScope::Terminate:
7457330f729Sjoerg return false;
7467330f729Sjoerg }
7477330f729Sjoerg
7487330f729Sjoerg llvm_unreachable("Invalid EHScope Kind!");
7497330f729Sjoerg }
7507330f729Sjoerg
getInvokeDestImpl()7517330f729Sjoerg llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
7527330f729Sjoerg assert(EHStack.requiresLandingPad());
7537330f729Sjoerg assert(!EHStack.empty());
7547330f729Sjoerg
755*e038c9c4Sjoerg // If exceptions are disabled/ignored and SEH is not in use, then there is no
756*e038c9c4Sjoerg // invoke destination. SEH "works" even if exceptions are off. In practice,
757*e038c9c4Sjoerg // this means that C++ destructors and other EH cleanups don't run, which is
758*e038c9c4Sjoerg // consistent with MSVC's behavior, except in the presence of -EHa
7597330f729Sjoerg const LangOptions &LO = CGM.getLangOpts();
760*e038c9c4Sjoerg if (!LO.Exceptions || LO.IgnoreExceptions) {
7617330f729Sjoerg if (!LO.Borland && !LO.MicrosoftExt)
7627330f729Sjoerg return nullptr;
7637330f729Sjoerg if (!currentFunctionUsesSEHTry())
7647330f729Sjoerg return nullptr;
7657330f729Sjoerg }
7667330f729Sjoerg
7677330f729Sjoerg // CUDA device code doesn't have exceptions.
7687330f729Sjoerg if (LO.CUDA && LO.CUDAIsDevice)
7697330f729Sjoerg return nullptr;
7707330f729Sjoerg
7717330f729Sjoerg // Check the innermost scope for a cached landing pad. If this is
7727330f729Sjoerg // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
7737330f729Sjoerg llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
7747330f729Sjoerg if (LP) return LP;
7757330f729Sjoerg
7767330f729Sjoerg const EHPersonality &Personality = EHPersonality::get(*this);
7777330f729Sjoerg
7787330f729Sjoerg if (!CurFn->hasPersonalityFn())
7797330f729Sjoerg CurFn->setPersonalityFn(getOpaquePersonalityFn(CGM, Personality));
7807330f729Sjoerg
7817330f729Sjoerg if (Personality.usesFuncletPads()) {
7827330f729Sjoerg // We don't need separate landing pads in the funclet model.
7837330f729Sjoerg LP = getEHDispatchBlock(EHStack.getInnermostEHScope());
7847330f729Sjoerg } else {
7857330f729Sjoerg // Build the landing pad for this scope.
7867330f729Sjoerg LP = EmitLandingPad();
7877330f729Sjoerg }
7887330f729Sjoerg
7897330f729Sjoerg assert(LP);
7907330f729Sjoerg
7917330f729Sjoerg // Cache the landing pad on the innermost scope. If this is a
7927330f729Sjoerg // non-EH scope, cache the landing pad on the enclosing scope, too.
7937330f729Sjoerg for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
7947330f729Sjoerg ir->setCachedLandingPad(LP);
7957330f729Sjoerg if (!isNonEHScope(*ir)) break;
7967330f729Sjoerg }
7977330f729Sjoerg
7987330f729Sjoerg return LP;
7997330f729Sjoerg }
8007330f729Sjoerg
EmitLandingPad()8017330f729Sjoerg llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
8027330f729Sjoerg assert(EHStack.requiresLandingPad());
803*e038c9c4Sjoerg assert(!CGM.getLangOpts().IgnoreExceptions &&
804*e038c9c4Sjoerg "LandingPad should not be emitted when -fignore-exceptions are in "
805*e038c9c4Sjoerg "effect.");
8067330f729Sjoerg EHScope &innermostEHScope = *EHStack.find(EHStack.getInnermostEHScope());
8077330f729Sjoerg switch (innermostEHScope.getKind()) {
8087330f729Sjoerg case EHScope::Terminate:
8097330f729Sjoerg return getTerminateLandingPad();
8107330f729Sjoerg
8117330f729Sjoerg case EHScope::Catch:
8127330f729Sjoerg case EHScope::Cleanup:
8137330f729Sjoerg case EHScope::Filter:
8147330f729Sjoerg if (llvm::BasicBlock *lpad = innermostEHScope.getCachedLandingPad())
8157330f729Sjoerg return lpad;
8167330f729Sjoerg }
8177330f729Sjoerg
8187330f729Sjoerg // Save the current IR generation state.
8197330f729Sjoerg CGBuilderTy::InsertPoint savedIP = Builder.saveAndClearIP();
8207330f729Sjoerg auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, CurEHLocation);
8217330f729Sjoerg
8227330f729Sjoerg // Create and configure the landing pad.
8237330f729Sjoerg llvm::BasicBlock *lpad = createBasicBlock("lpad");
8247330f729Sjoerg EmitBlock(lpad);
8257330f729Sjoerg
8267330f729Sjoerg llvm::LandingPadInst *LPadInst =
8277330f729Sjoerg Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty), 0);
8287330f729Sjoerg
8297330f729Sjoerg llvm::Value *LPadExn = Builder.CreateExtractValue(LPadInst, 0);
8307330f729Sjoerg Builder.CreateStore(LPadExn, getExceptionSlot());
8317330f729Sjoerg llvm::Value *LPadSel = Builder.CreateExtractValue(LPadInst, 1);
8327330f729Sjoerg Builder.CreateStore(LPadSel, getEHSelectorSlot());
8337330f729Sjoerg
8347330f729Sjoerg // Save the exception pointer. It's safe to use a single exception
8357330f729Sjoerg // pointer per function because EH cleanups can never have nested
8367330f729Sjoerg // try/catches.
8377330f729Sjoerg // Build the landingpad instruction.
8387330f729Sjoerg
8397330f729Sjoerg // Accumulate all the handlers in scope.
8407330f729Sjoerg bool hasCatchAll = false;
8417330f729Sjoerg bool hasCleanup = false;
8427330f729Sjoerg bool hasFilter = false;
8437330f729Sjoerg SmallVector<llvm::Value*, 4> filterTypes;
8447330f729Sjoerg llvm::SmallPtrSet<llvm::Value*, 4> catchTypes;
8457330f729Sjoerg for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end(); I != E;
8467330f729Sjoerg ++I) {
8477330f729Sjoerg
8487330f729Sjoerg switch (I->getKind()) {
8497330f729Sjoerg case EHScope::Cleanup:
8507330f729Sjoerg // If we have a cleanup, remember that.
8517330f729Sjoerg hasCleanup = (hasCleanup || cast<EHCleanupScope>(*I).isEHCleanup());
8527330f729Sjoerg continue;
8537330f729Sjoerg
8547330f729Sjoerg case EHScope::Filter: {
8557330f729Sjoerg assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
8567330f729Sjoerg assert(!hasCatchAll && "EH filter reached after catch-all");
8577330f729Sjoerg
8587330f729Sjoerg // Filter scopes get added to the landingpad in weird ways.
8597330f729Sjoerg EHFilterScope &filter = cast<EHFilterScope>(*I);
8607330f729Sjoerg hasFilter = true;
8617330f729Sjoerg
8627330f729Sjoerg // Add all the filter values.
8637330f729Sjoerg for (unsigned i = 0, e = filter.getNumFilters(); i != e; ++i)
8647330f729Sjoerg filterTypes.push_back(filter.getFilter(i));
8657330f729Sjoerg goto done;
8667330f729Sjoerg }
8677330f729Sjoerg
8687330f729Sjoerg case EHScope::Terminate:
8697330f729Sjoerg // Terminate scopes are basically catch-alls.
8707330f729Sjoerg assert(!hasCatchAll);
8717330f729Sjoerg hasCatchAll = true;
8727330f729Sjoerg goto done;
8737330f729Sjoerg
8747330f729Sjoerg case EHScope::Catch:
8757330f729Sjoerg break;
8767330f729Sjoerg }
8777330f729Sjoerg
8787330f729Sjoerg EHCatchScope &catchScope = cast<EHCatchScope>(*I);
8797330f729Sjoerg for (unsigned hi = 0, he = catchScope.getNumHandlers(); hi != he; ++hi) {
8807330f729Sjoerg EHCatchScope::Handler handler = catchScope.getHandler(hi);
8817330f729Sjoerg assert(handler.Type.Flags == 0 &&
8827330f729Sjoerg "landingpads do not support catch handler flags");
8837330f729Sjoerg
8847330f729Sjoerg // If this is a catch-all, register that and abort.
8857330f729Sjoerg if (!handler.Type.RTTI) {
8867330f729Sjoerg assert(!hasCatchAll);
8877330f729Sjoerg hasCatchAll = true;
8887330f729Sjoerg goto done;
8897330f729Sjoerg }
8907330f729Sjoerg
8917330f729Sjoerg // Check whether we already have a handler for this type.
8927330f729Sjoerg if (catchTypes.insert(handler.Type.RTTI).second)
8937330f729Sjoerg // If not, add it directly to the landingpad.
8947330f729Sjoerg LPadInst->addClause(handler.Type.RTTI);
8957330f729Sjoerg }
8967330f729Sjoerg }
8977330f729Sjoerg
8987330f729Sjoerg done:
8997330f729Sjoerg // If we have a catch-all, add null to the landingpad.
9007330f729Sjoerg assert(!(hasCatchAll && hasFilter));
9017330f729Sjoerg if (hasCatchAll) {
9027330f729Sjoerg LPadInst->addClause(getCatchAllValue(*this));
9037330f729Sjoerg
9047330f729Sjoerg // If we have an EH filter, we need to add those handlers in the
9057330f729Sjoerg // right place in the landingpad, which is to say, at the end.
9067330f729Sjoerg } else if (hasFilter) {
9077330f729Sjoerg // Create a filter expression: a constant array indicating which filter
9087330f729Sjoerg // types there are. The personality routine only lands here if the filter
9097330f729Sjoerg // doesn't match.
9107330f729Sjoerg SmallVector<llvm::Constant*, 8> Filters;
9117330f729Sjoerg llvm::ArrayType *AType =
9127330f729Sjoerg llvm::ArrayType::get(!filterTypes.empty() ?
9137330f729Sjoerg filterTypes[0]->getType() : Int8PtrTy,
9147330f729Sjoerg filterTypes.size());
9157330f729Sjoerg
9167330f729Sjoerg for (unsigned i = 0, e = filterTypes.size(); i != e; ++i)
9177330f729Sjoerg Filters.push_back(cast<llvm::Constant>(filterTypes[i]));
9187330f729Sjoerg llvm::Constant *FilterArray = llvm::ConstantArray::get(AType, Filters);
9197330f729Sjoerg LPadInst->addClause(FilterArray);
9207330f729Sjoerg
9217330f729Sjoerg // Also check whether we need a cleanup.
9227330f729Sjoerg if (hasCleanup)
9237330f729Sjoerg LPadInst->setCleanup(true);
9247330f729Sjoerg
9257330f729Sjoerg // Otherwise, signal that we at least have cleanups.
9267330f729Sjoerg } else if (hasCleanup) {
9277330f729Sjoerg LPadInst->setCleanup(true);
9287330f729Sjoerg }
9297330f729Sjoerg
9307330f729Sjoerg assert((LPadInst->getNumClauses() > 0 || LPadInst->isCleanup()) &&
9317330f729Sjoerg "landingpad instruction has no clauses!");
9327330f729Sjoerg
9337330f729Sjoerg // Tell the backend how to generate the landing pad.
9347330f729Sjoerg Builder.CreateBr(getEHDispatchBlock(EHStack.getInnermostEHScope()));
9357330f729Sjoerg
9367330f729Sjoerg // Restore the old IR generation state.
9377330f729Sjoerg Builder.restoreIP(savedIP);
9387330f729Sjoerg
9397330f729Sjoerg return lpad;
9407330f729Sjoerg }
9417330f729Sjoerg
emitCatchPadBlock(CodeGenFunction & CGF,EHCatchScope & CatchScope)9427330f729Sjoerg static void emitCatchPadBlock(CodeGenFunction &CGF, EHCatchScope &CatchScope) {
9437330f729Sjoerg llvm::BasicBlock *DispatchBlock = CatchScope.getCachedEHDispatchBlock();
9447330f729Sjoerg assert(DispatchBlock);
9457330f729Sjoerg
9467330f729Sjoerg CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveIP();
9477330f729Sjoerg CGF.EmitBlockAfterUses(DispatchBlock);
9487330f729Sjoerg
9497330f729Sjoerg llvm::Value *ParentPad = CGF.CurrentFuncletPad;
9507330f729Sjoerg if (!ParentPad)
9517330f729Sjoerg ParentPad = llvm::ConstantTokenNone::get(CGF.getLLVMContext());
9527330f729Sjoerg llvm::BasicBlock *UnwindBB =
9537330f729Sjoerg CGF.getEHDispatchBlock(CatchScope.getEnclosingEHScope());
9547330f729Sjoerg
9557330f729Sjoerg unsigned NumHandlers = CatchScope.getNumHandlers();
9567330f729Sjoerg llvm::CatchSwitchInst *CatchSwitch =
9577330f729Sjoerg CGF.Builder.CreateCatchSwitch(ParentPad, UnwindBB, NumHandlers);
9587330f729Sjoerg
9597330f729Sjoerg // Test against each of the exception types we claim to catch.
9607330f729Sjoerg for (unsigned I = 0; I < NumHandlers; ++I) {
9617330f729Sjoerg const EHCatchScope::Handler &Handler = CatchScope.getHandler(I);
9627330f729Sjoerg
9637330f729Sjoerg CatchTypeInfo TypeInfo = Handler.Type;
9647330f729Sjoerg if (!TypeInfo.RTTI)
9657330f729Sjoerg TypeInfo.RTTI = llvm::Constant::getNullValue(CGF.VoidPtrTy);
9667330f729Sjoerg
9677330f729Sjoerg CGF.Builder.SetInsertPoint(Handler.Block);
9687330f729Sjoerg
9697330f729Sjoerg if (EHPersonality::get(CGF).isMSVCXXPersonality()) {
9707330f729Sjoerg CGF.Builder.CreateCatchPad(
9717330f729Sjoerg CatchSwitch, {TypeInfo.RTTI, CGF.Builder.getInt32(TypeInfo.Flags),
9727330f729Sjoerg llvm::Constant::getNullValue(CGF.VoidPtrTy)});
9737330f729Sjoerg } else {
9747330f729Sjoerg CGF.Builder.CreateCatchPad(CatchSwitch, {TypeInfo.RTTI});
9757330f729Sjoerg }
9767330f729Sjoerg
9777330f729Sjoerg CatchSwitch->addHandler(Handler.Block);
9787330f729Sjoerg }
9797330f729Sjoerg CGF.Builder.restoreIP(SavedIP);
9807330f729Sjoerg }
9817330f729Sjoerg
9827330f729Sjoerg // Wasm uses Windows-style EH instructions, but it merges all catch clauses into
9837330f729Sjoerg // one big catchpad, within which we use Itanium's landingpad-style selector
9847330f729Sjoerg // comparison instructions.
emitWasmCatchPadBlock(CodeGenFunction & CGF,EHCatchScope & CatchScope)9857330f729Sjoerg static void emitWasmCatchPadBlock(CodeGenFunction &CGF,
9867330f729Sjoerg EHCatchScope &CatchScope) {
9877330f729Sjoerg llvm::BasicBlock *DispatchBlock = CatchScope.getCachedEHDispatchBlock();
9887330f729Sjoerg assert(DispatchBlock);
9897330f729Sjoerg
9907330f729Sjoerg CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveIP();
9917330f729Sjoerg CGF.EmitBlockAfterUses(DispatchBlock);
9927330f729Sjoerg
9937330f729Sjoerg llvm::Value *ParentPad = CGF.CurrentFuncletPad;
9947330f729Sjoerg if (!ParentPad)
9957330f729Sjoerg ParentPad = llvm::ConstantTokenNone::get(CGF.getLLVMContext());
9967330f729Sjoerg llvm::BasicBlock *UnwindBB =
9977330f729Sjoerg CGF.getEHDispatchBlock(CatchScope.getEnclosingEHScope());
9987330f729Sjoerg
9997330f729Sjoerg unsigned NumHandlers = CatchScope.getNumHandlers();
10007330f729Sjoerg llvm::CatchSwitchInst *CatchSwitch =
10017330f729Sjoerg CGF.Builder.CreateCatchSwitch(ParentPad, UnwindBB, NumHandlers);
10027330f729Sjoerg
10037330f729Sjoerg // We don't use a landingpad instruction, so generate intrinsic calls to
10047330f729Sjoerg // provide exception and selector values.
10057330f729Sjoerg llvm::BasicBlock *WasmCatchStartBlock = CGF.createBasicBlock("catch.start");
10067330f729Sjoerg CatchSwitch->addHandler(WasmCatchStartBlock);
10077330f729Sjoerg CGF.EmitBlockAfterUses(WasmCatchStartBlock);
10087330f729Sjoerg
10097330f729Sjoerg // Create a catchpad instruction.
10107330f729Sjoerg SmallVector<llvm::Value *, 4> CatchTypes;
10117330f729Sjoerg for (unsigned I = 0, E = NumHandlers; I < E; ++I) {
10127330f729Sjoerg const EHCatchScope::Handler &Handler = CatchScope.getHandler(I);
10137330f729Sjoerg CatchTypeInfo TypeInfo = Handler.Type;
10147330f729Sjoerg if (!TypeInfo.RTTI)
10157330f729Sjoerg TypeInfo.RTTI = llvm::Constant::getNullValue(CGF.VoidPtrTy);
10167330f729Sjoerg CatchTypes.push_back(TypeInfo.RTTI);
10177330f729Sjoerg }
10187330f729Sjoerg auto *CPI = CGF.Builder.CreateCatchPad(CatchSwitch, CatchTypes);
10197330f729Sjoerg
10207330f729Sjoerg // Create calls to wasm.get.exception and wasm.get.ehselector intrinsics.
10217330f729Sjoerg // Before they are lowered appropriately later, they provide values for the
10227330f729Sjoerg // exception and selector.
10237330f729Sjoerg llvm::Function *GetExnFn =
10247330f729Sjoerg CGF.CGM.getIntrinsic(llvm::Intrinsic::wasm_get_exception);
10257330f729Sjoerg llvm::Function *GetSelectorFn =
10267330f729Sjoerg CGF.CGM.getIntrinsic(llvm::Intrinsic::wasm_get_ehselector);
10277330f729Sjoerg llvm::CallInst *Exn = CGF.Builder.CreateCall(GetExnFn, CPI);
10287330f729Sjoerg CGF.Builder.CreateStore(Exn, CGF.getExceptionSlot());
10297330f729Sjoerg llvm::CallInst *Selector = CGF.Builder.CreateCall(GetSelectorFn, CPI);
10307330f729Sjoerg
10317330f729Sjoerg llvm::Function *TypeIDFn = CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
10327330f729Sjoerg
10337330f729Sjoerg // If there's only a single catch-all, branch directly to its handler.
10347330f729Sjoerg if (CatchScope.getNumHandlers() == 1 &&
10357330f729Sjoerg CatchScope.getHandler(0).isCatchAll()) {
10367330f729Sjoerg CGF.Builder.CreateBr(CatchScope.getHandler(0).Block);
10377330f729Sjoerg CGF.Builder.restoreIP(SavedIP);
10387330f729Sjoerg return;
10397330f729Sjoerg }
10407330f729Sjoerg
10417330f729Sjoerg // Test against each of the exception types we claim to catch.
10427330f729Sjoerg for (unsigned I = 0, E = NumHandlers;; ++I) {
10437330f729Sjoerg assert(I < E && "ran off end of handlers!");
10447330f729Sjoerg const EHCatchScope::Handler &Handler = CatchScope.getHandler(I);
10457330f729Sjoerg CatchTypeInfo TypeInfo = Handler.Type;
10467330f729Sjoerg if (!TypeInfo.RTTI)
10477330f729Sjoerg TypeInfo.RTTI = llvm::Constant::getNullValue(CGF.VoidPtrTy);
10487330f729Sjoerg
10497330f729Sjoerg // Figure out the next block.
10507330f729Sjoerg llvm::BasicBlock *NextBlock;
10517330f729Sjoerg
10527330f729Sjoerg bool EmitNextBlock = false, NextIsEnd = false;
10537330f729Sjoerg
10547330f729Sjoerg // If this is the last handler, we're at the end, and the next block is a
10557330f729Sjoerg // block that contains a call to the rethrow function, so we can unwind to
10567330f729Sjoerg // the enclosing EH scope. The call itself will be generated later.
10577330f729Sjoerg if (I + 1 == E) {
10587330f729Sjoerg NextBlock = CGF.createBasicBlock("rethrow");
10597330f729Sjoerg EmitNextBlock = true;
10607330f729Sjoerg NextIsEnd = true;
10617330f729Sjoerg
10627330f729Sjoerg // If the next handler is a catch-all, we're at the end, and the
10637330f729Sjoerg // next block is that handler.
10647330f729Sjoerg } else if (CatchScope.getHandler(I + 1).isCatchAll()) {
10657330f729Sjoerg NextBlock = CatchScope.getHandler(I + 1).Block;
10667330f729Sjoerg NextIsEnd = true;
10677330f729Sjoerg
10687330f729Sjoerg // Otherwise, we're not at the end and we need a new block.
10697330f729Sjoerg } else {
10707330f729Sjoerg NextBlock = CGF.createBasicBlock("catch.fallthrough");
10717330f729Sjoerg EmitNextBlock = true;
10727330f729Sjoerg }
10737330f729Sjoerg
10747330f729Sjoerg // Figure out the catch type's index in the LSDA's type table.
10757330f729Sjoerg llvm::CallInst *TypeIndex = CGF.Builder.CreateCall(TypeIDFn, TypeInfo.RTTI);
10767330f729Sjoerg TypeIndex->setDoesNotThrow();
10777330f729Sjoerg
10787330f729Sjoerg llvm::Value *MatchesTypeIndex =
10797330f729Sjoerg CGF.Builder.CreateICmpEQ(Selector, TypeIndex, "matches");
10807330f729Sjoerg CGF.Builder.CreateCondBr(MatchesTypeIndex, Handler.Block, NextBlock);
10817330f729Sjoerg
10827330f729Sjoerg if (EmitNextBlock)
10837330f729Sjoerg CGF.EmitBlock(NextBlock);
10847330f729Sjoerg if (NextIsEnd)
10857330f729Sjoerg break;
10867330f729Sjoerg }
10877330f729Sjoerg
10887330f729Sjoerg CGF.Builder.restoreIP(SavedIP);
10897330f729Sjoerg }
10907330f729Sjoerg
10917330f729Sjoerg /// Emit the structure of the dispatch block for the given catch scope.
10927330f729Sjoerg /// It is an invariant that the dispatch block already exists.
emitCatchDispatchBlock(CodeGenFunction & CGF,EHCatchScope & catchScope)10937330f729Sjoerg static void emitCatchDispatchBlock(CodeGenFunction &CGF,
10947330f729Sjoerg EHCatchScope &catchScope) {
10957330f729Sjoerg if (EHPersonality::get(CGF).isWasmPersonality())
10967330f729Sjoerg return emitWasmCatchPadBlock(CGF, catchScope);
10977330f729Sjoerg if (EHPersonality::get(CGF).usesFuncletPads())
10987330f729Sjoerg return emitCatchPadBlock(CGF, catchScope);
10997330f729Sjoerg
11007330f729Sjoerg llvm::BasicBlock *dispatchBlock = catchScope.getCachedEHDispatchBlock();
11017330f729Sjoerg assert(dispatchBlock);
11027330f729Sjoerg
11037330f729Sjoerg // If there's only a single catch-all, getEHDispatchBlock returned
11047330f729Sjoerg // that catch-all as the dispatch block.
11057330f729Sjoerg if (catchScope.getNumHandlers() == 1 &&
11067330f729Sjoerg catchScope.getHandler(0).isCatchAll()) {
11077330f729Sjoerg assert(dispatchBlock == catchScope.getHandler(0).Block);
11087330f729Sjoerg return;
11097330f729Sjoerg }
11107330f729Sjoerg
11117330f729Sjoerg CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveIP();
11127330f729Sjoerg CGF.EmitBlockAfterUses(dispatchBlock);
11137330f729Sjoerg
11147330f729Sjoerg // Select the right handler.
11157330f729Sjoerg llvm::Function *llvm_eh_typeid_for =
11167330f729Sjoerg CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
11177330f729Sjoerg
11187330f729Sjoerg // Load the selector value.
11197330f729Sjoerg llvm::Value *selector = CGF.getSelectorFromSlot();
11207330f729Sjoerg
11217330f729Sjoerg // Test against each of the exception types we claim to catch.
11227330f729Sjoerg for (unsigned i = 0, e = catchScope.getNumHandlers(); ; ++i) {
11237330f729Sjoerg assert(i < e && "ran off end of handlers!");
11247330f729Sjoerg const EHCatchScope::Handler &handler = catchScope.getHandler(i);
11257330f729Sjoerg
11267330f729Sjoerg llvm::Value *typeValue = handler.Type.RTTI;
11277330f729Sjoerg assert(handler.Type.Flags == 0 &&
11287330f729Sjoerg "landingpads do not support catch handler flags");
11297330f729Sjoerg assert(typeValue && "fell into catch-all case!");
11307330f729Sjoerg typeValue = CGF.Builder.CreateBitCast(typeValue, CGF.Int8PtrTy);
11317330f729Sjoerg
11327330f729Sjoerg // Figure out the next block.
11337330f729Sjoerg bool nextIsEnd;
11347330f729Sjoerg llvm::BasicBlock *nextBlock;
11357330f729Sjoerg
11367330f729Sjoerg // If this is the last handler, we're at the end, and the next
11377330f729Sjoerg // block is the block for the enclosing EH scope.
11387330f729Sjoerg if (i + 1 == e) {
11397330f729Sjoerg nextBlock = CGF.getEHDispatchBlock(catchScope.getEnclosingEHScope());
11407330f729Sjoerg nextIsEnd = true;
11417330f729Sjoerg
11427330f729Sjoerg // If the next handler is a catch-all, we're at the end, and the
11437330f729Sjoerg // next block is that handler.
11447330f729Sjoerg } else if (catchScope.getHandler(i+1).isCatchAll()) {
11457330f729Sjoerg nextBlock = catchScope.getHandler(i+1).Block;
11467330f729Sjoerg nextIsEnd = true;
11477330f729Sjoerg
11487330f729Sjoerg // Otherwise, we're not at the end and we need a new block.
11497330f729Sjoerg } else {
11507330f729Sjoerg nextBlock = CGF.createBasicBlock("catch.fallthrough");
11517330f729Sjoerg nextIsEnd = false;
11527330f729Sjoerg }
11537330f729Sjoerg
11547330f729Sjoerg // Figure out the catch type's index in the LSDA's type table.
11557330f729Sjoerg llvm::CallInst *typeIndex =
11567330f729Sjoerg CGF.Builder.CreateCall(llvm_eh_typeid_for, typeValue);
11577330f729Sjoerg typeIndex->setDoesNotThrow();
11587330f729Sjoerg
11597330f729Sjoerg llvm::Value *matchesTypeIndex =
11607330f729Sjoerg CGF.Builder.CreateICmpEQ(selector, typeIndex, "matches");
11617330f729Sjoerg CGF.Builder.CreateCondBr(matchesTypeIndex, handler.Block, nextBlock);
11627330f729Sjoerg
11637330f729Sjoerg // If the next handler is a catch-all, we're completely done.
11647330f729Sjoerg if (nextIsEnd) {
11657330f729Sjoerg CGF.Builder.restoreIP(savedIP);
11667330f729Sjoerg return;
11677330f729Sjoerg }
11687330f729Sjoerg // Otherwise we need to emit and continue at that block.
11697330f729Sjoerg CGF.EmitBlock(nextBlock);
11707330f729Sjoerg }
11717330f729Sjoerg }
11727330f729Sjoerg
popCatchScope()11737330f729Sjoerg void CodeGenFunction::popCatchScope() {
11747330f729Sjoerg EHCatchScope &catchScope = cast<EHCatchScope>(*EHStack.begin());
11757330f729Sjoerg if (catchScope.hasEHBranches())
11767330f729Sjoerg emitCatchDispatchBlock(*this, catchScope);
11777330f729Sjoerg EHStack.popCatch();
11787330f729Sjoerg }
11797330f729Sjoerg
ExitCXXTryStmt(const CXXTryStmt & S,bool IsFnTryBlock)11807330f729Sjoerg void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
11817330f729Sjoerg unsigned NumHandlers = S.getNumHandlers();
11827330f729Sjoerg EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
11837330f729Sjoerg assert(CatchScope.getNumHandlers() == NumHandlers);
11847330f729Sjoerg llvm::BasicBlock *DispatchBlock = CatchScope.getCachedEHDispatchBlock();
11857330f729Sjoerg
11867330f729Sjoerg // If the catch was not required, bail out now.
11877330f729Sjoerg if (!CatchScope.hasEHBranches()) {
11887330f729Sjoerg CatchScope.clearHandlerBlocks();
11897330f729Sjoerg EHStack.popCatch();
11907330f729Sjoerg return;
11917330f729Sjoerg }
11927330f729Sjoerg
11937330f729Sjoerg // Emit the structure of the EH dispatch for this catch.
11947330f729Sjoerg emitCatchDispatchBlock(*this, CatchScope);
11957330f729Sjoerg
11967330f729Sjoerg // Copy the handler blocks off before we pop the EH stack. Emitting
11977330f729Sjoerg // the handlers might scribble on this memory.
11987330f729Sjoerg SmallVector<EHCatchScope::Handler, 8> Handlers(
11997330f729Sjoerg CatchScope.begin(), CatchScope.begin() + NumHandlers);
12007330f729Sjoerg
12017330f729Sjoerg EHStack.popCatch();
12027330f729Sjoerg
12037330f729Sjoerg // The fall-through block.
12047330f729Sjoerg llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
12057330f729Sjoerg
12067330f729Sjoerg // We just emitted the body of the try; jump to the continue block.
12077330f729Sjoerg if (HaveInsertPoint())
12087330f729Sjoerg Builder.CreateBr(ContBB);
12097330f729Sjoerg
12107330f729Sjoerg // Determine if we need an implicit rethrow for all these catch handlers;
12117330f729Sjoerg // see the comment below.
12127330f729Sjoerg bool doImplicitRethrow = false;
12137330f729Sjoerg if (IsFnTryBlock)
12147330f729Sjoerg doImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
12157330f729Sjoerg isa<CXXConstructorDecl>(CurCodeDecl);
12167330f729Sjoerg
12177330f729Sjoerg // Wasm uses Windows-style EH instructions, but merges all catch clauses into
12187330f729Sjoerg // one big catchpad. So we save the old funclet pad here before we traverse
12197330f729Sjoerg // each catch handler.
12207330f729Sjoerg SaveAndRestore<llvm::Instruction *> RestoreCurrentFuncletPad(
12217330f729Sjoerg CurrentFuncletPad);
12227330f729Sjoerg llvm::BasicBlock *WasmCatchStartBlock = nullptr;
12237330f729Sjoerg if (EHPersonality::get(*this).isWasmPersonality()) {
12247330f729Sjoerg auto *CatchSwitch =
12257330f729Sjoerg cast<llvm::CatchSwitchInst>(DispatchBlock->getFirstNonPHI());
12267330f729Sjoerg WasmCatchStartBlock = CatchSwitch->hasUnwindDest()
12277330f729Sjoerg ? CatchSwitch->getSuccessor(1)
12287330f729Sjoerg : CatchSwitch->getSuccessor(0);
12297330f729Sjoerg auto *CPI = cast<llvm::CatchPadInst>(WasmCatchStartBlock->getFirstNonPHI());
12307330f729Sjoerg CurrentFuncletPad = CPI;
12317330f729Sjoerg }
12327330f729Sjoerg
12337330f729Sjoerg // Perversely, we emit the handlers backwards precisely because we
12347330f729Sjoerg // want them to appear in source order. In all of these cases, the
12357330f729Sjoerg // catch block will have exactly one predecessor, which will be a
12367330f729Sjoerg // particular block in the catch dispatch. However, in the case of
12377330f729Sjoerg // a catch-all, one of the dispatch blocks will branch to two
12387330f729Sjoerg // different handlers, and EmitBlockAfterUses will cause the second
12397330f729Sjoerg // handler to be moved before the first.
12407330f729Sjoerg bool HasCatchAll = false;
12417330f729Sjoerg for (unsigned I = NumHandlers; I != 0; --I) {
12427330f729Sjoerg HasCatchAll |= Handlers[I - 1].isCatchAll();
12437330f729Sjoerg llvm::BasicBlock *CatchBlock = Handlers[I-1].Block;
12447330f729Sjoerg EmitBlockAfterUses(CatchBlock);
12457330f729Sjoerg
12467330f729Sjoerg // Catch the exception if this isn't a catch-all.
12477330f729Sjoerg const CXXCatchStmt *C = S.getHandler(I-1);
12487330f729Sjoerg
12497330f729Sjoerg // Enter a cleanup scope, including the catch variable and the
12507330f729Sjoerg // end-catch.
12517330f729Sjoerg RunCleanupsScope CatchScope(*this);
12527330f729Sjoerg
12537330f729Sjoerg // Initialize the catch variable and set up the cleanups.
12547330f729Sjoerg SaveAndRestore<llvm::Instruction *> RestoreCurrentFuncletPad(
12557330f729Sjoerg CurrentFuncletPad);
12567330f729Sjoerg CGM.getCXXABI().emitBeginCatch(*this, C);
12577330f729Sjoerg
12587330f729Sjoerg // Emit the PGO counter increment.
12597330f729Sjoerg incrementProfileCounter(C);
12607330f729Sjoerg
12617330f729Sjoerg // Perform the body of the catch.
12627330f729Sjoerg EmitStmt(C->getHandlerBlock());
12637330f729Sjoerg
12647330f729Sjoerg // [except.handle]p11:
12657330f729Sjoerg // The currently handled exception is rethrown if control
12667330f729Sjoerg // reaches the end of a handler of the function-try-block of a
12677330f729Sjoerg // constructor or destructor.
12687330f729Sjoerg
12697330f729Sjoerg // It is important that we only do this on fallthrough and not on
12707330f729Sjoerg // return. Note that it's illegal to put a return in a
12717330f729Sjoerg // constructor function-try-block's catch handler (p14), so this
12727330f729Sjoerg // really only applies to destructors.
12737330f729Sjoerg if (doImplicitRethrow && HaveInsertPoint()) {
12747330f729Sjoerg CGM.getCXXABI().emitRethrow(*this, /*isNoReturn*/false);
12757330f729Sjoerg Builder.CreateUnreachable();
12767330f729Sjoerg Builder.ClearInsertionPoint();
12777330f729Sjoerg }
12787330f729Sjoerg
12797330f729Sjoerg // Fall out through the catch cleanups.
12807330f729Sjoerg CatchScope.ForceCleanup();
12817330f729Sjoerg
12827330f729Sjoerg // Branch out of the try.
12837330f729Sjoerg if (HaveInsertPoint())
12847330f729Sjoerg Builder.CreateBr(ContBB);
12857330f729Sjoerg }
12867330f729Sjoerg
12877330f729Sjoerg // Because in wasm we merge all catch clauses into one big catchpad, in case
12887330f729Sjoerg // none of the types in catch handlers matches after we test against each of
12897330f729Sjoerg // them, we should unwind to the next EH enclosing scope. We generate a call
12907330f729Sjoerg // to rethrow function here to do that.
12917330f729Sjoerg if (EHPersonality::get(*this).isWasmPersonality() && !HasCatchAll) {
12927330f729Sjoerg assert(WasmCatchStartBlock);
12937330f729Sjoerg // Navigate for the "rethrow" block we created in emitWasmCatchPadBlock().
12947330f729Sjoerg // Wasm uses landingpad-style conditional branches to compare selectors, so
12957330f729Sjoerg // we follow the false destination for each of the cond branches to reach
12967330f729Sjoerg // the rethrow block.
12977330f729Sjoerg llvm::BasicBlock *RethrowBlock = WasmCatchStartBlock;
12987330f729Sjoerg while (llvm::Instruction *TI = RethrowBlock->getTerminator()) {
12997330f729Sjoerg auto *BI = cast<llvm::BranchInst>(TI);
13007330f729Sjoerg assert(BI->isConditional());
13017330f729Sjoerg RethrowBlock = BI->getSuccessor(1);
13027330f729Sjoerg }
13037330f729Sjoerg assert(RethrowBlock != WasmCatchStartBlock && RethrowBlock->empty());
13047330f729Sjoerg Builder.SetInsertPoint(RethrowBlock);
13057330f729Sjoerg llvm::Function *RethrowInCatchFn =
1306*e038c9c4Sjoerg CGM.getIntrinsic(llvm::Intrinsic::wasm_rethrow);
13077330f729Sjoerg EmitNoreturnRuntimeCallOrInvoke(RethrowInCatchFn, {});
13087330f729Sjoerg }
13097330f729Sjoerg
13107330f729Sjoerg EmitBlock(ContBB);
13117330f729Sjoerg incrementProfileCounter(&S);
13127330f729Sjoerg }
13137330f729Sjoerg
13147330f729Sjoerg namespace {
13157330f729Sjoerg struct CallEndCatchForFinally final : EHScopeStack::Cleanup {
13167330f729Sjoerg llvm::Value *ForEHVar;
13177330f729Sjoerg llvm::FunctionCallee EndCatchFn;
CallEndCatchForFinally__anon3e0594620211::CallEndCatchForFinally13187330f729Sjoerg CallEndCatchForFinally(llvm::Value *ForEHVar,
13197330f729Sjoerg llvm::FunctionCallee EndCatchFn)
13207330f729Sjoerg : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
13217330f729Sjoerg
Emit__anon3e0594620211::CallEndCatchForFinally13227330f729Sjoerg void Emit(CodeGenFunction &CGF, Flags flags) override {
13237330f729Sjoerg llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
13247330f729Sjoerg llvm::BasicBlock *CleanupContBB =
13257330f729Sjoerg CGF.createBasicBlock("finally.cleanup.cont");
13267330f729Sjoerg
13277330f729Sjoerg llvm::Value *ShouldEndCatch =
13287330f729Sjoerg CGF.Builder.CreateFlagLoad(ForEHVar, "finally.endcatch");
13297330f729Sjoerg CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
13307330f729Sjoerg CGF.EmitBlock(EndCatchBB);
13317330f729Sjoerg CGF.EmitRuntimeCallOrInvoke(EndCatchFn); // catch-all, so might throw
13327330f729Sjoerg CGF.EmitBlock(CleanupContBB);
13337330f729Sjoerg }
13347330f729Sjoerg };
13357330f729Sjoerg
13367330f729Sjoerg struct PerformFinally final : EHScopeStack::Cleanup {
13377330f729Sjoerg const Stmt *Body;
13387330f729Sjoerg llvm::Value *ForEHVar;
13397330f729Sjoerg llvm::FunctionCallee EndCatchFn;
13407330f729Sjoerg llvm::FunctionCallee RethrowFn;
13417330f729Sjoerg llvm::Value *SavedExnVar;
13427330f729Sjoerg
PerformFinally__anon3e0594620211::PerformFinally13437330f729Sjoerg PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
13447330f729Sjoerg llvm::FunctionCallee EndCatchFn,
13457330f729Sjoerg llvm::FunctionCallee RethrowFn, llvm::Value *SavedExnVar)
13467330f729Sjoerg : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
13477330f729Sjoerg RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
13487330f729Sjoerg
Emit__anon3e0594620211::PerformFinally13497330f729Sjoerg void Emit(CodeGenFunction &CGF, Flags flags) override {
13507330f729Sjoerg // Enter a cleanup to call the end-catch function if one was provided.
13517330f729Sjoerg if (EndCatchFn)
13527330f729Sjoerg CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
13537330f729Sjoerg ForEHVar, EndCatchFn);
13547330f729Sjoerg
13557330f729Sjoerg // Save the current cleanup destination in case there are
13567330f729Sjoerg // cleanups in the finally block.
13577330f729Sjoerg llvm::Value *SavedCleanupDest =
13587330f729Sjoerg CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
13597330f729Sjoerg "cleanup.dest.saved");
13607330f729Sjoerg
13617330f729Sjoerg // Emit the finally block.
13627330f729Sjoerg CGF.EmitStmt(Body);
13637330f729Sjoerg
13647330f729Sjoerg // If the end of the finally is reachable, check whether this was
13657330f729Sjoerg // for EH. If so, rethrow.
13667330f729Sjoerg if (CGF.HaveInsertPoint()) {
13677330f729Sjoerg llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
13687330f729Sjoerg llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
13697330f729Sjoerg
13707330f729Sjoerg llvm::Value *ShouldRethrow =
13717330f729Sjoerg CGF.Builder.CreateFlagLoad(ForEHVar, "finally.shouldthrow");
13727330f729Sjoerg CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
13737330f729Sjoerg
13747330f729Sjoerg CGF.EmitBlock(RethrowBB);
13757330f729Sjoerg if (SavedExnVar) {
13767330f729Sjoerg CGF.EmitRuntimeCallOrInvoke(RethrowFn,
1377*e038c9c4Sjoerg CGF.Builder.CreateAlignedLoad(CGF.Int8PtrTy, SavedExnVar,
1378*e038c9c4Sjoerg CGF.getPointerAlign()));
13797330f729Sjoerg } else {
13807330f729Sjoerg CGF.EmitRuntimeCallOrInvoke(RethrowFn);
13817330f729Sjoerg }
13827330f729Sjoerg CGF.Builder.CreateUnreachable();
13837330f729Sjoerg
13847330f729Sjoerg CGF.EmitBlock(ContBB);
13857330f729Sjoerg
13867330f729Sjoerg // Restore the cleanup destination.
13877330f729Sjoerg CGF.Builder.CreateStore(SavedCleanupDest,
13887330f729Sjoerg CGF.getNormalCleanupDestSlot());
13897330f729Sjoerg }
13907330f729Sjoerg
13917330f729Sjoerg // Leave the end-catch cleanup. As an optimization, pretend that
13927330f729Sjoerg // the fallthrough path was inaccessible; we've dynamically proven
13937330f729Sjoerg // that we're not in the EH case along that path.
13947330f729Sjoerg if (EndCatchFn) {
13957330f729Sjoerg CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
13967330f729Sjoerg CGF.PopCleanupBlock();
13977330f729Sjoerg CGF.Builder.restoreIP(SavedIP);
13987330f729Sjoerg }
13997330f729Sjoerg
14007330f729Sjoerg // Now make sure we actually have an insertion point or the
14017330f729Sjoerg // cleanup gods will hate us.
14027330f729Sjoerg CGF.EnsureInsertPoint();
14037330f729Sjoerg }
14047330f729Sjoerg };
14057330f729Sjoerg } // end anonymous namespace
14067330f729Sjoerg
14077330f729Sjoerg /// Enters a finally block for an implementation using zero-cost
14087330f729Sjoerg /// exceptions. This is mostly general, but hard-codes some
14097330f729Sjoerg /// language/ABI-specific behavior in the catch-all sections.
enter(CodeGenFunction & CGF,const Stmt * body,llvm::FunctionCallee beginCatchFn,llvm::FunctionCallee endCatchFn,llvm::FunctionCallee rethrowFn)14107330f729Sjoerg void CodeGenFunction::FinallyInfo::enter(CodeGenFunction &CGF, const Stmt *body,
14117330f729Sjoerg llvm::FunctionCallee beginCatchFn,
14127330f729Sjoerg llvm::FunctionCallee endCatchFn,
14137330f729Sjoerg llvm::FunctionCallee rethrowFn) {
14147330f729Sjoerg assert((!!beginCatchFn) == (!!endCatchFn) &&
14157330f729Sjoerg "begin/end catch functions not paired");
14167330f729Sjoerg assert(rethrowFn && "rethrow function is required");
14177330f729Sjoerg
14187330f729Sjoerg BeginCatchFn = beginCatchFn;
14197330f729Sjoerg
14207330f729Sjoerg // The rethrow function has one of the following two types:
14217330f729Sjoerg // void (*)()
14227330f729Sjoerg // void (*)(void*)
14237330f729Sjoerg // In the latter case we need to pass it the exception object.
14247330f729Sjoerg // But we can't use the exception slot because the @finally might
14257330f729Sjoerg // have a landing pad (which would overwrite the exception slot).
14267330f729Sjoerg llvm::FunctionType *rethrowFnTy = rethrowFn.getFunctionType();
14277330f729Sjoerg SavedExnVar = nullptr;
14287330f729Sjoerg if (rethrowFnTy->getNumParams())
14297330f729Sjoerg SavedExnVar = CGF.CreateTempAlloca(CGF.Int8PtrTy, "finally.exn");
14307330f729Sjoerg
14317330f729Sjoerg // A finally block is a statement which must be executed on any edge
14327330f729Sjoerg // out of a given scope. Unlike a cleanup, the finally block may
14337330f729Sjoerg // contain arbitrary control flow leading out of itself. In
14347330f729Sjoerg // addition, finally blocks should always be executed, even if there
14357330f729Sjoerg // are no catch handlers higher on the stack. Therefore, we
14367330f729Sjoerg // surround the protected scope with a combination of a normal
14377330f729Sjoerg // cleanup (to catch attempts to break out of the block via normal
14387330f729Sjoerg // control flow) and an EH catch-all (semantically "outside" any try
14397330f729Sjoerg // statement to which the finally block might have been attached).
14407330f729Sjoerg // The finally block itself is generated in the context of a cleanup
14417330f729Sjoerg // which conditionally leaves the catch-all.
14427330f729Sjoerg
14437330f729Sjoerg // Jump destination for performing the finally block on an exception
14447330f729Sjoerg // edge. We'll never actually reach this block, so unreachable is
14457330f729Sjoerg // fine.
14467330f729Sjoerg RethrowDest = CGF.getJumpDestInCurrentScope(CGF.getUnreachableBlock());
14477330f729Sjoerg
14487330f729Sjoerg // Whether the finally block is being executed for EH purposes.
14497330f729Sjoerg ForEHVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "finally.for-eh");
14507330f729Sjoerg CGF.Builder.CreateFlagStore(false, ForEHVar);
14517330f729Sjoerg
14527330f729Sjoerg // Enter a normal cleanup which will perform the @finally block.
14537330f729Sjoerg CGF.EHStack.pushCleanup<PerformFinally>(NormalCleanup, body,
14547330f729Sjoerg ForEHVar, endCatchFn,
14557330f729Sjoerg rethrowFn, SavedExnVar);
14567330f729Sjoerg
14577330f729Sjoerg // Enter a catch-all scope.
14587330f729Sjoerg llvm::BasicBlock *catchBB = CGF.createBasicBlock("finally.catchall");
14597330f729Sjoerg EHCatchScope *catchScope = CGF.EHStack.pushCatch(1);
14607330f729Sjoerg catchScope->setCatchAllHandler(0, catchBB);
14617330f729Sjoerg }
14627330f729Sjoerg
exit(CodeGenFunction & CGF)14637330f729Sjoerg void CodeGenFunction::FinallyInfo::exit(CodeGenFunction &CGF) {
14647330f729Sjoerg // Leave the finally catch-all.
14657330f729Sjoerg EHCatchScope &catchScope = cast<EHCatchScope>(*CGF.EHStack.begin());
14667330f729Sjoerg llvm::BasicBlock *catchBB = catchScope.getHandler(0).Block;
14677330f729Sjoerg
14687330f729Sjoerg CGF.popCatchScope();
14697330f729Sjoerg
14707330f729Sjoerg // If there are any references to the catch-all block, emit it.
14717330f729Sjoerg if (catchBB->use_empty()) {
14727330f729Sjoerg delete catchBB;
14737330f729Sjoerg } else {
14747330f729Sjoerg CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveAndClearIP();
14757330f729Sjoerg CGF.EmitBlock(catchBB);
14767330f729Sjoerg
14777330f729Sjoerg llvm::Value *exn = nullptr;
14787330f729Sjoerg
14797330f729Sjoerg // If there's a begin-catch function, call it.
14807330f729Sjoerg if (BeginCatchFn) {
14817330f729Sjoerg exn = CGF.getExceptionFromSlot();
14827330f729Sjoerg CGF.EmitNounwindRuntimeCall(BeginCatchFn, exn);
14837330f729Sjoerg }
14847330f729Sjoerg
14857330f729Sjoerg // If we need to remember the exception pointer to rethrow later, do so.
14867330f729Sjoerg if (SavedExnVar) {
14877330f729Sjoerg if (!exn) exn = CGF.getExceptionFromSlot();
14887330f729Sjoerg CGF.Builder.CreateAlignedStore(exn, SavedExnVar, CGF.getPointerAlign());
14897330f729Sjoerg }
14907330f729Sjoerg
14917330f729Sjoerg // Tell the cleanups in the finally block that we're do this for EH.
14927330f729Sjoerg CGF.Builder.CreateFlagStore(true, ForEHVar);
14937330f729Sjoerg
14947330f729Sjoerg // Thread a jump through the finally cleanup.
14957330f729Sjoerg CGF.EmitBranchThroughCleanup(RethrowDest);
14967330f729Sjoerg
14977330f729Sjoerg CGF.Builder.restoreIP(savedIP);
14987330f729Sjoerg }
14997330f729Sjoerg
15007330f729Sjoerg // Finally, leave the @finally cleanup.
15017330f729Sjoerg CGF.PopCleanupBlock();
15027330f729Sjoerg }
15037330f729Sjoerg
getTerminateLandingPad()15047330f729Sjoerg llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
15057330f729Sjoerg if (TerminateLandingPad)
15067330f729Sjoerg return TerminateLandingPad;
15077330f729Sjoerg
15087330f729Sjoerg CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
15097330f729Sjoerg
15107330f729Sjoerg // This will get inserted at the end of the function.
15117330f729Sjoerg TerminateLandingPad = createBasicBlock("terminate.lpad");
15127330f729Sjoerg Builder.SetInsertPoint(TerminateLandingPad);
15137330f729Sjoerg
15147330f729Sjoerg // Tell the backend that this is a landing pad.
15157330f729Sjoerg const EHPersonality &Personality = EHPersonality::get(*this);
15167330f729Sjoerg
15177330f729Sjoerg if (!CurFn->hasPersonalityFn())
15187330f729Sjoerg CurFn->setPersonalityFn(getOpaquePersonalityFn(CGM, Personality));
15197330f729Sjoerg
15207330f729Sjoerg llvm::LandingPadInst *LPadInst =
15217330f729Sjoerg Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty), 0);
15227330f729Sjoerg LPadInst->addClause(getCatchAllValue(*this));
15237330f729Sjoerg
15247330f729Sjoerg llvm::Value *Exn = nullptr;
15257330f729Sjoerg if (getLangOpts().CPlusPlus)
15267330f729Sjoerg Exn = Builder.CreateExtractValue(LPadInst, 0);
15277330f729Sjoerg llvm::CallInst *terminateCall =
15287330f729Sjoerg CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
15297330f729Sjoerg terminateCall->setDoesNotReturn();
15307330f729Sjoerg Builder.CreateUnreachable();
15317330f729Sjoerg
15327330f729Sjoerg // Restore the saved insertion state.
15337330f729Sjoerg Builder.restoreIP(SavedIP);
15347330f729Sjoerg
15357330f729Sjoerg return TerminateLandingPad;
15367330f729Sjoerg }
15377330f729Sjoerg
getTerminateHandler()15387330f729Sjoerg llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
15397330f729Sjoerg if (TerminateHandler)
15407330f729Sjoerg return TerminateHandler;
15417330f729Sjoerg
15427330f729Sjoerg // Set up the terminate handler. This block is inserted at the very
15437330f729Sjoerg // end of the function by FinishFunction.
15447330f729Sjoerg TerminateHandler = createBasicBlock("terminate.handler");
15457330f729Sjoerg CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
15467330f729Sjoerg Builder.SetInsertPoint(TerminateHandler);
15477330f729Sjoerg
15487330f729Sjoerg llvm::Value *Exn = nullptr;
15497330f729Sjoerg if (getLangOpts().CPlusPlus)
15507330f729Sjoerg Exn = getExceptionFromSlot();
15517330f729Sjoerg llvm::CallInst *terminateCall =
15527330f729Sjoerg CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
15537330f729Sjoerg terminateCall->setDoesNotReturn();
15547330f729Sjoerg Builder.CreateUnreachable();
15557330f729Sjoerg
15567330f729Sjoerg // Restore the saved insertion state.
15577330f729Sjoerg Builder.restoreIP(SavedIP);
15587330f729Sjoerg
15597330f729Sjoerg return TerminateHandler;
15607330f729Sjoerg }
15617330f729Sjoerg
getTerminateFunclet()15627330f729Sjoerg llvm::BasicBlock *CodeGenFunction::getTerminateFunclet() {
15637330f729Sjoerg assert(EHPersonality::get(*this).usesFuncletPads() &&
15647330f729Sjoerg "use getTerminateLandingPad for non-funclet EH");
15657330f729Sjoerg
15667330f729Sjoerg llvm::BasicBlock *&TerminateFunclet = TerminateFunclets[CurrentFuncletPad];
15677330f729Sjoerg if (TerminateFunclet)
15687330f729Sjoerg return TerminateFunclet;
15697330f729Sjoerg
15707330f729Sjoerg CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
15717330f729Sjoerg
15727330f729Sjoerg // Set up the terminate handler. This block is inserted at the very
15737330f729Sjoerg // end of the function by FinishFunction.
15747330f729Sjoerg TerminateFunclet = createBasicBlock("terminate.handler");
15757330f729Sjoerg Builder.SetInsertPoint(TerminateFunclet);
15767330f729Sjoerg
15777330f729Sjoerg // Create the cleanuppad using the current parent pad as its token. Use 'none'
15787330f729Sjoerg // if this is a top-level terminate scope, which is the common case.
15797330f729Sjoerg SaveAndRestore<llvm::Instruction *> RestoreCurrentFuncletPad(
15807330f729Sjoerg CurrentFuncletPad);
15817330f729Sjoerg llvm::Value *ParentPad = CurrentFuncletPad;
15827330f729Sjoerg if (!ParentPad)
15837330f729Sjoerg ParentPad = llvm::ConstantTokenNone::get(CGM.getLLVMContext());
15847330f729Sjoerg CurrentFuncletPad = Builder.CreateCleanupPad(ParentPad);
15857330f729Sjoerg
15867330f729Sjoerg // Emit the __std_terminate call.
15877330f729Sjoerg llvm::CallInst *terminateCall =
1588*e038c9c4Sjoerg CGM.getCXXABI().emitTerminateForUnexpectedException(*this, nullptr);
15897330f729Sjoerg terminateCall->setDoesNotReturn();
15907330f729Sjoerg Builder.CreateUnreachable();
15917330f729Sjoerg
15927330f729Sjoerg // Restore the saved insertion state.
15937330f729Sjoerg Builder.restoreIP(SavedIP);
15947330f729Sjoerg
15957330f729Sjoerg return TerminateFunclet;
15967330f729Sjoerg }
15977330f729Sjoerg
getEHResumeBlock(bool isCleanup)15987330f729Sjoerg llvm::BasicBlock *CodeGenFunction::getEHResumeBlock(bool isCleanup) {
15997330f729Sjoerg if (EHResumeBlock) return EHResumeBlock;
16007330f729Sjoerg
16017330f729Sjoerg CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
16027330f729Sjoerg
16037330f729Sjoerg // We emit a jump to a notional label at the outermost unwind state.
16047330f729Sjoerg EHResumeBlock = createBasicBlock("eh.resume");
16057330f729Sjoerg Builder.SetInsertPoint(EHResumeBlock);
16067330f729Sjoerg
16077330f729Sjoerg const EHPersonality &Personality = EHPersonality::get(*this);
16087330f729Sjoerg
16097330f729Sjoerg // This can always be a call because we necessarily didn't find
16107330f729Sjoerg // anything on the EH stack which needs our help.
16117330f729Sjoerg const char *RethrowName = Personality.CatchallRethrowFn;
16127330f729Sjoerg if (RethrowName != nullptr && !isCleanup) {
16137330f729Sjoerg EmitRuntimeCall(getCatchallRethrowFn(CGM, RethrowName),
16147330f729Sjoerg getExceptionFromSlot())->setDoesNotReturn();
16157330f729Sjoerg Builder.CreateUnreachable();
16167330f729Sjoerg Builder.restoreIP(SavedIP);
16177330f729Sjoerg return EHResumeBlock;
16187330f729Sjoerg }
16197330f729Sjoerg
16207330f729Sjoerg // Recreate the landingpad's return value for the 'resume' instruction.
16217330f729Sjoerg llvm::Value *Exn = getExceptionFromSlot();
16227330f729Sjoerg llvm::Value *Sel = getSelectorFromSlot();
16237330f729Sjoerg
16247330f729Sjoerg llvm::Type *LPadType = llvm::StructType::get(Exn->getType(), Sel->getType());
16257330f729Sjoerg llvm::Value *LPadVal = llvm::UndefValue::get(LPadType);
16267330f729Sjoerg LPadVal = Builder.CreateInsertValue(LPadVal, Exn, 0, "lpad.val");
16277330f729Sjoerg LPadVal = Builder.CreateInsertValue(LPadVal, Sel, 1, "lpad.val");
16287330f729Sjoerg
16297330f729Sjoerg Builder.CreateResume(LPadVal);
16307330f729Sjoerg Builder.restoreIP(SavedIP);
16317330f729Sjoerg return EHResumeBlock;
16327330f729Sjoerg }
16337330f729Sjoerg
EmitSEHTryStmt(const SEHTryStmt & S)16347330f729Sjoerg void CodeGenFunction::EmitSEHTryStmt(const SEHTryStmt &S) {
16357330f729Sjoerg EnterSEHTryStmt(S);
16367330f729Sjoerg {
16377330f729Sjoerg JumpDest TryExit = getJumpDestInCurrentScope("__try.__leave");
16387330f729Sjoerg
16397330f729Sjoerg SEHTryEpilogueStack.push_back(&TryExit);
1640*e038c9c4Sjoerg
1641*e038c9c4Sjoerg llvm::BasicBlock *TryBB = nullptr;
1642*e038c9c4Sjoerg // IsEHa: emit an invoke to _seh_try_begin() runtime for -EHa
1643*e038c9c4Sjoerg if (getLangOpts().EHAsynch) {
1644*e038c9c4Sjoerg EmitRuntimeCallOrInvoke(getSehTryBeginFn(CGM));
1645*e038c9c4Sjoerg if (SEHTryEpilogueStack.size() == 1) // outermost only
1646*e038c9c4Sjoerg TryBB = Builder.GetInsertBlock();
1647*e038c9c4Sjoerg }
1648*e038c9c4Sjoerg
16497330f729Sjoerg EmitStmt(S.getTryBlock());
1650*e038c9c4Sjoerg
1651*e038c9c4Sjoerg // Volatilize all blocks in Try, till current insert point
1652*e038c9c4Sjoerg if (TryBB) {
1653*e038c9c4Sjoerg llvm::SmallPtrSet<llvm::BasicBlock *, 10> Visited;
1654*e038c9c4Sjoerg VolatilizeTryBlocks(TryBB, Visited);
1655*e038c9c4Sjoerg }
1656*e038c9c4Sjoerg
16577330f729Sjoerg SEHTryEpilogueStack.pop_back();
16587330f729Sjoerg
16597330f729Sjoerg if (!TryExit.getBlock()->use_empty())
16607330f729Sjoerg EmitBlock(TryExit.getBlock(), /*IsFinished=*/true);
16617330f729Sjoerg else
16627330f729Sjoerg delete TryExit.getBlock();
16637330f729Sjoerg }
16647330f729Sjoerg ExitSEHTryStmt(S);
16657330f729Sjoerg }
16667330f729Sjoerg
1667*e038c9c4Sjoerg // Recursively walk through blocks in a _try
1668*e038c9c4Sjoerg // and make all memory instructions volatile
VolatilizeTryBlocks(llvm::BasicBlock * BB,llvm::SmallPtrSet<llvm::BasicBlock *,10> & V)1669*e038c9c4Sjoerg void CodeGenFunction::VolatilizeTryBlocks(
1670*e038c9c4Sjoerg llvm::BasicBlock *BB, llvm::SmallPtrSet<llvm::BasicBlock *, 10> &V) {
1671*e038c9c4Sjoerg if (BB == SEHTryEpilogueStack.back()->getBlock() /* end of Try */ ||
1672*e038c9c4Sjoerg !V.insert(BB).second /* already visited */ ||
1673*e038c9c4Sjoerg !BB->getParent() /* not emitted */ || BB->empty())
1674*e038c9c4Sjoerg return;
1675*e038c9c4Sjoerg
1676*e038c9c4Sjoerg if (!BB->isEHPad()) {
1677*e038c9c4Sjoerg for (llvm::BasicBlock::iterator J = BB->begin(), JE = BB->end(); J != JE;
1678*e038c9c4Sjoerg ++J) {
1679*e038c9c4Sjoerg if (auto LI = dyn_cast<llvm::LoadInst>(J)) {
1680*e038c9c4Sjoerg LI->setVolatile(true);
1681*e038c9c4Sjoerg } else if (auto SI = dyn_cast<llvm::StoreInst>(J)) {
1682*e038c9c4Sjoerg SI->setVolatile(true);
1683*e038c9c4Sjoerg } else if (auto* MCI = dyn_cast<llvm::MemIntrinsic>(J)) {
1684*e038c9c4Sjoerg MCI->setVolatile(llvm::ConstantInt::get(Builder.getInt1Ty(), 1));
1685*e038c9c4Sjoerg }
1686*e038c9c4Sjoerg }
1687*e038c9c4Sjoerg }
1688*e038c9c4Sjoerg const llvm::Instruction *TI = BB->getTerminator();
1689*e038c9c4Sjoerg if (TI) {
1690*e038c9c4Sjoerg unsigned N = TI->getNumSuccessors();
1691*e038c9c4Sjoerg for (unsigned I = 0; I < N; I++)
1692*e038c9c4Sjoerg VolatilizeTryBlocks(TI->getSuccessor(I), V);
1693*e038c9c4Sjoerg }
1694*e038c9c4Sjoerg }
1695*e038c9c4Sjoerg
16967330f729Sjoerg namespace {
16977330f729Sjoerg struct PerformSEHFinally final : EHScopeStack::Cleanup {
16987330f729Sjoerg llvm::Function *OutlinedFinally;
PerformSEHFinally__anon3e0594620311::PerformSEHFinally16997330f729Sjoerg PerformSEHFinally(llvm::Function *OutlinedFinally)
17007330f729Sjoerg : OutlinedFinally(OutlinedFinally) {}
17017330f729Sjoerg
Emit__anon3e0594620311::PerformSEHFinally17027330f729Sjoerg void Emit(CodeGenFunction &CGF, Flags F) override {
17037330f729Sjoerg ASTContext &Context = CGF.getContext();
17047330f729Sjoerg CodeGenModule &CGM = CGF.CGM;
17057330f729Sjoerg
17067330f729Sjoerg CallArgList Args;
17077330f729Sjoerg
17087330f729Sjoerg // Compute the two argument values.
17097330f729Sjoerg QualType ArgTys[2] = {Context.UnsignedCharTy, Context.VoidPtrTy};
17107330f729Sjoerg llvm::Value *FP = nullptr;
17117330f729Sjoerg // If CFG.IsOutlinedSEHHelper is true, then we are within a finally block.
17127330f729Sjoerg if (CGF.IsOutlinedSEHHelper) {
17137330f729Sjoerg FP = &CGF.CurFn->arg_begin()[1];
17147330f729Sjoerg } else {
17157330f729Sjoerg llvm::Function *LocalAddrFn =
17167330f729Sjoerg CGM.getIntrinsic(llvm::Intrinsic::localaddress);
17177330f729Sjoerg FP = CGF.Builder.CreateCall(LocalAddrFn);
17187330f729Sjoerg }
17197330f729Sjoerg
17207330f729Sjoerg llvm::Value *IsForEH =
17217330f729Sjoerg llvm::ConstantInt::get(CGF.ConvertType(ArgTys[0]), F.isForEHCleanup());
1722*e038c9c4Sjoerg
1723*e038c9c4Sjoerg // Except _leave and fall-through at the end, all other exits in a _try
1724*e038c9c4Sjoerg // (return/goto/continue/break) are considered as abnormal terminations
1725*e038c9c4Sjoerg // since _leave/fall-through is always Indexed 0,
1726*e038c9c4Sjoerg // just use NormalCleanupDestSlot (>= 1 for goto/return/..),
1727*e038c9c4Sjoerg // as 1st Arg to indicate abnormal termination
1728*e038c9c4Sjoerg if (!F.isForEHCleanup() && F.hasExitSwitch()) {
1729*e038c9c4Sjoerg Address Addr = CGF.getNormalCleanupDestSlot();
1730*e038c9c4Sjoerg llvm::Value *Load = CGF.Builder.CreateLoad(Addr, "cleanup.dest");
1731*e038c9c4Sjoerg llvm::Value *Zero = llvm::Constant::getNullValue(CGM.Int32Ty);
1732*e038c9c4Sjoerg IsForEH = CGF.Builder.CreateICmpNE(Load, Zero);
1733*e038c9c4Sjoerg }
1734*e038c9c4Sjoerg
17357330f729Sjoerg Args.add(RValue::get(IsForEH), ArgTys[0]);
17367330f729Sjoerg Args.add(RValue::get(FP), ArgTys[1]);
17377330f729Sjoerg
17387330f729Sjoerg // Arrange a two-arg function info and type.
17397330f729Sjoerg const CGFunctionInfo &FnInfo =
17407330f729Sjoerg CGM.getTypes().arrangeBuiltinFunctionCall(Context.VoidTy, Args);
17417330f729Sjoerg
17427330f729Sjoerg auto Callee = CGCallee::forDirect(OutlinedFinally);
17437330f729Sjoerg CGF.EmitCall(FnInfo, Callee, ReturnValueSlot(), Args);
17447330f729Sjoerg }
17457330f729Sjoerg };
17467330f729Sjoerg } // end anonymous namespace
17477330f729Sjoerg
17487330f729Sjoerg namespace {
17497330f729Sjoerg /// Find all local variable captures in the statement.
17507330f729Sjoerg struct CaptureFinder : ConstStmtVisitor<CaptureFinder> {
17517330f729Sjoerg CodeGenFunction &ParentCGF;
17527330f729Sjoerg const VarDecl *ParentThis;
17537330f729Sjoerg llvm::SmallSetVector<const VarDecl *, 4> Captures;
17547330f729Sjoerg Address SEHCodeSlot = Address::invalid();
CaptureFinder__anon3e0594620411::CaptureFinder17557330f729Sjoerg CaptureFinder(CodeGenFunction &ParentCGF, const VarDecl *ParentThis)
17567330f729Sjoerg : ParentCGF(ParentCGF), ParentThis(ParentThis) {}
17577330f729Sjoerg
17587330f729Sjoerg // Return true if we need to do any capturing work.
foundCaptures__anon3e0594620411::CaptureFinder17597330f729Sjoerg bool foundCaptures() {
17607330f729Sjoerg return !Captures.empty() || SEHCodeSlot.isValid();
17617330f729Sjoerg }
17627330f729Sjoerg
Visit__anon3e0594620411::CaptureFinder17637330f729Sjoerg void Visit(const Stmt *S) {
17647330f729Sjoerg // See if this is a capture, then recurse.
17657330f729Sjoerg ConstStmtVisitor<CaptureFinder>::Visit(S);
17667330f729Sjoerg for (const Stmt *Child : S->children())
17677330f729Sjoerg if (Child)
17687330f729Sjoerg Visit(Child);
17697330f729Sjoerg }
17707330f729Sjoerg
VisitDeclRefExpr__anon3e0594620411::CaptureFinder17717330f729Sjoerg void VisitDeclRefExpr(const DeclRefExpr *E) {
17727330f729Sjoerg // If this is already a capture, just make sure we capture 'this'.
1773*e038c9c4Sjoerg if (E->refersToEnclosingVariableOrCapture())
17747330f729Sjoerg Captures.insert(ParentThis);
17757330f729Sjoerg
17767330f729Sjoerg const auto *D = dyn_cast<VarDecl>(E->getDecl());
17777330f729Sjoerg if (D && D->isLocalVarDeclOrParm() && D->hasLocalStorage())
17787330f729Sjoerg Captures.insert(D);
17797330f729Sjoerg }
17807330f729Sjoerg
VisitCXXThisExpr__anon3e0594620411::CaptureFinder17817330f729Sjoerg void VisitCXXThisExpr(const CXXThisExpr *E) {
17827330f729Sjoerg Captures.insert(ParentThis);
17837330f729Sjoerg }
17847330f729Sjoerg
VisitCallExpr__anon3e0594620411::CaptureFinder17857330f729Sjoerg void VisitCallExpr(const CallExpr *E) {
17867330f729Sjoerg // We only need to add parent frame allocations for these builtins in x86.
17877330f729Sjoerg if (ParentCGF.getTarget().getTriple().getArch() != llvm::Triple::x86)
17887330f729Sjoerg return;
17897330f729Sjoerg
17907330f729Sjoerg unsigned ID = E->getBuiltinCallee();
17917330f729Sjoerg switch (ID) {
17927330f729Sjoerg case Builtin::BI__exception_code:
17937330f729Sjoerg case Builtin::BI_exception_code:
17947330f729Sjoerg // This is the simple case where we are the outermost finally. All we
17957330f729Sjoerg // have to do here is make sure we escape this and recover it in the
17967330f729Sjoerg // outlined handler.
17977330f729Sjoerg if (!SEHCodeSlot.isValid())
17987330f729Sjoerg SEHCodeSlot = ParentCGF.SEHCodeSlotStack.back();
17997330f729Sjoerg break;
18007330f729Sjoerg }
18017330f729Sjoerg }
18027330f729Sjoerg };
18037330f729Sjoerg } // end anonymous namespace
18047330f729Sjoerg
recoverAddrOfEscapedLocal(CodeGenFunction & ParentCGF,Address ParentVar,llvm::Value * ParentFP)18057330f729Sjoerg Address CodeGenFunction::recoverAddrOfEscapedLocal(CodeGenFunction &ParentCGF,
18067330f729Sjoerg Address ParentVar,
18077330f729Sjoerg llvm::Value *ParentFP) {
18087330f729Sjoerg llvm::CallInst *RecoverCall = nullptr;
18097330f729Sjoerg CGBuilderTy Builder(*this, AllocaInsertPt);
18107330f729Sjoerg if (auto *ParentAlloca = dyn_cast<llvm::AllocaInst>(ParentVar.getPointer())) {
18117330f729Sjoerg // Mark the variable escaped if nobody else referenced it and compute the
18127330f729Sjoerg // localescape index.
18137330f729Sjoerg auto InsertPair = ParentCGF.EscapedLocals.insert(
18147330f729Sjoerg std::make_pair(ParentAlloca, ParentCGF.EscapedLocals.size()));
18157330f729Sjoerg int FrameEscapeIdx = InsertPair.first->second;
18167330f729Sjoerg // call i8* @llvm.localrecover(i8* bitcast(@parentFn), i8* %fp, i32 N)
18177330f729Sjoerg llvm::Function *FrameRecoverFn = llvm::Intrinsic::getDeclaration(
18187330f729Sjoerg &CGM.getModule(), llvm::Intrinsic::localrecover);
18197330f729Sjoerg llvm::Constant *ParentI8Fn =
18207330f729Sjoerg llvm::ConstantExpr::getBitCast(ParentCGF.CurFn, Int8PtrTy);
18217330f729Sjoerg RecoverCall = Builder.CreateCall(
18227330f729Sjoerg FrameRecoverFn, {ParentI8Fn, ParentFP,
18237330f729Sjoerg llvm::ConstantInt::get(Int32Ty, FrameEscapeIdx)});
18247330f729Sjoerg
18257330f729Sjoerg } else {
18267330f729Sjoerg // If the parent didn't have an alloca, we're doing some nested outlining.
18277330f729Sjoerg // Just clone the existing localrecover call, but tweak the FP argument to
18287330f729Sjoerg // use our FP value. All other arguments are constants.
18297330f729Sjoerg auto *ParentRecover =
18307330f729Sjoerg cast<llvm::IntrinsicInst>(ParentVar.getPointer()->stripPointerCasts());
18317330f729Sjoerg assert(ParentRecover->getIntrinsicID() == llvm::Intrinsic::localrecover &&
18327330f729Sjoerg "expected alloca or localrecover in parent LocalDeclMap");
18337330f729Sjoerg RecoverCall = cast<llvm::CallInst>(ParentRecover->clone());
18347330f729Sjoerg RecoverCall->setArgOperand(1, ParentFP);
18357330f729Sjoerg RecoverCall->insertBefore(AllocaInsertPt);
18367330f729Sjoerg }
18377330f729Sjoerg
18387330f729Sjoerg // Bitcast the variable, rename it, and insert it in the local decl map.
18397330f729Sjoerg llvm::Value *ChildVar =
18407330f729Sjoerg Builder.CreateBitCast(RecoverCall, ParentVar.getType());
18417330f729Sjoerg ChildVar->setName(ParentVar.getName());
18427330f729Sjoerg return Address(ChildVar, ParentVar.getAlignment());
18437330f729Sjoerg }
18447330f729Sjoerg
EmitCapturedLocals(CodeGenFunction & ParentCGF,const Stmt * OutlinedStmt,bool IsFilter)18457330f729Sjoerg void CodeGenFunction::EmitCapturedLocals(CodeGenFunction &ParentCGF,
18467330f729Sjoerg const Stmt *OutlinedStmt,
18477330f729Sjoerg bool IsFilter) {
18487330f729Sjoerg // Find all captures in the Stmt.
18497330f729Sjoerg CaptureFinder Finder(ParentCGF, ParentCGF.CXXABIThisDecl);
18507330f729Sjoerg Finder.Visit(OutlinedStmt);
18517330f729Sjoerg
18527330f729Sjoerg // We can exit early on x86_64 when there are no captures. We just have to
18537330f729Sjoerg // save the exception code in filters so that __exception_code() works.
18547330f729Sjoerg if (!Finder.foundCaptures() &&
18557330f729Sjoerg CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
18567330f729Sjoerg if (IsFilter)
18577330f729Sjoerg EmitSEHExceptionCodeSave(ParentCGF, nullptr, nullptr);
18587330f729Sjoerg return;
18597330f729Sjoerg }
18607330f729Sjoerg
18617330f729Sjoerg llvm::Value *EntryFP = nullptr;
18627330f729Sjoerg CGBuilderTy Builder(CGM, AllocaInsertPt);
18637330f729Sjoerg if (IsFilter && CGM.getTarget().getTriple().getArch() == llvm::Triple::x86) {
18647330f729Sjoerg // 32-bit SEH filters need to be careful about FP recovery. The end of the
18657330f729Sjoerg // EH registration is passed in as the EBP physical register. We can
18667330f729Sjoerg // recover that with llvm.frameaddress(1).
18677330f729Sjoerg EntryFP = Builder.CreateCall(
18687330f729Sjoerg CGM.getIntrinsic(llvm::Intrinsic::frameaddress, AllocaInt8PtrTy),
18697330f729Sjoerg {Builder.getInt32(1)});
18707330f729Sjoerg } else {
18717330f729Sjoerg // Otherwise, for x64 and 32-bit finally functions, the parent FP is the
18727330f729Sjoerg // second parameter.
18737330f729Sjoerg auto AI = CurFn->arg_begin();
18747330f729Sjoerg ++AI;
18757330f729Sjoerg EntryFP = &*AI;
18767330f729Sjoerg }
18777330f729Sjoerg
18787330f729Sjoerg llvm::Value *ParentFP = EntryFP;
18797330f729Sjoerg if (IsFilter) {
18807330f729Sjoerg // Given whatever FP the runtime provided us in EntryFP, recover the true
18817330f729Sjoerg // frame pointer of the parent function. We only need to do this in filters,
18827330f729Sjoerg // since finally funclets recover the parent FP for us.
18837330f729Sjoerg llvm::Function *RecoverFPIntrin =
18847330f729Sjoerg CGM.getIntrinsic(llvm::Intrinsic::eh_recoverfp);
18857330f729Sjoerg llvm::Constant *ParentI8Fn =
18867330f729Sjoerg llvm::ConstantExpr::getBitCast(ParentCGF.CurFn, Int8PtrTy);
18877330f729Sjoerg ParentFP = Builder.CreateCall(RecoverFPIntrin, {ParentI8Fn, EntryFP});
1888*e038c9c4Sjoerg
1889*e038c9c4Sjoerg // if the parent is a _finally, the passed-in ParentFP is the FP
1890*e038c9c4Sjoerg // of parent _finally, not Establisher's FP (FP of outermost function).
1891*e038c9c4Sjoerg // Establkisher FP is 2nd paramenter passed into parent _finally.
1892*e038c9c4Sjoerg // Fortunately, it's always saved in parent's frame. The following
1893*e038c9c4Sjoerg // code retrieves it, and escapes it so that spill instruction won't be
1894*e038c9c4Sjoerg // optimized away.
1895*e038c9c4Sjoerg if (ParentCGF.ParentCGF != nullptr) {
1896*e038c9c4Sjoerg // Locate and escape Parent's frame_pointer.addr alloca
1897*e038c9c4Sjoerg // Depending on target, should be 1st/2nd one in LocalDeclMap.
1898*e038c9c4Sjoerg // Let's just scan for ImplicitParamDecl with VoidPtrTy.
1899*e038c9c4Sjoerg llvm::AllocaInst *FramePtrAddrAlloca = nullptr;
1900*e038c9c4Sjoerg for (auto &I : ParentCGF.LocalDeclMap) {
1901*e038c9c4Sjoerg const VarDecl *D = cast<VarDecl>(I.first);
1902*e038c9c4Sjoerg if (isa<ImplicitParamDecl>(D) &&
1903*e038c9c4Sjoerg D->getType() == getContext().VoidPtrTy) {
1904*e038c9c4Sjoerg assert(D->getName().startswith("frame_pointer"));
1905*e038c9c4Sjoerg FramePtrAddrAlloca = cast<llvm::AllocaInst>(I.second.getPointer());
1906*e038c9c4Sjoerg break;
1907*e038c9c4Sjoerg }
1908*e038c9c4Sjoerg }
1909*e038c9c4Sjoerg assert(FramePtrAddrAlloca);
1910*e038c9c4Sjoerg auto InsertPair = ParentCGF.EscapedLocals.insert(
1911*e038c9c4Sjoerg std::make_pair(FramePtrAddrAlloca, ParentCGF.EscapedLocals.size()));
1912*e038c9c4Sjoerg int FrameEscapeIdx = InsertPair.first->second;
1913*e038c9c4Sjoerg
1914*e038c9c4Sjoerg // an example of a filter's prolog::
1915*e038c9c4Sjoerg // %0 = call i8* @llvm.eh.recoverfp(bitcast(@"?fin$0@0@main@@"),..)
1916*e038c9c4Sjoerg // %1 = call i8* @llvm.localrecover(bitcast(@"?fin$0@0@main@@"),..)
1917*e038c9c4Sjoerg // %2 = bitcast i8* %1 to i8**
1918*e038c9c4Sjoerg // %3 = load i8*, i8* *%2, align 8
1919*e038c9c4Sjoerg // ==> %3 is the frame-pointer of outermost host function
1920*e038c9c4Sjoerg llvm::Function *FrameRecoverFn = llvm::Intrinsic::getDeclaration(
1921*e038c9c4Sjoerg &CGM.getModule(), llvm::Intrinsic::localrecover);
1922*e038c9c4Sjoerg llvm::Constant *ParentI8Fn =
1923*e038c9c4Sjoerg llvm::ConstantExpr::getBitCast(ParentCGF.CurFn, Int8PtrTy);
1924*e038c9c4Sjoerg ParentFP = Builder.CreateCall(
1925*e038c9c4Sjoerg FrameRecoverFn, {ParentI8Fn, ParentFP,
1926*e038c9c4Sjoerg llvm::ConstantInt::get(Int32Ty, FrameEscapeIdx)});
1927*e038c9c4Sjoerg ParentFP = Builder.CreateBitCast(ParentFP, CGM.VoidPtrPtrTy);
1928*e038c9c4Sjoerg ParentFP = Builder.CreateLoad(Address(ParentFP, getPointerAlign()));
1929*e038c9c4Sjoerg }
19307330f729Sjoerg }
19317330f729Sjoerg
19327330f729Sjoerg // Create llvm.localrecover calls for all captures.
19337330f729Sjoerg for (const VarDecl *VD : Finder.Captures) {
19347330f729Sjoerg if (VD->getType()->isVariablyModifiedType()) {
19357330f729Sjoerg CGM.ErrorUnsupported(VD, "VLA captured by SEH");
19367330f729Sjoerg continue;
19377330f729Sjoerg }
19387330f729Sjoerg assert((isa<ImplicitParamDecl>(VD) || VD->isLocalVarDeclOrParm()) &&
19397330f729Sjoerg "captured non-local variable");
19407330f729Sjoerg
1941*e038c9c4Sjoerg auto L = ParentCGF.LambdaCaptureFields.find(VD);
1942*e038c9c4Sjoerg if (L != ParentCGF.LambdaCaptureFields.end()) {
1943*e038c9c4Sjoerg LambdaCaptureFields[VD] = L->second;
1944*e038c9c4Sjoerg continue;
1945*e038c9c4Sjoerg }
1946*e038c9c4Sjoerg
19477330f729Sjoerg // If this decl hasn't been declared yet, it will be declared in the
19487330f729Sjoerg // OutlinedStmt.
19497330f729Sjoerg auto I = ParentCGF.LocalDeclMap.find(VD);
19507330f729Sjoerg if (I == ParentCGF.LocalDeclMap.end())
19517330f729Sjoerg continue;
19527330f729Sjoerg
19537330f729Sjoerg Address ParentVar = I->second;
1954*e038c9c4Sjoerg Address Recovered =
1955*e038c9c4Sjoerg recoverAddrOfEscapedLocal(ParentCGF, ParentVar, ParentFP);
1956*e038c9c4Sjoerg setAddrOfLocalVar(VD, Recovered);
1957*e038c9c4Sjoerg
1958*e038c9c4Sjoerg if (isa<ImplicitParamDecl>(VD)) {
1959*e038c9c4Sjoerg CXXABIThisAlignment = ParentCGF.CXXABIThisAlignment;
1960*e038c9c4Sjoerg CXXThisAlignment = ParentCGF.CXXThisAlignment;
1961*e038c9c4Sjoerg CXXABIThisValue = Builder.CreateLoad(Recovered, "this");
1962*e038c9c4Sjoerg if (ParentCGF.LambdaThisCaptureField) {
1963*e038c9c4Sjoerg LambdaThisCaptureField = ParentCGF.LambdaThisCaptureField;
1964*e038c9c4Sjoerg // We are in a lambda function where "this" is captured so the
1965*e038c9c4Sjoerg // CXXThisValue need to be loaded from the lambda capture
1966*e038c9c4Sjoerg LValue ThisFieldLValue =
1967*e038c9c4Sjoerg EmitLValueForLambdaField(LambdaThisCaptureField);
1968*e038c9c4Sjoerg if (!LambdaThisCaptureField->getType()->isPointerType()) {
1969*e038c9c4Sjoerg CXXThisValue = ThisFieldLValue.getAddress(*this).getPointer();
1970*e038c9c4Sjoerg } else {
1971*e038c9c4Sjoerg CXXThisValue = EmitLoadOfLValue(ThisFieldLValue, SourceLocation())
1972*e038c9c4Sjoerg .getScalarVal();
1973*e038c9c4Sjoerg }
1974*e038c9c4Sjoerg } else {
1975*e038c9c4Sjoerg CXXThisValue = CXXABIThisValue;
1976*e038c9c4Sjoerg }
1977*e038c9c4Sjoerg }
19787330f729Sjoerg }
19797330f729Sjoerg
19807330f729Sjoerg if (Finder.SEHCodeSlot.isValid()) {
19817330f729Sjoerg SEHCodeSlotStack.push_back(
19827330f729Sjoerg recoverAddrOfEscapedLocal(ParentCGF, Finder.SEHCodeSlot, ParentFP));
19837330f729Sjoerg }
19847330f729Sjoerg
19857330f729Sjoerg if (IsFilter)
19867330f729Sjoerg EmitSEHExceptionCodeSave(ParentCGF, ParentFP, EntryFP);
19877330f729Sjoerg }
19887330f729Sjoerg
19897330f729Sjoerg /// Arrange a function prototype that can be called by Windows exception
19907330f729Sjoerg /// handling personalities. On Win64, the prototype looks like:
19917330f729Sjoerg /// RetTy func(void *EHPtrs, void *ParentFP);
startOutlinedSEHHelper(CodeGenFunction & ParentCGF,bool IsFilter,const Stmt * OutlinedStmt)19927330f729Sjoerg void CodeGenFunction::startOutlinedSEHHelper(CodeGenFunction &ParentCGF,
19937330f729Sjoerg bool IsFilter,
19947330f729Sjoerg const Stmt *OutlinedStmt) {
19957330f729Sjoerg SourceLocation StartLoc = OutlinedStmt->getBeginLoc();
19967330f729Sjoerg
19977330f729Sjoerg // Get the mangled function name.
19987330f729Sjoerg SmallString<128> Name;
19997330f729Sjoerg {
20007330f729Sjoerg llvm::raw_svector_ostream OS(Name);
20017330f729Sjoerg const NamedDecl *ParentSEHFn = ParentCGF.CurSEHParent;
20027330f729Sjoerg assert(ParentSEHFn && "No CurSEHParent!");
20037330f729Sjoerg MangleContext &Mangler = CGM.getCXXABI().getMangleContext();
20047330f729Sjoerg if (IsFilter)
20057330f729Sjoerg Mangler.mangleSEHFilterExpression(ParentSEHFn, OS);
20067330f729Sjoerg else
20077330f729Sjoerg Mangler.mangleSEHFinallyBlock(ParentSEHFn, OS);
20087330f729Sjoerg }
20097330f729Sjoerg
20107330f729Sjoerg FunctionArgList Args;
20117330f729Sjoerg if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86 || !IsFilter) {
20127330f729Sjoerg // All SEH finally functions take two parameters. Win64 filters take two
20137330f729Sjoerg // parameters. Win32 filters take no parameters.
20147330f729Sjoerg if (IsFilter) {
20157330f729Sjoerg Args.push_back(ImplicitParamDecl::Create(
20167330f729Sjoerg getContext(), /*DC=*/nullptr, StartLoc,
20177330f729Sjoerg &getContext().Idents.get("exception_pointers"),
20187330f729Sjoerg getContext().VoidPtrTy, ImplicitParamDecl::Other));
20197330f729Sjoerg } else {
20207330f729Sjoerg Args.push_back(ImplicitParamDecl::Create(
20217330f729Sjoerg getContext(), /*DC=*/nullptr, StartLoc,
20227330f729Sjoerg &getContext().Idents.get("abnormal_termination"),
20237330f729Sjoerg getContext().UnsignedCharTy, ImplicitParamDecl::Other));
20247330f729Sjoerg }
20257330f729Sjoerg Args.push_back(ImplicitParamDecl::Create(
20267330f729Sjoerg getContext(), /*DC=*/nullptr, StartLoc,
20277330f729Sjoerg &getContext().Idents.get("frame_pointer"), getContext().VoidPtrTy,
20287330f729Sjoerg ImplicitParamDecl::Other));
20297330f729Sjoerg }
20307330f729Sjoerg
20317330f729Sjoerg QualType RetTy = IsFilter ? getContext().LongTy : getContext().VoidTy;
20327330f729Sjoerg
20337330f729Sjoerg const CGFunctionInfo &FnInfo =
20347330f729Sjoerg CGM.getTypes().arrangeBuiltinFunctionDeclaration(RetTy, Args);
20357330f729Sjoerg
20367330f729Sjoerg llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
20377330f729Sjoerg llvm::Function *Fn = llvm::Function::Create(
20387330f729Sjoerg FnTy, llvm::GlobalValue::InternalLinkage, Name.str(), &CGM.getModule());
20397330f729Sjoerg
20407330f729Sjoerg IsOutlinedSEHHelper = true;
20417330f729Sjoerg
20427330f729Sjoerg StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args,
20437330f729Sjoerg OutlinedStmt->getBeginLoc(), OutlinedStmt->getBeginLoc());
20447330f729Sjoerg CurSEHParent = ParentCGF.CurSEHParent;
20457330f729Sjoerg
2046*e038c9c4Sjoerg CGM.SetInternalFunctionAttributes(GlobalDecl(), CurFn, FnInfo);
20477330f729Sjoerg EmitCapturedLocals(ParentCGF, OutlinedStmt, IsFilter);
20487330f729Sjoerg }
20497330f729Sjoerg
20507330f729Sjoerg /// Create a stub filter function that will ultimately hold the code of the
20517330f729Sjoerg /// filter expression. The EH preparation passes in LLVM will outline the code
20527330f729Sjoerg /// from the main function body into this stub.
20537330f729Sjoerg llvm::Function *
GenerateSEHFilterFunction(CodeGenFunction & ParentCGF,const SEHExceptStmt & Except)20547330f729Sjoerg CodeGenFunction::GenerateSEHFilterFunction(CodeGenFunction &ParentCGF,
20557330f729Sjoerg const SEHExceptStmt &Except) {
20567330f729Sjoerg const Expr *FilterExpr = Except.getFilterExpr();
20577330f729Sjoerg startOutlinedSEHHelper(ParentCGF, true, FilterExpr);
20587330f729Sjoerg
20597330f729Sjoerg // Emit the original filter expression, convert to i32, and return.
20607330f729Sjoerg llvm::Value *R = EmitScalarExpr(FilterExpr);
20617330f729Sjoerg R = Builder.CreateIntCast(R, ConvertType(getContext().LongTy),
20627330f729Sjoerg FilterExpr->getType()->isSignedIntegerType());
20637330f729Sjoerg Builder.CreateStore(R, ReturnValue);
20647330f729Sjoerg
20657330f729Sjoerg FinishFunction(FilterExpr->getEndLoc());
20667330f729Sjoerg
20677330f729Sjoerg return CurFn;
20687330f729Sjoerg }
20697330f729Sjoerg
20707330f729Sjoerg llvm::Function *
GenerateSEHFinallyFunction(CodeGenFunction & ParentCGF,const SEHFinallyStmt & Finally)20717330f729Sjoerg CodeGenFunction::GenerateSEHFinallyFunction(CodeGenFunction &ParentCGF,
20727330f729Sjoerg const SEHFinallyStmt &Finally) {
20737330f729Sjoerg const Stmt *FinallyBlock = Finally.getBlock();
20747330f729Sjoerg startOutlinedSEHHelper(ParentCGF, false, FinallyBlock);
20757330f729Sjoerg
20767330f729Sjoerg // Emit the original filter expression, convert to i32, and return.
20777330f729Sjoerg EmitStmt(FinallyBlock);
20787330f729Sjoerg
20797330f729Sjoerg FinishFunction(FinallyBlock->getEndLoc());
20807330f729Sjoerg
20817330f729Sjoerg return CurFn;
20827330f729Sjoerg }
20837330f729Sjoerg
EmitSEHExceptionCodeSave(CodeGenFunction & ParentCGF,llvm::Value * ParentFP,llvm::Value * EntryFP)20847330f729Sjoerg void CodeGenFunction::EmitSEHExceptionCodeSave(CodeGenFunction &ParentCGF,
20857330f729Sjoerg llvm::Value *ParentFP,
20867330f729Sjoerg llvm::Value *EntryFP) {
20877330f729Sjoerg // Get the pointer to the EXCEPTION_POINTERS struct. This is returned by the
20887330f729Sjoerg // __exception_info intrinsic.
20897330f729Sjoerg if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
20907330f729Sjoerg // On Win64, the info is passed as the first parameter to the filter.
20917330f729Sjoerg SEHInfo = &*CurFn->arg_begin();
20927330f729Sjoerg SEHCodeSlotStack.push_back(
20937330f729Sjoerg CreateMemTemp(getContext().IntTy, "__exception_code"));
20947330f729Sjoerg } else {
20957330f729Sjoerg // On Win32, the EBP on entry to the filter points to the end of an
20967330f729Sjoerg // exception registration object. It contains 6 32-bit fields, and the info
20977330f729Sjoerg // pointer is stored in the second field. So, GEP 20 bytes backwards and
20987330f729Sjoerg // load the pointer.
20997330f729Sjoerg SEHInfo = Builder.CreateConstInBoundsGEP1_32(Int8Ty, EntryFP, -20);
21007330f729Sjoerg SEHInfo = Builder.CreateBitCast(SEHInfo, Int8PtrTy->getPointerTo());
21017330f729Sjoerg SEHInfo = Builder.CreateAlignedLoad(Int8PtrTy, SEHInfo, getPointerAlign());
21027330f729Sjoerg SEHCodeSlotStack.push_back(recoverAddrOfEscapedLocal(
21037330f729Sjoerg ParentCGF, ParentCGF.SEHCodeSlotStack.back(), ParentFP));
21047330f729Sjoerg }
21057330f729Sjoerg
21067330f729Sjoerg // Save the exception code in the exception slot to unify exception access in
21077330f729Sjoerg // the filter function and the landing pad.
21087330f729Sjoerg // struct EXCEPTION_POINTERS {
21097330f729Sjoerg // EXCEPTION_RECORD *ExceptionRecord;
21107330f729Sjoerg // CONTEXT *ContextRecord;
21117330f729Sjoerg // };
21127330f729Sjoerg // int exceptioncode = exception_pointers->ExceptionRecord->ExceptionCode;
21137330f729Sjoerg llvm::Type *RecordTy = CGM.Int32Ty->getPointerTo();
21147330f729Sjoerg llvm::Type *PtrsTy = llvm::StructType::get(RecordTy, CGM.VoidPtrTy);
21157330f729Sjoerg llvm::Value *Ptrs = Builder.CreateBitCast(SEHInfo, PtrsTy->getPointerTo());
21167330f729Sjoerg llvm::Value *Rec = Builder.CreateStructGEP(PtrsTy, Ptrs, 0);
2117*e038c9c4Sjoerg Rec = Builder.CreateAlignedLoad(RecordTy, Rec, getPointerAlign());
2118*e038c9c4Sjoerg llvm::Value *Code = Builder.CreateAlignedLoad(Int32Ty, Rec, getIntAlign());
21197330f729Sjoerg assert(!SEHCodeSlotStack.empty() && "emitting EH code outside of __except");
21207330f729Sjoerg Builder.CreateStore(Code, SEHCodeSlotStack.back());
21217330f729Sjoerg }
21227330f729Sjoerg
EmitSEHExceptionInfo()21237330f729Sjoerg llvm::Value *CodeGenFunction::EmitSEHExceptionInfo() {
21247330f729Sjoerg // Sema should diagnose calling this builtin outside of a filter context, but
21257330f729Sjoerg // don't crash if we screw up.
21267330f729Sjoerg if (!SEHInfo)
21277330f729Sjoerg return llvm::UndefValue::get(Int8PtrTy);
21287330f729Sjoerg assert(SEHInfo->getType() == Int8PtrTy);
21297330f729Sjoerg return SEHInfo;
21307330f729Sjoerg }
21317330f729Sjoerg
EmitSEHExceptionCode()21327330f729Sjoerg llvm::Value *CodeGenFunction::EmitSEHExceptionCode() {
21337330f729Sjoerg assert(!SEHCodeSlotStack.empty() && "emitting EH code outside of __except");
21347330f729Sjoerg return Builder.CreateLoad(SEHCodeSlotStack.back());
21357330f729Sjoerg }
21367330f729Sjoerg
EmitSEHAbnormalTermination()21377330f729Sjoerg llvm::Value *CodeGenFunction::EmitSEHAbnormalTermination() {
21387330f729Sjoerg // Abnormal termination is just the first parameter to the outlined finally
21397330f729Sjoerg // helper.
21407330f729Sjoerg auto AI = CurFn->arg_begin();
21417330f729Sjoerg return Builder.CreateZExt(&*AI, Int32Ty);
21427330f729Sjoerg }
21437330f729Sjoerg
pushSEHCleanup(CleanupKind Kind,llvm::Function * FinallyFunc)21447330f729Sjoerg void CodeGenFunction::pushSEHCleanup(CleanupKind Kind,
21457330f729Sjoerg llvm::Function *FinallyFunc) {
21467330f729Sjoerg EHStack.pushCleanup<PerformSEHFinally>(Kind, FinallyFunc);
21477330f729Sjoerg }
21487330f729Sjoerg
EnterSEHTryStmt(const SEHTryStmt & S)21497330f729Sjoerg void CodeGenFunction::EnterSEHTryStmt(const SEHTryStmt &S) {
21507330f729Sjoerg CodeGenFunction HelperCGF(CGM, /*suppressNewContext=*/true);
2151*e038c9c4Sjoerg HelperCGF.ParentCGF = this;
21527330f729Sjoerg if (const SEHFinallyStmt *Finally = S.getFinallyHandler()) {
21537330f729Sjoerg // Outline the finally block.
21547330f729Sjoerg llvm::Function *FinallyFunc =
21557330f729Sjoerg HelperCGF.GenerateSEHFinallyFunction(*this, *Finally);
21567330f729Sjoerg
21577330f729Sjoerg // Push a cleanup for __finally blocks.
21587330f729Sjoerg EHStack.pushCleanup<PerformSEHFinally>(NormalAndEHCleanup, FinallyFunc);
21597330f729Sjoerg return;
21607330f729Sjoerg }
21617330f729Sjoerg
21627330f729Sjoerg // Otherwise, we must have an __except block.
21637330f729Sjoerg const SEHExceptStmt *Except = S.getExceptHandler();
21647330f729Sjoerg assert(Except);
21657330f729Sjoerg EHCatchScope *CatchScope = EHStack.pushCatch(1);
21667330f729Sjoerg SEHCodeSlotStack.push_back(
21677330f729Sjoerg CreateMemTemp(getContext().IntTy, "__exception_code"));
21687330f729Sjoerg
21697330f729Sjoerg // If the filter is known to evaluate to 1, then we can use the clause
21707330f729Sjoerg // "catch i8* null". We can't do this on x86 because the filter has to save
21717330f729Sjoerg // the exception code.
21727330f729Sjoerg llvm::Constant *C =
21737330f729Sjoerg ConstantEmitter(*this).tryEmitAbstract(Except->getFilterExpr(),
21747330f729Sjoerg getContext().IntTy);
21757330f729Sjoerg if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86 && C &&
21767330f729Sjoerg C->isOneValue()) {
21777330f729Sjoerg CatchScope->setCatchAllHandler(0, createBasicBlock("__except"));
21787330f729Sjoerg return;
21797330f729Sjoerg }
21807330f729Sjoerg
21817330f729Sjoerg // In general, we have to emit an outlined filter function. Use the function
21827330f729Sjoerg // in place of the RTTI typeinfo global that C++ EH uses.
21837330f729Sjoerg llvm::Function *FilterFunc =
21847330f729Sjoerg HelperCGF.GenerateSEHFilterFunction(*this, *Except);
21857330f729Sjoerg llvm::Constant *OpaqueFunc =
21867330f729Sjoerg llvm::ConstantExpr::getBitCast(FilterFunc, Int8PtrTy);
21877330f729Sjoerg CatchScope->setHandler(0, OpaqueFunc, createBasicBlock("__except.ret"));
21887330f729Sjoerg }
21897330f729Sjoerg
ExitSEHTryStmt(const SEHTryStmt & S)21907330f729Sjoerg void CodeGenFunction::ExitSEHTryStmt(const SEHTryStmt &S) {
21917330f729Sjoerg // Just pop the cleanup if it's a __finally block.
21927330f729Sjoerg if (S.getFinallyHandler()) {
21937330f729Sjoerg PopCleanupBlock();
21947330f729Sjoerg return;
21957330f729Sjoerg }
21967330f729Sjoerg
2197*e038c9c4Sjoerg // IsEHa: emit an invoke _seh_try_end() to mark end of FT flow
2198*e038c9c4Sjoerg if (getLangOpts().EHAsynch && Builder.GetInsertBlock()) {
2199*e038c9c4Sjoerg llvm::FunctionCallee SehTryEnd = getSehTryEndFn(CGM);
2200*e038c9c4Sjoerg EmitRuntimeCallOrInvoke(SehTryEnd);
2201*e038c9c4Sjoerg }
2202*e038c9c4Sjoerg
22037330f729Sjoerg // Otherwise, we must have an __except block.
22047330f729Sjoerg const SEHExceptStmt *Except = S.getExceptHandler();
22057330f729Sjoerg assert(Except && "__try must have __finally xor __except");
22067330f729Sjoerg EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
22077330f729Sjoerg
22087330f729Sjoerg // Don't emit the __except block if the __try block lacked invokes.
22097330f729Sjoerg // TODO: Model unwind edges from instructions, either with iload / istore or
22107330f729Sjoerg // a try body function.
22117330f729Sjoerg if (!CatchScope.hasEHBranches()) {
22127330f729Sjoerg CatchScope.clearHandlerBlocks();
22137330f729Sjoerg EHStack.popCatch();
22147330f729Sjoerg SEHCodeSlotStack.pop_back();
22157330f729Sjoerg return;
22167330f729Sjoerg }
22177330f729Sjoerg
22187330f729Sjoerg // The fall-through block.
22197330f729Sjoerg llvm::BasicBlock *ContBB = createBasicBlock("__try.cont");
22207330f729Sjoerg
22217330f729Sjoerg // We just emitted the body of the __try; jump to the continue block.
22227330f729Sjoerg if (HaveInsertPoint())
22237330f729Sjoerg Builder.CreateBr(ContBB);
22247330f729Sjoerg
22257330f729Sjoerg // Check if our filter function returned true.
22267330f729Sjoerg emitCatchDispatchBlock(*this, CatchScope);
22277330f729Sjoerg
22287330f729Sjoerg // Grab the block before we pop the handler.
22297330f729Sjoerg llvm::BasicBlock *CatchPadBB = CatchScope.getHandler(0).Block;
22307330f729Sjoerg EHStack.popCatch();
22317330f729Sjoerg
22327330f729Sjoerg EmitBlockAfterUses(CatchPadBB);
22337330f729Sjoerg
22347330f729Sjoerg // __except blocks don't get outlined into funclets, so immediately do a
22357330f729Sjoerg // catchret.
22367330f729Sjoerg llvm::CatchPadInst *CPI =
22377330f729Sjoerg cast<llvm::CatchPadInst>(CatchPadBB->getFirstNonPHI());
22387330f729Sjoerg llvm::BasicBlock *ExceptBB = createBasicBlock("__except");
22397330f729Sjoerg Builder.CreateCatchRet(CPI, ExceptBB);
22407330f729Sjoerg EmitBlock(ExceptBB);
22417330f729Sjoerg
22427330f729Sjoerg // On Win64, the exception code is returned in EAX. Copy it into the slot.
22437330f729Sjoerg if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
22447330f729Sjoerg llvm::Function *SEHCodeIntrin =
22457330f729Sjoerg CGM.getIntrinsic(llvm::Intrinsic::eh_exceptioncode);
22467330f729Sjoerg llvm::Value *Code = Builder.CreateCall(SEHCodeIntrin, {CPI});
22477330f729Sjoerg Builder.CreateStore(Code, SEHCodeSlotStack.back());
22487330f729Sjoerg }
22497330f729Sjoerg
22507330f729Sjoerg // Emit the __except body.
22517330f729Sjoerg EmitStmt(Except->getBlock());
22527330f729Sjoerg
22537330f729Sjoerg // End the lifetime of the exception code.
22547330f729Sjoerg SEHCodeSlotStack.pop_back();
22557330f729Sjoerg
22567330f729Sjoerg if (HaveInsertPoint())
22577330f729Sjoerg Builder.CreateBr(ContBB);
22587330f729Sjoerg
22597330f729Sjoerg EmitBlock(ContBB);
22607330f729Sjoerg }
22617330f729Sjoerg
EmitSEHLeaveStmt(const SEHLeaveStmt & S)22627330f729Sjoerg void CodeGenFunction::EmitSEHLeaveStmt(const SEHLeaveStmt &S) {
22637330f729Sjoerg // If this code is reachable then emit a stop point (if generating
22647330f729Sjoerg // debug info). We have to do this ourselves because we are on the
22657330f729Sjoerg // "simple" statement path.
22667330f729Sjoerg if (HaveInsertPoint())
22677330f729Sjoerg EmitStopPoint(&S);
22687330f729Sjoerg
22697330f729Sjoerg // This must be a __leave from a __finally block, which we warn on and is UB.
22707330f729Sjoerg // Just emit unreachable.
22717330f729Sjoerg if (!isSEHTryScope()) {
22727330f729Sjoerg Builder.CreateUnreachable();
22737330f729Sjoerg Builder.ClearInsertionPoint();
22747330f729Sjoerg return;
22757330f729Sjoerg }
22767330f729Sjoerg
22777330f729Sjoerg EmitBranchThroughCleanup(*SEHTryEpilogueStack.back());
22787330f729Sjoerg }
2279