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