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/Intrinsics.h"
21 #include "llvm/Support/CallSite.h"
22 
23 using namespace clang;
24 using namespace CodeGen;
25 
26 static llvm::Constant *getAllocateExceptionFn(CodeGenFunction &CGF) {
27   // void *__cxa_allocate_exception(size_t thrown_size);
28 
29   llvm::FunctionType *FTy =
30     llvm::FunctionType::get(CGF.Int8PtrTy, CGF.SizeTy, /*IsVarArgs=*/false);
31 
32   return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
33 }
34 
35 static llvm::Constant *getFreeExceptionFn(CodeGenFunction &CGF) {
36   // void __cxa_free_exception(void *thrown_exception);
37 
38   llvm::FunctionType *FTy =
39     llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, /*IsVarArgs=*/false);
40 
41   return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_free_exception");
42 }
43 
44 static llvm::Constant *getThrowFn(CodeGenFunction &CGF) {
45   // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
46   //                  void (*dest) (void *));
47 
48   llvm::Type *Args[3] = { CGF.Int8PtrTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
49   llvm::FunctionType *FTy =
50     llvm::FunctionType::get(CGF.VoidTy, Args, /*IsVarArgs=*/false);
51 
52   return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
53 }
54 
55 static llvm::Constant *getReThrowFn(CodeGenFunction &CGF) {
56   // void __cxa_rethrow();
57 
58   llvm::FunctionType *FTy =
59     llvm::FunctionType::get(CGF.VoidTy, /*IsVarArgs=*/false);
60 
61   return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
62 }
63 
64 static llvm::Constant *getGetExceptionPtrFn(CodeGenFunction &CGF) {
65   // void *__cxa_get_exception_ptr(void*);
66 
67   llvm::FunctionType *FTy =
68     llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrTy, /*IsVarArgs=*/false);
69 
70   return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
71 }
72 
73 static llvm::Constant *getBeginCatchFn(CodeGenFunction &CGF) {
74   // void *__cxa_begin_catch(void*);
75 
76   llvm::FunctionType *FTy =
77     llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrTy, /*IsVarArgs=*/false);
78 
79   return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
80 }
81 
82 static llvm::Constant *getEndCatchFn(CodeGenFunction &CGF) {
83   // void __cxa_end_catch();
84 
85   llvm::FunctionType *FTy =
86     llvm::FunctionType::get(CGF.VoidTy, /*IsVarArgs=*/false);
87 
88   return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
89 }
90 
91 static llvm::Constant *getUnexpectedFn(CodeGenFunction &CGF) {
92   // void __cxa_call_unexepcted(void *thrown_exception);
93 
94   llvm::FunctionType *FTy =
95     llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, /*IsVarArgs=*/false);
96 
97   return CGF.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(CodeGenFunction &CGF) {
119   // void __terminate();
120 
121   llvm::FunctionType *FTy =
122     llvm::FunctionType::get(CGF.VoidTy, /*IsVarArgs=*/false);
123 
124   StringRef name;
125 
126   // In C++, use std::terminate().
127   if (CGF.getLangOpts().CPlusPlus)
128     name = "_ZSt9terminatev"; // FIXME: mangling!
129   else if (CGF.getLangOpts().ObjC1 &&
130            CGF.getLangOpts().ObjCRuntime.hasTerminate())
131     name = "objc_terminate";
132   else
133     name = "abort";
134   return CGF.CGM.CreateRuntimeFunction(FTy, name);
135 }
136 
137 static llvm::Constant *getCatchallRethrowFn(CodeGenFunction &CGF,
138                                             StringRef Name) {
139   llvm::FunctionType *FTy =
140     llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, /*IsVarArgs=*/false);
141 
142   return CGF.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::Constant::use_iterator
267          I = Fn->use_begin(), E = Fn->use_end(); I != E; ++I) {
268     llvm::User *User = *I;
269 
270     // Conditionally white-list bitcasts.
271     if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(User)) {
272       if (CE->getOpcode() != llvm::Instruction::BitCast) return false;
273       if (!PersonalityHasOnlyCXXUses(CE))
274         return false;
275       continue;
276     }
277 
278     // Otherwise, it has to be a landingpad instruction.
279     llvm::LandingPadInst *LPI = dyn_cast<llvm::LandingPadInst>(User);
280     if (!LPI) return false;
281 
282     for (unsigned I = 0, E = LPI->getNumClauses(); I != E; ++I) {
283       // Look for something that would've been returned by the ObjC
284       // runtime's GetEHType() method.
285       llvm::Value *Val = LPI->getClause(I)->stripPointerCasts();
286       if (LPI->isCatch(I)) {
287         // Check if the catch value has the ObjC prefix.
288         if (llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Val))
289           // ObjC EH selector entries are always global variables with
290           // names starting like this.
291           if (GV->getName().startswith("OBJC_EHTYPE"))
292             return false;
293       } else {
294         // Check if any of the filter values have the ObjC prefix.
295         llvm::Constant *CVal = cast<llvm::Constant>(Val);
296         for (llvm::User::op_iterator
297                II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II) {
298           if (llvm::GlobalVariable *GV =
299               cast<llvm::GlobalVariable>((*II)->stripPointerCasts()))
300             // ObjC EH selector entries are always global variables with
301             // names starting like this.
302             if (GV->getName().startswith("OBJC_EHTYPE"))
303               return false;
304         }
305       }
306     }
307   }
308 
309   return true;
310 }
311 
312 /// Try to use the C++ personality function in ObjC++.  Not doing this
313 /// can cause some incompatibilities with gcc, which is more
314 /// aggressive about only using the ObjC++ personality in a function
315 /// when it really needs it.
316 void CodeGenModule::SimplifyPersonality() {
317   // If we're not in ObjC++ -fexceptions, there's nothing to do.
318   if (!LangOpts.CPlusPlus || !LangOpts.ObjC1 || !LangOpts.Exceptions)
319     return;
320 
321   // Both the problem this endeavors to fix and the way the logic
322   // above works is specific to the NeXT runtime.
323   if (!LangOpts.ObjCRuntime.isNeXTFamily())
324     return;
325 
326   const EHPersonality &ObjCXX = EHPersonality::get(LangOpts);
327   const EHPersonality &CXX = getCXXPersonality(LangOpts);
328   if (&ObjCXX == &CXX)
329     return;
330 
331   assert(std::strcmp(ObjCXX.PersonalityFn, CXX.PersonalityFn) != 0 &&
332          "Different EHPersonalities using the same personality function.");
333 
334   llvm::Function *Fn = getModule().getFunction(ObjCXX.PersonalityFn);
335 
336   // Nothing to do if it's unused.
337   if (!Fn || Fn->use_empty()) return;
338 
339   // Can't do the optimization if it has non-C++ uses.
340   if (!PersonalityHasOnlyCXXUses(Fn)) return;
341 
342   // Create the C++ personality function and kill off the old
343   // function.
344   llvm::Constant *CXXFn = getPersonalityFn(*this, CXX);
345 
346   // This can happen if the user is screwing with us.
347   if (Fn->getType() != CXXFn->getType()) return;
348 
349   Fn->replaceAllUsesWith(CXXFn);
350   Fn->eraseFromParent();
351 }
352 
353 /// Returns the value to inject into a selector to indicate the
354 /// presence of a catch-all.
355 static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
356   // Possibly we should use @llvm.eh.catch.all.value here.
357   return llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
358 }
359 
360 namespace {
361   /// A cleanup to free the exception object if its initialization
362   /// throws.
363   struct FreeException : EHScopeStack::Cleanup {
364     llvm::Value *exn;
365     FreeException(llvm::Value *exn) : exn(exn) {}
366     void Emit(CodeGenFunction &CGF, Flags flags) {
367       CGF.Builder.CreateCall(getFreeExceptionFn(CGF), exn)
368         ->setDoesNotThrow();
369     }
370   };
371 }
372 
373 // Emits an exception expression into the given location.  This
374 // differs from EmitAnyExprToMem only in that, if a final copy-ctor
375 // call is required, an exception within that copy ctor causes
376 // std::terminate to be invoked.
377 static void EmitAnyExprToExn(CodeGenFunction &CGF, const Expr *e,
378                              llvm::Value *addr) {
379   // Make sure the exception object is cleaned up if there's an
380   // exception during initialization.
381   CGF.pushFullExprCleanup<FreeException>(EHCleanup, addr);
382   EHScopeStack::stable_iterator cleanup = CGF.EHStack.stable_begin();
383 
384   // __cxa_allocate_exception returns a void*;  we need to cast this
385   // to the appropriate type for the object.
386   llvm::Type *ty = CGF.ConvertTypeForMem(e->getType())->getPointerTo();
387   llvm::Value *typedAddr = CGF.Builder.CreateBitCast(addr, ty);
388 
389   // FIXME: this isn't quite right!  If there's a final unelided call
390   // to a copy constructor, then according to [except.terminate]p1 we
391   // must call std::terminate() if that constructor throws, because
392   // technically that copy occurs after the exception expression is
393   // evaluated but before the exception is caught.  But the best way
394   // to handle that is to teach EmitAggExpr to do the final copy
395   // differently if it can't be elided.
396   CGF.EmitAnyExprToMem(e, typedAddr, e->getType().getQualifiers(),
397                        /*IsInit*/ true);
398 
399   // Deactivate the cleanup block.
400   CGF.DeactivateCleanupBlock(cleanup, cast<llvm::Instruction>(typedAddr));
401 }
402 
403 llvm::Value *CodeGenFunction::getExceptionSlot() {
404   if (!ExceptionSlot)
405     ExceptionSlot = CreateTempAlloca(Int8PtrTy, "exn.slot");
406   return ExceptionSlot;
407 }
408 
409 llvm::Value *CodeGenFunction::getEHSelectorSlot() {
410   if (!EHSelectorSlot)
411     EHSelectorSlot = CreateTempAlloca(Int32Ty, "ehselector.slot");
412   return EHSelectorSlot;
413 }
414 
415 llvm::Value *CodeGenFunction::getExceptionFromSlot() {
416   return Builder.CreateLoad(getExceptionSlot(), "exn");
417 }
418 
419 llvm::Value *CodeGenFunction::getSelectorFromSlot() {
420   return Builder.CreateLoad(getEHSelectorSlot(), "sel");
421 }
422 
423 void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E) {
424   if (!E->getSubExpr()) {
425     if (getInvokeDest()) {
426       Builder.CreateInvoke(getReThrowFn(*this),
427                            getUnreachableBlock(),
428                            getInvokeDest())
429         ->setDoesNotReturn();
430     } else {
431       Builder.CreateCall(getReThrowFn(*this))->setDoesNotReturn();
432       Builder.CreateUnreachable();
433     }
434 
435     // throw is an expression, and the expression emitters expect us
436     // to leave ourselves at a valid insertion point.
437     EmitBlock(createBasicBlock("throw.cont"));
438 
439     return;
440   }
441 
442   QualType ThrowType = E->getSubExpr()->getType();
443 
444   if (ThrowType->isObjCObjectPointerType()) {
445     const Stmt *ThrowStmt = E->getSubExpr();
446     const ObjCAtThrowStmt S(E->getExprLoc(),
447                             const_cast<Stmt *>(ThrowStmt));
448     CGM.getObjCRuntime().EmitThrowStmt(*this, S, false);
449     // This will clear insertion point which was not cleared in
450     // call to EmitThrowStmt.
451     EmitBlock(createBasicBlock("throw.cont"));
452     return;
453   }
454 
455   // Now allocate the exception object.
456   llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
457   uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
458 
459   llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(*this);
460   llvm::CallInst *ExceptionPtr =
461     Builder.CreateCall(AllocExceptionFn,
462                        llvm::ConstantInt::get(SizeTy, TypeSize),
463                        "exception");
464   ExceptionPtr->setDoesNotThrow();
465 
466   EmitAnyExprToExn(*this, E->getSubExpr(), ExceptionPtr);
467 
468   // Now throw the exception.
469   llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
470                                                          /*ForEH=*/true);
471 
472   // The address of the destructor.  If the exception type has a
473   // trivial destructor (or isn't a record), we just pass null.
474   llvm::Constant *Dtor = 0;
475   if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
476     CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
477     if (!Record->hasTrivialDestructor()) {
478       CXXDestructorDecl *DtorD = Record->getDestructor();
479       Dtor = CGM.GetAddrOfCXXDestructor(DtorD, Dtor_Complete);
480       Dtor = llvm::ConstantExpr::getBitCast(Dtor, Int8PtrTy);
481     }
482   }
483   if (!Dtor) Dtor = llvm::Constant::getNullValue(Int8PtrTy);
484 
485   if (getInvokeDest()) {
486     llvm::InvokeInst *ThrowCall =
487       Builder.CreateInvoke3(getThrowFn(*this),
488                             getUnreachableBlock(), getInvokeDest(),
489                             ExceptionPtr, TypeInfo, Dtor);
490     ThrowCall->setDoesNotReturn();
491   } else {
492     llvm::CallInst *ThrowCall =
493       Builder.CreateCall3(getThrowFn(*this), ExceptionPtr, TypeInfo, Dtor);
494     ThrowCall->setDoesNotReturn();
495     Builder.CreateUnreachable();
496   }
497 
498   // throw is an expression, and the expression emitters expect us
499   // to leave ourselves at a valid insertion point.
500   EmitBlock(createBasicBlock("throw.cont"));
501 }
502 
503 void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
504   if (!CGM.getLangOpts().CXXExceptions)
505     return;
506 
507   const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
508   if (FD == 0)
509     return;
510   const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
511   if (Proto == 0)
512     return;
513 
514   ExceptionSpecificationType EST = Proto->getExceptionSpecType();
515   if (isNoexceptExceptionSpec(EST)) {
516     if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
517       // noexcept functions are simple terminate scopes.
518       EHStack.pushTerminate();
519     }
520   } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
521     unsigned NumExceptions = Proto->getNumExceptions();
522     EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
523 
524     for (unsigned I = 0; I != NumExceptions; ++I) {
525       QualType Ty = Proto->getExceptionType(I);
526       QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
527       llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType,
528                                                         /*ForEH=*/true);
529       Filter->setFilter(I, EHType);
530     }
531   }
532 }
533 
534 /// Emit the dispatch block for a filter scope if necessary.
535 static void emitFilterDispatchBlock(CodeGenFunction &CGF,
536                                     EHFilterScope &filterScope) {
537   llvm::BasicBlock *dispatchBlock = filterScope.getCachedEHDispatchBlock();
538   if (!dispatchBlock) return;
539   if (dispatchBlock->use_empty()) {
540     delete dispatchBlock;
541     return;
542   }
543 
544   CGF.EmitBlockAfterUses(dispatchBlock);
545 
546   // If this isn't a catch-all filter, we need to check whether we got
547   // here because the filter triggered.
548   if (filterScope.getNumFilters()) {
549     // Load the selector value.
550     llvm::Value *selector = CGF.getSelectorFromSlot();
551     llvm::BasicBlock *unexpectedBB = CGF.createBasicBlock("ehspec.unexpected");
552 
553     llvm::Value *zero = CGF.Builder.getInt32(0);
554     llvm::Value *failsFilter =
555       CGF.Builder.CreateICmpSLT(selector, zero, "ehspec.fails");
556     CGF.Builder.CreateCondBr(failsFilter, unexpectedBB, CGF.getEHResumeBlock(false));
557 
558     CGF.EmitBlock(unexpectedBB);
559   }
560 
561   // Call __cxa_call_unexpected.  This doesn't need to be an invoke
562   // because __cxa_call_unexpected magically filters exceptions
563   // according to the last landing pad the exception was thrown
564   // into.  Seriously.
565   llvm::Value *exn = CGF.getExceptionFromSlot();
566   CGF.Builder.CreateCall(getUnexpectedFn(CGF), exn)
567     ->setDoesNotReturn();
568   CGF.Builder.CreateUnreachable();
569 }
570 
571 void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
572   if (!CGM.getLangOpts().CXXExceptions)
573     return;
574 
575   const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
576   if (FD == 0)
577     return;
578   const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
579   if (Proto == 0)
580     return;
581 
582   ExceptionSpecificationType EST = Proto->getExceptionSpecType();
583   if (isNoexceptExceptionSpec(EST)) {
584     if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
585       EHStack.popTerminate();
586     }
587   } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
588     EHFilterScope &filterScope = cast<EHFilterScope>(*EHStack.begin());
589     emitFilterDispatchBlock(*this, filterScope);
590     EHStack.popFilter();
591   }
592 }
593 
594 void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
595   EnterCXXTryStmt(S);
596   EmitStmt(S.getTryBlock());
597   ExitCXXTryStmt(S);
598 }
599 
600 void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
601   unsigned NumHandlers = S.getNumHandlers();
602   EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
603 
604   for (unsigned I = 0; I != NumHandlers; ++I) {
605     const CXXCatchStmt *C = S.getHandler(I);
606 
607     llvm::BasicBlock *Handler = createBasicBlock("catch");
608     if (C->getExceptionDecl()) {
609       // FIXME: Dropping the reference type on the type into makes it
610       // impossible to correctly implement catch-by-reference
611       // semantics for pointers.  Unfortunately, this is what all
612       // existing compilers do, and it's not clear that the standard
613       // personality routine is capable of doing this right.  See C++ DR 388:
614       //   http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
615       QualType CaughtType = C->getCaughtType();
616       CaughtType = CaughtType.getNonReferenceType().getUnqualifiedType();
617 
618       llvm::Value *TypeInfo = 0;
619       if (CaughtType->isObjCObjectPointerType())
620         TypeInfo = CGM.getObjCRuntime().GetEHType(CaughtType);
621       else
622         TypeInfo = CGM.GetAddrOfRTTIDescriptor(CaughtType, /*ForEH=*/true);
623       CatchScope->setHandler(I, TypeInfo, Handler);
624     } else {
625       // No exception decl indicates '...', a catch-all.
626       CatchScope->setCatchAllHandler(I, Handler);
627     }
628   }
629 }
630 
631 llvm::BasicBlock *
632 CodeGenFunction::getEHDispatchBlock(EHScopeStack::stable_iterator si) {
633   // The dispatch block for the end of the scope chain is a block that
634   // just resumes unwinding.
635   if (si == EHStack.stable_end())
636     return getEHResumeBlock(true);
637 
638   // Otherwise, we should look at the actual scope.
639   EHScope &scope = *EHStack.find(si);
640 
641   llvm::BasicBlock *dispatchBlock = scope.getCachedEHDispatchBlock();
642   if (!dispatchBlock) {
643     switch (scope.getKind()) {
644     case EHScope::Catch: {
645       // Apply a special case to a single catch-all.
646       EHCatchScope &catchScope = cast<EHCatchScope>(scope);
647       if (catchScope.getNumHandlers() == 1 &&
648           catchScope.getHandler(0).isCatchAll()) {
649         dispatchBlock = catchScope.getHandler(0).Block;
650 
651       // Otherwise, make a dispatch block.
652       } else {
653         dispatchBlock = createBasicBlock("catch.dispatch");
654       }
655       break;
656     }
657 
658     case EHScope::Cleanup:
659       dispatchBlock = createBasicBlock("ehcleanup");
660       break;
661 
662     case EHScope::Filter:
663       dispatchBlock = createBasicBlock("filter.dispatch");
664       break;
665 
666     case EHScope::Terminate:
667       dispatchBlock = getTerminateHandler();
668       break;
669     }
670     scope.setCachedEHDispatchBlock(dispatchBlock);
671   }
672   return dispatchBlock;
673 }
674 
675 /// Check whether this is a non-EH scope, i.e. a scope which doesn't
676 /// affect exception handling.  Currently, the only non-EH scopes are
677 /// normal-only cleanup scopes.
678 static bool isNonEHScope(const EHScope &S) {
679   switch (S.getKind()) {
680   case EHScope::Cleanup:
681     return !cast<EHCleanupScope>(S).isEHCleanup();
682   case EHScope::Filter:
683   case EHScope::Catch:
684   case EHScope::Terminate:
685     return false;
686   }
687 
688   llvm_unreachable("Invalid EHScope Kind!");
689 }
690 
691 llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
692   assert(EHStack.requiresLandingPad());
693   assert(!EHStack.empty());
694 
695   if (!CGM.getLangOpts().Exceptions)
696     return 0;
697 
698   // Check the innermost scope for a cached landing pad.  If this is
699   // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
700   llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
701   if (LP) return LP;
702 
703   // Build the landing pad for this scope.
704   LP = EmitLandingPad();
705   assert(LP);
706 
707   // Cache the landing pad on the innermost scope.  If this is a
708   // non-EH scope, cache the landing pad on the enclosing scope, too.
709   for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
710     ir->setCachedLandingPad(LP);
711     if (!isNonEHScope(*ir)) break;
712   }
713 
714   return LP;
715 }
716 
717 // This code contains a hack to work around a design flaw in
718 // LLVM's EH IR which breaks semantics after inlining.  This same
719 // hack is implemented in llvm-gcc.
720 //
721 // The LLVM EH abstraction is basically a thin veneer over the
722 // traditional GCC zero-cost design: for each range of instructions
723 // in the function, there is (at most) one "landing pad" with an
724 // associated chain of EH actions.  A language-specific personality
725 // function interprets this chain of actions and (1) decides whether
726 // or not to resume execution at the landing pad and (2) if so,
727 // provides an integer indicating why it's stopping.  In LLVM IR,
728 // the association of a landing pad with a range of instructions is
729 // achieved via an invoke instruction, the chain of actions becomes
730 // the arguments to the @llvm.eh.selector call, and the selector
731 // call returns the integer indicator.  Other than the required
732 // presence of two intrinsic function calls in the landing pad,
733 // the IR exactly describes the layout of the output code.
734 //
735 // A principal advantage of this design is that it is completely
736 // language-agnostic; in theory, the LLVM optimizers can treat
737 // landing pads neutrally, and targets need only know how to lower
738 // the intrinsics to have a functioning exceptions system (assuming
739 // that platform exceptions follow something approximately like the
740 // GCC design).  Unfortunately, landing pads cannot be combined in a
741 // language-agnostic way: given selectors A and B, there is no way
742 // to make a single landing pad which faithfully represents the
743 // semantics of propagating an exception first through A, then
744 // through B, without knowing how the personality will interpret the
745 // (lowered form of the) selectors.  This means that inlining has no
746 // choice but to crudely chain invokes (i.e., to ignore invokes in
747 // the inlined function, but to turn all unwindable calls into
748 // invokes), which is only semantically valid if every unwind stops
749 // at every landing pad.
750 //
751 // Therefore, the invoke-inline hack is to guarantee that every
752 // landing pad has a catch-all.
753 enum CleanupHackLevel_t {
754   /// A level of hack that requires that all landing pads have
755   /// catch-alls.
756   CHL_MandatoryCatchall,
757 
758   /// A level of hack that requires that all landing pads handle
759   /// cleanups.
760   CHL_MandatoryCleanup,
761 
762   /// No hacks at all;  ideal IR generation.
763   CHL_Ideal
764 };
765 const CleanupHackLevel_t CleanupHackLevel = CHL_MandatoryCleanup;
766 
767 llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
768   assert(EHStack.requiresLandingPad());
769 
770   EHScope &innermostEHScope = *EHStack.find(EHStack.getInnermostEHScope());
771   switch (innermostEHScope.getKind()) {
772   case EHScope::Terminate:
773     return getTerminateLandingPad();
774 
775   case EHScope::Catch:
776   case EHScope::Cleanup:
777   case EHScope::Filter:
778     if (llvm::BasicBlock *lpad = innermostEHScope.getCachedLandingPad())
779       return lpad;
780   }
781 
782   // Save the current IR generation state.
783   CGBuilderTy::InsertPoint savedIP = Builder.saveAndClearIP();
784 
785   const EHPersonality &personality = EHPersonality::get(getLangOpts());
786 
787   // Create and configure the landing pad.
788   llvm::BasicBlock *lpad = createBasicBlock("lpad");
789   EmitBlock(lpad);
790 
791   llvm::LandingPadInst *LPadInst =
792     Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, NULL),
793                              getOpaquePersonalityFn(CGM, personality), 0);
794 
795   llvm::Value *LPadExn = Builder.CreateExtractValue(LPadInst, 0);
796   Builder.CreateStore(LPadExn, getExceptionSlot());
797   llvm::Value *LPadSel = Builder.CreateExtractValue(LPadInst, 1);
798   Builder.CreateStore(LPadSel, getEHSelectorSlot());
799 
800   // Save the exception pointer.  It's safe to use a single exception
801   // pointer per function because EH cleanups can never have nested
802   // try/catches.
803   // Build the landingpad instruction.
804 
805   // Accumulate all the handlers in scope.
806   bool hasCatchAll = false;
807   bool hasCleanup = false;
808   bool hasFilter = false;
809   SmallVector<llvm::Value*, 4> filterTypes;
810   llvm::SmallPtrSet<llvm::Value*, 4> catchTypes;
811   for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end();
812          I != E; ++I) {
813 
814     switch (I->getKind()) {
815     case EHScope::Cleanup:
816       // If we have a cleanup, remember that.
817       hasCleanup = (hasCleanup || cast<EHCleanupScope>(*I).isEHCleanup());
818       continue;
819 
820     case EHScope::Filter: {
821       assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
822       assert(!hasCatchAll && "EH filter reached after catch-all");
823 
824       // Filter scopes get added to the landingpad in weird ways.
825       EHFilterScope &filter = cast<EHFilterScope>(*I);
826       hasFilter = true;
827 
828       // Add all the filter values.
829       for (unsigned i = 0, e = filter.getNumFilters(); i != e; ++i)
830         filterTypes.push_back(filter.getFilter(i));
831       goto done;
832     }
833 
834     case EHScope::Terminate:
835       // Terminate scopes are basically catch-alls.
836       assert(!hasCatchAll);
837       hasCatchAll = true;
838       goto done;
839 
840     case EHScope::Catch:
841       break;
842     }
843 
844     EHCatchScope &catchScope = cast<EHCatchScope>(*I);
845     for (unsigned hi = 0, he = catchScope.getNumHandlers(); hi != he; ++hi) {
846       EHCatchScope::Handler handler = catchScope.getHandler(hi);
847 
848       // If this is a catch-all, register that and abort.
849       if (!handler.Type) {
850         assert(!hasCatchAll);
851         hasCatchAll = true;
852         goto done;
853       }
854 
855       // Check whether we already have a handler for this type.
856       if (catchTypes.insert(handler.Type))
857         // If not, add it directly to the landingpad.
858         LPadInst->addClause(handler.Type);
859     }
860   }
861 
862  done:
863   // If we have a catch-all, add null to the landingpad.
864   assert(!(hasCatchAll && hasFilter));
865   if (hasCatchAll) {
866     LPadInst->addClause(getCatchAllValue(*this));
867 
868   // If we have an EH filter, we need to add those handlers in the
869   // right place in the landingpad, which is to say, at the end.
870   } else if (hasFilter) {
871     // Create a filter expression: a constant array indicating which filter
872     // types there are. The personality routine only lands here if the filter
873     // doesn't match.
874     SmallVector<llvm::Constant*, 8> Filters;
875     llvm::ArrayType *AType =
876       llvm::ArrayType::get(!filterTypes.empty() ?
877                              filterTypes[0]->getType() : Int8PtrTy,
878                            filterTypes.size());
879 
880     for (unsigned i = 0, e = filterTypes.size(); i != e; ++i)
881       Filters.push_back(cast<llvm::Constant>(filterTypes[i]));
882     llvm::Constant *FilterArray = llvm::ConstantArray::get(AType, Filters);
883     LPadInst->addClause(FilterArray);
884 
885     // Also check whether we need a cleanup.
886     if (hasCleanup)
887       LPadInst->setCleanup(true);
888 
889   // Otherwise, signal that we at least have cleanups.
890   } else if (CleanupHackLevel == CHL_MandatoryCatchall || hasCleanup) {
891     if (CleanupHackLevel == CHL_MandatoryCatchall)
892       LPadInst->addClause(getCatchAllValue(*this));
893     else
894       LPadInst->setCleanup(true);
895   }
896 
897   assert((LPadInst->getNumClauses() > 0 || LPadInst->isCleanup()) &&
898          "landingpad instruction has no clauses!");
899 
900   // Tell the backend how to generate the landing pad.
901   Builder.CreateBr(getEHDispatchBlock(EHStack.getInnermostEHScope()));
902 
903   // Restore the old IR generation state.
904   Builder.restoreIP(savedIP);
905 
906   return lpad;
907 }
908 
909 namespace {
910   /// A cleanup to call __cxa_end_catch.  In many cases, the caught
911   /// exception type lets us state definitively that the thrown exception
912   /// type does not have a destructor.  In particular:
913   ///   - Catch-alls tell us nothing, so we have to conservatively
914   ///     assume that the thrown exception might have a destructor.
915   ///   - Catches by reference behave according to their base types.
916   ///   - Catches of non-record types will only trigger for exceptions
917   ///     of non-record types, which never have destructors.
918   ///   - Catches of record types can trigger for arbitrary subclasses
919   ///     of the caught type, so we have to assume the actual thrown
920   ///     exception type might have a throwing destructor, even if the
921   ///     caught type's destructor is trivial or nothrow.
922   struct CallEndCatch : EHScopeStack::Cleanup {
923     CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
924     bool MightThrow;
925 
926     void Emit(CodeGenFunction &CGF, Flags flags) {
927       if (!MightThrow) {
928         CGF.Builder.CreateCall(getEndCatchFn(CGF))->setDoesNotThrow();
929         return;
930       }
931 
932       CGF.EmitCallOrInvoke(getEndCatchFn(CGF));
933     }
934   };
935 }
936 
937 /// Emits a call to __cxa_begin_catch and enters a cleanup to call
938 /// __cxa_end_catch.
939 ///
940 /// \param EndMightThrow - true if __cxa_end_catch might throw
941 static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
942                                    llvm::Value *Exn,
943                                    bool EndMightThrow) {
944   llvm::CallInst *Call = CGF.Builder.CreateCall(getBeginCatchFn(CGF), Exn);
945   Call->setDoesNotThrow();
946 
947   CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
948 
949   return Call;
950 }
951 
952 /// A "special initializer" callback for initializing a catch
953 /// parameter during catch initialization.
954 static void InitCatchParam(CodeGenFunction &CGF,
955                            const VarDecl &CatchParam,
956                            llvm::Value *ParamAddr) {
957   // Load the exception from where the landing pad saved it.
958   llvm::Value *Exn = CGF.getExceptionFromSlot();
959 
960   CanQualType CatchType =
961     CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
962   llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
963 
964   // If we're catching by reference, we can just cast the object
965   // pointer to the appropriate pointer.
966   if (isa<ReferenceType>(CatchType)) {
967     QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
968     bool EndCatchMightThrow = CaughtType->isRecordType();
969 
970     // __cxa_begin_catch returns the adjusted object pointer.
971     llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
972 
973     // We have no way to tell the personality function that we're
974     // catching by reference, so if we're catching a pointer,
975     // __cxa_begin_catch will actually return that pointer by value.
976     if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
977       QualType PointeeType = PT->getPointeeType();
978 
979       // When catching by reference, generally we should just ignore
980       // this by-value pointer and use the exception object instead.
981       if (!PointeeType->isRecordType()) {
982 
983         // Exn points to the struct _Unwind_Exception header, which
984         // we have to skip past in order to reach the exception data.
985         unsigned HeaderSize =
986           CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
987         AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
988 
989       // However, if we're catching a pointer-to-record type that won't
990       // work, because the personality function might have adjusted
991       // the pointer.  There's actually no way for us to fully satisfy
992       // the language/ABI contract here:  we can't use Exn because it
993       // might have the wrong adjustment, but we can't use the by-value
994       // pointer because it's off by a level of abstraction.
995       //
996       // The current solution is to dump the adjusted pointer into an
997       // alloca, which breaks language semantics (because changing the
998       // pointer doesn't change the exception) but at least works.
999       // The better solution would be to filter out non-exact matches
1000       // and rethrow them, but this is tricky because the rethrow
1001       // really needs to be catchable by other sites at this landing
1002       // pad.  The best solution is to fix the personality function.
1003       } else {
1004         // Pull the pointer for the reference type off.
1005         llvm::Type *PtrTy =
1006           cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
1007 
1008         // Create the temporary and write the adjusted pointer into it.
1009         llvm::Value *ExnPtrTmp = CGF.CreateTempAlloca(PtrTy, "exn.byref.tmp");
1010         llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1011         CGF.Builder.CreateStore(Casted, ExnPtrTmp);
1012 
1013         // Bind the reference to the temporary.
1014         AdjustedExn = ExnPtrTmp;
1015       }
1016     }
1017 
1018     llvm::Value *ExnCast =
1019       CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
1020     CGF.Builder.CreateStore(ExnCast, ParamAddr);
1021     return;
1022   }
1023 
1024   // Non-aggregates (plus complexes).
1025   bool IsComplex = false;
1026   if (!CGF.hasAggregateLLVMType(CatchType) ||
1027       (IsComplex = CatchType->isAnyComplexType())) {
1028     llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
1029 
1030     // If the catch type is a pointer type, __cxa_begin_catch returns
1031     // the pointer by value.
1032     if (CatchType->hasPointerRepresentation()) {
1033       llvm::Value *CastExn =
1034         CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
1035 
1036       switch (CatchType.getQualifiers().getObjCLifetime()) {
1037       case Qualifiers::OCL_Strong:
1038         CastExn = CGF.EmitARCRetainNonBlock(CastExn);
1039         // fallthrough
1040 
1041       case Qualifiers::OCL_None:
1042       case Qualifiers::OCL_ExplicitNone:
1043       case Qualifiers::OCL_Autoreleasing:
1044         CGF.Builder.CreateStore(CastExn, ParamAddr);
1045         return;
1046 
1047       case Qualifiers::OCL_Weak:
1048         CGF.EmitARCInitWeak(ParamAddr, CastExn);
1049         return;
1050       }
1051       llvm_unreachable("bad ownership qualifier!");
1052     }
1053 
1054     // Otherwise, it returns a pointer into the exception object.
1055 
1056     llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
1057     llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1058 
1059     if (IsComplex) {
1060       CGF.StoreComplexToAddr(CGF.LoadComplexFromAddr(Cast, /*volatile*/ false),
1061                              ParamAddr, /*volatile*/ false);
1062     } else {
1063       unsigned Alignment =
1064         CGF.getContext().getDeclAlign(&CatchParam).getQuantity();
1065       llvm::Value *ExnLoad = CGF.Builder.CreateLoad(Cast, "exn.scalar");
1066       CGF.EmitStoreOfScalar(ExnLoad, ParamAddr, /*volatile*/ false, Alignment,
1067                             CatchType);
1068     }
1069     return;
1070   }
1071 
1072   assert(isa<RecordType>(CatchType) && "unexpected catch type!");
1073 
1074   llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
1075 
1076   // Check for a copy expression.  If we don't have a copy expression,
1077   // that means a trivial copy is okay.
1078   const Expr *copyExpr = CatchParam.getInit();
1079   if (!copyExpr) {
1080     llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
1081     llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
1082     CGF.EmitAggregateCopy(ParamAddr, adjustedExn, CatchType);
1083     return;
1084   }
1085 
1086   // We have to call __cxa_get_exception_ptr to get the adjusted
1087   // pointer before copying.
1088   llvm::CallInst *rawAdjustedExn =
1089     CGF.Builder.CreateCall(getGetExceptionPtrFn(CGF), Exn);
1090   rawAdjustedExn->setDoesNotThrow();
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));
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     EHStack.popCatch();
1251     return;
1252   }
1253 
1254   // Emit the structure of the EH dispatch for this catch.
1255   emitCatchDispatchBlock(*this, CatchScope);
1256 
1257   // Copy the handler blocks off before we pop the EH stack.  Emitting
1258   // the handlers might scribble on this memory.
1259   SmallVector<EHCatchScope::Handler, 8> Handlers(NumHandlers);
1260   memcpy(Handlers.data(), CatchScope.begin(),
1261          NumHandlers * sizeof(EHCatchScope::Handler));
1262 
1263   EHStack.popCatch();
1264 
1265   // The fall-through block.
1266   llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
1267 
1268   // We just emitted the body of the try; jump to the continue block.
1269   if (HaveInsertPoint())
1270     Builder.CreateBr(ContBB);
1271 
1272   // Determine if we need an implicit rethrow for all these catch handlers;
1273   // see the comment below.
1274   bool doImplicitRethrow = false;
1275   if (IsFnTryBlock)
1276     doImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
1277                         isa<CXXConstructorDecl>(CurCodeDecl);
1278 
1279   // Perversely, we emit the handlers backwards precisely because we
1280   // want them to appear in source order.  In all of these cases, the
1281   // catch block will have exactly one predecessor, which will be a
1282   // particular block in the catch dispatch.  However, in the case of
1283   // a catch-all, one of the dispatch blocks will branch to two
1284   // different handlers, and EmitBlockAfterUses will cause the second
1285   // handler to be moved before the first.
1286   for (unsigned I = NumHandlers; I != 0; --I) {
1287     llvm::BasicBlock *CatchBlock = Handlers[I-1].Block;
1288     EmitBlockAfterUses(CatchBlock);
1289 
1290     // Catch the exception if this isn't a catch-all.
1291     const CXXCatchStmt *C = S.getHandler(I-1);
1292 
1293     // Enter a cleanup scope, including the catch variable and the
1294     // end-catch.
1295     RunCleanupsScope CatchScope(*this);
1296 
1297     // Initialize the catch variable and set up the cleanups.
1298     BeginCatch(*this, C);
1299 
1300     // Perform the body of the catch.
1301     EmitStmt(C->getHandlerBlock());
1302 
1303     // [except.handle]p11:
1304     //   The currently handled exception is rethrown if control
1305     //   reaches the end of a handler of the function-try-block of a
1306     //   constructor or destructor.
1307 
1308     // It is important that we only do this on fallthrough and not on
1309     // return.  Note that it's illegal to put a return in a
1310     // constructor function-try-block's catch handler (p14), so this
1311     // really only applies to destructors.
1312     if (doImplicitRethrow && HaveInsertPoint()) {
1313       EmitCallOrInvoke(getReThrowFn(*this));
1314       Builder.CreateUnreachable();
1315       Builder.ClearInsertionPoint();
1316     }
1317 
1318     // Fall out through the catch cleanups.
1319     CatchScope.ForceCleanup();
1320 
1321     // Branch out of the try.
1322     if (HaveInsertPoint())
1323       Builder.CreateBr(ContBB);
1324   }
1325 
1326   EmitBlock(ContBB);
1327 }
1328 
1329 namespace {
1330   struct CallEndCatchForFinally : EHScopeStack::Cleanup {
1331     llvm::Value *ForEHVar;
1332     llvm::Value *EndCatchFn;
1333     CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn)
1334       : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
1335 
1336     void Emit(CodeGenFunction &CGF, Flags flags) {
1337       llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
1338       llvm::BasicBlock *CleanupContBB =
1339         CGF.createBasicBlock("finally.cleanup.cont");
1340 
1341       llvm::Value *ShouldEndCatch =
1342         CGF.Builder.CreateLoad(ForEHVar, "finally.endcatch");
1343       CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1344       CGF.EmitBlock(EndCatchBB);
1345       CGF.EmitCallOrInvoke(EndCatchFn); // catch-all, so might throw
1346       CGF.EmitBlock(CleanupContBB);
1347     }
1348   };
1349 
1350   struct PerformFinally : EHScopeStack::Cleanup {
1351     const Stmt *Body;
1352     llvm::Value *ForEHVar;
1353     llvm::Value *EndCatchFn;
1354     llvm::Value *RethrowFn;
1355     llvm::Value *SavedExnVar;
1356 
1357     PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
1358                    llvm::Value *EndCatchFn,
1359                    llvm::Value *RethrowFn, llvm::Value *SavedExnVar)
1360       : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1361         RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
1362 
1363     void Emit(CodeGenFunction &CGF, Flags flags) {
1364       // Enter a cleanup to call the end-catch function if one was provided.
1365       if (EndCatchFn)
1366         CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
1367                                                         ForEHVar, EndCatchFn);
1368 
1369       // Save the current cleanup destination in case there are
1370       // cleanups in the finally block.
1371       llvm::Value *SavedCleanupDest =
1372         CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
1373                                "cleanup.dest.saved");
1374 
1375       // Emit the finally block.
1376       CGF.EmitStmt(Body);
1377 
1378       // If the end of the finally is reachable, check whether this was
1379       // for EH.  If so, rethrow.
1380       if (CGF.HaveInsertPoint()) {
1381         llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
1382         llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
1383 
1384         llvm::Value *ShouldRethrow =
1385           CGF.Builder.CreateLoad(ForEHVar, "finally.shouldthrow");
1386         CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1387 
1388         CGF.EmitBlock(RethrowBB);
1389         if (SavedExnVar) {
1390           CGF.EmitCallOrInvoke(RethrowFn, CGF.Builder.CreateLoad(SavedExnVar));
1391         } else {
1392           CGF.EmitCallOrInvoke(RethrowFn);
1393         }
1394         CGF.Builder.CreateUnreachable();
1395 
1396         CGF.EmitBlock(ContBB);
1397 
1398         // Restore the cleanup destination.
1399         CGF.Builder.CreateStore(SavedCleanupDest,
1400                                 CGF.getNormalCleanupDestSlot());
1401       }
1402 
1403       // Leave the end-catch cleanup.  As an optimization, pretend that
1404       // the fallthrough path was inaccessible; we've dynamically proven
1405       // that we're not in the EH case along that path.
1406       if (EndCatchFn) {
1407         CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1408         CGF.PopCleanupBlock();
1409         CGF.Builder.restoreIP(SavedIP);
1410       }
1411 
1412       // Now make sure we actually have an insertion point or the
1413       // cleanup gods will hate us.
1414       CGF.EnsureInsertPoint();
1415     }
1416   };
1417 }
1418 
1419 /// Enters a finally block for an implementation using zero-cost
1420 /// exceptions.  This is mostly general, but hard-codes some
1421 /// language/ABI-specific behavior in the catch-all sections.
1422 void CodeGenFunction::FinallyInfo::enter(CodeGenFunction &CGF,
1423                                          const Stmt *body,
1424                                          llvm::Constant *beginCatchFn,
1425                                          llvm::Constant *endCatchFn,
1426                                          llvm::Constant *rethrowFn) {
1427   assert((beginCatchFn != 0) == (endCatchFn != 0) &&
1428          "begin/end catch functions not paired");
1429   assert(rethrowFn && "rethrow function is required");
1430 
1431   BeginCatchFn = beginCatchFn;
1432 
1433   // The rethrow function has one of the following two types:
1434   //   void (*)()
1435   //   void (*)(void*)
1436   // In the latter case we need to pass it the exception object.
1437   // But we can't use the exception slot because the @finally might
1438   // have a landing pad (which would overwrite the exception slot).
1439   llvm::FunctionType *rethrowFnTy =
1440     cast<llvm::FunctionType>(
1441       cast<llvm::PointerType>(rethrowFn->getType())->getElementType());
1442   SavedExnVar = 0;
1443   if (rethrowFnTy->getNumParams())
1444     SavedExnVar = CGF.CreateTempAlloca(CGF.Int8PtrTy, "finally.exn");
1445 
1446   // A finally block is a statement which must be executed on any edge
1447   // out of a given scope.  Unlike a cleanup, the finally block may
1448   // contain arbitrary control flow leading out of itself.  In
1449   // addition, finally blocks should always be executed, even if there
1450   // are no catch handlers higher on the stack.  Therefore, we
1451   // surround the protected scope with a combination of a normal
1452   // cleanup (to catch attempts to break out of the block via normal
1453   // control flow) and an EH catch-all (semantically "outside" any try
1454   // statement to which the finally block might have been attached).
1455   // The finally block itself is generated in the context of a cleanup
1456   // which conditionally leaves the catch-all.
1457 
1458   // Jump destination for performing the finally block on an exception
1459   // edge.  We'll never actually reach this block, so unreachable is
1460   // fine.
1461   RethrowDest = CGF.getJumpDestInCurrentScope(CGF.getUnreachableBlock());
1462 
1463   // Whether the finally block is being executed for EH purposes.
1464   ForEHVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "finally.for-eh");
1465   CGF.Builder.CreateStore(CGF.Builder.getFalse(), ForEHVar);
1466 
1467   // Enter a normal cleanup which will perform the @finally block.
1468   CGF.EHStack.pushCleanup<PerformFinally>(NormalCleanup, body,
1469                                           ForEHVar, endCatchFn,
1470                                           rethrowFn, SavedExnVar);
1471 
1472   // Enter a catch-all scope.
1473   llvm::BasicBlock *catchBB = CGF.createBasicBlock("finally.catchall");
1474   EHCatchScope *catchScope = CGF.EHStack.pushCatch(1);
1475   catchScope->setCatchAllHandler(0, catchBB);
1476 }
1477 
1478 void CodeGenFunction::FinallyInfo::exit(CodeGenFunction &CGF) {
1479   // Leave the finally catch-all.
1480   EHCatchScope &catchScope = cast<EHCatchScope>(*CGF.EHStack.begin());
1481   llvm::BasicBlock *catchBB = catchScope.getHandler(0).Block;
1482 
1483   CGF.popCatchScope();
1484 
1485   // If there are any references to the catch-all block, emit it.
1486   if (catchBB->use_empty()) {
1487     delete catchBB;
1488   } else {
1489     CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveAndClearIP();
1490     CGF.EmitBlock(catchBB);
1491 
1492     llvm::Value *exn = 0;
1493 
1494     // If there's a begin-catch function, call it.
1495     if (BeginCatchFn) {
1496       exn = CGF.getExceptionFromSlot();
1497       CGF.Builder.CreateCall(BeginCatchFn, exn)->setDoesNotThrow();
1498     }
1499 
1500     // If we need to remember the exception pointer to rethrow later, do so.
1501     if (SavedExnVar) {
1502       if (!exn) exn = CGF.getExceptionFromSlot();
1503       CGF.Builder.CreateStore(exn, SavedExnVar);
1504     }
1505 
1506     // Tell the cleanups in the finally block that we're do this for EH.
1507     CGF.Builder.CreateStore(CGF.Builder.getTrue(), ForEHVar);
1508 
1509     // Thread a jump through the finally cleanup.
1510     CGF.EmitBranchThroughCleanup(RethrowDest);
1511 
1512     CGF.Builder.restoreIP(savedIP);
1513   }
1514 
1515   // Finally, leave the @finally cleanup.
1516   CGF.PopCleanupBlock();
1517 }
1518 
1519 llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
1520   if (TerminateLandingPad)
1521     return TerminateLandingPad;
1522 
1523   CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1524 
1525   // This will get inserted at the end of the function.
1526   TerminateLandingPad = createBasicBlock("terminate.lpad");
1527   Builder.SetInsertPoint(TerminateLandingPad);
1528 
1529   // Tell the backend that this is a landing pad.
1530   const EHPersonality &Personality = EHPersonality::get(CGM.getLangOpts());
1531   llvm::LandingPadInst *LPadInst =
1532     Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, NULL),
1533                              getOpaquePersonalityFn(CGM, Personality), 0);
1534   LPadInst->addClause(getCatchAllValue(*this));
1535 
1536   llvm::CallInst *TerminateCall = Builder.CreateCall(getTerminateFn(*this));
1537   TerminateCall->setDoesNotReturn();
1538   TerminateCall->setDoesNotThrow();
1539   Builder.CreateUnreachable();
1540 
1541   // Restore the saved insertion state.
1542   Builder.restoreIP(SavedIP);
1543 
1544   return TerminateLandingPad;
1545 }
1546 
1547 llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
1548   if (TerminateHandler)
1549     return TerminateHandler;
1550 
1551   CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1552 
1553   // Set up the terminate handler.  This block is inserted at the very
1554   // end of the function by FinishFunction.
1555   TerminateHandler = createBasicBlock("terminate.handler");
1556   Builder.SetInsertPoint(TerminateHandler);
1557   llvm::CallInst *TerminateCall = Builder.CreateCall(getTerminateFn(*this));
1558   TerminateCall->setDoesNotReturn();
1559   TerminateCall->setDoesNotThrow();
1560   Builder.CreateUnreachable();
1561 
1562   // Restore the saved insertion state.
1563   Builder.restoreIP(SavedIP);
1564 
1565   return TerminateHandler;
1566 }
1567 
1568 llvm::BasicBlock *CodeGenFunction::getEHResumeBlock(bool isCleanup) {
1569   if (EHResumeBlock) return EHResumeBlock;
1570 
1571   CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1572 
1573   // We emit a jump to a notional label at the outermost unwind state.
1574   EHResumeBlock = createBasicBlock("eh.resume");
1575   Builder.SetInsertPoint(EHResumeBlock);
1576 
1577   const EHPersonality &Personality = EHPersonality::get(CGM.getLangOpts());
1578 
1579   // This can always be a call because we necessarily didn't find
1580   // anything on the EH stack which needs our help.
1581   const char *RethrowName = Personality.CatchallRethrowFn;
1582   if (RethrowName != 0 && !isCleanup) {
1583     Builder.CreateCall(getCatchallRethrowFn(*this, RethrowName),
1584                        getExceptionFromSlot())
1585       ->setDoesNotReturn();
1586   } else {
1587     switch (CleanupHackLevel) {
1588     case CHL_MandatoryCatchall:
1589       // In mandatory-catchall mode, we need to use
1590       // _Unwind_Resume_or_Rethrow, or whatever the personality's
1591       // equivalent is.
1592       Builder.CreateCall(getUnwindResumeOrRethrowFn(),
1593                          getExceptionFromSlot())
1594         ->setDoesNotReturn();
1595       break;
1596     case CHL_MandatoryCleanup: {
1597       // In mandatory-cleanup mode, we should use 'resume'.
1598 
1599       // Recreate the landingpad's return value for the 'resume' instruction.
1600       llvm::Value *Exn = getExceptionFromSlot();
1601       llvm::Value *Sel = getSelectorFromSlot();
1602 
1603       llvm::Type *LPadType = llvm::StructType::get(Exn->getType(),
1604                                                    Sel->getType(), NULL);
1605       llvm::Value *LPadVal = llvm::UndefValue::get(LPadType);
1606       LPadVal = Builder.CreateInsertValue(LPadVal, Exn, 0, "lpad.val");
1607       LPadVal = Builder.CreateInsertValue(LPadVal, Sel, 1, "lpad.val");
1608 
1609       Builder.CreateResume(LPadVal);
1610       Builder.restoreIP(SavedIP);
1611       return EHResumeBlock;
1612     }
1613     case CHL_Ideal:
1614       // In an idealized mode where we don't have to worry about the
1615       // optimizer combining landing pads, we should just use
1616       // _Unwind_Resume (or the personality's equivalent).
1617       Builder.CreateCall(getUnwindResumeFn(), getExceptionFromSlot())
1618         ->setDoesNotReturn();
1619       break;
1620     }
1621   }
1622 
1623   Builder.CreateUnreachable();
1624 
1625   Builder.restoreIP(SavedIP);
1626 
1627   return EHResumeBlock;
1628 }
1629