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