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