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