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