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