CGException.cpp revision 3026348bd4c13a0f83b59839f64065e0fcbea253
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
26using namespace clang;
27using namespace CodeGen;
28
29static 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
38static 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
47static 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
58static 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
67static 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
76static 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
85static 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
94static 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
103llvm::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
112llvm::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
121static 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
140static 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
148const EHPersonality EHPersonality::GNU_C("__gcc_personality_v0");
149const EHPersonality EHPersonality::GNU_C_SJLJ("__gcc_personality_sj0");
150const EHPersonality EHPersonality::NeXT_ObjC("__objc_personality_v0");
151const EHPersonality EHPersonality::GNU_CPlusPlus("__gxx_personality_v0");
152const EHPersonality EHPersonality::GNU_CPlusPlus_SJLJ("__gxx_personality_sj0");
153const EHPersonality EHPersonality::GNU_ObjC("__gnu_objc_personality_v0",
154                                            "objc_exception_throw");
155const EHPersonality EHPersonality::GNU_ObjCXX("__gnustep_objcxx_personality_v0");
156
157static const EHPersonality &getCPersonality(const LangOptions &L) {
158  if (L.SjLjExceptions)
159    return EHPersonality::GNU_C_SJLJ;
160  return EHPersonality::GNU_C;
161}
162
163static 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
172static 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.
181static 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
200const 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
211static 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
221static 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.
229static 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.
280void 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.
317static 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
322namespace {
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.
339static 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, cast<llvm::Instruction>(typedAddr));
363}
364
365llvm::Value *CodeGenFunction::getExceptionSlot() {
366  if (!ExceptionSlot)
367    ExceptionSlot = CreateTempAlloca(Int8PtrTy, "exn.slot");
368  return ExceptionSlot;
369}
370
371llvm::Value *CodeGenFunction::getEHSelectorSlot() {
372  if (!EHSelectorSlot)
373    EHSelectorSlot = CreateTempAlloca(Int32Ty, "ehselector.slot");
374  return EHSelectorSlot;
375}
376
377llvm::Value *CodeGenFunction::getExceptionFromSlot() {
378  return Builder.CreateLoad(getExceptionSlot(), "exn");
379}
380
381llvm::Value *CodeGenFunction::getSelectorFromSlot() {
382  return Builder.CreateLoad(getEHSelectorSlot(), "sel");
383}
384
385void 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
454void 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.
486static 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
522void 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
545void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
546  EnterCXXTryStmt(S);
547  EmitStmt(S.getTryBlock());
548  ExitCXXTryStmt(S);
549}
550
551void 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
582llvm::BasicBlock *
583CodeGenFunction::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.
629static 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  llvm_unreachable("Invalid EHScope Kind!");
640}
641
642llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
643  assert(EHStack.requiresLandingPad());
644  assert(!EHStack.empty());
645
646  if (!CGM.getLangOptions().Exceptions)
647    return 0;
648
649  // Check the innermost scope for a cached landing pad.  If this is
650  // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
651  llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
652  if (LP) return LP;
653
654  // Build the landing pad for this scope.
655  LP = EmitLandingPad();
656  assert(LP);
657
658  // Cache the landing pad on the innermost scope.  If this is a
659  // non-EH scope, cache the landing pad on the enclosing scope, too.
660  for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
661    ir->setCachedLandingPad(LP);
662    if (!isNonEHScope(*ir)) break;
663  }
664
665  return LP;
666}
667
668// This code contains a hack to work around a design flaw in
669// LLVM's EH IR which breaks semantics after inlining.  This same
670// hack is implemented in llvm-gcc.
671//
672// The LLVM EH abstraction is basically a thin veneer over the
673// traditional GCC zero-cost design: for each range of instructions
674// in the function, there is (at most) one "landing pad" with an
675// associated chain of EH actions.  A language-specific personality
676// function interprets this chain of actions and (1) decides whether
677// or not to resume execution at the landing pad and (2) if so,
678// provides an integer indicating why it's stopping.  In LLVM IR,
679// the association of a landing pad with a range of instructions is
680// achieved via an invoke instruction, the chain of actions becomes
681// the arguments to the @llvm.eh.selector call, and the selector
682// call returns the integer indicator.  Other than the required
683// presence of two intrinsic function calls in the landing pad,
684// the IR exactly describes the layout of the output code.
685//
686// A principal advantage of this design is that it is completely
687// language-agnostic; in theory, the LLVM optimizers can treat
688// landing pads neutrally, and targets need only know how to lower
689// the intrinsics to have a functioning exceptions system (assuming
690// that platform exceptions follow something approximately like the
691// GCC design).  Unfortunately, landing pads cannot be combined in a
692// language-agnostic way: given selectors A and B, there is no way
693// to make a single landing pad which faithfully represents the
694// semantics of propagating an exception first through A, then
695// through B, without knowing how the personality will interpret the
696// (lowered form of the) selectors.  This means that inlining has no
697// choice but to crudely chain invokes (i.e., to ignore invokes in
698// the inlined function, but to turn all unwindable calls into
699// invokes), which is only semantically valid if every unwind stops
700// at every landing pad.
701//
702// Therefore, the invoke-inline hack is to guarantee that every
703// landing pad has a catch-all.
704enum CleanupHackLevel_t {
705  /// A level of hack that requires that all landing pads have
706  /// catch-alls.
707  CHL_MandatoryCatchall,
708
709  /// A level of hack that requires that all landing pads handle
710  /// cleanups.
711  CHL_MandatoryCleanup,
712
713  /// No hacks at all;  ideal IR generation.
714  CHL_Ideal
715};
716const CleanupHackLevel_t CleanupHackLevel = CHL_MandatoryCleanup;
717
718llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
719  assert(EHStack.requiresLandingPad());
720
721  EHScope &innermostEHScope = *EHStack.find(EHStack.getInnermostEHScope());
722  switch (innermostEHScope.getKind()) {
723  case EHScope::Terminate:
724    return getTerminateLandingPad();
725
726  case EHScope::Catch:
727  case EHScope::Cleanup:
728  case EHScope::Filter:
729    if (llvm::BasicBlock *lpad = innermostEHScope.getCachedLandingPad())
730      return lpad;
731  }
732
733  // Save the current IR generation state.
734  CGBuilderTy::InsertPoint savedIP = Builder.saveAndClearIP();
735
736  const EHPersonality &personality = EHPersonality::get(getLangOptions());
737
738  // Create and configure the landing pad.
739  llvm::BasicBlock *lpad = createBasicBlock("lpad");
740  EmitBlock(lpad);
741
742  llvm::LandingPadInst *LPadInst =
743    Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, NULL),
744                             getOpaquePersonalityFn(CGM, personality), 0);
745
746  llvm::Value *LPadExn = Builder.CreateExtractValue(LPadInst, 0);
747  Builder.CreateStore(LPadExn, getExceptionSlot());
748  llvm::Value *LPadSel = Builder.CreateExtractValue(LPadInst, 1);
749  Builder.CreateStore(LPadSel, getEHSelectorSlot());
750
751  // Save the exception pointer.  It's safe to use a single exception
752  // pointer per function because EH cleanups can never have nested
753  // try/catches.
754  // Build the landingpad instruction.
755
756  // Accumulate all the handlers in scope.
757  bool hasCatchAll = false;
758  bool hasCleanup = false;
759  bool hasFilter = false;
760  SmallVector<llvm::Value*, 4> filterTypes;
761  llvm::SmallPtrSet<llvm::Value*, 4> catchTypes;
762  for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end();
763         I != E; ++I) {
764
765    switch (I->getKind()) {
766    case EHScope::Cleanup:
767      // If we have a cleanup, remember that.
768      hasCleanup = (hasCleanup || cast<EHCleanupScope>(*I).isEHCleanup());
769      continue;
770
771    case EHScope::Filter: {
772      assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
773      assert(!hasCatchAll && "EH filter reached after catch-all");
774
775      // Filter scopes get added to the landingpad in weird ways.
776      EHFilterScope &filter = cast<EHFilterScope>(*I);
777      hasFilter = true;
778
779      // Add all the filter values.
780      for (unsigned i = 0, e = filter.getNumFilters(); i != e; ++i)
781        filterTypes.push_back(filter.getFilter(i));
782      goto done;
783    }
784
785    case EHScope::Terminate:
786      // Terminate scopes are basically catch-alls.
787      assert(!hasCatchAll);
788      hasCatchAll = true;
789      goto done;
790
791    case EHScope::Catch:
792      break;
793    }
794
795    EHCatchScope &catchScope = cast<EHCatchScope>(*I);
796    for (unsigned hi = 0, he = catchScope.getNumHandlers(); hi != he; ++hi) {
797      EHCatchScope::Handler handler = catchScope.getHandler(hi);
798
799      // If this is a catch-all, register that and abort.
800      if (!handler.Type) {
801        assert(!hasCatchAll);
802        hasCatchAll = true;
803        goto done;
804      }
805
806      // Check whether we already have a handler for this type.
807      if (catchTypes.insert(handler.Type))
808        // If not, add it directly to the landingpad.
809        LPadInst->addClause(handler.Type);
810    }
811  }
812
813 done:
814  // If we have a catch-all, add null to the landingpad.
815  assert(!(hasCatchAll && hasFilter));
816  if (hasCatchAll) {
817    LPadInst->addClause(getCatchAllValue(*this));
818
819  // If we have an EH filter, we need to add those handlers in the
820  // right place in the landingpad, which is to say, at the end.
821  } else if (hasFilter) {
822    // Create a filter expression: a constant array indicating which filter
823    // types there are. The personality routine only lands here if the filter
824    // doesn't match.
825    llvm::SmallVector<llvm::Constant*, 8> Filters;
826    llvm::ArrayType *AType =
827      llvm::ArrayType::get(!filterTypes.empty() ?
828                             filterTypes[0]->getType() : Int8PtrTy,
829                           filterTypes.size());
830
831    for (unsigned i = 0, e = filterTypes.size(); i != e; ++i)
832      Filters.push_back(cast<llvm::Constant>(filterTypes[i]));
833    llvm::Constant *FilterArray = llvm::ConstantArray::get(AType, Filters);
834    LPadInst->addClause(FilterArray);
835
836    // Also check whether we need a cleanup.
837    if (hasCleanup)
838      LPadInst->setCleanup(true);
839
840  // Otherwise, signal that we at least have cleanups.
841  } else if (CleanupHackLevel == CHL_MandatoryCatchall || hasCleanup) {
842    if (CleanupHackLevel == CHL_MandatoryCatchall)
843      LPadInst->addClause(getCatchAllValue(*this));
844    else
845      LPadInst->setCleanup(true);
846  }
847
848  assert((LPadInst->getNumClauses() > 0 || LPadInst->isCleanup()) &&
849         "landingpad instruction has no clauses!");
850
851  // Tell the backend how to generate the landing pad.
852  Builder.CreateBr(getEHDispatchBlock(EHStack.getInnermostEHScope()));
853
854  // Restore the old IR generation state.
855  Builder.restoreIP(savedIP);
856
857  return lpad;
858}
859
860namespace {
861  /// A cleanup to call __cxa_end_catch.  In many cases, the caught
862  /// exception type lets us state definitively that the thrown exception
863  /// type does not have a destructor.  In particular:
864  ///   - Catch-alls tell us nothing, so we have to conservatively
865  ///     assume that the thrown exception might have a destructor.
866  ///   - Catches by reference behave according to their base types.
867  ///   - Catches of non-record types will only trigger for exceptions
868  ///     of non-record types, which never have destructors.
869  ///   - Catches of record types can trigger for arbitrary subclasses
870  ///     of the caught type, so we have to assume the actual thrown
871  ///     exception type might have a throwing destructor, even if the
872  ///     caught type's destructor is trivial or nothrow.
873  struct CallEndCatch : EHScopeStack::Cleanup {
874    CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
875    bool MightThrow;
876
877    void Emit(CodeGenFunction &CGF, Flags flags) {
878      if (!MightThrow) {
879        CGF.Builder.CreateCall(getEndCatchFn(CGF))->setDoesNotThrow();
880        return;
881      }
882
883      CGF.EmitCallOrInvoke(getEndCatchFn(CGF));
884    }
885  };
886}
887
888/// Emits a call to __cxa_begin_catch and enters a cleanup to call
889/// __cxa_end_catch.
890///
891/// \param EndMightThrow - true if __cxa_end_catch might throw
892static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
893                                   llvm::Value *Exn,
894                                   bool EndMightThrow) {
895  llvm::CallInst *Call = CGF.Builder.CreateCall(getBeginCatchFn(CGF), Exn);
896  Call->setDoesNotThrow();
897
898  CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
899
900  return Call;
901}
902
903/// A "special initializer" callback for initializing a catch
904/// parameter during catch initialization.
905static void InitCatchParam(CodeGenFunction &CGF,
906                           const VarDecl &CatchParam,
907                           llvm::Value *ParamAddr) {
908  // Load the exception from where the landing pad saved it.
909  llvm::Value *Exn = CGF.getExceptionFromSlot();
910
911  CanQualType CatchType =
912    CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
913  llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
914
915  // If we're catching by reference, we can just cast the object
916  // pointer to the appropriate pointer.
917  if (isa<ReferenceType>(CatchType)) {
918    QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
919    bool EndCatchMightThrow = CaughtType->isRecordType();
920
921    // __cxa_begin_catch returns the adjusted object pointer.
922    llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
923
924    // We have no way to tell the personality function that we're
925    // catching by reference, so if we're catching a pointer,
926    // __cxa_begin_catch will actually return that pointer by value.
927    if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
928      QualType PointeeType = PT->getPointeeType();
929
930      // When catching by reference, generally we should just ignore
931      // this by-value pointer and use the exception object instead.
932      if (!PointeeType->isRecordType()) {
933
934        // Exn points to the struct _Unwind_Exception header, which
935        // we have to skip past in order to reach the exception data.
936        unsigned HeaderSize =
937          CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
938        AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
939
940      // However, if we're catching a pointer-to-record type that won't
941      // work, because the personality function might have adjusted
942      // the pointer.  There's actually no way for us to fully satisfy
943      // the language/ABI contract here:  we can't use Exn because it
944      // might have the wrong adjustment, but we can't use the by-value
945      // pointer because it's off by a level of abstraction.
946      //
947      // The current solution is to dump the adjusted pointer into an
948      // alloca, which breaks language semantics (because changing the
949      // pointer doesn't change the exception) but at least works.
950      // The better solution would be to filter out non-exact matches
951      // and rethrow them, but this is tricky because the rethrow
952      // really needs to be catchable by other sites at this landing
953      // pad.  The best solution is to fix the personality function.
954      } else {
955        // Pull the pointer for the reference type off.
956        llvm::Type *PtrTy =
957          cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
958
959        // Create the temporary and write the adjusted pointer into it.
960        llvm::Value *ExnPtrTmp = CGF.CreateTempAlloca(PtrTy, "exn.byref.tmp");
961        llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
962        CGF.Builder.CreateStore(Casted, ExnPtrTmp);
963
964        // Bind the reference to the temporary.
965        AdjustedExn = ExnPtrTmp;
966      }
967    }
968
969    llvm::Value *ExnCast =
970      CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
971    CGF.Builder.CreateStore(ExnCast, ParamAddr);
972    return;
973  }
974
975  // Non-aggregates (plus complexes).
976  bool IsComplex = false;
977  if (!CGF.hasAggregateLLVMType(CatchType) ||
978      (IsComplex = CatchType->isAnyComplexType())) {
979    llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
980
981    // If the catch type is a pointer type, __cxa_begin_catch returns
982    // the pointer by value.
983    if (CatchType->hasPointerRepresentation()) {
984      llvm::Value *CastExn =
985        CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
986
987      switch (CatchType.getQualifiers().getObjCLifetime()) {
988      case Qualifiers::OCL_Strong:
989        CastExn = CGF.EmitARCRetainNonBlock(CastExn);
990        // fallthrough
991
992      case Qualifiers::OCL_None:
993      case Qualifiers::OCL_ExplicitNone:
994      case Qualifiers::OCL_Autoreleasing:
995        CGF.Builder.CreateStore(CastExn, ParamAddr);
996        return;
997
998      case Qualifiers::OCL_Weak:
999        CGF.EmitARCInitWeak(ParamAddr, CastExn);
1000        return;
1001      }
1002      llvm_unreachable("bad ownership qualifier!");
1003    }
1004
1005    // Otherwise, it returns a pointer into the exception object.
1006
1007    llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
1008    llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1009
1010    if (IsComplex) {
1011      CGF.StoreComplexToAddr(CGF.LoadComplexFromAddr(Cast, /*volatile*/ false),
1012                             ParamAddr, /*volatile*/ false);
1013    } else {
1014      unsigned Alignment =
1015        CGF.getContext().getDeclAlign(&CatchParam).getQuantity();
1016      llvm::Value *ExnLoad = CGF.Builder.CreateLoad(Cast, "exn.scalar");
1017      CGF.EmitStoreOfScalar(ExnLoad, ParamAddr, /*volatile*/ false, Alignment,
1018                            CatchType);
1019    }
1020    return;
1021  }
1022
1023  assert(isa<RecordType>(CatchType) && "unexpected catch type!");
1024
1025  llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
1026
1027  // Check for a copy expression.  If we don't have a copy expression,
1028  // that means a trivial copy is okay.
1029  const Expr *copyExpr = CatchParam.getInit();
1030  if (!copyExpr) {
1031    llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
1032    llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
1033    CGF.EmitAggregateCopy(ParamAddr, adjustedExn, CatchType);
1034    return;
1035  }
1036
1037  // We have to call __cxa_get_exception_ptr to get the adjusted
1038  // pointer before copying.
1039  llvm::CallInst *rawAdjustedExn =
1040    CGF.Builder.CreateCall(getGetExceptionPtrFn(CGF), Exn);
1041  rawAdjustedExn->setDoesNotThrow();
1042
1043  // Cast that to the appropriate type.
1044  llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
1045
1046  // The copy expression is defined in terms of an OpaqueValueExpr.
1047  // Find it and map it to the adjusted expression.
1048  CodeGenFunction::OpaqueValueMapping
1049    opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
1050           CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
1051
1052  // Call the copy ctor in a terminate scope.
1053  CGF.EHStack.pushTerminate();
1054
1055  // Perform the copy construction.
1056  CharUnits Alignment = CGF.getContext().getDeclAlign(&CatchParam);
1057  CGF.EmitAggExpr(copyExpr,
1058                  AggValueSlot::forAddr(ParamAddr, Alignment, Qualifiers(),
1059                                        AggValueSlot::IsNotDestructed,
1060                                        AggValueSlot::DoesNotNeedGCBarriers,
1061                                        AggValueSlot::IsNotAliased));
1062
1063  // Leave the terminate scope.
1064  CGF.EHStack.popTerminate();
1065
1066  // Undo the opaque value mapping.
1067  opaque.pop();
1068
1069  // Finally we can call __cxa_begin_catch.
1070  CallBeginCatch(CGF, Exn, true);
1071}
1072
1073/// Begins a catch statement by initializing the catch variable and
1074/// calling __cxa_begin_catch.
1075static void BeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *S) {
1076  // We have to be very careful with the ordering of cleanups here:
1077  //   C++ [except.throw]p4:
1078  //     The destruction [of the exception temporary] occurs
1079  //     immediately after the destruction of the object declared in
1080  //     the exception-declaration in the handler.
1081  //
1082  // So the precise ordering is:
1083  //   1.  Construct catch variable.
1084  //   2.  __cxa_begin_catch
1085  //   3.  Enter __cxa_end_catch cleanup
1086  //   4.  Enter dtor cleanup
1087  //
1088  // We do this by using a slightly abnormal initialization process.
1089  // Delegation sequence:
1090  //   - ExitCXXTryStmt opens a RunCleanupsScope
1091  //     - EmitAutoVarAlloca creates the variable and debug info
1092  //       - InitCatchParam initializes the variable from the exception
1093  //       - CallBeginCatch calls __cxa_begin_catch
1094  //       - CallBeginCatch enters the __cxa_end_catch cleanup
1095  //     - EmitAutoVarCleanups enters the variable destructor cleanup
1096  //   - EmitCXXTryStmt emits the code for the catch body
1097  //   - EmitCXXTryStmt close the RunCleanupsScope
1098
1099  VarDecl *CatchParam = S->getExceptionDecl();
1100  if (!CatchParam) {
1101    llvm::Value *Exn = CGF.getExceptionFromSlot();
1102    CallBeginCatch(CGF, Exn, true);
1103    return;
1104  }
1105
1106  // Emit the local.
1107  CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
1108  InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF));
1109  CGF.EmitAutoVarCleanups(var);
1110}
1111
1112namespace {
1113  struct CallRethrow : EHScopeStack::Cleanup {
1114    void Emit(CodeGenFunction &CGF, Flags flags) {
1115      CGF.EmitCallOrInvoke(getReThrowFn(CGF));
1116    }
1117  };
1118}
1119
1120/// Emit the structure of the dispatch block for the given catch scope.
1121/// It is an invariant that the dispatch block already exists.
1122static void emitCatchDispatchBlock(CodeGenFunction &CGF,
1123                                   EHCatchScope &catchScope) {
1124  llvm::BasicBlock *dispatchBlock = catchScope.getCachedEHDispatchBlock();
1125  assert(dispatchBlock);
1126
1127  // If there's only a single catch-all, getEHDispatchBlock returned
1128  // that catch-all as the dispatch block.
1129  if (catchScope.getNumHandlers() == 1 &&
1130      catchScope.getHandler(0).isCatchAll()) {
1131    assert(dispatchBlock == catchScope.getHandler(0).Block);
1132    return;
1133  }
1134
1135  CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveIP();
1136  CGF.EmitBlockAfterUses(dispatchBlock);
1137
1138  // Select the right handler.
1139  llvm::Value *llvm_eh_typeid_for =
1140    CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
1141
1142  // Load the selector value.
1143  llvm::Value *selector = CGF.getSelectorFromSlot();
1144
1145  // Test against each of the exception types we claim to catch.
1146  for (unsigned i = 0, e = catchScope.getNumHandlers(); ; ++i) {
1147    assert(i < e && "ran off end of handlers!");
1148    const EHCatchScope::Handler &handler = catchScope.getHandler(i);
1149
1150    llvm::Value *typeValue = handler.Type;
1151    assert(typeValue && "fell into catch-all case!");
1152    typeValue = CGF.Builder.CreateBitCast(typeValue, CGF.Int8PtrTy);
1153
1154    // Figure out the next block.
1155    bool nextIsEnd;
1156    llvm::BasicBlock *nextBlock;
1157
1158    // If this is the last handler, we're at the end, and the next
1159    // block is the block for the enclosing EH scope.
1160    if (i + 1 == e) {
1161      nextBlock = CGF.getEHDispatchBlock(catchScope.getEnclosingEHScope());
1162      nextIsEnd = true;
1163
1164    // If the next handler is a catch-all, we're at the end, and the
1165    // next block is that handler.
1166    } else if (catchScope.getHandler(i+1).isCatchAll()) {
1167      nextBlock = catchScope.getHandler(i+1).Block;
1168      nextIsEnd = true;
1169
1170    // Otherwise, we're not at the end and we need a new block.
1171    } else {
1172      nextBlock = CGF.createBasicBlock("catch.fallthrough");
1173      nextIsEnd = false;
1174    }
1175
1176    // Figure out the catch type's index in the LSDA's type table.
1177    llvm::CallInst *typeIndex =
1178      CGF.Builder.CreateCall(llvm_eh_typeid_for, typeValue);
1179    typeIndex->setDoesNotThrow();
1180
1181    llvm::Value *matchesTypeIndex =
1182      CGF.Builder.CreateICmpEQ(selector, typeIndex, "matches");
1183    CGF.Builder.CreateCondBr(matchesTypeIndex, handler.Block, nextBlock);
1184
1185    // If the next handler is a catch-all, we're completely done.
1186    if (nextIsEnd) {
1187      CGF.Builder.restoreIP(savedIP);
1188      return;
1189
1190    // Otherwise we need to emit and continue at that block.
1191    } else {
1192      CGF.EmitBlock(nextBlock);
1193    }
1194  }
1195
1196  llvm_unreachable("fell out of loop!");
1197}
1198
1199void CodeGenFunction::popCatchScope() {
1200  EHCatchScope &catchScope = cast<EHCatchScope>(*EHStack.begin());
1201  if (catchScope.hasEHBranches())
1202    emitCatchDispatchBlock(*this, catchScope);
1203  EHStack.popCatch();
1204}
1205
1206void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
1207  unsigned NumHandlers = S.getNumHandlers();
1208  EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1209  assert(CatchScope.getNumHandlers() == NumHandlers);
1210
1211  // If the catch was not required, bail out now.
1212  if (!CatchScope.hasEHBranches()) {
1213    EHStack.popCatch();
1214    return;
1215  }
1216
1217  // Emit the structure of the EH dispatch for this catch.
1218  emitCatchDispatchBlock(*this, CatchScope);
1219
1220  // Copy the handler blocks off before we pop the EH stack.  Emitting
1221  // the handlers might scribble on this memory.
1222  SmallVector<EHCatchScope::Handler, 8> Handlers(NumHandlers);
1223  memcpy(Handlers.data(), CatchScope.begin(),
1224         NumHandlers * sizeof(EHCatchScope::Handler));
1225
1226  EHStack.popCatch();
1227
1228  // The fall-through block.
1229  llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
1230
1231  // We just emitted the body of the try; jump to the continue block.
1232  if (HaveInsertPoint())
1233    Builder.CreateBr(ContBB);
1234
1235  // Determine if we need an implicit rethrow for all these catch handlers.
1236  bool ImplicitRethrow = false;
1237  if (IsFnTryBlock)
1238    ImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
1239                      isa<CXXConstructorDecl>(CurCodeDecl);
1240
1241  // Perversely, we emit the handlers backwards precisely because we
1242  // want them to appear in source order.  In all of these cases, the
1243  // catch block will have exactly one predecessor, which will be a
1244  // particular block in the catch dispatch.  However, in the case of
1245  // a catch-all, one of the dispatch blocks will branch to two
1246  // different handlers, and EmitBlockAfterUses will cause the second
1247  // handler to be moved before the first.
1248  for (unsigned I = NumHandlers; I != 0; --I) {
1249    llvm::BasicBlock *CatchBlock = Handlers[I-1].Block;
1250    EmitBlockAfterUses(CatchBlock);
1251
1252    // Catch the exception if this isn't a catch-all.
1253    const CXXCatchStmt *C = S.getHandler(I-1);
1254
1255    // Enter a cleanup scope, including the catch variable and the
1256    // end-catch.
1257    RunCleanupsScope CatchScope(*this);
1258
1259    // Initialize the catch variable and set up the cleanups.
1260    BeginCatch(*this, C);
1261
1262    // If there's an implicit rethrow, push a normal "cleanup" to call
1263    // _cxa_rethrow.  This needs to happen before __cxa_end_catch is
1264    // called, and so it is pushed after BeginCatch.
1265    if (ImplicitRethrow)
1266      EHStack.pushCleanup<CallRethrow>(NormalCleanup);
1267
1268    // Perform the body of the catch.
1269    EmitStmt(C->getHandlerBlock());
1270
1271    // Fall out through the catch cleanups.
1272    CatchScope.ForceCleanup();
1273
1274    // Branch out of the try.
1275    if (HaveInsertPoint())
1276      Builder.CreateBr(ContBB);
1277  }
1278
1279  EmitBlock(ContBB);
1280}
1281
1282namespace {
1283  struct CallEndCatchForFinally : EHScopeStack::Cleanup {
1284    llvm::Value *ForEHVar;
1285    llvm::Value *EndCatchFn;
1286    CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn)
1287      : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
1288
1289    void Emit(CodeGenFunction &CGF, Flags flags) {
1290      llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
1291      llvm::BasicBlock *CleanupContBB =
1292        CGF.createBasicBlock("finally.cleanup.cont");
1293
1294      llvm::Value *ShouldEndCatch =
1295        CGF.Builder.CreateLoad(ForEHVar, "finally.endcatch");
1296      CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1297      CGF.EmitBlock(EndCatchBB);
1298      CGF.EmitCallOrInvoke(EndCatchFn); // catch-all, so might throw
1299      CGF.EmitBlock(CleanupContBB);
1300    }
1301  };
1302
1303  struct PerformFinally : EHScopeStack::Cleanup {
1304    const Stmt *Body;
1305    llvm::Value *ForEHVar;
1306    llvm::Value *EndCatchFn;
1307    llvm::Value *RethrowFn;
1308    llvm::Value *SavedExnVar;
1309
1310    PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
1311                   llvm::Value *EndCatchFn,
1312                   llvm::Value *RethrowFn, llvm::Value *SavedExnVar)
1313      : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1314        RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
1315
1316    void Emit(CodeGenFunction &CGF, Flags flags) {
1317      // Enter a cleanup to call the end-catch function if one was provided.
1318      if (EndCatchFn)
1319        CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
1320                                                        ForEHVar, EndCatchFn);
1321
1322      // Save the current cleanup destination in case there are
1323      // cleanups in the finally block.
1324      llvm::Value *SavedCleanupDest =
1325        CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
1326                               "cleanup.dest.saved");
1327
1328      // Emit the finally block.
1329      CGF.EmitStmt(Body);
1330
1331      // If the end of the finally is reachable, check whether this was
1332      // for EH.  If so, rethrow.
1333      if (CGF.HaveInsertPoint()) {
1334        llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
1335        llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
1336
1337        llvm::Value *ShouldRethrow =
1338          CGF.Builder.CreateLoad(ForEHVar, "finally.shouldthrow");
1339        CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1340
1341        CGF.EmitBlock(RethrowBB);
1342        if (SavedExnVar) {
1343          CGF.EmitCallOrInvoke(RethrowFn, CGF.Builder.CreateLoad(SavedExnVar));
1344        } else {
1345          CGF.EmitCallOrInvoke(RethrowFn);
1346        }
1347        CGF.Builder.CreateUnreachable();
1348
1349        CGF.EmitBlock(ContBB);
1350
1351        // Restore the cleanup destination.
1352        CGF.Builder.CreateStore(SavedCleanupDest,
1353                                CGF.getNormalCleanupDestSlot());
1354      }
1355
1356      // Leave the end-catch cleanup.  As an optimization, pretend that
1357      // the fallthrough path was inaccessible; we've dynamically proven
1358      // that we're not in the EH case along that path.
1359      if (EndCatchFn) {
1360        CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1361        CGF.PopCleanupBlock();
1362        CGF.Builder.restoreIP(SavedIP);
1363      }
1364
1365      // Now make sure we actually have an insertion point or the
1366      // cleanup gods will hate us.
1367      CGF.EnsureInsertPoint();
1368    }
1369  };
1370}
1371
1372/// Enters a finally block for an implementation using zero-cost
1373/// exceptions.  This is mostly general, but hard-codes some
1374/// language/ABI-specific behavior in the catch-all sections.
1375void CodeGenFunction::FinallyInfo::enter(CodeGenFunction &CGF,
1376                                         const Stmt *body,
1377                                         llvm::Constant *beginCatchFn,
1378                                         llvm::Constant *endCatchFn,
1379                                         llvm::Constant *rethrowFn) {
1380  assert((beginCatchFn != 0) == (endCatchFn != 0) &&
1381         "begin/end catch functions not paired");
1382  assert(rethrowFn && "rethrow function is required");
1383
1384  BeginCatchFn = beginCatchFn;
1385
1386  // The rethrow function has one of the following two types:
1387  //   void (*)()
1388  //   void (*)(void*)
1389  // In the latter case we need to pass it the exception object.
1390  // But we can't use the exception slot because the @finally might
1391  // have a landing pad (which would overwrite the exception slot).
1392  llvm::FunctionType *rethrowFnTy =
1393    cast<llvm::FunctionType>(
1394      cast<llvm::PointerType>(rethrowFn->getType())->getElementType());
1395  SavedExnVar = 0;
1396  if (rethrowFnTy->getNumParams())
1397    SavedExnVar = CGF.CreateTempAlloca(CGF.Int8PtrTy, "finally.exn");
1398
1399  // A finally block is a statement which must be executed on any edge
1400  // out of a given scope.  Unlike a cleanup, the finally block may
1401  // contain arbitrary control flow leading out of itself.  In
1402  // addition, finally blocks should always be executed, even if there
1403  // are no catch handlers higher on the stack.  Therefore, we
1404  // surround the protected scope with a combination of a normal
1405  // cleanup (to catch attempts to break out of the block via normal
1406  // control flow) and an EH catch-all (semantically "outside" any try
1407  // statement to which the finally block might have been attached).
1408  // The finally block itself is generated in the context of a cleanup
1409  // which conditionally leaves the catch-all.
1410
1411  // Jump destination for performing the finally block on an exception
1412  // edge.  We'll never actually reach this block, so unreachable is
1413  // fine.
1414  RethrowDest = CGF.getJumpDestInCurrentScope(CGF.getUnreachableBlock());
1415
1416  // Whether the finally block is being executed for EH purposes.
1417  ForEHVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "finally.for-eh");
1418  CGF.Builder.CreateStore(CGF.Builder.getFalse(), ForEHVar);
1419
1420  // Enter a normal cleanup which will perform the @finally block.
1421  CGF.EHStack.pushCleanup<PerformFinally>(NormalCleanup, body,
1422                                          ForEHVar, endCatchFn,
1423                                          rethrowFn, SavedExnVar);
1424
1425  // Enter a catch-all scope.
1426  llvm::BasicBlock *catchBB = CGF.createBasicBlock("finally.catchall");
1427  EHCatchScope *catchScope = CGF.EHStack.pushCatch(1);
1428  catchScope->setCatchAllHandler(0, catchBB);
1429}
1430
1431void CodeGenFunction::FinallyInfo::exit(CodeGenFunction &CGF) {
1432  // Leave the finally catch-all.
1433  EHCatchScope &catchScope = cast<EHCatchScope>(*CGF.EHStack.begin());
1434  llvm::BasicBlock *catchBB = catchScope.getHandler(0).Block;
1435
1436  CGF.popCatchScope();
1437
1438  // If there are any references to the catch-all block, emit it.
1439  if (catchBB->use_empty()) {
1440    delete catchBB;
1441  } else {
1442    CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveAndClearIP();
1443    CGF.EmitBlock(catchBB);
1444
1445    llvm::Value *exn = 0;
1446
1447    // If there's a begin-catch function, call it.
1448    if (BeginCatchFn) {
1449      exn = CGF.getExceptionFromSlot();
1450      CGF.Builder.CreateCall(BeginCatchFn, exn)->setDoesNotThrow();
1451    }
1452
1453    // If we need to remember the exception pointer to rethrow later, do so.
1454    if (SavedExnVar) {
1455      if (!exn) exn = CGF.getExceptionFromSlot();
1456      CGF.Builder.CreateStore(exn, SavedExnVar);
1457    }
1458
1459    // Tell the cleanups in the finally block that we're do this for EH.
1460    CGF.Builder.CreateStore(CGF.Builder.getTrue(), ForEHVar);
1461
1462    // Thread a jump through the finally cleanup.
1463    CGF.EmitBranchThroughCleanup(RethrowDest);
1464
1465    CGF.Builder.restoreIP(savedIP);
1466  }
1467
1468  // Finally, leave the @finally cleanup.
1469  CGF.PopCleanupBlock();
1470}
1471
1472llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
1473  if (TerminateLandingPad)
1474    return TerminateLandingPad;
1475
1476  CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1477
1478  // This will get inserted at the end of the function.
1479  TerminateLandingPad = createBasicBlock("terminate.lpad");
1480  Builder.SetInsertPoint(TerminateLandingPad);
1481
1482  // Tell the backend that this is a landing pad.
1483  const EHPersonality &Personality = EHPersonality::get(CGM.getLangOptions());
1484  llvm::LandingPadInst *LPadInst =
1485    Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, NULL),
1486                             getOpaquePersonalityFn(CGM, Personality), 0);
1487  LPadInst->addClause(getCatchAllValue(*this));
1488
1489  llvm::CallInst *TerminateCall = Builder.CreateCall(getTerminateFn(*this));
1490  TerminateCall->setDoesNotReturn();
1491  TerminateCall->setDoesNotThrow();
1492  Builder.CreateUnreachable();
1493
1494  // Restore the saved insertion state.
1495  Builder.restoreIP(SavedIP);
1496
1497  return TerminateLandingPad;
1498}
1499
1500llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
1501  if (TerminateHandler)
1502    return TerminateHandler;
1503
1504  CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1505
1506  // Set up the terminate handler.  This block is inserted at the very
1507  // end of the function by FinishFunction.
1508  TerminateHandler = createBasicBlock("terminate.handler");
1509  Builder.SetInsertPoint(TerminateHandler);
1510  llvm::CallInst *TerminateCall = Builder.CreateCall(getTerminateFn(*this));
1511  TerminateCall->setDoesNotReturn();
1512  TerminateCall->setDoesNotThrow();
1513  Builder.CreateUnreachable();
1514
1515  // Restore the saved insertion state.
1516  Builder.restoreIP(SavedIP);
1517
1518  return TerminateHandler;
1519}
1520
1521llvm::BasicBlock *CodeGenFunction::getEHResumeBlock() {
1522  if (EHResumeBlock) return EHResumeBlock;
1523
1524  CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1525
1526  // We emit a jump to a notional label at the outermost unwind state.
1527  EHResumeBlock = createBasicBlock("eh.resume");
1528  Builder.SetInsertPoint(EHResumeBlock);
1529
1530  const EHPersonality &Personality = EHPersonality::get(CGM.getLangOptions());
1531
1532  // This can always be a call because we necessarily didn't find
1533  // anything on the EH stack which needs our help.
1534  StringRef RethrowName = Personality.getCatchallRethrowFnName();
1535  if (!RethrowName.empty()) {
1536    Builder.CreateCall(getCatchallRethrowFn(*this, RethrowName),
1537                       getExceptionFromSlot())
1538      ->setDoesNotReturn();
1539  } else {
1540    switch (CleanupHackLevel) {
1541    case CHL_MandatoryCatchall:
1542      // In mandatory-catchall mode, we need to use
1543      // _Unwind_Resume_or_Rethrow, or whatever the personality's
1544      // equivalent is.
1545      Builder.CreateCall(getUnwindResumeOrRethrowFn(),
1546                         getExceptionFromSlot())
1547        ->setDoesNotReturn();
1548      break;
1549    case CHL_MandatoryCleanup: {
1550      // In mandatory-cleanup mode, we should use 'resume'.
1551
1552      // Recreate the landingpad's return value for the 'resume' instruction.
1553      llvm::Value *Exn = getExceptionFromSlot();
1554      llvm::Value *Sel = getSelectorFromSlot();
1555
1556      llvm::Type *LPadType = llvm::StructType::get(Exn->getType(),
1557                                                   Sel->getType(), NULL);
1558      llvm::Value *LPadVal = llvm::UndefValue::get(LPadType);
1559      LPadVal = Builder.CreateInsertValue(LPadVal, Exn, 0, "lpad.val");
1560      LPadVal = Builder.CreateInsertValue(LPadVal, Sel, 1, "lpad.val");
1561
1562      Builder.CreateResume(LPadVal);
1563      Builder.restoreIP(SavedIP);
1564      return EHResumeBlock;
1565    }
1566    case CHL_Ideal:
1567      // In an idealized mode where we don't have to worry about the
1568      // optimizer combining landing pads, we should just use
1569      // _Unwind_Resume (or the personality's equivalent).
1570      Builder.CreateCall(getUnwindResumeFn(), getExceptionFromSlot())
1571        ->setDoesNotReturn();
1572      break;
1573    }
1574  }
1575
1576  Builder.CreateUnreachable();
1577
1578  Builder.restoreIP(SavedIP);
1579
1580  return EHResumeBlock;
1581}
1582