1 //===--- CGException.cpp - Emit LLVM Code for C++ exceptions --------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This contains code dealing with C++ exception related code generation.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CodeGenFunction.h"
15 #include "CGCXXABI.h"
16 #include "CGCleanup.h"
17 #include "CGObjCRuntime.h"
18 #include "TargetInfo.h"
19 #include "clang/AST/Mangle.h"
20 #include "clang/AST/StmtCXX.h"
21 #include "clang/AST/StmtObjC.h"
22 #include "llvm/IR/CallSite.h"
23 #include "llvm/IR/Intrinsics.h"
24 
25 using namespace clang;
26 using namespace CodeGen;
27 
28 static llvm::Constant *getFreeExceptionFn(CodeGenModule &CGM) {
29   // void __cxa_free_exception(void *thrown_exception);
30 
31   llvm::FunctionType *FTy =
32     llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
33 
34   return CGM.CreateRuntimeFunction(FTy, "__cxa_free_exception");
35 }
36 
37 static llvm::Constant *getUnexpectedFn(CodeGenModule &CGM) {
38   // void __cxa_call_unexpected(void *thrown_exception);
39 
40   llvm::FunctionType *FTy =
41     llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
42 
43   return CGM.CreateRuntimeFunction(FTy, "__cxa_call_unexpected");
44 }
45 
46 llvm::Constant *CodeGenModule::getTerminateFn() {
47   // void __terminate();
48 
49   llvm::FunctionType *FTy =
50     llvm::FunctionType::get(VoidTy, /*IsVarArgs=*/false);
51 
52   StringRef name;
53 
54   // In C++, use std::terminate().
55   if (getLangOpts().CPlusPlus &&
56       getTarget().getCXXABI().isItaniumFamily()) {
57     name = "_ZSt9terminatev";
58   } else if (getLangOpts().CPlusPlus &&
59              getTarget().getCXXABI().isMicrosoft()) {
60     name = "\01?terminate@@YAXXZ";
61   } else if (getLangOpts().ObjC1 &&
62              getLangOpts().ObjCRuntime.hasTerminate())
63     name = "objc_terminate";
64   else
65     name = "abort";
66   return CreateRuntimeFunction(FTy, name);
67 }
68 
69 static llvm::Constant *getCatchallRethrowFn(CodeGenModule &CGM,
70                                             StringRef Name) {
71   llvm::FunctionType *FTy =
72     llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
73 
74   return CGM.CreateRuntimeFunction(FTy, Name);
75 }
76 
77 namespace {
78   /// The exceptions personality for a function.
79   struct EHPersonality {
80     const char *PersonalityFn;
81 
82     // If this is non-null, this personality requires a non-standard
83     // function for rethrowing an exception after a catchall cleanup.
84     // This function must have prototype void(void*).
85     const char *CatchallRethrowFn;
86 
87     static const EHPersonality &get(CodeGenModule &CGM,
88                                     const FunctionDecl *FD);
89     static const EHPersonality &get(CodeGenFunction &CGF) {
90       return get(CGF.CGM, dyn_cast_or_null<FunctionDecl>(CGF.CurCodeDecl));
91     }
92 
93     static const EHPersonality GNU_C;
94     static const EHPersonality GNU_C_SJLJ;
95     static const EHPersonality GNU_C_SEH;
96     static const EHPersonality GNU_ObjC;
97     static const EHPersonality GNUstep_ObjC;
98     static const EHPersonality GNU_ObjCXX;
99     static const EHPersonality NeXT_ObjC;
100     static const EHPersonality GNU_CPlusPlus;
101     static const EHPersonality GNU_CPlusPlus_SJLJ;
102     static const EHPersonality GNU_CPlusPlus_SEH;
103     static const EHPersonality MSVC_except_handler;
104     static const EHPersonality MSVC_C_specific_handler;
105     static const EHPersonality MSVC_CxxFrameHandler3;
106   };
107 }
108 
109 const EHPersonality EHPersonality::GNU_C = { "__gcc_personality_v0", nullptr };
110 const EHPersonality
111 EHPersonality::GNU_C_SJLJ = { "__gcc_personality_sj0", nullptr };
112 const EHPersonality
113 EHPersonality::GNU_C_SEH = { "__gcc_personality_seh0", nullptr };
114 const EHPersonality
115 EHPersonality::NeXT_ObjC = { "__objc_personality_v0", nullptr };
116 const EHPersonality
117 EHPersonality::GNU_CPlusPlus = { "__gxx_personality_v0", nullptr };
118 const EHPersonality
119 EHPersonality::GNU_CPlusPlus_SJLJ = { "__gxx_personality_sj0", nullptr };
120 const EHPersonality
121 EHPersonality::GNU_CPlusPlus_SEH = { "__gxx_personality_seh0", nullptr };
122 const EHPersonality
123 EHPersonality::GNU_ObjC = {"__gnu_objc_personality_v0", "objc_exception_throw"};
124 const EHPersonality
125 EHPersonality::GNU_ObjCXX = { "__gnustep_objcxx_personality_v0", nullptr };
126 const EHPersonality
127 EHPersonality::GNUstep_ObjC = { "__gnustep_objc_personality_v0", nullptr };
128 const EHPersonality
129 EHPersonality::MSVC_except_handler = { "_except_handler3", nullptr };
130 const EHPersonality
131 EHPersonality::MSVC_C_specific_handler = { "__C_specific_handler", nullptr };
132 const EHPersonality
133 EHPersonality::MSVC_CxxFrameHandler3 = { "__CxxFrameHandler3", nullptr };
134 
135 /// On Win64, use libgcc's SEH personality function. We fall back to dwarf on
136 /// other platforms, unless the user asked for SjLj exceptions.
137 static bool useLibGCCSEHPersonality(const llvm::Triple &T) {
138   return T.isOSWindows() && T.getArch() == llvm::Triple::x86_64;
139 }
140 
141 static const EHPersonality &getCPersonality(const llvm::Triple &T,
142                                             const LangOptions &L) {
143   if (L.SjLjExceptions)
144     return EHPersonality::GNU_C_SJLJ;
145   else if (useLibGCCSEHPersonality(T))
146     return EHPersonality::GNU_C_SEH;
147   return EHPersonality::GNU_C;
148 }
149 
150 static const EHPersonality &getObjCPersonality(const llvm::Triple &T,
151                                                const LangOptions &L) {
152   switch (L.ObjCRuntime.getKind()) {
153   case ObjCRuntime::FragileMacOSX:
154     return getCPersonality(T, L);
155   case ObjCRuntime::MacOSX:
156   case ObjCRuntime::iOS:
157     return EHPersonality::NeXT_ObjC;
158   case ObjCRuntime::GNUstep:
159     if (L.ObjCRuntime.getVersion() >= VersionTuple(1, 7))
160       return EHPersonality::GNUstep_ObjC;
161     // fallthrough
162   case ObjCRuntime::GCC:
163   case ObjCRuntime::ObjFW:
164     return EHPersonality::GNU_ObjC;
165   }
166   llvm_unreachable("bad runtime kind");
167 }
168 
169 static const EHPersonality &getCXXPersonality(const llvm::Triple &T,
170                                               const LangOptions &L) {
171   if (L.SjLjExceptions)
172     return EHPersonality::GNU_CPlusPlus_SJLJ;
173   else if (useLibGCCSEHPersonality(T))
174     return EHPersonality::GNU_CPlusPlus_SEH;
175   return EHPersonality::GNU_CPlusPlus;
176 }
177 
178 /// Determines the personality function to use when both C++
179 /// and Objective-C exceptions are being caught.
180 static const EHPersonality &getObjCXXPersonality(const llvm::Triple &T,
181                                                  const LangOptions &L) {
182   switch (L.ObjCRuntime.getKind()) {
183   // The ObjC personality defers to the C++ personality for non-ObjC
184   // handlers.  Unlike the C++ case, we use the same personality
185   // function on targets using (backend-driven) SJLJ EH.
186   case ObjCRuntime::MacOSX:
187   case ObjCRuntime::iOS:
188     return EHPersonality::NeXT_ObjC;
189 
190   // In the fragile ABI, just use C++ exception handling and hope
191   // they're not doing crazy exception mixing.
192   case ObjCRuntime::FragileMacOSX:
193     return getCXXPersonality(T, L);
194 
195   // The GCC runtime's personality function inherently doesn't support
196   // mixed EH.  Use the C++ personality just to avoid returning null.
197   case ObjCRuntime::GCC:
198   case ObjCRuntime::ObjFW: // XXX: this will change soon
199     return EHPersonality::GNU_ObjC;
200   case ObjCRuntime::GNUstep:
201     return EHPersonality::GNU_ObjCXX;
202   }
203   llvm_unreachable("bad runtime kind");
204 }
205 
206 static const EHPersonality &getSEHPersonalityMSVC(const llvm::Triple &T) {
207   if (T.getArch() == llvm::Triple::x86)
208     return EHPersonality::MSVC_except_handler;
209   return EHPersonality::MSVC_C_specific_handler;
210 }
211 
212 const EHPersonality &EHPersonality::get(CodeGenModule &CGM,
213                                         const FunctionDecl *FD) {
214   const llvm::Triple &T = CGM.getTarget().getTriple();
215   const LangOptions &L = CGM.getLangOpts();
216 
217   // Try to pick a personality function that is compatible with MSVC if we're
218   // not compiling Obj-C. Obj-C users better have an Obj-C runtime that supports
219   // the GCC-style personality function.
220   if (T.isWindowsMSVCEnvironment() && !L.ObjC1) {
221     if (L.SjLjExceptions)
222       return EHPersonality::GNU_CPlusPlus_SJLJ;
223     else if (FD && FD->usesSEHTry())
224       return getSEHPersonalityMSVC(T);
225     else
226       return EHPersonality::MSVC_CxxFrameHandler3;
227   }
228 
229   if (L.CPlusPlus && L.ObjC1)
230     return getObjCXXPersonality(T, L);
231   else if (L.CPlusPlus)
232     return getCXXPersonality(T, L);
233   else if (L.ObjC1)
234     return getObjCPersonality(T, L);
235   else
236     return getCPersonality(T, L);
237 }
238 
239 static llvm::Constant *getPersonalityFn(CodeGenModule &CGM,
240                                         const EHPersonality &Personality) {
241   llvm::Constant *Fn =
242     CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.Int32Ty, true),
243                               Personality.PersonalityFn);
244   return Fn;
245 }
246 
247 static llvm::Constant *getOpaquePersonalityFn(CodeGenModule &CGM,
248                                         const EHPersonality &Personality) {
249   llvm::Constant *Fn = getPersonalityFn(CGM, Personality);
250   return llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
251 }
252 
253 /// Check whether a personality function could reasonably be swapped
254 /// for a C++ personality function.
255 static bool PersonalityHasOnlyCXXUses(llvm::Constant *Fn) {
256   for (llvm::User *U : Fn->users()) {
257     // Conditionally white-list bitcasts.
258     if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(U)) {
259       if (CE->getOpcode() != llvm::Instruction::BitCast) return false;
260       if (!PersonalityHasOnlyCXXUses(CE))
261         return false;
262       continue;
263     }
264 
265     // Otherwise, it has to be a landingpad instruction.
266     llvm::LandingPadInst *LPI = dyn_cast<llvm::LandingPadInst>(U);
267     if (!LPI) return false;
268 
269     for (unsigned I = 0, E = LPI->getNumClauses(); I != E; ++I) {
270       // Look for something that would've been returned by the ObjC
271       // runtime's GetEHType() method.
272       llvm::Value *Val = LPI->getClause(I)->stripPointerCasts();
273       if (LPI->isCatch(I)) {
274         // Check if the catch value has the ObjC prefix.
275         if (llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Val))
276           // ObjC EH selector entries are always global variables with
277           // names starting like this.
278           if (GV->getName().startswith("OBJC_EHTYPE"))
279             return false;
280       } else {
281         // Check if any of the filter values have the ObjC prefix.
282         llvm::Constant *CVal = cast<llvm::Constant>(Val);
283         for (llvm::User::op_iterator
284                II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II) {
285           if (llvm::GlobalVariable *GV =
286               cast<llvm::GlobalVariable>((*II)->stripPointerCasts()))
287             // ObjC EH selector entries are always global variables with
288             // names starting like this.
289             if (GV->getName().startswith("OBJC_EHTYPE"))
290               return false;
291         }
292       }
293     }
294   }
295 
296   return true;
297 }
298 
299 /// Try to use the C++ personality function in ObjC++.  Not doing this
300 /// can cause some incompatibilities with gcc, which is more
301 /// aggressive about only using the ObjC++ personality in a function
302 /// when it really needs it.
303 void CodeGenModule::SimplifyPersonality() {
304   // If we're not in ObjC++ -fexceptions, there's nothing to do.
305   if (!LangOpts.CPlusPlus || !LangOpts.ObjC1 || !LangOpts.Exceptions)
306     return;
307 
308   // Both the problem this endeavors to fix and the way the logic
309   // above works is specific to the NeXT runtime.
310   if (!LangOpts.ObjCRuntime.isNeXTFamily())
311     return;
312 
313   const EHPersonality &ObjCXX = EHPersonality::get(*this, /*FD=*/nullptr);
314   const EHPersonality &CXX =
315       getCXXPersonality(getTarget().getTriple(), LangOpts);
316   if (&ObjCXX == &CXX)
317     return;
318 
319   assert(std::strcmp(ObjCXX.PersonalityFn, CXX.PersonalityFn) != 0 &&
320          "Different EHPersonalities using the same personality function.");
321 
322   llvm::Function *Fn = getModule().getFunction(ObjCXX.PersonalityFn);
323 
324   // Nothing to do if it's unused.
325   if (!Fn || Fn->use_empty()) return;
326 
327   // Can't do the optimization if it has non-C++ uses.
328   if (!PersonalityHasOnlyCXXUses(Fn)) return;
329 
330   // Create the C++ personality function and kill off the old
331   // function.
332   llvm::Constant *CXXFn = getPersonalityFn(*this, CXX);
333 
334   // This can happen if the user is screwing with us.
335   if (Fn->getType() != CXXFn->getType()) return;
336 
337   Fn->replaceAllUsesWith(CXXFn);
338   Fn->eraseFromParent();
339 }
340 
341 /// Returns the value to inject into a selector to indicate the
342 /// presence of a catch-all.
343 static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
344   // Possibly we should use @llvm.eh.catch.all.value here.
345   return llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
346 }
347 
348 namespace {
349   /// A cleanup to free the exception object if its initialization
350   /// throws.
351   struct FreeException : EHScopeStack::Cleanup {
352     llvm::Value *exn;
353     FreeException(llvm::Value *exn) : exn(exn) {}
354     void Emit(CodeGenFunction &CGF, Flags flags) override {
355       CGF.EmitNounwindRuntimeCall(getFreeExceptionFn(CGF.CGM), exn);
356     }
357   };
358 }
359 
360 // Emits an exception expression into the given location.  This
361 // differs from EmitAnyExprToMem only in that, if a final copy-ctor
362 // call is required, an exception within that copy ctor causes
363 // std::terminate to be invoked.
364 void CodeGenFunction::EmitAnyExprToExn(const Expr *e, llvm::Value *addr) {
365   // Make sure the exception object is cleaned up if there's an
366   // exception during initialization.
367   pushFullExprCleanup<FreeException>(EHCleanup, addr);
368   EHScopeStack::stable_iterator cleanup = EHStack.stable_begin();
369 
370   // __cxa_allocate_exception returns a void*;  we need to cast this
371   // to the appropriate type for the object.
372   llvm::Type *ty = ConvertTypeForMem(e->getType())->getPointerTo();
373   llvm::Value *typedAddr = Builder.CreateBitCast(addr, ty);
374 
375   // FIXME: this isn't quite right!  If there's a final unelided call
376   // to a copy constructor, then according to [except.terminate]p1 we
377   // must call std::terminate() if that constructor throws, because
378   // technically that copy occurs after the exception expression is
379   // evaluated but before the exception is caught.  But the best way
380   // to handle that is to teach EmitAggExpr to do the final copy
381   // differently if it can't be elided.
382   EmitAnyExprToMem(e, typedAddr, e->getType().getQualifiers(),
383                    /*IsInit*/ true);
384 
385   // Deactivate the cleanup block.
386   DeactivateCleanupBlock(cleanup, cast<llvm::Instruction>(typedAddr));
387 }
388 
389 llvm::Value *CodeGenFunction::getExceptionSlot() {
390   if (!ExceptionSlot)
391     ExceptionSlot = CreateTempAlloca(Int8PtrTy, "exn.slot");
392   return ExceptionSlot;
393 }
394 
395 llvm::Value *CodeGenFunction::getEHSelectorSlot() {
396   if (!EHSelectorSlot)
397     EHSelectorSlot = CreateTempAlloca(Int32Ty, "ehselector.slot");
398   return EHSelectorSlot;
399 }
400 
401 llvm::Value *CodeGenFunction::getExceptionFromSlot() {
402   return Builder.CreateLoad(getExceptionSlot(), "exn");
403 }
404 
405 llvm::Value *CodeGenFunction::getSelectorFromSlot() {
406   return Builder.CreateLoad(getEHSelectorSlot(), "sel");
407 }
408 
409 llvm::Value *CodeGenFunction::getAbnormalTerminationSlot() {
410   if (!AbnormalTerminationSlot)
411     AbnormalTerminationSlot =
412         CreateTempAlloca(Int8Ty, "abnormal.termination.slot");
413   return AbnormalTerminationSlot;
414 }
415 
416 void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E,
417                                        bool KeepInsertionPoint) {
418   if (const Expr *SubExpr = E->getSubExpr()) {
419     QualType ThrowType = SubExpr->getType();
420     if (ThrowType->isObjCObjectPointerType()) {
421       const Stmt *ThrowStmt = E->getSubExpr();
422       const ObjCAtThrowStmt S(E->getExprLoc(), const_cast<Stmt *>(ThrowStmt));
423       CGM.getObjCRuntime().EmitThrowStmt(*this, S, false);
424     } else {
425       CGM.getCXXABI().emitThrow(*this, E);
426     }
427   } else {
428     CGM.getCXXABI().emitRethrow(*this, /*isNoReturn=*/true);
429   }
430 
431   // throw is an expression, and the expression emitters expect us
432   // to leave ourselves at a valid insertion point.
433   if (KeepInsertionPoint)
434     EmitBlock(createBasicBlock("throw.cont"));
435 }
436 
437 void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
438   if (!CGM.getLangOpts().CXXExceptions)
439     return;
440 
441   const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
442   if (!FD) {
443     // Check if CapturedDecl is nothrow and create terminate scope for it.
444     if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
445       if (CD->isNothrow())
446         EHStack.pushTerminate();
447     }
448     return;
449   }
450   const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
451   if (!Proto)
452     return;
453 
454   ExceptionSpecificationType EST = Proto->getExceptionSpecType();
455   if (isNoexceptExceptionSpec(EST)) {
456     if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
457       // noexcept functions are simple terminate scopes.
458       EHStack.pushTerminate();
459     }
460   } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
461     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     EHFilterScope &filterScope = cast<EHFilterScope>(*EHStack.begin());
536     emitFilterDispatchBlock(*this, filterScope);
537     EHStack.popFilter();
538   }
539 }
540 
541 void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
542   EnterCXXTryStmt(S);
543   EmitStmt(S.getTryBlock());
544   ExitCXXTryStmt(S);
545 }
546 
547 void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
548   unsigned NumHandlers = S.getNumHandlers();
549   EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
550 
551   for (unsigned I = 0; I != NumHandlers; ++I) {
552     const CXXCatchStmt *C = S.getHandler(I);
553 
554     llvm::BasicBlock *Handler = createBasicBlock("catch");
555     if (C->getExceptionDecl()) {
556       // FIXME: Dropping the reference type on the type into makes it
557       // impossible to correctly implement catch-by-reference
558       // semantics for pointers.  Unfortunately, this is what all
559       // existing compilers do, and it's not clear that the standard
560       // personality routine is capable of doing this right.  See C++ DR 388:
561       //   http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
562       Qualifiers CaughtTypeQuals;
563       QualType CaughtType = CGM.getContext().getUnqualifiedArrayType(
564           C->getCaughtType().getNonReferenceType(), CaughtTypeQuals);
565 
566       llvm::Constant *TypeInfo = nullptr;
567       if (CaughtType->isObjCObjectPointerType())
568         TypeInfo = CGM.getObjCRuntime().GetEHType(CaughtType);
569       else
570         TypeInfo =
571             CGM.getAddrOfCXXHandlerMapEntry(CaughtType, C->getCaughtType());
572       CatchScope->setHandler(I, TypeInfo, Handler);
573     } else {
574       // No exception decl indicates '...', a catch-all.
575       CatchScope->setCatchAllHandler(I, Handler);
576     }
577   }
578 }
579 
580 llvm::BasicBlock *
581 CodeGenFunction::getEHDispatchBlock(EHScopeStack::stable_iterator si) {
582   // The dispatch block for the end of the scope chain is a block that
583   // just resumes unwinding.
584   if (si == EHStack.stable_end())
585     return getEHResumeBlock(true);
586 
587   // Otherwise, we should look at the actual scope.
588   EHScope &scope = *EHStack.find(si);
589 
590   llvm::BasicBlock *dispatchBlock = scope.getCachedEHDispatchBlock();
591   if (!dispatchBlock) {
592     switch (scope.getKind()) {
593     case EHScope::Catch: {
594       // Apply a special case to a single catch-all.
595       EHCatchScope &catchScope = cast<EHCatchScope>(scope);
596       if (catchScope.getNumHandlers() == 1 &&
597           catchScope.getHandler(0).isCatchAll()) {
598         dispatchBlock = catchScope.getHandler(0).Block;
599 
600       // Otherwise, make a dispatch block.
601       } else {
602         dispatchBlock = createBasicBlock("catch.dispatch");
603       }
604       break;
605     }
606 
607     case EHScope::Cleanup:
608       dispatchBlock = createBasicBlock("ehcleanup");
609       break;
610 
611     case EHScope::Filter:
612       dispatchBlock = createBasicBlock("filter.dispatch");
613       break;
614 
615     case EHScope::Terminate:
616       dispatchBlock = getTerminateHandler();
617       break;
618     }
619     scope.setCachedEHDispatchBlock(dispatchBlock);
620   }
621   return dispatchBlock;
622 }
623 
624 /// Check whether this is a non-EH scope, i.e. a scope which doesn't
625 /// affect exception handling.  Currently, the only non-EH scopes are
626 /// normal-only cleanup scopes.
627 static bool isNonEHScope(const EHScope &S) {
628   switch (S.getKind()) {
629   case EHScope::Cleanup:
630     return !cast<EHCleanupScope>(S).isEHCleanup();
631   case EHScope::Filter:
632   case EHScope::Catch:
633   case EHScope::Terminate:
634     return false;
635   }
636 
637   llvm_unreachable("Invalid EHScope Kind!");
638 }
639 
640 llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
641   assert(EHStack.requiresLandingPad());
642   assert(!EHStack.empty());
643 
644   // If exceptions are disabled, there are usually no landingpads. However, when
645   // SEH is enabled, functions using SEH still get landingpads.
646   const LangOptions &LO = CGM.getLangOpts();
647   if (!LO.Exceptions) {
648     if (!LO.Borland && !LO.MicrosoftExt)
649       return nullptr;
650     if (!currentFunctionUsesSEHTry())
651       return nullptr;
652   }
653 
654   // Check the innermost scope for a cached landing pad.  If this is
655   // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
656   llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
657   if (LP) return LP;
658 
659   // Build the landing pad for this scope.
660   LP = EmitLandingPad();
661   assert(LP);
662 
663   // Cache the landing pad on the innermost scope.  If this is a
664   // non-EH scope, cache the landing pad on the enclosing scope, too.
665   for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
666     ir->setCachedLandingPad(LP);
667     if (!isNonEHScope(*ir)) break;
668   }
669 
670   return LP;
671 }
672 
673 llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
674   assert(EHStack.requiresLandingPad());
675 
676   EHScope &innermostEHScope = *EHStack.find(EHStack.getInnermostEHScope());
677   switch (innermostEHScope.getKind()) {
678   case EHScope::Terminate:
679     return getTerminateLandingPad();
680 
681   case EHScope::Catch:
682   case EHScope::Cleanup:
683   case EHScope::Filter:
684     if (llvm::BasicBlock *lpad = innermostEHScope.getCachedLandingPad())
685       return lpad;
686   }
687 
688   // Save the current IR generation state.
689   CGBuilderTy::InsertPoint savedIP = Builder.saveAndClearIP();
690   auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, CurEHLocation);
691 
692   const EHPersonality &personality = EHPersonality::get(*this);
693 
694   // Create and configure the landing pad.
695   llvm::BasicBlock *lpad = createBasicBlock("lpad");
696   EmitBlock(lpad);
697 
698   llvm::LandingPadInst *LPadInst =
699     Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, nullptr),
700                              getOpaquePersonalityFn(CGM, personality), 0);
701 
702   llvm::Value *LPadExn = Builder.CreateExtractValue(LPadInst, 0);
703   Builder.CreateStore(LPadExn, getExceptionSlot());
704   llvm::Value *LPadSel = Builder.CreateExtractValue(LPadInst, 1);
705   Builder.CreateStore(LPadSel, getEHSelectorSlot());
706 
707   // Save the exception pointer.  It's safe to use a single exception
708   // pointer per function because EH cleanups can never have nested
709   // try/catches.
710   // Build the landingpad instruction.
711 
712   // Accumulate all the handlers in scope.
713   bool hasCatchAll = false;
714   bool hasCleanup = false;
715   bool hasFilter = false;
716   SmallVector<llvm::Value*, 4> filterTypes;
717   llvm::SmallPtrSet<llvm::Value*, 4> catchTypes;
718   for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end(); I != E;
719        ++I) {
720 
721     switch (I->getKind()) {
722     case EHScope::Cleanup:
723       // If we have a cleanup, remember that.
724       hasCleanup = (hasCleanup || cast<EHCleanupScope>(*I).isEHCleanup());
725       continue;
726 
727     case EHScope::Filter: {
728       assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
729       assert(!hasCatchAll && "EH filter reached after catch-all");
730 
731       // Filter scopes get added to the landingpad in weird ways.
732       EHFilterScope &filter = cast<EHFilterScope>(*I);
733       hasFilter = true;
734 
735       // Add all the filter values.
736       for (unsigned i = 0, e = filter.getNumFilters(); i != e; ++i)
737         filterTypes.push_back(filter.getFilter(i));
738       goto done;
739     }
740 
741     case EHScope::Terminate:
742       // Terminate scopes are basically catch-alls.
743       assert(!hasCatchAll);
744       hasCatchAll = true;
745       goto done;
746 
747     case EHScope::Catch:
748       break;
749     }
750 
751     EHCatchScope &catchScope = cast<EHCatchScope>(*I);
752     for (unsigned hi = 0, he = catchScope.getNumHandlers(); hi != he; ++hi) {
753       EHCatchScope::Handler handler = catchScope.getHandler(hi);
754 
755       // If this is a catch-all, register that and abort.
756       if (!handler.Type) {
757         assert(!hasCatchAll);
758         hasCatchAll = true;
759         goto done;
760       }
761 
762       // Check whether we already have a handler for this type.
763       if (catchTypes.insert(handler.Type).second)
764         // If not, add it directly to the landingpad.
765         LPadInst->addClause(handler.Type);
766     }
767   }
768 
769  done:
770   // If we have a catch-all, add null to the landingpad.
771   assert(!(hasCatchAll && hasFilter));
772   if (hasCatchAll) {
773     LPadInst->addClause(getCatchAllValue(*this));
774 
775   // If we have an EH filter, we need to add those handlers in the
776   // right place in the landingpad, which is to say, at the end.
777   } else if (hasFilter) {
778     // Create a filter expression: a constant array indicating which filter
779     // types there are. The personality routine only lands here if the filter
780     // doesn't match.
781     SmallVector<llvm::Constant*, 8> Filters;
782     llvm::ArrayType *AType =
783       llvm::ArrayType::get(!filterTypes.empty() ?
784                              filterTypes[0]->getType() : Int8PtrTy,
785                            filterTypes.size());
786 
787     for (unsigned i = 0, e = filterTypes.size(); i != e; ++i)
788       Filters.push_back(cast<llvm::Constant>(filterTypes[i]));
789     llvm::Constant *FilterArray = llvm::ConstantArray::get(AType, Filters);
790     LPadInst->addClause(FilterArray);
791 
792     // Also check whether we need a cleanup.
793     if (hasCleanup)
794       LPadInst->setCleanup(true);
795 
796   // Otherwise, signal that we at least have cleanups.
797   } else if (hasCleanup) {
798     LPadInst->setCleanup(true);
799   }
800 
801   assert((LPadInst->getNumClauses() > 0 || LPadInst->isCleanup()) &&
802          "landingpad instruction has no clauses!");
803 
804   // Tell the backend how to generate the landing pad.
805   Builder.CreateBr(getEHDispatchBlock(EHStack.getInnermostEHScope()));
806 
807   // Restore the old IR generation state.
808   Builder.restoreIP(savedIP);
809 
810   return lpad;
811 }
812 
813 /// Emit the structure of the dispatch block for the given catch scope.
814 /// It is an invariant that the dispatch block already exists.
815 static void emitCatchDispatchBlock(CodeGenFunction &CGF,
816                                    EHCatchScope &catchScope) {
817   llvm::BasicBlock *dispatchBlock = catchScope.getCachedEHDispatchBlock();
818   assert(dispatchBlock);
819 
820   // If there's only a single catch-all, getEHDispatchBlock returned
821   // that catch-all as the dispatch block.
822   if (catchScope.getNumHandlers() == 1 &&
823       catchScope.getHandler(0).isCatchAll()) {
824     assert(dispatchBlock == catchScope.getHandler(0).Block);
825     return;
826   }
827 
828   CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveIP();
829   CGF.EmitBlockAfterUses(dispatchBlock);
830 
831   // Select the right handler.
832   llvm::Value *llvm_eh_typeid_for =
833     CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
834 
835   // Load the selector value.
836   llvm::Value *selector = CGF.getSelectorFromSlot();
837 
838   // Test against each of the exception types we claim to catch.
839   for (unsigned i = 0, e = catchScope.getNumHandlers(); ; ++i) {
840     assert(i < e && "ran off end of handlers!");
841     const EHCatchScope::Handler &handler = catchScope.getHandler(i);
842 
843     llvm::Value *typeValue = handler.Type;
844     assert(typeValue && "fell into catch-all case!");
845     typeValue = CGF.Builder.CreateBitCast(typeValue, CGF.Int8PtrTy);
846 
847     // Figure out the next block.
848     bool nextIsEnd;
849     llvm::BasicBlock *nextBlock;
850 
851     // If this is the last handler, we're at the end, and the next
852     // block is the block for the enclosing EH scope.
853     if (i + 1 == e) {
854       nextBlock = CGF.getEHDispatchBlock(catchScope.getEnclosingEHScope());
855       nextIsEnd = true;
856 
857     // If the next handler is a catch-all, we're at the end, and the
858     // next block is that handler.
859     } else if (catchScope.getHandler(i+1).isCatchAll()) {
860       nextBlock = catchScope.getHandler(i+1).Block;
861       nextIsEnd = true;
862 
863     // Otherwise, we're not at the end and we need a new block.
864     } else {
865       nextBlock = CGF.createBasicBlock("catch.fallthrough");
866       nextIsEnd = false;
867     }
868 
869     // Figure out the catch type's index in the LSDA's type table.
870     llvm::CallInst *typeIndex =
871       CGF.Builder.CreateCall(llvm_eh_typeid_for, typeValue);
872     typeIndex->setDoesNotThrow();
873 
874     llvm::Value *matchesTypeIndex =
875       CGF.Builder.CreateICmpEQ(selector, typeIndex, "matches");
876     CGF.Builder.CreateCondBr(matchesTypeIndex, handler.Block, nextBlock);
877 
878     // If the next handler is a catch-all, we're completely done.
879     if (nextIsEnd) {
880       CGF.Builder.restoreIP(savedIP);
881       return;
882     }
883     // Otherwise we need to emit and continue at that block.
884     CGF.EmitBlock(nextBlock);
885   }
886 }
887 
888 void CodeGenFunction::popCatchScope() {
889   EHCatchScope &catchScope = cast<EHCatchScope>(*EHStack.begin());
890   if (catchScope.hasEHBranches())
891     emitCatchDispatchBlock(*this, catchScope);
892   EHStack.popCatch();
893 }
894 
895 void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
896   unsigned NumHandlers = S.getNumHandlers();
897   EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
898   assert(CatchScope.getNumHandlers() == NumHandlers);
899 
900   // If the catch was not required, bail out now.
901   if (!CatchScope.hasEHBranches()) {
902     CatchScope.clearHandlerBlocks();
903     EHStack.popCatch();
904     return;
905   }
906 
907   // Emit the structure of the EH dispatch for this catch.
908   emitCatchDispatchBlock(*this, CatchScope);
909 
910   // Copy the handler blocks off before we pop the EH stack.  Emitting
911   // the handlers might scribble on this memory.
912   SmallVector<EHCatchScope::Handler, 8> Handlers(NumHandlers);
913   memcpy(Handlers.data(), CatchScope.begin(),
914          NumHandlers * sizeof(EHCatchScope::Handler));
915 
916   EHStack.popCatch();
917 
918   // The fall-through block.
919   llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
920 
921   // We just emitted the body of the try; jump to the continue block.
922   if (HaveInsertPoint())
923     Builder.CreateBr(ContBB);
924 
925   // Determine if we need an implicit rethrow for all these catch handlers;
926   // see the comment below.
927   bool doImplicitRethrow = false;
928   if (IsFnTryBlock)
929     doImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
930                         isa<CXXConstructorDecl>(CurCodeDecl);
931 
932   // Perversely, we emit the handlers backwards precisely because we
933   // want them to appear in source order.  In all of these cases, the
934   // catch block will have exactly one predecessor, which will be a
935   // particular block in the catch dispatch.  However, in the case of
936   // a catch-all, one of the dispatch blocks will branch to two
937   // different handlers, and EmitBlockAfterUses will cause the second
938   // handler to be moved before the first.
939   for (unsigned I = NumHandlers; I != 0; --I) {
940     llvm::BasicBlock *CatchBlock = Handlers[I-1].Block;
941     EmitBlockAfterUses(CatchBlock);
942 
943     // Catch the exception if this isn't a catch-all.
944     const CXXCatchStmt *C = S.getHandler(I-1);
945 
946     // Enter a cleanup scope, including the catch variable and the
947     // end-catch.
948     RunCleanupsScope CatchScope(*this);
949 
950     // Initialize the catch variable and set up the cleanups.
951     CGM.getCXXABI().emitBeginCatch(*this, C);
952 
953     // Emit the PGO counter increment.
954     RegionCounter CatchCnt = getPGORegionCounter(C);
955     CatchCnt.beginRegion(Builder);
956 
957     // Perform the body of the catch.
958     EmitStmt(C->getHandlerBlock());
959 
960     // [except.handle]p11:
961     //   The currently handled exception is rethrown if control
962     //   reaches the end of a handler of the function-try-block of a
963     //   constructor or destructor.
964 
965     // It is important that we only do this on fallthrough and not on
966     // return.  Note that it's illegal to put a return in a
967     // constructor function-try-block's catch handler (p14), so this
968     // really only applies to destructors.
969     if (doImplicitRethrow && HaveInsertPoint()) {
970       CGM.getCXXABI().emitRethrow(*this, /*isNoReturn*/false);
971       Builder.CreateUnreachable();
972       Builder.ClearInsertionPoint();
973     }
974 
975     // Fall out through the catch cleanups.
976     CatchScope.ForceCleanup();
977 
978     // Branch out of the try.
979     if (HaveInsertPoint())
980       Builder.CreateBr(ContBB);
981   }
982 
983   RegionCounter ContCnt = getPGORegionCounter(&S);
984   EmitBlock(ContBB);
985   ContCnt.beginRegion(Builder);
986 }
987 
988 namespace {
989   struct CallEndCatchForFinally : EHScopeStack::Cleanup {
990     llvm::Value *ForEHVar;
991     llvm::Value *EndCatchFn;
992     CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn)
993       : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
994 
995     void Emit(CodeGenFunction &CGF, Flags flags) override {
996       llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
997       llvm::BasicBlock *CleanupContBB =
998         CGF.createBasicBlock("finally.cleanup.cont");
999 
1000       llvm::Value *ShouldEndCatch =
1001         CGF.Builder.CreateLoad(ForEHVar, "finally.endcatch");
1002       CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1003       CGF.EmitBlock(EndCatchBB);
1004       CGF.EmitRuntimeCallOrInvoke(EndCatchFn); // catch-all, so might throw
1005       CGF.EmitBlock(CleanupContBB);
1006     }
1007   };
1008 
1009   struct PerformFinally : EHScopeStack::Cleanup {
1010     const Stmt *Body;
1011     llvm::Value *ForEHVar;
1012     llvm::Value *EndCatchFn;
1013     llvm::Value *RethrowFn;
1014     llvm::Value *SavedExnVar;
1015 
1016     PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
1017                    llvm::Value *EndCatchFn,
1018                    llvm::Value *RethrowFn, llvm::Value *SavedExnVar)
1019       : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1020         RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
1021 
1022     void Emit(CodeGenFunction &CGF, Flags flags) override {
1023       // Enter a cleanup to call the end-catch function if one was provided.
1024       if (EndCatchFn)
1025         CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
1026                                                         ForEHVar, EndCatchFn);
1027 
1028       // Save the current cleanup destination in case there are
1029       // cleanups in the finally block.
1030       llvm::Value *SavedCleanupDest =
1031         CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
1032                                "cleanup.dest.saved");
1033 
1034       // Emit the finally block.
1035       CGF.EmitStmt(Body);
1036 
1037       // If the end of the finally is reachable, check whether this was
1038       // for EH.  If so, rethrow.
1039       if (CGF.HaveInsertPoint()) {
1040         llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
1041         llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
1042 
1043         llvm::Value *ShouldRethrow =
1044           CGF.Builder.CreateLoad(ForEHVar, "finally.shouldthrow");
1045         CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1046 
1047         CGF.EmitBlock(RethrowBB);
1048         if (SavedExnVar) {
1049           CGF.EmitRuntimeCallOrInvoke(RethrowFn,
1050                                       CGF.Builder.CreateLoad(SavedExnVar));
1051         } else {
1052           CGF.EmitRuntimeCallOrInvoke(RethrowFn);
1053         }
1054         CGF.Builder.CreateUnreachable();
1055 
1056         CGF.EmitBlock(ContBB);
1057 
1058         // Restore the cleanup destination.
1059         CGF.Builder.CreateStore(SavedCleanupDest,
1060                                 CGF.getNormalCleanupDestSlot());
1061       }
1062 
1063       // Leave the end-catch cleanup.  As an optimization, pretend that
1064       // the fallthrough path was inaccessible; we've dynamically proven
1065       // that we're not in the EH case along that path.
1066       if (EndCatchFn) {
1067         CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1068         CGF.PopCleanupBlock();
1069         CGF.Builder.restoreIP(SavedIP);
1070       }
1071 
1072       // Now make sure we actually have an insertion point or the
1073       // cleanup gods will hate us.
1074       CGF.EnsureInsertPoint();
1075     }
1076   };
1077 }
1078 
1079 /// Enters a finally block for an implementation using zero-cost
1080 /// exceptions.  This is mostly general, but hard-codes some
1081 /// language/ABI-specific behavior in the catch-all sections.
1082 void CodeGenFunction::FinallyInfo::enter(CodeGenFunction &CGF,
1083                                          const Stmt *body,
1084                                          llvm::Constant *beginCatchFn,
1085                                          llvm::Constant *endCatchFn,
1086                                          llvm::Constant *rethrowFn) {
1087   assert((beginCatchFn != nullptr) == (endCatchFn != nullptr) &&
1088          "begin/end catch functions not paired");
1089   assert(rethrowFn && "rethrow function is required");
1090 
1091   BeginCatchFn = beginCatchFn;
1092 
1093   // The rethrow function has one of the following two types:
1094   //   void (*)()
1095   //   void (*)(void*)
1096   // In the latter case we need to pass it the exception object.
1097   // But we can't use the exception slot because the @finally might
1098   // have a landing pad (which would overwrite the exception slot).
1099   llvm::FunctionType *rethrowFnTy =
1100     cast<llvm::FunctionType>(
1101       cast<llvm::PointerType>(rethrowFn->getType())->getElementType());
1102   SavedExnVar = nullptr;
1103   if (rethrowFnTy->getNumParams())
1104     SavedExnVar = CGF.CreateTempAlloca(CGF.Int8PtrTy, "finally.exn");
1105 
1106   // A finally block is a statement which must be executed on any edge
1107   // out of a given scope.  Unlike a cleanup, the finally block may
1108   // contain arbitrary control flow leading out of itself.  In
1109   // addition, finally blocks should always be executed, even if there
1110   // are no catch handlers higher on the stack.  Therefore, we
1111   // surround the protected scope with a combination of a normal
1112   // cleanup (to catch attempts to break out of the block via normal
1113   // control flow) and an EH catch-all (semantically "outside" any try
1114   // statement to which the finally block might have been attached).
1115   // The finally block itself is generated in the context of a cleanup
1116   // which conditionally leaves the catch-all.
1117 
1118   // Jump destination for performing the finally block on an exception
1119   // edge.  We'll never actually reach this block, so unreachable is
1120   // fine.
1121   RethrowDest = CGF.getJumpDestInCurrentScope(CGF.getUnreachableBlock());
1122 
1123   // Whether the finally block is being executed for EH purposes.
1124   ForEHVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "finally.for-eh");
1125   CGF.Builder.CreateStore(CGF.Builder.getFalse(), ForEHVar);
1126 
1127   // Enter a normal cleanup which will perform the @finally block.
1128   CGF.EHStack.pushCleanup<PerformFinally>(NormalCleanup, body,
1129                                           ForEHVar, endCatchFn,
1130                                           rethrowFn, SavedExnVar);
1131 
1132   // Enter a catch-all scope.
1133   llvm::BasicBlock *catchBB = CGF.createBasicBlock("finally.catchall");
1134   EHCatchScope *catchScope = CGF.EHStack.pushCatch(1);
1135   catchScope->setCatchAllHandler(0, catchBB);
1136 }
1137 
1138 void CodeGenFunction::FinallyInfo::exit(CodeGenFunction &CGF) {
1139   // Leave the finally catch-all.
1140   EHCatchScope &catchScope = cast<EHCatchScope>(*CGF.EHStack.begin());
1141   llvm::BasicBlock *catchBB = catchScope.getHandler(0).Block;
1142 
1143   CGF.popCatchScope();
1144 
1145   // If there are any references to the catch-all block, emit it.
1146   if (catchBB->use_empty()) {
1147     delete catchBB;
1148   } else {
1149     CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveAndClearIP();
1150     CGF.EmitBlock(catchBB);
1151 
1152     llvm::Value *exn = nullptr;
1153 
1154     // If there's a begin-catch function, call it.
1155     if (BeginCatchFn) {
1156       exn = CGF.getExceptionFromSlot();
1157       CGF.EmitNounwindRuntimeCall(BeginCatchFn, exn);
1158     }
1159 
1160     // If we need to remember the exception pointer to rethrow later, do so.
1161     if (SavedExnVar) {
1162       if (!exn) exn = CGF.getExceptionFromSlot();
1163       CGF.Builder.CreateStore(exn, SavedExnVar);
1164     }
1165 
1166     // Tell the cleanups in the finally block that we're do this for EH.
1167     CGF.Builder.CreateStore(CGF.Builder.getTrue(), ForEHVar);
1168 
1169     // Thread a jump through the finally cleanup.
1170     CGF.EmitBranchThroughCleanup(RethrowDest);
1171 
1172     CGF.Builder.restoreIP(savedIP);
1173   }
1174 
1175   // Finally, leave the @finally cleanup.
1176   CGF.PopCleanupBlock();
1177 }
1178 
1179 llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
1180   if (TerminateLandingPad)
1181     return TerminateLandingPad;
1182 
1183   CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1184 
1185   // This will get inserted at the end of the function.
1186   TerminateLandingPad = createBasicBlock("terminate.lpad");
1187   Builder.SetInsertPoint(TerminateLandingPad);
1188 
1189   // Tell the backend that this is a landing pad.
1190   const EHPersonality &Personality = EHPersonality::get(*this);
1191   llvm::LandingPadInst *LPadInst =
1192     Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, nullptr),
1193                              getOpaquePersonalityFn(CGM, Personality), 0);
1194   LPadInst->addClause(getCatchAllValue(*this));
1195 
1196   llvm::Value *Exn = 0;
1197   if (getLangOpts().CPlusPlus)
1198     Exn = Builder.CreateExtractValue(LPadInst, 0);
1199   llvm::CallInst *terminateCall =
1200       CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
1201   terminateCall->setDoesNotReturn();
1202   Builder.CreateUnreachable();
1203 
1204   // Restore the saved insertion state.
1205   Builder.restoreIP(SavedIP);
1206 
1207   return TerminateLandingPad;
1208 }
1209 
1210 llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
1211   if (TerminateHandler)
1212     return TerminateHandler;
1213 
1214   CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1215 
1216   // Set up the terminate handler.  This block is inserted at the very
1217   // end of the function by FinishFunction.
1218   TerminateHandler = createBasicBlock("terminate.handler");
1219   Builder.SetInsertPoint(TerminateHandler);
1220   llvm::Value *Exn = 0;
1221   if (getLangOpts().CPlusPlus)
1222     Exn = getExceptionFromSlot();
1223   llvm::CallInst *terminateCall =
1224       CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
1225   terminateCall->setDoesNotReturn();
1226   Builder.CreateUnreachable();
1227 
1228   // Restore the saved insertion state.
1229   Builder.restoreIP(SavedIP);
1230 
1231   return TerminateHandler;
1232 }
1233 
1234 llvm::BasicBlock *CodeGenFunction::getEHResumeBlock(bool isCleanup) {
1235   if (EHResumeBlock) return EHResumeBlock;
1236 
1237   CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1238 
1239   // We emit a jump to a notional label at the outermost unwind state.
1240   EHResumeBlock = createBasicBlock("eh.resume");
1241   Builder.SetInsertPoint(EHResumeBlock);
1242 
1243   const EHPersonality &Personality = EHPersonality::get(*this);
1244 
1245   // This can always be a call because we necessarily didn't find
1246   // anything on the EH stack which needs our help.
1247   const char *RethrowName = Personality.CatchallRethrowFn;
1248   if (RethrowName != nullptr && !isCleanup) {
1249     EmitRuntimeCall(getCatchallRethrowFn(CGM, RethrowName),
1250                     getExceptionFromSlot())->setDoesNotReturn();
1251     Builder.CreateUnreachable();
1252     Builder.restoreIP(SavedIP);
1253     return EHResumeBlock;
1254   }
1255 
1256   // Recreate the landingpad's return value for the 'resume' instruction.
1257   llvm::Value *Exn = getExceptionFromSlot();
1258   llvm::Value *Sel = getSelectorFromSlot();
1259 
1260   llvm::Type *LPadType = llvm::StructType::get(Exn->getType(),
1261                                                Sel->getType(), nullptr);
1262   llvm::Value *LPadVal = llvm::UndefValue::get(LPadType);
1263   LPadVal = Builder.CreateInsertValue(LPadVal, Exn, 0, "lpad.val");
1264   LPadVal = Builder.CreateInsertValue(LPadVal, Sel, 1, "lpad.val");
1265 
1266   Builder.CreateResume(LPadVal);
1267   Builder.restoreIP(SavedIP);
1268   return EHResumeBlock;
1269 }
1270 
1271 void CodeGenFunction::EmitSEHTryStmt(const SEHTryStmt &S) {
1272   // FIXME: Implement SEH on other architectures.
1273   const llvm::Triple &T = CGM.getTarget().getTriple();
1274   if (T.getArch() != llvm::Triple::x86_64 ||
1275       !T.isKnownWindowsMSVCEnvironment()) {
1276     ErrorUnsupported(&S, "__try statement");
1277     return;
1278   }
1279 
1280   SEHFinallyInfo FI;
1281   EnterSEHTryStmt(S, FI);
1282   {
1283     JumpDest TryExit = getJumpDestInCurrentScope("__try.__leave");
1284 
1285     SEHTryEpilogueStack.push_back(&TryExit);
1286     EmitStmt(S.getTryBlock());
1287     SEHTryEpilogueStack.pop_back();
1288 
1289     if (!TryExit.getBlock()->use_empty())
1290       EmitBlock(TryExit.getBlock(), /*IsFinished=*/true);
1291     else
1292       delete TryExit.getBlock();
1293   }
1294   ExitSEHTryStmt(S, FI);
1295 }
1296 
1297 namespace {
1298 struct PerformSEHFinally : EHScopeStack::Cleanup  {
1299   CodeGenFunction::SEHFinallyInfo *FI;
1300   PerformSEHFinally(CodeGenFunction::SEHFinallyInfo *FI) : FI(FI) {}
1301 
1302   void Emit(CodeGenFunction &CGF, Flags F) override {
1303     // Cleanups are emitted at most twice: once for normal control flow and once
1304     // for exception control flow. Branch into the finally block, and remember
1305     // the continuation block so we can branch out later.
1306     if (!FI->FinallyBB) {
1307       FI->FinallyBB = CGF.createBasicBlock("__finally");
1308       FI->FinallyBB->insertInto(CGF.CurFn);
1309       FI->FinallyBB->moveAfter(CGF.Builder.GetInsertBlock());
1310     }
1311 
1312     // Set the termination status and branch in.
1313     CGF.Builder.CreateStore(
1314         llvm::ConstantInt::get(CGF.Int8Ty, F.isForEHCleanup()),
1315         CGF.getAbnormalTerminationSlot());
1316     CGF.Builder.CreateBr(FI->FinallyBB);
1317 
1318     // Create a continuation block for normal or exceptional control.
1319     if (F.isForEHCleanup()) {
1320       assert(!FI->ResumeBB && "double emission for EH");
1321       FI->ResumeBB = CGF.createBasicBlock("__finally.resume");
1322       CGF.EmitBlock(FI->ResumeBB);
1323     } else {
1324       assert(F.isForNormalCleanup() && !FI->ContBB && "double normal emission");
1325       FI->ContBB = CGF.createBasicBlock("__finally.cont");
1326       CGF.EmitBlock(FI->ContBB);
1327       // Try to keep source order.
1328       FI->ContBB->moveAfter(FI->FinallyBB);
1329     }
1330   }
1331 };
1332 }
1333 
1334 /// Create a stub filter function that will ultimately hold the code of the
1335 /// filter expression. The EH preparation passes in LLVM will outline the code
1336 /// from the main function body into this stub.
1337 llvm::Function *
1338 CodeGenFunction::GenerateSEHFilterFunction(CodeGenFunction &ParentCGF,
1339                                            const SEHExceptStmt &Except) {
1340   const Decl *ParentCodeDecl = ParentCGF.CurCodeDecl;
1341   llvm::Function *ParentFn = ParentCGF.CurFn;
1342 
1343   Expr *FilterExpr = Except.getFilterExpr();
1344 
1345   // Get the mangled function name.
1346   SmallString<128> Name;
1347   {
1348     llvm::raw_svector_ostream OS(Name);
1349     const NamedDecl *Parent = dyn_cast_or_null<NamedDecl>(ParentCodeDecl);
1350     assert(Parent && "FIXME: handle unnamed decls (lambdas, blocks) with SEH");
1351     CGM.getCXXABI().getMangleContext().mangleSEHFilterExpression(Parent, OS);
1352   }
1353 
1354   // Arrange a function with the declaration:
1355   // int filt(EXCEPTION_POINTERS *exception_pointers, void *frame_pointer)
1356   QualType RetTy = getContext().IntTy;
1357   FunctionArgList Args;
1358   SEHPointersDecl = ImplicitParamDecl::Create(
1359       getContext(), nullptr, FilterExpr->getLocStart(),
1360       &getContext().Idents.get("exception_pointers"), getContext().VoidPtrTy);
1361   Args.push_back(SEHPointersDecl);
1362   Args.push_back(ImplicitParamDecl::Create(
1363       getContext(), nullptr, FilterExpr->getLocStart(),
1364       &getContext().Idents.get("frame_pointer"), getContext().VoidPtrTy));
1365   const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionDeclaration(
1366       RetTy, Args, FunctionType::ExtInfo(), /*isVariadic=*/false);
1367   llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
1368   llvm::Function *Fn = llvm::Function::Create(FnTy, ParentFn->getLinkage(),
1369                                               Name.str(), &CGM.getModule());
1370   // The filter is either in the same comdat as the function, or it's internal.
1371   if (llvm::Comdat *C = ParentFn->getComdat()) {
1372     Fn->setComdat(C);
1373   } else if (ParentFn->hasWeakLinkage() || ParentFn->hasLinkOnceLinkage()) {
1374     // FIXME: Unreachable with Rafael's changes?
1375     llvm::Comdat *C = CGM.getModule().getOrInsertComdat(ParentFn->getName());
1376     ParentFn->setComdat(C);
1377     Fn->setComdat(C);
1378   } else {
1379     Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
1380   }
1381 
1382   StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args,
1383                 FilterExpr->getLocStart(), FilterExpr->getLocStart());
1384 
1385   EmitSEHExceptionCodeSave();
1386 
1387   // Insert dummy allocas for every local variable in scope. We'll initialize
1388   // them and prune the unused ones after we find out which ones were
1389   // referenced.
1390   for (const auto &DeclPtrs : ParentCGF.LocalDeclMap) {
1391     const Decl *VD = DeclPtrs.first;
1392     llvm::Value *Ptr = DeclPtrs.second;
1393     auto *ValTy = cast<llvm::PointerType>(Ptr->getType())->getElementType();
1394     LocalDeclMap[VD] = CreateTempAlloca(ValTy, Ptr->getName() + ".filt");
1395   }
1396 
1397   // Emit the original filter expression, convert to i32, and return.
1398   llvm::Value *R = EmitScalarExpr(FilterExpr);
1399   R = Builder.CreateIntCast(R, CGM.IntTy,
1400                             FilterExpr->getType()->isSignedIntegerType());
1401   Builder.CreateStore(R, ReturnValue);
1402 
1403   FinishFunction(FilterExpr->getLocEnd());
1404 
1405   for (const auto &DeclPtrs : ParentCGF.LocalDeclMap) {
1406     const Decl *VD = DeclPtrs.first;
1407     auto *Alloca = cast<llvm::AllocaInst>(LocalDeclMap[VD]);
1408     if (Alloca->hasNUses(0)) {
1409       Alloca->eraseFromParent();
1410       continue;
1411     }
1412     ErrorUnsupported(FilterExpr,
1413                      "SEH filter expression local variable capture");
1414   }
1415 
1416   return Fn;
1417 }
1418 
1419 void CodeGenFunction::EmitSEHExceptionCodeSave() {
1420   // Save the exception code in the exception slot to unify exception access in
1421   // the filter function and the landing pad.
1422   // struct EXCEPTION_POINTERS {
1423   //   EXCEPTION_RECORD *ExceptionRecord;
1424   //   CONTEXT *ContextRecord;
1425   // };
1426   // void *exn.slot =
1427   //     (void *)(uintptr_t)exception_pointers->ExceptionRecord->ExceptionCode;
1428   llvm::Value *Ptrs = Builder.CreateLoad(GetAddrOfLocalVar(SEHPointersDecl));
1429   llvm::Type *RecordTy = CGM.Int32Ty->getPointerTo();
1430   llvm::Type *PtrsTy = llvm::StructType::get(RecordTy, CGM.VoidPtrTy, nullptr);
1431   Ptrs = Builder.CreateBitCast(Ptrs, PtrsTy->getPointerTo());
1432   llvm::Value *Rec = Builder.CreateStructGEP(Ptrs, 0);
1433   Rec = Builder.CreateLoad(Rec);
1434   llvm::Value *Code = Builder.CreateLoad(Rec);
1435   Code = Builder.CreateZExt(Code, CGM.IntPtrTy);
1436   // FIXME: Change landing pads to produce {i32, i32} and make the exception
1437   // slot an i32.
1438   Code = Builder.CreateIntToPtr(Code, CGM.VoidPtrTy);
1439   Builder.CreateStore(Code, getExceptionSlot());
1440 }
1441 
1442 llvm::Value *CodeGenFunction::EmitSEHExceptionInfo() {
1443   // Sema should diagnose calling this builtin outside of a filter context, but
1444   // don't crash if we screw up.
1445   if (!SEHPointersDecl)
1446     return llvm::UndefValue::get(Int8PtrTy);
1447   return Builder.CreateLoad(GetAddrOfLocalVar(SEHPointersDecl));
1448 }
1449 
1450 llvm::Value *CodeGenFunction::EmitSEHExceptionCode() {
1451   // If we're in a landing pad or filter function, the exception slot contains
1452   // the code.
1453   assert(ExceptionSlot);
1454   llvm::Value *Code =
1455       Builder.CreatePtrToInt(getExceptionFromSlot(), CGM.IntPtrTy);
1456   return Builder.CreateTrunc(Code, CGM.Int32Ty);
1457 }
1458 
1459 llvm::Value *CodeGenFunction::EmitSEHAbnormalTermination() {
1460   // Load from the abnormal termination slot. It will be uninitialized outside
1461   // of __finally blocks, which we should warn or error on.
1462   llvm::Value *IsEH = Builder.CreateLoad(getAbnormalTerminationSlot());
1463   return Builder.CreateZExt(IsEH, Int32Ty);
1464 }
1465 
1466 void CodeGenFunction::EnterSEHTryStmt(const SEHTryStmt &S, SEHFinallyInfo &FI) {
1467   if (S.getFinallyHandler()) {
1468     // Push a cleanup for __finally blocks.
1469     EHStack.pushCleanup<PerformSEHFinally>(NormalAndEHCleanup, &FI);
1470     return;
1471   }
1472 
1473   // Otherwise, we must have an __except block.
1474   SEHExceptStmt *Except = S.getExceptHandler();
1475   assert(Except);
1476   EHCatchScope *CatchScope = EHStack.pushCatch(1);
1477 
1478   // If the filter is known to evaluate to 1, then we can use the clause "catch
1479   // i8* null".
1480   llvm::Constant *C =
1481       CGM.EmitConstantExpr(Except->getFilterExpr(), getContext().IntTy, this);
1482   if (C && C->isOneValue()) {
1483     CatchScope->setCatchAllHandler(0, createBasicBlock("__except"));
1484     return;
1485   }
1486 
1487   // In general, we have to emit an outlined filter function. Use the function
1488   // in place of the RTTI typeinfo global that C++ EH uses.
1489   CodeGenFunction FilterCGF(CGM, /*suppressNewContext=*/true);
1490   llvm::Function *FilterFunc =
1491       FilterCGF.GenerateSEHFilterFunction(*this, *Except);
1492   llvm::Constant *OpaqueFunc =
1493       llvm::ConstantExpr::getBitCast(FilterFunc, Int8PtrTy);
1494   CatchScope->setHandler(0, OpaqueFunc, createBasicBlock("__except"));
1495 }
1496 
1497 void CodeGenFunction::ExitSEHTryStmt(const SEHTryStmt &S, SEHFinallyInfo &FI) {
1498   // Just pop the cleanup if it's a __finally block.
1499   if (const SEHFinallyStmt *Finally = S.getFinallyHandler()) {
1500     PopCleanupBlock();
1501     assert(FI.ContBB && "did not emit normal cleanup");
1502 
1503     // Emit the code into FinallyBB.
1504     CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1505     Builder.SetInsertPoint(FI.FinallyBB);
1506     EmitStmt(Finally->getBlock());
1507 
1508     if (HaveInsertPoint()) {
1509       if (FI.ResumeBB) {
1510         llvm::Value *IsEH = Builder.CreateLoad(getAbnormalTerminationSlot(),
1511                                                "abnormal.termination");
1512         IsEH = Builder.CreateICmpEQ(IsEH, llvm::ConstantInt::get(Int8Ty, 0));
1513         Builder.CreateCondBr(IsEH, FI.ContBB, FI.ResumeBB);
1514       } else {
1515         // There was nothing exceptional in the try body, so we only have normal
1516         // control flow.
1517         Builder.CreateBr(FI.ContBB);
1518       }
1519     }
1520 
1521     Builder.restoreIP(SavedIP);
1522 
1523     return;
1524   }
1525 
1526   // Otherwise, we must have an __except block.
1527   const SEHExceptStmt *Except = S.getExceptHandler();
1528   assert(Except && "__try must have __finally xor __except");
1529   EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1530 
1531   // Don't emit the __except block if the __try block lacked invokes.
1532   // TODO: Model unwind edges from instructions, either with iload / istore or
1533   // a try body function.
1534   if (!CatchScope.hasEHBranches()) {
1535     CatchScope.clearHandlerBlocks();
1536     EHStack.popCatch();
1537     return;
1538   }
1539 
1540   // The fall-through block.
1541   llvm::BasicBlock *ContBB = createBasicBlock("__try.cont");
1542 
1543   // We just emitted the body of the __try; jump to the continue block.
1544   if (HaveInsertPoint())
1545     Builder.CreateBr(ContBB);
1546 
1547   // Check if our filter function returned true.
1548   emitCatchDispatchBlock(*this, CatchScope);
1549 
1550   // Grab the block before we pop the handler.
1551   llvm::BasicBlock *ExceptBB = CatchScope.getHandler(0).Block;
1552   EHStack.popCatch();
1553 
1554   EmitBlockAfterUses(ExceptBB);
1555 
1556   // Emit the __except body.
1557   EmitStmt(Except->getBlock());
1558 
1559   if (HaveInsertPoint())
1560     Builder.CreateBr(ContBB);
1561 
1562   EmitBlock(ContBB);
1563 }
1564 
1565 void CodeGenFunction::EmitSEHLeaveStmt(const SEHLeaveStmt &S) {
1566   // If this code is reachable then emit a stop point (if generating
1567   // debug info). We have to do this ourselves because we are on the
1568   // "simple" statement path.
1569   if (HaveInsertPoint())
1570     EmitStopPoint(&S);
1571 
1572   assert(!SEHTryEpilogueStack.empty() &&
1573          "sema should have rejected this __leave");
1574   EmitBranchThroughCleanup(*SEHTryEpilogueStack.back());
1575 }
1576