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