CGException.cpp revision da549e8995c447542d5631b8b67fcc3a9582797a
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 selector call.
243    if (!isa<llvm::EHSelectorInst>(User)) return false;
244
245    llvm::EHSelectorInst *Selector = cast<llvm::EHSelectorInst>(User);
246    for (unsigned I = 2, E = Selector->getNumArgOperands(); I != E; ++I) {
247      // Look for something that would've been returned by the ObjC
248      // runtime's GetEHType() method.
249      llvm::GlobalVariable *GV
250        = dyn_cast<llvm::GlobalVariable>(Selector->getArgOperand(I));
251      if (!GV) continue;
252
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    }
258  }
259
260  return true;
261}
262
263/// Try to use the C++ personality function in ObjC++.  Not doing this
264/// can cause some incompatibilities with gcc, which is more
265/// aggressive about only using the ObjC++ personality in a function
266/// when it really needs it.
267void CodeGenModule::SimplifyPersonality() {
268  // For now, this is really a Darwin-specific operation.
269  if (!Context.Target.getTriple().isOSDarwin())
270    return;
271
272  // If we're not in ObjC++ -fexceptions, there's nothing to do.
273  if (!Features.CPlusPlus || !Features.ObjC1 || !Features.Exceptions)
274    return;
275
276  const EHPersonality &ObjCXX = EHPersonality::get(Features);
277  const EHPersonality &CXX = getCXXPersonality(Features);
278  if (&ObjCXX == &CXX ||
279      ObjCXX.getPersonalityFnName() == CXX.getPersonalityFnName())
280    return;
281
282  llvm::Function *Fn =
283    getModule().getFunction(ObjCXX.getPersonalityFnName());
284
285  // Nothing to do if it's unused.
286  if (!Fn || Fn->use_empty()) return;
287
288  // Can't do the optimization if it has non-C++ uses.
289  if (!PersonalityHasOnlyCXXUses(Fn)) return;
290
291  // Create the C++ personality function and kill off the old
292  // function.
293  llvm::Constant *CXXFn = getPersonalityFn(*this, CXX);
294
295  // This can happen if the user is screwing with us.
296  if (Fn->getType() != CXXFn->getType()) return;
297
298  Fn->replaceAllUsesWith(CXXFn);
299  Fn->eraseFromParent();
300}
301
302/// Returns the value to inject into a selector to indicate the
303/// presence of a catch-all.
304static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
305  // Possibly we should use @llvm.eh.catch.all.value here.
306  return llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
307}
308
309/// Returns the value to inject into a selector to indicate the
310/// presence of a cleanup.
311static llvm::Constant *getCleanupValue(CodeGenFunction &CGF) {
312  return llvm::ConstantInt::get(CGF.Builder.getInt32Ty(), 0);
313}
314
315namespace {
316  /// A cleanup to free the exception object if its initialization
317  /// throws.
318  struct FreeException : EHScopeStack::Cleanup {
319    llvm::Value *exn;
320    FreeException(llvm::Value *exn) : exn(exn) {}
321    void Emit(CodeGenFunction &CGF, Flags flags) {
322      CGF.Builder.CreateCall(getFreeExceptionFn(CGF), exn)
323        ->setDoesNotThrow();
324    }
325  };
326}
327
328// Emits an exception expression into the given location.  This
329// differs from EmitAnyExprToMem only in that, if a final copy-ctor
330// call is required, an exception within that copy ctor causes
331// std::terminate to be invoked.
332static void EmitAnyExprToExn(CodeGenFunction &CGF, const Expr *e,
333                             llvm::Value *addr) {
334  // Make sure the exception object is cleaned up if there's an
335  // exception during initialization.
336  CGF.pushFullExprCleanup<FreeException>(EHCleanup, addr);
337  EHScopeStack::stable_iterator cleanup = CGF.EHStack.stable_begin();
338
339  // __cxa_allocate_exception returns a void*;  we need to cast this
340  // to the appropriate type for the object.
341  llvm::Type *ty = CGF.ConvertTypeForMem(e->getType())->getPointerTo();
342  llvm::Value *typedAddr = CGF.Builder.CreateBitCast(addr, ty);
343
344  // FIXME: this isn't quite right!  If there's a final unelided call
345  // to a copy constructor, then according to [except.terminate]p1 we
346  // must call std::terminate() if that constructor throws, because
347  // technically that copy occurs after the exception expression is
348  // evaluated but before the exception is caught.  But the best way
349  // to handle that is to teach EmitAggExpr to do the final copy
350  // differently if it can't be elided.
351  CGF.EmitAnyExprToMem(e, typedAddr, e->getType().getQualifiers(),
352                       /*IsInit*/ true);
353
354  // Deactivate the cleanup block.
355  CGF.DeactivateCleanupBlock(cleanup);
356}
357
358llvm::Value *CodeGenFunction::getExceptionSlot() {
359  if (!ExceptionSlot)
360    ExceptionSlot = CreateTempAlloca(Int8PtrTy, "exn.slot");
361  return ExceptionSlot;
362}
363
364llvm::Value *CodeGenFunction::getEHSelectorSlot() {
365  if (!EHSelectorSlot)
366    EHSelectorSlot = CreateTempAlloca(Int32Ty, "ehselector.slot");
367  return EHSelectorSlot;
368}
369
370void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E) {
371  if (!E->getSubExpr()) {
372    if (getInvokeDest()) {
373      Builder.CreateInvoke(getReThrowFn(*this),
374                           getUnreachableBlock(),
375                           getInvokeDest())
376        ->setDoesNotReturn();
377    } else {
378      Builder.CreateCall(getReThrowFn(*this))->setDoesNotReturn();
379      Builder.CreateUnreachable();
380    }
381
382    // throw is an expression, and the expression emitters expect us
383    // to leave ourselves at a valid insertion point.
384    EmitBlock(createBasicBlock("throw.cont"));
385
386    return;
387  }
388
389  QualType ThrowType = E->getSubExpr()->getType();
390
391  // Now allocate the exception object.
392  llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
393  uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
394
395  llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(*this);
396  llvm::CallInst *ExceptionPtr =
397    Builder.CreateCall(AllocExceptionFn,
398                       llvm::ConstantInt::get(SizeTy, TypeSize),
399                       "exception");
400  ExceptionPtr->setDoesNotThrow();
401
402  EmitAnyExprToExn(*this, E->getSubExpr(), ExceptionPtr);
403
404  // Now throw the exception.
405  llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
406                                                         /*ForEH=*/true);
407
408  // The address of the destructor.  If the exception type has a
409  // trivial destructor (or isn't a record), we just pass null.
410  llvm::Constant *Dtor = 0;
411  if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
412    CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
413    if (!Record->hasTrivialDestructor()) {
414      CXXDestructorDecl *DtorD = Record->getDestructor();
415      Dtor = CGM.GetAddrOfCXXDestructor(DtorD, Dtor_Complete);
416      Dtor = llvm::ConstantExpr::getBitCast(Dtor, Int8PtrTy);
417    }
418  }
419  if (!Dtor) Dtor = llvm::Constant::getNullValue(Int8PtrTy);
420
421  if (getInvokeDest()) {
422    llvm::InvokeInst *ThrowCall =
423      Builder.CreateInvoke3(getThrowFn(*this),
424                            getUnreachableBlock(), getInvokeDest(),
425                            ExceptionPtr, TypeInfo, Dtor);
426    ThrowCall->setDoesNotReturn();
427  } else {
428    llvm::CallInst *ThrowCall =
429      Builder.CreateCall3(getThrowFn(*this), ExceptionPtr, TypeInfo, Dtor);
430    ThrowCall->setDoesNotReturn();
431    Builder.CreateUnreachable();
432  }
433
434  // throw is an expression, and the expression emitters expect us
435  // to leave ourselves at a valid insertion point.
436  EmitBlock(createBasicBlock("throw.cont"));
437}
438
439void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
440  if (!CGM.getLangOptions().CXXExceptions)
441    return;
442
443  const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
444  if (FD == 0)
445    return;
446  const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
447  if (Proto == 0)
448    return;
449
450  ExceptionSpecificationType EST = Proto->getExceptionSpecType();
451  if (isNoexceptExceptionSpec(EST)) {
452    if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
453      // noexcept functions are simple terminate scopes.
454      EHStack.pushTerminate();
455    }
456  } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
457    unsigned NumExceptions = Proto->getNumExceptions();
458    EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
459
460    for (unsigned I = 0; I != NumExceptions; ++I) {
461      QualType Ty = Proto->getExceptionType(I);
462      QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
463      llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType,
464                                                        /*ForEH=*/true);
465      Filter->setFilter(I, EHType);
466    }
467  }
468}
469
470void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
471  if (!CGM.getLangOptions().CXXExceptions)
472    return;
473
474  const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
475  if (FD == 0)
476    return;
477  const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
478  if (Proto == 0)
479    return;
480
481  ExceptionSpecificationType EST = Proto->getExceptionSpecType();
482  if (isNoexceptExceptionSpec(EST)) {
483    if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
484      EHStack.popTerminate();
485    }
486  } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
487    EHStack.popFilter();
488  }
489}
490
491void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
492  EnterCXXTryStmt(S);
493  EmitStmt(S.getTryBlock());
494  ExitCXXTryStmt(S);
495}
496
497void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
498  unsigned NumHandlers = S.getNumHandlers();
499  EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
500
501  for (unsigned I = 0; I != NumHandlers; ++I) {
502    const CXXCatchStmt *C = S.getHandler(I);
503
504    llvm::BasicBlock *Handler = createBasicBlock("catch");
505    if (C->getExceptionDecl()) {
506      // FIXME: Dropping the reference type on the type into makes it
507      // impossible to correctly implement catch-by-reference
508      // semantics for pointers.  Unfortunately, this is what all
509      // existing compilers do, and it's not clear that the standard
510      // personality routine is capable of doing this right.  See C++ DR 388:
511      //   http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
512      QualType CaughtType = C->getCaughtType();
513      CaughtType = CaughtType.getNonReferenceType().getUnqualifiedType();
514
515      llvm::Value *TypeInfo = 0;
516      if (CaughtType->isObjCObjectPointerType())
517        TypeInfo = CGM.getObjCRuntime().GetEHType(CaughtType);
518      else
519        TypeInfo = CGM.GetAddrOfRTTIDescriptor(CaughtType, /*ForEH=*/true);
520      CatchScope->setHandler(I, TypeInfo, Handler);
521    } else {
522      // No exception decl indicates '...', a catch-all.
523      CatchScope->setCatchAllHandler(I, Handler);
524    }
525  }
526}
527
528/// Check whether this is a non-EH scope, i.e. a scope which doesn't
529/// affect exception handling.  Currently, the only non-EH scopes are
530/// normal-only cleanup scopes.
531static bool isNonEHScope(const EHScope &S) {
532  switch (S.getKind()) {
533  case EHScope::Cleanup:
534    return !cast<EHCleanupScope>(S).isEHCleanup();
535  case EHScope::Filter:
536  case EHScope::Catch:
537  case EHScope::Terminate:
538    return false;
539  }
540
541  // Suppress warning.
542  return false;
543}
544
545llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
546  assert(EHStack.requiresLandingPad());
547  assert(!EHStack.empty());
548
549  if (!CGM.getLangOptions().Exceptions)
550    return 0;
551
552  // Check the innermost scope for a cached landing pad.  If this is
553  // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
554  llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
555  if (LP) return LP;
556
557  // Build the landing pad for this scope.
558  LP = EmitLandingPad();
559  assert(LP);
560
561  // Cache the landing pad on the innermost scope.  If this is a
562  // non-EH scope, cache the landing pad on the enclosing scope, too.
563  for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
564    ir->setCachedLandingPad(LP);
565    if (!isNonEHScope(*ir)) break;
566  }
567
568  return LP;
569}
570
571// This code contains a hack to work around a design flaw in
572// LLVM's EH IR which breaks semantics after inlining.  This same
573// hack is implemented in llvm-gcc.
574//
575// The LLVM EH abstraction is basically a thin veneer over the
576// traditional GCC zero-cost design: for each range of instructions
577// in the function, there is (at most) one "landing pad" with an
578// associated chain of EH actions.  A language-specific personality
579// function interprets this chain of actions and (1) decides whether
580// or not to resume execution at the landing pad and (2) if so,
581// provides an integer indicating why it's stopping.  In LLVM IR,
582// the association of a landing pad with a range of instructions is
583// achieved via an invoke instruction, the chain of actions becomes
584// the arguments to the @llvm.eh.selector call, and the selector
585// call returns the integer indicator.  Other than the required
586// presence of two intrinsic function calls in the landing pad,
587// the IR exactly describes the layout of the output code.
588//
589// A principal advantage of this design is that it is completely
590// language-agnostic; in theory, the LLVM optimizers can treat
591// landing pads neutrally, and targets need only know how to lower
592// the intrinsics to have a functioning exceptions system (assuming
593// that platform exceptions follow something approximately like the
594// GCC design).  Unfortunately, landing pads cannot be combined in a
595// language-agnostic way: given selectors A and B, there is no way
596// to make a single landing pad which faithfully represents the
597// semantics of propagating an exception first through A, then
598// through B, without knowing how the personality will interpret the
599// (lowered form of the) selectors.  This means that inlining has no
600// choice but to crudely chain invokes (i.e., to ignore invokes in
601// the inlined function, but to turn all unwindable calls into
602// invokes), which is only semantically valid if every unwind stops
603// at every landing pad.
604//
605// Therefore, the invoke-inline hack is to guarantee that every
606// landing pad has a catch-all.
607enum CleanupHackLevel_t {
608  /// A level of hack that requires that all landing pads have
609  /// catch-alls.
610  CHL_MandatoryCatchall,
611
612  /// A level of hack that requires that all landing pads handle
613  /// cleanups.
614  CHL_MandatoryCleanup,
615
616  /// No hacks at all;  ideal IR generation.
617  CHL_Ideal
618};
619const CleanupHackLevel_t CleanupHackLevel = CHL_MandatoryCleanup;
620
621llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
622  assert(EHStack.requiresLandingPad());
623
624  for (EHScopeStack::iterator ir = EHStack.begin(); ; ) {
625    assert(ir != EHStack.end() &&
626           "stack requiring landing pad is nothing but non-EH scopes?");
627
628    // If this is a terminate scope, just use the singleton terminate
629    // landing pad.
630    if (isa<EHTerminateScope>(*ir))
631      return getTerminateLandingPad();
632
633    // If this isn't an EH scope, iterate; otherwise break out.
634    if (!isNonEHScope(*ir)) break;
635    ++ir;
636
637    // We haven't checked this scope for a cached landing pad yet.
638    if (llvm::BasicBlock *LP = ir->getCachedLandingPad())
639      return LP;
640  }
641
642  // Save the current IR generation state.
643  CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
644
645  const EHPersonality &Personality = EHPersonality::get(getLangOptions());
646
647  // Create and configure the landing pad.
648  llvm::BasicBlock *LP = createBasicBlock("lpad");
649  EmitBlock(LP);
650
651  // Save the exception pointer.  It's safe to use a single exception
652  // pointer per function because EH cleanups can never have nested
653  // try/catches.
654  llvm::CallInst *Exn =
655    Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_exception), "exn");
656  Exn->setDoesNotThrow();
657  Builder.CreateStore(Exn, getExceptionSlot());
658
659  // Build the selector arguments.
660  SmallVector<llvm::Value*, 8> EHSelector;
661  EHSelector.push_back(Exn);
662  EHSelector.push_back(getOpaquePersonalityFn(CGM, Personality));
663
664  // Accumulate all the handlers in scope.
665  llvm::DenseMap<llvm::Value*, UnwindDest> EHHandlers;
666  UnwindDest CatchAll;
667  bool HasEHCleanup = false;
668  bool HasEHFilter = false;
669  SmallVector<llvm::Value*, 8> EHFilters;
670  for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end();
671         I != E; ++I) {
672
673    switch (I->getKind()) {
674    case EHScope::Cleanup:
675      if (!HasEHCleanup)
676        HasEHCleanup = cast<EHCleanupScope>(*I).isEHCleanup();
677      // We otherwise don't care about cleanups.
678      continue;
679
680    case EHScope::Filter: {
681      assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
682      assert(!CatchAll.isValid() && "EH filter reached after catch-all");
683
684      // Filter scopes get added to the selector in weird ways.
685      EHFilterScope &Filter = cast<EHFilterScope>(*I);
686      HasEHFilter = true;
687
688      // Add all the filter values which we aren't already explicitly
689      // catching.
690      for (unsigned I = 0, E = Filter.getNumFilters(); I != E; ++I) {
691        llvm::Value *FV = Filter.getFilter(I);
692        if (!EHHandlers.count(FV))
693          EHFilters.push_back(FV);
694      }
695      goto done;
696    }
697
698    case EHScope::Terminate:
699      // Terminate scopes are basically catch-alls.
700      assert(!CatchAll.isValid());
701      CatchAll = UnwindDest(getTerminateHandler(),
702                            EHStack.getEnclosingEHCleanup(I),
703                            cast<EHTerminateScope>(*I).getDestIndex());
704      goto done;
705
706    case EHScope::Catch:
707      break;
708    }
709
710    EHCatchScope &Catch = cast<EHCatchScope>(*I);
711    for (unsigned HI = 0, HE = Catch.getNumHandlers(); HI != HE; ++HI) {
712      EHCatchScope::Handler Handler = Catch.getHandler(HI);
713
714      // Catch-all.  We should only have one of these per catch.
715      if (!Handler.Type) {
716        assert(!CatchAll.isValid());
717        CatchAll = UnwindDest(Handler.Block,
718                              EHStack.getEnclosingEHCleanup(I),
719                              Handler.Index);
720        continue;
721      }
722
723      // Check whether we already have a handler for this type.
724      UnwindDest &Dest = EHHandlers[Handler.Type];
725      if (Dest.isValid()) continue;
726
727      EHSelector.push_back(Handler.Type);
728      Dest = UnwindDest(Handler.Block,
729                        EHStack.getEnclosingEHCleanup(I),
730                        Handler.Index);
731    }
732
733    // Stop if we found a catch-all.
734    if (CatchAll.isValid()) break;
735  }
736
737 done:
738  unsigned LastToEmitInLoop = EHSelector.size();
739
740  // If we have a catch-all, add null to the selector.
741  if (CatchAll.isValid()) {
742    EHSelector.push_back(getCatchAllValue(*this));
743
744  // If we have an EH filter, we need to add those handlers in the
745  // right place in the selector, which is to say, at the end.
746  } else if (HasEHFilter) {
747    // Create a filter expression: an integer constant saying how many
748    // filters there are (+1 to avoid ambiguity with 0 for cleanup),
749    // followed by the filter types.  The personality routine only
750    // lands here if the filter doesn't match.
751    EHSelector.push_back(llvm::ConstantInt::get(Builder.getInt32Ty(),
752                                                EHFilters.size() + 1));
753    EHSelector.append(EHFilters.begin(), EHFilters.end());
754
755    // Also check whether we need a cleanup.
756    if (CleanupHackLevel == CHL_MandatoryCatchall || HasEHCleanup)
757      EHSelector.push_back(CleanupHackLevel == CHL_MandatoryCatchall
758                           ? getCatchAllValue(*this)
759                           : getCleanupValue(*this));
760
761  // Otherwise, signal that we at least have cleanups.
762  } else if (CleanupHackLevel == CHL_MandatoryCatchall || HasEHCleanup) {
763    EHSelector.push_back(CleanupHackLevel == CHL_MandatoryCatchall
764                         ? getCatchAllValue(*this)
765                         : getCleanupValue(*this));
766
767  // At the MandatoryCleanup hack level, we don't need to actually
768  // spuriously tell the unwinder that we have cleanups, but we do
769  // need to always be prepared to handle cleanups.
770  } else if (CleanupHackLevel == CHL_MandatoryCleanup) {
771    // Just don't decrement LastToEmitInLoop.
772
773  } else {
774    assert(LastToEmitInLoop > 2);
775    LastToEmitInLoop--;
776  }
777
778  assert(EHSelector.size() >= 3 && "selector call has only two arguments!");
779
780  // Tell the backend how to generate the landing pad.
781  llvm::CallInst *Selection =
782    Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_selector),
783                       EHSelector, "eh.selector");
784  Selection->setDoesNotThrow();
785
786  // Save the selector value in mandatory-cleanup mode.
787  if (CleanupHackLevel == CHL_MandatoryCleanup)
788    Builder.CreateStore(Selection, getEHSelectorSlot());
789
790  // Select the right handler.
791  llvm::Value *llvm_eh_typeid_for =
792    CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
793
794  // The results of llvm_eh_typeid_for aren't reliable --- at least
795  // not locally --- so we basically have to do this as an 'if' chain.
796  // We walk through the first N-1 catch clauses, testing and chaining,
797  // and then fall into the final clause (which is either a cleanup, a
798  // filter (possibly with a cleanup), a catch-all, or another catch).
799  for (unsigned I = 2; I != LastToEmitInLoop; ++I) {
800    llvm::Value *Type = EHSelector[I];
801    UnwindDest Dest = EHHandlers[Type];
802    assert(Dest.isValid() && "no handler entry for value in selector?");
803
804    // Figure out where to branch on a match.  As a debug code-size
805    // optimization, if the scope depth matches the innermost cleanup,
806    // we branch directly to the catch handler.
807    llvm::BasicBlock *Match = Dest.getBlock();
808    bool MatchNeedsCleanup =
809      Dest.getScopeDepth() != EHStack.getInnermostEHCleanup();
810    if (MatchNeedsCleanup)
811      Match = createBasicBlock("eh.match");
812
813    llvm::BasicBlock *Next = createBasicBlock("eh.next");
814
815    // Check whether the exception matches.
816    llvm::CallInst *Id
817      = Builder.CreateCall(llvm_eh_typeid_for,
818                           Builder.CreateBitCast(Type, Int8PtrTy));
819    Id->setDoesNotThrow();
820    Builder.CreateCondBr(Builder.CreateICmpEQ(Selection, Id),
821                         Match, Next);
822
823    // Emit match code if necessary.
824    if (MatchNeedsCleanup) {
825      EmitBlock(Match);
826      EmitBranchThroughEHCleanup(Dest);
827    }
828
829    // Continue to the next match.
830    EmitBlock(Next);
831  }
832
833  // Emit the final case in the selector.
834  // This might be a catch-all....
835  if (CatchAll.isValid()) {
836    assert(isa<llvm::ConstantPointerNull>(EHSelector.back()));
837    EmitBranchThroughEHCleanup(CatchAll);
838
839  // ...or an EH filter...
840  } else if (HasEHFilter) {
841    llvm::Value *SavedSelection = Selection;
842
843    // First, unwind out to the outermost scope if necessary.
844    if (EHStack.hasEHCleanups()) {
845      // The end here might not dominate the beginning, so we might need to
846      // save the selector if we need it.
847      llvm::AllocaInst *SelectorVar = 0;
848      if (HasEHCleanup) {
849        SelectorVar = CreateTempAlloca(Builder.getInt32Ty(), "selector.var");
850        Builder.CreateStore(Selection, SelectorVar);
851      }
852
853      llvm::BasicBlock *CleanupContBB = createBasicBlock("ehspec.cleanup.cont");
854      EmitBranchThroughEHCleanup(UnwindDest(CleanupContBB, EHStack.stable_end(),
855                                            EHStack.getNextEHDestIndex()));
856      EmitBlock(CleanupContBB);
857
858      if (HasEHCleanup)
859        SavedSelection = Builder.CreateLoad(SelectorVar, "ehspec.saved-selector");
860    }
861
862    // If there was a cleanup, we'll need to actually check whether we
863    // landed here because the filter triggered.
864    if (CleanupHackLevel != CHL_Ideal || HasEHCleanup) {
865      llvm::BasicBlock *UnexpectedBB = createBasicBlock("ehspec.unexpected");
866
867      llvm::Constant *Zero = llvm::ConstantInt::get(Int32Ty, 0);
868      llvm::Value *FailsFilter =
869        Builder.CreateICmpSLT(SavedSelection, Zero, "ehspec.fails");
870      Builder.CreateCondBr(FailsFilter, UnexpectedBB, getRethrowDest().getBlock());
871
872      EmitBlock(UnexpectedBB);
873    }
874
875    // Call __cxa_call_unexpected.  This doesn't need to be an invoke
876    // because __cxa_call_unexpected magically filters exceptions
877    // according to the last landing pad the exception was thrown
878    // into.  Seriously.
879    Builder.CreateCall(getUnexpectedFn(*this),
880                       Builder.CreateLoad(getExceptionSlot()))
881      ->setDoesNotReturn();
882    Builder.CreateUnreachable();
883
884  // ...or a normal catch handler...
885  } else if (CleanupHackLevel == CHL_Ideal && !HasEHCleanup) {
886    llvm::Value *Type = EHSelector.back();
887    EmitBranchThroughEHCleanup(EHHandlers[Type]);
888
889  // ...or a cleanup.
890  } else {
891    EmitBranchThroughEHCleanup(getRethrowDest());
892  }
893
894  // Restore the old IR generation state.
895  Builder.restoreIP(SavedIP);
896
897  return LP;
898}
899
900namespace {
901  /// A cleanup to call __cxa_end_catch.  In many cases, the caught
902  /// exception type lets us state definitively that the thrown exception
903  /// type does not have a destructor.  In particular:
904  ///   - Catch-alls tell us nothing, so we have to conservatively
905  ///     assume that the thrown exception might have a destructor.
906  ///   - Catches by reference behave according to their base types.
907  ///   - Catches of non-record types will only trigger for exceptions
908  ///     of non-record types, which never have destructors.
909  ///   - Catches of record types can trigger for arbitrary subclasses
910  ///     of the caught type, so we have to assume the actual thrown
911  ///     exception type might have a throwing destructor, even if the
912  ///     caught type's destructor is trivial or nothrow.
913  struct CallEndCatch : EHScopeStack::Cleanup {
914    CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
915    bool MightThrow;
916
917    void Emit(CodeGenFunction &CGF, Flags flags) {
918      if (!MightThrow) {
919        CGF.Builder.CreateCall(getEndCatchFn(CGF))->setDoesNotThrow();
920        return;
921      }
922
923      CGF.EmitCallOrInvoke(getEndCatchFn(CGF));
924    }
925  };
926}
927
928/// Emits a call to __cxa_begin_catch and enters a cleanup to call
929/// __cxa_end_catch.
930///
931/// \param EndMightThrow - true if __cxa_end_catch might throw
932static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
933                                   llvm::Value *Exn,
934                                   bool EndMightThrow) {
935  llvm::CallInst *Call = CGF.Builder.CreateCall(getBeginCatchFn(CGF), Exn);
936  Call->setDoesNotThrow();
937
938  CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
939
940  return Call;
941}
942
943/// A "special initializer" callback for initializing a catch
944/// parameter during catch initialization.
945static void InitCatchParam(CodeGenFunction &CGF,
946                           const VarDecl &CatchParam,
947                           llvm::Value *ParamAddr) {
948  // Load the exception from where the landing pad saved it.
949  llvm::Value *Exn = CGF.Builder.CreateLoad(CGF.getExceptionSlot(), "exn");
950
951  CanQualType CatchType =
952    CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
953  llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
954
955  // If we're catching by reference, we can just cast the object
956  // pointer to the appropriate pointer.
957  if (isa<ReferenceType>(CatchType)) {
958    QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
959    bool EndCatchMightThrow = CaughtType->isRecordType();
960
961    // __cxa_begin_catch returns the adjusted object pointer.
962    llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
963
964    // We have no way to tell the personality function that we're
965    // catching by reference, so if we're catching a pointer,
966    // __cxa_begin_catch will actually return that pointer by value.
967    if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
968      QualType PointeeType = PT->getPointeeType();
969
970      // When catching by reference, generally we should just ignore
971      // this by-value pointer and use the exception object instead.
972      if (!PointeeType->isRecordType()) {
973
974        // Exn points to the struct _Unwind_Exception header, which
975        // we have to skip past in order to reach the exception data.
976        unsigned HeaderSize =
977          CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
978        AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
979
980      // However, if we're catching a pointer-to-record type that won't
981      // work, because the personality function might have adjusted
982      // the pointer.  There's actually no way for us to fully satisfy
983      // the language/ABI contract here:  we can't use Exn because it
984      // might have the wrong adjustment, but we can't use the by-value
985      // pointer because it's off by a level of abstraction.
986      //
987      // The current solution is to dump the adjusted pointer into an
988      // alloca, which breaks language semantics (because changing the
989      // pointer doesn't change the exception) but at least works.
990      // The better solution would be to filter out non-exact matches
991      // and rethrow them, but this is tricky because the rethrow
992      // really needs to be catchable by other sites at this landing
993      // pad.  The best solution is to fix the personality function.
994      } else {
995        // Pull the pointer for the reference type off.
996        llvm::Type *PtrTy =
997          cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
998
999        // Create the temporary and write the adjusted pointer into it.
1000        llvm::Value *ExnPtrTmp = CGF.CreateTempAlloca(PtrTy, "exn.byref.tmp");
1001        llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1002        CGF.Builder.CreateStore(Casted, ExnPtrTmp);
1003
1004        // Bind the reference to the temporary.
1005        AdjustedExn = ExnPtrTmp;
1006      }
1007    }
1008
1009    llvm::Value *ExnCast =
1010      CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
1011    CGF.Builder.CreateStore(ExnCast, ParamAddr);
1012    return;
1013  }
1014
1015  // Non-aggregates (plus complexes).
1016  bool IsComplex = false;
1017  if (!CGF.hasAggregateLLVMType(CatchType) ||
1018      (IsComplex = CatchType->isAnyComplexType())) {
1019    llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
1020
1021    // If the catch type is a pointer type, __cxa_begin_catch returns
1022    // the pointer by value.
1023    if (CatchType->hasPointerRepresentation()) {
1024      llvm::Value *CastExn =
1025        CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
1026      CGF.Builder.CreateStore(CastExn, ParamAddr);
1027      return;
1028    }
1029
1030    // Otherwise, it returns a pointer into the exception object.
1031
1032    llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
1033    llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1034
1035    if (IsComplex) {
1036      CGF.StoreComplexToAddr(CGF.LoadComplexFromAddr(Cast, /*volatile*/ false),
1037                             ParamAddr, /*volatile*/ false);
1038    } else {
1039      unsigned Alignment =
1040        CGF.getContext().getDeclAlign(&CatchParam).getQuantity();
1041      llvm::Value *ExnLoad = CGF.Builder.CreateLoad(Cast, "exn.scalar");
1042      CGF.EmitStoreOfScalar(ExnLoad, ParamAddr, /*volatile*/ false, Alignment,
1043                            CatchType);
1044    }
1045    return;
1046  }
1047
1048  assert(isa<RecordType>(CatchType) && "unexpected catch type!");
1049
1050  llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
1051
1052  // Check for a copy expression.  If we don't have a copy expression,
1053  // that means a trivial copy is okay.
1054  const Expr *copyExpr = CatchParam.getInit();
1055  if (!copyExpr) {
1056    llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
1057    llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
1058    CGF.EmitAggregateCopy(ParamAddr, adjustedExn, CatchType);
1059    return;
1060  }
1061
1062  // We have to call __cxa_get_exception_ptr to get the adjusted
1063  // pointer before copying.
1064  llvm::CallInst *rawAdjustedExn =
1065    CGF.Builder.CreateCall(getGetExceptionPtrFn(CGF), Exn);
1066  rawAdjustedExn->setDoesNotThrow();
1067
1068  // Cast that to the appropriate type.
1069  llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
1070
1071  // The copy expression is defined in terms of an OpaqueValueExpr.
1072  // Find it and map it to the adjusted expression.
1073  CodeGenFunction::OpaqueValueMapping
1074    opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
1075           CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
1076
1077  // Call the copy ctor in a terminate scope.
1078  CGF.EHStack.pushTerminate();
1079
1080  // Perform the copy construction.
1081  CGF.EmitAggExpr(copyExpr, AggValueSlot::forAddr(ParamAddr, Qualifiers(),
1082                                                  false));
1083
1084  // Leave the terminate scope.
1085  CGF.EHStack.popTerminate();
1086
1087  // Undo the opaque value mapping.
1088  opaque.pop();
1089
1090  // Finally we can call __cxa_begin_catch.
1091  CallBeginCatch(CGF, Exn, true);
1092}
1093
1094/// Begins a catch statement by initializing the catch variable and
1095/// calling __cxa_begin_catch.
1096static void BeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *S) {
1097  // We have to be very careful with the ordering of cleanups here:
1098  //   C++ [except.throw]p4:
1099  //     The destruction [of the exception temporary] occurs
1100  //     immediately after the destruction of the object declared in
1101  //     the exception-declaration in the handler.
1102  //
1103  // So the precise ordering is:
1104  //   1.  Construct catch variable.
1105  //   2.  __cxa_begin_catch
1106  //   3.  Enter __cxa_end_catch cleanup
1107  //   4.  Enter dtor cleanup
1108  //
1109  // We do this by using a slightly abnormal initialization process.
1110  // Delegation sequence:
1111  //   - ExitCXXTryStmt opens a RunCleanupsScope
1112  //     - EmitAutoVarAlloca creates the variable and debug info
1113  //       - InitCatchParam initializes the variable from the exception
1114  //       - CallBeginCatch calls __cxa_begin_catch
1115  //       - CallBeginCatch enters the __cxa_end_catch cleanup
1116  //     - EmitAutoVarCleanups enters the variable destructor cleanup
1117  //   - EmitCXXTryStmt emits the code for the catch body
1118  //   - EmitCXXTryStmt close the RunCleanupsScope
1119
1120  VarDecl *CatchParam = S->getExceptionDecl();
1121  if (!CatchParam) {
1122    llvm::Value *Exn = CGF.Builder.CreateLoad(CGF.getExceptionSlot(), "exn");
1123    CallBeginCatch(CGF, Exn, true);
1124    return;
1125  }
1126
1127  // Emit the local.
1128  CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
1129  InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF));
1130  CGF.EmitAutoVarCleanups(var);
1131}
1132
1133namespace {
1134  struct CallRethrow : EHScopeStack::Cleanup {
1135    void Emit(CodeGenFunction &CGF, Flags flags) {
1136      CGF.EmitCallOrInvoke(getReThrowFn(CGF));
1137    }
1138  };
1139}
1140
1141void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
1142  unsigned NumHandlers = S.getNumHandlers();
1143  EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1144  assert(CatchScope.getNumHandlers() == NumHandlers);
1145
1146  // Copy the handler blocks off before we pop the EH stack.  Emitting
1147  // the handlers might scribble on this memory.
1148  SmallVector<EHCatchScope::Handler, 8> Handlers(NumHandlers);
1149  memcpy(Handlers.data(), CatchScope.begin(),
1150         NumHandlers * sizeof(EHCatchScope::Handler));
1151  EHStack.popCatch();
1152
1153  // The fall-through block.
1154  llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
1155
1156  // We just emitted the body of the try; jump to the continue block.
1157  if (HaveInsertPoint())
1158    Builder.CreateBr(ContBB);
1159
1160  // Determine if we need an implicit rethrow for all these catch handlers.
1161  bool ImplicitRethrow = false;
1162  if (IsFnTryBlock)
1163    ImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
1164                      isa<CXXConstructorDecl>(CurCodeDecl);
1165
1166  for (unsigned I = 0; I != NumHandlers; ++I) {
1167    llvm::BasicBlock *CatchBlock = Handlers[I].Block;
1168    EmitBlock(CatchBlock);
1169
1170    // Catch the exception if this isn't a catch-all.
1171    const CXXCatchStmt *C = S.getHandler(I);
1172
1173    // Enter a cleanup scope, including the catch variable and the
1174    // end-catch.
1175    RunCleanupsScope CatchScope(*this);
1176
1177    // Initialize the catch variable and set up the cleanups.
1178    BeginCatch(*this, C);
1179
1180    // If there's an implicit rethrow, push a normal "cleanup" to call
1181    // _cxa_rethrow.  This needs to happen before __cxa_end_catch is
1182    // called, and so it is pushed after BeginCatch.
1183    if (ImplicitRethrow)
1184      EHStack.pushCleanup<CallRethrow>(NormalCleanup);
1185
1186    // Perform the body of the catch.
1187    EmitStmt(C->getHandlerBlock());
1188
1189    // Fall out through the catch cleanups.
1190    CatchScope.ForceCleanup();
1191
1192    // Branch out of the try.
1193    if (HaveInsertPoint())
1194      Builder.CreateBr(ContBB);
1195  }
1196
1197  EmitBlock(ContBB);
1198}
1199
1200namespace {
1201  struct CallEndCatchForFinally : EHScopeStack::Cleanup {
1202    llvm::Value *ForEHVar;
1203    llvm::Value *EndCatchFn;
1204    CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn)
1205      : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
1206
1207    void Emit(CodeGenFunction &CGF, Flags flags) {
1208      llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
1209      llvm::BasicBlock *CleanupContBB =
1210        CGF.createBasicBlock("finally.cleanup.cont");
1211
1212      llvm::Value *ShouldEndCatch =
1213        CGF.Builder.CreateLoad(ForEHVar, "finally.endcatch");
1214      CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1215      CGF.EmitBlock(EndCatchBB);
1216      CGF.EmitCallOrInvoke(EndCatchFn); // catch-all, so might throw
1217      CGF.EmitBlock(CleanupContBB);
1218    }
1219  };
1220
1221  struct PerformFinally : EHScopeStack::Cleanup {
1222    const Stmt *Body;
1223    llvm::Value *ForEHVar;
1224    llvm::Value *EndCatchFn;
1225    llvm::Value *RethrowFn;
1226    llvm::Value *SavedExnVar;
1227
1228    PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
1229                   llvm::Value *EndCatchFn,
1230                   llvm::Value *RethrowFn, llvm::Value *SavedExnVar)
1231      : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1232        RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
1233
1234    void Emit(CodeGenFunction &CGF, Flags flags) {
1235      // Enter a cleanup to call the end-catch function if one was provided.
1236      if (EndCatchFn)
1237        CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
1238                                                        ForEHVar, EndCatchFn);
1239
1240      // Save the current cleanup destination in case there are
1241      // cleanups in the finally block.
1242      llvm::Value *SavedCleanupDest =
1243        CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
1244                               "cleanup.dest.saved");
1245
1246      // Emit the finally block.
1247      CGF.EmitStmt(Body);
1248
1249      // If the end of the finally is reachable, check whether this was
1250      // for EH.  If so, rethrow.
1251      if (CGF.HaveInsertPoint()) {
1252        llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
1253        llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
1254
1255        llvm::Value *ShouldRethrow =
1256          CGF.Builder.CreateLoad(ForEHVar, "finally.shouldthrow");
1257        CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1258
1259        CGF.EmitBlock(RethrowBB);
1260        if (SavedExnVar) {
1261          CGF.EmitCallOrInvoke(RethrowFn, CGF.Builder.CreateLoad(SavedExnVar));
1262        } else {
1263          CGF.EmitCallOrInvoke(RethrowFn);
1264        }
1265        CGF.Builder.CreateUnreachable();
1266
1267        CGF.EmitBlock(ContBB);
1268
1269        // Restore the cleanup destination.
1270        CGF.Builder.CreateStore(SavedCleanupDest,
1271                                CGF.getNormalCleanupDestSlot());
1272      }
1273
1274      // Leave the end-catch cleanup.  As an optimization, pretend that
1275      // the fallthrough path was inaccessible; we've dynamically proven
1276      // that we're not in the EH case along that path.
1277      if (EndCatchFn) {
1278        CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1279        CGF.PopCleanupBlock();
1280        CGF.Builder.restoreIP(SavedIP);
1281      }
1282
1283      // Now make sure we actually have an insertion point or the
1284      // cleanup gods will hate us.
1285      CGF.EnsureInsertPoint();
1286    }
1287  };
1288}
1289
1290/// Enters a finally block for an implementation using zero-cost
1291/// exceptions.  This is mostly general, but hard-codes some
1292/// language/ABI-specific behavior in the catch-all sections.
1293void CodeGenFunction::FinallyInfo::enter(CodeGenFunction &CGF,
1294                                         const Stmt *body,
1295                                         llvm::Constant *beginCatchFn,
1296                                         llvm::Constant *endCatchFn,
1297                                         llvm::Constant *rethrowFn) {
1298  assert((beginCatchFn != 0) == (endCatchFn != 0) &&
1299         "begin/end catch functions not paired");
1300  assert(rethrowFn && "rethrow function is required");
1301
1302  BeginCatchFn = beginCatchFn;
1303
1304  // The rethrow function has one of the following two types:
1305  //   void (*)()
1306  //   void (*)(void*)
1307  // In the latter case we need to pass it the exception object.
1308  // But we can't use the exception slot because the @finally might
1309  // have a landing pad (which would overwrite the exception slot).
1310  llvm::FunctionType *rethrowFnTy =
1311    cast<llvm::FunctionType>(
1312      cast<llvm::PointerType>(rethrowFn->getType())->getElementType());
1313  SavedExnVar = 0;
1314  if (rethrowFnTy->getNumParams())
1315    SavedExnVar = CGF.CreateTempAlloca(CGF.Int8PtrTy, "finally.exn");
1316
1317  // A finally block is a statement which must be executed on any edge
1318  // out of a given scope.  Unlike a cleanup, the finally block may
1319  // contain arbitrary control flow leading out of itself.  In
1320  // addition, finally blocks should always be executed, even if there
1321  // are no catch handlers higher on the stack.  Therefore, we
1322  // surround the protected scope with a combination of a normal
1323  // cleanup (to catch attempts to break out of the block via normal
1324  // control flow) and an EH catch-all (semantically "outside" any try
1325  // statement to which the finally block might have been attached).
1326  // The finally block itself is generated in the context of a cleanup
1327  // which conditionally leaves the catch-all.
1328
1329  // Jump destination for performing the finally block on an exception
1330  // edge.  We'll never actually reach this block, so unreachable is
1331  // fine.
1332  RethrowDest = CGF.getJumpDestInCurrentScope(CGF.getUnreachableBlock());
1333
1334  // Whether the finally block is being executed for EH purposes.
1335  ForEHVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "finally.for-eh");
1336  CGF.Builder.CreateStore(CGF.Builder.getFalse(), ForEHVar);
1337
1338  // Enter a normal cleanup which will perform the @finally block.
1339  CGF.EHStack.pushCleanup<PerformFinally>(NormalCleanup, body,
1340                                          ForEHVar, endCatchFn,
1341                                          rethrowFn, SavedExnVar);
1342
1343  // Enter a catch-all scope.
1344  llvm::BasicBlock *catchBB = CGF.createBasicBlock("finally.catchall");
1345  EHCatchScope *catchScope = CGF.EHStack.pushCatch(1);
1346  catchScope->setCatchAllHandler(0, catchBB);
1347}
1348
1349void CodeGenFunction::FinallyInfo::exit(CodeGenFunction &CGF) {
1350  // Leave the finally catch-all.
1351  EHCatchScope &catchScope = cast<EHCatchScope>(*CGF.EHStack.begin());
1352  llvm::BasicBlock *catchBB = catchScope.getHandler(0).Block;
1353  CGF.EHStack.popCatch();
1354
1355  // If there are any references to the catch-all block, emit it.
1356  if (catchBB->use_empty()) {
1357    delete catchBB;
1358  } else {
1359    CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveAndClearIP();
1360    CGF.EmitBlock(catchBB);
1361
1362    llvm::Value *exn = 0;
1363
1364    // If there's a begin-catch function, call it.
1365    if (BeginCatchFn) {
1366      exn = CGF.Builder.CreateLoad(CGF.getExceptionSlot());
1367      CGF.Builder.CreateCall(BeginCatchFn, exn)->setDoesNotThrow();
1368    }
1369
1370    // If we need to remember the exception pointer to rethrow later, do so.
1371    if (SavedExnVar) {
1372      if (!exn) exn = CGF.Builder.CreateLoad(CGF.getExceptionSlot());
1373      CGF.Builder.CreateStore(exn, SavedExnVar);
1374    }
1375
1376    // Tell the cleanups in the finally block that we're do this for EH.
1377    CGF.Builder.CreateStore(CGF.Builder.getTrue(), ForEHVar);
1378
1379    // Thread a jump through the finally cleanup.
1380    CGF.EmitBranchThroughCleanup(RethrowDest);
1381
1382    CGF.Builder.restoreIP(savedIP);
1383  }
1384
1385  // Finally, leave the @finally cleanup.
1386  CGF.PopCleanupBlock();
1387}
1388
1389llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
1390  if (TerminateLandingPad)
1391    return TerminateLandingPad;
1392
1393  CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1394
1395  // This will get inserted at the end of the function.
1396  TerminateLandingPad = createBasicBlock("terminate.lpad");
1397  Builder.SetInsertPoint(TerminateLandingPad);
1398
1399  // Tell the backend that this is a landing pad.
1400  llvm::CallInst *Exn =
1401    Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_exception), "exn");
1402  Exn->setDoesNotThrow();
1403
1404  const EHPersonality &Personality = EHPersonality::get(CGM.getLangOptions());
1405
1406  // Tell the backend what the exception table should be:
1407  // nothing but a catch-all.
1408  llvm::Value *Args[3] = { Exn, getOpaquePersonalityFn(CGM, Personality),
1409                           getCatchAllValue(*this) };
1410  Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_selector),
1411                     Args, "eh.selector")
1412    ->setDoesNotThrow();
1413
1414  llvm::CallInst *TerminateCall = Builder.CreateCall(getTerminateFn(*this));
1415  TerminateCall->setDoesNotReturn();
1416  TerminateCall->setDoesNotThrow();
1417  Builder.CreateUnreachable();
1418
1419  // Restore the saved insertion state.
1420  Builder.restoreIP(SavedIP);
1421
1422  return TerminateLandingPad;
1423}
1424
1425llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
1426  if (TerminateHandler)
1427    return TerminateHandler;
1428
1429  CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1430
1431  // Set up the terminate handler.  This block is inserted at the very
1432  // end of the function by FinishFunction.
1433  TerminateHandler = createBasicBlock("terminate.handler");
1434  Builder.SetInsertPoint(TerminateHandler);
1435  llvm::CallInst *TerminateCall = Builder.CreateCall(getTerminateFn(*this));
1436  TerminateCall->setDoesNotReturn();
1437  TerminateCall->setDoesNotThrow();
1438  Builder.CreateUnreachable();
1439
1440  // Restore the saved insertion state.
1441  Builder.restoreIP(SavedIP);
1442
1443  return TerminateHandler;
1444}
1445
1446CodeGenFunction::UnwindDest CodeGenFunction::getRethrowDest() {
1447  if (RethrowBlock.isValid()) return RethrowBlock;
1448
1449  CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1450
1451  // We emit a jump to a notional label at the outermost unwind state.
1452  llvm::BasicBlock *Unwind = createBasicBlock("eh.resume");
1453  Builder.SetInsertPoint(Unwind);
1454
1455  const EHPersonality &Personality = EHPersonality::get(CGM.getLangOptions());
1456
1457  // This can always be a call because we necessarily didn't find
1458  // anything on the EH stack which needs our help.
1459  StringRef RethrowName = Personality.getCatchallRethrowFnName();
1460  if (!RethrowName.empty()) {
1461    Builder.CreateCall(getCatchallRethrowFn(*this, RethrowName),
1462                       Builder.CreateLoad(getExceptionSlot()))
1463      ->setDoesNotReturn();
1464  } else {
1465    llvm::Value *Exn = Builder.CreateLoad(getExceptionSlot());
1466
1467    switch (CleanupHackLevel) {
1468    case CHL_MandatoryCatchall:
1469      // In mandatory-catchall mode, we need to use
1470      // _Unwind_Resume_or_Rethrow, or whatever the personality's
1471      // equivalent is.
1472      Builder.CreateCall(getUnwindResumeOrRethrowFn(), Exn)
1473        ->setDoesNotReturn();
1474      break;
1475    case CHL_MandatoryCleanup: {
1476      // In mandatory-cleanup mode, we should use llvm.eh.resume.
1477      llvm::Value *Selector = Builder.CreateLoad(getEHSelectorSlot());
1478      Builder.CreateCall2(CGM.getIntrinsic(llvm::Intrinsic::eh_resume),
1479                          Exn, Selector)
1480        ->setDoesNotReturn();
1481      break;
1482    }
1483    case CHL_Ideal:
1484      // In an idealized mode where we don't have to worry about the
1485      // optimizer combining landing pads, we should just use
1486      // _Unwind_Resume (or the personality's equivalent).
1487      Builder.CreateCall(getUnwindResumeFn(), Exn)
1488        ->setDoesNotReturn();
1489      break;
1490    }
1491  }
1492
1493  Builder.CreateUnreachable();
1494
1495  Builder.restoreIP(SavedIP);
1496
1497  RethrowBlock = UnwindDest(Unwind, EHStack.stable_end(), 0);
1498  return RethrowBlock;
1499}
1500
1501