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