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