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