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