blob: 49979f3279dc8600e11d1bc5f652bee4dbda66fc [file] [log] [blame]
Anders Carlsson76f4a902007-08-21 17:43:55 +00001//===---- CGBuiltin.cpp - Emit LLVM Code for builtins ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Anders Carlsson76f4a902007-08-21 17:43:55 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Objective-C code as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
Devang Pateld2d66652011-01-19 01:36:36 +000014#include "CGDebugInfo.h"
Ted Kremenek43e06332008-04-09 15:51:31 +000015#include "CGObjCRuntime.h"
Anders Carlsson76f4a902007-08-21 17:43:55 +000016#include "CodeGenFunction.h"
17#include "CodeGenModule.h"
John McCall31168b02011-06-15 23:02:42 +000018#include "TargetInfo.h"
Daniel Dunbar9e22c0d2008-08-29 08:11:39 +000019#include "clang/AST/ASTContext.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000020#include "clang/AST/DeclObjC.h"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000021#include "clang/AST/StmtObjC.h"
Daniel Dunbarc5d33042008-09-03 00:27:26 +000022#include "clang/Basic/Diagnostic.h"
Anders Carlsson2e744e82008-08-30 19:51:14 +000023#include "llvm/ADT/STLExtras.h"
Daniel Dunbara08dff12008-09-24 04:04:31 +000024#include "llvm/Target/TargetData.h"
John McCall31168b02011-06-15 23:02:42 +000025#include "llvm/InlineAsm.h"
Anders Carlsson76f4a902007-08-21 17:43:55 +000026using namespace clang;
27using namespace CodeGen;
28
John McCall31168b02011-06-15 23:02:42 +000029typedef llvm::PointerIntPair<llvm::Value*,1,bool> TryEmitResult;
30static TryEmitResult
31tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e);
32
33/// Given the address of a variable of pointer type, find the correct
34/// null to store into it.
35static llvm::Constant *getNullForVariable(llvm::Value *addr) {
Chris Lattner2192fe52011-07-18 04:24:23 +000036 llvm::Type *type =
John McCall31168b02011-06-15 23:02:42 +000037 cast<llvm::PointerType>(addr->getType())->getElementType();
38 return llvm::ConstantPointerNull::get(cast<llvm::PointerType>(type));
39}
40
Chris Lattnerb1d329d2008-06-24 17:04:18 +000041/// Emits an instance of NSConstantString representing the object.
Mike Stump11289f42009-09-09 15:08:12 +000042llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E)
Daniel Dunbar44b58a22008-11-25 21:53:21 +000043{
David Chisnall481e3a82010-01-23 02:40:42 +000044 llvm::Constant *C =
45 CGM.getObjCRuntime().GenerateConstantString(E->getString());
Daniel Dunbar66912a12008-08-20 00:28:19 +000046 // FIXME: This bitcast should just be made an invariant on the Runtime.
Owen Andersonade90fd2009-07-29 18:54:39 +000047 return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
Chris Lattnerb1d329d2008-06-24 17:04:18 +000048}
49
50/// Emit a selector.
51llvm::Value *CodeGenFunction::EmitObjCSelectorExpr(const ObjCSelectorExpr *E) {
52 // Untyped selector.
53 // Note that this implementation allows for non-constant strings to be passed
54 // as arguments to @selector(). Currently, the only thing preventing this
55 // behaviour is the type checking in the front end.
Daniel Dunbar45858d22010-02-03 20:11:42 +000056 return CGM.getObjCRuntime().GetSelector(Builder, E->getSelector());
Chris Lattnerb1d329d2008-06-24 17:04:18 +000057}
58
Daniel Dunbar66912a12008-08-20 00:28:19 +000059llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) {
60 // FIXME: This should pass the Decl not the name.
61 return CGM.getObjCRuntime().GenerateProtocolRef(Builder, E->getProtocol());
62}
Chris Lattnerb1d329d2008-06-24 17:04:18 +000063
Douglas Gregor33823722011-06-11 01:09:30 +000064/// \brief Adjust the type of the result of an Objective-C message send
65/// expression when the method has a related result type.
66static RValue AdjustRelatedResultType(CodeGenFunction &CGF,
67 const Expr *E,
68 const ObjCMethodDecl *Method,
69 RValue Result) {
70 if (!Method)
71 return Result;
John McCall31168b02011-06-15 23:02:42 +000072
Douglas Gregor33823722011-06-11 01:09:30 +000073 if (!Method->hasRelatedResultType() ||
74 CGF.getContext().hasSameType(E->getType(), Method->getResultType()) ||
75 !Result.isScalar())
76 return Result;
77
78 // We have applied a related result type. Cast the rvalue appropriately.
79 return RValue::get(CGF.Builder.CreateBitCast(Result.getScalarVal(),
80 CGF.ConvertType(E->getType())));
81}
Chris Lattnerb1d329d2008-06-24 17:04:18 +000082
John McCallcf166702011-07-22 08:53:00 +000083/// Decide whether to extend the lifetime of the receiver of a
84/// returns-inner-pointer message.
85static bool
86shouldExtendReceiverForInnerPointerMessage(const ObjCMessageExpr *message) {
87 switch (message->getReceiverKind()) {
88
89 // For a normal instance message, we should extend unless the
90 // receiver is loaded from a variable with precise lifetime.
91 case ObjCMessageExpr::Instance: {
92 const Expr *receiver = message->getInstanceReceiver();
93 const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(receiver);
94 if (!ice || ice->getCastKind() != CK_LValueToRValue) return true;
95 receiver = ice->getSubExpr()->IgnoreParens();
96
97 // Only __strong variables.
98 if (receiver->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
99 return true;
100
101 // All ivars and fields have precise lifetime.
102 if (isa<MemberExpr>(receiver) || isa<ObjCIvarRefExpr>(receiver))
103 return false;
104
105 // Otherwise, check for variables.
106 const DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(ice->getSubExpr());
107 if (!declRef) return true;
108 const VarDecl *var = dyn_cast<VarDecl>(declRef->getDecl());
109 if (!var) return true;
110
111 // All variables have precise lifetime except local variables with
112 // automatic storage duration that aren't specially marked.
113 return (var->hasLocalStorage() &&
114 !var->hasAttr<ObjCPreciseLifetimeAttr>());
115 }
116
117 case ObjCMessageExpr::Class:
118 case ObjCMessageExpr::SuperClass:
119 // It's never necessary for class objects.
120 return false;
121
122 case ObjCMessageExpr::SuperInstance:
123 // We generally assume that 'self' lives throughout a method call.
124 return false;
125 }
126
127 llvm_unreachable("invalid receiver kind");
128}
129
John McCall78a15112010-05-22 01:48:05 +0000130RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E,
131 ReturnValueSlot Return) {
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000132 // Only the lookup mechanism and first two arguments of the method
133 // implementation vary between runtimes. We can get the receiver and
134 // arguments in generic code.
Mike Stump11289f42009-09-09 15:08:12 +0000135
John McCall31168b02011-06-15 23:02:42 +0000136 bool isDelegateInit = E->isDelegateInitCall();
137
John McCallcf166702011-07-22 08:53:00 +0000138 const ObjCMethodDecl *method = E->getMethodDecl();
Fariborz Jahanian326efeb2012-01-28 18:46:31 +0000139
John McCall31168b02011-06-15 23:02:42 +0000140 // We don't retain the receiver in delegate init calls, and this is
141 // safe because the receiver value is always loaded from 'self',
142 // which we zero out. We don't want to Block_copy block receivers,
143 // though.
144 bool retainSelf =
145 (!isDelegateInit &&
146 CGM.getLangOptions().ObjCAutoRefCount &&
John McCallcf166702011-07-22 08:53:00 +0000147 method &&
148 method->hasAttr<NSConsumesSelfAttr>());
John McCall31168b02011-06-15 23:02:42 +0000149
Daniel Dunbar8d480592008-08-11 18:12:00 +0000150 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000151 bool isSuperMessage = false;
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000152 bool isClassMessage = false;
David Chisnall01aa4672010-04-28 19:33:36 +0000153 ObjCInterfaceDecl *OID = 0;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000154 // Find the receiver
Douglas Gregor33823722011-06-11 01:09:30 +0000155 QualType ReceiverType;
Daniel Dunbarb2197802010-04-22 03:17:06 +0000156 llvm::Value *Receiver = 0;
Douglas Gregor9a129192010-04-21 00:45:42 +0000157 switch (E->getReceiverKind()) {
158 case ObjCMessageExpr::Instance:
Douglas Gregor33823722011-06-11 01:09:30 +0000159 ReceiverType = E->getInstanceReceiver()->getType();
John McCall31168b02011-06-15 23:02:42 +0000160 if (retainSelf) {
161 TryEmitResult ter = tryEmitARCRetainScalarExpr(*this,
162 E->getInstanceReceiver());
163 Receiver = ter.getPointer();
John McCallcf166702011-07-22 08:53:00 +0000164 if (ter.getInt()) retainSelf = false;
John McCall31168b02011-06-15 23:02:42 +0000165 } else
166 Receiver = EmitScalarExpr(E->getInstanceReceiver());
Douglas Gregor9a129192010-04-21 00:45:42 +0000167 break;
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +0000168
Douglas Gregor9a129192010-04-21 00:45:42 +0000169 case ObjCMessageExpr::Class: {
Douglas Gregor33823722011-06-11 01:09:30 +0000170 ReceiverType = E->getClassReceiver();
171 const ObjCObjectType *ObjTy = ReceiverType->getAs<ObjCObjectType>();
John McCall3e294922010-05-17 20:12:43 +0000172 assert(ObjTy && "Invalid Objective-C class message send");
173 OID = ObjTy->getInterface();
174 assert(OID && "Invalid Objective-C class message send");
David Chisnall01aa4672010-04-28 19:33:36 +0000175 Receiver = Runtime.GetClass(Builder, OID);
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000176 isClassMessage = true;
Douglas Gregor9a129192010-04-21 00:45:42 +0000177 break;
178 }
179
180 case ObjCMessageExpr::SuperInstance:
Douglas Gregor33823722011-06-11 01:09:30 +0000181 ReceiverType = E->getSuperType();
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000182 Receiver = LoadObjCSelf();
Douglas Gregor9a129192010-04-21 00:45:42 +0000183 isSuperMessage = true;
184 break;
185
186 case ObjCMessageExpr::SuperClass:
Douglas Gregor33823722011-06-11 01:09:30 +0000187 ReceiverType = E->getSuperType();
Douglas Gregor9a129192010-04-21 00:45:42 +0000188 Receiver = LoadObjCSelf();
189 isSuperMessage = true;
190 isClassMessage = true;
191 break;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000192 }
193
Fariborz Jahanian326efeb2012-01-28 18:46:31 +0000194 // Check to see if receiver must be null checked before method is sent
195 // to the receiver.
196 NullReturnState nullReturn;
197 if (CGM.getLangOptions().ObjCAutoRefCount && method)
198 for (ObjCMethodDecl::param_const_iterator i = method->param_begin(),
199 e = method->param_end(); i != e; ++i) {
200 const ParmVarDecl *ParamDecl = (*i);
201 if (ParamDecl->hasAttr<NSConsumedAttr>()) {
202 nullReturn.init(*this, Receiver);
203 break;
204 }
205 }
206
John McCallcf166702011-07-22 08:53:00 +0000207 if (retainSelf)
208 Receiver = EmitARCRetainNonBlock(Receiver);
209
210 // In ARC, we sometimes want to "extend the lifetime"
211 // (i.e. retain+autorelease) of receivers of returns-inner-pointer
212 // messages.
213 if (getLangOptions().ObjCAutoRefCount && method &&
214 method->hasAttr<ObjCReturnsInnerPointerAttr>() &&
215 shouldExtendReceiverForInnerPointerMessage(E))
216 Receiver = EmitARCRetainAutorelease(ReceiverType, Receiver);
217
John McCall31168b02011-06-15 23:02:42 +0000218 QualType ResultType =
John McCallcf166702011-07-22 08:53:00 +0000219 method ? method->getResultType() : E->getType();
John McCall31168b02011-06-15 23:02:42 +0000220
Daniel Dunbarc722b852008-08-30 03:02:31 +0000221 CallArgList Args;
John McCallcf166702011-07-22 08:53:00 +0000222 EmitCallArgs(Args, method, E->arg_begin(), E->arg_end());
Mike Stump11289f42009-09-09 15:08:12 +0000223
John McCall31168b02011-06-15 23:02:42 +0000224 // For delegate init calls in ARC, do an unsafe store of null into
225 // self. This represents the call taking direct ownership of that
226 // value. We have to do this after emitting the other call
227 // arguments because they might also reference self, but we don't
228 // have to worry about any of them modifying self because that would
229 // be an undefined read and write of an object in unordered
230 // expressions.
231 if (isDelegateInit) {
232 assert(getLangOptions().ObjCAutoRefCount &&
233 "delegate init calls should only be marked in ARC");
234
235 // Do an unsafe store of null into self.
236 llvm::Value *selfAddr =
237 LocalDeclMap[cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl()];
238 assert(selfAddr && "no self entry for a delegate init call?");
239
240 Builder.CreateStore(getNullForVariable(selfAddr), selfAddr);
241 }
Anders Carlsson280e61f12010-06-21 20:59:55 +0000242
Douglas Gregor33823722011-06-11 01:09:30 +0000243 RValue result;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000244 if (isSuperMessage) {
Chris Lattner6cfec782008-06-26 04:42:20 +0000245 // super is only valid in an Objective-C method
246 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +0000247 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
Douglas Gregor33823722011-06-11 01:09:30 +0000248 result = Runtime.GenerateMessageSendSuper(*this, Return, ResultType,
249 E->getSelector(),
250 OMD->getClassInterface(),
251 isCategoryImpl,
252 Receiver,
253 isClassMessage,
254 Args,
John McCallcf166702011-07-22 08:53:00 +0000255 method);
Douglas Gregor33823722011-06-11 01:09:30 +0000256 } else {
257 result = Runtime.GenerateMessageSend(*this, Return, ResultType,
258 E->getSelector(),
259 Receiver, Args, OID,
John McCallcf166702011-07-22 08:53:00 +0000260 method);
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000261 }
John McCall31168b02011-06-15 23:02:42 +0000262
263 // For delegate init calls in ARC, implicitly store the result of
264 // the call back into self. This takes ownership of the value.
265 if (isDelegateInit) {
266 llvm::Value *selfAddr =
267 LocalDeclMap[cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl()];
268 llvm::Value *newSelf = result.getScalarVal();
269
270 // The delegate return type isn't necessarily a matching type; in
271 // fact, it's quite likely to be 'id'.
Chris Lattner2192fe52011-07-18 04:24:23 +0000272 llvm::Type *selfTy =
John McCall31168b02011-06-15 23:02:42 +0000273 cast<llvm::PointerType>(selfAddr->getType())->getElementType();
274 newSelf = Builder.CreateBitCast(newSelf, selfTy);
275
276 Builder.CreateStore(newSelf, selfAddr);
277 }
Fariborz Jahanian326efeb2012-01-28 18:46:31 +0000278 RValue rvalue = AdjustRelatedResultType(*this, E, method, result);
279 return nullReturn.complete(*this, rvalue, ResultType);
Anders Carlsson76f4a902007-08-21 17:43:55 +0000280}
281
John McCall31168b02011-06-15 23:02:42 +0000282namespace {
283struct FinishARCDealloc : EHScopeStack::Cleanup {
John McCall30317fd2011-07-12 20:27:29 +0000284 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall31168b02011-06-15 23:02:42 +0000285 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CGF.CurCodeDecl);
John McCalldffafde2011-07-13 18:26:47 +0000286
287 const ObjCImplDecl *impl = cast<ObjCImplDecl>(method->getDeclContext());
John McCall31168b02011-06-15 23:02:42 +0000288 const ObjCInterfaceDecl *iface = impl->getClassInterface();
289 if (!iface->getSuperClass()) return;
290
John McCalldffafde2011-07-13 18:26:47 +0000291 bool isCategory = isa<ObjCCategoryImplDecl>(impl);
292
John McCall31168b02011-06-15 23:02:42 +0000293 // Call [super dealloc] if we have a superclass.
294 llvm::Value *self = CGF.LoadObjCSelf();
295
296 CallArgList args;
297 CGF.CGM.getObjCRuntime().GenerateMessageSendSuper(CGF, ReturnValueSlot(),
298 CGF.getContext().VoidTy,
299 method->getSelector(),
300 iface,
John McCalldffafde2011-07-13 18:26:47 +0000301 isCategory,
John McCall31168b02011-06-15 23:02:42 +0000302 self,
303 /*is class msg*/ false,
304 args,
305 method);
306 }
307};
Fariborz Jahanian326efeb2012-01-28 18:46:31 +0000308
John McCall31168b02011-06-15 23:02:42 +0000309}
310
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000311/// StartObjCMethod - Begin emission of an ObjCMethod. This generates
312/// the LLVM function and sets the other context used by
313/// CodeGenFunction.
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +0000314void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
Devang Patele7ce5402011-05-19 23:37:41 +0000315 const ObjCContainerDecl *CD,
316 SourceLocation StartLoc) {
John McCalla738c252011-03-09 04:27:21 +0000317 FunctionArgList args;
Devang Patela2c048e2010-04-05 21:09:15 +0000318 // Check if we should generate debug info for this method.
Devang Pateld6ffebb2011-03-07 18:45:56 +0000319 if (CGM.getModuleDebugInfo() && !OMD->hasAttr<NoDebugAttr>())
320 DebugInfo = CGM.getModuleDebugInfo();
Devang Patela2c048e2010-04-05 21:09:15 +0000321
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +0000322 llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
Daniel Dunbar449a3392008-09-04 23:41:35 +0000323
Daniel Dunbarc3e7cff2009-04-17 00:48:04 +0000324 const CGFunctionInfo &FI = CGM.getTypes().getFunctionInfo(OMD);
325 CGM.SetInternalFunctionAttributes(OMD, Fn, FI);
Chris Lattner5696e7b2008-06-17 18:05:57 +0000326
John McCalla738c252011-03-09 04:27:21 +0000327 args.push_back(OMD->getSelfDecl());
328 args.push_back(OMD->getCmdDecl());
Chris Lattner5696e7b2008-06-17 18:05:57 +0000329
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +0000330 for (ObjCMethodDecl::param_const_iterator PI = OMD->param_begin(),
Chris Lattnera4997152009-02-20 18:43:26 +0000331 E = OMD->param_end(); PI != E; ++PI)
John McCalla738c252011-03-09 04:27:21 +0000332 args.push_back(*PI);
Chris Lattner5696e7b2008-06-17 18:05:57 +0000333
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000334 CurGD = OMD;
335
Devang Patele7ce5402011-05-19 23:37:41 +0000336 StartFunction(OMD, OMD->getResultType(), Fn, FI, args, StartLoc);
John McCall31168b02011-06-15 23:02:42 +0000337
338 // In ARC, certain methods get an extra cleanup.
339 if (CGM.getLangOptions().ObjCAutoRefCount &&
340 OMD->isInstanceMethod() &&
341 OMD->getSelector().isUnarySelector()) {
342 const IdentifierInfo *ident =
343 OMD->getSelector().getIdentifierInfoForSlot(0);
344 if (ident->isStr("dealloc"))
345 EHStack.pushCleanup<FinishARCDealloc>(getARCCleanupKind());
346 }
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000347}
Daniel Dunbara94ecd22008-08-16 03:19:19 +0000348
John McCall31168b02011-06-15 23:02:42 +0000349static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
350 LValue lvalue, QualType type);
351
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000352/// Generate an Objective-C method. An Objective-C method is a C function with
Mike Stump11289f42009-09-09 15:08:12 +0000353/// its pointer, name, and types registered in the class struture.
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000354void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
Devang Patele7ce5402011-05-19 23:37:41 +0000355 StartObjCMethod(OMD, OMD->getClassInterface(), OMD->getLocStart());
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +0000356 EmitStmt(OMD->getBody());
357 FinishFunction(OMD->getBodyRBrace());
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000358}
359
John McCallb923ece2011-09-12 23:06:44 +0000360/// emitStructGetterCall - Call the runtime function to load a property
361/// into the return value slot.
362static void emitStructGetterCall(CodeGenFunction &CGF, ObjCIvarDecl *ivar,
363 bool isAtomic, bool hasStrong) {
364 ASTContext &Context = CGF.getContext();
365
366 llvm::Value *src =
367 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(),
368 ivar, 0).getAddress();
369
370 // objc_copyStruct (ReturnValue, &structIvar,
371 // sizeof (Type of Ivar), isAtomic, false);
372 CallArgList args;
373
374 llvm::Value *dest = CGF.Builder.CreateBitCast(CGF.ReturnValue, CGF.VoidPtrTy);
375 args.add(RValue::get(dest), Context.VoidPtrTy);
376
377 src = CGF.Builder.CreateBitCast(src, CGF.VoidPtrTy);
378 args.add(RValue::get(src), Context.VoidPtrTy);
379
380 CharUnits size = CGF.getContext().getTypeSizeInChars(ivar->getType());
381 args.add(RValue::get(CGF.CGM.getSize(size)), Context.getSizeType());
382 args.add(RValue::get(CGF.Builder.getInt1(isAtomic)), Context.BoolTy);
383 args.add(RValue::get(CGF.Builder.getInt1(hasStrong)), Context.BoolTy);
384
385 llvm::Value *fn = CGF.CGM.getObjCRuntime().GetGetStructFunction();
386 CGF.EmitCall(CGF.getTypes().getFunctionInfo(Context.VoidTy, args,
387 FunctionType::ExtInfo()),
388 fn, ReturnValueSlot(), args);
389}
390
John McCallf4528ae2011-09-13 03:34:09 +0000391/// Determine whether the given architecture supports unaligned atomic
392/// accesses. They don't have to be fast, just faster than a function
393/// call and a mutex.
394static bool hasUnalignedAtomics(llvm::Triple::ArchType arch) {
Eli Friedman5be3e6a2011-09-13 20:48:30 +0000395 // FIXME: Allow unaligned atomic load/store on x86. (It is not
396 // currently supported by the backend.)
397 return 0;
John McCallf4528ae2011-09-13 03:34:09 +0000398}
399
400/// Return the maximum size that permits atomic accesses for the given
401/// architecture.
402static CharUnits getMaxAtomicAccessSize(CodeGenModule &CGM,
403 llvm::Triple::ArchType arch) {
404 // ARM has 8-byte atomic accesses, but it's not clear whether we
405 // want to rely on them here.
406
407 // In the default case, just assume that any size up to a pointer is
408 // fine given adequate alignment.
409 return CharUnits::fromQuantity(CGM.PointerSizeInBytes);
410}
411
412namespace {
413 class PropertyImplStrategy {
414 public:
415 enum StrategyKind {
416 /// The 'native' strategy is to use the architecture's provided
417 /// reads and writes.
418 Native,
419
420 /// Use objc_setProperty and objc_getProperty.
421 GetSetProperty,
422
423 /// Use objc_setProperty for the setter, but use expression
424 /// evaluation for the getter.
425 SetPropertyAndExpressionGet,
426
427 /// Use objc_copyStruct.
428 CopyStruct,
429
430 /// The 'expression' strategy is to emit normal assignment or
431 /// lvalue-to-rvalue expressions.
432 Expression
433 };
434
435 StrategyKind getKind() const { return StrategyKind(Kind); }
436
437 bool hasStrongMember() const { return HasStrong; }
438 bool isAtomic() const { return IsAtomic; }
439 bool isCopy() const { return IsCopy; }
440
441 CharUnits getIvarSize() const { return IvarSize; }
442 CharUnits getIvarAlignment() const { return IvarAlignment; }
443
444 PropertyImplStrategy(CodeGenModule &CGM,
445 const ObjCPropertyImplDecl *propImpl);
446
447 private:
448 unsigned Kind : 8;
449 unsigned IsAtomic : 1;
450 unsigned IsCopy : 1;
451 unsigned HasStrong : 1;
452
453 CharUnits IvarSize;
454 CharUnits IvarAlignment;
455 };
456}
457
458/// Pick an implementation strategy for the the given property synthesis.
459PropertyImplStrategy::PropertyImplStrategy(CodeGenModule &CGM,
460 const ObjCPropertyImplDecl *propImpl) {
461 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
John McCall43192862011-09-13 18:31:23 +0000462 ObjCPropertyDecl::SetterKind setterKind = prop->getSetterKind();
John McCallf4528ae2011-09-13 03:34:09 +0000463
John McCall43192862011-09-13 18:31:23 +0000464 IsCopy = (setterKind == ObjCPropertyDecl::Copy);
465 IsAtomic = prop->isAtomic();
John McCallf4528ae2011-09-13 03:34:09 +0000466 HasStrong = false; // doesn't matter here.
467
468 // Evaluate the ivar's size and alignment.
469 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
470 QualType ivarType = ivar->getType();
471 llvm::tie(IvarSize, IvarAlignment)
472 = CGM.getContext().getTypeInfoInChars(ivarType);
473
474 // If we have a copy property, we always have to use getProperty/setProperty.
John McCall43192862011-09-13 18:31:23 +0000475 // TODO: we could actually use setProperty and an expression for non-atomics.
John McCallf4528ae2011-09-13 03:34:09 +0000476 if (IsCopy) {
477 Kind = GetSetProperty;
478 return;
479 }
480
John McCall43192862011-09-13 18:31:23 +0000481 // Handle retain.
482 if (setterKind == ObjCPropertyDecl::Retain) {
John McCallf4528ae2011-09-13 03:34:09 +0000483 // In GC-only, there's nothing special that needs to be done.
Douglas Gregor79a91412011-09-13 17:21:33 +0000484 if (CGM.getLangOptions().getGC() == LangOptions::GCOnly) {
John McCallf4528ae2011-09-13 03:34:09 +0000485 // fallthrough
486
487 // In ARC, if the property is non-atomic, use expression emission,
488 // which translates to objc_storeStrong. This isn't required, but
489 // it's slightly nicer.
490 } else if (CGM.getLangOptions().ObjCAutoRefCount && !IsAtomic) {
491 Kind = Expression;
492 return;
493
494 // Otherwise, we need to at least use setProperty. However, if
495 // the property isn't atomic, we can use normal expression
496 // emission for the getter.
497 } else if (!IsAtomic) {
498 Kind = SetPropertyAndExpressionGet;
499 return;
500
501 // Otherwise, we have to use both setProperty and getProperty.
502 } else {
503 Kind = GetSetProperty;
504 return;
505 }
506 }
507
508 // If we're not atomic, just use expression accesses.
509 if (!IsAtomic) {
510 Kind = Expression;
511 return;
512 }
513
John McCall0e5c0862011-09-13 05:36:29 +0000514 // Properties on bitfield ivars need to be emitted using expression
515 // accesses even if they're nominally atomic.
516 if (ivar->isBitField()) {
517 Kind = Expression;
518 return;
519 }
520
John McCallf4528ae2011-09-13 03:34:09 +0000521 // GC-qualified or ARC-qualified ivars need to be emitted as
522 // expressions. This actually works out to being atomic anyway,
523 // except for ARC __strong, but that should trigger the above code.
524 if (ivarType.hasNonTrivialObjCLifetime() ||
Douglas Gregor79a91412011-09-13 17:21:33 +0000525 (CGM.getLangOptions().getGC() &&
John McCallf4528ae2011-09-13 03:34:09 +0000526 CGM.getContext().getObjCGCAttrKind(ivarType))) {
527 Kind = Expression;
528 return;
529 }
530
531 // Compute whether the ivar has strong members.
Douglas Gregor79a91412011-09-13 17:21:33 +0000532 if (CGM.getLangOptions().getGC())
John McCallf4528ae2011-09-13 03:34:09 +0000533 if (const RecordType *recordType = ivarType->getAs<RecordType>())
534 HasStrong = recordType->getDecl()->hasObjectMember();
535
536 // We can never access structs with object members with a native
537 // access, because we need to use write barriers. This is what
538 // objc_copyStruct is for.
539 if (HasStrong) {
540 Kind = CopyStruct;
541 return;
542 }
543
544 // Otherwise, this is target-dependent and based on the size and
545 // alignment of the ivar.
John McCall0bef0ba2011-09-13 07:33:34 +0000546
547 // If the size of the ivar is not a power of two, give up. We don't
548 // want to get into the business of doing compare-and-swaps.
549 if (!IvarSize.isPowerOfTwo()) {
550 Kind = CopyStruct;
551 return;
552 }
553
John McCallf4528ae2011-09-13 03:34:09 +0000554 llvm::Triple::ArchType arch =
555 CGM.getContext().getTargetInfo().getTriple().getArch();
556
557 // Most architectures require memory to fit within a single cache
558 // line, so the alignment has to be at least the size of the access.
559 // Otherwise we have to grab a lock.
560 if (IvarAlignment < IvarSize && !hasUnalignedAtomics(arch)) {
561 Kind = CopyStruct;
562 return;
563 }
564
565 // If the ivar's size exceeds the architecture's maximum atomic
566 // access size, we have to use CopyStruct.
567 if (IvarSize > getMaxAtomicAccessSize(CGM, arch)) {
568 Kind = CopyStruct;
569 return;
570 }
571
572 // Otherwise, we can use native loads and stores.
573 Kind = Native;
574}
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000575
576/// GenerateObjCGetter - Generate an Objective-C property getter
Steve Naroff5a7dd782009-01-10 22:55:25 +0000577/// function. The given Decl must be an ObjCImplementationDecl. @synthesize
578/// is illegal within a category.
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +0000579void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
580 const ObjCPropertyImplDecl *PID) {
Fariborz Jahanian4b501a22012-01-07 18:56:22 +0000581 llvm::Constant *AtomicHelperFn =
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000582 GenerateObjCAtomicGetterCopyHelperFunction(PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000583 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
584 ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
585 assert(OMD && "Invalid call to generate getter (empty method)");
Devang Patele7ce5402011-05-19 23:37:41 +0000586 StartObjCMethod(OMD, IMP->getClassInterface(), PID->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +0000587
Fariborz Jahanian4b501a22012-01-07 18:56:22 +0000588 generateObjCGetterBody(IMP, PID, AtomicHelperFn);
John McCallf4528ae2011-09-13 03:34:09 +0000589
590 FinishFunction();
591}
592
John McCallbdd81852011-09-13 06:00:03 +0000593static bool hasTrivialGetExpr(const ObjCPropertyImplDecl *propImpl) {
594 const Expr *getter = propImpl->getGetterCXXConstructor();
John McCallf4528ae2011-09-13 03:34:09 +0000595 if (!getter) return true;
596
597 // Sema only makes only of these when the ivar has a C++ class type,
598 // so the form is pretty constrained.
599
John McCallbdd81852011-09-13 06:00:03 +0000600 // If the property has a reference type, we might just be binding a
601 // reference, in which case the result will be a gl-value. We should
602 // treat this as a non-trivial operation.
603 if (getter->isGLValue())
604 return false;
605
John McCallf4528ae2011-09-13 03:34:09 +0000606 // If we selected a trivial copy-constructor, we're okay.
607 if (const CXXConstructExpr *construct = dyn_cast<CXXConstructExpr>(getter))
608 return (construct->getConstructor()->isTrivial());
609
610 // The constructor might require cleanups (in which case it's never
611 // trivial).
612 assert(isa<ExprWithCleanups>(getter));
613 return false;
614}
615
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000616/// emitCPPObjectAtomicGetterCall - Call the runtime function to
617/// copy the ivar into the resturn slot.
618static void emitCPPObjectAtomicGetterCall(CodeGenFunction &CGF,
619 llvm::Value *returnAddr,
620 ObjCIvarDecl *ivar,
621 llvm::Constant *AtomicHelperFn) {
622 // objc_copyCppObjectAtomic (&returnSlot, &CppObjectIvar,
623 // AtomicHelperFn);
624 CallArgList args;
625
626 // The 1st argument is the return Slot.
627 args.add(RValue::get(returnAddr), CGF.getContext().VoidPtrTy);
628
629 // The 2nd argument is the address of the ivar.
630 llvm::Value *ivarAddr =
631 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
632 CGF.LoadObjCSelf(), ivar, 0).getAddress();
633 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
634 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
635
636 // Third argument is the helper function.
637 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
638
639 llvm::Value *copyCppAtomicObjectFn =
640 CGF.CGM.getObjCRuntime().GetCppAtomicObjectFunction();
641 CGF.EmitCall(CGF.getTypes().getFunctionInfo(CGF.getContext().VoidTy, args,
642 FunctionType::ExtInfo()),
643 copyCppAtomicObjectFn, ReturnValueSlot(), args);
644}
645
John McCallf4528ae2011-09-13 03:34:09 +0000646void
647CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahanian4b501a22012-01-07 18:56:22 +0000648 const ObjCPropertyImplDecl *propImpl,
649 llvm::Constant *AtomicHelperFn) {
John McCallf4528ae2011-09-13 03:34:09 +0000650 // If there's a non-trivial 'get' expression, we just have to emit that.
651 if (!hasTrivialGetExpr(propImpl)) {
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000652 if (!AtomicHelperFn) {
653 ReturnStmt ret(SourceLocation(), propImpl->getGetterCXXConstructor(),
654 /*nrvo*/ 0);
655 EmitReturnStmt(ret);
656 }
657 else {
658 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
659 emitCPPObjectAtomicGetterCall(*this, ReturnValue,
660 ivar, AtomicHelperFn);
661 }
John McCallf4528ae2011-09-13 03:34:09 +0000662 return;
663 }
664
665 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
666 QualType propType = prop->getType();
667 ObjCMethodDecl *getterMethod = prop->getGetterMethodDecl();
668
669 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
670
671 // Pick an implementation strategy.
672 PropertyImplStrategy strategy(CGM, propImpl);
673 switch (strategy.getKind()) {
674 case PropertyImplStrategy::Native: {
675 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
676
677 // Currently, all atomic accesses have to be through integer
678 // types, so there's no point in trying to pick a prettier type.
679 llvm::Type *bitcastType =
680 llvm::Type::getIntNTy(getLLVMContext(),
681 getContext().toBits(strategy.getIvarSize()));
682 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
683
684 // Perform an atomic load. This does not impose ordering constraints.
685 llvm::Value *ivarAddr = LV.getAddress();
686 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
687 llvm::LoadInst *load = Builder.CreateLoad(ivarAddr, "load");
688 load->setAlignment(strategy.getIvarAlignment().getQuantity());
689 load->setAtomic(llvm::Unordered);
690
691 // Store that value into the return address. Doing this with a
692 // bitcast is likely to produce some pretty ugly IR, but it's not
693 // the *most* terrible thing in the world.
694 Builder.CreateStore(load, Builder.CreateBitCast(ReturnValue, bitcastType));
695
696 // Make sure we don't do an autorelease.
697 AutoreleaseResult = false;
698 return;
699 }
700
701 case PropertyImplStrategy::GetSetProperty: {
702 llvm::Value *getPropertyFn =
703 CGM.getObjCRuntime().GetPropertyGetFunction();
704 if (!getPropertyFn) {
705 CGM.ErrorUnsupported(propImpl, "Obj-C getter requiring atomic copy");
Daniel Dunbara08dff12008-09-24 04:04:31 +0000706 return;
707 }
708
709 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
710 // FIXME: Can't this be simpler? This might even be worse than the
711 // corresponding gcc code.
John McCallf4528ae2011-09-13 03:34:09 +0000712 llvm::Value *cmd =
713 Builder.CreateLoad(LocalDeclMap[getterMethod->getCmdDecl()], "cmd");
714 llvm::Value *self = Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
715 llvm::Value *ivarOffset =
716 EmitIvarOffset(classImpl->getClassInterface(), ivar);
717
718 CallArgList args;
719 args.add(RValue::get(self), getContext().getObjCIdType());
720 args.add(RValue::get(cmd), getContext().getObjCSelType());
721 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
John McCall43192862011-09-13 18:31:23 +0000722 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
723 getContext().BoolTy);
John McCallf4528ae2011-09-13 03:34:09 +0000724
Daniel Dunbar1ef73732009-02-03 23:43:59 +0000725 // FIXME: We shouldn't need to get the function info here, the
726 // runtime already should have computed it to build the function.
John McCallf4528ae2011-09-13 03:34:09 +0000727 RValue RV = EmitCall(getTypes().getFunctionInfo(propType, args,
John McCallb923ece2011-09-12 23:06:44 +0000728 FunctionType::ExtInfo()),
John McCallf4528ae2011-09-13 03:34:09 +0000729 getPropertyFn, ReturnValueSlot(), args);
730
Daniel Dunbara08dff12008-09-24 04:04:31 +0000731 // We need to fix the type here. Ivars with copy & retain are
732 // always objects so we don't need to worry about complex or
733 // aggregates.
Mike Stump11289f42009-09-09 15:08:12 +0000734 RV = RValue::get(Builder.CreateBitCast(RV.getScalarVal(),
John McCallf4528ae2011-09-13 03:34:09 +0000735 getTypes().ConvertType(propType)));
736
737 EmitReturnOfRValue(RV, propType);
John McCall31168b02011-06-15 23:02:42 +0000738
739 // objc_getProperty does an autorelease, so we should suppress ours.
740 AutoreleaseResult = false;
John McCall31168b02011-06-15 23:02:42 +0000741
John McCallf4528ae2011-09-13 03:34:09 +0000742 return;
743 }
744
745 case PropertyImplStrategy::CopyStruct:
746 emitStructGetterCall(*this, ivar, strategy.isAtomic(),
747 strategy.hasStrongMember());
748 return;
749
750 case PropertyImplStrategy::Expression:
751 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
752 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
753
754 QualType ivarType = ivar->getType();
755 if (ivarType->isAnyComplexType()) {
756 ComplexPairTy pair = LoadComplexFromAddr(LV.getAddress(),
757 LV.isVolatileQualified());
758 StoreComplexToAddr(pair, ReturnValue, LV.isVolatileQualified());
759 } else if (hasAggregateLLVMType(ivarType)) {
760 // The return value slot is guaranteed to not be aliased, but
761 // that's not necessarily the same as "on the stack", so
762 // we still potentially need objc_memmove_collectable.
763 EmitAggregateCopy(ReturnValue, LV.getAddress(), ivarType);
764 } else {
John McCall24fada12011-07-22 05:23:13 +0000765 llvm::Value *value;
766 if (propType->isReferenceType()) {
767 value = LV.getAddress();
768 } else {
769 // We want to load and autoreleaseReturnValue ARC __weak ivars.
770 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
John McCallf4528ae2011-09-13 03:34:09 +0000771 value = emitARCRetainLoadOfScalar(*this, LV, ivarType);
John McCall24fada12011-07-22 05:23:13 +0000772
773 // Otherwise we want to do a simple load, suppressing the
774 // final autorelease.
John McCall31168b02011-06-15 23:02:42 +0000775 } else {
John McCall24fada12011-07-22 05:23:13 +0000776 value = EmitLoadOfLValue(LV).getScalarVal();
777 AutoreleaseResult = false;
Fariborz Jahanianb24b5682011-03-28 23:47:18 +0000778 }
John McCall31168b02011-06-15 23:02:42 +0000779
John McCall24fada12011-07-22 05:23:13 +0000780 value = Builder.CreateBitCast(value, ConvertType(propType));
781 }
782
783 EmitReturnOfRValue(RValue::get(value), propType);
Fariborz Jahanianeab5ecd2009-03-03 18:49:40 +0000784 }
John McCallf4528ae2011-09-13 03:34:09 +0000785 return;
Daniel Dunbara08dff12008-09-24 04:04:31 +0000786 }
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000787
John McCallf4528ae2011-09-13 03:34:09 +0000788 }
789 llvm_unreachable("bad @property implementation strategy!");
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000790}
791
John McCallb923ece2011-09-12 23:06:44 +0000792/// emitStructSetterCall - Call the runtime function to store the value
793/// from the first formal parameter into the given ivar.
794static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD,
795 ObjCIvarDecl *ivar) {
Fariborz Jahanian302a3d42011-02-18 19:15:13 +0000796 // objc_copyStruct (&structIvar, &Arg,
797 // sizeof (struct something), true, false);
John McCall6acaef92011-09-10 09:30:49 +0000798 CallArgList args;
799
800 // The first argument is the address of the ivar.
John McCallb923ece2011-09-12 23:06:44 +0000801 llvm::Value *ivarAddr = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
802 CGF.LoadObjCSelf(), ivar, 0)
803 .getAddress();
804 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
805 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
John McCall6acaef92011-09-10 09:30:49 +0000806
807 // The second argument is the address of the parameter variable.
John McCallb923ece2011-09-12 23:06:44 +0000808 ParmVarDecl *argVar = *OMD->param_begin();
Fariborz Jahanian088f1bc2012-01-05 00:10:16 +0000809 DeclRefExpr argRef(argVar, argVar->getType().getNonReferenceType(),
810 VK_LValue, SourceLocation());
John McCallb923ece2011-09-12 23:06:44 +0000811 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress();
812 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
813 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
John McCall6acaef92011-09-10 09:30:49 +0000814
815 // The third argument is the sizeof the type.
816 llvm::Value *size =
John McCallb923ece2011-09-12 23:06:44 +0000817 CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(ivar->getType()));
818 args.add(RValue::get(size), CGF.getContext().getSizeType());
John McCall6acaef92011-09-10 09:30:49 +0000819
John McCallb923ece2011-09-12 23:06:44 +0000820 // The fourth argument is the 'isAtomic' flag.
821 args.add(RValue::get(CGF.Builder.getTrue()), CGF.getContext().BoolTy);
John McCall6acaef92011-09-10 09:30:49 +0000822
John McCallb923ece2011-09-12 23:06:44 +0000823 // The fifth argument is the 'hasStrong' flag.
824 // FIXME: should this really always be false?
825 args.add(RValue::get(CGF.Builder.getFalse()), CGF.getContext().BoolTy);
826
827 llvm::Value *copyStructFn = CGF.CGM.getObjCRuntime().GetSetStructFunction();
828 CGF.EmitCall(CGF.getTypes().getFunctionInfo(CGF.getContext().VoidTy, args,
829 FunctionType::ExtInfo()),
830 copyStructFn, ReturnValueSlot(), args);
Fariborz Jahanian302a3d42011-02-18 19:15:13 +0000831}
832
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +0000833/// emitCPPObjectAtomicSetterCall - Call the runtime function to store
834/// the value from the first formal parameter into the given ivar, using
835/// the Cpp API for atomic Cpp objects with non-trivial copy assignment.
836static void emitCPPObjectAtomicSetterCall(CodeGenFunction &CGF,
837 ObjCMethodDecl *OMD,
838 ObjCIvarDecl *ivar,
839 llvm::Constant *AtomicHelperFn) {
840 // objc_copyCppObjectAtomic (&CppObjectIvar, &Arg,
841 // AtomicHelperFn);
842 CallArgList args;
843
844 // The first argument is the address of the ivar.
845 llvm::Value *ivarAddr =
846 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
847 CGF.LoadObjCSelf(), ivar, 0).getAddress();
848 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
849 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
850
851 // The second argument is the address of the parameter variable.
852 ParmVarDecl *argVar = *OMD->param_begin();
853 DeclRefExpr argRef(argVar, argVar->getType().getNonReferenceType(),
854 VK_LValue, SourceLocation());
855 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress();
856 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
857 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
858
859 // Third argument is the helper function.
860 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
861
862 llvm::Value *copyCppAtomicObjectFn =
863 CGF.CGM.getObjCRuntime().GetCppAtomicObjectFunction();
864 CGF.EmitCall(CGF.getTypes().getFunctionInfo(CGF.getContext().VoidTy, args,
865 FunctionType::ExtInfo()),
866 copyCppAtomicObjectFn, ReturnValueSlot(), args);
867
868
869}
870
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000871
John McCallf4528ae2011-09-13 03:34:09 +0000872static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID) {
873 Expr *setter = PID->getSetterCXXAssignment();
874 if (!setter) return true;
875
876 // Sema only makes only of these when the ivar has a C++ class type,
877 // so the form is pretty constrained.
John McCall7f16c422011-09-10 09:17:20 +0000878
879 // An operator call is trivial if the function it calls is trivial.
John McCallf4528ae2011-09-13 03:34:09 +0000880 // This also implies that there's nothing non-trivial going on with
881 // the arguments, because operator= can only be trivial if it's a
882 // synthesized assignment operator and therefore both parameters are
883 // references.
884 if (CallExpr *call = dyn_cast<CallExpr>(setter)) {
John McCall7f16c422011-09-10 09:17:20 +0000885 if (const FunctionDecl *callee
886 = dyn_cast_or_null<FunctionDecl>(call->getCalleeDecl()))
887 if (callee->isTrivial())
888 return true;
889 return false;
Fariborz Jahanian5de53132011-04-06 16:05:26 +0000890 }
John McCall7f16c422011-09-10 09:17:20 +0000891
John McCallf4528ae2011-09-13 03:34:09 +0000892 assert(isa<ExprWithCleanups>(setter));
John McCall7f16c422011-09-10 09:17:20 +0000893 return false;
894}
895
John McCall7f16c422011-09-10 09:17:20 +0000896void
897CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +0000898 const ObjCPropertyImplDecl *propImpl,
899 llvm::Constant *AtomicHelperFn) {
John McCall7f16c422011-09-10 09:17:20 +0000900 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
Fariborz Jahanian17eaf402012-01-06 00:29:35 +0000901 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
John McCall7f16c422011-09-10 09:17:20 +0000902 ObjCMethodDecl *setterMethod = prop->getSetterMethodDecl();
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +0000903
904 // Just use the setter expression if Sema gave us one and it's
905 // non-trivial.
906 if (!hasTrivialSetExpr(propImpl)) {
907 if (!AtomicHelperFn)
908 // If non-atomic, assignment is called directly.
909 EmitStmt(propImpl->getSetterCXXAssignment());
910 else
911 // If atomic, assignment is called via a locking api.
912 emitCPPObjectAtomicSetterCall(*this, setterMethod, ivar,
913 AtomicHelperFn);
914 return;
915 }
John McCall7f16c422011-09-10 09:17:20 +0000916
John McCallf4528ae2011-09-13 03:34:09 +0000917 PropertyImplStrategy strategy(CGM, propImpl);
918 switch (strategy.getKind()) {
919 case PropertyImplStrategy::Native: {
920 llvm::Value *argAddr = LocalDeclMap[*setterMethod->param_begin()];
John McCall7f16c422011-09-10 09:17:20 +0000921
John McCallf4528ae2011-09-13 03:34:09 +0000922 LValue ivarLValue =
923 EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, /*quals*/ 0);
924 llvm::Value *ivarAddr = ivarLValue.getAddress();
John McCall7f16c422011-09-10 09:17:20 +0000925
John McCallf4528ae2011-09-13 03:34:09 +0000926 // Currently, all atomic accesses have to be through integer
927 // types, so there's no point in trying to pick a prettier type.
928 llvm::Type *bitcastType =
929 llvm::Type::getIntNTy(getLLVMContext(),
930 getContext().toBits(strategy.getIvarSize()));
931 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
932
933 // Cast both arguments to the chosen operation type.
934 argAddr = Builder.CreateBitCast(argAddr, bitcastType);
935 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
936
937 // This bitcast load is likely to cause some nasty IR.
938 llvm::Value *load = Builder.CreateLoad(argAddr);
939
940 // Perform an atomic store. There are no memory ordering requirements.
941 llvm::StoreInst *store = Builder.CreateStore(load, ivarAddr);
942 store->setAlignment(strategy.getIvarAlignment().getQuantity());
943 store->setAtomic(llvm::Unordered);
944 return;
945 }
946
947 case PropertyImplStrategy::GetSetProperty:
948 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
John McCall7f16c422011-09-10 09:17:20 +0000949 llvm::Value *setPropertyFn =
950 CGM.getObjCRuntime().GetPropertySetFunction();
951 if (!setPropertyFn) {
952 CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy");
953 return;
954 }
955
956 // Emit objc_setProperty((id) self, _cmd, offset, arg,
957 // <is-atomic>, <is-copy>).
958 llvm::Value *cmd =
959 Builder.CreateLoad(LocalDeclMap[setterMethod->getCmdDecl()]);
960 llvm::Value *self =
961 Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
962 llvm::Value *ivarOffset =
963 EmitIvarOffset(classImpl->getClassInterface(), ivar);
964 llvm::Value *arg = LocalDeclMap[*setterMethod->param_begin()];
965 arg = Builder.CreateBitCast(Builder.CreateLoad(arg, "arg"), VoidPtrTy);
966
967 CallArgList args;
968 args.add(RValue::get(self), getContext().getObjCIdType());
969 args.add(RValue::get(cmd), getContext().getObjCSelType());
970 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
971 args.add(RValue::get(arg), getContext().getObjCIdType());
John McCallf4528ae2011-09-13 03:34:09 +0000972 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
973 getContext().BoolTy);
974 args.add(RValue::get(Builder.getInt1(strategy.isCopy())),
975 getContext().BoolTy);
John McCall7f16c422011-09-10 09:17:20 +0000976 // FIXME: We shouldn't need to get the function info here, the runtime
977 // already should have computed it to build the function.
978 EmitCall(getTypes().getFunctionInfo(getContext().VoidTy, args,
979 FunctionType::ExtInfo()),
980 setPropertyFn, ReturnValueSlot(), args);
981 return;
982 }
983
John McCallf4528ae2011-09-13 03:34:09 +0000984 case PropertyImplStrategy::CopyStruct:
John McCallb923ece2011-09-12 23:06:44 +0000985 emitStructSetterCall(*this, setterMethod, ivar);
John McCall7f16c422011-09-10 09:17:20 +0000986 return;
John McCallf4528ae2011-09-13 03:34:09 +0000987
988 case PropertyImplStrategy::Expression:
989 break;
John McCall7f16c422011-09-10 09:17:20 +0000990 }
991
992 // Otherwise, fake up some ASTs and emit a normal assignment.
993 ValueDecl *selfDecl = setterMethod->getSelfDecl();
994 DeclRefExpr self(selfDecl, selfDecl->getType(), VK_LValue, SourceLocation());
995 ImplicitCastExpr selfLoad(ImplicitCastExpr::OnStack,
996 selfDecl->getType(), CK_LValueToRValue, &self,
997 VK_RValue);
998 ObjCIvarRefExpr ivarRef(ivar, ivar->getType().getNonReferenceType(),
999 SourceLocation(), &selfLoad, true, true);
1000
1001 ParmVarDecl *argDecl = *setterMethod->param_begin();
1002 QualType argType = argDecl->getType().getNonReferenceType();
1003 DeclRefExpr arg(argDecl, argType, VK_LValue, SourceLocation());
1004 ImplicitCastExpr argLoad(ImplicitCastExpr::OnStack,
1005 argType.getUnqualifiedType(), CK_LValueToRValue,
1006 &arg, VK_RValue);
1007
1008 // The property type can differ from the ivar type in some situations with
1009 // Objective-C pointer types, we can always bit cast the RHS in these cases.
1010 // The following absurdity is just to ensure well-formed IR.
1011 CastKind argCK = CK_NoOp;
1012 if (ivarRef.getType()->isObjCObjectPointerType()) {
1013 if (argLoad.getType()->isObjCObjectPointerType())
1014 argCK = CK_BitCast;
1015 else if (argLoad.getType()->isBlockPointerType())
1016 argCK = CK_BlockPointerToObjCPointerCast;
1017 else
1018 argCK = CK_CPointerToObjCPointerCast;
1019 } else if (ivarRef.getType()->isBlockPointerType()) {
1020 if (argLoad.getType()->isBlockPointerType())
1021 argCK = CK_BitCast;
1022 else
1023 argCK = CK_AnyPointerToBlockPointerCast;
1024 } else if (ivarRef.getType()->isPointerType()) {
1025 argCK = CK_BitCast;
1026 }
1027 ImplicitCastExpr argCast(ImplicitCastExpr::OnStack,
1028 ivarRef.getType(), argCK, &argLoad,
1029 VK_RValue);
1030 Expr *finalArg = &argLoad;
1031 if (!getContext().hasSameUnqualifiedType(ivarRef.getType(),
1032 argLoad.getType()))
1033 finalArg = &argCast;
1034
1035
1036 BinaryOperator assign(&ivarRef, finalArg, BO_Assign,
1037 ivarRef.getType(), VK_RValue, OK_Ordinary,
1038 SourceLocation());
1039 EmitStmt(&assign);
Fariborz Jahanian5de53132011-04-06 16:05:26 +00001040}
1041
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001042/// GenerateObjCSetter - Generate an Objective-C property setter
Steve Naroff5a7dd782009-01-10 22:55:25 +00001043/// function. The given Decl must be an ObjCImplementationDecl. @synthesize
1044/// is illegal within a category.
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00001045void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
1046 const ObjCPropertyImplDecl *PID) {
Fariborz Jahanian4b501a22012-01-07 18:56:22 +00001047 llvm::Constant *AtomicHelperFn =
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001048 GenerateObjCAtomicSetterCopyHelperFunction(PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001049 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
1050 ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
1051 assert(OMD && "Invalid call to generate setter (empty method)");
Devang Patele7ce5402011-05-19 23:37:41 +00001052 StartObjCMethod(OMD, IMP->getClassInterface(), PID->getLocStart());
Daniel Dunbar5449ce52008-09-24 06:32:09 +00001053
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001054 generateObjCSetterBody(IMP, PID, AtomicHelperFn);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001055
1056 FinishFunction();
Chris Lattner5696e7b2008-06-17 18:05:57 +00001057}
1058
John McCall6a4fa522011-03-22 07:05:39 +00001059namespace {
John McCall4bd0fb12011-07-12 16:41:08 +00001060 struct DestroyIvar : EHScopeStack::Cleanup {
1061 private:
1062 llvm::Value *addr;
John McCall6a4fa522011-03-22 07:05:39 +00001063 const ObjCIvarDecl *ivar;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001064 CodeGenFunction::Destroyer *destroyer;
John McCall4bd0fb12011-07-12 16:41:08 +00001065 bool useEHCleanupForArray;
1066 public:
1067 DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
1068 CodeGenFunction::Destroyer *destroyer,
1069 bool useEHCleanupForArray)
Peter Collingbourne1425b452012-01-26 03:33:36 +00001070 : addr(addr), ivar(ivar), destroyer(destroyer),
John McCall4bd0fb12011-07-12 16:41:08 +00001071 useEHCleanupForArray(useEHCleanupForArray) {}
John McCall6a4fa522011-03-22 07:05:39 +00001072
John McCall30317fd2011-07-12 20:27:29 +00001073 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall4bd0fb12011-07-12 16:41:08 +00001074 LValue lvalue
1075 = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
1076 CGF.emitDestroy(lvalue.getAddress(), ivar->getType(), destroyer,
John McCall30317fd2011-07-12 20:27:29 +00001077 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCall6a4fa522011-03-22 07:05:39 +00001078 }
1079 };
1080}
1081
John McCall4bd0fb12011-07-12 16:41:08 +00001082/// Like CodeGenFunction::destroyARCStrong, but do it with a call.
1083static void destroyARCStrongWithStore(CodeGenFunction &CGF,
1084 llvm::Value *addr,
1085 QualType type) {
1086 llvm::Value *null = getNullForVariable(addr);
1087 CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
1088}
John McCall31168b02011-06-15 23:02:42 +00001089
John McCall6a4fa522011-03-22 07:05:39 +00001090static void emitCXXDestructMethod(CodeGenFunction &CGF,
1091 ObjCImplementationDecl *impl) {
1092 CodeGenFunction::RunCleanupsScope scope(CGF);
1093
1094 llvm::Value *self = CGF.LoadObjCSelf();
1095
Jordy Rosea91768e2011-07-22 02:08:32 +00001096 const ObjCInterfaceDecl *iface = impl->getClassInterface();
1097 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCall6a4fa522011-03-22 07:05:39 +00001098 ivar; ivar = ivar->getNextIvar()) {
1099 QualType type = ivar->getType();
1100
John McCall6a4fa522011-03-22 07:05:39 +00001101 // Check whether the ivar is a destructible type.
John McCall4bd0fb12011-07-12 16:41:08 +00001102 QualType::DestructionKind dtorKind = type.isDestructedType();
1103 if (!dtorKind) continue;
John McCall6a4fa522011-03-22 07:05:39 +00001104
John McCall4bd0fb12011-07-12 16:41:08 +00001105 CodeGenFunction::Destroyer *destroyer = 0;
John McCall6a4fa522011-03-22 07:05:39 +00001106
John McCall4bd0fb12011-07-12 16:41:08 +00001107 // Use a call to objc_storeStrong to destroy strong ivars, for the
1108 // general benefit of the tools.
1109 if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne1425b452012-01-26 03:33:36 +00001110 destroyer = destroyARCStrongWithStore;
John McCall31168b02011-06-15 23:02:42 +00001111
John McCall4bd0fb12011-07-12 16:41:08 +00001112 // Otherwise use the default for the destruction kind.
1113 } else {
Peter Collingbourne1425b452012-01-26 03:33:36 +00001114 destroyer = CGF.getDestroyer(dtorKind);
John McCall6a4fa522011-03-22 07:05:39 +00001115 }
John McCall4bd0fb12011-07-12 16:41:08 +00001116
1117 CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);
1118
1119 CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer,
1120 cleanupKind & EHCleanup);
John McCall6a4fa522011-03-22 07:05:39 +00001121 }
1122
1123 assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
1124}
1125
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001126void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1127 ObjCMethodDecl *MD,
1128 bool ctor) {
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001129 MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
Devang Patele7ce5402011-05-19 23:37:41 +00001130 StartObjCMethod(MD, IMP->getClassInterface(), MD->getLocStart());
John McCall6a4fa522011-03-22 07:05:39 +00001131
1132 // Emit .cxx_construct.
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001133 if (ctor) {
John McCall31168b02011-06-15 23:02:42 +00001134 // Suppress the final autorelease in ARC.
1135 AutoreleaseResult = false;
1136
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001137 SmallVector<CXXCtorInitializer *, 8> IvarInitializers;
John McCall6a4fa522011-03-22 07:05:39 +00001138 for (ObjCImplementationDecl::init_const_iterator B = IMP->init_begin(),
1139 E = IMP->init_end(); B != E; ++B) {
1140 CXXCtorInitializer *IvarInit = (*B);
Francois Pichetd583da02010-12-04 09:14:42 +00001141 FieldDecl *Field = IvarInit->getAnyMember();
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001142 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Fariborz Jahanian499b9022010-04-28 22:30:33 +00001143 LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
1144 LoadObjCSelf(), Ivar, 0);
John McCall8d6fc952011-08-25 20:40:09 +00001145 EmitAggExpr(IvarInit->getInit(),
1146 AggValueSlot::forLValue(LV, AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00001147 AggValueSlot::DoesNotNeedGCBarriers,
1148 AggValueSlot::IsNotAliased));
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001149 }
1150 // constructor returns 'self'.
1151 CodeGenTypes &Types = CGM.getTypes();
1152 QualType IdTy(CGM.getContext().getObjCIdType());
1153 llvm::Value *SelfAsId =
1154 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
1155 EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
John McCall6a4fa522011-03-22 07:05:39 +00001156
1157 // Emit .cxx_destruct.
Chandler Carruthf3983652010-05-06 00:20:39 +00001158 } else {
John McCall6a4fa522011-03-22 07:05:39 +00001159 emitCXXDestructMethod(*this, IMP);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001160 }
1161 FinishFunction();
1162}
1163
Fariborz Jahanian08b0f662010-04-13 00:38:05 +00001164bool CodeGenFunction::IndirectObjCSetterArg(const CGFunctionInfo &FI) {
1165 CGFunctionInfo::const_arg_iterator it = FI.arg_begin();
1166 it++; it++;
1167 const ABIArgInfo &AI = it->info;
1168 // FIXME. Is this sufficient check?
1169 return (AI.getKind() == ABIArgInfo::Indirect);
1170}
1171
Fariborz Jahanian7e9d52a2010-04-13 18:32:24 +00001172bool CodeGenFunction::IvarTypeWithAggrGCObjects(QualType Ty) {
Douglas Gregor79a91412011-09-13 17:21:33 +00001173 if (CGM.getLangOptions().getGC() == LangOptions::NonGC)
Fariborz Jahanian7e9d52a2010-04-13 18:32:24 +00001174 return false;
1175 if (const RecordType *FDTTy = Ty.getTypePtr()->getAs<RecordType>())
1176 return FDTTy->getDecl()->hasObjectMember();
1177 return false;
1178}
1179
Daniel Dunbara08dff12008-09-24 04:04:31 +00001180llvm::Value *CodeGenFunction::LoadObjCSelf() {
Daniel Dunbara94ecd22008-08-16 03:19:19 +00001181 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1182 return Builder.CreateLoad(LocalDeclMap[OMD->getSelfDecl()], "self");
Chris Lattner5696e7b2008-06-17 18:05:57 +00001183}
1184
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00001185QualType CodeGenFunction::TypeOfSelfObject() {
1186 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1187 ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
Steve Naroff7cae42b2009-07-10 23:34:53 +00001188 const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
1189 getContext().getCanonicalType(selfDecl->getType()));
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00001190 return PTy->getPointeeType();
1191}
1192
Chris Lattnerd4808922009-03-22 21:03:39 +00001193void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
Mike Stump11289f42009-09-09 15:08:12 +00001194 llvm::Constant *EnumerationMutationFn =
Daniel Dunbara08dff12008-09-24 04:04:31 +00001195 CGM.getObjCRuntime().EnumerationMutationFunction();
Mike Stump11289f42009-09-09 15:08:12 +00001196
Daniel Dunbara08dff12008-09-24 04:04:31 +00001197 if (!EnumerationMutationFn) {
1198 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
1199 return;
1200 }
1201
Devang Pateld2d66652011-01-19 01:36:36 +00001202 CGDebugInfo *DI = getDebugInfo();
Eric Christopher7cdf9482011-10-13 21:45:18 +00001203 if (DI)
1204 DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
Devang Pateld2d66652011-01-19 01:36:36 +00001205
Devang Patel297207f2011-06-13 23:15:32 +00001206 // The local variable comes into scope immediately.
1207 AutoVarEmission variable = AutoVarEmission::invalid();
1208 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
1209 variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
1210
John McCall1c926b72011-01-07 01:49:06 +00001211 JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
Mike Stump11289f42009-09-09 15:08:12 +00001212
Anders Carlsson75658592008-08-31 02:33:12 +00001213 // Fast enumeration state.
Douglas Gregor636e2002011-08-09 17:23:49 +00001214 QualType StateTy = CGM.getObjCFastEnumerationStateType();
Daniel Dunbara7566f12010-02-09 02:48:28 +00001215 llvm::Value *StatePtr = CreateMemTemp(StateTy, "state.ptr");
Anders Carlssonc0964b62010-05-22 17:35:42 +00001216 EmitNullInitialization(StatePtr, StateTy);
Mike Stump11289f42009-09-09 15:08:12 +00001217
Anders Carlsson75658592008-08-31 02:33:12 +00001218 // Number of elements in the items array.
Anders Carlsson3f35a262008-08-31 04:05:03 +00001219 static const unsigned NumItems = 16;
Mike Stump11289f42009-09-09 15:08:12 +00001220
John McCall1c926b72011-01-07 01:49:06 +00001221 // Fetch the countByEnumeratingWithState:objects:count: selector.
Benjamin Kramer9e649c32010-03-30 11:36:44 +00001222 IdentifierInfo *II[] = {
1223 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
1224 &CGM.getContext().Idents.get("objects"),
1225 &CGM.getContext().Idents.get("count")
1226 };
1227 Selector FastEnumSel =
1228 CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
Anders Carlsson75658592008-08-31 02:33:12 +00001229
1230 QualType ItemsTy =
1231 getContext().getConstantArrayType(getContext().getObjCIdType(),
Mike Stump11289f42009-09-09 15:08:12 +00001232 llvm::APInt(32, NumItems),
Anders Carlsson75658592008-08-31 02:33:12 +00001233 ArrayType::Normal, 0);
Daniel Dunbara7566f12010-02-09 02:48:28 +00001234 llvm::Value *ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
Mike Stump11289f42009-09-09 15:08:12 +00001235
John McCall53848232011-07-27 01:07:15 +00001236 // Emit the collection pointer. In ARC, we do a retain.
1237 llvm::Value *Collection;
1238 if (getLangOptions().ObjCAutoRefCount) {
1239 Collection = EmitARCRetainScalarExpr(S.getCollection());
1240
1241 // Enter a cleanup to do the release.
1242 EmitObjCConsumeObject(S.getCollection()->getType(), Collection);
1243 } else {
1244 Collection = EmitScalarExpr(S.getCollection());
1245 }
Mike Stump11289f42009-09-09 15:08:12 +00001246
John McCall91e82dd2011-08-05 00:14:38 +00001247 // The 'continue' label needs to appear within the cleanup for the
1248 // collection object.
1249 JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
1250
John McCall1c926b72011-01-07 01:49:06 +00001251 // Send it our message:
Anders Carlsson75658592008-08-31 02:33:12 +00001252 CallArgList Args;
John McCall1c926b72011-01-07 01:49:06 +00001253
1254 // The first argument is a temporary of the enumeration-state type.
Eli Friedman43dca6a2011-05-02 17:57:46 +00001255 Args.add(RValue::get(StatePtr), getContext().getPointerType(StateTy));
Mike Stump11289f42009-09-09 15:08:12 +00001256
John McCall1c926b72011-01-07 01:49:06 +00001257 // The second argument is a temporary array with space for NumItems
1258 // pointers. We'll actually be loading elements from the array
1259 // pointer written into the control state; this buffer is so that
1260 // collections that *aren't* backed by arrays can still queue up
1261 // batches of elements.
Eli Friedman43dca6a2011-05-02 17:57:46 +00001262 Args.add(RValue::get(ItemsPtr), getContext().getPointerType(ItemsTy));
Mike Stump11289f42009-09-09 15:08:12 +00001263
John McCall1c926b72011-01-07 01:49:06 +00001264 // The third argument is the capacity of that temporary array.
Chris Lattner2192fe52011-07-18 04:24:23 +00001265 llvm::Type *UnsignedLongLTy = ConvertType(getContext().UnsignedLongTy);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001266 llvm::Constant *Count = llvm::ConstantInt::get(UnsignedLongLTy, NumItems);
Eli Friedman43dca6a2011-05-02 17:57:46 +00001267 Args.add(RValue::get(Count), getContext().UnsignedLongTy);
Mike Stump11289f42009-09-09 15:08:12 +00001268
John McCall1c926b72011-01-07 01:49:06 +00001269 // Start the enumeration.
Mike Stump11289f42009-09-09 15:08:12 +00001270 RValue CountRV =
John McCall78a15112010-05-22 01:48:05 +00001271 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlsson75658592008-08-31 02:33:12 +00001272 getContext().UnsignedLongTy,
1273 FastEnumSel,
David Chisnall01aa4672010-04-28 19:33:36 +00001274 Collection, Args);
Anders Carlsson75658592008-08-31 02:33:12 +00001275
John McCall1c926b72011-01-07 01:49:06 +00001276 // The initial number of objects that were returned in the buffer.
1277 llvm::Value *initialBufferLimit = CountRV.getScalarVal();
Mike Stump11289f42009-09-09 15:08:12 +00001278
John McCall1c926b72011-01-07 01:49:06 +00001279 llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
1280 llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
Mike Stump11289f42009-09-09 15:08:12 +00001281
John McCall1c926b72011-01-07 01:49:06 +00001282 llvm::Value *zero = llvm::Constant::getNullValue(UnsignedLongLTy);
Anders Carlsson75658592008-08-31 02:33:12 +00001283
John McCall1c926b72011-01-07 01:49:06 +00001284 // If the limit pointer was zero to begin with, the collection is
1285 // empty; skip all this.
1286 Builder.CreateCondBr(Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"),
1287 EmptyBB, LoopInitBB);
Anders Carlsson75658592008-08-31 02:33:12 +00001288
John McCall1c926b72011-01-07 01:49:06 +00001289 // Otherwise, initialize the loop.
1290 EmitBlock(LoopInitBB);
Mike Stump11289f42009-09-09 15:08:12 +00001291
John McCall1c926b72011-01-07 01:49:06 +00001292 // Save the initial mutations value. This is the value at an
1293 // address that was written into the state object by
1294 // countByEnumeratingWithState:objects:count:.
Mike Stump11289f42009-09-09 15:08:12 +00001295 llvm::Value *StateMutationsPtrPtr =
Anders Carlsson3f35a262008-08-31 04:05:03 +00001296 Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
Mike Stump11289f42009-09-09 15:08:12 +00001297 llvm::Value *StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr,
Anders Carlsson3f35a262008-08-31 04:05:03 +00001298 "mutationsptr");
Mike Stump11289f42009-09-09 15:08:12 +00001299
John McCall1c926b72011-01-07 01:49:06 +00001300 llvm::Value *initialMutations =
1301 Builder.CreateLoad(StateMutationsPtr, "forcoll.initial-mutations");
Mike Stump11289f42009-09-09 15:08:12 +00001302
John McCall1c926b72011-01-07 01:49:06 +00001303 // Start looping. This is the point we return to whenever we have a
1304 // fresh, non-empty batch of objects.
1305 llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
1306 EmitBlock(LoopBodyBB);
Mike Stump11289f42009-09-09 15:08:12 +00001307
John McCall1c926b72011-01-07 01:49:06 +00001308 // The current index into the buffer.
Jay Foad20c0f022011-03-30 11:28:58 +00001309 llvm::PHINode *index = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.index");
John McCall1c926b72011-01-07 01:49:06 +00001310 index->addIncoming(zero, LoopInitBB);
Anders Carlsson75658592008-08-31 02:33:12 +00001311
John McCall1c926b72011-01-07 01:49:06 +00001312 // The current buffer size.
Jay Foad20c0f022011-03-30 11:28:58 +00001313 llvm::PHINode *count = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.count");
John McCall1c926b72011-01-07 01:49:06 +00001314 count->addIncoming(initialBufferLimit, LoopInitBB);
Mike Stump11289f42009-09-09 15:08:12 +00001315
John McCall1c926b72011-01-07 01:49:06 +00001316 // Check whether the mutations value has changed from where it was
1317 // at start. StateMutationsPtr should actually be invariant between
1318 // refreshes.
Anders Carlsson3f35a262008-08-31 04:05:03 +00001319 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
John McCall1c926b72011-01-07 01:49:06 +00001320 llvm::Value *currentMutations
1321 = Builder.CreateLoad(StateMutationsPtr, "statemutations");
Anders Carlsson3f35a262008-08-31 04:05:03 +00001322
John McCall1c926b72011-01-07 01:49:06 +00001323 llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
Dan Gohman6ca99822011-03-02 22:39:34 +00001324 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
Mike Stump11289f42009-09-09 15:08:12 +00001325
John McCall1c926b72011-01-07 01:49:06 +00001326 Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
1327 WasNotMutatedBB, WasMutatedBB);
Mike Stump11289f42009-09-09 15:08:12 +00001328
John McCall1c926b72011-01-07 01:49:06 +00001329 // If so, call the enumeration-mutation function.
1330 EmitBlock(WasMutatedBB);
Anders Carlsson3f35a262008-08-31 04:05:03 +00001331 llvm::Value *V =
Mike Stump11289f42009-09-09 15:08:12 +00001332 Builder.CreateBitCast(Collection,
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001333 ConvertType(getContext().getObjCIdType()));
Daniel Dunbar84388bf2009-02-03 23:55:40 +00001334 CallArgList Args2;
Eli Friedman43dca6a2011-05-02 17:57:46 +00001335 Args2.add(RValue::get(V), getContext().getObjCIdType());
Mike Stump18bb9282009-05-16 07:57:57 +00001336 // FIXME: We shouldn't need to get the function info here, the runtime already
1337 // should have computed it to build the function.
John McCallab26cfa2010-02-05 21:31:56 +00001338 EmitCall(CGM.getTypes().getFunctionInfo(getContext().VoidTy, Args2,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001339 FunctionType::ExtInfo()),
Anders Carlsson61a401c2009-12-24 19:25:24 +00001340 EnumerationMutationFn, ReturnValueSlot(), Args2);
Mike Stump11289f42009-09-09 15:08:12 +00001341
John McCall1c926b72011-01-07 01:49:06 +00001342 // Otherwise, or if the mutation function returns, just continue.
1343 EmitBlock(WasNotMutatedBB);
Mike Stump11289f42009-09-09 15:08:12 +00001344
John McCall1c926b72011-01-07 01:49:06 +00001345 // Initialize the element variable.
1346 RunCleanupsScope elementVariableScope(*this);
John McCall9e2e22f2011-02-22 07:16:58 +00001347 bool elementIsVariable;
John McCall1c926b72011-01-07 01:49:06 +00001348 LValue elementLValue;
1349 QualType elementType;
1350 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
John McCall9e2e22f2011-02-22 07:16:58 +00001351 // Initialize the variable, in case it's a __block variable or something.
1352 EmitAutoVarInit(variable);
John McCall1c926b72011-01-07 01:49:06 +00001353
John McCall9e2e22f2011-02-22 07:16:58 +00001354 const VarDecl* D = cast<VarDecl>(SD->getSingleDecl());
John McCall1c926b72011-01-07 01:49:06 +00001355 DeclRefExpr tempDRE(const_cast<VarDecl*>(D), D->getType(),
1356 VK_LValue, SourceLocation());
1357 elementLValue = EmitLValue(&tempDRE);
1358 elementType = D->getType();
John McCall9e2e22f2011-02-22 07:16:58 +00001359 elementIsVariable = true;
John McCalld4631322011-06-17 06:42:21 +00001360
1361 if (D->isARCPseudoStrong())
1362 elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);
John McCall1c926b72011-01-07 01:49:06 +00001363 } else {
1364 elementLValue = LValue(); // suppress warning
1365 elementType = cast<Expr>(S.getElement())->getType();
John McCall9e2e22f2011-02-22 07:16:58 +00001366 elementIsVariable = false;
John McCall1c926b72011-01-07 01:49:06 +00001367 }
Chris Lattner2192fe52011-07-18 04:24:23 +00001368 llvm::Type *convertedElementType = ConvertType(elementType);
John McCall1c926b72011-01-07 01:49:06 +00001369
1370 // Fetch the buffer out of the enumeration state.
1371 // TODO: this pointer should actually be invariant between
1372 // refreshes, which would help us do certain loop optimizations.
Mike Stump11289f42009-09-09 15:08:12 +00001373 llvm::Value *StateItemsPtr =
Anders Carlsson75658592008-08-31 02:33:12 +00001374 Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
John McCall1c926b72011-01-07 01:49:06 +00001375 llvm::Value *EnumStateItems =
1376 Builder.CreateLoad(StateItemsPtr, "stateitems");
Anders Carlsson75658592008-08-31 02:33:12 +00001377
John McCall1c926b72011-01-07 01:49:06 +00001378 // Fetch the value at the current index from the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00001379 llvm::Value *CurrentItemPtr =
John McCall1c926b72011-01-07 01:49:06 +00001380 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
1381 llvm::Value *CurrentItem = Builder.CreateLoad(CurrentItemPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001382
John McCall1c926b72011-01-07 01:49:06 +00001383 // Cast that value to the right type.
1384 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
1385 "currentitem");
Mike Stump11289f42009-09-09 15:08:12 +00001386
John McCall1c926b72011-01-07 01:49:06 +00001387 // Make sure we have an l-value. Yes, this gets evaluated every
1388 // time through the loop.
John McCalld4631322011-06-17 06:42:21 +00001389 if (!elementIsVariable) {
John McCall1c926b72011-01-07 01:49:06 +00001390 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall55e1fbc2011-06-25 02:11:03 +00001391 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);
John McCalld4631322011-06-17 06:42:21 +00001392 } else {
1393 EmitScalarInit(CurrentItem, elementLValue);
1394 }
Mike Stump11289f42009-09-09 15:08:12 +00001395
John McCall9e2e22f2011-02-22 07:16:58 +00001396 // If we do have an element variable, this assignment is the end of
1397 // its initialization.
1398 if (elementIsVariable)
1399 EmitAutoVarCleanups(variable);
1400
John McCall1c926b72011-01-07 01:49:06 +00001401 // Perform the loop body, setting up break and continue labels.
Anders Carlsson33747b62009-02-10 05:52:02 +00001402 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
John McCall1c926b72011-01-07 01:49:06 +00001403 {
1404 RunCleanupsScope Scope(*this);
1405 EmitStmt(S.getBody());
1406 }
Anders Carlsson75658592008-08-31 02:33:12 +00001407 BreakContinueStack.pop_back();
Mike Stump11289f42009-09-09 15:08:12 +00001408
John McCall1c926b72011-01-07 01:49:06 +00001409 // Destroy the element variable now.
1410 elementVariableScope.ForceCleanup();
1411
1412 // Check whether there are more elements.
John McCallad5d61e2010-07-23 21:56:41 +00001413 EmitBlock(AfterBody.getBlock());
Mike Stump11289f42009-09-09 15:08:12 +00001414
John McCall1c926b72011-01-07 01:49:06 +00001415 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
Fariborz Jahanian6e7ecc82009-01-06 18:56:31 +00001416
John McCall1c926b72011-01-07 01:49:06 +00001417 // First we check in the local buffer.
1418 llvm::Value *indexPlusOne
1419 = Builder.CreateAdd(index, llvm::ConstantInt::get(UnsignedLongLTy, 1));
Anders Carlsson75658592008-08-31 02:33:12 +00001420
John McCall1c926b72011-01-07 01:49:06 +00001421 // If we haven't overrun the buffer yet, we can continue.
1422 Builder.CreateCondBr(Builder.CreateICmpULT(indexPlusOne, count),
1423 LoopBodyBB, FetchMoreBB);
1424
1425 index->addIncoming(indexPlusOne, AfterBody.getBlock());
1426 count->addIncoming(count, AfterBody.getBlock());
1427
1428 // Otherwise, we have to fetch more elements.
1429 EmitBlock(FetchMoreBB);
Mike Stump11289f42009-09-09 15:08:12 +00001430
1431 CountRV =
John McCall78a15112010-05-22 01:48:05 +00001432 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlsson75658592008-08-31 02:33:12 +00001433 getContext().UnsignedLongTy,
Mike Stump11289f42009-09-09 15:08:12 +00001434 FastEnumSel,
David Chisnall01aa4672010-04-28 19:33:36 +00001435 Collection, Args);
Mike Stump11289f42009-09-09 15:08:12 +00001436
John McCall1c926b72011-01-07 01:49:06 +00001437 // If we got a zero count, we're done.
1438 llvm::Value *refetchCount = CountRV.getScalarVal();
1439
1440 // (note that the message send might split FetchMoreBB)
1441 index->addIncoming(zero, Builder.GetInsertBlock());
1442 count->addIncoming(refetchCount, Builder.GetInsertBlock());
1443
1444 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
1445 EmptyBB, LoopBodyBB);
Mike Stump11289f42009-09-09 15:08:12 +00001446
Anders Carlsson75658592008-08-31 02:33:12 +00001447 // No more elements.
John McCall1c926b72011-01-07 01:49:06 +00001448 EmitBlock(EmptyBB);
Anders Carlsson75658592008-08-31 02:33:12 +00001449
John McCall9e2e22f2011-02-22 07:16:58 +00001450 if (!elementIsVariable) {
Anders Carlsson75658592008-08-31 02:33:12 +00001451 // If the element was not a declaration, set it to be null.
1452
John McCall1c926b72011-01-07 01:49:06 +00001453 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
1454 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall55e1fbc2011-06-25 02:11:03 +00001455 EmitStoreThroughLValue(RValue::get(null), elementLValue);
Anders Carlsson75658592008-08-31 02:33:12 +00001456 }
1457
Eric Christopher7cdf9482011-10-13 21:45:18 +00001458 if (DI)
1459 DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
Devang Pateld2d66652011-01-19 01:36:36 +00001460
John McCall53848232011-07-27 01:07:15 +00001461 // Leave the cleanup we entered in ARC.
1462 if (getLangOptions().ObjCAutoRefCount)
1463 PopCleanupBlock();
1464
John McCallad5d61e2010-07-23 21:56:41 +00001465 EmitBlock(LoopEnd.getBlock());
Anders Carlsson2e744e82008-08-30 19:51:14 +00001466}
1467
Mike Stump11289f42009-09-09 15:08:12 +00001468void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
John McCallbd309292010-07-06 01:34:17 +00001469 CGM.getObjCRuntime().EmitTryStmt(*this, S);
Anders Carlsson1963b0c2008-09-09 10:04:29 +00001470}
1471
Mike Stump11289f42009-09-09 15:08:12 +00001472void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
Anders Carlsson1963b0c2008-09-09 10:04:29 +00001473 CGM.getObjCRuntime().EmitThrowStmt(*this, S);
1474}
1475
Chris Lattnere132e242008-11-15 21:26:17 +00001476void CodeGenFunction::EmitObjCAtSynchronizedStmt(
Mike Stump11289f42009-09-09 15:08:12 +00001477 const ObjCAtSynchronizedStmt &S) {
John McCallbd309292010-07-06 01:34:17 +00001478 CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
Chris Lattnere132e242008-11-15 21:26:17 +00001479}
1480
John McCall2d637d22011-09-10 06:18:15 +00001481/// Produce the code for a CK_ARCProduceObject. Just does a
John McCall31168b02011-06-15 23:02:42 +00001482/// primitive retain.
1483llvm::Value *CodeGenFunction::EmitObjCProduceObject(QualType type,
1484 llvm::Value *value) {
1485 return EmitARCRetain(type, value);
1486}
1487
1488namespace {
1489 struct CallObjCRelease : EHScopeStack::Cleanup {
John McCall9c8e1c92011-08-03 22:24:24 +00001490 CallObjCRelease(llvm::Value *object) : object(object) {}
1491 llvm::Value *object;
John McCall31168b02011-06-15 23:02:42 +00001492
John McCall30317fd2011-07-12 20:27:29 +00001493 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall31168b02011-06-15 23:02:42 +00001494 CGF.EmitARCRelease(object, /*precise*/ true);
John McCall31168b02011-06-15 23:02:42 +00001495 }
1496 };
1497}
1498
John McCall2d637d22011-09-10 06:18:15 +00001499/// Produce the code for a CK_ARCConsumeObject. Does a primitive
John McCall31168b02011-06-15 23:02:42 +00001500/// release at the end of the full-expression.
1501llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type,
1502 llvm::Value *object) {
1503 // If we're in a conditional branch, we need to make the cleanup
John McCall9c8e1c92011-08-03 22:24:24 +00001504 // conditional.
1505 pushFullExprCleanup<CallObjCRelease>(getARCCleanupKind(), object);
John McCall31168b02011-06-15 23:02:42 +00001506 return object;
1507}
1508
1509llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type,
1510 llvm::Value *value) {
1511 return EmitARCRetainAutorelease(type, value);
1512}
1513
1514
1515static llvm::Constant *createARCRuntimeFunction(CodeGenModule &CGM,
Chris Lattner2192fe52011-07-18 04:24:23 +00001516 llvm::FunctionType *type,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001517 StringRef fnName) {
John McCall31168b02011-06-15 23:02:42 +00001518 llvm::Constant *fn = CGM.CreateRuntimeFunction(type, fnName);
1519
1520 // In -fobjc-no-arc-runtime, emit weak references to the runtime
1521 // support library.
John McCall24fc0de2011-07-06 00:26:06 +00001522 if (!CGM.getCodeGenOpts().ObjCRuntimeHasARC)
John McCall31168b02011-06-15 23:02:42 +00001523 if (llvm::Function *f = dyn_cast<llvm::Function>(fn))
1524 f->setLinkage(llvm::Function::ExternalWeakLinkage);
1525
1526 return fn;
1527}
1528
1529/// Perform an operation having the signature
1530/// i8* (i8*)
1531/// where a null input causes a no-op and returns null.
1532static llvm::Value *emitARCValueOperation(CodeGenFunction &CGF,
1533 llvm::Value *value,
1534 llvm::Constant *&fn,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001535 StringRef fnName) {
John McCall31168b02011-06-15 23:02:42 +00001536 if (isa<llvm::ConstantPointerNull>(value)) return value;
1537
1538 if (!fn) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00001539 std::vector<llvm::Type*> args(1, CGF.Int8PtrTy);
Chris Lattner2192fe52011-07-18 04:24:23 +00001540 llvm::FunctionType *fnType =
John McCall31168b02011-06-15 23:02:42 +00001541 llvm::FunctionType::get(CGF.Int8PtrTy, args, false);
1542 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1543 }
1544
1545 // Cast the argument to 'id'.
Chris Lattner2192fe52011-07-18 04:24:23 +00001546 llvm::Type *origType = value->getType();
John McCall31168b02011-06-15 23:02:42 +00001547 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1548
1549 // Call the function.
1550 llvm::CallInst *call = CGF.Builder.CreateCall(fn, value);
1551 call->setDoesNotThrow();
1552
1553 // Cast the result back to the original type.
1554 return CGF.Builder.CreateBitCast(call, origType);
1555}
1556
1557/// Perform an operation having the following signature:
1558/// i8* (i8**)
1559static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF,
1560 llvm::Value *addr,
1561 llvm::Constant *&fn,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001562 StringRef fnName) {
John McCall31168b02011-06-15 23:02:42 +00001563 if (!fn) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00001564 std::vector<llvm::Type*> args(1, CGF.Int8PtrPtrTy);
Chris Lattner2192fe52011-07-18 04:24:23 +00001565 llvm::FunctionType *fnType =
John McCall31168b02011-06-15 23:02:42 +00001566 llvm::FunctionType::get(CGF.Int8PtrTy, args, false);
1567 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1568 }
1569
1570 // Cast the argument to 'id*'.
Chris Lattner2192fe52011-07-18 04:24:23 +00001571 llvm::Type *origType = addr->getType();
John McCall31168b02011-06-15 23:02:42 +00001572 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1573
1574 // Call the function.
1575 llvm::CallInst *call = CGF.Builder.CreateCall(fn, addr);
1576 call->setDoesNotThrow();
1577
1578 // Cast the result back to a dereference of the original type.
1579 llvm::Value *result = call;
1580 if (origType != CGF.Int8PtrPtrTy)
1581 result = CGF.Builder.CreateBitCast(result,
1582 cast<llvm::PointerType>(origType)->getElementType());
1583
1584 return result;
1585}
1586
1587/// Perform an operation having the following signature:
1588/// i8* (i8**, i8*)
1589static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF,
1590 llvm::Value *addr,
1591 llvm::Value *value,
1592 llvm::Constant *&fn,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001593 StringRef fnName,
John McCall31168b02011-06-15 23:02:42 +00001594 bool ignored) {
1595 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
1596 == value->getType());
1597
1598 if (!fn) {
Benjamin Kramer22d24c22011-10-15 12:20:02 +00001599 llvm::Type *argTypes[] = { CGF.Int8PtrPtrTy, CGF.Int8PtrTy };
John McCall31168b02011-06-15 23:02:42 +00001600
Chris Lattner2192fe52011-07-18 04:24:23 +00001601 llvm::FunctionType *fnType
John McCall31168b02011-06-15 23:02:42 +00001602 = llvm::FunctionType::get(CGF.Int8PtrTy, argTypes, false);
1603 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1604 }
1605
Chris Lattner2192fe52011-07-18 04:24:23 +00001606 llvm::Type *origType = value->getType();
John McCall31168b02011-06-15 23:02:42 +00001607
1608 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1609 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1610
1611 llvm::CallInst *result = CGF.Builder.CreateCall2(fn, addr, value);
1612 result->setDoesNotThrow();
1613
1614 if (ignored) return 0;
1615
1616 return CGF.Builder.CreateBitCast(result, origType);
1617}
1618
1619/// Perform an operation having the following signature:
1620/// void (i8**, i8**)
1621static void emitARCCopyOperation(CodeGenFunction &CGF,
1622 llvm::Value *dst,
1623 llvm::Value *src,
1624 llvm::Constant *&fn,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001625 StringRef fnName) {
John McCall31168b02011-06-15 23:02:42 +00001626 assert(dst->getType() == src->getType());
1627
1628 if (!fn) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00001629 std::vector<llvm::Type*> argTypes(2, CGF.Int8PtrPtrTy);
Chris Lattner2192fe52011-07-18 04:24:23 +00001630 llvm::FunctionType *fnType
John McCall31168b02011-06-15 23:02:42 +00001631 = llvm::FunctionType::get(CGF.Builder.getVoidTy(), argTypes, false);
1632 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1633 }
1634
1635 dst = CGF.Builder.CreateBitCast(dst, CGF.Int8PtrPtrTy);
1636 src = CGF.Builder.CreateBitCast(src, CGF.Int8PtrPtrTy);
1637
1638 llvm::CallInst *result = CGF.Builder.CreateCall2(fn, dst, src);
1639 result->setDoesNotThrow();
1640}
1641
1642/// Produce the code to do a retain. Based on the type, calls one of:
1643/// call i8* @objc_retain(i8* %value)
1644/// call i8* @objc_retainBlock(i8* %value)
1645llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) {
1646 if (type->isBlockPointerType())
John McCallff613032011-10-04 06:23:45 +00001647 return EmitARCRetainBlock(value, /*mandatory*/ false);
John McCall31168b02011-06-15 23:02:42 +00001648 else
1649 return EmitARCRetainNonBlock(value);
1650}
1651
1652/// Retain the given object, with normal retain semantics.
1653/// call i8* @objc_retain(i8* %value)
1654llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) {
1655 return emitARCValueOperation(*this, value,
1656 CGM.getARCEntrypoints().objc_retain,
1657 "objc_retain");
1658}
1659
1660/// Retain the given block, with _Block_copy semantics.
1661/// call i8* @objc_retainBlock(i8* %value)
John McCallff613032011-10-04 06:23:45 +00001662///
1663/// \param mandatory - If false, emit the call with metadata
1664/// indicating that it's okay for the optimizer to eliminate this call
1665/// if it can prove that the block never escapes except down the stack.
1666llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value,
1667 bool mandatory) {
1668 llvm::Value *result
1669 = emitARCValueOperation(*this, value,
1670 CGM.getARCEntrypoints().objc_retainBlock,
1671 "objc_retainBlock");
1672
1673 // If the copy isn't mandatory, add !clang.arc.copy_on_escape to
1674 // tell the optimizer that it doesn't need to do this copy if the
1675 // block doesn't escape, where being passed as an argument doesn't
1676 // count as escaping.
1677 if (!mandatory && isa<llvm::Instruction>(result)) {
1678 llvm::CallInst *call
1679 = cast<llvm::CallInst>(result->stripPointerCasts());
1680 assert(call->getCalledValue() == CGM.getARCEntrypoints().objc_retainBlock);
1681
1682 SmallVector<llvm::Value*,1> args;
1683 call->setMetadata("clang.arc.copy_on_escape",
1684 llvm::MDNode::get(Builder.getContext(), args));
1685 }
1686
1687 return result;
John McCall31168b02011-06-15 23:02:42 +00001688}
1689
1690/// Retain the given object which is the result of a function call.
1691/// call i8* @objc_retainAutoreleasedReturnValue(i8* %value)
1692///
1693/// Yes, this function name is one character away from a different
1694/// call with completely different semantics.
1695llvm::Value *
1696CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) {
1697 // Fetch the void(void) inline asm which marks that we're going to
1698 // retain the autoreleased return value.
1699 llvm::InlineAsm *&marker
1700 = CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker;
1701 if (!marker) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001702 StringRef assembly
John McCall31168b02011-06-15 23:02:42 +00001703 = CGM.getTargetCodeGenInfo()
1704 .getARCRetainAutoreleasedReturnValueMarker();
1705
1706 // If we have an empty assembly string, there's nothing to do.
1707 if (assembly.empty()) {
1708
1709 // Otherwise, at -O0, build an inline asm that we're going to call
1710 // in a moment.
1711 } else if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1712 llvm::FunctionType *type =
1713 llvm::FunctionType::get(llvm::Type::getVoidTy(getLLVMContext()),
1714 /*variadic*/ false);
1715
1716 marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);
1717
1718 // If we're at -O1 and above, we don't want to litter the code
1719 // with this marker yet, so leave a breadcrumb for the ARC
1720 // optimizer to pick up.
1721 } else {
1722 llvm::NamedMDNode *metadata =
1723 CGM.getModule().getOrInsertNamedMetadata(
1724 "clang.arc.retainAutoreleasedReturnValueMarker");
1725 assert(metadata->getNumOperands() <= 1);
1726 if (metadata->getNumOperands() == 0) {
1727 llvm::Value *string = llvm::MDString::get(getLLVMContext(), assembly);
Jay Foad5709f7c2011-07-29 13:56:53 +00001728 metadata->addOperand(llvm::MDNode::get(getLLVMContext(), string));
John McCall31168b02011-06-15 23:02:42 +00001729 }
1730 }
1731 }
1732
1733 // Call the marker asm if we made one, which we do only at -O0.
1734 if (marker) Builder.CreateCall(marker);
1735
1736 return emitARCValueOperation(*this, value,
1737 CGM.getARCEntrypoints().objc_retainAutoreleasedReturnValue,
1738 "objc_retainAutoreleasedReturnValue");
1739}
1740
1741/// Release the given object.
1742/// call void @objc_release(i8* %value)
1743void CodeGenFunction::EmitARCRelease(llvm::Value *value, bool precise) {
1744 if (isa<llvm::ConstantPointerNull>(value)) return;
1745
1746 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_release;
1747 if (!fn) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00001748 std::vector<llvm::Type*> args(1, Int8PtrTy);
Chris Lattner2192fe52011-07-18 04:24:23 +00001749 llvm::FunctionType *fnType =
John McCall31168b02011-06-15 23:02:42 +00001750 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
1751 fn = createARCRuntimeFunction(CGM, fnType, "objc_release");
1752 }
1753
1754 // Cast the argument to 'id'.
1755 value = Builder.CreateBitCast(value, Int8PtrTy);
1756
1757 // Call objc_release.
1758 llvm::CallInst *call = Builder.CreateCall(fn, value);
1759 call->setDoesNotThrow();
1760
1761 if (!precise) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001762 SmallVector<llvm::Value*,1> args;
John McCall31168b02011-06-15 23:02:42 +00001763 call->setMetadata("clang.imprecise_release",
1764 llvm::MDNode::get(Builder.getContext(), args));
1765 }
1766}
1767
1768/// Store into a strong object. Always calls this:
1769/// call void @objc_storeStrong(i8** %addr, i8* %value)
1770llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(llvm::Value *addr,
1771 llvm::Value *value,
1772 bool ignored) {
1773 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
1774 == value->getType());
1775
1776 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_storeStrong;
1777 if (!fn) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00001778 llvm::Type *argTypes[] = { Int8PtrPtrTy, Int8PtrTy };
Chris Lattner2192fe52011-07-18 04:24:23 +00001779 llvm::FunctionType *fnType
John McCall31168b02011-06-15 23:02:42 +00001780 = llvm::FunctionType::get(Builder.getVoidTy(), argTypes, false);
1781 fn = createARCRuntimeFunction(CGM, fnType, "objc_storeStrong");
1782 }
1783
1784 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
1785 llvm::Value *castValue = Builder.CreateBitCast(value, Int8PtrTy);
1786
1787 Builder.CreateCall2(fn, addr, castValue)->setDoesNotThrow();
1788
1789 if (ignored) return 0;
1790 return value;
1791}
1792
1793/// Store into a strong object. Sometimes calls this:
1794/// call void @objc_storeStrong(i8** %addr, i8* %value)
1795/// Other times, breaks it down into components.
John McCall55e1fbc2011-06-25 02:11:03 +00001796llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst,
John McCall31168b02011-06-15 23:02:42 +00001797 llvm::Value *newValue,
1798 bool ignored) {
John McCall55e1fbc2011-06-25 02:11:03 +00001799 QualType type = dst.getType();
John McCall31168b02011-06-15 23:02:42 +00001800 bool isBlock = type->isBlockPointerType();
1801
1802 // Use a store barrier at -O0 unless this is a block type or the
1803 // lvalue is inadequately aligned.
1804 if (shouldUseFusedARCCalls() &&
1805 !isBlock &&
Eli Friedmana0544d62011-12-03 04:14:32 +00001806 (dst.getAlignment().isZero() ||
1807 dst.getAlignment() >= CharUnits::fromQuantity(PointerAlignInBytes))) {
John McCall31168b02011-06-15 23:02:42 +00001808 return EmitARCStoreStrongCall(dst.getAddress(), newValue, ignored);
1809 }
1810
1811 // Otherwise, split it out.
1812
1813 // Retain the new value.
1814 newValue = EmitARCRetain(type, newValue);
1815
1816 // Read the old value.
John McCall55e1fbc2011-06-25 02:11:03 +00001817 llvm::Value *oldValue = EmitLoadOfScalar(dst);
John McCall31168b02011-06-15 23:02:42 +00001818
1819 // Store. We do this before the release so that any deallocs won't
1820 // see the old value.
John McCall55e1fbc2011-06-25 02:11:03 +00001821 EmitStoreOfScalar(newValue, dst);
John McCall31168b02011-06-15 23:02:42 +00001822
1823 // Finally, release the old value.
1824 EmitARCRelease(oldValue, /*precise*/ false);
1825
1826 return newValue;
1827}
1828
1829/// Autorelease the given object.
1830/// call i8* @objc_autorelease(i8* %value)
1831llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) {
1832 return emitARCValueOperation(*this, value,
1833 CGM.getARCEntrypoints().objc_autorelease,
1834 "objc_autorelease");
1835}
1836
1837/// Autorelease the given object.
1838/// call i8* @objc_autoreleaseReturnValue(i8* %value)
1839llvm::Value *
1840CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) {
1841 return emitARCValueOperation(*this, value,
1842 CGM.getARCEntrypoints().objc_autoreleaseReturnValue,
1843 "objc_autoreleaseReturnValue");
1844}
1845
1846/// Do a fused retain/autorelease of the given object.
1847/// call i8* @objc_retainAutoreleaseReturnValue(i8* %value)
1848llvm::Value *
1849CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) {
1850 return emitARCValueOperation(*this, value,
1851 CGM.getARCEntrypoints().objc_retainAutoreleaseReturnValue,
1852 "objc_retainAutoreleaseReturnValue");
1853}
1854
1855/// Do a fused retain/autorelease of the given object.
1856/// call i8* @objc_retainAutorelease(i8* %value)
1857/// or
1858/// %retain = call i8* @objc_retainBlock(i8* %value)
1859/// call i8* @objc_autorelease(i8* %retain)
1860llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type,
1861 llvm::Value *value) {
1862 if (!type->isBlockPointerType())
1863 return EmitARCRetainAutoreleaseNonBlock(value);
1864
1865 if (isa<llvm::ConstantPointerNull>(value)) return value;
1866
Chris Lattner2192fe52011-07-18 04:24:23 +00001867 llvm::Type *origType = value->getType();
John McCall31168b02011-06-15 23:02:42 +00001868 value = Builder.CreateBitCast(value, Int8PtrTy);
John McCallff613032011-10-04 06:23:45 +00001869 value = EmitARCRetainBlock(value, /*mandatory*/ true);
John McCall31168b02011-06-15 23:02:42 +00001870 value = EmitARCAutorelease(value);
1871 return Builder.CreateBitCast(value, origType);
1872}
1873
1874/// Do a fused retain/autorelease of the given object.
1875/// call i8* @objc_retainAutorelease(i8* %value)
1876llvm::Value *
1877CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) {
1878 return emitARCValueOperation(*this, value,
1879 CGM.getARCEntrypoints().objc_retainAutorelease,
1880 "objc_retainAutorelease");
1881}
1882
1883/// i8* @objc_loadWeak(i8** %addr)
1884/// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
1885llvm::Value *CodeGenFunction::EmitARCLoadWeak(llvm::Value *addr) {
1886 return emitARCLoadOperation(*this, addr,
1887 CGM.getARCEntrypoints().objc_loadWeak,
1888 "objc_loadWeak");
1889}
1890
1891/// i8* @objc_loadWeakRetained(i8** %addr)
1892llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(llvm::Value *addr) {
1893 return emitARCLoadOperation(*this, addr,
1894 CGM.getARCEntrypoints().objc_loadWeakRetained,
1895 "objc_loadWeakRetained");
1896}
1897
1898/// i8* @objc_storeWeak(i8** %addr, i8* %value)
1899/// Returns %value.
1900llvm::Value *CodeGenFunction::EmitARCStoreWeak(llvm::Value *addr,
1901 llvm::Value *value,
1902 bool ignored) {
1903 return emitARCStoreOperation(*this, addr, value,
1904 CGM.getARCEntrypoints().objc_storeWeak,
1905 "objc_storeWeak", ignored);
1906}
1907
1908/// i8* @objc_initWeak(i8** %addr, i8* %value)
1909/// Returns %value. %addr is known to not have a current weak entry.
1910/// Essentially equivalent to:
1911/// *addr = nil; objc_storeWeak(addr, value);
1912void CodeGenFunction::EmitARCInitWeak(llvm::Value *addr, llvm::Value *value) {
1913 // If we're initializing to null, just write null to memory; no need
1914 // to get the runtime involved. But don't do this if optimization
1915 // is enabled, because accounting for this would make the optimizer
1916 // much more complicated.
1917 if (isa<llvm::ConstantPointerNull>(value) &&
1918 CGM.getCodeGenOpts().OptimizationLevel == 0) {
1919 Builder.CreateStore(value, addr);
1920 return;
1921 }
1922
1923 emitARCStoreOperation(*this, addr, value,
1924 CGM.getARCEntrypoints().objc_initWeak,
1925 "objc_initWeak", /*ignored*/ true);
1926}
1927
1928/// void @objc_destroyWeak(i8** %addr)
1929/// Essentially objc_storeWeak(addr, nil).
1930void CodeGenFunction::EmitARCDestroyWeak(llvm::Value *addr) {
1931 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_destroyWeak;
1932 if (!fn) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00001933 std::vector<llvm::Type*> args(1, Int8PtrPtrTy);
Chris Lattner2192fe52011-07-18 04:24:23 +00001934 llvm::FunctionType *fnType =
John McCall31168b02011-06-15 23:02:42 +00001935 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
1936 fn = createARCRuntimeFunction(CGM, fnType, "objc_destroyWeak");
1937 }
1938
1939 // Cast the argument to 'id*'.
1940 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
1941
1942 llvm::CallInst *call = Builder.CreateCall(fn, addr);
1943 call->setDoesNotThrow();
1944}
1945
1946/// void @objc_moveWeak(i8** %dest, i8** %src)
1947/// Disregards the current value in %dest. Leaves %src pointing to nothing.
1948/// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
1949void CodeGenFunction::EmitARCMoveWeak(llvm::Value *dst, llvm::Value *src) {
1950 emitARCCopyOperation(*this, dst, src,
1951 CGM.getARCEntrypoints().objc_moveWeak,
1952 "objc_moveWeak");
1953}
1954
1955/// void @objc_copyWeak(i8** %dest, i8** %src)
1956/// Disregards the current value in %dest. Essentially
1957/// objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
1958void CodeGenFunction::EmitARCCopyWeak(llvm::Value *dst, llvm::Value *src) {
1959 emitARCCopyOperation(*this, dst, src,
1960 CGM.getARCEntrypoints().objc_copyWeak,
1961 "objc_copyWeak");
1962}
1963
1964/// Produce the code to do a objc_autoreleasepool_push.
1965/// call i8* @objc_autoreleasePoolPush(void)
1966llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() {
1967 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPush;
1968 if (!fn) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001969 llvm::FunctionType *fnType =
John McCall31168b02011-06-15 23:02:42 +00001970 llvm::FunctionType::get(Int8PtrTy, false);
1971 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPush");
1972 }
1973
1974 llvm::CallInst *call = Builder.CreateCall(fn);
1975 call->setDoesNotThrow();
1976
1977 return call;
1978}
1979
1980/// Produce the code to do a primitive release.
1981/// call void @objc_autoreleasePoolPop(i8* %ptr)
1982void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) {
1983 assert(value->getType() == Int8PtrTy);
1984
1985 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPop;
1986 if (!fn) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00001987 std::vector<llvm::Type*> args(1, Int8PtrTy);
Chris Lattner2192fe52011-07-18 04:24:23 +00001988 llvm::FunctionType *fnType =
John McCall31168b02011-06-15 23:02:42 +00001989 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
1990
1991 // We don't want to use a weak import here; instead we should not
1992 // fall into this path.
1993 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPop");
1994 }
1995
1996 llvm::CallInst *call = Builder.CreateCall(fn, value);
1997 call->setDoesNotThrow();
1998}
1999
2000/// Produce the code to do an MRR version objc_autoreleasepool_push.
2001/// Which is: [[NSAutoreleasePool alloc] init];
2002/// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
2003/// init is declared as: - (id) init; in its NSObject super class.
2004///
2005llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() {
2006 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
2007 llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(Builder);
2008 // [NSAutoreleasePool alloc]
2009 IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");
2010 Selector AllocSel = getContext().Selectors.getSelector(0, &II);
2011 CallArgList Args;
2012 RValue AllocRV =
2013 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2014 getContext().getObjCIdType(),
2015 AllocSel, Receiver, Args);
2016
2017 // [Receiver init]
2018 Receiver = AllocRV.getScalarVal();
2019 II = &CGM.getContext().Idents.get("init");
2020 Selector InitSel = getContext().Selectors.getSelector(0, &II);
2021 RValue InitRV =
2022 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2023 getContext().getObjCIdType(),
2024 InitSel, Receiver, Args);
2025 return InitRV.getScalarVal();
2026}
2027
2028/// Produce the code to do a primitive release.
2029/// [tmp drain];
2030void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) {
2031 IdentifierInfo *II = &CGM.getContext().Idents.get("drain");
2032 Selector DrainSel = getContext().Selectors.getSelector(0, &II);
2033 CallArgList Args;
2034 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
2035 getContext().VoidTy, DrainSel, Arg, Args);
2036}
2037
John McCall82fe67b2011-07-09 01:37:26 +00002038void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF,
2039 llvm::Value *addr,
2040 QualType type) {
2041 llvm::Value *ptr = CGF.Builder.CreateLoad(addr, "strongdestroy");
2042 CGF.EmitARCRelease(ptr, /*precise*/ true);
2043}
2044
2045void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF,
2046 llvm::Value *addr,
2047 QualType type) {
2048 llvm::Value *ptr = CGF.Builder.CreateLoad(addr, "strongdestroy");
2049 CGF.EmitARCRelease(ptr, /*precise*/ false);
2050}
2051
2052void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF,
2053 llvm::Value *addr,
2054 QualType type) {
2055 CGF.EmitARCDestroyWeak(addr);
2056}
2057
John McCall31168b02011-06-15 23:02:42 +00002058namespace {
John McCall31168b02011-06-15 23:02:42 +00002059 struct CallObjCAutoreleasePoolObject : EHScopeStack::Cleanup {
2060 llvm::Value *Token;
2061
2062 CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2063
John McCall30317fd2011-07-12 20:27:29 +00002064 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall31168b02011-06-15 23:02:42 +00002065 CGF.EmitObjCAutoreleasePoolPop(Token);
2066 }
2067 };
2068 struct CallObjCMRRAutoreleasePoolObject : EHScopeStack::Cleanup {
2069 llvm::Value *Token;
2070
2071 CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2072
John McCall30317fd2011-07-12 20:27:29 +00002073 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall31168b02011-06-15 23:02:42 +00002074 CGF.EmitObjCMRRAutoreleasePoolPop(Token);
2075 }
2076 };
2077}
2078
2079void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) {
2080 if (CGM.getLangOptions().ObjCAutoRefCount)
2081 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
2082 else
2083 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);
2084}
2085
John McCall31168b02011-06-15 23:02:42 +00002086static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2087 LValue lvalue,
2088 QualType type) {
2089 switch (type.getObjCLifetime()) {
2090 case Qualifiers::OCL_None:
2091 case Qualifiers::OCL_ExplicitNone:
2092 case Qualifiers::OCL_Strong:
2093 case Qualifiers::OCL_Autoreleasing:
John McCall55e1fbc2011-06-25 02:11:03 +00002094 return TryEmitResult(CGF.EmitLoadOfLValue(lvalue).getScalarVal(),
John McCall31168b02011-06-15 23:02:42 +00002095 false);
2096
2097 case Qualifiers::OCL_Weak:
2098 return TryEmitResult(CGF.EmitARCLoadWeakRetained(lvalue.getAddress()),
2099 true);
2100 }
2101
2102 llvm_unreachable("impossible lifetime!");
John McCall31168b02011-06-15 23:02:42 +00002103}
2104
2105static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2106 const Expr *e) {
2107 e = e->IgnoreParens();
2108 QualType type = e->getType();
2109
John McCall154a2fd2011-08-30 00:57:29 +00002110 // If we're loading retained from a __strong xvalue, we can avoid
2111 // an extra retain/release pair by zeroing out the source of this
2112 // "move" operation.
2113 if (e->isXValue() &&
2114 !type.isConstQualified() &&
2115 type.getObjCLifetime() == Qualifiers::OCL_Strong) {
2116 // Emit the lvalue.
2117 LValue lv = CGF.EmitLValue(e);
2118
2119 // Load the object pointer.
2120 llvm::Value *result = CGF.EmitLoadOfLValue(lv).getScalarVal();
2121
2122 // Set the source pointer to NULL.
2123 CGF.EmitStoreOfScalar(getNullForVariable(lv.getAddress()), lv);
2124
2125 return TryEmitResult(result, true);
2126 }
2127
John McCall31168b02011-06-15 23:02:42 +00002128 // As a very special optimization, in ARC++, if the l-value is the
2129 // result of a non-volatile assignment, do a simple retain of the
2130 // result of the call to objc_storeWeak instead of reloading.
2131 if (CGF.getLangOptions().CPlusPlus &&
2132 !type.isVolatileQualified() &&
2133 type.getObjCLifetime() == Qualifiers::OCL_Weak &&
2134 isa<BinaryOperator>(e) &&
2135 cast<BinaryOperator>(e)->getOpcode() == BO_Assign)
2136 return TryEmitResult(CGF.EmitScalarExpr(e), false);
2137
2138 return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);
2139}
2140
2141static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2142 llvm::Value *value);
2143
2144/// Given that the given expression is some sort of call (which does
2145/// not return retained), emit a retain following it.
2146static llvm::Value *emitARCRetainCall(CodeGenFunction &CGF, const Expr *e) {
2147 llvm::Value *value = CGF.EmitScalarExpr(e);
2148 return emitARCRetainAfterCall(CGF, value);
2149}
2150
2151static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2152 llvm::Value *value) {
2153 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {
2154 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2155
2156 // Place the retain immediately following the call.
2157 CGF.Builder.SetInsertPoint(call->getParent(),
2158 ++llvm::BasicBlock::iterator(call));
2159 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2160
2161 CGF.Builder.restoreIP(ip);
2162 return value;
2163 } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) {
2164 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2165
2166 // Place the retain at the beginning of the normal destination block.
2167 llvm::BasicBlock *BB = invoke->getNormalDest();
2168 CGF.Builder.SetInsertPoint(BB, BB->begin());
2169 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2170
2171 CGF.Builder.restoreIP(ip);
2172 return value;
2173
2174 // Bitcasts can arise because of related-result returns. Rewrite
2175 // the operand.
2176 } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {
2177 llvm::Value *operand = bitcast->getOperand(0);
2178 operand = emitARCRetainAfterCall(CGF, operand);
2179 bitcast->setOperand(0, operand);
2180 return bitcast;
2181
2182 // Generic fall-back case.
2183 } else {
2184 // Retain using the non-block variant: we never need to do a copy
2185 // of a block that's been returned to us.
2186 return CGF.EmitARCRetainNonBlock(value);
2187 }
2188}
2189
John McCallcd78e802011-09-10 01:16:55 +00002190/// Determine whether it might be important to emit a separate
2191/// objc_retain_block on the result of the given expression, or
2192/// whether it's okay to just emit it in a +1 context.
2193static bool shouldEmitSeparateBlockRetain(const Expr *e) {
2194 assert(e->getType()->isBlockPointerType());
2195 e = e->IgnoreParens();
2196
2197 // For future goodness, emit block expressions directly in +1
2198 // contexts if we can.
2199 if (isa<BlockExpr>(e))
2200 return false;
2201
2202 if (const CastExpr *cast = dyn_cast<CastExpr>(e)) {
2203 switch (cast->getCastKind()) {
2204 // Emitting these operations in +1 contexts is goodness.
2205 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00002206 case CK_ARCReclaimReturnedObject:
2207 case CK_ARCConsumeObject:
2208 case CK_ARCProduceObject:
John McCallcd78e802011-09-10 01:16:55 +00002209 return false;
2210
2211 // These operations preserve a block type.
2212 case CK_NoOp:
2213 case CK_BitCast:
2214 return shouldEmitSeparateBlockRetain(cast->getSubExpr());
2215
2216 // These operations are known to be bad (or haven't been considered).
2217 case CK_AnyPointerToBlockPointerCast:
2218 default:
2219 return true;
2220 }
2221 }
2222
2223 return true;
2224}
2225
John McCallfe96e0b2011-11-06 09:01:30 +00002226/// Try to emit a PseudoObjectExpr at +1.
2227///
2228/// This massively duplicates emitPseudoObjectRValue.
2229static TryEmitResult tryEmitARCRetainPseudoObject(CodeGenFunction &CGF,
2230 const PseudoObjectExpr *E) {
2231 llvm::SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
2232
2233 // Find the result expression.
2234 const Expr *resultExpr = E->getResultExpr();
2235 assert(resultExpr);
2236 TryEmitResult result;
2237
2238 for (PseudoObjectExpr::const_semantics_iterator
2239 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
2240 const Expr *semantic = *i;
2241
2242 // If this semantic expression is an opaque value, bind it
2243 // to the result of its source expression.
2244 if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
2245 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
2246 OVMA opaqueData;
2247
2248 // If this semantic is the result of the pseudo-object
2249 // expression, try to evaluate the source as +1.
2250 if (ov == resultExpr) {
2251 assert(!OVMA::shouldBindAsLValue(ov));
2252 result = tryEmitARCRetainScalarExpr(CGF, ov->getSourceExpr());
2253 opaqueData = OVMA::bind(CGF, ov, RValue::get(result.getPointer()));
2254
2255 // Otherwise, just bind it.
2256 } else {
2257 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
2258 }
2259 opaques.push_back(opaqueData);
2260
2261 // Otherwise, if the expression is the result, evaluate it
2262 // and remember the result.
2263 } else if (semantic == resultExpr) {
2264 result = tryEmitARCRetainScalarExpr(CGF, semantic);
2265
2266 // Otherwise, evaluate the expression in an ignored context.
2267 } else {
2268 CGF.EmitIgnoredExpr(semantic);
2269 }
2270 }
2271
2272 // Unbind all the opaques now.
2273 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
2274 opaques[i].unbind(CGF);
2275
2276 return result;
2277}
2278
John McCall31168b02011-06-15 23:02:42 +00002279static TryEmitResult
2280tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) {
John McCall53848232011-07-27 01:07:15 +00002281 // Look through cleanups.
2282 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
John McCall08ef4662011-11-10 08:15:53 +00002283 CGF.enterFullExpression(cleanups);
John McCall53848232011-07-27 01:07:15 +00002284 CodeGenFunction::RunCleanupsScope scope(CGF);
2285 return tryEmitARCRetainScalarExpr(CGF, cleanups->getSubExpr());
2286 }
2287
John McCall31168b02011-06-15 23:02:42 +00002288 // The desired result type, if it differs from the type of the
2289 // ultimate opaque expression.
Chris Lattner2192fe52011-07-18 04:24:23 +00002290 llvm::Type *resultType = 0;
John McCall31168b02011-06-15 23:02:42 +00002291
2292 while (true) {
2293 e = e->IgnoreParens();
2294
2295 // There's a break at the end of this if-chain; anything
2296 // that wants to keep looping has to explicitly continue.
2297 if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
2298 switch (ce->getCastKind()) {
2299 // No-op casts don't change the type, so we just ignore them.
2300 case CK_NoOp:
2301 e = ce->getSubExpr();
2302 continue;
2303
2304 case CK_LValueToRValue: {
2305 TryEmitResult loadResult
2306 = tryEmitARCRetainLoadOfScalar(CGF, ce->getSubExpr());
2307 if (resultType) {
2308 llvm::Value *value = loadResult.getPointer();
2309 value = CGF.Builder.CreateBitCast(value, resultType);
2310 loadResult.setPointer(value);
2311 }
2312 return loadResult;
2313 }
2314
2315 // These casts can change the type, so remember that and
2316 // soldier on. We only need to remember the outermost such
2317 // cast, though.
John McCall9320b872011-09-09 05:25:32 +00002318 case CK_CPointerToObjCPointerCast:
2319 case CK_BlockPointerToObjCPointerCast:
John McCall31168b02011-06-15 23:02:42 +00002320 case CK_AnyPointerToBlockPointerCast:
2321 case CK_BitCast:
2322 if (!resultType)
2323 resultType = CGF.ConvertType(ce->getType());
2324 e = ce->getSubExpr();
2325 assert(e->getType()->hasPointerRepresentation());
2326 continue;
2327
2328 // For consumptions, just emit the subexpression and thus elide
2329 // the retain/release pair.
John McCall2d637d22011-09-10 06:18:15 +00002330 case CK_ARCConsumeObject: {
John McCall31168b02011-06-15 23:02:42 +00002331 llvm::Value *result = CGF.EmitScalarExpr(ce->getSubExpr());
2332 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2333 return TryEmitResult(result, true);
2334 }
2335
John McCallcd78e802011-09-10 01:16:55 +00002336 // Block extends are net +0. Naively, we could just recurse on
2337 // the subexpression, but actually we need to ensure that the
2338 // value is copied as a block, so there's a little filter here.
John McCall2d637d22011-09-10 06:18:15 +00002339 case CK_ARCExtendBlockObject: {
John McCallcd78e802011-09-10 01:16:55 +00002340 llvm::Value *result; // will be a +0 value
2341
2342 // If we can't safely assume the sub-expression will produce a
2343 // block-copied value, emit the sub-expression at +0.
2344 if (shouldEmitSeparateBlockRetain(ce->getSubExpr())) {
2345 result = CGF.EmitScalarExpr(ce->getSubExpr());
2346
2347 // Otherwise, try to emit the sub-expression at +1 recursively.
2348 } else {
2349 TryEmitResult subresult
2350 = tryEmitARCRetainScalarExpr(CGF, ce->getSubExpr());
2351 result = subresult.getPointer();
2352
2353 // If that produced a retained value, just use that,
2354 // possibly casting down.
2355 if (subresult.getInt()) {
2356 if (resultType)
2357 result = CGF.Builder.CreateBitCast(result, resultType);
2358 return TryEmitResult(result, true);
2359 }
2360
2361 // Otherwise it's +0.
2362 }
2363
2364 // Retain the object as a block, then cast down.
John McCallff613032011-10-04 06:23:45 +00002365 result = CGF.EmitARCRetainBlock(result, /*mandatory*/ true);
John McCallcd78e802011-09-10 01:16:55 +00002366 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2367 return TryEmitResult(result, true);
2368 }
2369
John McCall4db5c3c2011-07-07 06:58:02 +00002370 // For reclaims, emit the subexpression as a retained call and
2371 // skip the consumption.
John McCall2d637d22011-09-10 06:18:15 +00002372 case CK_ARCReclaimReturnedObject: {
John McCall4db5c3c2011-07-07 06:58:02 +00002373 llvm::Value *result = emitARCRetainCall(CGF, ce->getSubExpr());
2374 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2375 return TryEmitResult(result, true);
2376 }
2377
John McCall31168b02011-06-15 23:02:42 +00002378 default:
2379 break;
2380 }
2381
2382 // Skip __extension__.
2383 } else if (const UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
2384 if (op->getOpcode() == UO_Extension) {
2385 e = op->getSubExpr();
2386 continue;
2387 }
2388
2389 // For calls and message sends, use the retained-call logic.
2390 // Delegate inits are a special case in that they're the only
2391 // returns-retained expression that *isn't* surrounded by
2392 // a consume.
2393 } else if (isa<CallExpr>(e) ||
2394 (isa<ObjCMessageExpr>(e) &&
2395 !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) {
2396 llvm::Value *result = emitARCRetainCall(CGF, e);
2397 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2398 return TryEmitResult(result, true);
John McCallfe96e0b2011-11-06 09:01:30 +00002399
2400 // Look through pseudo-object expressions.
2401 } else if (const PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
2402 TryEmitResult result
2403 = tryEmitARCRetainPseudoObject(CGF, pseudo);
2404 if (resultType) {
2405 llvm::Value *value = result.getPointer();
2406 value = CGF.Builder.CreateBitCast(value, resultType);
2407 result.setPointer(value);
2408 }
2409 return result;
John McCall31168b02011-06-15 23:02:42 +00002410 }
2411
2412 // Conservatively halt the search at any other expression kind.
2413 break;
2414 }
2415
2416 // We didn't find an obvious production, so emit what we've got and
2417 // tell the caller that we didn't manage to retain.
2418 llvm::Value *result = CGF.EmitScalarExpr(e);
2419 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2420 return TryEmitResult(result, false);
2421}
2422
2423static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2424 LValue lvalue,
2425 QualType type) {
2426 TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
2427 llvm::Value *value = result.getPointer();
2428 if (!result.getInt())
2429 value = CGF.EmitARCRetain(type, value);
2430 return value;
2431}
2432
2433/// EmitARCRetainScalarExpr - Semantically equivalent to
2434/// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
2435/// best-effort attempt to peephole expressions that naturally produce
2436/// retained objects.
2437llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) {
2438 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2439 llvm::Value *value = result.getPointer();
2440 if (!result.getInt())
2441 value = EmitARCRetain(e->getType(), value);
2442 return value;
2443}
2444
2445llvm::Value *
2446CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) {
2447 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2448 llvm::Value *value = result.getPointer();
2449 if (result.getInt())
2450 value = EmitARCAutorelease(value);
2451 else
2452 value = EmitARCRetainAutorelease(e->getType(), value);
2453 return value;
2454}
2455
John McCallff613032011-10-04 06:23:45 +00002456llvm::Value *CodeGenFunction::EmitARCExtendBlockObject(const Expr *e) {
2457 llvm::Value *result;
2458 bool doRetain;
2459
2460 if (shouldEmitSeparateBlockRetain(e)) {
2461 result = EmitScalarExpr(e);
2462 doRetain = true;
2463 } else {
2464 TryEmitResult subresult = tryEmitARCRetainScalarExpr(*this, e);
2465 result = subresult.getPointer();
2466 doRetain = !subresult.getInt();
2467 }
2468
2469 if (doRetain)
2470 result = EmitARCRetainBlock(result, /*mandatory*/ true);
2471 return EmitObjCConsumeObject(e->getType(), result);
2472}
2473
John McCall248512a2011-10-01 10:32:24 +00002474llvm::Value *CodeGenFunction::EmitObjCThrowOperand(const Expr *expr) {
2475 // In ARC, retain and autorelease the expression.
2476 if (getLangOptions().ObjCAutoRefCount) {
2477 // Do so before running any cleanups for the full-expression.
2478 // tryEmitARCRetainScalarExpr does make an effort to do things
2479 // inside cleanups, but there are crazy cases like
2480 // @throw A().foo;
2481 // where a full retain+autorelease is required and would
2482 // otherwise happen after the destructor for the temporary.
John McCall08ef4662011-11-10 08:15:53 +00002483 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(expr)) {
2484 enterFullExpression(ewc);
John McCall248512a2011-10-01 10:32:24 +00002485 expr = ewc->getSubExpr();
John McCall08ef4662011-11-10 08:15:53 +00002486 }
John McCall248512a2011-10-01 10:32:24 +00002487
John McCall08ef4662011-11-10 08:15:53 +00002488 CodeGenFunction::RunCleanupsScope cleanups(*this);
John McCall248512a2011-10-01 10:32:24 +00002489 return EmitARCRetainAutoreleaseScalarExpr(expr);
2490 }
2491
2492 // Otherwise, use the normal scalar-expression emission. The
2493 // exception machinery doesn't do anything special with the
2494 // exception like retaining it, so there's no safety associated with
2495 // only running cleanups after the throw has started, and when it
2496 // matters it tends to be substantially inferior code.
2497 return EmitScalarExpr(expr);
2498}
2499
John McCall31168b02011-06-15 23:02:42 +00002500std::pair<LValue,llvm::Value*>
2501CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e,
2502 bool ignored) {
2503 // Evaluate the RHS first.
2504 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());
2505 llvm::Value *value = result.getPointer();
2506
John McCallb726a552011-07-28 07:23:35 +00002507 bool hasImmediateRetain = result.getInt();
2508
2509 // If we didn't emit a retained object, and the l-value is of block
2510 // type, then we need to emit the block-retain immediately in case
2511 // it invalidates the l-value.
2512 if (!hasImmediateRetain && e->getType()->isBlockPointerType()) {
John McCallff613032011-10-04 06:23:45 +00002513 value = EmitARCRetainBlock(value, /*mandatory*/ false);
John McCallb726a552011-07-28 07:23:35 +00002514 hasImmediateRetain = true;
2515 }
2516
John McCall31168b02011-06-15 23:02:42 +00002517 LValue lvalue = EmitLValue(e->getLHS());
2518
2519 // If the RHS was emitted retained, expand this.
John McCallb726a552011-07-28 07:23:35 +00002520 if (hasImmediateRetain) {
John McCall31168b02011-06-15 23:02:42 +00002521 llvm::Value *oldValue =
Eli Friedmana0544d62011-12-03 04:14:32 +00002522 EmitLoadOfScalar(lvalue);
2523 EmitStoreOfScalar(value, lvalue);
John McCall31168b02011-06-15 23:02:42 +00002524 EmitARCRelease(oldValue, /*precise*/ false);
2525 } else {
John McCall55e1fbc2011-06-25 02:11:03 +00002526 value = EmitARCStoreStrong(lvalue, value, ignored);
John McCall31168b02011-06-15 23:02:42 +00002527 }
2528
2529 return std::pair<LValue,llvm::Value*>(lvalue, value);
2530}
2531
2532std::pair<LValue,llvm::Value*>
2533CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) {
2534 llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS());
2535 LValue lvalue = EmitLValue(e->getLHS());
2536
Eli Friedmana0544d62011-12-03 04:14:32 +00002537 EmitStoreOfScalar(value, lvalue);
John McCall31168b02011-06-15 23:02:42 +00002538
2539 return std::pair<LValue,llvm::Value*>(lvalue, value);
2540}
2541
2542void CodeGenFunction::EmitObjCAutoreleasePoolStmt(
2543 const ObjCAutoreleasePoolStmt &ARPS) {
2544 const Stmt *subStmt = ARPS.getSubStmt();
2545 const CompoundStmt &S = cast<CompoundStmt>(*subStmt);
2546
2547 CGDebugInfo *DI = getDebugInfo();
Eric Christopher7cdf9482011-10-13 21:45:18 +00002548 if (DI)
2549 DI->EmitLexicalBlockStart(Builder, S.getLBracLoc());
John McCall31168b02011-06-15 23:02:42 +00002550
2551 // Keep track of the current cleanup stack depth.
2552 RunCleanupsScope Scope(*this);
John McCall24fc0de2011-07-06 00:26:06 +00002553 if (CGM.getCodeGenOpts().ObjCRuntimeHasARC) {
John McCall31168b02011-06-15 23:02:42 +00002554 llvm::Value *token = EmitObjCAutoreleasePoolPush();
2555 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);
2556 } else {
2557 llvm::Value *token = EmitObjCMRRAutoreleasePoolPush();
2558 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);
2559 }
2560
2561 for (CompoundStmt::const_body_iterator I = S.body_begin(),
2562 E = S.body_end(); I != E; ++I)
2563 EmitStmt(*I);
2564
Eric Christopher7cdf9482011-10-13 21:45:18 +00002565 if (DI)
2566 DI->EmitLexicalBlockEnd(Builder, S.getRBracLoc());
John McCall31168b02011-06-15 23:02:42 +00002567}
John McCall1bd25562011-06-24 23:21:27 +00002568
2569/// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
2570/// make sure it survives garbage collection until this point.
2571void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) {
2572 // We just use an inline assembly.
John McCall1bd25562011-06-24 23:21:27 +00002573 llvm::FunctionType *extenderType
Jay Foad5709f7c2011-07-29 13:56:53 +00002574 = llvm::FunctionType::get(VoidTy, VoidPtrTy, /*variadic*/ false);
John McCall1bd25562011-06-24 23:21:27 +00002575 llvm::Value *extender
2576 = llvm::InlineAsm::get(extenderType,
2577 /* assembly */ "",
2578 /* constraints */ "r",
2579 /* side effects */ true);
2580
2581 object = Builder.CreateBitCast(object, VoidPtrTy);
2582 Builder.CreateCall(extender, object)->setDoesNotThrow();
2583}
2584
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002585/// GenerateObjCAtomicSetterCopyHelperFunction - Given a c++ object type with
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002586/// non-trivial copy assignment function, produce following helper function.
2587/// static void copyHelper(Ty *dest, const Ty *source) { *dest = *source; }
2588///
2589llvm::Constant *
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002590CodeGenFunction::GenerateObjCAtomicSetterCopyHelperFunction(
2591 const ObjCPropertyImplDecl *PID) {
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00002592 // FIXME. This api is for NeXt runtime only for now.
2593 if (!getLangOptions().CPlusPlus || !getLangOptions().NeXTRuntime)
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002594 return 0;
2595 QualType Ty = PID->getPropertyIvarDecl()->getType();
2596 if (!Ty->isRecordType())
2597 return 0;
2598 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002599 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002600 return 0;
Fariborz Jahanian1bed4132012-01-08 19:13:23 +00002601 llvm::Constant * HelperFn = 0;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002602 if (hasTrivialSetExpr(PID))
2603 return 0;
2604 assert(PID->getSetterCXXAssignment() && "SetterCXXAssignment - null");
2605 if ((HelperFn = CGM.getAtomicSetterHelperFnMap(Ty)))
2606 return HelperFn;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002607
2608 ASTContext &C = getContext();
2609 IdentifierInfo *II
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002610 = &CGM.getContext().Idents.get("__assign_helper_atomic_property_");
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002611 FunctionDecl *FD = FunctionDecl::Create(C,
2612 C.getTranslationUnitDecl(),
2613 SourceLocation(),
2614 SourceLocation(), II, C.VoidTy, 0,
2615 SC_Static,
2616 SC_None,
2617 false,
2618 true);
2619
2620 QualType DestTy = C.getPointerType(Ty);
2621 QualType SrcTy = Ty;
2622 SrcTy.addConst();
2623 SrcTy = C.getPointerType(SrcTy);
2624
2625 FunctionArgList args;
2626 ImplicitParamDecl dstDecl(FD, SourceLocation(), 0, DestTy);
2627 args.push_back(&dstDecl);
2628 ImplicitParamDecl srcDecl(FD, SourceLocation(), 0, SrcTy);
2629 args.push_back(&srcDecl);
2630
2631 const CGFunctionInfo &FI =
2632 CGM.getTypes().getFunctionInfo(C.VoidTy, args, FunctionType::ExtInfo());
2633
2634 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI, false);
2635
2636 llvm::Function *Fn =
2637 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002638 "__assign_helper_atomic_property_", &CGM.getModule());
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002639
2640 if (CGM.getModuleDebugInfo())
2641 DebugInfo = CGM.getModuleDebugInfo();
2642
2643
2644 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
2645
2646 DeclRefExpr *DstExpr =
2647 new (C) DeclRefExpr(&dstDecl, DestTy,
2648 VK_RValue, SourceLocation());
2649
2650 Expr* DST = new (C) UnaryOperator(DstExpr, UO_Deref, DestTy->getPointeeType(),
2651 VK_LValue, OK_Ordinary, SourceLocation());
2652
2653 DeclRefExpr *SrcExpr =
2654 new (C) DeclRefExpr(&srcDecl, SrcTy,
2655 VK_RValue, SourceLocation());
2656
2657 Expr* SRC = new (C) UnaryOperator(SrcExpr, UO_Deref, SrcTy->getPointeeType(),
2658 VK_LValue, OK_Ordinary, SourceLocation());
2659
2660 Expr *Args[2] = { DST, SRC };
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002661 CallExpr *CalleeExp = cast<CallExpr>(PID->getSetterCXXAssignment());
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002662 CXXOperatorCallExpr *TheCall =
2663 new (C) CXXOperatorCallExpr(C, OO_Equal, CalleeExp->getCallee(),
2664 Args, 2, DestTy->getPointeeType(),
2665 VK_LValue, SourceLocation());
2666
2667 EmitStmt(TheCall);
2668
2669 FinishFunction();
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00002670 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002671 CGM.setAtomicSetterHelperFnMap(Ty, HelperFn);
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00002672 return HelperFn;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002673}
2674
2675llvm::Constant *
2676CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction(
2677 const ObjCPropertyImplDecl *PID) {
2678 // FIXME. This api is for NeXt runtime only for now.
2679 if (!getLangOptions().CPlusPlus || !getLangOptions().NeXTRuntime)
2680 return 0;
2681 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
2682 QualType Ty = PD->getType();
2683 if (!Ty->isRecordType())
2684 return 0;
2685 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
2686 return 0;
2687 llvm::Constant * HelperFn = 0;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002688
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002689 if (hasTrivialGetExpr(PID))
2690 return 0;
2691 assert(PID->getGetterCXXConstructor() && "getGetterCXXConstructor - null");
2692 if ((HelperFn = CGM.getAtomicGetterHelperFnMap(Ty)))
2693 return HelperFn;
2694
2695
2696 ASTContext &C = getContext();
2697 IdentifierInfo *II
2698 = &CGM.getContext().Idents.get("__copy_helper_atomic_property_");
2699 FunctionDecl *FD = FunctionDecl::Create(C,
2700 C.getTranslationUnitDecl(),
2701 SourceLocation(),
2702 SourceLocation(), II, C.VoidTy, 0,
2703 SC_Static,
2704 SC_None,
2705 false,
2706 true);
2707
2708 QualType DestTy = C.getPointerType(Ty);
2709 QualType SrcTy = Ty;
2710 SrcTy.addConst();
2711 SrcTy = C.getPointerType(SrcTy);
2712
2713 FunctionArgList args;
2714 ImplicitParamDecl dstDecl(FD, SourceLocation(), 0, DestTy);
2715 args.push_back(&dstDecl);
2716 ImplicitParamDecl srcDecl(FD, SourceLocation(), 0, SrcTy);
2717 args.push_back(&srcDecl);
2718
2719 const CGFunctionInfo &FI =
2720 CGM.getTypes().getFunctionInfo(C.VoidTy, args, FunctionType::ExtInfo());
2721
2722 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI, false);
2723
2724 llvm::Function *Fn =
2725 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
2726 "__copy_helper_atomic_property_", &CGM.getModule());
2727
2728 if (CGM.getModuleDebugInfo())
2729 DebugInfo = CGM.getModuleDebugInfo();
2730
2731
2732 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
2733
2734 DeclRefExpr *SrcExpr =
2735 new (C) DeclRefExpr(&srcDecl, SrcTy,
2736 VK_RValue, SourceLocation());
2737
2738 Expr* SRC = new (C) UnaryOperator(SrcExpr, UO_Deref, SrcTy->getPointeeType(),
2739 VK_LValue, OK_Ordinary, SourceLocation());
2740
2741 CXXConstructExpr *CXXConstExpr =
2742 cast<CXXConstructExpr>(PID->getGetterCXXConstructor());
2743
2744 SmallVector<Expr*, 4> ConstructorArgs;
2745 ConstructorArgs.push_back(SRC);
2746 CXXConstructExpr::arg_iterator A = CXXConstExpr->arg_begin();
2747 ++A;
2748
2749 for (CXXConstructExpr::arg_iterator AEnd = CXXConstExpr->arg_end();
2750 A != AEnd; ++A)
2751 ConstructorArgs.push_back(*A);
2752
2753 CXXConstructExpr *TheCXXConstructExpr =
2754 CXXConstructExpr::Create(C, Ty, SourceLocation(),
2755 CXXConstExpr->getConstructor(),
2756 CXXConstExpr->isElidable(),
2757 &ConstructorArgs[0], ConstructorArgs.size(),
2758 CXXConstExpr->hadMultipleCandidates(),
2759 CXXConstExpr->requiresZeroInitialization(),
2760 CXXConstExpr->getConstructionKind(), SourceRange());
2761
2762 DeclRefExpr *DstExpr =
2763 new (C) DeclRefExpr(&dstDecl, DestTy,
2764 VK_RValue, SourceLocation());
2765
2766 RValue DV = EmitAnyExpr(DstExpr);
2767 CharUnits Alignment = getContext().getTypeAlignInChars(TheCXXConstructExpr->getType());
2768 EmitAggExpr(TheCXXConstructExpr,
2769 AggValueSlot::forAddr(DV.getScalarVal(), Alignment, Qualifiers(),
2770 AggValueSlot::IsDestructed,
2771 AggValueSlot::DoesNotNeedGCBarriers,
2772 AggValueSlot::IsNotAliased));
2773
2774 FinishFunction();
2775 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
2776 CGM.setAtomicGetterHelperFnMap(Ty, HelperFn);
2777 return HelperFn;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002778}
2779
2780
Ted Kremenek43e06332008-04-09 15:51:31 +00002781CGObjCRuntime::~CGObjCRuntime() {}