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