CGException.cpp revision c88b6735ea8d2c0c5126239c0761e0e139117349
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
18#include "CodeGenFunction.h"
19using namespace clang;
20using namespace CodeGen;
21
22static llvm::Constant *getAllocateExceptionFn(CodeGenFunction &CGF) {
23  // void *__cxa_allocate_exception(size_t thrown_size);
24  const llvm::Type *SizeTy = CGF.ConvertType(CGF.getContext().getSizeType());
25  std::vector<const llvm::Type*> Args(1, SizeTy);
26
27  const llvm::FunctionType *FTy =
28  llvm::FunctionType::get(llvm::Type::getInt8PtrTy(CGF.getLLVMContext()),
29                          Args, false);
30
31  return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
32}
33
34static llvm::Constant *getFreeExceptionFn(CodeGenFunction &CGF) {
35  // void __cxa_free_exception(void *thrown_exception);
36  const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
37  std::vector<const llvm::Type*> Args(1, Int8PtrTy);
38
39  const llvm::FunctionType *FTy =
40  llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
41                          Args, false);
42
43  return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_free_exception");
44}
45
46static llvm::Constant *getThrowFn(CodeGenFunction &CGF) {
47  // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
48  //                  void (*dest) (void *));
49
50  const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
51  std::vector<const llvm::Type*> Args(3, Int8PtrTy);
52
53  const llvm::FunctionType *FTy =
54    llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
55                            Args, false);
56
57  return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
58}
59
60static llvm::Constant *getReThrowFn(CodeGenFunction &CGF) {
61  // void __cxa_rethrow();
62
63  const llvm::FunctionType *FTy =
64    llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()), false);
65
66  return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
67}
68
69static llvm::Constant *getBeginCatchFn(CodeGenFunction &CGF) {
70  // void* __cxa_begin_catch();
71
72  const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
73  std::vector<const llvm::Type*> Args(1, Int8PtrTy);
74
75  const llvm::FunctionType *FTy =
76    llvm::FunctionType::get(Int8PtrTy, Args, false);
77
78  return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
79}
80
81static llvm::Constant *getEndCatchFn(CodeGenFunction &CGF) {
82  // void __cxa_end_catch();
83
84  const llvm::FunctionType *FTy =
85    llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()), false);
86
87  return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
88}
89
90// FIXME: Eventually this will all go into the backend.  Set from the target for
91// now.
92static int using_sjlj_exceptions = 0;
93
94static llvm::Constant *getUnwindResumeOrRethrowFn(CodeGenFunction &CGF) {
95  const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
96  std::vector<const llvm::Type*> Args(1, Int8PtrTy);
97
98  const llvm::FunctionType *FTy =
99    llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()), Args,
100                            false);
101
102  if (using_sjlj_exceptions)
103    return CGF.CGM.CreateRuntimeFunction(FTy, "_Unwind_SjLj_Resume");
104  return CGF.CGM.CreateRuntimeFunction(FTy, "_Unwind_Resume_or_Rethrow");
105}
106
107static llvm::Constant *getTerminateFn(CodeGenFunction &CGF) {
108  // void __terminate();
109
110  const llvm::FunctionType *FTy =
111    llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()), false);
112
113  return CGF.CGM.CreateRuntimeFunction(FTy, "_ZSt9terminatev");
114}
115
116// CopyObject - Utility to copy an object.  Calls copy constructor as necessary.
117// N is casted to the right type.
118static void CopyObject(CodeGenFunction &CGF, const Expr *E, llvm::Value *N) {
119  QualType ObjectType = E->getType();
120
121  // Store the throw exception in the exception object.
122  if (!CGF.hasAggregateLLVMType(ObjectType)) {
123    llvm::Value *Value = CGF.EmitScalarExpr(E);
124    const llvm::Type *ValuePtrTy = Value->getType()->getPointerTo(0);
125
126    CGF.Builder.CreateStore(Value, CGF.Builder.CreateBitCast(N, ValuePtrTy));
127  } else {
128    const llvm::Type *Ty = CGF.ConvertType(ObjectType)->getPointerTo(0);
129    const CXXRecordDecl *RD;
130    RD = cast<CXXRecordDecl>(ObjectType->getAs<RecordType>()->getDecl());
131    llvm::Value *This = CGF.Builder.CreateBitCast(N, Ty);
132    if (RD->hasTrivialCopyConstructor()) {
133      CGF.EmitAggExpr(E, This, false);
134    } else if (CXXConstructorDecl *CopyCtor
135               = RD->getCopyConstructor(CGF.getContext(), 0)) {
136      // All temporaries end before we call __cxa_throw
137      CodeGenFunction::CleanupScope TryScope(CGF);
138      {
139        // These actions are only on the exceptional edge.
140        CodeGenFunction::DelayedCleanupBlock Scope(CGF, true);
141
142        llvm::Constant *FreeExceptionFn = getFreeExceptionFn(CGF);
143        const llvm::Type *Int8PtrTy
144          = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
145        llvm::Value *ExceptionPtr = CGF.Builder.CreateBitCast(N, Int8PtrTy);
146        CGF.Builder.CreateCall(FreeExceptionFn, ExceptionPtr);
147      }
148
149      llvm::Value *Src = CGF.EmitLValue(E).getAddress();
150
151      // Stolen from EmitClassAggrMemberwiseCopy
152      llvm::Value *Callee = CGF.CGM.GetAddrOfCXXConstructor(CopyCtor,
153                                                            Ctor_Complete);
154      CallArgList CallArgs;
155      CallArgs.push_back(std::make_pair(RValue::get(This),
156                                      CopyCtor->getThisType(CGF.getContext())));
157
158      // Push the Src ptr.
159      CallArgs.push_back(std::make_pair(RValue::get(Src),
160                                        CopyCtor->getParamDecl(0)->getType()));
161      QualType ResultType =
162        CopyCtor->getType()->getAs<FunctionType>()->getResultType();
163      CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
164                   Callee, CallArgs, CopyCtor);
165    } else
166      llvm::llvm_unreachable("uncopyable object");
167  }
168}
169
170// CopyObject - Utility to copy an object.  Calls copy constructor as necessary.
171// N is casted to the right type.
172static void CopyObject(CodeGenFunction &CGF, QualType ObjectType,
173                       llvm::Value *E, llvm::Value *N) {
174  // Store the throw exception in the exception object.
175  if (!CGF.hasAggregateLLVMType(ObjectType)) {
176    llvm::Value *Value = E;
177    const llvm::Type *ValuePtrTy = Value->getType()->getPointerTo(0);
178
179    CGF.Builder.CreateStore(Value, CGF.Builder.CreateBitCast(N, ValuePtrTy));
180  } else {
181    const llvm::Type *Ty = CGF.ConvertType(ObjectType)->getPointerTo(0);
182    const CXXRecordDecl *RD;
183    RD = cast<CXXRecordDecl>(ObjectType->getAs<RecordType>()->getDecl());
184    llvm::Value *This = CGF.Builder.CreateBitCast(N, Ty);
185    if (RD->hasTrivialCopyConstructor()) {
186      CGF.EmitAggregateCopy(This, E, ObjectType);
187    } else if (CXXConstructorDecl *CopyCtor
188               = RD->getCopyConstructor(CGF.getContext(), 0)) {
189      // FIXME: region management, call terminate
190      llvm::Value *Src = E;
191
192      // Stolen from EmitClassAggrMemberwiseCopy
193      llvm::Value *Callee = CGF.CGM.GetAddrOfCXXConstructor(CopyCtor,
194                                                            Ctor_Complete);
195      CallArgList CallArgs;
196      CallArgs.push_back(std::make_pair(RValue::get(This),
197                                      CopyCtor->getThisType(CGF.getContext())));
198
199      // Push the Src ptr.
200      CallArgs.push_back(std::make_pair(RValue::get(Src),
201                                        CopyCtor->getParamDecl(0)->getType()));
202      QualType ResultType =
203        CopyCtor->getType()->getAs<FunctionType>()->getResultType();
204      CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
205                   Callee, CallArgs, CopyCtor);
206      // FIXME: region management
207    } else
208      llvm::llvm_unreachable("uncopyable object");
209  }
210}
211
212void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E) {
213  if (!E->getSubExpr()) {
214    Builder.CreateCall(getReThrowFn(*this))->setDoesNotReturn();
215    Builder.CreateUnreachable();
216
217    // Clear the insertion point to indicate we are in unreachable code.
218    Builder.ClearInsertionPoint();
219    return;
220  }
221
222  QualType ThrowType = E->getSubExpr()->getType();
223  // FIXME: Handle cleanup.
224  if (!CleanupEntries.empty()){
225    ErrorUnsupported(E, "throw expression with cleanup entries");
226    return;
227  }
228
229  // Now allocate the exception object.
230  const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
231  uint64_t TypeSize = getContext().getTypeSize(ThrowType) / 8;
232
233  llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(*this);
234  llvm::Value *ExceptionPtr =
235    Builder.CreateCall(AllocExceptionFn,
236                       llvm::ConstantInt::get(SizeTy, TypeSize),
237                       "exception");
238
239  CopyObject(*this, E->getSubExpr(), ExceptionPtr);
240
241  // Now throw the exception.
242  const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(getLLVMContext());
243  llvm::Constant *TypeInfo = CGM.GenerateRtti(ThrowType);
244  llvm::Constant *Dtor = llvm::Constant::getNullValue(Int8PtrTy);
245
246  llvm::CallInst *ThrowCall =
247    Builder.CreateCall3(getThrowFn(*this), ExceptionPtr, TypeInfo, Dtor);
248  ThrowCall->setDoesNotReturn();
249  Builder.CreateUnreachable();
250
251  // Clear the insertion point to indicate we are in unreachable code.
252  Builder.ClearInsertionPoint();
253}
254
255void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
256  if (1) {
257    EmitStmt(S.getTryBlock());
258    return;
259  }
260  // FIXME: The below is still just a sketch of the code we need.
261  // Pointer to the personality function
262  llvm::Constant *Personality =
263    CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::getInt32Ty
264                                                      (VMContext),
265                                                      true),
266                              "__gxx_personality_v0");
267  Personality = llvm::ConstantExpr::getBitCast(Personality, PtrToInt8Ty);
268
269  llvm::BasicBlock *PrevLandingPad = getInvokeDest();
270  llvm::BasicBlock *TryHandler = createBasicBlock("try.handler");
271  llvm::BasicBlock *FinallyBlock = createBasicBlock("finally");
272  llvm::BasicBlock *FinallyRethrow = createBasicBlock("finally.throw");
273  llvm::BasicBlock *FinallyEnd = createBasicBlock("finally.end");
274
275  // Push an EH context entry, used for handling rethrows.
276  PushCleanupBlock(FinallyBlock);
277
278  // Emit the statements in the try {} block
279  setInvokeDest(TryHandler);
280
281  EmitStmt(S.getTryBlock());
282
283  // Jump to end if there is no exception
284  EmitBranchThroughCleanup(FinallyEnd);
285
286  // Emit the handlers
287  EmitBlock(TryHandler);
288
289  const llvm::IntegerType *Int8Ty;
290  const llvm::PointerType *PtrToInt8Ty;
291  Int8Ty = llvm::Type::getInt8Ty(VMContext);
292  // C string type.  Used in lots of places.
293  PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
294  llvm::Constant *Null = llvm::ConstantPointerNull::get(PtrToInt8Ty);
295  llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
296  llvm::Value *llvm_eh_exception =
297    CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
298  llvm::Value *llvm_eh_selector =
299    CGM.getIntrinsic(llvm::Intrinsic::eh_selector);
300  llvm::Value *llvm_eh_typeid_for =
301    CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
302  // Exception object
303  llvm::Value *Exc = Builder.CreateCall(llvm_eh_exception, "exc");
304  llvm::Value *RethrowPtr = CreateTempAlloca(Exc->getType(), "_rethrow");
305
306  SelectorArgs.push_back(Exc);
307  SelectorArgs.push_back(Personality);
308
309  bool HasCatchAll = false;
310  for (unsigned i = 0; i<S.getNumHandlers(); ++i) {
311    const CXXCatchStmt *C = S.getHandler(i);
312    VarDecl *CatchParam = C->getExceptionDecl();
313    if (CatchParam) {
314      llvm::Value *EHType = CGM.GenerateRtti(C->getCaughtType().getNonReferenceType());
315      SelectorArgs.push_back(EHType);
316    } else {
317      // null indicates catch all
318      SelectorArgs.push_back(Null);
319      HasCatchAll = true;
320    }
321  }
322
323  // We use a cleanup unless there was already a catch all.
324  if (!HasCatchAll) {
325    SelectorArgs.push_back(Null);
326  }
327
328  // Find which handler was matched.
329  llvm::Value *Selector
330    = Builder.CreateCall(llvm_eh_selector, SelectorArgs.begin(),
331                         SelectorArgs.end(), "selector");
332  llvm::BasicBlock *TerminateHandler = 0;
333  for (unsigned i = 0; i<S.getNumHandlers(); ++i) {
334    const CXXCatchStmt *C = S.getHandler(i);
335    VarDecl *CatchParam = C->getExceptionDecl();
336    Stmt *CatchBody = C->getHandlerBlock();
337
338    llvm::BasicBlock *Next = 0;
339
340    if (SelectorArgs[i+2] != Null) {
341      llvm::BasicBlock *Match = createBasicBlock("match");
342      Next = createBasicBlock("catch.next");
343      const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(getLLVMContext());
344      llvm::Value *Id
345        = Builder.CreateCall(llvm_eh_typeid_for,
346                             Builder.CreateBitCast(SelectorArgs[i+2],
347                                                   Int8PtrTy));
348      Builder.CreateCondBr(Builder.CreateICmpEQ(Selector, Id),
349                           Match, Next);
350      EmitBlock(Match);
351    }
352
353    llvm::BasicBlock *MatchEnd = createBasicBlock("match.end");
354    llvm::BasicBlock *MatchHandler = createBasicBlock("match.handler");
355
356    PushCleanupBlock(MatchEnd);
357    setInvokeDest(MatchHandler);
358
359    llvm::Value *ExcObject = Builder.CreateCall(getBeginCatchFn(*this), Exc);
360
361    // Bind the catch parameter if it exists.
362    if (CatchParam) {
363      QualType CatchType = CatchParam->getType().getNonReferenceType();
364      if (!CatchType.getTypePtr()->isPointerType())
365        CatchType = getContext().getPointerType(CatchType);
366      ExcObject =
367        Builder.CreateBitCast(ExcObject, ConvertType(CatchType));
368        // CatchParam is a ParmVarDecl because of the grammar
369        // construction used to handle this, but for codegen purposes
370        // we treat this as a local decl.
371      EmitLocalBlockVarDecl(*CatchParam);
372#if 0
373      // FIXME: objects with ctors, references
374      Builder.CreateStore(ExcObject, GetAddrOfLocalVar(CatchParam));
375#else
376      CopyObject(*this, CatchParam->getType().getNonReferenceType(),
377                 ExcObject, GetAddrOfLocalVar(CatchParam));
378#endif
379    }
380
381    EmitStmt(CatchBody);
382    EmitBranchThroughCleanup(FinallyEnd);
383
384    EmitBlock(MatchHandler);
385
386    llvm::Value *Exc = Builder.CreateCall(llvm_eh_exception, "exc");
387    // We are required to emit this call to satisfy LLVM, even
388    // though we don't use the result.
389    llvm::SmallVector<llvm::Value*, 8> Args;
390    Args.push_back(Exc);
391    Args.push_back(Personality);
392    Args.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
393                                          0));
394    Builder.CreateCall(llvm_eh_selector, Args.begin(), Args.end());
395    Builder.CreateStore(Exc, RethrowPtr);
396    EmitBranchThroughCleanup(FinallyRethrow);
397
398    CodeGenFunction::CleanupBlockInfo Info = PopCleanupBlock();
399
400    EmitBlock(MatchEnd);
401
402    // Set up terminate handler
403    bool GenerateTerminate = false;
404    if (!TerminateHandler) {
405      TerminateHandler = createBasicBlock("terminate.handler");
406      GenerateTerminate = true;
407    }
408    llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
409    Builder.CreateInvoke(getEndCatchFn(*this),
410                         Cont, TerminateHandler,
411                         Args.begin(), Args.begin());
412
413    EmitBlock(Cont);
414    if (Info.SwitchBlock)
415      EmitBlock(Info.SwitchBlock);
416    if (Info.EndBlock)
417      EmitBlock(Info.EndBlock);
418
419    Exc = Builder.CreateCall(llvm_eh_exception, "exc");
420    Builder.CreateStore(Exc, RethrowPtr);
421    EmitBranchThroughCleanup(FinallyRethrow);
422
423    if (GenerateTerminate) {
424      GenerateTerminate = false;
425      EmitBlock(TerminateHandler);
426      Exc = Builder.CreateCall(llvm_eh_exception, "exc");
427      // We are required to emit this call to satisfy LLVM, even
428      // though we don't use the result.
429      Args.clear();
430      Args.push_back(Exc);
431      Args.push_back(Personality);
432      Args.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
433                                            0));
434      Builder.CreateCall(llvm_eh_selector, Args.begin(), Args.end());
435      llvm::CallInst *TerminateCall =
436        Builder.CreateCall(getTerminateFn(*this));
437      TerminateCall->setDoesNotReturn();
438      TerminateCall->setDoesNotThrow();
439      Builder.CreateUnreachable();
440
441      // Clear the insertion point to indicate we are in unreachable code.
442      Builder.ClearInsertionPoint();
443    }
444
445    if (Next)
446      EmitBlock(Next);
447  }
448  if (!HasCatchAll)
449    EmitBranchThroughCleanup(FinallyRethrow);
450
451  CodeGenFunction::CleanupBlockInfo Info = PopCleanupBlock();
452
453  setInvokeDest(PrevLandingPad);
454
455  EmitBlock(FinallyBlock);
456
457  if (Info.SwitchBlock)
458    EmitBlock(Info.SwitchBlock);
459  if (Info.EndBlock)
460    EmitBlock(Info.EndBlock);
461
462  // Branch around the rethrow code.
463  EmitBranch(FinallyEnd);
464
465  EmitBlock(FinallyRethrow);
466  Builder.CreateCall(getUnwindResumeOrRethrowFn(*this),
467                     Builder.CreateLoad(RethrowPtr));
468  Builder.CreateUnreachable();
469
470  EmitBlock(FinallyEnd);
471}
472