blob: abd10a29c9e28ce5ad3fce651f50fc7d3c85e9ed [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)
David Chisnall9735ca62011-03-25 11:57:33 +000092 QualType IvarTy = Ivar->getType();
Chris Lattner2acc6e32011-07-18 04:24:23 +000093 llvm::Type *LTy = CGF.CGM.getTypes().ConvertTypeForMem(IvarTy);
Chandler Carruth72d2dab2012-12-06 11:14:44 +000094 llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue, CGF.Int8PtrTy);
David Chisnall9735ca62011-03-25 11:57:33 +000095 V = CGF.Builder.CreateInBoundsGEP(V, Offset, "add.ptr");
David Chisnall9735ca62011-03-25 11:57:33 +000096
97 if (!Ivar->isBitField()) {
Chandler Carruth72d2dab2012-12-06 11:14:44 +000098 V = CGF.Builder.CreateBitCast(V, llvm::PointerType::getUnqual(LTy));
Eli Friedmand71f4422011-12-19 23:03:09 +000099 LValue LV = CGF.MakeNaturalAlignAddrLValue(V, IvarTy);
David Chisnall9735ca62011-03-25 11:57:33 +0000100 LV.getQuals().addCVRQualifiers(CVRQualifiers);
101 return LV;
102 }
103
104 // We need to compute an access strategy for this bit-field. We are given the
105 // offset to the first byte in the bit-field, the sub-byte offset is taken
106 // from the original layout. We reuse the normal bit-field access strategy by
107 // treating this as an access to a struct where the bit-field is in byte 0,
108 // and adjust the containing type size as appropriate.
109 //
110 // FIXME: Note that currently we make a very conservative estimate of the
111 // alignment of the bit-field, because (a) it is not clear what guarantees the
112 // runtime makes us, and (b) we don't have a way to specify that the struct is
113 // at an alignment plus offset.
114 //
115 // Note, there is a subtle invariant here: we can only call this routine on
116 // non-synthesized ivars but we may be called for synthesized ivars. However,
117 // a synthesized ivar can never be a bit-field, so this is safe.
David Chisnall9735ca62011-03-25 11:57:33 +0000118 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();
Chandler Carruth72d2dab2012-12-06 11:14:44 +0000120 uint64_t AlignmentBits = CGF.CGM.getContext().getTargetInfo().getCharAlign();
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000121 uint64_t BitFieldSize = Ivar->getBitWidthValue(CGF.getContext());
Chandler Carruth72d2dab2012-12-06 11:14:44 +0000122 CharUnits StorageSize =
123 CGF.CGM.getContext().toCharUnitsFromBits(
124 llvm::RoundUpToAlignment(BitOffset + BitFieldSize, AlignmentBits));
125 CharUnits Alignment = CGF.CGM.getContext().toCharUnitsFromBits(AlignmentBits);
David Chisnall9735ca62011-03-25 11:57:33 +0000126
127 // Allocate a new CGBitFieldInfo object to describe this access.
128 //
129 // FIXME: This is incredibly wasteful, these should be uniqued or part of some
130 // layout object. However, this is blocked on other cleanups to the
131 // Objective-C code, so for now we just live with allocating a bunch of these
132 // objects.
133 CGBitFieldInfo *Info = new (CGF.CGM.getContext()) CGBitFieldInfo(
134 CGBitFieldInfo::MakeInfo(CGF.CGM.getTypes(), Ivar, BitOffset, BitFieldSize,
Chandler Carruth72d2dab2012-12-06 11:14:44 +0000135 CGF.CGM.getContext().toBits(StorageSize),
136 Alignment.getQuantity()));
David Chisnall9735ca62011-03-25 11:57:33 +0000137
Chandler Carruth72d2dab2012-12-06 11:14:44 +0000138 V = CGF.Builder.CreateBitCast(V,
139 llvm::Type::getIntNPtrTy(CGF.getLLVMContext(),
140 Info->StorageSize));
David Chisnall9735ca62011-03-25 11:57:33 +0000141 return LValue::MakeBitfield(V, *Info,
Eli Friedmanf4bcfa12012-06-27 21:19:48 +0000142 IvarTy.withCVRQualifiers(CVRQualifiers),
Chandler Carruth72d2dab2012-12-06 11:14:44 +0000143 Alignment);
David Chisnall9735ca62011-03-25 11:57:33 +0000144}
145
146namespace {
147 struct CatchHandler {
148 const VarDecl *Variable;
149 const Stmt *Body;
150 llvm::BasicBlock *Block;
151 llvm::Value *TypeInfo;
152 };
153
154 struct CallObjCEndCatch : EHScopeStack::Cleanup {
155 CallObjCEndCatch(bool MightThrow, llvm::Value *Fn) :
156 MightThrow(MightThrow), Fn(Fn) {}
157 bool MightThrow;
158 llvm::Value *Fn;
159
John McCallad346f42011-07-12 20:27:29 +0000160 void Emit(CodeGenFunction &CGF, Flags flags) {
David Chisnall9735ca62011-03-25 11:57:33 +0000161 if (!MightThrow) {
162 CGF.Builder.CreateCall(Fn)->setDoesNotThrow();
163 return;
164 }
165
John McCallbd7370a2013-02-28 19:01:20 +0000166 CGF.EmitRuntimeCallOrInvoke(Fn);
David Chisnall9735ca62011-03-25 11:57:33 +0000167 }
168 };
169}
170
171
172void CGObjCRuntime::EmitTryCatchStmt(CodeGenFunction &CGF,
173 const ObjCAtTryStmt &S,
David Chisnall789ecde2011-05-23 22:33:28 +0000174 llvm::Constant *beginCatchFn,
175 llvm::Constant *endCatchFn,
176 llvm::Constant *exceptionRethrowFn) {
David Chisnall9735ca62011-03-25 11:57:33 +0000177 // Jump destination for falling out of catch bodies.
178 CodeGenFunction::JumpDest Cont;
179 if (S.getNumCatchStmts())
180 Cont = CGF.getJumpDestInCurrentScope("eh.cont");
181
182 CodeGenFunction::FinallyInfo FinallyInfo;
183 if (const ObjCAtFinallyStmt *Finally = S.getFinallyStmt())
John McCalld768e9d2011-06-22 02:32:12 +0000184 FinallyInfo.enter(CGF, Finally->getFinallyBody(),
185 beginCatchFn, endCatchFn, exceptionRethrowFn);
David Chisnall9735ca62011-03-25 11:57:33 +0000186
Chris Lattner5f9e2722011-07-23 10:55:15 +0000187 SmallVector<CatchHandler, 8> Handlers;
David Chisnall9735ca62011-03-25 11:57:33 +0000188
189 // Enter the catch, if there is one.
190 if (S.getNumCatchStmts()) {
191 for (unsigned I = 0, N = S.getNumCatchStmts(); I != N; ++I) {
192 const ObjCAtCatchStmt *CatchStmt = S.getCatchStmt(I);
193 const VarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
194
195 Handlers.push_back(CatchHandler());
196 CatchHandler &Handler = Handlers.back();
197 Handler.Variable = CatchDecl;
198 Handler.Body = CatchStmt->getCatchBody();
199 Handler.Block = CGF.createBasicBlock("catch");
200
201 // @catch(...) always matches.
202 if (!CatchDecl) {
203 Handler.TypeInfo = 0; // catch-all
204 // Don't consider any other catches.
205 break;
206 }
207
208 Handler.TypeInfo = GetEHType(CatchDecl->getType());
209 }
210
211 EHCatchScope *Catch = CGF.EHStack.pushCatch(Handlers.size());
212 for (unsigned I = 0, E = Handlers.size(); I != E; ++I)
213 Catch->setHandler(I, Handlers[I].TypeInfo, Handlers[I].Block);
214 }
215
216 // Emit the try body.
217 CGF.EmitStmt(S.getTryBody());
218
219 // Leave the try.
220 if (S.getNumCatchStmts())
John McCall777d6e52011-08-11 02:22:43 +0000221 CGF.popCatchScope();
David Chisnall9735ca62011-03-25 11:57:33 +0000222
223 // Remember where we were.
224 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
225
226 // Emit the handlers.
227 for (unsigned I = 0, E = Handlers.size(); I != E; ++I) {
228 CatchHandler &Handler = Handlers[I];
229
230 CGF.EmitBlock(Handler.Block);
Bill Wendlingae270592011-09-15 18:57:19 +0000231 llvm::Value *RawExn = CGF.getExceptionFromSlot();
David Chisnall9735ca62011-03-25 11:57:33 +0000232
233 // Enter the catch.
234 llvm::Value *Exn = RawExn;
235 if (beginCatchFn) {
236 Exn = CGF.Builder.CreateCall(beginCatchFn, RawExn, "exn.adjusted");
237 cast<llvm::CallInst>(Exn)->setDoesNotThrow();
238 }
239
Eric Christopherb9c8c422011-10-19 00:44:01 +0000240 CodeGenFunction::LexicalScope cleanups(CGF, Handler.Body->getSourceRange());
John McCallfe3e3bd2011-05-12 01:00:15 +0000241
David Chisnall9735ca62011-03-25 11:57:33 +0000242 if (endCatchFn) {
243 // Add a cleanup to leave the catch.
244 bool EndCatchMightThrow = (Handler.Variable == 0);
245
246 CGF.EHStack.pushCleanup<CallObjCEndCatch>(NormalAndEHCleanup,
247 EndCatchMightThrow,
248 endCatchFn);
249 }
250
251 // Bind the catch parameter if it exists.
252 if (const VarDecl *CatchParam = Handler.Variable) {
Chris Lattner2acc6e32011-07-18 04:24:23 +0000253 llvm::Type *CatchType = CGF.ConvertType(CatchParam->getType());
David Chisnall9735ca62011-03-25 11:57:33 +0000254 llvm::Value *CastExn = CGF.Builder.CreateBitCast(Exn, CatchType);
255
256 CGF.EmitAutoVarDecl(*CatchParam);
John McCallb29b12d2012-01-17 20:16:56 +0000257
258 llvm::Value *CatchParamAddr = CGF.GetAddrOfLocalVar(CatchParam);
259
260 switch (CatchParam->getType().getQualifiers().getObjCLifetime()) {
261 case Qualifiers::OCL_Strong:
262 CastExn = CGF.EmitARCRetainNonBlock(CastExn);
263 // fallthrough
264
265 case Qualifiers::OCL_None:
266 case Qualifiers::OCL_ExplicitNone:
267 case Qualifiers::OCL_Autoreleasing:
268 CGF.Builder.CreateStore(CastExn, CatchParamAddr);
269 break;
270
271 case Qualifiers::OCL_Weak:
272 CGF.EmitARCInitWeak(CatchParamAddr, CastExn);
273 break;
274 }
David Chisnall9735ca62011-03-25 11:57:33 +0000275 }
276
277 CGF.ObjCEHValueStack.push_back(Exn);
278 CGF.EmitStmt(Handler.Body);
279 CGF.ObjCEHValueStack.pop_back();
280
John McCallfe3e3bd2011-05-12 01:00:15 +0000281 // Leave any cleanups associated with the catch.
282 cleanups.ForceCleanup();
David Chisnall9735ca62011-03-25 11:57:33 +0000283
284 CGF.EmitBranchThroughCleanup(Cont);
285 }
286
287 // Go back to the try-statement fallthrough.
288 CGF.Builder.restoreIP(SavedIP);
289
John McCalld768e9d2011-06-22 02:32:12 +0000290 // Pop out of the finally.
David Chisnall9735ca62011-03-25 11:57:33 +0000291 if (S.getFinallyStmt())
John McCalld768e9d2011-06-22 02:32:12 +0000292 FinallyInfo.exit(CGF);
David Chisnall9735ca62011-03-25 11:57:33 +0000293
294 if (Cont.isValid())
295 CGF.EmitBlock(Cont.getBlock());
296}
297
298namespace {
299 struct CallSyncExit : EHScopeStack::Cleanup {
300 llvm::Value *SyncExitFn;
301 llvm::Value *SyncArg;
302 CallSyncExit(llvm::Value *SyncExitFn, llvm::Value *SyncArg)
303 : SyncExitFn(SyncExitFn), SyncArg(SyncArg) {}
304
John McCallad346f42011-07-12 20:27:29 +0000305 void Emit(CodeGenFunction &CGF, Flags flags) {
David Chisnall9735ca62011-03-25 11:57:33 +0000306 CGF.Builder.CreateCall(SyncExitFn, SyncArg)->setDoesNotThrow();
307 }
308 };
309}
310
311void CGObjCRuntime::EmitAtSynchronizedStmt(CodeGenFunction &CGF,
312 const ObjCAtSynchronizedStmt &S,
313 llvm::Function *syncEnterFn,
314 llvm::Function *syncExitFn) {
John McCall07524032011-07-27 21:50:02 +0000315 CodeGenFunction::RunCleanupsScope cleanups(CGF);
316
317 // Evaluate the lock operand. This is guaranteed to dominate the
318 // ARC release and lock-release cleanups.
319 const Expr *lockExpr = S.getSynchExpr();
320 llvm::Value *lock;
David Blaikie4e4d0842012-03-11 07:00:24 +0000321 if (CGF.getLangOpts().ObjCAutoRefCount) {
John McCall07524032011-07-27 21:50:02 +0000322 lock = CGF.EmitARCRetainScalarExpr(lockExpr);
323 lock = CGF.EmitObjCConsumeObject(lockExpr->getType(), lock);
324 } else {
325 lock = CGF.EmitScalarExpr(lockExpr);
326 }
327 lock = CGF.Builder.CreateBitCast(lock, CGF.VoidPtrTy);
David Chisnall9735ca62011-03-25 11:57:33 +0000328
329 // Acquire the lock.
John McCall07524032011-07-27 21:50:02 +0000330 CGF.Builder.CreateCall(syncEnterFn, lock)->setDoesNotThrow();
David Chisnall9735ca62011-03-25 11:57:33 +0000331
332 // Register an all-paths cleanup to release the lock.
John McCall07524032011-07-27 21:50:02 +0000333 CGF.EHStack.pushCleanup<CallSyncExit>(NormalAndEHCleanup, syncExitFn, lock);
David Chisnall9735ca62011-03-25 11:57:33 +0000334
335 // Emit the body of the statement.
336 CGF.EmitStmt(S.getSynchBody());
David Chisnall9735ca62011-03-25 11:57:33 +0000337}
John McCallde5d3c72012-02-17 03:33:10 +0000338
339/// Compute the pointer-to-function type to which a message send
340/// should be casted in order to correctly call the given method
341/// with the given arguments.
342///
343/// \param method - may be null
344/// \param resultType - the result type to use if there's no method
James Dennettc7810fe2012-06-15 09:02:08 +0000345/// \param callArgs - the actual arguments, including implicit ones
John McCallde5d3c72012-02-17 03:33:10 +0000346CGObjCRuntime::MessageSendInfo
347CGObjCRuntime::getMessageSendInfo(const ObjCMethodDecl *method,
348 QualType resultType,
349 CallArgList &callArgs) {
350 // If there's a method, use information from that.
351 if (method) {
352 const CGFunctionInfo &signature =
353 CGM.getTypes().arrangeObjCMessageSendSignature(method, callArgs[0].Ty);
354
355 llvm::PointerType *signatureType =
356 CGM.getTypes().GetFunctionType(signature)->getPointerTo();
357
358 // If that's not variadic, there's no need to recompute the ABI
359 // arrangement.
360 if (!signature.isVariadic())
361 return MessageSendInfo(signature, signatureType);
362
363 // Otherwise, there is.
364 FunctionType::ExtInfo einfo = signature.getExtInfo();
365 const CGFunctionInfo &argsInfo =
John McCall0f3d0972012-07-07 06:41:13 +0000366 CGM.getTypes().arrangeFreeFunctionCall(resultType, callArgs, einfo,
367 signature.getRequiredArgs());
John McCallde5d3c72012-02-17 03:33:10 +0000368
369 return MessageSendInfo(argsInfo, signatureType);
370 }
371
372 // There's no method; just use a default CC.
373 const CGFunctionInfo &argsInfo =
John McCall0f3d0972012-07-07 06:41:13 +0000374 CGM.getTypes().arrangeFreeFunctionCall(resultType, callArgs,
375 FunctionType::ExtInfo(),
376 RequiredArgs::All);
John McCallde5d3c72012-02-17 03:33:10 +0000377
378 // Derive the signature to call from that.
379 llvm::PointerType *signatureType =
380 CGM.getTypes().GetFunctionType(argsInfo)->getPointerTo();
381 return MessageSendInfo(argsInfo, signatureType);
382}