blob: 744bed81f72eb16c1ef55c02ac000d7df1ab6d88 [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"
David Chisnall9735ca62011-03-25 11:57:33 +000017#include "CGCleanup.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000018#include "CGRecordLayout.h"
19#include "CodeGenFunction.h"
20#include "CodeGenModule.h"
David Chisnall9735ca62011-03-25 11:57:33 +000021#include "clang/AST/RecordLayout.h"
22#include "clang/AST/StmtObjC.h"
David Chisnall9735ca62011-03-25 11:57:33 +000023#include "llvm/Support/CallSite.h"
24
25using namespace clang;
26using namespace CodeGen;
27
28static uint64_t LookupFieldBitOffset(CodeGen::CodeGenModule &CGM,
29 const ObjCInterfaceDecl *OID,
30 const ObjCImplementationDecl *ID,
31 const ObjCIvarDecl *Ivar) {
32 const ObjCInterfaceDecl *Container = Ivar->getContainingInterface();
33
34 // FIXME: We should eliminate the need to have ObjCImplementationDecl passed
35 // in here; it should never be necessary because that should be the lexical
36 // decl context for the ivar.
37
38 // If we know have an implementation (and the ivar is in it) then
39 // look up in the implementation layout.
40 const ASTRecordLayout *RL;
Douglas Gregor60ef3082011-12-15 00:29:59 +000041 if (ID && declaresSameEntity(ID->getClassInterface(), Container))
David Chisnall9735ca62011-03-25 11:57:33 +000042 RL = &CGM.getContext().getASTObjCImplementationLayout(ID);
43 else
44 RL = &CGM.getContext().getASTObjCInterfaceLayout(Container);
45
46 // Compute field index.
47 //
48 // FIXME: The index here is closely tied to how ASTContext::getObjCLayout is
49 // implemented. This should be fixed to get the information from the layout
50 // directly.
51 unsigned Index = 0;
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +000052
Jordy Rosedb8264e2011-07-22 02:08:32 +000053 for (const ObjCIvarDecl *IVD = Container->all_declared_ivar_begin();
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +000054 IVD; IVD = IVD->getNextIvar()) {
55 if (Ivar == IVD)
David Chisnall9735ca62011-03-25 11:57:33 +000056 break;
57 ++Index;
58 }
David Chisnall9735ca62011-03-25 11:57:33 +000059 assert(Index < RL->getFieldCount() && "Ivar is not inside record layout!");
60
61 return RL->getFieldOffset(Index);
62}
63
Eli Friedmane5b46662012-11-06 22:15:52 +000064uint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM,
65 const ObjCInterfaceDecl *OID,
66 const ObjCIvarDecl *Ivar) {
67 return LookupFieldBitOffset(CGM, OID, 0, Ivar) /
68 CGM.getContext().getCharWidth();
David Chisnall9735ca62011-03-25 11:57:33 +000069}
70
Eli Friedmane5b46662012-11-06 22:15:52 +000071uint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM,
72 const ObjCImplementationDecl *OID,
73 const ObjCIvarDecl *Ivar) {
74 return LookupFieldBitOffset(CGM, OID->getClassInterface(), OID, Ivar) /
75 CGM.getContext().getCharWidth();
David Chisnall9735ca62011-03-25 11:57:33 +000076}
77
Eli Friedman77457862012-11-06 23:40:48 +000078unsigned CGObjCRuntime::ComputeBitfieldBitOffset(
79 CodeGen::CodeGenModule &CGM,
80 const ObjCInterfaceDecl *ID,
81 const ObjCIvarDecl *Ivar) {
82 return LookupFieldBitOffset(CGM, ID, ID->getImplementation(), Ivar);
83}
84
David Chisnall9735ca62011-03-25 11:57:33 +000085LValue CGObjCRuntime::EmitValueForIvarAtOffset(CodeGen::CodeGenFunction &CGF,
86 const ObjCInterfaceDecl *OID,
87 llvm::Value *BaseValue,
88 const ObjCIvarDecl *Ivar,
89 unsigned CVRQualifiers,
90 llvm::Value *Offset) {
91 // Compute (type*) ( (char *) BaseValue + Offset)
Chris Lattner8b418682012-02-07 00:39:47 +000092 llvm::Type *I8Ptr = CGF.Int8PtrTy;
David Chisnall9735ca62011-03-25 11:57:33 +000093 QualType IvarTy = Ivar->getType();
Chris Lattner2acc6e32011-07-18 04:24:23 +000094 llvm::Type *LTy = CGF.CGM.getTypes().ConvertTypeForMem(IvarTy);
David Chisnall9735ca62011-03-25 11:57:33 +000095 llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue, I8Ptr);
96 V = CGF.Builder.CreateInBoundsGEP(V, Offset, "add.ptr");
97 V = CGF.Builder.CreateBitCast(V, llvm::PointerType::getUnqual(LTy));
98
99 if (!Ivar->isBitField()) {
Eli Friedmand71f4422011-12-19 23:03:09 +0000100 LValue LV = CGF.MakeNaturalAlignAddrLValue(V, IvarTy);
David Chisnall9735ca62011-03-25 11:57:33 +0000101 LV.getQuals().addCVRQualifiers(CVRQualifiers);
102 return LV;
103 }
104
105 // We need to compute an access strategy for this bit-field. We are given the
106 // offset to the first byte in the bit-field, the sub-byte offset is taken
107 // from the original layout. We reuse the normal bit-field access strategy by
108 // treating this as an access to a struct where the bit-field is in byte 0,
109 // and adjust the containing type size as appropriate.
110 //
111 // FIXME: Note that currently we make a very conservative estimate of the
112 // alignment of the bit-field, because (a) it is not clear what guarantees the
113 // runtime makes us, and (b) we don't have a way to specify that the struct is
114 // at an alignment plus offset.
115 //
116 // Note, there is a subtle invariant here: we can only call this routine on
117 // non-synthesized ivars but we may be called for synthesized ivars. However,
118 // a synthesized ivar can never be a bit-field, so this is safe.
119 const ASTRecordLayout &RL =
120 CGF.CGM.getContext().getASTObjCInterfaceLayout(OID);
121 uint64_t TypeSizeInBits = CGF.CGM.getContext().toBits(RL.getSize());
122 uint64_t FieldBitOffset = LookupFieldBitOffset(CGF.CGM, OID, 0, Ivar);
Ken Dyck18052cd2011-04-22 17:23:43 +0000123 uint64_t BitOffset = FieldBitOffset % CGF.CGM.getContext().getCharWidth();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000124 uint64_t ContainingTypeAlign = CGF.CGM.getContext().getTargetInfo().getCharAlign();
David Chisnall9735ca62011-03-25 11:57:33 +0000125 uint64_t ContainingTypeSize = TypeSizeInBits - (FieldBitOffset - BitOffset);
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000126 uint64_t BitFieldSize = Ivar->getBitWidthValue(CGF.getContext());
Eli Friedmanf4bcfa12012-06-27 21:19:48 +0000127 CharUnits ContainingTypeAlignCharUnits =
128 CGF.CGM.getContext().toCharUnitsFromBits(ContainingTypeAlign);
David Chisnall9735ca62011-03-25 11:57:33 +0000129
130 // Allocate a new CGBitFieldInfo object to describe this access.
131 //
132 // FIXME: This is incredibly wasteful, these should be uniqued or part of some
133 // layout object. However, this is blocked on other cleanups to the
134 // Objective-C code, so for now we just live with allocating a bunch of these
135 // objects.
136 CGBitFieldInfo *Info = new (CGF.CGM.getContext()) CGBitFieldInfo(
137 CGBitFieldInfo::MakeInfo(CGF.CGM.getTypes(), Ivar, BitOffset, BitFieldSize,
138 ContainingTypeSize, ContainingTypeAlign));
139
140 return LValue::MakeBitfield(V, *Info,
Eli Friedmanf4bcfa12012-06-27 21:19:48 +0000141 IvarTy.withCVRQualifiers(CVRQualifiers),
142 ContainingTypeAlignCharUnits);
David Chisnall9735ca62011-03-25 11:57:33 +0000143}
144
145namespace {
146 struct CatchHandler {
147 const VarDecl *Variable;
148 const Stmt *Body;
149 llvm::BasicBlock *Block;
150 llvm::Value *TypeInfo;
151 };
152
153 struct CallObjCEndCatch : EHScopeStack::Cleanup {
154 CallObjCEndCatch(bool MightThrow, llvm::Value *Fn) :
155 MightThrow(MightThrow), Fn(Fn) {}
156 bool MightThrow;
157 llvm::Value *Fn;
158
John McCallad346f42011-07-12 20:27:29 +0000159 void Emit(CodeGenFunction &CGF, Flags flags) {
David Chisnall9735ca62011-03-25 11:57:33 +0000160 if (!MightThrow) {
161 CGF.Builder.CreateCall(Fn)->setDoesNotThrow();
162 return;
163 }
164
Jay Foad4c7d9f12011-07-15 08:37:34 +0000165 CGF.EmitCallOrInvoke(Fn);
David Chisnall9735ca62011-03-25 11:57:33 +0000166 }
167 };
168}
169
170
171void CGObjCRuntime::EmitTryCatchStmt(CodeGenFunction &CGF,
172 const ObjCAtTryStmt &S,
David Chisnall789ecde2011-05-23 22:33:28 +0000173 llvm::Constant *beginCatchFn,
174 llvm::Constant *endCatchFn,
175 llvm::Constant *exceptionRethrowFn) {
David Chisnall9735ca62011-03-25 11:57:33 +0000176 // Jump destination for falling out of catch bodies.
177 CodeGenFunction::JumpDest Cont;
178 if (S.getNumCatchStmts())
179 Cont = CGF.getJumpDestInCurrentScope("eh.cont");
180
181 CodeGenFunction::FinallyInfo FinallyInfo;
182 if (const ObjCAtFinallyStmt *Finally = S.getFinallyStmt())
John McCalld768e9d2011-06-22 02:32:12 +0000183 FinallyInfo.enter(CGF, Finally->getFinallyBody(),
184 beginCatchFn, endCatchFn, exceptionRethrowFn);
David Chisnall9735ca62011-03-25 11:57:33 +0000185
Chris Lattner5f9e2722011-07-23 10:55:15 +0000186 SmallVector<CatchHandler, 8> Handlers;
David Chisnall9735ca62011-03-25 11:57:33 +0000187
188 // Enter the catch, if there is one.
189 if (S.getNumCatchStmts()) {
190 for (unsigned I = 0, N = S.getNumCatchStmts(); I != N; ++I) {
191 const ObjCAtCatchStmt *CatchStmt = S.getCatchStmt(I);
192 const VarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
193
194 Handlers.push_back(CatchHandler());
195 CatchHandler &Handler = Handlers.back();
196 Handler.Variable = CatchDecl;
197 Handler.Body = CatchStmt->getCatchBody();
198 Handler.Block = CGF.createBasicBlock("catch");
199
200 // @catch(...) always matches.
201 if (!CatchDecl) {
202 Handler.TypeInfo = 0; // catch-all
203 // Don't consider any other catches.
204 break;
205 }
206
207 Handler.TypeInfo = GetEHType(CatchDecl->getType());
208 }
209
210 EHCatchScope *Catch = CGF.EHStack.pushCatch(Handlers.size());
211 for (unsigned I = 0, E = Handlers.size(); I != E; ++I)
212 Catch->setHandler(I, Handlers[I].TypeInfo, Handlers[I].Block);
213 }
214
215 // Emit the try body.
216 CGF.EmitStmt(S.getTryBody());
217
218 // Leave the try.
219 if (S.getNumCatchStmts())
John McCall777d6e52011-08-11 02:22:43 +0000220 CGF.popCatchScope();
David Chisnall9735ca62011-03-25 11:57:33 +0000221
222 // Remember where we were.
223 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
224
225 // Emit the handlers.
226 for (unsigned I = 0, E = Handlers.size(); I != E; ++I) {
227 CatchHandler &Handler = Handlers[I];
228
229 CGF.EmitBlock(Handler.Block);
Bill Wendlingae270592011-09-15 18:57:19 +0000230 llvm::Value *RawExn = CGF.getExceptionFromSlot();
David Chisnall9735ca62011-03-25 11:57:33 +0000231
232 // Enter the catch.
233 llvm::Value *Exn = RawExn;
234 if (beginCatchFn) {
235 Exn = CGF.Builder.CreateCall(beginCatchFn, RawExn, "exn.adjusted");
236 cast<llvm::CallInst>(Exn)->setDoesNotThrow();
237 }
238
Eric Christopherb9c8c422011-10-19 00:44:01 +0000239 CodeGenFunction::LexicalScope cleanups(CGF, Handler.Body->getSourceRange());
John McCallfe3e3bd2011-05-12 01:00:15 +0000240
David Chisnall9735ca62011-03-25 11:57:33 +0000241 if (endCatchFn) {
242 // Add a cleanup to leave the catch.
243 bool EndCatchMightThrow = (Handler.Variable == 0);
244
245 CGF.EHStack.pushCleanup<CallObjCEndCatch>(NormalAndEHCleanup,
246 EndCatchMightThrow,
247 endCatchFn);
248 }
249
250 // Bind the catch parameter if it exists.
251 if (const VarDecl *CatchParam = Handler.Variable) {
Chris Lattner2acc6e32011-07-18 04:24:23 +0000252 llvm::Type *CatchType = CGF.ConvertType(CatchParam->getType());
David Chisnall9735ca62011-03-25 11:57:33 +0000253 llvm::Value *CastExn = CGF.Builder.CreateBitCast(Exn, CatchType);
254
255 CGF.EmitAutoVarDecl(*CatchParam);
John McCallb29b12d2012-01-17 20:16:56 +0000256
257 llvm::Value *CatchParamAddr = CGF.GetAddrOfLocalVar(CatchParam);
258
259 switch (CatchParam->getType().getQualifiers().getObjCLifetime()) {
260 case Qualifiers::OCL_Strong:
261 CastExn = CGF.EmitARCRetainNonBlock(CastExn);
262 // fallthrough
263
264 case Qualifiers::OCL_None:
265 case Qualifiers::OCL_ExplicitNone:
266 case Qualifiers::OCL_Autoreleasing:
267 CGF.Builder.CreateStore(CastExn, CatchParamAddr);
268 break;
269
270 case Qualifiers::OCL_Weak:
271 CGF.EmitARCInitWeak(CatchParamAddr, CastExn);
272 break;
273 }
David Chisnall9735ca62011-03-25 11:57:33 +0000274 }
275
276 CGF.ObjCEHValueStack.push_back(Exn);
277 CGF.EmitStmt(Handler.Body);
278 CGF.ObjCEHValueStack.pop_back();
279
John McCallfe3e3bd2011-05-12 01:00:15 +0000280 // Leave any cleanups associated with the catch.
281 cleanups.ForceCleanup();
David Chisnall9735ca62011-03-25 11:57:33 +0000282
283 CGF.EmitBranchThroughCleanup(Cont);
284 }
285
286 // Go back to the try-statement fallthrough.
287 CGF.Builder.restoreIP(SavedIP);
288
John McCalld768e9d2011-06-22 02:32:12 +0000289 // Pop out of the finally.
David Chisnall9735ca62011-03-25 11:57:33 +0000290 if (S.getFinallyStmt())
John McCalld768e9d2011-06-22 02:32:12 +0000291 FinallyInfo.exit(CGF);
David Chisnall9735ca62011-03-25 11:57:33 +0000292
293 if (Cont.isValid())
294 CGF.EmitBlock(Cont.getBlock());
295}
296
297namespace {
298 struct CallSyncExit : EHScopeStack::Cleanup {
299 llvm::Value *SyncExitFn;
300 llvm::Value *SyncArg;
301 CallSyncExit(llvm::Value *SyncExitFn, llvm::Value *SyncArg)
302 : SyncExitFn(SyncExitFn), SyncArg(SyncArg) {}
303
John McCallad346f42011-07-12 20:27:29 +0000304 void Emit(CodeGenFunction &CGF, Flags flags) {
David Chisnall9735ca62011-03-25 11:57:33 +0000305 CGF.Builder.CreateCall(SyncExitFn, SyncArg)->setDoesNotThrow();
306 }
307 };
308}
309
310void CGObjCRuntime::EmitAtSynchronizedStmt(CodeGenFunction &CGF,
311 const ObjCAtSynchronizedStmt &S,
312 llvm::Function *syncEnterFn,
313 llvm::Function *syncExitFn) {
John McCall07524032011-07-27 21:50:02 +0000314 CodeGenFunction::RunCleanupsScope cleanups(CGF);
315
316 // Evaluate the lock operand. This is guaranteed to dominate the
317 // ARC release and lock-release cleanups.
318 const Expr *lockExpr = S.getSynchExpr();
319 llvm::Value *lock;
David Blaikie4e4d0842012-03-11 07:00:24 +0000320 if (CGF.getLangOpts().ObjCAutoRefCount) {
John McCall07524032011-07-27 21:50:02 +0000321 lock = CGF.EmitARCRetainScalarExpr(lockExpr);
322 lock = CGF.EmitObjCConsumeObject(lockExpr->getType(), lock);
323 } else {
324 lock = CGF.EmitScalarExpr(lockExpr);
325 }
326 lock = CGF.Builder.CreateBitCast(lock, CGF.VoidPtrTy);
David Chisnall9735ca62011-03-25 11:57:33 +0000327
328 // Acquire the lock.
John McCall07524032011-07-27 21:50:02 +0000329 CGF.Builder.CreateCall(syncEnterFn, lock)->setDoesNotThrow();
David Chisnall9735ca62011-03-25 11:57:33 +0000330
331 // Register an all-paths cleanup to release the lock.
John McCall07524032011-07-27 21:50:02 +0000332 CGF.EHStack.pushCleanup<CallSyncExit>(NormalAndEHCleanup, syncExitFn, lock);
David Chisnall9735ca62011-03-25 11:57:33 +0000333
334 // Emit the body of the statement.
335 CGF.EmitStmt(S.getSynchBody());
David Chisnall9735ca62011-03-25 11:57:33 +0000336}
John McCallde5d3c72012-02-17 03:33:10 +0000337
338/// Compute the pointer-to-function type to which a message send
339/// should be casted in order to correctly call the given method
340/// with the given arguments.
341///
342/// \param method - may be null
343/// \param resultType - the result type to use if there's no method
James Dennettc7810fe2012-06-15 09:02:08 +0000344/// \param callArgs - the actual arguments, including implicit ones
John McCallde5d3c72012-02-17 03:33:10 +0000345CGObjCRuntime::MessageSendInfo
346CGObjCRuntime::getMessageSendInfo(const ObjCMethodDecl *method,
347 QualType resultType,
348 CallArgList &callArgs) {
349 // If there's a method, use information from that.
350 if (method) {
351 const CGFunctionInfo &signature =
352 CGM.getTypes().arrangeObjCMessageSendSignature(method, callArgs[0].Ty);
353
354 llvm::PointerType *signatureType =
355 CGM.getTypes().GetFunctionType(signature)->getPointerTo();
356
357 // If that's not variadic, there's no need to recompute the ABI
358 // arrangement.
359 if (!signature.isVariadic())
360 return MessageSendInfo(signature, signatureType);
361
362 // Otherwise, there is.
363 FunctionType::ExtInfo einfo = signature.getExtInfo();
364 const CGFunctionInfo &argsInfo =
John McCall0f3d0972012-07-07 06:41:13 +0000365 CGM.getTypes().arrangeFreeFunctionCall(resultType, callArgs, einfo,
366 signature.getRequiredArgs());
John McCallde5d3c72012-02-17 03:33:10 +0000367
368 return MessageSendInfo(argsInfo, signatureType);
369 }
370
371 // There's no method; just use a default CC.
372 const CGFunctionInfo &argsInfo =
John McCall0f3d0972012-07-07 06:41:13 +0000373 CGM.getTypes().arrangeFreeFunctionCall(resultType, callArgs,
374 FunctionType::ExtInfo(),
375 RequiredArgs::All);
John McCallde5d3c72012-02-17 03:33:10 +0000376
377 // Derive the signature to call from that.
378 llvm::PointerType *signatureType =
379 CGM.getTypes().GetFunctionType(argsInfo)->getPointerTo();
380 return MessageSendInfo(argsInfo, signatureType);
381}