blob: 5845f1ec0260536f8b1caa267ce106d302a15e94 [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 McCall150b4622011-01-26 04:00:11 +0000175llvm::Value *CodeGenFunction::initFullExprCleanup() {
176 // Create a variable to decide whether the cleanup needs to be run.
177 llvm::AllocaInst *run = CreateTempAlloca(Builder.getInt1Ty(), "cleanup.cond");
178
179 // Initialize it to false at a site that's guaranteed to be run
180 // before each evaluation.
181 llvm::BasicBlock *block = OutermostConditional->getStartingBlock();
182 new llvm::StoreInst(Builder.getFalse(), run,
183 block->getFirstNonPHIOrDbg());
184
185 // Initialize it to true at the current location.
186 Builder.CreateStore(Builder.getTrue(), run);
187
188 return run;
189}
190
Anders Carlssond3379292009-10-30 02:27:02 +0000191static llvm::Constant *getAllocateExceptionFn(CodeGenFunction &CGF) {
192 // void *__cxa_allocate_exception(size_t thrown_size);
193 const llvm::Type *SizeTy = CGF.ConvertType(CGF.getContext().getSizeType());
194 std::vector<const llvm::Type*> Args(1, SizeTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000195
196 const llvm::FunctionType *FTy =
Anders Carlssond3379292009-10-30 02:27:02 +0000197 llvm::FunctionType::get(llvm::Type::getInt8PtrTy(CGF.getLLVMContext()),
198 Args, false);
Mike Stump8755ec32009-12-10 00:06:18 +0000199
Anders Carlssond3379292009-10-30 02:27:02 +0000200 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
201}
202
Mike Stump99533832009-12-02 07:41:41 +0000203static llvm::Constant *getFreeExceptionFn(CodeGenFunction &CGF) {
204 // void __cxa_free_exception(void *thrown_exception);
205 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
206 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000207
208 const llvm::FunctionType *FTy =
Mike Stump99533832009-12-02 07:41:41 +0000209 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
210 Args, false);
Mike Stump8755ec32009-12-10 00:06:18 +0000211
Mike Stump99533832009-12-02 07:41:41 +0000212 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_free_exception");
213}
214
Anders Carlssond3379292009-10-30 02:27:02 +0000215static llvm::Constant *getThrowFn(CodeGenFunction &CGF) {
Mike Stump8755ec32009-12-10 00:06:18 +0000216 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
Mike Stump99533832009-12-02 07:41:41 +0000217 // void (*dest) (void *));
Anders Carlssond3379292009-10-30 02:27:02 +0000218
219 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
220 std::vector<const llvm::Type*> Args(3, Int8PtrTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000221
222 const llvm::FunctionType *FTy =
Mike Stumpb4eea692009-11-20 00:56:31 +0000223 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
224 Args, false);
Mike Stump8755ec32009-12-10 00:06:18 +0000225
Anders Carlssond3379292009-10-30 02:27:02 +0000226 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
227}
228
Mike Stumpb4eea692009-11-20 00:56:31 +0000229static llvm::Constant *getReThrowFn(CodeGenFunction &CGF) {
Mike Stump99533832009-12-02 07:41:41 +0000230 // void __cxa_rethrow();
Mike Stumpb4eea692009-11-20 00:56:31 +0000231
Mike Stump8755ec32009-12-10 00:06:18 +0000232 const llvm::FunctionType *FTy =
Mike Stumpb4eea692009-11-20 00:56:31 +0000233 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()), false);
Mike Stump8755ec32009-12-10 00:06:18 +0000234
Mike Stumpb4eea692009-11-20 00:56:31 +0000235 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
236}
237
John McCallf1549f62010-07-06 01:34:17 +0000238static llvm::Constant *getGetExceptionPtrFn(CodeGenFunction &CGF) {
239 // void *__cxa_get_exception_ptr(void*);
240 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
241 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
242
243 const llvm::FunctionType *FTy =
244 llvm::FunctionType::get(Int8PtrTy, Args, false);
245
246 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
247}
248
Mike Stump2bf701e2009-11-20 23:44:51 +0000249static llvm::Constant *getBeginCatchFn(CodeGenFunction &CGF) {
John McCallf1549f62010-07-06 01:34:17 +0000250 // void *__cxa_begin_catch(void*);
Mike Stump2bf701e2009-11-20 23:44:51 +0000251
252 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
253 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000254
255 const llvm::FunctionType *FTy =
Mike Stump0f590be2009-12-01 03:41:18 +0000256 llvm::FunctionType::get(Int8PtrTy, Args, false);
Mike Stump8755ec32009-12-10 00:06:18 +0000257
Mike Stump2bf701e2009-11-20 23:44:51 +0000258 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
259}
260
261static llvm::Constant *getEndCatchFn(CodeGenFunction &CGF) {
Mike Stump99533832009-12-02 07:41:41 +0000262 // void __cxa_end_catch();
Mike Stump2bf701e2009-11-20 23:44:51 +0000263
Mike Stump8755ec32009-12-10 00:06:18 +0000264 const llvm::FunctionType *FTy =
Mike Stump2bf701e2009-11-20 23:44:51 +0000265 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()), false);
Mike Stump8755ec32009-12-10 00:06:18 +0000266
Mike Stump2bf701e2009-11-20 23:44:51 +0000267 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
268}
269
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000270static llvm::Constant *getUnexpectedFn(CodeGenFunction &CGF) {
271 // void __cxa_call_unexepcted(void *thrown_exception);
272
273 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
274 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000275
276 const llvm::FunctionType *FTy =
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000277 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
278 Args, false);
Mike Stump8755ec32009-12-10 00:06:18 +0000279
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000280 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_call_unexpected");
281}
282
Douglas Gregor86a3a032010-05-16 01:24:12 +0000283llvm::Constant *CodeGenFunction::getUnwindResumeOrRethrowFn() {
284 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(getLLVMContext());
Mike Stump0f590be2009-12-01 03:41:18 +0000285 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000286
287 const llvm::FunctionType *FTy =
Douglas Gregor86a3a032010-05-16 01:24:12 +0000288 llvm::FunctionType::get(llvm::Type::getVoidTy(getLLVMContext()), Args,
Mike Stump0f590be2009-12-01 03:41:18 +0000289 false);
Mike Stump8755ec32009-12-10 00:06:18 +0000290
Douglas Gregor86a3a032010-05-16 01:24:12 +0000291 if (CGM.getLangOptions().SjLjExceptions)
John McCalla5f2de22010-08-11 20:59:53 +0000292 return CGM.CreateRuntimeFunction(FTy, "_Unwind_SjLj_Resume_or_Rethrow");
Douglas Gregor86a3a032010-05-16 01:24:12 +0000293 return CGM.CreateRuntimeFunction(FTy, "_Unwind_Resume_or_Rethrow");
Mike Stump0f590be2009-12-01 03:41:18 +0000294}
295
Mike Stump99533832009-12-02 07:41:41 +0000296static llvm::Constant *getTerminateFn(CodeGenFunction &CGF) {
297 // void __terminate();
298
Mike Stump8755ec32009-12-10 00:06:18 +0000299 const llvm::FunctionType *FTy =
Mike Stump99533832009-12-02 07:41:41 +0000300 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()), false);
Mike Stump8755ec32009-12-10 00:06:18 +0000301
David Chisnall79a9ad82010-05-17 13:49:20 +0000302 return CGF.CGM.CreateRuntimeFunction(FTy,
303 CGF.CGM.getLangOptions().CPlusPlus ? "_ZSt9terminatev" : "abort");
304}
305
John McCall8262b6a2010-07-17 00:43:08 +0000306static llvm::Constant *getCatchallRethrowFn(CodeGenFunction &CGF,
John McCallb2593832010-09-16 06:16:50 +0000307 llvm::StringRef Name) {
John McCall8262b6a2010-07-17 00:43:08 +0000308 const llvm::Type *Int8PtrTy =
309 llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
310 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
311
312 const llvm::Type *VoidTy = llvm::Type::getVoidTy(CGF.getLLVMContext());
313 const llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, Args, false);
314
315 return CGF.CGM.CreateRuntimeFunction(FTy, Name);
John McCallf1549f62010-07-06 01:34:17 +0000316}
317
John McCall8262b6a2010-07-17 00:43:08 +0000318const EHPersonality EHPersonality::GNU_C("__gcc_personality_v0");
John McCall44680782010-11-07 02:35:25 +0000319const EHPersonality EHPersonality::GNU_C_SJLJ("__gcc_personality_sj0");
John McCall8262b6a2010-07-17 00:43:08 +0000320const EHPersonality EHPersonality::NeXT_ObjC("__objc_personality_v0");
321const EHPersonality EHPersonality::GNU_CPlusPlus("__gxx_personality_v0");
322const EHPersonality EHPersonality::GNU_CPlusPlus_SJLJ("__gxx_personality_sj0");
323const EHPersonality EHPersonality::GNU_ObjC("__gnu_objc_personality_v0",
324 "objc_exception_throw");
325
326static const EHPersonality &getCPersonality(const LangOptions &L) {
John McCall44680782010-11-07 02:35:25 +0000327 if (L.SjLjExceptions)
328 return EHPersonality::GNU_C_SJLJ;
John McCall8262b6a2010-07-17 00:43:08 +0000329 return EHPersonality::GNU_C;
330}
331
332static const EHPersonality &getObjCPersonality(const LangOptions &L) {
333 if (L.NeXTRuntime) {
334 if (L.ObjCNonFragileABI) return EHPersonality::NeXT_ObjC;
335 else return getCPersonality(L);
John McCallf1549f62010-07-06 01:34:17 +0000336 } else {
John McCall8262b6a2010-07-17 00:43:08 +0000337 return EHPersonality::GNU_ObjC;
John McCallf1549f62010-07-06 01:34:17 +0000338 }
339}
340
John McCall8262b6a2010-07-17 00:43:08 +0000341static const EHPersonality &getCXXPersonality(const LangOptions &L) {
342 if (L.SjLjExceptions)
343 return EHPersonality::GNU_CPlusPlus_SJLJ;
John McCallf1549f62010-07-06 01:34:17 +0000344 else
John McCall8262b6a2010-07-17 00:43:08 +0000345 return EHPersonality::GNU_CPlusPlus;
John McCallf1549f62010-07-06 01:34:17 +0000346}
347
348/// Determines the personality function to use when both C++
349/// and Objective-C exceptions are being caught.
John McCall8262b6a2010-07-17 00:43:08 +0000350static const EHPersonality &getObjCXXPersonality(const LangOptions &L) {
John McCallf1549f62010-07-06 01:34:17 +0000351 // The ObjC personality defers to the C++ personality for non-ObjC
352 // handlers. Unlike the C++ case, we use the same personality
353 // function on targets using (backend-driven) SJLJ EH.
John McCall8262b6a2010-07-17 00:43:08 +0000354 if (L.NeXTRuntime) {
355 if (L.ObjCNonFragileABI)
356 return EHPersonality::NeXT_ObjC;
John McCallf1549f62010-07-06 01:34:17 +0000357
358 // In the fragile ABI, just use C++ exception handling and hope
359 // they're not doing crazy exception mixing.
360 else
John McCall8262b6a2010-07-17 00:43:08 +0000361 return getCXXPersonality(L);
Chandler Carruthdcf22ad2010-05-17 20:58:49 +0000362 }
David Chisnall79a9ad82010-05-17 13:49:20 +0000363
John McCall8262b6a2010-07-17 00:43:08 +0000364 // The GNU runtime's personality function inherently doesn't support
365 // mixed EH. Use the C++ personality just to avoid returning null.
366 return getCXXPersonality(L);
John McCallf1549f62010-07-06 01:34:17 +0000367}
368
John McCall8262b6a2010-07-17 00:43:08 +0000369const EHPersonality &EHPersonality::get(const LangOptions &L) {
370 if (L.CPlusPlus && L.ObjC1)
371 return getObjCXXPersonality(L);
372 else if (L.CPlusPlus)
373 return getCXXPersonality(L);
374 else if (L.ObjC1)
375 return getObjCPersonality(L);
John McCallf1549f62010-07-06 01:34:17 +0000376 else
John McCall8262b6a2010-07-17 00:43:08 +0000377 return getCPersonality(L);
378}
John McCallf1549f62010-07-06 01:34:17 +0000379
John McCallb2593832010-09-16 06:16:50 +0000380static llvm::Constant *getPersonalityFn(CodeGenModule &CGM,
John McCall8262b6a2010-07-17 00:43:08 +0000381 const EHPersonality &Personality) {
John McCall8262b6a2010-07-17 00:43:08 +0000382 llvm::Constant *Fn =
John McCallb2593832010-09-16 06:16:50 +0000383 CGM.CreateRuntimeFunction(llvm::FunctionType::get(
384 llvm::Type::getInt32Ty(CGM.getLLVMContext()),
385 true),
386 Personality.getPersonalityFnName());
387 return Fn;
388}
389
390static llvm::Constant *getOpaquePersonalityFn(CodeGenModule &CGM,
391 const EHPersonality &Personality) {
392 llvm::Constant *Fn = getPersonalityFn(CGM, Personality);
393 return llvm::ConstantExpr::getBitCast(Fn, CGM.PtrToInt8Ty);
394}
395
396/// Check whether a personality function could reasonably be swapped
397/// for a C++ personality function.
398static bool PersonalityHasOnlyCXXUses(llvm::Constant *Fn) {
399 for (llvm::Constant::use_iterator
400 I = Fn->use_begin(), E = Fn->use_end(); I != E; ++I) {
401 llvm::User *User = *I;
402
403 // Conditionally white-list bitcasts.
404 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(User)) {
405 if (CE->getOpcode() != llvm::Instruction::BitCast) return false;
406 if (!PersonalityHasOnlyCXXUses(CE))
407 return false;
408 continue;
409 }
410
411 // Otherwise, it has to be a selector call.
412 if (!isa<llvm::EHSelectorInst>(User)) return false;
413
414 llvm::EHSelectorInst *Selector = cast<llvm::EHSelectorInst>(User);
415 for (unsigned I = 2, E = Selector->getNumArgOperands(); I != E; ++I) {
416 // Look for something that would've been returned by the ObjC
417 // runtime's GetEHType() method.
418 llvm::GlobalVariable *GV
419 = dyn_cast<llvm::GlobalVariable>(Selector->getArgOperand(I));
420 if (!GV) continue;
421
422 // ObjC EH selector entries are always global variables with
423 // names starting like this.
424 if (GV->getName().startswith("OBJC_EHTYPE"))
425 return false;
426 }
427 }
428
429 return true;
430}
431
432/// Try to use the C++ personality function in ObjC++. Not doing this
433/// can cause some incompatibilities with gcc, which is more
434/// aggressive about only using the ObjC++ personality in a function
435/// when it really needs it.
436void CodeGenModule::SimplifyPersonality() {
437 // For now, this is really a Darwin-specific operation.
438 if (Context.Target.getTriple().getOS() != llvm::Triple::Darwin)
439 return;
440
441 // If we're not in ObjC++ -fexceptions, there's nothing to do.
442 if (!Features.CPlusPlus || !Features.ObjC1 || !Features.Exceptions)
443 return;
444
445 const EHPersonality &ObjCXX = EHPersonality::get(Features);
446 const EHPersonality &CXX = getCXXPersonality(Features);
447 if (&ObjCXX == &CXX ||
448 ObjCXX.getPersonalityFnName() == CXX.getPersonalityFnName())
449 return;
450
451 llvm::Function *Fn =
452 getModule().getFunction(ObjCXX.getPersonalityFnName());
453
454 // Nothing to do if it's unused.
455 if (!Fn || Fn->use_empty()) return;
456
457 // Can't do the optimization if it has non-C++ uses.
458 if (!PersonalityHasOnlyCXXUses(Fn)) return;
459
460 // Create the C++ personality function and kill off the old
461 // function.
462 llvm::Constant *CXXFn = getPersonalityFn(*this, CXX);
463
464 // This can happen if the user is screwing with us.
465 if (Fn->getType() != CXXFn->getType()) return;
466
467 Fn->replaceAllUsesWith(CXXFn);
468 Fn->eraseFromParent();
John McCallf1549f62010-07-06 01:34:17 +0000469}
470
471/// Returns the value to inject into a selector to indicate the
472/// presence of a catch-all.
473static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
474 // Possibly we should use @llvm.eh.catch.all.value here.
475 return llvm::ConstantPointerNull::get(CGF.CGM.PtrToInt8Ty);
476}
477
478/// Returns the value to inject into a selector to indicate the
479/// presence of a cleanup.
480static llvm::Constant *getCleanupValue(CodeGenFunction &CGF) {
481 return llvm::ConstantInt::get(CGF.Builder.getInt32Ty(), 0);
Mike Stump99533832009-12-02 07:41:41 +0000482}
483
John McCall09faeab2010-07-13 21:17:51 +0000484namespace {
485 /// A cleanup to free the exception object if its initialization
486 /// throws.
John McCall1f0fca52010-07-21 07:22:38 +0000487 struct FreeExceptionCleanup : EHScopeStack::Cleanup {
John McCall09faeab2010-07-13 21:17:51 +0000488 FreeExceptionCleanup(llvm::Value *ShouldFreeVar,
489 llvm::Value *ExnLocVar)
490 : ShouldFreeVar(ShouldFreeVar), ExnLocVar(ExnLocVar) {}
491
492 llvm::Value *ShouldFreeVar;
493 llvm::Value *ExnLocVar;
494
495 void Emit(CodeGenFunction &CGF, bool IsForEH) {
496 llvm::BasicBlock *FreeBB = CGF.createBasicBlock("free-exnobj");
497 llvm::BasicBlock *DoneBB = CGF.createBasicBlock("free-exnobj.done");
498
499 llvm::Value *ShouldFree = CGF.Builder.CreateLoad(ShouldFreeVar,
500 "should-free-exnobj");
501 CGF.Builder.CreateCondBr(ShouldFree, FreeBB, DoneBB);
502 CGF.EmitBlock(FreeBB);
503 llvm::Value *ExnLocLocal = CGF.Builder.CreateLoad(ExnLocVar, "exnobj");
504 CGF.Builder.CreateCall(getFreeExceptionFn(CGF), ExnLocLocal)
505 ->setDoesNotThrow();
506 CGF.EmitBlock(DoneBB);
507 }
508 };
509}
510
John McCallac418162010-04-22 01:10:34 +0000511// Emits an exception expression into the given location. This
512// differs from EmitAnyExprToMem only in that, if a final copy-ctor
513// call is required, an exception within that copy ctor causes
514// std::terminate to be invoked.
515static void EmitAnyExprToExn(CodeGenFunction &CGF, const Expr *E,
516 llvm::Value *ExnLoc) {
517 // We want to release the allocated exception object if this
518 // expression throws. We do this by pushing an EH-only cleanup
519 // block which, furthermore, deactivates itself after the expression
520 // is complete.
521 llvm::AllocaInst *ShouldFreeVar =
522 CGF.CreateTempAlloca(llvm::Type::getInt1Ty(CGF.getLLVMContext()),
523 "should-free-exnobj.var");
524 CGF.InitTempAlloca(ShouldFreeVar,
525 llvm::ConstantInt::getFalse(CGF.getLLVMContext()));
Mike Stump0f590be2009-12-01 03:41:18 +0000526
John McCallac418162010-04-22 01:10:34 +0000527 // A variable holding the exception pointer. This is necessary
528 // because the throw expression does not necessarily dominate the
529 // cleanup, for example if it appears in a conditional expression.
530 llvm::AllocaInst *ExnLocVar =
531 CGF.CreateTempAlloca(ExnLoc->getType(), "exnobj.var");
Mike Stump8755ec32009-12-10 00:06:18 +0000532
John McCallf1549f62010-07-06 01:34:17 +0000533 // Make sure the exception object is cleaned up if there's an
534 // exception during initialization.
John McCall09faeab2010-07-13 21:17:51 +0000535 // FIXME: stmt expressions might require this to be a normal
536 // cleanup, too.
John McCall1f0fca52010-07-21 07:22:38 +0000537 CGF.EHStack.pushCleanup<FreeExceptionCleanup>(EHCleanup,
538 ShouldFreeVar,
539 ExnLocVar);
John McCallf1549f62010-07-06 01:34:17 +0000540 EHScopeStack::stable_iterator Cleanup = CGF.EHStack.stable_begin();
John McCallac418162010-04-22 01:10:34 +0000541
542 CGF.Builder.CreateStore(ExnLoc, ExnLocVar);
543 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(CGF.getLLVMContext()),
544 ShouldFreeVar);
545
546 // __cxa_allocate_exception returns a void*; we need to cast this
547 // to the appropriate type for the object.
John McCall14e1bc92010-10-29 08:14:02 +0000548 const llvm::Type *Ty = CGF.ConvertTypeForMem(E->getType())->getPointerTo();
John McCallac418162010-04-22 01:10:34 +0000549 llvm::Value *TypedExnLoc = CGF.Builder.CreateBitCast(ExnLoc, Ty);
550
551 // FIXME: this isn't quite right! If there's a final unelided call
552 // to a copy constructor, then according to [except.terminate]p1 we
553 // must call std::terminate() if that constructor throws, because
554 // technically that copy occurs after the exception expression is
555 // evaluated but before the exception is caught. But the best way
556 // to handle that is to teach EmitAggExpr to do the final copy
557 // differently if it can't be elided.
John McCall558d2ab2010-09-15 10:14:12 +0000558 CGF.EmitAnyExprToMem(E, TypedExnLoc, /*Volatile*/ false, /*IsInit*/ true);
John McCallac418162010-04-22 01:10:34 +0000559
560 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(CGF.getLLVMContext()),
561 ShouldFreeVar);
562
John McCallf1549f62010-07-06 01:34:17 +0000563 // Technically, the exception object is like a temporary; it has to
564 // be cleaned up when its full-expression is complete.
565 // Unfortunately, the AST represents full-expressions by creating a
John McCall4765fa02010-12-06 08:20:24 +0000566 // ExprWithCleanups, which it only does when there are actually
John McCallf1549f62010-07-06 01:34:17 +0000567 // temporaries.
568 //
569 // If any cleanups have been added since we pushed ours, they must
570 // be from temporaries; this will get popped at the same time.
571 // Otherwise we need to pop ours off. FIXME: this is very brittle.
572 if (Cleanup == CGF.EHStack.stable_begin())
573 CGF.PopCleanupBlock();
Mike Stump0f590be2009-12-01 03:41:18 +0000574}
575
John McCallf1549f62010-07-06 01:34:17 +0000576llvm::Value *CodeGenFunction::getExceptionSlot() {
577 if (!ExceptionSlot) {
578 const llvm::Type *i8p = llvm::Type::getInt8PtrTy(getLLVMContext());
579 ExceptionSlot = CreateTempAlloca(i8p, "exn.slot");
Mike Stump0f590be2009-12-01 03:41:18 +0000580 }
John McCallf1549f62010-07-06 01:34:17 +0000581 return ExceptionSlot;
Mike Stump0f590be2009-12-01 03:41:18 +0000582}
583
Anders Carlsson756b5c42009-10-30 01:42:31 +0000584void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E) {
Anders Carlssond3379292009-10-30 02:27:02 +0000585 if (!E->getSubExpr()) {
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000586 if (getInvokeDest()) {
John McCallf1549f62010-07-06 01:34:17 +0000587 Builder.CreateInvoke(getReThrowFn(*this),
588 getUnreachableBlock(),
589 getInvokeDest())
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000590 ->setDoesNotReturn();
John McCallf1549f62010-07-06 01:34:17 +0000591 } else {
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000592 Builder.CreateCall(getReThrowFn(*this))->setDoesNotReturn();
John McCallf1549f62010-07-06 01:34:17 +0000593 Builder.CreateUnreachable();
594 }
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000595
John McCallcd5b22e2011-01-12 03:41:02 +0000596 // throw is an expression, and the expression emitters expect us
597 // to leave ourselves at a valid insertion point.
598 EmitBlock(createBasicBlock("throw.cont"));
599
Anders Carlssond3379292009-10-30 02:27:02 +0000600 return;
601 }
Mike Stump8755ec32009-12-10 00:06:18 +0000602
Anders Carlssond3379292009-10-30 02:27:02 +0000603 QualType ThrowType = E->getSubExpr()->getType();
Mike Stump8755ec32009-12-10 00:06:18 +0000604
Anders Carlssond3379292009-10-30 02:27:02 +0000605 // Now allocate the exception object.
606 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
John McCall3d3ec1c2010-04-21 10:05:39 +0000607 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
Mike Stump8755ec32009-12-10 00:06:18 +0000608
Anders Carlssond3379292009-10-30 02:27:02 +0000609 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(*this);
John McCallf1549f62010-07-06 01:34:17 +0000610 llvm::CallInst *ExceptionPtr =
Mike Stump8755ec32009-12-10 00:06:18 +0000611 Builder.CreateCall(AllocExceptionFn,
Anders Carlssond3379292009-10-30 02:27:02 +0000612 llvm::ConstantInt::get(SizeTy, TypeSize),
613 "exception");
John McCallf1549f62010-07-06 01:34:17 +0000614 ExceptionPtr->setDoesNotThrow();
Anders Carlsson8370c582009-12-11 00:32:37 +0000615
John McCallac418162010-04-22 01:10:34 +0000616 EmitAnyExprToExn(*this, E->getSubExpr(), ExceptionPtr);
Mike Stump8755ec32009-12-10 00:06:18 +0000617
Anders Carlssond3379292009-10-30 02:27:02 +0000618 // Now throw the exception.
619 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(getLLVMContext());
Anders Carlsson82a113a2011-01-24 01:59:49 +0000620 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
621 /*ForEH=*/true);
John McCallac418162010-04-22 01:10:34 +0000622
623 // The address of the destructor. If the exception type has a
624 // trivial destructor (or isn't a record), we just pass null.
625 llvm::Constant *Dtor = 0;
626 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
627 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
628 if (!Record->hasTrivialDestructor()) {
Douglas Gregor1d110e02010-07-01 14:13:13 +0000629 CXXDestructorDecl *DtorD = Record->getDestructor();
John McCallac418162010-04-22 01:10:34 +0000630 Dtor = CGM.GetAddrOfCXXDestructor(DtorD, Dtor_Complete);
631 Dtor = llvm::ConstantExpr::getBitCast(Dtor, Int8PtrTy);
632 }
633 }
634 if (!Dtor) Dtor = llvm::Constant::getNullValue(Int8PtrTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000635
Mike Stump0a3816e2009-12-04 01:51:45 +0000636 if (getInvokeDest()) {
Mike Stump8755ec32009-12-10 00:06:18 +0000637 llvm::InvokeInst *ThrowCall =
John McCallf1549f62010-07-06 01:34:17 +0000638 Builder.CreateInvoke3(getThrowFn(*this),
639 getUnreachableBlock(), getInvokeDest(),
Mike Stump0a3816e2009-12-04 01:51:45 +0000640 ExceptionPtr, TypeInfo, Dtor);
641 ThrowCall->setDoesNotReturn();
Mike Stump0a3816e2009-12-04 01:51:45 +0000642 } else {
Mike Stump8755ec32009-12-10 00:06:18 +0000643 llvm::CallInst *ThrowCall =
Mike Stump0a3816e2009-12-04 01:51:45 +0000644 Builder.CreateCall3(getThrowFn(*this), ExceptionPtr, TypeInfo, Dtor);
645 ThrowCall->setDoesNotReturn();
John McCallf1549f62010-07-06 01:34:17 +0000646 Builder.CreateUnreachable();
Mike Stump0a3816e2009-12-04 01:51:45 +0000647 }
Mike Stump8755ec32009-12-10 00:06:18 +0000648
John McCallcd5b22e2011-01-12 03:41:02 +0000649 // throw is an expression, and the expression emitters expect us
650 // to leave ourselves at a valid insertion point.
651 EmitBlock(createBasicBlock("throw.cont"));
Anders Carlsson756b5c42009-10-30 01:42:31 +0000652}
Mike Stump2bf701e2009-11-20 23:44:51 +0000653
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000654void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
Anders Carlssona994ee42010-02-06 23:59:05 +0000655 if (!Exceptions)
656 return;
657
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000658 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
659 if (FD == 0)
660 return;
661 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
662 if (Proto == 0)
663 return;
664
665 assert(!Proto->hasAnyExceptionSpec() && "function with parameter pack");
666
667 if (!Proto->hasExceptionSpec())
668 return;
669
John McCallf1549f62010-07-06 01:34:17 +0000670 unsigned NumExceptions = Proto->getNumExceptions();
671 EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000672
John McCallf1549f62010-07-06 01:34:17 +0000673 for (unsigned I = 0; I != NumExceptions; ++I) {
674 QualType Ty = Proto->getExceptionType(I);
675 QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
Anders Carlsson82a113a2011-01-24 01:59:49 +0000676 llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType,
677 /*ForEH=*/true);
John McCallf1549f62010-07-06 01:34:17 +0000678 Filter->setFilter(I, EHType);
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000679 }
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000680}
681
682void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
Anders Carlssona994ee42010-02-06 23:59:05 +0000683 if (!Exceptions)
684 return;
685
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000686 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
687 if (FD == 0)
688 return;
689 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
690 if (Proto == 0)
691 return;
692
693 if (!Proto->hasExceptionSpec())
694 return;
695
John McCallf1549f62010-07-06 01:34:17 +0000696 EHStack.popFilter();
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000697}
698
Mike Stump2bf701e2009-11-20 23:44:51 +0000699void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
John McCall59a70002010-07-07 06:56:46 +0000700 EnterCXXTryStmt(S);
John McCall9fc6a772010-02-19 09:25:03 +0000701 EmitStmt(S.getTryBlock());
John McCall59a70002010-07-07 06:56:46 +0000702 ExitCXXTryStmt(S);
John McCall9fc6a772010-02-19 09:25:03 +0000703}
704
John McCall59a70002010-07-07 06:56:46 +0000705void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallf1549f62010-07-06 01:34:17 +0000706 unsigned NumHandlers = S.getNumHandlers();
707 EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
John McCall9fc6a772010-02-19 09:25:03 +0000708
John McCallf1549f62010-07-06 01:34:17 +0000709 for (unsigned I = 0; I != NumHandlers; ++I) {
710 const CXXCatchStmt *C = S.getHandler(I);
John McCall9fc6a772010-02-19 09:25:03 +0000711
John McCallf1549f62010-07-06 01:34:17 +0000712 llvm::BasicBlock *Handler = createBasicBlock("catch");
713 if (C->getExceptionDecl()) {
714 // FIXME: Dropping the reference type on the type into makes it
715 // impossible to correctly implement catch-by-reference
716 // semantics for pointers. Unfortunately, this is what all
717 // existing compilers do, and it's not clear that the standard
718 // personality routine is capable of doing this right. See C++ DR 388:
719 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
720 QualType CaughtType = C->getCaughtType();
721 CaughtType = CaughtType.getNonReferenceType().getUnqualifiedType();
John McCall5a180392010-07-24 00:37:23 +0000722
723 llvm::Value *TypeInfo = 0;
724 if (CaughtType->isObjCObjectPointerType())
725 TypeInfo = CGM.getObjCRuntime().GetEHType(CaughtType);
726 else
Anders Carlsson82a113a2011-01-24 01:59:49 +0000727 TypeInfo = CGM.GetAddrOfRTTIDescriptor(CaughtType, /*ForEH=*/true);
John McCallf1549f62010-07-06 01:34:17 +0000728 CatchScope->setHandler(I, TypeInfo, Handler);
729 } else {
730 // No exception decl indicates '...', a catch-all.
731 CatchScope->setCatchAllHandler(I, Handler);
732 }
733 }
John McCallf1549f62010-07-06 01:34:17 +0000734}
735
736/// Check whether this is a non-EH scope, i.e. a scope which doesn't
737/// affect exception handling. Currently, the only non-EH scopes are
738/// normal-only cleanup scopes.
739static bool isNonEHScope(const EHScope &S) {
John McCallda65ea82010-07-13 20:32:21 +0000740 switch (S.getKind()) {
John McCall1f0fca52010-07-21 07:22:38 +0000741 case EHScope::Cleanup:
742 return !cast<EHCleanupScope>(S).isEHCleanup();
John McCallda65ea82010-07-13 20:32:21 +0000743 case EHScope::Filter:
744 case EHScope::Catch:
745 case EHScope::Terminate:
746 return false;
747 }
748
749 // Suppress warning.
750 return false;
John McCallf1549f62010-07-06 01:34:17 +0000751}
752
753llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
754 assert(EHStack.requiresLandingPad());
755 assert(!EHStack.empty());
756
John McCallda65ea82010-07-13 20:32:21 +0000757 if (!Exceptions)
758 return 0;
759
John McCallf1549f62010-07-06 01:34:17 +0000760 // Check the innermost scope for a cached landing pad. If this is
761 // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
762 llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
763 if (LP) return LP;
764
765 // Build the landing pad for this scope.
766 LP = EmitLandingPad();
767 assert(LP);
768
769 // Cache the landing pad on the innermost scope. If this is a
770 // non-EH scope, cache the landing pad on the enclosing scope, too.
771 for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
772 ir->setCachedLandingPad(LP);
773 if (!isNonEHScope(*ir)) break;
774 }
775
776 return LP;
777}
778
779llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
780 assert(EHStack.requiresLandingPad());
781
782 // This function contains a hack to work around a design flaw in
783 // LLVM's EH IR which breaks semantics after inlining. This same
784 // hack is implemented in llvm-gcc.
785 //
786 // The LLVM EH abstraction is basically a thin veneer over the
787 // traditional GCC zero-cost design: for each range of instructions
788 // in the function, there is (at most) one "landing pad" with an
789 // associated chain of EH actions. A language-specific personality
790 // function interprets this chain of actions and (1) decides whether
791 // or not to resume execution at the landing pad and (2) if so,
792 // provides an integer indicating why it's stopping. In LLVM IR,
793 // the association of a landing pad with a range of instructions is
794 // achieved via an invoke instruction, the chain of actions becomes
795 // the arguments to the @llvm.eh.selector call, and the selector
796 // call returns the integer indicator. Other than the required
797 // presence of two intrinsic function calls in the landing pad,
798 // the IR exactly describes the layout of the output code.
799 //
800 // A principal advantage of this design is that it is completely
801 // language-agnostic; in theory, the LLVM optimizers can treat
802 // landing pads neutrally, and targets need only know how to lower
803 // the intrinsics to have a functioning exceptions system (assuming
804 // that platform exceptions follow something approximately like the
805 // GCC design). Unfortunately, landing pads cannot be combined in a
806 // language-agnostic way: given selectors A and B, there is no way
807 // to make a single landing pad which faithfully represents the
808 // semantics of propagating an exception first through A, then
809 // through B, without knowing how the personality will interpret the
810 // (lowered form of the) selectors. This means that inlining has no
811 // choice but to crudely chain invokes (i.e., to ignore invokes in
812 // the inlined function, but to turn all unwindable calls into
813 // invokes), which is only semantically valid if every unwind stops
814 // at every landing pad.
815 //
816 // Therefore, the invoke-inline hack is to guarantee that every
817 // landing pad has a catch-all.
818 const bool UseInvokeInlineHack = true;
819
820 for (EHScopeStack::iterator ir = EHStack.begin(); ; ) {
821 assert(ir != EHStack.end() &&
822 "stack requiring landing pad is nothing but non-EH scopes?");
823
824 // If this is a terminate scope, just use the singleton terminate
825 // landing pad.
826 if (isa<EHTerminateScope>(*ir))
827 return getTerminateLandingPad();
828
829 // If this isn't an EH scope, iterate; otherwise break out.
830 if (!isNonEHScope(*ir)) break;
831 ++ir;
832
833 // We haven't checked this scope for a cached landing pad yet.
834 if (llvm::BasicBlock *LP = ir->getCachedLandingPad())
835 return LP;
836 }
837
838 // Save the current IR generation state.
839 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
840
John McCall8262b6a2010-07-17 00:43:08 +0000841 const EHPersonality &Personality =
842 EHPersonality::get(CGF.CGM.getLangOptions());
843
John McCallf1549f62010-07-06 01:34:17 +0000844 // Create and configure the landing pad.
845 llvm::BasicBlock *LP = createBasicBlock("lpad");
846 EmitBlock(LP);
847
848 // Save the exception pointer. It's safe to use a single exception
849 // pointer per function because EH cleanups can never have nested
850 // try/catches.
851 llvm::CallInst *Exn =
852 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_exception), "exn");
853 Exn->setDoesNotThrow();
854 Builder.CreateStore(Exn, getExceptionSlot());
855
856 // Build the selector arguments.
857 llvm::SmallVector<llvm::Value*, 8> EHSelector;
858 EHSelector.push_back(Exn);
John McCallb2593832010-09-16 06:16:50 +0000859 EHSelector.push_back(getOpaquePersonalityFn(CGM, Personality));
John McCallf1549f62010-07-06 01:34:17 +0000860
861 // Accumulate all the handlers in scope.
John McCallff8e1152010-07-23 21:56:41 +0000862 llvm::DenseMap<llvm::Value*, UnwindDest> EHHandlers;
863 UnwindDest CatchAll;
John McCallf1549f62010-07-06 01:34:17 +0000864 bool HasEHCleanup = false;
865 bool HasEHFilter = false;
866 llvm::SmallVector<llvm::Value*, 8> EHFilters;
867 for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end();
868 I != E; ++I) {
869
870 switch (I->getKind()) {
John McCall1f0fca52010-07-21 07:22:38 +0000871 case EHScope::Cleanup:
John McCallda65ea82010-07-13 20:32:21 +0000872 if (!HasEHCleanup)
John McCall1f0fca52010-07-21 07:22:38 +0000873 HasEHCleanup = cast<EHCleanupScope>(*I).isEHCleanup();
John McCallda65ea82010-07-13 20:32:21 +0000874 // We otherwise don't care about cleanups.
875 continue;
876
John McCallf1549f62010-07-06 01:34:17 +0000877 case EHScope::Filter: {
878 assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
John McCallff8e1152010-07-23 21:56:41 +0000879 assert(!CatchAll.isValid() && "EH filter reached after catch-all");
John McCallf1549f62010-07-06 01:34:17 +0000880
881 // Filter scopes get added to the selector in wierd ways.
882 EHFilterScope &Filter = cast<EHFilterScope>(*I);
883 HasEHFilter = true;
884
885 // Add all the filter values which we aren't already explicitly
886 // catching.
887 for (unsigned I = 0, E = Filter.getNumFilters(); I != E; ++I) {
888 llvm::Value *FV = Filter.getFilter(I);
889 if (!EHHandlers.count(FV))
890 EHFilters.push_back(FV);
891 }
892 goto done;
893 }
894
895 case EHScope::Terminate:
896 // Terminate scopes are basically catch-alls.
John McCallff8e1152010-07-23 21:56:41 +0000897 assert(!CatchAll.isValid());
898 CatchAll = UnwindDest(getTerminateHandler(),
899 EHStack.getEnclosingEHCleanup(I),
900 cast<EHTerminateScope>(*I).getDestIndex());
John McCallf1549f62010-07-06 01:34:17 +0000901 goto done;
902
903 case EHScope::Catch:
904 break;
905 }
906
907 EHCatchScope &Catch = cast<EHCatchScope>(*I);
908 for (unsigned HI = 0, HE = Catch.getNumHandlers(); HI != HE; ++HI) {
909 EHCatchScope::Handler Handler = Catch.getHandler(HI);
910
911 // Catch-all. We should only have one of these per catch.
912 if (!Handler.Type) {
John McCallff8e1152010-07-23 21:56:41 +0000913 assert(!CatchAll.isValid());
914 CatchAll = UnwindDest(Handler.Block,
915 EHStack.getEnclosingEHCleanup(I),
916 Handler.Index);
John McCallf1549f62010-07-06 01:34:17 +0000917 continue;
918 }
919
920 // Check whether we already have a handler for this type.
John McCallff8e1152010-07-23 21:56:41 +0000921 UnwindDest &Dest = EHHandlers[Handler.Type];
922 if (Dest.isValid()) continue;
John McCallf1549f62010-07-06 01:34:17 +0000923
924 EHSelector.push_back(Handler.Type);
John McCallff8e1152010-07-23 21:56:41 +0000925 Dest = UnwindDest(Handler.Block,
926 EHStack.getEnclosingEHCleanup(I),
927 Handler.Index);
John McCallf1549f62010-07-06 01:34:17 +0000928 }
929
930 // Stop if we found a catch-all.
John McCallff8e1152010-07-23 21:56:41 +0000931 if (CatchAll.isValid()) break;
John McCallf1549f62010-07-06 01:34:17 +0000932 }
933
934 done:
935 unsigned LastToEmitInLoop = EHSelector.size();
936
937 // If we have a catch-all, add null to the selector.
John McCallff8e1152010-07-23 21:56:41 +0000938 if (CatchAll.isValid()) {
John McCallf1549f62010-07-06 01:34:17 +0000939 EHSelector.push_back(getCatchAllValue(CGF));
940
941 // If we have an EH filter, we need to add those handlers in the
942 // right place in the selector, which is to say, at the end.
943 } else if (HasEHFilter) {
944 // Create a filter expression: an integer constant saying how many
945 // filters there are (+1 to avoid ambiguity with 0 for cleanup),
946 // followed by the filter types. The personality routine only
947 // lands here if the filter doesn't match.
948 EHSelector.push_back(llvm::ConstantInt::get(Builder.getInt32Ty(),
949 EHFilters.size() + 1));
950 EHSelector.append(EHFilters.begin(), EHFilters.end());
951
952 // Also check whether we need a cleanup.
953 if (UseInvokeInlineHack || HasEHCleanup)
954 EHSelector.push_back(UseInvokeInlineHack
955 ? getCatchAllValue(CGF)
956 : getCleanupValue(CGF));
957
958 // Otherwise, signal that we at least have cleanups.
959 } else if (UseInvokeInlineHack || HasEHCleanup) {
960 EHSelector.push_back(UseInvokeInlineHack
961 ? getCatchAllValue(CGF)
962 : getCleanupValue(CGF));
963 } else {
964 assert(LastToEmitInLoop > 2);
965 LastToEmitInLoop--;
966 }
967
968 assert(EHSelector.size() >= 3 && "selector call has only two arguments!");
969
970 // Tell the backend how to generate the landing pad.
971 llvm::CallInst *Selection =
972 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_selector),
973 EHSelector.begin(), EHSelector.end(), "eh.selector");
974 Selection->setDoesNotThrow();
975
976 // Select the right handler.
977 llvm::Value *llvm_eh_typeid_for =
978 CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
979
980 // The results of llvm_eh_typeid_for aren't reliable --- at least
981 // not locally --- so we basically have to do this as an 'if' chain.
982 // We walk through the first N-1 catch clauses, testing and chaining,
983 // and then fall into the final clause (which is either a cleanup, a
984 // filter (possibly with a cleanup), a catch-all, or another catch).
985 for (unsigned I = 2; I != LastToEmitInLoop; ++I) {
986 llvm::Value *Type = EHSelector[I];
John McCallff8e1152010-07-23 21:56:41 +0000987 UnwindDest Dest = EHHandlers[Type];
988 assert(Dest.isValid() && "no handler entry for value in selector?");
John McCallf1549f62010-07-06 01:34:17 +0000989
990 // Figure out where to branch on a match. As a debug code-size
991 // optimization, if the scope depth matches the innermost cleanup,
992 // we branch directly to the catch handler.
John McCallff8e1152010-07-23 21:56:41 +0000993 llvm::BasicBlock *Match = Dest.getBlock();
994 bool MatchNeedsCleanup =
995 Dest.getScopeDepth() != EHStack.getInnermostEHCleanup();
John McCallf1549f62010-07-06 01:34:17 +0000996 if (MatchNeedsCleanup)
997 Match = createBasicBlock("eh.match");
998
999 llvm::BasicBlock *Next = createBasicBlock("eh.next");
1000
1001 // Check whether the exception matches.
1002 llvm::CallInst *Id
1003 = Builder.CreateCall(llvm_eh_typeid_for,
1004 Builder.CreateBitCast(Type, CGM.PtrToInt8Ty));
1005 Id->setDoesNotThrow();
1006 Builder.CreateCondBr(Builder.CreateICmpEQ(Selection, Id),
1007 Match, Next);
1008
1009 // Emit match code if necessary.
1010 if (MatchNeedsCleanup) {
1011 EmitBlock(Match);
1012 EmitBranchThroughEHCleanup(Dest);
1013 }
1014
1015 // Continue to the next match.
1016 EmitBlock(Next);
1017 }
1018
1019 // Emit the final case in the selector.
1020 // This might be a catch-all....
John McCallff8e1152010-07-23 21:56:41 +00001021 if (CatchAll.isValid()) {
John McCallf1549f62010-07-06 01:34:17 +00001022 assert(isa<llvm::ConstantPointerNull>(EHSelector.back()));
1023 EmitBranchThroughEHCleanup(CatchAll);
1024
1025 // ...or an EH filter...
1026 } else if (HasEHFilter) {
1027 llvm::Value *SavedSelection = Selection;
1028
1029 // First, unwind out to the outermost scope if necessary.
1030 if (EHStack.hasEHCleanups()) {
1031 // The end here might not dominate the beginning, so we might need to
1032 // save the selector if we need it.
1033 llvm::AllocaInst *SelectorVar = 0;
1034 if (HasEHCleanup) {
1035 SelectorVar = CreateTempAlloca(Builder.getInt32Ty(), "selector.var");
1036 Builder.CreateStore(Selection, SelectorVar);
1037 }
1038
1039 llvm::BasicBlock *CleanupContBB = createBasicBlock("ehspec.cleanup.cont");
John McCallff8e1152010-07-23 21:56:41 +00001040 EmitBranchThroughEHCleanup(UnwindDest(CleanupContBB, EHStack.stable_end(),
1041 EHStack.getNextEHDestIndex()));
John McCallf1549f62010-07-06 01:34:17 +00001042 EmitBlock(CleanupContBB);
1043
1044 if (HasEHCleanup)
1045 SavedSelection = Builder.CreateLoad(SelectorVar, "ehspec.saved-selector");
1046 }
1047
1048 // If there was a cleanup, we'll need to actually check whether we
1049 // landed here because the filter triggered.
1050 if (UseInvokeInlineHack || HasEHCleanup) {
1051 llvm::BasicBlock *RethrowBB = createBasicBlock("cleanup");
1052 llvm::BasicBlock *UnexpectedBB = createBasicBlock("ehspec.unexpected");
1053
1054 llvm::Constant *Zero = llvm::ConstantInt::get(Builder.getInt32Ty(), 0);
1055 llvm::Value *FailsFilter =
1056 Builder.CreateICmpSLT(SavedSelection, Zero, "ehspec.fails");
1057 Builder.CreateCondBr(FailsFilter, UnexpectedBB, RethrowBB);
1058
1059 // The rethrow block is where we land if this was a cleanup.
1060 // TODO: can this be _Unwind_Resume if the InvokeInlineHack is off?
1061 EmitBlock(RethrowBB);
1062 Builder.CreateCall(getUnwindResumeOrRethrowFn(),
1063 Builder.CreateLoad(getExceptionSlot()))
1064 ->setDoesNotReturn();
1065 Builder.CreateUnreachable();
1066
1067 EmitBlock(UnexpectedBB);
1068 }
1069
1070 // Call __cxa_call_unexpected. This doesn't need to be an invoke
1071 // because __cxa_call_unexpected magically filters exceptions
1072 // according to the last landing pad the exception was thrown
1073 // into. Seriously.
1074 Builder.CreateCall(getUnexpectedFn(*this),
1075 Builder.CreateLoad(getExceptionSlot()))
1076 ->setDoesNotReturn();
1077 Builder.CreateUnreachable();
1078
1079 // ...or a normal catch handler...
1080 } else if (!UseInvokeInlineHack && !HasEHCleanup) {
1081 llvm::Value *Type = EHSelector.back();
1082 EmitBranchThroughEHCleanup(EHHandlers[Type]);
1083
1084 // ...or a cleanup.
1085 } else {
John McCallff8e1152010-07-23 21:56:41 +00001086 EmitBranchThroughEHCleanup(getRethrowDest());
John McCallf1549f62010-07-06 01:34:17 +00001087 }
1088
1089 // Restore the old IR generation state.
1090 Builder.restoreIP(SavedIP);
1091
1092 return LP;
1093}
1094
John McCall8e3f8612010-07-13 22:12:14 +00001095namespace {
1096 /// A cleanup to call __cxa_end_catch. In many cases, the caught
1097 /// exception type lets us state definitively that the thrown exception
1098 /// type does not have a destructor. In particular:
1099 /// - Catch-alls tell us nothing, so we have to conservatively
1100 /// assume that the thrown exception might have a destructor.
1101 /// - Catches by reference behave according to their base types.
1102 /// - Catches of non-record types will only trigger for exceptions
1103 /// of non-record types, which never have destructors.
1104 /// - Catches of record types can trigger for arbitrary subclasses
1105 /// of the caught type, so we have to assume the actual thrown
1106 /// exception type might have a throwing destructor, even if the
1107 /// caught type's destructor is trivial or nothrow.
John McCall1f0fca52010-07-21 07:22:38 +00001108 struct CallEndCatch : EHScopeStack::Cleanup {
John McCall8e3f8612010-07-13 22:12:14 +00001109 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
1110 bool MightThrow;
1111
1112 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1113 if (!MightThrow) {
1114 CGF.Builder.CreateCall(getEndCatchFn(CGF))->setDoesNotThrow();
1115 return;
1116 }
1117
1118 CGF.EmitCallOrInvoke(getEndCatchFn(CGF), 0, 0);
1119 }
1120 };
1121}
1122
John McCallf1549f62010-07-06 01:34:17 +00001123/// Emits a call to __cxa_begin_catch and enters a cleanup to call
1124/// __cxa_end_catch.
John McCall8e3f8612010-07-13 22:12:14 +00001125///
1126/// \param EndMightThrow - true if __cxa_end_catch might throw
1127static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
1128 llvm::Value *Exn,
1129 bool EndMightThrow) {
John McCallf1549f62010-07-06 01:34:17 +00001130 llvm::CallInst *Call = CGF.Builder.CreateCall(getBeginCatchFn(CGF), Exn);
1131 Call->setDoesNotThrow();
1132
John McCall1f0fca52010-07-21 07:22:38 +00001133 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
John McCallf1549f62010-07-06 01:34:17 +00001134
1135 return Call;
1136}
1137
1138/// A "special initializer" callback for initializing a catch
1139/// parameter during catch initialization.
1140static void InitCatchParam(CodeGenFunction &CGF,
1141 const VarDecl &CatchParam,
1142 llvm::Value *ParamAddr) {
1143 // Load the exception from where the landing pad saved it.
1144 llvm::Value *Exn = CGF.Builder.CreateLoad(CGF.getExceptionSlot(), "exn");
1145
1146 CanQualType CatchType =
1147 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
1148 const llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
1149
1150 // If we're catching by reference, we can just cast the object
1151 // pointer to the appropriate pointer.
1152 if (isa<ReferenceType>(CatchType)) {
John McCall204b0752010-07-20 22:17:55 +00001153 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
1154 bool EndCatchMightThrow = CaughtType->isRecordType();
John McCall8e3f8612010-07-13 22:12:14 +00001155
John McCallf1549f62010-07-06 01:34:17 +00001156 // __cxa_begin_catch returns the adjusted object pointer.
John McCall8e3f8612010-07-13 22:12:14 +00001157 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
John McCall204b0752010-07-20 22:17:55 +00001158
1159 // We have no way to tell the personality function that we're
1160 // catching by reference, so if we're catching a pointer,
1161 // __cxa_begin_catch will actually return that pointer by value.
1162 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
1163 QualType PointeeType = PT->getPointeeType();
1164
1165 // When catching by reference, generally we should just ignore
1166 // this by-value pointer and use the exception object instead.
1167 if (!PointeeType->isRecordType()) {
1168
1169 // Exn points to the struct _Unwind_Exception header, which
1170 // we have to skip past in order to reach the exception data.
1171 unsigned HeaderSize =
1172 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
1173 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
1174
1175 // However, if we're catching a pointer-to-record type that won't
1176 // work, because the personality function might have adjusted
1177 // the pointer. There's actually no way for us to fully satisfy
1178 // the language/ABI contract here: we can't use Exn because it
1179 // might have the wrong adjustment, but we can't use the by-value
1180 // pointer because it's off by a level of abstraction.
1181 //
1182 // The current solution is to dump the adjusted pointer into an
1183 // alloca, which breaks language semantics (because changing the
1184 // pointer doesn't change the exception) but at least works.
1185 // The better solution would be to filter out non-exact matches
1186 // and rethrow them, but this is tricky because the rethrow
1187 // really needs to be catchable by other sites at this landing
1188 // pad. The best solution is to fix the personality function.
1189 } else {
1190 // Pull the pointer for the reference type off.
1191 const llvm::Type *PtrTy =
1192 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
1193
1194 // Create the temporary and write the adjusted pointer into it.
1195 llvm::Value *ExnPtrTmp = CGF.CreateTempAlloca(PtrTy, "exn.byref.tmp");
1196 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1197 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
1198
1199 // Bind the reference to the temporary.
1200 AdjustedExn = ExnPtrTmp;
1201 }
1202 }
1203
John McCallf1549f62010-07-06 01:34:17 +00001204 llvm::Value *ExnCast =
1205 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
1206 CGF.Builder.CreateStore(ExnCast, ParamAddr);
1207 return;
1208 }
1209
1210 // Non-aggregates (plus complexes).
1211 bool IsComplex = false;
1212 if (!CGF.hasAggregateLLVMType(CatchType) ||
1213 (IsComplex = CatchType->isAnyComplexType())) {
John McCall8e3f8612010-07-13 22:12:14 +00001214 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
John McCallf1549f62010-07-06 01:34:17 +00001215
1216 // If the catch type is a pointer type, __cxa_begin_catch returns
1217 // the pointer by value.
1218 if (CatchType->hasPointerRepresentation()) {
1219 llvm::Value *CastExn =
1220 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
1221 CGF.Builder.CreateStore(CastExn, ParamAddr);
1222 return;
1223 }
1224
1225 // Otherwise, it returns a pointer into the exception object.
1226
1227 const llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
1228 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1229
1230 if (IsComplex) {
1231 CGF.StoreComplexToAddr(CGF.LoadComplexFromAddr(Cast, /*volatile*/ false),
1232 ParamAddr, /*volatile*/ false);
1233 } else {
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001234 unsigned Alignment =
1235 CGF.getContext().getDeclAlign(&CatchParam).getQuantity();
John McCallf1549f62010-07-06 01:34:17 +00001236 llvm::Value *ExnLoad = CGF.Builder.CreateLoad(Cast, "exn.scalar");
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001237 CGF.EmitStoreOfScalar(ExnLoad, ParamAddr, /*volatile*/ false, Alignment,
1238 CatchType);
John McCallf1549f62010-07-06 01:34:17 +00001239 }
1240 return;
1241 }
1242
1243 // FIXME: this *really* needs to be done via a proper, Sema-emitted
1244 // initializer expression.
1245
1246 CXXRecordDecl *RD = CatchType.getTypePtr()->getAsCXXRecordDecl();
1247 assert(RD && "aggregate catch type was not a record!");
1248
1249 const llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
1250
1251 if (RD->hasTrivialCopyConstructor()) {
John McCall8e3f8612010-07-13 22:12:14 +00001252 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, true);
John McCallf1549f62010-07-06 01:34:17 +00001253 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1254 CGF.EmitAggregateCopy(ParamAddr, Cast, CatchType);
1255 return;
1256 }
1257
1258 // We have to call __cxa_get_exception_ptr to get the adjusted
1259 // pointer before copying.
1260 llvm::CallInst *AdjustedExn =
1261 CGF.Builder.CreateCall(getGetExceptionPtrFn(CGF), Exn);
1262 AdjustedExn->setDoesNotThrow();
1263 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1264
1265 CXXConstructorDecl *CD = RD->getCopyConstructor(CGF.getContext(), 0);
1266 assert(CD && "record has no copy constructor!");
1267 llvm::Value *CopyCtor = CGF.CGM.GetAddrOfCXXConstructor(CD, Ctor_Complete);
1268
1269 CallArgList CallArgs;
1270 CallArgs.push_back(std::make_pair(RValue::get(ParamAddr),
1271 CD->getThisType(CGF.getContext())));
1272 CallArgs.push_back(std::make_pair(RValue::get(Cast),
1273 CD->getParamDecl(0)->getType()));
1274
1275 const FunctionProtoType *FPT
1276 = CD->getType()->getAs<FunctionProtoType>();
1277
1278 // Call the copy ctor in a terminate scope.
1279 CGF.EHStack.pushTerminate();
1280 CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(CallArgs, FPT),
1281 CopyCtor, ReturnValueSlot(), CallArgs, CD);
1282 CGF.EHStack.popTerminate();
1283
1284 // Finally we can call __cxa_begin_catch.
John McCall8e3f8612010-07-13 22:12:14 +00001285 CallBeginCatch(CGF, Exn, true);
John McCallf1549f62010-07-06 01:34:17 +00001286}
1287
1288/// Begins a catch statement by initializing the catch variable and
1289/// calling __cxa_begin_catch.
1290static void BeginCatch(CodeGenFunction &CGF,
1291 const CXXCatchStmt *S) {
1292 // We have to be very careful with the ordering of cleanups here:
1293 // C++ [except.throw]p4:
1294 // The destruction [of the exception temporary] occurs
1295 // immediately after the destruction of the object declared in
1296 // the exception-declaration in the handler.
1297 //
1298 // So the precise ordering is:
1299 // 1. Construct catch variable.
1300 // 2. __cxa_begin_catch
1301 // 3. Enter __cxa_end_catch cleanup
1302 // 4. Enter dtor cleanup
1303 //
1304 // We do this by initializing the exception variable with a
1305 // "special initializer", InitCatchParam. Delegation sequence:
1306 // - ExitCXXTryStmt opens a RunCleanupsScope
1307 // - EmitLocalBlockVarDecl creates the variable and debug info
1308 // - InitCatchParam initializes the variable from the exception
1309 // - CallBeginCatch calls __cxa_begin_catch
1310 // - CallBeginCatch enters the __cxa_end_catch cleanup
1311 // - EmitLocalBlockVarDecl enters the variable destructor cleanup
1312 // - EmitCXXTryStmt emits the code for the catch body
1313 // - EmitCXXTryStmt close the RunCleanupsScope
1314
1315 VarDecl *CatchParam = S->getExceptionDecl();
1316 if (!CatchParam) {
1317 llvm::Value *Exn = CGF.Builder.CreateLoad(CGF.getExceptionSlot(), "exn");
John McCall8e3f8612010-07-13 22:12:14 +00001318 CallBeginCatch(CGF, Exn, true);
John McCallf1549f62010-07-06 01:34:17 +00001319 return;
1320 }
1321
1322 // Emit the local.
John McCallb6bbcc92010-10-15 04:57:14 +00001323 CGF.EmitAutoVarDecl(*CatchParam, &InitCatchParam);
John McCall9fc6a772010-02-19 09:25:03 +00001324}
1325
John McCallfcd5c0c2010-07-13 22:24:23 +00001326namespace {
John McCall1f0fca52010-07-21 07:22:38 +00001327 struct CallRethrow : EHScopeStack::Cleanup {
John McCallfcd5c0c2010-07-13 22:24:23 +00001328 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1329 CGF.EmitCallOrInvoke(getReThrowFn(CGF), 0, 0);
1330 }
1331 };
1332}
1333
John McCall59a70002010-07-07 06:56:46 +00001334void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallf1549f62010-07-06 01:34:17 +00001335 unsigned NumHandlers = S.getNumHandlers();
1336 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1337 assert(CatchScope.getNumHandlers() == NumHandlers);
Mike Stump2bf701e2009-11-20 23:44:51 +00001338
John McCallf1549f62010-07-06 01:34:17 +00001339 // Copy the handler blocks off before we pop the EH stack. Emitting
1340 // the handlers might scribble on this memory.
1341 llvm::SmallVector<EHCatchScope::Handler, 8> Handlers(NumHandlers);
1342 memcpy(Handlers.data(), CatchScope.begin(),
1343 NumHandlers * sizeof(EHCatchScope::Handler));
1344 EHStack.popCatch();
Mike Stump2bf701e2009-11-20 23:44:51 +00001345
John McCallf1549f62010-07-06 01:34:17 +00001346 // The fall-through block.
1347 llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
Mike Stump2bf701e2009-11-20 23:44:51 +00001348
John McCallf1549f62010-07-06 01:34:17 +00001349 // We just emitted the body of the try; jump to the continue block.
1350 if (HaveInsertPoint())
1351 Builder.CreateBr(ContBB);
Mike Stump639787c2009-12-02 19:53:57 +00001352
John McCall59a70002010-07-07 06:56:46 +00001353 // Determine if we need an implicit rethrow for all these catch handlers.
1354 bool ImplicitRethrow = false;
1355 if (IsFnTryBlock)
1356 ImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
1357 isa<CXXConstructorDecl>(CurCodeDecl);
1358
John McCallf1549f62010-07-06 01:34:17 +00001359 for (unsigned I = 0; I != NumHandlers; ++I) {
1360 llvm::BasicBlock *CatchBlock = Handlers[I].Block;
1361 EmitBlock(CatchBlock);
Mike Stump8755ec32009-12-10 00:06:18 +00001362
John McCallf1549f62010-07-06 01:34:17 +00001363 // Catch the exception if this isn't a catch-all.
1364 const CXXCatchStmt *C = S.getHandler(I);
Mike Stump2bf701e2009-11-20 23:44:51 +00001365
John McCallf1549f62010-07-06 01:34:17 +00001366 // Enter a cleanup scope, including the catch variable and the
1367 // end-catch.
1368 RunCleanupsScope CatchScope(*this);
Mike Stump2bf701e2009-11-20 23:44:51 +00001369
John McCallf1549f62010-07-06 01:34:17 +00001370 // Initialize the catch variable and set up the cleanups.
1371 BeginCatch(*this, C);
1372
John McCall59a70002010-07-07 06:56:46 +00001373 // If there's an implicit rethrow, push a normal "cleanup" to call
John McCallfcd5c0c2010-07-13 22:24:23 +00001374 // _cxa_rethrow. This needs to happen before __cxa_end_catch is
1375 // called, and so it is pushed after BeginCatch.
1376 if (ImplicitRethrow)
John McCall1f0fca52010-07-21 07:22:38 +00001377 EHStack.pushCleanup<CallRethrow>(NormalCleanup);
John McCall59a70002010-07-07 06:56:46 +00001378
John McCallf1549f62010-07-06 01:34:17 +00001379 // Perform the body of the catch.
1380 EmitStmt(C->getHandlerBlock());
1381
1382 // Fall out through the catch cleanups.
1383 CatchScope.ForceCleanup();
1384
1385 // Branch out of the try.
1386 if (HaveInsertPoint())
1387 Builder.CreateBr(ContBB);
Mike Stump2bf701e2009-11-20 23:44:51 +00001388 }
1389
John McCallf1549f62010-07-06 01:34:17 +00001390 EmitBlock(ContBB);
Mike Stump2bf701e2009-11-20 23:44:51 +00001391}
Mike Stumpd88ea562009-12-09 03:35:49 +00001392
John McCall55b20fc2010-07-21 00:52:03 +00001393namespace {
John McCall1f0fca52010-07-21 07:22:38 +00001394 struct CallEndCatchForFinally : EHScopeStack::Cleanup {
John McCall55b20fc2010-07-21 00:52:03 +00001395 llvm::Value *ForEHVar;
1396 llvm::Value *EndCatchFn;
1397 CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn)
1398 : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
1399
1400 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1401 llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
1402 llvm::BasicBlock *CleanupContBB =
1403 CGF.createBasicBlock("finally.cleanup.cont");
1404
1405 llvm::Value *ShouldEndCatch =
1406 CGF.Builder.CreateLoad(ForEHVar, "finally.endcatch");
1407 CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1408 CGF.EmitBlock(EndCatchBB);
1409 CGF.EmitCallOrInvoke(EndCatchFn, 0, 0); // catch-all, so might throw
1410 CGF.EmitBlock(CleanupContBB);
1411 }
1412 };
John McCall77199712010-07-21 05:47:49 +00001413
John McCall1f0fca52010-07-21 07:22:38 +00001414 struct PerformFinally : EHScopeStack::Cleanup {
John McCall77199712010-07-21 05:47:49 +00001415 const Stmt *Body;
1416 llvm::Value *ForEHVar;
1417 llvm::Value *EndCatchFn;
1418 llvm::Value *RethrowFn;
1419 llvm::Value *SavedExnVar;
1420
1421 PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
1422 llvm::Value *EndCatchFn,
1423 llvm::Value *RethrowFn, llvm::Value *SavedExnVar)
1424 : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1425 RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
1426
1427 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1428 // Enter a cleanup to call the end-catch function if one was provided.
1429 if (EndCatchFn)
John McCall1f0fca52010-07-21 07:22:38 +00001430 CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
1431 ForEHVar, EndCatchFn);
John McCall77199712010-07-21 05:47:49 +00001432
John McCalld96a8e72010-08-11 00:16:14 +00001433 // Save the current cleanup destination in case there are
1434 // cleanups in the finally block.
1435 llvm::Value *SavedCleanupDest =
1436 CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
1437 "cleanup.dest.saved");
1438
John McCall77199712010-07-21 05:47:49 +00001439 // Emit the finally block.
1440 CGF.EmitStmt(Body);
1441
1442 // If the end of the finally is reachable, check whether this was
1443 // for EH. If so, rethrow.
1444 if (CGF.HaveInsertPoint()) {
1445 llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
1446 llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
1447
1448 llvm::Value *ShouldRethrow =
1449 CGF.Builder.CreateLoad(ForEHVar, "finally.shouldthrow");
1450 CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1451
1452 CGF.EmitBlock(RethrowBB);
1453 if (SavedExnVar) {
1454 llvm::Value *Args[] = { CGF.Builder.CreateLoad(SavedExnVar) };
1455 CGF.EmitCallOrInvoke(RethrowFn, Args, Args+1);
1456 } else {
1457 CGF.EmitCallOrInvoke(RethrowFn, 0, 0);
1458 }
1459 CGF.Builder.CreateUnreachable();
1460
1461 CGF.EmitBlock(ContBB);
John McCalld96a8e72010-08-11 00:16:14 +00001462
1463 // Restore the cleanup destination.
1464 CGF.Builder.CreateStore(SavedCleanupDest,
1465 CGF.getNormalCleanupDestSlot());
John McCall77199712010-07-21 05:47:49 +00001466 }
1467
1468 // Leave the end-catch cleanup. As an optimization, pretend that
1469 // the fallthrough path was inaccessible; we've dynamically proven
1470 // that we're not in the EH case along that path.
1471 if (EndCatchFn) {
1472 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1473 CGF.PopCleanupBlock();
1474 CGF.Builder.restoreIP(SavedIP);
1475 }
1476
1477 // Now make sure we actually have an insertion point or the
1478 // cleanup gods will hate us.
1479 CGF.EnsureInsertPoint();
1480 }
1481 };
John McCall55b20fc2010-07-21 00:52:03 +00001482}
1483
John McCallf1549f62010-07-06 01:34:17 +00001484/// Enters a finally block for an implementation using zero-cost
1485/// exceptions. This is mostly general, but hard-codes some
1486/// language/ABI-specific behavior in the catch-all sections.
1487CodeGenFunction::FinallyInfo
1488CodeGenFunction::EnterFinallyBlock(const Stmt *Body,
1489 llvm::Constant *BeginCatchFn,
1490 llvm::Constant *EndCatchFn,
1491 llvm::Constant *RethrowFn) {
1492 assert((BeginCatchFn != 0) == (EndCatchFn != 0) &&
1493 "begin/end catch functions not paired");
1494 assert(RethrowFn && "rethrow function is required");
Mike Stumpd88ea562009-12-09 03:35:49 +00001495
John McCallf1549f62010-07-06 01:34:17 +00001496 // The rethrow function has one of the following two types:
1497 // void (*)()
1498 // void (*)(void*)
1499 // In the latter case we need to pass it the exception object.
1500 // But we can't use the exception slot because the @finally might
1501 // have a landing pad (which would overwrite the exception slot).
1502 const llvm::FunctionType *RethrowFnTy =
1503 cast<llvm::FunctionType>(
1504 cast<llvm::PointerType>(RethrowFn->getType())
1505 ->getElementType());
1506 llvm::Value *SavedExnVar = 0;
1507 if (RethrowFnTy->getNumParams())
1508 SavedExnVar = CreateTempAlloca(Builder.getInt8PtrTy(), "finally.exn");
Mike Stumpd88ea562009-12-09 03:35:49 +00001509
John McCallf1549f62010-07-06 01:34:17 +00001510 // A finally block is a statement which must be executed on any edge
1511 // out of a given scope. Unlike a cleanup, the finally block may
1512 // contain arbitrary control flow leading out of itself. In
1513 // addition, finally blocks should always be executed, even if there
1514 // are no catch handlers higher on the stack. Therefore, we
1515 // surround the protected scope with a combination of a normal
1516 // cleanup (to catch attempts to break out of the block via normal
1517 // control flow) and an EH catch-all (semantically "outside" any try
1518 // statement to which the finally block might have been attached).
1519 // The finally block itself is generated in the context of a cleanup
1520 // which conditionally leaves the catch-all.
John McCall3d3ec1c2010-04-21 10:05:39 +00001521
John McCallf1549f62010-07-06 01:34:17 +00001522 FinallyInfo Info;
John McCall3d3ec1c2010-04-21 10:05:39 +00001523
John McCallf1549f62010-07-06 01:34:17 +00001524 // Jump destination for performing the finally block on an exception
1525 // edge. We'll never actually reach this block, so unreachable is
1526 // fine.
1527 JumpDest RethrowDest = getJumpDestInCurrentScope(getUnreachableBlock());
John McCall3d3ec1c2010-04-21 10:05:39 +00001528
John McCallf1549f62010-07-06 01:34:17 +00001529 // Whether the finally block is being executed for EH purposes.
1530 llvm::AllocaInst *ForEHVar = CreateTempAlloca(CGF.Builder.getInt1Ty(),
1531 "finally.for-eh");
1532 InitTempAlloca(ForEHVar, llvm::ConstantInt::getFalse(getLLVMContext()));
Mike Stumpd88ea562009-12-09 03:35:49 +00001533
John McCallf1549f62010-07-06 01:34:17 +00001534 // Enter a normal cleanup which will perform the @finally block.
John McCall1f0fca52010-07-21 07:22:38 +00001535 EHStack.pushCleanup<PerformFinally>(NormalCleanup, Body,
1536 ForEHVar, EndCatchFn,
1537 RethrowFn, SavedExnVar);
John McCallf1549f62010-07-06 01:34:17 +00001538
1539 // Enter a catch-all scope.
1540 llvm::BasicBlock *CatchAllBB = createBasicBlock("finally.catchall");
1541 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1542 Builder.SetInsertPoint(CatchAllBB);
1543
1544 // If there's a begin-catch function, call it.
1545 if (BeginCatchFn) {
1546 Builder.CreateCall(BeginCatchFn, Builder.CreateLoad(getExceptionSlot()))
1547 ->setDoesNotThrow();
1548 }
1549
1550 // If we need to remember the exception pointer to rethrow later, do so.
1551 if (SavedExnVar) {
1552 llvm::Value *SavedExn = Builder.CreateLoad(getExceptionSlot());
1553 Builder.CreateStore(SavedExn, SavedExnVar);
1554 }
1555
1556 // Tell the finally block that we're in EH.
1557 Builder.CreateStore(llvm::ConstantInt::getTrue(getLLVMContext()), ForEHVar);
1558
1559 // Thread a jump through the finally cleanup.
1560 EmitBranchThroughCleanup(RethrowDest);
1561
1562 Builder.restoreIP(SavedIP);
1563
1564 EHCatchScope *CatchScope = EHStack.pushCatch(1);
1565 CatchScope->setCatchAllHandler(0, CatchAllBB);
1566
1567 return Info;
1568}
1569
1570void CodeGenFunction::ExitFinallyBlock(FinallyInfo &Info) {
1571 // Leave the finally catch-all.
1572 EHCatchScope &Catch = cast<EHCatchScope>(*EHStack.begin());
1573 llvm::BasicBlock *CatchAllBB = Catch.getHandler(0).Block;
1574 EHStack.popCatch();
1575
1576 // And leave the normal cleanup.
1577 PopCleanupBlock();
1578
1579 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1580 EmitBlock(CatchAllBB, true);
1581
1582 Builder.restoreIP(SavedIP);
1583}
1584
1585llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
1586 if (TerminateLandingPad)
1587 return TerminateLandingPad;
1588
1589 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1590
1591 // This will get inserted at the end of the function.
1592 TerminateLandingPad = createBasicBlock("terminate.lpad");
1593 Builder.SetInsertPoint(TerminateLandingPad);
1594
1595 // Tell the backend that this is a landing pad.
1596 llvm::CallInst *Exn =
1597 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_exception), "exn");
1598 Exn->setDoesNotThrow();
John McCall8262b6a2010-07-17 00:43:08 +00001599
1600 const EHPersonality &Personality = EHPersonality::get(CGM.getLangOptions());
John McCallf1549f62010-07-06 01:34:17 +00001601
1602 // Tell the backend what the exception table should be:
1603 // nothing but a catch-all.
John McCallb2593832010-09-16 06:16:50 +00001604 llvm::Value *Args[3] = { Exn, getOpaquePersonalityFn(CGM, Personality),
John McCallf1549f62010-07-06 01:34:17 +00001605 getCatchAllValue(*this) };
1606 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_selector),
1607 Args, Args+3, "eh.selector")
1608 ->setDoesNotThrow();
1609
1610 llvm::CallInst *TerminateCall = Builder.CreateCall(getTerminateFn(*this));
1611 TerminateCall->setDoesNotReturn();
1612 TerminateCall->setDoesNotThrow();
Mike Stumpd88ea562009-12-09 03:35:49 +00001613 CGF.Builder.CreateUnreachable();
1614
John McCallf1549f62010-07-06 01:34:17 +00001615 // Restore the saved insertion state.
1616 Builder.restoreIP(SavedIP);
John McCall891f80e2010-04-30 00:06:43 +00001617
John McCallf1549f62010-07-06 01:34:17 +00001618 return TerminateLandingPad;
Mike Stumpd88ea562009-12-09 03:35:49 +00001619}
Mike Stump9b39c512009-12-09 22:59:31 +00001620
1621llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
Mike Stump182f3832009-12-10 00:02:42 +00001622 if (TerminateHandler)
1623 return TerminateHandler;
1624
John McCallf1549f62010-07-06 01:34:17 +00001625 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
Mike Stump76958092009-12-09 23:31:35 +00001626
John McCallf1549f62010-07-06 01:34:17 +00001627 // Set up the terminate handler. This block is inserted at the very
1628 // end of the function by FinishFunction.
Mike Stump182f3832009-12-10 00:02:42 +00001629 TerminateHandler = createBasicBlock("terminate.handler");
John McCallf1549f62010-07-06 01:34:17 +00001630 Builder.SetInsertPoint(TerminateHandler);
1631 llvm::CallInst *TerminateCall = Builder.CreateCall(getTerminateFn(*this));
Mike Stump9b39c512009-12-09 22:59:31 +00001632 TerminateCall->setDoesNotReturn();
1633 TerminateCall->setDoesNotThrow();
1634 Builder.CreateUnreachable();
1635
John McCall3d3ec1c2010-04-21 10:05:39 +00001636 // Restore the saved insertion state.
John McCallf1549f62010-07-06 01:34:17 +00001637 Builder.restoreIP(SavedIP);
Mike Stump76958092009-12-09 23:31:35 +00001638
Mike Stump9b39c512009-12-09 22:59:31 +00001639 return TerminateHandler;
1640}
John McCallf1549f62010-07-06 01:34:17 +00001641
John McCallff8e1152010-07-23 21:56:41 +00001642CodeGenFunction::UnwindDest CodeGenFunction::getRethrowDest() {
1643 if (RethrowBlock.isValid()) return RethrowBlock;
1644
1645 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1646
1647 // We emit a jump to a notional label at the outermost unwind state.
1648 llvm::BasicBlock *Unwind = createBasicBlock("eh.resume");
1649 Builder.SetInsertPoint(Unwind);
1650
1651 const EHPersonality &Personality = EHPersonality::get(CGM.getLangOptions());
1652
1653 // This can always be a call because we necessarily didn't find
1654 // anything on the EH stack which needs our help.
John McCallb2593832010-09-16 06:16:50 +00001655 llvm::StringRef RethrowName = Personality.getCatchallRethrowFnName();
John McCallff8e1152010-07-23 21:56:41 +00001656 llvm::Constant *RethrowFn;
John McCallb2593832010-09-16 06:16:50 +00001657 if (!RethrowName.empty())
John McCallff8e1152010-07-23 21:56:41 +00001658 RethrowFn = getCatchallRethrowFn(*this, RethrowName);
1659 else
1660 RethrowFn = getUnwindResumeOrRethrowFn();
1661
1662 Builder.CreateCall(RethrowFn, Builder.CreateLoad(getExceptionSlot()))
1663 ->setDoesNotReturn();
1664 Builder.CreateUnreachable();
1665
1666 Builder.restoreIP(SavedIP);
1667
1668 RethrowBlock = UnwindDest(Unwind, EHStack.stable_end(), 0);
1669 return RethrowBlock;
1670}
1671
John McCall1f0fca52010-07-21 07:22:38 +00001672EHScopeStack::Cleanup::~Cleanup() {
1673 llvm_unreachable("Cleanup is indestructable");
John McCall3e29f962010-07-13 23:19:49 +00001674}
John McCall150b4622011-01-26 04:00:11 +00001675
1676void EHScopeStack::ConditionalCleanup::Emit(CodeGenFunction &CGF,
1677 bool IsForEHCleanup) {
1678 // Determine whether we should run the cleanup.
1679 llvm::Value *condVal = CGF.Builder.CreateLoad(cond, "cond.should-run");
1680
1681 llvm::BasicBlock *cleanup = CGF.createBasicBlock("cond-cleanup.run");
1682 llvm::BasicBlock *cont = CGF.createBasicBlock("cond-cleanup.cont");
1683
1684 // If we shouldn't run the cleanup, jump directly to the continuation block.
1685 CGF.Builder.CreateCondBr(condVal, cleanup, cont);
1686 CGF.EmitBlock(cleanup);
1687
1688 // Emit the core of the cleanup.
1689 EmitImpl(CGF, IsForEHCleanup);
1690 assert(CGF.HaveInsertPoint() && "cleanup didn't end with valid IP!");
1691
1692 // Fall into the continuation block.
1693 CGF.EmitBlock(cont);
1694}