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