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