blob: 49b1ce12bc02e4819220ea211f0eb05a82c673cf [file] [log] [blame]
David Chisnall9735ca62011-03-25 11:57:33 +00001//==- CGObjCRuntime.cpp - Interface to Shared Objective-C Runtime Features ==//
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 abstract class defines the interface for Objective-C runtime-specific
11// code generation. It provides some concrete helper methods for functionality
12// shared between all (or most) of the Objective-C runtimes supported by clang.
13//
14//===----------------------------------------------------------------------===//
15
16#include "CGObjCRuntime.h"
17
18#include "CGRecordLayout.h"
19#include "CodeGenModule.h"
20#include "CodeGenFunction.h"
21#include "CGCleanup.h"
22
23#include "clang/AST/RecordLayout.h"
24#include "clang/AST/StmtObjC.h"
25
26#include "llvm/Support/CallSite.h"
27
28using namespace clang;
29using namespace CodeGen;
30
31static uint64_t LookupFieldBitOffset(CodeGen::CodeGenModule &CGM,
32 const ObjCInterfaceDecl *OID,
33 const ObjCImplementationDecl *ID,
34 const ObjCIvarDecl *Ivar) {
35 const ObjCInterfaceDecl *Container = Ivar->getContainingInterface();
36
37 // FIXME: We should eliminate the need to have ObjCImplementationDecl passed
38 // in here; it should never be necessary because that should be the lexical
39 // decl context for the ivar.
40
41 // If we know have an implementation (and the ivar is in it) then
42 // look up in the implementation layout.
43 const ASTRecordLayout *RL;
44 if (ID && ID->getClassInterface() == Container)
45 RL = &CGM.getContext().getASTObjCImplementationLayout(ID);
46 else
47 RL = &CGM.getContext().getASTObjCInterfaceLayout(Container);
48
49 // Compute field index.
50 //
51 // FIXME: The index here is closely tied to how ASTContext::getObjCLayout is
52 // implemented. This should be fixed to get the information from the layout
53 // directly.
54 unsigned Index = 0;
55 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars;
56 CGM.getContext().ShallowCollectObjCIvars(Container, Ivars);
57 for (unsigned k = 0, e = Ivars.size(); k != e; ++k) {
58 if (Ivar == Ivars[k])
59 break;
60 ++Index;
61 }
62 assert(Index != Ivars.size() && "Ivar is not inside container!");
63 assert(Index < RL->getFieldCount() && "Ivar is not inside record layout!");
64
65 return RL->getFieldOffset(Index);
66}
67
68uint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM,
69 const ObjCInterfaceDecl *OID,
70 const ObjCIvarDecl *Ivar) {
71 return LookupFieldBitOffset(CGM, OID, 0, Ivar) / 8;
72}
73
74uint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM,
75 const ObjCImplementationDecl *OID,
76 const ObjCIvarDecl *Ivar) {
77 return LookupFieldBitOffset(CGM, OID->getClassInterface(), OID, Ivar) / 8;
78}
79
80LValue CGObjCRuntime::EmitValueForIvarAtOffset(CodeGen::CodeGenFunction &CGF,
81 const ObjCInterfaceDecl *OID,
82 llvm::Value *BaseValue,
83 const ObjCIvarDecl *Ivar,
84 unsigned CVRQualifiers,
85 llvm::Value *Offset) {
86 // Compute (type*) ( (char *) BaseValue + Offset)
87 const llvm::Type *I8Ptr = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
88 QualType IvarTy = Ivar->getType();
89 const llvm::Type *LTy = CGF.CGM.getTypes().ConvertTypeForMem(IvarTy);
90 llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue, I8Ptr);
91 V = CGF.Builder.CreateInBoundsGEP(V, Offset, "add.ptr");
92 V = CGF.Builder.CreateBitCast(V, llvm::PointerType::getUnqual(LTy));
93
94 if (!Ivar->isBitField()) {
95 LValue LV = CGF.MakeAddrLValue(V, IvarTy);
96 LV.getQuals().addCVRQualifiers(CVRQualifiers);
97 return LV;
98 }
99
100 // We need to compute an access strategy for this bit-field. We are given the
101 // offset to the first byte in the bit-field, the sub-byte offset is taken
102 // from the original layout. We reuse the normal bit-field access strategy by
103 // treating this as an access to a struct where the bit-field is in byte 0,
104 // and adjust the containing type size as appropriate.
105 //
106 // FIXME: Note that currently we make a very conservative estimate of the
107 // alignment of the bit-field, because (a) it is not clear what guarantees the
108 // runtime makes us, and (b) we don't have a way to specify that the struct is
109 // at an alignment plus offset.
110 //
111 // Note, there is a subtle invariant here: we can only call this routine on
112 // non-synthesized ivars but we may be called for synthesized ivars. However,
113 // a synthesized ivar can never be a bit-field, so this is safe.
114 const ASTRecordLayout &RL =
115 CGF.CGM.getContext().getASTObjCInterfaceLayout(OID);
116 uint64_t TypeSizeInBits = CGF.CGM.getContext().toBits(RL.getSize());
117 uint64_t FieldBitOffset = LookupFieldBitOffset(CGF.CGM, OID, 0, Ivar);
118 uint64_t BitOffset = FieldBitOffset % 8;
119 uint64_t ContainingTypeAlign = 8;
120 uint64_t ContainingTypeSize = TypeSizeInBits - (FieldBitOffset - BitOffset);
121 uint64_t BitFieldSize =
122 Ivar->getBitWidth()->EvaluateAsInt(CGF.getContext()).getZExtValue();
123
124 // Allocate a new CGBitFieldInfo object to describe this access.
125 //
126 // FIXME: This is incredibly wasteful, these should be uniqued or part of some
127 // layout object. However, this is blocked on other cleanups to the
128 // Objective-C code, so for now we just live with allocating a bunch of these
129 // objects.
130 CGBitFieldInfo *Info = new (CGF.CGM.getContext()) CGBitFieldInfo(
131 CGBitFieldInfo::MakeInfo(CGF.CGM.getTypes(), Ivar, BitOffset, BitFieldSize,
132 ContainingTypeSize, ContainingTypeAlign));
133
134 return LValue::MakeBitfield(V, *Info,
135 IvarTy.getCVRQualifiers() | CVRQualifiers);
136}
137
138namespace {
139 struct CatchHandler {
140 const VarDecl *Variable;
141 const Stmt *Body;
142 llvm::BasicBlock *Block;
143 llvm::Value *TypeInfo;
144 };
145
146 struct CallObjCEndCatch : EHScopeStack::Cleanup {
147 CallObjCEndCatch(bool MightThrow, llvm::Value *Fn) :
148 MightThrow(MightThrow), Fn(Fn) {}
149 bool MightThrow;
150 llvm::Value *Fn;
151
152 void Emit(CodeGenFunction &CGF, bool IsForEH) {
153 if (!MightThrow) {
154 CGF.Builder.CreateCall(Fn)->setDoesNotThrow();
155 return;
156 }
157
158 CGF.EmitCallOrInvoke(Fn, 0, 0);
159 }
160 };
161}
162
163
164void CGObjCRuntime::EmitTryCatchStmt(CodeGenFunction &CGF,
165 const ObjCAtTryStmt &S,
166 llvm::Function *beginCatchFn,
167 llvm::Function *endCatchFn,
168 llvm::Function *exceptionRethrowFn) {
169 // Jump destination for falling out of catch bodies.
170 CodeGenFunction::JumpDest Cont;
171 if (S.getNumCatchStmts())
172 Cont = CGF.getJumpDestInCurrentScope("eh.cont");
173
174 CodeGenFunction::FinallyInfo FinallyInfo;
175 if (const ObjCAtFinallyStmt *Finally = S.getFinallyStmt())
176 FinallyInfo = CGF.EnterFinallyBlock(Finally->getFinallyBody(),
177 beginCatchFn,
178 endCatchFn,
179 exceptionRethrowFn);
180
181 llvm::SmallVector<CatchHandler, 8> Handlers;
182
183 // Enter the catch, if there is one.
184 if (S.getNumCatchStmts()) {
185 for (unsigned I = 0, N = S.getNumCatchStmts(); I != N; ++I) {
186 const ObjCAtCatchStmt *CatchStmt = S.getCatchStmt(I);
187 const VarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
188
189 Handlers.push_back(CatchHandler());
190 CatchHandler &Handler = Handlers.back();
191 Handler.Variable = CatchDecl;
192 Handler.Body = CatchStmt->getCatchBody();
193 Handler.Block = CGF.createBasicBlock("catch");
194
195 // @catch(...) always matches.
196 if (!CatchDecl) {
197 Handler.TypeInfo = 0; // catch-all
198 // Don't consider any other catches.
199 break;
200 }
201
202 Handler.TypeInfo = GetEHType(CatchDecl->getType());
203 }
204
205 EHCatchScope *Catch = CGF.EHStack.pushCatch(Handlers.size());
206 for (unsigned I = 0, E = Handlers.size(); I != E; ++I)
207 Catch->setHandler(I, Handlers[I].TypeInfo, Handlers[I].Block);
208 }
209
210 // Emit the try body.
211 CGF.EmitStmt(S.getTryBody());
212
213 // Leave the try.
214 if (S.getNumCatchStmts())
215 CGF.EHStack.popCatch();
216
217 // Remember where we were.
218 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
219
220 // Emit the handlers.
221 for (unsigned I = 0, E = Handlers.size(); I != E; ++I) {
222 CatchHandler &Handler = Handlers[I];
223
224 CGF.EmitBlock(Handler.Block);
225 llvm::Value *RawExn = CGF.Builder.CreateLoad(CGF.getExceptionSlot());
226
227 // Enter the catch.
228 llvm::Value *Exn = RawExn;
229 if (beginCatchFn) {
230 Exn = CGF.Builder.CreateCall(beginCatchFn, RawExn, "exn.adjusted");
231 cast<llvm::CallInst>(Exn)->setDoesNotThrow();
232 }
233
234 if (endCatchFn) {
235 // Add a cleanup to leave the catch.
236 bool EndCatchMightThrow = (Handler.Variable == 0);
237
238 CGF.EHStack.pushCleanup<CallObjCEndCatch>(NormalAndEHCleanup,
239 EndCatchMightThrow,
240 endCatchFn);
241 }
242
243 // Bind the catch parameter if it exists.
244 if (const VarDecl *CatchParam = Handler.Variable) {
245 const llvm::Type *CatchType = CGF.ConvertType(CatchParam->getType());
246 llvm::Value *CastExn = CGF.Builder.CreateBitCast(Exn, CatchType);
247
248 CGF.EmitAutoVarDecl(*CatchParam);
249 CGF.Builder.CreateStore(CastExn, CGF.GetAddrOfLocalVar(CatchParam));
250 }
251
252 CGF.ObjCEHValueStack.push_back(Exn);
253 CGF.EmitStmt(Handler.Body);
254 CGF.ObjCEHValueStack.pop_back();
255
256 // Leave the earlier cleanup.
257 if (endCatchFn)
258 CGF.PopCleanupBlock();
259
260 CGF.EmitBranchThroughCleanup(Cont);
261 }
262
263 // Go back to the try-statement fallthrough.
264 CGF.Builder.restoreIP(SavedIP);
265
266 // Pop out of the normal cleanup on the finally.
267 if (S.getFinallyStmt())
268 CGF.ExitFinallyBlock(FinallyInfo);
269
270 if (Cont.isValid())
271 CGF.EmitBlock(Cont.getBlock());
272}
273
274namespace {
275 struct CallSyncExit : EHScopeStack::Cleanup {
276 llvm::Value *SyncExitFn;
277 llvm::Value *SyncArg;
278 CallSyncExit(llvm::Value *SyncExitFn, llvm::Value *SyncArg)
279 : SyncExitFn(SyncExitFn), SyncArg(SyncArg) {}
280
281 void Emit(CodeGenFunction &CGF, bool IsForEHCleanup) {
282 CGF.Builder.CreateCall(SyncExitFn, SyncArg)->setDoesNotThrow();
283 }
284 };
285}
286
287void CGObjCRuntime::EmitAtSynchronizedStmt(CodeGenFunction &CGF,
288 const ObjCAtSynchronizedStmt &S,
289 llvm::Function *syncEnterFn,
290 llvm::Function *syncExitFn) {
291 // Evaluate the lock operand. This should dominate the cleanup.
292 llvm::Value *SyncArg =
293 CGF.EmitScalarExpr(S.getSynchExpr());
294
295 // Acquire the lock.
296 SyncArg = CGF.Builder.CreateBitCast(SyncArg, syncEnterFn->getFunctionType()->getParamType(0));
297 CGF.Builder.CreateCall(syncEnterFn, SyncArg);
298
299 // Register an all-paths cleanup to release the lock.
300 CGF.EHStack.pushCleanup<CallSyncExit>(NormalAndEHCleanup, syncExitFn,
301 SyncArg);
302
303 // Emit the body of the statement.
304 CGF.EmitStmt(S.getSynchBody());
305
306 // Pop the lock-release cleanup.
307 CGF.PopCleanupBlock();
308}