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     return;
497   const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
498   if (Proto == 0)
499     return;
500 
501   ExceptionSpecificationType EST = Proto->getExceptionSpecType();
502   if (isNoexceptExceptionSpec(EST)) {
503     if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
504       // noexcept functions are simple terminate scopes.
505       EHStack.pushTerminate();
506     }
507   } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
508     unsigned NumExceptions = Proto->getNumExceptions();
509     EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
510 
511     for (unsigned I = 0; I != NumExceptions; ++I) {
512       QualType Ty = Proto->getExceptionType(I);
513       QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
514       llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType,
515                                                         /*ForEH=*/true);
516       Filter->setFilter(I, EHType);
517     }
518   }
519 }
520 
521 /// Emit the dispatch block for a filter scope if necessary.
522 static void emitFilterDispatchBlock(CodeGenFunction &CGF,
523                                     EHFilterScope &filterScope) {
524   llvm::BasicBlock *dispatchBlock = filterScope.getCachedEHDispatchBlock();
525   if (!dispatchBlock) return;
526   if (dispatchBlock->use_empty()) {
527     delete dispatchBlock;
528     return;
529   }
530 
531   CGF.EmitBlockAfterUses(dispatchBlock);
532 
533   // If this isn't a catch-all filter, we need to check whether we got
534   // here because the filter triggered.
535   if (filterScope.getNumFilters()) {
536     // Load the selector value.
537     llvm::Value *selector = CGF.getSelectorFromSlot();
538     llvm::BasicBlock *unexpectedBB = CGF.createBasicBlock("ehspec.unexpected");
539 
540     llvm::Value *zero = CGF.Builder.getInt32(0);
541     llvm::Value *failsFilter =
542       CGF.Builder.CreateICmpSLT(selector, zero, "ehspec.fails");
543     CGF.Builder.CreateCondBr(failsFilter, unexpectedBB, CGF.getEHResumeBlock(false));
544 
545     CGF.EmitBlock(unexpectedBB);
546   }
547 
548   // Call __cxa_call_unexpected.  This doesn't need to be an invoke
549   // because __cxa_call_unexpected magically filters exceptions
550   // according to the last landing pad the exception was thrown
551   // into.  Seriously.
552   llvm::Value *exn = CGF.getExceptionFromSlot();
553   CGF.EmitRuntimeCall(getUnexpectedFn(CGF.CGM), exn)
554     ->setDoesNotReturn();
555   CGF.Builder.CreateUnreachable();
556 }
557 
558 void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
559   if (!CGM.getLangOpts().CXXExceptions)
560     return;
561 
562   const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
563   if (FD == 0)
564     return;
565   const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
566   if (Proto == 0)
567     return;
568 
569   ExceptionSpecificationType EST = Proto->getExceptionSpecType();
570   if (isNoexceptExceptionSpec(EST)) {
571     if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
572       EHStack.popTerminate();
573     }
574   } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
575     EHFilterScope &filterScope = cast<EHFilterScope>(*EHStack.begin());
576     emitFilterDispatchBlock(*this, filterScope);
577     EHStack.popFilter();
578   }
579 }
580 
581 void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
582   if (CGM.getTarget().getTriple().isWindowsMSVCEnvironment()) {
583     ErrorUnsupported(&S, "try statement");
584     return;
585   }
586 
587   EnterCXXTryStmt(S);
588   EmitStmt(S.getTryBlock());
589   ExitCXXTryStmt(S);
590 }
591 
592 void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
593   unsigned NumHandlers = S.getNumHandlers();
594   EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
595 
596   for (unsigned I = 0; I != NumHandlers; ++I) {
597     const CXXCatchStmt *C = S.getHandler(I);
598 
599     llvm::BasicBlock *Handler = createBasicBlock("catch");
600     if (C->getExceptionDecl()) {
601       // FIXME: Dropping the reference type on the type into makes it
602       // impossible to correctly implement catch-by-reference
603       // semantics for pointers.  Unfortunately, this is what all
604       // existing compilers do, and it's not clear that the standard
605       // personality routine is capable of doing this right.  See C++ DR 388:
606       //   http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
607       QualType CaughtType = C->getCaughtType();
608       CaughtType = CaughtType.getNonReferenceType().getUnqualifiedType();
609 
610       llvm::Value *TypeInfo = 0;
611       if (CaughtType->isObjCObjectPointerType())
612         TypeInfo = CGM.getObjCRuntime().GetEHType(CaughtType);
613       else
614         TypeInfo = CGM.GetAddrOfRTTIDescriptor(CaughtType, /*ForEH=*/true);
615       CatchScope->setHandler(I, TypeInfo, Handler);
616     } else {
617       // No exception decl indicates '...', a catch-all.
618       CatchScope->setCatchAllHandler(I, Handler);
619     }
620   }
621 }
622 
623 llvm::BasicBlock *
624 CodeGenFunction::getEHDispatchBlock(EHScopeStack::stable_iterator si) {
625   // The dispatch block for the end of the scope chain is a block that
626   // just resumes unwinding.
627   if (si == EHStack.stable_end())
628     return getEHResumeBlock(true);
629 
630   // Otherwise, we should look at the actual scope.
631   EHScope &scope = *EHStack.find(si);
632 
633   llvm::BasicBlock *dispatchBlock = scope.getCachedEHDispatchBlock();
634   if (!dispatchBlock) {
635     switch (scope.getKind()) {
636     case EHScope::Catch: {
637       // Apply a special case to a single catch-all.
638       EHCatchScope &catchScope = cast<EHCatchScope>(scope);
639       if (catchScope.getNumHandlers() == 1 &&
640           catchScope.getHandler(0).isCatchAll()) {
641         dispatchBlock = catchScope.getHandler(0).Block;
642 
643       // Otherwise, make a dispatch block.
644       } else {
645         dispatchBlock = createBasicBlock("catch.dispatch");
646       }
647       break;
648     }
649 
650     case EHScope::Cleanup:
651       dispatchBlock = createBasicBlock("ehcleanup");
652       break;
653 
654     case EHScope::Filter:
655       dispatchBlock = createBasicBlock("filter.dispatch");
656       break;
657 
658     case EHScope::Terminate:
659       dispatchBlock = getTerminateHandler();
660       break;
661     }
662     scope.setCachedEHDispatchBlock(dispatchBlock);
663   }
664   return dispatchBlock;
665 }
666 
667 /// Check whether this is a non-EH scope, i.e. a scope which doesn't
668 /// affect exception handling.  Currently, the only non-EH scopes are
669 /// normal-only cleanup scopes.
670 static bool isNonEHScope(const EHScope &S) {
671   switch (S.getKind()) {
672   case EHScope::Cleanup:
673     return !cast<EHCleanupScope>(S).isEHCleanup();
674   case EHScope::Filter:
675   case EHScope::Catch:
676   case EHScope::Terminate:
677     return false;
678   }
679 
680   llvm_unreachable("Invalid EHScope Kind!");
681 }
682 
683 llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
684   assert(EHStack.requiresLandingPad());
685   assert(!EHStack.empty());
686 
687   if (!CGM.getLangOpts().Exceptions)
688     return 0;
689 
690   // Check the innermost scope for a cached landing pad.  If this is
691   // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
692   llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
693   if (LP) return LP;
694 
695   // Build the landing pad for this scope.
696   LP = EmitLandingPad();
697   assert(LP);
698 
699   // Cache the landing pad on the innermost scope.  If this is a
700   // non-EH scope, cache the landing pad on the enclosing scope, too.
701   for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
702     ir->setCachedLandingPad(LP);
703     if (!isNonEHScope(*ir)) break;
704   }
705 
706   return LP;
707 }
708 
709 // This code contains a hack to work around a design flaw in
710 // LLVM's EH IR which breaks semantics after inlining.  This same
711 // hack is implemented in llvm-gcc.
712 //
713 // The LLVM EH abstraction is basically a thin veneer over the
714 // traditional GCC zero-cost design: for each range of instructions
715 // in the function, there is (at most) one "landing pad" with an
716 // associated chain of EH actions.  A language-specific personality
717 // function interprets this chain of actions and (1) decides whether
718 // or not to resume execution at the landing pad and (2) if so,
719 // provides an integer indicating why it's stopping.  In LLVM IR,
720 // the association of a landing pad with a range of instructions is
721 // achieved via an invoke instruction, the chain of actions becomes
722 // the arguments to the @llvm.eh.selector call, and the selector
723 // call returns the integer indicator.  Other than the required
724 // presence of two intrinsic function calls in the landing pad,
725 // the IR exactly describes the layout of the output code.
726 //
727 // A principal advantage of this design is that it is completely
728 // language-agnostic; in theory, the LLVM optimizers can treat
729 // landing pads neutrally, and targets need only know how to lower
730 // the intrinsics to have a functioning exceptions system (assuming
731 // that platform exceptions follow something approximately like the
732 // GCC design).  Unfortunately, landing pads cannot be combined in a
733 // language-agnostic way: given selectors A and B, there is no way
734 // to make a single landing pad which faithfully represents the
735 // semantics of propagating an exception first through A, then
736 // through B, without knowing how the personality will interpret the
737 // (lowered form of the) selectors.  This means that inlining has no
738 // choice but to crudely chain invokes (i.e., to ignore invokes in
739 // the inlined function, but to turn all unwindable calls into
740 // invokes), which is only semantically valid if every unwind stops
741 // at every landing pad.
742 //
743 // Therefore, the invoke-inline hack is to guarantee that every
744 // landing pad has a catch-all.
745 enum CleanupHackLevel_t {
746   /// A level of hack that requires that all landing pads have
747   /// catch-alls.
748   CHL_MandatoryCatchall,
749 
750   /// A level of hack that requires that all landing pads handle
751   /// cleanups.
752   CHL_MandatoryCleanup,
753 
754   /// No hacks at all;  ideal IR generation.
755   CHL_Ideal
756 };
757 const CleanupHackLevel_t CleanupHackLevel = CHL_MandatoryCleanup;
758 
759 llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
760   assert(EHStack.requiresLandingPad());
761 
762   EHScope &innermostEHScope = *EHStack.find(EHStack.getInnermostEHScope());
763   switch (innermostEHScope.getKind()) {
764   case EHScope::Terminate:
765     return getTerminateLandingPad();
766 
767   case EHScope::Catch:
768   case EHScope::Cleanup:
769   case EHScope::Filter:
770     if (llvm::BasicBlock *lpad = innermostEHScope.getCachedLandingPad())
771       return lpad;
772   }
773 
774   // Save the current IR generation state.
775   CGBuilderTy::InsertPoint savedIP = Builder.saveAndClearIP();
776   SaveAndRestoreLocation AutoRestoreLocation(*this, Builder);
777   if (CGDebugInfo *DI = getDebugInfo())
778     DI->EmitLocation(Builder, CurEHLocation);
779 
780   const EHPersonality &personality = EHPersonality::get(getLangOpts());
781 
782   // Create and configure the landing pad.
783   llvm::BasicBlock *lpad = createBasicBlock("lpad");
784   EmitBlock(lpad);
785 
786   llvm::LandingPadInst *LPadInst =
787     Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, NULL),
788                              getOpaquePersonalityFn(CGM, personality), 0);
789 
790   llvm::Value *LPadExn = Builder.CreateExtractValue(LPadInst, 0);
791   Builder.CreateStore(LPadExn, getExceptionSlot());
792   llvm::Value *LPadSel = Builder.CreateExtractValue(LPadInst, 1);
793   Builder.CreateStore(LPadSel, getEHSelectorSlot());
794 
795   // Save the exception pointer.  It's safe to use a single exception
796   // pointer per function because EH cleanups can never have nested
797   // try/catches.
798   // Build the landingpad instruction.
799 
800   // Accumulate all the handlers in scope.
801   bool hasCatchAll = false;
802   bool hasCleanup = false;
803   bool hasFilter = false;
804   SmallVector<llvm::Value*, 4> filterTypes;
805   llvm::SmallPtrSet<llvm::Value*, 4> catchTypes;
806   for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end();
807          I != E; ++I) {
808 
809     switch (I->getKind()) {
810     case EHScope::Cleanup:
811       // If we have a cleanup, remember that.
812       hasCleanup = (hasCleanup || cast<EHCleanupScope>(*I).isEHCleanup());
813       continue;
814 
815     case EHScope::Filter: {
816       assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
817       assert(!hasCatchAll && "EH filter reached after catch-all");
818 
819       // Filter scopes get added to the landingpad in weird ways.
820       EHFilterScope &filter = cast<EHFilterScope>(*I);
821       hasFilter = true;
822 
823       // Add all the filter values.
824       for (unsigned i = 0, e = filter.getNumFilters(); i != e; ++i)
825         filterTypes.push_back(filter.getFilter(i));
826       goto done;
827     }
828 
829     case EHScope::Terminate:
830       // Terminate scopes are basically catch-alls.
831       assert(!hasCatchAll);
832       hasCatchAll = true;
833       goto done;
834 
835     case EHScope::Catch:
836       break;
837     }
838 
839     EHCatchScope &catchScope = cast<EHCatchScope>(*I);
840     for (unsigned hi = 0, he = catchScope.getNumHandlers(); hi != he; ++hi) {
841       EHCatchScope::Handler handler = catchScope.getHandler(hi);
842 
843       // If this is a catch-all, register that and abort.
844       if (!handler.Type) {
845         assert(!hasCatchAll);
846         hasCatchAll = true;
847         goto done;
848       }
849 
850       // Check whether we already have a handler for this type.
851       if (catchTypes.insert(handler.Type))
852         // If not, add it directly to the landingpad.
853         LPadInst->addClause(handler.Type);
854     }
855   }
856 
857  done:
858   // If we have a catch-all, add null to the landingpad.
859   assert(!(hasCatchAll && hasFilter));
860   if (hasCatchAll) {
861     LPadInst->addClause(getCatchAllValue(*this));
862 
863   // If we have an EH filter, we need to add those handlers in the
864   // right place in the landingpad, which is to say, at the end.
865   } else if (hasFilter) {
866     // Create a filter expression: a constant array indicating which filter
867     // types there are. The personality routine only lands here if the filter
868     // doesn't match.
869     SmallVector<llvm::Constant*, 8> Filters;
870     llvm::ArrayType *AType =
871       llvm::ArrayType::get(!filterTypes.empty() ?
872                              filterTypes[0]->getType() : Int8PtrTy,
873                            filterTypes.size());
874 
875     for (unsigned i = 0, e = filterTypes.size(); i != e; ++i)
876       Filters.push_back(cast<llvm::Constant>(filterTypes[i]));
877     llvm::Constant *FilterArray = llvm::ConstantArray::get(AType, Filters);
878     LPadInst->addClause(FilterArray);
879 
880     // Also check whether we need a cleanup.
881     if (hasCleanup)
882       LPadInst->setCleanup(true);
883 
884   // Otherwise, signal that we at least have cleanups.
885   } else if (CleanupHackLevel == CHL_MandatoryCatchall || hasCleanup) {
886     if (CleanupHackLevel == CHL_MandatoryCatchall)
887       LPadInst->addClause(getCatchAllValue(*this));
888     else
889       LPadInst->setCleanup(true);
890   }
891 
892   assert((LPadInst->getNumClauses() > 0 || LPadInst->isCleanup()) &&
893          "landingpad instruction has no clauses!");
894 
895   // Tell the backend how to generate the landing pad.
896   Builder.CreateBr(getEHDispatchBlock(EHStack.getInnermostEHScope()));
897 
898   // Restore the old IR generation state.
899   Builder.restoreIP(savedIP);
900 
901   return lpad;
902 }
903 
904 namespace {
905   /// A cleanup to call __cxa_end_catch.  In many cases, the caught
906   /// exception type lets us state definitively that the thrown exception
907   /// type does not have a destructor.  In particular:
908   ///   - Catch-alls tell us nothing, so we have to conservatively
909   ///     assume that the thrown exception might have a destructor.
910   ///   - Catches by reference behave according to their base types.
911   ///   - Catches of non-record types will only trigger for exceptions
912   ///     of non-record types, which never have destructors.
913   ///   - Catches of record types can trigger for arbitrary subclasses
914   ///     of the caught type, so we have to assume the actual thrown
915   ///     exception type might have a throwing destructor, even if the
916   ///     caught type's destructor is trivial or nothrow.
917   struct CallEndCatch : EHScopeStack::Cleanup {
918     CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
919     bool MightThrow;
920 
921     void Emit(CodeGenFunction &CGF, Flags flags) override {
922       if (!MightThrow) {
923         CGF.EmitNounwindRuntimeCall(getEndCatchFn(CGF.CGM));
924         return;
925       }
926 
927       CGF.EmitRuntimeCallOrInvoke(getEndCatchFn(CGF.CGM));
928     }
929   };
930 }
931 
932 /// Emits a call to __cxa_begin_catch and enters a cleanup to call
933 /// __cxa_end_catch.
934 ///
935 /// \param EndMightThrow - true if __cxa_end_catch might throw
936 static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
937                                    llvm::Value *Exn,
938                                    bool EndMightThrow) {
939   llvm::CallInst *call =
940     CGF.EmitNounwindRuntimeCall(getBeginCatchFn(CGF.CGM), Exn);
941 
942   CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
943 
944   return call;
945 }
946 
947 /// A "special initializer" callback for initializing a catch
948 /// parameter during catch initialization.
949 static void InitCatchParam(CodeGenFunction &CGF,
950                            const VarDecl &CatchParam,
951                            llvm::Value *ParamAddr,
952                            SourceLocation Loc) {
953   // Load the exception from where the landing pad saved it.
954   llvm::Value *Exn = CGF.getExceptionFromSlot();
955 
956   CanQualType CatchType =
957     CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
958   llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
959 
960   // If we're catching by reference, we can just cast the object
961   // pointer to the appropriate pointer.
962   if (isa<ReferenceType>(CatchType)) {
963     QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
964     bool EndCatchMightThrow = CaughtType->isRecordType();
965 
966     // __cxa_begin_catch returns the adjusted object pointer.
967     llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
968 
969     // We have no way to tell the personality function that we're
970     // catching by reference, so if we're catching a pointer,
971     // __cxa_begin_catch will actually return that pointer by value.
972     if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
973       QualType PointeeType = PT->getPointeeType();
974 
975       // When catching by reference, generally we should just ignore
976       // this by-value pointer and use the exception object instead.
977       if (!PointeeType->isRecordType()) {
978 
979         // Exn points to the struct _Unwind_Exception header, which
980         // we have to skip past in order to reach the exception data.
981         unsigned HeaderSize =
982           CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
983         AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
984 
985       // However, if we're catching a pointer-to-record type that won't
986       // work, because the personality function might have adjusted
987       // the pointer.  There's actually no way for us to fully satisfy
988       // the language/ABI contract here:  we can't use Exn because it
989       // might have the wrong adjustment, but we can't use the by-value
990       // pointer because it's off by a level of abstraction.
991       //
992       // The current solution is to dump the adjusted pointer into an
993       // alloca, which breaks language semantics (because changing the
994       // pointer doesn't change the exception) but at least works.
995       // The better solution would be to filter out non-exact matches
996       // and rethrow them, but this is tricky because the rethrow
997       // really needs to be catchable by other sites at this landing
998       // pad.  The best solution is to fix the personality function.
999       } else {
1000         // Pull the pointer for the reference type off.
1001         llvm::Type *PtrTy =
1002           cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
1003 
1004         // Create the temporary and write the adjusted pointer into it.
1005         llvm::Value *ExnPtrTmp = CGF.CreateTempAlloca(PtrTy, "exn.byref.tmp");
1006         llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1007         CGF.Builder.CreateStore(Casted, ExnPtrTmp);
1008 
1009         // Bind the reference to the temporary.
1010         AdjustedExn = ExnPtrTmp;
1011       }
1012     }
1013 
1014     llvm::Value *ExnCast =
1015       CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
1016     CGF.Builder.CreateStore(ExnCast, ParamAddr);
1017     return;
1018   }
1019 
1020   // Scalars and complexes.
1021   TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType);
1022   if (TEK != TEK_Aggregate) {
1023     llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
1024 
1025     // If the catch type is a pointer type, __cxa_begin_catch returns
1026     // the pointer by value.
1027     if (CatchType->hasPointerRepresentation()) {
1028       llvm::Value *CastExn =
1029         CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
1030 
1031       switch (CatchType.getQualifiers().getObjCLifetime()) {
1032       case Qualifiers::OCL_Strong:
1033         CastExn = CGF.EmitARCRetainNonBlock(CastExn);
1034         // fallthrough
1035 
1036       case Qualifiers::OCL_None:
1037       case Qualifiers::OCL_ExplicitNone:
1038       case Qualifiers::OCL_Autoreleasing:
1039         CGF.Builder.CreateStore(CastExn, ParamAddr);
1040         return;
1041 
1042       case Qualifiers::OCL_Weak:
1043         CGF.EmitARCInitWeak(ParamAddr, CastExn);
1044         return;
1045       }
1046       llvm_unreachable("bad ownership qualifier!");
1047     }
1048 
1049     // Otherwise, it returns a pointer into the exception object.
1050 
1051     llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
1052     llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1053 
1054     LValue srcLV = CGF.MakeNaturalAlignAddrLValue(Cast, CatchType);
1055     LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType,
1056                                   CGF.getContext().getDeclAlign(&CatchParam));
1057     switch (TEK) {
1058     case TEK_Complex:
1059       CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV,
1060                              /*init*/ true);
1061       return;
1062     case TEK_Scalar: {
1063       llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc);
1064       CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true);
1065       return;
1066     }
1067     case TEK_Aggregate:
1068       llvm_unreachable("evaluation kind filtered out!");
1069     }
1070     llvm_unreachable("bad evaluation kind");
1071   }
1072 
1073   assert(isa<RecordType>(CatchType) && "unexpected catch type!");
1074 
1075   llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
1076 
1077   // Check for a copy expression.  If we don't have a copy expression,
1078   // that means a trivial copy is okay.
1079   const Expr *copyExpr = CatchParam.getInit();
1080   if (!copyExpr) {
1081     llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
1082     llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
1083     CGF.EmitAggregateCopy(ParamAddr, adjustedExn, CatchType);
1084     return;
1085   }
1086 
1087   // We have to call __cxa_get_exception_ptr to get the adjusted
1088   // pointer before copying.
1089   llvm::CallInst *rawAdjustedExn =
1090     CGF.EmitNounwindRuntimeCall(getGetExceptionPtrFn(CGF.CGM), Exn);
1091 
1092   // Cast that to the appropriate type.
1093   llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
1094 
1095   // The copy expression is defined in terms of an OpaqueValueExpr.
1096   // Find it and map it to the adjusted expression.
1097   CodeGenFunction::OpaqueValueMapping
1098     opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
1099            CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
1100 
1101   // Call the copy ctor in a terminate scope.
1102   CGF.EHStack.pushTerminate();
1103 
1104   // Perform the copy construction.
1105   CharUnits Alignment = CGF.getContext().getDeclAlign(&CatchParam);
1106   CGF.EmitAggExpr(copyExpr,
1107                   AggValueSlot::forAddr(ParamAddr, Alignment, Qualifiers(),
1108                                         AggValueSlot::IsNotDestructed,
1109                                         AggValueSlot::DoesNotNeedGCBarriers,
1110                                         AggValueSlot::IsNotAliased));
1111 
1112   // Leave the terminate scope.
1113   CGF.EHStack.popTerminate();
1114 
1115   // Undo the opaque value mapping.
1116   opaque.pop();
1117 
1118   // Finally we can call __cxa_begin_catch.
1119   CallBeginCatch(CGF, Exn, true);
1120 }
1121 
1122 /// Begins a catch statement by initializing the catch variable and
1123 /// calling __cxa_begin_catch.
1124 static void BeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *S) {
1125   // We have to be very careful with the ordering of cleanups here:
1126   //   C++ [except.throw]p4:
1127   //     The destruction [of the exception temporary] occurs
1128   //     immediately after the destruction of the object declared in
1129   //     the exception-declaration in the handler.
1130   //
1131   // So the precise ordering is:
1132   //   1.  Construct catch variable.
1133   //   2.  __cxa_begin_catch
1134   //   3.  Enter __cxa_end_catch cleanup
1135   //   4.  Enter dtor cleanup
1136   //
1137   // We do this by using a slightly abnormal initialization process.
1138   // Delegation sequence:
1139   //   - ExitCXXTryStmt opens a RunCleanupsScope
1140   //     - EmitAutoVarAlloca creates the variable and debug info
1141   //       - InitCatchParam initializes the variable from the exception
1142   //       - CallBeginCatch calls __cxa_begin_catch
1143   //       - CallBeginCatch enters the __cxa_end_catch cleanup
1144   //     - EmitAutoVarCleanups enters the variable destructor cleanup
1145   //   - EmitCXXTryStmt emits the code for the catch body
1146   //   - EmitCXXTryStmt close the RunCleanupsScope
1147 
1148   VarDecl *CatchParam = S->getExceptionDecl();
1149   if (!CatchParam) {
1150     llvm::Value *Exn = CGF.getExceptionFromSlot();
1151     CallBeginCatch(CGF, Exn, true);
1152     return;
1153   }
1154 
1155   // Emit the local.
1156   CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
1157   InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF), S->getLocStart());
1158   CGF.EmitAutoVarCleanups(var);
1159 }
1160 
1161 /// Emit the structure of the dispatch block for the given catch scope.
1162 /// It is an invariant that the dispatch block already exists.
1163 static void emitCatchDispatchBlock(CodeGenFunction &CGF,
1164                                    EHCatchScope &catchScope) {
1165   llvm::BasicBlock *dispatchBlock = catchScope.getCachedEHDispatchBlock();
1166   assert(dispatchBlock);
1167 
1168   // If there's only a single catch-all, getEHDispatchBlock returned
1169   // that catch-all as the dispatch block.
1170   if (catchScope.getNumHandlers() == 1 &&
1171       catchScope.getHandler(0).isCatchAll()) {
1172     assert(dispatchBlock == catchScope.getHandler(0).Block);
1173     return;
1174   }
1175 
1176   CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveIP();
1177   CGF.EmitBlockAfterUses(dispatchBlock);
1178 
1179   // Select the right handler.
1180   llvm::Value *llvm_eh_typeid_for =
1181     CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
1182 
1183   // Load the selector value.
1184   llvm::Value *selector = CGF.getSelectorFromSlot();
1185 
1186   // Test against each of the exception types we claim to catch.
1187   for (unsigned i = 0, e = catchScope.getNumHandlers(); ; ++i) {
1188     assert(i < e && "ran off end of handlers!");
1189     const EHCatchScope::Handler &handler = catchScope.getHandler(i);
1190 
1191     llvm::Value *typeValue = handler.Type;
1192     assert(typeValue && "fell into catch-all case!");
1193     typeValue = CGF.Builder.CreateBitCast(typeValue, CGF.Int8PtrTy);
1194 
1195     // Figure out the next block.
1196     bool nextIsEnd;
1197     llvm::BasicBlock *nextBlock;
1198 
1199     // If this is the last handler, we're at the end, and the next
1200     // block is the block for the enclosing EH scope.
1201     if (i + 1 == e) {
1202       nextBlock = CGF.getEHDispatchBlock(catchScope.getEnclosingEHScope());
1203       nextIsEnd = true;
1204 
1205     // If the next handler is a catch-all, we're at the end, and the
1206     // next block is that handler.
1207     } else if (catchScope.getHandler(i+1).isCatchAll()) {
1208       nextBlock = catchScope.getHandler(i+1).Block;
1209       nextIsEnd = true;
1210 
1211     // Otherwise, we're not at the end and we need a new block.
1212     } else {
1213       nextBlock = CGF.createBasicBlock("catch.fallthrough");
1214       nextIsEnd = false;
1215     }
1216 
1217     // Figure out the catch type's index in the LSDA's type table.
1218     llvm::CallInst *typeIndex =
1219       CGF.Builder.CreateCall(llvm_eh_typeid_for, typeValue);
1220     typeIndex->setDoesNotThrow();
1221 
1222     llvm::Value *matchesTypeIndex =
1223       CGF.Builder.CreateICmpEQ(selector, typeIndex, "matches");
1224     CGF.Builder.CreateCondBr(matchesTypeIndex, handler.Block, nextBlock);
1225 
1226     // If the next handler is a catch-all, we're completely done.
1227     if (nextIsEnd) {
1228       CGF.Builder.restoreIP(savedIP);
1229       return;
1230     }
1231     // Otherwise we need to emit and continue at that block.
1232     CGF.EmitBlock(nextBlock);
1233   }
1234 }
1235 
1236 void CodeGenFunction::popCatchScope() {
1237   EHCatchScope &catchScope = cast<EHCatchScope>(*EHStack.begin());
1238   if (catchScope.hasEHBranches())
1239     emitCatchDispatchBlock(*this, catchScope);
1240   EHStack.popCatch();
1241 }
1242 
1243 void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
1244   unsigned NumHandlers = S.getNumHandlers();
1245   EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1246   assert(CatchScope.getNumHandlers() == NumHandlers);
1247 
1248   // If the catch was not required, bail out now.
1249   if (!CatchScope.hasEHBranches()) {
1250     CatchScope.clearHandlerBlocks();
1251     EHStack.popCatch();
1252     return;
1253   }
1254 
1255   // Emit the structure of the EH dispatch for this catch.
1256   emitCatchDispatchBlock(*this, CatchScope);
1257 
1258   // Copy the handler blocks off before we pop the EH stack.  Emitting
1259   // the handlers might scribble on this memory.
1260   SmallVector<EHCatchScope::Handler, 8> Handlers(NumHandlers);
1261   memcpy(Handlers.data(), CatchScope.begin(),
1262          NumHandlers * sizeof(EHCatchScope::Handler));
1263 
1264   EHStack.popCatch();
1265 
1266   // The fall-through block.
1267   llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
1268 
1269   // We just emitted the body of the try; jump to the continue block.
1270   if (HaveInsertPoint())
1271     Builder.CreateBr(ContBB);
1272 
1273   // Determine if we need an implicit rethrow for all these catch handlers;
1274   // see the comment below.
1275   bool doImplicitRethrow = false;
1276   if (IsFnTryBlock)
1277     doImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
1278                         isa<CXXConstructorDecl>(CurCodeDecl);
1279 
1280   // Perversely, we emit the handlers backwards precisely because we
1281   // want them to appear in source order.  In all of these cases, the
1282   // catch block will have exactly one predecessor, which will be a
1283   // particular block in the catch dispatch.  However, in the case of
1284   // a catch-all, one of the dispatch blocks will branch to two
1285   // different handlers, and EmitBlockAfterUses will cause the second
1286   // handler to be moved before the first.
1287   for (unsigned I = NumHandlers; I != 0; --I) {
1288     llvm::BasicBlock *CatchBlock = Handlers[I-1].Block;
1289     EmitBlockAfterUses(CatchBlock);
1290 
1291     // Catch the exception if this isn't a catch-all.
1292     const CXXCatchStmt *C = S.getHandler(I-1);
1293 
1294     // Enter a cleanup scope, including the catch variable and the
1295     // end-catch.
1296     RunCleanupsScope CatchScope(*this);
1297 
1298     // Initialize the catch variable and set up the cleanups.
1299     BeginCatch(*this, C);
1300 
1301     // Emit the PGO counter increment.
1302     RegionCounter CatchCnt = getPGORegionCounter(C);
1303     CatchCnt.beginRegion(Builder);
1304 
1305     // Perform the body of the catch.
1306     EmitStmt(C->getHandlerBlock());
1307 
1308     // [except.handle]p11:
1309     //   The currently handled exception is rethrown if control
1310     //   reaches the end of a handler of the function-try-block of a
1311     //   constructor or destructor.
1312 
1313     // It is important that we only do this on fallthrough and not on
1314     // return.  Note that it's illegal to put a return in a
1315     // constructor function-try-block's catch handler (p14), so this
1316     // really only applies to destructors.
1317     if (doImplicitRethrow && HaveInsertPoint()) {
1318       EmitRuntimeCallOrInvoke(getReThrowFn(CGM));
1319       Builder.CreateUnreachable();
1320       Builder.ClearInsertionPoint();
1321     }
1322 
1323     // Fall out through the catch cleanups.
1324     CatchScope.ForceCleanup();
1325 
1326     // Branch out of the try.
1327     if (HaveInsertPoint())
1328       Builder.CreateBr(ContBB);
1329   }
1330 
1331   RegionCounter ContCnt = getPGORegionCounter(&S);
1332   EmitBlock(ContBB);
1333   ContCnt.beginRegion(Builder);
1334 }
1335 
1336 namespace {
1337   struct CallEndCatchForFinally : EHScopeStack::Cleanup {
1338     llvm::Value *ForEHVar;
1339     llvm::Value *EndCatchFn;
1340     CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn)
1341       : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
1342 
1343     void Emit(CodeGenFunction &CGF, Flags flags) override {
1344       llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
1345       llvm::BasicBlock *CleanupContBB =
1346         CGF.createBasicBlock("finally.cleanup.cont");
1347 
1348       llvm::Value *ShouldEndCatch =
1349         CGF.Builder.CreateLoad(ForEHVar, "finally.endcatch");
1350       CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1351       CGF.EmitBlock(EndCatchBB);
1352       CGF.EmitRuntimeCallOrInvoke(EndCatchFn); // catch-all, so might throw
1353       CGF.EmitBlock(CleanupContBB);
1354     }
1355   };
1356 
1357   struct PerformFinally : EHScopeStack::Cleanup {
1358     const Stmt *Body;
1359     llvm::Value *ForEHVar;
1360     llvm::Value *EndCatchFn;
1361     llvm::Value *RethrowFn;
1362     llvm::Value *SavedExnVar;
1363 
1364     PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
1365                    llvm::Value *EndCatchFn,
1366                    llvm::Value *RethrowFn, llvm::Value *SavedExnVar)
1367       : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1368         RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
1369 
1370     void Emit(CodeGenFunction &CGF, Flags flags) override {
1371       // Enter a cleanup to call the end-catch function if one was provided.
1372       if (EndCatchFn)
1373         CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
1374                                                         ForEHVar, EndCatchFn);
1375 
1376       // Save the current cleanup destination in case there are
1377       // cleanups in the finally block.
1378       llvm::Value *SavedCleanupDest =
1379         CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
1380                                "cleanup.dest.saved");
1381 
1382       // Emit the finally block.
1383       CGF.EmitStmt(Body);
1384 
1385       // If the end of the finally is reachable, check whether this was
1386       // for EH.  If so, rethrow.
1387       if (CGF.HaveInsertPoint()) {
1388         llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
1389         llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
1390 
1391         llvm::Value *ShouldRethrow =
1392           CGF.Builder.CreateLoad(ForEHVar, "finally.shouldthrow");
1393         CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1394 
1395         CGF.EmitBlock(RethrowBB);
1396         if (SavedExnVar) {
1397           CGF.EmitRuntimeCallOrInvoke(RethrowFn,
1398                                       CGF.Builder.CreateLoad(SavedExnVar));
1399         } else {
1400           CGF.EmitRuntimeCallOrInvoke(RethrowFn);
1401         }
1402         CGF.Builder.CreateUnreachable();
1403 
1404         CGF.EmitBlock(ContBB);
1405 
1406         // Restore the cleanup destination.
1407         CGF.Builder.CreateStore(SavedCleanupDest,
1408                                 CGF.getNormalCleanupDestSlot());
1409       }
1410 
1411       // Leave the end-catch cleanup.  As an optimization, pretend that
1412       // the fallthrough path was inaccessible; we've dynamically proven
1413       // that we're not in the EH case along that path.
1414       if (EndCatchFn) {
1415         CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1416         CGF.PopCleanupBlock();
1417         CGF.Builder.restoreIP(SavedIP);
1418       }
1419 
1420       // Now make sure we actually have an insertion point or the
1421       // cleanup gods will hate us.
1422       CGF.EnsureInsertPoint();
1423     }
1424   };
1425 }
1426 
1427 /// Enters a finally block for an implementation using zero-cost
1428 /// exceptions.  This is mostly general, but hard-codes some
1429 /// language/ABI-specific behavior in the catch-all sections.
1430 void CodeGenFunction::FinallyInfo::enter(CodeGenFunction &CGF,
1431                                          const Stmt *body,
1432                                          llvm::Constant *beginCatchFn,
1433                                          llvm::Constant *endCatchFn,
1434                                          llvm::Constant *rethrowFn) {
1435   assert((beginCatchFn != 0) == (endCatchFn != 0) &&
1436          "begin/end catch functions not paired");
1437   assert(rethrowFn && "rethrow function is required");
1438 
1439   BeginCatchFn = beginCatchFn;
1440 
1441   // The rethrow function has one of the following two types:
1442   //   void (*)()
1443   //   void (*)(void*)
1444   // In the latter case we need to pass it the exception object.
1445   // But we can't use the exception slot because the @finally might
1446   // have a landing pad (which would overwrite the exception slot).
1447   llvm::FunctionType *rethrowFnTy =
1448     cast<llvm::FunctionType>(
1449       cast<llvm::PointerType>(rethrowFn->getType())->getElementType());
1450   SavedExnVar = 0;
1451   if (rethrowFnTy->getNumParams())
1452     SavedExnVar = CGF.CreateTempAlloca(CGF.Int8PtrTy, "finally.exn");
1453 
1454   // A finally block is a statement which must be executed on any edge
1455   // out of a given scope.  Unlike a cleanup, the finally block may
1456   // contain arbitrary control flow leading out of itself.  In
1457   // addition, finally blocks should always be executed, even if there
1458   // are no catch handlers higher on the stack.  Therefore, we
1459   // surround the protected scope with a combination of a normal
1460   // cleanup (to catch attempts to break out of the block via normal
1461   // control flow) and an EH catch-all (semantically "outside" any try
1462   // statement to which the finally block might have been attached).
1463   // The finally block itself is generated in the context of a cleanup
1464   // which conditionally leaves the catch-all.
1465 
1466   // Jump destination for performing the finally block on an exception
1467   // edge.  We'll never actually reach this block, so unreachable is
1468   // fine.
1469   RethrowDest = CGF.getJumpDestInCurrentScope(CGF.getUnreachableBlock());
1470 
1471   // Whether the finally block is being executed for EH purposes.
1472   ForEHVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "finally.for-eh");
1473   CGF.Builder.CreateStore(CGF.Builder.getFalse(), ForEHVar);
1474 
1475   // Enter a normal cleanup which will perform the @finally block.
1476   CGF.EHStack.pushCleanup<PerformFinally>(NormalCleanup, body,
1477                                           ForEHVar, endCatchFn,
1478                                           rethrowFn, SavedExnVar);
1479 
1480   // Enter a catch-all scope.
1481   llvm::BasicBlock *catchBB = CGF.createBasicBlock("finally.catchall");
1482   EHCatchScope *catchScope = CGF.EHStack.pushCatch(1);
1483   catchScope->setCatchAllHandler(0, catchBB);
1484 }
1485 
1486 void CodeGenFunction::FinallyInfo::exit(CodeGenFunction &CGF) {
1487   // Leave the finally catch-all.
1488   EHCatchScope &catchScope = cast<EHCatchScope>(*CGF.EHStack.begin());
1489   llvm::BasicBlock *catchBB = catchScope.getHandler(0).Block;
1490 
1491   CGF.popCatchScope();
1492 
1493   // If there are any references to the catch-all block, emit it.
1494   if (catchBB->use_empty()) {
1495     delete catchBB;
1496   } else {
1497     CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveAndClearIP();
1498     CGF.EmitBlock(catchBB);
1499 
1500     llvm::Value *exn = 0;
1501 
1502     // If there's a begin-catch function, call it.
1503     if (BeginCatchFn) {
1504       exn = CGF.getExceptionFromSlot();
1505       CGF.EmitNounwindRuntimeCall(BeginCatchFn, exn);
1506     }
1507 
1508     // If we need to remember the exception pointer to rethrow later, do so.
1509     if (SavedExnVar) {
1510       if (!exn) exn = CGF.getExceptionFromSlot();
1511       CGF.Builder.CreateStore(exn, SavedExnVar);
1512     }
1513 
1514     // Tell the cleanups in the finally block that we're do this for EH.
1515     CGF.Builder.CreateStore(CGF.Builder.getTrue(), ForEHVar);
1516 
1517     // Thread a jump through the finally cleanup.
1518     CGF.EmitBranchThroughCleanup(RethrowDest);
1519 
1520     CGF.Builder.restoreIP(savedIP);
1521   }
1522 
1523   // Finally, leave the @finally cleanup.
1524   CGF.PopCleanupBlock();
1525 }
1526 
1527 /// In a terminate landing pad, should we use __clang__call_terminate
1528 /// or just a naked call to std::terminate?
1529 ///
1530 /// __clang_call_terminate calls __cxa_begin_catch, which then allows
1531 /// std::terminate to usefully report something about the
1532 /// violating exception.
1533 static bool useClangCallTerminate(CodeGenModule &CGM) {
1534   // Only do this for Itanium-family ABIs in C++ mode.
1535   return (CGM.getLangOpts().CPlusPlus &&
1536           CGM.getTarget().getCXXABI().isItaniumFamily());
1537 }
1538 
1539 /// Get or define the following function:
1540 ///   void @__clang_call_terminate(i8* %exn) nounwind noreturn
1541 /// This code is used only in C++.
1542 static llvm::Constant *getClangCallTerminateFn(CodeGenModule &CGM) {
1543   llvm::FunctionType *fnTy =
1544     llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
1545   llvm::Constant *fnRef =
1546     CGM.CreateRuntimeFunction(fnTy, "__clang_call_terminate");
1547 
1548   llvm::Function *fn = dyn_cast<llvm::Function>(fnRef);
1549   if (fn && fn->empty()) {
1550     fn->setDoesNotThrow();
1551     fn->setDoesNotReturn();
1552 
1553     // What we really want is to massively penalize inlining without
1554     // forbidding it completely.  The difference between that and
1555     // 'noinline' is negligible.
1556     fn->addFnAttr(llvm::Attribute::NoInline);
1557 
1558     // Allow this function to be shared across translation units, but
1559     // we don't want it to turn into an exported symbol.
1560     fn->setLinkage(llvm::Function::LinkOnceODRLinkage);
1561     fn->setVisibility(llvm::Function::HiddenVisibility);
1562 
1563     // Set up the function.
1564     llvm::BasicBlock *entry =
1565       llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn);
1566     CGBuilderTy builder(entry);
1567 
1568     // Pull the exception pointer out of the parameter list.
1569     llvm::Value *exn = &*fn->arg_begin();
1570 
1571     // Call __cxa_begin_catch(exn).
1572     llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn);
1573     catchCall->setDoesNotThrow();
1574     catchCall->setCallingConv(CGM.getRuntimeCC());
1575 
1576     // Call std::terminate().
1577     llvm::CallInst *termCall = builder.CreateCall(getTerminateFn(CGM));
1578     termCall->setDoesNotThrow();
1579     termCall->setDoesNotReturn();
1580     termCall->setCallingConv(CGM.getRuntimeCC());
1581 
1582     // std::terminate cannot return.
1583     builder.CreateUnreachable();
1584   }
1585 
1586   return fnRef;
1587 }
1588 
1589 llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
1590   if (TerminateLandingPad)
1591     return TerminateLandingPad;
1592 
1593   CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1594 
1595   // This will get inserted at the end of the function.
1596   TerminateLandingPad = createBasicBlock("terminate.lpad");
1597   Builder.SetInsertPoint(TerminateLandingPad);
1598 
1599   // Tell the backend that this is a landing pad.
1600   const EHPersonality &Personality = EHPersonality::get(CGM.getLangOpts());
1601   llvm::LandingPadInst *LPadInst =
1602     Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, NULL),
1603                              getOpaquePersonalityFn(CGM, Personality), 0);
1604   LPadInst->addClause(getCatchAllValue(*this));
1605 
1606   llvm::CallInst *terminateCall;
1607   if (useClangCallTerminate(CGM)) {
1608     // Extract out the exception pointer.
1609     llvm::Value *exn = Builder.CreateExtractValue(LPadInst, 0);
1610     terminateCall = EmitNounwindRuntimeCall(getClangCallTerminateFn(CGM), exn);
1611   } else {
1612     terminateCall = EmitNounwindRuntimeCall(getTerminateFn(CGM));
1613   }
1614   terminateCall->setDoesNotReturn();
1615   Builder.CreateUnreachable();
1616 
1617   // Restore the saved insertion state.
1618   Builder.restoreIP(SavedIP);
1619 
1620   return TerminateLandingPad;
1621 }
1622 
1623 llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
1624   if (TerminateHandler)
1625     return TerminateHandler;
1626 
1627   CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1628 
1629   // Set up the terminate handler.  This block is inserted at the very
1630   // end of the function by FinishFunction.
1631   TerminateHandler = createBasicBlock("terminate.handler");
1632   Builder.SetInsertPoint(TerminateHandler);
1633   llvm::CallInst *terminateCall;
1634   if (useClangCallTerminate(CGM)) {
1635     // Load the exception pointer.
1636     llvm::Value *exn = getExceptionFromSlot();
1637     terminateCall = EmitNounwindRuntimeCall(getClangCallTerminateFn(CGM), exn);
1638   } else {
1639     terminateCall = EmitNounwindRuntimeCall(getTerminateFn(CGM));
1640   }
1641   terminateCall->setDoesNotReturn();
1642   Builder.CreateUnreachable();
1643 
1644   // Restore the saved insertion state.
1645   Builder.restoreIP(SavedIP);
1646 
1647   return TerminateHandler;
1648 }
1649 
1650 llvm::BasicBlock *CodeGenFunction::getEHResumeBlock(bool isCleanup) {
1651   if (EHResumeBlock) return EHResumeBlock;
1652 
1653   CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1654 
1655   // We emit a jump to a notional label at the outermost unwind state.
1656   EHResumeBlock = createBasicBlock("eh.resume");
1657   Builder.SetInsertPoint(EHResumeBlock);
1658 
1659   const EHPersonality &Personality = EHPersonality::get(CGM.getLangOpts());
1660 
1661   // This can always be a call because we necessarily didn't find
1662   // anything on the EH stack which needs our help.
1663   const char *RethrowName = Personality.CatchallRethrowFn;
1664   if (RethrowName != 0 && !isCleanup) {
1665     EmitRuntimeCall(getCatchallRethrowFn(CGM, RethrowName),
1666                       getExceptionFromSlot())
1667       ->setDoesNotReturn();
1668   } else {
1669     switch (CleanupHackLevel) {
1670     case CHL_MandatoryCatchall:
1671       // In mandatory-catchall mode, we need to use
1672       // _Unwind_Resume_or_Rethrow, or whatever the personality's
1673       // equivalent is.
1674       EmitRuntimeCall(getUnwindResumeOrRethrowFn(),
1675                         getExceptionFromSlot())
1676         ->setDoesNotReturn();
1677       break;
1678     case CHL_MandatoryCleanup: {
1679       // In mandatory-cleanup mode, we should use 'resume'.
1680 
1681       // Recreate the landingpad's return value for the 'resume' instruction.
1682       llvm::Value *Exn = getExceptionFromSlot();
1683       llvm::Value *Sel = getSelectorFromSlot();
1684 
1685       llvm::Type *LPadType = llvm::StructType::get(Exn->getType(),
1686                                                    Sel->getType(), NULL);
1687       llvm::Value *LPadVal = llvm::UndefValue::get(LPadType);
1688       LPadVal = Builder.CreateInsertValue(LPadVal, Exn, 0, "lpad.val");
1689       LPadVal = Builder.CreateInsertValue(LPadVal, Sel, 1, "lpad.val");
1690 
1691       Builder.CreateResume(LPadVal);
1692       Builder.restoreIP(SavedIP);
1693       return EHResumeBlock;
1694     }
1695     case CHL_Ideal:
1696       // In an idealized mode where we don't have to worry about the
1697       // optimizer combining landing pads, we should just use
1698       // _Unwind_Resume (or the personality's equivalent).
1699       EmitRuntimeCall(getUnwindResumeFn(), getExceptionFromSlot())
1700         ->setDoesNotReturn();
1701       break;
1702     }
1703   }
1704 
1705   Builder.CreateUnreachable();
1706 
1707   Builder.restoreIP(SavedIP);
1708 
1709   return EHResumeBlock;
1710 }
1711 
1712 void CodeGenFunction::EmitSEHTryStmt(const SEHTryStmt &S) {
1713   CGM.ErrorUnsupported(&S, "SEH __try");
1714 }
1715