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 
18 #include "CodeGenFunction.h"
19 using namespace clang;
20 using namespace CodeGen;
21 
22 static llvm::Constant *getAllocateExceptionFn(CodeGenFunction &CGF) {
23   // void *__cxa_allocate_exception(size_t thrown_size);
24   const llvm::Type *SizeTy = CGF.ConvertType(CGF.getContext().getSizeType());
25   std::vector<const llvm::Type*> Args(1, SizeTy);
26 
27   const llvm::FunctionType *FTy =
28   llvm::FunctionType::get(llvm::Type::getInt8PtrTy(CGF.getLLVMContext()),
29                           Args, false);
30 
31   return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
32 }
33 
34 static llvm::Constant *getFreeExceptionFn(CodeGenFunction &CGF) {
35   // void __cxa_free_exception(void *thrown_exception);
36   const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
37   std::vector<const llvm::Type*> Args(1, Int8PtrTy);
38 
39   const llvm::FunctionType *FTy =
40   llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
41                           Args, false);
42 
43   return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_free_exception");
44 }
45 
46 static llvm::Constant *getThrowFn(CodeGenFunction &CGF) {
47   // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
48   //                  void (*dest) (void *));
49 
50   const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
51   std::vector<const llvm::Type*> Args(3, Int8PtrTy);
52 
53   const llvm::FunctionType *FTy =
54     llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
55                             Args, false);
56 
57   return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
58 }
59 
60 static llvm::Constant *getReThrowFn(CodeGenFunction &CGF) {
61   // void __cxa_rethrow();
62 
63   const llvm::FunctionType *FTy =
64     llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()), false);
65 
66   return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
67 }
68 
69 static llvm::Constant *getBeginCatchFn(CodeGenFunction &CGF) {
70   // void* __cxa_begin_catch();
71 
72   const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
73   std::vector<const llvm::Type*> Args(1, Int8PtrTy);
74 
75   const llvm::FunctionType *FTy =
76     llvm::FunctionType::get(Int8PtrTy, Args, false);
77 
78   return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
79 }
80 
81 static llvm::Constant *getEndCatchFn(CodeGenFunction &CGF) {
82   // void __cxa_end_catch();
83 
84   const llvm::FunctionType *FTy =
85     llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()), false);
86 
87   return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
88 }
89 
90 static llvm::Constant *getUnexpectedFn(CodeGenFunction &CGF) {
91   // void __cxa_call_unexepcted(void *thrown_exception);
92 
93   const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
94   std::vector<const llvm::Type*> Args(1, Int8PtrTy);
95 
96   const llvm::FunctionType *FTy =
97     llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
98                             Args, false);
99 
100   return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_call_unexpected");
101 }
102 
103 llvm::Constant *CodeGenFunction::getUnwindResumeOrRethrowFn() {
104   const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(getLLVMContext());
105   std::vector<const llvm::Type*> Args(1, Int8PtrTy);
106 
107   const llvm::FunctionType *FTy =
108     llvm::FunctionType::get(llvm::Type::getVoidTy(getLLVMContext()), Args,
109                             false);
110 
111   if (CGM.getLangOptions().SjLjExceptions)
112     return CGM.CreateRuntimeFunction(FTy, "_Unwind_SjLj_Resume");
113   return CGM.CreateRuntimeFunction(FTy, "_Unwind_Resume_or_Rethrow");
114 }
115 
116 static llvm::Constant *getTerminateFn(CodeGenFunction &CGF) {
117   // void __terminate();
118 
119   const llvm::FunctionType *FTy =
120     llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()), false);
121 
122   return CGF.CGM.CreateRuntimeFunction(FTy,
123       CGF.CGM.getLangOptions().CPlusPlus ? "_ZSt9terminatev" : "abort");
124 }
125 
126 static llvm::Constant *getPersonalityFn(CodeGenModule &CGM) {
127   const char *PersonalityFnName = "__gcc_personality_v0";
128   LangOptions Opts = CGM.getLangOptions();
129   if (Opts.CPlusPlus)
130      PersonalityFnName = "__gxx_personality_v0";
131   else if (Opts.ObjC1) {
132     if (Opts.NeXTRuntime) {
133       if (Opts.ObjCNonFragileABI)
134         PersonalityFnName = "__gcc_personality_v0";
135     } else
136       PersonalityFnName = "__gnu_objc_personality_v0";
137   }
138 
139   llvm::Constant *Personality =
140   CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::getInt32Ty(
141                                                         CGM.getLLVMContext()),
142                                                     true),
143       PersonalityFnName);
144   return llvm::ConstantExpr::getBitCast(Personality, CGM.PtrToInt8Ty);
145 }
146 
147 // Emits an exception expression into the given location.  This
148 // differs from EmitAnyExprToMem only in that, if a final copy-ctor
149 // call is required, an exception within that copy ctor causes
150 // std::terminate to be invoked.
151 static void EmitAnyExprToExn(CodeGenFunction &CGF, const Expr *E,
152                              llvm::Value *ExnLoc) {
153   // We want to release the allocated exception object if this
154   // expression throws.  We do this by pushing an EH-only cleanup
155   // block which, furthermore, deactivates itself after the expression
156   // is complete.
157   llvm::AllocaInst *ShouldFreeVar =
158     CGF.CreateTempAlloca(llvm::Type::getInt1Ty(CGF.getLLVMContext()),
159                          "should-free-exnobj.var");
160   CGF.InitTempAlloca(ShouldFreeVar,
161                      llvm::ConstantInt::getFalse(CGF.getLLVMContext()));
162 
163   // A variable holding the exception pointer.  This is necessary
164   // because the throw expression does not necessarily dominate the
165   // cleanup, for example if it appears in a conditional expression.
166   llvm::AllocaInst *ExnLocVar =
167     CGF.CreateTempAlloca(ExnLoc->getType(), "exnobj.var");
168 
169   llvm::BasicBlock *SavedInvokeDest = CGF.getInvokeDest();
170   {
171     CodeGenFunction::EHCleanupBlock Cleanup(CGF);
172     llvm::BasicBlock *FreeBB = CGF.createBasicBlock("free-exnobj");
173     llvm::BasicBlock *DoneBB = CGF.createBasicBlock("free-exnobj.done");
174 
175     llvm::Value *ShouldFree = CGF.Builder.CreateLoad(ShouldFreeVar,
176                                                      "should-free-exnobj");
177     CGF.Builder.CreateCondBr(ShouldFree, FreeBB, DoneBB);
178     CGF.EmitBlock(FreeBB);
179     llvm::Value *ExnLocLocal = CGF.Builder.CreateLoad(ExnLocVar, "exnobj");
180     CGF.Builder.CreateCall(getFreeExceptionFn(CGF), ExnLocLocal);
181     CGF.EmitBlock(DoneBB);
182   }
183   llvm::BasicBlock *Cleanup = CGF.getInvokeDest();
184 
185   CGF.Builder.CreateStore(ExnLoc, ExnLocVar);
186   CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(CGF.getLLVMContext()),
187                           ShouldFreeVar);
188 
189   // __cxa_allocate_exception returns a void*;  we need to cast this
190   // to the appropriate type for the object.
191   const llvm::Type *Ty = CGF.ConvertType(E->getType())->getPointerTo();
192   llvm::Value *TypedExnLoc = CGF.Builder.CreateBitCast(ExnLoc, Ty);
193 
194   // FIXME: this isn't quite right!  If there's a final unelided call
195   // to a copy constructor, then according to [except.terminate]p1 we
196   // must call std::terminate() if that constructor throws, because
197   // technically that copy occurs after the exception expression is
198   // evaluated but before the exception is caught.  But the best way
199   // to handle that is to teach EmitAggExpr to do the final copy
200   // differently if it can't be elided.
201   CGF.EmitAnyExprToMem(E, TypedExnLoc, /*Volatile*/ false);
202 
203   CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(CGF.getLLVMContext()),
204                           ShouldFreeVar);
205 
206   // Pop the cleanup block if it's still the top of the cleanup stack.
207   // Otherwise, temporaries have been created and our cleanup will get
208   // properly removed in time.
209   // TODO: this is not very resilient.
210   if (CGF.getInvokeDest() == Cleanup)
211     CGF.setInvokeDest(SavedInvokeDest);
212 }
213 
214 // CopyObject - Utility to copy an object.  Calls copy constructor as necessary.
215 // N is casted to the right type.
216 static void CopyObject(CodeGenFunction &CGF, QualType ObjectType,
217                        bool WasPointer, bool WasPointerReference,
218                        llvm::Value *E, llvm::Value *N) {
219   // Store the throw exception in the exception object.
220   if (WasPointer || !CGF.hasAggregateLLVMType(ObjectType)) {
221     llvm::Value *Value = E;
222     if (!WasPointer)
223       Value = CGF.Builder.CreateLoad(Value);
224     const llvm::Type *ValuePtrTy = Value->getType()->getPointerTo(0);
225     if (WasPointerReference) {
226       llvm::Value *Tmp = CGF.CreateTempAlloca(Value->getType(), "catch.param");
227       CGF.Builder.CreateStore(Value, Tmp);
228       Value = Tmp;
229       ValuePtrTy = Value->getType()->getPointerTo(0);
230     }
231     N = CGF.Builder.CreateBitCast(N, ValuePtrTy);
232     CGF.Builder.CreateStore(Value, N);
233   } else {
234     const llvm::Type *Ty = CGF.ConvertType(ObjectType)->getPointerTo(0);
235     const CXXRecordDecl *RD;
236     RD = cast<CXXRecordDecl>(ObjectType->getAs<RecordType>()->getDecl());
237     llvm::Value *This = CGF.Builder.CreateBitCast(N, Ty);
238     if (RD->hasTrivialCopyConstructor()) {
239       CGF.EmitAggregateCopy(This, E, ObjectType);
240     } else if (CXXConstructorDecl *CopyCtor
241                = RD->getCopyConstructor(CGF.getContext(), 0)) {
242       llvm::Value *Src = E;
243 
244       // Stolen from EmitClassAggrMemberwiseCopy
245       llvm::Value *Callee = CGF.CGM.GetAddrOfCXXConstructor(CopyCtor,
246                                                             Ctor_Complete);
247       CallArgList CallArgs;
248       CallArgs.push_back(std::make_pair(RValue::get(This),
249                                       CopyCtor->getThisType(CGF.getContext())));
250 
251       // Push the Src ptr.
252       CallArgs.push_back(std::make_pair(RValue::get(Src),
253                                         CopyCtor->getParamDecl(0)->getType()));
254 
255       const FunctionProtoType *FPT
256         = CopyCtor->getType()->getAs<FunctionProtoType>();
257       CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(CallArgs, FPT),
258                    Callee, ReturnValueSlot(), CallArgs, CopyCtor);
259     } else
260       llvm_unreachable("uncopyable object");
261   }
262 }
263 
264 void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E) {
265   if (!E->getSubExpr()) {
266     if (getInvokeDest()) {
267       llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
268       Builder.CreateInvoke(getReThrowFn(*this), Cont, getInvokeDest())
269         ->setDoesNotReturn();
270       EmitBlock(Cont);
271     } else
272       Builder.CreateCall(getReThrowFn(*this))->setDoesNotReturn();
273     Builder.CreateUnreachable();
274 
275     // Clear the insertion point to indicate we are in unreachable code.
276     Builder.ClearInsertionPoint();
277     return;
278   }
279 
280   QualType ThrowType = E->getSubExpr()->getType();
281 
282   // Now allocate the exception object.
283   const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
284   uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
285 
286   llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(*this);
287   llvm::Value *ExceptionPtr =
288     Builder.CreateCall(AllocExceptionFn,
289                        llvm::ConstantInt::get(SizeTy, TypeSize),
290                        "exception");
291 
292   EmitAnyExprToExn(*this, E->getSubExpr(), ExceptionPtr);
293 
294   // Now throw the exception.
295   const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(getLLVMContext());
296   llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType, true);
297 
298   // The address of the destructor.  If the exception type has a
299   // trivial destructor (or isn't a record), we just pass null.
300   llvm::Constant *Dtor = 0;
301   if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
302     CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
303     if (!Record->hasTrivialDestructor()) {
304       CXXDestructorDecl *DtorD = Record->getDestructor(getContext());
305       Dtor = CGM.GetAddrOfCXXDestructor(DtorD, Dtor_Complete);
306       Dtor = llvm::ConstantExpr::getBitCast(Dtor, Int8PtrTy);
307     }
308   }
309   if (!Dtor) Dtor = llvm::Constant::getNullValue(Int8PtrTy);
310 
311   if (getInvokeDest()) {
312     llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
313     llvm::InvokeInst *ThrowCall =
314       Builder.CreateInvoke3(getThrowFn(*this), Cont, getInvokeDest(),
315                             ExceptionPtr, TypeInfo, Dtor);
316     ThrowCall->setDoesNotReturn();
317     EmitBlock(Cont);
318   } else {
319     llvm::CallInst *ThrowCall =
320       Builder.CreateCall3(getThrowFn(*this), ExceptionPtr, TypeInfo, Dtor);
321     ThrowCall->setDoesNotReturn();
322   }
323   Builder.CreateUnreachable();
324 
325   // Clear the insertion point to indicate we are in unreachable code.
326   Builder.ClearInsertionPoint();
327 
328   // FIXME: For now, emit a dummy basic block because expr emitters in generally
329   // are not ready to handle emitting expressions at unreachable points.
330   EnsureInsertPoint();
331 }
332 
333 void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
334   if (!Exceptions)
335     return;
336 
337   const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
338   if (FD == 0)
339     return;
340   const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
341   if (Proto == 0)
342     return;
343 
344   assert(!Proto->hasAnyExceptionSpec() && "function with parameter pack");
345 
346   if (!Proto->hasExceptionSpec())
347     return;
348 
349   llvm::Constant *Personality = getPersonalityFn(CGM);
350   llvm::Value *llvm_eh_exception =
351     CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
352   llvm::Value *llvm_eh_selector =
353     CGM.getIntrinsic(llvm::Intrinsic::eh_selector);
354   const llvm::IntegerType *Int8Ty;
355   const llvm::PointerType *PtrToInt8Ty;
356   Int8Ty = llvm::Type::getInt8Ty(VMContext);
357   // C string type.  Used in lots of places.
358   PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
359   llvm::Constant *Null = llvm::ConstantPointerNull::get(PtrToInt8Ty);
360   llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
361 
362   llvm::BasicBlock *PrevLandingPad = getInvokeDest();
363   llvm::BasicBlock *EHSpecHandler = createBasicBlock("ehspec.handler");
364   llvm::BasicBlock *Match = createBasicBlock("match");
365   llvm::BasicBlock *Unwind = 0;
366 
367   assert(PrevLandingPad == 0 && "EHSpec has invoke context");
368   (void)PrevLandingPad;
369 
370   llvm::BasicBlock *Cont = createBasicBlock("cont");
371 
372   EmitBranchThroughCleanup(Cont);
373 
374   // Emit the statements in the try {} block
375   setInvokeDest(EHSpecHandler);
376 
377   EmitBlock(EHSpecHandler);
378   // Exception object
379   llvm::Value *Exc = Builder.CreateCall(llvm_eh_exception, "exc");
380   llvm::Value *RethrowPtr = CreateTempAlloca(Exc->getType(), "_rethrow");
381 
382   SelectorArgs.push_back(Exc);
383   SelectorArgs.push_back(Personality);
384   SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
385                                                 Proto->getNumExceptions()+1));
386 
387   for (unsigned i = 0; i < Proto->getNumExceptions(); ++i) {
388     QualType Ty = Proto->getExceptionType(i);
389     QualType ExceptType
390       = Ty.getNonReferenceType().getUnqualifiedType();
391     llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType, true);
392     SelectorArgs.push_back(EHType);
393   }
394   if (Proto->getNumExceptions())
395     SelectorArgs.push_back(Null);
396 
397   // Find which handler was matched.
398   llvm::Value *Selector
399     = Builder.CreateCall(llvm_eh_selector, SelectorArgs.begin(),
400                          SelectorArgs.end(), "selector");
401   if (Proto->getNumExceptions()) {
402     Unwind = createBasicBlock("Unwind");
403 
404     Builder.CreateStore(Exc, RethrowPtr);
405     Builder.CreateCondBr(Builder.CreateICmpSLT(Selector,
406                                                llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
407                                                                       0)),
408                          Match, Unwind);
409 
410     EmitBlock(Match);
411   }
412   Builder.CreateCall(getUnexpectedFn(*this), Exc)->setDoesNotReturn();
413   Builder.CreateUnreachable();
414 
415   if (Proto->getNumExceptions()) {
416     EmitBlock(Unwind);
417     Builder.CreateCall(getUnwindResumeOrRethrowFn(),
418                        Builder.CreateLoad(RethrowPtr));
419     Builder.CreateUnreachable();
420   }
421 
422   EmitBlock(Cont);
423 }
424 
425 void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
426   if (!Exceptions)
427     return;
428 
429   const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
430   if (FD == 0)
431     return;
432   const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
433   if (Proto == 0)
434     return;
435 
436   if (!Proto->hasExceptionSpec())
437     return;
438 
439   setInvokeDest(0);
440 }
441 
442 void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
443   CXXTryStmtInfo Info = EnterCXXTryStmt(S);
444   EmitStmt(S.getTryBlock());
445   ExitCXXTryStmt(S, Info);
446 }
447 
448 CodeGenFunction::CXXTryStmtInfo
449 CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S) {
450   CXXTryStmtInfo Info;
451   Info.SavedLandingPad = getInvokeDest();
452   Info.HandlerBlock = createBasicBlock("try.handler");
453   Info.FinallyBlock = createBasicBlock("finally");
454 
455   PushCleanupBlock(Info.FinallyBlock);
456   setInvokeDest(Info.HandlerBlock);
457 
458   return Info;
459 }
460 
461 void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S,
462                                      CXXTryStmtInfo TryInfo) {
463   // Pointer to the personality function
464   llvm::Constant *Personality = getPersonalityFn(CGM);
465   llvm::Value *llvm_eh_exception =
466     CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
467   llvm::Value *llvm_eh_selector =
468     CGM.getIntrinsic(llvm::Intrinsic::eh_selector);
469 
470   llvm::BasicBlock *PrevLandingPad = TryInfo.SavedLandingPad;
471   llvm::BasicBlock *TryHandler = TryInfo.HandlerBlock;
472   llvm::BasicBlock *FinallyBlock = TryInfo.FinallyBlock;
473   llvm::BasicBlock *FinallyRethrow = createBasicBlock("finally.throw");
474   llvm::BasicBlock *FinallyEnd = createBasicBlock("finally.end");
475 
476   // Jump to end if there is no exception
477   EmitBranchThroughCleanup(FinallyEnd);
478 
479   llvm::BasicBlock *TerminateHandler = getTerminateHandler();
480 
481   // Emit the handlers
482   EmitBlock(TryHandler);
483 
484   const llvm::IntegerType *Int8Ty;
485   const llvm::PointerType *PtrToInt8Ty;
486   Int8Ty = llvm::Type::getInt8Ty(VMContext);
487   // C string type.  Used in lots of places.
488   PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
489   llvm::Constant *Null = llvm::ConstantPointerNull::get(PtrToInt8Ty);
490   llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
491   llvm::Value *llvm_eh_typeid_for =
492     CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
493   // Exception object
494   llvm::Value *Exc = Builder.CreateCall(llvm_eh_exception, "exc");
495   llvm::Value *RethrowPtr = CreateTempAlloca(Exc->getType(), "_rethrow");
496 
497   SelectorArgs.push_back(Exc);
498   SelectorArgs.push_back(Personality);
499 
500   bool HasCatchAll = false;
501   for (unsigned i = 0; i<S.getNumHandlers(); ++i) {
502     const CXXCatchStmt *C = S.getHandler(i);
503     VarDecl *CatchParam = C->getExceptionDecl();
504     if (CatchParam) {
505       // C++ [except.handle]p3 indicates that top-level cv-qualifiers
506       // are ignored.
507       QualType CaughtType = C->getCaughtType().getNonReferenceType();
508       llvm::Value *EHTypeInfo
509         = CGM.GetAddrOfRTTIDescriptor(CaughtType.getUnqualifiedType(), true);
510       SelectorArgs.push_back(EHTypeInfo);
511     } else {
512       // null indicates catch all
513       SelectorArgs.push_back(Null);
514       HasCatchAll = true;
515     }
516   }
517 
518   // We use a cleanup unless there was already a catch all.
519   if (!HasCatchAll) {
520     SelectorArgs.push_back(Null);
521   }
522 
523   // Find which handler was matched.
524   llvm::Value *Selector
525     = Builder.CreateCall(llvm_eh_selector, SelectorArgs.begin(),
526                          SelectorArgs.end(), "selector");
527   for (unsigned i = 0; i<S.getNumHandlers(); ++i) {
528     const CXXCatchStmt *C = S.getHandler(i);
529     VarDecl *CatchParam = C->getExceptionDecl();
530     Stmt *CatchBody = C->getHandlerBlock();
531 
532     llvm::BasicBlock *Next = 0;
533 
534     if (SelectorArgs[i+2] != Null) {
535       llvm::BasicBlock *Match = createBasicBlock("match");
536       Next = createBasicBlock("catch.next");
537       const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(getLLVMContext());
538       llvm::Value *Id
539         = Builder.CreateCall(llvm_eh_typeid_for,
540                              Builder.CreateBitCast(SelectorArgs[i+2],
541                                                    Int8PtrTy));
542       Builder.CreateCondBr(Builder.CreateICmpEQ(Selector, Id),
543                            Match, Next);
544       EmitBlock(Match);
545     }
546 
547     llvm::BasicBlock *MatchEnd = createBasicBlock("match.end");
548     llvm::BasicBlock *MatchHandler = createBasicBlock("match.handler");
549 
550     PushCleanupBlock(MatchEnd);
551     setInvokeDest(MatchHandler);
552 
553     llvm::Value *ExcObject = Builder.CreateCall(getBeginCatchFn(*this), Exc);
554 
555     {
556       CleanupScope CatchScope(*this);
557       // Bind the catch parameter if it exists.
558       if (CatchParam) {
559         QualType CatchType = CatchParam->getType().getNonReferenceType();
560         setInvokeDest(TerminateHandler);
561         bool WasPointer = true;
562         bool WasPointerReference = false;
563         CatchType = CGM.getContext().getCanonicalType(CatchType);
564         if (CatchType.getTypePtr()->isPointerType()) {
565           if (isa<ReferenceType>(CatchParam->getType()))
566             WasPointerReference = true;
567         } else {
568           if (!isa<ReferenceType>(CatchParam->getType()))
569             WasPointer = false;
570           CatchType = getContext().getPointerType(CatchType);
571         }
572         ExcObject = Builder.CreateBitCast(ExcObject, ConvertType(CatchType));
573         EmitLocalBlockVarDecl(*CatchParam);
574         // FIXME: we need to do this sooner so that the EH region for the
575         // cleanup doesn't start until after the ctor completes, use a decl
576         // init?
577         CopyObject(*this, CatchParam->getType().getNonReferenceType(),
578                    WasPointer, WasPointerReference, ExcObject,
579                    GetAddrOfLocalVar(CatchParam));
580         setInvokeDest(MatchHandler);
581       }
582 
583       EmitStmt(CatchBody);
584     }
585 
586     EmitBranchThroughCleanup(FinallyEnd);
587 
588     EmitBlock(MatchHandler);
589 
590     llvm::Value *Exc = Builder.CreateCall(llvm_eh_exception, "exc");
591     // We are required to emit this call to satisfy LLVM, even
592     // though we don't use the result.
593     llvm::Value *Args[] = {
594       Exc, Personality,
595       llvm::ConstantInt::getNullValue(llvm::Type::getInt32Ty(VMContext))
596     };
597     Builder.CreateCall(llvm_eh_selector, &Args[0], llvm::array_endof(Args));
598     Builder.CreateStore(Exc, RethrowPtr);
599     EmitBranchThroughCleanup(FinallyRethrow);
600 
601     CodeGenFunction::CleanupBlockInfo Info = PopCleanupBlock();
602 
603     EmitBlock(MatchEnd);
604 
605     llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
606     Builder.CreateInvoke(getEndCatchFn(*this),
607                          Cont, TerminateHandler,
608                          &Args[0], &Args[0]);
609     EmitBlock(Cont);
610     if (Info.SwitchBlock)
611       EmitBlock(Info.SwitchBlock);
612     if (Info.EndBlock)
613       EmitBlock(Info.EndBlock);
614 
615     Exc = Builder.CreateCall(llvm_eh_exception, "exc");
616     Builder.CreateStore(Exc, RethrowPtr);
617     EmitBranchThroughCleanup(FinallyRethrow);
618 
619     if (Next)
620       EmitBlock(Next);
621   }
622   if (!HasCatchAll) {
623     Builder.CreateStore(Exc, RethrowPtr);
624     EmitBranchThroughCleanup(FinallyRethrow);
625   }
626 
627   CodeGenFunction::CleanupBlockInfo Info = PopCleanupBlock();
628 
629   setInvokeDest(PrevLandingPad);
630 
631   EmitBlock(FinallyBlock);
632 
633   if (Info.SwitchBlock)
634     EmitBlock(Info.SwitchBlock);
635   if (Info.EndBlock)
636     EmitBlock(Info.EndBlock);
637 
638   // Branch around the rethrow code.
639   EmitBranch(FinallyEnd);
640 
641   EmitBlock(FinallyRethrow);
642   // FIXME: Eventually we can chain the handlers together and just do a call
643   // here.
644   if (getInvokeDest()) {
645     llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
646     Builder.CreateInvoke(getUnwindResumeOrRethrowFn(), Cont,
647                          getInvokeDest(),
648                          Builder.CreateLoad(RethrowPtr));
649     EmitBlock(Cont);
650   } else
651     Builder.CreateCall(getUnwindResumeOrRethrowFn(),
652                        Builder.CreateLoad(RethrowPtr));
653 
654   Builder.CreateUnreachable();
655 
656   EmitBlock(FinallyEnd);
657 }
658 
659 CodeGenFunction::EHCleanupBlock::~EHCleanupBlock() {
660   CGF.setInvokeDest(PreviousInvokeDest);
661 
662   llvm::BasicBlock *EndOfCleanup = CGF.Builder.GetInsertBlock();
663 
664   // Jump to the beginning of the cleanup.
665   CGF.Builder.SetInsertPoint(CleanupHandler, CleanupHandler->begin());
666 
667   // The libstdc++ personality function.
668   // TODO: generalize to work with other libraries.
669   llvm::Constant *Personality = getPersonalityFn(CGF.CGM);
670 
671   // %exception = call i8* @llvm.eh.exception()
672   //   Magic intrinsic which tells gives us a handle to the caught
673   //   exception.
674   llvm::Value *llvm_eh_exception =
675     CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
676   llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
677 
678   llvm::Constant *Null = llvm::ConstantPointerNull::get(CGF.PtrToInt8Ty);
679 
680   // %ignored = call i32 @llvm.eh.selector(i8* %exception,
681   //                                       i8* @__gxx_personality_v0,
682   //                                       i8* null)
683   //   Magic intrinsic which tells LLVM that this invoke landing pad is
684   //   just a cleanup block.
685   llvm::Value *Args[] = { Exc, Personality, Null };
686   llvm::Value *llvm_eh_selector =
687     CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector);
688   CGF.Builder.CreateCall(llvm_eh_selector, &Args[0], llvm::array_endof(Args));
689 
690   // And then we fall through into the code that the user put there.
691   // Jump back to the end of the cleanup.
692   CGF.Builder.SetInsertPoint(EndOfCleanup);
693 
694   // Rethrow the exception.
695   if (CGF.getInvokeDest()) {
696     llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
697     CGF.Builder.CreateInvoke(CGF.getUnwindResumeOrRethrowFn(), Cont,
698                              CGF.getInvokeDest(), Exc);
699     CGF.EmitBlock(Cont);
700   } else
701     CGF.Builder.CreateCall(CGF.getUnwindResumeOrRethrowFn(), Exc);
702   CGF.Builder.CreateUnreachable();
703 
704   // Resume inserting where we started, but put the new cleanup
705   // handler in place.
706   if (PreviousInsertionBlock)
707     CGF.Builder.SetInsertPoint(PreviousInsertionBlock);
708   else
709     CGF.Builder.ClearInsertionPoint();
710 
711   if (CGF.Exceptions)
712     CGF.setInvokeDest(CleanupHandler);
713 }
714 
715 llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
716   if (TerminateHandler)
717     return TerminateHandler;
718 
719   // We don't want to change anything at the current location, so
720   // save it aside and clear the insert point.
721   llvm::BasicBlock *SavedInsertBlock = Builder.GetInsertBlock();
722   llvm::BasicBlock::iterator SavedInsertPoint = Builder.GetInsertPoint();
723   Builder.ClearInsertionPoint();
724 
725   llvm::Constant *Personality = getPersonalityFn(CGM);
726   llvm::Value *llvm_eh_exception =
727     CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
728   llvm::Value *llvm_eh_selector =
729     CGM.getIntrinsic(llvm::Intrinsic::eh_selector);
730 
731   // Set up terminate handler
732   TerminateHandler = createBasicBlock("terminate.handler");
733   EmitBlock(TerminateHandler);
734   llvm::Value *Exc = Builder.CreateCall(llvm_eh_exception, "exc");
735   // We are required to emit this call to satisfy LLVM, even
736   // though we don't use the result.
737   llvm::Value *Args[] = {
738     Exc, Personality,
739     llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 1)
740   };
741   Builder.CreateCall(llvm_eh_selector, &Args[0], llvm::array_endof(Args));
742   llvm::CallInst *TerminateCall =
743     Builder.CreateCall(getTerminateFn(*this));
744   TerminateCall->setDoesNotReturn();
745   TerminateCall->setDoesNotThrow();
746   Builder.CreateUnreachable();
747 
748   // Restore the saved insertion state.
749   Builder.SetInsertPoint(SavedInsertBlock, SavedInsertPoint);
750 
751   return TerminateHandler;
752 }
753