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