xref: /openbsd-src/gnu/llvm/clang/lib/CodeGen/CGException.cpp (revision 12c855180aad702bbcca06e0398d774beeafb155)
1e5dd7070Spatrick //===--- CGException.cpp - Emit LLVM Code for C++ exceptions ----*- C++ -*-===//
2e5dd7070Spatrick //
3e5dd7070Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e5dd7070Spatrick // See https://llvm.org/LICENSE.txt for license information.
5e5dd7070Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6e5dd7070Spatrick //
7e5dd7070Spatrick //===----------------------------------------------------------------------===//
8e5dd7070Spatrick //
9e5dd7070Spatrick // This contains code dealing with C++ exception related code generation.
10e5dd7070Spatrick //
11e5dd7070Spatrick //===----------------------------------------------------------------------===//
12e5dd7070Spatrick 
13e5dd7070Spatrick #include "CGCXXABI.h"
14e5dd7070Spatrick #include "CGCleanup.h"
15e5dd7070Spatrick #include "CGObjCRuntime.h"
16e5dd7070Spatrick #include "CodeGenFunction.h"
17e5dd7070Spatrick #include "ConstantEmitter.h"
18e5dd7070Spatrick #include "TargetInfo.h"
19e5dd7070Spatrick #include "clang/AST/Mangle.h"
20e5dd7070Spatrick #include "clang/AST/StmtCXX.h"
21e5dd7070Spatrick #include "clang/AST/StmtObjC.h"
22e5dd7070Spatrick #include "clang/AST/StmtVisitor.h"
23ec727ea7Spatrick #include "clang/Basic/DiagnosticSema.h"
24e5dd7070Spatrick #include "clang/Basic/TargetBuiltins.h"
25e5dd7070Spatrick #include "llvm/IR/IntrinsicInst.h"
26e5dd7070Spatrick #include "llvm/IR/Intrinsics.h"
27e5dd7070Spatrick #include "llvm/IR/IntrinsicsWebAssembly.h"
28e5dd7070Spatrick #include "llvm/Support/SaveAndRestore.h"
29e5dd7070Spatrick 
30e5dd7070Spatrick using namespace clang;
31e5dd7070Spatrick using namespace CodeGen;
32e5dd7070Spatrick 
getFreeExceptionFn(CodeGenModule & CGM)33e5dd7070Spatrick static llvm::FunctionCallee getFreeExceptionFn(CodeGenModule &CGM) {
34e5dd7070Spatrick   // void __cxa_free_exception(void *thrown_exception);
35e5dd7070Spatrick 
36e5dd7070Spatrick   llvm::FunctionType *FTy =
37e5dd7070Spatrick     llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*isVarArg=*/false);
38e5dd7070Spatrick 
39e5dd7070Spatrick   return CGM.CreateRuntimeFunction(FTy, "__cxa_free_exception");
40e5dd7070Spatrick }
41e5dd7070Spatrick 
getSehTryBeginFn(CodeGenModule & CGM)42a9ac8606Spatrick static llvm::FunctionCallee getSehTryBeginFn(CodeGenModule &CGM) {
43a9ac8606Spatrick   llvm::FunctionType *FTy =
44a9ac8606Spatrick       llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
45a9ac8606Spatrick   return CGM.CreateRuntimeFunction(FTy, "llvm.seh.try.begin");
46a9ac8606Spatrick }
47a9ac8606Spatrick 
getSehTryEndFn(CodeGenModule & CGM)48a9ac8606Spatrick static llvm::FunctionCallee getSehTryEndFn(CodeGenModule &CGM) {
49a9ac8606Spatrick   llvm::FunctionType *FTy =
50a9ac8606Spatrick       llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
51a9ac8606Spatrick   return CGM.CreateRuntimeFunction(FTy, "llvm.seh.try.end");
52a9ac8606Spatrick }
53a9ac8606Spatrick 
getUnexpectedFn(CodeGenModule & CGM)54e5dd7070Spatrick static llvm::FunctionCallee getUnexpectedFn(CodeGenModule &CGM) {
55e5dd7070Spatrick   // void __cxa_call_unexpected(void *thrown_exception);
56e5dd7070Spatrick 
57e5dd7070Spatrick   llvm::FunctionType *FTy =
58e5dd7070Spatrick     llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*isVarArg=*/false);
59e5dd7070Spatrick 
60e5dd7070Spatrick   return CGM.CreateRuntimeFunction(FTy, "__cxa_call_unexpected");
61e5dd7070Spatrick }
62e5dd7070Spatrick 
getTerminateFn()63e5dd7070Spatrick llvm::FunctionCallee CodeGenModule::getTerminateFn() {
64e5dd7070Spatrick   // void __terminate();
65e5dd7070Spatrick 
66e5dd7070Spatrick   llvm::FunctionType *FTy =
67e5dd7070Spatrick     llvm::FunctionType::get(VoidTy, /*isVarArg=*/false);
68e5dd7070Spatrick 
69e5dd7070Spatrick   StringRef name;
70e5dd7070Spatrick 
71e5dd7070Spatrick   // In C++, use std::terminate().
72e5dd7070Spatrick   if (getLangOpts().CPlusPlus &&
73e5dd7070Spatrick       getTarget().getCXXABI().isItaniumFamily()) {
74e5dd7070Spatrick     name = "_ZSt9terminatev";
75e5dd7070Spatrick   } else if (getLangOpts().CPlusPlus &&
76e5dd7070Spatrick              getTarget().getCXXABI().isMicrosoft()) {
77e5dd7070Spatrick     if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
78e5dd7070Spatrick       name = "__std_terminate";
79e5dd7070Spatrick     else
80e5dd7070Spatrick       name = "?terminate@@YAXXZ";
81e5dd7070Spatrick   } else if (getLangOpts().ObjC &&
82e5dd7070Spatrick              getLangOpts().ObjCRuntime.hasTerminate())
83e5dd7070Spatrick     name = "objc_terminate";
84e5dd7070Spatrick   else
85e5dd7070Spatrick     name = "abort";
86e5dd7070Spatrick   return CreateRuntimeFunction(FTy, name);
87e5dd7070Spatrick }
88e5dd7070Spatrick 
getCatchallRethrowFn(CodeGenModule & CGM,StringRef Name)89e5dd7070Spatrick static llvm::FunctionCallee getCatchallRethrowFn(CodeGenModule &CGM,
90e5dd7070Spatrick                                                  StringRef Name) {
91e5dd7070Spatrick   llvm::FunctionType *FTy =
92e5dd7070Spatrick     llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*isVarArg=*/false);
93e5dd7070Spatrick 
94e5dd7070Spatrick   return CGM.CreateRuntimeFunction(FTy, Name);
95e5dd7070Spatrick }
96e5dd7070Spatrick 
97e5dd7070Spatrick const EHPersonality EHPersonality::GNU_C = { "__gcc_personality_v0", nullptr };
98e5dd7070Spatrick const EHPersonality
99e5dd7070Spatrick EHPersonality::GNU_C_SJLJ = { "__gcc_personality_sj0", nullptr };
100e5dd7070Spatrick const EHPersonality
101e5dd7070Spatrick EHPersonality::GNU_C_SEH = { "__gcc_personality_seh0", nullptr };
102e5dd7070Spatrick const EHPersonality
103e5dd7070Spatrick EHPersonality::NeXT_ObjC = { "__objc_personality_v0", nullptr };
104e5dd7070Spatrick const EHPersonality
105e5dd7070Spatrick EHPersonality::GNU_CPlusPlus = { "__gxx_personality_v0", nullptr };
106e5dd7070Spatrick const EHPersonality
107e5dd7070Spatrick EHPersonality::GNU_CPlusPlus_SJLJ = { "__gxx_personality_sj0", nullptr };
108e5dd7070Spatrick const EHPersonality
109e5dd7070Spatrick EHPersonality::GNU_CPlusPlus_SEH = { "__gxx_personality_seh0", nullptr };
110e5dd7070Spatrick const EHPersonality
111e5dd7070Spatrick EHPersonality::GNU_ObjC = {"__gnu_objc_personality_v0", "objc_exception_throw"};
112e5dd7070Spatrick const EHPersonality
113e5dd7070Spatrick EHPersonality::GNU_ObjC_SJLJ = {"__gnu_objc_personality_sj0", "objc_exception_throw"};
114e5dd7070Spatrick const EHPersonality
115e5dd7070Spatrick EHPersonality::GNU_ObjC_SEH = {"__gnu_objc_personality_seh0", "objc_exception_throw"};
116e5dd7070Spatrick const EHPersonality
117e5dd7070Spatrick EHPersonality::GNU_ObjCXX = { "__gnustep_objcxx_personality_v0", nullptr };
118e5dd7070Spatrick const EHPersonality
119e5dd7070Spatrick EHPersonality::GNUstep_ObjC = { "__gnustep_objc_personality_v0", nullptr };
120e5dd7070Spatrick const EHPersonality
121e5dd7070Spatrick EHPersonality::MSVC_except_handler = { "_except_handler3", nullptr };
122e5dd7070Spatrick const EHPersonality
123e5dd7070Spatrick EHPersonality::MSVC_C_specific_handler = { "__C_specific_handler", nullptr };
124e5dd7070Spatrick const EHPersonality
125e5dd7070Spatrick EHPersonality::MSVC_CxxFrameHandler3 = { "__CxxFrameHandler3", nullptr };
126e5dd7070Spatrick const EHPersonality
127e5dd7070Spatrick EHPersonality::GNU_Wasm_CPlusPlus = { "__gxx_wasm_personality_v0", nullptr };
128a9ac8606Spatrick const EHPersonality EHPersonality::XL_CPlusPlus = {"__xlcxx_personality_v1",
129a9ac8606Spatrick                                                    nullptr};
130e5dd7070Spatrick 
getCPersonality(const TargetInfo & Target,const LangOptions & L)131e5dd7070Spatrick static const EHPersonality &getCPersonality(const TargetInfo &Target,
132e5dd7070Spatrick                                             const LangOptions &L) {
133e5dd7070Spatrick   const llvm::Triple &T = Target.getTriple();
134e5dd7070Spatrick   if (T.isWindowsMSVCEnvironment())
135e5dd7070Spatrick     return EHPersonality::MSVC_CxxFrameHandler3;
136a9ac8606Spatrick   if (L.hasSjLjExceptions())
137e5dd7070Spatrick     return EHPersonality::GNU_C_SJLJ;
138a9ac8606Spatrick   if (L.hasDWARFExceptions())
139e5dd7070Spatrick     return EHPersonality::GNU_C;
140a9ac8606Spatrick   if (L.hasSEHExceptions())
141e5dd7070Spatrick     return EHPersonality::GNU_C_SEH;
142e5dd7070Spatrick   return EHPersonality::GNU_C;
143e5dd7070Spatrick }
144e5dd7070Spatrick 
getObjCPersonality(const TargetInfo & Target,const LangOptions & L)145e5dd7070Spatrick static const EHPersonality &getObjCPersonality(const TargetInfo &Target,
146e5dd7070Spatrick                                                const LangOptions &L) {
147e5dd7070Spatrick   const llvm::Triple &T = Target.getTriple();
148e5dd7070Spatrick   if (T.isWindowsMSVCEnvironment())
149e5dd7070Spatrick     return EHPersonality::MSVC_CxxFrameHandler3;
150e5dd7070Spatrick 
151e5dd7070Spatrick   switch (L.ObjCRuntime.getKind()) {
152e5dd7070Spatrick   case ObjCRuntime::FragileMacOSX:
153e5dd7070Spatrick     return getCPersonality(Target, L);
154e5dd7070Spatrick   case ObjCRuntime::MacOSX:
155e5dd7070Spatrick   case ObjCRuntime::iOS:
156e5dd7070Spatrick   case ObjCRuntime::WatchOS:
157e5dd7070Spatrick     return EHPersonality::NeXT_ObjC;
158e5dd7070Spatrick   case ObjCRuntime::GNUstep:
159e5dd7070Spatrick     if (L.ObjCRuntime.getVersion() >= VersionTuple(1, 7))
160e5dd7070Spatrick       return EHPersonality::GNUstep_ObjC;
161*12c85518Srobert     [[fallthrough]];
162e5dd7070Spatrick   case ObjCRuntime::GCC:
163e5dd7070Spatrick   case ObjCRuntime::ObjFW:
164a9ac8606Spatrick     if (L.hasSjLjExceptions())
165e5dd7070Spatrick       return EHPersonality::GNU_ObjC_SJLJ;
166a9ac8606Spatrick     if (L.hasSEHExceptions())
167e5dd7070Spatrick       return EHPersonality::GNU_ObjC_SEH;
168e5dd7070Spatrick     return EHPersonality::GNU_ObjC;
169e5dd7070Spatrick   }
170e5dd7070Spatrick   llvm_unreachable("bad runtime kind");
171e5dd7070Spatrick }
172e5dd7070Spatrick 
getCXXPersonality(const TargetInfo & Target,const LangOptions & L)173e5dd7070Spatrick static const EHPersonality &getCXXPersonality(const TargetInfo &Target,
174e5dd7070Spatrick                                               const LangOptions &L) {
175e5dd7070Spatrick   const llvm::Triple &T = Target.getTriple();
176e5dd7070Spatrick   if (T.isWindowsMSVCEnvironment())
177e5dd7070Spatrick     return EHPersonality::MSVC_CxxFrameHandler3;
178a9ac8606Spatrick   if (T.isOSAIX())
179a9ac8606Spatrick     return EHPersonality::XL_CPlusPlus;
180a9ac8606Spatrick   if (L.hasSjLjExceptions())
181e5dd7070Spatrick     return EHPersonality::GNU_CPlusPlus_SJLJ;
182a9ac8606Spatrick   if (L.hasDWARFExceptions())
183e5dd7070Spatrick     return EHPersonality::GNU_CPlusPlus;
184a9ac8606Spatrick   if (L.hasSEHExceptions())
185e5dd7070Spatrick     return EHPersonality::GNU_CPlusPlus_SEH;
186a9ac8606Spatrick   if (L.hasWasmExceptions())
187e5dd7070Spatrick     return EHPersonality::GNU_Wasm_CPlusPlus;
188e5dd7070Spatrick   return EHPersonality::GNU_CPlusPlus;
189e5dd7070Spatrick }
190e5dd7070Spatrick 
191e5dd7070Spatrick /// Determines the personality function to use when both C++
192e5dd7070Spatrick /// and Objective-C exceptions are being caught.
getObjCXXPersonality(const TargetInfo & Target,const LangOptions & L)193e5dd7070Spatrick static const EHPersonality &getObjCXXPersonality(const TargetInfo &Target,
194e5dd7070Spatrick                                                  const LangOptions &L) {
195e5dd7070Spatrick   if (Target.getTriple().isWindowsMSVCEnvironment())
196e5dd7070Spatrick     return EHPersonality::MSVC_CxxFrameHandler3;
197e5dd7070Spatrick 
198e5dd7070Spatrick   switch (L.ObjCRuntime.getKind()) {
199e5dd7070Spatrick   // In the fragile ABI, just use C++ exception handling and hope
200e5dd7070Spatrick   // they're not doing crazy exception mixing.
201e5dd7070Spatrick   case ObjCRuntime::FragileMacOSX:
202e5dd7070Spatrick     return getCXXPersonality(Target, L);
203e5dd7070Spatrick 
204e5dd7070Spatrick   // The ObjC personality defers to the C++ personality for non-ObjC
205e5dd7070Spatrick   // handlers.  Unlike the C++ case, we use the same personality
206e5dd7070Spatrick   // function on targets using (backend-driven) SJLJ EH.
207e5dd7070Spatrick   case ObjCRuntime::MacOSX:
208e5dd7070Spatrick   case ObjCRuntime::iOS:
209e5dd7070Spatrick   case ObjCRuntime::WatchOS:
210e5dd7070Spatrick     return getObjCPersonality(Target, L);
211e5dd7070Spatrick 
212e5dd7070Spatrick   case ObjCRuntime::GNUstep:
213e5dd7070Spatrick     return EHPersonality::GNU_ObjCXX;
214e5dd7070Spatrick 
215e5dd7070Spatrick   // The GCC runtime's personality function inherently doesn't support
216e5dd7070Spatrick   // mixed EH.  Use the ObjC personality just to avoid returning null.
217e5dd7070Spatrick   case ObjCRuntime::GCC:
218e5dd7070Spatrick   case ObjCRuntime::ObjFW:
219e5dd7070Spatrick     return getObjCPersonality(Target, L);
220e5dd7070Spatrick   }
221e5dd7070Spatrick   llvm_unreachable("bad runtime kind");
222e5dd7070Spatrick }
223e5dd7070Spatrick 
getSEHPersonalityMSVC(const llvm::Triple & T)224e5dd7070Spatrick static const EHPersonality &getSEHPersonalityMSVC(const llvm::Triple &T) {
225e5dd7070Spatrick   if (T.getArch() == llvm::Triple::x86)
226e5dd7070Spatrick     return EHPersonality::MSVC_except_handler;
227e5dd7070Spatrick   return EHPersonality::MSVC_C_specific_handler;
228e5dd7070Spatrick }
229e5dd7070Spatrick 
get(CodeGenModule & CGM,const FunctionDecl * FD)230e5dd7070Spatrick const EHPersonality &EHPersonality::get(CodeGenModule &CGM,
231e5dd7070Spatrick                                         const FunctionDecl *FD) {
232e5dd7070Spatrick   const llvm::Triple &T = CGM.getTarget().getTriple();
233e5dd7070Spatrick   const LangOptions &L = CGM.getLangOpts();
234e5dd7070Spatrick   const TargetInfo &Target = CGM.getTarget();
235e5dd7070Spatrick 
236e5dd7070Spatrick   // Functions using SEH get an SEH personality.
237e5dd7070Spatrick   if (FD && FD->usesSEHTry())
238e5dd7070Spatrick     return getSEHPersonalityMSVC(T);
239e5dd7070Spatrick 
240e5dd7070Spatrick   if (L.ObjC)
241e5dd7070Spatrick     return L.CPlusPlus ? getObjCXXPersonality(Target, L)
242e5dd7070Spatrick                        : getObjCPersonality(Target, L);
243e5dd7070Spatrick   return L.CPlusPlus ? getCXXPersonality(Target, L)
244e5dd7070Spatrick                      : getCPersonality(Target, L);
245e5dd7070Spatrick }
246e5dd7070Spatrick 
get(CodeGenFunction & CGF)247e5dd7070Spatrick const EHPersonality &EHPersonality::get(CodeGenFunction &CGF) {
248e5dd7070Spatrick   const auto *FD = CGF.CurCodeDecl;
249e5dd7070Spatrick   // For outlined finallys and filters, use the SEH personality in case they
250e5dd7070Spatrick   // contain more SEH. This mostly only affects finallys. Filters could
251e5dd7070Spatrick   // hypothetically use gnu statement expressions to sneak in nested SEH.
252*12c85518Srobert   FD = FD ? FD : CGF.CurSEHParent.getDecl();
253e5dd7070Spatrick   return get(CGF.CGM, dyn_cast_or_null<FunctionDecl>(FD));
254e5dd7070Spatrick }
255e5dd7070Spatrick 
getPersonalityFn(CodeGenModule & CGM,const EHPersonality & Personality)256e5dd7070Spatrick static llvm::FunctionCallee getPersonalityFn(CodeGenModule &CGM,
257e5dd7070Spatrick                                              const EHPersonality &Personality) {
258e5dd7070Spatrick   return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.Int32Ty, true),
259e5dd7070Spatrick                                    Personality.PersonalityFn,
260e5dd7070Spatrick                                    llvm::AttributeList(), /*Local=*/true);
261e5dd7070Spatrick }
262e5dd7070Spatrick 
getOpaquePersonalityFn(CodeGenModule & CGM,const EHPersonality & Personality)263e5dd7070Spatrick static llvm::Constant *getOpaquePersonalityFn(CodeGenModule &CGM,
264e5dd7070Spatrick                                         const EHPersonality &Personality) {
265e5dd7070Spatrick   llvm::FunctionCallee Fn = getPersonalityFn(CGM, Personality);
266e5dd7070Spatrick   llvm::PointerType* Int8PtrTy = llvm::PointerType::get(
267e5dd7070Spatrick       llvm::Type::getInt8Ty(CGM.getLLVMContext()),
268e5dd7070Spatrick       CGM.getDataLayout().getProgramAddressSpace());
269e5dd7070Spatrick 
270e5dd7070Spatrick   return llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(Fn.getCallee()),
271e5dd7070Spatrick                                         Int8PtrTy);
272e5dd7070Spatrick }
273e5dd7070Spatrick 
274e5dd7070Spatrick /// Check whether a landingpad instruction only uses C++ features.
LandingPadHasOnlyCXXUses(llvm::LandingPadInst * LPI)275e5dd7070Spatrick static bool LandingPadHasOnlyCXXUses(llvm::LandingPadInst *LPI) {
276e5dd7070Spatrick   for (unsigned I = 0, E = LPI->getNumClauses(); I != E; ++I) {
277e5dd7070Spatrick     // Look for something that would've been returned by the ObjC
278e5dd7070Spatrick     // runtime's GetEHType() method.
279e5dd7070Spatrick     llvm::Value *Val = LPI->getClause(I)->stripPointerCasts();
280e5dd7070Spatrick     if (LPI->isCatch(I)) {
281e5dd7070Spatrick       // Check if the catch value has the ObjC prefix.
282e5dd7070Spatrick       if (llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Val))
283e5dd7070Spatrick         // ObjC EH selector entries are always global variables with
284e5dd7070Spatrick         // names starting like this.
285e5dd7070Spatrick         if (GV->getName().startswith("OBJC_EHTYPE"))
286e5dd7070Spatrick           return false;
287e5dd7070Spatrick     } else {
288e5dd7070Spatrick       // Check if any of the filter values have the ObjC prefix.
289e5dd7070Spatrick       llvm::Constant *CVal = cast<llvm::Constant>(Val);
290e5dd7070Spatrick       for (llvm::User::op_iterator
291e5dd7070Spatrick               II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II) {
292e5dd7070Spatrick         if (llvm::GlobalVariable *GV =
293e5dd7070Spatrick             cast<llvm::GlobalVariable>((*II)->stripPointerCasts()))
294e5dd7070Spatrick           // ObjC EH selector entries are always global variables with
295e5dd7070Spatrick           // names starting like this.
296e5dd7070Spatrick           if (GV->getName().startswith("OBJC_EHTYPE"))
297e5dd7070Spatrick             return false;
298e5dd7070Spatrick       }
299e5dd7070Spatrick     }
300e5dd7070Spatrick   }
301e5dd7070Spatrick   return true;
302e5dd7070Spatrick }
303e5dd7070Spatrick 
304e5dd7070Spatrick /// Check whether a personality function could reasonably be swapped
305e5dd7070Spatrick /// for a C++ personality function.
PersonalityHasOnlyCXXUses(llvm::Constant * Fn)306e5dd7070Spatrick static bool PersonalityHasOnlyCXXUses(llvm::Constant *Fn) {
307e5dd7070Spatrick   for (llvm::User *U : Fn->users()) {
308e5dd7070Spatrick     // Conditionally white-list bitcasts.
309e5dd7070Spatrick     if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(U)) {
310e5dd7070Spatrick       if (CE->getOpcode() != llvm::Instruction::BitCast) return false;
311e5dd7070Spatrick       if (!PersonalityHasOnlyCXXUses(CE))
312e5dd7070Spatrick         return false;
313e5dd7070Spatrick       continue;
314e5dd7070Spatrick     }
315e5dd7070Spatrick 
316e5dd7070Spatrick     // Otherwise it must be a function.
317e5dd7070Spatrick     llvm::Function *F = dyn_cast<llvm::Function>(U);
318e5dd7070Spatrick     if (!F) return false;
319e5dd7070Spatrick 
320e5dd7070Spatrick     for (auto BB = F->begin(), E = F->end(); BB != E; ++BB) {
321e5dd7070Spatrick       if (BB->isLandingPad())
322e5dd7070Spatrick         if (!LandingPadHasOnlyCXXUses(BB->getLandingPadInst()))
323e5dd7070Spatrick           return false;
324e5dd7070Spatrick     }
325e5dd7070Spatrick   }
326e5dd7070Spatrick 
327e5dd7070Spatrick   return true;
328e5dd7070Spatrick }
329e5dd7070Spatrick 
330e5dd7070Spatrick /// Try to use the C++ personality function in ObjC++.  Not doing this
331e5dd7070Spatrick /// can cause some incompatibilities with gcc, which is more
332e5dd7070Spatrick /// aggressive about only using the ObjC++ personality in a function
333e5dd7070Spatrick /// when it really needs it.
SimplifyPersonality()334e5dd7070Spatrick void CodeGenModule::SimplifyPersonality() {
335e5dd7070Spatrick   // If we're not in ObjC++ -fexceptions, there's nothing to do.
336e5dd7070Spatrick   if (!LangOpts.CPlusPlus || !LangOpts.ObjC || !LangOpts.Exceptions)
337e5dd7070Spatrick     return;
338e5dd7070Spatrick 
339e5dd7070Spatrick   // Both the problem this endeavors to fix and the way the logic
340e5dd7070Spatrick   // above works is specific to the NeXT runtime.
341e5dd7070Spatrick   if (!LangOpts.ObjCRuntime.isNeXTFamily())
342e5dd7070Spatrick     return;
343e5dd7070Spatrick 
344e5dd7070Spatrick   const EHPersonality &ObjCXX = EHPersonality::get(*this, /*FD=*/nullptr);
345e5dd7070Spatrick   const EHPersonality &CXX = getCXXPersonality(getTarget(), LangOpts);
346e5dd7070Spatrick   if (&ObjCXX == &CXX)
347e5dd7070Spatrick     return;
348e5dd7070Spatrick 
349e5dd7070Spatrick   assert(std::strcmp(ObjCXX.PersonalityFn, CXX.PersonalityFn) != 0 &&
350e5dd7070Spatrick          "Different EHPersonalities using the same personality function.");
351e5dd7070Spatrick 
352e5dd7070Spatrick   llvm::Function *Fn = getModule().getFunction(ObjCXX.PersonalityFn);
353e5dd7070Spatrick 
354e5dd7070Spatrick   // Nothing to do if it's unused.
355e5dd7070Spatrick   if (!Fn || Fn->use_empty()) return;
356e5dd7070Spatrick 
357e5dd7070Spatrick   // Can't do the optimization if it has non-C++ uses.
358e5dd7070Spatrick   if (!PersonalityHasOnlyCXXUses(Fn)) return;
359e5dd7070Spatrick 
360e5dd7070Spatrick   // Create the C++ personality function and kill off the old
361e5dd7070Spatrick   // function.
362e5dd7070Spatrick   llvm::FunctionCallee CXXFn = getPersonalityFn(*this, CXX);
363e5dd7070Spatrick 
364e5dd7070Spatrick   // This can happen if the user is screwing with us.
365e5dd7070Spatrick   if (Fn->getType() != CXXFn.getCallee()->getType())
366e5dd7070Spatrick     return;
367e5dd7070Spatrick 
368e5dd7070Spatrick   Fn->replaceAllUsesWith(CXXFn.getCallee());
369e5dd7070Spatrick   Fn->eraseFromParent();
370e5dd7070Spatrick }
371e5dd7070Spatrick 
372e5dd7070Spatrick /// Returns the value to inject into a selector to indicate the
373e5dd7070Spatrick /// presence of a catch-all.
getCatchAllValue(CodeGenFunction & CGF)374e5dd7070Spatrick static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
375e5dd7070Spatrick   // Possibly we should use @llvm.eh.catch.all.value here.
376e5dd7070Spatrick   return llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
377e5dd7070Spatrick }
378e5dd7070Spatrick 
379e5dd7070Spatrick namespace {
380e5dd7070Spatrick   /// A cleanup to free the exception object if its initialization
381e5dd7070Spatrick   /// throws.
382e5dd7070Spatrick   struct FreeException final : EHScopeStack::Cleanup {
383e5dd7070Spatrick     llvm::Value *exn;
FreeException__anon650da12e0111::FreeException384e5dd7070Spatrick     FreeException(llvm::Value *exn) : exn(exn) {}
Emit__anon650da12e0111::FreeException385e5dd7070Spatrick     void Emit(CodeGenFunction &CGF, Flags flags) override {
386e5dd7070Spatrick       CGF.EmitNounwindRuntimeCall(getFreeExceptionFn(CGF.CGM), exn);
387e5dd7070Spatrick     }
388e5dd7070Spatrick   };
389e5dd7070Spatrick } // end anonymous namespace
390e5dd7070Spatrick 
391e5dd7070Spatrick // Emits an exception expression into the given location.  This
392e5dd7070Spatrick // differs from EmitAnyExprToMem only in that, if a final copy-ctor
393e5dd7070Spatrick // call is required, an exception within that copy ctor causes
394e5dd7070Spatrick // std::terminate to be invoked.
EmitAnyExprToExn(const Expr * e,Address addr)395e5dd7070Spatrick void CodeGenFunction::EmitAnyExprToExn(const Expr *e, Address addr) {
396e5dd7070Spatrick   // Make sure the exception object is cleaned up if there's an
397e5dd7070Spatrick   // exception during initialization.
398e5dd7070Spatrick   pushFullExprCleanup<FreeException>(EHCleanup, addr.getPointer());
399e5dd7070Spatrick   EHScopeStack::stable_iterator cleanup = EHStack.stable_begin();
400e5dd7070Spatrick 
401e5dd7070Spatrick   // __cxa_allocate_exception returns a void*;  we need to cast this
402e5dd7070Spatrick   // to the appropriate type for the object.
403*12c85518Srobert   llvm::Type *ty = ConvertTypeForMem(e->getType());
404*12c85518Srobert   Address typedAddr = Builder.CreateElementBitCast(addr, ty);
405e5dd7070Spatrick 
406e5dd7070Spatrick   // FIXME: this isn't quite right!  If there's a final unelided call
407e5dd7070Spatrick   // to a copy constructor, then according to [except.terminate]p1 we
408e5dd7070Spatrick   // must call std::terminate() if that constructor throws, because
409e5dd7070Spatrick   // technically that copy occurs after the exception expression is
410e5dd7070Spatrick   // evaluated but before the exception is caught.  But the best way
411e5dd7070Spatrick   // to handle that is to teach EmitAggExpr to do the final copy
412e5dd7070Spatrick   // differently if it can't be elided.
413e5dd7070Spatrick   EmitAnyExprToMem(e, typedAddr, e->getType().getQualifiers(),
414e5dd7070Spatrick                    /*IsInit*/ true);
415e5dd7070Spatrick 
416e5dd7070Spatrick   // Deactivate the cleanup block.
417e5dd7070Spatrick   DeactivateCleanupBlock(cleanup,
418e5dd7070Spatrick                          cast<llvm::Instruction>(typedAddr.getPointer()));
419e5dd7070Spatrick }
420e5dd7070Spatrick 
getExceptionSlot()421e5dd7070Spatrick Address CodeGenFunction::getExceptionSlot() {
422e5dd7070Spatrick   if (!ExceptionSlot)
423e5dd7070Spatrick     ExceptionSlot = CreateTempAlloca(Int8PtrTy, "exn.slot");
424*12c85518Srobert   return Address(ExceptionSlot, Int8PtrTy, getPointerAlign());
425e5dd7070Spatrick }
426e5dd7070Spatrick 
getEHSelectorSlot()427e5dd7070Spatrick Address CodeGenFunction::getEHSelectorSlot() {
428e5dd7070Spatrick   if (!EHSelectorSlot)
429e5dd7070Spatrick     EHSelectorSlot = CreateTempAlloca(Int32Ty, "ehselector.slot");
430*12c85518Srobert   return Address(EHSelectorSlot, Int32Ty, CharUnits::fromQuantity(4));
431e5dd7070Spatrick }
432e5dd7070Spatrick 
getExceptionFromSlot()433e5dd7070Spatrick llvm::Value *CodeGenFunction::getExceptionFromSlot() {
434e5dd7070Spatrick   return Builder.CreateLoad(getExceptionSlot(), "exn");
435e5dd7070Spatrick }
436e5dd7070Spatrick 
getSelectorFromSlot()437e5dd7070Spatrick llvm::Value *CodeGenFunction::getSelectorFromSlot() {
438e5dd7070Spatrick   return Builder.CreateLoad(getEHSelectorSlot(), "sel");
439e5dd7070Spatrick }
440e5dd7070Spatrick 
EmitCXXThrowExpr(const CXXThrowExpr * E,bool KeepInsertionPoint)441e5dd7070Spatrick void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E,
442e5dd7070Spatrick                                        bool KeepInsertionPoint) {
443e5dd7070Spatrick   if (const Expr *SubExpr = E->getSubExpr()) {
444e5dd7070Spatrick     QualType ThrowType = SubExpr->getType();
445e5dd7070Spatrick     if (ThrowType->isObjCObjectPointerType()) {
446e5dd7070Spatrick       const Stmt *ThrowStmt = E->getSubExpr();
447e5dd7070Spatrick       const ObjCAtThrowStmt S(E->getExprLoc(), const_cast<Stmt *>(ThrowStmt));
448e5dd7070Spatrick       CGM.getObjCRuntime().EmitThrowStmt(*this, S, false);
449e5dd7070Spatrick     } else {
450e5dd7070Spatrick       CGM.getCXXABI().emitThrow(*this, E);
451e5dd7070Spatrick     }
452e5dd7070Spatrick   } else {
453e5dd7070Spatrick     CGM.getCXXABI().emitRethrow(*this, /*isNoReturn=*/true);
454e5dd7070Spatrick   }
455e5dd7070Spatrick 
456e5dd7070Spatrick   // throw is an expression, and the expression emitters expect us
457e5dd7070Spatrick   // to leave ourselves at a valid insertion point.
458e5dd7070Spatrick   if (KeepInsertionPoint)
459e5dd7070Spatrick     EmitBlock(createBasicBlock("throw.cont"));
460e5dd7070Spatrick }
461e5dd7070Spatrick 
EmitStartEHSpec(const Decl * D)462e5dd7070Spatrick void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
463e5dd7070Spatrick   if (!CGM.getLangOpts().CXXExceptions)
464e5dd7070Spatrick     return;
465e5dd7070Spatrick 
466e5dd7070Spatrick   const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
467e5dd7070Spatrick   if (!FD) {
468e5dd7070Spatrick     // Check if CapturedDecl is nothrow and create terminate scope for it.
469e5dd7070Spatrick     if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
470e5dd7070Spatrick       if (CD->isNothrow())
471e5dd7070Spatrick         EHStack.pushTerminate();
472e5dd7070Spatrick     }
473e5dd7070Spatrick     return;
474e5dd7070Spatrick   }
475e5dd7070Spatrick   const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
476e5dd7070Spatrick   if (!Proto)
477e5dd7070Spatrick     return;
478e5dd7070Spatrick 
479e5dd7070Spatrick   ExceptionSpecificationType EST = Proto->getExceptionSpecType();
480*12c85518Srobert   // In C++17 and later, 'throw()' aka EST_DynamicNone is treated the same way
481*12c85518Srobert   // as noexcept. In earlier standards, it is handled in this block, along with
482*12c85518Srobert   // 'throw(X...)'.
483*12c85518Srobert   if (EST == EST_Dynamic ||
484*12c85518Srobert       (EST == EST_DynamicNone && !getLangOpts().CPlusPlus17)) {
485e5dd7070Spatrick     // TODO: Revisit exception specifications for the MS ABI.  There is a way to
486e5dd7070Spatrick     // encode these in an object file but MSVC doesn't do anything with it.
487e5dd7070Spatrick     if (getTarget().getCXXABI().isMicrosoft())
488e5dd7070Spatrick       return;
489a9ac8606Spatrick     // In Wasm EH we currently treat 'throw()' in the same way as 'noexcept'. In
490ec727ea7Spatrick     // case of throw with types, we ignore it and print a warning for now.
491a9ac8606Spatrick     // TODO Correctly handle exception specification in Wasm EH
492a9ac8606Spatrick     if (CGM.getLangOpts().hasWasmExceptions()) {
493ec727ea7Spatrick       if (EST == EST_DynamicNone)
494ec727ea7Spatrick         EHStack.pushTerminate();
495ec727ea7Spatrick       else
496ec727ea7Spatrick         CGM.getDiags().Report(D->getLocation(),
497ec727ea7Spatrick                               diag::warn_wasm_dynamic_exception_spec_ignored)
498ec727ea7Spatrick             << FD->getExceptionSpecSourceRange();
499ec727ea7Spatrick       return;
500ec727ea7Spatrick     }
501a9ac8606Spatrick     // Currently Emscripten EH only handles 'throw()' but not 'throw' with
502a9ac8606Spatrick     // types. 'throw()' handling will be done in JS glue code so we don't need
503a9ac8606Spatrick     // to do anything in that case. Just print a warning message in case of
504a9ac8606Spatrick     // throw with types.
505a9ac8606Spatrick     // TODO Correctly handle exception specification in Emscripten EH
506a9ac8606Spatrick     if (getTarget().getCXXABI() == TargetCXXABI::WebAssembly &&
507a9ac8606Spatrick         CGM.getLangOpts().getExceptionHandling() ==
508a9ac8606Spatrick             LangOptions::ExceptionHandlingKind::None &&
509a9ac8606Spatrick         EST == EST_Dynamic)
510a9ac8606Spatrick       CGM.getDiags().Report(D->getLocation(),
511a9ac8606Spatrick                             diag::warn_wasm_dynamic_exception_spec_ignored)
512a9ac8606Spatrick           << FD->getExceptionSpecSourceRange();
513a9ac8606Spatrick 
514e5dd7070Spatrick     unsigned NumExceptions = Proto->getNumExceptions();
515e5dd7070Spatrick     EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
516e5dd7070Spatrick 
517e5dd7070Spatrick     for (unsigned I = 0; I != NumExceptions; ++I) {
518e5dd7070Spatrick       QualType Ty = Proto->getExceptionType(I);
519e5dd7070Spatrick       QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
520e5dd7070Spatrick       llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType,
521e5dd7070Spatrick                                                         /*ForEH=*/true);
522e5dd7070Spatrick       Filter->setFilter(I, EHType);
523e5dd7070Spatrick     }
524*12c85518Srobert   } else if (Proto->canThrow() == CT_Cannot) {
525*12c85518Srobert     // noexcept functions are simple terminate scopes.
526*12c85518Srobert     if (!getLangOpts().EHAsynch) // -EHa: HW exception still can occur
527*12c85518Srobert       EHStack.pushTerminate();
528e5dd7070Spatrick   }
529e5dd7070Spatrick }
530e5dd7070Spatrick 
531e5dd7070Spatrick /// Emit the dispatch block for a filter scope if necessary.
emitFilterDispatchBlock(CodeGenFunction & CGF,EHFilterScope & filterScope)532e5dd7070Spatrick static void emitFilterDispatchBlock(CodeGenFunction &CGF,
533e5dd7070Spatrick                                     EHFilterScope &filterScope) {
534e5dd7070Spatrick   llvm::BasicBlock *dispatchBlock = filterScope.getCachedEHDispatchBlock();
535e5dd7070Spatrick   if (!dispatchBlock) return;
536e5dd7070Spatrick   if (dispatchBlock->use_empty()) {
537e5dd7070Spatrick     delete dispatchBlock;
538e5dd7070Spatrick     return;
539e5dd7070Spatrick   }
540e5dd7070Spatrick 
541e5dd7070Spatrick   CGF.EmitBlockAfterUses(dispatchBlock);
542e5dd7070Spatrick 
543e5dd7070Spatrick   // If this isn't a catch-all filter, we need to check whether we got
544e5dd7070Spatrick   // here because the filter triggered.
545e5dd7070Spatrick   if (filterScope.getNumFilters()) {
546e5dd7070Spatrick     // Load the selector value.
547e5dd7070Spatrick     llvm::Value *selector = CGF.getSelectorFromSlot();
548e5dd7070Spatrick     llvm::BasicBlock *unexpectedBB = CGF.createBasicBlock("ehspec.unexpected");
549e5dd7070Spatrick 
550e5dd7070Spatrick     llvm::Value *zero = CGF.Builder.getInt32(0);
551e5dd7070Spatrick     llvm::Value *failsFilter =
552e5dd7070Spatrick         CGF.Builder.CreateICmpSLT(selector, zero, "ehspec.fails");
553e5dd7070Spatrick     CGF.Builder.CreateCondBr(failsFilter, unexpectedBB,
554e5dd7070Spatrick                              CGF.getEHResumeBlock(false));
555e5dd7070Spatrick 
556e5dd7070Spatrick     CGF.EmitBlock(unexpectedBB);
557e5dd7070Spatrick   }
558e5dd7070Spatrick 
559e5dd7070Spatrick   // Call __cxa_call_unexpected.  This doesn't need to be an invoke
560e5dd7070Spatrick   // because __cxa_call_unexpected magically filters exceptions
561e5dd7070Spatrick   // according to the last landing pad the exception was thrown
562e5dd7070Spatrick   // into.  Seriously.
563e5dd7070Spatrick   llvm::Value *exn = CGF.getExceptionFromSlot();
564e5dd7070Spatrick   CGF.EmitRuntimeCall(getUnexpectedFn(CGF.CGM), exn)
565e5dd7070Spatrick     ->setDoesNotReturn();
566e5dd7070Spatrick   CGF.Builder.CreateUnreachable();
567e5dd7070Spatrick }
568e5dd7070Spatrick 
EmitEndEHSpec(const Decl * D)569e5dd7070Spatrick void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
570e5dd7070Spatrick   if (!CGM.getLangOpts().CXXExceptions)
571e5dd7070Spatrick     return;
572e5dd7070Spatrick 
573e5dd7070Spatrick   const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
574e5dd7070Spatrick   if (!FD) {
575e5dd7070Spatrick     // Check if CapturedDecl is nothrow and pop terminate scope for it.
576e5dd7070Spatrick     if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
577a9ac8606Spatrick       if (CD->isNothrow() && !EHStack.empty())
578e5dd7070Spatrick         EHStack.popTerminate();
579e5dd7070Spatrick     }
580e5dd7070Spatrick     return;
581e5dd7070Spatrick   }
582e5dd7070Spatrick   const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
583e5dd7070Spatrick   if (!Proto)
584e5dd7070Spatrick     return;
585e5dd7070Spatrick 
586e5dd7070Spatrick   ExceptionSpecificationType EST = Proto->getExceptionSpecType();
587*12c85518Srobert   if (EST == EST_Dynamic ||
588*12c85518Srobert       (EST == EST_DynamicNone && !getLangOpts().CPlusPlus17)) {
589e5dd7070Spatrick     // TODO: Revisit exception specifications for the MS ABI.  There is a way to
590e5dd7070Spatrick     // encode these in an object file but MSVC doesn't do anything with it.
591e5dd7070Spatrick     if (getTarget().getCXXABI().isMicrosoft())
592e5dd7070Spatrick       return;
593ec727ea7Spatrick     // In wasm we currently treat 'throw()' in the same way as 'noexcept'. In
594ec727ea7Spatrick     // case of throw with types, we ignore it and print a warning for now.
595ec727ea7Spatrick     // TODO Correctly handle exception specification in wasm
596a9ac8606Spatrick     if (CGM.getLangOpts().hasWasmExceptions()) {
597ec727ea7Spatrick       if (EST == EST_DynamicNone)
598ec727ea7Spatrick         EHStack.popTerminate();
599ec727ea7Spatrick       return;
600ec727ea7Spatrick     }
601e5dd7070Spatrick     EHFilterScope &filterScope = cast<EHFilterScope>(*EHStack.begin());
602e5dd7070Spatrick     emitFilterDispatchBlock(*this, filterScope);
603e5dd7070Spatrick     EHStack.popFilter();
604*12c85518Srobert   } else if (Proto->canThrow() == CT_Cannot &&
605*12c85518Srobert               /* possible empty when under async exceptions */
606*12c85518Srobert              !EHStack.empty()) {
607*12c85518Srobert     EHStack.popTerminate();
608e5dd7070Spatrick   }
609e5dd7070Spatrick }
610e5dd7070Spatrick 
EmitCXXTryStmt(const CXXTryStmt & S)611e5dd7070Spatrick void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
612e5dd7070Spatrick   EnterCXXTryStmt(S);
613e5dd7070Spatrick   EmitStmt(S.getTryBlock());
614e5dd7070Spatrick   ExitCXXTryStmt(S);
615e5dd7070Spatrick }
616e5dd7070Spatrick 
EnterCXXTryStmt(const CXXTryStmt & S,bool IsFnTryBlock)617e5dd7070Spatrick void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
618e5dd7070Spatrick   unsigned NumHandlers = S.getNumHandlers();
619e5dd7070Spatrick   EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
620e5dd7070Spatrick 
621e5dd7070Spatrick   for (unsigned I = 0; I != NumHandlers; ++I) {
622e5dd7070Spatrick     const CXXCatchStmt *C = S.getHandler(I);
623e5dd7070Spatrick 
624e5dd7070Spatrick     llvm::BasicBlock *Handler = createBasicBlock("catch");
625e5dd7070Spatrick     if (C->getExceptionDecl()) {
626e5dd7070Spatrick       // FIXME: Dropping the reference type on the type into makes it
627e5dd7070Spatrick       // impossible to correctly implement catch-by-reference
628e5dd7070Spatrick       // semantics for pointers.  Unfortunately, this is what all
629e5dd7070Spatrick       // existing compilers do, and it's not clear that the standard
630e5dd7070Spatrick       // personality routine is capable of doing this right.  See C++ DR 388:
631e5dd7070Spatrick       //   http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
632e5dd7070Spatrick       Qualifiers CaughtTypeQuals;
633e5dd7070Spatrick       QualType CaughtType = CGM.getContext().getUnqualifiedArrayType(
634e5dd7070Spatrick           C->getCaughtType().getNonReferenceType(), CaughtTypeQuals);
635e5dd7070Spatrick 
636e5dd7070Spatrick       CatchTypeInfo TypeInfo{nullptr, 0};
637e5dd7070Spatrick       if (CaughtType->isObjCObjectPointerType())
638e5dd7070Spatrick         TypeInfo.RTTI = CGM.getObjCRuntime().GetEHType(CaughtType);
639e5dd7070Spatrick       else
640e5dd7070Spatrick         TypeInfo = CGM.getCXXABI().getAddrOfCXXCatchHandlerType(
641e5dd7070Spatrick             CaughtType, C->getCaughtType());
642e5dd7070Spatrick       CatchScope->setHandler(I, TypeInfo, Handler);
643e5dd7070Spatrick     } else {
644e5dd7070Spatrick       // No exception decl indicates '...', a catch-all.
645e5dd7070Spatrick       CatchScope->setHandler(I, CGM.getCXXABI().getCatchAllTypeInfo(), Handler);
646a9ac8606Spatrick       // Under async exceptions, catch(...) need to catch HW exception too
647a9ac8606Spatrick       // Mark scope with SehTryBegin as a SEH __try scope
648a9ac8606Spatrick       if (getLangOpts().EHAsynch)
649a9ac8606Spatrick         EmitRuntimeCallOrInvoke(getSehTryBeginFn(CGM));
650e5dd7070Spatrick     }
651e5dd7070Spatrick   }
652e5dd7070Spatrick }
653e5dd7070Spatrick 
654e5dd7070Spatrick llvm::BasicBlock *
getEHDispatchBlock(EHScopeStack::stable_iterator si)655e5dd7070Spatrick CodeGenFunction::getEHDispatchBlock(EHScopeStack::stable_iterator si) {
656e5dd7070Spatrick   if (EHPersonality::get(*this).usesFuncletPads())
657e5dd7070Spatrick     return getFuncletEHDispatchBlock(si);
658e5dd7070Spatrick 
659e5dd7070Spatrick   // The dispatch block for the end of the scope chain is a block that
660e5dd7070Spatrick   // just resumes unwinding.
661e5dd7070Spatrick   if (si == EHStack.stable_end())
662e5dd7070Spatrick     return getEHResumeBlock(true);
663e5dd7070Spatrick 
664e5dd7070Spatrick   // Otherwise, we should look at the actual scope.
665e5dd7070Spatrick   EHScope &scope = *EHStack.find(si);
666e5dd7070Spatrick 
667e5dd7070Spatrick   llvm::BasicBlock *dispatchBlock = scope.getCachedEHDispatchBlock();
668e5dd7070Spatrick   if (!dispatchBlock) {
669e5dd7070Spatrick     switch (scope.getKind()) {
670e5dd7070Spatrick     case EHScope::Catch: {
671e5dd7070Spatrick       // Apply a special case to a single catch-all.
672e5dd7070Spatrick       EHCatchScope &catchScope = cast<EHCatchScope>(scope);
673e5dd7070Spatrick       if (catchScope.getNumHandlers() == 1 &&
674e5dd7070Spatrick           catchScope.getHandler(0).isCatchAll()) {
675e5dd7070Spatrick         dispatchBlock = catchScope.getHandler(0).Block;
676e5dd7070Spatrick 
677e5dd7070Spatrick       // Otherwise, make a dispatch block.
678e5dd7070Spatrick       } else {
679e5dd7070Spatrick         dispatchBlock = createBasicBlock("catch.dispatch");
680e5dd7070Spatrick       }
681e5dd7070Spatrick       break;
682e5dd7070Spatrick     }
683e5dd7070Spatrick 
684e5dd7070Spatrick     case EHScope::Cleanup:
685e5dd7070Spatrick       dispatchBlock = createBasicBlock("ehcleanup");
686e5dd7070Spatrick       break;
687e5dd7070Spatrick 
688e5dd7070Spatrick     case EHScope::Filter:
689e5dd7070Spatrick       dispatchBlock = createBasicBlock("filter.dispatch");
690e5dd7070Spatrick       break;
691e5dd7070Spatrick 
692e5dd7070Spatrick     case EHScope::Terminate:
693e5dd7070Spatrick       dispatchBlock = getTerminateHandler();
694e5dd7070Spatrick       break;
695e5dd7070Spatrick     }
696e5dd7070Spatrick     scope.setCachedEHDispatchBlock(dispatchBlock);
697e5dd7070Spatrick   }
698e5dd7070Spatrick   return dispatchBlock;
699e5dd7070Spatrick }
700e5dd7070Spatrick 
701e5dd7070Spatrick llvm::BasicBlock *
getFuncletEHDispatchBlock(EHScopeStack::stable_iterator SI)702e5dd7070Spatrick CodeGenFunction::getFuncletEHDispatchBlock(EHScopeStack::stable_iterator SI) {
703e5dd7070Spatrick   // Returning nullptr indicates that the previous dispatch block should unwind
704e5dd7070Spatrick   // to caller.
705e5dd7070Spatrick   if (SI == EHStack.stable_end())
706e5dd7070Spatrick     return nullptr;
707e5dd7070Spatrick 
708e5dd7070Spatrick   // Otherwise, we should look at the actual scope.
709e5dd7070Spatrick   EHScope &EHS = *EHStack.find(SI);
710e5dd7070Spatrick 
711e5dd7070Spatrick   llvm::BasicBlock *DispatchBlock = EHS.getCachedEHDispatchBlock();
712e5dd7070Spatrick   if (DispatchBlock)
713e5dd7070Spatrick     return DispatchBlock;
714e5dd7070Spatrick 
715e5dd7070Spatrick   if (EHS.getKind() == EHScope::Terminate)
716e5dd7070Spatrick     DispatchBlock = getTerminateFunclet();
717e5dd7070Spatrick   else
718e5dd7070Spatrick     DispatchBlock = createBasicBlock();
719e5dd7070Spatrick   CGBuilderTy Builder(*this, DispatchBlock);
720e5dd7070Spatrick 
721e5dd7070Spatrick   switch (EHS.getKind()) {
722e5dd7070Spatrick   case EHScope::Catch:
723e5dd7070Spatrick     DispatchBlock->setName("catch.dispatch");
724e5dd7070Spatrick     break;
725e5dd7070Spatrick 
726e5dd7070Spatrick   case EHScope::Cleanup:
727e5dd7070Spatrick     DispatchBlock->setName("ehcleanup");
728e5dd7070Spatrick     break;
729e5dd7070Spatrick 
730e5dd7070Spatrick   case EHScope::Filter:
731e5dd7070Spatrick     llvm_unreachable("exception specifications not handled yet!");
732e5dd7070Spatrick 
733e5dd7070Spatrick   case EHScope::Terminate:
734e5dd7070Spatrick     DispatchBlock->setName("terminate");
735e5dd7070Spatrick     break;
736e5dd7070Spatrick   }
737e5dd7070Spatrick   EHS.setCachedEHDispatchBlock(DispatchBlock);
738e5dd7070Spatrick   return DispatchBlock;
739e5dd7070Spatrick }
740e5dd7070Spatrick 
741e5dd7070Spatrick /// Check whether this is a non-EH scope, i.e. a scope which doesn't
742e5dd7070Spatrick /// affect exception handling.  Currently, the only non-EH scopes are
743e5dd7070Spatrick /// normal-only cleanup scopes.
isNonEHScope(const EHScope & S)744e5dd7070Spatrick static bool isNonEHScope(const EHScope &S) {
745e5dd7070Spatrick   switch (S.getKind()) {
746e5dd7070Spatrick   case EHScope::Cleanup:
747e5dd7070Spatrick     return !cast<EHCleanupScope>(S).isEHCleanup();
748e5dd7070Spatrick   case EHScope::Filter:
749e5dd7070Spatrick   case EHScope::Catch:
750e5dd7070Spatrick   case EHScope::Terminate:
751e5dd7070Spatrick     return false;
752e5dd7070Spatrick   }
753e5dd7070Spatrick 
754e5dd7070Spatrick   llvm_unreachable("Invalid EHScope Kind!");
755e5dd7070Spatrick }
756e5dd7070Spatrick 
getInvokeDestImpl()757e5dd7070Spatrick llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
758e5dd7070Spatrick   assert(EHStack.requiresLandingPad());
759e5dd7070Spatrick   assert(!EHStack.empty());
760e5dd7070Spatrick 
761ec727ea7Spatrick   // If exceptions are disabled/ignored and SEH is not in use, then there is no
762ec727ea7Spatrick   // invoke destination. SEH "works" even if exceptions are off. In practice,
763ec727ea7Spatrick   // this means that C++ destructors and other EH cleanups don't run, which is
764a9ac8606Spatrick   // consistent with MSVC's behavior, except in the presence of -EHa
765e5dd7070Spatrick   const LangOptions &LO = CGM.getLangOpts();
766ec727ea7Spatrick   if (!LO.Exceptions || LO.IgnoreExceptions) {
767e5dd7070Spatrick     if (!LO.Borland && !LO.MicrosoftExt)
768e5dd7070Spatrick       return nullptr;
769e5dd7070Spatrick     if (!currentFunctionUsesSEHTry())
770e5dd7070Spatrick       return nullptr;
771e5dd7070Spatrick   }
772e5dd7070Spatrick 
773e5dd7070Spatrick   // CUDA device code doesn't have exceptions.
774e5dd7070Spatrick   if (LO.CUDA && LO.CUDAIsDevice)
775e5dd7070Spatrick     return nullptr;
776e5dd7070Spatrick 
777e5dd7070Spatrick   // Check the innermost scope for a cached landing pad.  If this is
778e5dd7070Spatrick   // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
779e5dd7070Spatrick   llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
780e5dd7070Spatrick   if (LP) return LP;
781e5dd7070Spatrick 
782e5dd7070Spatrick   const EHPersonality &Personality = EHPersonality::get(*this);
783e5dd7070Spatrick 
784e5dd7070Spatrick   if (!CurFn->hasPersonalityFn())
785e5dd7070Spatrick     CurFn->setPersonalityFn(getOpaquePersonalityFn(CGM, Personality));
786e5dd7070Spatrick 
787e5dd7070Spatrick   if (Personality.usesFuncletPads()) {
788e5dd7070Spatrick     // We don't need separate landing pads in the funclet model.
789e5dd7070Spatrick     LP = getEHDispatchBlock(EHStack.getInnermostEHScope());
790e5dd7070Spatrick   } else {
791e5dd7070Spatrick     // Build the landing pad for this scope.
792e5dd7070Spatrick     LP = EmitLandingPad();
793e5dd7070Spatrick   }
794e5dd7070Spatrick 
795e5dd7070Spatrick   assert(LP);
796e5dd7070Spatrick 
797e5dd7070Spatrick   // Cache the landing pad on the innermost scope.  If this is a
798e5dd7070Spatrick   // non-EH scope, cache the landing pad on the enclosing scope, too.
799e5dd7070Spatrick   for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
800e5dd7070Spatrick     ir->setCachedLandingPad(LP);
801e5dd7070Spatrick     if (!isNonEHScope(*ir)) break;
802e5dd7070Spatrick   }
803e5dd7070Spatrick 
804e5dd7070Spatrick   return LP;
805e5dd7070Spatrick }
806e5dd7070Spatrick 
EmitLandingPad()807e5dd7070Spatrick llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
808e5dd7070Spatrick   assert(EHStack.requiresLandingPad());
809ec727ea7Spatrick   assert(!CGM.getLangOpts().IgnoreExceptions &&
810ec727ea7Spatrick          "LandingPad should not be emitted when -fignore-exceptions are in "
811ec727ea7Spatrick          "effect.");
812e5dd7070Spatrick   EHScope &innermostEHScope = *EHStack.find(EHStack.getInnermostEHScope());
813e5dd7070Spatrick   switch (innermostEHScope.getKind()) {
814e5dd7070Spatrick   case EHScope::Terminate:
815e5dd7070Spatrick     return getTerminateLandingPad();
816e5dd7070Spatrick 
817e5dd7070Spatrick   case EHScope::Catch:
818e5dd7070Spatrick   case EHScope::Cleanup:
819e5dd7070Spatrick   case EHScope::Filter:
820e5dd7070Spatrick     if (llvm::BasicBlock *lpad = innermostEHScope.getCachedLandingPad())
821e5dd7070Spatrick       return lpad;
822e5dd7070Spatrick   }
823e5dd7070Spatrick 
824e5dd7070Spatrick   // Save the current IR generation state.
825e5dd7070Spatrick   CGBuilderTy::InsertPoint savedIP = Builder.saveAndClearIP();
826e5dd7070Spatrick   auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, CurEHLocation);
827e5dd7070Spatrick 
828e5dd7070Spatrick   // Create and configure the landing pad.
829e5dd7070Spatrick   llvm::BasicBlock *lpad = createBasicBlock("lpad");
830e5dd7070Spatrick   EmitBlock(lpad);
831e5dd7070Spatrick 
832e5dd7070Spatrick   llvm::LandingPadInst *LPadInst =
833e5dd7070Spatrick       Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty), 0);
834e5dd7070Spatrick 
835e5dd7070Spatrick   llvm::Value *LPadExn = Builder.CreateExtractValue(LPadInst, 0);
836e5dd7070Spatrick   Builder.CreateStore(LPadExn, getExceptionSlot());
837e5dd7070Spatrick   llvm::Value *LPadSel = Builder.CreateExtractValue(LPadInst, 1);
838e5dd7070Spatrick   Builder.CreateStore(LPadSel, getEHSelectorSlot());
839e5dd7070Spatrick 
840e5dd7070Spatrick   // Save the exception pointer.  It's safe to use a single exception
841e5dd7070Spatrick   // pointer per function because EH cleanups can never have nested
842e5dd7070Spatrick   // try/catches.
843e5dd7070Spatrick   // Build the landingpad instruction.
844e5dd7070Spatrick 
845e5dd7070Spatrick   // Accumulate all the handlers in scope.
846e5dd7070Spatrick   bool hasCatchAll = false;
847e5dd7070Spatrick   bool hasCleanup = false;
848e5dd7070Spatrick   bool hasFilter = false;
849e5dd7070Spatrick   SmallVector<llvm::Value*, 4> filterTypes;
850e5dd7070Spatrick   llvm::SmallPtrSet<llvm::Value*, 4> catchTypes;
851e5dd7070Spatrick   for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end(); I != E;
852e5dd7070Spatrick        ++I) {
853e5dd7070Spatrick 
854e5dd7070Spatrick     switch (I->getKind()) {
855e5dd7070Spatrick     case EHScope::Cleanup:
856e5dd7070Spatrick       // If we have a cleanup, remember that.
857e5dd7070Spatrick       hasCleanup = (hasCleanup || cast<EHCleanupScope>(*I).isEHCleanup());
858e5dd7070Spatrick       continue;
859e5dd7070Spatrick 
860e5dd7070Spatrick     case EHScope::Filter: {
861e5dd7070Spatrick       assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
862e5dd7070Spatrick       assert(!hasCatchAll && "EH filter reached after catch-all");
863e5dd7070Spatrick 
864e5dd7070Spatrick       // Filter scopes get added to the landingpad in weird ways.
865e5dd7070Spatrick       EHFilterScope &filter = cast<EHFilterScope>(*I);
866e5dd7070Spatrick       hasFilter = true;
867e5dd7070Spatrick 
868e5dd7070Spatrick       // Add all the filter values.
869e5dd7070Spatrick       for (unsigned i = 0, e = filter.getNumFilters(); i != e; ++i)
870e5dd7070Spatrick         filterTypes.push_back(filter.getFilter(i));
871e5dd7070Spatrick       goto done;
872e5dd7070Spatrick     }
873e5dd7070Spatrick 
874e5dd7070Spatrick     case EHScope::Terminate:
875e5dd7070Spatrick       // Terminate scopes are basically catch-alls.
876e5dd7070Spatrick       assert(!hasCatchAll);
877e5dd7070Spatrick       hasCatchAll = true;
878e5dd7070Spatrick       goto done;
879e5dd7070Spatrick 
880e5dd7070Spatrick     case EHScope::Catch:
881e5dd7070Spatrick       break;
882e5dd7070Spatrick     }
883e5dd7070Spatrick 
884e5dd7070Spatrick     EHCatchScope &catchScope = cast<EHCatchScope>(*I);
885e5dd7070Spatrick     for (unsigned hi = 0, he = catchScope.getNumHandlers(); hi != he; ++hi) {
886e5dd7070Spatrick       EHCatchScope::Handler handler = catchScope.getHandler(hi);
887e5dd7070Spatrick       assert(handler.Type.Flags == 0 &&
888e5dd7070Spatrick              "landingpads do not support catch handler flags");
889e5dd7070Spatrick 
890e5dd7070Spatrick       // If this is a catch-all, register that and abort.
891e5dd7070Spatrick       if (!handler.Type.RTTI) {
892e5dd7070Spatrick         assert(!hasCatchAll);
893e5dd7070Spatrick         hasCatchAll = true;
894e5dd7070Spatrick         goto done;
895e5dd7070Spatrick       }
896e5dd7070Spatrick 
897e5dd7070Spatrick       // Check whether we already have a handler for this type.
898e5dd7070Spatrick       if (catchTypes.insert(handler.Type.RTTI).second)
899e5dd7070Spatrick         // If not, add it directly to the landingpad.
900e5dd7070Spatrick         LPadInst->addClause(handler.Type.RTTI);
901e5dd7070Spatrick     }
902e5dd7070Spatrick   }
903e5dd7070Spatrick 
904e5dd7070Spatrick  done:
905e5dd7070Spatrick   // If we have a catch-all, add null to the landingpad.
906e5dd7070Spatrick   assert(!(hasCatchAll && hasFilter));
907e5dd7070Spatrick   if (hasCatchAll) {
908e5dd7070Spatrick     LPadInst->addClause(getCatchAllValue(*this));
909e5dd7070Spatrick 
910e5dd7070Spatrick   // If we have an EH filter, we need to add those handlers in the
911e5dd7070Spatrick   // right place in the landingpad, which is to say, at the end.
912e5dd7070Spatrick   } else if (hasFilter) {
913e5dd7070Spatrick     // Create a filter expression: a constant array indicating which filter
914e5dd7070Spatrick     // types there are. The personality routine only lands here if the filter
915e5dd7070Spatrick     // doesn't match.
916e5dd7070Spatrick     SmallVector<llvm::Constant*, 8> Filters;
917e5dd7070Spatrick     llvm::ArrayType *AType =
918e5dd7070Spatrick       llvm::ArrayType::get(!filterTypes.empty() ?
919e5dd7070Spatrick                              filterTypes[0]->getType() : Int8PtrTy,
920e5dd7070Spatrick                            filterTypes.size());
921e5dd7070Spatrick 
922e5dd7070Spatrick     for (unsigned i = 0, e = filterTypes.size(); i != e; ++i)
923e5dd7070Spatrick       Filters.push_back(cast<llvm::Constant>(filterTypes[i]));
924e5dd7070Spatrick     llvm::Constant *FilterArray = llvm::ConstantArray::get(AType, Filters);
925e5dd7070Spatrick     LPadInst->addClause(FilterArray);
926e5dd7070Spatrick 
927e5dd7070Spatrick     // Also check whether we need a cleanup.
928e5dd7070Spatrick     if (hasCleanup)
929e5dd7070Spatrick       LPadInst->setCleanup(true);
930e5dd7070Spatrick 
931e5dd7070Spatrick   // Otherwise, signal that we at least have cleanups.
932e5dd7070Spatrick   } else if (hasCleanup) {
933e5dd7070Spatrick     LPadInst->setCleanup(true);
934e5dd7070Spatrick   }
935e5dd7070Spatrick 
936e5dd7070Spatrick   assert((LPadInst->getNumClauses() > 0 || LPadInst->isCleanup()) &&
937e5dd7070Spatrick          "landingpad instruction has no clauses!");
938e5dd7070Spatrick 
939e5dd7070Spatrick   // Tell the backend how to generate the landing pad.
940e5dd7070Spatrick   Builder.CreateBr(getEHDispatchBlock(EHStack.getInnermostEHScope()));
941e5dd7070Spatrick 
942e5dd7070Spatrick   // Restore the old IR generation state.
943e5dd7070Spatrick   Builder.restoreIP(savedIP);
944e5dd7070Spatrick 
945e5dd7070Spatrick   return lpad;
946e5dd7070Spatrick }
947e5dd7070Spatrick 
emitCatchPadBlock(CodeGenFunction & CGF,EHCatchScope & CatchScope)948e5dd7070Spatrick static void emitCatchPadBlock(CodeGenFunction &CGF, EHCatchScope &CatchScope) {
949e5dd7070Spatrick   llvm::BasicBlock *DispatchBlock = CatchScope.getCachedEHDispatchBlock();
950e5dd7070Spatrick   assert(DispatchBlock);
951e5dd7070Spatrick 
952e5dd7070Spatrick   CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveIP();
953e5dd7070Spatrick   CGF.EmitBlockAfterUses(DispatchBlock);
954e5dd7070Spatrick 
955e5dd7070Spatrick   llvm::Value *ParentPad = CGF.CurrentFuncletPad;
956e5dd7070Spatrick   if (!ParentPad)
957e5dd7070Spatrick     ParentPad = llvm::ConstantTokenNone::get(CGF.getLLVMContext());
958e5dd7070Spatrick   llvm::BasicBlock *UnwindBB =
959e5dd7070Spatrick       CGF.getEHDispatchBlock(CatchScope.getEnclosingEHScope());
960e5dd7070Spatrick 
961e5dd7070Spatrick   unsigned NumHandlers = CatchScope.getNumHandlers();
962e5dd7070Spatrick   llvm::CatchSwitchInst *CatchSwitch =
963e5dd7070Spatrick       CGF.Builder.CreateCatchSwitch(ParentPad, UnwindBB, NumHandlers);
964e5dd7070Spatrick 
965e5dd7070Spatrick   // Test against each of the exception types we claim to catch.
966e5dd7070Spatrick   for (unsigned I = 0; I < NumHandlers; ++I) {
967e5dd7070Spatrick     const EHCatchScope::Handler &Handler = CatchScope.getHandler(I);
968e5dd7070Spatrick 
969e5dd7070Spatrick     CatchTypeInfo TypeInfo = Handler.Type;
970e5dd7070Spatrick     if (!TypeInfo.RTTI)
971e5dd7070Spatrick       TypeInfo.RTTI = llvm::Constant::getNullValue(CGF.VoidPtrTy);
972e5dd7070Spatrick 
973e5dd7070Spatrick     CGF.Builder.SetInsertPoint(Handler.Block);
974e5dd7070Spatrick 
975e5dd7070Spatrick     if (EHPersonality::get(CGF).isMSVCXXPersonality()) {
976e5dd7070Spatrick       CGF.Builder.CreateCatchPad(
977e5dd7070Spatrick           CatchSwitch, {TypeInfo.RTTI, CGF.Builder.getInt32(TypeInfo.Flags),
978e5dd7070Spatrick                         llvm::Constant::getNullValue(CGF.VoidPtrTy)});
979e5dd7070Spatrick     } else {
980e5dd7070Spatrick       CGF.Builder.CreateCatchPad(CatchSwitch, {TypeInfo.RTTI});
981e5dd7070Spatrick     }
982e5dd7070Spatrick 
983e5dd7070Spatrick     CatchSwitch->addHandler(Handler.Block);
984e5dd7070Spatrick   }
985e5dd7070Spatrick   CGF.Builder.restoreIP(SavedIP);
986e5dd7070Spatrick }
987e5dd7070Spatrick 
988e5dd7070Spatrick // Wasm uses Windows-style EH instructions, but it merges all catch clauses into
989e5dd7070Spatrick // one big catchpad, within which we use Itanium's landingpad-style selector
990e5dd7070Spatrick // comparison instructions.
emitWasmCatchPadBlock(CodeGenFunction & CGF,EHCatchScope & CatchScope)991e5dd7070Spatrick static void emitWasmCatchPadBlock(CodeGenFunction &CGF,
992e5dd7070Spatrick                                   EHCatchScope &CatchScope) {
993e5dd7070Spatrick   llvm::BasicBlock *DispatchBlock = CatchScope.getCachedEHDispatchBlock();
994e5dd7070Spatrick   assert(DispatchBlock);
995e5dd7070Spatrick 
996e5dd7070Spatrick   CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveIP();
997e5dd7070Spatrick   CGF.EmitBlockAfterUses(DispatchBlock);
998e5dd7070Spatrick 
999e5dd7070Spatrick   llvm::Value *ParentPad = CGF.CurrentFuncletPad;
1000e5dd7070Spatrick   if (!ParentPad)
1001e5dd7070Spatrick     ParentPad = llvm::ConstantTokenNone::get(CGF.getLLVMContext());
1002e5dd7070Spatrick   llvm::BasicBlock *UnwindBB =
1003e5dd7070Spatrick       CGF.getEHDispatchBlock(CatchScope.getEnclosingEHScope());
1004e5dd7070Spatrick 
1005e5dd7070Spatrick   unsigned NumHandlers = CatchScope.getNumHandlers();
1006e5dd7070Spatrick   llvm::CatchSwitchInst *CatchSwitch =
1007e5dd7070Spatrick       CGF.Builder.CreateCatchSwitch(ParentPad, UnwindBB, NumHandlers);
1008e5dd7070Spatrick 
1009e5dd7070Spatrick   // We don't use a landingpad instruction, so generate intrinsic calls to
1010e5dd7070Spatrick   // provide exception and selector values.
1011e5dd7070Spatrick   llvm::BasicBlock *WasmCatchStartBlock = CGF.createBasicBlock("catch.start");
1012e5dd7070Spatrick   CatchSwitch->addHandler(WasmCatchStartBlock);
1013e5dd7070Spatrick   CGF.EmitBlockAfterUses(WasmCatchStartBlock);
1014e5dd7070Spatrick 
1015e5dd7070Spatrick   // Create a catchpad instruction.
1016e5dd7070Spatrick   SmallVector<llvm::Value *, 4> CatchTypes;
1017e5dd7070Spatrick   for (unsigned I = 0, E = NumHandlers; I < E; ++I) {
1018e5dd7070Spatrick     const EHCatchScope::Handler &Handler = CatchScope.getHandler(I);
1019e5dd7070Spatrick     CatchTypeInfo TypeInfo = Handler.Type;
1020e5dd7070Spatrick     if (!TypeInfo.RTTI)
1021e5dd7070Spatrick       TypeInfo.RTTI = llvm::Constant::getNullValue(CGF.VoidPtrTy);
1022e5dd7070Spatrick     CatchTypes.push_back(TypeInfo.RTTI);
1023e5dd7070Spatrick   }
1024e5dd7070Spatrick   auto *CPI = CGF.Builder.CreateCatchPad(CatchSwitch, CatchTypes);
1025e5dd7070Spatrick 
1026e5dd7070Spatrick   // Create calls to wasm.get.exception and wasm.get.ehselector intrinsics.
1027e5dd7070Spatrick   // Before they are lowered appropriately later, they provide values for the
1028e5dd7070Spatrick   // exception and selector.
1029e5dd7070Spatrick   llvm::Function *GetExnFn =
1030e5dd7070Spatrick       CGF.CGM.getIntrinsic(llvm::Intrinsic::wasm_get_exception);
1031e5dd7070Spatrick   llvm::Function *GetSelectorFn =
1032e5dd7070Spatrick       CGF.CGM.getIntrinsic(llvm::Intrinsic::wasm_get_ehselector);
1033e5dd7070Spatrick   llvm::CallInst *Exn = CGF.Builder.CreateCall(GetExnFn, CPI);
1034e5dd7070Spatrick   CGF.Builder.CreateStore(Exn, CGF.getExceptionSlot());
1035e5dd7070Spatrick   llvm::CallInst *Selector = CGF.Builder.CreateCall(GetSelectorFn, CPI);
1036e5dd7070Spatrick 
1037e5dd7070Spatrick   llvm::Function *TypeIDFn = CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
1038e5dd7070Spatrick 
1039e5dd7070Spatrick   // If there's only a single catch-all, branch directly to its handler.
1040e5dd7070Spatrick   if (CatchScope.getNumHandlers() == 1 &&
1041e5dd7070Spatrick       CatchScope.getHandler(0).isCatchAll()) {
1042e5dd7070Spatrick     CGF.Builder.CreateBr(CatchScope.getHandler(0).Block);
1043e5dd7070Spatrick     CGF.Builder.restoreIP(SavedIP);
1044e5dd7070Spatrick     return;
1045e5dd7070Spatrick   }
1046e5dd7070Spatrick 
1047e5dd7070Spatrick   // Test against each of the exception types we claim to catch.
1048e5dd7070Spatrick   for (unsigned I = 0, E = NumHandlers;; ++I) {
1049e5dd7070Spatrick     assert(I < E && "ran off end of handlers!");
1050e5dd7070Spatrick     const EHCatchScope::Handler &Handler = CatchScope.getHandler(I);
1051e5dd7070Spatrick     CatchTypeInfo TypeInfo = Handler.Type;
1052e5dd7070Spatrick     if (!TypeInfo.RTTI)
1053e5dd7070Spatrick       TypeInfo.RTTI = llvm::Constant::getNullValue(CGF.VoidPtrTy);
1054e5dd7070Spatrick 
1055e5dd7070Spatrick     // Figure out the next block.
1056e5dd7070Spatrick     llvm::BasicBlock *NextBlock;
1057e5dd7070Spatrick 
1058e5dd7070Spatrick     bool EmitNextBlock = false, NextIsEnd = false;
1059e5dd7070Spatrick 
1060e5dd7070Spatrick     // If this is the last handler, we're at the end, and the next block is a
1061e5dd7070Spatrick     // block that contains a call to the rethrow function, so we can unwind to
1062e5dd7070Spatrick     // the enclosing EH scope. The call itself will be generated later.
1063e5dd7070Spatrick     if (I + 1 == E) {
1064e5dd7070Spatrick       NextBlock = CGF.createBasicBlock("rethrow");
1065e5dd7070Spatrick       EmitNextBlock = true;
1066e5dd7070Spatrick       NextIsEnd = true;
1067e5dd7070Spatrick 
1068e5dd7070Spatrick       // If the next handler is a catch-all, we're at the end, and the
1069e5dd7070Spatrick       // next block is that handler.
1070e5dd7070Spatrick     } else if (CatchScope.getHandler(I + 1).isCatchAll()) {
1071e5dd7070Spatrick       NextBlock = CatchScope.getHandler(I + 1).Block;
1072e5dd7070Spatrick       NextIsEnd = true;
1073e5dd7070Spatrick 
1074e5dd7070Spatrick       // Otherwise, we're not at the end and we need a new block.
1075e5dd7070Spatrick     } else {
1076e5dd7070Spatrick       NextBlock = CGF.createBasicBlock("catch.fallthrough");
1077e5dd7070Spatrick       EmitNextBlock = true;
1078e5dd7070Spatrick     }
1079e5dd7070Spatrick 
1080e5dd7070Spatrick     // Figure out the catch type's index in the LSDA's type table.
1081e5dd7070Spatrick     llvm::CallInst *TypeIndex = CGF.Builder.CreateCall(TypeIDFn, TypeInfo.RTTI);
1082e5dd7070Spatrick     TypeIndex->setDoesNotThrow();
1083e5dd7070Spatrick 
1084e5dd7070Spatrick     llvm::Value *MatchesTypeIndex =
1085e5dd7070Spatrick         CGF.Builder.CreateICmpEQ(Selector, TypeIndex, "matches");
1086e5dd7070Spatrick     CGF.Builder.CreateCondBr(MatchesTypeIndex, Handler.Block, NextBlock);
1087e5dd7070Spatrick 
1088e5dd7070Spatrick     if (EmitNextBlock)
1089e5dd7070Spatrick       CGF.EmitBlock(NextBlock);
1090e5dd7070Spatrick     if (NextIsEnd)
1091e5dd7070Spatrick       break;
1092e5dd7070Spatrick   }
1093e5dd7070Spatrick 
1094e5dd7070Spatrick   CGF.Builder.restoreIP(SavedIP);
1095e5dd7070Spatrick }
1096e5dd7070Spatrick 
1097e5dd7070Spatrick /// Emit the structure of the dispatch block for the given catch scope.
1098e5dd7070Spatrick /// It is an invariant that the dispatch block already exists.
emitCatchDispatchBlock(CodeGenFunction & CGF,EHCatchScope & catchScope)1099e5dd7070Spatrick static void emitCatchDispatchBlock(CodeGenFunction &CGF,
1100e5dd7070Spatrick                                    EHCatchScope &catchScope) {
1101e5dd7070Spatrick   if (EHPersonality::get(CGF).isWasmPersonality())
1102e5dd7070Spatrick     return emitWasmCatchPadBlock(CGF, catchScope);
1103e5dd7070Spatrick   if (EHPersonality::get(CGF).usesFuncletPads())
1104e5dd7070Spatrick     return emitCatchPadBlock(CGF, catchScope);
1105e5dd7070Spatrick 
1106e5dd7070Spatrick   llvm::BasicBlock *dispatchBlock = catchScope.getCachedEHDispatchBlock();
1107e5dd7070Spatrick   assert(dispatchBlock);
1108e5dd7070Spatrick 
1109e5dd7070Spatrick   // If there's only a single catch-all, getEHDispatchBlock returned
1110e5dd7070Spatrick   // that catch-all as the dispatch block.
1111e5dd7070Spatrick   if (catchScope.getNumHandlers() == 1 &&
1112e5dd7070Spatrick       catchScope.getHandler(0).isCatchAll()) {
1113e5dd7070Spatrick     assert(dispatchBlock == catchScope.getHandler(0).Block);
1114e5dd7070Spatrick     return;
1115e5dd7070Spatrick   }
1116e5dd7070Spatrick 
1117e5dd7070Spatrick   CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveIP();
1118e5dd7070Spatrick   CGF.EmitBlockAfterUses(dispatchBlock);
1119e5dd7070Spatrick 
1120e5dd7070Spatrick   // Select the right handler.
1121e5dd7070Spatrick   llvm::Function *llvm_eh_typeid_for =
1122e5dd7070Spatrick     CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
1123e5dd7070Spatrick 
1124e5dd7070Spatrick   // Load the selector value.
1125e5dd7070Spatrick   llvm::Value *selector = CGF.getSelectorFromSlot();
1126e5dd7070Spatrick 
1127e5dd7070Spatrick   // Test against each of the exception types we claim to catch.
1128e5dd7070Spatrick   for (unsigned i = 0, e = catchScope.getNumHandlers(); ; ++i) {
1129e5dd7070Spatrick     assert(i < e && "ran off end of handlers!");
1130e5dd7070Spatrick     const EHCatchScope::Handler &handler = catchScope.getHandler(i);
1131e5dd7070Spatrick 
1132e5dd7070Spatrick     llvm::Value *typeValue = handler.Type.RTTI;
1133e5dd7070Spatrick     assert(handler.Type.Flags == 0 &&
1134e5dd7070Spatrick            "landingpads do not support catch handler flags");
1135e5dd7070Spatrick     assert(typeValue && "fell into catch-all case!");
1136e5dd7070Spatrick     typeValue = CGF.Builder.CreateBitCast(typeValue, CGF.Int8PtrTy);
1137e5dd7070Spatrick 
1138e5dd7070Spatrick     // Figure out the next block.
1139e5dd7070Spatrick     bool nextIsEnd;
1140e5dd7070Spatrick     llvm::BasicBlock *nextBlock;
1141e5dd7070Spatrick 
1142e5dd7070Spatrick     // If this is the last handler, we're at the end, and the next
1143e5dd7070Spatrick     // block is the block for the enclosing EH scope.
1144e5dd7070Spatrick     if (i + 1 == e) {
1145e5dd7070Spatrick       nextBlock = CGF.getEHDispatchBlock(catchScope.getEnclosingEHScope());
1146e5dd7070Spatrick       nextIsEnd = true;
1147e5dd7070Spatrick 
1148e5dd7070Spatrick     // If the next handler is a catch-all, we're at the end, and the
1149e5dd7070Spatrick     // next block is that handler.
1150e5dd7070Spatrick     } else if (catchScope.getHandler(i+1).isCatchAll()) {
1151e5dd7070Spatrick       nextBlock = catchScope.getHandler(i+1).Block;
1152e5dd7070Spatrick       nextIsEnd = true;
1153e5dd7070Spatrick 
1154e5dd7070Spatrick     // Otherwise, we're not at the end and we need a new block.
1155e5dd7070Spatrick     } else {
1156e5dd7070Spatrick       nextBlock = CGF.createBasicBlock("catch.fallthrough");
1157e5dd7070Spatrick       nextIsEnd = false;
1158e5dd7070Spatrick     }
1159e5dd7070Spatrick 
1160e5dd7070Spatrick     // Figure out the catch type's index in the LSDA's type table.
1161e5dd7070Spatrick     llvm::CallInst *typeIndex =
1162e5dd7070Spatrick       CGF.Builder.CreateCall(llvm_eh_typeid_for, typeValue);
1163e5dd7070Spatrick     typeIndex->setDoesNotThrow();
1164e5dd7070Spatrick 
1165e5dd7070Spatrick     llvm::Value *matchesTypeIndex =
1166e5dd7070Spatrick       CGF.Builder.CreateICmpEQ(selector, typeIndex, "matches");
1167e5dd7070Spatrick     CGF.Builder.CreateCondBr(matchesTypeIndex, handler.Block, nextBlock);
1168e5dd7070Spatrick 
1169e5dd7070Spatrick     // If the next handler is a catch-all, we're completely done.
1170e5dd7070Spatrick     if (nextIsEnd) {
1171e5dd7070Spatrick       CGF.Builder.restoreIP(savedIP);
1172e5dd7070Spatrick       return;
1173e5dd7070Spatrick     }
1174e5dd7070Spatrick     // Otherwise we need to emit and continue at that block.
1175e5dd7070Spatrick     CGF.EmitBlock(nextBlock);
1176e5dd7070Spatrick   }
1177e5dd7070Spatrick }
1178e5dd7070Spatrick 
popCatchScope()1179e5dd7070Spatrick void CodeGenFunction::popCatchScope() {
1180e5dd7070Spatrick   EHCatchScope &catchScope = cast<EHCatchScope>(*EHStack.begin());
1181e5dd7070Spatrick   if (catchScope.hasEHBranches())
1182e5dd7070Spatrick     emitCatchDispatchBlock(*this, catchScope);
1183e5dd7070Spatrick   EHStack.popCatch();
1184e5dd7070Spatrick }
1185e5dd7070Spatrick 
ExitCXXTryStmt(const CXXTryStmt & S,bool IsFnTryBlock)1186e5dd7070Spatrick void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
1187e5dd7070Spatrick   unsigned NumHandlers = S.getNumHandlers();
1188e5dd7070Spatrick   EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1189e5dd7070Spatrick   assert(CatchScope.getNumHandlers() == NumHandlers);
1190e5dd7070Spatrick   llvm::BasicBlock *DispatchBlock = CatchScope.getCachedEHDispatchBlock();
1191e5dd7070Spatrick 
1192e5dd7070Spatrick   // If the catch was not required, bail out now.
1193e5dd7070Spatrick   if (!CatchScope.hasEHBranches()) {
1194e5dd7070Spatrick     CatchScope.clearHandlerBlocks();
1195e5dd7070Spatrick     EHStack.popCatch();
1196e5dd7070Spatrick     return;
1197e5dd7070Spatrick   }
1198e5dd7070Spatrick 
1199e5dd7070Spatrick   // Emit the structure of the EH dispatch for this catch.
1200e5dd7070Spatrick   emitCatchDispatchBlock(*this, CatchScope);
1201e5dd7070Spatrick 
1202e5dd7070Spatrick   // Copy the handler blocks off before we pop the EH stack.  Emitting
1203e5dd7070Spatrick   // the handlers might scribble on this memory.
1204e5dd7070Spatrick   SmallVector<EHCatchScope::Handler, 8> Handlers(
1205e5dd7070Spatrick       CatchScope.begin(), CatchScope.begin() + NumHandlers);
1206e5dd7070Spatrick 
1207e5dd7070Spatrick   EHStack.popCatch();
1208e5dd7070Spatrick 
1209e5dd7070Spatrick   // The fall-through block.
1210e5dd7070Spatrick   llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
1211e5dd7070Spatrick 
1212e5dd7070Spatrick   // We just emitted the body of the try; jump to the continue block.
1213e5dd7070Spatrick   if (HaveInsertPoint())
1214e5dd7070Spatrick     Builder.CreateBr(ContBB);
1215e5dd7070Spatrick 
1216e5dd7070Spatrick   // Determine if we need an implicit rethrow for all these catch handlers;
1217e5dd7070Spatrick   // see the comment below.
1218e5dd7070Spatrick   bool doImplicitRethrow = false;
1219e5dd7070Spatrick   if (IsFnTryBlock)
1220e5dd7070Spatrick     doImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
1221e5dd7070Spatrick                         isa<CXXConstructorDecl>(CurCodeDecl);
1222e5dd7070Spatrick 
1223e5dd7070Spatrick   // Wasm uses Windows-style EH instructions, but merges all catch clauses into
1224e5dd7070Spatrick   // one big catchpad. So we save the old funclet pad here before we traverse
1225e5dd7070Spatrick   // each catch handler.
1226*12c85518Srobert   SaveAndRestore RestoreCurrentFuncletPad(CurrentFuncletPad);
1227e5dd7070Spatrick   llvm::BasicBlock *WasmCatchStartBlock = nullptr;
1228e5dd7070Spatrick   if (EHPersonality::get(*this).isWasmPersonality()) {
1229e5dd7070Spatrick     auto *CatchSwitch =
1230e5dd7070Spatrick         cast<llvm::CatchSwitchInst>(DispatchBlock->getFirstNonPHI());
1231e5dd7070Spatrick     WasmCatchStartBlock = CatchSwitch->hasUnwindDest()
1232e5dd7070Spatrick                               ? CatchSwitch->getSuccessor(1)
1233e5dd7070Spatrick                               : CatchSwitch->getSuccessor(0);
1234e5dd7070Spatrick     auto *CPI = cast<llvm::CatchPadInst>(WasmCatchStartBlock->getFirstNonPHI());
1235e5dd7070Spatrick     CurrentFuncletPad = CPI;
1236e5dd7070Spatrick   }
1237e5dd7070Spatrick 
1238e5dd7070Spatrick   // Perversely, we emit the handlers backwards precisely because we
1239e5dd7070Spatrick   // want them to appear in source order.  In all of these cases, the
1240e5dd7070Spatrick   // catch block will have exactly one predecessor, which will be a
1241e5dd7070Spatrick   // particular block in the catch dispatch.  However, in the case of
1242e5dd7070Spatrick   // a catch-all, one of the dispatch blocks will branch to two
1243e5dd7070Spatrick   // different handlers, and EmitBlockAfterUses will cause the second
1244e5dd7070Spatrick   // handler to be moved before the first.
1245e5dd7070Spatrick   bool HasCatchAll = false;
1246e5dd7070Spatrick   for (unsigned I = NumHandlers; I != 0; --I) {
1247e5dd7070Spatrick     HasCatchAll |= Handlers[I - 1].isCatchAll();
1248e5dd7070Spatrick     llvm::BasicBlock *CatchBlock = Handlers[I-1].Block;
1249e5dd7070Spatrick     EmitBlockAfterUses(CatchBlock);
1250e5dd7070Spatrick 
1251e5dd7070Spatrick     // Catch the exception if this isn't a catch-all.
1252e5dd7070Spatrick     const CXXCatchStmt *C = S.getHandler(I-1);
1253e5dd7070Spatrick 
1254e5dd7070Spatrick     // Enter a cleanup scope, including the catch variable and the
1255e5dd7070Spatrick     // end-catch.
1256e5dd7070Spatrick     RunCleanupsScope CatchScope(*this);
1257e5dd7070Spatrick 
1258e5dd7070Spatrick     // Initialize the catch variable and set up the cleanups.
1259*12c85518Srobert     SaveAndRestore RestoreCurrentFuncletPad(CurrentFuncletPad);
1260e5dd7070Spatrick     CGM.getCXXABI().emitBeginCatch(*this, C);
1261e5dd7070Spatrick 
1262e5dd7070Spatrick     // Emit the PGO counter increment.
1263e5dd7070Spatrick     incrementProfileCounter(C);
1264e5dd7070Spatrick 
1265e5dd7070Spatrick     // Perform the body of the catch.
1266e5dd7070Spatrick     EmitStmt(C->getHandlerBlock());
1267e5dd7070Spatrick 
1268e5dd7070Spatrick     // [except.handle]p11:
1269e5dd7070Spatrick     //   The currently handled exception is rethrown if control
1270e5dd7070Spatrick     //   reaches the end of a handler of the function-try-block of a
1271e5dd7070Spatrick     //   constructor or destructor.
1272e5dd7070Spatrick 
1273e5dd7070Spatrick     // It is important that we only do this on fallthrough and not on
1274e5dd7070Spatrick     // return.  Note that it's illegal to put a return in a
1275e5dd7070Spatrick     // constructor function-try-block's catch handler (p14), so this
1276e5dd7070Spatrick     // really only applies to destructors.
1277e5dd7070Spatrick     if (doImplicitRethrow && HaveInsertPoint()) {
1278e5dd7070Spatrick       CGM.getCXXABI().emitRethrow(*this, /*isNoReturn*/false);
1279e5dd7070Spatrick       Builder.CreateUnreachable();
1280e5dd7070Spatrick       Builder.ClearInsertionPoint();
1281e5dd7070Spatrick     }
1282e5dd7070Spatrick 
1283e5dd7070Spatrick     // Fall out through the catch cleanups.
1284e5dd7070Spatrick     CatchScope.ForceCleanup();
1285e5dd7070Spatrick 
1286e5dd7070Spatrick     // Branch out of the try.
1287e5dd7070Spatrick     if (HaveInsertPoint())
1288e5dd7070Spatrick       Builder.CreateBr(ContBB);
1289e5dd7070Spatrick   }
1290e5dd7070Spatrick 
1291e5dd7070Spatrick   // Because in wasm we merge all catch clauses into one big catchpad, in case
1292e5dd7070Spatrick   // none of the types in catch handlers matches after we test against each of
1293e5dd7070Spatrick   // them, we should unwind to the next EH enclosing scope. We generate a call
1294e5dd7070Spatrick   // to rethrow function here to do that.
1295e5dd7070Spatrick   if (EHPersonality::get(*this).isWasmPersonality() && !HasCatchAll) {
1296e5dd7070Spatrick     assert(WasmCatchStartBlock);
1297e5dd7070Spatrick     // Navigate for the "rethrow" block we created in emitWasmCatchPadBlock().
1298e5dd7070Spatrick     // Wasm uses landingpad-style conditional branches to compare selectors, so
1299e5dd7070Spatrick     // we follow the false destination for each of the cond branches to reach
1300e5dd7070Spatrick     // the rethrow block.
1301e5dd7070Spatrick     llvm::BasicBlock *RethrowBlock = WasmCatchStartBlock;
1302e5dd7070Spatrick     while (llvm::Instruction *TI = RethrowBlock->getTerminator()) {
1303e5dd7070Spatrick       auto *BI = cast<llvm::BranchInst>(TI);
1304e5dd7070Spatrick       assert(BI->isConditional());
1305e5dd7070Spatrick       RethrowBlock = BI->getSuccessor(1);
1306e5dd7070Spatrick     }
1307e5dd7070Spatrick     assert(RethrowBlock != WasmCatchStartBlock && RethrowBlock->empty());
1308e5dd7070Spatrick     Builder.SetInsertPoint(RethrowBlock);
1309e5dd7070Spatrick     llvm::Function *RethrowInCatchFn =
1310a9ac8606Spatrick         CGM.getIntrinsic(llvm::Intrinsic::wasm_rethrow);
1311e5dd7070Spatrick     EmitNoreturnRuntimeCallOrInvoke(RethrowInCatchFn, {});
1312e5dd7070Spatrick   }
1313e5dd7070Spatrick 
1314e5dd7070Spatrick   EmitBlock(ContBB);
1315e5dd7070Spatrick   incrementProfileCounter(&S);
1316e5dd7070Spatrick }
1317e5dd7070Spatrick 
1318e5dd7070Spatrick namespace {
1319e5dd7070Spatrick   struct CallEndCatchForFinally final : EHScopeStack::Cleanup {
1320e5dd7070Spatrick     llvm::Value *ForEHVar;
1321e5dd7070Spatrick     llvm::FunctionCallee EndCatchFn;
CallEndCatchForFinally__anon650da12e0211::CallEndCatchForFinally1322e5dd7070Spatrick     CallEndCatchForFinally(llvm::Value *ForEHVar,
1323e5dd7070Spatrick                            llvm::FunctionCallee EndCatchFn)
1324e5dd7070Spatrick         : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
1325e5dd7070Spatrick 
Emit__anon650da12e0211::CallEndCatchForFinally1326e5dd7070Spatrick     void Emit(CodeGenFunction &CGF, Flags flags) override {
1327e5dd7070Spatrick       llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
1328e5dd7070Spatrick       llvm::BasicBlock *CleanupContBB =
1329e5dd7070Spatrick         CGF.createBasicBlock("finally.cleanup.cont");
1330e5dd7070Spatrick 
1331e5dd7070Spatrick       llvm::Value *ShouldEndCatch =
1332e5dd7070Spatrick         CGF.Builder.CreateFlagLoad(ForEHVar, "finally.endcatch");
1333e5dd7070Spatrick       CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1334e5dd7070Spatrick       CGF.EmitBlock(EndCatchBB);
1335e5dd7070Spatrick       CGF.EmitRuntimeCallOrInvoke(EndCatchFn); // catch-all, so might throw
1336e5dd7070Spatrick       CGF.EmitBlock(CleanupContBB);
1337e5dd7070Spatrick     }
1338e5dd7070Spatrick   };
1339e5dd7070Spatrick 
1340e5dd7070Spatrick   struct PerformFinally final : EHScopeStack::Cleanup {
1341e5dd7070Spatrick     const Stmt *Body;
1342e5dd7070Spatrick     llvm::Value *ForEHVar;
1343e5dd7070Spatrick     llvm::FunctionCallee EndCatchFn;
1344e5dd7070Spatrick     llvm::FunctionCallee RethrowFn;
1345e5dd7070Spatrick     llvm::Value *SavedExnVar;
1346e5dd7070Spatrick 
PerformFinally__anon650da12e0211::PerformFinally1347e5dd7070Spatrick     PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
1348e5dd7070Spatrick                    llvm::FunctionCallee EndCatchFn,
1349e5dd7070Spatrick                    llvm::FunctionCallee RethrowFn, llvm::Value *SavedExnVar)
1350e5dd7070Spatrick         : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1351e5dd7070Spatrick           RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
1352e5dd7070Spatrick 
Emit__anon650da12e0211::PerformFinally1353e5dd7070Spatrick     void Emit(CodeGenFunction &CGF, Flags flags) override {
1354e5dd7070Spatrick       // Enter a cleanup to call the end-catch function if one was provided.
1355e5dd7070Spatrick       if (EndCatchFn)
1356e5dd7070Spatrick         CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
1357e5dd7070Spatrick                                                         ForEHVar, EndCatchFn);
1358e5dd7070Spatrick 
1359e5dd7070Spatrick       // Save the current cleanup destination in case there are
1360e5dd7070Spatrick       // cleanups in the finally block.
1361e5dd7070Spatrick       llvm::Value *SavedCleanupDest =
1362e5dd7070Spatrick         CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
1363e5dd7070Spatrick                                "cleanup.dest.saved");
1364e5dd7070Spatrick 
1365e5dd7070Spatrick       // Emit the finally block.
1366e5dd7070Spatrick       CGF.EmitStmt(Body);
1367e5dd7070Spatrick 
1368e5dd7070Spatrick       // If the end of the finally is reachable, check whether this was
1369e5dd7070Spatrick       // for EH.  If so, rethrow.
1370e5dd7070Spatrick       if (CGF.HaveInsertPoint()) {
1371e5dd7070Spatrick         llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
1372e5dd7070Spatrick         llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
1373e5dd7070Spatrick 
1374e5dd7070Spatrick         llvm::Value *ShouldRethrow =
1375e5dd7070Spatrick           CGF.Builder.CreateFlagLoad(ForEHVar, "finally.shouldthrow");
1376e5dd7070Spatrick         CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1377e5dd7070Spatrick 
1378e5dd7070Spatrick         CGF.EmitBlock(RethrowBB);
1379e5dd7070Spatrick         if (SavedExnVar) {
1380e5dd7070Spatrick           CGF.EmitRuntimeCallOrInvoke(RethrowFn,
1381a9ac8606Spatrick             CGF.Builder.CreateAlignedLoad(CGF.Int8PtrTy, SavedExnVar,
1382a9ac8606Spatrick                                           CGF.getPointerAlign()));
1383e5dd7070Spatrick         } else {
1384e5dd7070Spatrick           CGF.EmitRuntimeCallOrInvoke(RethrowFn);
1385e5dd7070Spatrick         }
1386e5dd7070Spatrick         CGF.Builder.CreateUnreachable();
1387e5dd7070Spatrick 
1388e5dd7070Spatrick         CGF.EmitBlock(ContBB);
1389e5dd7070Spatrick 
1390e5dd7070Spatrick         // Restore the cleanup destination.
1391e5dd7070Spatrick         CGF.Builder.CreateStore(SavedCleanupDest,
1392e5dd7070Spatrick                                 CGF.getNormalCleanupDestSlot());
1393e5dd7070Spatrick       }
1394e5dd7070Spatrick 
1395e5dd7070Spatrick       // Leave the end-catch cleanup.  As an optimization, pretend that
1396e5dd7070Spatrick       // the fallthrough path was inaccessible; we've dynamically proven
1397e5dd7070Spatrick       // that we're not in the EH case along that path.
1398e5dd7070Spatrick       if (EndCatchFn) {
1399e5dd7070Spatrick         CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1400e5dd7070Spatrick         CGF.PopCleanupBlock();
1401e5dd7070Spatrick         CGF.Builder.restoreIP(SavedIP);
1402e5dd7070Spatrick       }
1403e5dd7070Spatrick 
1404e5dd7070Spatrick       // Now make sure we actually have an insertion point or the
1405e5dd7070Spatrick       // cleanup gods will hate us.
1406e5dd7070Spatrick       CGF.EnsureInsertPoint();
1407e5dd7070Spatrick     }
1408e5dd7070Spatrick   };
1409e5dd7070Spatrick } // end anonymous namespace
1410e5dd7070Spatrick 
1411e5dd7070Spatrick /// Enters a finally block for an implementation using zero-cost
1412e5dd7070Spatrick /// exceptions.  This is mostly general, but hard-codes some
1413e5dd7070Spatrick /// language/ABI-specific behavior in the catch-all sections.
enter(CodeGenFunction & CGF,const Stmt * body,llvm::FunctionCallee beginCatchFn,llvm::FunctionCallee endCatchFn,llvm::FunctionCallee rethrowFn)1414e5dd7070Spatrick void CodeGenFunction::FinallyInfo::enter(CodeGenFunction &CGF, const Stmt *body,
1415e5dd7070Spatrick                                          llvm::FunctionCallee beginCatchFn,
1416e5dd7070Spatrick                                          llvm::FunctionCallee endCatchFn,
1417e5dd7070Spatrick                                          llvm::FunctionCallee rethrowFn) {
1418e5dd7070Spatrick   assert((!!beginCatchFn) == (!!endCatchFn) &&
1419e5dd7070Spatrick          "begin/end catch functions not paired");
1420e5dd7070Spatrick   assert(rethrowFn && "rethrow function is required");
1421e5dd7070Spatrick 
1422e5dd7070Spatrick   BeginCatchFn = beginCatchFn;
1423e5dd7070Spatrick 
1424e5dd7070Spatrick   // The rethrow function has one of the following two types:
1425e5dd7070Spatrick   //   void (*)()
1426e5dd7070Spatrick   //   void (*)(void*)
1427e5dd7070Spatrick   // In the latter case we need to pass it the exception object.
1428e5dd7070Spatrick   // But we can't use the exception slot because the @finally might
1429e5dd7070Spatrick   // have a landing pad (which would overwrite the exception slot).
1430e5dd7070Spatrick   llvm::FunctionType *rethrowFnTy = rethrowFn.getFunctionType();
1431e5dd7070Spatrick   SavedExnVar = nullptr;
1432e5dd7070Spatrick   if (rethrowFnTy->getNumParams())
1433e5dd7070Spatrick     SavedExnVar = CGF.CreateTempAlloca(CGF.Int8PtrTy, "finally.exn");
1434e5dd7070Spatrick 
1435e5dd7070Spatrick   // A finally block is a statement which must be executed on any edge
1436e5dd7070Spatrick   // out of a given scope.  Unlike a cleanup, the finally block may
1437e5dd7070Spatrick   // contain arbitrary control flow leading out of itself.  In
1438e5dd7070Spatrick   // addition, finally blocks should always be executed, even if there
1439e5dd7070Spatrick   // are no catch handlers higher on the stack.  Therefore, we
1440e5dd7070Spatrick   // surround the protected scope with a combination of a normal
1441e5dd7070Spatrick   // cleanup (to catch attempts to break out of the block via normal
1442e5dd7070Spatrick   // control flow) and an EH catch-all (semantically "outside" any try
1443e5dd7070Spatrick   // statement to which the finally block might have been attached).
1444e5dd7070Spatrick   // The finally block itself is generated in the context of a cleanup
1445e5dd7070Spatrick   // which conditionally leaves the catch-all.
1446e5dd7070Spatrick 
1447e5dd7070Spatrick   // Jump destination for performing the finally block on an exception
1448e5dd7070Spatrick   // edge.  We'll never actually reach this block, so unreachable is
1449e5dd7070Spatrick   // fine.
1450e5dd7070Spatrick   RethrowDest = CGF.getJumpDestInCurrentScope(CGF.getUnreachableBlock());
1451e5dd7070Spatrick 
1452e5dd7070Spatrick   // Whether the finally block is being executed for EH purposes.
1453e5dd7070Spatrick   ForEHVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "finally.for-eh");
1454e5dd7070Spatrick   CGF.Builder.CreateFlagStore(false, ForEHVar);
1455e5dd7070Spatrick 
1456e5dd7070Spatrick   // Enter a normal cleanup which will perform the @finally block.
1457e5dd7070Spatrick   CGF.EHStack.pushCleanup<PerformFinally>(NormalCleanup, body,
1458e5dd7070Spatrick                                           ForEHVar, endCatchFn,
1459e5dd7070Spatrick                                           rethrowFn, SavedExnVar);
1460e5dd7070Spatrick 
1461e5dd7070Spatrick   // Enter a catch-all scope.
1462e5dd7070Spatrick   llvm::BasicBlock *catchBB = CGF.createBasicBlock("finally.catchall");
1463e5dd7070Spatrick   EHCatchScope *catchScope = CGF.EHStack.pushCatch(1);
1464e5dd7070Spatrick   catchScope->setCatchAllHandler(0, catchBB);
1465e5dd7070Spatrick }
1466e5dd7070Spatrick 
exit(CodeGenFunction & CGF)1467e5dd7070Spatrick void CodeGenFunction::FinallyInfo::exit(CodeGenFunction &CGF) {
1468e5dd7070Spatrick   // Leave the finally catch-all.
1469e5dd7070Spatrick   EHCatchScope &catchScope = cast<EHCatchScope>(*CGF.EHStack.begin());
1470e5dd7070Spatrick   llvm::BasicBlock *catchBB = catchScope.getHandler(0).Block;
1471e5dd7070Spatrick 
1472e5dd7070Spatrick   CGF.popCatchScope();
1473e5dd7070Spatrick 
1474e5dd7070Spatrick   // If there are any references to the catch-all block, emit it.
1475e5dd7070Spatrick   if (catchBB->use_empty()) {
1476e5dd7070Spatrick     delete catchBB;
1477e5dd7070Spatrick   } else {
1478e5dd7070Spatrick     CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveAndClearIP();
1479e5dd7070Spatrick     CGF.EmitBlock(catchBB);
1480e5dd7070Spatrick 
1481e5dd7070Spatrick     llvm::Value *exn = nullptr;
1482e5dd7070Spatrick 
1483e5dd7070Spatrick     // If there's a begin-catch function, call it.
1484e5dd7070Spatrick     if (BeginCatchFn) {
1485e5dd7070Spatrick       exn = CGF.getExceptionFromSlot();
1486e5dd7070Spatrick       CGF.EmitNounwindRuntimeCall(BeginCatchFn, exn);
1487e5dd7070Spatrick     }
1488e5dd7070Spatrick 
1489e5dd7070Spatrick     // If we need to remember the exception pointer to rethrow later, do so.
1490e5dd7070Spatrick     if (SavedExnVar) {
1491e5dd7070Spatrick       if (!exn) exn = CGF.getExceptionFromSlot();
1492e5dd7070Spatrick       CGF.Builder.CreateAlignedStore(exn, SavedExnVar, CGF.getPointerAlign());
1493e5dd7070Spatrick     }
1494e5dd7070Spatrick 
1495e5dd7070Spatrick     // Tell the cleanups in the finally block that we're do this for EH.
1496e5dd7070Spatrick     CGF.Builder.CreateFlagStore(true, ForEHVar);
1497e5dd7070Spatrick 
1498e5dd7070Spatrick     // Thread a jump through the finally cleanup.
1499e5dd7070Spatrick     CGF.EmitBranchThroughCleanup(RethrowDest);
1500e5dd7070Spatrick 
1501e5dd7070Spatrick     CGF.Builder.restoreIP(savedIP);
1502e5dd7070Spatrick   }
1503e5dd7070Spatrick 
1504e5dd7070Spatrick   // Finally, leave the @finally cleanup.
1505e5dd7070Spatrick   CGF.PopCleanupBlock();
1506e5dd7070Spatrick }
1507e5dd7070Spatrick 
getTerminateLandingPad()1508e5dd7070Spatrick llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
1509e5dd7070Spatrick   if (TerminateLandingPad)
1510e5dd7070Spatrick     return TerminateLandingPad;
1511e5dd7070Spatrick 
1512e5dd7070Spatrick   CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1513e5dd7070Spatrick 
1514e5dd7070Spatrick   // This will get inserted at the end of the function.
1515e5dd7070Spatrick   TerminateLandingPad = createBasicBlock("terminate.lpad");
1516e5dd7070Spatrick   Builder.SetInsertPoint(TerminateLandingPad);
1517e5dd7070Spatrick 
1518e5dd7070Spatrick   // Tell the backend that this is a landing pad.
1519e5dd7070Spatrick   const EHPersonality &Personality = EHPersonality::get(*this);
1520e5dd7070Spatrick 
1521e5dd7070Spatrick   if (!CurFn->hasPersonalityFn())
1522e5dd7070Spatrick     CurFn->setPersonalityFn(getOpaquePersonalityFn(CGM, Personality));
1523e5dd7070Spatrick 
1524e5dd7070Spatrick   llvm::LandingPadInst *LPadInst =
1525e5dd7070Spatrick       Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty), 0);
1526e5dd7070Spatrick   LPadInst->addClause(getCatchAllValue(*this));
1527e5dd7070Spatrick 
1528e5dd7070Spatrick   llvm::Value *Exn = nullptr;
1529e5dd7070Spatrick   if (getLangOpts().CPlusPlus)
1530e5dd7070Spatrick     Exn = Builder.CreateExtractValue(LPadInst, 0);
1531e5dd7070Spatrick   llvm::CallInst *terminateCall =
1532e5dd7070Spatrick       CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
1533e5dd7070Spatrick   terminateCall->setDoesNotReturn();
1534e5dd7070Spatrick   Builder.CreateUnreachable();
1535e5dd7070Spatrick 
1536e5dd7070Spatrick   // Restore the saved insertion state.
1537e5dd7070Spatrick   Builder.restoreIP(SavedIP);
1538e5dd7070Spatrick 
1539e5dd7070Spatrick   return TerminateLandingPad;
1540e5dd7070Spatrick }
1541e5dd7070Spatrick 
getTerminateHandler()1542e5dd7070Spatrick llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
1543e5dd7070Spatrick   if (TerminateHandler)
1544e5dd7070Spatrick     return TerminateHandler;
1545e5dd7070Spatrick 
1546e5dd7070Spatrick   // Set up the terminate handler.  This block is inserted at the very
1547e5dd7070Spatrick   // end of the function by FinishFunction.
1548e5dd7070Spatrick   TerminateHandler = createBasicBlock("terminate.handler");
1549e5dd7070Spatrick   CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1550e5dd7070Spatrick   Builder.SetInsertPoint(TerminateHandler);
1551e5dd7070Spatrick 
1552e5dd7070Spatrick   llvm::Value *Exn = nullptr;
1553e5dd7070Spatrick   if (getLangOpts().CPlusPlus)
1554e5dd7070Spatrick     Exn = getExceptionFromSlot();
1555e5dd7070Spatrick   llvm::CallInst *terminateCall =
1556e5dd7070Spatrick       CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
1557e5dd7070Spatrick   terminateCall->setDoesNotReturn();
1558e5dd7070Spatrick   Builder.CreateUnreachable();
1559e5dd7070Spatrick 
1560e5dd7070Spatrick   // Restore the saved insertion state.
1561e5dd7070Spatrick   Builder.restoreIP(SavedIP);
1562e5dd7070Spatrick 
1563e5dd7070Spatrick   return TerminateHandler;
1564e5dd7070Spatrick }
1565e5dd7070Spatrick 
getTerminateFunclet()1566e5dd7070Spatrick llvm::BasicBlock *CodeGenFunction::getTerminateFunclet() {
1567e5dd7070Spatrick   assert(EHPersonality::get(*this).usesFuncletPads() &&
1568e5dd7070Spatrick          "use getTerminateLandingPad for non-funclet EH");
1569e5dd7070Spatrick 
1570e5dd7070Spatrick   llvm::BasicBlock *&TerminateFunclet = TerminateFunclets[CurrentFuncletPad];
1571e5dd7070Spatrick   if (TerminateFunclet)
1572e5dd7070Spatrick     return TerminateFunclet;
1573e5dd7070Spatrick 
1574e5dd7070Spatrick   CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1575e5dd7070Spatrick 
1576e5dd7070Spatrick   // Set up the terminate handler.  This block is inserted at the very
1577e5dd7070Spatrick   // end of the function by FinishFunction.
1578e5dd7070Spatrick   TerminateFunclet = createBasicBlock("terminate.handler");
1579e5dd7070Spatrick   Builder.SetInsertPoint(TerminateFunclet);
1580e5dd7070Spatrick 
1581e5dd7070Spatrick   // Create the cleanuppad using the current parent pad as its token. Use 'none'
1582e5dd7070Spatrick   // if this is a top-level terminate scope, which is the common case.
1583*12c85518Srobert   SaveAndRestore RestoreCurrentFuncletPad(CurrentFuncletPad);
1584e5dd7070Spatrick   llvm::Value *ParentPad = CurrentFuncletPad;
1585e5dd7070Spatrick   if (!ParentPad)
1586e5dd7070Spatrick     ParentPad = llvm::ConstantTokenNone::get(CGM.getLLVMContext());
1587e5dd7070Spatrick   CurrentFuncletPad = Builder.CreateCleanupPad(ParentPad);
1588e5dd7070Spatrick 
1589e5dd7070Spatrick   // Emit the __std_terminate call.
1590e5dd7070Spatrick   llvm::CallInst *terminateCall =
1591a9ac8606Spatrick       CGM.getCXXABI().emitTerminateForUnexpectedException(*this, nullptr);
1592e5dd7070Spatrick   terminateCall->setDoesNotReturn();
1593e5dd7070Spatrick   Builder.CreateUnreachable();
1594e5dd7070Spatrick 
1595e5dd7070Spatrick   // Restore the saved insertion state.
1596e5dd7070Spatrick   Builder.restoreIP(SavedIP);
1597e5dd7070Spatrick 
1598e5dd7070Spatrick   return TerminateFunclet;
1599e5dd7070Spatrick }
1600e5dd7070Spatrick 
getEHResumeBlock(bool isCleanup)1601e5dd7070Spatrick llvm::BasicBlock *CodeGenFunction::getEHResumeBlock(bool isCleanup) {
1602e5dd7070Spatrick   if (EHResumeBlock) return EHResumeBlock;
1603e5dd7070Spatrick 
1604e5dd7070Spatrick   CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1605e5dd7070Spatrick 
1606e5dd7070Spatrick   // We emit a jump to a notional label at the outermost unwind state.
1607e5dd7070Spatrick   EHResumeBlock = createBasicBlock("eh.resume");
1608e5dd7070Spatrick   Builder.SetInsertPoint(EHResumeBlock);
1609e5dd7070Spatrick 
1610e5dd7070Spatrick   const EHPersonality &Personality = EHPersonality::get(*this);
1611e5dd7070Spatrick 
1612e5dd7070Spatrick   // This can always be a call because we necessarily didn't find
1613e5dd7070Spatrick   // anything on the EH stack which needs our help.
1614e5dd7070Spatrick   const char *RethrowName = Personality.CatchallRethrowFn;
1615e5dd7070Spatrick   if (RethrowName != nullptr && !isCleanup) {
1616e5dd7070Spatrick     EmitRuntimeCall(getCatchallRethrowFn(CGM, RethrowName),
1617e5dd7070Spatrick                     getExceptionFromSlot())->setDoesNotReturn();
1618e5dd7070Spatrick     Builder.CreateUnreachable();
1619e5dd7070Spatrick     Builder.restoreIP(SavedIP);
1620e5dd7070Spatrick     return EHResumeBlock;
1621e5dd7070Spatrick   }
1622e5dd7070Spatrick 
1623e5dd7070Spatrick   // Recreate the landingpad's return value for the 'resume' instruction.
1624e5dd7070Spatrick   llvm::Value *Exn = getExceptionFromSlot();
1625e5dd7070Spatrick   llvm::Value *Sel = getSelectorFromSlot();
1626e5dd7070Spatrick 
1627e5dd7070Spatrick   llvm::Type *LPadType = llvm::StructType::get(Exn->getType(), Sel->getType());
1628*12c85518Srobert   llvm::Value *LPadVal = llvm::PoisonValue::get(LPadType);
1629e5dd7070Spatrick   LPadVal = Builder.CreateInsertValue(LPadVal, Exn, 0, "lpad.val");
1630e5dd7070Spatrick   LPadVal = Builder.CreateInsertValue(LPadVal, Sel, 1, "lpad.val");
1631e5dd7070Spatrick 
1632e5dd7070Spatrick   Builder.CreateResume(LPadVal);
1633e5dd7070Spatrick   Builder.restoreIP(SavedIP);
1634e5dd7070Spatrick   return EHResumeBlock;
1635e5dd7070Spatrick }
1636e5dd7070Spatrick 
EmitSEHTryStmt(const SEHTryStmt & S)1637e5dd7070Spatrick void CodeGenFunction::EmitSEHTryStmt(const SEHTryStmt &S) {
1638e5dd7070Spatrick   EnterSEHTryStmt(S);
1639e5dd7070Spatrick   {
1640e5dd7070Spatrick     JumpDest TryExit = getJumpDestInCurrentScope("__try.__leave");
1641e5dd7070Spatrick 
1642e5dd7070Spatrick     SEHTryEpilogueStack.push_back(&TryExit);
1643a9ac8606Spatrick 
1644a9ac8606Spatrick     llvm::BasicBlock *TryBB = nullptr;
1645a9ac8606Spatrick     // IsEHa: emit an invoke to _seh_try_begin() runtime for -EHa
1646a9ac8606Spatrick     if (getLangOpts().EHAsynch) {
1647a9ac8606Spatrick       EmitRuntimeCallOrInvoke(getSehTryBeginFn(CGM));
1648a9ac8606Spatrick       if (SEHTryEpilogueStack.size() == 1) // outermost only
1649a9ac8606Spatrick         TryBB = Builder.GetInsertBlock();
1650a9ac8606Spatrick     }
1651a9ac8606Spatrick 
1652e5dd7070Spatrick     EmitStmt(S.getTryBlock());
1653a9ac8606Spatrick 
1654a9ac8606Spatrick     // Volatilize all blocks in Try, till current insert point
1655a9ac8606Spatrick     if (TryBB) {
1656a9ac8606Spatrick       llvm::SmallPtrSet<llvm::BasicBlock *, 10> Visited;
1657a9ac8606Spatrick       VolatilizeTryBlocks(TryBB, Visited);
1658a9ac8606Spatrick     }
1659a9ac8606Spatrick 
1660e5dd7070Spatrick     SEHTryEpilogueStack.pop_back();
1661e5dd7070Spatrick 
1662e5dd7070Spatrick     if (!TryExit.getBlock()->use_empty())
1663e5dd7070Spatrick       EmitBlock(TryExit.getBlock(), /*IsFinished=*/true);
1664e5dd7070Spatrick     else
1665e5dd7070Spatrick       delete TryExit.getBlock();
1666e5dd7070Spatrick   }
1667e5dd7070Spatrick   ExitSEHTryStmt(S);
1668e5dd7070Spatrick }
1669e5dd7070Spatrick 
1670a9ac8606Spatrick //  Recursively walk through blocks in a _try
1671a9ac8606Spatrick //      and make all memory instructions volatile
VolatilizeTryBlocks(llvm::BasicBlock * BB,llvm::SmallPtrSet<llvm::BasicBlock *,10> & V)1672a9ac8606Spatrick void CodeGenFunction::VolatilizeTryBlocks(
1673a9ac8606Spatrick     llvm::BasicBlock *BB, llvm::SmallPtrSet<llvm::BasicBlock *, 10> &V) {
1674a9ac8606Spatrick   if (BB == SEHTryEpilogueStack.back()->getBlock() /* end of Try */ ||
1675a9ac8606Spatrick       !V.insert(BB).second /* already visited */ ||
1676a9ac8606Spatrick       !BB->getParent() /* not emitted */ || BB->empty())
1677a9ac8606Spatrick     return;
1678a9ac8606Spatrick 
1679a9ac8606Spatrick   if (!BB->isEHPad()) {
1680a9ac8606Spatrick     for (llvm::BasicBlock::iterator J = BB->begin(), JE = BB->end(); J != JE;
1681a9ac8606Spatrick          ++J) {
1682a9ac8606Spatrick       if (auto LI = dyn_cast<llvm::LoadInst>(J)) {
1683a9ac8606Spatrick         LI->setVolatile(true);
1684a9ac8606Spatrick       } else if (auto SI = dyn_cast<llvm::StoreInst>(J)) {
1685a9ac8606Spatrick         SI->setVolatile(true);
1686a9ac8606Spatrick       } else if (auto* MCI = dyn_cast<llvm::MemIntrinsic>(J)) {
1687a9ac8606Spatrick         MCI->setVolatile(llvm::ConstantInt::get(Builder.getInt1Ty(), 1));
1688a9ac8606Spatrick       }
1689a9ac8606Spatrick     }
1690a9ac8606Spatrick   }
1691a9ac8606Spatrick   const llvm::Instruction *TI = BB->getTerminator();
1692a9ac8606Spatrick   if (TI) {
1693a9ac8606Spatrick     unsigned N = TI->getNumSuccessors();
1694a9ac8606Spatrick     for (unsigned I = 0; I < N; I++)
1695a9ac8606Spatrick       VolatilizeTryBlocks(TI->getSuccessor(I), V);
1696a9ac8606Spatrick   }
1697a9ac8606Spatrick }
1698a9ac8606Spatrick 
1699e5dd7070Spatrick namespace {
1700e5dd7070Spatrick struct PerformSEHFinally final : EHScopeStack::Cleanup {
1701e5dd7070Spatrick   llvm::Function *OutlinedFinally;
PerformSEHFinally__anon650da12e0311::PerformSEHFinally1702e5dd7070Spatrick   PerformSEHFinally(llvm::Function *OutlinedFinally)
1703e5dd7070Spatrick       : OutlinedFinally(OutlinedFinally) {}
1704e5dd7070Spatrick 
Emit__anon650da12e0311::PerformSEHFinally1705e5dd7070Spatrick   void Emit(CodeGenFunction &CGF, Flags F) override {
1706e5dd7070Spatrick     ASTContext &Context = CGF.getContext();
1707e5dd7070Spatrick     CodeGenModule &CGM = CGF.CGM;
1708e5dd7070Spatrick 
1709e5dd7070Spatrick     CallArgList Args;
1710e5dd7070Spatrick 
1711e5dd7070Spatrick     // Compute the two argument values.
1712e5dd7070Spatrick     QualType ArgTys[2] = {Context.UnsignedCharTy, Context.VoidPtrTy};
1713e5dd7070Spatrick     llvm::Value *FP = nullptr;
1714e5dd7070Spatrick     // If CFG.IsOutlinedSEHHelper is true, then we are within a finally block.
1715e5dd7070Spatrick     if (CGF.IsOutlinedSEHHelper) {
1716e5dd7070Spatrick       FP = &CGF.CurFn->arg_begin()[1];
1717e5dd7070Spatrick     } else {
1718e5dd7070Spatrick       llvm::Function *LocalAddrFn =
1719e5dd7070Spatrick           CGM.getIntrinsic(llvm::Intrinsic::localaddress);
1720e5dd7070Spatrick       FP = CGF.Builder.CreateCall(LocalAddrFn);
1721e5dd7070Spatrick     }
1722e5dd7070Spatrick 
1723e5dd7070Spatrick     llvm::Value *IsForEH =
1724e5dd7070Spatrick         llvm::ConstantInt::get(CGF.ConvertType(ArgTys[0]), F.isForEHCleanup());
1725ec727ea7Spatrick 
1726ec727ea7Spatrick     // Except _leave and fall-through at the end, all other exits in a _try
1727ec727ea7Spatrick     //   (return/goto/continue/break) are considered as abnormal terminations
1728ec727ea7Spatrick     //   since _leave/fall-through is always Indexed 0,
1729ec727ea7Spatrick     //   just use NormalCleanupDestSlot (>= 1 for goto/return/..),
1730ec727ea7Spatrick     //   as 1st Arg to indicate abnormal termination
1731ec727ea7Spatrick     if (!F.isForEHCleanup() && F.hasExitSwitch()) {
1732ec727ea7Spatrick       Address Addr = CGF.getNormalCleanupDestSlot();
1733ec727ea7Spatrick       llvm::Value *Load = CGF.Builder.CreateLoad(Addr, "cleanup.dest");
1734ec727ea7Spatrick       llvm::Value *Zero = llvm::Constant::getNullValue(CGM.Int32Ty);
1735ec727ea7Spatrick       IsForEH = CGF.Builder.CreateICmpNE(Load, Zero);
1736ec727ea7Spatrick     }
1737ec727ea7Spatrick 
1738e5dd7070Spatrick     Args.add(RValue::get(IsForEH), ArgTys[0]);
1739e5dd7070Spatrick     Args.add(RValue::get(FP), ArgTys[1]);
1740e5dd7070Spatrick 
1741e5dd7070Spatrick     // Arrange a two-arg function info and type.
1742e5dd7070Spatrick     const CGFunctionInfo &FnInfo =
1743e5dd7070Spatrick         CGM.getTypes().arrangeBuiltinFunctionCall(Context.VoidTy, Args);
1744e5dd7070Spatrick 
1745e5dd7070Spatrick     auto Callee = CGCallee::forDirect(OutlinedFinally);
1746e5dd7070Spatrick     CGF.EmitCall(FnInfo, Callee, ReturnValueSlot(), Args);
1747e5dd7070Spatrick   }
1748e5dd7070Spatrick };
1749e5dd7070Spatrick } // end anonymous namespace
1750e5dd7070Spatrick 
1751e5dd7070Spatrick namespace {
1752e5dd7070Spatrick /// Find all local variable captures in the statement.
1753e5dd7070Spatrick struct CaptureFinder : ConstStmtVisitor<CaptureFinder> {
1754e5dd7070Spatrick   CodeGenFunction &ParentCGF;
1755e5dd7070Spatrick   const VarDecl *ParentThis;
1756e5dd7070Spatrick   llvm::SmallSetVector<const VarDecl *, 4> Captures;
1757e5dd7070Spatrick   Address SEHCodeSlot = Address::invalid();
CaptureFinder__anon650da12e0411::CaptureFinder1758e5dd7070Spatrick   CaptureFinder(CodeGenFunction &ParentCGF, const VarDecl *ParentThis)
1759e5dd7070Spatrick       : ParentCGF(ParentCGF), ParentThis(ParentThis) {}
1760e5dd7070Spatrick 
1761e5dd7070Spatrick   // Return true if we need to do any capturing work.
foundCaptures__anon650da12e0411::CaptureFinder1762e5dd7070Spatrick   bool foundCaptures() {
1763e5dd7070Spatrick     return !Captures.empty() || SEHCodeSlot.isValid();
1764e5dd7070Spatrick   }
1765e5dd7070Spatrick 
Visit__anon650da12e0411::CaptureFinder1766e5dd7070Spatrick   void Visit(const Stmt *S) {
1767e5dd7070Spatrick     // See if this is a capture, then recurse.
1768e5dd7070Spatrick     ConstStmtVisitor<CaptureFinder>::Visit(S);
1769e5dd7070Spatrick     for (const Stmt *Child : S->children())
1770e5dd7070Spatrick       if (Child)
1771e5dd7070Spatrick         Visit(Child);
1772e5dd7070Spatrick   }
1773e5dd7070Spatrick 
VisitDeclRefExpr__anon650da12e0411::CaptureFinder1774e5dd7070Spatrick   void VisitDeclRefExpr(const DeclRefExpr *E) {
1775e5dd7070Spatrick     // If this is already a capture, just make sure we capture 'this'.
1776a9ac8606Spatrick     if (E->refersToEnclosingVariableOrCapture())
1777e5dd7070Spatrick       Captures.insert(ParentThis);
1778e5dd7070Spatrick 
1779e5dd7070Spatrick     const auto *D = dyn_cast<VarDecl>(E->getDecl());
1780e5dd7070Spatrick     if (D && D->isLocalVarDeclOrParm() && D->hasLocalStorage())
1781e5dd7070Spatrick       Captures.insert(D);
1782e5dd7070Spatrick   }
1783e5dd7070Spatrick 
VisitCXXThisExpr__anon650da12e0411::CaptureFinder1784e5dd7070Spatrick   void VisitCXXThisExpr(const CXXThisExpr *E) {
1785e5dd7070Spatrick     Captures.insert(ParentThis);
1786e5dd7070Spatrick   }
1787e5dd7070Spatrick 
VisitCallExpr__anon650da12e0411::CaptureFinder1788e5dd7070Spatrick   void VisitCallExpr(const CallExpr *E) {
1789e5dd7070Spatrick     // We only need to add parent frame allocations for these builtins in x86.
1790e5dd7070Spatrick     if (ParentCGF.getTarget().getTriple().getArch() != llvm::Triple::x86)
1791e5dd7070Spatrick       return;
1792e5dd7070Spatrick 
1793e5dd7070Spatrick     unsigned ID = E->getBuiltinCallee();
1794e5dd7070Spatrick     switch (ID) {
1795e5dd7070Spatrick     case Builtin::BI__exception_code:
1796e5dd7070Spatrick     case Builtin::BI_exception_code:
1797e5dd7070Spatrick       // This is the simple case where we are the outermost finally. All we
1798e5dd7070Spatrick       // have to do here is make sure we escape this and recover it in the
1799e5dd7070Spatrick       // outlined handler.
1800e5dd7070Spatrick       if (!SEHCodeSlot.isValid())
1801e5dd7070Spatrick         SEHCodeSlot = ParentCGF.SEHCodeSlotStack.back();
1802e5dd7070Spatrick       break;
1803e5dd7070Spatrick     }
1804e5dd7070Spatrick   }
1805e5dd7070Spatrick };
1806e5dd7070Spatrick } // end anonymous namespace
1807e5dd7070Spatrick 
recoverAddrOfEscapedLocal(CodeGenFunction & ParentCGF,Address ParentVar,llvm::Value * ParentFP)1808e5dd7070Spatrick Address CodeGenFunction::recoverAddrOfEscapedLocal(CodeGenFunction &ParentCGF,
1809e5dd7070Spatrick                                                    Address ParentVar,
1810e5dd7070Spatrick                                                    llvm::Value *ParentFP) {
1811e5dd7070Spatrick   llvm::CallInst *RecoverCall = nullptr;
1812e5dd7070Spatrick   CGBuilderTy Builder(*this, AllocaInsertPt);
1813e5dd7070Spatrick   if (auto *ParentAlloca = dyn_cast<llvm::AllocaInst>(ParentVar.getPointer())) {
1814e5dd7070Spatrick     // Mark the variable escaped if nobody else referenced it and compute the
1815e5dd7070Spatrick     // localescape index.
1816e5dd7070Spatrick     auto InsertPair = ParentCGF.EscapedLocals.insert(
1817e5dd7070Spatrick         std::make_pair(ParentAlloca, ParentCGF.EscapedLocals.size()));
1818e5dd7070Spatrick     int FrameEscapeIdx = InsertPair.first->second;
1819e5dd7070Spatrick     // call i8* @llvm.localrecover(i8* bitcast(@parentFn), i8* %fp, i32 N)
1820e5dd7070Spatrick     llvm::Function *FrameRecoverFn = llvm::Intrinsic::getDeclaration(
1821e5dd7070Spatrick         &CGM.getModule(), llvm::Intrinsic::localrecover);
1822e5dd7070Spatrick     llvm::Constant *ParentI8Fn =
1823e5dd7070Spatrick         llvm::ConstantExpr::getBitCast(ParentCGF.CurFn, Int8PtrTy);
1824e5dd7070Spatrick     RecoverCall = Builder.CreateCall(
1825e5dd7070Spatrick         FrameRecoverFn, {ParentI8Fn, ParentFP,
1826e5dd7070Spatrick                          llvm::ConstantInt::get(Int32Ty, FrameEscapeIdx)});
1827e5dd7070Spatrick 
1828e5dd7070Spatrick   } else {
1829e5dd7070Spatrick     // If the parent didn't have an alloca, we're doing some nested outlining.
1830e5dd7070Spatrick     // Just clone the existing localrecover call, but tweak the FP argument to
1831e5dd7070Spatrick     // use our FP value. All other arguments are constants.
1832e5dd7070Spatrick     auto *ParentRecover =
1833e5dd7070Spatrick         cast<llvm::IntrinsicInst>(ParentVar.getPointer()->stripPointerCasts());
1834e5dd7070Spatrick     assert(ParentRecover->getIntrinsicID() == llvm::Intrinsic::localrecover &&
1835e5dd7070Spatrick            "expected alloca or localrecover in parent LocalDeclMap");
1836e5dd7070Spatrick     RecoverCall = cast<llvm::CallInst>(ParentRecover->clone());
1837e5dd7070Spatrick     RecoverCall->setArgOperand(1, ParentFP);
1838e5dd7070Spatrick     RecoverCall->insertBefore(AllocaInsertPt);
1839e5dd7070Spatrick   }
1840e5dd7070Spatrick 
1841e5dd7070Spatrick   // Bitcast the variable, rename it, and insert it in the local decl map.
1842e5dd7070Spatrick   llvm::Value *ChildVar =
1843e5dd7070Spatrick       Builder.CreateBitCast(RecoverCall, ParentVar.getType());
1844e5dd7070Spatrick   ChildVar->setName(ParentVar.getName());
1845*12c85518Srobert   return ParentVar.withPointer(ChildVar);
1846e5dd7070Spatrick }
1847e5dd7070Spatrick 
EmitCapturedLocals(CodeGenFunction & ParentCGF,const Stmt * OutlinedStmt,bool IsFilter)1848e5dd7070Spatrick void CodeGenFunction::EmitCapturedLocals(CodeGenFunction &ParentCGF,
1849e5dd7070Spatrick                                          const Stmt *OutlinedStmt,
1850e5dd7070Spatrick                                          bool IsFilter) {
1851e5dd7070Spatrick   // Find all captures in the Stmt.
1852e5dd7070Spatrick   CaptureFinder Finder(ParentCGF, ParentCGF.CXXABIThisDecl);
1853e5dd7070Spatrick   Finder.Visit(OutlinedStmt);
1854e5dd7070Spatrick 
1855e5dd7070Spatrick   // We can exit early on x86_64 when there are no captures. We just have to
1856e5dd7070Spatrick   // save the exception code in filters so that __exception_code() works.
1857e5dd7070Spatrick   if (!Finder.foundCaptures() &&
1858e5dd7070Spatrick       CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
1859e5dd7070Spatrick     if (IsFilter)
1860e5dd7070Spatrick       EmitSEHExceptionCodeSave(ParentCGF, nullptr, nullptr);
1861e5dd7070Spatrick     return;
1862e5dd7070Spatrick   }
1863e5dd7070Spatrick 
1864e5dd7070Spatrick   llvm::Value *EntryFP = nullptr;
1865e5dd7070Spatrick   CGBuilderTy Builder(CGM, AllocaInsertPt);
1866e5dd7070Spatrick   if (IsFilter && CGM.getTarget().getTriple().getArch() == llvm::Triple::x86) {
1867e5dd7070Spatrick     // 32-bit SEH filters need to be careful about FP recovery.  The end of the
1868e5dd7070Spatrick     // EH registration is passed in as the EBP physical register.  We can
1869e5dd7070Spatrick     // recover that with llvm.frameaddress(1).
1870e5dd7070Spatrick     EntryFP = Builder.CreateCall(
1871e5dd7070Spatrick         CGM.getIntrinsic(llvm::Intrinsic::frameaddress, AllocaInt8PtrTy),
1872e5dd7070Spatrick         {Builder.getInt32(1)});
1873e5dd7070Spatrick   } else {
1874e5dd7070Spatrick     // Otherwise, for x64 and 32-bit finally functions, the parent FP is the
1875e5dd7070Spatrick     // second parameter.
1876e5dd7070Spatrick     auto AI = CurFn->arg_begin();
1877e5dd7070Spatrick     ++AI;
1878e5dd7070Spatrick     EntryFP = &*AI;
1879e5dd7070Spatrick   }
1880e5dd7070Spatrick 
1881e5dd7070Spatrick   llvm::Value *ParentFP = EntryFP;
1882e5dd7070Spatrick   if (IsFilter) {
1883e5dd7070Spatrick     // Given whatever FP the runtime provided us in EntryFP, recover the true
1884e5dd7070Spatrick     // frame pointer of the parent function. We only need to do this in filters,
1885e5dd7070Spatrick     // since finally funclets recover the parent FP for us.
1886e5dd7070Spatrick     llvm::Function *RecoverFPIntrin =
1887e5dd7070Spatrick         CGM.getIntrinsic(llvm::Intrinsic::eh_recoverfp);
1888e5dd7070Spatrick     llvm::Constant *ParentI8Fn =
1889e5dd7070Spatrick         llvm::ConstantExpr::getBitCast(ParentCGF.CurFn, Int8PtrTy);
1890e5dd7070Spatrick     ParentFP = Builder.CreateCall(RecoverFPIntrin, {ParentI8Fn, EntryFP});
1891ec727ea7Spatrick 
1892ec727ea7Spatrick     // if the parent is a _finally, the passed-in ParentFP is the FP
1893ec727ea7Spatrick     // of parent _finally, not Establisher's FP (FP of outermost function).
1894ec727ea7Spatrick     // Establkisher FP is 2nd paramenter passed into parent _finally.
1895ec727ea7Spatrick     // Fortunately, it's always saved in parent's frame. The following
1896ec727ea7Spatrick     // code retrieves it, and escapes it so that spill instruction won't be
1897ec727ea7Spatrick     // optimized away.
1898ec727ea7Spatrick     if (ParentCGF.ParentCGF != nullptr) {
1899ec727ea7Spatrick       // Locate and escape Parent's frame_pointer.addr alloca
1900ec727ea7Spatrick       // Depending on target, should be 1st/2nd one in LocalDeclMap.
1901ec727ea7Spatrick       // Let's just scan for ImplicitParamDecl with VoidPtrTy.
1902ec727ea7Spatrick       llvm::AllocaInst *FramePtrAddrAlloca = nullptr;
1903ec727ea7Spatrick       for (auto &I : ParentCGF.LocalDeclMap) {
1904ec727ea7Spatrick         const VarDecl *D = cast<VarDecl>(I.first);
1905ec727ea7Spatrick         if (isa<ImplicitParamDecl>(D) &&
1906ec727ea7Spatrick             D->getType() == getContext().VoidPtrTy) {
1907ec727ea7Spatrick           assert(D->getName().startswith("frame_pointer"));
1908ec727ea7Spatrick           FramePtrAddrAlloca = cast<llvm::AllocaInst>(I.second.getPointer());
1909ec727ea7Spatrick           break;
1910ec727ea7Spatrick         }
1911ec727ea7Spatrick       }
1912ec727ea7Spatrick       assert(FramePtrAddrAlloca);
1913ec727ea7Spatrick       auto InsertPair = ParentCGF.EscapedLocals.insert(
1914ec727ea7Spatrick           std::make_pair(FramePtrAddrAlloca, ParentCGF.EscapedLocals.size()));
1915ec727ea7Spatrick       int FrameEscapeIdx = InsertPair.first->second;
1916ec727ea7Spatrick 
1917ec727ea7Spatrick       // an example of a filter's prolog::
1918ec727ea7Spatrick       // %0 = call i8* @llvm.eh.recoverfp(bitcast(@"?fin$0@0@main@@"),..)
1919ec727ea7Spatrick       // %1 = call i8* @llvm.localrecover(bitcast(@"?fin$0@0@main@@"),..)
1920ec727ea7Spatrick       // %2 = bitcast i8* %1 to i8**
1921ec727ea7Spatrick       // %3 = load i8*, i8* *%2, align 8
1922ec727ea7Spatrick       //   ==> %3 is the frame-pointer of outermost host function
1923ec727ea7Spatrick       llvm::Function *FrameRecoverFn = llvm::Intrinsic::getDeclaration(
1924ec727ea7Spatrick           &CGM.getModule(), llvm::Intrinsic::localrecover);
1925ec727ea7Spatrick       llvm::Constant *ParentI8Fn =
1926ec727ea7Spatrick           llvm::ConstantExpr::getBitCast(ParentCGF.CurFn, Int8PtrTy);
1927ec727ea7Spatrick       ParentFP = Builder.CreateCall(
1928ec727ea7Spatrick           FrameRecoverFn, {ParentI8Fn, ParentFP,
1929ec727ea7Spatrick                            llvm::ConstantInt::get(Int32Ty, FrameEscapeIdx)});
1930ec727ea7Spatrick       ParentFP = Builder.CreateBitCast(ParentFP, CGM.VoidPtrPtrTy);
1931*12c85518Srobert       ParentFP = Builder.CreateLoad(
1932*12c85518Srobert           Address(ParentFP, CGM.VoidPtrTy, getPointerAlign()));
1933ec727ea7Spatrick     }
1934e5dd7070Spatrick   }
1935e5dd7070Spatrick 
1936e5dd7070Spatrick   // Create llvm.localrecover calls for all captures.
1937e5dd7070Spatrick   for (const VarDecl *VD : Finder.Captures) {
1938e5dd7070Spatrick     if (VD->getType()->isVariablyModifiedType()) {
1939e5dd7070Spatrick       CGM.ErrorUnsupported(VD, "VLA captured by SEH");
1940e5dd7070Spatrick       continue;
1941e5dd7070Spatrick     }
1942e5dd7070Spatrick     assert((isa<ImplicitParamDecl>(VD) || VD->isLocalVarDeclOrParm()) &&
1943e5dd7070Spatrick            "captured non-local variable");
1944e5dd7070Spatrick 
1945a9ac8606Spatrick     auto L = ParentCGF.LambdaCaptureFields.find(VD);
1946a9ac8606Spatrick     if (L != ParentCGF.LambdaCaptureFields.end()) {
1947a9ac8606Spatrick       LambdaCaptureFields[VD] = L->second;
1948a9ac8606Spatrick       continue;
1949a9ac8606Spatrick     }
1950a9ac8606Spatrick 
1951e5dd7070Spatrick     // If this decl hasn't been declared yet, it will be declared in the
1952e5dd7070Spatrick     // OutlinedStmt.
1953e5dd7070Spatrick     auto I = ParentCGF.LocalDeclMap.find(VD);
1954e5dd7070Spatrick     if (I == ParentCGF.LocalDeclMap.end())
1955e5dd7070Spatrick       continue;
1956e5dd7070Spatrick 
1957e5dd7070Spatrick     Address ParentVar = I->second;
1958a9ac8606Spatrick     Address Recovered =
1959a9ac8606Spatrick         recoverAddrOfEscapedLocal(ParentCGF, ParentVar, ParentFP);
1960a9ac8606Spatrick     setAddrOfLocalVar(VD, Recovered);
1961a9ac8606Spatrick 
1962a9ac8606Spatrick     if (isa<ImplicitParamDecl>(VD)) {
1963a9ac8606Spatrick       CXXABIThisAlignment = ParentCGF.CXXABIThisAlignment;
1964a9ac8606Spatrick       CXXThisAlignment = ParentCGF.CXXThisAlignment;
1965a9ac8606Spatrick       CXXABIThisValue = Builder.CreateLoad(Recovered, "this");
1966a9ac8606Spatrick       if (ParentCGF.LambdaThisCaptureField) {
1967a9ac8606Spatrick         LambdaThisCaptureField = ParentCGF.LambdaThisCaptureField;
1968a9ac8606Spatrick         // We are in a lambda function where "this" is captured so the
1969a9ac8606Spatrick         // CXXThisValue need to be loaded from the lambda capture
1970a9ac8606Spatrick         LValue ThisFieldLValue =
1971a9ac8606Spatrick             EmitLValueForLambdaField(LambdaThisCaptureField);
1972a9ac8606Spatrick         if (!LambdaThisCaptureField->getType()->isPointerType()) {
1973a9ac8606Spatrick           CXXThisValue = ThisFieldLValue.getAddress(*this).getPointer();
1974a9ac8606Spatrick         } else {
1975a9ac8606Spatrick           CXXThisValue = EmitLoadOfLValue(ThisFieldLValue, SourceLocation())
1976a9ac8606Spatrick                              .getScalarVal();
1977a9ac8606Spatrick         }
1978a9ac8606Spatrick       } else {
1979a9ac8606Spatrick         CXXThisValue = CXXABIThisValue;
1980a9ac8606Spatrick       }
1981a9ac8606Spatrick     }
1982e5dd7070Spatrick   }
1983e5dd7070Spatrick 
1984e5dd7070Spatrick   if (Finder.SEHCodeSlot.isValid()) {
1985e5dd7070Spatrick     SEHCodeSlotStack.push_back(
1986e5dd7070Spatrick         recoverAddrOfEscapedLocal(ParentCGF, Finder.SEHCodeSlot, ParentFP));
1987e5dd7070Spatrick   }
1988e5dd7070Spatrick 
1989e5dd7070Spatrick   if (IsFilter)
1990e5dd7070Spatrick     EmitSEHExceptionCodeSave(ParentCGF, ParentFP, EntryFP);
1991e5dd7070Spatrick }
1992e5dd7070Spatrick 
1993e5dd7070Spatrick /// Arrange a function prototype that can be called by Windows exception
1994e5dd7070Spatrick /// handling personalities. On Win64, the prototype looks like:
1995e5dd7070Spatrick /// RetTy func(void *EHPtrs, void *ParentFP);
startOutlinedSEHHelper(CodeGenFunction & ParentCGF,bool IsFilter,const Stmt * OutlinedStmt)1996e5dd7070Spatrick void CodeGenFunction::startOutlinedSEHHelper(CodeGenFunction &ParentCGF,
1997e5dd7070Spatrick                                              bool IsFilter,
1998e5dd7070Spatrick                                              const Stmt *OutlinedStmt) {
1999e5dd7070Spatrick   SourceLocation StartLoc = OutlinedStmt->getBeginLoc();
2000e5dd7070Spatrick 
2001e5dd7070Spatrick   // Get the mangled function name.
2002e5dd7070Spatrick   SmallString<128> Name;
2003e5dd7070Spatrick   {
2004e5dd7070Spatrick     llvm::raw_svector_ostream OS(Name);
2005*12c85518Srobert     GlobalDecl ParentSEHFn = ParentCGF.CurSEHParent;
2006e5dd7070Spatrick     assert(ParentSEHFn && "No CurSEHParent!");
2007e5dd7070Spatrick     MangleContext &Mangler = CGM.getCXXABI().getMangleContext();
2008e5dd7070Spatrick     if (IsFilter)
2009e5dd7070Spatrick       Mangler.mangleSEHFilterExpression(ParentSEHFn, OS);
2010e5dd7070Spatrick     else
2011e5dd7070Spatrick       Mangler.mangleSEHFinallyBlock(ParentSEHFn, OS);
2012e5dd7070Spatrick   }
2013e5dd7070Spatrick 
2014e5dd7070Spatrick   FunctionArgList Args;
2015e5dd7070Spatrick   if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86 || !IsFilter) {
2016e5dd7070Spatrick     // All SEH finally functions take two parameters. Win64 filters take two
2017e5dd7070Spatrick     // parameters. Win32 filters take no parameters.
2018e5dd7070Spatrick     if (IsFilter) {
2019e5dd7070Spatrick       Args.push_back(ImplicitParamDecl::Create(
2020e5dd7070Spatrick           getContext(), /*DC=*/nullptr, StartLoc,
2021e5dd7070Spatrick           &getContext().Idents.get("exception_pointers"),
2022e5dd7070Spatrick           getContext().VoidPtrTy, ImplicitParamDecl::Other));
2023e5dd7070Spatrick     } else {
2024e5dd7070Spatrick       Args.push_back(ImplicitParamDecl::Create(
2025e5dd7070Spatrick           getContext(), /*DC=*/nullptr, StartLoc,
2026e5dd7070Spatrick           &getContext().Idents.get("abnormal_termination"),
2027e5dd7070Spatrick           getContext().UnsignedCharTy, ImplicitParamDecl::Other));
2028e5dd7070Spatrick     }
2029e5dd7070Spatrick     Args.push_back(ImplicitParamDecl::Create(
2030e5dd7070Spatrick         getContext(), /*DC=*/nullptr, StartLoc,
2031e5dd7070Spatrick         &getContext().Idents.get("frame_pointer"), getContext().VoidPtrTy,
2032e5dd7070Spatrick         ImplicitParamDecl::Other));
2033e5dd7070Spatrick   }
2034e5dd7070Spatrick 
2035e5dd7070Spatrick   QualType RetTy = IsFilter ? getContext().LongTy : getContext().VoidTy;
2036e5dd7070Spatrick 
2037e5dd7070Spatrick   const CGFunctionInfo &FnInfo =
2038e5dd7070Spatrick     CGM.getTypes().arrangeBuiltinFunctionDeclaration(RetTy, Args);
2039e5dd7070Spatrick 
2040e5dd7070Spatrick   llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
2041e5dd7070Spatrick   llvm::Function *Fn = llvm::Function::Create(
2042e5dd7070Spatrick       FnTy, llvm::GlobalValue::InternalLinkage, Name.str(), &CGM.getModule());
2043e5dd7070Spatrick 
2044e5dd7070Spatrick   IsOutlinedSEHHelper = true;
2045e5dd7070Spatrick 
2046e5dd7070Spatrick   StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args,
2047e5dd7070Spatrick                 OutlinedStmt->getBeginLoc(), OutlinedStmt->getBeginLoc());
2048e5dd7070Spatrick   CurSEHParent = ParentCGF.CurSEHParent;
2049e5dd7070Spatrick 
2050ec727ea7Spatrick   CGM.SetInternalFunctionAttributes(GlobalDecl(), CurFn, FnInfo);
2051e5dd7070Spatrick   EmitCapturedLocals(ParentCGF, OutlinedStmt, IsFilter);
2052e5dd7070Spatrick }
2053e5dd7070Spatrick 
2054e5dd7070Spatrick /// Create a stub filter function that will ultimately hold the code of the
2055e5dd7070Spatrick /// filter expression. The EH preparation passes in LLVM will outline the code
2056e5dd7070Spatrick /// from the main function body into this stub.
2057e5dd7070Spatrick llvm::Function *
GenerateSEHFilterFunction(CodeGenFunction & ParentCGF,const SEHExceptStmt & Except)2058e5dd7070Spatrick CodeGenFunction::GenerateSEHFilterFunction(CodeGenFunction &ParentCGF,
2059e5dd7070Spatrick                                            const SEHExceptStmt &Except) {
2060e5dd7070Spatrick   const Expr *FilterExpr = Except.getFilterExpr();
2061e5dd7070Spatrick   startOutlinedSEHHelper(ParentCGF, true, FilterExpr);
2062e5dd7070Spatrick 
2063e5dd7070Spatrick   // Emit the original filter expression, convert to i32, and return.
2064e5dd7070Spatrick   llvm::Value *R = EmitScalarExpr(FilterExpr);
2065e5dd7070Spatrick   R = Builder.CreateIntCast(R, ConvertType(getContext().LongTy),
2066e5dd7070Spatrick                             FilterExpr->getType()->isSignedIntegerType());
2067e5dd7070Spatrick   Builder.CreateStore(R, ReturnValue);
2068e5dd7070Spatrick 
2069e5dd7070Spatrick   FinishFunction(FilterExpr->getEndLoc());
2070e5dd7070Spatrick 
2071e5dd7070Spatrick   return CurFn;
2072e5dd7070Spatrick }
2073e5dd7070Spatrick 
2074e5dd7070Spatrick llvm::Function *
GenerateSEHFinallyFunction(CodeGenFunction & ParentCGF,const SEHFinallyStmt & Finally)2075e5dd7070Spatrick CodeGenFunction::GenerateSEHFinallyFunction(CodeGenFunction &ParentCGF,
2076e5dd7070Spatrick                                             const SEHFinallyStmt &Finally) {
2077e5dd7070Spatrick   const Stmt *FinallyBlock = Finally.getBlock();
2078e5dd7070Spatrick   startOutlinedSEHHelper(ParentCGF, false, FinallyBlock);
2079e5dd7070Spatrick 
2080e5dd7070Spatrick   // Emit the original filter expression, convert to i32, and return.
2081e5dd7070Spatrick   EmitStmt(FinallyBlock);
2082e5dd7070Spatrick 
2083e5dd7070Spatrick   FinishFunction(FinallyBlock->getEndLoc());
2084e5dd7070Spatrick 
2085e5dd7070Spatrick   return CurFn;
2086e5dd7070Spatrick }
2087e5dd7070Spatrick 
EmitSEHExceptionCodeSave(CodeGenFunction & ParentCGF,llvm::Value * ParentFP,llvm::Value * EntryFP)2088e5dd7070Spatrick void CodeGenFunction::EmitSEHExceptionCodeSave(CodeGenFunction &ParentCGF,
2089e5dd7070Spatrick                                                llvm::Value *ParentFP,
2090e5dd7070Spatrick                                                llvm::Value *EntryFP) {
2091e5dd7070Spatrick   // Get the pointer to the EXCEPTION_POINTERS struct. This is returned by the
2092e5dd7070Spatrick   // __exception_info intrinsic.
2093e5dd7070Spatrick   if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
2094e5dd7070Spatrick     // On Win64, the info is passed as the first parameter to the filter.
2095e5dd7070Spatrick     SEHInfo = &*CurFn->arg_begin();
2096e5dd7070Spatrick     SEHCodeSlotStack.push_back(
2097e5dd7070Spatrick         CreateMemTemp(getContext().IntTy, "__exception_code"));
2098e5dd7070Spatrick   } else {
2099e5dd7070Spatrick     // On Win32, the EBP on entry to the filter points to the end of an
2100e5dd7070Spatrick     // exception registration object. It contains 6 32-bit fields, and the info
2101e5dd7070Spatrick     // pointer is stored in the second field. So, GEP 20 bytes backwards and
2102e5dd7070Spatrick     // load the pointer.
2103e5dd7070Spatrick     SEHInfo = Builder.CreateConstInBoundsGEP1_32(Int8Ty, EntryFP, -20);
2104e5dd7070Spatrick     SEHInfo = Builder.CreateBitCast(SEHInfo, Int8PtrTy->getPointerTo());
2105e5dd7070Spatrick     SEHInfo = Builder.CreateAlignedLoad(Int8PtrTy, SEHInfo, getPointerAlign());
2106e5dd7070Spatrick     SEHCodeSlotStack.push_back(recoverAddrOfEscapedLocal(
2107e5dd7070Spatrick         ParentCGF, ParentCGF.SEHCodeSlotStack.back(), ParentFP));
2108e5dd7070Spatrick   }
2109e5dd7070Spatrick 
2110e5dd7070Spatrick   // Save the exception code in the exception slot to unify exception access in
2111e5dd7070Spatrick   // the filter function and the landing pad.
2112e5dd7070Spatrick   // struct EXCEPTION_POINTERS {
2113e5dd7070Spatrick   //   EXCEPTION_RECORD *ExceptionRecord;
2114e5dd7070Spatrick   //   CONTEXT *ContextRecord;
2115e5dd7070Spatrick   // };
2116e5dd7070Spatrick   // int exceptioncode = exception_pointers->ExceptionRecord->ExceptionCode;
2117e5dd7070Spatrick   llvm::Type *RecordTy = CGM.Int32Ty->getPointerTo();
2118e5dd7070Spatrick   llvm::Type *PtrsTy = llvm::StructType::get(RecordTy, CGM.VoidPtrTy);
2119e5dd7070Spatrick   llvm::Value *Ptrs = Builder.CreateBitCast(SEHInfo, PtrsTy->getPointerTo());
2120e5dd7070Spatrick   llvm::Value *Rec = Builder.CreateStructGEP(PtrsTy, Ptrs, 0);
2121a9ac8606Spatrick   Rec = Builder.CreateAlignedLoad(RecordTy, Rec, getPointerAlign());
2122a9ac8606Spatrick   llvm::Value *Code = Builder.CreateAlignedLoad(Int32Ty, Rec, getIntAlign());
2123e5dd7070Spatrick   assert(!SEHCodeSlotStack.empty() && "emitting EH code outside of __except");
2124e5dd7070Spatrick   Builder.CreateStore(Code, SEHCodeSlotStack.back());
2125e5dd7070Spatrick }
2126e5dd7070Spatrick 
EmitSEHExceptionInfo()2127e5dd7070Spatrick llvm::Value *CodeGenFunction::EmitSEHExceptionInfo() {
2128e5dd7070Spatrick   // Sema should diagnose calling this builtin outside of a filter context, but
2129e5dd7070Spatrick   // don't crash if we screw up.
2130e5dd7070Spatrick   if (!SEHInfo)
2131e5dd7070Spatrick     return llvm::UndefValue::get(Int8PtrTy);
2132e5dd7070Spatrick   assert(SEHInfo->getType() == Int8PtrTy);
2133e5dd7070Spatrick   return SEHInfo;
2134e5dd7070Spatrick }
2135e5dd7070Spatrick 
EmitSEHExceptionCode()2136e5dd7070Spatrick llvm::Value *CodeGenFunction::EmitSEHExceptionCode() {
2137e5dd7070Spatrick   assert(!SEHCodeSlotStack.empty() && "emitting EH code outside of __except");
2138e5dd7070Spatrick   return Builder.CreateLoad(SEHCodeSlotStack.back());
2139e5dd7070Spatrick }
2140e5dd7070Spatrick 
EmitSEHAbnormalTermination()2141e5dd7070Spatrick llvm::Value *CodeGenFunction::EmitSEHAbnormalTermination() {
2142e5dd7070Spatrick   // Abnormal termination is just the first parameter to the outlined finally
2143e5dd7070Spatrick   // helper.
2144e5dd7070Spatrick   auto AI = CurFn->arg_begin();
2145e5dd7070Spatrick   return Builder.CreateZExt(&*AI, Int32Ty);
2146e5dd7070Spatrick }
2147e5dd7070Spatrick 
pushSEHCleanup(CleanupKind Kind,llvm::Function * FinallyFunc)2148e5dd7070Spatrick void CodeGenFunction::pushSEHCleanup(CleanupKind Kind,
2149e5dd7070Spatrick                                      llvm::Function *FinallyFunc) {
2150e5dd7070Spatrick   EHStack.pushCleanup<PerformSEHFinally>(Kind, FinallyFunc);
2151e5dd7070Spatrick }
2152e5dd7070Spatrick 
EnterSEHTryStmt(const SEHTryStmt & S)2153e5dd7070Spatrick void CodeGenFunction::EnterSEHTryStmt(const SEHTryStmt &S) {
2154e5dd7070Spatrick   CodeGenFunction HelperCGF(CGM, /*suppressNewContext=*/true);
2155ec727ea7Spatrick   HelperCGF.ParentCGF = this;
2156e5dd7070Spatrick   if (const SEHFinallyStmt *Finally = S.getFinallyHandler()) {
2157e5dd7070Spatrick     // Outline the finally block.
2158e5dd7070Spatrick     llvm::Function *FinallyFunc =
2159e5dd7070Spatrick         HelperCGF.GenerateSEHFinallyFunction(*this, *Finally);
2160e5dd7070Spatrick 
2161e5dd7070Spatrick     // Push a cleanup for __finally blocks.
2162e5dd7070Spatrick     EHStack.pushCleanup<PerformSEHFinally>(NormalAndEHCleanup, FinallyFunc);
2163e5dd7070Spatrick     return;
2164e5dd7070Spatrick   }
2165e5dd7070Spatrick 
2166e5dd7070Spatrick   // Otherwise, we must have an __except block.
2167e5dd7070Spatrick   const SEHExceptStmt *Except = S.getExceptHandler();
2168e5dd7070Spatrick   assert(Except);
2169e5dd7070Spatrick   EHCatchScope *CatchScope = EHStack.pushCatch(1);
2170e5dd7070Spatrick   SEHCodeSlotStack.push_back(
2171e5dd7070Spatrick       CreateMemTemp(getContext().IntTy, "__exception_code"));
2172e5dd7070Spatrick 
2173e5dd7070Spatrick   // If the filter is known to evaluate to 1, then we can use the clause
2174e5dd7070Spatrick   // "catch i8* null". We can't do this on x86 because the filter has to save
2175e5dd7070Spatrick   // the exception code.
2176e5dd7070Spatrick   llvm::Constant *C =
2177e5dd7070Spatrick     ConstantEmitter(*this).tryEmitAbstract(Except->getFilterExpr(),
2178e5dd7070Spatrick                                            getContext().IntTy);
2179e5dd7070Spatrick   if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86 && C &&
2180e5dd7070Spatrick       C->isOneValue()) {
2181e5dd7070Spatrick     CatchScope->setCatchAllHandler(0, createBasicBlock("__except"));
2182e5dd7070Spatrick     return;
2183e5dd7070Spatrick   }
2184e5dd7070Spatrick 
2185e5dd7070Spatrick   // In general, we have to emit an outlined filter function. Use the function
2186e5dd7070Spatrick   // in place of the RTTI typeinfo global that C++ EH uses.
2187e5dd7070Spatrick   llvm::Function *FilterFunc =
2188e5dd7070Spatrick       HelperCGF.GenerateSEHFilterFunction(*this, *Except);
2189e5dd7070Spatrick   llvm::Constant *OpaqueFunc =
2190e5dd7070Spatrick       llvm::ConstantExpr::getBitCast(FilterFunc, Int8PtrTy);
2191e5dd7070Spatrick   CatchScope->setHandler(0, OpaqueFunc, createBasicBlock("__except.ret"));
2192e5dd7070Spatrick }
2193e5dd7070Spatrick 
ExitSEHTryStmt(const SEHTryStmt & S)2194e5dd7070Spatrick void CodeGenFunction::ExitSEHTryStmt(const SEHTryStmt &S) {
2195e5dd7070Spatrick   // Just pop the cleanup if it's a __finally block.
2196e5dd7070Spatrick   if (S.getFinallyHandler()) {
2197e5dd7070Spatrick     PopCleanupBlock();
2198e5dd7070Spatrick     return;
2199e5dd7070Spatrick   }
2200e5dd7070Spatrick 
2201a9ac8606Spatrick   // IsEHa: emit an invoke _seh_try_end() to mark end of FT flow
2202a9ac8606Spatrick   if (getLangOpts().EHAsynch && Builder.GetInsertBlock()) {
2203a9ac8606Spatrick     llvm::FunctionCallee SehTryEnd = getSehTryEndFn(CGM);
2204a9ac8606Spatrick     EmitRuntimeCallOrInvoke(SehTryEnd);
2205a9ac8606Spatrick   }
2206a9ac8606Spatrick 
2207e5dd7070Spatrick   // Otherwise, we must have an __except block.
2208e5dd7070Spatrick   const SEHExceptStmt *Except = S.getExceptHandler();
2209e5dd7070Spatrick   assert(Except && "__try must have __finally xor __except");
2210e5dd7070Spatrick   EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
2211e5dd7070Spatrick 
2212e5dd7070Spatrick   // Don't emit the __except block if the __try block lacked invokes.
2213e5dd7070Spatrick   // TODO: Model unwind edges from instructions, either with iload / istore or
2214e5dd7070Spatrick   // a try body function.
2215e5dd7070Spatrick   if (!CatchScope.hasEHBranches()) {
2216e5dd7070Spatrick     CatchScope.clearHandlerBlocks();
2217e5dd7070Spatrick     EHStack.popCatch();
2218e5dd7070Spatrick     SEHCodeSlotStack.pop_back();
2219e5dd7070Spatrick     return;
2220e5dd7070Spatrick   }
2221e5dd7070Spatrick 
2222e5dd7070Spatrick   // The fall-through block.
2223e5dd7070Spatrick   llvm::BasicBlock *ContBB = createBasicBlock("__try.cont");
2224e5dd7070Spatrick 
2225e5dd7070Spatrick   // We just emitted the body of the __try; jump to the continue block.
2226e5dd7070Spatrick   if (HaveInsertPoint())
2227e5dd7070Spatrick     Builder.CreateBr(ContBB);
2228e5dd7070Spatrick 
2229e5dd7070Spatrick   // Check if our filter function returned true.
2230e5dd7070Spatrick   emitCatchDispatchBlock(*this, CatchScope);
2231e5dd7070Spatrick 
2232e5dd7070Spatrick   // Grab the block before we pop the handler.
2233e5dd7070Spatrick   llvm::BasicBlock *CatchPadBB = CatchScope.getHandler(0).Block;
2234e5dd7070Spatrick   EHStack.popCatch();
2235e5dd7070Spatrick 
2236e5dd7070Spatrick   EmitBlockAfterUses(CatchPadBB);
2237e5dd7070Spatrick 
2238e5dd7070Spatrick   // __except blocks don't get outlined into funclets, so immediately do a
2239e5dd7070Spatrick   // catchret.
2240e5dd7070Spatrick   llvm::CatchPadInst *CPI =
2241e5dd7070Spatrick       cast<llvm::CatchPadInst>(CatchPadBB->getFirstNonPHI());
2242e5dd7070Spatrick   llvm::BasicBlock *ExceptBB = createBasicBlock("__except");
2243e5dd7070Spatrick   Builder.CreateCatchRet(CPI, ExceptBB);
2244e5dd7070Spatrick   EmitBlock(ExceptBB);
2245e5dd7070Spatrick 
2246e5dd7070Spatrick   // On Win64, the exception code is returned in EAX. Copy it into the slot.
2247e5dd7070Spatrick   if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
2248e5dd7070Spatrick     llvm::Function *SEHCodeIntrin =
2249e5dd7070Spatrick         CGM.getIntrinsic(llvm::Intrinsic::eh_exceptioncode);
2250e5dd7070Spatrick     llvm::Value *Code = Builder.CreateCall(SEHCodeIntrin, {CPI});
2251e5dd7070Spatrick     Builder.CreateStore(Code, SEHCodeSlotStack.back());
2252e5dd7070Spatrick   }
2253e5dd7070Spatrick 
2254e5dd7070Spatrick   // Emit the __except body.
2255e5dd7070Spatrick   EmitStmt(Except->getBlock());
2256e5dd7070Spatrick 
2257e5dd7070Spatrick   // End the lifetime of the exception code.
2258e5dd7070Spatrick   SEHCodeSlotStack.pop_back();
2259e5dd7070Spatrick 
2260e5dd7070Spatrick   if (HaveInsertPoint())
2261e5dd7070Spatrick     Builder.CreateBr(ContBB);
2262e5dd7070Spatrick 
2263e5dd7070Spatrick   EmitBlock(ContBB);
2264e5dd7070Spatrick }
2265e5dd7070Spatrick 
EmitSEHLeaveStmt(const SEHLeaveStmt & S)2266e5dd7070Spatrick void CodeGenFunction::EmitSEHLeaveStmt(const SEHLeaveStmt &S) {
2267e5dd7070Spatrick   // If this code is reachable then emit a stop point (if generating
2268e5dd7070Spatrick   // debug info). We have to do this ourselves because we are on the
2269e5dd7070Spatrick   // "simple" statement path.
2270e5dd7070Spatrick   if (HaveInsertPoint())
2271e5dd7070Spatrick     EmitStopPoint(&S);
2272e5dd7070Spatrick 
2273e5dd7070Spatrick   // This must be a __leave from a __finally block, which we warn on and is UB.
2274e5dd7070Spatrick   // Just emit unreachable.
2275e5dd7070Spatrick   if (!isSEHTryScope()) {
2276e5dd7070Spatrick     Builder.CreateUnreachable();
2277e5dd7070Spatrick     Builder.ClearInsertionPoint();
2278e5dd7070Spatrick     return;
2279e5dd7070Spatrick   }
2280e5dd7070Spatrick 
2281e5dd7070Spatrick   EmitBranchThroughCleanup(*SEHTryEpilogueStack.back());
2282e5dd7070Spatrick }
2283