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