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