1198893Srdivacky//===--- CGException.cpp - Emit LLVM Code for C++ exceptions --------------===//
2198893Srdivacky//
3198893Srdivacky//                     The LLVM Compiler Infrastructure
4198893Srdivacky//
5198893Srdivacky// This file is distributed under the University of Illinois Open Source
6198893Srdivacky// License. See LICENSE.TXT for details.
7198893Srdivacky//
8198893Srdivacky//===----------------------------------------------------------------------===//
9198893Srdivacky//
10198893Srdivacky// This contains code dealing with C++ exception related code generation.
11198893Srdivacky//
12198893Srdivacky//===----------------------------------------------------------------------===//
13198893Srdivacky
14234353Sdim#include "CodeGenFunction.h"
15234353Sdim#include "CGCleanup.h"
16234353Sdim#include "CGObjCRuntime.h"
17234353Sdim#include "TargetInfo.h"
18199990Srdivacky#include "clang/AST/StmtCXX.h"
19249423Sdim#include "clang/AST/StmtObjC.h"
20249423Sdim#include "llvm/IR/Intrinsics.h"
21210299Sed#include "llvm/Support/CallSite.h"
22199990Srdivacky
23198893Srdivackyusing namespace clang;
24198893Srdivackyusing namespace CodeGen;
25198893Srdivacky
26249423Sdimstatic llvm::Constant *getAllocateExceptionFn(CodeGenModule &CGM) {
27198893Srdivacky  // void *__cxa_allocate_exception(size_t thrown_size);
28221345Sdim
29226633Sdim  llvm::FunctionType *FTy =
30249423Sdim    llvm::FunctionType::get(CGM.Int8PtrTy, CGM.SizeTy, /*IsVarArgs=*/false);
31200583Srdivacky
32249423Sdim  return CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
33198893Srdivacky}
34198893Srdivacky
35249423Sdimstatic llvm::Constant *getFreeExceptionFn(CodeGenModule &CGM) {
36200583Srdivacky  // void __cxa_free_exception(void *thrown_exception);
37221345Sdim
38226633Sdim  llvm::FunctionType *FTy =
39249423Sdim    llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
40200583Srdivacky
41249423Sdim  return CGM.CreateRuntimeFunction(FTy, "__cxa_free_exception");
42200583Srdivacky}
43200583Srdivacky
44249423Sdimstatic llvm::Constant *getThrowFn(CodeGenModule &CGM) {
45200583Srdivacky  // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
46200583Srdivacky  //                  void (*dest) (void *));
47198893Srdivacky
48249423Sdim  llvm::Type *Args[3] = { CGM.Int8PtrTy, CGM.Int8PtrTy, CGM.Int8PtrTy };
49226633Sdim  llvm::FunctionType *FTy =
50249423Sdim    llvm::FunctionType::get(CGM.VoidTy, Args, /*IsVarArgs=*/false);
51200583Srdivacky
52249423Sdim  return CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
53198893Srdivacky}
54198893Srdivacky
55249423Sdimstatic llvm::Constant *getReThrowFn(CodeGenModule &CGM) {
56200583Srdivacky  // void __cxa_rethrow();
57199990Srdivacky
58226633Sdim  llvm::FunctionType *FTy =
59249423Sdim    llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
60200583Srdivacky
61249423Sdim  return CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
62199990Srdivacky}
63199990Srdivacky
64249423Sdimstatic llvm::Constant *getGetExceptionPtrFn(CodeGenModule &CGM) {
65210299Sed  // void *__cxa_get_exception_ptr(void*);
66221345Sdim
67226633Sdim  llvm::FunctionType *FTy =
68249423Sdim    llvm::FunctionType::get(CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
69210299Sed
70249423Sdim  return CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
71210299Sed}
72210299Sed
73249423Sdimstatic llvm::Constant *getBeginCatchFn(CodeGenModule &CGM) {
74210299Sed  // void *__cxa_begin_catch(void*);
75199990Srdivacky
76226633Sdim  llvm::FunctionType *FTy =
77249423Sdim    llvm::FunctionType::get(CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
78200583Srdivacky
79249423Sdim  return CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
80199990Srdivacky}
81199990Srdivacky
82249423Sdimstatic llvm::Constant *getEndCatchFn(CodeGenModule &CGM) {
83200583Srdivacky  // void __cxa_end_catch();
84199990Srdivacky
85226633Sdim  llvm::FunctionType *FTy =
86249423Sdim    llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
87200583Srdivacky
88249423Sdim  return CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
89199990Srdivacky}
90199990Srdivacky
91249423Sdimstatic llvm::Constant *getUnexpectedFn(CodeGenModule &CGM) {
92263508Sdim  // void __cxa_call_unexpected(void *thrown_exception);
93200583Srdivacky
94226633Sdim  llvm::FunctionType *FTy =
95249423Sdim    llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
96200583Srdivacky
97249423Sdim  return CGM.CreateRuntimeFunction(FTy, "__cxa_call_unexpected");
98200583Srdivacky}
99200583Srdivacky
100223017Sdimllvm::Constant *CodeGenFunction::getUnwindResumeFn() {
101226633Sdim  llvm::FunctionType *FTy =
102226633Sdim    llvm::FunctionType::get(VoidTy, Int8PtrTy, /*IsVarArgs=*/false);
103223017Sdim
104234353Sdim  if (CGM.getLangOpts().SjLjExceptions)
105223017Sdim    return CGM.CreateRuntimeFunction(FTy, "_Unwind_SjLj_Resume");
106223017Sdim  return CGM.CreateRuntimeFunction(FTy, "_Unwind_Resume");
107223017Sdim}
108223017Sdim
109208600Srdivackyllvm::Constant *CodeGenFunction::getUnwindResumeOrRethrowFn() {
110226633Sdim  llvm::FunctionType *FTy =
111226633Sdim    llvm::FunctionType::get(VoidTy, Int8PtrTy, /*IsVarArgs=*/false);
112200583Srdivacky
113234353Sdim  if (CGM.getLangOpts().SjLjExceptions)
114212904Sdim    return CGM.CreateRuntimeFunction(FTy, "_Unwind_SjLj_Resume_or_Rethrow");
115208600Srdivacky  return CGM.CreateRuntimeFunction(FTy, "_Unwind_Resume_or_Rethrow");
116199990Srdivacky}
117199990Srdivacky
118249423Sdimstatic llvm::Constant *getTerminateFn(CodeGenModule &CGM) {
119200583Srdivacky  // void __terminate();
120200583Srdivacky
121226633Sdim  llvm::FunctionType *FTy =
122249423Sdim    llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
123200583Srdivacky
124226633Sdim  StringRef name;
125224145Sdim
126224145Sdim  // In C++, use std::terminate().
127249423Sdim  if (CGM.getLangOpts().CPlusPlus)
128224145Sdim    name = "_ZSt9terminatev"; // FIXME: mangling!
129249423Sdim  else if (CGM.getLangOpts().ObjC1 &&
130249423Sdim           CGM.getLangOpts().ObjCRuntime.hasTerminate())
131224145Sdim    name = "objc_terminate";
132224145Sdim  else
133224145Sdim    name = "abort";
134249423Sdim  return CGM.CreateRuntimeFunction(FTy, name);
135200583Srdivacky}
136200583Srdivacky
137249423Sdimstatic llvm::Constant *getCatchallRethrowFn(CodeGenModule &CGM,
138226633Sdim                                            StringRef Name) {
139226633Sdim  llvm::FunctionType *FTy =
140249423Sdim    llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
141212904Sdim
142249423Sdim  return CGM.CreateRuntimeFunction(FTy, Name);
143210299Sed}
144210299Sed
145234353Sdimnamespace {
146234353Sdim  /// The exceptions personality for a function.
147234353Sdim  struct EHPersonality {
148234353Sdim    const char *PersonalityFn;
149212904Sdim
150234353Sdim    // If this is non-null, this personality requires a non-standard
151234353Sdim    // function for rethrowing an exception after a catchall cleanup.
152234353Sdim    // This function must have prototype void(void*).
153234353Sdim    const char *CatchallRethrowFn;
154234353Sdim
155234353Sdim    static const EHPersonality &get(const LangOptions &Lang);
156234353Sdim    static const EHPersonality GNU_C;
157234353Sdim    static const EHPersonality GNU_C_SJLJ;
158234353Sdim    static const EHPersonality GNU_ObjC;
159249423Sdim    static const EHPersonality GNUstep_ObjC;
160234353Sdim    static const EHPersonality GNU_ObjCXX;
161234353Sdim    static const EHPersonality NeXT_ObjC;
162234353Sdim    static const EHPersonality GNU_CPlusPlus;
163234353Sdim    static const EHPersonality GNU_CPlusPlus_SJLJ;
164234353Sdim  };
165234353Sdim}
166234353Sdim
167234353Sdimconst EHPersonality EHPersonality::GNU_C = { "__gcc_personality_v0", 0 };
168234353Sdimconst EHPersonality EHPersonality::GNU_C_SJLJ = { "__gcc_personality_sj0", 0 };
169234353Sdimconst EHPersonality EHPersonality::NeXT_ObjC = { "__objc_personality_v0", 0 };
170234353Sdimconst EHPersonality EHPersonality::GNU_CPlusPlus = { "__gxx_personality_v0", 0};
171234353Sdimconst EHPersonality
172234353SdimEHPersonality::GNU_CPlusPlus_SJLJ = { "__gxx_personality_sj0", 0 };
173234353Sdimconst EHPersonality
174234353SdimEHPersonality::GNU_ObjC = {"__gnu_objc_personality_v0", "objc_exception_throw"};
175234353Sdimconst EHPersonality
176234353SdimEHPersonality::GNU_ObjCXX = { "__gnustep_objcxx_personality_v0", 0 };
177249423Sdimconst EHPersonality
178249423SdimEHPersonality::GNUstep_ObjC = { "__gnustep_objc_personality_v0", 0 };
179234353Sdim
180212904Sdimstatic const EHPersonality &getCPersonality(const LangOptions &L) {
181218893Sdim  if (L.SjLjExceptions)
182218893Sdim    return EHPersonality::GNU_C_SJLJ;
183212904Sdim  return EHPersonality::GNU_C;
184212904Sdim}
185212904Sdim
186212904Sdimstatic const EHPersonality &getObjCPersonality(const LangOptions &L) {
187239462Sdim  switch (L.ObjCRuntime.getKind()) {
188239462Sdim  case ObjCRuntime::FragileMacOSX:
189239462Sdim    return getCPersonality(L);
190239462Sdim  case ObjCRuntime::MacOSX:
191239462Sdim  case ObjCRuntime::iOS:
192239462Sdim    return EHPersonality::NeXT_ObjC;
193239462Sdim  case ObjCRuntime::GNUstep:
194249423Sdim    if (L.ObjCRuntime.getVersion() >= VersionTuple(1, 7))
195249423Sdim      return EHPersonality::GNUstep_ObjC;
196249423Sdim    // fallthrough
197239462Sdim  case ObjCRuntime::GCC:
198239462Sdim  case ObjCRuntime::ObjFW:
199212904Sdim    return EHPersonality::GNU_ObjC;
200208600Srdivacky  }
201239462Sdim  llvm_unreachable("bad runtime kind");
202210299Sed}
203208600Srdivacky
204212904Sdimstatic const EHPersonality &getCXXPersonality(const LangOptions &L) {
205212904Sdim  if (L.SjLjExceptions)
206212904Sdim    return EHPersonality::GNU_CPlusPlus_SJLJ;
207210299Sed  else
208212904Sdim    return EHPersonality::GNU_CPlusPlus;
209210299Sed}
210210299Sed
211210299Sed/// Determines the personality function to use when both C++
212210299Sed/// and Objective-C exceptions are being caught.
213212904Sdimstatic const EHPersonality &getObjCXXPersonality(const LangOptions &L) {
214239462Sdim  switch (L.ObjCRuntime.getKind()) {
215210299Sed  // The ObjC personality defers to the C++ personality for non-ObjC
216210299Sed  // handlers.  Unlike the C++ case, we use the same personality
217210299Sed  // function on targets using (backend-driven) SJLJ EH.
218239462Sdim  case ObjCRuntime::MacOSX:
219239462Sdim  case ObjCRuntime::iOS:
220239462Sdim    return EHPersonality::NeXT_ObjC;
221210299Sed
222239462Sdim  // In the fragile ABI, just use C++ exception handling and hope
223239462Sdim  // they're not doing crazy exception mixing.
224239462Sdim  case ObjCRuntime::FragileMacOSX:
225239462Sdim    return getCXXPersonality(L);
226210299Sed
227239462Sdim  // The GCC runtime's personality function inherently doesn't support
228212904Sdim  // mixed EH.  Use the C++ personality just to avoid returning null.
229239462Sdim  case ObjCRuntime::GCC:
230239462Sdim  case ObjCRuntime::ObjFW: // XXX: this will change soon
231239462Sdim    return EHPersonality::GNU_ObjC;
232239462Sdim  case ObjCRuntime::GNUstep:
233239462Sdim    return EHPersonality::GNU_ObjCXX;
234239462Sdim  }
235239462Sdim  llvm_unreachable("bad runtime kind");
236210299Sed}
237210299Sed
238212904Sdimconst EHPersonality &EHPersonality::get(const LangOptions &L) {
239212904Sdim  if (L.CPlusPlus && L.ObjC1)
240212904Sdim    return getObjCXXPersonality(L);
241212904Sdim  else if (L.CPlusPlus)
242212904Sdim    return getCXXPersonality(L);
243212904Sdim  else if (L.ObjC1)
244212904Sdim    return getObjCPersonality(L);
245210299Sed  else
246212904Sdim    return getCPersonality(L);
247212904Sdim}
248210299Sed
249218893Sdimstatic llvm::Constant *getPersonalityFn(CodeGenModule &CGM,
250212904Sdim                                        const EHPersonality &Personality) {
251212904Sdim  llvm::Constant *Fn =
252234353Sdim    CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.Int32Ty, true),
253234353Sdim                              Personality.PersonalityFn);
254218893Sdim  return Fn;
255208600Srdivacky}
256208600Srdivacky
257218893Sdimstatic llvm::Constant *getOpaquePersonalityFn(CodeGenModule &CGM,
258218893Sdim                                        const EHPersonality &Personality) {
259218893Sdim  llvm::Constant *Fn = getPersonalityFn(CGM, Personality);
260218893Sdim  return llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
261218893Sdim}
262218893Sdim
263218893Sdim/// Check whether a personality function could reasonably be swapped
264218893Sdim/// for a C++ personality function.
265218893Sdimstatic bool PersonalityHasOnlyCXXUses(llvm::Constant *Fn) {
266218893Sdim  for (llvm::Constant::use_iterator
267218893Sdim         I = Fn->use_begin(), E = Fn->use_end(); I != E; ++I) {
268218893Sdim    llvm::User *User = *I;
269218893Sdim
270218893Sdim    // Conditionally white-list bitcasts.
271218893Sdim    if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(User)) {
272218893Sdim      if (CE->getOpcode() != llvm::Instruction::BitCast) return false;
273218893Sdim      if (!PersonalityHasOnlyCXXUses(CE))
274218893Sdim        return false;
275218893Sdim      continue;
276218893Sdim    }
277218893Sdim
278226633Sdim    // Otherwise, it has to be a landingpad instruction.
279226633Sdim    llvm::LandingPadInst *LPI = dyn_cast<llvm::LandingPadInst>(User);
280226633Sdim    if (!LPI) return false;
281218893Sdim
282226633Sdim    for (unsigned I = 0, E = LPI->getNumClauses(); I != E; ++I) {
283218893Sdim      // Look for something that would've been returned by the ObjC
284218893Sdim      // runtime's GetEHType() method.
285226633Sdim      llvm::Value *Val = LPI->getClause(I)->stripPointerCasts();
286226633Sdim      if (LPI->isCatch(I)) {
287226633Sdim        // Check if the catch value has the ObjC prefix.
288226633Sdim        if (llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Val))
289226633Sdim          // ObjC EH selector entries are always global variables with
290226633Sdim          // names starting like this.
291226633Sdim          if (GV->getName().startswith("OBJC_EHTYPE"))
292226633Sdim            return false;
293226633Sdim      } else {
294226633Sdim        // Check if any of the filter values have the ObjC prefix.
295226633Sdim        llvm::Constant *CVal = cast<llvm::Constant>(Val);
296226633Sdim        for (llvm::User::op_iterator
297226633Sdim               II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II) {
298226633Sdim          if (llvm::GlobalVariable *GV =
299226633Sdim              cast<llvm::GlobalVariable>((*II)->stripPointerCasts()))
300226633Sdim            // ObjC EH selector entries are always global variables with
301226633Sdim            // names starting like this.
302226633Sdim            if (GV->getName().startswith("OBJC_EHTYPE"))
303226633Sdim              return false;
304226633Sdim        }
305226633Sdim      }
306218893Sdim    }
307218893Sdim  }
308218893Sdim
309218893Sdim  return true;
310218893Sdim}
311218893Sdim
312218893Sdim/// Try to use the C++ personality function in ObjC++.  Not doing this
313218893Sdim/// can cause some incompatibilities with gcc, which is more
314218893Sdim/// aggressive about only using the ObjC++ personality in a function
315218893Sdim/// when it really needs it.
316218893Sdimvoid CodeGenModule::SimplifyPersonality() {
317218893Sdim  // If we're not in ObjC++ -fexceptions, there's nothing to do.
318234353Sdim  if (!LangOpts.CPlusPlus || !LangOpts.ObjC1 || !LangOpts.Exceptions)
319218893Sdim    return;
320218893Sdim
321243830Sdim  // Both the problem this endeavors to fix and the way the logic
322243830Sdim  // above works is specific to the NeXT runtime.
323243830Sdim  if (!LangOpts.ObjCRuntime.isNeXTFamily())
324243830Sdim    return;
325243830Sdim
326234353Sdim  const EHPersonality &ObjCXX = EHPersonality::get(LangOpts);
327234353Sdim  const EHPersonality &CXX = getCXXPersonality(LangOpts);
328234353Sdim  if (&ObjCXX == &CXX)
329218893Sdim    return;
330218893Sdim
331234353Sdim  assert(std::strcmp(ObjCXX.PersonalityFn, CXX.PersonalityFn) != 0 &&
332234353Sdim         "Different EHPersonalities using the same personality function.");
333218893Sdim
334234353Sdim  llvm::Function *Fn = getModule().getFunction(ObjCXX.PersonalityFn);
335234353Sdim
336218893Sdim  // Nothing to do if it's unused.
337218893Sdim  if (!Fn || Fn->use_empty()) return;
338218893Sdim
339218893Sdim  // Can't do the optimization if it has non-C++ uses.
340218893Sdim  if (!PersonalityHasOnlyCXXUses(Fn)) return;
341218893Sdim
342218893Sdim  // Create the C++ personality function and kill off the old
343218893Sdim  // function.
344218893Sdim  llvm::Constant *CXXFn = getPersonalityFn(*this, CXX);
345218893Sdim
346218893Sdim  // This can happen if the user is screwing with us.
347218893Sdim  if (Fn->getType() != CXXFn->getType()) return;
348218893Sdim
349218893Sdim  Fn->replaceAllUsesWith(CXXFn);
350218893Sdim  Fn->eraseFromParent();
351218893Sdim}
352218893Sdim
353210299Sed/// Returns the value to inject into a selector to indicate the
354210299Sed/// presence of a catch-all.
355210299Sedstatic llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
356210299Sed  // Possibly we should use @llvm.eh.catch.all.value here.
357218893Sdim  return llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
358210299Sed}
359210299Sed
360210299Sednamespace {
361210299Sed  /// A cleanup to free the exception object if its initialization
362210299Sed  /// throws.
363224145Sdim  struct FreeException : EHScopeStack::Cleanup {
364224145Sdim    llvm::Value *exn;
365224145Sdim    FreeException(llvm::Value *exn) : exn(exn) {}
366224145Sdim    void Emit(CodeGenFunction &CGF, Flags flags) {
367249423Sdim      CGF.EmitNounwindRuntimeCall(getFreeExceptionFn(CGF.CGM), exn);
368210299Sed    }
369210299Sed  };
370210299Sed}
371210299Sed
372207619Srdivacky// Emits an exception expression into the given location.  This
373207619Srdivacky// differs from EmitAnyExprToMem only in that, if a final copy-ctor
374207619Srdivacky// call is required, an exception within that copy ctor causes
375207619Srdivacky// std::terminate to be invoked.
376218893Sdimstatic void EmitAnyExprToExn(CodeGenFunction &CGF, const Expr *e,
377218893Sdim                             llvm::Value *addr) {
378210299Sed  // Make sure the exception object is cleaned up if there's an
379210299Sed  // exception during initialization.
380218893Sdim  CGF.pushFullExprCleanup<FreeException>(EHCleanup, addr);
381218893Sdim  EHScopeStack::stable_iterator cleanup = CGF.EHStack.stable_begin();
382201361Srdivacky
383207619Srdivacky  // __cxa_allocate_exception returns a void*;  we need to cast this
384207619Srdivacky  // to the appropriate type for the object.
385226633Sdim  llvm::Type *ty = CGF.ConvertTypeForMem(e->getType())->getPointerTo();
386218893Sdim  llvm::Value *typedAddr = CGF.Builder.CreateBitCast(addr, ty);
387200583Srdivacky
388207619Srdivacky  // FIXME: this isn't quite right!  If there's a final unelided call
389207619Srdivacky  // to a copy constructor, then according to [except.terminate]p1 we
390207619Srdivacky  // must call std::terminate() if that constructor throws, because
391207619Srdivacky  // technically that copy occurs after the exception expression is
392207619Srdivacky  // evaluated but before the exception is caught.  But the best way
393207619Srdivacky  // to handle that is to teach EmitAggExpr to do the final copy
394207619Srdivacky  // differently if it can't be elided.
395224145Sdim  CGF.EmitAnyExprToMem(e, typedAddr, e->getType().getQualifiers(),
396224145Sdim                       /*IsInit*/ true);
397201361Srdivacky
398218893Sdim  // Deactivate the cleanup block.
399234353Sdim  CGF.DeactivateCleanupBlock(cleanup, cast<llvm::Instruction>(typedAddr));
400199990Srdivacky}
401199990Srdivacky
402210299Sedllvm::Value *CodeGenFunction::getExceptionSlot() {
403223017Sdim  if (!ExceptionSlot)
404223017Sdim    ExceptionSlot = CreateTempAlloca(Int8PtrTy, "exn.slot");
405210299Sed  return ExceptionSlot;
406199990Srdivacky}
407199990Srdivacky
408223017Sdimllvm::Value *CodeGenFunction::getEHSelectorSlot() {
409223017Sdim  if (!EHSelectorSlot)
410223017Sdim    EHSelectorSlot = CreateTempAlloca(Int32Ty, "ehselector.slot");
411223017Sdim  return EHSelectorSlot;
412223017Sdim}
413223017Sdim
414226633Sdimllvm::Value *CodeGenFunction::getExceptionFromSlot() {
415226633Sdim  return Builder.CreateLoad(getExceptionSlot(), "exn");
416226633Sdim}
417226633Sdim
418226633Sdimllvm::Value *CodeGenFunction::getSelectorFromSlot() {
419226633Sdim  return Builder.CreateLoad(getEHSelectorSlot(), "sel");
420226633Sdim}
421226633Sdim
422251662Sdimvoid CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E,
423251662Sdim                                       bool KeepInsertionPoint) {
424198893Srdivacky  if (!E->getSubExpr()) {
425249423Sdim    EmitNoreturnRuntimeCallOrInvoke(getReThrowFn(CGM),
426249423Sdim                                    ArrayRef<llvm::Value*>());
427199990Srdivacky
428218893Sdim    // throw is an expression, and the expression emitters expect us
429218893Sdim    // to leave ourselves at a valid insertion point.
430251662Sdim    if (KeepInsertionPoint)
431251662Sdim      EmitBlock(createBasicBlock("throw.cont"));
432218893Sdim
433198893Srdivacky    return;
434198893Srdivacky  }
435200583Srdivacky
436198893Srdivacky  QualType ThrowType = E->getSubExpr()->getType();
437200583Srdivacky
438249423Sdim  if (ThrowType->isObjCObjectPointerType()) {
439249423Sdim    const Stmt *ThrowStmt = E->getSubExpr();
440249423Sdim    const ObjCAtThrowStmt S(E->getExprLoc(),
441249423Sdim                            const_cast<Stmt *>(ThrowStmt));
442249423Sdim    CGM.getObjCRuntime().EmitThrowStmt(*this, S, false);
443249423Sdim    // This will clear insertion point which was not cleared in
444249423Sdim    // call to EmitThrowStmt.
445251662Sdim    if (KeepInsertionPoint)
446251662Sdim      EmitBlock(createBasicBlock("throw.cont"));
447249423Sdim    return;
448249423Sdim  }
449249423Sdim
450198893Srdivacky  // Now allocate the exception object.
451226633Sdim  llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
452207619Srdivacky  uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
453200583Srdivacky
454249423Sdim  llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(CGM);
455210299Sed  llvm::CallInst *ExceptionPtr =
456249423Sdim    EmitNounwindRuntimeCall(AllocExceptionFn,
457249423Sdim                            llvm::ConstantInt::get(SizeTy, TypeSize),
458249423Sdim                            "exception");
459200583Srdivacky
460207619Srdivacky  EmitAnyExprToExn(*this, E->getSubExpr(), ExceptionPtr);
461198893Srdivacky
462198893Srdivacky  // Now throw the exception.
463218893Sdim  llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
464218893Sdim                                                         /*ForEH=*/true);
465200583Srdivacky
466207619Srdivacky  // The address of the destructor.  If the exception type has a
467207619Srdivacky  // trivial destructor (or isn't a record), we just pass null.
468207619Srdivacky  llvm::Constant *Dtor = 0;
469207619Srdivacky  if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
470207619Srdivacky    CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
471207619Srdivacky    if (!Record->hasTrivialDestructor()) {
472210299Sed      CXXDestructorDecl *DtorD = Record->getDestructor();
473207619Srdivacky      Dtor = CGM.GetAddrOfCXXDestructor(DtorD, Dtor_Complete);
474207619Srdivacky      Dtor = llvm::ConstantExpr::getBitCast(Dtor, Int8PtrTy);
475207619Srdivacky    }
476207619Srdivacky  }
477207619Srdivacky  if (!Dtor) Dtor = llvm::Constant::getNullValue(Int8PtrTy);
478207619Srdivacky
479249423Sdim  llvm::Value *args[] = { ExceptionPtr, TypeInfo, Dtor };
480249423Sdim  EmitNoreturnRuntimeCallOrInvoke(getThrowFn(CGM), args);
481200583Srdivacky
482218893Sdim  // throw is an expression, and the expression emitters expect us
483218893Sdim  // to leave ourselves at a valid insertion point.
484251662Sdim  if (KeepInsertionPoint)
485251662Sdim    EmitBlock(createBasicBlock("throw.cont"));
486198893Srdivacky}
487199990Srdivacky
488200583Srdivackyvoid CodeGenFunction::EmitStartEHSpec(const Decl *D) {
489234353Sdim  if (!CGM.getLangOpts().CXXExceptions)
490203955Srdivacky    return;
491203955Srdivacky
492200583Srdivacky  const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
493200583Srdivacky  if (FD == 0)
494200583Srdivacky    return;
495200583Srdivacky  const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
496200583Srdivacky  if (Proto == 0)
497200583Srdivacky    return;
498200583Srdivacky
499221345Sdim  ExceptionSpecificationType EST = Proto->getExceptionSpecType();
500221345Sdim  if (isNoexceptExceptionSpec(EST)) {
501221345Sdim    if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
502221345Sdim      // noexcept functions are simple terminate scopes.
503221345Sdim      EHStack.pushTerminate();
504221345Sdim    }
505221345Sdim  } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
506221345Sdim    unsigned NumExceptions = Proto->getNumExceptions();
507221345Sdim    EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
508200583Srdivacky
509221345Sdim    for (unsigned I = 0; I != NumExceptions; ++I) {
510221345Sdim      QualType Ty = Proto->getExceptionType(I);
511221345Sdim      QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
512221345Sdim      llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType,
513221345Sdim                                                        /*ForEH=*/true);
514221345Sdim      Filter->setFilter(I, EHType);
515221345Sdim    }
516200583Srdivacky  }
517200583Srdivacky}
518200583Srdivacky
519226633Sdim/// Emit the dispatch block for a filter scope if necessary.
520226633Sdimstatic void emitFilterDispatchBlock(CodeGenFunction &CGF,
521226633Sdim                                    EHFilterScope &filterScope) {
522226633Sdim  llvm::BasicBlock *dispatchBlock = filterScope.getCachedEHDispatchBlock();
523226633Sdim  if (!dispatchBlock) return;
524226633Sdim  if (dispatchBlock->use_empty()) {
525226633Sdim    delete dispatchBlock;
526226633Sdim    return;
527226633Sdim  }
528226633Sdim
529226633Sdim  CGF.EmitBlockAfterUses(dispatchBlock);
530226633Sdim
531226633Sdim  // If this isn't a catch-all filter, we need to check whether we got
532226633Sdim  // here because the filter triggered.
533226633Sdim  if (filterScope.getNumFilters()) {
534226633Sdim    // Load the selector value.
535226633Sdim    llvm::Value *selector = CGF.getSelectorFromSlot();
536226633Sdim    llvm::BasicBlock *unexpectedBB = CGF.createBasicBlock("ehspec.unexpected");
537226633Sdim
538226633Sdim    llvm::Value *zero = CGF.Builder.getInt32(0);
539226633Sdim    llvm::Value *failsFilter =
540226633Sdim      CGF.Builder.CreateICmpSLT(selector, zero, "ehspec.fails");
541243830Sdim    CGF.Builder.CreateCondBr(failsFilter, unexpectedBB, CGF.getEHResumeBlock(false));
542226633Sdim
543226633Sdim    CGF.EmitBlock(unexpectedBB);
544226633Sdim  }
545226633Sdim
546226633Sdim  // Call __cxa_call_unexpected.  This doesn't need to be an invoke
547226633Sdim  // because __cxa_call_unexpected magically filters exceptions
548226633Sdim  // according to the last landing pad the exception was thrown
549226633Sdim  // into.  Seriously.
550226633Sdim  llvm::Value *exn = CGF.getExceptionFromSlot();
551249423Sdim  CGF.EmitRuntimeCall(getUnexpectedFn(CGF.CGM), exn)
552226633Sdim    ->setDoesNotReturn();
553226633Sdim  CGF.Builder.CreateUnreachable();
554226633Sdim}
555226633Sdim
556200583Srdivackyvoid CodeGenFunction::EmitEndEHSpec(const Decl *D) {
557234353Sdim  if (!CGM.getLangOpts().CXXExceptions)
558203955Srdivacky    return;
559203955Srdivacky
560200583Srdivacky  const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
561200583Srdivacky  if (FD == 0)
562200583Srdivacky    return;
563200583Srdivacky  const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
564200583Srdivacky  if (Proto == 0)
565200583Srdivacky    return;
566200583Srdivacky
567221345Sdim  ExceptionSpecificationType EST = Proto->getExceptionSpecType();
568221345Sdim  if (isNoexceptExceptionSpec(EST)) {
569221345Sdim    if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
570221345Sdim      EHStack.popTerminate();
571221345Sdim    }
572221345Sdim  } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
573226633Sdim    EHFilterScope &filterScope = cast<EHFilterScope>(*EHStack.begin());
574226633Sdim    emitFilterDispatchBlock(*this, filterScope);
575221345Sdim    EHStack.popFilter();
576221345Sdim  }
577200583Srdivacky}
578200583Srdivacky
579199990Srdivackyvoid CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
580210299Sed  EnterCXXTryStmt(S);
581204643Srdivacky  EmitStmt(S.getTryBlock());
582210299Sed  ExitCXXTryStmt(S);
583204643Srdivacky}
584204643Srdivacky
585210299Sedvoid CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
586210299Sed  unsigned NumHandlers = S.getNumHandlers();
587210299Sed  EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
588204643Srdivacky
589210299Sed  for (unsigned I = 0; I != NumHandlers; ++I) {
590210299Sed    const CXXCatchStmt *C = S.getHandler(I);
591204643Srdivacky
592210299Sed    llvm::BasicBlock *Handler = createBasicBlock("catch");
593210299Sed    if (C->getExceptionDecl()) {
594210299Sed      // FIXME: Dropping the reference type on the type into makes it
595210299Sed      // impossible to correctly implement catch-by-reference
596210299Sed      // semantics for pointers.  Unfortunately, this is what all
597210299Sed      // existing compilers do, and it's not clear that the standard
598210299Sed      // personality routine is capable of doing this right.  See C++ DR 388:
599210299Sed      //   http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
600210299Sed      QualType CaughtType = C->getCaughtType();
601210299Sed      CaughtType = CaughtType.getNonReferenceType().getUnqualifiedType();
602212904Sdim
603212904Sdim      llvm::Value *TypeInfo = 0;
604212904Sdim      if (CaughtType->isObjCObjectPointerType())
605212904Sdim        TypeInfo = CGM.getObjCRuntime().GetEHType(CaughtType);
606212904Sdim      else
607218893Sdim        TypeInfo = CGM.GetAddrOfRTTIDescriptor(CaughtType, /*ForEH=*/true);
608210299Sed      CatchScope->setHandler(I, TypeInfo, Handler);
609210299Sed    } else {
610210299Sed      // No exception decl indicates '...', a catch-all.
611210299Sed      CatchScope->setCatchAllHandler(I, Handler);
612210299Sed    }
613210299Sed  }
614204643Srdivacky}
615204643Srdivacky
616226633Sdimllvm::BasicBlock *
617226633SdimCodeGenFunction::getEHDispatchBlock(EHScopeStack::stable_iterator si) {
618226633Sdim  // The dispatch block for the end of the scope chain is a block that
619226633Sdim  // just resumes unwinding.
620226633Sdim  if (si == EHStack.stable_end())
621243830Sdim    return getEHResumeBlock(true);
622226633Sdim
623226633Sdim  // Otherwise, we should look at the actual scope.
624226633Sdim  EHScope &scope = *EHStack.find(si);
625226633Sdim
626226633Sdim  llvm::BasicBlock *dispatchBlock = scope.getCachedEHDispatchBlock();
627226633Sdim  if (!dispatchBlock) {
628226633Sdim    switch (scope.getKind()) {
629226633Sdim    case EHScope::Catch: {
630226633Sdim      // Apply a special case to a single catch-all.
631226633Sdim      EHCatchScope &catchScope = cast<EHCatchScope>(scope);
632226633Sdim      if (catchScope.getNumHandlers() == 1 &&
633226633Sdim          catchScope.getHandler(0).isCatchAll()) {
634226633Sdim        dispatchBlock = catchScope.getHandler(0).Block;
635226633Sdim
636226633Sdim      // Otherwise, make a dispatch block.
637226633Sdim      } else {
638226633Sdim        dispatchBlock = createBasicBlock("catch.dispatch");
639226633Sdim      }
640226633Sdim      break;
641226633Sdim    }
642226633Sdim
643226633Sdim    case EHScope::Cleanup:
644226633Sdim      dispatchBlock = createBasicBlock("ehcleanup");
645226633Sdim      break;
646226633Sdim
647226633Sdim    case EHScope::Filter:
648226633Sdim      dispatchBlock = createBasicBlock("filter.dispatch");
649226633Sdim      break;
650226633Sdim
651226633Sdim    case EHScope::Terminate:
652226633Sdim      dispatchBlock = getTerminateHandler();
653226633Sdim      break;
654226633Sdim    }
655226633Sdim    scope.setCachedEHDispatchBlock(dispatchBlock);
656226633Sdim  }
657226633Sdim  return dispatchBlock;
658226633Sdim}
659226633Sdim
660210299Sed/// Check whether this is a non-EH scope, i.e. a scope which doesn't
661210299Sed/// affect exception handling.  Currently, the only non-EH scopes are
662210299Sed/// normal-only cleanup scopes.
663210299Sedstatic bool isNonEHScope(const EHScope &S) {
664210299Sed  switch (S.getKind()) {
665210299Sed  case EHScope::Cleanup:
666210299Sed    return !cast<EHCleanupScope>(S).isEHCleanup();
667210299Sed  case EHScope::Filter:
668210299Sed  case EHScope::Catch:
669210299Sed  case EHScope::Terminate:
670210299Sed    return false;
671210299Sed  }
672199990Srdivacky
673234353Sdim  llvm_unreachable("Invalid EHScope Kind!");
674210299Sed}
675199990Srdivacky
676210299Sedllvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
677210299Sed  assert(EHStack.requiresLandingPad());
678210299Sed  assert(!EHStack.empty());
679199990Srdivacky
680234353Sdim  if (!CGM.getLangOpts().Exceptions)
681210299Sed    return 0;
682200583Srdivacky
683210299Sed  // Check the innermost scope for a cached landing pad.  If this is
684210299Sed  // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
685210299Sed  llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
686210299Sed  if (LP) return LP;
687200583Srdivacky
688210299Sed  // Build the landing pad for this scope.
689210299Sed  LP = EmitLandingPad();
690210299Sed  assert(LP);
691199990Srdivacky
692210299Sed  // Cache the landing pad on the innermost scope.  If this is a
693210299Sed  // non-EH scope, cache the landing pad on the enclosing scope, too.
694210299Sed  for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
695210299Sed    ir->setCachedLandingPad(LP);
696210299Sed    if (!isNonEHScope(*ir)) break;
697210299Sed  }
698199990Srdivacky
699210299Sed  return LP;
700210299Sed}
701210299Sed
702223017Sdim// This code contains a hack to work around a design flaw in
703223017Sdim// LLVM's EH IR which breaks semantics after inlining.  This same
704223017Sdim// hack is implemented in llvm-gcc.
705223017Sdim//
706223017Sdim// The LLVM EH abstraction is basically a thin veneer over the
707223017Sdim// traditional GCC zero-cost design: for each range of instructions
708223017Sdim// in the function, there is (at most) one "landing pad" with an
709223017Sdim// associated chain of EH actions.  A language-specific personality
710223017Sdim// function interprets this chain of actions and (1) decides whether
711223017Sdim// or not to resume execution at the landing pad and (2) if so,
712223017Sdim// provides an integer indicating why it's stopping.  In LLVM IR,
713223017Sdim// the association of a landing pad with a range of instructions is
714223017Sdim// achieved via an invoke instruction, the chain of actions becomes
715223017Sdim// the arguments to the @llvm.eh.selector call, and the selector
716223017Sdim// call returns the integer indicator.  Other than the required
717223017Sdim// presence of two intrinsic function calls in the landing pad,
718223017Sdim// the IR exactly describes the layout of the output code.
719223017Sdim//
720223017Sdim// A principal advantage of this design is that it is completely
721223017Sdim// language-agnostic; in theory, the LLVM optimizers can treat
722223017Sdim// landing pads neutrally, and targets need only know how to lower
723223017Sdim// the intrinsics to have a functioning exceptions system (assuming
724223017Sdim// that platform exceptions follow something approximately like the
725223017Sdim// GCC design).  Unfortunately, landing pads cannot be combined in a
726223017Sdim// language-agnostic way: given selectors A and B, there is no way
727223017Sdim// to make a single landing pad which faithfully represents the
728223017Sdim// semantics of propagating an exception first through A, then
729223017Sdim// through B, without knowing how the personality will interpret the
730223017Sdim// (lowered form of the) selectors.  This means that inlining has no
731223017Sdim// choice but to crudely chain invokes (i.e., to ignore invokes in
732223017Sdim// the inlined function, but to turn all unwindable calls into
733223017Sdim// invokes), which is only semantically valid if every unwind stops
734223017Sdim// at every landing pad.
735223017Sdim//
736223017Sdim// Therefore, the invoke-inline hack is to guarantee that every
737223017Sdim// landing pad has a catch-all.
738223017Sdimenum CleanupHackLevel_t {
739223017Sdim  /// A level of hack that requires that all landing pads have
740223017Sdim  /// catch-alls.
741223017Sdim  CHL_MandatoryCatchall,
742223017Sdim
743223017Sdim  /// A level of hack that requires that all landing pads handle
744223017Sdim  /// cleanups.
745223017Sdim  CHL_MandatoryCleanup,
746223017Sdim
747223017Sdim  /// No hacks at all;  ideal IR generation.
748223017Sdim  CHL_Ideal
749223017Sdim};
750223017Sdimconst CleanupHackLevel_t CleanupHackLevel = CHL_MandatoryCleanup;
751223017Sdim
752210299Sedllvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
753210299Sed  assert(EHStack.requiresLandingPad());
754210299Sed
755226633Sdim  EHScope &innermostEHScope = *EHStack.find(EHStack.getInnermostEHScope());
756226633Sdim  switch (innermostEHScope.getKind()) {
757226633Sdim  case EHScope::Terminate:
758226633Sdim    return getTerminateLandingPad();
759210299Sed
760226633Sdim  case EHScope::Catch:
761226633Sdim  case EHScope::Cleanup:
762226633Sdim  case EHScope::Filter:
763226633Sdim    if (llvm::BasicBlock *lpad = innermostEHScope.getCachedLandingPad())
764226633Sdim      return lpad;
765210299Sed  }
766210299Sed
767210299Sed  // Save the current IR generation state.
768226633Sdim  CGBuilderTy::InsertPoint savedIP = Builder.saveAndClearIP();
769263508Sdim  SourceLocation SavedLocation;
770263508Sdim  if (CGDebugInfo *DI = getDebugInfo()) {
771263508Sdim    SavedLocation = DI->getLocation();
772263508Sdim    DI->EmitLocation(Builder, CurEHLocation);
773263508Sdim  }
774210299Sed
775234353Sdim  const EHPersonality &personality = EHPersonality::get(getLangOpts());
776212904Sdim
777210299Sed  // Create and configure the landing pad.
778226633Sdim  llvm::BasicBlock *lpad = createBasicBlock("lpad");
779226633Sdim  EmitBlock(lpad);
780210299Sed
781226633Sdim  llvm::LandingPadInst *LPadInst =
782226633Sdim    Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, NULL),
783226633Sdim                             getOpaquePersonalityFn(CGM, personality), 0);
784226633Sdim
785226633Sdim  llvm::Value *LPadExn = Builder.CreateExtractValue(LPadInst, 0);
786226633Sdim  Builder.CreateStore(LPadExn, getExceptionSlot());
787226633Sdim  llvm::Value *LPadSel = Builder.CreateExtractValue(LPadInst, 1);
788226633Sdim  Builder.CreateStore(LPadSel, getEHSelectorSlot());
789226633Sdim
790210299Sed  // Save the exception pointer.  It's safe to use a single exception
791210299Sed  // pointer per function because EH cleanups can never have nested
792210299Sed  // try/catches.
793226633Sdim  // Build the landingpad instruction.
794210299Sed
795210299Sed  // Accumulate all the handlers in scope.
796226633Sdim  bool hasCatchAll = false;
797226633Sdim  bool hasCleanup = false;
798226633Sdim  bool hasFilter = false;
799226633Sdim  SmallVector<llvm::Value*, 4> filterTypes;
800226633Sdim  llvm::SmallPtrSet<llvm::Value*, 4> catchTypes;
801210299Sed  for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end();
802210299Sed         I != E; ++I) {
803210299Sed
804210299Sed    switch (I->getKind()) {
805210299Sed    case EHScope::Cleanup:
806226633Sdim      // If we have a cleanup, remember that.
807226633Sdim      hasCleanup = (hasCleanup || cast<EHCleanupScope>(*I).isEHCleanup());
808210299Sed      continue;
809210299Sed
810210299Sed    case EHScope::Filter: {
811210299Sed      assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
812226633Sdim      assert(!hasCatchAll && "EH filter reached after catch-all");
813210299Sed
814226633Sdim      // Filter scopes get added to the landingpad in weird ways.
815226633Sdim      EHFilterScope &filter = cast<EHFilterScope>(*I);
816226633Sdim      hasFilter = true;
817210299Sed
818226633Sdim      // Add all the filter values.
819226633Sdim      for (unsigned i = 0, e = filter.getNumFilters(); i != e; ++i)
820226633Sdim        filterTypes.push_back(filter.getFilter(i));
821210299Sed      goto done;
822199990Srdivacky    }
823210299Sed
824210299Sed    case EHScope::Terminate:
825210299Sed      // Terminate scopes are basically catch-alls.
826226633Sdim      assert(!hasCatchAll);
827226633Sdim      hasCatchAll = true;
828210299Sed      goto done;
829210299Sed
830210299Sed    case EHScope::Catch:
831210299Sed      break;
832210299Sed    }
833210299Sed
834226633Sdim    EHCatchScope &catchScope = cast<EHCatchScope>(*I);
835226633Sdim    for (unsigned hi = 0, he = catchScope.getNumHandlers(); hi != he; ++hi) {
836226633Sdim      EHCatchScope::Handler handler = catchScope.getHandler(hi);
837210299Sed
838226633Sdim      // If this is a catch-all, register that and abort.
839226633Sdim      if (!handler.Type) {
840226633Sdim        assert(!hasCatchAll);
841226633Sdim        hasCatchAll = true;
842226633Sdim        goto done;
843210299Sed      }
844210299Sed
845210299Sed      // Check whether we already have a handler for this type.
846226633Sdim      if (catchTypes.insert(handler.Type))
847226633Sdim        // If not, add it directly to the landingpad.
848226633Sdim        LPadInst->addClause(handler.Type);
849210299Sed    }
850199990Srdivacky  }
851199990Srdivacky
852210299Sed done:
853226633Sdim  // If we have a catch-all, add null to the landingpad.
854226633Sdim  assert(!(hasCatchAll && hasFilter));
855226633Sdim  if (hasCatchAll) {
856226633Sdim    LPadInst->addClause(getCatchAllValue(*this));
857210299Sed
858210299Sed  // If we have an EH filter, we need to add those handlers in the
859226633Sdim  // right place in the landingpad, which is to say, at the end.
860226633Sdim  } else if (hasFilter) {
861226633Sdim    // Create a filter expression: a constant array indicating which filter
862226633Sdim    // types there are. The personality routine only lands here if the filter
863226633Sdim    // doesn't match.
864249423Sdim    SmallVector<llvm::Constant*, 8> Filters;
865226633Sdim    llvm::ArrayType *AType =
866226633Sdim      llvm::ArrayType::get(!filterTypes.empty() ?
867226633Sdim                             filterTypes[0]->getType() : Int8PtrTy,
868226633Sdim                           filterTypes.size());
869210299Sed
870226633Sdim    for (unsigned i = 0, e = filterTypes.size(); i != e; ++i)
871226633Sdim      Filters.push_back(cast<llvm::Constant>(filterTypes[i]));
872226633Sdim    llvm::Constant *FilterArray = llvm::ConstantArray::get(AType, Filters);
873226633Sdim    LPadInst->addClause(FilterArray);
874226633Sdim
875210299Sed    // Also check whether we need a cleanup.
876226633Sdim    if (hasCleanup)
877226633Sdim      LPadInst->setCleanup(true);
878210299Sed
879210299Sed  // Otherwise, signal that we at least have cleanups.
880226633Sdim  } else if (CleanupHackLevel == CHL_MandatoryCatchall || hasCleanup) {
881226633Sdim    if (CleanupHackLevel == CHL_MandatoryCatchall)
882226633Sdim      LPadInst->addClause(getCatchAllValue(*this));
883226633Sdim    else
884226633Sdim      LPadInst->setCleanup(true);
885199990Srdivacky  }
886199990Srdivacky
887226633Sdim  assert((LPadInst->getNumClauses() > 0 || LPadInst->isCleanup()) &&
888226633Sdim         "landingpad instruction has no clauses!");
889199990Srdivacky
890210299Sed  // Tell the backend how to generate the landing pad.
891226633Sdim  Builder.CreateBr(getEHDispatchBlock(EHStack.getInnermostEHScope()));
892223017Sdim
893210299Sed  // Restore the old IR generation state.
894226633Sdim  Builder.restoreIP(savedIP);
895263508Sdim  if (CGDebugInfo *DI = getDebugInfo())
896263508Sdim    DI->EmitLocation(Builder, SavedLocation);
897210299Sed
898226633Sdim  return lpad;
899210299Sed}
900210299Sed
901210299Sednamespace {
902210299Sed  /// A cleanup to call __cxa_end_catch.  In many cases, the caught
903210299Sed  /// exception type lets us state definitively that the thrown exception
904210299Sed  /// type does not have a destructor.  In particular:
905210299Sed  ///   - Catch-alls tell us nothing, so we have to conservatively
906210299Sed  ///     assume that the thrown exception might have a destructor.
907210299Sed  ///   - Catches by reference behave according to their base types.
908210299Sed  ///   - Catches of non-record types will only trigger for exceptions
909210299Sed  ///     of non-record types, which never have destructors.
910210299Sed  ///   - Catches of record types can trigger for arbitrary subclasses
911210299Sed  ///     of the caught type, so we have to assume the actual thrown
912210299Sed  ///     exception type might have a throwing destructor, even if the
913210299Sed  ///     caught type's destructor is trivial or nothrow.
914212904Sdim  struct CallEndCatch : EHScopeStack::Cleanup {
915210299Sed    CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
916210299Sed    bool MightThrow;
917210299Sed
918224145Sdim    void Emit(CodeGenFunction &CGF, Flags flags) {
919210299Sed      if (!MightThrow) {
920249423Sdim        CGF.EmitNounwindRuntimeCall(getEndCatchFn(CGF.CGM));
921210299Sed        return;
922210299Sed      }
923210299Sed
924249423Sdim      CGF.EmitRuntimeCallOrInvoke(getEndCatchFn(CGF.CGM));
925210299Sed    }
926210299Sed  };
927210299Sed}
928210299Sed
929210299Sed/// Emits a call to __cxa_begin_catch and enters a cleanup to call
930210299Sed/// __cxa_end_catch.
931210299Sed///
932210299Sed/// \param EndMightThrow - true if __cxa_end_catch might throw
933210299Sedstatic llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
934210299Sed                                   llvm::Value *Exn,
935210299Sed                                   bool EndMightThrow) {
936249423Sdim  llvm::CallInst *call =
937249423Sdim    CGF.EmitNounwindRuntimeCall(getBeginCatchFn(CGF.CGM), Exn);
938210299Sed
939212904Sdim  CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
940210299Sed
941249423Sdim  return call;
942210299Sed}
943210299Sed
944210299Sed/// A "special initializer" callback for initializing a catch
945210299Sed/// parameter during catch initialization.
946210299Sedstatic void InitCatchParam(CodeGenFunction &CGF,
947210299Sed                           const VarDecl &CatchParam,
948263508Sdim                           llvm::Value *ParamAddr,
949263508Sdim                           SourceLocation Loc) {
950210299Sed  // Load the exception from where the landing pad saved it.
951226633Sdim  llvm::Value *Exn = CGF.getExceptionFromSlot();
952210299Sed
953210299Sed  CanQualType CatchType =
954210299Sed    CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
955226633Sdim  llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
956210299Sed
957210299Sed  // If we're catching by reference, we can just cast the object
958210299Sed  // pointer to the appropriate pointer.
959210299Sed  if (isa<ReferenceType>(CatchType)) {
960212904Sdim    QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
961212904Sdim    bool EndCatchMightThrow = CaughtType->isRecordType();
962210299Sed
963210299Sed    // __cxa_begin_catch returns the adjusted object pointer.
964210299Sed    llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
965212904Sdim
966212904Sdim    // We have no way to tell the personality function that we're
967212904Sdim    // catching by reference, so if we're catching a pointer,
968212904Sdim    // __cxa_begin_catch will actually return that pointer by value.
969212904Sdim    if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
970212904Sdim      QualType PointeeType = PT->getPointeeType();
971212904Sdim
972212904Sdim      // When catching by reference, generally we should just ignore
973212904Sdim      // this by-value pointer and use the exception object instead.
974212904Sdim      if (!PointeeType->isRecordType()) {
975212904Sdim
976212904Sdim        // Exn points to the struct _Unwind_Exception header, which
977212904Sdim        // we have to skip past in order to reach the exception data.
978212904Sdim        unsigned HeaderSize =
979212904Sdim          CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
980212904Sdim        AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
981212904Sdim
982212904Sdim      // However, if we're catching a pointer-to-record type that won't
983212904Sdim      // work, because the personality function might have adjusted
984212904Sdim      // the pointer.  There's actually no way for us to fully satisfy
985212904Sdim      // the language/ABI contract here:  we can't use Exn because it
986212904Sdim      // might have the wrong adjustment, but we can't use the by-value
987212904Sdim      // pointer because it's off by a level of abstraction.
988212904Sdim      //
989212904Sdim      // The current solution is to dump the adjusted pointer into an
990212904Sdim      // alloca, which breaks language semantics (because changing the
991212904Sdim      // pointer doesn't change the exception) but at least works.
992212904Sdim      // The better solution would be to filter out non-exact matches
993212904Sdim      // and rethrow them, but this is tricky because the rethrow
994212904Sdim      // really needs to be catchable by other sites at this landing
995212904Sdim      // pad.  The best solution is to fix the personality function.
996212904Sdim      } else {
997212904Sdim        // Pull the pointer for the reference type off.
998226633Sdim        llvm::Type *PtrTy =
999212904Sdim          cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
1000212904Sdim
1001212904Sdim        // Create the temporary and write the adjusted pointer into it.
1002212904Sdim        llvm::Value *ExnPtrTmp = CGF.CreateTempAlloca(PtrTy, "exn.byref.tmp");
1003212904Sdim        llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1004212904Sdim        CGF.Builder.CreateStore(Casted, ExnPtrTmp);
1005212904Sdim
1006212904Sdim        // Bind the reference to the temporary.
1007212904Sdim        AdjustedExn = ExnPtrTmp;
1008212904Sdim      }
1009212904Sdim    }
1010212904Sdim
1011210299Sed    llvm::Value *ExnCast =
1012210299Sed      CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
1013210299Sed    CGF.Builder.CreateStore(ExnCast, ParamAddr);
1014210299Sed    return;
1015200583Srdivacky  }
1016199990Srdivacky
1017249423Sdim  // Scalars and complexes.
1018249423Sdim  TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType);
1019249423Sdim  if (TEK != TEK_Aggregate) {
1020210299Sed    llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
1021210299Sed
1022210299Sed    // If the catch type is a pointer type, __cxa_begin_catch returns
1023210299Sed    // the pointer by value.
1024210299Sed    if (CatchType->hasPointerRepresentation()) {
1025210299Sed      llvm::Value *CastExn =
1026210299Sed        CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
1027234353Sdim
1028234353Sdim      switch (CatchType.getQualifiers().getObjCLifetime()) {
1029234353Sdim      case Qualifiers::OCL_Strong:
1030234353Sdim        CastExn = CGF.EmitARCRetainNonBlock(CastExn);
1031234353Sdim        // fallthrough
1032234353Sdim
1033234353Sdim      case Qualifiers::OCL_None:
1034234353Sdim      case Qualifiers::OCL_ExplicitNone:
1035234353Sdim      case Qualifiers::OCL_Autoreleasing:
1036234353Sdim        CGF.Builder.CreateStore(CastExn, ParamAddr);
1037234353Sdim        return;
1038234353Sdim
1039234353Sdim      case Qualifiers::OCL_Weak:
1040234353Sdim        CGF.EmitARCInitWeak(ParamAddr, CastExn);
1041234353Sdim        return;
1042234353Sdim      }
1043234353Sdim      llvm_unreachable("bad ownership qualifier!");
1044210299Sed    }
1045199990Srdivacky
1046210299Sed    // Otherwise, it returns a pointer into the exception object.
1047199990Srdivacky
1048226633Sdim    llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
1049210299Sed    llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1050199990Srdivacky
1051249423Sdim    LValue srcLV = CGF.MakeNaturalAlignAddrLValue(Cast, CatchType);
1052249423Sdim    LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType,
1053249423Sdim                                  CGF.getContext().getDeclAlign(&CatchParam));
1054249423Sdim    switch (TEK) {
1055249423Sdim    case TEK_Complex:
1056263508Sdim      CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV,
1057249423Sdim                             /*init*/ true);
1058249423Sdim      return;
1059249423Sdim    case TEK_Scalar: {
1060263508Sdim      llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc);
1061249423Sdim      CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true);
1062249423Sdim      return;
1063210299Sed    }
1064249423Sdim    case TEK_Aggregate:
1065249423Sdim      llvm_unreachable("evaluation kind filtered out!");
1066249423Sdim    }
1067249423Sdim    llvm_unreachable("bad evaluation kind");
1068210299Sed  }
1069199990Srdivacky
1070218893Sdim  assert(isa<RecordType>(CatchType) && "unexpected catch type!");
1071199990Srdivacky
1072226633Sdim  llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
1073199990Srdivacky
1074218893Sdim  // Check for a copy expression.  If we don't have a copy expression,
1075218893Sdim  // that means a trivial copy is okay.
1076218893Sdim  const Expr *copyExpr = CatchParam.getInit();
1077218893Sdim  if (!copyExpr) {
1078218893Sdim    llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
1079218893Sdim    llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
1080218893Sdim    CGF.EmitAggregateCopy(ParamAddr, adjustedExn, CatchType);
1081210299Sed    return;
1082210299Sed  }
1083210299Sed
1084210299Sed  // We have to call __cxa_get_exception_ptr to get the adjusted
1085210299Sed  // pointer before copying.
1086218893Sdim  llvm::CallInst *rawAdjustedExn =
1087249423Sdim    CGF.EmitNounwindRuntimeCall(getGetExceptionPtrFn(CGF.CGM), Exn);
1088210299Sed
1089218893Sdim  // Cast that to the appropriate type.
1090218893Sdim  llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
1091210299Sed
1092218893Sdim  // The copy expression is defined in terms of an OpaqueValueExpr.
1093218893Sdim  // Find it and map it to the adjusted expression.
1094218893Sdim  CodeGenFunction::OpaqueValueMapping
1095218893Sdim    opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
1096218893Sdim           CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
1097210299Sed
1098210299Sed  // Call the copy ctor in a terminate scope.
1099210299Sed  CGF.EHStack.pushTerminate();
1100218893Sdim
1101218893Sdim  // Perform the copy construction.
1102234353Sdim  CharUnits Alignment = CGF.getContext().getDeclAlign(&CatchParam);
1103234353Sdim  CGF.EmitAggExpr(copyExpr,
1104234353Sdim                  AggValueSlot::forAddr(ParamAddr, Alignment, Qualifiers(),
1105234353Sdim                                        AggValueSlot::IsNotDestructed,
1106234353Sdim                                        AggValueSlot::DoesNotNeedGCBarriers,
1107234353Sdim                                        AggValueSlot::IsNotAliased));
1108218893Sdim
1109218893Sdim  // Leave the terminate scope.
1110210299Sed  CGF.EHStack.popTerminate();
1111210299Sed
1112218893Sdim  // Undo the opaque value mapping.
1113218893Sdim  opaque.pop();
1114218893Sdim
1115210299Sed  // Finally we can call __cxa_begin_catch.
1116210299Sed  CallBeginCatch(CGF, Exn, true);
1117199990Srdivacky}
1118200583Srdivacky
1119210299Sed/// Begins a catch statement by initializing the catch variable and
1120210299Sed/// calling __cxa_begin_catch.
1121218893Sdimstatic void BeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *S) {
1122210299Sed  // We have to be very careful with the ordering of cleanups here:
1123210299Sed  //   C++ [except.throw]p4:
1124210299Sed  //     The destruction [of the exception temporary] occurs
1125210299Sed  //     immediately after the destruction of the object declared in
1126210299Sed  //     the exception-declaration in the handler.
1127210299Sed  //
1128210299Sed  // So the precise ordering is:
1129210299Sed  //   1.  Construct catch variable.
1130210299Sed  //   2.  __cxa_begin_catch
1131210299Sed  //   3.  Enter __cxa_end_catch cleanup
1132210299Sed  //   4.  Enter dtor cleanup
1133210299Sed  //
1134219077Sdim  // We do this by using a slightly abnormal initialization process.
1135219077Sdim  // Delegation sequence:
1136210299Sed  //   - ExitCXXTryStmt opens a RunCleanupsScope
1137219077Sdim  //     - EmitAutoVarAlloca creates the variable and debug info
1138210299Sed  //       - InitCatchParam initializes the variable from the exception
1139219077Sdim  //       - CallBeginCatch calls __cxa_begin_catch
1140219077Sdim  //       - CallBeginCatch enters the __cxa_end_catch cleanup
1141219077Sdim  //     - EmitAutoVarCleanups enters the variable destructor cleanup
1142210299Sed  //   - EmitCXXTryStmt emits the code for the catch body
1143210299Sed  //   - EmitCXXTryStmt close the RunCleanupsScope
1144200583Srdivacky
1145210299Sed  VarDecl *CatchParam = S->getExceptionDecl();
1146210299Sed  if (!CatchParam) {
1147226633Sdim    llvm::Value *Exn = CGF.getExceptionFromSlot();
1148210299Sed    CallBeginCatch(CGF, Exn, true);
1149210299Sed    return;
1150210299Sed  }
1151200583Srdivacky
1152210299Sed  // Emit the local.
1153219077Sdim  CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
1154263508Sdim  InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF), S->getLocStart());
1155219077Sdim  CGF.EmitAutoVarCleanups(var);
1156210299Sed}
1157207619Srdivacky
1158226633Sdim/// Emit the structure of the dispatch block for the given catch scope.
1159226633Sdim/// It is an invariant that the dispatch block already exists.
1160226633Sdimstatic void emitCatchDispatchBlock(CodeGenFunction &CGF,
1161226633Sdim                                   EHCatchScope &catchScope) {
1162226633Sdim  llvm::BasicBlock *dispatchBlock = catchScope.getCachedEHDispatchBlock();
1163226633Sdim  assert(dispatchBlock);
1164226633Sdim
1165226633Sdim  // If there's only a single catch-all, getEHDispatchBlock returned
1166226633Sdim  // that catch-all as the dispatch block.
1167226633Sdim  if (catchScope.getNumHandlers() == 1 &&
1168226633Sdim      catchScope.getHandler(0).isCatchAll()) {
1169226633Sdim    assert(dispatchBlock == catchScope.getHandler(0).Block);
1170226633Sdim    return;
1171226633Sdim  }
1172226633Sdim
1173226633Sdim  CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveIP();
1174226633Sdim  CGF.EmitBlockAfterUses(dispatchBlock);
1175226633Sdim
1176226633Sdim  // Select the right handler.
1177226633Sdim  llvm::Value *llvm_eh_typeid_for =
1178226633Sdim    CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
1179226633Sdim
1180226633Sdim  // Load the selector value.
1181226633Sdim  llvm::Value *selector = CGF.getSelectorFromSlot();
1182226633Sdim
1183226633Sdim  // Test against each of the exception types we claim to catch.
1184226633Sdim  for (unsigned i = 0, e = catchScope.getNumHandlers(); ; ++i) {
1185226633Sdim    assert(i < e && "ran off end of handlers!");
1186226633Sdim    const EHCatchScope::Handler &handler = catchScope.getHandler(i);
1187226633Sdim
1188226633Sdim    llvm::Value *typeValue = handler.Type;
1189226633Sdim    assert(typeValue && "fell into catch-all case!");
1190226633Sdim    typeValue = CGF.Builder.CreateBitCast(typeValue, CGF.Int8PtrTy);
1191226633Sdim
1192226633Sdim    // Figure out the next block.
1193226633Sdim    bool nextIsEnd;
1194226633Sdim    llvm::BasicBlock *nextBlock;
1195226633Sdim
1196226633Sdim    // If this is the last handler, we're at the end, and the next
1197226633Sdim    // block is the block for the enclosing EH scope.
1198226633Sdim    if (i + 1 == e) {
1199226633Sdim      nextBlock = CGF.getEHDispatchBlock(catchScope.getEnclosingEHScope());
1200226633Sdim      nextIsEnd = true;
1201226633Sdim
1202226633Sdim    // If the next handler is a catch-all, we're at the end, and the
1203226633Sdim    // next block is that handler.
1204226633Sdim    } else if (catchScope.getHandler(i+1).isCatchAll()) {
1205226633Sdim      nextBlock = catchScope.getHandler(i+1).Block;
1206226633Sdim      nextIsEnd = true;
1207226633Sdim
1208226633Sdim    // Otherwise, we're not at the end and we need a new block.
1209226633Sdim    } else {
1210226633Sdim      nextBlock = CGF.createBasicBlock("catch.fallthrough");
1211226633Sdim      nextIsEnd = false;
1212226633Sdim    }
1213226633Sdim
1214226633Sdim    // Figure out the catch type's index in the LSDA's type table.
1215226633Sdim    llvm::CallInst *typeIndex =
1216226633Sdim      CGF.Builder.CreateCall(llvm_eh_typeid_for, typeValue);
1217226633Sdim    typeIndex->setDoesNotThrow();
1218226633Sdim
1219226633Sdim    llvm::Value *matchesTypeIndex =
1220226633Sdim      CGF.Builder.CreateICmpEQ(selector, typeIndex, "matches");
1221226633Sdim    CGF.Builder.CreateCondBr(matchesTypeIndex, handler.Block, nextBlock);
1222226633Sdim
1223226633Sdim    // If the next handler is a catch-all, we're completely done.
1224226633Sdim    if (nextIsEnd) {
1225226633Sdim      CGF.Builder.restoreIP(savedIP);
1226226633Sdim      return;
1227234353Sdim    }
1228226633Sdim    // Otherwise we need to emit and continue at that block.
1229234353Sdim    CGF.EmitBlock(nextBlock);
1230226633Sdim  }
1231226633Sdim}
1232226633Sdim
1233226633Sdimvoid CodeGenFunction::popCatchScope() {
1234226633Sdim  EHCatchScope &catchScope = cast<EHCatchScope>(*EHStack.begin());
1235226633Sdim  if (catchScope.hasEHBranches())
1236226633Sdim    emitCatchDispatchBlock(*this, catchScope);
1237226633Sdim  EHStack.popCatch();
1238226633Sdim}
1239226633Sdim
1240210299Sedvoid CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
1241210299Sed  unsigned NumHandlers = S.getNumHandlers();
1242210299Sed  EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1243210299Sed  assert(CatchScope.getNumHandlers() == NumHandlers);
1244207619Srdivacky
1245226633Sdim  // If the catch was not required, bail out now.
1246226633Sdim  if (!CatchScope.hasEHBranches()) {
1247226633Sdim    EHStack.popCatch();
1248226633Sdim    return;
1249226633Sdim  }
1250226633Sdim
1251226633Sdim  // Emit the structure of the EH dispatch for this catch.
1252226633Sdim  emitCatchDispatchBlock(*this, CatchScope);
1253226633Sdim
1254210299Sed  // Copy the handler blocks off before we pop the EH stack.  Emitting
1255210299Sed  // the handlers might scribble on this memory.
1256226633Sdim  SmallVector<EHCatchScope::Handler, 8> Handlers(NumHandlers);
1257210299Sed  memcpy(Handlers.data(), CatchScope.begin(),
1258210299Sed         NumHandlers * sizeof(EHCatchScope::Handler));
1259226633Sdim
1260210299Sed  EHStack.popCatch();
1261200583Srdivacky
1262210299Sed  // The fall-through block.
1263210299Sed  llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
1264200583Srdivacky
1265210299Sed  // We just emitted the body of the try; jump to the continue block.
1266210299Sed  if (HaveInsertPoint())
1267210299Sed    Builder.CreateBr(ContBB);
1268210299Sed
1269239462Sdim  // Determine if we need an implicit rethrow for all these catch handlers;
1270239462Sdim  // see the comment below.
1271239462Sdim  bool doImplicitRethrow = false;
1272210299Sed  if (IsFnTryBlock)
1273239462Sdim    doImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
1274239462Sdim                        isa<CXXConstructorDecl>(CurCodeDecl);
1275210299Sed
1276226633Sdim  // Perversely, we emit the handlers backwards precisely because we
1277226633Sdim  // want them to appear in source order.  In all of these cases, the
1278226633Sdim  // catch block will have exactly one predecessor, which will be a
1279226633Sdim  // particular block in the catch dispatch.  However, in the case of
1280226633Sdim  // a catch-all, one of the dispatch blocks will branch to two
1281226633Sdim  // different handlers, and EmitBlockAfterUses will cause the second
1282226633Sdim  // handler to be moved before the first.
1283226633Sdim  for (unsigned I = NumHandlers; I != 0; --I) {
1284226633Sdim    llvm::BasicBlock *CatchBlock = Handlers[I-1].Block;
1285226633Sdim    EmitBlockAfterUses(CatchBlock);
1286210299Sed
1287210299Sed    // Catch the exception if this isn't a catch-all.
1288226633Sdim    const CXXCatchStmt *C = S.getHandler(I-1);
1289210299Sed
1290210299Sed    // Enter a cleanup scope, including the catch variable and the
1291210299Sed    // end-catch.
1292210299Sed    RunCleanupsScope CatchScope(*this);
1293210299Sed
1294210299Sed    // Initialize the catch variable and set up the cleanups.
1295210299Sed    BeginCatch(*this, C);
1296210299Sed
1297210299Sed    // Perform the body of the catch.
1298210299Sed    EmitStmt(C->getHandlerBlock());
1299210299Sed
1300239462Sdim    // [except.handle]p11:
1301239462Sdim    //   The currently handled exception is rethrown if control
1302239462Sdim    //   reaches the end of a handler of the function-try-block of a
1303239462Sdim    //   constructor or destructor.
1304239462Sdim
1305239462Sdim    // It is important that we only do this on fallthrough and not on
1306239462Sdim    // return.  Note that it's illegal to put a return in a
1307239462Sdim    // constructor function-try-block's catch handler (p14), so this
1308239462Sdim    // really only applies to destructors.
1309239462Sdim    if (doImplicitRethrow && HaveInsertPoint()) {
1310249423Sdim      EmitRuntimeCallOrInvoke(getReThrowFn(CGM));
1311239462Sdim      Builder.CreateUnreachable();
1312239462Sdim      Builder.ClearInsertionPoint();
1313239462Sdim    }
1314239462Sdim
1315210299Sed    // Fall out through the catch cleanups.
1316210299Sed    CatchScope.ForceCleanup();
1317210299Sed
1318210299Sed    // Branch out of the try.
1319210299Sed    if (HaveInsertPoint())
1320210299Sed      Builder.CreateBr(ContBB);
1321210299Sed  }
1322210299Sed
1323210299Sed  EmitBlock(ContBB);
1324210299Sed}
1325210299Sed
1326212904Sdimnamespace {
1327212904Sdim  struct CallEndCatchForFinally : EHScopeStack::Cleanup {
1328212904Sdim    llvm::Value *ForEHVar;
1329212904Sdim    llvm::Value *EndCatchFn;
1330212904Sdim    CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn)
1331212904Sdim      : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
1332212904Sdim
1333224145Sdim    void Emit(CodeGenFunction &CGF, Flags flags) {
1334212904Sdim      llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
1335212904Sdim      llvm::BasicBlock *CleanupContBB =
1336212904Sdim        CGF.createBasicBlock("finally.cleanup.cont");
1337212904Sdim
1338212904Sdim      llvm::Value *ShouldEndCatch =
1339212904Sdim        CGF.Builder.CreateLoad(ForEHVar, "finally.endcatch");
1340212904Sdim      CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1341212904Sdim      CGF.EmitBlock(EndCatchBB);
1342249423Sdim      CGF.EmitRuntimeCallOrInvoke(EndCatchFn); // catch-all, so might throw
1343212904Sdim      CGF.EmitBlock(CleanupContBB);
1344212904Sdim    }
1345212904Sdim  };
1346212904Sdim
1347212904Sdim  struct PerformFinally : EHScopeStack::Cleanup {
1348212904Sdim    const Stmt *Body;
1349212904Sdim    llvm::Value *ForEHVar;
1350212904Sdim    llvm::Value *EndCatchFn;
1351212904Sdim    llvm::Value *RethrowFn;
1352212904Sdim    llvm::Value *SavedExnVar;
1353212904Sdim
1354212904Sdim    PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
1355212904Sdim                   llvm::Value *EndCatchFn,
1356212904Sdim                   llvm::Value *RethrowFn, llvm::Value *SavedExnVar)
1357212904Sdim      : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1358212904Sdim        RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
1359212904Sdim
1360224145Sdim    void Emit(CodeGenFunction &CGF, Flags flags) {
1361212904Sdim      // Enter a cleanup to call the end-catch function if one was provided.
1362212904Sdim      if (EndCatchFn)
1363212904Sdim        CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
1364212904Sdim                                                        ForEHVar, EndCatchFn);
1365212904Sdim
1366212904Sdim      // Save the current cleanup destination in case there are
1367212904Sdim      // cleanups in the finally block.
1368212904Sdim      llvm::Value *SavedCleanupDest =
1369212904Sdim        CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
1370212904Sdim                               "cleanup.dest.saved");
1371212904Sdim
1372212904Sdim      // Emit the finally block.
1373212904Sdim      CGF.EmitStmt(Body);
1374212904Sdim
1375212904Sdim      // If the end of the finally is reachable, check whether this was
1376212904Sdim      // for EH.  If so, rethrow.
1377212904Sdim      if (CGF.HaveInsertPoint()) {
1378212904Sdim        llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
1379212904Sdim        llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
1380212904Sdim
1381212904Sdim        llvm::Value *ShouldRethrow =
1382212904Sdim          CGF.Builder.CreateLoad(ForEHVar, "finally.shouldthrow");
1383212904Sdim        CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1384212904Sdim
1385212904Sdim        CGF.EmitBlock(RethrowBB);
1386212904Sdim        if (SavedExnVar) {
1387249423Sdim          CGF.EmitRuntimeCallOrInvoke(RethrowFn,
1388249423Sdim                                      CGF.Builder.CreateLoad(SavedExnVar));
1389212904Sdim        } else {
1390249423Sdim          CGF.EmitRuntimeCallOrInvoke(RethrowFn);
1391212904Sdim        }
1392212904Sdim        CGF.Builder.CreateUnreachable();
1393212904Sdim
1394212904Sdim        CGF.EmitBlock(ContBB);
1395212904Sdim
1396212904Sdim        // Restore the cleanup destination.
1397212904Sdim        CGF.Builder.CreateStore(SavedCleanupDest,
1398212904Sdim                                CGF.getNormalCleanupDestSlot());
1399212904Sdim      }
1400212904Sdim
1401212904Sdim      // Leave the end-catch cleanup.  As an optimization, pretend that
1402212904Sdim      // the fallthrough path was inaccessible; we've dynamically proven
1403212904Sdim      // that we're not in the EH case along that path.
1404212904Sdim      if (EndCatchFn) {
1405212904Sdim        CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1406212904Sdim        CGF.PopCleanupBlock();
1407212904Sdim        CGF.Builder.restoreIP(SavedIP);
1408212904Sdim      }
1409212904Sdim
1410212904Sdim      // Now make sure we actually have an insertion point or the
1411212904Sdim      // cleanup gods will hate us.
1412212904Sdim      CGF.EnsureInsertPoint();
1413212904Sdim    }
1414212904Sdim  };
1415212904Sdim}
1416212904Sdim
1417210299Sed/// Enters a finally block for an implementation using zero-cost
1418210299Sed/// exceptions.  This is mostly general, but hard-codes some
1419210299Sed/// language/ABI-specific behavior in the catch-all sections.
1420224145Sdimvoid CodeGenFunction::FinallyInfo::enter(CodeGenFunction &CGF,
1421224145Sdim                                         const Stmt *body,
1422224145Sdim                                         llvm::Constant *beginCatchFn,
1423224145Sdim                                         llvm::Constant *endCatchFn,
1424224145Sdim                                         llvm::Constant *rethrowFn) {
1425224145Sdim  assert((beginCatchFn != 0) == (endCatchFn != 0) &&
1426210299Sed         "begin/end catch functions not paired");
1427224145Sdim  assert(rethrowFn && "rethrow function is required");
1428210299Sed
1429224145Sdim  BeginCatchFn = beginCatchFn;
1430224145Sdim
1431210299Sed  // The rethrow function has one of the following two types:
1432210299Sed  //   void (*)()
1433210299Sed  //   void (*)(void*)
1434210299Sed  // In the latter case we need to pass it the exception object.
1435210299Sed  // But we can't use the exception slot because the @finally might
1436210299Sed  // have a landing pad (which would overwrite the exception slot).
1437226633Sdim  llvm::FunctionType *rethrowFnTy =
1438210299Sed    cast<llvm::FunctionType>(
1439224145Sdim      cast<llvm::PointerType>(rethrowFn->getType())->getElementType());
1440224145Sdim  SavedExnVar = 0;
1441224145Sdim  if (rethrowFnTy->getNumParams())
1442224145Sdim    SavedExnVar = CGF.CreateTempAlloca(CGF.Int8PtrTy, "finally.exn");
1443210299Sed
1444210299Sed  // A finally block is a statement which must be executed on any edge
1445210299Sed  // out of a given scope.  Unlike a cleanup, the finally block may
1446210299Sed  // contain arbitrary control flow leading out of itself.  In
1447210299Sed  // addition, finally blocks should always be executed, even if there
1448210299Sed  // are no catch handlers higher on the stack.  Therefore, we
1449210299Sed  // surround the protected scope with a combination of a normal
1450210299Sed  // cleanup (to catch attempts to break out of the block via normal
1451210299Sed  // control flow) and an EH catch-all (semantically "outside" any try
1452210299Sed  // statement to which the finally block might have been attached).
1453210299Sed  // The finally block itself is generated in the context of a cleanup
1454210299Sed  // which conditionally leaves the catch-all.
1455210299Sed
1456210299Sed  // Jump destination for performing the finally block on an exception
1457210299Sed  // edge.  We'll never actually reach this block, so unreachable is
1458210299Sed  // fine.
1459224145Sdim  RethrowDest = CGF.getJumpDestInCurrentScope(CGF.getUnreachableBlock());
1460210299Sed
1461210299Sed  // Whether the finally block is being executed for EH purposes.
1462224145Sdim  ForEHVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "finally.for-eh");
1463224145Sdim  CGF.Builder.CreateStore(CGF.Builder.getFalse(), ForEHVar);
1464210299Sed
1465210299Sed  // Enter a normal cleanup which will perform the @finally block.
1466224145Sdim  CGF.EHStack.pushCleanup<PerformFinally>(NormalCleanup, body,
1467224145Sdim                                          ForEHVar, endCatchFn,
1468224145Sdim                                          rethrowFn, SavedExnVar);
1469210299Sed
1470210299Sed  // Enter a catch-all scope.
1471224145Sdim  llvm::BasicBlock *catchBB = CGF.createBasicBlock("finally.catchall");
1472224145Sdim  EHCatchScope *catchScope = CGF.EHStack.pushCatch(1);
1473224145Sdim  catchScope->setCatchAllHandler(0, catchBB);
1474224145Sdim}
1475210299Sed
1476224145Sdimvoid CodeGenFunction::FinallyInfo::exit(CodeGenFunction &CGF) {
1477224145Sdim  // Leave the finally catch-all.
1478224145Sdim  EHCatchScope &catchScope = cast<EHCatchScope>(*CGF.EHStack.begin());
1479224145Sdim  llvm::BasicBlock *catchBB = catchScope.getHandler(0).Block;
1480210299Sed
1481226633Sdim  CGF.popCatchScope();
1482226633Sdim
1483224145Sdim  // If there are any references to the catch-all block, emit it.
1484224145Sdim  if (catchBB->use_empty()) {
1485224145Sdim    delete catchBB;
1486224145Sdim  } else {
1487224145Sdim    CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveAndClearIP();
1488224145Sdim    CGF.EmitBlock(catchBB);
1489210299Sed
1490224145Sdim    llvm::Value *exn = 0;
1491210299Sed
1492224145Sdim    // If there's a begin-catch function, call it.
1493224145Sdim    if (BeginCatchFn) {
1494226633Sdim      exn = CGF.getExceptionFromSlot();
1495249423Sdim      CGF.EmitNounwindRuntimeCall(BeginCatchFn, exn);
1496224145Sdim    }
1497210299Sed
1498224145Sdim    // If we need to remember the exception pointer to rethrow later, do so.
1499224145Sdim    if (SavedExnVar) {
1500226633Sdim      if (!exn) exn = CGF.getExceptionFromSlot();
1501224145Sdim      CGF.Builder.CreateStore(exn, SavedExnVar);
1502224145Sdim    }
1503210299Sed
1504224145Sdim    // Tell the cleanups in the finally block that we're do this for EH.
1505224145Sdim    CGF.Builder.CreateStore(CGF.Builder.getTrue(), ForEHVar);
1506210299Sed
1507224145Sdim    // Thread a jump through the finally cleanup.
1508224145Sdim    CGF.EmitBranchThroughCleanup(RethrowDest);
1509210299Sed
1510224145Sdim    CGF.Builder.restoreIP(savedIP);
1511224145Sdim  }
1512210299Sed
1513224145Sdim  // Finally, leave the @finally cleanup.
1514224145Sdim  CGF.PopCleanupBlock();
1515210299Sed}
1516210299Sed
1517249423Sdim/// In a terminate landing pad, should we use __clang__call_terminate
1518249423Sdim/// or just a naked call to std::terminate?
1519249423Sdim///
1520249423Sdim/// __clang_call_terminate calls __cxa_begin_catch, which then allows
1521249423Sdim/// std::terminate to usefully report something about the
1522249423Sdim/// violating exception.
1523249423Sdimstatic bool useClangCallTerminate(CodeGenModule &CGM) {
1524249423Sdim  // Only do this for Itanium-family ABIs in C++ mode.
1525249423Sdim  return (CGM.getLangOpts().CPlusPlus &&
1526249423Sdim          CGM.getTarget().getCXXABI().isItaniumFamily());
1527249423Sdim}
1528249423Sdim
1529249423Sdim/// Get or define the following function:
1530249423Sdim///   void @__clang_call_terminate(i8* %exn) nounwind noreturn
1531249423Sdim/// This code is used only in C++.
1532249423Sdimstatic llvm::Constant *getClangCallTerminateFn(CodeGenModule &CGM) {
1533249423Sdim  llvm::FunctionType *fnTy =
1534249423Sdim    llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
1535249423Sdim  llvm::Constant *fnRef =
1536249423Sdim    CGM.CreateRuntimeFunction(fnTy, "__clang_call_terminate");
1537249423Sdim
1538249423Sdim  llvm::Function *fn = dyn_cast<llvm::Function>(fnRef);
1539249423Sdim  if (fn && fn->empty()) {
1540249423Sdim    fn->setDoesNotThrow();
1541249423Sdim    fn->setDoesNotReturn();
1542249423Sdim
1543249423Sdim    // What we really want is to massively penalize inlining without
1544249423Sdim    // forbidding it completely.  The difference between that and
1545249423Sdim    // 'noinline' is negligible.
1546249423Sdim    fn->addFnAttr(llvm::Attribute::NoInline);
1547249423Sdim
1548249423Sdim    // Allow this function to be shared across translation units, but
1549249423Sdim    // we don't want it to turn into an exported symbol.
1550249423Sdim    fn->setLinkage(llvm::Function::LinkOnceODRLinkage);
1551249423Sdim    fn->setVisibility(llvm::Function::HiddenVisibility);
1552249423Sdim
1553249423Sdim    // Set up the function.
1554249423Sdim    llvm::BasicBlock *entry =
1555249423Sdim      llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn);
1556249423Sdim    CGBuilderTy builder(entry);
1557249423Sdim
1558249423Sdim    // Pull the exception pointer out of the parameter list.
1559249423Sdim    llvm::Value *exn = &*fn->arg_begin();
1560249423Sdim
1561249423Sdim    // Call __cxa_begin_catch(exn).
1562249423Sdim    llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn);
1563249423Sdim    catchCall->setDoesNotThrow();
1564249423Sdim    catchCall->setCallingConv(CGM.getRuntimeCC());
1565249423Sdim
1566249423Sdim    // Call std::terminate().
1567249423Sdim    llvm::CallInst *termCall = builder.CreateCall(getTerminateFn(CGM));
1568249423Sdim    termCall->setDoesNotThrow();
1569249423Sdim    termCall->setDoesNotReturn();
1570249423Sdim    termCall->setCallingConv(CGM.getRuntimeCC());
1571249423Sdim
1572249423Sdim    // std::terminate cannot return.
1573249423Sdim    builder.CreateUnreachable();
1574249423Sdim  }
1575249423Sdim
1576249423Sdim  return fnRef;
1577249423Sdim}
1578249423Sdim
1579210299Sedllvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
1580210299Sed  if (TerminateLandingPad)
1581210299Sed    return TerminateLandingPad;
1582210299Sed
1583210299Sed  CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1584210299Sed
1585210299Sed  // This will get inserted at the end of the function.
1586210299Sed  TerminateLandingPad = createBasicBlock("terminate.lpad");
1587210299Sed  Builder.SetInsertPoint(TerminateLandingPad);
1588210299Sed
1589210299Sed  // Tell the backend that this is a landing pad.
1590234353Sdim  const EHPersonality &Personality = EHPersonality::get(CGM.getLangOpts());
1591226633Sdim  llvm::LandingPadInst *LPadInst =
1592226633Sdim    Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, NULL),
1593226633Sdim                             getOpaquePersonalityFn(CGM, Personality), 0);
1594226633Sdim  LPadInst->addClause(getCatchAllValue(*this));
1595210299Sed
1596249423Sdim  llvm::CallInst *terminateCall;
1597249423Sdim  if (useClangCallTerminate(CGM)) {
1598249423Sdim    // Extract out the exception pointer.
1599249423Sdim    llvm::Value *exn = Builder.CreateExtractValue(LPadInst, 0);
1600249423Sdim    terminateCall = EmitNounwindRuntimeCall(getClangCallTerminateFn(CGM), exn);
1601249423Sdim  } else {
1602249423Sdim    terminateCall = EmitNounwindRuntimeCall(getTerminateFn(CGM));
1603249423Sdim  }
1604249423Sdim  terminateCall->setDoesNotReturn();
1605218893Sdim  Builder.CreateUnreachable();
1606200583Srdivacky
1607210299Sed  // Restore the saved insertion state.
1608210299Sed  Builder.restoreIP(SavedIP);
1609207619Srdivacky
1610210299Sed  return TerminateLandingPad;
1611200583Srdivacky}
1612200583Srdivacky
1613200583Srdivackyllvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
1614200583Srdivacky  if (TerminateHandler)
1615200583Srdivacky    return TerminateHandler;
1616200583Srdivacky
1617210299Sed  CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1618200583Srdivacky
1619210299Sed  // Set up the terminate handler.  This block is inserted at the very
1620210299Sed  // end of the function by FinishFunction.
1621200583Srdivacky  TerminateHandler = createBasicBlock("terminate.handler");
1622210299Sed  Builder.SetInsertPoint(TerminateHandler);
1623263508Sdim  llvm::CallInst *terminateCall;
1624263508Sdim  if (useClangCallTerminate(CGM)) {
1625263508Sdim    // Load the exception pointer.
1626263508Sdim    llvm::Value *exn = getExceptionFromSlot();
1627263508Sdim    terminateCall = EmitNounwindRuntimeCall(getClangCallTerminateFn(CGM), exn);
1628263508Sdim  } else {
1629263508Sdim    terminateCall = EmitNounwindRuntimeCall(getTerminateFn(CGM));
1630263508Sdim  }
1631263508Sdim  terminateCall->setDoesNotReturn();
1632200583Srdivacky  Builder.CreateUnreachable();
1633200583Srdivacky
1634207619Srdivacky  // Restore the saved insertion state.
1635210299Sed  Builder.restoreIP(SavedIP);
1636200583Srdivacky
1637200583Srdivacky  return TerminateHandler;
1638200583Srdivacky}
1639210299Sed
1640243830Sdimllvm::BasicBlock *CodeGenFunction::getEHResumeBlock(bool isCleanup) {
1641226633Sdim  if (EHResumeBlock) return EHResumeBlock;
1642210299Sed
1643212904Sdim  CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1644210299Sed
1645212904Sdim  // We emit a jump to a notional label at the outermost unwind state.
1646226633Sdim  EHResumeBlock = createBasicBlock("eh.resume");
1647226633Sdim  Builder.SetInsertPoint(EHResumeBlock);
1648210299Sed
1649234353Sdim  const EHPersonality &Personality = EHPersonality::get(CGM.getLangOpts());
1650210299Sed
1651212904Sdim  // This can always be a call because we necessarily didn't find
1652212904Sdim  // anything on the EH stack which needs our help.
1653234353Sdim  const char *RethrowName = Personality.CatchallRethrowFn;
1654243830Sdim  if (RethrowName != 0 && !isCleanup) {
1655249423Sdim    EmitRuntimeCall(getCatchallRethrowFn(CGM, RethrowName),
1656249423Sdim                      getExceptionFromSlot())
1657223017Sdim      ->setDoesNotReturn();
1658223017Sdim  } else {
1659223017Sdim    switch (CleanupHackLevel) {
1660223017Sdim    case CHL_MandatoryCatchall:
1661223017Sdim      // In mandatory-catchall mode, we need to use
1662223017Sdim      // _Unwind_Resume_or_Rethrow, or whatever the personality's
1663223017Sdim      // equivalent is.
1664249423Sdim      EmitRuntimeCall(getUnwindResumeOrRethrowFn(),
1665249423Sdim                        getExceptionFromSlot())
1666223017Sdim        ->setDoesNotReturn();
1667223017Sdim      break;
1668223017Sdim    case CHL_MandatoryCleanup: {
1669226633Sdim      // In mandatory-cleanup mode, we should use 'resume'.
1670226633Sdim
1671226633Sdim      // Recreate the landingpad's return value for the 'resume' instruction.
1672226633Sdim      llvm::Value *Exn = getExceptionFromSlot();
1673226633Sdim      llvm::Value *Sel = getSelectorFromSlot();
1674226633Sdim
1675226633Sdim      llvm::Type *LPadType = llvm::StructType::get(Exn->getType(),
1676226633Sdim                                                   Sel->getType(), NULL);
1677226633Sdim      llvm::Value *LPadVal = llvm::UndefValue::get(LPadType);
1678226633Sdim      LPadVal = Builder.CreateInsertValue(LPadVal, Exn, 0, "lpad.val");
1679226633Sdim      LPadVal = Builder.CreateInsertValue(LPadVal, Sel, 1, "lpad.val");
1680226633Sdim
1681226633Sdim      Builder.CreateResume(LPadVal);
1682226633Sdim      Builder.restoreIP(SavedIP);
1683226633Sdim      return EHResumeBlock;
1684223017Sdim    }
1685223017Sdim    case CHL_Ideal:
1686223017Sdim      // In an idealized mode where we don't have to worry about the
1687223017Sdim      // optimizer combining landing pads, we should just use
1688223017Sdim      // _Unwind_Resume (or the personality's equivalent).
1689249423Sdim      EmitRuntimeCall(getUnwindResumeFn(), getExceptionFromSlot())
1690223017Sdim        ->setDoesNotReturn();
1691223017Sdim      break;
1692223017Sdim    }
1693223017Sdim  }
1694223017Sdim
1695212904Sdim  Builder.CreateUnreachable();
1696210299Sed
1697212904Sdim  Builder.restoreIP(SavedIP);
1698210299Sed
1699226633Sdim  return EHResumeBlock;
1700210299Sed}
1701263508Sdim
1702263508Sdimvoid CodeGenFunction::EmitSEHTryStmt(const SEHTryStmt &S) {
1703263508Sdim  CGM.ErrorUnsupported(&S, "SEH __try");
1704263508Sdim}
1705