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 : 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   // The dispatch block for the end of the scope chain is a block that
563   // just resumes unwinding.
564   if (si == EHStack.stable_end())
565     return getEHResumeBlock(true);
566 
567   // Otherwise, we should look at the actual scope.
568   EHScope &scope = *EHStack.find(si);
569 
570   llvm::BasicBlock *dispatchBlock = scope.getCachedEHDispatchBlock();
571   if (!dispatchBlock) {
572     switch (scope.getKind()) {
573     case EHScope::Catch: {
574       // Apply a special case to a single catch-all.
575       EHCatchScope &catchScope = cast<EHCatchScope>(scope);
576       if (catchScope.getNumHandlers() == 1 &&
577           catchScope.getHandler(0).isCatchAll()) {
578         dispatchBlock = catchScope.getHandler(0).Block;
579 
580       // Otherwise, make a dispatch block.
581       } else {
582         dispatchBlock = createBasicBlock("catch.dispatch");
583       }
584       break;
585     }
586 
587     case EHScope::Cleanup:
588       dispatchBlock = createBasicBlock("ehcleanup");
589       break;
590 
591     case EHScope::Filter:
592       dispatchBlock = createBasicBlock("filter.dispatch");
593       break;
594 
595     case EHScope::Terminate:
596       dispatchBlock = getTerminateHandler();
597       break;
598     }
599     scope.setCachedEHDispatchBlock(dispatchBlock);
600   }
601   return dispatchBlock;
602 }
603 
604 /// Check whether this is a non-EH scope, i.e. a scope which doesn't
605 /// affect exception handling.  Currently, the only non-EH scopes are
606 /// normal-only cleanup scopes.
607 static bool isNonEHScope(const EHScope &S) {
608   switch (S.getKind()) {
609   case EHScope::Cleanup:
610     return !cast<EHCleanupScope>(S).isEHCleanup();
611   case EHScope::Filter:
612   case EHScope::Catch:
613   case EHScope::Terminate:
614     return false;
615   }
616 
617   llvm_unreachable("Invalid EHScope Kind!");
618 }
619 
620 llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
621   assert(EHStack.requiresLandingPad());
622   assert(!EHStack.empty());
623 
624   // If exceptions are disabled, there are usually no landingpads. However, when
625   // SEH is enabled, functions using SEH still get landingpads.
626   const LangOptions &LO = CGM.getLangOpts();
627   if (!LO.Exceptions) {
628     if (!LO.Borland && !LO.MicrosoftExt)
629       return nullptr;
630     if (!currentFunctionUsesSEHTry())
631       return nullptr;
632   }
633 
634   // Check the innermost scope for a cached landing pad.  If this is
635   // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
636   llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
637   if (LP) return LP;
638 
639   // Build the landing pad for this scope.
640   LP = EmitLandingPad();
641   assert(LP);
642 
643   // Cache the landing pad on the innermost scope.  If this is a
644   // non-EH scope, cache the landing pad on the enclosing scope, too.
645   for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
646     ir->setCachedLandingPad(LP);
647     if (!isNonEHScope(*ir)) break;
648   }
649 
650   return LP;
651 }
652 
653 llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
654   assert(EHStack.requiresLandingPad());
655 
656   EHScope &innermostEHScope = *EHStack.find(EHStack.getInnermostEHScope());
657   switch (innermostEHScope.getKind()) {
658   case EHScope::Terminate:
659     return getTerminateLandingPad();
660 
661   case EHScope::Catch:
662   case EHScope::Cleanup:
663   case EHScope::Filter:
664     if (llvm::BasicBlock *lpad = innermostEHScope.getCachedLandingPad())
665       return lpad;
666   }
667 
668   // Save the current IR generation state.
669   CGBuilderTy::InsertPoint savedIP = Builder.saveAndClearIP();
670   auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, CurEHLocation);
671 
672   const EHPersonality &personality = EHPersonality::get(*this);
673 
674   if (!CurFn->hasPersonalityFn())
675     CurFn->setPersonalityFn(getOpaquePersonalityFn(CGM, personality));
676 
677   // Create and configure the landing pad.
678   llvm::BasicBlock *lpad = createBasicBlock("lpad");
679   EmitBlock(lpad);
680 
681   llvm::LandingPadInst *LPadInst = Builder.CreateLandingPad(
682       llvm::StructType::get(Int8PtrTy, Int32Ty, nullptr), 0);
683 
684   llvm::Value *LPadExn = Builder.CreateExtractValue(LPadInst, 0);
685   Builder.CreateStore(LPadExn, getExceptionSlot());
686   llvm::Value *LPadSel = Builder.CreateExtractValue(LPadInst, 1);
687   Builder.CreateStore(LPadSel, getEHSelectorSlot());
688 
689   // Save the exception pointer.  It's safe to use a single exception
690   // pointer per function because EH cleanups can never have nested
691   // try/catches.
692   // Build the landingpad instruction.
693 
694   // Accumulate all the handlers in scope.
695   bool hasCatchAll = false;
696   bool hasCleanup = false;
697   bool hasFilter = false;
698   SmallVector<llvm::Value*, 4> filterTypes;
699   llvm::SmallPtrSet<llvm::Value*, 4> catchTypes;
700   for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end(); I != E;
701        ++I) {
702 
703     switch (I->getKind()) {
704     case EHScope::Cleanup:
705       // If we have a cleanup, remember that.
706       hasCleanup = (hasCleanup || cast<EHCleanupScope>(*I).isEHCleanup());
707       continue;
708 
709     case EHScope::Filter: {
710       assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
711       assert(!hasCatchAll && "EH filter reached after catch-all");
712 
713       // Filter scopes get added to the landingpad in weird ways.
714       EHFilterScope &filter = cast<EHFilterScope>(*I);
715       hasFilter = true;
716 
717       // Add all the filter values.
718       for (unsigned i = 0, e = filter.getNumFilters(); i != e; ++i)
719         filterTypes.push_back(filter.getFilter(i));
720       goto done;
721     }
722 
723     case EHScope::Terminate:
724       // Terminate scopes are basically catch-alls.
725       assert(!hasCatchAll);
726       hasCatchAll = true;
727       goto done;
728 
729     case EHScope::Catch:
730       break;
731     }
732 
733     EHCatchScope &catchScope = cast<EHCatchScope>(*I);
734     for (unsigned hi = 0, he = catchScope.getNumHandlers(); hi != he; ++hi) {
735       EHCatchScope::Handler handler = catchScope.getHandler(hi);
736 
737       // If this is a catch-all, register that and abort.
738       if (!handler.Type) {
739         assert(!hasCatchAll);
740         hasCatchAll = true;
741         goto done;
742       }
743 
744       // Check whether we already have a handler for this type.
745       if (catchTypes.insert(handler.Type).second)
746         // If not, add it directly to the landingpad.
747         LPadInst->addClause(handler.Type);
748     }
749   }
750 
751  done:
752   // If we have a catch-all, add null to the landingpad.
753   assert(!(hasCatchAll && hasFilter));
754   if (hasCatchAll) {
755     LPadInst->addClause(getCatchAllValue(*this));
756 
757   // If we have an EH filter, we need to add those handlers in the
758   // right place in the landingpad, which is to say, at the end.
759   } else if (hasFilter) {
760     // Create a filter expression: a constant array indicating which filter
761     // types there are. The personality routine only lands here if the filter
762     // doesn't match.
763     SmallVector<llvm::Constant*, 8> Filters;
764     llvm::ArrayType *AType =
765       llvm::ArrayType::get(!filterTypes.empty() ?
766                              filterTypes[0]->getType() : Int8PtrTy,
767                            filterTypes.size());
768 
769     for (unsigned i = 0, e = filterTypes.size(); i != e; ++i)
770       Filters.push_back(cast<llvm::Constant>(filterTypes[i]));
771     llvm::Constant *FilterArray = llvm::ConstantArray::get(AType, Filters);
772     LPadInst->addClause(FilterArray);
773 
774     // Also check whether we need a cleanup.
775     if (hasCleanup)
776       LPadInst->setCleanup(true);
777 
778   // Otherwise, signal that we at least have cleanups.
779   } else if (hasCleanup) {
780     LPadInst->setCleanup(true);
781   }
782 
783   assert((LPadInst->getNumClauses() > 0 || LPadInst->isCleanup()) &&
784          "landingpad instruction has no clauses!");
785 
786   // Tell the backend how to generate the landing pad.
787   Builder.CreateBr(getEHDispatchBlock(EHStack.getInnermostEHScope()));
788 
789   // Restore the old IR generation state.
790   Builder.restoreIP(savedIP);
791 
792   return lpad;
793 }
794 
795 /// Emit the structure of the dispatch block for the given catch scope.
796 /// It is an invariant that the dispatch block already exists.
797 static void emitCatchDispatchBlock(CodeGenFunction &CGF,
798                                    EHCatchScope &catchScope) {
799   llvm::BasicBlock *dispatchBlock = catchScope.getCachedEHDispatchBlock();
800   assert(dispatchBlock);
801 
802   // If there's only a single catch-all, getEHDispatchBlock returned
803   // that catch-all as the dispatch block.
804   if (catchScope.getNumHandlers() == 1 &&
805       catchScope.getHandler(0).isCatchAll()) {
806     assert(dispatchBlock == catchScope.getHandler(0).Block);
807     return;
808   }
809 
810   CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveIP();
811   CGF.EmitBlockAfterUses(dispatchBlock);
812 
813   // Select the right handler.
814   llvm::Value *llvm_eh_typeid_for =
815     CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
816 
817   // Load the selector value.
818   llvm::Value *selector = CGF.getSelectorFromSlot();
819 
820   // Test against each of the exception types we claim to catch.
821   for (unsigned i = 0, e = catchScope.getNumHandlers(); ; ++i) {
822     assert(i < e && "ran off end of handlers!");
823     const EHCatchScope::Handler &handler = catchScope.getHandler(i);
824 
825     llvm::Value *typeValue = handler.Type;
826     assert(typeValue && "fell into catch-all case!");
827     typeValue = CGF.Builder.CreateBitCast(typeValue, CGF.Int8PtrTy);
828 
829     // Figure out the next block.
830     bool nextIsEnd;
831     llvm::BasicBlock *nextBlock;
832 
833     // If this is the last handler, we're at the end, and the next
834     // block is the block for the enclosing EH scope.
835     if (i + 1 == e) {
836       nextBlock = CGF.getEHDispatchBlock(catchScope.getEnclosingEHScope());
837       nextIsEnd = true;
838 
839     // If the next handler is a catch-all, we're at the end, and the
840     // next block is that handler.
841     } else if (catchScope.getHandler(i+1).isCatchAll()) {
842       nextBlock = catchScope.getHandler(i+1).Block;
843       nextIsEnd = true;
844 
845     // Otherwise, we're not at the end and we need a new block.
846     } else {
847       nextBlock = CGF.createBasicBlock("catch.fallthrough");
848       nextIsEnd = false;
849     }
850 
851     // Figure out the catch type's index in the LSDA's type table.
852     llvm::CallInst *typeIndex =
853       CGF.Builder.CreateCall(llvm_eh_typeid_for, typeValue);
854     typeIndex->setDoesNotThrow();
855 
856     llvm::Value *matchesTypeIndex =
857       CGF.Builder.CreateICmpEQ(selector, typeIndex, "matches");
858     CGF.Builder.CreateCondBr(matchesTypeIndex, handler.Block, nextBlock);
859 
860     // If the next handler is a catch-all, we're completely done.
861     if (nextIsEnd) {
862       CGF.Builder.restoreIP(savedIP);
863       return;
864     }
865     // Otherwise we need to emit and continue at that block.
866     CGF.EmitBlock(nextBlock);
867   }
868 }
869 
870 void CodeGenFunction::popCatchScope() {
871   EHCatchScope &catchScope = cast<EHCatchScope>(*EHStack.begin());
872   if (catchScope.hasEHBranches())
873     emitCatchDispatchBlock(*this, catchScope);
874   EHStack.popCatch();
875 }
876 
877 void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
878   unsigned NumHandlers = S.getNumHandlers();
879   EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
880   assert(CatchScope.getNumHandlers() == NumHandlers);
881 
882   // If the catch was not required, bail out now.
883   if (!CatchScope.hasEHBranches()) {
884     CatchScope.clearHandlerBlocks();
885     EHStack.popCatch();
886     return;
887   }
888 
889   // Emit the structure of the EH dispatch for this catch.
890   emitCatchDispatchBlock(*this, CatchScope);
891 
892   // Copy the handler blocks off before we pop the EH stack.  Emitting
893   // the handlers might scribble on this memory.
894   SmallVector<EHCatchScope::Handler, 8> Handlers(NumHandlers);
895   memcpy(Handlers.data(), CatchScope.begin(),
896          NumHandlers * sizeof(EHCatchScope::Handler));
897 
898   EHStack.popCatch();
899 
900   // The fall-through block.
901   llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
902 
903   // We just emitted the body of the try; jump to the continue block.
904   if (HaveInsertPoint())
905     Builder.CreateBr(ContBB);
906 
907   // Determine if we need an implicit rethrow for all these catch handlers;
908   // see the comment below.
909   bool doImplicitRethrow = false;
910   if (IsFnTryBlock)
911     doImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
912                         isa<CXXConstructorDecl>(CurCodeDecl);
913 
914   // Perversely, we emit the handlers backwards precisely because we
915   // want them to appear in source order.  In all of these cases, the
916   // catch block will have exactly one predecessor, which will be a
917   // particular block in the catch dispatch.  However, in the case of
918   // a catch-all, one of the dispatch blocks will branch to two
919   // different handlers, and EmitBlockAfterUses will cause the second
920   // handler to be moved before the first.
921   for (unsigned I = NumHandlers; I != 0; --I) {
922     llvm::BasicBlock *CatchBlock = Handlers[I-1].Block;
923     EmitBlockAfterUses(CatchBlock);
924 
925     // Catch the exception if this isn't a catch-all.
926     const CXXCatchStmt *C = S.getHandler(I-1);
927 
928     // Enter a cleanup scope, including the catch variable and the
929     // end-catch.
930     RunCleanupsScope CatchScope(*this);
931 
932     // Initialize the catch variable and set up the cleanups.
933     CGM.getCXXABI().emitBeginCatch(*this, C);
934 
935     // Emit the PGO counter increment.
936     incrementProfileCounter(C);
937 
938     // Perform the body of the catch.
939     EmitStmt(C->getHandlerBlock());
940 
941     // [except.handle]p11:
942     //   The currently handled exception is rethrown if control
943     //   reaches the end of a handler of the function-try-block of a
944     //   constructor or destructor.
945 
946     // It is important that we only do this on fallthrough and not on
947     // return.  Note that it's illegal to put a return in a
948     // constructor function-try-block's catch handler (p14), so this
949     // really only applies to destructors.
950     if (doImplicitRethrow && HaveInsertPoint()) {
951       CGM.getCXXABI().emitRethrow(*this, /*isNoReturn*/false);
952       Builder.CreateUnreachable();
953       Builder.ClearInsertionPoint();
954     }
955 
956     // Fall out through the catch cleanups.
957     CatchScope.ForceCleanup();
958 
959     // Branch out of the try.
960     if (HaveInsertPoint())
961       Builder.CreateBr(ContBB);
962   }
963 
964   EmitBlock(ContBB);
965   incrementProfileCounter(&S);
966 }
967 
968 namespace {
969   struct CallEndCatchForFinally : EHScopeStack::Cleanup {
970     llvm::Value *ForEHVar;
971     llvm::Value *EndCatchFn;
972     CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn)
973       : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
974 
975     void Emit(CodeGenFunction &CGF, Flags flags) override {
976       llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
977       llvm::BasicBlock *CleanupContBB =
978         CGF.createBasicBlock("finally.cleanup.cont");
979 
980       llvm::Value *ShouldEndCatch =
981         CGF.Builder.CreateLoad(ForEHVar, "finally.endcatch");
982       CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
983       CGF.EmitBlock(EndCatchBB);
984       CGF.EmitRuntimeCallOrInvoke(EndCatchFn); // catch-all, so might throw
985       CGF.EmitBlock(CleanupContBB);
986     }
987   };
988 
989   struct PerformFinally : EHScopeStack::Cleanup {
990     const Stmt *Body;
991     llvm::Value *ForEHVar;
992     llvm::Value *EndCatchFn;
993     llvm::Value *RethrowFn;
994     llvm::Value *SavedExnVar;
995 
996     PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
997                    llvm::Value *EndCatchFn,
998                    llvm::Value *RethrowFn, llvm::Value *SavedExnVar)
999       : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1000         RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
1001 
1002     void Emit(CodeGenFunction &CGF, Flags flags) override {
1003       // Enter a cleanup to call the end-catch function if one was provided.
1004       if (EndCatchFn)
1005         CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
1006                                                         ForEHVar, EndCatchFn);
1007 
1008       // Save the current cleanup destination in case there are
1009       // cleanups in the finally block.
1010       llvm::Value *SavedCleanupDest =
1011         CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
1012                                "cleanup.dest.saved");
1013 
1014       // Emit the finally block.
1015       CGF.EmitStmt(Body);
1016 
1017       // If the end of the finally is reachable, check whether this was
1018       // for EH.  If so, rethrow.
1019       if (CGF.HaveInsertPoint()) {
1020         llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
1021         llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
1022 
1023         llvm::Value *ShouldRethrow =
1024           CGF.Builder.CreateLoad(ForEHVar, "finally.shouldthrow");
1025         CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1026 
1027         CGF.EmitBlock(RethrowBB);
1028         if (SavedExnVar) {
1029           CGF.EmitRuntimeCallOrInvoke(RethrowFn,
1030                                       CGF.Builder.CreateLoad(SavedExnVar));
1031         } else {
1032           CGF.EmitRuntimeCallOrInvoke(RethrowFn);
1033         }
1034         CGF.Builder.CreateUnreachable();
1035 
1036         CGF.EmitBlock(ContBB);
1037 
1038         // Restore the cleanup destination.
1039         CGF.Builder.CreateStore(SavedCleanupDest,
1040                                 CGF.getNormalCleanupDestSlot());
1041       }
1042 
1043       // Leave the end-catch cleanup.  As an optimization, pretend that
1044       // the fallthrough path was inaccessible; we've dynamically proven
1045       // that we're not in the EH case along that path.
1046       if (EndCatchFn) {
1047         CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1048         CGF.PopCleanupBlock();
1049         CGF.Builder.restoreIP(SavedIP);
1050       }
1051 
1052       // Now make sure we actually have an insertion point or the
1053       // cleanup gods will hate us.
1054       CGF.EnsureInsertPoint();
1055     }
1056   };
1057 }
1058 
1059 /// Enters a finally block for an implementation using zero-cost
1060 /// exceptions.  This is mostly general, but hard-codes some
1061 /// language/ABI-specific behavior in the catch-all sections.
1062 void CodeGenFunction::FinallyInfo::enter(CodeGenFunction &CGF,
1063                                          const Stmt *body,
1064                                          llvm::Constant *beginCatchFn,
1065                                          llvm::Constant *endCatchFn,
1066                                          llvm::Constant *rethrowFn) {
1067   assert((beginCatchFn != nullptr) == (endCatchFn != nullptr) &&
1068          "begin/end catch functions not paired");
1069   assert(rethrowFn && "rethrow function is required");
1070 
1071   BeginCatchFn = beginCatchFn;
1072 
1073   // The rethrow function has one of the following two types:
1074   //   void (*)()
1075   //   void (*)(void*)
1076   // In the latter case we need to pass it the exception object.
1077   // But we can't use the exception slot because the @finally might
1078   // have a landing pad (which would overwrite the exception slot).
1079   llvm::FunctionType *rethrowFnTy =
1080     cast<llvm::FunctionType>(
1081       cast<llvm::PointerType>(rethrowFn->getType())->getElementType());
1082   SavedExnVar = nullptr;
1083   if (rethrowFnTy->getNumParams())
1084     SavedExnVar = CGF.CreateTempAlloca(CGF.Int8PtrTy, "finally.exn");
1085 
1086   // A finally block is a statement which must be executed on any edge
1087   // out of a given scope.  Unlike a cleanup, the finally block may
1088   // contain arbitrary control flow leading out of itself.  In
1089   // addition, finally blocks should always be executed, even if there
1090   // are no catch handlers higher on the stack.  Therefore, we
1091   // surround the protected scope with a combination of a normal
1092   // cleanup (to catch attempts to break out of the block via normal
1093   // control flow) and an EH catch-all (semantically "outside" any try
1094   // statement to which the finally block might have been attached).
1095   // The finally block itself is generated in the context of a cleanup
1096   // which conditionally leaves the catch-all.
1097 
1098   // Jump destination for performing the finally block on an exception
1099   // edge.  We'll never actually reach this block, so unreachable is
1100   // fine.
1101   RethrowDest = CGF.getJumpDestInCurrentScope(CGF.getUnreachableBlock());
1102 
1103   // Whether the finally block is being executed for EH purposes.
1104   ForEHVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "finally.for-eh");
1105   CGF.Builder.CreateStore(CGF.Builder.getFalse(), ForEHVar);
1106 
1107   // Enter a normal cleanup which will perform the @finally block.
1108   CGF.EHStack.pushCleanup<PerformFinally>(NormalCleanup, body,
1109                                           ForEHVar, endCatchFn,
1110                                           rethrowFn, SavedExnVar);
1111 
1112   // Enter a catch-all scope.
1113   llvm::BasicBlock *catchBB = CGF.createBasicBlock("finally.catchall");
1114   EHCatchScope *catchScope = CGF.EHStack.pushCatch(1);
1115   catchScope->setCatchAllHandler(0, catchBB);
1116 }
1117 
1118 void CodeGenFunction::FinallyInfo::exit(CodeGenFunction &CGF) {
1119   // Leave the finally catch-all.
1120   EHCatchScope &catchScope = cast<EHCatchScope>(*CGF.EHStack.begin());
1121   llvm::BasicBlock *catchBB = catchScope.getHandler(0).Block;
1122 
1123   CGF.popCatchScope();
1124 
1125   // If there are any references to the catch-all block, emit it.
1126   if (catchBB->use_empty()) {
1127     delete catchBB;
1128   } else {
1129     CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveAndClearIP();
1130     CGF.EmitBlock(catchBB);
1131 
1132     llvm::Value *exn = nullptr;
1133 
1134     // If there's a begin-catch function, call it.
1135     if (BeginCatchFn) {
1136       exn = CGF.getExceptionFromSlot();
1137       CGF.EmitNounwindRuntimeCall(BeginCatchFn, exn);
1138     }
1139 
1140     // If we need to remember the exception pointer to rethrow later, do so.
1141     if (SavedExnVar) {
1142       if (!exn) exn = CGF.getExceptionFromSlot();
1143       CGF.Builder.CreateStore(exn, SavedExnVar);
1144     }
1145 
1146     // Tell the cleanups in the finally block that we're do this for EH.
1147     CGF.Builder.CreateStore(CGF.Builder.getTrue(), ForEHVar);
1148 
1149     // Thread a jump through the finally cleanup.
1150     CGF.EmitBranchThroughCleanup(RethrowDest);
1151 
1152     CGF.Builder.restoreIP(savedIP);
1153   }
1154 
1155   // Finally, leave the @finally cleanup.
1156   CGF.PopCleanupBlock();
1157 }
1158 
1159 llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
1160   if (TerminateLandingPad)
1161     return TerminateLandingPad;
1162 
1163   CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1164 
1165   // This will get inserted at the end of the function.
1166   TerminateLandingPad = createBasicBlock("terminate.lpad");
1167   Builder.SetInsertPoint(TerminateLandingPad);
1168 
1169   // Tell the backend that this is a landing pad.
1170   const EHPersonality &Personality = EHPersonality::get(*this);
1171 
1172   if (!CurFn->hasPersonalityFn())
1173     CurFn->setPersonalityFn(getOpaquePersonalityFn(CGM, Personality));
1174 
1175   llvm::LandingPadInst *LPadInst = Builder.CreateLandingPad(
1176       llvm::StructType::get(Int8PtrTy, Int32Ty, nullptr), 0);
1177   LPadInst->addClause(getCatchAllValue(*this));
1178 
1179   llvm::Value *Exn = 0;
1180   if (getLangOpts().CPlusPlus)
1181     Exn = Builder.CreateExtractValue(LPadInst, 0);
1182   llvm::CallInst *terminateCall =
1183       CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
1184   terminateCall->setDoesNotReturn();
1185   Builder.CreateUnreachable();
1186 
1187   // Restore the saved insertion state.
1188   Builder.restoreIP(SavedIP);
1189 
1190   return TerminateLandingPad;
1191 }
1192 
1193 llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
1194   if (TerminateHandler)
1195     return TerminateHandler;
1196 
1197   CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1198 
1199   // Set up the terminate handler.  This block is inserted at the very
1200   // end of the function by FinishFunction.
1201   TerminateHandler = createBasicBlock("terminate.handler");
1202   Builder.SetInsertPoint(TerminateHandler);
1203   llvm::Value *Exn = 0;
1204   if (getLangOpts().CPlusPlus)
1205     Exn = getExceptionFromSlot();
1206   llvm::CallInst *terminateCall =
1207       CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
1208   terminateCall->setDoesNotReturn();
1209   Builder.CreateUnreachable();
1210 
1211   // Restore the saved insertion state.
1212   Builder.restoreIP(SavedIP);
1213 
1214   return TerminateHandler;
1215 }
1216 
1217 llvm::BasicBlock *CodeGenFunction::getEHResumeBlock(bool isCleanup) {
1218   if (EHResumeBlock) return EHResumeBlock;
1219 
1220   CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1221 
1222   // We emit a jump to a notional label at the outermost unwind state.
1223   EHResumeBlock = createBasicBlock("eh.resume");
1224   Builder.SetInsertPoint(EHResumeBlock);
1225 
1226   const EHPersonality &Personality = EHPersonality::get(*this);
1227 
1228   // This can always be a call because we necessarily didn't find
1229   // anything on the EH stack which needs our help.
1230   const char *RethrowName = Personality.CatchallRethrowFn;
1231   if (RethrowName != nullptr && !isCleanup) {
1232     EmitRuntimeCall(getCatchallRethrowFn(CGM, RethrowName),
1233                     getExceptionFromSlot())->setDoesNotReturn();
1234     Builder.CreateUnreachable();
1235     Builder.restoreIP(SavedIP);
1236     return EHResumeBlock;
1237   }
1238 
1239   // Recreate the landingpad's return value for the 'resume' instruction.
1240   llvm::Value *Exn = getExceptionFromSlot();
1241   llvm::Value *Sel = getSelectorFromSlot();
1242 
1243   llvm::Type *LPadType = llvm::StructType::get(Exn->getType(),
1244                                                Sel->getType(), nullptr);
1245   llvm::Value *LPadVal = llvm::UndefValue::get(LPadType);
1246   LPadVal = Builder.CreateInsertValue(LPadVal, Exn, 0, "lpad.val");
1247   LPadVal = Builder.CreateInsertValue(LPadVal, Sel, 1, "lpad.val");
1248 
1249   Builder.CreateResume(LPadVal);
1250   Builder.restoreIP(SavedIP);
1251   return EHResumeBlock;
1252 }
1253 
1254 void CodeGenFunction::EmitSEHTryStmt(const SEHTryStmt &S) {
1255   EnterSEHTryStmt(S);
1256   {
1257     JumpDest TryExit = getJumpDestInCurrentScope("__try.__leave");
1258 
1259     SEHTryEpilogueStack.push_back(&TryExit);
1260     EmitStmt(S.getTryBlock());
1261     SEHTryEpilogueStack.pop_back();
1262 
1263     if (!TryExit.getBlock()->use_empty())
1264       EmitBlock(TryExit.getBlock(), /*IsFinished=*/true);
1265     else
1266       delete TryExit.getBlock();
1267   }
1268   ExitSEHTryStmt(S);
1269 }
1270 
1271 namespace {
1272 struct PerformSEHFinally : EHScopeStack::Cleanup {
1273   llvm::Function *OutlinedFinally;
1274   PerformSEHFinally(llvm::Function *OutlinedFinally)
1275       : OutlinedFinally(OutlinedFinally) {}
1276 
1277   void Emit(CodeGenFunction &CGF, Flags F) override {
1278     ASTContext &Context = CGF.getContext();
1279     CodeGenModule &CGM = CGF.CGM;
1280 
1281     CallArgList Args;
1282 
1283     // Compute the two argument values.
1284     QualType ArgTys[2] = {Context.UnsignedCharTy, Context.VoidPtrTy};
1285     llvm::Value *LocalAddrFn = CGM.getIntrinsic(llvm::Intrinsic::localaddress);
1286     llvm::Value *FP = CGF.Builder.CreateCall(LocalAddrFn);
1287     llvm::Value *IsForEH =
1288         llvm::ConstantInt::get(CGF.ConvertType(ArgTys[0]), F.isForEHCleanup());
1289     Args.add(RValue::get(IsForEH), ArgTys[0]);
1290     Args.add(RValue::get(FP), ArgTys[1]);
1291 
1292     // Arrange a two-arg function info and type.
1293     FunctionProtoType::ExtProtoInfo EPI;
1294     const auto *FPT = cast<FunctionProtoType>(
1295         Context.getFunctionType(Context.VoidTy, ArgTys, EPI));
1296     const CGFunctionInfo &FnInfo =
1297         CGM.getTypes().arrangeFreeFunctionCall(Args, FPT,
1298                                                /*chainCall=*/false);
1299 
1300     CGF.EmitCall(FnInfo, OutlinedFinally, ReturnValueSlot(), Args);
1301   }
1302 };
1303 }
1304 
1305 namespace {
1306 /// Find all local variable captures in the statement.
1307 struct CaptureFinder : ConstStmtVisitor<CaptureFinder> {
1308   CodeGenFunction &ParentCGF;
1309   const VarDecl *ParentThis;
1310   SmallVector<const VarDecl *, 4> Captures;
1311   llvm::Value *SEHCodeSlot = nullptr;
1312   CaptureFinder(CodeGenFunction &ParentCGF, const VarDecl *ParentThis)
1313       : ParentCGF(ParentCGF), ParentThis(ParentThis) {}
1314 
1315   // Return true if we need to do any capturing work.
1316   bool foundCaptures() {
1317     return !Captures.empty() || SEHCodeSlot;
1318   }
1319 
1320   void Visit(const Stmt *S) {
1321     // See if this is a capture, then recurse.
1322     ConstStmtVisitor<CaptureFinder>::Visit(S);
1323     for (const Stmt *Child : S->children())
1324       if (Child)
1325         Visit(Child);
1326   }
1327 
1328   void VisitDeclRefExpr(const DeclRefExpr *E) {
1329     // If this is already a capture, just make sure we capture 'this'.
1330     if (E->refersToEnclosingVariableOrCapture()) {
1331       Captures.push_back(ParentThis);
1332       return;
1333     }
1334 
1335     const auto *D = dyn_cast<VarDecl>(E->getDecl());
1336     if (D && D->isLocalVarDeclOrParm() && D->hasLocalStorage())
1337       Captures.push_back(D);
1338   }
1339 
1340   void VisitCXXThisExpr(const CXXThisExpr *E) {
1341     Captures.push_back(ParentThis);
1342   }
1343 
1344   void VisitCallExpr(const CallExpr *E) {
1345     // We only need to add parent frame allocations for these builtins in x86.
1346     if (ParentCGF.getTarget().getTriple().getArch() != llvm::Triple::x86)
1347       return;
1348 
1349     unsigned ID = E->getBuiltinCallee();
1350     switch (ID) {
1351     case Builtin::BI__exception_code:
1352     case Builtin::BI_exception_code:
1353       // This is the simple case where we are the outermost finally. All we
1354       // have to do here is make sure we escape this and recover it in the
1355       // outlined handler.
1356       if (!SEHCodeSlot)
1357         SEHCodeSlot = ParentCGF.SEHCodeSlotStack.back();
1358       break;
1359     }
1360   }
1361 };
1362 }
1363 
1364 llvm::Value *CodeGenFunction::recoverAddrOfEscapedLocal(
1365     CodeGenFunction &ParentCGF, llvm::Value *ParentVar, llvm::Value *ParentFP) {
1366   llvm::CallInst *RecoverCall = nullptr;
1367   CGBuilderTy Builder(AllocaInsertPt);
1368   if (auto *ParentAlloca = dyn_cast<llvm::AllocaInst>(ParentVar)) {
1369     // Mark the variable escaped if nobody else referenced it and compute the
1370     // localescape index.
1371     auto InsertPair = ParentCGF.EscapedLocals.insert(
1372         std::make_pair(ParentAlloca, ParentCGF.EscapedLocals.size()));
1373     int FrameEscapeIdx = InsertPair.first->second;
1374     // call i8* @llvm.localrecover(i8* bitcast(@parentFn), i8* %fp, i32 N)
1375     llvm::Function *FrameRecoverFn = llvm::Intrinsic::getDeclaration(
1376         &CGM.getModule(), llvm::Intrinsic::localrecover);
1377     llvm::Constant *ParentI8Fn =
1378         llvm::ConstantExpr::getBitCast(ParentCGF.CurFn, Int8PtrTy);
1379     RecoverCall = Builder.CreateCall(
1380         FrameRecoverFn, {ParentI8Fn, ParentFP,
1381                          llvm::ConstantInt::get(Int32Ty, FrameEscapeIdx)});
1382 
1383   } else {
1384     // If the parent didn't have an alloca, we're doing some nested outlining.
1385     // Just clone the existing localrecover call, but tweak the FP argument to
1386     // use our FP value. All other arguments are constants.
1387     auto *ParentRecover =
1388         cast<llvm::IntrinsicInst>(ParentVar->stripPointerCasts());
1389     assert(ParentRecover->getIntrinsicID() == llvm::Intrinsic::localrecover &&
1390            "expected alloca or localrecover in parent LocalDeclMap");
1391     RecoverCall = cast<llvm::CallInst>(ParentRecover->clone());
1392     RecoverCall->setArgOperand(1, ParentFP);
1393     RecoverCall->insertBefore(AllocaInsertPt);
1394   }
1395 
1396   // Bitcast the variable, rename it, and insert it in the local decl map.
1397   llvm::Value *ChildVar =
1398       Builder.CreateBitCast(RecoverCall, ParentVar->getType());
1399   ChildVar->setName(ParentVar->getName());
1400   return ChildVar;
1401 }
1402 
1403 void CodeGenFunction::EmitCapturedLocals(CodeGenFunction &ParentCGF,
1404                                          const Stmt *OutlinedStmt,
1405                                          bool IsFilter) {
1406   // Find all captures in the Stmt.
1407   CaptureFinder Finder(ParentCGF, ParentCGF.CXXABIThisDecl);
1408   Finder.Visit(OutlinedStmt);
1409 
1410   // We can exit early on x86_64 when there are no captures. We just have to
1411   // save the exception code in filters so that __exception_code() works.
1412   if (!Finder.foundCaptures() &&
1413       CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
1414     if (IsFilter)
1415       EmitSEHExceptionCodeSave(ParentCGF, nullptr, nullptr);
1416     return;
1417   }
1418 
1419   llvm::Value *EntryEBP = nullptr;
1420   llvm::Value *ParentFP;
1421   if (IsFilter && CGM.getTarget().getTriple().getArch() == llvm::Triple::x86) {
1422     // 32-bit SEH filters need to be careful about FP recovery.  The end of the
1423     // EH registration is passed in as the EBP physical register.  We can
1424     // recover that with llvm.frameaddress(1), and adjust that to recover the
1425     // parent's true frame pointer.
1426     CGBuilderTy Builder(AllocaInsertPt);
1427     EntryEBP = Builder.CreateCall(
1428         CGM.getIntrinsic(llvm::Intrinsic::frameaddress), {Builder.getInt32(1)});
1429     llvm::Function *RecoverFPIntrin =
1430         CGM.getIntrinsic(llvm::Intrinsic::x86_seh_recoverfp);
1431     llvm::Constant *ParentI8Fn =
1432         llvm::ConstantExpr::getBitCast(ParentCGF.CurFn, Int8PtrTy);
1433     ParentFP = Builder.CreateCall(RecoverFPIntrin, {ParentI8Fn, EntryEBP});
1434   } else {
1435     // Otherwise, for x64 and 32-bit finally functions, the parent FP is the
1436     // second parameter.
1437     auto AI = CurFn->arg_begin();
1438     ++AI;
1439     ParentFP = AI;
1440   }
1441 
1442   // Create llvm.localrecover calls for all captures.
1443   for (const VarDecl *VD : Finder.Captures) {
1444     if (isa<ImplicitParamDecl>(VD)) {
1445       CGM.ErrorUnsupported(VD, "'this' captured by SEH");
1446       CXXThisValue = llvm::UndefValue::get(ConvertTypeForMem(VD->getType()));
1447       continue;
1448     }
1449     if (VD->getType()->isVariablyModifiedType()) {
1450       CGM.ErrorUnsupported(VD, "VLA captured by SEH");
1451       continue;
1452     }
1453     assert((isa<ImplicitParamDecl>(VD) || VD->isLocalVarDeclOrParm()) &&
1454            "captured non-local variable");
1455 
1456     // If this decl hasn't been declared yet, it will be declared in the
1457     // OutlinedStmt.
1458     auto I = ParentCGF.LocalDeclMap.find(VD);
1459     if (I == ParentCGF.LocalDeclMap.end())
1460       continue;
1461     llvm::Value *ParentVar = I->second;
1462 
1463     LocalDeclMap[VD] =
1464         recoverAddrOfEscapedLocal(ParentCGF, ParentVar, ParentFP);
1465   }
1466 
1467   if (Finder.SEHCodeSlot) {
1468     SEHCodeSlotStack.push_back(
1469         recoverAddrOfEscapedLocal(ParentCGF, Finder.SEHCodeSlot, ParentFP));
1470   }
1471 
1472   if (IsFilter)
1473     EmitSEHExceptionCodeSave(ParentCGF, ParentFP, EntryEBP);
1474 }
1475 
1476 /// Arrange a function prototype that can be called by Windows exception
1477 /// handling personalities. On Win64, the prototype looks like:
1478 /// RetTy func(void *EHPtrs, void *ParentFP);
1479 void CodeGenFunction::startOutlinedSEHHelper(CodeGenFunction &ParentCGF,
1480                                              bool IsFilter,
1481                                              const Stmt *OutlinedStmt) {
1482   SourceLocation StartLoc = OutlinedStmt->getLocStart();
1483 
1484   // Get the mangled function name.
1485   SmallString<128> Name;
1486   {
1487     llvm::raw_svector_ostream OS(Name);
1488     const Decl *ParentCodeDecl = ParentCGF.CurCodeDecl;
1489     const NamedDecl *Parent = dyn_cast_or_null<NamedDecl>(ParentCodeDecl);
1490     assert(Parent && "FIXME: handle unnamed decls (lambdas, blocks) with SEH");
1491     MangleContext &Mangler = CGM.getCXXABI().getMangleContext();
1492     if (IsFilter)
1493       Mangler.mangleSEHFilterExpression(Parent, OS);
1494     else
1495       Mangler.mangleSEHFinallyBlock(Parent, OS);
1496   }
1497 
1498   FunctionArgList Args;
1499   if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86 || !IsFilter) {
1500     // All SEH finally functions take two parameters. Win64 filters take two
1501     // parameters. Win32 filters take no parameters.
1502     if (IsFilter) {
1503       Args.push_back(ImplicitParamDecl::Create(
1504           getContext(), nullptr, StartLoc,
1505           &getContext().Idents.get("exception_pointers"),
1506           getContext().VoidPtrTy));
1507     } else {
1508       Args.push_back(ImplicitParamDecl::Create(
1509           getContext(), nullptr, StartLoc,
1510           &getContext().Idents.get("abnormal_termination"),
1511           getContext().UnsignedCharTy));
1512     }
1513     Args.push_back(ImplicitParamDecl::Create(
1514         getContext(), nullptr, StartLoc,
1515         &getContext().Idents.get("frame_pointer"), getContext().VoidPtrTy));
1516   }
1517 
1518   QualType RetTy = IsFilter ? getContext().LongTy : getContext().VoidTy;
1519 
1520   llvm::Function *ParentFn = ParentCGF.CurFn;
1521   const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionDeclaration(
1522       RetTy, Args, FunctionType::ExtInfo(), /*isVariadic=*/false);
1523 
1524   llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
1525   llvm::Function *Fn = llvm::Function::Create(
1526       FnTy, llvm::GlobalValue::InternalLinkage, Name.str(), &CGM.getModule());
1527   // The filter is either in the same comdat as the function, or it's internal.
1528   if (llvm::Comdat *C = ParentFn->getComdat()) {
1529     Fn->setComdat(C);
1530   } else if (ParentFn->hasWeakLinkage() || ParentFn->hasLinkOnceLinkage()) {
1531     llvm::Comdat *C = CGM.getModule().getOrInsertComdat(ParentFn->getName());
1532     ParentFn->setComdat(C);
1533     Fn->setComdat(C);
1534   } else {
1535     Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
1536   }
1537 
1538   IsOutlinedSEHHelper = true;
1539 
1540   StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args,
1541                 OutlinedStmt->getLocStart(), OutlinedStmt->getLocStart());
1542 
1543   CGM.SetLLVMFunctionAttributes(nullptr, FnInfo, CurFn);
1544   EmitCapturedLocals(ParentCGF, OutlinedStmt, IsFilter);
1545 }
1546 
1547 /// Create a stub filter function that will ultimately hold the code of the
1548 /// filter expression. The EH preparation passes in LLVM will outline the code
1549 /// from the main function body into this stub.
1550 llvm::Function *
1551 CodeGenFunction::GenerateSEHFilterFunction(CodeGenFunction &ParentCGF,
1552                                            const SEHExceptStmt &Except) {
1553   const Expr *FilterExpr = Except.getFilterExpr();
1554   startOutlinedSEHHelper(ParentCGF, true, FilterExpr);
1555 
1556   // Emit the original filter expression, convert to i32, and return.
1557   llvm::Value *R = EmitScalarExpr(FilterExpr);
1558   R = Builder.CreateIntCast(R, ConvertType(getContext().LongTy),
1559                             FilterExpr->getType()->isSignedIntegerType());
1560   Builder.CreateStore(R, ReturnValue);
1561 
1562   FinishFunction(FilterExpr->getLocEnd());
1563 
1564   return CurFn;
1565 }
1566 
1567 llvm::Function *
1568 CodeGenFunction::GenerateSEHFinallyFunction(CodeGenFunction &ParentCGF,
1569                                             const SEHFinallyStmt &Finally) {
1570   const Stmt *FinallyBlock = Finally.getBlock();
1571   startOutlinedSEHHelper(ParentCGF, false, FinallyBlock);
1572 
1573   // Mark finally block calls as nounwind and noinline to make LLVM's job a
1574   // little easier.
1575   // FIXME: Remove these restrictions in the future.
1576   CurFn->addFnAttr(llvm::Attribute::NoUnwind);
1577   CurFn->addFnAttr(llvm::Attribute::NoInline);
1578 
1579   // Emit the original filter expression, convert to i32, and return.
1580   EmitStmt(FinallyBlock);
1581 
1582   FinishFunction(FinallyBlock->getLocEnd());
1583 
1584   return CurFn;
1585 }
1586 
1587 void CodeGenFunction::EmitSEHExceptionCodeSave(CodeGenFunction &ParentCGF,
1588                                                llvm::Value *ParentFP,
1589                                                llvm::Value *EntryEBP) {
1590   // Get the pointer to the EXCEPTION_POINTERS struct. This is returned by the
1591   // __exception_info intrinsic.
1592   if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
1593     // On Win64, the info is passed as the first parameter to the filter.
1594     auto AI = CurFn->arg_begin();
1595     SEHInfo = AI;
1596     SEHCodeSlotStack.push_back(
1597         CreateMemTemp(getContext().IntTy, "__exception_code"));
1598   } else {
1599     // On Win32, the EBP on entry to the filter points to the end of an
1600     // exception registration object. It contains 6 32-bit fields, and the info
1601     // pointer is stored in the second field. So, GEP 20 bytes backwards and
1602     // load the pointer.
1603     SEHInfo = Builder.CreateConstInBoundsGEP1_32(Int8Ty, EntryEBP, -20);
1604     SEHInfo = Builder.CreateBitCast(SEHInfo, Int8PtrTy->getPointerTo());
1605     SEHInfo = Builder.CreateLoad(Int8PtrTy, SEHInfo);
1606     SEHCodeSlotStack.push_back(recoverAddrOfEscapedLocal(
1607         ParentCGF, ParentCGF.SEHCodeSlotStack.back(), ParentFP));
1608   }
1609 
1610   // Save the exception code in the exception slot to unify exception access in
1611   // the filter function and the landing pad.
1612   // struct EXCEPTION_POINTERS {
1613   //   EXCEPTION_RECORD *ExceptionRecord;
1614   //   CONTEXT *ContextRecord;
1615   // };
1616   // int exceptioncode = exception_pointers->ExceptionRecord->ExceptionCode;
1617   llvm::Type *RecordTy = CGM.Int32Ty->getPointerTo();
1618   llvm::Type *PtrsTy = llvm::StructType::get(RecordTy, CGM.VoidPtrTy, nullptr);
1619   llvm::Value *Ptrs = Builder.CreateBitCast(SEHInfo, PtrsTy->getPointerTo());
1620   llvm::Value *Rec = Builder.CreateStructGEP(PtrsTy, Ptrs, 0);
1621   Rec = Builder.CreateLoad(Rec);
1622   llvm::Value *Code = Builder.CreateLoad(Rec);
1623   assert(!SEHCodeSlotStack.empty() && "emitting EH code outside of __except");
1624   Builder.CreateStore(Code, SEHCodeSlotStack.back());
1625 }
1626 
1627 llvm::Value *CodeGenFunction::EmitSEHExceptionInfo() {
1628   // Sema should diagnose calling this builtin outside of a filter context, but
1629   // don't crash if we screw up.
1630   if (!SEHInfo)
1631     return llvm::UndefValue::get(Int8PtrTy);
1632   assert(SEHInfo->getType() == Int8PtrTy);
1633   return SEHInfo;
1634 }
1635 
1636 llvm::Value *CodeGenFunction::EmitSEHExceptionCode() {
1637   assert(!SEHCodeSlotStack.empty() && "emitting EH code outside of __except");
1638   return Builder.CreateLoad(Int32Ty, SEHCodeSlotStack.back());
1639 }
1640 
1641 llvm::Value *CodeGenFunction::EmitSEHAbnormalTermination() {
1642   // Abnormal termination is just the first parameter to the outlined finally
1643   // helper.
1644   auto AI = CurFn->arg_begin();
1645   return Builder.CreateZExt(&*AI, Int32Ty);
1646 }
1647 
1648 void CodeGenFunction::EnterSEHTryStmt(const SEHTryStmt &S) {
1649   CodeGenFunction HelperCGF(CGM, /*suppressNewContext=*/true);
1650   if (const SEHFinallyStmt *Finally = S.getFinallyHandler()) {
1651     // Outline the finally block.
1652     llvm::Function *FinallyFunc =
1653         HelperCGF.GenerateSEHFinallyFunction(*this, *Finally);
1654 
1655     // Push a cleanup for __finally blocks.
1656     EHStack.pushCleanup<PerformSEHFinally>(NormalAndEHCleanup, FinallyFunc);
1657     return;
1658   }
1659 
1660   // Otherwise, we must have an __except block.
1661   const SEHExceptStmt *Except = S.getExceptHandler();
1662   assert(Except);
1663   EHCatchScope *CatchScope = EHStack.pushCatch(1);
1664   SEHCodeSlotStack.push_back(
1665       CreateMemTemp(getContext().IntTy, "__exception_code"));
1666 
1667   // If the filter is known to evaluate to 1, then we can use the clause
1668   // "catch i8* null". We can't do this on x86 because the filter has to save
1669   // the exception code.
1670   llvm::Constant *C =
1671       CGM.EmitConstantExpr(Except->getFilterExpr(), getContext().IntTy, this);
1672   if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86 && C &&
1673       C->isOneValue()) {
1674     CatchScope->setCatchAllHandler(0, createBasicBlock("__except"));
1675     return;
1676   }
1677 
1678   // In general, we have to emit an outlined filter function. Use the function
1679   // in place of the RTTI typeinfo global that C++ EH uses.
1680   llvm::Function *FilterFunc =
1681       HelperCGF.GenerateSEHFilterFunction(*this, *Except);
1682   llvm::Constant *OpaqueFunc =
1683       llvm::ConstantExpr::getBitCast(FilterFunc, Int8PtrTy);
1684   CatchScope->setHandler(0, OpaqueFunc, createBasicBlock("__except"));
1685 }
1686 
1687 void CodeGenFunction::ExitSEHTryStmt(const SEHTryStmt &S) {
1688   // Just pop the cleanup if it's a __finally block.
1689   if (S.getFinallyHandler()) {
1690     PopCleanupBlock();
1691     return;
1692   }
1693 
1694   // Otherwise, we must have an __except block.
1695   const SEHExceptStmt *Except = S.getExceptHandler();
1696   assert(Except && "__try must have __finally xor __except");
1697   EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1698 
1699   // Don't emit the __except block if the __try block lacked invokes.
1700   // TODO: Model unwind edges from instructions, either with iload / istore or
1701   // a try body function.
1702   if (!CatchScope.hasEHBranches()) {
1703     CatchScope.clearHandlerBlocks();
1704     EHStack.popCatch();
1705     SEHCodeSlotStack.pop_back();
1706     return;
1707   }
1708 
1709   // The fall-through block.
1710   llvm::BasicBlock *ContBB = createBasicBlock("__try.cont");
1711 
1712   // We just emitted the body of the __try; jump to the continue block.
1713   if (HaveInsertPoint())
1714     Builder.CreateBr(ContBB);
1715 
1716   // Check if our filter function returned true.
1717   emitCatchDispatchBlock(*this, CatchScope);
1718 
1719   // Grab the block before we pop the handler.
1720   llvm::BasicBlock *ExceptBB = CatchScope.getHandler(0).Block;
1721   EHStack.popCatch();
1722 
1723   EmitBlockAfterUses(ExceptBB);
1724 
1725   // On Win64, the exception pointer is the exception code. Copy it to the slot.
1726   if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
1727     llvm::Value *Code =
1728         Builder.CreatePtrToInt(getExceptionFromSlot(), IntPtrTy);
1729     Code = Builder.CreateTrunc(Code, Int32Ty);
1730     Builder.CreateStore(Code, SEHCodeSlotStack.back());
1731   }
1732 
1733   // Emit the __except body.
1734   EmitStmt(Except->getBlock());
1735 
1736   // End the lifetime of the exception code.
1737   SEHCodeSlotStack.pop_back();
1738 
1739   if (HaveInsertPoint())
1740     Builder.CreateBr(ContBB);
1741 
1742   EmitBlock(ContBB);
1743 }
1744 
1745 void CodeGenFunction::EmitSEHLeaveStmt(const SEHLeaveStmt &S) {
1746   // If this code is reachable then emit a stop point (if generating
1747   // debug info). We have to do this ourselves because we are on the
1748   // "simple" statement path.
1749   if (HaveInsertPoint())
1750     EmitStopPoint(&S);
1751 
1752   // This must be a __leave from a __finally block, which we warn on and is UB.
1753   // Just emit unreachable.
1754   if (!isSEHTryScope()) {
1755     Builder.CreateUnreachable();
1756     Builder.ClearInsertionPoint();
1757     return;
1758   }
1759 
1760   EmitBranchThroughCleanup(*SEHTryEpilogueStack.back());
1761 }
1762