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