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