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