blob: edfee95efccd7587cf5f8b143fd2a443668afd44 [file] [log] [blame]
Anders Carlsson756b5c42009-10-30 01:42:31 +00001//===--- 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
Mike Stump2bf701e2009-11-20 23:44:51 +000014#include "clang/AST/StmtCXX.h"
15
16#include "llvm/Intrinsics.h"
John McCallb2593832010-09-16 06:16:50 +000017#include "llvm/IntrinsicInst.h"
John McCallf1549f62010-07-06 01:34:17 +000018#include "llvm/Support/CallSite.h"
Mike Stump2bf701e2009-11-20 23:44:51 +000019
John McCall5a180392010-07-24 00:37:23 +000020#include "CGObjCRuntime.h"
Anders Carlsson756b5c42009-10-30 01:42:31 +000021#include "CodeGenFunction.h"
John McCallf1549f62010-07-06 01:34:17 +000022#include "CGException.h"
John McCall204b0752010-07-20 22:17:55 +000023#include "TargetInfo.h"
John McCallf1549f62010-07-06 01:34:17 +000024
Anders Carlsson756b5c42009-10-30 01:42:31 +000025using namespace clang;
26using namespace CodeGen;
27
John McCallf1549f62010-07-06 01:34:17 +000028/// Push an entry of the given size onto this protected-scope stack.
29char *EHScopeStack::allocate(size_t Size) {
30 if (!StartOfBuffer) {
31 unsigned Capacity = 1024;
32 while (Capacity < Size) Capacity *= 2;
33 StartOfBuffer = new char[Capacity];
34 StartOfData = EndOfBuffer = StartOfBuffer + Capacity;
35 } else if (static_cast<size_t>(StartOfData - StartOfBuffer) < Size) {
36 unsigned CurrentCapacity = EndOfBuffer - StartOfBuffer;
37 unsigned UsedCapacity = CurrentCapacity - (StartOfData - StartOfBuffer);
38
39 unsigned NewCapacity = CurrentCapacity;
40 do {
41 NewCapacity *= 2;
42 } while (NewCapacity < UsedCapacity + Size);
43
44 char *NewStartOfBuffer = new char[NewCapacity];
45 char *NewEndOfBuffer = NewStartOfBuffer + NewCapacity;
46 char *NewStartOfData = NewEndOfBuffer - UsedCapacity;
47 memcpy(NewStartOfData, StartOfData, UsedCapacity);
48 delete [] StartOfBuffer;
49 StartOfBuffer = NewStartOfBuffer;
50 EndOfBuffer = NewEndOfBuffer;
51 StartOfData = NewStartOfData;
52 }
53
54 assert(StartOfBuffer + Size <= StartOfData);
55 StartOfData -= Size;
56 return StartOfData;
57}
58
59EHScopeStack::stable_iterator
60EHScopeStack::getEnclosingEHCleanup(iterator it) const {
61 assert(it != end());
62 do {
John McCall1f0fca52010-07-21 07:22:38 +000063 if (isa<EHCleanupScope>(*it)) {
64 if (cast<EHCleanupScope>(*it).isEHCleanup())
John McCallda65ea82010-07-13 20:32:21 +000065 return stabilize(it);
John McCall1f0fca52010-07-21 07:22:38 +000066 return cast<EHCleanupScope>(*it).getEnclosingEHCleanup();
John McCallda65ea82010-07-13 20:32:21 +000067 }
John McCallf1549f62010-07-06 01:34:17 +000068 ++it;
69 } while (it != end());
70 return stable_end();
71}
72
73
John McCall1f0fca52010-07-21 07:22:38 +000074void *EHScopeStack::pushCleanup(CleanupKind Kind, size_t Size) {
John McCallda65ea82010-07-13 20:32:21 +000075 assert(((Size % sizeof(void*)) == 0) && "cleanup type is misaligned");
John McCall1f0fca52010-07-21 07:22:38 +000076 char *Buffer = allocate(EHCleanupScope::getSizeForCleanupSize(Size));
John McCallcd2d2b72010-08-13 21:20:51 +000077 bool IsNormalCleanup = Kind & NormalCleanup;
78 bool IsEHCleanup = Kind & EHCleanup;
79 bool IsActive = !(Kind & InactiveCleanup);
John McCall1f0fca52010-07-21 07:22:38 +000080 EHCleanupScope *Scope =
81 new (Buffer) EHCleanupScope(IsNormalCleanup,
82 IsEHCleanup,
John McCallcd2d2b72010-08-13 21:20:51 +000083 IsActive,
John McCall1f0fca52010-07-21 07:22:38 +000084 Size,
85 BranchFixups.size(),
86 InnermostNormalCleanup,
87 InnermostEHCleanup);
John McCallda65ea82010-07-13 20:32:21 +000088 if (IsNormalCleanup)
89 InnermostNormalCleanup = stable_begin();
90 if (IsEHCleanup)
91 InnermostEHCleanup = stable_begin();
92
93 return Scope->getCleanupBuffer();
94}
95
John McCallf1549f62010-07-06 01:34:17 +000096void EHScopeStack::popCleanup() {
97 assert(!empty() && "popping exception stack when not empty");
98
John McCall1f0fca52010-07-21 07:22:38 +000099 assert(isa<EHCleanupScope>(*begin()));
100 EHCleanupScope &Cleanup = cast<EHCleanupScope>(*begin());
John McCall7495f222010-07-21 07:11:21 +0000101 InnermostNormalCleanup = Cleanup.getEnclosingNormalCleanup();
102 InnermostEHCleanup = Cleanup.getEnclosingEHCleanup();
103 StartOfData += Cleanup.getAllocatedSize();
John McCallf1549f62010-07-06 01:34:17 +0000104
John McCallff8e1152010-07-23 21:56:41 +0000105 if (empty()) NextEHDestIndex = FirstEHDestIndex;
106
107 // Destroy the cleanup.
108 Cleanup.~EHCleanupScope();
109
John McCallf1549f62010-07-06 01:34:17 +0000110 // Check whether we can shrink the branch-fixups stack.
111 if (!BranchFixups.empty()) {
112 // If we no longer have any normal cleanups, all the fixups are
113 // complete.
114 if (!hasNormalCleanups())
115 BranchFixups.clear();
116
117 // Otherwise we can still trim out unnecessary nulls.
118 else
119 popNullFixups();
120 }
121}
122
123EHFilterScope *EHScopeStack::pushFilter(unsigned NumFilters) {
124 char *Buffer = allocate(EHFilterScope::getSizeForNumFilters(NumFilters));
125 CatchDepth++;
126 return new (Buffer) EHFilterScope(NumFilters);
127}
128
129void EHScopeStack::popFilter() {
130 assert(!empty() && "popping exception stack when not empty");
131
132 EHFilterScope &Filter = cast<EHFilterScope>(*begin());
133 StartOfData += EHFilterScope::getSizeForNumFilters(Filter.getNumFilters());
134
John McCallff8e1152010-07-23 21:56:41 +0000135 if (empty()) NextEHDestIndex = FirstEHDestIndex;
136
John McCallf1549f62010-07-06 01:34:17 +0000137 assert(CatchDepth > 0 && "mismatched filter push/pop");
138 CatchDepth--;
139}
140
141EHCatchScope *EHScopeStack::pushCatch(unsigned NumHandlers) {
142 char *Buffer = allocate(EHCatchScope::getSizeForNumHandlers(NumHandlers));
143 CatchDepth++;
John McCallff8e1152010-07-23 21:56:41 +0000144 EHCatchScope *Scope = new (Buffer) EHCatchScope(NumHandlers);
145 for (unsigned I = 0; I != NumHandlers; ++I)
146 Scope->getHandlers()[I].Index = getNextEHDestIndex();
147 return Scope;
John McCallf1549f62010-07-06 01:34:17 +0000148}
149
150void EHScopeStack::pushTerminate() {
151 char *Buffer = allocate(EHTerminateScope::getSize());
152 CatchDepth++;
John McCallff8e1152010-07-23 21:56:41 +0000153 new (Buffer) EHTerminateScope(getNextEHDestIndex());
John McCallf1549f62010-07-06 01:34:17 +0000154}
155
156/// Remove any 'null' fixups on the stack. However, we can't pop more
157/// fixups than the fixup depth on the innermost normal cleanup, or
158/// else fixups that we try to add to that cleanup will end up in the
159/// wrong place. We *could* try to shrink fixup depths, but that's
160/// actually a lot of work for little benefit.
161void EHScopeStack::popNullFixups() {
162 // We expect this to only be called when there's still an innermost
163 // normal cleanup; otherwise there really shouldn't be any fixups.
164 assert(hasNormalCleanups());
165
166 EHScopeStack::iterator it = find(InnermostNormalCleanup);
John McCall1f0fca52010-07-21 07:22:38 +0000167 unsigned MinSize = cast<EHCleanupScope>(*it).getFixupDepth();
John McCallf1549f62010-07-06 01:34:17 +0000168 assert(BranchFixups.size() >= MinSize && "fixup stack out of order");
169
170 while (BranchFixups.size() > MinSize &&
171 BranchFixups.back().Destination == 0)
172 BranchFixups.pop_back();
173}
174
John McCall3ad32c82011-01-28 08:37:24 +0000175void CodeGenFunction::initFullExprCleanup() {
John McCall150b4622011-01-26 04:00:11 +0000176 // Create a variable to decide whether the cleanup needs to be run.
John McCall3ad32c82011-01-28 08:37:24 +0000177 llvm::AllocaInst *active
178 = CreateTempAlloca(Builder.getInt1Ty(), "cleanup.cond");
John McCall150b4622011-01-26 04:00:11 +0000179
180 // Initialize it to false at a site that's guaranteed to be run
181 // before each evaluation.
182 llvm::BasicBlock *block = OutermostConditional->getStartingBlock();
John McCall3ad32c82011-01-28 08:37:24 +0000183 new llvm::StoreInst(Builder.getFalse(), active, &block->back());
John McCall150b4622011-01-26 04:00:11 +0000184
185 // Initialize it to true at the current location.
John McCall3ad32c82011-01-28 08:37:24 +0000186 Builder.CreateStore(Builder.getTrue(), active);
John McCall150b4622011-01-26 04:00:11 +0000187
John McCall3ad32c82011-01-28 08:37:24 +0000188 // Set that as the active flag in the cleanup.
189 EHCleanupScope &cleanup = cast<EHCleanupScope>(*EHStack.begin());
190 assert(cleanup.getActiveFlag() == 0 && "cleanup already has active flag?");
191 cleanup.setActiveFlag(active);
192
193 if (cleanup.isNormalCleanup()) cleanup.setTestFlagInNormalCleanup();
194 if (cleanup.isEHCleanup()) cleanup.setTestFlagInEHCleanup();
John McCall150b4622011-01-26 04:00:11 +0000195}
196
Anders Carlssond3379292009-10-30 02:27:02 +0000197static llvm::Constant *getAllocateExceptionFn(CodeGenFunction &CGF) {
198 // void *__cxa_allocate_exception(size_t thrown_size);
199 const llvm::Type *SizeTy = CGF.ConvertType(CGF.getContext().getSizeType());
200 std::vector<const llvm::Type*> Args(1, SizeTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000201
202 const llvm::FunctionType *FTy =
Anders Carlssond3379292009-10-30 02:27:02 +0000203 llvm::FunctionType::get(llvm::Type::getInt8PtrTy(CGF.getLLVMContext()),
204 Args, false);
Mike Stump8755ec32009-12-10 00:06:18 +0000205
Anders Carlssond3379292009-10-30 02:27:02 +0000206 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
207}
208
Mike Stump99533832009-12-02 07:41:41 +0000209static llvm::Constant *getFreeExceptionFn(CodeGenFunction &CGF) {
210 // void __cxa_free_exception(void *thrown_exception);
211 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
212 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000213
214 const llvm::FunctionType *FTy =
Mike Stump99533832009-12-02 07:41:41 +0000215 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
216 Args, false);
Mike Stump8755ec32009-12-10 00:06:18 +0000217
Mike Stump99533832009-12-02 07:41:41 +0000218 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_free_exception");
219}
220
Anders Carlssond3379292009-10-30 02:27:02 +0000221static llvm::Constant *getThrowFn(CodeGenFunction &CGF) {
Mike Stump8755ec32009-12-10 00:06:18 +0000222 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
Mike Stump99533832009-12-02 07:41:41 +0000223 // void (*dest) (void *));
Anders Carlssond3379292009-10-30 02:27:02 +0000224
225 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
226 std::vector<const llvm::Type*> Args(3, Int8PtrTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000227
228 const llvm::FunctionType *FTy =
Mike Stumpb4eea692009-11-20 00:56:31 +0000229 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
230 Args, false);
Mike Stump8755ec32009-12-10 00:06:18 +0000231
Anders Carlssond3379292009-10-30 02:27:02 +0000232 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
233}
234
Mike Stumpb4eea692009-11-20 00:56:31 +0000235static llvm::Constant *getReThrowFn(CodeGenFunction &CGF) {
Mike Stump99533832009-12-02 07:41:41 +0000236 // void __cxa_rethrow();
Mike Stumpb4eea692009-11-20 00:56:31 +0000237
Mike Stump8755ec32009-12-10 00:06:18 +0000238 const llvm::FunctionType *FTy =
Mike Stumpb4eea692009-11-20 00:56:31 +0000239 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()), false);
Mike Stump8755ec32009-12-10 00:06:18 +0000240
Mike Stumpb4eea692009-11-20 00:56:31 +0000241 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
242}
243
John McCallf1549f62010-07-06 01:34:17 +0000244static llvm::Constant *getGetExceptionPtrFn(CodeGenFunction &CGF) {
245 // void *__cxa_get_exception_ptr(void*);
246 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
247 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
248
249 const llvm::FunctionType *FTy =
250 llvm::FunctionType::get(Int8PtrTy, Args, false);
251
252 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
253}
254
Mike Stump2bf701e2009-11-20 23:44:51 +0000255static llvm::Constant *getBeginCatchFn(CodeGenFunction &CGF) {
John McCallf1549f62010-07-06 01:34:17 +0000256 // void *__cxa_begin_catch(void*);
Mike Stump2bf701e2009-11-20 23:44:51 +0000257
258 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
259 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000260
261 const llvm::FunctionType *FTy =
Mike Stump0f590be2009-12-01 03:41:18 +0000262 llvm::FunctionType::get(Int8PtrTy, Args, false);
Mike Stump8755ec32009-12-10 00:06:18 +0000263
Mike Stump2bf701e2009-11-20 23:44:51 +0000264 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
265}
266
267static llvm::Constant *getEndCatchFn(CodeGenFunction &CGF) {
Mike Stump99533832009-12-02 07:41:41 +0000268 // void __cxa_end_catch();
Mike Stump2bf701e2009-11-20 23:44:51 +0000269
Mike Stump8755ec32009-12-10 00:06:18 +0000270 const llvm::FunctionType *FTy =
Mike Stump2bf701e2009-11-20 23:44:51 +0000271 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()), false);
Mike Stump8755ec32009-12-10 00:06:18 +0000272
Mike Stump2bf701e2009-11-20 23:44:51 +0000273 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
274}
275
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000276static llvm::Constant *getUnexpectedFn(CodeGenFunction &CGF) {
277 // void __cxa_call_unexepcted(void *thrown_exception);
278
279 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
280 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000281
282 const llvm::FunctionType *FTy =
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000283 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
284 Args, false);
Mike Stump8755ec32009-12-10 00:06:18 +0000285
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000286 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_call_unexpected");
287}
288
Douglas Gregor86a3a032010-05-16 01:24:12 +0000289llvm::Constant *CodeGenFunction::getUnwindResumeOrRethrowFn() {
290 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(getLLVMContext());
Mike Stump0f590be2009-12-01 03:41:18 +0000291 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000292
293 const llvm::FunctionType *FTy =
Douglas Gregor86a3a032010-05-16 01:24:12 +0000294 llvm::FunctionType::get(llvm::Type::getVoidTy(getLLVMContext()), Args,
Mike Stump0f590be2009-12-01 03:41:18 +0000295 false);
Mike Stump8755ec32009-12-10 00:06:18 +0000296
Douglas Gregor86a3a032010-05-16 01:24:12 +0000297 if (CGM.getLangOptions().SjLjExceptions)
John McCalla5f2de22010-08-11 20:59:53 +0000298 return CGM.CreateRuntimeFunction(FTy, "_Unwind_SjLj_Resume_or_Rethrow");
Douglas Gregor86a3a032010-05-16 01:24:12 +0000299 return CGM.CreateRuntimeFunction(FTy, "_Unwind_Resume_or_Rethrow");
Mike Stump0f590be2009-12-01 03:41:18 +0000300}
301
Mike Stump99533832009-12-02 07:41:41 +0000302static llvm::Constant *getTerminateFn(CodeGenFunction &CGF) {
303 // void __terminate();
304
Mike Stump8755ec32009-12-10 00:06:18 +0000305 const llvm::FunctionType *FTy =
Mike Stump99533832009-12-02 07:41:41 +0000306 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()), false);
Mike Stump8755ec32009-12-10 00:06:18 +0000307
David Chisnall79a9ad82010-05-17 13:49:20 +0000308 return CGF.CGM.CreateRuntimeFunction(FTy,
309 CGF.CGM.getLangOptions().CPlusPlus ? "_ZSt9terminatev" : "abort");
310}
311
John McCall8262b6a2010-07-17 00:43:08 +0000312static llvm::Constant *getCatchallRethrowFn(CodeGenFunction &CGF,
John McCallb2593832010-09-16 06:16:50 +0000313 llvm::StringRef Name) {
John McCall8262b6a2010-07-17 00:43:08 +0000314 const llvm::Type *Int8PtrTy =
315 llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
316 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
317
318 const llvm::Type *VoidTy = llvm::Type::getVoidTy(CGF.getLLVMContext());
319 const llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, Args, false);
320
321 return CGF.CGM.CreateRuntimeFunction(FTy, Name);
John McCallf1549f62010-07-06 01:34:17 +0000322}
323
John McCall8262b6a2010-07-17 00:43:08 +0000324const EHPersonality EHPersonality::GNU_C("__gcc_personality_v0");
John McCall44680782010-11-07 02:35:25 +0000325const EHPersonality EHPersonality::GNU_C_SJLJ("__gcc_personality_sj0");
John McCall8262b6a2010-07-17 00:43:08 +0000326const EHPersonality EHPersonality::NeXT_ObjC("__objc_personality_v0");
327const EHPersonality EHPersonality::GNU_CPlusPlus("__gxx_personality_v0");
328const EHPersonality EHPersonality::GNU_CPlusPlus_SJLJ("__gxx_personality_sj0");
329const EHPersonality EHPersonality::GNU_ObjC("__gnu_objc_personality_v0",
330 "objc_exception_throw");
331
332static const EHPersonality &getCPersonality(const LangOptions &L) {
John McCall44680782010-11-07 02:35:25 +0000333 if (L.SjLjExceptions)
334 return EHPersonality::GNU_C_SJLJ;
John McCall8262b6a2010-07-17 00:43:08 +0000335 return EHPersonality::GNU_C;
336}
337
338static const EHPersonality &getObjCPersonality(const LangOptions &L) {
339 if (L.NeXTRuntime) {
340 if (L.ObjCNonFragileABI) return EHPersonality::NeXT_ObjC;
341 else return getCPersonality(L);
John McCallf1549f62010-07-06 01:34:17 +0000342 } else {
John McCall8262b6a2010-07-17 00:43:08 +0000343 return EHPersonality::GNU_ObjC;
John McCallf1549f62010-07-06 01:34:17 +0000344 }
345}
346
John McCall8262b6a2010-07-17 00:43:08 +0000347static const EHPersonality &getCXXPersonality(const LangOptions &L) {
348 if (L.SjLjExceptions)
349 return EHPersonality::GNU_CPlusPlus_SJLJ;
John McCallf1549f62010-07-06 01:34:17 +0000350 else
John McCall8262b6a2010-07-17 00:43:08 +0000351 return EHPersonality::GNU_CPlusPlus;
John McCallf1549f62010-07-06 01:34:17 +0000352}
353
354/// Determines the personality function to use when both C++
355/// and Objective-C exceptions are being caught.
John McCall8262b6a2010-07-17 00:43:08 +0000356static const EHPersonality &getObjCXXPersonality(const LangOptions &L) {
John McCallf1549f62010-07-06 01:34:17 +0000357 // The ObjC personality defers to the C++ personality for non-ObjC
358 // handlers. Unlike the C++ case, we use the same personality
359 // function on targets using (backend-driven) SJLJ EH.
John McCall8262b6a2010-07-17 00:43:08 +0000360 if (L.NeXTRuntime) {
361 if (L.ObjCNonFragileABI)
362 return EHPersonality::NeXT_ObjC;
John McCallf1549f62010-07-06 01:34:17 +0000363
364 // In the fragile ABI, just use C++ exception handling and hope
365 // they're not doing crazy exception mixing.
366 else
John McCall8262b6a2010-07-17 00:43:08 +0000367 return getCXXPersonality(L);
Chandler Carruthdcf22ad2010-05-17 20:58:49 +0000368 }
David Chisnall79a9ad82010-05-17 13:49:20 +0000369
John McCall8262b6a2010-07-17 00:43:08 +0000370 // The GNU runtime's personality function inherently doesn't support
371 // mixed EH. Use the C++ personality just to avoid returning null.
372 return getCXXPersonality(L);
John McCallf1549f62010-07-06 01:34:17 +0000373}
374
John McCall8262b6a2010-07-17 00:43:08 +0000375const EHPersonality &EHPersonality::get(const LangOptions &L) {
376 if (L.CPlusPlus && L.ObjC1)
377 return getObjCXXPersonality(L);
378 else if (L.CPlusPlus)
379 return getCXXPersonality(L);
380 else if (L.ObjC1)
381 return getObjCPersonality(L);
John McCallf1549f62010-07-06 01:34:17 +0000382 else
John McCall8262b6a2010-07-17 00:43:08 +0000383 return getCPersonality(L);
384}
John McCallf1549f62010-07-06 01:34:17 +0000385
John McCallb2593832010-09-16 06:16:50 +0000386static llvm::Constant *getPersonalityFn(CodeGenModule &CGM,
John McCall8262b6a2010-07-17 00:43:08 +0000387 const EHPersonality &Personality) {
John McCall8262b6a2010-07-17 00:43:08 +0000388 llvm::Constant *Fn =
John McCallb2593832010-09-16 06:16:50 +0000389 CGM.CreateRuntimeFunction(llvm::FunctionType::get(
390 llvm::Type::getInt32Ty(CGM.getLLVMContext()),
391 true),
392 Personality.getPersonalityFnName());
393 return Fn;
394}
395
396static llvm::Constant *getOpaquePersonalityFn(CodeGenModule &CGM,
397 const EHPersonality &Personality) {
398 llvm::Constant *Fn = getPersonalityFn(CGM, Personality);
399 return llvm::ConstantExpr::getBitCast(Fn, CGM.PtrToInt8Ty);
400}
401
402/// Check whether a personality function could reasonably be swapped
403/// for a C++ personality function.
404static bool PersonalityHasOnlyCXXUses(llvm::Constant *Fn) {
405 for (llvm::Constant::use_iterator
406 I = Fn->use_begin(), E = Fn->use_end(); I != E; ++I) {
407 llvm::User *User = *I;
408
409 // Conditionally white-list bitcasts.
410 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(User)) {
411 if (CE->getOpcode() != llvm::Instruction::BitCast) return false;
412 if (!PersonalityHasOnlyCXXUses(CE))
413 return false;
414 continue;
415 }
416
417 // Otherwise, it has to be a selector call.
418 if (!isa<llvm::EHSelectorInst>(User)) return false;
419
420 llvm::EHSelectorInst *Selector = cast<llvm::EHSelectorInst>(User);
421 for (unsigned I = 2, E = Selector->getNumArgOperands(); I != E; ++I) {
422 // Look for something that would've been returned by the ObjC
423 // runtime's GetEHType() method.
424 llvm::GlobalVariable *GV
425 = dyn_cast<llvm::GlobalVariable>(Selector->getArgOperand(I));
426 if (!GV) continue;
427
428 // ObjC EH selector entries are always global variables with
429 // names starting like this.
430 if (GV->getName().startswith("OBJC_EHTYPE"))
431 return false;
432 }
433 }
434
435 return true;
436}
437
438/// Try to use the C++ personality function in ObjC++. Not doing this
439/// can cause some incompatibilities with gcc, which is more
440/// aggressive about only using the ObjC++ personality in a function
441/// when it really needs it.
442void CodeGenModule::SimplifyPersonality() {
443 // For now, this is really a Darwin-specific operation.
444 if (Context.Target.getTriple().getOS() != llvm::Triple::Darwin)
445 return;
446
447 // If we're not in ObjC++ -fexceptions, there's nothing to do.
448 if (!Features.CPlusPlus || !Features.ObjC1 || !Features.Exceptions)
449 return;
450
451 const EHPersonality &ObjCXX = EHPersonality::get(Features);
452 const EHPersonality &CXX = getCXXPersonality(Features);
453 if (&ObjCXX == &CXX ||
454 ObjCXX.getPersonalityFnName() == CXX.getPersonalityFnName())
455 return;
456
457 llvm::Function *Fn =
458 getModule().getFunction(ObjCXX.getPersonalityFnName());
459
460 // Nothing to do if it's unused.
461 if (!Fn || Fn->use_empty()) return;
462
463 // Can't do the optimization if it has non-C++ uses.
464 if (!PersonalityHasOnlyCXXUses(Fn)) return;
465
466 // Create the C++ personality function and kill off the old
467 // function.
468 llvm::Constant *CXXFn = getPersonalityFn(*this, CXX);
469
470 // This can happen if the user is screwing with us.
471 if (Fn->getType() != CXXFn->getType()) return;
472
473 Fn->replaceAllUsesWith(CXXFn);
474 Fn->eraseFromParent();
John McCallf1549f62010-07-06 01:34:17 +0000475}
476
477/// Returns the value to inject into a selector to indicate the
478/// presence of a catch-all.
479static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
480 // Possibly we should use @llvm.eh.catch.all.value here.
481 return llvm::ConstantPointerNull::get(CGF.CGM.PtrToInt8Ty);
482}
483
484/// Returns the value to inject into a selector to indicate the
485/// presence of a cleanup.
486static llvm::Constant *getCleanupValue(CodeGenFunction &CGF) {
487 return llvm::ConstantInt::get(CGF.Builder.getInt32Ty(), 0);
Mike Stump99533832009-12-02 07:41:41 +0000488}
489
John McCall09faeab2010-07-13 21:17:51 +0000490namespace {
491 /// A cleanup to free the exception object if its initialization
492 /// throws.
John McCall3ad32c82011-01-28 08:37:24 +0000493 struct FreeException {
494 static void Emit(CodeGenFunction &CGF, bool forEH,
495 llvm::Value *exn) {
496 CGF.Builder.CreateCall(getFreeExceptionFn(CGF), exn)
John McCall09faeab2010-07-13 21:17:51 +0000497 ->setDoesNotThrow();
John McCall09faeab2010-07-13 21:17:51 +0000498 }
499 };
500}
501
John McCallac418162010-04-22 01:10:34 +0000502// Emits an exception expression into the given location. This
503// differs from EmitAnyExprToMem only in that, if a final copy-ctor
504// call is required, an exception within that copy ctor causes
505// std::terminate to be invoked.
John McCall3ad32c82011-01-28 08:37:24 +0000506static void EmitAnyExprToExn(CodeGenFunction &CGF, const Expr *e,
507 llvm::Value *addr) {
John McCallf1549f62010-07-06 01:34:17 +0000508 // Make sure the exception object is cleaned up if there's an
509 // exception during initialization.
John McCall3ad32c82011-01-28 08:37:24 +0000510 CGF.pushFullExprCleanup<FreeException>(EHCleanup, addr);
511 EHScopeStack::stable_iterator cleanup = CGF.EHStack.stable_begin();
John McCallac418162010-04-22 01:10:34 +0000512
513 // __cxa_allocate_exception returns a void*; we need to cast this
514 // to the appropriate type for the object.
John McCall3ad32c82011-01-28 08:37:24 +0000515 const llvm::Type *ty = CGF.ConvertTypeForMem(e->getType())->getPointerTo();
516 llvm::Value *typedAddr = CGF.Builder.CreateBitCast(addr, ty);
John McCallac418162010-04-22 01:10:34 +0000517
518 // FIXME: this isn't quite right! If there's a final unelided call
519 // to a copy constructor, then according to [except.terminate]p1 we
520 // must call std::terminate() if that constructor throws, because
521 // technically that copy occurs after the exception expression is
522 // evaluated but before the exception is caught. But the best way
523 // to handle that is to teach EmitAggExpr to do the final copy
524 // differently if it can't be elided.
John McCall3ad32c82011-01-28 08:37:24 +0000525 CGF.EmitAnyExprToMem(e, typedAddr, /*Volatile*/ false, /*IsInit*/ true);
John McCallac418162010-04-22 01:10:34 +0000526
John McCall3ad32c82011-01-28 08:37:24 +0000527 // Deactivate the cleanup block.
528 CGF.DeactivateCleanupBlock(cleanup);
Mike Stump0f590be2009-12-01 03:41:18 +0000529}
530
John McCallf1549f62010-07-06 01:34:17 +0000531llvm::Value *CodeGenFunction::getExceptionSlot() {
532 if (!ExceptionSlot) {
533 const llvm::Type *i8p = llvm::Type::getInt8PtrTy(getLLVMContext());
534 ExceptionSlot = CreateTempAlloca(i8p, "exn.slot");
Mike Stump0f590be2009-12-01 03:41:18 +0000535 }
John McCallf1549f62010-07-06 01:34:17 +0000536 return ExceptionSlot;
Mike Stump0f590be2009-12-01 03:41:18 +0000537}
538
Anders Carlsson756b5c42009-10-30 01:42:31 +0000539void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E) {
Anders Carlssond3379292009-10-30 02:27:02 +0000540 if (!E->getSubExpr()) {
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000541 if (getInvokeDest()) {
John McCallf1549f62010-07-06 01:34:17 +0000542 Builder.CreateInvoke(getReThrowFn(*this),
543 getUnreachableBlock(),
544 getInvokeDest())
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000545 ->setDoesNotReturn();
John McCallf1549f62010-07-06 01:34:17 +0000546 } else {
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000547 Builder.CreateCall(getReThrowFn(*this))->setDoesNotReturn();
John McCallf1549f62010-07-06 01:34:17 +0000548 Builder.CreateUnreachable();
549 }
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000550
John McCallcd5b22e2011-01-12 03:41:02 +0000551 // throw is an expression, and the expression emitters expect us
552 // to leave ourselves at a valid insertion point.
553 EmitBlock(createBasicBlock("throw.cont"));
554
Anders Carlssond3379292009-10-30 02:27:02 +0000555 return;
556 }
Mike Stump8755ec32009-12-10 00:06:18 +0000557
Anders Carlssond3379292009-10-30 02:27:02 +0000558 QualType ThrowType = E->getSubExpr()->getType();
Mike Stump8755ec32009-12-10 00:06:18 +0000559
Anders Carlssond3379292009-10-30 02:27:02 +0000560 // Now allocate the exception object.
561 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
John McCall3d3ec1c2010-04-21 10:05:39 +0000562 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
Mike Stump8755ec32009-12-10 00:06:18 +0000563
Anders Carlssond3379292009-10-30 02:27:02 +0000564 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(*this);
John McCallf1549f62010-07-06 01:34:17 +0000565 llvm::CallInst *ExceptionPtr =
Mike Stump8755ec32009-12-10 00:06:18 +0000566 Builder.CreateCall(AllocExceptionFn,
Anders Carlssond3379292009-10-30 02:27:02 +0000567 llvm::ConstantInt::get(SizeTy, TypeSize),
568 "exception");
John McCallf1549f62010-07-06 01:34:17 +0000569 ExceptionPtr->setDoesNotThrow();
Anders Carlsson8370c582009-12-11 00:32:37 +0000570
John McCallac418162010-04-22 01:10:34 +0000571 EmitAnyExprToExn(*this, E->getSubExpr(), ExceptionPtr);
Mike Stump8755ec32009-12-10 00:06:18 +0000572
Anders Carlssond3379292009-10-30 02:27:02 +0000573 // Now throw the exception.
574 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(getLLVMContext());
Anders Carlsson82a113a2011-01-24 01:59:49 +0000575 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
576 /*ForEH=*/true);
John McCallac418162010-04-22 01:10:34 +0000577
578 // The address of the destructor. If the exception type has a
579 // trivial destructor (or isn't a record), we just pass null.
580 llvm::Constant *Dtor = 0;
581 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
582 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
583 if (!Record->hasTrivialDestructor()) {
Douglas Gregor1d110e02010-07-01 14:13:13 +0000584 CXXDestructorDecl *DtorD = Record->getDestructor();
John McCallac418162010-04-22 01:10:34 +0000585 Dtor = CGM.GetAddrOfCXXDestructor(DtorD, Dtor_Complete);
586 Dtor = llvm::ConstantExpr::getBitCast(Dtor, Int8PtrTy);
587 }
588 }
589 if (!Dtor) Dtor = llvm::Constant::getNullValue(Int8PtrTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000590
Mike Stump0a3816e2009-12-04 01:51:45 +0000591 if (getInvokeDest()) {
Mike Stump8755ec32009-12-10 00:06:18 +0000592 llvm::InvokeInst *ThrowCall =
John McCallf1549f62010-07-06 01:34:17 +0000593 Builder.CreateInvoke3(getThrowFn(*this),
594 getUnreachableBlock(), getInvokeDest(),
Mike Stump0a3816e2009-12-04 01:51:45 +0000595 ExceptionPtr, TypeInfo, Dtor);
596 ThrowCall->setDoesNotReturn();
Mike Stump0a3816e2009-12-04 01:51:45 +0000597 } else {
Mike Stump8755ec32009-12-10 00:06:18 +0000598 llvm::CallInst *ThrowCall =
Mike Stump0a3816e2009-12-04 01:51:45 +0000599 Builder.CreateCall3(getThrowFn(*this), ExceptionPtr, TypeInfo, Dtor);
600 ThrowCall->setDoesNotReturn();
John McCallf1549f62010-07-06 01:34:17 +0000601 Builder.CreateUnreachable();
Mike Stump0a3816e2009-12-04 01:51:45 +0000602 }
Mike Stump8755ec32009-12-10 00:06:18 +0000603
John McCallcd5b22e2011-01-12 03:41:02 +0000604 // throw is an expression, and the expression emitters expect us
605 // to leave ourselves at a valid insertion point.
606 EmitBlock(createBasicBlock("throw.cont"));
Anders Carlsson756b5c42009-10-30 01:42:31 +0000607}
Mike Stump2bf701e2009-11-20 23:44:51 +0000608
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000609void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
Anders Carlssona994ee42010-02-06 23:59:05 +0000610 if (!Exceptions)
611 return;
612
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000613 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
614 if (FD == 0)
615 return;
616 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
617 if (Proto == 0)
618 return;
619
620 assert(!Proto->hasAnyExceptionSpec() && "function with parameter pack");
621
622 if (!Proto->hasExceptionSpec())
623 return;
624
John McCallf1549f62010-07-06 01:34:17 +0000625 unsigned NumExceptions = Proto->getNumExceptions();
626 EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000627
John McCallf1549f62010-07-06 01:34:17 +0000628 for (unsigned I = 0; I != NumExceptions; ++I) {
629 QualType Ty = Proto->getExceptionType(I);
630 QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
Anders Carlsson82a113a2011-01-24 01:59:49 +0000631 llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType,
632 /*ForEH=*/true);
John McCallf1549f62010-07-06 01:34:17 +0000633 Filter->setFilter(I, EHType);
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000634 }
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000635}
636
637void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
Anders Carlssona994ee42010-02-06 23:59:05 +0000638 if (!Exceptions)
639 return;
640
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000641 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
642 if (FD == 0)
643 return;
644 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
645 if (Proto == 0)
646 return;
647
648 if (!Proto->hasExceptionSpec())
649 return;
650
John McCallf1549f62010-07-06 01:34:17 +0000651 EHStack.popFilter();
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000652}
653
Mike Stump2bf701e2009-11-20 23:44:51 +0000654void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
John McCall59a70002010-07-07 06:56:46 +0000655 EnterCXXTryStmt(S);
John McCall9fc6a772010-02-19 09:25:03 +0000656 EmitStmt(S.getTryBlock());
John McCall59a70002010-07-07 06:56:46 +0000657 ExitCXXTryStmt(S);
John McCall9fc6a772010-02-19 09:25:03 +0000658}
659
John McCall59a70002010-07-07 06:56:46 +0000660void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallf1549f62010-07-06 01:34:17 +0000661 unsigned NumHandlers = S.getNumHandlers();
662 EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
John McCall9fc6a772010-02-19 09:25:03 +0000663
John McCallf1549f62010-07-06 01:34:17 +0000664 for (unsigned I = 0; I != NumHandlers; ++I) {
665 const CXXCatchStmt *C = S.getHandler(I);
John McCall9fc6a772010-02-19 09:25:03 +0000666
John McCallf1549f62010-07-06 01:34:17 +0000667 llvm::BasicBlock *Handler = createBasicBlock("catch");
668 if (C->getExceptionDecl()) {
669 // FIXME: Dropping the reference type on the type into makes it
670 // impossible to correctly implement catch-by-reference
671 // semantics for pointers. Unfortunately, this is what all
672 // existing compilers do, and it's not clear that the standard
673 // personality routine is capable of doing this right. See C++ DR 388:
674 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
675 QualType CaughtType = C->getCaughtType();
676 CaughtType = CaughtType.getNonReferenceType().getUnqualifiedType();
John McCall5a180392010-07-24 00:37:23 +0000677
678 llvm::Value *TypeInfo = 0;
679 if (CaughtType->isObjCObjectPointerType())
680 TypeInfo = CGM.getObjCRuntime().GetEHType(CaughtType);
681 else
Anders Carlsson82a113a2011-01-24 01:59:49 +0000682 TypeInfo = CGM.GetAddrOfRTTIDescriptor(CaughtType, /*ForEH=*/true);
John McCallf1549f62010-07-06 01:34:17 +0000683 CatchScope->setHandler(I, TypeInfo, Handler);
684 } else {
685 // No exception decl indicates '...', a catch-all.
686 CatchScope->setCatchAllHandler(I, Handler);
687 }
688 }
John McCallf1549f62010-07-06 01:34:17 +0000689}
690
691/// Check whether this is a non-EH scope, i.e. a scope which doesn't
692/// affect exception handling. Currently, the only non-EH scopes are
693/// normal-only cleanup scopes.
694static bool isNonEHScope(const EHScope &S) {
John McCallda65ea82010-07-13 20:32:21 +0000695 switch (S.getKind()) {
John McCall1f0fca52010-07-21 07:22:38 +0000696 case EHScope::Cleanup:
697 return !cast<EHCleanupScope>(S).isEHCleanup();
John McCallda65ea82010-07-13 20:32:21 +0000698 case EHScope::Filter:
699 case EHScope::Catch:
700 case EHScope::Terminate:
701 return false;
702 }
703
704 // Suppress warning.
705 return false;
John McCallf1549f62010-07-06 01:34:17 +0000706}
707
708llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
709 assert(EHStack.requiresLandingPad());
710 assert(!EHStack.empty());
711
John McCallda65ea82010-07-13 20:32:21 +0000712 if (!Exceptions)
713 return 0;
714
John McCallf1549f62010-07-06 01:34:17 +0000715 // Check the innermost scope for a cached landing pad. If this is
716 // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
717 llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
718 if (LP) return LP;
719
720 // Build the landing pad for this scope.
721 LP = EmitLandingPad();
722 assert(LP);
723
724 // Cache the landing pad on the innermost scope. If this is a
725 // non-EH scope, cache the landing pad on the enclosing scope, too.
726 for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
727 ir->setCachedLandingPad(LP);
728 if (!isNonEHScope(*ir)) break;
729 }
730
731 return LP;
732}
733
734llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
735 assert(EHStack.requiresLandingPad());
736
737 // This function contains a hack to work around a design flaw in
738 // LLVM's EH IR which breaks semantics after inlining. This same
739 // hack is implemented in llvm-gcc.
740 //
741 // The LLVM EH abstraction is basically a thin veneer over the
742 // traditional GCC zero-cost design: for each range of instructions
743 // in the function, there is (at most) one "landing pad" with an
744 // associated chain of EH actions. A language-specific personality
745 // function interprets this chain of actions and (1) decides whether
746 // or not to resume execution at the landing pad and (2) if so,
747 // provides an integer indicating why it's stopping. In LLVM IR,
748 // the association of a landing pad with a range of instructions is
749 // achieved via an invoke instruction, the chain of actions becomes
750 // the arguments to the @llvm.eh.selector call, and the selector
751 // call returns the integer indicator. Other than the required
752 // presence of two intrinsic function calls in the landing pad,
753 // the IR exactly describes the layout of the output code.
754 //
755 // A principal advantage of this design is that it is completely
756 // language-agnostic; in theory, the LLVM optimizers can treat
757 // landing pads neutrally, and targets need only know how to lower
758 // the intrinsics to have a functioning exceptions system (assuming
759 // that platform exceptions follow something approximately like the
760 // GCC design). Unfortunately, landing pads cannot be combined in a
761 // language-agnostic way: given selectors A and B, there is no way
762 // to make a single landing pad which faithfully represents the
763 // semantics of propagating an exception first through A, then
764 // through B, without knowing how the personality will interpret the
765 // (lowered form of the) selectors. This means that inlining has no
766 // choice but to crudely chain invokes (i.e., to ignore invokes in
767 // the inlined function, but to turn all unwindable calls into
768 // invokes), which is only semantically valid if every unwind stops
769 // at every landing pad.
770 //
771 // Therefore, the invoke-inline hack is to guarantee that every
772 // landing pad has a catch-all.
773 const bool UseInvokeInlineHack = true;
774
775 for (EHScopeStack::iterator ir = EHStack.begin(); ; ) {
776 assert(ir != EHStack.end() &&
777 "stack requiring landing pad is nothing but non-EH scopes?");
778
779 // If this is a terminate scope, just use the singleton terminate
780 // landing pad.
781 if (isa<EHTerminateScope>(*ir))
782 return getTerminateLandingPad();
783
784 // If this isn't an EH scope, iterate; otherwise break out.
785 if (!isNonEHScope(*ir)) break;
786 ++ir;
787
788 // We haven't checked this scope for a cached landing pad yet.
789 if (llvm::BasicBlock *LP = ir->getCachedLandingPad())
790 return LP;
791 }
792
793 // Save the current IR generation state.
794 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
795
John McCall8262b6a2010-07-17 00:43:08 +0000796 const EHPersonality &Personality =
797 EHPersonality::get(CGF.CGM.getLangOptions());
798
John McCallf1549f62010-07-06 01:34:17 +0000799 // Create and configure the landing pad.
800 llvm::BasicBlock *LP = createBasicBlock("lpad");
801 EmitBlock(LP);
802
803 // Save the exception pointer. It's safe to use a single exception
804 // pointer per function because EH cleanups can never have nested
805 // try/catches.
806 llvm::CallInst *Exn =
807 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_exception), "exn");
808 Exn->setDoesNotThrow();
809 Builder.CreateStore(Exn, getExceptionSlot());
810
811 // Build the selector arguments.
812 llvm::SmallVector<llvm::Value*, 8> EHSelector;
813 EHSelector.push_back(Exn);
John McCallb2593832010-09-16 06:16:50 +0000814 EHSelector.push_back(getOpaquePersonalityFn(CGM, Personality));
John McCallf1549f62010-07-06 01:34:17 +0000815
816 // Accumulate all the handlers in scope.
John McCallff8e1152010-07-23 21:56:41 +0000817 llvm::DenseMap<llvm::Value*, UnwindDest> EHHandlers;
818 UnwindDest CatchAll;
John McCallf1549f62010-07-06 01:34:17 +0000819 bool HasEHCleanup = false;
820 bool HasEHFilter = false;
821 llvm::SmallVector<llvm::Value*, 8> EHFilters;
822 for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end();
823 I != E; ++I) {
824
825 switch (I->getKind()) {
John McCall1f0fca52010-07-21 07:22:38 +0000826 case EHScope::Cleanup:
John McCallda65ea82010-07-13 20:32:21 +0000827 if (!HasEHCleanup)
John McCall1f0fca52010-07-21 07:22:38 +0000828 HasEHCleanup = cast<EHCleanupScope>(*I).isEHCleanup();
John McCallda65ea82010-07-13 20:32:21 +0000829 // We otherwise don't care about cleanups.
830 continue;
831
John McCallf1549f62010-07-06 01:34:17 +0000832 case EHScope::Filter: {
833 assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
John McCallff8e1152010-07-23 21:56:41 +0000834 assert(!CatchAll.isValid() && "EH filter reached after catch-all");
John McCallf1549f62010-07-06 01:34:17 +0000835
836 // Filter scopes get added to the selector in wierd ways.
837 EHFilterScope &Filter = cast<EHFilterScope>(*I);
838 HasEHFilter = true;
839
840 // Add all the filter values which we aren't already explicitly
841 // catching.
842 for (unsigned I = 0, E = Filter.getNumFilters(); I != E; ++I) {
843 llvm::Value *FV = Filter.getFilter(I);
844 if (!EHHandlers.count(FV))
845 EHFilters.push_back(FV);
846 }
847 goto done;
848 }
849
850 case EHScope::Terminate:
851 // Terminate scopes are basically catch-alls.
John McCallff8e1152010-07-23 21:56:41 +0000852 assert(!CatchAll.isValid());
853 CatchAll = UnwindDest(getTerminateHandler(),
854 EHStack.getEnclosingEHCleanup(I),
855 cast<EHTerminateScope>(*I).getDestIndex());
John McCallf1549f62010-07-06 01:34:17 +0000856 goto done;
857
858 case EHScope::Catch:
859 break;
860 }
861
862 EHCatchScope &Catch = cast<EHCatchScope>(*I);
863 for (unsigned HI = 0, HE = Catch.getNumHandlers(); HI != HE; ++HI) {
864 EHCatchScope::Handler Handler = Catch.getHandler(HI);
865
866 // Catch-all. We should only have one of these per catch.
867 if (!Handler.Type) {
John McCallff8e1152010-07-23 21:56:41 +0000868 assert(!CatchAll.isValid());
869 CatchAll = UnwindDest(Handler.Block,
870 EHStack.getEnclosingEHCleanup(I),
871 Handler.Index);
John McCallf1549f62010-07-06 01:34:17 +0000872 continue;
873 }
874
875 // Check whether we already have a handler for this type.
John McCallff8e1152010-07-23 21:56:41 +0000876 UnwindDest &Dest = EHHandlers[Handler.Type];
877 if (Dest.isValid()) continue;
John McCallf1549f62010-07-06 01:34:17 +0000878
879 EHSelector.push_back(Handler.Type);
John McCallff8e1152010-07-23 21:56:41 +0000880 Dest = UnwindDest(Handler.Block,
881 EHStack.getEnclosingEHCleanup(I),
882 Handler.Index);
John McCallf1549f62010-07-06 01:34:17 +0000883 }
884
885 // Stop if we found a catch-all.
John McCallff8e1152010-07-23 21:56:41 +0000886 if (CatchAll.isValid()) break;
John McCallf1549f62010-07-06 01:34:17 +0000887 }
888
889 done:
890 unsigned LastToEmitInLoop = EHSelector.size();
891
892 // If we have a catch-all, add null to the selector.
John McCallff8e1152010-07-23 21:56:41 +0000893 if (CatchAll.isValid()) {
John McCallf1549f62010-07-06 01:34:17 +0000894 EHSelector.push_back(getCatchAllValue(CGF));
895
896 // If we have an EH filter, we need to add those handlers in the
897 // right place in the selector, which is to say, at the end.
898 } else if (HasEHFilter) {
899 // Create a filter expression: an integer constant saying how many
900 // filters there are (+1 to avoid ambiguity with 0 for cleanup),
901 // followed by the filter types. The personality routine only
902 // lands here if the filter doesn't match.
903 EHSelector.push_back(llvm::ConstantInt::get(Builder.getInt32Ty(),
904 EHFilters.size() + 1));
905 EHSelector.append(EHFilters.begin(), EHFilters.end());
906
907 // Also check whether we need a cleanup.
908 if (UseInvokeInlineHack || HasEHCleanup)
909 EHSelector.push_back(UseInvokeInlineHack
910 ? getCatchAllValue(CGF)
911 : getCleanupValue(CGF));
912
913 // Otherwise, signal that we at least have cleanups.
914 } else if (UseInvokeInlineHack || HasEHCleanup) {
915 EHSelector.push_back(UseInvokeInlineHack
916 ? getCatchAllValue(CGF)
917 : getCleanupValue(CGF));
918 } else {
919 assert(LastToEmitInLoop > 2);
920 LastToEmitInLoop--;
921 }
922
923 assert(EHSelector.size() >= 3 && "selector call has only two arguments!");
924
925 // Tell the backend how to generate the landing pad.
926 llvm::CallInst *Selection =
927 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_selector),
928 EHSelector.begin(), EHSelector.end(), "eh.selector");
929 Selection->setDoesNotThrow();
930
931 // Select the right handler.
932 llvm::Value *llvm_eh_typeid_for =
933 CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
934
935 // The results of llvm_eh_typeid_for aren't reliable --- at least
936 // not locally --- so we basically have to do this as an 'if' chain.
937 // We walk through the first N-1 catch clauses, testing and chaining,
938 // and then fall into the final clause (which is either a cleanup, a
939 // filter (possibly with a cleanup), a catch-all, or another catch).
940 for (unsigned I = 2; I != LastToEmitInLoop; ++I) {
941 llvm::Value *Type = EHSelector[I];
John McCallff8e1152010-07-23 21:56:41 +0000942 UnwindDest Dest = EHHandlers[Type];
943 assert(Dest.isValid() && "no handler entry for value in selector?");
John McCallf1549f62010-07-06 01:34:17 +0000944
945 // Figure out where to branch on a match. As a debug code-size
946 // optimization, if the scope depth matches the innermost cleanup,
947 // we branch directly to the catch handler.
John McCallff8e1152010-07-23 21:56:41 +0000948 llvm::BasicBlock *Match = Dest.getBlock();
949 bool MatchNeedsCleanup =
950 Dest.getScopeDepth() != EHStack.getInnermostEHCleanup();
John McCallf1549f62010-07-06 01:34:17 +0000951 if (MatchNeedsCleanup)
952 Match = createBasicBlock("eh.match");
953
954 llvm::BasicBlock *Next = createBasicBlock("eh.next");
955
956 // Check whether the exception matches.
957 llvm::CallInst *Id
958 = Builder.CreateCall(llvm_eh_typeid_for,
959 Builder.CreateBitCast(Type, CGM.PtrToInt8Ty));
960 Id->setDoesNotThrow();
961 Builder.CreateCondBr(Builder.CreateICmpEQ(Selection, Id),
962 Match, Next);
963
964 // Emit match code if necessary.
965 if (MatchNeedsCleanup) {
966 EmitBlock(Match);
967 EmitBranchThroughEHCleanup(Dest);
968 }
969
970 // Continue to the next match.
971 EmitBlock(Next);
972 }
973
974 // Emit the final case in the selector.
975 // This might be a catch-all....
John McCallff8e1152010-07-23 21:56:41 +0000976 if (CatchAll.isValid()) {
John McCallf1549f62010-07-06 01:34:17 +0000977 assert(isa<llvm::ConstantPointerNull>(EHSelector.back()));
978 EmitBranchThroughEHCleanup(CatchAll);
979
980 // ...or an EH filter...
981 } else if (HasEHFilter) {
982 llvm::Value *SavedSelection = Selection;
983
984 // First, unwind out to the outermost scope if necessary.
985 if (EHStack.hasEHCleanups()) {
986 // The end here might not dominate the beginning, so we might need to
987 // save the selector if we need it.
988 llvm::AllocaInst *SelectorVar = 0;
989 if (HasEHCleanup) {
990 SelectorVar = CreateTempAlloca(Builder.getInt32Ty(), "selector.var");
991 Builder.CreateStore(Selection, SelectorVar);
992 }
993
994 llvm::BasicBlock *CleanupContBB = createBasicBlock("ehspec.cleanup.cont");
John McCallff8e1152010-07-23 21:56:41 +0000995 EmitBranchThroughEHCleanup(UnwindDest(CleanupContBB, EHStack.stable_end(),
996 EHStack.getNextEHDestIndex()));
John McCallf1549f62010-07-06 01:34:17 +0000997 EmitBlock(CleanupContBB);
998
999 if (HasEHCleanup)
1000 SavedSelection = Builder.CreateLoad(SelectorVar, "ehspec.saved-selector");
1001 }
1002
1003 // If there was a cleanup, we'll need to actually check whether we
1004 // landed here because the filter triggered.
1005 if (UseInvokeInlineHack || HasEHCleanup) {
1006 llvm::BasicBlock *RethrowBB = createBasicBlock("cleanup");
1007 llvm::BasicBlock *UnexpectedBB = createBasicBlock("ehspec.unexpected");
1008
1009 llvm::Constant *Zero = llvm::ConstantInt::get(Builder.getInt32Ty(), 0);
1010 llvm::Value *FailsFilter =
1011 Builder.CreateICmpSLT(SavedSelection, Zero, "ehspec.fails");
1012 Builder.CreateCondBr(FailsFilter, UnexpectedBB, RethrowBB);
1013
1014 // The rethrow block is where we land if this was a cleanup.
1015 // TODO: can this be _Unwind_Resume if the InvokeInlineHack is off?
1016 EmitBlock(RethrowBB);
1017 Builder.CreateCall(getUnwindResumeOrRethrowFn(),
1018 Builder.CreateLoad(getExceptionSlot()))
1019 ->setDoesNotReturn();
1020 Builder.CreateUnreachable();
1021
1022 EmitBlock(UnexpectedBB);
1023 }
1024
1025 // Call __cxa_call_unexpected. This doesn't need to be an invoke
1026 // because __cxa_call_unexpected magically filters exceptions
1027 // according to the last landing pad the exception was thrown
1028 // into. Seriously.
1029 Builder.CreateCall(getUnexpectedFn(*this),
1030 Builder.CreateLoad(getExceptionSlot()))
1031 ->setDoesNotReturn();
1032 Builder.CreateUnreachable();
1033
1034 // ...or a normal catch handler...
1035 } else if (!UseInvokeInlineHack && !HasEHCleanup) {
1036 llvm::Value *Type = EHSelector.back();
1037 EmitBranchThroughEHCleanup(EHHandlers[Type]);
1038
1039 // ...or a cleanup.
1040 } else {
John McCallff8e1152010-07-23 21:56:41 +00001041 EmitBranchThroughEHCleanup(getRethrowDest());
John McCallf1549f62010-07-06 01:34:17 +00001042 }
1043
1044 // Restore the old IR generation state.
1045 Builder.restoreIP(SavedIP);
1046
1047 return LP;
1048}
1049
John McCall8e3f8612010-07-13 22:12:14 +00001050namespace {
1051 /// A cleanup to call __cxa_end_catch. In many cases, the caught
1052 /// exception type lets us state definitively that the thrown exception
1053 /// type does not have a destructor. In particular:
1054 /// - Catch-alls tell us nothing, so we have to conservatively
1055 /// assume that the thrown exception might have a destructor.
1056 /// - Catches by reference behave according to their base types.
1057 /// - Catches of non-record types will only trigger for exceptions
1058 /// of non-record types, which never have destructors.
1059 /// - Catches of record types can trigger for arbitrary subclasses
1060 /// of the caught type, so we have to assume the actual thrown
1061 /// exception type might have a throwing destructor, even if the
1062 /// caught type's destructor is trivial or nothrow.
John McCall1f0fca52010-07-21 07:22:38 +00001063 struct CallEndCatch : EHScopeStack::Cleanup {
John McCall8e3f8612010-07-13 22:12:14 +00001064 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
1065 bool MightThrow;
1066
1067 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1068 if (!MightThrow) {
1069 CGF.Builder.CreateCall(getEndCatchFn(CGF))->setDoesNotThrow();
1070 return;
1071 }
1072
1073 CGF.EmitCallOrInvoke(getEndCatchFn(CGF), 0, 0);
1074 }
1075 };
1076}
1077
John McCallf1549f62010-07-06 01:34:17 +00001078/// Emits a call to __cxa_begin_catch and enters a cleanup to call
1079/// __cxa_end_catch.
John McCall8e3f8612010-07-13 22:12:14 +00001080///
1081/// \param EndMightThrow - true if __cxa_end_catch might throw
1082static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
1083 llvm::Value *Exn,
1084 bool EndMightThrow) {
John McCallf1549f62010-07-06 01:34:17 +00001085 llvm::CallInst *Call = CGF.Builder.CreateCall(getBeginCatchFn(CGF), Exn);
1086 Call->setDoesNotThrow();
1087
John McCall1f0fca52010-07-21 07:22:38 +00001088 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
John McCallf1549f62010-07-06 01:34:17 +00001089
1090 return Call;
1091}
1092
1093/// A "special initializer" callback for initializing a catch
1094/// parameter during catch initialization.
1095static void InitCatchParam(CodeGenFunction &CGF,
1096 const VarDecl &CatchParam,
1097 llvm::Value *ParamAddr) {
1098 // Load the exception from where the landing pad saved it.
1099 llvm::Value *Exn = CGF.Builder.CreateLoad(CGF.getExceptionSlot(), "exn");
1100
1101 CanQualType CatchType =
1102 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
1103 const llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
1104
1105 // If we're catching by reference, we can just cast the object
1106 // pointer to the appropriate pointer.
1107 if (isa<ReferenceType>(CatchType)) {
John McCall204b0752010-07-20 22:17:55 +00001108 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
1109 bool EndCatchMightThrow = CaughtType->isRecordType();
John McCall8e3f8612010-07-13 22:12:14 +00001110
John McCallf1549f62010-07-06 01:34:17 +00001111 // __cxa_begin_catch returns the adjusted object pointer.
John McCall8e3f8612010-07-13 22:12:14 +00001112 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
John McCall204b0752010-07-20 22:17:55 +00001113
1114 // We have no way to tell the personality function that we're
1115 // catching by reference, so if we're catching a pointer,
1116 // __cxa_begin_catch will actually return that pointer by value.
1117 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
1118 QualType PointeeType = PT->getPointeeType();
1119
1120 // When catching by reference, generally we should just ignore
1121 // this by-value pointer and use the exception object instead.
1122 if (!PointeeType->isRecordType()) {
1123
1124 // Exn points to the struct _Unwind_Exception header, which
1125 // we have to skip past in order to reach the exception data.
1126 unsigned HeaderSize =
1127 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
1128 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
1129
1130 // However, if we're catching a pointer-to-record type that won't
1131 // work, because the personality function might have adjusted
1132 // the pointer. There's actually no way for us to fully satisfy
1133 // the language/ABI contract here: we can't use Exn because it
1134 // might have the wrong adjustment, but we can't use the by-value
1135 // pointer because it's off by a level of abstraction.
1136 //
1137 // The current solution is to dump the adjusted pointer into an
1138 // alloca, which breaks language semantics (because changing the
1139 // pointer doesn't change the exception) but at least works.
1140 // The better solution would be to filter out non-exact matches
1141 // and rethrow them, but this is tricky because the rethrow
1142 // really needs to be catchable by other sites at this landing
1143 // pad. The best solution is to fix the personality function.
1144 } else {
1145 // Pull the pointer for the reference type off.
1146 const llvm::Type *PtrTy =
1147 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
1148
1149 // Create the temporary and write the adjusted pointer into it.
1150 llvm::Value *ExnPtrTmp = CGF.CreateTempAlloca(PtrTy, "exn.byref.tmp");
1151 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1152 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
1153
1154 // Bind the reference to the temporary.
1155 AdjustedExn = ExnPtrTmp;
1156 }
1157 }
1158
John McCallf1549f62010-07-06 01:34:17 +00001159 llvm::Value *ExnCast =
1160 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
1161 CGF.Builder.CreateStore(ExnCast, ParamAddr);
1162 return;
1163 }
1164
1165 // Non-aggregates (plus complexes).
1166 bool IsComplex = false;
1167 if (!CGF.hasAggregateLLVMType(CatchType) ||
1168 (IsComplex = CatchType->isAnyComplexType())) {
John McCall8e3f8612010-07-13 22:12:14 +00001169 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
John McCallf1549f62010-07-06 01:34:17 +00001170
1171 // If the catch type is a pointer type, __cxa_begin_catch returns
1172 // the pointer by value.
1173 if (CatchType->hasPointerRepresentation()) {
1174 llvm::Value *CastExn =
1175 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
1176 CGF.Builder.CreateStore(CastExn, ParamAddr);
1177 return;
1178 }
1179
1180 // Otherwise, it returns a pointer into the exception object.
1181
1182 const llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
1183 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1184
1185 if (IsComplex) {
1186 CGF.StoreComplexToAddr(CGF.LoadComplexFromAddr(Cast, /*volatile*/ false),
1187 ParamAddr, /*volatile*/ false);
1188 } else {
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001189 unsigned Alignment =
1190 CGF.getContext().getDeclAlign(&CatchParam).getQuantity();
John McCallf1549f62010-07-06 01:34:17 +00001191 llvm::Value *ExnLoad = CGF.Builder.CreateLoad(Cast, "exn.scalar");
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001192 CGF.EmitStoreOfScalar(ExnLoad, ParamAddr, /*volatile*/ false, Alignment,
1193 CatchType);
John McCallf1549f62010-07-06 01:34:17 +00001194 }
1195 return;
1196 }
1197
1198 // FIXME: this *really* needs to be done via a proper, Sema-emitted
1199 // initializer expression.
1200
1201 CXXRecordDecl *RD = CatchType.getTypePtr()->getAsCXXRecordDecl();
1202 assert(RD && "aggregate catch type was not a record!");
1203
1204 const llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
1205
1206 if (RD->hasTrivialCopyConstructor()) {
John McCall8e3f8612010-07-13 22:12:14 +00001207 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, true);
John McCallf1549f62010-07-06 01:34:17 +00001208 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1209 CGF.EmitAggregateCopy(ParamAddr, Cast, CatchType);
1210 return;
1211 }
1212
1213 // We have to call __cxa_get_exception_ptr to get the adjusted
1214 // pointer before copying.
1215 llvm::CallInst *AdjustedExn =
1216 CGF.Builder.CreateCall(getGetExceptionPtrFn(CGF), Exn);
1217 AdjustedExn->setDoesNotThrow();
1218 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1219
1220 CXXConstructorDecl *CD = RD->getCopyConstructor(CGF.getContext(), 0);
1221 assert(CD && "record has no copy constructor!");
1222 llvm::Value *CopyCtor = CGF.CGM.GetAddrOfCXXConstructor(CD, Ctor_Complete);
1223
1224 CallArgList CallArgs;
1225 CallArgs.push_back(std::make_pair(RValue::get(ParamAddr),
1226 CD->getThisType(CGF.getContext())));
1227 CallArgs.push_back(std::make_pair(RValue::get(Cast),
1228 CD->getParamDecl(0)->getType()));
1229
1230 const FunctionProtoType *FPT
1231 = CD->getType()->getAs<FunctionProtoType>();
1232
1233 // Call the copy ctor in a terminate scope.
1234 CGF.EHStack.pushTerminate();
1235 CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(CallArgs, FPT),
1236 CopyCtor, ReturnValueSlot(), CallArgs, CD);
1237 CGF.EHStack.popTerminate();
1238
1239 // Finally we can call __cxa_begin_catch.
John McCall8e3f8612010-07-13 22:12:14 +00001240 CallBeginCatch(CGF, Exn, true);
John McCallf1549f62010-07-06 01:34:17 +00001241}
1242
1243/// Begins a catch statement by initializing the catch variable and
1244/// calling __cxa_begin_catch.
1245static void BeginCatch(CodeGenFunction &CGF,
1246 const CXXCatchStmt *S) {
1247 // We have to be very careful with the ordering of cleanups here:
1248 // C++ [except.throw]p4:
1249 // The destruction [of the exception temporary] occurs
1250 // immediately after the destruction of the object declared in
1251 // the exception-declaration in the handler.
1252 //
1253 // So the precise ordering is:
1254 // 1. Construct catch variable.
1255 // 2. __cxa_begin_catch
1256 // 3. Enter __cxa_end_catch cleanup
1257 // 4. Enter dtor cleanup
1258 //
1259 // We do this by initializing the exception variable with a
1260 // "special initializer", InitCatchParam. Delegation sequence:
1261 // - ExitCXXTryStmt opens a RunCleanupsScope
1262 // - EmitLocalBlockVarDecl creates the variable and debug info
1263 // - InitCatchParam initializes the variable from the exception
1264 // - CallBeginCatch calls __cxa_begin_catch
1265 // - CallBeginCatch enters the __cxa_end_catch cleanup
1266 // - EmitLocalBlockVarDecl enters the variable destructor cleanup
1267 // - EmitCXXTryStmt emits the code for the catch body
1268 // - EmitCXXTryStmt close the RunCleanupsScope
1269
1270 VarDecl *CatchParam = S->getExceptionDecl();
1271 if (!CatchParam) {
1272 llvm::Value *Exn = CGF.Builder.CreateLoad(CGF.getExceptionSlot(), "exn");
John McCall8e3f8612010-07-13 22:12:14 +00001273 CallBeginCatch(CGF, Exn, true);
John McCallf1549f62010-07-06 01:34:17 +00001274 return;
1275 }
1276
1277 // Emit the local.
John McCallb6bbcc92010-10-15 04:57:14 +00001278 CGF.EmitAutoVarDecl(*CatchParam, &InitCatchParam);
John McCall9fc6a772010-02-19 09:25:03 +00001279}
1280
John McCallfcd5c0c2010-07-13 22:24:23 +00001281namespace {
John McCall1f0fca52010-07-21 07:22:38 +00001282 struct CallRethrow : EHScopeStack::Cleanup {
John McCallfcd5c0c2010-07-13 22:24:23 +00001283 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1284 CGF.EmitCallOrInvoke(getReThrowFn(CGF), 0, 0);
1285 }
1286 };
1287}
1288
John McCall59a70002010-07-07 06:56:46 +00001289void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallf1549f62010-07-06 01:34:17 +00001290 unsigned NumHandlers = S.getNumHandlers();
1291 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1292 assert(CatchScope.getNumHandlers() == NumHandlers);
Mike Stump2bf701e2009-11-20 23:44:51 +00001293
John McCallf1549f62010-07-06 01:34:17 +00001294 // Copy the handler blocks off before we pop the EH stack. Emitting
1295 // the handlers might scribble on this memory.
1296 llvm::SmallVector<EHCatchScope::Handler, 8> Handlers(NumHandlers);
1297 memcpy(Handlers.data(), CatchScope.begin(),
1298 NumHandlers * sizeof(EHCatchScope::Handler));
1299 EHStack.popCatch();
Mike Stump2bf701e2009-11-20 23:44:51 +00001300
John McCallf1549f62010-07-06 01:34:17 +00001301 // The fall-through block.
1302 llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
Mike Stump2bf701e2009-11-20 23:44:51 +00001303
John McCallf1549f62010-07-06 01:34:17 +00001304 // We just emitted the body of the try; jump to the continue block.
1305 if (HaveInsertPoint())
1306 Builder.CreateBr(ContBB);
Mike Stump639787c2009-12-02 19:53:57 +00001307
John McCall59a70002010-07-07 06:56:46 +00001308 // Determine if we need an implicit rethrow for all these catch handlers.
1309 bool ImplicitRethrow = false;
1310 if (IsFnTryBlock)
1311 ImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
1312 isa<CXXConstructorDecl>(CurCodeDecl);
1313
John McCallf1549f62010-07-06 01:34:17 +00001314 for (unsigned I = 0; I != NumHandlers; ++I) {
1315 llvm::BasicBlock *CatchBlock = Handlers[I].Block;
1316 EmitBlock(CatchBlock);
Mike Stump8755ec32009-12-10 00:06:18 +00001317
John McCallf1549f62010-07-06 01:34:17 +00001318 // Catch the exception if this isn't a catch-all.
1319 const CXXCatchStmt *C = S.getHandler(I);
Mike Stump2bf701e2009-11-20 23:44:51 +00001320
John McCallf1549f62010-07-06 01:34:17 +00001321 // Enter a cleanup scope, including the catch variable and the
1322 // end-catch.
1323 RunCleanupsScope CatchScope(*this);
Mike Stump2bf701e2009-11-20 23:44:51 +00001324
John McCallf1549f62010-07-06 01:34:17 +00001325 // Initialize the catch variable and set up the cleanups.
1326 BeginCatch(*this, C);
1327
John McCall59a70002010-07-07 06:56:46 +00001328 // If there's an implicit rethrow, push a normal "cleanup" to call
John McCallfcd5c0c2010-07-13 22:24:23 +00001329 // _cxa_rethrow. This needs to happen before __cxa_end_catch is
1330 // called, and so it is pushed after BeginCatch.
1331 if (ImplicitRethrow)
John McCall1f0fca52010-07-21 07:22:38 +00001332 EHStack.pushCleanup<CallRethrow>(NormalCleanup);
John McCall59a70002010-07-07 06:56:46 +00001333
John McCallf1549f62010-07-06 01:34:17 +00001334 // Perform the body of the catch.
1335 EmitStmt(C->getHandlerBlock());
1336
1337 // Fall out through the catch cleanups.
1338 CatchScope.ForceCleanup();
1339
1340 // Branch out of the try.
1341 if (HaveInsertPoint())
1342 Builder.CreateBr(ContBB);
Mike Stump2bf701e2009-11-20 23:44:51 +00001343 }
1344
John McCallf1549f62010-07-06 01:34:17 +00001345 EmitBlock(ContBB);
Mike Stump2bf701e2009-11-20 23:44:51 +00001346}
Mike Stumpd88ea562009-12-09 03:35:49 +00001347
John McCall55b20fc2010-07-21 00:52:03 +00001348namespace {
John McCall1f0fca52010-07-21 07:22:38 +00001349 struct CallEndCatchForFinally : EHScopeStack::Cleanup {
John McCall55b20fc2010-07-21 00:52:03 +00001350 llvm::Value *ForEHVar;
1351 llvm::Value *EndCatchFn;
1352 CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn)
1353 : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
1354
1355 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1356 llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
1357 llvm::BasicBlock *CleanupContBB =
1358 CGF.createBasicBlock("finally.cleanup.cont");
1359
1360 llvm::Value *ShouldEndCatch =
1361 CGF.Builder.CreateLoad(ForEHVar, "finally.endcatch");
1362 CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1363 CGF.EmitBlock(EndCatchBB);
1364 CGF.EmitCallOrInvoke(EndCatchFn, 0, 0); // catch-all, so might throw
1365 CGF.EmitBlock(CleanupContBB);
1366 }
1367 };
John McCall77199712010-07-21 05:47:49 +00001368
John McCall1f0fca52010-07-21 07:22:38 +00001369 struct PerformFinally : EHScopeStack::Cleanup {
John McCall77199712010-07-21 05:47:49 +00001370 const Stmt *Body;
1371 llvm::Value *ForEHVar;
1372 llvm::Value *EndCatchFn;
1373 llvm::Value *RethrowFn;
1374 llvm::Value *SavedExnVar;
1375
1376 PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
1377 llvm::Value *EndCatchFn,
1378 llvm::Value *RethrowFn, llvm::Value *SavedExnVar)
1379 : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1380 RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
1381
1382 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1383 // Enter a cleanup to call the end-catch function if one was provided.
1384 if (EndCatchFn)
John McCall1f0fca52010-07-21 07:22:38 +00001385 CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
1386 ForEHVar, EndCatchFn);
John McCall77199712010-07-21 05:47:49 +00001387
John McCalld96a8e72010-08-11 00:16:14 +00001388 // Save the current cleanup destination in case there are
1389 // cleanups in the finally block.
1390 llvm::Value *SavedCleanupDest =
1391 CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
1392 "cleanup.dest.saved");
1393
John McCall77199712010-07-21 05:47:49 +00001394 // Emit the finally block.
1395 CGF.EmitStmt(Body);
1396
1397 // If the end of the finally is reachable, check whether this was
1398 // for EH. If so, rethrow.
1399 if (CGF.HaveInsertPoint()) {
1400 llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
1401 llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
1402
1403 llvm::Value *ShouldRethrow =
1404 CGF.Builder.CreateLoad(ForEHVar, "finally.shouldthrow");
1405 CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1406
1407 CGF.EmitBlock(RethrowBB);
1408 if (SavedExnVar) {
1409 llvm::Value *Args[] = { CGF.Builder.CreateLoad(SavedExnVar) };
1410 CGF.EmitCallOrInvoke(RethrowFn, Args, Args+1);
1411 } else {
1412 CGF.EmitCallOrInvoke(RethrowFn, 0, 0);
1413 }
1414 CGF.Builder.CreateUnreachable();
1415
1416 CGF.EmitBlock(ContBB);
John McCalld96a8e72010-08-11 00:16:14 +00001417
1418 // Restore the cleanup destination.
1419 CGF.Builder.CreateStore(SavedCleanupDest,
1420 CGF.getNormalCleanupDestSlot());
John McCall77199712010-07-21 05:47:49 +00001421 }
1422
1423 // Leave the end-catch cleanup. As an optimization, pretend that
1424 // the fallthrough path was inaccessible; we've dynamically proven
1425 // that we're not in the EH case along that path.
1426 if (EndCatchFn) {
1427 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1428 CGF.PopCleanupBlock();
1429 CGF.Builder.restoreIP(SavedIP);
1430 }
1431
1432 // Now make sure we actually have an insertion point or the
1433 // cleanup gods will hate us.
1434 CGF.EnsureInsertPoint();
1435 }
1436 };
John McCall55b20fc2010-07-21 00:52:03 +00001437}
1438
John McCallf1549f62010-07-06 01:34:17 +00001439/// Enters a finally block for an implementation using zero-cost
1440/// exceptions. This is mostly general, but hard-codes some
1441/// language/ABI-specific behavior in the catch-all sections.
1442CodeGenFunction::FinallyInfo
1443CodeGenFunction::EnterFinallyBlock(const Stmt *Body,
1444 llvm::Constant *BeginCatchFn,
1445 llvm::Constant *EndCatchFn,
1446 llvm::Constant *RethrowFn) {
1447 assert((BeginCatchFn != 0) == (EndCatchFn != 0) &&
1448 "begin/end catch functions not paired");
1449 assert(RethrowFn && "rethrow function is required");
Mike Stumpd88ea562009-12-09 03:35:49 +00001450
John McCallf1549f62010-07-06 01:34:17 +00001451 // The rethrow function has one of the following two types:
1452 // void (*)()
1453 // void (*)(void*)
1454 // In the latter case we need to pass it the exception object.
1455 // But we can't use the exception slot because the @finally might
1456 // have a landing pad (which would overwrite the exception slot).
1457 const llvm::FunctionType *RethrowFnTy =
1458 cast<llvm::FunctionType>(
1459 cast<llvm::PointerType>(RethrowFn->getType())
1460 ->getElementType());
1461 llvm::Value *SavedExnVar = 0;
1462 if (RethrowFnTy->getNumParams())
1463 SavedExnVar = CreateTempAlloca(Builder.getInt8PtrTy(), "finally.exn");
Mike Stumpd88ea562009-12-09 03:35:49 +00001464
John McCallf1549f62010-07-06 01:34:17 +00001465 // A finally block is a statement which must be executed on any edge
1466 // out of a given scope. Unlike a cleanup, the finally block may
1467 // contain arbitrary control flow leading out of itself. In
1468 // addition, finally blocks should always be executed, even if there
1469 // are no catch handlers higher on the stack. Therefore, we
1470 // surround the protected scope with a combination of a normal
1471 // cleanup (to catch attempts to break out of the block via normal
1472 // control flow) and an EH catch-all (semantically "outside" any try
1473 // statement to which the finally block might have been attached).
1474 // The finally block itself is generated in the context of a cleanup
1475 // which conditionally leaves the catch-all.
John McCall3d3ec1c2010-04-21 10:05:39 +00001476
John McCallf1549f62010-07-06 01:34:17 +00001477 FinallyInfo Info;
John McCall3d3ec1c2010-04-21 10:05:39 +00001478
John McCallf1549f62010-07-06 01:34:17 +00001479 // Jump destination for performing the finally block on an exception
1480 // edge. We'll never actually reach this block, so unreachable is
1481 // fine.
1482 JumpDest RethrowDest = getJumpDestInCurrentScope(getUnreachableBlock());
John McCall3d3ec1c2010-04-21 10:05:39 +00001483
John McCallf1549f62010-07-06 01:34:17 +00001484 // Whether the finally block is being executed for EH purposes.
1485 llvm::AllocaInst *ForEHVar = CreateTempAlloca(CGF.Builder.getInt1Ty(),
1486 "finally.for-eh");
1487 InitTempAlloca(ForEHVar, llvm::ConstantInt::getFalse(getLLVMContext()));
Mike Stumpd88ea562009-12-09 03:35:49 +00001488
John McCallf1549f62010-07-06 01:34:17 +00001489 // Enter a normal cleanup which will perform the @finally block.
John McCall1f0fca52010-07-21 07:22:38 +00001490 EHStack.pushCleanup<PerformFinally>(NormalCleanup, Body,
1491 ForEHVar, EndCatchFn,
1492 RethrowFn, SavedExnVar);
John McCallf1549f62010-07-06 01:34:17 +00001493
1494 // Enter a catch-all scope.
1495 llvm::BasicBlock *CatchAllBB = createBasicBlock("finally.catchall");
1496 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1497 Builder.SetInsertPoint(CatchAllBB);
1498
1499 // If there's a begin-catch function, call it.
1500 if (BeginCatchFn) {
1501 Builder.CreateCall(BeginCatchFn, Builder.CreateLoad(getExceptionSlot()))
1502 ->setDoesNotThrow();
1503 }
1504
1505 // If we need to remember the exception pointer to rethrow later, do so.
1506 if (SavedExnVar) {
1507 llvm::Value *SavedExn = Builder.CreateLoad(getExceptionSlot());
1508 Builder.CreateStore(SavedExn, SavedExnVar);
1509 }
1510
1511 // Tell the finally block that we're in EH.
1512 Builder.CreateStore(llvm::ConstantInt::getTrue(getLLVMContext()), ForEHVar);
1513
1514 // Thread a jump through the finally cleanup.
1515 EmitBranchThroughCleanup(RethrowDest);
1516
1517 Builder.restoreIP(SavedIP);
1518
1519 EHCatchScope *CatchScope = EHStack.pushCatch(1);
1520 CatchScope->setCatchAllHandler(0, CatchAllBB);
1521
1522 return Info;
1523}
1524
1525void CodeGenFunction::ExitFinallyBlock(FinallyInfo &Info) {
1526 // Leave the finally catch-all.
1527 EHCatchScope &Catch = cast<EHCatchScope>(*EHStack.begin());
1528 llvm::BasicBlock *CatchAllBB = Catch.getHandler(0).Block;
1529 EHStack.popCatch();
1530
1531 // And leave the normal cleanup.
1532 PopCleanupBlock();
1533
1534 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1535 EmitBlock(CatchAllBB, true);
1536
1537 Builder.restoreIP(SavedIP);
1538}
1539
1540llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
1541 if (TerminateLandingPad)
1542 return TerminateLandingPad;
1543
1544 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1545
1546 // This will get inserted at the end of the function.
1547 TerminateLandingPad = createBasicBlock("terminate.lpad");
1548 Builder.SetInsertPoint(TerminateLandingPad);
1549
1550 // Tell the backend that this is a landing pad.
1551 llvm::CallInst *Exn =
1552 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_exception), "exn");
1553 Exn->setDoesNotThrow();
John McCall8262b6a2010-07-17 00:43:08 +00001554
1555 const EHPersonality &Personality = EHPersonality::get(CGM.getLangOptions());
John McCallf1549f62010-07-06 01:34:17 +00001556
1557 // Tell the backend what the exception table should be:
1558 // nothing but a catch-all.
John McCallb2593832010-09-16 06:16:50 +00001559 llvm::Value *Args[3] = { Exn, getOpaquePersonalityFn(CGM, Personality),
John McCallf1549f62010-07-06 01:34:17 +00001560 getCatchAllValue(*this) };
1561 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_selector),
1562 Args, Args+3, "eh.selector")
1563 ->setDoesNotThrow();
1564
1565 llvm::CallInst *TerminateCall = Builder.CreateCall(getTerminateFn(*this));
1566 TerminateCall->setDoesNotReturn();
1567 TerminateCall->setDoesNotThrow();
Mike Stumpd88ea562009-12-09 03:35:49 +00001568 CGF.Builder.CreateUnreachable();
1569
John McCallf1549f62010-07-06 01:34:17 +00001570 // Restore the saved insertion state.
1571 Builder.restoreIP(SavedIP);
John McCall891f80e2010-04-30 00:06:43 +00001572
John McCallf1549f62010-07-06 01:34:17 +00001573 return TerminateLandingPad;
Mike Stumpd88ea562009-12-09 03:35:49 +00001574}
Mike Stump9b39c512009-12-09 22:59:31 +00001575
1576llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
Mike Stump182f3832009-12-10 00:02:42 +00001577 if (TerminateHandler)
1578 return TerminateHandler;
1579
John McCallf1549f62010-07-06 01:34:17 +00001580 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
Mike Stump76958092009-12-09 23:31:35 +00001581
John McCallf1549f62010-07-06 01:34:17 +00001582 // Set up the terminate handler. This block is inserted at the very
1583 // end of the function by FinishFunction.
Mike Stump182f3832009-12-10 00:02:42 +00001584 TerminateHandler = createBasicBlock("terminate.handler");
John McCallf1549f62010-07-06 01:34:17 +00001585 Builder.SetInsertPoint(TerminateHandler);
1586 llvm::CallInst *TerminateCall = Builder.CreateCall(getTerminateFn(*this));
Mike Stump9b39c512009-12-09 22:59:31 +00001587 TerminateCall->setDoesNotReturn();
1588 TerminateCall->setDoesNotThrow();
1589 Builder.CreateUnreachable();
1590
John McCall3d3ec1c2010-04-21 10:05:39 +00001591 // Restore the saved insertion state.
John McCallf1549f62010-07-06 01:34:17 +00001592 Builder.restoreIP(SavedIP);
Mike Stump76958092009-12-09 23:31:35 +00001593
Mike Stump9b39c512009-12-09 22:59:31 +00001594 return TerminateHandler;
1595}
John McCallf1549f62010-07-06 01:34:17 +00001596
John McCallff8e1152010-07-23 21:56:41 +00001597CodeGenFunction::UnwindDest CodeGenFunction::getRethrowDest() {
1598 if (RethrowBlock.isValid()) return RethrowBlock;
1599
1600 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1601
1602 // We emit a jump to a notional label at the outermost unwind state.
1603 llvm::BasicBlock *Unwind = createBasicBlock("eh.resume");
1604 Builder.SetInsertPoint(Unwind);
1605
1606 const EHPersonality &Personality = EHPersonality::get(CGM.getLangOptions());
1607
1608 // This can always be a call because we necessarily didn't find
1609 // anything on the EH stack which needs our help.
John McCallb2593832010-09-16 06:16:50 +00001610 llvm::StringRef RethrowName = Personality.getCatchallRethrowFnName();
John McCallff8e1152010-07-23 21:56:41 +00001611 llvm::Constant *RethrowFn;
John McCallb2593832010-09-16 06:16:50 +00001612 if (!RethrowName.empty())
John McCallff8e1152010-07-23 21:56:41 +00001613 RethrowFn = getCatchallRethrowFn(*this, RethrowName);
1614 else
1615 RethrowFn = getUnwindResumeOrRethrowFn();
1616
1617 Builder.CreateCall(RethrowFn, Builder.CreateLoad(getExceptionSlot()))
1618 ->setDoesNotReturn();
1619 Builder.CreateUnreachable();
1620
1621 Builder.restoreIP(SavedIP);
1622
1623 RethrowBlock = UnwindDest(Unwind, EHStack.stable_end(), 0);
1624 return RethrowBlock;
1625}
1626
John McCall1f0fca52010-07-21 07:22:38 +00001627EHScopeStack::Cleanup::~Cleanup() {
1628 llvm_unreachable("Cleanup is indestructable");
John McCall3e29f962010-07-13 23:19:49 +00001629}