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