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