blob: 93700960df230b82a10faebefcc5ec81f0ec1d20 [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;
Douglas Gregor60ef3082011-12-15 00:29:59 +000044 if (ID && declaresSameEntity(ID->getClassInterface(), Container))
David Chisnall9735ca62011-03-25 11:57:33 +000045 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;
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +000055
Jordy Rosedb8264e2011-07-22 02:08:32 +000056 for (const ObjCIvarDecl *IVD = Container->all_declared_ivar_begin();
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +000057 IVD; IVD = IVD->getNextIvar()) {
58 if (Ivar == IVD)
David Chisnall9735ca62011-03-25 11:57:33 +000059 break;
60 ++Index;
61 }
David Chisnall9735ca62011-03-25 11:57:33 +000062 assert(Index < RL->getFieldCount() && "Ivar is not inside record layout!");
63
64 return RL->getFieldOffset(Index);
65}
66
67uint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM,
68 const ObjCInterfaceDecl *OID,
69 const ObjCIvarDecl *Ivar) {
Ken Dyck0afe9672011-04-14 01:00:39 +000070 return LookupFieldBitOffset(CGM, OID, 0, Ivar) /
71 CGM.getContext().getCharWidth();
David Chisnall9735ca62011-03-25 11:57:33 +000072}
73
74uint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM,
75 const ObjCImplementationDecl *OID,
76 const ObjCIvarDecl *Ivar) {
Ken Dyck0afe9672011-04-14 01:00:39 +000077 return LookupFieldBitOffset(CGM, OID->getClassInterface(), OID, Ivar) /
78 CGM.getContext().getCharWidth();
David Chisnall9735ca62011-03-25 11:57:33 +000079}
80
81LValue CGObjCRuntime::EmitValueForIvarAtOffset(CodeGen::CodeGenFunction &CGF,
82 const ObjCInterfaceDecl *OID,
83 llvm::Value *BaseValue,
84 const ObjCIvarDecl *Ivar,
85 unsigned CVRQualifiers,
86 llvm::Value *Offset) {
87 // Compute (type*) ( (char *) BaseValue + Offset)
Chris Lattner8b418682012-02-07 00:39:47 +000088 llvm::Type *I8Ptr = CGF.Int8PtrTy;
David Chisnall9735ca62011-03-25 11:57:33 +000089 QualType IvarTy = Ivar->getType();
Chris Lattner2acc6e32011-07-18 04:24:23 +000090 llvm::Type *LTy = CGF.CGM.getTypes().ConvertTypeForMem(IvarTy);
David Chisnall9735ca62011-03-25 11:57:33 +000091 llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue, I8Ptr);
92 V = CGF.Builder.CreateInBoundsGEP(V, Offset, "add.ptr");
93 V = CGF.Builder.CreateBitCast(V, llvm::PointerType::getUnqual(LTy));
94
95 if (!Ivar->isBitField()) {
Eli Friedmand71f4422011-12-19 23:03:09 +000096 LValue LV = CGF.MakeNaturalAlignAddrLValue(V, IvarTy);
David Chisnall9735ca62011-03-25 11:57:33 +000097 LV.getQuals().addCVRQualifiers(CVRQualifiers);
98 return LV;
99 }
100
101 // We need to compute an access strategy for this bit-field. We are given the
102 // offset to the first byte in the bit-field, the sub-byte offset is taken
103 // from the original layout. We reuse the normal bit-field access strategy by
104 // treating this as an access to a struct where the bit-field is in byte 0,
105 // and adjust the containing type size as appropriate.
106 //
107 // FIXME: Note that currently we make a very conservative estimate of the
108 // alignment of the bit-field, because (a) it is not clear what guarantees the
109 // runtime makes us, and (b) we don't have a way to specify that the struct is
110 // at an alignment plus offset.
111 //
112 // Note, there is a subtle invariant here: we can only call this routine on
113 // non-synthesized ivars but we may be called for synthesized ivars. However,
114 // a synthesized ivar can never be a bit-field, so this is safe.
115 const ASTRecordLayout &RL =
116 CGF.CGM.getContext().getASTObjCInterfaceLayout(OID);
117 uint64_t TypeSizeInBits = CGF.CGM.getContext().toBits(RL.getSize());
118 uint64_t FieldBitOffset = LookupFieldBitOffset(CGF.CGM, OID, 0, Ivar);
Ken Dyck18052cd2011-04-22 17:23:43 +0000119 uint64_t BitOffset = FieldBitOffset % CGF.CGM.getContext().getCharWidth();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000120 uint64_t ContainingTypeAlign = CGF.CGM.getContext().getTargetInfo().getCharAlign();
David Chisnall9735ca62011-03-25 11:57:33 +0000121 uint64_t ContainingTypeSize = TypeSizeInBits - (FieldBitOffset - BitOffset);
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000122 uint64_t BitFieldSize = Ivar->getBitWidthValue(CGF.getContext());
David Chisnall9735ca62011-03-25 11:57:33 +0000123
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,
John McCalla07398e2011-06-16 04:16:24 +0000135 IvarTy.withCVRQualifiers(CVRQualifiers));
David Chisnall9735ca62011-03-25 11:57:33 +0000136}
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
John McCallad346f42011-07-12 20:27:29 +0000152 void Emit(CodeGenFunction &CGF, Flags flags) {
David Chisnall9735ca62011-03-25 11:57:33 +0000153 if (!MightThrow) {
154 CGF.Builder.CreateCall(Fn)->setDoesNotThrow();
155 return;
156 }
157
Jay Foad4c7d9f12011-07-15 08:37:34 +0000158 CGF.EmitCallOrInvoke(Fn);
David Chisnall9735ca62011-03-25 11:57:33 +0000159 }
160 };
161}
162
163
164void CGObjCRuntime::EmitTryCatchStmt(CodeGenFunction &CGF,
165 const ObjCAtTryStmt &S,
David Chisnall789ecde2011-05-23 22:33:28 +0000166 llvm::Constant *beginCatchFn,
167 llvm::Constant *endCatchFn,
168 llvm::Constant *exceptionRethrowFn) {
David Chisnall9735ca62011-03-25 11:57:33 +0000169 // 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())
John McCalld768e9d2011-06-22 02:32:12 +0000176 FinallyInfo.enter(CGF, Finally->getFinallyBody(),
177 beginCatchFn, endCatchFn, exceptionRethrowFn);
David Chisnall9735ca62011-03-25 11:57:33 +0000178
Chris Lattner5f9e2722011-07-23 10:55:15 +0000179 SmallVector<CatchHandler, 8> Handlers;
David Chisnall9735ca62011-03-25 11:57:33 +0000180
181 // Enter the catch, if there is one.
182 if (S.getNumCatchStmts()) {
183 for (unsigned I = 0, N = S.getNumCatchStmts(); I != N; ++I) {
184 const ObjCAtCatchStmt *CatchStmt = S.getCatchStmt(I);
185 const VarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
186
187 Handlers.push_back(CatchHandler());
188 CatchHandler &Handler = Handlers.back();
189 Handler.Variable = CatchDecl;
190 Handler.Body = CatchStmt->getCatchBody();
191 Handler.Block = CGF.createBasicBlock("catch");
192
193 // @catch(...) always matches.
194 if (!CatchDecl) {
195 Handler.TypeInfo = 0; // catch-all
196 // Don't consider any other catches.
197 break;
198 }
199
200 Handler.TypeInfo = GetEHType(CatchDecl->getType());
201 }
202
203 EHCatchScope *Catch = CGF.EHStack.pushCatch(Handlers.size());
204 for (unsigned I = 0, E = Handlers.size(); I != E; ++I)
205 Catch->setHandler(I, Handlers[I].TypeInfo, Handlers[I].Block);
206 }
207
208 // Emit the try body.
209 CGF.EmitStmt(S.getTryBody());
210
211 // Leave the try.
212 if (S.getNumCatchStmts())
John McCall777d6e52011-08-11 02:22:43 +0000213 CGF.popCatchScope();
David Chisnall9735ca62011-03-25 11:57:33 +0000214
215 // Remember where we were.
216 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
217
218 // Emit the handlers.
219 for (unsigned I = 0, E = Handlers.size(); I != E; ++I) {
220 CatchHandler &Handler = Handlers[I];
221
222 CGF.EmitBlock(Handler.Block);
Bill Wendlingae270592011-09-15 18:57:19 +0000223 llvm::Value *RawExn = CGF.getExceptionFromSlot();
David Chisnall9735ca62011-03-25 11:57:33 +0000224
225 // Enter the catch.
226 llvm::Value *Exn = RawExn;
227 if (beginCatchFn) {
228 Exn = CGF.Builder.CreateCall(beginCatchFn, RawExn, "exn.adjusted");
229 cast<llvm::CallInst>(Exn)->setDoesNotThrow();
230 }
231
Eric Christopherb9c8c422011-10-19 00:44:01 +0000232 CodeGenFunction::LexicalScope cleanups(CGF, Handler.Body->getSourceRange());
John McCallfe3e3bd2011-05-12 01:00:15 +0000233
David Chisnall9735ca62011-03-25 11:57:33 +0000234 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) {
Chris Lattner2acc6e32011-07-18 04:24:23 +0000245 llvm::Type *CatchType = CGF.ConvertType(CatchParam->getType());
David Chisnall9735ca62011-03-25 11:57:33 +0000246 llvm::Value *CastExn = CGF.Builder.CreateBitCast(Exn, CatchType);
247
248 CGF.EmitAutoVarDecl(*CatchParam);
John McCallb29b12d2012-01-17 20:16:56 +0000249
250 llvm::Value *CatchParamAddr = CGF.GetAddrOfLocalVar(CatchParam);
251
252 switch (CatchParam->getType().getQualifiers().getObjCLifetime()) {
253 case Qualifiers::OCL_Strong:
254 CastExn = CGF.EmitARCRetainNonBlock(CastExn);
255 // fallthrough
256
257 case Qualifiers::OCL_None:
258 case Qualifiers::OCL_ExplicitNone:
259 case Qualifiers::OCL_Autoreleasing:
260 CGF.Builder.CreateStore(CastExn, CatchParamAddr);
261 break;
262
263 case Qualifiers::OCL_Weak:
264 CGF.EmitARCInitWeak(CatchParamAddr, CastExn);
265 break;
266 }
David Chisnall9735ca62011-03-25 11:57:33 +0000267 }
268
269 CGF.ObjCEHValueStack.push_back(Exn);
270 CGF.EmitStmt(Handler.Body);
271 CGF.ObjCEHValueStack.pop_back();
272
John McCallfe3e3bd2011-05-12 01:00:15 +0000273 // Leave any cleanups associated with the catch.
274 cleanups.ForceCleanup();
David Chisnall9735ca62011-03-25 11:57:33 +0000275
276 CGF.EmitBranchThroughCleanup(Cont);
277 }
278
279 // Go back to the try-statement fallthrough.
280 CGF.Builder.restoreIP(SavedIP);
281
John McCalld768e9d2011-06-22 02:32:12 +0000282 // Pop out of the finally.
David Chisnall9735ca62011-03-25 11:57:33 +0000283 if (S.getFinallyStmt())
John McCalld768e9d2011-06-22 02:32:12 +0000284 FinallyInfo.exit(CGF);
David Chisnall9735ca62011-03-25 11:57:33 +0000285
286 if (Cont.isValid())
287 CGF.EmitBlock(Cont.getBlock());
288}
289
290namespace {
291 struct CallSyncExit : EHScopeStack::Cleanup {
292 llvm::Value *SyncExitFn;
293 llvm::Value *SyncArg;
294 CallSyncExit(llvm::Value *SyncExitFn, llvm::Value *SyncArg)
295 : SyncExitFn(SyncExitFn), SyncArg(SyncArg) {}
296
John McCallad346f42011-07-12 20:27:29 +0000297 void Emit(CodeGenFunction &CGF, Flags flags) {
David Chisnall9735ca62011-03-25 11:57:33 +0000298 CGF.Builder.CreateCall(SyncExitFn, SyncArg)->setDoesNotThrow();
299 }
300 };
301}
302
303void CGObjCRuntime::EmitAtSynchronizedStmt(CodeGenFunction &CGF,
304 const ObjCAtSynchronizedStmt &S,
305 llvm::Function *syncEnterFn,
306 llvm::Function *syncExitFn) {
John McCall07524032011-07-27 21:50:02 +0000307 CodeGenFunction::RunCleanupsScope cleanups(CGF);
308
309 // Evaluate the lock operand. This is guaranteed to dominate the
310 // ARC release and lock-release cleanups.
311 const Expr *lockExpr = S.getSynchExpr();
312 llvm::Value *lock;
David Blaikie4e4d0842012-03-11 07:00:24 +0000313 if (CGF.getLangOpts().ObjCAutoRefCount) {
John McCall07524032011-07-27 21:50:02 +0000314 lock = CGF.EmitARCRetainScalarExpr(lockExpr);
315 lock = CGF.EmitObjCConsumeObject(lockExpr->getType(), lock);
316 } else {
317 lock = CGF.EmitScalarExpr(lockExpr);
318 }
319 lock = CGF.Builder.CreateBitCast(lock, CGF.VoidPtrTy);
David Chisnall9735ca62011-03-25 11:57:33 +0000320
321 // Acquire the lock.
John McCall07524032011-07-27 21:50:02 +0000322 CGF.Builder.CreateCall(syncEnterFn, lock)->setDoesNotThrow();
David Chisnall9735ca62011-03-25 11:57:33 +0000323
324 // Register an all-paths cleanup to release the lock.
John McCall07524032011-07-27 21:50:02 +0000325 CGF.EHStack.pushCleanup<CallSyncExit>(NormalAndEHCleanup, syncExitFn, lock);
David Chisnall9735ca62011-03-25 11:57:33 +0000326
327 // Emit the body of the statement.
328 CGF.EmitStmt(S.getSynchBody());
David Chisnall9735ca62011-03-25 11:57:33 +0000329}
John McCallde5d3c72012-02-17 03:33:10 +0000330
331/// Compute the pointer-to-function type to which a message send
332/// should be casted in order to correctly call the given method
333/// with the given arguments.
334///
335/// \param method - may be null
336/// \param resultType - the result type to use if there's no method
337/// \param argInfo - the actual arguments, including implicit ones
338CGObjCRuntime::MessageSendInfo
339CGObjCRuntime::getMessageSendInfo(const ObjCMethodDecl *method,
340 QualType resultType,
341 CallArgList &callArgs) {
342 // If there's a method, use information from that.
343 if (method) {
344 const CGFunctionInfo &signature =
345 CGM.getTypes().arrangeObjCMessageSendSignature(method, callArgs[0].Ty);
346
347 llvm::PointerType *signatureType =
348 CGM.getTypes().GetFunctionType(signature)->getPointerTo();
349
350 // If that's not variadic, there's no need to recompute the ABI
351 // arrangement.
352 if (!signature.isVariadic())
353 return MessageSendInfo(signature, signatureType);
354
355 // Otherwise, there is.
356 FunctionType::ExtInfo einfo = signature.getExtInfo();
357 const CGFunctionInfo &argsInfo =
358 CGM.getTypes().arrangeFunctionCall(resultType, callArgs, einfo,
359 signature.getRequiredArgs());
360
361 return MessageSendInfo(argsInfo, signatureType);
362 }
363
364 // There's no method; just use a default CC.
365 const CGFunctionInfo &argsInfo =
366 CGM.getTypes().arrangeFunctionCall(resultType, callArgs,
367 FunctionType::ExtInfo(),
368 RequiredArgs::All);
369
370 // Derive the signature to call from that.
371 llvm::PointerType *signatureType =
372 CGM.getTypes().GetFunctionType(argsInfo)->getPointerTo();
373 return MessageSendInfo(argsInfo, signatureType);
374}