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