blob: 11e5e6452809bd9ea627e4bcc45f1bd9493d2998 [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
Anders Carlssond3379292009-10-30 02:27:02 +0000175static llvm::Constant *getAllocateExceptionFn(CodeGenFunction &CGF) {
176 // void *__cxa_allocate_exception(size_t thrown_size);
177 const llvm::Type *SizeTy = CGF.ConvertType(CGF.getContext().getSizeType());
178 std::vector<const llvm::Type*> Args(1, SizeTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000179
180 const llvm::FunctionType *FTy =
Anders Carlssond3379292009-10-30 02:27:02 +0000181 llvm::FunctionType::get(llvm::Type::getInt8PtrTy(CGF.getLLVMContext()),
182 Args, false);
Mike Stump8755ec32009-12-10 00:06:18 +0000183
Anders Carlssond3379292009-10-30 02:27:02 +0000184 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
185}
186
Mike Stump99533832009-12-02 07:41:41 +0000187static llvm::Constant *getFreeExceptionFn(CodeGenFunction &CGF) {
188 // void __cxa_free_exception(void *thrown_exception);
189 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
190 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000191
192 const llvm::FunctionType *FTy =
Mike Stump99533832009-12-02 07:41:41 +0000193 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
194 Args, false);
Mike Stump8755ec32009-12-10 00:06:18 +0000195
Mike Stump99533832009-12-02 07:41:41 +0000196 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_free_exception");
197}
198
Anders Carlssond3379292009-10-30 02:27:02 +0000199static llvm::Constant *getThrowFn(CodeGenFunction &CGF) {
Mike Stump8755ec32009-12-10 00:06:18 +0000200 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
Mike Stump99533832009-12-02 07:41:41 +0000201 // void (*dest) (void *));
Anders Carlssond3379292009-10-30 02:27:02 +0000202
203 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
204 std::vector<const llvm::Type*> Args(3, Int8PtrTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000205
206 const llvm::FunctionType *FTy =
Mike Stumpb4eea692009-11-20 00:56:31 +0000207 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
208 Args, false);
Mike Stump8755ec32009-12-10 00:06:18 +0000209
Anders Carlssond3379292009-10-30 02:27:02 +0000210 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
211}
212
Mike Stumpb4eea692009-11-20 00:56:31 +0000213static llvm::Constant *getReThrowFn(CodeGenFunction &CGF) {
Mike Stump99533832009-12-02 07:41:41 +0000214 // void __cxa_rethrow();
Mike Stumpb4eea692009-11-20 00:56:31 +0000215
Mike Stump8755ec32009-12-10 00:06:18 +0000216 const llvm::FunctionType *FTy =
Mike Stumpb4eea692009-11-20 00:56:31 +0000217 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()), false);
Mike Stump8755ec32009-12-10 00:06:18 +0000218
Mike Stumpb4eea692009-11-20 00:56:31 +0000219 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
220}
221
John McCallf1549f62010-07-06 01:34:17 +0000222static llvm::Constant *getGetExceptionPtrFn(CodeGenFunction &CGF) {
223 // void *__cxa_get_exception_ptr(void*);
224 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
225 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
226
227 const llvm::FunctionType *FTy =
228 llvm::FunctionType::get(Int8PtrTy, Args, false);
229
230 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
231}
232
Mike Stump2bf701e2009-11-20 23:44:51 +0000233static llvm::Constant *getBeginCatchFn(CodeGenFunction &CGF) {
John McCallf1549f62010-07-06 01:34:17 +0000234 // void *__cxa_begin_catch(void*);
Mike Stump2bf701e2009-11-20 23:44:51 +0000235
236 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
237 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000238
239 const llvm::FunctionType *FTy =
Mike Stump0f590be2009-12-01 03:41:18 +0000240 llvm::FunctionType::get(Int8PtrTy, Args, false);
Mike Stump8755ec32009-12-10 00:06:18 +0000241
Mike Stump2bf701e2009-11-20 23:44:51 +0000242 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
243}
244
245static llvm::Constant *getEndCatchFn(CodeGenFunction &CGF) {
Mike Stump99533832009-12-02 07:41:41 +0000246 // void __cxa_end_catch();
Mike Stump2bf701e2009-11-20 23:44:51 +0000247
Mike Stump8755ec32009-12-10 00:06:18 +0000248 const llvm::FunctionType *FTy =
Mike Stump2bf701e2009-11-20 23:44:51 +0000249 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()), false);
Mike Stump8755ec32009-12-10 00:06:18 +0000250
Mike Stump2bf701e2009-11-20 23:44:51 +0000251 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
252}
253
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000254static llvm::Constant *getUnexpectedFn(CodeGenFunction &CGF) {
255 // void __cxa_call_unexepcted(void *thrown_exception);
256
257 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
258 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000259
260 const llvm::FunctionType *FTy =
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000261 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
262 Args, false);
Mike Stump8755ec32009-12-10 00:06:18 +0000263
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000264 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_call_unexpected");
265}
266
Douglas Gregor86a3a032010-05-16 01:24:12 +0000267llvm::Constant *CodeGenFunction::getUnwindResumeOrRethrowFn() {
268 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(getLLVMContext());
Mike Stump0f590be2009-12-01 03:41:18 +0000269 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000270
271 const llvm::FunctionType *FTy =
Douglas Gregor86a3a032010-05-16 01:24:12 +0000272 llvm::FunctionType::get(llvm::Type::getVoidTy(getLLVMContext()), Args,
Mike Stump0f590be2009-12-01 03:41:18 +0000273 false);
Mike Stump8755ec32009-12-10 00:06:18 +0000274
Douglas Gregor86a3a032010-05-16 01:24:12 +0000275 if (CGM.getLangOptions().SjLjExceptions)
John McCalla5f2de22010-08-11 20:59:53 +0000276 return CGM.CreateRuntimeFunction(FTy, "_Unwind_SjLj_Resume_or_Rethrow");
Douglas Gregor86a3a032010-05-16 01:24:12 +0000277 return CGM.CreateRuntimeFunction(FTy, "_Unwind_Resume_or_Rethrow");
Mike Stump0f590be2009-12-01 03:41:18 +0000278}
279
Mike Stump99533832009-12-02 07:41:41 +0000280static llvm::Constant *getTerminateFn(CodeGenFunction &CGF) {
281 // void __terminate();
282
Mike Stump8755ec32009-12-10 00:06:18 +0000283 const llvm::FunctionType *FTy =
Mike Stump99533832009-12-02 07:41:41 +0000284 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()), false);
Mike Stump8755ec32009-12-10 00:06:18 +0000285
David Chisnall79a9ad82010-05-17 13:49:20 +0000286 return CGF.CGM.CreateRuntimeFunction(FTy,
287 CGF.CGM.getLangOptions().CPlusPlus ? "_ZSt9terminatev" : "abort");
288}
289
John McCall8262b6a2010-07-17 00:43:08 +0000290static llvm::Constant *getCatchallRethrowFn(CodeGenFunction &CGF,
John McCallb2593832010-09-16 06:16:50 +0000291 llvm::StringRef Name) {
John McCall8262b6a2010-07-17 00:43:08 +0000292 const llvm::Type *Int8PtrTy =
293 llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
294 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
295
296 const llvm::Type *VoidTy = llvm::Type::getVoidTy(CGF.getLLVMContext());
297 const llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, Args, false);
298
299 return CGF.CGM.CreateRuntimeFunction(FTy, Name);
John McCallf1549f62010-07-06 01:34:17 +0000300}
301
John McCall8262b6a2010-07-17 00:43:08 +0000302const EHPersonality EHPersonality::GNU_C("__gcc_personality_v0");
John McCall44680782010-11-07 02:35:25 +0000303const EHPersonality EHPersonality::GNU_C_SJLJ("__gcc_personality_sj0");
John McCall8262b6a2010-07-17 00:43:08 +0000304const EHPersonality EHPersonality::NeXT_ObjC("__objc_personality_v0");
305const EHPersonality EHPersonality::GNU_CPlusPlus("__gxx_personality_v0");
306const EHPersonality EHPersonality::GNU_CPlusPlus_SJLJ("__gxx_personality_sj0");
307const EHPersonality EHPersonality::GNU_ObjC("__gnu_objc_personality_v0",
308 "objc_exception_throw");
309
310static const EHPersonality &getCPersonality(const LangOptions &L) {
John McCall44680782010-11-07 02:35:25 +0000311 if (L.SjLjExceptions)
312 return EHPersonality::GNU_C_SJLJ;
John McCall8262b6a2010-07-17 00:43:08 +0000313 return EHPersonality::GNU_C;
314}
315
316static const EHPersonality &getObjCPersonality(const LangOptions &L) {
317 if (L.NeXTRuntime) {
318 if (L.ObjCNonFragileABI) return EHPersonality::NeXT_ObjC;
319 else return getCPersonality(L);
John McCallf1549f62010-07-06 01:34:17 +0000320 } else {
John McCall8262b6a2010-07-17 00:43:08 +0000321 return EHPersonality::GNU_ObjC;
John McCallf1549f62010-07-06 01:34:17 +0000322 }
323}
324
John McCall8262b6a2010-07-17 00:43:08 +0000325static const EHPersonality &getCXXPersonality(const LangOptions &L) {
326 if (L.SjLjExceptions)
327 return EHPersonality::GNU_CPlusPlus_SJLJ;
John McCallf1549f62010-07-06 01:34:17 +0000328 else
John McCall8262b6a2010-07-17 00:43:08 +0000329 return EHPersonality::GNU_CPlusPlus;
John McCallf1549f62010-07-06 01:34:17 +0000330}
331
332/// Determines the personality function to use when both C++
333/// and Objective-C exceptions are being caught.
John McCall8262b6a2010-07-17 00:43:08 +0000334static const EHPersonality &getObjCXXPersonality(const LangOptions &L) {
John McCallf1549f62010-07-06 01:34:17 +0000335 // The ObjC personality defers to the C++ personality for non-ObjC
336 // handlers. Unlike the C++ case, we use the same personality
337 // function on targets using (backend-driven) SJLJ EH.
John McCall8262b6a2010-07-17 00:43:08 +0000338 if (L.NeXTRuntime) {
339 if (L.ObjCNonFragileABI)
340 return EHPersonality::NeXT_ObjC;
John McCallf1549f62010-07-06 01:34:17 +0000341
342 // In the fragile ABI, just use C++ exception handling and hope
343 // they're not doing crazy exception mixing.
344 else
John McCall8262b6a2010-07-17 00:43:08 +0000345 return getCXXPersonality(L);
Chandler Carruthdcf22ad2010-05-17 20:58:49 +0000346 }
David Chisnall79a9ad82010-05-17 13:49:20 +0000347
John McCall8262b6a2010-07-17 00:43:08 +0000348 // The GNU runtime's personality function inherently doesn't support
349 // mixed EH. Use the C++ personality just to avoid returning null.
350 return getCXXPersonality(L);
John McCallf1549f62010-07-06 01:34:17 +0000351}
352
John McCall8262b6a2010-07-17 00:43:08 +0000353const EHPersonality &EHPersonality::get(const LangOptions &L) {
354 if (L.CPlusPlus && L.ObjC1)
355 return getObjCXXPersonality(L);
356 else if (L.CPlusPlus)
357 return getCXXPersonality(L);
358 else if (L.ObjC1)
359 return getObjCPersonality(L);
John McCallf1549f62010-07-06 01:34:17 +0000360 else
John McCall8262b6a2010-07-17 00:43:08 +0000361 return getCPersonality(L);
362}
John McCallf1549f62010-07-06 01:34:17 +0000363
John McCallb2593832010-09-16 06:16:50 +0000364static llvm::Constant *getPersonalityFn(CodeGenModule &CGM,
John McCall8262b6a2010-07-17 00:43:08 +0000365 const EHPersonality &Personality) {
John McCall8262b6a2010-07-17 00:43:08 +0000366 llvm::Constant *Fn =
John McCallb2593832010-09-16 06:16:50 +0000367 CGM.CreateRuntimeFunction(llvm::FunctionType::get(
368 llvm::Type::getInt32Ty(CGM.getLLVMContext()),
369 true),
370 Personality.getPersonalityFnName());
371 return Fn;
372}
373
374static llvm::Constant *getOpaquePersonalityFn(CodeGenModule &CGM,
375 const EHPersonality &Personality) {
376 llvm::Constant *Fn = getPersonalityFn(CGM, Personality);
377 return llvm::ConstantExpr::getBitCast(Fn, CGM.PtrToInt8Ty);
378}
379
380/// Check whether a personality function could reasonably be swapped
381/// for a C++ personality function.
382static bool PersonalityHasOnlyCXXUses(llvm::Constant *Fn) {
383 for (llvm::Constant::use_iterator
384 I = Fn->use_begin(), E = Fn->use_end(); I != E; ++I) {
385 llvm::User *User = *I;
386
387 // Conditionally white-list bitcasts.
388 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(User)) {
389 if (CE->getOpcode() != llvm::Instruction::BitCast) return false;
390 if (!PersonalityHasOnlyCXXUses(CE))
391 return false;
392 continue;
393 }
394
395 // Otherwise, it has to be a selector call.
396 if (!isa<llvm::EHSelectorInst>(User)) return false;
397
398 llvm::EHSelectorInst *Selector = cast<llvm::EHSelectorInst>(User);
399 for (unsigned I = 2, E = Selector->getNumArgOperands(); I != E; ++I) {
400 // Look for something that would've been returned by the ObjC
401 // runtime's GetEHType() method.
402 llvm::GlobalVariable *GV
403 = dyn_cast<llvm::GlobalVariable>(Selector->getArgOperand(I));
404 if (!GV) continue;
405
406 // ObjC EH selector entries are always global variables with
407 // names starting like this.
408 if (GV->getName().startswith("OBJC_EHTYPE"))
409 return false;
410 }
411 }
412
413 return true;
414}
415
416/// Try to use the C++ personality function in ObjC++. Not doing this
417/// can cause some incompatibilities with gcc, which is more
418/// aggressive about only using the ObjC++ personality in a function
419/// when it really needs it.
420void CodeGenModule::SimplifyPersonality() {
421 // For now, this is really a Darwin-specific operation.
422 if (Context.Target.getTriple().getOS() != llvm::Triple::Darwin)
423 return;
424
425 // If we're not in ObjC++ -fexceptions, there's nothing to do.
426 if (!Features.CPlusPlus || !Features.ObjC1 || !Features.Exceptions)
427 return;
428
429 const EHPersonality &ObjCXX = EHPersonality::get(Features);
430 const EHPersonality &CXX = getCXXPersonality(Features);
431 if (&ObjCXX == &CXX ||
432 ObjCXX.getPersonalityFnName() == CXX.getPersonalityFnName())
433 return;
434
435 llvm::Function *Fn =
436 getModule().getFunction(ObjCXX.getPersonalityFnName());
437
438 // Nothing to do if it's unused.
439 if (!Fn || Fn->use_empty()) return;
440
441 // Can't do the optimization if it has non-C++ uses.
442 if (!PersonalityHasOnlyCXXUses(Fn)) return;
443
444 // Create the C++ personality function and kill off the old
445 // function.
446 llvm::Constant *CXXFn = getPersonalityFn(*this, CXX);
447
448 // This can happen if the user is screwing with us.
449 if (Fn->getType() != CXXFn->getType()) return;
450
451 Fn->replaceAllUsesWith(CXXFn);
452 Fn->eraseFromParent();
John McCallf1549f62010-07-06 01:34:17 +0000453}
454
455/// Returns the value to inject into a selector to indicate the
456/// presence of a catch-all.
457static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
458 // Possibly we should use @llvm.eh.catch.all.value here.
459 return llvm::ConstantPointerNull::get(CGF.CGM.PtrToInt8Ty);
460}
461
462/// Returns the value to inject into a selector to indicate the
463/// presence of a cleanup.
464static llvm::Constant *getCleanupValue(CodeGenFunction &CGF) {
465 return llvm::ConstantInt::get(CGF.Builder.getInt32Ty(), 0);
Mike Stump99533832009-12-02 07:41:41 +0000466}
467
John McCall09faeab2010-07-13 21:17:51 +0000468namespace {
469 /// A cleanup to free the exception object if its initialization
470 /// throws.
John McCall1f0fca52010-07-21 07:22:38 +0000471 struct FreeExceptionCleanup : EHScopeStack::Cleanup {
John McCall09faeab2010-07-13 21:17:51 +0000472 FreeExceptionCleanup(llvm::Value *ShouldFreeVar,
473 llvm::Value *ExnLocVar)
474 : ShouldFreeVar(ShouldFreeVar), ExnLocVar(ExnLocVar) {}
475
476 llvm::Value *ShouldFreeVar;
477 llvm::Value *ExnLocVar;
478
479 void Emit(CodeGenFunction &CGF, bool IsForEH) {
480 llvm::BasicBlock *FreeBB = CGF.createBasicBlock("free-exnobj");
481 llvm::BasicBlock *DoneBB = CGF.createBasicBlock("free-exnobj.done");
482
483 llvm::Value *ShouldFree = CGF.Builder.CreateLoad(ShouldFreeVar,
484 "should-free-exnobj");
485 CGF.Builder.CreateCondBr(ShouldFree, FreeBB, DoneBB);
486 CGF.EmitBlock(FreeBB);
487 llvm::Value *ExnLocLocal = CGF.Builder.CreateLoad(ExnLocVar, "exnobj");
488 CGF.Builder.CreateCall(getFreeExceptionFn(CGF), ExnLocLocal)
489 ->setDoesNotThrow();
490 CGF.EmitBlock(DoneBB);
491 }
492 };
493}
494
John McCallac418162010-04-22 01:10:34 +0000495// Emits an exception expression into the given location. This
496// differs from EmitAnyExprToMem only in that, if a final copy-ctor
497// call is required, an exception within that copy ctor causes
498// std::terminate to be invoked.
499static void EmitAnyExprToExn(CodeGenFunction &CGF, const Expr *E,
500 llvm::Value *ExnLoc) {
501 // We want to release the allocated exception object if this
502 // expression throws. We do this by pushing an EH-only cleanup
503 // block which, furthermore, deactivates itself after the expression
504 // is complete.
505 llvm::AllocaInst *ShouldFreeVar =
506 CGF.CreateTempAlloca(llvm::Type::getInt1Ty(CGF.getLLVMContext()),
507 "should-free-exnobj.var");
508 CGF.InitTempAlloca(ShouldFreeVar,
509 llvm::ConstantInt::getFalse(CGF.getLLVMContext()));
Mike Stump0f590be2009-12-01 03:41:18 +0000510
John McCallac418162010-04-22 01:10:34 +0000511 // A variable holding the exception pointer. This is necessary
512 // because the throw expression does not necessarily dominate the
513 // cleanup, for example if it appears in a conditional expression.
514 llvm::AllocaInst *ExnLocVar =
515 CGF.CreateTempAlloca(ExnLoc->getType(), "exnobj.var");
Mike Stump8755ec32009-12-10 00:06:18 +0000516
John McCallf1549f62010-07-06 01:34:17 +0000517 // Make sure the exception object is cleaned up if there's an
518 // exception during initialization.
John McCall09faeab2010-07-13 21:17:51 +0000519 // FIXME: stmt expressions might require this to be a normal
520 // cleanup, too.
John McCall1f0fca52010-07-21 07:22:38 +0000521 CGF.EHStack.pushCleanup<FreeExceptionCleanup>(EHCleanup,
522 ShouldFreeVar,
523 ExnLocVar);
John McCallf1549f62010-07-06 01:34:17 +0000524 EHScopeStack::stable_iterator Cleanup = CGF.EHStack.stable_begin();
John McCallac418162010-04-22 01:10:34 +0000525
526 CGF.Builder.CreateStore(ExnLoc, ExnLocVar);
527 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(CGF.getLLVMContext()),
528 ShouldFreeVar);
529
530 // __cxa_allocate_exception returns a void*; we need to cast this
531 // to the appropriate type for the object.
John McCall14e1bc92010-10-29 08:14:02 +0000532 const llvm::Type *Ty = CGF.ConvertTypeForMem(E->getType())->getPointerTo();
John McCallac418162010-04-22 01:10:34 +0000533 llvm::Value *TypedExnLoc = CGF.Builder.CreateBitCast(ExnLoc, Ty);
534
535 // FIXME: this isn't quite right! If there's a final unelided call
536 // to a copy constructor, then according to [except.terminate]p1 we
537 // must call std::terminate() if that constructor throws, because
538 // technically that copy occurs after the exception expression is
539 // evaluated but before the exception is caught. But the best way
540 // to handle that is to teach EmitAggExpr to do the final copy
541 // differently if it can't be elided.
John McCall558d2ab2010-09-15 10:14:12 +0000542 CGF.EmitAnyExprToMem(E, TypedExnLoc, /*Volatile*/ false, /*IsInit*/ true);
John McCallac418162010-04-22 01:10:34 +0000543
544 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(CGF.getLLVMContext()),
545 ShouldFreeVar);
546
John McCallf1549f62010-07-06 01:34:17 +0000547 // Technically, the exception object is like a temporary; it has to
548 // be cleaned up when its full-expression is complete.
549 // Unfortunately, the AST represents full-expressions by creating a
John McCall4765fa02010-12-06 08:20:24 +0000550 // ExprWithCleanups, which it only does when there are actually
John McCallf1549f62010-07-06 01:34:17 +0000551 // temporaries.
552 //
553 // If any cleanups have been added since we pushed ours, they must
554 // be from temporaries; this will get popped at the same time.
555 // Otherwise we need to pop ours off. FIXME: this is very brittle.
556 if (Cleanup == CGF.EHStack.stable_begin())
557 CGF.PopCleanupBlock();
Mike Stump0f590be2009-12-01 03:41:18 +0000558}
559
John McCallf1549f62010-07-06 01:34:17 +0000560llvm::Value *CodeGenFunction::getExceptionSlot() {
561 if (!ExceptionSlot) {
562 const llvm::Type *i8p = llvm::Type::getInt8PtrTy(getLLVMContext());
563 ExceptionSlot = CreateTempAlloca(i8p, "exn.slot");
Mike Stump0f590be2009-12-01 03:41:18 +0000564 }
John McCallf1549f62010-07-06 01:34:17 +0000565 return ExceptionSlot;
Mike Stump0f590be2009-12-01 03:41:18 +0000566}
567
Anders Carlsson756b5c42009-10-30 01:42:31 +0000568void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E) {
Anders Carlssond3379292009-10-30 02:27:02 +0000569 if (!E->getSubExpr()) {
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000570 if (getInvokeDest()) {
John McCallf1549f62010-07-06 01:34:17 +0000571 Builder.CreateInvoke(getReThrowFn(*this),
572 getUnreachableBlock(),
573 getInvokeDest())
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000574 ->setDoesNotReturn();
John McCallf1549f62010-07-06 01:34:17 +0000575 } else {
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000576 Builder.CreateCall(getReThrowFn(*this))->setDoesNotReturn();
John McCallf1549f62010-07-06 01:34:17 +0000577 Builder.CreateUnreachable();
578 }
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000579
580 // Clear the insertion point to indicate we are in unreachable code.
581 Builder.ClearInsertionPoint();
Anders Carlssond3379292009-10-30 02:27:02 +0000582 return;
583 }
Mike Stump8755ec32009-12-10 00:06:18 +0000584
Anders Carlssond3379292009-10-30 02:27:02 +0000585 QualType ThrowType = E->getSubExpr()->getType();
Mike Stump8755ec32009-12-10 00:06:18 +0000586
Anders Carlssond3379292009-10-30 02:27:02 +0000587 // Now allocate the exception object.
588 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
John McCall3d3ec1c2010-04-21 10:05:39 +0000589 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
Mike Stump8755ec32009-12-10 00:06:18 +0000590
Anders Carlssond3379292009-10-30 02:27:02 +0000591 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(*this);
John McCallf1549f62010-07-06 01:34:17 +0000592 llvm::CallInst *ExceptionPtr =
Mike Stump8755ec32009-12-10 00:06:18 +0000593 Builder.CreateCall(AllocExceptionFn,
Anders Carlssond3379292009-10-30 02:27:02 +0000594 llvm::ConstantInt::get(SizeTy, TypeSize),
595 "exception");
John McCallf1549f62010-07-06 01:34:17 +0000596 ExceptionPtr->setDoesNotThrow();
Anders Carlsson8370c582009-12-11 00:32:37 +0000597
John McCallac418162010-04-22 01:10:34 +0000598 EmitAnyExprToExn(*this, E->getSubExpr(), ExceptionPtr);
Mike Stump8755ec32009-12-10 00:06:18 +0000599
Anders Carlssond3379292009-10-30 02:27:02 +0000600 // Now throw the exception.
601 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(getLLVMContext());
John McCall9dffe6f2010-04-30 01:15:21 +0000602 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType, true);
John McCallac418162010-04-22 01:10:34 +0000603
604 // The address of the destructor. If the exception type has a
605 // trivial destructor (or isn't a record), we just pass null.
606 llvm::Constant *Dtor = 0;
607 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
608 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
609 if (!Record->hasTrivialDestructor()) {
Douglas Gregor1d110e02010-07-01 14:13:13 +0000610 CXXDestructorDecl *DtorD = Record->getDestructor();
John McCallac418162010-04-22 01:10:34 +0000611 Dtor = CGM.GetAddrOfCXXDestructor(DtorD, Dtor_Complete);
612 Dtor = llvm::ConstantExpr::getBitCast(Dtor, Int8PtrTy);
613 }
614 }
615 if (!Dtor) Dtor = llvm::Constant::getNullValue(Int8PtrTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000616
Mike Stump0a3816e2009-12-04 01:51:45 +0000617 if (getInvokeDest()) {
Mike Stump8755ec32009-12-10 00:06:18 +0000618 llvm::InvokeInst *ThrowCall =
John McCallf1549f62010-07-06 01:34:17 +0000619 Builder.CreateInvoke3(getThrowFn(*this),
620 getUnreachableBlock(), getInvokeDest(),
Mike Stump0a3816e2009-12-04 01:51:45 +0000621 ExceptionPtr, TypeInfo, Dtor);
622 ThrowCall->setDoesNotReturn();
Mike Stump0a3816e2009-12-04 01:51:45 +0000623 } else {
Mike Stump8755ec32009-12-10 00:06:18 +0000624 llvm::CallInst *ThrowCall =
Mike Stump0a3816e2009-12-04 01:51:45 +0000625 Builder.CreateCall3(getThrowFn(*this), ExceptionPtr, TypeInfo, Dtor);
626 ThrowCall->setDoesNotReturn();
John McCallf1549f62010-07-06 01:34:17 +0000627 Builder.CreateUnreachable();
Mike Stump0a3816e2009-12-04 01:51:45 +0000628 }
Mike Stump8755ec32009-12-10 00:06:18 +0000629
Anders Carlssond3379292009-10-30 02:27:02 +0000630 // Clear the insertion point to indicate we are in unreachable code.
631 Builder.ClearInsertionPoint();
Mike Stumpc2ab4862009-12-07 20:12:14 +0000632
633 // FIXME: For now, emit a dummy basic block because expr emitters in generally
634 // are not ready to handle emitting expressions at unreachable points.
635 EnsureInsertPoint();
Anders Carlsson756b5c42009-10-30 01:42:31 +0000636}
Mike Stump2bf701e2009-11-20 23:44:51 +0000637
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000638void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
Anders Carlssona994ee42010-02-06 23:59:05 +0000639 if (!Exceptions)
640 return;
641
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000642 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
643 if (FD == 0)
644 return;
645 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
646 if (Proto == 0)
647 return;
648
649 assert(!Proto->hasAnyExceptionSpec() && "function with parameter pack");
650
651 if (!Proto->hasExceptionSpec())
652 return;
653
John McCallf1549f62010-07-06 01:34:17 +0000654 unsigned NumExceptions = Proto->getNumExceptions();
655 EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000656
John McCallf1549f62010-07-06 01:34:17 +0000657 for (unsigned I = 0; I != NumExceptions; ++I) {
658 QualType Ty = Proto->getExceptionType(I);
659 QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
John McCall9dffe6f2010-04-30 01:15:21 +0000660 llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType, true);
John McCallf1549f62010-07-06 01:34:17 +0000661 Filter->setFilter(I, EHType);
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000662 }
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000663}
664
665void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
Anders Carlssona994ee42010-02-06 23:59:05 +0000666 if (!Exceptions)
667 return;
668
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000669 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
670 if (FD == 0)
671 return;
672 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
673 if (Proto == 0)
674 return;
675
676 if (!Proto->hasExceptionSpec())
677 return;
678
John McCallf1549f62010-07-06 01:34:17 +0000679 EHStack.popFilter();
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000680}
681
Mike Stump2bf701e2009-11-20 23:44:51 +0000682void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
John McCall59a70002010-07-07 06:56:46 +0000683 EnterCXXTryStmt(S);
John McCall9fc6a772010-02-19 09:25:03 +0000684 EmitStmt(S.getTryBlock());
John McCall59a70002010-07-07 06:56:46 +0000685 ExitCXXTryStmt(S);
John McCall9fc6a772010-02-19 09:25:03 +0000686}
687
John McCall59a70002010-07-07 06:56:46 +0000688void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallf1549f62010-07-06 01:34:17 +0000689 unsigned NumHandlers = S.getNumHandlers();
690 EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
John McCall9fc6a772010-02-19 09:25:03 +0000691
John McCallf1549f62010-07-06 01:34:17 +0000692 for (unsigned I = 0; I != NumHandlers; ++I) {
693 const CXXCatchStmt *C = S.getHandler(I);
John McCall9fc6a772010-02-19 09:25:03 +0000694
John McCallf1549f62010-07-06 01:34:17 +0000695 llvm::BasicBlock *Handler = createBasicBlock("catch");
696 if (C->getExceptionDecl()) {
697 // FIXME: Dropping the reference type on the type into makes it
698 // impossible to correctly implement catch-by-reference
699 // semantics for pointers. Unfortunately, this is what all
700 // existing compilers do, and it's not clear that the standard
701 // personality routine is capable of doing this right. See C++ DR 388:
702 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
703 QualType CaughtType = C->getCaughtType();
704 CaughtType = CaughtType.getNonReferenceType().getUnqualifiedType();
John McCall5a180392010-07-24 00:37:23 +0000705
706 llvm::Value *TypeInfo = 0;
707 if (CaughtType->isObjCObjectPointerType())
708 TypeInfo = CGM.getObjCRuntime().GetEHType(CaughtType);
709 else
710 TypeInfo = CGM.GetAddrOfRTTIDescriptor(CaughtType, true);
John McCallf1549f62010-07-06 01:34:17 +0000711 CatchScope->setHandler(I, TypeInfo, Handler);
712 } else {
713 // No exception decl indicates '...', a catch-all.
714 CatchScope->setCatchAllHandler(I, Handler);
715 }
716 }
John McCallf1549f62010-07-06 01:34:17 +0000717}
718
719/// Check whether this is a non-EH scope, i.e. a scope which doesn't
720/// affect exception handling. Currently, the only non-EH scopes are
721/// normal-only cleanup scopes.
722static bool isNonEHScope(const EHScope &S) {
John McCallda65ea82010-07-13 20:32:21 +0000723 switch (S.getKind()) {
John McCall1f0fca52010-07-21 07:22:38 +0000724 case EHScope::Cleanup:
725 return !cast<EHCleanupScope>(S).isEHCleanup();
John McCallda65ea82010-07-13 20:32:21 +0000726 case EHScope::Filter:
727 case EHScope::Catch:
728 case EHScope::Terminate:
729 return false;
730 }
731
732 // Suppress warning.
733 return false;
John McCallf1549f62010-07-06 01:34:17 +0000734}
735
736llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
737 assert(EHStack.requiresLandingPad());
738 assert(!EHStack.empty());
739
John McCallda65ea82010-07-13 20:32:21 +0000740 if (!Exceptions)
741 return 0;
742
John McCallf1549f62010-07-06 01:34:17 +0000743 // Check the innermost scope for a cached landing pad. If this is
744 // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
745 llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
746 if (LP) return LP;
747
748 // Build the landing pad for this scope.
749 LP = EmitLandingPad();
750 assert(LP);
751
752 // Cache the landing pad on the innermost scope. If this is a
753 // non-EH scope, cache the landing pad on the enclosing scope, too.
754 for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
755 ir->setCachedLandingPad(LP);
756 if (!isNonEHScope(*ir)) break;
757 }
758
759 return LP;
760}
761
762llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
763 assert(EHStack.requiresLandingPad());
764
765 // This function contains a hack to work around a design flaw in
766 // LLVM's EH IR which breaks semantics after inlining. This same
767 // hack is implemented in llvm-gcc.
768 //
769 // The LLVM EH abstraction is basically a thin veneer over the
770 // traditional GCC zero-cost design: for each range of instructions
771 // in the function, there is (at most) one "landing pad" with an
772 // associated chain of EH actions. A language-specific personality
773 // function interprets this chain of actions and (1) decides whether
774 // or not to resume execution at the landing pad and (2) if so,
775 // provides an integer indicating why it's stopping. In LLVM IR,
776 // the association of a landing pad with a range of instructions is
777 // achieved via an invoke instruction, the chain of actions becomes
778 // the arguments to the @llvm.eh.selector call, and the selector
779 // call returns the integer indicator. Other than the required
780 // presence of two intrinsic function calls in the landing pad,
781 // the IR exactly describes the layout of the output code.
782 //
783 // A principal advantage of this design is that it is completely
784 // language-agnostic; in theory, the LLVM optimizers can treat
785 // landing pads neutrally, and targets need only know how to lower
786 // the intrinsics to have a functioning exceptions system (assuming
787 // that platform exceptions follow something approximately like the
788 // GCC design). Unfortunately, landing pads cannot be combined in a
789 // language-agnostic way: given selectors A and B, there is no way
790 // to make a single landing pad which faithfully represents the
791 // semantics of propagating an exception first through A, then
792 // through B, without knowing how the personality will interpret the
793 // (lowered form of the) selectors. This means that inlining has no
794 // choice but to crudely chain invokes (i.e., to ignore invokes in
795 // the inlined function, but to turn all unwindable calls into
796 // invokes), which is only semantically valid if every unwind stops
797 // at every landing pad.
798 //
799 // Therefore, the invoke-inline hack is to guarantee that every
800 // landing pad has a catch-all.
801 const bool UseInvokeInlineHack = true;
802
803 for (EHScopeStack::iterator ir = EHStack.begin(); ; ) {
804 assert(ir != EHStack.end() &&
805 "stack requiring landing pad is nothing but non-EH scopes?");
806
807 // If this is a terminate scope, just use the singleton terminate
808 // landing pad.
809 if (isa<EHTerminateScope>(*ir))
810 return getTerminateLandingPad();
811
812 // If this isn't an EH scope, iterate; otherwise break out.
813 if (!isNonEHScope(*ir)) break;
814 ++ir;
815
816 // We haven't checked this scope for a cached landing pad yet.
817 if (llvm::BasicBlock *LP = ir->getCachedLandingPad())
818 return LP;
819 }
820
821 // Save the current IR generation state.
822 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
823
John McCall8262b6a2010-07-17 00:43:08 +0000824 const EHPersonality &Personality =
825 EHPersonality::get(CGF.CGM.getLangOptions());
826
John McCallf1549f62010-07-06 01:34:17 +0000827 // Create and configure the landing pad.
828 llvm::BasicBlock *LP = createBasicBlock("lpad");
829 EmitBlock(LP);
830
831 // Save the exception pointer. It's safe to use a single exception
832 // pointer per function because EH cleanups can never have nested
833 // try/catches.
834 llvm::CallInst *Exn =
835 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_exception), "exn");
836 Exn->setDoesNotThrow();
837 Builder.CreateStore(Exn, getExceptionSlot());
838
839 // Build the selector arguments.
840 llvm::SmallVector<llvm::Value*, 8> EHSelector;
841 EHSelector.push_back(Exn);
John McCallb2593832010-09-16 06:16:50 +0000842 EHSelector.push_back(getOpaquePersonalityFn(CGM, Personality));
John McCallf1549f62010-07-06 01:34:17 +0000843
844 // Accumulate all the handlers in scope.
John McCallff8e1152010-07-23 21:56:41 +0000845 llvm::DenseMap<llvm::Value*, UnwindDest> EHHandlers;
846 UnwindDest CatchAll;
John McCallf1549f62010-07-06 01:34:17 +0000847 bool HasEHCleanup = false;
848 bool HasEHFilter = false;
849 llvm::SmallVector<llvm::Value*, 8> EHFilters;
850 for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end();
851 I != E; ++I) {
852
853 switch (I->getKind()) {
John McCall1f0fca52010-07-21 07:22:38 +0000854 case EHScope::Cleanup:
John McCallda65ea82010-07-13 20:32:21 +0000855 if (!HasEHCleanup)
John McCall1f0fca52010-07-21 07:22:38 +0000856 HasEHCleanup = cast<EHCleanupScope>(*I).isEHCleanup();
John McCallda65ea82010-07-13 20:32:21 +0000857 // We otherwise don't care about cleanups.
858 continue;
859
John McCallf1549f62010-07-06 01:34:17 +0000860 case EHScope::Filter: {
861 assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
John McCallff8e1152010-07-23 21:56:41 +0000862 assert(!CatchAll.isValid() && "EH filter reached after catch-all");
John McCallf1549f62010-07-06 01:34:17 +0000863
864 // Filter scopes get added to the selector in wierd ways.
865 EHFilterScope &Filter = cast<EHFilterScope>(*I);
866 HasEHFilter = true;
867
868 // Add all the filter values which we aren't already explicitly
869 // catching.
870 for (unsigned I = 0, E = Filter.getNumFilters(); I != E; ++I) {
871 llvm::Value *FV = Filter.getFilter(I);
872 if (!EHHandlers.count(FV))
873 EHFilters.push_back(FV);
874 }
875 goto done;
876 }
877
878 case EHScope::Terminate:
879 // Terminate scopes are basically catch-alls.
John McCallff8e1152010-07-23 21:56:41 +0000880 assert(!CatchAll.isValid());
881 CatchAll = UnwindDest(getTerminateHandler(),
882 EHStack.getEnclosingEHCleanup(I),
883 cast<EHTerminateScope>(*I).getDestIndex());
John McCallf1549f62010-07-06 01:34:17 +0000884 goto done;
885
886 case EHScope::Catch:
887 break;
888 }
889
890 EHCatchScope &Catch = cast<EHCatchScope>(*I);
891 for (unsigned HI = 0, HE = Catch.getNumHandlers(); HI != HE; ++HI) {
892 EHCatchScope::Handler Handler = Catch.getHandler(HI);
893
894 // Catch-all. We should only have one of these per catch.
895 if (!Handler.Type) {
John McCallff8e1152010-07-23 21:56:41 +0000896 assert(!CatchAll.isValid());
897 CatchAll = UnwindDest(Handler.Block,
898 EHStack.getEnclosingEHCleanup(I),
899 Handler.Index);
John McCallf1549f62010-07-06 01:34:17 +0000900 continue;
901 }
902
903 // Check whether we already have a handler for this type.
John McCallff8e1152010-07-23 21:56:41 +0000904 UnwindDest &Dest = EHHandlers[Handler.Type];
905 if (Dest.isValid()) continue;
John McCallf1549f62010-07-06 01:34:17 +0000906
907 EHSelector.push_back(Handler.Type);
John McCallff8e1152010-07-23 21:56:41 +0000908 Dest = UnwindDest(Handler.Block,
909 EHStack.getEnclosingEHCleanup(I),
910 Handler.Index);
John McCallf1549f62010-07-06 01:34:17 +0000911 }
912
913 // Stop if we found a catch-all.
John McCallff8e1152010-07-23 21:56:41 +0000914 if (CatchAll.isValid()) break;
John McCallf1549f62010-07-06 01:34:17 +0000915 }
916
917 done:
918 unsigned LastToEmitInLoop = EHSelector.size();
919
920 // If we have a catch-all, add null to the selector.
John McCallff8e1152010-07-23 21:56:41 +0000921 if (CatchAll.isValid()) {
John McCallf1549f62010-07-06 01:34:17 +0000922 EHSelector.push_back(getCatchAllValue(CGF));
923
924 // If we have an EH filter, we need to add those handlers in the
925 // right place in the selector, which is to say, at the end.
926 } else if (HasEHFilter) {
927 // Create a filter expression: an integer constant saying how many
928 // filters there are (+1 to avoid ambiguity with 0 for cleanup),
929 // followed by the filter types. The personality routine only
930 // lands here if the filter doesn't match.
931 EHSelector.push_back(llvm::ConstantInt::get(Builder.getInt32Ty(),
932 EHFilters.size() + 1));
933 EHSelector.append(EHFilters.begin(), EHFilters.end());
934
935 // Also check whether we need a cleanup.
936 if (UseInvokeInlineHack || HasEHCleanup)
937 EHSelector.push_back(UseInvokeInlineHack
938 ? getCatchAllValue(CGF)
939 : getCleanupValue(CGF));
940
941 // Otherwise, signal that we at least have cleanups.
942 } else if (UseInvokeInlineHack || HasEHCleanup) {
943 EHSelector.push_back(UseInvokeInlineHack
944 ? getCatchAllValue(CGF)
945 : getCleanupValue(CGF));
946 } else {
947 assert(LastToEmitInLoop > 2);
948 LastToEmitInLoop--;
949 }
950
951 assert(EHSelector.size() >= 3 && "selector call has only two arguments!");
952
953 // Tell the backend how to generate the landing pad.
954 llvm::CallInst *Selection =
955 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_selector),
956 EHSelector.begin(), EHSelector.end(), "eh.selector");
957 Selection->setDoesNotThrow();
958
959 // Select the right handler.
960 llvm::Value *llvm_eh_typeid_for =
961 CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
962
963 // The results of llvm_eh_typeid_for aren't reliable --- at least
964 // not locally --- so we basically have to do this as an 'if' chain.
965 // We walk through the first N-1 catch clauses, testing and chaining,
966 // and then fall into the final clause (which is either a cleanup, a
967 // filter (possibly with a cleanup), a catch-all, or another catch).
968 for (unsigned I = 2; I != LastToEmitInLoop; ++I) {
969 llvm::Value *Type = EHSelector[I];
John McCallff8e1152010-07-23 21:56:41 +0000970 UnwindDest Dest = EHHandlers[Type];
971 assert(Dest.isValid() && "no handler entry for value in selector?");
John McCallf1549f62010-07-06 01:34:17 +0000972
973 // Figure out where to branch on a match. As a debug code-size
974 // optimization, if the scope depth matches the innermost cleanup,
975 // we branch directly to the catch handler.
John McCallff8e1152010-07-23 21:56:41 +0000976 llvm::BasicBlock *Match = Dest.getBlock();
977 bool MatchNeedsCleanup =
978 Dest.getScopeDepth() != EHStack.getInnermostEHCleanup();
John McCallf1549f62010-07-06 01:34:17 +0000979 if (MatchNeedsCleanup)
980 Match = createBasicBlock("eh.match");
981
982 llvm::BasicBlock *Next = createBasicBlock("eh.next");
983
984 // Check whether the exception matches.
985 llvm::CallInst *Id
986 = Builder.CreateCall(llvm_eh_typeid_for,
987 Builder.CreateBitCast(Type, CGM.PtrToInt8Ty));
988 Id->setDoesNotThrow();
989 Builder.CreateCondBr(Builder.CreateICmpEQ(Selection, Id),
990 Match, Next);
991
992 // Emit match code if necessary.
993 if (MatchNeedsCleanup) {
994 EmitBlock(Match);
995 EmitBranchThroughEHCleanup(Dest);
996 }
997
998 // Continue to the next match.
999 EmitBlock(Next);
1000 }
1001
1002 // Emit the final case in the selector.
1003 // This might be a catch-all....
John McCallff8e1152010-07-23 21:56:41 +00001004 if (CatchAll.isValid()) {
John McCallf1549f62010-07-06 01:34:17 +00001005 assert(isa<llvm::ConstantPointerNull>(EHSelector.back()));
1006 EmitBranchThroughEHCleanup(CatchAll);
1007
1008 // ...or an EH filter...
1009 } else if (HasEHFilter) {
1010 llvm::Value *SavedSelection = Selection;
1011
1012 // First, unwind out to the outermost scope if necessary.
1013 if (EHStack.hasEHCleanups()) {
1014 // The end here might not dominate the beginning, so we might need to
1015 // save the selector if we need it.
1016 llvm::AllocaInst *SelectorVar = 0;
1017 if (HasEHCleanup) {
1018 SelectorVar = CreateTempAlloca(Builder.getInt32Ty(), "selector.var");
1019 Builder.CreateStore(Selection, SelectorVar);
1020 }
1021
1022 llvm::BasicBlock *CleanupContBB = createBasicBlock("ehspec.cleanup.cont");
John McCallff8e1152010-07-23 21:56:41 +00001023 EmitBranchThroughEHCleanup(UnwindDest(CleanupContBB, EHStack.stable_end(),
1024 EHStack.getNextEHDestIndex()));
John McCallf1549f62010-07-06 01:34:17 +00001025 EmitBlock(CleanupContBB);
1026
1027 if (HasEHCleanup)
1028 SavedSelection = Builder.CreateLoad(SelectorVar, "ehspec.saved-selector");
1029 }
1030
1031 // If there was a cleanup, we'll need to actually check whether we
1032 // landed here because the filter triggered.
1033 if (UseInvokeInlineHack || HasEHCleanup) {
1034 llvm::BasicBlock *RethrowBB = createBasicBlock("cleanup");
1035 llvm::BasicBlock *UnexpectedBB = createBasicBlock("ehspec.unexpected");
1036
1037 llvm::Constant *Zero = llvm::ConstantInt::get(Builder.getInt32Ty(), 0);
1038 llvm::Value *FailsFilter =
1039 Builder.CreateICmpSLT(SavedSelection, Zero, "ehspec.fails");
1040 Builder.CreateCondBr(FailsFilter, UnexpectedBB, RethrowBB);
1041
1042 // The rethrow block is where we land if this was a cleanup.
1043 // TODO: can this be _Unwind_Resume if the InvokeInlineHack is off?
1044 EmitBlock(RethrowBB);
1045 Builder.CreateCall(getUnwindResumeOrRethrowFn(),
1046 Builder.CreateLoad(getExceptionSlot()))
1047 ->setDoesNotReturn();
1048 Builder.CreateUnreachable();
1049
1050 EmitBlock(UnexpectedBB);
1051 }
1052
1053 // Call __cxa_call_unexpected. This doesn't need to be an invoke
1054 // because __cxa_call_unexpected magically filters exceptions
1055 // according to the last landing pad the exception was thrown
1056 // into. Seriously.
1057 Builder.CreateCall(getUnexpectedFn(*this),
1058 Builder.CreateLoad(getExceptionSlot()))
1059 ->setDoesNotReturn();
1060 Builder.CreateUnreachable();
1061
1062 // ...or a normal catch handler...
1063 } else if (!UseInvokeInlineHack && !HasEHCleanup) {
1064 llvm::Value *Type = EHSelector.back();
1065 EmitBranchThroughEHCleanup(EHHandlers[Type]);
1066
1067 // ...or a cleanup.
1068 } else {
John McCallff8e1152010-07-23 21:56:41 +00001069 EmitBranchThroughEHCleanup(getRethrowDest());
John McCallf1549f62010-07-06 01:34:17 +00001070 }
1071
1072 // Restore the old IR generation state.
1073 Builder.restoreIP(SavedIP);
1074
1075 return LP;
1076}
1077
John McCall8e3f8612010-07-13 22:12:14 +00001078namespace {
1079 /// A cleanup to call __cxa_end_catch. In many cases, the caught
1080 /// exception type lets us state definitively that the thrown exception
1081 /// type does not have a destructor. In particular:
1082 /// - Catch-alls tell us nothing, so we have to conservatively
1083 /// assume that the thrown exception might have a destructor.
1084 /// - Catches by reference behave according to their base types.
1085 /// - Catches of non-record types will only trigger for exceptions
1086 /// of non-record types, which never have destructors.
1087 /// - Catches of record types can trigger for arbitrary subclasses
1088 /// of the caught type, so we have to assume the actual thrown
1089 /// exception type might have a throwing destructor, even if the
1090 /// caught type's destructor is trivial or nothrow.
John McCall1f0fca52010-07-21 07:22:38 +00001091 struct CallEndCatch : EHScopeStack::Cleanup {
John McCall8e3f8612010-07-13 22:12:14 +00001092 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
1093 bool MightThrow;
1094
1095 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1096 if (!MightThrow) {
1097 CGF.Builder.CreateCall(getEndCatchFn(CGF))->setDoesNotThrow();
1098 return;
1099 }
1100
1101 CGF.EmitCallOrInvoke(getEndCatchFn(CGF), 0, 0);
1102 }
1103 };
1104}
1105
John McCallf1549f62010-07-06 01:34:17 +00001106/// Emits a call to __cxa_begin_catch and enters a cleanup to call
1107/// __cxa_end_catch.
John McCall8e3f8612010-07-13 22:12:14 +00001108///
1109/// \param EndMightThrow - true if __cxa_end_catch might throw
1110static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
1111 llvm::Value *Exn,
1112 bool EndMightThrow) {
John McCallf1549f62010-07-06 01:34:17 +00001113 llvm::CallInst *Call = CGF.Builder.CreateCall(getBeginCatchFn(CGF), Exn);
1114 Call->setDoesNotThrow();
1115
John McCall1f0fca52010-07-21 07:22:38 +00001116 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
John McCallf1549f62010-07-06 01:34:17 +00001117
1118 return Call;
1119}
1120
1121/// A "special initializer" callback for initializing a catch
1122/// parameter during catch initialization.
1123static void InitCatchParam(CodeGenFunction &CGF,
1124 const VarDecl &CatchParam,
1125 llvm::Value *ParamAddr) {
1126 // Load the exception from where the landing pad saved it.
1127 llvm::Value *Exn = CGF.Builder.CreateLoad(CGF.getExceptionSlot(), "exn");
1128
1129 CanQualType CatchType =
1130 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
1131 const llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
1132
1133 // If we're catching by reference, we can just cast the object
1134 // pointer to the appropriate pointer.
1135 if (isa<ReferenceType>(CatchType)) {
John McCall204b0752010-07-20 22:17:55 +00001136 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
1137 bool EndCatchMightThrow = CaughtType->isRecordType();
John McCall8e3f8612010-07-13 22:12:14 +00001138
John McCallf1549f62010-07-06 01:34:17 +00001139 // __cxa_begin_catch returns the adjusted object pointer.
John McCall8e3f8612010-07-13 22:12:14 +00001140 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
John McCall204b0752010-07-20 22:17:55 +00001141
1142 // We have no way to tell the personality function that we're
1143 // catching by reference, so if we're catching a pointer,
1144 // __cxa_begin_catch will actually return that pointer by value.
1145 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
1146 QualType PointeeType = PT->getPointeeType();
1147
1148 // When catching by reference, generally we should just ignore
1149 // this by-value pointer and use the exception object instead.
1150 if (!PointeeType->isRecordType()) {
1151
1152 // Exn points to the struct _Unwind_Exception header, which
1153 // we have to skip past in order to reach the exception data.
1154 unsigned HeaderSize =
1155 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
1156 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
1157
1158 // However, if we're catching a pointer-to-record type that won't
1159 // work, because the personality function might have adjusted
1160 // the pointer. There's actually no way for us to fully satisfy
1161 // the language/ABI contract here: we can't use Exn because it
1162 // might have the wrong adjustment, but we can't use the by-value
1163 // pointer because it's off by a level of abstraction.
1164 //
1165 // The current solution is to dump the adjusted pointer into an
1166 // alloca, which breaks language semantics (because changing the
1167 // pointer doesn't change the exception) but at least works.
1168 // The better solution would be to filter out non-exact matches
1169 // and rethrow them, but this is tricky because the rethrow
1170 // really needs to be catchable by other sites at this landing
1171 // pad. The best solution is to fix the personality function.
1172 } else {
1173 // Pull the pointer for the reference type off.
1174 const llvm::Type *PtrTy =
1175 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
1176
1177 // Create the temporary and write the adjusted pointer into it.
1178 llvm::Value *ExnPtrTmp = CGF.CreateTempAlloca(PtrTy, "exn.byref.tmp");
1179 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1180 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
1181
1182 // Bind the reference to the temporary.
1183 AdjustedExn = ExnPtrTmp;
1184 }
1185 }
1186
John McCallf1549f62010-07-06 01:34:17 +00001187 llvm::Value *ExnCast =
1188 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
1189 CGF.Builder.CreateStore(ExnCast, ParamAddr);
1190 return;
1191 }
1192
1193 // Non-aggregates (plus complexes).
1194 bool IsComplex = false;
1195 if (!CGF.hasAggregateLLVMType(CatchType) ||
1196 (IsComplex = CatchType->isAnyComplexType())) {
John McCall8e3f8612010-07-13 22:12:14 +00001197 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
John McCallf1549f62010-07-06 01:34:17 +00001198
1199 // If the catch type is a pointer type, __cxa_begin_catch returns
1200 // the pointer by value.
1201 if (CatchType->hasPointerRepresentation()) {
1202 llvm::Value *CastExn =
1203 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
1204 CGF.Builder.CreateStore(CastExn, ParamAddr);
1205 return;
1206 }
1207
1208 // Otherwise, it returns a pointer into the exception object.
1209
1210 const llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
1211 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1212
1213 if (IsComplex) {
1214 CGF.StoreComplexToAddr(CGF.LoadComplexFromAddr(Cast, /*volatile*/ false),
1215 ParamAddr, /*volatile*/ false);
1216 } else {
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001217 unsigned Alignment =
1218 CGF.getContext().getDeclAlign(&CatchParam).getQuantity();
John McCallf1549f62010-07-06 01:34:17 +00001219 llvm::Value *ExnLoad = CGF.Builder.CreateLoad(Cast, "exn.scalar");
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001220 CGF.EmitStoreOfScalar(ExnLoad, ParamAddr, /*volatile*/ false, Alignment,
1221 CatchType);
John McCallf1549f62010-07-06 01:34:17 +00001222 }
1223 return;
1224 }
1225
1226 // FIXME: this *really* needs to be done via a proper, Sema-emitted
1227 // initializer expression.
1228
1229 CXXRecordDecl *RD = CatchType.getTypePtr()->getAsCXXRecordDecl();
1230 assert(RD && "aggregate catch type was not a record!");
1231
1232 const llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
1233
1234 if (RD->hasTrivialCopyConstructor()) {
John McCall8e3f8612010-07-13 22:12:14 +00001235 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, true);
John McCallf1549f62010-07-06 01:34:17 +00001236 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1237 CGF.EmitAggregateCopy(ParamAddr, Cast, CatchType);
1238 return;
1239 }
1240
1241 // We have to call __cxa_get_exception_ptr to get the adjusted
1242 // pointer before copying.
1243 llvm::CallInst *AdjustedExn =
1244 CGF.Builder.CreateCall(getGetExceptionPtrFn(CGF), Exn);
1245 AdjustedExn->setDoesNotThrow();
1246 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1247
1248 CXXConstructorDecl *CD = RD->getCopyConstructor(CGF.getContext(), 0);
1249 assert(CD && "record has no copy constructor!");
1250 llvm::Value *CopyCtor = CGF.CGM.GetAddrOfCXXConstructor(CD, Ctor_Complete);
1251
1252 CallArgList CallArgs;
1253 CallArgs.push_back(std::make_pair(RValue::get(ParamAddr),
1254 CD->getThisType(CGF.getContext())));
1255 CallArgs.push_back(std::make_pair(RValue::get(Cast),
1256 CD->getParamDecl(0)->getType()));
1257
1258 const FunctionProtoType *FPT
1259 = CD->getType()->getAs<FunctionProtoType>();
1260
1261 // Call the copy ctor in a terminate scope.
1262 CGF.EHStack.pushTerminate();
1263 CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(CallArgs, FPT),
1264 CopyCtor, ReturnValueSlot(), CallArgs, CD);
1265 CGF.EHStack.popTerminate();
1266
1267 // Finally we can call __cxa_begin_catch.
John McCall8e3f8612010-07-13 22:12:14 +00001268 CallBeginCatch(CGF, Exn, true);
John McCallf1549f62010-07-06 01:34:17 +00001269}
1270
1271/// Begins a catch statement by initializing the catch variable and
1272/// calling __cxa_begin_catch.
1273static void BeginCatch(CodeGenFunction &CGF,
1274 const CXXCatchStmt *S) {
1275 // We have to be very careful with the ordering of cleanups here:
1276 // C++ [except.throw]p4:
1277 // The destruction [of the exception temporary] occurs
1278 // immediately after the destruction of the object declared in
1279 // the exception-declaration in the handler.
1280 //
1281 // So the precise ordering is:
1282 // 1. Construct catch variable.
1283 // 2. __cxa_begin_catch
1284 // 3. Enter __cxa_end_catch cleanup
1285 // 4. Enter dtor cleanup
1286 //
1287 // We do this by initializing the exception variable with a
1288 // "special initializer", InitCatchParam. Delegation sequence:
1289 // - ExitCXXTryStmt opens a RunCleanupsScope
1290 // - EmitLocalBlockVarDecl creates the variable and debug info
1291 // - InitCatchParam initializes the variable from the exception
1292 // - CallBeginCatch calls __cxa_begin_catch
1293 // - CallBeginCatch enters the __cxa_end_catch cleanup
1294 // - EmitLocalBlockVarDecl enters the variable destructor cleanup
1295 // - EmitCXXTryStmt emits the code for the catch body
1296 // - EmitCXXTryStmt close the RunCleanupsScope
1297
1298 VarDecl *CatchParam = S->getExceptionDecl();
1299 if (!CatchParam) {
1300 llvm::Value *Exn = CGF.Builder.CreateLoad(CGF.getExceptionSlot(), "exn");
John McCall8e3f8612010-07-13 22:12:14 +00001301 CallBeginCatch(CGF, Exn, true);
John McCallf1549f62010-07-06 01:34:17 +00001302 return;
1303 }
1304
1305 // Emit the local.
John McCallb6bbcc92010-10-15 04:57:14 +00001306 CGF.EmitAutoVarDecl(*CatchParam, &InitCatchParam);
John McCall9fc6a772010-02-19 09:25:03 +00001307}
1308
John McCallfcd5c0c2010-07-13 22:24:23 +00001309namespace {
John McCall1f0fca52010-07-21 07:22:38 +00001310 struct CallRethrow : EHScopeStack::Cleanup {
John McCallfcd5c0c2010-07-13 22:24:23 +00001311 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1312 CGF.EmitCallOrInvoke(getReThrowFn(CGF), 0, 0);
1313 }
1314 };
1315}
1316
John McCall59a70002010-07-07 06:56:46 +00001317void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallf1549f62010-07-06 01:34:17 +00001318 unsigned NumHandlers = S.getNumHandlers();
1319 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1320 assert(CatchScope.getNumHandlers() == NumHandlers);
Mike Stump2bf701e2009-11-20 23:44:51 +00001321
John McCallf1549f62010-07-06 01:34:17 +00001322 // Copy the handler blocks off before we pop the EH stack. Emitting
1323 // the handlers might scribble on this memory.
1324 llvm::SmallVector<EHCatchScope::Handler, 8> Handlers(NumHandlers);
1325 memcpy(Handlers.data(), CatchScope.begin(),
1326 NumHandlers * sizeof(EHCatchScope::Handler));
1327 EHStack.popCatch();
Mike Stump2bf701e2009-11-20 23:44:51 +00001328
John McCallf1549f62010-07-06 01:34:17 +00001329 // The fall-through block.
1330 llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
Mike Stump2bf701e2009-11-20 23:44:51 +00001331
John McCallf1549f62010-07-06 01:34:17 +00001332 // We just emitted the body of the try; jump to the continue block.
1333 if (HaveInsertPoint())
1334 Builder.CreateBr(ContBB);
Mike Stump639787c2009-12-02 19:53:57 +00001335
John McCall59a70002010-07-07 06:56:46 +00001336 // Determine if we need an implicit rethrow for all these catch handlers.
1337 bool ImplicitRethrow = false;
1338 if (IsFnTryBlock)
1339 ImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
1340 isa<CXXConstructorDecl>(CurCodeDecl);
1341
John McCallf1549f62010-07-06 01:34:17 +00001342 for (unsigned I = 0; I != NumHandlers; ++I) {
1343 llvm::BasicBlock *CatchBlock = Handlers[I].Block;
1344 EmitBlock(CatchBlock);
Mike Stump8755ec32009-12-10 00:06:18 +00001345
John McCallf1549f62010-07-06 01:34:17 +00001346 // Catch the exception if this isn't a catch-all.
1347 const CXXCatchStmt *C = S.getHandler(I);
Mike Stump2bf701e2009-11-20 23:44:51 +00001348
John McCallf1549f62010-07-06 01:34:17 +00001349 // Enter a cleanup scope, including the catch variable and the
1350 // end-catch.
1351 RunCleanupsScope CatchScope(*this);
Mike Stump2bf701e2009-11-20 23:44:51 +00001352
John McCallf1549f62010-07-06 01:34:17 +00001353 // Initialize the catch variable and set up the cleanups.
1354 BeginCatch(*this, C);
1355
John McCall59a70002010-07-07 06:56:46 +00001356 // If there's an implicit rethrow, push a normal "cleanup" to call
John McCallfcd5c0c2010-07-13 22:24:23 +00001357 // _cxa_rethrow. This needs to happen before __cxa_end_catch is
1358 // called, and so it is pushed after BeginCatch.
1359 if (ImplicitRethrow)
John McCall1f0fca52010-07-21 07:22:38 +00001360 EHStack.pushCleanup<CallRethrow>(NormalCleanup);
John McCall59a70002010-07-07 06:56:46 +00001361
John McCallf1549f62010-07-06 01:34:17 +00001362 // Perform the body of the catch.
1363 EmitStmt(C->getHandlerBlock());
1364
1365 // Fall out through the catch cleanups.
1366 CatchScope.ForceCleanup();
1367
1368 // Branch out of the try.
1369 if (HaveInsertPoint())
1370 Builder.CreateBr(ContBB);
Mike Stump2bf701e2009-11-20 23:44:51 +00001371 }
1372
John McCallf1549f62010-07-06 01:34:17 +00001373 EmitBlock(ContBB);
Mike Stump2bf701e2009-11-20 23:44:51 +00001374}
Mike Stumpd88ea562009-12-09 03:35:49 +00001375
John McCall55b20fc2010-07-21 00:52:03 +00001376namespace {
John McCall1f0fca52010-07-21 07:22:38 +00001377 struct CallEndCatchForFinally : EHScopeStack::Cleanup {
John McCall55b20fc2010-07-21 00:52:03 +00001378 llvm::Value *ForEHVar;
1379 llvm::Value *EndCatchFn;
1380 CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn)
1381 : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
1382
1383 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1384 llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
1385 llvm::BasicBlock *CleanupContBB =
1386 CGF.createBasicBlock("finally.cleanup.cont");
1387
1388 llvm::Value *ShouldEndCatch =
1389 CGF.Builder.CreateLoad(ForEHVar, "finally.endcatch");
1390 CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1391 CGF.EmitBlock(EndCatchBB);
1392 CGF.EmitCallOrInvoke(EndCatchFn, 0, 0); // catch-all, so might throw
1393 CGF.EmitBlock(CleanupContBB);
1394 }
1395 };
John McCall77199712010-07-21 05:47:49 +00001396
John McCall1f0fca52010-07-21 07:22:38 +00001397 struct PerformFinally : EHScopeStack::Cleanup {
John McCall77199712010-07-21 05:47:49 +00001398 const Stmt *Body;
1399 llvm::Value *ForEHVar;
1400 llvm::Value *EndCatchFn;
1401 llvm::Value *RethrowFn;
1402 llvm::Value *SavedExnVar;
1403
1404 PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
1405 llvm::Value *EndCatchFn,
1406 llvm::Value *RethrowFn, llvm::Value *SavedExnVar)
1407 : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1408 RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
1409
1410 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1411 // Enter a cleanup to call the end-catch function if one was provided.
1412 if (EndCatchFn)
John McCall1f0fca52010-07-21 07:22:38 +00001413 CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
1414 ForEHVar, EndCatchFn);
John McCall77199712010-07-21 05:47:49 +00001415
John McCalld96a8e72010-08-11 00:16:14 +00001416 // Save the current cleanup destination in case there are
1417 // cleanups in the finally block.
1418 llvm::Value *SavedCleanupDest =
1419 CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
1420 "cleanup.dest.saved");
1421
John McCall77199712010-07-21 05:47:49 +00001422 // Emit the finally block.
1423 CGF.EmitStmt(Body);
1424
1425 // If the end of the finally is reachable, check whether this was
1426 // for EH. If so, rethrow.
1427 if (CGF.HaveInsertPoint()) {
1428 llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
1429 llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
1430
1431 llvm::Value *ShouldRethrow =
1432 CGF.Builder.CreateLoad(ForEHVar, "finally.shouldthrow");
1433 CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1434
1435 CGF.EmitBlock(RethrowBB);
1436 if (SavedExnVar) {
1437 llvm::Value *Args[] = { CGF.Builder.CreateLoad(SavedExnVar) };
1438 CGF.EmitCallOrInvoke(RethrowFn, Args, Args+1);
1439 } else {
1440 CGF.EmitCallOrInvoke(RethrowFn, 0, 0);
1441 }
1442 CGF.Builder.CreateUnreachable();
1443
1444 CGF.EmitBlock(ContBB);
John McCalld96a8e72010-08-11 00:16:14 +00001445
1446 // Restore the cleanup destination.
1447 CGF.Builder.CreateStore(SavedCleanupDest,
1448 CGF.getNormalCleanupDestSlot());
John McCall77199712010-07-21 05:47:49 +00001449 }
1450
1451 // Leave the end-catch cleanup. As an optimization, pretend that
1452 // the fallthrough path was inaccessible; we've dynamically proven
1453 // that we're not in the EH case along that path.
1454 if (EndCatchFn) {
1455 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1456 CGF.PopCleanupBlock();
1457 CGF.Builder.restoreIP(SavedIP);
1458 }
1459
1460 // Now make sure we actually have an insertion point or the
1461 // cleanup gods will hate us.
1462 CGF.EnsureInsertPoint();
1463 }
1464 };
John McCall55b20fc2010-07-21 00:52:03 +00001465}
1466
John McCallf1549f62010-07-06 01:34:17 +00001467/// Enters a finally block for an implementation using zero-cost
1468/// exceptions. This is mostly general, but hard-codes some
1469/// language/ABI-specific behavior in the catch-all sections.
1470CodeGenFunction::FinallyInfo
1471CodeGenFunction::EnterFinallyBlock(const Stmt *Body,
1472 llvm::Constant *BeginCatchFn,
1473 llvm::Constant *EndCatchFn,
1474 llvm::Constant *RethrowFn) {
1475 assert((BeginCatchFn != 0) == (EndCatchFn != 0) &&
1476 "begin/end catch functions not paired");
1477 assert(RethrowFn && "rethrow function is required");
Mike Stumpd88ea562009-12-09 03:35:49 +00001478
John McCallf1549f62010-07-06 01:34:17 +00001479 // The rethrow function has one of the following two types:
1480 // void (*)()
1481 // void (*)(void*)
1482 // In the latter case we need to pass it the exception object.
1483 // But we can't use the exception slot because the @finally might
1484 // have a landing pad (which would overwrite the exception slot).
1485 const llvm::FunctionType *RethrowFnTy =
1486 cast<llvm::FunctionType>(
1487 cast<llvm::PointerType>(RethrowFn->getType())
1488 ->getElementType());
1489 llvm::Value *SavedExnVar = 0;
1490 if (RethrowFnTy->getNumParams())
1491 SavedExnVar = CreateTempAlloca(Builder.getInt8PtrTy(), "finally.exn");
Mike Stumpd88ea562009-12-09 03:35:49 +00001492
John McCallf1549f62010-07-06 01:34:17 +00001493 // A finally block is a statement which must be executed on any edge
1494 // out of a given scope. Unlike a cleanup, the finally block may
1495 // contain arbitrary control flow leading out of itself. In
1496 // addition, finally blocks should always be executed, even if there
1497 // are no catch handlers higher on the stack. Therefore, we
1498 // surround the protected scope with a combination of a normal
1499 // cleanup (to catch attempts to break out of the block via normal
1500 // control flow) and an EH catch-all (semantically "outside" any try
1501 // statement to which the finally block might have been attached).
1502 // The finally block itself is generated in the context of a cleanup
1503 // which conditionally leaves the catch-all.
John McCall3d3ec1c2010-04-21 10:05:39 +00001504
John McCallf1549f62010-07-06 01:34:17 +00001505 FinallyInfo Info;
John McCall3d3ec1c2010-04-21 10:05:39 +00001506
John McCallf1549f62010-07-06 01:34:17 +00001507 // Jump destination for performing the finally block on an exception
1508 // edge. We'll never actually reach this block, so unreachable is
1509 // fine.
1510 JumpDest RethrowDest = getJumpDestInCurrentScope(getUnreachableBlock());
John McCall3d3ec1c2010-04-21 10:05:39 +00001511
John McCallf1549f62010-07-06 01:34:17 +00001512 // Whether the finally block is being executed for EH purposes.
1513 llvm::AllocaInst *ForEHVar = CreateTempAlloca(CGF.Builder.getInt1Ty(),
1514 "finally.for-eh");
1515 InitTempAlloca(ForEHVar, llvm::ConstantInt::getFalse(getLLVMContext()));
Mike Stumpd88ea562009-12-09 03:35:49 +00001516
John McCallf1549f62010-07-06 01:34:17 +00001517 // Enter a normal cleanup which will perform the @finally block.
John McCall1f0fca52010-07-21 07:22:38 +00001518 EHStack.pushCleanup<PerformFinally>(NormalCleanup, Body,
1519 ForEHVar, EndCatchFn,
1520 RethrowFn, SavedExnVar);
John McCallf1549f62010-07-06 01:34:17 +00001521
1522 // Enter a catch-all scope.
1523 llvm::BasicBlock *CatchAllBB = createBasicBlock("finally.catchall");
1524 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1525 Builder.SetInsertPoint(CatchAllBB);
1526
1527 // If there's a begin-catch function, call it.
1528 if (BeginCatchFn) {
1529 Builder.CreateCall(BeginCatchFn, Builder.CreateLoad(getExceptionSlot()))
1530 ->setDoesNotThrow();
1531 }
1532
1533 // If we need to remember the exception pointer to rethrow later, do so.
1534 if (SavedExnVar) {
1535 llvm::Value *SavedExn = Builder.CreateLoad(getExceptionSlot());
1536 Builder.CreateStore(SavedExn, SavedExnVar);
1537 }
1538
1539 // Tell the finally block that we're in EH.
1540 Builder.CreateStore(llvm::ConstantInt::getTrue(getLLVMContext()), ForEHVar);
1541
1542 // Thread a jump through the finally cleanup.
1543 EmitBranchThroughCleanup(RethrowDest);
1544
1545 Builder.restoreIP(SavedIP);
1546
1547 EHCatchScope *CatchScope = EHStack.pushCatch(1);
1548 CatchScope->setCatchAllHandler(0, CatchAllBB);
1549
1550 return Info;
1551}
1552
1553void CodeGenFunction::ExitFinallyBlock(FinallyInfo &Info) {
1554 // Leave the finally catch-all.
1555 EHCatchScope &Catch = cast<EHCatchScope>(*EHStack.begin());
1556 llvm::BasicBlock *CatchAllBB = Catch.getHandler(0).Block;
1557 EHStack.popCatch();
1558
1559 // And leave the normal cleanup.
1560 PopCleanupBlock();
1561
1562 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1563 EmitBlock(CatchAllBB, true);
1564
1565 Builder.restoreIP(SavedIP);
1566}
1567
1568llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
1569 if (TerminateLandingPad)
1570 return TerminateLandingPad;
1571
1572 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1573
1574 // This will get inserted at the end of the function.
1575 TerminateLandingPad = createBasicBlock("terminate.lpad");
1576 Builder.SetInsertPoint(TerminateLandingPad);
1577
1578 // Tell the backend that this is a landing pad.
1579 llvm::CallInst *Exn =
1580 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_exception), "exn");
1581 Exn->setDoesNotThrow();
John McCall8262b6a2010-07-17 00:43:08 +00001582
1583 const EHPersonality &Personality = EHPersonality::get(CGM.getLangOptions());
John McCallf1549f62010-07-06 01:34:17 +00001584
1585 // Tell the backend what the exception table should be:
1586 // nothing but a catch-all.
John McCallb2593832010-09-16 06:16:50 +00001587 llvm::Value *Args[3] = { Exn, getOpaquePersonalityFn(CGM, Personality),
John McCallf1549f62010-07-06 01:34:17 +00001588 getCatchAllValue(*this) };
1589 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_selector),
1590 Args, Args+3, "eh.selector")
1591 ->setDoesNotThrow();
1592
1593 llvm::CallInst *TerminateCall = Builder.CreateCall(getTerminateFn(*this));
1594 TerminateCall->setDoesNotReturn();
1595 TerminateCall->setDoesNotThrow();
Mike Stumpd88ea562009-12-09 03:35:49 +00001596 CGF.Builder.CreateUnreachable();
1597
John McCallf1549f62010-07-06 01:34:17 +00001598 // Restore the saved insertion state.
1599 Builder.restoreIP(SavedIP);
John McCall891f80e2010-04-30 00:06:43 +00001600
John McCallf1549f62010-07-06 01:34:17 +00001601 return TerminateLandingPad;
Mike Stumpd88ea562009-12-09 03:35:49 +00001602}
Mike Stump9b39c512009-12-09 22:59:31 +00001603
1604llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
Mike Stump182f3832009-12-10 00:02:42 +00001605 if (TerminateHandler)
1606 return TerminateHandler;
1607
John McCallf1549f62010-07-06 01:34:17 +00001608 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
Mike Stump76958092009-12-09 23:31:35 +00001609
John McCallf1549f62010-07-06 01:34:17 +00001610 // Set up the terminate handler. This block is inserted at the very
1611 // end of the function by FinishFunction.
Mike Stump182f3832009-12-10 00:02:42 +00001612 TerminateHandler = createBasicBlock("terminate.handler");
John McCallf1549f62010-07-06 01:34:17 +00001613 Builder.SetInsertPoint(TerminateHandler);
1614 llvm::CallInst *TerminateCall = Builder.CreateCall(getTerminateFn(*this));
Mike Stump9b39c512009-12-09 22:59:31 +00001615 TerminateCall->setDoesNotReturn();
1616 TerminateCall->setDoesNotThrow();
1617 Builder.CreateUnreachable();
1618
John McCall3d3ec1c2010-04-21 10:05:39 +00001619 // Restore the saved insertion state.
John McCallf1549f62010-07-06 01:34:17 +00001620 Builder.restoreIP(SavedIP);
Mike Stump76958092009-12-09 23:31:35 +00001621
Mike Stump9b39c512009-12-09 22:59:31 +00001622 return TerminateHandler;
1623}
John McCallf1549f62010-07-06 01:34:17 +00001624
John McCallff8e1152010-07-23 21:56:41 +00001625CodeGenFunction::UnwindDest CodeGenFunction::getRethrowDest() {
1626 if (RethrowBlock.isValid()) return RethrowBlock;
1627
1628 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1629
1630 // We emit a jump to a notional label at the outermost unwind state.
1631 llvm::BasicBlock *Unwind = createBasicBlock("eh.resume");
1632 Builder.SetInsertPoint(Unwind);
1633
1634 const EHPersonality &Personality = EHPersonality::get(CGM.getLangOptions());
1635
1636 // This can always be a call because we necessarily didn't find
1637 // anything on the EH stack which needs our help.
John McCallb2593832010-09-16 06:16:50 +00001638 llvm::StringRef RethrowName = Personality.getCatchallRethrowFnName();
John McCallff8e1152010-07-23 21:56:41 +00001639 llvm::Constant *RethrowFn;
John McCallb2593832010-09-16 06:16:50 +00001640 if (!RethrowName.empty())
John McCallff8e1152010-07-23 21:56:41 +00001641 RethrowFn = getCatchallRethrowFn(*this, RethrowName);
1642 else
1643 RethrowFn = getUnwindResumeOrRethrowFn();
1644
1645 Builder.CreateCall(RethrowFn, Builder.CreateLoad(getExceptionSlot()))
1646 ->setDoesNotReturn();
1647 Builder.CreateUnreachable();
1648
1649 Builder.restoreIP(SavedIP);
1650
1651 RethrowBlock = UnwindDest(Unwind, EHStack.stable_end(), 0);
1652 return RethrowBlock;
1653}
1654
John McCall1f0fca52010-07-21 07:22:38 +00001655EHScopeStack::Cleanup::~Cleanup() {
1656 llvm_unreachable("Cleanup is indestructable");
John McCall3e29f962010-07-13 23:19:49 +00001657}