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